summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlan Hourihane <alanh@tungstengraphics.com>2003-04-17 11:25:39 +0000
committerAlan Hourihane <alanh@tungstengraphics.com>2003-04-17 11:25:39 +0000
commitf1f331ef4d987d2f3a6ae7e6dcb654e24c3f551e (patch)
tree95109a22881bcd1aca1c43c5a892e50f3a2eb716
parentca81dd07b7bf31392034313f69d942f05d7f0b01 (diff)
add definition for FB_ACCEL_ATI_RADEONembedded-1-20030417
-rw-r--r--src/kernel/fbdev/radeonfb/radeonfb.c3
1 files changed, 3 insertions, 0 deletions
diff --git a/src/kernel/fbdev/radeonfb/radeonfb.c b/src/kernel/fbdev/radeonfb/radeonfb.c
index fc9240ce3636..580d26cce9e5 100644
--- a/src/kernel/fbdev/radeonfb/radeonfb.c
+++ b/src/kernel/fbdev/radeonfb/radeonfb.c
@@ -140,6 +140,9 @@
#include <linux/radeonfb.h>
+#ifndef FB_ACCEL_ATI_RADEON
+#define FB_ACCEL_ATI_RADEON 38
+#endif
#define DEBUG 0
d>space:mode:
authortstellar <tstellar@91177308-0d34-0410-b5e6-96231b3b80d8>2012-09-18 19:40:39 +0000
committertstellar <tstellar@91177308-0d34-0410-b5e6-96231b3b80d8>2012-09-18 19:40:39 +0000
commit15d14cb83df480dd4aab6435873ca50254891a2d (patch)
treee5ef7d77a1e7703b625d5de82d50c26e4944cdc7
Create R600 Branch
git-svn-id: https://llvm.org/svn/llvm-project/llvm/branches/R600/@164161 91177308-0d34-0410-b5e6-96231b3b80d8
Diffstat
-rw-r--r--.gitignore47
-rw-r--r--CMakeLists.txt502
-rw-r--r--CODE_OWNERS.TXT51
-rw-r--r--CREDITS.TXT425
-rw-r--r--LICENSE.TXT70
-rw-r--r--LLVMBuild.txt24
-rw-r--r--Makefile269
-rw-r--r--Makefile.common69
-rw-r--r--Makefile.config.in375
-rw-r--r--Makefile.rules2344
-rw-r--r--README.txt17
-rwxr-xr-xautoconf/AutoRegen.sh58
-rw-r--r--autoconf/ExportMap.map7
-rw-r--r--autoconf/LICENSE.TXT24
-rw-r--r--autoconf/README.TXT49
-rwxr-xr-xautoconf/config.guess1520
-rwxr-xr-xautoconf/config.sub1766
-rw-r--r--autoconf/configure.ac1737
-rwxr-xr-xautoconf/depcomp522
-rwxr-xr-xautoconf/install-sh322
-rw-r--r--autoconf/ltmain.sh6863
-rw-r--r--autoconf/m4/build_exeext.m442
-rw-r--r--autoconf/m4/c_printf_a.m431
-rw-r--r--autoconf/m4/check_gnu_make.m426
-rw-r--r--autoconf/m4/config_makefile.m49
-rw-r--r--autoconf/m4/config_project.m414
-rw-r--r--autoconf/m4/cxx_flag_check.m42
-rw-r--r--autoconf/m4/find_std_program.m4118
-rw-r--r--autoconf/m4/func_isinf.m436
-rw-r--r--autoconf/m4/func_isnan.m427
-rw-r--r--autoconf/m4/func_mmap_file.m426
-rw-r--r--autoconf/m4/header_mmap_anonymous.m421
-rw-r--r--autoconf/m4/huge_val.m420
-rw-r--r--autoconf/m4/libtool.m46389
-rw-r--r--autoconf/m4/link_options.m4108
-rw-r--r--autoconf/m4/linux_mixed_64_32.m417
-rw-r--r--autoconf/m4/ltdl.m4418
-rw-r--r--autoconf/m4/need_dev_zero_for_mmap.m417
-rw-r--r--autoconf/m4/path_tclsh.m439
-rw-r--r--autoconf/m4/rand48.m412
-rw-r--r--autoconf/m4/sanity_check.m431
-rw-r--r--autoconf/m4/single_cxx_check.m410
-rw-r--r--autoconf/m4/visibility_inlines_hidden.m424
-rwxr-xr-xautoconf/missing353
-rwxr-xr-xautoconf/mkinstalldirs150
-rw-r--r--bindings/LLVMBuild.txt21
-rw-r--r--bindings/Makefile16
-rw-r--r--bindings/README.txt3
-rw-r--r--bindings/ocaml/Makefile19
-rw-r--r--bindings/ocaml/Makefile.ocaml415
-rw-r--r--bindings/ocaml/analysis/Makefile19
-rw-r--r--bindings/ocaml/analysis/analysis_ocaml.c72
-rw-r--r--bindings/ocaml/analysis/llvm_analysis.ml22
-rw-r--r--bindings/ocaml/analysis/llvm_analysis.mli46
-rw-r--r--bindings/ocaml/bitreader/Makefile19
-rw-r--r--bindings/ocaml/bitreader/bitreader_ocaml.c73
-rw-r--r--bindings/ocaml/bitreader/llvm_bitreader.ml20
-rw-r--r--bindings/ocaml/bitreader/llvm_bitreader.mli28
-rw-r--r--bindings/ocaml/bitwriter/Makefile19
-rw-r--r--bindings/ocaml/bitwriter/bitwriter_ocaml.c45
-rw-r--r--bindings/ocaml/bitwriter/llvm_bitwriter.ml25
-rw-r--r--bindings/ocaml/bitwriter/llvm_bitwriter.mli30
-rw-r--r--bindings/ocaml/executionengine/Makefile19
-rw-r--r--bindings/ocaml/executionengine/executionengine_ocaml.c326
-rw-r--r--bindings/ocaml/executionengine/llvm_executionengine.ml112
-rw-r--r--bindings/ocaml/executionengine/llvm_executionengine.mli163
-rw-r--r--bindings/ocaml/llvm/META.llvm.in63
-rw-r--r--bindings/ocaml/llvm/Makefile42
-rw-r--r--bindings/ocaml/llvm/llvm.ml1240
-rw-r--r--bindings/ocaml/llvm/llvm.mli2405
-rw-r--r--bindings/ocaml/llvm/llvm_ocaml.c2031
-rw-r--r--bindings/ocaml/target/Makefile19
-rw-r--r--bindings/ocaml/target/llvm_target.ml42
-rw-r--r--bindings/ocaml/target/llvm_target.mli95
-rw-r--r--bindings/ocaml/target/target_ocaml.c102
-rw-r--r--bindings/ocaml/transforms/Makefile18
-rw-r--r--bindings/ocaml/transforms/ipo/Makefile20
-rw-r--r--bindings/ocaml/transforms/ipo/ipo_ocaml.c104
-rw-r--r--bindings/ocaml/transforms/ipo/llvm_ipo.ml65
-rw-r--r--bindings/ocaml/transforms/ipo/llvm_ipo.mli65
-rw-r--r--bindings/ocaml/transforms/scalar/Makefile20
-rw-r--r--bindings/ocaml/transforms/scalar/llvm_scalar_opts.ml111
-rw-r--r--bindings/ocaml/transforms/scalar/llvm_scalar_opts.mli164
-rw-r--r--bindings/ocaml/transforms/scalar/scalar_opts_ocaml.c201
-rw-r--r--bindings/python/README.txt67
-rw-r--r--bindings/python/llvm/__init__.py0
-rw-r--r--bindings/python/llvm/common.py106
-rw-r--r--bindings/python/llvm/core.py98
-rw-r--r--bindings/python/llvm/disassembler.py134
-rw-r--r--bindings/python/llvm/enumerations.py211
-rw-r--r--bindings/python/llvm/object.py523
-rw-r--r--bindings/python/llvm/tests/__init__.py0
-rw-r--r--bindings/python/llvm/tests/base.py32
-rw-r--r--bindings/python/llvm/tests/test_core.py23
-rw-r--r--bindings/python/llvm/tests/test_disassembler.py28
-rw-r--r--bindings/python/llvm/tests/test_object.py67
-rw-r--r--cmake/README1
-rwxr-xr-xcmake/config-ix.cmake419
-rwxr-xr-xcmake/modules/AddLLVM.cmake294
-rw-r--r--cmake/modules/AddLLVMDefinitions.cmake13
-rw-r--r--cmake/modules/CMakeLists.txt37
-rw-r--r--cmake/modules/CheckAtomic.cmake29
-rw-r--r--cmake/modules/ChooseMSVCCRT.cmake106
-rw-r--r--cmake/modules/GetHostTriple.cmake30
-rw-r--r--cmake/modules/HandleLLVMOptions.cmake209
-rwxr-xr-xcmake/modules/LLVM-Config.cmake178
-rw-r--r--cmake/modules/LLVMConfig.cmake.in51
-rw-r--r--cmake/modules/LLVMConfigVersion.cmake.in1
-rw-r--r--cmake/modules/LLVMParseArguments.cmake80
-rw-r--r--cmake/modules/LLVMProcessSources.cmake94
-rw-r--r--cmake/modules/TableGen.cmake130
-rw-r--r--cmake/modules/VersionFromVCS.cmake70
-rw-r--r--cmake/platforms/Android.cmake21
-rwxr-xr-xconfigure22949
-rw-r--r--docs/AliasAnalysis.rst702
-rw-r--r--docs/Atomics.rst441
-rw-r--r--docs/BitCodeFormat.rst1045
-rw-r--r--docs/BranchWeightMetadata.rst118
-rw-r--r--docs/Bugpoint.rst218
-rw-r--r--docs/CMake.rst423
-rw-r--r--docs/CodeGenerator.rst2428
-rw-r--r--docs/CodingStandards.rst1175
-rw-r--r--docs/CommandGuide/FileCheck.rst284
-rw-r--r--docs/CommandGuide/bugpoint.rst247
-rw-r--r--docs/CommandGuide/index.rst53
-rw-r--r--docs/CommandGuide/lit.rst474
-rw-r--r--docs/CommandGuide/llc.rst251
-rw-r--r--docs/CommandGuide/lli.rst300
-rw-r--r--docs/CommandGuide/llvm-ar.rst458
-rw-r--r--docs/CommandGuide/llvm-as.rst56
-rw-r--r--docs/CommandGuide/llvm-bcanalyzer.rst424
-rw-r--r--docs/CommandGuide/llvm-build.rst102
-rw-r--r--docs/CommandGuide/llvm-config.rst176
-rw-r--r--docs/CommandGuide/llvm-cov.rst51
-rw-r--r--docs/CommandGuide/llvm-diff.rst56
-rw-r--r--docs/CommandGuide/llvm-dis.rst69
-rw-r--r--docs/CommandGuide/llvm-extract.rst104
-rw-r--r--docs/CommandGuide/llvm-link.rst96
-rw-r--r--docs/CommandGuide/llvm-nm.rst189
-rw-r--r--docs/CommandGuide/llvm-prof.rst63
-rw-r--r--docs/CommandGuide/llvm-ranlib.rst61
-rw-r--r--docs/CommandGuide/llvm-stress.rst48
-rw-r--r--docs/CommandGuide/opt.rst183
-rw-r--r--docs/CommandGuide/tblgen.rst186
-rw-r--r--docs/CommandLine.rst1615
-rw-r--r--docs/CompilerWriterInfo.html267
-rw-r--r--docs/DebuggingJITedCode.html184
-rw-r--r--docs/DeveloperPolicy.rst508
-rw-r--r--docs/ExceptionHandling.rst367
-rw-r--r--docs/ExtendedIntegerResults.txt133
-rw-r--r--docs/ExtendingLLVM.html379
-rw-r--r--docs/FAQ.rst464
-rw-r--r--docs/GCCFEBuildInstrs.html279
-rw-r--r--docs/GarbageCollection.html1389
-rw-r--r--docs/GetElementPtr.rst538
-rw-r--r--docs/GettingStarted.html1760
-rw-r--r--docs/GettingStartedVS.rst234
-rw-r--r--docs/GoldPlugin.html227
-rw-r--r--docs/HistoricalNotes/2000-11-18-EarlyDesignIdeas.txt74
-rw-r--r--docs/HistoricalNotes/2000-11-18-EarlyDesignIdeasResp.txt199
-rw-r--r--docs/HistoricalNotes/2000-12-06-EncodingIdea.txt30
-rw-r--r--docs/HistoricalNotes/2000-12-06-MeetingSummary.txt83
-rw-r--r--docs/HistoricalNotes/2001-01-31-UniversalIRIdea.txt39
-rw-r--r--docs/HistoricalNotes/2001-02-06-TypeNotationDebate.txt67
-rw-r--r--docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp1.txt75
-rw-r--r--docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp2.txt53
-rw-r--r--docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp4.txt89
-rw-r--r--docs/HistoricalNotes/2001-02-09-AdveComments.txt120
-rw-r--r--docs/HistoricalNotes/2001-02-09-AdveCommentsResponse.txt245
-rw-r--r--docs/HistoricalNotes/2001-02-13-Reference-Memory.txt39
-rw-r--r--docs/HistoricalNotes/2001-02-13-Reference-MemoryResponse.txt47
-rw-r--r--docs/HistoricalNotes/2001-04-16-DynamicCompilation.txt49
-rw-r--r--docs/HistoricalNotes/2001-05-18-ExceptionHandling.txt202
-rw-r--r--docs/HistoricalNotes/2001-05-19-ExceptionResponse.txt45
-rw-r--r--docs/HistoricalNotes/2001-06-01-GCCOptimizations.txt63
-rw-r--r--docs/HistoricalNotes/2001-06-01-GCCOptimizations2.txt71
-rw-r--r--docs/HistoricalNotes/2001-06-20-.NET-Differences.txt30
-rw-r--r--docs/HistoricalNotes/2001-07-06-LoweringIRForCodeGen.txt31
-rw-r--r--docs/HistoricalNotes/2001-09-18-OptimizeExceptions.txt56
-rw-r--r--docs/HistoricalNotes/2002-05-12-InstListChange.txt55
-rw-r--r--docs/HistoricalNotes/2002-06-25-MegaPatchInfo.txt72
-rw-r--r--docs/HistoricalNotes/2003-01-23-CygwinNotes.txt28
-rw-r--r--docs/HistoricalNotes/2003-06-25-Reoptimizer1.txt137
-rw-r--r--docs/HistoricalNotes/2003-06-26-Reoptimizer2.txt110
-rw-r--r--docs/HistoricalNotes/2007-OriginalClangReadme.txt178
-rw-r--r--docs/HowToAddABuilder.rst90
-rw-r--r--docs/HowToReleaseLLVM.html581
-rw-r--r--docs/HowToSubmitABug.html345
-rw-r--r--docs/LLVMBuild.html368
-rw-r--r--docs/LLVMBuild.txt21
-rw-r--r--docs/LangRef.html8731
-rw-r--r--docs/Lexicon.rst194
-rw-r--r--docs/LinkTimeOptimization.rst298
-rw-r--r--docs/Makefile127
-rw-r--r--docs/Makefile.sphinx159
-rw-r--r--docs/MakefileGuide.rst956
-rw-r--r--docs/Packaging.rst75
-rw-r--r--docs/Passes.html2066
-rw-r--r--docs/ProgrammersManual.html4137
-rw-r--r--docs/Projects.rst327
-rw-r--r--docs/README.txt12
-rw-r--r--docs/ReleaseNotes.html755
-rw-r--r--docs/SegmentedStacks.rst80
-rw-r--r--docs/SourceLevelDebugging.html2858
-rw-r--r--docs/SystemLibrary.html316
-rw-r--r--docs/TableGenFundamentals.rst799
-rw-r--r--docs/TestSuiteMakefileGuide.html351
-rw-r--r--docs/TestingGuide.html915
-rw-r--r--docs/WritingAnLLVMBackend.html2533
-rw-r--r--docs/WritingAnLLVMPass.html1954
-rw-r--r--docs/_static/lines.gifbin0 -> 91 bytes
-rw-r--r--docs/_static/llvm.css112
-rw-r--r--docs/_templates/indexsidebar.html7
-rw-r--r--docs/_templates/layout.html13
-rw-r--r--docs/_themes/llvm-theme/layout.html23
-rw-r--r--docs/_themes/llvm-theme/static/contents.pngbin0 -> 202 bytes
-rw-r--r--docs/_themes/llvm-theme/static/llvm-theme.css374
-rw-r--r--docs/_themes/llvm-theme/static/logo.pngbin0 -> 9864 bytes
-rw-r--r--docs/_themes/llvm-theme/static/navigation.pngbin0 -> 218 bytes
-rw-r--r--docs/_themes/llvm-theme/theme.conf4
-rw-r--r--docs/conf.py252
-rw-r--r--docs/design_and_overview.rst36
-rw-r--r--docs/development_process.rst30
-rw-r--r--docs/doxygen.cfg.in1632
-rw-r--r--docs/doxygen.css408
-rw-r--r--docs/doxygen.footer13
-rw-r--r--docs/doxygen.header9
-rw-r--r--docs/doxygen.intro18
-rw-r--r--docs/index.rst70
-rw-r--r--docs/mailing_lists.rst35
-rw-r--r--docs/make.bat190
-rw-r--r--docs/programming.rst40
-rw-r--r--docs/re_format.7756
-rw-r--r--docs/subsystems.rst91
-rw-r--r--docs/tutorial/LangImpl1.html348
-rw-r--r--docs/tutorial/LangImpl2.html1231
-rw-r--r--docs/tutorial/LangImpl3.html1268
-rw-r--r--docs/tutorial/LangImpl4.html1152
-rw-r--r--docs/tutorial/LangImpl5-cfg.pngbin0 -> 38586 bytes
-rw-r--r--docs/tutorial/LangImpl5.html1772
-rw-r--r--docs/tutorial/LangImpl6.html1829
-rw-r--r--docs/tutorial/LangImpl7.html2164
-rw-r--r--docs/tutorial/LangImpl8.html359
-rw-r--r--docs/tutorial/OCamlLangImpl1.html365
-rw-r--r--docs/tutorial/OCamlLangImpl2.html1043
-rw-r--r--docs/tutorial/OCamlLangImpl3.html1093
-rw-r--r--docs/tutorial/OCamlLangImpl4.html1026
-rw-r--r--docs/tutorial/OCamlLangImpl5.html1560
-rw-r--r--docs/tutorial/OCamlLangImpl6.html1574
-rw-r--r--docs/tutorial/OCamlLangImpl7.html1904
-rw-r--r--docs/tutorial/OCamlLangImpl8.html359
-rw-r--r--docs/tutorial/index.html48
-rw-r--r--docs/userguides.rst90
-rw-r--r--docs/yaml2obj.rst222
-rw-r--r--examples/BrainF/BrainF.cpp467
-rw-r--r--examples/BrainF/BrainF.h94
-rw-r--r--examples/BrainF/BrainFDriver.cpp159
-rw-r--r--examples/BrainF/CMakeLists.txt6
-rw-r--r--examples/BrainF/Makefile15
-rw-r--r--examples/CMakeLists.txt13
-rw-r--r--examples/ExceptionDemo/CMakeLists.txt6
-rw-r--r--examples/ExceptionDemo/ExceptionDemo.cpp2006
-rw-r--r--examples/ExceptionDemo/Makefile16
-rw-r--r--examples/Fibonacci/CMakeLists.txt5
-rw-r--r--examples/Fibonacci/Makefile17
-rw-r--r--examples/Fibonacci/fibonacci.cpp137
-rw-r--r--examples/HowToUseJIT/CMakeLists.txt5
-rw-r--r--examples/HowToUseJIT/HowToUseJIT.cpp133
-rw-r--r--examples/HowToUseJIT/Makefile15
-rw-r--r--examples/Kaleidoscope/CMakeLists.txt6
-rw-r--r--examples/Kaleidoscope/Chapter2/CMakeLists.txt3
-rw-r--r--examples/Kaleidoscope/Chapter2/Makefile13
-rw-r--r--examples/Kaleidoscope/Chapter2/toy.cpp398
-rw-r--r--examples/Kaleidoscope/Chapter3/CMakeLists.txt5
-rw-r--r--examples/Kaleidoscope/Chapter3/Makefile15
-rw-r--r--examples/Kaleidoscope/Chapter3/toy.cpp563
-rw-r--r--examples/Kaleidoscope/Chapter4/CMakeLists.txt5
-rw-r--r--examples/Kaleidoscope/Chapter4/Makefile15
-rw-r--r--examples/Kaleidoscope/Chapter4/toy.cpp613
-rw-r--r--examples/Kaleidoscope/Chapter5/CMakeLists.txt5
-rw-r--r--examples/Kaleidoscope/Chapter5/Makefile15
-rw-r--r--examples/Kaleidoscope/Chapter5/toy.cpp858
-rw-r--r--examples/Kaleidoscope/Chapter6/CMakeLists.txt5
-rw-r--r--examples/Kaleidoscope/Chapter6/Makefile15
-rw-r--r--examples/Kaleidoscope/Chapter6/toy.cpp976
-rw-r--r--examples/Kaleidoscope/Chapter7/CMakeLists.txt6
-rw-r--r--examples/Kaleidoscope/Chapter7/Makefile16
-rw-r--r--examples/Kaleidoscope/Chapter7/toy.cpp1142
-rw-r--r--examples/Kaleidoscope/Makefile15
-rw-r--r--examples/LLVMBuild.txt21
-rw-r--r--examples/Makefile32
-rw-r--r--examples/ModuleMaker/CMakeLists.txt5
-rw-r--r--examples/ModuleMaker/Makefile14
-rw-r--r--examples/ModuleMaker/ModuleMaker.cpp64
-rw-r--r--examples/ModuleMaker/README.txt8
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter2/Makefile22
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter2/_tags1
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter2/ast.ml25
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter2/lexer.ml52
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter2/parser.ml122
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter2/token.ml15
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter2/toplevel.ml34
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter2/toy.ml21
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/Makefile24
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/_tags2
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/ast.ml25
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/codegen.ml100
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/lexer.ml52
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/myocamlbuild.ml6
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/parser.ml122
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/token.ml15
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/toplevel.ml39
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter3/toy.ml26
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/Makefile25
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/_tags4
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/ast.ml25
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/bindings.c7
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/codegen.ml103
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/lexer.ml52
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/myocamlbuild.ml10
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/parser.ml122
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/token.ml15
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/toplevel.ml49
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter4/toy.ml53
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/Makefile25
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/_tags4
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/ast.ml31
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/bindings.c7
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/codegen.ml225
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/lexer.ml57
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/myocamlbuild.ml10
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/parser.ml158
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/token.ml19
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/toplevel.ml49
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter5/toy.ml53
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/Makefile34
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/_tags4
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/ast.ml36
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/bindings.c13
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/codegen.ml251
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/lexer.ml59
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/myocamlbuild.ml10
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/parser.ml195
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/token.ml22
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/toplevel.ml49
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter6/toy.ml53
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/Makefile34
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/_tags4
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/ast.ml39
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/bindings.c13
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/codegen.ml370
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/lexer.ml60
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/myocamlbuild.ml10
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/parser.ml221
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/token.ml25
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/toplevel.ml49
-rw-r--r--examples/OCaml-Kaleidoscope/Chapter7/toy.ml57
-rw-r--r--examples/OCaml-Kaleidoscope/Makefile15
-rw-r--r--examples/ParallelJIT/CMakeLists.txt9
-rw-r--r--examples/ParallelJIT/Makefile17
-rw-r--r--examples/ParallelJIT/ParallelJIT.cpp305
-rw-r--r--include/llvm-c/Analysis.h65
-rw-r--r--include/llvm-c/BitReader.h76
-rw-r--r--include/llvm-c/BitWriter.h56
-rw-r--r--include/llvm-c/Core.h2706
-rw-r--r--include/llvm-c/Disassembler.h175
-rw-r--r--include/llvm-c/EnhancedDisassembly.h530
-rw-r--r--include/llvm-c/ExecutionEngine.h163
-rw-r--r--include/llvm-c/Initialization.h54
-rw-r--r--include/llvm-c/LinkTimeOptimizer.h69
-rw-r--r--include/llvm-c/Linker.h42
-rw-r--r--include/llvm-c/Object.h149
-rw-r--r--include/llvm-c/Target.h253
-rw-r--r--include/llvm-c/TargetMachine.h142
-rw-r--r--include/llvm-c/Transforms/IPO.h81
-rw-r--r--include/llvm-c/Transforms/PassManagerBuilder.h101
-rw-r--r--include/llvm-c/Transforms/Scalar.h134
-rw-r--r--include/llvm-c/Transforms/Vectorize.h48
-rw-r--r--include/llvm-c/lto.h302
-rw-r--r--include/llvm/ADT/APFloat.h468
-rw-r--r--include/llvm/ADT/APInt.h1785
-rw-r--r--include/llvm/ADT/APSInt.h312
-rw-r--r--include/llvm/ADT/ArrayRef.h305
-rw-r--r--include/llvm/ADT/BitVector.h533
-rw-r--r--include/llvm/ADT/DAGDeltaAlgorithm.h77
-rw-r--r--include/llvm/ADT/DeltaAlgorithm.h91
-rw-r--r--include/llvm/ADT/DenseMap.h1038
-rw-r--r--include/llvm/ADT/DenseMapInfo.h168
-rw-r--r--include/llvm/ADT/DenseSet.h129
-rw-r--r--include/llvm/ADT/DepthFirstIterator.h268
-rw-r--r--include/llvm/ADT/EquivalenceClasses.h283
-rw-r--r--include/llvm/ADT/FoldingSet.h794
-rw-r--r--include/llvm/ADT/GraphTraits.h106
-rw-r--r--include/llvm/ADT/Hashing.h765
-rw-r--r--include/llvm/ADT/ImmutableIntervalMap.h248
-rw-r--r--include/llvm/ADT/ImmutableList.h229
-rw-r--r--include/llvm/ADT/ImmutableMap.h418
-rw-r--r--include/llvm/ADT/ImmutableSet.h1223
-rw-r--r--include/llvm/ADT/InMemoryStruct.h77
-rw-r--r--include/llvm/ADT/IndexedMap.h82
-rw-r--r--include/llvm/ADT/IntEqClasses.h88
-rw-r--r--include/llvm/ADT/IntervalMap.h2146
-rw-r--r--include/llvm/ADT/IntrusiveRefCntPtr.h243
-rw-r--r--include/llvm/ADT/MapVector.h153
-rw-r--r--include/llvm/ADT/NullablePtr.h52
-rw-r--r--include/llvm/ADT/Optional.h120
-rw-r--r--include/llvm/ADT/OwningPtr.h134
-rw-r--r--include/llvm/ADT/PackedVector.h158
-rw-r--r--include/llvm/ADT/PointerIntPair.h178
-rw-r--r--include/llvm/ADT/PointerUnion.h452
-rw-r--r--include/llvm/ADT/PostOrderIterator.h279
-rw-r--r--include/llvm/ADT/PriorityQueue.h84
-rw-r--r--include/llvm/ADT/SCCIterator.h220
-rw-r--r--include/llvm/ADT/STLExtras.h312
-rw-r--r--include/llvm/ADT/ScopedHashTable.h256
-rw-r--r--include/llvm/ADT/SetOperations.h71
-rw-r--r--include/llvm/ADT/SetVector.h184
-rw-r--r--include/llvm/ADT/SmallBitVector.h544
-rw-r--r--include/llvm/ADT/SmallPtrSet.h308
-rw-r--r--include/llvm/ADT/SmallSet.h118
-rw-r--r--include/llvm/ADT/SmallString.h300
-rw-r--r--include/llvm/ADT/SmallVector.h938
-rw-r--r--include/llvm/ADT/SparseBitVector.h881
-rw-r--r--include/llvm/ADT/SparseSet.h308
-rw-r--r--include/llvm/ADT/Statistic.h139
-rw-r--r--include/llvm/ADT/StringExtras.h134
-rw-r--r--include/llvm/ADT/StringMap.h463
-rw-r--r--include/llvm/ADT/StringRef.h554
-rw-r--r--include/llvm/ADT/StringSet.h38
-rw-r--r--include/llvm/ADT/StringSwitch.h126
-rw-r--r--include/llvm/ADT/TinyPtrVector.h291
-rw-r--r--include/llvm/ADT/Triple.h436
-rw-r--r--include/llvm/ADT/Twine.h524
-rw-r--r--include/llvm/ADT/UniqueVector.h89
-rw-r--r--include/llvm/ADT/ValueMap.h378
-rw-r--r--include/llvm/ADT/VariadicFunction.h331
-rw-r--r--include/llvm/ADT/edit_distance.h102
-rw-r--r--include/llvm/ADT/ilist.h705
-rw-r--r--include/llvm/ADT/ilist_node.h106
-rw-r--r--include/llvm/Analysis/AliasAnalysis.h603
-rw-r--r--include/llvm/Analysis/AliasSetTracker.h438
-rw-r--r--include/llvm/Analysis/BlockFrequencyImpl.h342
-rw-r--r--include/llvm/Analysis/BlockFrequencyInfo.h55
-rw-r--r--include/llvm/Analysis/BranchProbabilityInfo.h148
-rw-r--r--include/llvm/Analysis/CFGPrinter.h114
-rw-r--r--include/llvm/Analysis/CallGraph.h378
-rw-r--r--include/llvm/Analysis/CaptureTracking.h63
-rw-r--r--include/llvm/Analysis/CodeMetrics.h95
-rw-r--r--include/llvm/Analysis/ConstantFolding.h102
-rw-r--r--include/llvm/Analysis/ConstantsScanner.h93
-rw-r--r--include/llvm/Analysis/DOTGraphTraitsPass.h83
-rw-r--r--include/llvm/Analysis/DomPrinter.h30
-rw-r--r--include/llvm/Analysis/DominanceFrontier.h190
-rw-r--r--include/llvm/Analysis/DominatorInternals.h289
-rw-r--r--include/llvm/Analysis/Dominators.h921
-rw-r--r--include/llvm/Analysis/FindUsedTypes.h66
-rw-r--r--include/llvm/Analysis/IVUsers.h185
-rw-r--r--include/llvm/Analysis/InlineCost.h132
-rw-r--r--include/llvm/Analysis/InstructionSimplify.h218
-rw-r--r--include/llvm/Analysis/Interval.h153
-rw-r--r--include/llvm/Analysis/IntervalIterator.h259
-rw-r--r--include/llvm/Analysis/IntervalPartition.h111
-rw-r--r--include/llvm/Analysis/LazyValueInfo.h81
-rw-r--r--include/llvm/Analysis/LibCallAliasAnalysis.h73
-rw-r--r--include/llvm/Analysis/LibCallSemantics.h167
-rw-r--r--include/llvm/Analysis/Lint.h49
-rw-r--r--include/llvm/Analysis/Loads.h57
-rw-r--r--include/llvm/Analysis/LoopDependenceAnalysis.h124
-rw-r--r--include/llvm/Analysis/LoopInfo.h700
-rw-r--r--include/llvm/Analysis/LoopInfoImpl.h569
-rw-r--r--include/llvm/Analysis/LoopIterator.h182
-rw-r--r--include/llvm/Analysis/LoopPass.h158
-rw-r--r--include/llvm/Analysis/MemoryBuiltins.h265
-rw-r--r--include/llvm/Analysis/MemoryDependenceAnalysis.h442
-rw-r--r--include/llvm/Analysis/PHITransAddr.h121
-rw-r--r--include/llvm/Analysis/Passes.h213
-rw-r--r--include/llvm/Analysis/PathNumbering.h304
-rw-r--r--include/llvm/Analysis/PathProfileInfo.h112
-rw-r--r--include/llvm/Analysis/PostDominators.h106
-rw-r--r--include/llvm/Analysis/ProfileDataLoader.h142
-rw-r--r--include/llvm/Analysis/ProfileDataTypes.h39
-rw-r--r--include/llvm/Analysis/ProfileInfo.h247
-rw-r--r--include/llvm/Analysis/ProfileInfoLoader.h81
-rw-r--r--include/llvm/Analysis/ProfileInfoTypes.h52
-rw-r--r--include/llvm/Analysis/RegionInfo.h721
-rw-r--r--include/llvm/Analysis/RegionIterator.h342
-rw-r--r--include/llvm/Analysis/RegionPass.h126
-rw-r--r--include/llvm/Analysis/RegionPrinter.h26
-rw-r--r--include/llvm/Analysis/ScalarEvolution.h889
-rw-r--r--include/llvm/Analysis/ScalarEvolutionExpander.h269
-rw-r--r--include/llvm/Analysis/ScalarEvolutionExpressions.h567
-rw-r--r--include/llvm/Analysis/ScalarEvolutionNormalization.h78
-rw-r--r--include/llvm/Analysis/SparsePropagation.h206
-rw-r--r--include/llvm/Analysis/Trace.h119
-rw-r--r--include/llvm/Analysis/ValueTracking.h189
-rw-r--r--include/llvm/Analysis/Verifier.h75
-rw-r--r--include/llvm/Argument.h92
-rw-r--r--include/llvm/Assembly/AssemblyAnnotationWriter.h63
-rw-r--r--include/llvm/Assembly/Parser.h64
-rw-r--r--include/llvm/Assembly/PrintModulePass.h42
-rw-r--r--include/llvm/Assembly/Writer.h37
-rw-r--r--include/llvm/Attributes.h411
-rw-r--r--include/llvm/AutoUpgrade.h44
-rw-r--r--include/llvm/BasicBlock.h291
-rw-r--r--include/llvm/Bitcode/Archive.h538
-rw-r--r--include/llvm/Bitcode/BitCodes.h186
-rw-r--r--include/llvm/Bitcode/BitstreamReader.h668
-rw-r--r--include/llvm/Bitcode/BitstreamWriter.h548
-rw-r--r--include/llvm/Bitcode/LLVMBitCodes.h329
-rw-r--r--include/llvm/Bitcode/ReaderWriter.h154
-rw-r--r--include/llvm/CMakeLists.txt19
-rw-r--r--include/llvm/CallGraphSCCPass.h104
-rw-r--r--include/llvm/CallingConv.h103
-rw-r--r--include/llvm/CodeGen/Analysis.h97
-rw-r--r--include/llvm/CodeGen/AsmPrinter.h491
-rw-r--r--include/llvm/CodeGen/CalcSpillWeights.h78
-rw-r--r--include/llvm/CodeGen/CallingConvLower.h325
-rw-r--r--include/llvm/CodeGen/DFAPacketizer.h167
-rw-r--r--include/llvm/CodeGen/EdgeBundles.h69
-rw-r--r--include/llvm/CodeGen/FastISel.h406
-rw-r--r--include/llvm/CodeGen/FunctionLoweringInfo.h231
-rw-r--r--include/llvm/CodeGen/GCMetadata.h194
-rw-r--r--include/llvm/CodeGen/GCMetadataPrinter.h74
-rw-r--r--include/llvm/CodeGen/GCStrategy.h153
-rw-r--r--include/llvm/CodeGen/GCs.h35
-rw-r--r--include/llvm/CodeGen/ISDOpcodes.h822
-rw-r--r--include/llvm/CodeGen/IntrinsicLowering.h59
-rw-r--r--include/llvm/CodeGen/JITCodeEmitter.h342
-rw-r--r--include/llvm/CodeGen/LatencyPriorityQueue.h100
-rw-r--r--include/llvm/CodeGen/LexicalScopes.h254
-rw-r--r--include/llvm/CodeGen/LinkAllAsmWriterComponents.h37
-rw-r--r--include/llvm/CodeGen/LinkAllCodegenComponents.h53
-rw-r--r--include/llvm/CodeGen/LiveInterval.h611
-rw-r--r--include/llvm/CodeGen/LiveIntervalAnalysis.h407
-rw-r--r--include/llvm/CodeGen/LiveRangeEdit.h210
-rw-r--r--include/llvm/CodeGen/LiveStackAnalysis.h99
-rw-r--r--include/llvm/CodeGen/LiveVariables.h315
-rw-r--r--include/llvm/CodeGen/MachORelocation.h56
-rw-r--r--include/llvm/CodeGen/MachineBasicBlock.h703
-rw-r--r--include/llvm/CodeGen/MachineBlockFrequencyInfo.h56
-rw-r--r--include/llvm/CodeGen/MachineBranchProbabilityInfo.h89
-rw-r--r--include/llvm/CodeGen/MachineCodeEmitter.h335
-rw-r--r--include/llvm/CodeGen/MachineCodeInfo.h53
-rw-r--r--include/llvm/CodeGen/MachineConstantPool.h174
-rw-r--r--include/llvm/CodeGen/MachineDominators.h203
-rw-r--r--include/llvm/CodeGen/MachineFrameInfo.h577
-rw-r--r--include/llvm/CodeGen/MachineFunction.h491
-rw-r--r--include/llvm/CodeGen/MachineFunctionAnalysis.h51
-rw-r--r--include/llvm/CodeGen/MachineFunctionPass.h59
-rw-r--r--include/llvm/CodeGen/MachineInstr.h1029
-rw-r--r--include/llvm/CodeGen/MachineInstrBuilder.h327
-rw-r--r--include/llvm/CodeGen/MachineInstrBundle.h237
-rw-r--r--include/llvm/CodeGen/MachineJumpTableInfo.h130
-rw-r--r--include/llvm/CodeGen/MachineLoopInfo.h190
-rw-r--r--include/llvm/CodeGen/MachineLoopRanges.h112
-rw-r--r--include/llvm/CodeGen/MachineMemOperand.h183
-rw-r--r--include/llvm/CodeGen/MachineModuleInfo.h405
-rw-r--r--include/llvm/CodeGen/MachineModuleInfoImpls.h97
-rw-r--r--include/llvm/CodeGen/MachineOperand.h692
-rw-r--r--include/llvm/CodeGen/MachinePassRegistry.h158
-rw-r--r--include/llvm/CodeGen/MachinePostDominators.h87
-rw-r--r--include/llvm/CodeGen/MachineRegisterInfo.h584
-rw-r--r--include/llvm/CodeGen/MachineRelocation.h342
-rw-r--r--include/llvm/CodeGen/MachineSSAUpdater.h117
-rw-r--r--include/llvm/CodeGen/MachineScheduler.h338
-rw-r--r--include/llvm/CodeGen/PBQP/Graph.h461
-rw-r--r--include/llvm/CodeGen/PBQP/HeuristicBase.h247
-rw-r--r--include/llvm/CodeGen/PBQP/HeuristicSolver.h616
-rw-r--r--include/llvm/CodeGen/PBQP/Heuristics/Briggs.h469
-rw-r--r--include/llvm/CodeGen/PBQP/Math.h288
-rw-r--r--include/llvm/CodeGen/PBQP/Solution.h94
-rw-r--r--include/llvm/CodeGen/Passes.h514
-rw-r--r--include/llvm/CodeGen/PseudoSourceValue.h112
-rw-r--r--include/llvm/CodeGen/RegAllocPBQP.h168
-rw-r--r--include/llvm/CodeGen/RegAllocRegistry.h66
-rw-r--r--include/llvm/CodeGen/RegisterClassInfo.h132
-rw-r--r--include/llvm/CodeGen/RegisterPressure.h282
-rw-r--r--include/llvm/CodeGen/RegisterScavenging.h170
-rw-r--r--include/llvm/CodeGen/ResourcePriorityQueue.h142
-rw-r--r--include/llvm/CodeGen/RuntimeLibcalls.h330
-rw-r--r--include/llvm/CodeGen/ScheduleDAG.h728
-rw-r--r--include/llvm/CodeGen/ScheduleDAGInstrs.h352
-rw-r--r--include/llvm/CodeGen/ScheduleHazardRecognizer.h95
-rw-r--r--include/llvm/CodeGen/SchedulerRegistry.h107
-rw-r--r--include/llvm/CodeGen/ScoreboardHazardRecognizer.h127
-rw-r--r--include/llvm/CodeGen/SelectionDAG.h1099
-rw-r--r--include/llvm/CodeGen/SelectionDAGISel.h282
-rw-r--r--include/llvm/CodeGen/SelectionDAGNodes.h1888
-rw-r--r--include/llvm/CodeGen/SlotIndexes.h649
-rw-r--r--include/llvm/CodeGen/TargetLoweringObjectFileImpl.h136
-rw-r--r--include/llvm/CodeGen/TargetSchedule.h79
-rw-r--r--include/llvm/CodeGen/ValueTypes.h755
-rw-r--r--include/llvm/CodeGen/ValueTypes.td83
-rw-r--r--include/llvm/Config/AsmParsers.def.in29
-rw-r--r--include/llvm/Config/AsmPrinters.def.in29
-rw-r--r--include/llvm/Config/Disassemblers.def.in29
-rw-r--r--include/llvm/Config/Targets.def.in28
-rw-r--r--include/llvm/Config/config.h.cmake731
-rw-r--r--include/llvm/Config/config.h.in714
-rw-r--r--include/llvm/Config/llvm-config.h.cmake121
-rw-r--r--include/llvm/Config/llvm-config.h.in121
-rw-r--r--include/llvm/Constant.h158
-rw-r--r--include/llvm/Constants.h1170
-rw-r--r--include/llvm/DIBuilder.h568
-rw-r--r--include/llvm/DebugInfo.h892
-rw-r--r--include/llvm/DebugInfo/DIContext.h115
-rw-r--r--include/llvm/DefaultPasses.h168
-rw-r--r--include/llvm/DerivedTypes.h463
-rw-r--r--include/llvm/ExecutionEngine/ExecutionEngine.h623
-rw-r--r--include/llvm/ExecutionEngine/GenericValue.h44
-rw-r--r--include/llvm/ExecutionEngine/IntelJITEventsWrapper.h102
-rw-r--r--include/llvm/ExecutionEngine/Interpreter.h38
-rw-r--r--include/llvm/ExecutionEngine/JIT.h38
-rw-r--r--include/llvm/ExecutionEngine/JITEventListener.h116
-rw-r--r--include/llvm/ExecutionEngine/JITMemoryManager.h206
-rw-r--r--include/llvm/ExecutionEngine/MCJIT.h38
-rw-r--r--include/llvm/ExecutionEngine/OProfileWrapper.h124
-rw-r--r--include/llvm/ExecutionEngine/RuntimeDyld.h94
-rw-r--r--include/llvm/Function.h458
-rw-r--r--include/llvm/GVMaterializer.h66
-rw-r--r--include/llvm/GlobalAlias.h94
-rw-r--r--include/llvm/GlobalValue.h300
-rw-r--r--include/llvm/GlobalVariable.h192
-rw-r--r--include/llvm/IRBuilder.h1296
-rw-r--r--include/llvm/InitializePasses.h266
-rw-r--r--include/llvm/InlineAsm.h308
-rw-r--r--include/llvm/InstrTypes.h854
-rw-r--r--include/llvm/Instruction.def199
-rw-r--r--include/llvm/Instruction.h408
-rw-r--r--include/llvm/Instructions.h3727
-rw-r--r--include/llvm/IntrinsicInst.h282
-rw-r--r--include/llvm/Intrinsics.h128
-rw-r--r--include/llvm/Intrinsics.td465
-rw-r--r--include/llvm/IntrinsicsARM.td442
-rw-r--r--include/llvm/IntrinsicsCellSPU.td242
-rw-r--r--include/llvm/IntrinsicsHexagon.td4877
-rw-r--r--include/llvm/IntrinsicsMips.td389
-rw-r--r--include/llvm/IntrinsicsNVVM.td952
-rw-r--r--include/llvm/IntrinsicsPowerPC.td465
-rw-r--r--include/llvm/IntrinsicsX86.td2561
-rw-r--r--include/llvm/IntrinsicsXCore.td114
-rw-r--r--include/llvm/LLVMContext.h113
-rw-r--r--include/llvm/LinkAllPasses.h172
-rw-r--r--include/llvm/LinkAllVMCore.h53
-rw-r--r--include/llvm/Linker.h306
-rw-r--r--include/llvm/MC/EDInstInfo.h29
-rw-r--r--include/llvm/MC/MCAsmBackend.h157
-rw-r--r--include/llvm/MC/MCAsmInfo.h561
-rw-r--r--include/llvm/MC/MCAsmInfoCOFF.h36
-rw-r--r--include/llvm/MC/MCAsmInfoDarwin.h29
-rw-r--r--include/llvm/MC/MCAsmLayout.h105
-rw-r--r--include/llvm/MC/MCAssembler.h973
-rw-r--r--include/llvm/MC/MCAtom.h68
-rw-r--r--include/llvm/MC/MCCodeEmitter.h40
-rw-r--r--include/llvm/MC/MCCodeGenInfo.h48
-rw-r--r--include/llvm/MC/MCContext.h411
-rw-r--r--include/llvm/MC/MCDirectives.h65
-rw-r--r--include/llvm/MC/MCDisassembler.h136
-rw-r--r--include/llvm/MC/MCDwarf.h338
-rw-r--r--include/llvm/MC/MCELFObjectWriter.h152
-rw-r--r--include/llvm/MC/MCELFSymbolFlags.h58
-rw-r--r--include/llvm/MC/MCExpr.h469
-rw-r--r--include/llvm/MC/MCFixedLenDisassembler.h32
-rw-r--r--include/llvm/MC/MCFixup.h112
-rw-r--r--include/llvm/MC/MCFixupKindInfo.h43
-rw-r--r--include/llvm/MC/MCInst.h204
-rw-r--r--include/llvm/MC/MCInstPrinter.h66
-rw-r--r--include/llvm/MC/MCInstrAnalysis.h61
-rw-r--r--include/llvm/MC/MCInstrDesc.h542
-rw-r--r--include/llvm/MC/MCInstrInfo.h62
-rw-r--r--include/llvm/MC/MCInstrItineraries.h257
-rw-r--r--include/llvm/MC/MCLabel.h58
-rw-r--r--include/llvm/MC/MCMachOSymbolFlags.h46
-rw-r--r--include/llvm/MC/MCMachObjectWriter.h262
-rw-r--r--include/llvm/MC/MCModule.h58
-rw-r--r--include/llvm/MC/MCObjectFileInfo.h312
-rw-r--r--include/llvm/MC/MCObjectStreamer.h91
-rw-r--r--include/llvm/MC/MCObjectWriter.h190
-rw-r--r--include/llvm/MC/MCParser/AsmCond.h40
-rw-r--r--include/llvm/MC/MCParser/AsmLexer.h70
-rw-r--r--include/llvm/MC/MCParser/MCAsmLexer.h182
-rw-r--r--include/llvm/MC/MCParser/MCAsmParser.h144
-rw-r--r--include/llvm/MC/MCParser/MCAsmParserExtension.h80
-rw-r--r--include/llvm/MC/MCParser/MCParsedAsmOperand.h56
-rw-r--r--include/llvm/MC/MCRegisterInfo.h503
-rw-r--r--include/llvm/MC/MCSchedule.h230
-rw-r--r--include/llvm/MC/MCSection.h73
-rw-r--r--include/llvm/MC/MCSectionCOFF.h69
-rw-r--r--include/llvm/MC/MCSectionELF.h88
-rw-r--r--include/llvm/MC/MCSectionMachO.h182
-rw-r--r--include/llvm/MC/MCStreamer.h626
-rw-r--r--include/llvm/MC/MCSubtargetInfo.h136
-rw-r--r--include/llvm/MC/MCSymbol.h165
-rw-r--r--include/llvm/MC/MCTargetAsmLexer.h89
-rw-r--r--include/llvm/MC/MCTargetAsmParser.h122
-rw-r--r--include/llvm/MC/MCValue.h77
-rw-r--r--include/llvm/MC/MCWin64EH.h93
-rw-r--r--include/llvm/MC/MCWinCOFFObjectWriter.h36
-rw-r--r--include/llvm/MC/MachineLocation.h98
-rw-r--r--include/llvm/MC/SectionKind.h240
-rw-r--r--include/llvm/MC/SubtargetFeature.h115
-rw-r--r--include/llvm/MDBuilder.h141
-rw-r--r--include/llvm/Metadata.h244
-rw-r--r--include/llvm/Module.h605
-rw-r--r--include/llvm/Object/Archive.h145
-rw-r--r--include/llvm/Object/Binary.h104
-rw-r--r--include/llvm/Object/COFF.h206
-rw-r--r--include/llvm/Object/ELF.h2595
-rw-r--r--include/llvm/Object/Error.h50
-rw-r--r--include/llvm/Object/MachO.h133
-rw-r--r--include/llvm/Object/MachOFormat.h396
-rw-r--r--include/llvm/Object/MachOObject.h207
-rw-r--r--include/llvm/Object/ObjectFile.h604
-rw-r--r--include/llvm/OperandTraits.h160
-rw-r--r--include/llvm/Operator.h326
-rw-r--r--include/llvm/Pass.h376
-rw-r--r--include/llvm/PassAnalysisSupport.h253
-rw-r--r--include/llvm/PassManager.h103
-rw-r--r--include/llvm/PassManagers.h461
-rw-r--r--include/llvm/PassRegistry.h84
-rw-r--r--include/llvm/PassSupport.h341
-rw-r--r--include/llvm/Support/AIXDataTypesFix.h25
-rw-r--r--include/llvm/Support/AlignOf.h170
-rw-r--r--include/llvm/Support/Allocator.h242
-rw-r--r--include/llvm/Support/Atomic.h39
-rw-r--r--include/llvm/Support/BlockFrequency.h65
-rw-r--r--include/llvm/Support/BranchProbability.h77
-rw-r--r--include/llvm/Support/CFG.h357
-rw-r--r--include/llvm/Support/COFF.h594
-rw-r--r--include/llvm/Support/CallSite.h316
-rw-r--r--include/llvm/Support/Capacity.h32
-rw-r--r--include/llvm/Support/Casting.h233
-rw-r--r--include/llvm/Support/CodeGen.h52
-rw-r--r--include/llvm/Support/CommandLine.h1689
-rw-r--r--include/llvm/Support/Compiler.h217
-rw-r--r--include/llvm/Support/ConstantFolder.h238
-rw-r--r--include/llvm/Support/ConstantRange.h269
-rw-r--r--include/llvm/Support/CrashRecoveryContext.h200
-rw-r--r--include/llvm/Support/DOTGraphTraits.h161
-rw-r--r--include/llvm/Support/DataExtractor.h352
-rw-r--r--include/llvm/Support/DataFlow.h103
-rw-r--r--include/llvm/Support/DataStream.h38
-rw-r--r--include/llvm/Support/DataTypes.h.cmake203
-rw-r--r--include/llvm/Support/DataTypes.h.in200
-rw-r--r--include/llvm/Support/Debug.h101
-rw-r--r--include/llvm/Support/DebugLoc.h112
-rw-r--r--include/llvm/Support/Disassembler.h35
-rw-r--r--include/llvm/Support/Dwarf.h740
-rw-r--r--include/llvm/Support/DynamicLibrary.h104
-rw-r--r--include/llvm/Support/ELF.h1282
-rw-r--r--include/llvm/Support/Endian.h224
-rw-r--r--include/llvm/Support/Errno.h34
-rw-r--r--include/llvm/Support/ErrorHandling.h106
-rw-r--r--include/llvm/Support/FEnv.h56
-rw-r--r--include/llvm/Support/FileOutputBuffer.h98
-rw-r--r--include/llvm/Support/FileSystem.h894
-rw-r--r--include/llvm/Support/FileUtilities.h80
-rw-r--r--include/llvm/Support/Format.h236
-rw-r--r--include/llvm/Support/FormattedStream.h155
-rw-r--r--include/llvm/Support/GCOV.h226
-rw-r--r--include/llvm/Support/GetElementPtrTypeIterator.h113
-rw-r--r--include/llvm/Support/GraphWriter.h357
-rw-r--r--include/llvm/Support/Host.h66
-rw-r--r--include/llvm/Support/IRReader.h112
-rw-r--r--include/llvm/Support/IncludeFile.h79
-rw-r--r--include/llvm/Support/InstIterator.h147
-rw-r--r--include/llvm/Support/InstVisitor.h282
-rw-r--r--include/llvm/Support/IntegersSubset.h541
-rw-r--r--include/llvm/Support/IntegersSubsetMapping.h588
-rw-r--r--include/llvm/Support/LEB128.h95
-rw-r--r--include/llvm/Support/LICENSE.TXT6
-rw-r--r--include/llvm/Support/LeakDetector.h92
-rw-r--r--include/llvm/Support/Locale.h17
-rw-r--r--include/llvm/Support/LockFileManager.h74
-rw-r--r--include/llvm/Support/MachO.h714
-rw-r--r--include/llvm/Support/ManagedStatic.h115
-rw-r--r--include/llvm/Support/MathExtras.h487
-rw-r--r--include/llvm/Support/Memory.h96
-rw-r--r--include/llvm/Support/MemoryBuffer.h142
-rw-r--r--include/llvm/Support/MemoryObject.h69
-rw-r--r--include/llvm/Support/Mutex.h155
-rw-r--r--include/llvm/Support/MutexGuard.h41
-rw-r--r--include/llvm/Support/NoFolder.h298
-rw-r--r--include/llvm/Support/OutputBuffer.h166
-rw-r--r--include/llvm/Support/PassNameParser.h137
-rw-r--r--include/llvm/Support/Path.h16
-rw-r--r--include/llvm/Support/PathV1.h743
-rw-r--r--include/llvm/Support/PathV2.h381
-rw-r--r--include/llvm/Support/PatternMatch.h824
-rw-r--r--include/llvm/Support/PluginLoader.h37
-rw-r--r--include/llvm/Support/PointerLikeTypeTraits.h81
-rw-r--r--include/llvm/Support/PredIteratorCache.h70
-rw-r--r--include/llvm/Support/PrettyStackTrace.h73
-rw-r--r--include/llvm/Support/Process.h158
-rw-r--r--include/llvm/Support/Program.h159
-rw-r--r--include/llvm/Support/RWMutex.h174
-rw-r--r--include/llvm/Support/Recycler.h118
-rw-r--r--include/llvm/Support/RecyclingAllocator.h73
-rw-r--r--include/llvm/Support/Regex.h81
-rw-r--r--include/llvm/Support/Registry.h224
-rw-r--r--include/llvm/Support/RegistryParser.h55
-rw-r--r--include/llvm/Support/SMLoc.h61
-rw-r--r--include/llvm/Support/SaveAndRestore.h47
-rw-r--r--include/llvm/Support/Signals.h59
-rw-r--r--include/llvm/Support/Solaris.h40
-rw-r--r--include/llvm/Support/SourceMgr.h206
-rw-r--r--include/llvm/Support/StreamableMemoryObject.h182
-rw-r--r--include/llvm/Support/StringPool.h139
-rw-r--r--include/llvm/Support/SwapByteOrder.h101
-rw-r--r--include/llvm/Support/SystemUtils.h44
-rw-r--r--include/llvm/Support/TargetFolder.h255
-rw-r--r--include/llvm/Support/TargetRegistry.h1160
-rw-r--r--include/llvm/Support/TargetSelect.h166
-rw-r--r--include/llvm/Support/ThreadLocal.h63
-rw-r--r--include/llvm/Support/Threading.h59
-rw-r--r--include/llvm/Support/TimeValue.h379
-rw-r--r--include/llvm/Support/Timer.h195
-rw-r--r--include/llvm/Support/ToolOutputFile.h62
-rw-r--r--include/llvm/Support/Valgrind.h75
-rw-r--r--include/llvm/Support/ValueHandle.h416
-rw-r--r--include/llvm/Support/Win64EH.h100
-rw-r--r--include/llvm/Support/YAMLParser.h559
-rw-r--r--include/llvm/Support/circular_raw_ostream.h171
-rw-r--r--include/llvm/Support/raw_os_ostream.h42
-rw-r--r--include/llvm/Support/raw_ostream.h509
-rw-r--r--include/llvm/Support/system_error.h905
-rw-r--r--include/llvm/Support/type_traits.h220
-rw-r--r--include/llvm/SymbolTableListTraits.h78
-rw-r--r--include/llvm/TableGen/Error.h49
-rw-r--r--include/llvm/TableGen/Main.h26
-rw-r--r--include/llvm/TableGen/Record.h1635
-rw-r--r--include/llvm/TableGen/StringMatcher.h54
-rw-r--r--include/llvm/TableGen/TableGenAction.h35
-rw-r--r--include/llvm/TableGen/TableGenBackend.h29
-rw-r--r--include/llvm/Target/Mangler.h73
-rw-r--r--include/llvm/Target/Target.td1008
-rw-r--r--include/llvm/Target/TargetCallingConv.h144
-rw-r--r--include/llvm/Target/TargetCallingConv.td146
-rw-r--r--include/llvm/Target/TargetData.h363
-rw-r--r--include/llvm/Target/TargetELFWriterInfo.h121
-rw-r--r--include/llvm/Target/TargetFrameLowering.h193
-rw-r--r--include/llvm/Target/TargetInstrInfo.h1048
-rw-r--r--include/llvm/Target/TargetIntrinsicInfo.h65
-rw-r--r--include/llvm/Target/TargetItinerary.td136
-rw-r--r--include/llvm/Target/TargetJITInfo.h137
-rw-r--r--include/llvm/Target/TargetLibraryInfo.h424
-rw-r--r--include/llvm/Target/TargetLowering.h2170
-rw-r--r--include/llvm/Target/TargetLoweringObjectFile.h148
-rw-r--r--include/llvm/Target/TargetMachine.h338
-rw-r--r--include/llvm/Target/TargetOpcodes.h99
-rw-r--r--include/llvm/Target/TargetOptions.h214
-rw-r--r--include/llvm/Target/TargetRegisterInfo.h916
-rw-r--r--include/llvm/Target/TargetSchedule.td325
-rw-r--r--include/llvm/Target/TargetSelectionDAG.td1030
-rw-r--r--include/llvm/Target/TargetSelectionDAGInfo.h101
-rw-r--r--include/llvm/Target/TargetSubtargetInfo.h79
-rw-r--r--include/llvm/Transforms/IPO.h203
-rw-r--r--include/llvm/Transforms/IPO/InlinerPass.h90
-rw-r--r--include/llvm/Transforms/IPO/PassManagerBuilder.h149
-rw-r--r--include/llvm/Transforms/Instrumentation.h50
-rw-r--r--include/llvm/Transforms/Scalar.h378
-rw-r--r--include/llvm/Transforms/Utils/AddrModeMatcher.h108
-rw-r--r--include/llvm/Transforms/Utils/BasicBlockUtils.h208
-rw-r--r--include/llvm/Transforms/Utils/BuildLibCalls.h125
-rw-r--r--include/llvm/Transforms/Utils/BypassSlowDivision.h33
-rw-r--r--include/llvm/Transforms/Utils/Cloning.h206
-rw-r--r--include/llvm/Transforms/Utils/CmpInstAnalysis.h66
-rw-r--r--include/llvm/Transforms/Utils/CodeExtractor.h127
-rw-r--r--include/llvm/Transforms/Utils/Local.h255
-rw-r--r--include/llvm/Transforms/Utils/ModuleUtils.h33
-rw-r--r--include/llvm/Transforms/Utils/PromoteMemToReg.h44
-rw-r--r--include/llvm/Transforms/Utils/SSAUpdater.h166
-rw-r--r--include/llvm/Transforms/Utils/SSAUpdaterImpl.h456
-rw-r--r--include/llvm/Transforms/Utils/SimplifyIndVar.h52
-rw-r--r--include/llvm/Transforms/Utils/UnifyFunctionExitNodes.h51
-rw-r--r--include/llvm/Transforms/Utils/UnrollLoop.h33
-rw-r--r--include/llvm/Transforms/Utils/ValueMapper.h80
-rw-r--r--include/llvm/Transforms/Vectorize.h124
-rw-r--r--include/llvm/Type.h453
-rw-r--r--include/llvm/TypeBuilder.h399
-rw-r--r--include/llvm/TypeFinder.h78
-rw-r--r--include/llvm/Use.h220
-rw-r--r--include/llvm/User.h177
-rw-r--r--include/llvm/Value.h416
-rw-r--r--include/llvm/ValueSymbolTable.h133
-rw-r--r--lib/Analysis/AliasAnalysis.cpp543
-rw-r--r--lib/Analysis/AliasAnalysisCounter.cpp171
-rw-r--r--lib/Analysis/AliasAnalysisEvaluator.cpp300
-rw-r--r--lib/Analysis/AliasDebugger.cpp138
-rw-r--r--lib/Analysis/AliasSetTracker.cpp655
-rw-r--r--lib/Analysis/Analysis.cpp106
-rw-r--r--lib/Analysis/BasicAliasAnalysis.cpp1286
-rw-r--r--lib/Analysis/BlockFrequencyInfo.cpp63
-rw-r--r--lib/Analysis/BranchProbabilityInfo.cpp558
-rw-r--r--lib/Analysis/CFGPrinter.cpp165
-rw-r--r--lib/Analysis/CMakeLists.txt64
-rw-r--r--lib/Analysis/CaptureTracking.cpp175
-rw-r--r--lib/Analysis/CodeMetrics.cpp204
-rw-r--r--lib/Analysis/ConstantFolding.cpp1476
-rw-r--r--lib/Analysis/DbgInfoPrinter.cpp224
-rw-r--r--lib/Analysis/DomPrinter.cpp232
-rw-r--r--lib/Analysis/DominanceFrontier.cpp141
-rw-r--r--lib/Analysis/IPA/CMakeLists.txt9
-rw-r--r--lib/Analysis/IPA/CallGraph.cpp337
-rw-r--r--lib/Analysis/IPA/CallGraphSCCPass.cpp611
-rw-r--r--lib/Analysis/IPA/FindUsedTypes.cpp101
-rw-r--r--lib/Analysis/IPA/GlobalsModRef.cpp607
-rw-r--r--lib/Analysis/IPA/IPA.cpp29
-rw-r--r--lib/Analysis/IPA/LLVMBuild.txt23
-rw-r--r--lib/Analysis/IPA/Makefile15
-rw-r--r--lib/Analysis/IVUsers.cpp335
-rw-r--r--lib/Analysis/InlineCost.cpp1020
-rw-r--r--lib/Analysis/InstCount.cpp87
-rw-r--r--lib/Analysis/InstructionSimplify.cpp2952
-rw-r--r--lib/Analysis/Interval.cpp58
-rw-r--r--lib/Analysis/IntervalPartition.cpp114
-rw-r--r--lib/Analysis/LLVMBuild.txt25
-rw-r--r--lib/Analysis/LazyValueInfo.cpp1139
-rw-r--r--lib/Analysis/LibCallAliasAnalysis.cpp137
-rw-r--r--lib/Analysis/LibCallSemantics.cpp63
-rw-r--r--lib/Analysis/Lint.cpp658
-rw-r--r--lib/Analysis/Loads.cpp250
-rw-r--r--lib/Analysis/LoopDependenceAnalysis.cpp362
-rw-r--r--lib/Analysis/LoopInfo.cpp625
-rw-r--r--lib/Analysis/LoopPass.cpp363
-rw-r--r--lib/Analysis/Makefile16
-rw-r--r--lib/Analysis/MemDepPrinter.cpp192
-rw-r--r--lib/Analysis/MemoryBuiltins.cpp770
-rw-r--r--lib/Analysis/MemoryDependenceAnalysis.cpp1507
-rw-r--r--lib/Analysis/ModuleDebugInfoPrinter.cpp87
-rw-r--r--lib/Analysis/NoAliasAnalysis.cpp88
-rw-r--r--lib/Analysis/PHITransAddr.cpp443
-rw-r--r--lib/Analysis/PathNumbering.cpp522
-rw-r--r--lib/Analysis/PathProfileInfo.cpp434
-rw-r--r--lib/Analysis/PathProfileVerifier.cpp207
-rw-r--r--lib/Analysis/PostDominators.cpp51
-rw-r--r--lib/Analysis/ProfileDataLoader.cpp162
-rw-r--r--lib/Analysis/ProfileDataLoaderPass.cpp188
-rw-r--r--lib/Analysis/ProfileEstimatorPass.cpp426
-rw-r--r--lib/Analysis/ProfileInfo.cpp1079
-rw-r--r--lib/Analysis/ProfileInfoLoader.cpp155
-rw-r--r--lib/Analysis/ProfileInfoLoaderPass.cpp267
-rw-r--r--lib/Analysis/ProfileVerifierPass.cpp382
-rw-r--r--lib/Analysis/README.txt30
-rw-r--r--lib/Analysis/RegionInfo.cpp835
-rw-r--r--lib/Analysis/RegionPass.cpp275
-rw-r--r--lib/Analysis/RegionPrinter.cpp218
-rw-r--r--lib/Analysis/ScalarEvolution.cpp6934
-rw-r--r--lib/Analysis/ScalarEvolutionAliasAnalysis.cpp173
-rw-r--r--lib/Analysis/ScalarEvolutionExpander.cpp1743
-rw-r--r--lib/Analysis/ScalarEvolutionNormalization.cpp223
-rw-r--r--lib/Analysis/SparsePropagation.cpp347
-rw-r--r--lib/Analysis/Trace.cpp53
-rw-r--r--lib/Analysis/TypeBasedAliasAnalysis.cpp300
-rw-r--r--lib/Analysis/ValueTracking.cpp1935
-rw-r--r--lib/Archive/Archive.cpp261
-rw-r--r--lib/Archive/ArchiveInternals.h89
-rw-r--r--lib/Archive/ArchiveReader.cpp632
-rw-r--r--lib/Archive/ArchiveWriter.cpp488
-rw-r--r--lib/Archive/CMakeLists.txt5
-rw-r--r--lib/Archive/LLVMBuild.txt22
-rw-r--r--lib/Archive/Makefile17
-rw-r--r--lib/AsmParser/CMakeLists.txt6
-rw-r--r--lib/AsmParser/LLLexer.cpp841
-rw-r--r--lib/AsmParser/LLLexer.h92
-rw-r--r--lib/AsmParser/LLParser.cpp4043
-rw-r--r--lib/AsmParser/LLParser.h385
-rw-r--r--lib/AsmParser/LLToken.h164
-rw-r--r--lib/AsmParser/LLVMBuild.txt22
-rw-r--r--lib/AsmParser/Makefile14
-rw-r--r--lib/AsmParser/Parser.cpp62
-rw-r--r--lib/Bitcode/CMakeLists.txt2
-rw-r--r--lib/Bitcode/LLVMBuild.txt24
-rw-r--r--lib/Bitcode/Makefile14
-rw-r--r--lib/Bitcode/Reader/BitReader.cpp88
-rw-r--r--lib/Bitcode/Reader/BitcodeReader.cpp2995
-rw-r--r--lib/Bitcode/Reader/BitcodeReader.h296
-rw-r--r--lib/Bitcode/Reader/CMakeLists.txt6
-rw-r--r--lib/Bitcode/Reader/LLVMBuild.txt22
-rw-r--r--lib/Bitcode/Reader/Makefile15
-rw-r--r--lib/Bitcode/Writer/BitWriter.cpp40
-rw-r--r--lib/Bitcode/Writer/BitcodeWriter.cpp1929
-rw-r--r--lib/Bitcode/Writer/BitcodeWriterPass.cpp41
-rw-r--r--lib/Bitcode/Writer/CMakeLists.txt6
-rw-r--r--lib/Bitcode/Writer/LLVMBuild.txt22
-rw-r--r--lib/Bitcode/Writer/Makefile15
-rw-r--r--lib/Bitcode/Writer/ValueEnumerator.cpp528
-rw-r--r--lib/Bitcode/Writer/ValueEnumerator.h157
-rw-r--r--lib/CMakeLists.txt15
-rw-r--r--lib/CodeGen/AggressiveAntiDepBreaker.cpp960
-rw-r--r--lib/CodeGen/AggressiveAntiDepBreaker.h184
-rw-r--r--lib/CodeGen/AllocationOrder.cpp79
-rw-r--r--lib/CodeGen/AllocationOrder.h72
-rw-r--r--lib/CodeGen/Analysis.cpp366
-rw-r--r--lib/CodeGen/AntiDepBreaker.h71
-rw-r--r--lib/CodeGen/AsmPrinter/ARMException.cpp92
-rw-r--r--lib/CodeGen/AsmPrinter/AsmPrinter.cpp2201
-rw-r--r--lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp200
-rw-r--r--lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp553
-rw-r--r--lib/CodeGen/AsmPrinter/CMakeLists.txt14
-rw-r--r--lib/CodeGen/AsmPrinter/DIE.cpp350
-rw-r--r--lib/CodeGen/AsmPrinter/DIE.h396
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfAccelTable.cpp264
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfAccelTable.h283
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfCFIException.cpp155
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp1546
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfCompileUnit.h339
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfDebug.cpp2238
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfDebug.h545
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfException.cpp731
-rw-r--r--lib/CodeGen/AsmPrinter/DwarfException.h231
-rw-r--r--lib/CodeGen/AsmPrinter/LLVMBuild.txt22
-rw-r--r--lib/CodeGen/AsmPrinter/Makefile13
-rw-r--r--lib/CodeGen/AsmPrinter/OcamlGCPrinter.cpp166
-rw-r--r--lib/CodeGen/AsmPrinter/Win64Exception.cpp115
-rw-r--r--lib/CodeGen/BranchFolding.cpp1728
-rw-r--r--lib/CodeGen/BranchFolding.h123
-rw-r--r--lib/CodeGen/CMakeLists.txt115
-rw-r--r--lib/CodeGen/CalcSpillWeights.cpp202
-rw-r--r--lib/CodeGen/CallingConvLower.cpp180
-rw-r--r--lib/CodeGen/CodeGen.cpp77
-rw-r--r--lib/CodeGen/CodePlacementOpt.cpp422
-rw-r--r--lib/CodeGen/CriticalAntiDepBreaker.cpp658
-rw-r--r--lib/CodeGen/CriticalAntiDepBreaker.h109
-rw-r--r--lib/CodeGen/DFAPacketizer.cpp225
-rw-r--r--lib/CodeGen/DeadMachineInstructionElim.cpp203
-rw-r--r--lib/CodeGen/DwarfEHPrepare.cpp183
-rw-r--r--lib/CodeGen/EarlyIfConversion.cpp801
-rw-r--r--lib/CodeGen/EdgeBundles.cpp97
-rw-r--r--lib/CodeGen/ExecutionDepsFix.cpp722
-rw-r--r--lib/CodeGen/ExpandISelPseudos.cpp74
-rw-r--r--lib/CodeGen/ExpandPostRAPseudos.cpp234
-rw-r--r--lib/CodeGen/GCMetadata.cpp213
-rw-r--r--lib/CodeGen/GCMetadataPrinter.cpp27
-rw-r--r--lib/CodeGen/GCStrategy.cpp422
-rw-r--r--lib/CodeGen/IfConversion.cpp1583
-rw-r--r--lib/CodeGen/InlineSpiller.cpp1295
-rw-r--r--lib/CodeGen/InterferenceCache.cpp231
-rw-r--r--lib/CodeGen/InterferenceCache.h228
-rw-r--r--lib/CodeGen/IntrinsicLowering.cpp565
-rw-r--r--lib/CodeGen/JITCodeEmitter.cpp14
-rw-r--r--lib/CodeGen/LLVMBuild.txt25
-rw-r--r--lib/CodeGen/LLVMTargetMachine.cpp291
-rw-r--r--lib/CodeGen/LatencyPriorityQueue.cpp152
-rw-r--r--lib/CodeGen/LexicalScopes.cpp337
-rw-r--r--lib/CodeGen/LiveDebugVariables.cpp1028
-rw-r--r--lib/CodeGen/LiveDebugVariables.h70
-rw-r--r--lib/CodeGen/LiveInterval.cpp875
-rw-r--r--lib/CodeGen/LiveIntervalAnalysis.cpp1527
-rw-r--r--lib/CodeGen/LiveIntervalUnion.cpp233
-rw-r--r--lib/CodeGen/LiveIntervalUnion.h210
-rw-r--r--lib/CodeGen/LiveRangeCalc.cpp354
-rw-r--r--lib/CodeGen/LiveRangeCalc.h239
-rw-r--r--lib/CodeGen/LiveRangeEdit.cpp380
-rw-r--r--lib/CodeGen/LiveRegMatrix.cpp154
-rw-r--r--lib/CodeGen/LiveRegMatrix.h148
-rw-r--r--lib/CodeGen/LiveStackAnalysis.cpp83
-rw-r--r--lib/CodeGen/LiveVariables.cpp851
-rw-r--r--lib/CodeGen/LocalStackSlotAllocation.cpp356
-rw-r--r--lib/CodeGen/MachineBasicBlock.cpp1052
-rw-r--r--lib/CodeGen/MachineBlockFrequencyInfo.cpp61
-rw-r--r--lib/CodeGen/MachineBlockPlacement.cpp1164
-rw-r--r--lib/CodeGen/MachineBranchProbabilityInfo.cpp126
-rw-r--r--lib/CodeGen/MachineCSE.cpp641
-rw-r--r--lib/CodeGen/MachineCodeEmitter.cpp14
-rw-r--r--lib/CodeGen/MachineCopyPropagation.cpp320
-rw-r--r--lib/CodeGen/MachineDominators.cpp59
-rw-r--r--lib/CodeGen/MachineFunction.cpp773
-rw-r--r--lib/CodeGen/MachineFunctionAnalysis.cpp57
-rw-r--r--lib/CodeGen/MachineFunctionPass.cpp56
-rw-r--r--lib/CodeGen/MachineFunctionPrinterPass.cpp67
-rw-r--r--lib/CodeGen/MachineInstr.cpp1955
-rw-r--r--lib/CodeGen/MachineInstrBundle.cpp328
-rw-r--r--lib/CodeGen/MachineLICM.cpp1489
-rw-r--r--lib/CodeGen/MachineLoopInfo.cpp81
-rw-r--r--lib/CodeGen/MachineLoopRanges.cpp116
-rw-r--r--lib/CodeGen/MachineModuleInfo.cpp576
-rw-r--r--lib/CodeGen/MachineModuleInfoImpls.cpp45
-rw-r--r--lib/CodeGen/MachinePassRegistry.cpp55
-rw-r--r--lib/CodeGen/MachinePostDominators.cpp55
-rw-r--r--lib/CodeGen/MachineRegisterInfo.cpp327
-rw-r--r--lib/CodeGen/MachineSSAUpdater.cpp366
-rw-r--r--lib/CodeGen/MachineScheduler.cpp1273
-rw-r--r--lib/CodeGen/MachineSink.cpp714
-rw-r--r--lib/CodeGen/MachineTraceMetrics.cpp1153
-rw-r--r--lib/CodeGen/MachineTraceMetrics.h341
-rw-r--r--lib/CodeGen/MachineVerifier.cpp1590
-rw-r--r--lib/CodeGen/Makefile22
-rw-r--r--lib/CodeGen/OcamlGC.cpp37
-rw-r--r--lib/CodeGen/OptimizePHIs.cpp193
-rw-r--r--lib/CodeGen/PHIElimination.cpp494
-rw-r--r--lib/CodeGen/PHIEliminationUtils.cpp61
-rw-r--r--lib/CodeGen/PHIEliminationUtils.h25
-rw-r--r--lib/CodeGen/Passes.cpp747
-rw-r--r--lib/CodeGen/PeepholeOptimizer.cpp561
-rw-r--r--lib/CodeGen/PostRASchedulerList.cpp793
-rw-r--r--lib/CodeGen/ProcessImplicitDefs.cpp170
-rw-r--r--lib/CodeGen/PrologEpilogInserter.cpp863
-rw-r--r--lib/CodeGen/PrologEpilogInserter.h173
-rw-r--r--lib/CodeGen/PseudoSourceValue.cpp132
-rw-r--r--lib/CodeGen/README.txt199
-rw-r--r--lib/CodeGen/RegAllocBase.cpp145
-rw-r--r--lib/CodeGen/RegAllocBase.h108
-rw-r--r--lib/CodeGen/RegAllocBasic.cpp295
-rw-r--r--lib/CodeGen/RegAllocFast.cpp1156
-rw-r--r--lib/CodeGen/RegAllocGreedy.cpp1776
-rw-r--r--lib/CodeGen/RegAllocPBQP.cpp639
-rw-r--r--lib/CodeGen/RegisterClassInfo.cpp124
-rw-r--r--lib/CodeGen/RegisterCoalescer.cpp2135
-rw-r--r--lib/CodeGen/RegisterCoalescer.h120
-rw-r--r--lib/CodeGen/RegisterPressure.cpp843
-rw-r--r--lib/CodeGen/RegisterScavenging.cpp392
-rw-r--r--lib/CodeGen/ScheduleDAG.cpp597
-rw-r--r--lib/CodeGen/ScheduleDAGInstrs.cpp1034
-rw-r--r--lib/CodeGen/ScheduleDAGPrinter.cpp96
-rw-r--r--lib/CodeGen/ScoreboardHazardRecognizer.cpp248
-rw-r--r--lib/CodeGen/SelectionDAG/CMakeLists.txt27
-rw-r--r--lib/CodeGen/SelectionDAG/DAGCombiner.cpp9239
-rw-r--r--lib/CodeGen/SelectionDAG/FastISel.cpp1473
-rw-r--r--lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp484
-rw-r--r--lib/CodeGen/SelectionDAG/InstrEmitter.cpp989
-rw-r--r--lib/CodeGen/SelectionDAG/InstrEmitter.h142
-rw-r--r--lib/CodeGen/SelectionDAG/LLVMBuild.txt22
-rw-r--r--lib/CodeGen/SelectionDAG/LegalizeDAG.cpp3707
-rw-r--r--lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp1463
-rw-r--r--lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp3029
-rw-r--r--lib/CodeGen/SelectionDAG/LegalizeTypes.cpp1148
-rw-r--r--lib/CodeGen/SelectionDAG/LegalizeTypes.h753
-rw-r--r--lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp521
-rw-r--r--lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp620
-rw-r--r--lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp2717
-rw-r--r--lib/CodeGen/SelectionDAG/Makefile13
-rw-r--r--lib/CodeGen/SelectionDAG/ResourcePriorityQueue.cpp657
-rw-r--r--lib/CodeGen/SelectionDAG/SDNodeDbgValue.h114
-rw-r--r--lib/CodeGen/SelectionDAG/SDNodeOrdering.h54
-rw-r--r--lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp639
-rw-r--r--lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp3010
-rw-r--r--lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp914
-rw-r--r--lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.h178
-rw-r--r--lib/CodeGen/SelectionDAG/ScheduleDAGVLIW.cpp276
-rw-r--r--lib/CodeGen/SelectionDAG/SelectionDAG.cpp6262
-rw-r--r--lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp6925
-rw-r--r--lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h566
-rw-r--r--lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp644
-rw-r--r--lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp3011
-rw-r--r--lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp299
-rw-r--r--lib/CodeGen/SelectionDAG/TargetLowering.cpp3445
-rw-r--r--lib/CodeGen/SelectionDAG/TargetSelectionDAGInfo.cpp23
-rw-r--r--lib/CodeGen/ShadowStackGC.cpp452
-rw-r--r--lib/CodeGen/ShrinkWrapping.cpp1153
-rw-r--r--lib/CodeGen/SjLjEHPrepare.cpp493
-rw-r--r--lib/CodeGen/SlotIndexes.cpp180
-rw-r--r--lib/CodeGen/SpillPlacement.cpp380
-rw-r--r--lib/CodeGen/SpillPlacement.h156
-rw-r--r--lib/CodeGen/Spiller.cpp194
-rw-r--r--lib/CodeGen/Spiller.h47
-rw-r--r--lib/CodeGen/SplitKit.cpp1432
-rw-r--r--lib/CodeGen/SplitKit.h469
-rw-r--r--lib/CodeGen/StackColoring.cpp775
-rw-r--r--lib/CodeGen/StackProtector.cpp283
-rw-r--r--lib/CodeGen/StackSlotColoring.cpp439
-rw-r--r--lib/CodeGen/StrongPHIElimination.cpp825
-rw-r--r--lib/CodeGen/TailDuplication.cpp970
-rw-r--r--lib/CodeGen/TargetFrameLoweringImpl.cpp45
-rw-r--r--lib/CodeGen/TargetInstrInfoImpl.cpp679
-rw-r--r--lib/CodeGen/TargetLoweringObjectFileImpl.cpp750
-rw-r--r--lib/CodeGen/TargetOptionsImpl.cpp52
-rw-r--r--lib/CodeGen/TargetSchedule.cpp182
-rw-r--r--lib/CodeGen/TwoAddressInstructionPass.cpp1783
-rw-r--r--lib/CodeGen/UnreachableBlockElim.cpp215
-rw-r--r--lib/CodeGen/VirtRegMap.cpp351
-rw-r--r--lib/CodeGen/VirtRegMap.h190
-rw-r--r--lib/DebugInfo/CMakeLists.txt13
-rw-r--r--lib/DebugInfo/DIContext.cpp26
-rw-r--r--lib/DebugInfo/DWARFAbbreviationDeclaration.cpp83
-rw-r--r--lib/DebugInfo/DWARFAbbreviationDeclaration.h54
-rw-r--r--lib/DebugInfo/DWARFAttribute.h30
-rw-r--r--lib/DebugInfo/DWARFCompileUnit.cpp275
-rw-r--r--lib/DebugInfo/DWARFCompileUnit.h124
-rw-r--r--lib/DebugInfo/DWARFContext.cpp296
-rw-r--r--lib/DebugInfo/DWARFContext.h131
-rw-r--r--lib/DebugInfo/DWARFDebugAbbrev.cpp106
-rw-r--r--lib/DebugInfo/DWARFDebugAbbrev.h73
-rw-r--r--lib/DebugInfo/DWARFDebugArangeSet.cpp151
-rw-r--r--lib/DebugInfo/DWARFDebugArangeSet.h75
-rw-r--r--lib/DebugInfo/DWARFDebugAranges.cpp223
-rw-r--r--lib/DebugInfo/DWARFDebugAranges.h98
-rw-r--r--lib/DebugInfo/DWARFDebugInfoEntry.cpp577
-rw-r--r--lib/DebugInfo/DWARFDebugInfoEntry.h176
-rw-r--r--lib/DebugInfo/DWARFDebugLine.cpp542
-rw-r--r--lib/DebugInfo/DWARFDebugLine.h246
-rw-r--r--lib/DebugInfo/DWARFDebugRangeList.cpp67
-rw-r--r--lib/DebugInfo/DWARFDebugRangeList.h78
-rw-r--r--lib/DebugInfo/DWARFFormValue.cpp476
-rw-r--r--lib/DebugInfo/DWARFFormValue.h78
-rw-r--r--lib/DebugInfo/LLVMBuild.txt22
-rw-r--r--lib/DebugInfo/Makefile14
-rw-r--r--lib/ExecutionEngine/CMakeLists.txt20
-rw-r--r--lib/ExecutionEngine/EventListenerCommon.h67
-rw-r--r--lib/ExecutionEngine/ExecutionEngine.cpp1155
-rw-r--r--lib/ExecutionEngine/ExecutionEngineBindings.cpp252
-rw-r--r--lib/ExecutionEngine/IntelJITEvents/CMakeLists.txt11
-rw-r--r--lib/ExecutionEngine/IntelJITEvents/IntelJITEventListener.cpp183
-rw-r--r--lib/ExecutionEngine/IntelJITEvents/LLVMBuild.txt23
-rw-r--r--lib/ExecutionEngine/IntelJITEvents/Makefile17
-rw-r--r--lib/ExecutionEngine/Interpreter/CMakeLists.txt19
-rw-r--r--lib/ExecutionEngine/Interpreter/Execution.cpp1361
-rw-r--r--lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp484
-rw-r--r--lib/ExecutionEngine/Interpreter/Interpreter.cpp98
-rw-r--r--lib/ExecutionEngine/Interpreter/Interpreter.h247
-rw-r--r--lib/ExecutionEngine/Interpreter/LLVMBuild.txt22
-rw-r--r--lib/ExecutionEngine/Interpreter/Makefile13
-rw-r--r--lib/ExecutionEngine/JIT/CMakeLists.txt9
-rw-r--r--lib/ExecutionEngine/JIT/JIT.cpp847
-rw-r--r--lib/ExecutionEngine/JIT/JIT.h226
-rw-r--r--lib/ExecutionEngine/JIT/JITDwarfEmitter.cpp596
-rw-r--r--lib/ExecutionEngine/JIT/JITDwarfEmitter.h73
-rw-r--r--lib/ExecutionEngine/JIT/JITEmitter.cpp1299
-rw-r--r--lib/ExecutionEngine/JIT/JITMemoryManager.cpp924
-rw-r--r--lib/ExecutionEngine/JIT/LLVMBuild.txt22
-rw-r--r--lib/ExecutionEngine/JIT/Makefile38
-rw-r--r--lib/ExecutionEngine/LLVMBuild.txt25
-rw-r--r--lib/ExecutionEngine/MCJIT/CMakeLists.txt4
-rw-r--r--lib/ExecutionEngine/MCJIT/LLVMBuild.txt22
-rw-r--r--lib/ExecutionEngine/MCJIT/MCJIT.cpp274
-rw-r--r--lib/ExecutionEngine/MCJIT/MCJIT.h106
-rw-r--r--lib/ExecutionEngine/MCJIT/MCJITMemoryManager.cpp14
-rw-r--r--lib/ExecutionEngine/MCJIT/MCJITMemoryManager.h50
-rw-r--r--lib/ExecutionEngine/MCJIT/Makefile13
-rw-r--r--lib/ExecutionEngine/Makefile24
-rw-r--r--lib/ExecutionEngine/OProfileJIT/CMakeLists.txt7
-rw-r--r--lib/ExecutionEngine/OProfileJIT/LLVMBuild.txt23
-rw-r--r--lib/ExecutionEngine/OProfileJIT/Makefile18
-rw-r--r--lib/ExecutionEngine/OProfileJIT/OProfileJITEventListener.cpp177
-rw-r--r--lib/ExecutionEngine/OProfileJIT/OProfileWrapper.cpp263
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/CMakeLists.txt6
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/GDBRegistrar.cpp214
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/JITRegistrar.h43
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/LLVMBuild.txt22
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/Makefile13
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/ObjectImage.h59
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp504
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp529
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h77
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h308
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp307
-rw-r--r--lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.h71
-rw-r--r--lib/ExecutionEngine/TargetSelect.cpp93
-rw-r--r--lib/LLVMBuild.txt24
-rw-r--r--lib/Linker/CMakeLists.txt6
-rw-r--r--lib/Linker/LLVMBuild.txt22
-rw-r--r--lib/Linker/LinkArchives.cpp197
-rw-r--r--lib/Linker/LinkItems.cpp241
-rw-r--r--lib/Linker/LinkModules.cpp1353
-rw-r--r--lib/Linker/Linker.cpp181
-rw-r--r--lib/Linker/Makefile15
-rw-r--r--lib/MC/CMakeLists.txt49
-rw-r--r--lib/MC/ELFObjectWriter.cpp1564
-rw-r--r--lib/MC/LLVMBuild.txt25
-rw-r--r--lib/MC/MCAsmBackend.cpp46
-rw-r--r--lib/MC/MCAsmInfo.cpp140
-rw-r--r--lib/MC/MCAsmInfoCOFF.cpp53
-rw-r--r--lib/MC/MCAsmInfoDarwin.cpp64
-rw-r--r--lib/MC/MCAsmStreamer.cpp1355
-rw-r--r--lib/MC/MCAssembler.cpp984
-rw-r--r--lib/MC/MCAtom.cpp97
-rw-r--r--lib/MC/MCCodeEmitter.cpp18
-rw-r--r--lib/MC/MCCodeGenInfo.cpp23
-rw-r--r--lib/MC/MCContext.cpp348
-rw-r--r--lib/MC/MCDisassembler.cpp14
-rw-r--r--lib/MC/MCDisassembler/CMakeLists.txt8
-rw-r--r--lib/MC/MCDisassembler/Disassembler.cpp186
-rw-r--r--lib/MC/MCDisassembler/Disassembler.h117
-rw-r--r--lib/MC/MCDisassembler/EDDisassembler.cpp399
-rw-r--r--lib/MC/MCDisassembler/EDDisassembler.h271
-rw-r--r--lib/MC/MCDisassembler/EDInfo.h84
-rw-r--r--lib/MC/MCDisassembler/EDInst.cpp212
-rw-r--r--lib/MC/MCDisassembler/EDInst.h182
-rw-r--r--lib/MC/MCDisassembler/EDMain.cpp276
-rw-r--r--lib/MC/MCDisassembler/EDOperand.cpp315
-rw-r--r--lib/MC/MCDisassembler/EDOperand.h91
-rw-r--r--lib/MC/MCDisassembler/EDToken.cpp214
-rw-r--r--lib/MC/MCDisassembler/EDToken.h139
-rw-r--r--lib/MC/MCDisassembler/LLVMBuild.txt22
-rw-r--r--lib/MC/MCDisassembler/Makefile14
-rw-r--r--lib/MC/MCDwarf.cpp1462
-rw-r--r--lib/MC/MCELF.cpp71
-rw-r--r--lib/MC/MCELF.h35
-rw-r--r--lib/MC/MCELFObjectTargetWriter.cpp48
-rw-r--r--lib/MC/MCELFStreamer.cpp523
-rw-r--r--lib/MC/MCExpr.cpp635
-rw-r--r--lib/MC/MCInst.cpp72
-rw-r--r--lib/MC/MCInstPrinter.cpp38
-rw-r--r--lib/MC/MCInstrAnalysis.cpp21
-rw-r--r--lib/MC/MCLabel.cpp23
-rw-r--r--lib/MC/MCMachOStreamer.cpp466
-rw-r--r--lib/MC/MCMachObjectTargetWriter.cpp22
-rw-r--r--lib/MC/MCModule.cpp45
-rw-r--r--lib/MC/MCNullStreamer.cpp110
-rw-r--r--lib/MC/MCObjectFileInfo.cpp591
-rw-r--r--lib/MC/MCObjectStreamer.cpp284
-rw-r--r--lib/MC/MCObjectWriter.cpp56
-rw-r--r--lib/MC/MCParser/AsmLexer.cpp469
-rw-r--r--lib/MC/MCParser/AsmParser.cpp3422
-rw-r--r--lib/MC/MCParser/CMakeLists.txt11
-rw-r--r--lib/MC/MCParser/COFFAsmParser.cpp498
-rw-r--r--lib/MC/MCParser/DarwinAsmParser.cpp747
-rw-r--r--lib/MC/MCParser/ELFAsmParser.cpp611
-rw-r--r--lib/MC/MCParser/LLVMBuild.txt22
-rw-r--r--lib/MC/MCParser/MCAsmLexer.cpp31
-rw-r--r--lib/MC/MCParser/MCAsmParser.cpp50
-rw-r--r--lib/MC/MCParser/MCAsmParserExtension.cpp22
-rw-r--r--lib/MC/MCParser/MCTargetAsmParser.cpp19
-rw-r--r--lib/MC/MCParser/Makefile15
-rw-r--r--lib/MC/MCPureStreamer.cpp236
-rw-r--r--lib/MC/MCRegisterInfo.cpp74
-rw-r--r--lib/MC/MCSection.cpp22
-rw-r--r--lib/MC/MCSectionCOFF.cpp84
-rw-r--r--lib/MC/MCSectionELF.cpp150
-rw-r--r--lib/MC/MCSectionMachO.cpp303
-rw-r--r--lib/MC/MCStreamer.cpp602
-rw-r--r--lib/MC/MCSubtargetInfo.cpp118
-rw-r--r--lib/MC/MCSymbol.cpp83
-rw-r--r--lib/MC/MCTargetAsmLexer.cpp16
-rw-r--r--lib/MC/MCValue.cpp38
-rw-r--r--lib/MC/MCWin64EH.cpp278
-rw-r--r--lib/MC/MachObjectWriter.cpp879
-rw-r--r--lib/MC/Makefile16
-rw-r--r--lib/MC/SubtargetFeature.cpp397
-rw-r--r--lib/MC/WinCOFFObjectWriter.cpp904
-rw-r--r--lib/MC/WinCOFFStreamer.cpp418
-rw-r--r--lib/Makefile17
-rw-r--r--lib/Object/Archive.cpp272
-rw-r--r--lib/Object/Binary.cpp103
-rw-r--r--lib/Object/CMakeLists.txt11
-rw-r--r--lib/Object/COFFObjectFile.cpp825
-rw-r--r--lib/Object/ELFObjectFile.cpp40
-rw-r--r--lib/Object/Error.cpp57
-rw-r--r--lib/Object/LLVMBuild.txt22
-rw-r--r--lib/Object/MachOObject.cpp410
-rw-r--r--lib/Object/MachOObjectFile.cpp1295
-rw-r--r--lib/Object/Makefile14
-rw-r--r--lib/Object/Object.cpp218
-rw-r--r--lib/Object/ObjectFile.cpp64
-rw-r--r--lib/Support/APFloat.cpp3644
-rw-r--r--lib/Support/APInt.cpp2870
-rw-r--r--lib/Support/APSInt.cpp23
-rw-r--r--lib/Support/Allocator.cpp188
-rw-r--r--lib/Support/Atomic.cpp112
-rw-r--r--lib/Support/BlockFrequency.cpp130
-rw-r--r--lib/Support/BranchProbability.cpp36
-rw-r--r--lib/Support/CMakeLists.txt114
-rw-r--r--lib/Support/COPYRIGHT.regex54
-rw-r--r--lib/Support/CommandLine.cpp1428
-rw-r--r--lib/Support/ConstantRange.cpp731
-rw-r--r--lib/Support/CrashRecoveryContext.cpp346
-rw-r--r--lib/Support/DAGDeltaAlgorithm.cpp360
-rw-r--r--lib/Support/DataExtractor.cpp175
-rw-r--r--lib/Support/DataStream.cpp98
-rw-r--r--lib/Support/Debug.cpp134
-rw-r--r--lib/Support/DeltaAlgorithm.cpp114
-rw-r--r--lib/Support/Disassembler.cpp75
-rw-r--r--lib/Support/Dwarf.cpp709
-rw-r--r--lib/Support/DynamicLibrary.cpp189
-rw-r--r--lib/Support/Errno.cpp74
-rw-r--r--lib/Support/ErrorHandling.cpp99
-rw-r--r--lib/Support/FileOutputBuffer.cpp148
-rw-r--r--lib/Support/FileUtilities.cpp280
-rw-r--r--lib/Support/FoldingSet.cpp426
-rw-r--r--lib/Support/FormattedStream.cpp101
-rw-r--r--lib/Support/GraphWriter.cpp198
-rw-r--r--lib/Support/Hashing.cpp29
-rw-r--r--lib/Support/Host.cpp519
-rw-r--r--lib/Support/IncludeFile.cpp20
-rw-r--r--lib/Support/IntEqClasses.cpp70
-rw-r--r--lib/Support/IntervalMap.cpp161
-rw-r--r--lib/Support/IntrusiveRefCntPtr.cpp14
-rw-r--r--lib/Support/IsInf.cpp49
-rw-r--r--lib/Support/IsNAN.cpp33
-rw-r--r--lib/Support/LLVMBuild.txt21
-rw-r--r--lib/Support/Locale.cpp10
-rw-r--r--lib/Support/LocaleGeneric.inc17
-rw-r--r--lib/Support/LocaleWindows.inc15
-rw-r--r--lib/Support/LocaleXlocale.inc61
-rw-r--r--lib/Support/LockFileManager.cpp216
-rw-r--r--lib/Support/Makefile22
-rw-r--r--lib/Support/ManagedStatic.cpp81
-rw-r--r--lib/Support/Memory.cpp77
-rw-r--r--lib/Support/MemoryBuffer.cpp389
-rw-r--r--lib/Support/MemoryObject.cpp37
-rw-r--r--lib/Support/Mutex.cpp129
-rw-r--r--lib/Support/Path.cpp296
-rw-r--r--lib/Support/PathV2.cpp921
-rw-r--r--lib/Support/PluginLoader.cpp47
-rw-r--r--lib/Support/PrettyStackTrace.cpp133
-rw-r--r--lib/Support/Process.cpp33
-rw-r--r--lib/Support/Program.cpp57
-rw-r--r--lib/Support/README.txt.system43
-rw-r--r--lib/Support/RWMutex.cpp125
-rw-r--r--lib/Support/Regex.cpp168
-rw-r--r--lib/Support/SearchForAddressOfSpecialSymbol.cpp58
-rw-r--r--lib/Support/Signals.cpp34
-rw-r--r--lib/Support/SmallPtrSet.cpp281
-rw-r--r--lib/Support/SmallVector.cpp40
-rw-r--r--lib/Support/SourceMgr.cpp360
-rw-r--r--lib/Support/Statistic.cpp154
-rw-r--r--lib/Support/StreamableMemoryObject.cpp141
-rw-r--r--lib/Support/StringExtras.cpp59
-rw-r--r--lib/Support/StringMap.cpp238
-rw-r--r--lib/Support/StringPool.cpp35
-rw-r--r--lib/Support/StringRef.cpp468
-rw-r--r--lib/Support/SystemUtils.cpp55
-rw-r--r--lib/Support/TargetRegistry.cpp163
-rw-r--r--lib/Support/ThreadLocal.cpp92
-rw-r--r--lib/Support/Threading.cpp147
-rw-r--r--lib/Support/TimeValue.cpp57
-rw-r--r--lib/Support/Timer.cpp389
-rw-r--r--lib/Support/ToolOutputFile.cpp43
-rw-r--r--lib/Support/Triple.cpp792
-rw-r--r--lib/Support/Twine.cpp171
-rw-r--r--lib/Support/Unix/Host.inc63
-rw-r--r--lib/Support/Unix/Memory.inc159
-rw-r--r--lib/Support/Unix/Mutex.inc43
-rw-r--r--lib/Support/Unix/Path.inc891
-rw-r--r--lib/Support/Unix/PathV2.inc682
-rw-r--r--lib/Support/Unix/Process.inc334
-rw-r--r--lib/Support/Unix/Program.inc430
-rw-r--r--lib/Support/Unix/README.txt16
-rw-r--r--lib/Support/Unix/RWMutex.inc43
-rw-r--r--lib/Support/Unix/Signals.inc355
-rw-r--r--lib/Support/Unix/ThreadLocal.inc26
-rw-r--r--lib/Support/Unix/TimeValue.inc56
-rw-r--r--lib/Support/Unix/Unix.h81
-rw-r--r--lib/Support/Unix/system_error.inc34
-rw-r--r--lib/Support/Valgrind.cpp67
-rw-r--r--lib/Support/Windows/DynamicLibrary.inc163
-rw-r--r--lib/Support/Windows/Host.inc22
-rw-r--r--lib/Support/Windows/Memory.inc120
-rw-r--r--lib/Support/Windows/Mutex.inc58
-rw-r--r--lib/Support/Windows/Path.inc926
-rw-r--r--lib/Support/Windows/PathV2.inc1007
-rw-r--r--lib/Support/Windows/Process.inc259
-rw-r--r--lib/Support/Windows/Program.inc421
-rw-r--r--lib/Support/Windows/RWMutex.inc134
-rw-r--r--lib/Support/Windows/Signals.inc488
-rw-r--r--lib/Support/Windows/ThreadLocal.inc53
-rw-r--r--lib/Support/Windows/TimeValue.inc51
-rw-r--r--lib/Support/Windows/Windows.h150
-rw-r--r--lib/Support/Windows/explicit_symbols.inc66
-rw-r--r--lib/Support/Windows/system_error.inc142
-rw-r--r--lib/Support/YAMLParser.cpp2121
-rw-r--r--lib/Support/circular_raw_ostream.cpp45
-rw-r--r--lib/Support/raw_os_ostream.cpp30
-rw-r--r--lib/Support/raw_ostream.cpp783
-rw-r--r--lib/Support/regcclass.h70
-rw-r--r--lib/Support/regcname.h139
-rw-r--r--lib/Support/regcomp.c1525
-rw-r--r--lib/Support/regengine.inc1034
-rw-r--r--lib/Support/regerror.c135
-rw-r--r--lib/Support/regex2.h157
-rw-r--r--lib/Support/regex_impl.h108
-rw-r--r--lib/Support/regexec.c162
-rw-r--r--lib/Support/regfree.c72
-rw-r--r--lib/Support/regstrlcpy.c52
-rw-r--r--lib/Support/regutils.h53
-rw-r--r--lib/Support/system_error.cpp130
-rw-r--r--lib/TableGen/CMakeLists.txt14
-rw-r--r--lib/TableGen/Error.cpp66
-rw-r--r--lib/TableGen/LLVMBuild.txt22
-rw-r--r--lib/TableGen/Main.cpp127
-rw-r--r--lib/TableGen/Makefile18
-rw-r--r--lib/TableGen/Record.cpp2054
-rw-r--r--lib/TableGen/StringMatcher.cpp149
-rw-r--r--lib/TableGen/TGLexer.cpp478
-rw-r--r--lib/TableGen/TGLexer.h127
-rw-r--r--lib/TableGen/TGParser.cpp2566
-rw-r--r--lib/TableGen/TGParser.h190
-rw-r--r--lib/TableGen/TableGenAction.cpp15
-rw-r--r--lib/TableGen/TableGenBackend.cpp37
-rw-r--r--lib/Target/ARM/ARM.h51
-rw-r--r--lib/Target/ARM/ARM.td275
-rw-r--r--lib/Target/ARM/ARMAsmPrinter.cpp2056
-rw-r--r--lib/Target/ARM/ARMAsmPrinter.h132
-rw-r--r--lib/Target/ARM/ARMBaseInstrInfo.cpp3663
-rw-r--r--lib/Target/ARM/ARMBaseInstrInfo.h412
-rw-r--r--lib/Target/ARM/ARMBaseRegisterInfo.cpp1146
-rw-r--r--lib/Target/ARM/ARMBaseRegisterInfo.h198
-rw-r--r--lib/Target/ARM/ARMBuildAttrs.h131
-rw-r--r--lib/Target/ARM/ARMCallingConv.h159
-rw-r--r--lib/Target/ARM/ARMCallingConv.td204
-rw-r--r--lib/Target/ARM/ARMCodeEmitter.cpp1912
-rw-r--r--lib/Target/ARM/ARMConstantIslandPass.cpp2061
-rw-r--r--lib/Target/ARM/ARMConstantPoolValue.cpp319
-rw-r--r--lib/Target/ARM/ARMConstantPoolValue.h233
-rw-r--r--lib/Target/ARM/ARMELFWriterInfo.cpp78
-rw-r--r--lib/Target/ARM/ARMELFWriterInfo.h59
-rw-r--r--lib/Target/ARM/ARMExpandPseudoInsts.cpp1302
-rw-r--r--lib/Target/ARM/ARMFastISel.cpp2799
-rw-r--r--lib/Target/ARM/ARMFrameLowering.cpp1429
-rw-r--r--lib/Target/ARM/ARMFrameLowering.h77
-rw-r--r--lib/Target/ARM/ARMHazardRecognizer.cpp98
-rw-r--r--lib/Target/ARM/ARMHazardRecognizer.h56
-rw-r--r--lib/Target/ARM/ARMISelDAGToDAG.cpp3345
-rw-r--r--lib/Target/ARM/ARMISelLowering.cpp9921
-rw-r--r--lib/Target/ARM/ARMISelLowering.h558
-rw-r--r--lib/Target/ARM/ARMInstrFormats.td2073
-rw-r--r--lib/Target/ARM/ARMInstrInfo.cpp86
-rw-r--r--lib/Target/ARM/ARMInstrInfo.h46
-rw-r--r--lib/Target/ARM/ARMInstrInfo.td5124
-rw-r--r--lib/Target/ARM/ARMInstrNEON.td6716
-rw-r--r--lib/Target/ARM/ARMInstrThumb.td1420
-rw-r--r--lib/Target/ARM/ARMInstrThumb2.td4329
-rw-r--r--lib/Target/ARM/ARMInstrVFP.td1477
-rw-r--r--lib/Target/ARM/ARMJITInfo.cpp336
-rw-r--r--lib/Target/ARM/ARMJITInfo.h183
-rw-r--r--lib/Target/ARM/ARMLoadStoreOptimizer.cpp1912
-rw-r--r--lib/Target/ARM/ARMMCInstLower.cpp125
-rw-r--r--lib/Target/ARM/ARMMachineFunctionInfo.cpp14
-rw-r--r--lib/Target/ARM/ARMMachineFunctionInfo.h267
-rw-r--r--lib/Target/ARM/ARMPerfectShuffle.h6586
-rw-r--r--lib/Target/ARM/ARMRegisterInfo.cpp24
-rw-r--r--lib/Target/ARM/ARMRegisterInfo.h33
-rw-r--r--lib/Target/ARM/ARMRegisterInfo.td384
-rw-r--r--lib/Target/ARM/ARMRelocations.h62
-rw-r--r--lib/Target/ARM/ARMSchedule.td263
-rw-r--r--lib/Target/ARM/ARMScheduleA8.td1075
-rw-r--r--lib/Target/ARM/ARMScheduleA9.td2486
-rw-r--r--lib/Target/ARM/ARMScheduleV6.td300
-rw-r--r--lib/Target/ARM/ARMSelectionDAGInfo.cpp200
-rw-r--r--lib/Target/ARM/ARMSelectionDAGInfo.h68
-rw-r--r--lib/Target/ARM/ARMSubtarget.cpp197
-rw-r--r--lib/Target/ARM/ARMSubtarget.h281
-rw-r--r--lib/Target/ARM/ARMTargetMachine.cpp202
-rw-r--r--lib/Target/ARM/ARMTargetMachine.h149
-rw-r--r--lib/Target/ARM/ARMTargetObjectFile.cpp40
-rw-r--r--lib/Target/ARM/ARMTargetObjectFile.h38
-rw-r--r--lib/Target/ARM/AsmParser/ARMAsmLexer.cpp138
-rw-r--r--lib/Target/ARM/AsmParser/ARMAsmParser.cpp7783
-rw-r--r--lib/Target/ARM/AsmParser/CMakeLists.txt8
-rw-r--r--lib/Target/ARM/AsmParser/LLVMBuild.txt23
-rw-r--r--lib/Target/ARM/AsmParser/Makefile15
-rw-r--r--lib/Target/ARM/CMakeLists.txt66
-rw-r--r--lib/Target/ARM/Disassembler/ARMDisassembler.cpp4545
-rw-r--r--lib/Target/ARM/Disassembler/CMakeLists.txt13
-rw-r--r--lib/Target/ARM/Disassembler/LLVMBuild.txt23
-rw-r--r--lib/Target/ARM/Disassembler/Makefile16
-rw-r--r--lib/Target/ARM/InstPrinter/ARMInstPrinter.cpp1234
-rw-r--r--lib/Target/ARM/InstPrinter/ARMInstPrinter.h161
-rw-r--r--lib/Target/ARM/InstPrinter/CMakeLists.txt7
-rw-r--r--lib/Target/ARM/InstPrinter/LLVMBuild.txt23
-rw-r--r--lib/Target/ARM/InstPrinter/Makefile15
-rw-r--r--lib/Target/ARM/LLVMBuild.txt35
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMAddressingModes.h668
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp698
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMBaseInfo.h421
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMELFObjectWriter.cpp285
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMFixupKinds.h119
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp60
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h35
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp1514
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMMCExpr.cpp72
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMMCExpr.h76
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp278
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h77
-rw-r--r--lib/Target/ARM/MCTargetDesc/ARMMachObjectWriter.cpp449
-rw-r--r--lib/Target/ARM/MCTargetDesc/CMakeLists.txt14
-rw-r--r--lib/Target/ARM/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/ARM/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/ARM/MLxExpansionPass.cpp333
-rw-r--r--lib/Target/ARM/Makefile24
-rw-r--r--lib/Target/ARM/README-Thumb.txt267
-rw-r--r--lib/Target/ARM/README-Thumb2.txt6
-rw-r--r--lib/Target/ARM/README.txt733
-rw-r--r--lib/Target/ARM/TargetInfo/ARMTargetInfo.cpp23
-rw-r--r--lib/Target/ARM/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/ARM/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/ARM/TargetInfo/Makefile15
-rw-r--r--lib/Target/ARM/Thumb1FrameLowering.cpp369
-rw-r--r--lib/Target/ARM/Thumb1FrameLowering.h52
-rw-r--r--lib/Target/ARM/Thumb1InstrInfo.cpp104
-rw-r--r--lib/Target/ARM/Thumb1InstrInfo.h61
-rw-r--r--lib/Target/ARM/Thumb1RegisterInfo.cpp726
-rw-r--r--lib/Target/ARM/Thumb1RegisterInfo.h69
-rw-r--r--lib/Target/ARM/Thumb2ITBlockPass.cpp274
-rw-r--r--lib/Target/ARM/Thumb2InstrInfo.cpp572
-rw-r--r--lib/Target/ARM/Thumb2InstrInfo.h75
-rw-r--r--lib/Target/ARM/Thumb2RegisterInfo.cpp52
-rw-r--r--lib/Target/ARM/Thumb2RegisterInfo.h42
-rw-r--r--lib/Target/ARM/Thumb2SizeReduction.cpp944
-rw-r--r--lib/Target/CMakeLists.txt20
-rw-r--r--lib/Target/CellSPU/CMakeLists.txt30
-rw-r--r--lib/Target/CellSPU/CellSDKIntrinsics.td449
-rw-r--r--lib/Target/CellSPU/LLVMBuild.txt32
-rw-r--r--lib/Target/CellSPU/MCTargetDesc/CMakeLists.txt6
-rw-r--r--lib/Target/CellSPU/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/CellSPU/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/CellSPU/MCTargetDesc/SPUMCAsmInfo.cpp43
-rw-r--r--lib/Target/CellSPU/MCTargetDesc/SPUMCAsmInfo.h30
-rw-r--r--lib/Target/CellSPU/MCTargetDesc/SPUMCTargetDesc.cpp94
-rw-r--r--lib/Target/CellSPU/MCTargetDesc/SPUMCTargetDesc.h38
-rw-r--r--lib/Target/CellSPU/Makefile20
-rw-r--r--lib/Target/CellSPU/README.txt106
-rw-r--r--lib/Target/CellSPU/SPU.h31
-rw-r--r--lib/Target/CellSPU/SPU.td66
-rw-r--r--lib/Target/CellSPU/SPU128InstrInfo.td41
-rw-r--r--lib/Target/CellSPU/SPU64InstrInfo.td408
-rw-r--r--lib/Target/CellSPU/SPUAsmPrinter.cpp333
-rw-r--r--lib/Target/CellSPU/SPUCallingConv.td53
-rw-r--r--lib/Target/CellSPU/SPUFrameLowering.cpp256
-rw-r--r--lib/Target/CellSPU/SPUFrameLowering.h80
-rw-r--r--lib/Target/CellSPU/SPUHazardRecognizers.cpp135
-rw-r--r--lib/Target/CellSPU/SPUHazardRecognizers.h37
-rw-r--r--lib/Target/CellSPU/SPUISelDAGToDAG.cpp1192
-rw-r--r--lib/Target/CellSPU/SPUISelLowering.cpp3266
-rw-r--r--lib/Target/CellSPU/SPUISelLowering.h178
-rw-r--r--lib/Target/CellSPU/SPUInstrBuilder.h43
-rw-r--r--lib/Target/CellSPU/SPUInstrFormats.td320
-rw-r--r--lib/Target/CellSPU/SPUInstrInfo.cpp449
-rw-r--r--lib/Target/CellSPU/SPUInstrInfo.h84
-rw-r--r--lib/Target/CellSPU/SPUInstrInfo.td4484
-rw-r--r--lib/Target/CellSPU/SPUMachineFunction.cpp14
-rw-r--r--lib/Target/CellSPU/SPUMachineFunction.h50
-rw-r--r--lib/Target/CellSPU/SPUMathInstr.td97
-rw-r--r--lib/Target/CellSPU/SPUNodes.td159
-rw-r--r--lib/Target/CellSPU/SPUNopFiller.cpp153
-rw-r--r--lib/Target/CellSPU/SPUOperands.td664
-rw-r--r--lib/Target/CellSPU/SPURegisterInfo.cpp357
-rw-r--r--lib/Target/CellSPU/SPURegisterInfo.h106
-rw-r--r--lib/Target/CellSPU/SPURegisterInfo.td183
-rw-r--r--lib/Target/CellSPU/SPURegisterNames.h19
-rw-r--r--lib/Target/CellSPU/SPUSchedule.td59
-rw-r--r--lib/Target/CellSPU/SPUSelectionDAGInfo.cpp23
-rw-r--r--lib/Target/CellSPU/SPUSelectionDAGInfo.h31
-rw-r--r--lib/Target/CellSPU/SPUSubtarget.cpp65
-rw-r--r--lib/Target/CellSPU/SPUSubtarget.h97
-rw-r--r--lib/Target/CellSPU/SPUTargetMachine.cpp93
-rw-r--r--lib/Target/CellSPU/SPUTargetMachine.h87
-rw-r--r--lib/Target/CellSPU/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/CellSPU/TargetInfo/CellSPUTargetInfo.cpp20
-rw-r--r--lib/Target/CellSPU/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/CellSPU/TargetInfo/Makefile15
-rw-r--r--lib/Target/CppBackend/CMakeLists.txt5
-rw-r--r--lib/Target/CppBackend/CPPBackend.cpp2110
-rw-r--r--lib/Target/CppBackend/CPPTargetMachine.h46
-rw-r--r--lib/Target/CppBackend/LLVMBuild.txt31
-rw-r--r--lib/Target/CppBackend/Makefile16
-rw-r--r--lib/Target/CppBackend/TargetInfo/CMakeLists.txt5
-rw-r--r--lib/Target/CppBackend/TargetInfo/CppBackendTargetInfo.cpp28
-rw-r--r--lib/Target/CppBackend/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/CppBackend/TargetInfo/Makefile15
-rw-r--r--lib/Target/Hexagon/CMakeLists.txt41
-rw-r--r--lib/Target/Hexagon/Hexagon.h77
-rw-r--r--lib/Target/Hexagon/Hexagon.td76
-rw-r--r--lib/Target/Hexagon/HexagonAsmPrinter.cpp314
-rwxr-xr-xlib/Target/Hexagon/HexagonAsmPrinter.h165
-rw-r--r--lib/Target/Hexagon/HexagonCFGOptimizer.cpp235
-rw-r--r--lib/Target/Hexagon/HexagonCallingConv.td35
-rw-r--r--lib/Target/Hexagon/HexagonCallingConvLower.cpp204
-rw-r--r--lib/Target/Hexagon/HexagonCallingConvLower.h189
-rw-r--r--lib/Target/Hexagon/HexagonExpandPredSpillCode.cpp179
-rw-r--r--lib/Target/Hexagon/HexagonFrameLowering.cpp332
-rw-r--r--lib/Target/Hexagon/HexagonFrameLowering.h50
-rw-r--r--lib/Target/Hexagon/HexagonHardwareLoops.cpp647
-rw-r--r--lib/Target/Hexagon/HexagonISelDAGToDAG.cpp1509
-rw-r--r--lib/Target/Hexagon/HexagonISelLowering.cpp1630
-rw-r--r--lib/Target/Hexagon/HexagonISelLowering.h160
-rw-r--r--lib/Target/Hexagon/HexagonImmediates.td508
-rw-r--r--lib/Target/Hexagon/HexagonInstrFormats.td336
-rw-r--r--lib/Target/Hexagon/HexagonInstrFormatsV4.td67
-rw-r--r--lib/Target/Hexagon/HexagonInstrInfo.cpp2850
-rw-r--r--lib/Target/Hexagon/HexagonInstrInfo.h186
-rw-r--r--lib/Target/Hexagon/HexagonInstrInfo.td3549
-rw-r--r--lib/Target/Hexagon/HexagonInstrInfoV3.td137
-rw-r--r--lib/Target/Hexagon/HexagonInstrInfoV4.td5777
-rw-r--r--lib/Target/Hexagon/HexagonInstrInfoV5.td626
-rw-r--r--lib/Target/Hexagon/HexagonIntrinsics.td3503
-rw-r--r--lib/Target/Hexagon/HexagonIntrinsicsDerived.td39
-rw-r--r--lib/Target/Hexagon/HexagonIntrinsicsV3.td50
-rw-r--r--lib/Target/Hexagon/HexagonIntrinsicsV4.td369
-rw-r--r--lib/Target/Hexagon/HexagonIntrinsicsV5.td395
-rw-r--r--lib/Target/Hexagon/HexagonMCInst.h41
-rw-r--r--lib/Target/Hexagon/HexagonMCInstLower.cpp93
-rw-r--r--lib/Target/Hexagon/HexagonMachineFunctionInfo.h75
-rw-r--r--lib/Target/Hexagon/HexagonMachineScheduler.cpp679
-rw-r--r--lib/Target/Hexagon/HexagonMachineScheduler.h251
-rw-r--r--lib/Target/Hexagon/HexagonNewValueJump.cpp647
-rw-r--r--lib/Target/Hexagon/HexagonPeephole.cpp323
-rw-r--r--lib/Target/Hexagon/HexagonRegisterInfo.cpp374
-rw-r--r--lib/Target/Hexagon/HexagonRegisterInfo.h99
-rw-r--r--lib/Target/Hexagon/HexagonRegisterInfo.td167
-rw-r--r--lib/Target/Hexagon/HexagonRemoveSZExtArgs.cpp82
-rw-r--r--lib/Target/Hexagon/HexagonSchedule.td61
-rw-r--r--lib/Target/Hexagon/HexagonScheduleV4.td66
-rw-r--r--lib/Target/Hexagon/HexagonSelectCCInfo.td121
-rw-r--r--lib/Target/Hexagon/HexagonSelectionDAGInfo.cpp46
-rw-r--r--lib/Target/Hexagon/HexagonSelectionDAGInfo.h40
-rw-r--r--lib/Target/Hexagon/HexagonSplitTFRCondSets.cpp215
-rw-r--r--lib/Target/Hexagon/HexagonSubtarget.cpp77
-rw-r--r--lib/Target/Hexagon/HexagonSubtarget.h80
-rw-r--r--lib/Target/Hexagon/HexagonTargetMachine.cpp167
-rw-r--r--lib/Target/Hexagon/HexagonTargetMachine.h83
-rw-r--r--lib/Target/Hexagon/HexagonTargetObjectFile.cpp94
-rw-r--r--lib/Target/Hexagon/HexagonTargetObjectFile.h40
-rw-r--r--lib/Target/Hexagon/HexagonVLIWPacketizer.cpp3646
-rw-r--r--lib/Target/Hexagon/HexagonVarargsCallingConvention.h141
-rw-r--r--lib/Target/Hexagon/InstPrinter/CMakeLists.txt5
-rw-r--r--lib/Target/Hexagon/InstPrinter/HexagonInstPrinter.cpp198
-rw-r--r--lib/Target/Hexagon/InstPrinter/HexagonInstPrinter.h76
-rw-r--r--lib/Target/Hexagon/InstPrinter/LLVMBuild.txt23
-rw-r--r--lib/Target/Hexagon/InstPrinter/Makefile15
-rw-r--r--lib/Target/Hexagon/LLVMBuild.txt32
-rw-r--r--lib/Target/Hexagon/MCTargetDesc/CMakeLists.txt6
-rw-r--r--lib/Target/Hexagon/MCTargetDesc/HexagonBaseInfo.h70
-rw-r--r--lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.cpp36
-rw-r--r--lib/Target/Hexagon/MCTargetDesc/HexagonMCAsmInfo.h30
-rw-r--r--lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.cpp95
-rw-r--r--lib/Target/Hexagon/MCTargetDesc/HexagonMCTargetDesc.h39
-rw-r--r--lib/Target/Hexagon/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/Hexagon/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/Hexagon/Makefile23
-rw-r--r--lib/Target/Hexagon/TargetInfo/CMakeLists.txt8
-rw-r--r--lib/Target/Hexagon/TargetInfo/HexagonTargetInfo.cpp19
-rw-r--r--lib/Target/Hexagon/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/Hexagon/TargetInfo/Makefile15
-rw-r--r--lib/Target/LLVMBuild.txt56
-rw-r--r--lib/Target/MBlaze/AsmParser/CMakeLists.txt9
-rw-r--r--lib/Target/MBlaze/AsmParser/LLVMBuild.txt23
-rw-r--r--lib/Target/MBlaze/AsmParser/MBlazeAsmLexer.cpp115
-rw-r--r--lib/Target/MBlaze/AsmParser/MBlazeAsmParser.cpp567
-rw-r--r--lib/Target/MBlaze/AsmParser/Makefile15
-rw-r--r--lib/Target/MBlaze/CMakeLists.txt39
-rw-r--r--lib/Target/MBlaze/Disassembler/CMakeLists.txt16
-rw-r--r--lib/Target/MBlaze/Disassembler/LLVMBuild.txt23
-rw-r--r--lib/Target/MBlaze/Disassembler/MBlazeDisassembler.cpp726
-rw-r--r--lib/Target/MBlaze/Disassembler/MBlazeDisassembler.h54
-rw-r--r--lib/Target/MBlaze/Disassembler/Makefile16
-rw-r--r--lib/Target/MBlaze/InstPrinter/CMakeLists.txt8
-rw-r--r--lib/Target/MBlaze/InstPrinter/LLVMBuild.txt23
-rw-r--r--lib/Target/MBlaze/InstPrinter/MBlazeInstPrinter.cpp71
-rw-r--r--lib/Target/MBlaze/InstPrinter/MBlazeInstPrinter.h43
-rw-r--r--lib/Target/MBlaze/InstPrinter/Makefile16
-rw-r--r--lib/Target/MBlaze/LLVMBuild.txt34
-rw-r--r--lib/Target/MBlaze/MBlaze.h32
-rw-r--r--lib/Target/MBlaze/MBlaze.td73
-rw-r--r--lib/Target/MBlaze/MBlazeAsmPrinter.cpp326
-rw-r--r--lib/Target/MBlaze/MBlazeCallingConv.td24
-rw-r--r--lib/Target/MBlaze/MBlazeDelaySlotFiller.cpp254
-rw-r--r--lib/Target/MBlaze/MBlazeELFWriterInfo.cpp107
-rw-r--r--lib/Target/MBlaze/MBlazeELFWriterInfo.h59
-rw-r--r--lib/Target/MBlaze/MBlazeFrameLowering.cpp449
-rw-r--r--lib/Target/MBlaze/MBlazeFrameLowering.h52
-rw-r--r--lib/Target/MBlaze/MBlazeISelDAGToDAG.cpp277
-rw-r--r--lib/Target/MBlaze/MBlazeISelLowering.cpp1154
-rw-r--r--lib/Target/MBlaze/MBlazeISelLowering.h179
-rw-r--r--lib/Target/MBlaze/MBlazeInstrFPU.td219
-rw-r--r--lib/Target/MBlaze/MBlazeInstrFSL.td229
-rw-r--r--lib/Target/MBlaze/MBlazeInstrFormats.td228
-rw-r--r--lib/Target/MBlaze/MBlazeInstrInfo.cpp297
-rw-r--r--lib/Target/MBlaze/MBlazeInstrInfo.h240
-rw-r--r--lib/Target/MBlaze/MBlazeInstrInfo.td1052
-rw-r--r--lib/Target/MBlaze/MBlazeIntrinsicInfo.cpp111
-rw-r--r--lib/Target/MBlaze/MBlazeIntrinsicInfo.h33
-rw-r--r--lib/Target/MBlaze/MBlazeIntrinsics.td131
-rw-r--r--lib/Target/MBlaze/MBlazeMCInstLower.cpp167
-rw-r--r--lib/Target/MBlaze/MBlazeMCInstLower.h47
-rw-r--r--lib/Target/MBlaze/MBlazeMachineFunction.cpp14
-rw-r--r--lib/Target/MBlaze/MBlazeMachineFunction.h169
-rw-r--r--lib/Target/MBlaze/MBlazeRegisterInfo.cpp191
-rw-r--r--lib/Target/MBlaze/MBlazeRegisterInfo.h73
-rw-r--r--lib/Target/MBlaze/MBlazeRegisterInfo.td148
-rw-r--r--lib/Target/MBlaze/MBlazeRelocations.h47
-rw-r--r--lib/Target/MBlaze/MBlazeSchedule.td50
-rw-r--r--lib/Target/MBlaze/MBlazeSchedule3.td236
-rw-r--r--lib/Target/MBlaze/MBlazeSchedule5.td267
-rw-r--r--lib/Target/MBlaze/MBlazeSelectionDAGInfo.cpp23
-rw-r--r--lib/Target/MBlaze/MBlazeSelectionDAGInfo.h31
-rw-r--r--lib/Target/MBlaze/MBlazeSubtarget.cpp56
-rw-r--r--lib/Target/MBlaze/MBlazeSubtarget.h75
-rw-r--r--lib/Target/MBlaze/MBlazeTargetMachine.cpp81
-rw-r--r--lib/Target/MBlaze/MBlazeTargetMachine.h86
-rw-r--r--lib/Target/MBlaze/MBlazeTargetObjectFile.cpp90
-rw-r--r--lib/Target/MBlaze/MBlazeTargetObjectFile.h40
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/CMakeLists.txt9
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/MBlazeAsmBackend.cpp171
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/MBlazeBaseInfo.h237
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/MBlazeELFObjectWriter.cpp77
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/MBlazeMCAsmInfo.cpp26
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/MBlazeMCAsmInfo.h30
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/MBlazeMCCodeEmitter.cpp222
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/MBlazeMCTargetDesc.cpp141
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/MBlazeMCTargetDesc.h56
-rw-r--r--lib/Target/MBlaze/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/MBlaze/Makefile24
-rw-r--r--lib/Target/MBlaze/TODO21
-rw-r--r--lib/Target/MBlaze/TargetInfo/CMakeLists.txt8
-rw-r--r--lib/Target/MBlaze/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/MBlaze/TargetInfo/MBlazeTargetInfo.cpp19
-rw-r--r--lib/Target/MBlaze/TargetInfo/Makefile15
-rw-r--r--lib/Target/MSP430/CMakeLists.txt30
-rw-r--r--lib/Target/MSP430/InstPrinter/CMakeLists.txt7
-rw-r--r--lib/Target/MSP430/InstPrinter/LLVMBuild.txt23
-rw-r--r--lib/Target/MSP430/InstPrinter/MSP430InstPrinter.cpp114
-rw-r--r--lib/Target/MSP430/InstPrinter/MSP430InstPrinter.h44
-rw-r--r--lib/Target/MSP430/InstPrinter/Makefile15
-rw-r--r--lib/Target/MSP430/LLVMBuild.txt32
-rw-r--r--lib/Target/MSP430/MCTargetDesc/CMakeLists.txt6
-rw-r--r--lib/Target/MSP430/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.cpp31
-rw-r--r--lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.h31
-rw-r--r--lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.cpp94
-rw-r--r--lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.h36
-rw-r--r--lib/Target/MSP430/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/MSP430/MSP430.h47
-rw-r--r--lib/Target/MSP430/MSP430.td66
-rw-r--r--lib/Target/MSP430/MSP430AsmPrinter.cpp167
-rw-r--r--lib/Target/MSP430/MSP430BranchSelector.cpp180
-rw-r--r--lib/Target/MSP430/MSP430CallingConv.td37
-rw-r--r--lib/Target/MSP430/MSP430FrameLowering.cpp223
-rw-r--r--lib/Target/MSP430/MSP430FrameLowering.h53
-rw-r--r--lib/Target/MSP430/MSP430ISelDAGToDAG.cpp492
-rw-r--r--lib/Target/MSP430/MSP430ISelLowering.cpp1194
-rw-r--r--lib/Target/MSP430/MSP430ISelLowering.h176
-rw-r--r--lib/Target/MSP430/MSP430InstrFormats.td211
-rw-r--r--lib/Target/MSP430/MSP430InstrInfo.cpp326
-rw-r--r--lib/Target/MSP430/MSP430InstrInfo.h91
-rw-r--r--lib/Target/MSP430/MSP430InstrInfo.td1211
-rw-r--r--lib/Target/MSP430/MSP430MCInstLower.cpp153
-rw-r--r--lib/Target/MSP430/MSP430MCInstLower.h47
-rw-r--r--lib/Target/MSP430/MSP430MachineFunctionInfo.cpp14
-rw-r--r--lib/Target/MSP430/MSP430MachineFunctionInfo.h48
-rw-r--r--lib/Target/MSP430/MSP430RegisterInfo.cpp241
-rw-r--r--lib/Target/MSP430/MSP430RegisterInfo.h60
-rw-r--r--lib/Target/MSP430/MSP430RegisterInfo.td81
-rw-r--r--lib/Target/MSP430/MSP430SelectionDAGInfo.cpp23
-rw-r--r--lib/Target/MSP430/MSP430SelectionDAGInfo.h31
-rw-r--r--lib/Target/MSP430/MSP430Subtarget.cpp34
-rw-r--r--lib/Target/MSP430/MSP430Subtarget.h42
-rw-r--r--lib/Target/MSP430/MSP430TargetMachine.cpp71
-rw-r--r--lib/Target/MSP430/MSP430TargetMachine.h70
-rw-r--r--lib/Target/MSP430/Makefile23
-rw-r--r--lib/Target/MSP430/README.txt40
-rw-r--r--lib/Target/MSP430/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/MSP430/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/MSP430/TargetInfo/MSP430TargetInfo.cpp20
-rw-r--r--lib/Target/MSP430/TargetInfo/Makefile15
-rw-r--r--lib/Target/Makefile20
-rw-r--r--lib/Target/Mangler.cpp237
-rw-r--r--lib/Target/Mips/AsmParser/CMakeLists.txt6
-rw-r--r--lib/Target/Mips/AsmParser/LLVMBuild.txt23
-rw-r--r--lib/Target/Mips/AsmParser/Makefile15
-rw-r--r--lib/Target/Mips/AsmParser/MipsAsmParser.cpp951
-rw-r--r--lib/Target/Mips/CMakeLists.txt50
-rw-r--r--lib/Target/Mips/Disassembler/CMakeLists.txt15
-rw-r--r--lib/Target/Mips/Disassembler/LLVMBuild.txt23
-rw-r--r--lib/Target/Mips/Disassembler/Makefile16
-rw-r--r--lib/Target/Mips/Disassembler/MipsDisassembler.cpp523
-rw-r--r--lib/Target/Mips/InstPrinter/CMakeLists.txt7
-rw-r--r--lib/Target/Mips/InstPrinter/LLVMBuild.txt23
-rw-r--r--lib/Target/Mips/InstPrinter/Makefile16
-rw-r--r--lib/Target/Mips/InstPrinter/MipsInstPrinter.cpp199
-rw-r--r--lib/Target/Mips/InstPrinter/MipsInstPrinter.h100
-rw-r--r--lib/Target/Mips/LLVMBuild.txt35
-rw-r--r--lib/Target/Mips/MCTargetDesc/CMakeLists.txt9
-rw-r--r--lib/Target/Mips/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/Mips/MCTargetDesc/Makefile17
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsAsmBackend.cpp270
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsBaseInfo.h238
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsELFObjectWriter.cpp281
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsFixupKinds.h127
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.cpp42
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.h31
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp311
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp214
-rw-r--r--lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h72
-rw-r--r--lib/Target/Mips/Makefile25
-rw-r--r--lib/Target/Mips/Mips.h33
-rw-r--r--lib/Target/Mips/Mips.td114
-rw-r--r--lib/Target/Mips/Mips16FrameLowering.cpp87
-rw-r--r--lib/Target/Mips/Mips16FrameLowering.h43
-rw-r--r--lib/Target/Mips/Mips16InstrFormats.td663
-rw-r--r--lib/Target/Mips/Mips16InstrInfo.cpp132
-rw-r--r--lib/Target/Mips/Mips16InstrInfo.h76
-rw-r--r--lib/Target/Mips/Mips16InstrInfo.td433
-rw-r--r--lib/Target/Mips/Mips16RegisterInfo.cpp110
-rw-r--r--lib/Target/Mips/Mips16RegisterInfo.h37
-rw-r--r--lib/Target/Mips/Mips64InstrInfo.td309
-rw-r--r--lib/Target/Mips/MipsAnalyzeImmediate.cpp153
-rw-r--r--lib/Target/Mips/MipsAnalyzeImmediate.h63
-rw-r--r--lib/Target/Mips/MipsAsmPrinter.cpp575
-rw-r--r--lib/Target/Mips/MipsAsmPrinter.h81
-rw-r--r--lib/Target/Mips/MipsCallingConv.td243
-rw-r--r--lib/Target/Mips/MipsCodeEmitter.cpp399
-rw-r--r--lib/Target/Mips/MipsCondMov.td234
-rw-r--r--lib/Target/Mips/MipsDelaySlotFiller.cpp269
-rw-r--r--lib/Target/Mips/MipsDirectObjLower.cpp86
-rw-r--r--lib/Target/Mips/MipsDirectObjLower.h28
-rw-r--r--lib/Target/Mips/MipsELFWriterInfo.cpp92
-rw-r--r--lib/Target/Mips/MipsELFWriterInfo.h59
-rw-r--r--lib/Target/Mips/MipsFrameLowering.cpp100
-rw-r--r--lib/Target/Mips/MipsFrameLowering.h45
-rw-r--r--lib/Target/Mips/MipsISelDAGToDAG.cpp602
-rw-r--r--lib/Target/Mips/MipsISelLowering.cpp3495
-rw-r--r--lib/Target/Mips/MipsISelLowering.h224
-rw-r--r--lib/Target/Mips/MipsInstrFPU.td474
-rw-r--r--lib/Target/Mips/MipsInstrFormats.td348
-rw-r--r--lib/Target/Mips/MipsInstrInfo.cpp270
-rw-r--r--lib/Target/Mips/MipsInstrInfo.h97
-rw-r--r--lib/Target/Mips/MipsInstrInfo.td1235
-rw-r--r--lib/Target/Mips/MipsJITInfo.cpp278
-rw-r--r--lib/Target/Mips/MipsJITInfo.h68
-rw-r--r--lib/Target/Mips/MipsLongBranch.cpp443
-rw-r--r--lib/Target/Mips/MipsMCInstLower.cpp162
-rw-r--r--lib/Target/Mips/MipsMCInstLower.h44
-rw-r--r--lib/Target/Mips/MipsMachineFunction.cpp46
-rw-r--r--lib/Target/Mips/MipsMachineFunction.h95
-rw-r--r--lib/Target/Mips/MipsRegisterInfo.cpp198
-rw-r--r--lib/Target/Mips/MipsRegisterInfo.h75
-rw-r--r--lib/Target/Mips/MipsRegisterInfo.td324
-rw-r--r--lib/Target/Mips/MipsRelocations.h41
-rw-r--r--lib/Target/Mips/MipsSEFrameLowering.cpp210
-rw-r--r--lib/Target/Mips/MipsSEFrameLowering.h44
-rw-r--r--lib/Target/Mips/MipsSEInstrInfo.cpp359
-rw-r--r--lib/Target/Mips/MipsSEInstrInfo.h92
-rw-r--r--lib/Target/Mips/MipsSERegisterInfo.cpp137
-rw-r--r--lib/Target/Mips/MipsSERegisterInfo.h42
-rw-r--r--lib/Target/Mips/MipsSchedule.td63
-rw-r--r--lib/Target/Mips/MipsSelectionDAGInfo.cpp23
-rw-r--r--lib/Target/Mips/MipsSelectionDAGInfo.h31
-rw-r--r--lib/Target/Mips/MipsSubtarget.cpp72
-rw-r--r--lib/Target/Mips/MipsSubtarget.h153
-rw-r--r--lib/Target/Mips/MipsTargetMachine.cpp127
-rw-r--r--lib/Target/Mips/MipsTargetMachine.h107
-rw-r--r--lib/Target/Mips/MipsTargetObjectFile.cpp104
-rw-r--r--lib/Target/Mips/MipsTargetObjectFile.h41
-rw-r--r--lib/Target/Mips/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/Mips/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/Mips/TargetInfo/Makefile15
-rw-r--r--lib/Target/Mips/TargetInfo/MipsTargetInfo.cpp31
-rw-r--r--lib/Target/NVPTX/CMakeLists.txt34
-rw-r--r--lib/Target/NVPTX/InstPrinter/CMakeLists.txt7
-rw-r--r--lib/Target/NVPTX/InstPrinter/LLVMBuild.txt23
-rw-r--r--lib/Target/NVPTX/InstPrinter/Makefile15
-rw-r--r--lib/Target/NVPTX/InstPrinter/NVPTXInstPrinter.cpp1
-rw-r--r--lib/Target/NVPTX/LLVMBuild.txt32
-rw-r--r--lib/Target/NVPTX/MCTargetDesc/CMakeLists.txt9
-rw-r--r--lib/Target/NVPTX/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/NVPTX/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/NVPTX/MCTargetDesc/NVPTXBaseInfo.h88
-rw-r--r--lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.cpp63
-rw-r--r--lib/Target/NVPTX/MCTargetDesc/NVPTXMCAsmInfo.h30
-rw-r--r--lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.cpp91
-rw-r--r--lib/Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.h36
-rw-r--r--lib/Target/NVPTX/Makefile23
-rw-r--r--lib/Target/NVPTX/ManagedStringPool.h49
-rw-r--r--lib/Target/NVPTX/NVPTX.h137
-rw-r--r--lib/Target/NVPTX/NVPTX.td44
-rw-r--r--lib/Target/NVPTX/NVPTXAllocaHoisting.cpp48
-rw-r--r--lib/Target/NVPTX/NVPTXAllocaHoisting.h49
-rw-r--r--lib/Target/NVPTX/NVPTXAsmPrinter.cpp2064
-rw-r--r--lib/Target/NVPTX/NVPTXAsmPrinter.h315
-rw-r--r--lib/Target/NVPTX/NVPTXFrameLowering.cpp76
-rw-r--r--lib/Target/NVPTX/NVPTXFrameLowering.h40
-rw-r--r--lib/Target/NVPTX/NVPTXISelDAGToDAG.cpp683
-rw-r--r--lib/Target/NVPTX/NVPTXISelDAGToDAG.h105
-rw-r--r--lib/Target/NVPTX/NVPTXISelLowering.cpp1291
-rw-r--r--lib/Target/NVPTX/NVPTXISelLowering.h144
-rw-r--r--lib/Target/NVPTX/NVPTXInstrFormats.td43
-rw-r--r--lib/Target/NVPTX/NVPTXInstrInfo.cpp326
-rw-r--r--lib/Target/NVPTX/NVPTXInstrInfo.h83
-rw-r--r--lib/Target/NVPTX/NVPTXInstrInfo.td2837
-rw-r--r--lib/Target/NVPTX/NVPTXIntrinsics.td1675
-rw-r--r--lib/Target/NVPTX/NVPTXLowerAggrCopies.cpp208
-rw-r--r--lib/Target/NVPTX/NVPTXLowerAggrCopies.h47
-rw-r--r--lib/Target/NVPTX/NVPTXNumRegisters.h20
-rw-r--r--lib/Target/NVPTX/NVPTXRegisterInfo.cpp325
-rw-r--r--lib/Target/NVPTX/NVPTXRegisterInfo.h92
-rw-r--r--lib/Target/NVPTX/NVPTXRegisterInfo.td108
-rw-r--r--lib/Target/NVPTX/NVPTXSection.h45
-rw-r--r--lib/Target/NVPTX/NVPTXSplitBBatBar.cpp77
-rw-r--r--lib/Target/NVPTX/NVPTXSplitBBatBar.h41
-rw-r--r--lib/Target/NVPTX/NVPTXSubtarget.cpp57
-rw-r--r--lib/Target/NVPTX/NVPTXSubtarget.h92
-rw-r--r--lib/Target/NVPTX/NVPTXTargetMachine.cpp133
-rw-r--r--lib/Target/NVPTX/NVPTXTargetMachine.h125
-rw-r--r--lib/Target/NVPTX/NVPTXTargetObjectFile.h105
-rw-r--r--lib/Target/NVPTX/NVPTXUtilities.cpp514
-rw-r--r--lib/Target/NVPTX/NVPTXUtilities.h94
-rw-r--r--lib/Target/NVPTX/NVPTXVector.td1481
-rw-r--r--lib/Target/NVPTX/NVPTXutil.cpp92
-rw-r--r--lib/Target/NVPTX/NVPTXutil.h25
-rw-r--r--lib/Target/NVPTX/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/NVPTX/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/NVPTX/TargetInfo/Makefile15
-rw-r--r--lib/Target/NVPTX/TargetInfo/NVPTXTargetInfo.cpp23
-rw-r--r--lib/Target/NVPTX/VectorElementize.cpp1248
-rw-r--r--lib/Target/NVPTX/cl_common_defines.h125
-rw-r--r--lib/Target/NVPTX/gen-register-defs.py202
-rw-r--r--lib/Target/PowerPC/CMakeLists.txt36
-rw-r--r--lib/Target/PowerPC/InstPrinter/CMakeLists.txt7
-rw-r--r--lib/Target/PowerPC/InstPrinter/LLVMBuild.txt23
-rw-r--r--lib/Target/PowerPC/InstPrinter/Makefile16
-rw-r--r--lib/Target/PowerPC/InstPrinter/PPCInstPrinter.cpp322
-rw-r--r--lib/Target/PowerPC/InstPrinter/PPCInstPrinter.h69
-rw-r--r--lib/Target/PowerPC/LLVMBuild.txt33
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/CMakeLists.txt10
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp190
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCBaseInfo.h70
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCELFObjectWriter.cpp103
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCFixupKinds.h45
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp68
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h35
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.cpp194
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp155
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h61
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCPredicates.cpp31
-rw-r--r--lib/Target/PowerPC/MCTargetDesc/PPCPredicates.h37
-rw-r--r--lib/Target/PowerPC/Makefile23
-rw-r--r--lib/Target/PowerPC/PPC.h80
-rw-r--r--lib/Target/PowerPC/PPC.td147
-rw-r--r--lib/Target/PowerPC/PPCAsmPrinter.cpp751
-rw-r--r--lib/Target/PowerPC/PPCBranchSelector.cpp186
-rw-r--r--lib/Target/PowerPC/PPCCTRLoops.cpp724
-rw-r--r--lib/Target/PowerPC/PPCCallingConv.td159
-rw-r--r--lib/Target/PowerPC/PPCCodeEmitter.cpp263
-rw-r--r--lib/Target/PowerPC/PPCFrameLowering.cpp1186
-rw-r--r--lib/Target/PowerPC/PPCFrameLowering.h280
-rw-r--r--lib/Target/PowerPC/PPCHazardRecognizers.cpp245
-rw-r--r--lib/Target/PowerPC/PPCHazardRecognizers.h91
-rw-r--r--lib/Target/PowerPC/PPCISelDAGToDAG.cpp1143
-rw-r--r--lib/Target/PowerPC/PPCISelLowering.cpp5990
-rw-r--r--lib/Target/PowerPC/PPCISelLowering.h501
-rw-r--r--lib/Target/PowerPC/PPCInstr64Bit.td880
-rw-r--r--lib/Target/PowerPC/PPCInstrAltivec.td691
-rw-r--r--lib/Target/PowerPC/PPCInstrBuilder.h43
-rw-r--r--lib/Target/PowerPC/PPCInstrFormats.td972
-rw-r--r--lib/Target/PowerPC/PPCInstrInfo.cpp789
-rw-r--r--lib/Target/PowerPC/PPCInstrInfo.h155
-rw-r--r--lib/Target/PowerPC/PPCInstrInfo.td1578
-rw-r--r--lib/Target/PowerPC/PPCJITInfo.cpp470
-rw-r--r--lib/Target/PowerPC/PPCJITInfo.h49
-rw-r--r--lib/Target/PowerPC/PPCMCInstLower.cpp187
-rw-r--r--lib/Target/PowerPC/PPCMachineFunctionInfo.cpp15
-rw-r--r--lib/Target/PowerPC/PPCMachineFunctionInfo.h133
-rw-r--r--lib/Target/PowerPC/PPCPerfectShuffle.h6586
-rw-r--r--lib/Target/PowerPC/PPCRegisterInfo.cpp670
-rw-r--r--lib/Target/PowerPC/PPCRegisterInfo.h84
-rw-r--r--lib/Target/PowerPC/PPCRegisterInfo.td332
-rw-r--r--lib/Target/PowerPC/PPCRelocations.h56
-rw-r--r--lib/Target/PowerPC/PPCSchedule.td519
-rw-r--r--lib/Target/PowerPC/PPCSchedule440.td663
-rw-r--r--lib/Target/PowerPC/PPCScheduleA2.td751
-rw-r--r--lib/Target/PowerPC/PPCScheduleE500mc.td265
-rw-r--r--lib/Target/PowerPC/PPCScheduleE5500.td309
-rw-r--r--lib/Target/PowerPC/PPCScheduleG3.td71
-rw-r--r--lib/Target/PowerPC/PPCScheduleG4.td81
-rw-r--r--lib/Target/PowerPC/PPCScheduleG4Plus.td88
-rw-r--r--lib/Target/PowerPC/PPCScheduleG5.td94
-rw-r--r--lib/Target/PowerPC/PPCSelectionDAGInfo.cpp23
-rw-r--r--lib/Target/PowerPC/PPCSelectionDAGInfo.h31
-rw-r--r--lib/Target/PowerPC/PPCSubtarget.cpp135
-rw-r--r--lib/Target/PowerPC/PPCSubtarget.h167
-rw-r--r--lib/Target/PowerPC/PPCTargetMachine.cpp128
-rw-r--r--lib/Target/PowerPC/PPCTargetMachine.h97
-rw-r--r--lib/Target/PowerPC/README.txt938
-rw-r--r--lib/Target/PowerPC/README_ALTIVEC.txt211
-rw-r--r--lib/Target/PowerPC/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/PowerPC/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/PowerPC/TargetInfo/Makefile15
-rw-r--r--lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.cpp23
-rw-r--r--lib/Target/README.txt2369
-rw-r--r--lib/Target/Sparc/CMakeLists.txt29
-rw-r--r--lib/Target/Sparc/DelaySlotFiller.cpp320
-rw-r--r--lib/Target/Sparc/FPMover.cpp141
-rw-r--r--lib/Target/Sparc/LLVMBuild.txt32
-rw-r--r--lib/Target/Sparc/MCTargetDesc/CMakeLists.txt6
-rw-r--r--lib/Target/Sparc/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/Sparc/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.cpp43
-rw-r--r--lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.h31
-rw-r--r--lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.cpp81
-rw-r--r--lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h39
-rw-r--r--lib/Target/Sparc/Makefile22
-rw-r--r--lib/Target/Sparc/README.txt59
-rw-r--r--lib/Target/Sparc/Sparc.h108
-rw-r--r--lib/Target/Sparc/Sparc.td72
-rw-r--r--lib/Target/Sparc/SparcAsmPrinter.cpp261
-rw-r--r--lib/Target/Sparc/SparcCallingConv.td36
-rw-r--r--lib/Target/Sparc/SparcFrameLowering.cpp80
-rw-r--r--lib/Target/Sparc/SparcFrameLowering.h40
-rw-r--r--lib/Target/Sparc/SparcISelDAGToDAG.cpp211
-rw-r--r--lib/Target/Sparc/SparcISelLowering.cpp1278
-rw-r--r--lib/Target/Sparc/SparcISelLowering.h96
-rw-r--r--lib/Target/Sparc/SparcInstrFormats.td114
-rw-r--r--lib/Target/Sparc/SparcInstrInfo.cpp357
-rw-r--r--lib/Target/Sparc/SparcInstrInfo.h107
-rw-r--r--lib/Target/Sparc/SparcInstrInfo.td825
-rw-r--r--lib/Target/Sparc/SparcMachineFunctionInfo.cpp14
-rw-r--r--lib/Target/Sparc/SparcMachineFunctionInfo.h48
-rw-r--r--lib/Target/Sparc/SparcRegisterInfo.cpp122
-rw-r--r--lib/Target/Sparc/SparcRegisterInfo.h58
-rw-r--r--lib/Target/Sparc/SparcRegisterInfo.td160
-rw-r--r--lib/Target/Sparc/SparcSelectionDAGInfo.cpp23
-rw-r--r--lib/Target/Sparc/SparcSelectionDAGInfo.h31
-rw-r--r--lib/Target/Sparc/SparcSubtarget.cpp46
-rw-r--r--lib/Target/Sparc/SparcSubtarget.h59
-rw-r--r--lib/Target/Sparc/SparcTargetMachine.cpp98
-rw-r--r--lib/Target/Sparc/SparcTargetMachine.h87
-rw-r--r--lib/Target/Sparc/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/Sparc/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/Sparc/TargetInfo/Makefile15
-rw-r--r--lib/Target/Sparc/TargetInfo/SparcTargetInfo.cpp21
-rw-r--r--lib/Target/Target.cpp108
-rw-r--r--lib/Target/TargetData.cpp663
-rw-r--r--lib/Target/TargetELFWriterInfo.cpp25
-rw-r--r--lib/Target/TargetInstrInfo.cpp88
-rw-r--r--lib/Target/TargetIntrinsicInfo.cpp30
-rw-r--r--lib/Target/TargetJITInfo.cpp14
-rw-r--r--lib/Target/TargetLibraryInfo.cpp352
-rw-r--r--lib/Target/TargetLoweringObjectFile.cpp319
-rw-r--r--lib/Target/TargetMachine.cpp164
-rw-r--r--lib/Target/TargetMachineC.cpp197
-rw-r--r--lib/Target/TargetRegisterInfo.cpp248
-rw-r--r--lib/Target/TargetSubtargetInfo.cpp33
-rw-r--r--lib/Target/X86/AsmParser/CMakeLists.txt8
-rw-r--r--lib/Target/X86/AsmParser/LLVMBuild.txt23
-rw-r--r--lib/Target/X86/AsmParser/Makefile15
-rw-r--r--lib/Target/X86/AsmParser/X86AsmLexer.cpp160
-rw-r--r--lib/Target/X86/AsmParser/X86AsmParser.cpp1826
-rw-r--r--lib/Target/X86/CMakeLists.txt62
-rw-r--r--lib/Target/X86/Disassembler/CMakeLists.txt16
-rw-r--r--lib/Target/X86/Disassembler/LLVMBuild.txt23
-rw-r--r--lib/Target/X86/Disassembler/Makefile16
-rw-r--r--lib/Target/X86/Disassembler/X86Disassembler.cpp821
-rw-r--r--lib/Target/X86/Disassembler/X86Disassembler.h135
-rw-r--r--lib/Target/X86/Disassembler/X86DisassemblerDecoder.c1663
-rw-r--r--lib/Target/X86/Disassembler/X86DisassemblerDecoder.h588
-rw-r--r--lib/Target/X86/Disassembler/X86DisassemblerDecoderCommon.h398
-rw-r--r--lib/Target/X86/InstPrinter/CMakeLists.txt9
-rw-r--r--lib/Target/X86/InstPrinter/LLVMBuild.txt23
-rw-r--r--lib/Target/X86/InstPrinter/Makefile15
-rw-r--r--lib/Target/X86/InstPrinter/X86ATTInstPrinter.cpp172
-rw-r--r--lib/Target/X86/InstPrinter/X86ATTInstPrinter.h86
-rw-r--r--lib/Target/X86/InstPrinter/X86InstComments.cpp572
-rw-r--r--lib/Target/X86/InstPrinter/X86InstComments.h25
-rw-r--r--lib/Target/X86/InstPrinter/X86IntelInstPrinter.cpp178
-rw-r--r--lib/Target/X86/InstPrinter/X86IntelInstPrinter.h95
-rw-r--r--lib/Target/X86/LLVMBuild.txt35
-rw-r--r--lib/Target/X86/MCTargetDesc/CMakeLists.txt14
-rw-r--r--lib/Target/X86/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/X86/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp474
-rw-r--r--lib/Target/X86/MCTargetDesc/X86BaseInfo.h624
-rw-r--r--lib/Target/X86/MCTargetDesc/X86ELFObjectWriter.cpp224
-rw-r--r--lib/Target/X86/MCTargetDesc/X86FixupKinds.h33
-rw-r--r--lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp145
-rw-r--r--lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h58
-rw-r--r--lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp1223
-rw-r--r--lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp544
-rw-r--r--lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h115
-rw-r--r--lib/Target/X86/MCTargetDesc/X86MachObjectWriter.cpp554
-rw-r--r--lib/Target/X86/MCTargetDesc/X86WinCOFFObjectWriter.cpp65
-rw-r--r--lib/Target/X86/Makefile24
-rw-r--r--lib/Target/X86/README-FPStack.txt85
-rw-r--r--lib/Target/X86/README-MMX.txt71
-rw-r--r--lib/Target/X86/README-SSE.txt955
-rw-r--r--lib/Target/X86/README-UNIMPLEMENTED.txt14
-rw-r--r--lib/Target/X86/README-X86-64.txt184
-rw-r--r--lib/Target/X86/README.txt2080
-rw-r--r--lib/Target/X86/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/X86/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/X86/TargetInfo/Makefile16
-rw-r--r--lib/Target/X86/TargetInfo/X86TargetInfo.cpp23
-rw-r--r--lib/Target/X86/Utils/CMakeLists.txt7
-rw-r--r--lib/Target/X86/Utils/LLVMBuild.txt23
-rw-r--r--lib/Target/X86/Utils/Makefile15
-rw-r--r--lib/Target/X86/Utils/X86ShuffleDecode.cpp199
-rw-r--r--lib/Target/X86/Utils/X86ShuffleDecode.h69
-rw-r--r--lib/Target/X86/X86.h74
-rw-r--r--lib/Target/X86/X86.td313
-rw-r--r--lib/Target/X86/X86AsmPrinter.cpp747
-rw-r--r--lib/Target/X86/X86AsmPrinter.h82
-rw-r--r--lib/Target/X86/X86COFFMachineModuleInfo.cpp19
-rw-r--r--lib/Target/X86/X86COFFMachineModuleInfo.h46
-rw-r--r--lib/Target/X86/X86CallingConv.td428
-rw-r--r--lib/Target/X86/X86CodeEmitter.cpp1484
-rw-r--r--lib/Target/X86/X86CompilationCallback_Win64.asm68
-rw-r--r--lib/Target/X86/X86ELFWriterInfo.cpp147
-rw-r--r--lib/Target/X86/X86ELFWriterInfo.h59
-rw-r--r--lib/Target/X86/X86FastISel.cpp2212
-rw-r--r--lib/Target/X86/X86FloatingPoint.cpp1768
-rw-r--r--lib/Target/X86/X86FrameLowering.cpp1584
-rw-r--r--lib/Target/X86/X86FrameLowering.h70
-rw-r--r--lib/Target/X86/X86ISelDAGToDAG.cpp2744
-rw-r--r--lib/Target/X86/X86ISelLowering.cpp16873
-rw-r--r--lib/Target/X86/X86ISelLowering.h940
-rw-r--r--lib/Target/X86/X86Instr3DNow.td102
-rw-r--r--lib/Target/X86/X86InstrArithmetic.td1242
-rw-r--r--lib/Target/X86/X86InstrBuilder.h183
-rw-r--r--lib/Target/X86/X86InstrCMovSetCC.td110
-rw-r--r--lib/Target/X86/X86InstrCompiler.td1844
-rw-r--r--lib/Target/X86/X86InstrControl.td273
-rw-r--r--lib/Target/X86/X86InstrExtension.td173
-rw-r--r--lib/Target/X86/X86InstrFMA.td365
-rw-r--r--lib/Target/X86/X86InstrFPStack.td680
-rw-r--r--lib/Target/X86/X86InstrFormats.td656
-rw-r--r--lib/Target/X86/X86InstrFragmentsSIMD.td417
-rw-r--r--lib/Target/X86/X86InstrInfo.cpp4822
-rw-r--r--lib/Target/X86/X86InstrInfo.h416
-rw-r--r--lib/Target/X86/X86InstrInfo.td2051
-rw-r--r--lib/Target/X86/X86InstrMMX.td590
-rw-r--r--lib/Target/X86/X86InstrSSE.td8080
-rw-r--r--lib/Target/X86/X86InstrSVM.td62
-rw-r--r--lib/Target/X86/X86InstrShiftRotate.td876
-rw-r--r--lib/Target/X86/X86InstrSystem.td500
-rw-r--r--lib/Target/X86/X86InstrVMX.td66
-rw-r--r--lib/Target/X86/X86InstrXOP.td310
-rw-r--r--lib/Target/X86/X86JITInfo.cpp587
-rw-r--r--lib/Target/X86/X86JITInfo.h81
-rw-r--r--lib/Target/X86/X86MCInstLower.cpp744
-rw-r--r--lib/Target/X86/X86MCInstLower.h52
-rw-r--r--lib/Target/X86/X86MachineFunctionInfo.cpp14
-rw-r--r--lib/Target/X86/X86MachineFunctionInfo.h145
-rw-r--r--lib/Target/X86/X86RegisterInfo.cpp815
-rw-r--r--lib/Target/X86/X86RegisterInfo.h149
-rw-r--r--lib/Target/X86/X86RegisterInfo.td417
-rw-r--r--lib/Target/X86/X86Relocations.h52
-rw-r--r--lib/Target/X86/X86Schedule.td481
-rw-r--r--lib/Target/X86/X86ScheduleAtom.td530
-rw-r--r--lib/Target/X86/X86SelectionDAGInfo.cpp262
-rw-r--r--lib/Target/X86/X86SelectionDAGInfo.h56
-rw-r--r--lib/Target/X86/X86Subtarget.cpp436
-rw-r--r--lib/Target/X86/X86Subtarget.h326
-rw-r--r--lib/Target/X86/X86TargetMachine.cpp196
-rw-r--r--lib/Target/X86/X86TargetMachine.h139
-rw-r--r--lib/Target/X86/X86TargetObjectFile.cpp53
-rw-r--r--lib/Target/X86/X86TargetObjectFile.h43
-rw-r--r--lib/Target/X86/X86VZeroUpper.cpp283
-rw-r--r--lib/Target/XCore/CMakeLists.txt28
-rw-r--r--lib/Target/XCore/LLVMBuild.txt32
-rw-r--r--lib/Target/XCore/MCTargetDesc/CMakeLists.txt9
-rw-r--r--lib/Target/XCore/MCTargetDesc/LLVMBuild.txt23
-rw-r--r--lib/Target/XCore/MCTargetDesc/Makefile16
-rw-r--r--lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.cpp32
-rw-r--r--lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.h31
-rw-r--r--lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.cpp90
-rw-r--r--lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h38
-rw-r--r--lib/Target/XCore/Makefile23
-rw-r--r--lib/Target/XCore/README.txt7
-rw-r--r--lib/Target/XCore/TargetInfo/CMakeLists.txt7
-rw-r--r--lib/Target/XCore/TargetInfo/LLVMBuild.txt23
-rw-r--r--lib/Target/XCore/TargetInfo/Makefile16
-rw-r--r--lib/Target/XCore/TargetInfo/XCoreTargetInfo.cpp19
-rw-r--r--lib/Target/XCore/XCore.h32
-rw-r--r--lib/Target/XCore/XCore.td47
-rw-r--r--lib/Target/XCore/XCoreAsmPrinter.cpp334
-rw-r--r--lib/Target/XCore/XCoreCallingConv.td36
-rw-r--r--lib/Target/XCore/XCoreFrameLowering.cpp373
-rw-r--r--lib/Target/XCore/XCoreFrameLowering.h54
-rw-r--r--lib/Target/XCore/XCoreISelDAGToDAG.cpp301
-rw-r--r--lib/Target/XCore/XCoreISelLowering.cpp1624
-rw-r--r--lib/Target/XCore/XCoreISelLowering.h195
-rw-r--r--lib/Target/XCore/XCoreInstrFormats.td120
-rw-r--r--lib/Target/XCore/XCoreInstrInfo.cpp406
-rw-r--r--lib/Target/XCore/XCoreInstrInfo.h93
-rw-r--r--lib/Target/XCore/XCoreInstrInfo.td1249
-rw-r--r--lib/Target/XCore/XCoreMachineFunctionInfo.cpp14
-rw-r--r--lib/Target/XCore/XCoreMachineFunctionInfo.h69
-rw-r--r--lib/Target/XCore/XCoreRegisterInfo.cpp317
-rw-r--r--lib/Target/XCore/XCoreRegisterInfo.h73
-rw-r--r--lib/Target/XCore/XCoreRegisterInfo.td56
-rw-r--r--lib/Target/XCore/XCoreSelectionDAGInfo.cpp23
-rw-r--r--lib/Target/XCore/XCoreSelectionDAGInfo.h31
-rw-r--r--lib/Target/XCore/XCoreSubtarget.cpp30
-rw-r--r--lib/Target/XCore/XCoreSubtarget.h43
-rw-r--r--lib/Target/XCore/XCoreTargetMachine.cpp65
-rw-r--r--lib/Target/XCore/XCoreTargetMachine.h64
-rw-r--r--lib/Target/XCore/XCoreTargetObjectFile.cpp65
-rw-r--r--lib/Target/XCore/XCoreTargetObjectFile.h25
-rw-r--r--lib/Transforms/CMakeLists.txt7
-rw-r--r--lib/Transforms/Hello/CMakeLists.txt3
-rw-r--r--lib/Transforms/Hello/Hello.cpp64
-rw-r--r--lib/Transforms/Hello/Hello.exports0
-rw-r--r--lib/Transforms/Hello/Makefile24
-rw-r--r--lib/Transforms/IPO/ArgumentPromotion.cpp899
-rw-r--r--lib/Transforms/IPO/CMakeLists.txt24
-rw-r--r--lib/Transforms/IPO/ConstantMerge.cpp229
-rw-r--r--lib/Transforms/IPO/DeadArgumentElimination.cpp1001
-rw-r--r--lib/Transforms/IPO/ExtractGV.cpp92
-rw-r--r--lib/Transforms/IPO/FunctionAttrs.cpp597
-rw-r--r--lib/Transforms/IPO/GlobalDCE.cpp211
-rw-r--r--lib/Transforms/IPO/GlobalOpt.cpp3152
-rw-r--r--lib/Transforms/IPO/IPConstantPropagation.cpp279
-rw-r--r--lib/Transforms/IPO/IPO.cpp107
-rw-r--r--lib/Transforms/IPO/InlineAlways.cpp132
-rw-r--r--lib/Transforms/IPO/InlineSimple.cpp68
-rw-r--r--lib/Transforms/IPO/Inliner.cpp578
-rw-r--r--lib/Transforms/IPO/Internalize.cpp198
-rw-r--r--lib/Transforms/IPO/LLVMBuild.txt23
-rw-r--r--lib/Transforms/IPO/LoopExtractor.cpp304
-rw-r--r--lib/Transforms/IPO/Makefile15
-rw-r--r--lib/Transforms/IPO/MergeFunctions.cpp872
-rw-r--r--lib/Transforms/IPO/PartialInlining.cpp183
-rw-r--r--lib/Transforms/IPO/PassManagerBuilder.cpp380
-rw-r--r--lib/Transforms/IPO/PruneEH.cpp256
-rw-r--r--lib/Transforms/IPO/StripDeadPrototypes.cpp73
-rw-r--r--lib/Transforms/IPO/StripSymbols.cpp414
-rw-r--r--lib/Transforms/InstCombine/CMakeLists.txt17
-rw-r--r--lib/Transforms/InstCombine/InstCombine.h374
-rw-r--r--lib/Transforms/InstCombine/InstCombineAddSub.cpp661
-rw-r--r--lib/Transforms/InstCombine/InstCombineAndOrXor.cpp2285
-rw-r--r--lib/Transforms/InstCombine/InstCombineCalls.cpp1404
-rw-r--r--lib/Transforms/InstCombine/InstCombineCasts.cpp1759
-rw-r--r--lib/Transforms/InstCombine/InstCombineCompares.cpp3043
-rw-r--r--lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp824
-rw-r--r--lib/Transforms/InstCombine/InstCombineMulDivRem.cpp751
-rw-r--r--lib/Transforms/InstCombine/InstCombinePHI.cpp904
-rw-r--r--lib/Transforms/InstCombine/InstCombineSelect.cpp918
-rw-r--r--lib/Transforms/InstCombine/InstCombineShifts.cpp813
-rw-r--r--lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp1181
-rw-r--r--lib/Transforms/InstCombine/InstCombineVectorOps.cpp672
-rw-r--r--lib/Transforms/InstCombine/InstCombineWorklist.h106
-rw-r--r--lib/Transforms/InstCombine/InstructionCombining.cpp2150
-rw-r--r--lib/Transforms/InstCombine/LLVMBuild.txt22
-rw-r--r--lib/Transforms/InstCombine/Makefile15
-rw-r--r--lib/Transforms/Instrumentation/AddressSanitizer.cpp1165
-rw-r--r--lib/Transforms/Instrumentation/BlackList.cpp102
-rw-r--r--lib/Transforms/Instrumentation/BlackList.h55
-rw-r--r--lib/Transforms/Instrumentation/BoundsChecking.cpp213
-rw-r--r--lib/Transforms/Instrumentation/CMakeLists.txt14
-rw-r--r--lib/Transforms/Instrumentation/EdgeProfiling.cpp117
-rw-r--r--lib/Transforms/Instrumentation/GCOVProfiling.cpp788
-rw-r--r--lib/Transforms/Instrumentation/Instrumentation.cpp36
-rw-r--r--lib/Transforms/Instrumentation/LLVMBuild.txt22
-rw-r--r--lib/Transforms/Instrumentation/Makefile15
-rw-r--r--lib/Transforms/Instrumentation/MaximumSpanningTree.h111
-rw-r--r--lib/Transforms/Instrumentation/OptimalEdgeProfiling.cpp225
-rw-r--r--lib/Transforms/Instrumentation/PathProfiling.cpp1425
-rw-r--r--lib/Transforms/Instrumentation/ProfilingUtils.cpp169
-rw-r--r--lib/Transforms/Instrumentation/ProfilingUtils.h36
-rw-r--r--lib/Transforms/Instrumentation/ThreadSanitizer.cpp412
-rw-r--r--lib/Transforms/LLVMBuild.txt24
-rw-r--r--lib/Transforms/Makefile20
-rw-r--r--lib/Transforms/Scalar/ADCE.cpp97
-rw-r--r--lib/Transforms/Scalar/BasicBlockPlacement.cpp152
-rw-r--r--lib/Transforms/Scalar/CMakeLists.txt37
-rw-r--r--lib/Transforms/Scalar/CodeGenPrepare.cpp1367
-rw-r--r--lib/Transforms/Scalar/ConstantProp.cpp98
-rw-r--r--lib/Transforms/Scalar/CorrelatedValuePropagation.cpp297
-rw-r--r--lib/Transforms/Scalar/DCE.cpp139
-rw-r--r--lib/Transforms/Scalar/DeadStoreElimination.cpp853
-rw-r--r--lib/Transforms/Scalar/EarlyCSE.cpp572
-rw-r--r--lib/Transforms/Scalar/GVN.cpp2622
-rw-r--r--lib/Transforms/Scalar/GlobalMerge.cpp226
-rw-r--r--lib/Transforms/Scalar/IndVarSimplify.cpp1801
-rw-r--r--lib/Transforms/Scalar/JumpThreading.cpp1609
-rw-r--r--lib/Transforms/Scalar/LICM.cpp880
-rw-r--r--lib/Transforms/Scalar/LLVMBuild.txt23
-rw-r--r--lib/Transforms/Scalar/LoopDeletion.cpp248
-rw-r--r--lib/Transforms/Scalar/LoopIdiomRecognize.cpp636
-rw-r--r--lib/Transforms/Scalar/LoopInstSimplify.cpp174
-rw-r--r--lib/Transforms/Scalar/LoopRotation.cpp497
-rw-r--r--lib/Transforms/Scalar/LoopStrengthReduce.cpp4837
-rw-r--r--lib/Transforms/Scalar/LoopUnrollPass.cpp224
-rw-r--r--lib/Transforms/Scalar/LoopUnswitch.cpp1281
-rw-r--r--lib/Transforms/Scalar/LowerAtomic.cpp142
-rw-r--r--lib/Transforms/Scalar/Makefile15
-rw-r--r--lib/Transforms/Scalar/MemCpyOptimizer.cpp994
-rw-r--r--lib/Transforms/Scalar/ObjCARC.cpp4217
-rw-r--r--lib/Transforms/Scalar/Reassociate.cpp1704
-rw-r--r--lib/Transforms/Scalar/Reg2Mem.cpp133
-rw-r--r--lib/Transforms/Scalar/SCCP.cpp1946
-rw-r--r--lib/Transforms/Scalar/SROA.cpp3041
-rw-r--r--lib/Transforms/Scalar/Scalar.cpp194
-rw-r--r--lib/Transforms/Scalar/ScalarReplAggregates.cpp2611
-rw-r--r--lib/Transforms/Scalar/SimplifyCFGPass.cpp341
-rw-r--r--lib/Transforms/Scalar/SimplifyLibCalls.cpp2544
-rw-r--r--lib/Transforms/Scalar/Sink.cpp270
-rw-r--r--lib/Transforms/Scalar/TailRecursionElimination.cpp634
-rw-r--r--lib/Transforms/Utils/AddrModeMatcher.cpp577
-rw-r--r--lib/Transforms/Utils/BasicBlockUtils.cpp689
-rw-r--r--lib/Transforms/Utils/BreakCriticalEdges.cpp409
-rw-r--r--lib/Transforms/Utils/BuildLibCalls.cpp567
-rw-r--r--lib/Transforms/Utils/BypassSlowDivision.cpp253
-rw-r--r--lib/Transforms/Utils/CMakeLists.txt35
-rw-r--r--lib/Transforms/Utils/CloneFunction.cpp571
-rw-r--r--lib/Transforms/Utils/CloneModule.cpp126
-rw-r--r--lib/Transforms/Utils/CmpInstAnalysis.cpp96
-rw-r--r--lib/Transforms/Utils/CodeExtractor.cpp779
-rw-r--r--lib/Transforms/Utils/DemoteRegToStack.cpp133
-rw-r--r--lib/Transforms/Utils/InlineFunction.cpp887
-rw-r--r--lib/Transforms/Utils/InstructionNamer.cpp64
-rw-r--r--lib/Transforms/Utils/LCSSA.cpp279
-rw-r--r--lib/Transforms/Utils/LLVMBuild.txt22
-rw-r--r--lib/Transforms/Utils/Local.cpp930
-rw-r--r--lib/Transforms/Utils/LoopSimplify.cpp793
-rw-r--r--lib/Transforms/Utils/LoopUnroll.cpp457
-rw-r--r--lib/Transforms/Utils/LoopUnrollRuntime.cpp374
-rw-r--r--lib/Transforms/Utils/LowerExpectIntrinsic.cpp174
-rw-r--r--lib/Transforms/Utils/LowerInvoke.cpp582
-rw-r--r--lib/Transforms/Utils/LowerSwitch.cpp305
-rw-r--r--lib/Transforms/Utils/Makefile15
-rw-r--r--lib/Transforms/Utils/Mem2Reg.cpp90
-rw-r--r--lib/Transforms/Utils/MetaRenamer.cpp132
-rw-r--r--lib/Transforms/Utils/ModuleUtils.cpp64
-rw-r--r--lib/Transforms/Utils/PromoteMemoryToRegister.cpp1141
-rw-r--r--lib/Transforms/Utils/SSAUpdater.cpp530
-rw-r--r--lib/Transforms/Utils/SimplifyCFG.cpp3623
-rw-r--r--lib/Transforms/Utils/SimplifyIndVar.cpp393
-rw-r--r--lib/Transforms/Utils/SimplifyInstructions.cpp100
-rw-r--r--lib/Transforms/Utils/UnifyFunctionExitNodes.cpp122
-rw-r--r--lib/Transforms/Utils/Utils.cpp38
-rw-r--r--lib/Transforms/Utils/ValueMapper.cpp200
-rw-r--r--lib/Transforms/Vectorize/BBVectorize.cpp2437
-rw-r--r--lib/Transforms/Vectorize/CMakeLists.txt6
-rw-r--r--lib/Transforms/Vectorize/LLVMBuild.txt24
-rw-r--r--lib/Transforms/Vectorize/Makefile15
-rw-r--r--lib/Transforms/Vectorize/Vectorize.cpp39
-rw-r--r--lib/VMCore/AsmWriter.cpp2159
-rw-r--r--lib/VMCore/Attributes.cpp356
-rw-r--r--lib/VMCore/AutoUpgrade.cpp392
-rw-r--r--lib/VMCore/BasicBlock.cpp371
-rw-r--r--lib/VMCore/CMakeLists.txt52
-rw-r--r--lib/VMCore/ConstantFold.cpp2076
-rw-r--r--lib/VMCore/ConstantFold.h56
-rw-r--r--lib/VMCore/Constants.cpp2644
-rw-r--r--lib/VMCore/ConstantsContext.h774
-rw-r--r--lib/VMCore/Core.cpp2380
-rw-r--r--lib/VMCore/DIBuilder.cpp1043
-rw-r--r--lib/VMCore/DebugInfo.cpp1168
-rw-r--r--lib/VMCore/DebugLoc.cpp315
-rw-r--r--lib/VMCore/Dominators.cpp302
-rw-r--r--lib/VMCore/Function.cpp663
-rw-r--r--lib/VMCore/GCOV.cpp281
-rw-r--r--lib/VMCore/GVMaterializer.cpp18
-rw-r--r--lib/VMCore/Globals.cpp263
-rw-r--r--lib/VMCore/IRBuilder.cpp149
-rw-r--r--lib/VMCore/InlineAsm.cpp295
-rw-r--r--lib/VMCore/Instruction.cpp447
-rw-r--r--lib/VMCore/Instructions.cpp3537
-rw-r--r--lib/VMCore/IntrinsicInst.cpp73
-rw-r--r--lib/VMCore/LLVMBuild.txt22
-rw-r--r--lib/VMCore/LLVMContext.cpp162
-rw-r--r--lib/VMCore/LLVMContextImpl.cpp133
-rw-r--r--lib/VMCore/LLVMContextImpl.h364
-rw-r--r--lib/VMCore/LeakDetector.cpp69
-rw-r--r--lib/VMCore/LeaksContext.h92
-rw-r--r--lib/VMCore/Makefile34
-rw-r--r--lib/VMCore/Metadata.cpp744
-rw-r--r--lib/VMCore/Module.cpp469
-rw-r--r--lib/VMCore/Pass.cpp297
-rw-r--r--lib/VMCore/PassManager.cpp1861
-rw-r--r--lib/VMCore/PassRegistry.cpp209
-rw-r--r--lib/VMCore/PrintModulePass.cpp101
-rw-r--r--lib/VMCore/SymbolTableListTraitsImpl.h118
-rw-r--r--lib/VMCore/Type.cpp789
-rw-r--r--lib/VMCore/TypeFinder.cpp148
-rw-r--r--lib/VMCore/Use.cpp145
-rw-r--r--lib/VMCore/User.cpp81
-rw-r--r--lib/VMCore/Value.cpp694
-rw-r--r--lib/VMCore/ValueSymbolTable.cpp117
-rw-r--r--lib/VMCore/ValueTypes.cpp228
-rw-r--r--lib/VMCore/Verifier.cpp1953
-rw-r--r--llvm.spec.in67
-rw-r--r--projects/CMakeLists.txt20
-rw-r--r--projects/LLVMBuild.txt21
-rw-r--r--projects/Makefile28
-rw-r--r--projects/sample/Makefile18
-rw-r--r--projects/sample/Makefile.common.in26
-rw-r--r--projects/sample/Makefile.llvm.config.in311
-rw-r--r--projects/sample/Makefile.llvm.rules2236
-rwxr-xr-xprojects/sample/autoconf/AutoRegen.sh45
-rw-r--r--projects/sample/autoconf/ExportMap.map7
-rw-r--r--projects/sample/autoconf/LICENSE.TXT24
-rwxr-xr-xprojects/sample/autoconf/config.guess1516
-rwxr-xr-xprojects/sample/autoconf/config.sub1766
-rw-r--r--projects/sample/autoconf/configure.ac1472
-rwxr-xr-xprojects/sample/autoconf/install-sh322
-rw-r--r--projects/sample/autoconf/ltmain.sh6863
-rw-r--r--projects/sample/autoconf/m4/build_exeext.m442
-rw-r--r--projects/sample/autoconf/m4/c_printf_a.m431
-rw-r--r--projects/sample/autoconf/m4/check_gnu_make.m426
-rw-r--r--projects/sample/autoconf/m4/config_makefile.m49
-rw-r--r--projects/sample/autoconf/m4/config_project.m414
-rw-r--r--projects/sample/autoconf/m4/cxx_flag_check.m42
-rw-r--r--projects/sample/autoconf/m4/find_std_program.m4118
-rw-r--r--projects/sample/autoconf/m4/func_isinf.m436
-rw-r--r--projects/sample/autoconf/m4/func_isnan.m427
-rw-r--r--projects/sample/autoconf/m4/func_mmap_file.m426
-rw-r--r--projects/sample/autoconf/m4/header_mmap_anonymous.m421
-rw-r--r--projects/sample/autoconf/m4/huge_val.m420
-rw-r--r--projects/sample/autoconf/m4/libtool.m46389
-rw-r--r--projects/sample/autoconf/m4/link_options.m4108
-rw-r--r--projects/sample/autoconf/m4/linux_mixed_64_32.m417
-rw-r--r--projects/sample/autoconf/m4/ltdl.m4418
-rw-r--r--projects/sample/autoconf/m4/need_dev_zero_for_mmap.m417
-rw-r--r--projects/sample/autoconf/m4/path_tclsh.m439
-rw-r--r--projects/sample/autoconf/m4/rand48.m412
-rw-r--r--projects/sample/autoconf/m4/sanity_check.m431
-rw-r--r--projects/sample/autoconf/m4/single_cxx_check.m410
-rw-r--r--projects/sample/autoconf/m4/visibility_inlines_hidden.m424
-rwxr-xr-xprojects/sample/autoconf/mkinstalldirs150
-rwxr-xr-xprojects/sample/configure22312
-rw-r--r--projects/sample/docs/index.html6
-rw-r--r--projects/sample/include/sample.h8
-rw-r--r--projects/sample/lib/Makefile13
-rw-r--r--projects/sample/lib/sample/Makefile16
-rw-r--r--projects/sample/lib/sample/sample.c25
-rw-r--r--projects/sample/tools/Makefile13
-rw-r--r--projects/sample/tools/sample/Makefile23
-rw-r--r--projects/sample/tools/sample/main.c14
-rw-r--r--runtime/CMakeLists.txt5
-rw-r--r--runtime/LLVMBuild.txt21
-rw-r--r--runtime/Makefile31
-rw-r--r--runtime/README.txt4
-rw-r--r--runtime/libprofile/BasicBlockTracing.c67
-rw-r--r--runtime/libprofile/CMakeLists.txt20
-rw-r--r--runtime/libprofile/CommonProfiling.c151
-rw-r--r--runtime/libprofile/EdgeProfiling.c45
-rw-r--r--runtime/libprofile/GCDAProfiling.c205
-rw-r--r--runtime/libprofile/Makefile51
-rw-r--r--runtime/libprofile/OptimalEdgeProfiling.c45
-rw-r--r--runtime/libprofile/PathProfiling.c270
-rw-r--r--runtime/libprofile/Profiling.h36
-rw-r--r--runtime/libprofile/libprofile.exports12
-rw-r--r--test/Analysis/BasicAA/2003-02-26-AccessSizeTest.ll20
-rw-r--r--test/Analysis/BasicAA/2003-03-04-GEPCrash.ll7
-rw-r--r--test/Analysis/BasicAA/2003-04-22-GEPProblem.ll14
-rw-r--r--test/Analysis/BasicAA/2003-04-25-GEPCrash.ll7
-rw-r--r--test/Analysis/BasicAA/2003-05-21-GEP-Problem.ll21
-rw-r--r--test/Analysis/BasicAA/2003-06-01-AliasCrash.ll11
-rw-r--r--test/Analysis/BasicAA/2003-07-03-BasicAACrash.ll10
-rw-r--r--test/Analysis/BasicAA/2003-09-19-LocalArgument.ll15
-rw-r--r--test/Analysis/BasicAA/2003-11-04-SimpleCases.ll18
-rw-r--r--test/Analysis/BasicAA/2003-12-11-ConstExprGEP.ll20
-rw-r--r--test/Analysis/BasicAA/2004-07-28-MustAliasbug.ll11
-rw-r--r--test/Analysis/BasicAA/2006-03-03-BadArraySubscript.ll33
-rw-r--r--test/Analysis/BasicAA/2006-11-03-BasicAAVectorCrash.ll48
-rw-r--r--test/Analysis/BasicAA/2007-01-13-BasePointerBadNoAlias.ll34
-rw-r--r--test/Analysis/BasicAA/2007-08-01-NoAliasAndCalls.ll13
-rw-r--r--test/Analysis/BasicAA/2007-08-01-NoAliasAndGEP.ll20
-rw-r--r--test/Analysis/BasicAA/2007-08-05-GetOverloadedModRef.ll16
-rw-r--r--test/Analysis/BasicAA/2007-10-24-ArgumentsGlobals.ll16
-rw-r--r--test/Analysis/BasicAA/2007-11-05-SizeCrash.ll34
-rw-r--r--test/Analysis/BasicAA/2007-12-08-OutOfBoundsCrash.ll31
-rw-r--r--test/Analysis/BasicAA/2008-04-15-Byval.ll19
-rw-r--r--test/Analysis/BasicAA/2008-06-02-GEPTailCrash.ll15
-rw-r--r--test/Analysis/BasicAA/2008-11-23-NoaliasRet.ll14
-rw-r--r--test/Analysis/BasicAA/2009-03-04-GEPNoalias.ll14
-rw-r--r--test/Analysis/BasicAA/2009-10-13-AtomicModRef.ll15
-rw-r--r--test/Analysis/BasicAA/2009-10-13-GEP-BaseNoAlias.ll33
-rw-r--r--test/Analysis/BasicAA/2010-09-15-GEP-SignedArithmetic.ll17
-rw-r--r--test/Analysis/BasicAA/aligned-overread.ll25
-rw-r--r--test/Analysis/BasicAA/args-rets-allocas-loads.ll311
-rw-r--r--test/Analysis/BasicAA/byval.ll18
-rw-r--r--test/Analysis/BasicAA/cas.ll14
-rw-r--r--test/Analysis/BasicAA/constant-over-index.ll28
-rw-r--r--test/Analysis/BasicAA/dag.ll41
-rw-r--r--test/Analysis/BasicAA/empty.ll12
-rw-r--r--test/Analysis/BasicAA/featuretest.ll127
-rw-r--r--test/Analysis/BasicAA/full-store-partial-alias.ll35
-rw-r--r--test/Analysis/BasicAA/gcsetest.ll61
-rw-r--r--test/Analysis/BasicAA/gep-alias.ll203
-rw-r--r--test/Analysis/BasicAA/getmodrefinfo-cs-cs.ll26
-rw-r--r--test/Analysis/BasicAA/global-size.ll40
-rw-r--r--test/Analysis/BasicAA/intrinsics.ll39
-rw-r--r--test/Analysis/BasicAA/lit.local.cfg1
-rw-r--r--test/Analysis/BasicAA/memset_pattern.ll21
-rw-r--r--test/Analysis/BasicAA/modref.ll151
-rw-r--r--test/Analysis/BasicAA/must-and-partial.ll39
-rw-r--r--test/Analysis/BasicAA/no-escape-call.ll24
-rw-r--r--test/Analysis/BasicAA/noalias-geps.ll54
-rw-r--r--test/Analysis/BasicAA/nocapture.ll15
-rw-r--r--test/Analysis/BasicAA/phi-aa.ll31
-rw-r--r--test/Analysis/BasicAA/phi-and-select.ll82
-rw-r--r--test/Analysis/BasicAA/phi-speculation.ll33
-rw-r--r--test/Analysis/BasicAA/pure-const-dce.ll51
-rw-r--r--test/Analysis/BasicAA/store-promote.ll54
-rw-r--r--test/Analysis/BasicAA/tailcall-modref.ll16
-rw-r--r--test/Analysis/BasicAA/underlying-value.ll25
-rw-r--r--test/Analysis/BasicAA/unreachable-block.ll16
-rw-r--r--test/Analysis/BlockFrequencyInfo/basic.ll92
-rw-r--r--test/Analysis/BlockFrequencyInfo/lit.local.cfg1
-rw-r--r--test/Analysis/BranchProbabilityInfo/basic.ll117
-rw-r--r--test/Analysis/BranchProbabilityInfo/lit.local.cfg1
-rw-r--r--test/Analysis/BranchProbabilityInfo/loop.ll365
-rw-r--r--test/Analysis/BranchProbabilityInfo/noreturn.ll79
-rw-r--r--test/Analysis/CallGraph/2008-09-09-DirectCall.ll17
-rw-r--r--test/Analysis/CallGraph/2008-09-09-UsedByGlobal.ll9
-rw-r--r--test/Analysis/CallGraph/lit.local.cfg1
-rw-r--r--test/Analysis/CallGraph/no-intrinsics.ll13
-rw-r--r--test/Analysis/Dominators/2006-10-02-BreakCritEdges.ll21
-rw-r--r--test/Analysis/Dominators/2007-01-14-BreakCritEdges.ll187
-rw-r--r--test/Analysis/Dominators/2007-07-11-SplitBlock.ll21
-rw-r--r--test/Analysis/Dominators/2007-07-12-SplitBlock.ll13
-rw-r--r--test/Analysis/Dominators/invoke.ll19
-rw-r--r--test/Analysis/Dominators/lit.local.cfg1
-rw-r--r--test/Analysis/GlobalsModRef/2008-09-03-ReadGlobals.ll20
-rw-r--r--test/Analysis/GlobalsModRef/aliastest.ll14
-rw-r--r--test/Analysis/GlobalsModRef/chaining-analysis.ll24
-rw-r--r--test/Analysis/GlobalsModRef/indirect-global.ll22
-rw-r--r--test/Analysis/GlobalsModRef/lit.local.cfg1
-rw-r--r--test/Analysis/GlobalsModRef/modreftest.ll18
-rw-r--r--test/Analysis/GlobalsModRef/pr12351.ll33
-rw-r--r--test/Analysis/GlobalsModRef/purecse.ll27
-rw-r--r--test/Analysis/GlobalsModRef/volatile-instrs.ll34
-rw-r--r--test/Analysis/LoopDependenceAnalysis/alias.ll44
-rw-r--r--test/Analysis/LoopDependenceAnalysis/lit.local.cfg1
-rw-r--r--test/Analysis/LoopDependenceAnalysis/siv-strong.ll110
-rw-r--r--test/Analysis/LoopDependenceAnalysis/siv-weak-crossing.ll118
-rw-r--r--test/Analysis/LoopDependenceAnalysis/siv-weak-zero.ll56
-rw-r--r--test/Analysis/LoopDependenceAnalysis/ziv.ll63
-rw-r--r--test/Analysis/LoopInfo/2003-05-15-NestingProblem.ll30
-rw-r--r--test/Analysis/LoopInfo/lit.local.cfg1
-rw-r--r--test/Analysis/PostDominators/lit.local.cfg1
-rw-r--r--test/Analysis/PostDominators/pr1098.ll14
-rw-r--r--test/Analysis/PostDominators/pr6047_a.ll15
-rw-r--r--test/Analysis/PostDominators/pr6047_b.ll19
-rw-r--r--test/Analysis/PostDominators/pr6047_c.ll147
-rw-r--r--test/Analysis/PostDominators/pr6047_d.ll24
-rw-r--r--test/Analysis/Profiling/edge-profiling.ll139
-rw-r--r--test/Analysis/Profiling/lit.local.cfg1
-rw-r--r--test/Analysis/Profiling/load-branch-weights-ifs.ll122
-rw-r--r--test/Analysis/Profiling/load-branch-weights-loops.ll188
-rw-r--r--test/Analysis/Profiling/load-branch-weights-switches.ll165
-rw-r--r--test/Analysis/Profiling/profiling-tool-chain.ll212
-rw-r--r--test/Analysis/RegionInfo/20100809_bb_not_in_domtree.ll20
-rw-r--r--test/Analysis/RegionInfo/block_sort.ll42
-rw-r--r--test/Analysis/RegionInfo/cond_loop.ll33
-rw-r--r--test/Analysis/RegionInfo/condition_complicated.ll60
-rw-r--r--test/Analysis/RegionInfo/condition_complicated_2.ll44
-rw-r--r--test/Analysis/RegionInfo/condition_forward_edge.ll26
-rw-r--r--test/Analysis/RegionInfo/condition_same_exit.ll31
-rw-r--r--test/Analysis/RegionInfo/condition_simple.ll28
-rw-r--r--test/Analysis/RegionInfo/exit_in_condition.ll38
-rw-r--r--test/Analysis/RegionInfo/infinite_loop.ll20
-rw-r--r--test/Analysis/RegionInfo/infinite_loop_2.ll36
-rw-r--r--test/Analysis/RegionInfo/infinite_loop_3.ll52
-rw-r--r--test/Analysis/RegionInfo/infinite_loop_4.ll48
-rw-r--r--test/Analysis/RegionInfo/lit.local.cfg1
-rw-r--r--test/Analysis/RegionInfo/loop_with_condition.ll46
-rw-r--r--test/Analysis/RegionInfo/loops_1.ll40
-rw-r--r--test/Analysis/RegionInfo/loops_2.ll49
-rw-r--r--test/Analysis/RegionInfo/mix_1.ll69
-rw-r--r--test/Analysis/RegionInfo/multiple_exiting_edge.ll38
-rw-r--r--test/Analysis/RegionInfo/nested_loops.ll33
-rw-r--r--test/Analysis/RegionInfo/next.ll49
-rw-r--r--test/Analysis/RegionInfo/paper.ll55
-rw-r--r--test/Analysis/RegionInfo/two_loops_same_header.ll46
-rw-r--r--test/Analysis/ScalarEvolution/2007-07-15-NegativeStride.ll21
-rw-r--r--test/Analysis/ScalarEvolution/2007-08-06-MisinterpretBranch.ll18
-rw-r--r--test/Analysis/ScalarEvolution/2007-08-06-Unsigned.ll30
-rw-r--r--test/Analysis/ScalarEvolution/2007-09-27-LargeStepping.ll22
-rw-r--r--test/Analysis/ScalarEvolution/2007-11-14-SignedAddRec.ll24
-rw-r--r--test/Analysis/ScalarEvolution/2007-11-18-OrInstruction.ll21
-rw-r--r--test/Analysis/ScalarEvolution/2008-02-11-ReversedCondition.ll15
-rw-r--r--test/Analysis/ScalarEvolution/2008-02-12-SMAXTripCount.ll17
-rw-r--r--test/Analysis/ScalarEvolution/2008-02-15-UMax.ll17
-rw-r--r--test/Analysis/ScalarEvolution/2008-05-25-NegativeStepToZero.ll22
-rw-r--r--test/Analysis/ScalarEvolution/2008-06-12-BinomialInt64.ll43
-rw-r--r--test/Analysis/ScalarEvolution/2008-07-12-UnneededSelect1.ll36
-rw-r--r--test/Analysis/ScalarEvolution/2008-07-12-UnneededSelect2.ll30
-rw-r--r--test/Analysis/ScalarEvolution/2008-07-19-InfiniteLoop.ll15
-rw-r--r--test/Analysis/ScalarEvolution/2008-07-19-WrappingIV.ll15
-rw-r--r--test/Analysis/ScalarEvolution/2008-07-29-SGTTripCount.ll28
-rw-r--r--test/Analysis/ScalarEvolution/2008-07-29-SMinExpr.ll26
-rw-r--r--test/Analysis/ScalarEvolution/2008-08-04-IVOverflow.ll27
-rw-r--r--test/Analysis/ScalarEvolution/2008-08-04-LongAddRec.ll58
-rw-r--r--test/Analysis/ScalarEvolution/2008-11-02-QuadraticCrash.ll21
-rw-r--r--test/Analysis/ScalarEvolution/2008-11-15-CubicOOM.ll19
-rw-r--r--test/Analysis/ScalarEvolution/2008-11-18-LessThanOrEqual.ll31
-rw-r--r--test/Analysis/ScalarEvolution/2008-11-18-Stride1.ll35
-rw-r--r--test/Analysis/ScalarEvolution/2008-11-18-Stride2.ll34
-rw-r--r--test/Analysis/ScalarEvolution/2008-12-08-FiniteSGE.ll24
-rw-r--r--test/Analysis/ScalarEvolution/2008-12-11-SMaxOverflow.ll30
-rw-r--r--test/Analysis/ScalarEvolution/2008-12-14-StrideAndSigned.ll22
-rw-r--r--test/Analysis/ScalarEvolution/2008-12-15-DontUseSDiv.ll21
-rw-r--r--test/Analysis/ScalarEvolution/2009-01-02-SignedNegativeStride.ll40
-rw-r--r--test/Analysis/ScalarEvolution/2009-04-22-TruncCast.ll37
-rw-r--r--test/Analysis/ScalarEvolution/2009-05-09-PointerEdgeCount.ll28
-rw-r--r--test/Analysis/ScalarEvolution/2009-07-04-GroupConstantsWidthMismatch.ll16
-rw-r--r--test/Analysis/ScalarEvolution/2010-09-03-RequiredTransitive.ll24
-rw-r--r--test/Analysis/ScalarEvolution/2011-03-09-ExactNoMaxBECount.ll34
-rw-r--r--test/Analysis/ScalarEvolution/2011-04-26-FoldAddRec.ll33
-rw-r--r--test/Analysis/ScalarEvolution/2011-10-04-ConstEvolve.ll50
-rw-r--r--test/Analysis/ScalarEvolution/2012-03-26-LoadConstant.ll47
-rw-r--r--test/Analysis/ScalarEvolution/2012-05-18-LoopPredRecurse.ll30
-rw-r--r--test/Analysis/ScalarEvolution/2012-05-29-MulAddRec.ll45
-rw-r--r--test/Analysis/ScalarEvolution/SolveQuadraticEquation.ll103
-rw-r--r--test/Analysis/ScalarEvolution/and-xor.ll8
-rw-r--r--test/Analysis/ScalarEvolution/avoid-infinite-recursion-0.ll30
-rw-r--r--test/Analysis/ScalarEvolution/avoid-infinite-recursion-1.ll354
-rw-r--r--test/Analysis/ScalarEvolution/avoid-smax-0.ll35
-rw-r--r--test/Analysis/ScalarEvolution/avoid-smax-1.ll234
-rw-r--r--test/Analysis/ScalarEvolution/div-overflow.ll10
-rw-r--r--test/Analysis/ScalarEvolution/do-loop.ll18
-rw-r--r--test/Analysis/ScalarEvolution/fold.ll62
-rw-r--r--test/Analysis/ScalarEvolution/how-far-to-zero.ll27
-rw-r--r--test/Analysis/ScalarEvolution/lit.local.cfg1
-rw-r--r--test/Analysis/ScalarEvolution/load.ll65
-rw-r--r--test/Analysis/ScalarEvolution/max-trip-count.ll100
-rw-r--r--test/Analysis/ScalarEvolution/nsw-offset.ll77
-rw-r--r--test/Analysis/ScalarEvolution/nsw.ll124
-rw-r--r--test/Analysis/ScalarEvolution/pointer-sign-bits.ll220
-rw-r--r--test/Analysis/ScalarEvolution/pr3909.ll30
-rw-r--r--test/Analysis/ScalarEvolution/scev-aa.ll215
-rw-r--r--test/Analysis/ScalarEvolution/sext-inreg.ll30
-rw-r--r--test/Analysis/ScalarEvolution/sext-iv-0.ll38
-rw-r--r--test/Analysis/ScalarEvolution/sext-iv-1.ll100
-rw-r--r--test/Analysis/ScalarEvolution/sext-iv-2.ll74
-rw-r--r--test/Analysis/ScalarEvolution/sle.ll27
-rw-r--r--test/Analysis/ScalarEvolution/smax.ll12
-rw-r--r--test/Analysis/ScalarEvolution/trip-count.ll28
-rw-r--r--test/Analysis/ScalarEvolution/trip-count10.ll126
-rw-r--r--test/Analysis/ScalarEvolution/trip-count11.ll29
-rw-r--r--test/Analysis/ScalarEvolution/trip-count12.ll35
-rw-r--r--test/Analysis/ScalarEvolution/trip-count2.ll34
-rw-r--r--test/Analysis/ScalarEvolution/trip-count3.ll78
-rw-r--r--test/Analysis/ScalarEvolution/trip-count4.ll24
-rw-r--r--test/Analysis/ScalarEvolution/trip-count5.ll48
-rw-r--r--test/Analysis/ScalarEvolution/trip-count6.ll37
-rw-r--r--test/Analysis/ScalarEvolution/trip-count7.ll150
-rw-r--r--test/Analysis/ScalarEvolution/trip-count8.ll37
-rw-r--r--test/Analysis/ScalarEvolution/trip-count9.ll408
-rw-r--r--test/Analysis/ScalarEvolution/undefined.ll39
-rw-r--r--test/Analysis/ScalarEvolution/unreachable-code.ll13
-rw-r--r--test/Analysis/ScalarEvolution/unsimplified-loop.ll29
-rw-r--r--test/Analysis/ScalarEvolution/xor-and.ll12
-rw-r--r--test/Analysis/ScalarEvolution/zext-wrap.ll24
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/aliastest.ll62
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/argument-promotion.ll31
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/dse.ll66
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/dynamic-indices.ll131
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/functionattrs.ll81
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/gvn-nonlocal-type-mismatch.ll91
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/intrinsics.ll27
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/licm.ll61
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/lit.local.cfg1
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/memcpyopt.ll23
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/precedence.ll46
-rw-r--r--test/Analysis/TypeBasedAliasAnalysis/sink.ll20
-rw-r--r--test/Archive/GNU.abin0 -> 4210 bytes
-rw-r--r--test/Archive/IsNAN.obin0 -> 2280 bytes
-rw-r--r--test/Archive/MacOSX.abin0 -> 4166 bytes
-rw-r--r--test/Archive/README.txt24
-rw-r--r--test/Archive/SVR4.abin0 -> 4214 bytes
-rw-r--r--test/Archive/check_binary_output.ll4
-rw-r--r--test/Archive/evenlen1
-rw-r--r--test/Archive/extract.ll16
-rw-r--r--test/Archive/lit.local.cfg1
-rw-r--r--test/Archive/oddlen1
-rw-r--r--test/Archive/toc_GNU.ll8
-rw-r--r--test/Archive/toc_MacOSX.ll9
-rw-r--r--test/Archive/toc_SVR4.ll8
-rw-r--r--test/Archive/toc_xpg4.ll8
-rw-r--r--test/Archive/very_long_bytecode_file_name.bcbin0 -> 1465 bytes
-rw-r--r--test/Archive/xpg4.abin0 -> 4214 bytes
-rw-r--r--test/Assembler/2002-03-08-NameCollision.ll15
-rw-r--r--test/Assembler/2002-03-08-NameCollision2.ll12
-rw-r--r--test/Assembler/2002-04-07-HexFloatConstants.ll16
-rw-r--r--test/Assembler/2002-04-07-InfConstant.ll9
-rw-r--r--test/Assembler/2002-04-29-NameBinding.ll18
-rw-r--r--test/Assembler/2002-05-02-InvalidForwardRef.ll10
-rw-r--r--test/Assembler/2002-07-14-OpaqueType.ll10
-rw-r--r--test/Assembler/2002-07-25-QuoteInString.ll5
-rw-r--r--test/Assembler/2002-07-25-ReturnPtrFunction.ll13
-rw-r--r--test/Assembler/2002-07-31-SlashInString.ll5
-rw-r--r--test/Assembler/2002-08-15-CastAmbiguity.ll6
-rw-r--r--test/Assembler/2002-08-15-ConstantExprProblem.ll16
-rw-r--r--test/Assembler/2002-08-15-UnresolvedGlobalReference.ll8
-rw-r--r--test/Assembler/2002-08-16-ConstExprInlined.ll22
-rw-r--r--test/Assembler/2002-08-19-BytecodeReader.ll17
-rw-r--r--test/Assembler/2002-08-22-DominanceProblem.ll17
-rw-r--r--test/Assembler/2002-10-08-LargeArrayPerformance.ll8
-rw-r--r--test/Assembler/2002-10-13-ConstantEncodingProblem.ll5
-rw-r--r--test/Assembler/2002-12-15-GlobalResolve.ll7
-rw-r--r--test/Assembler/2003-01-30-UnsignedString.ll4
-rw-r--r--test/Assembler/2003-04-15-ConstantInitAssertion.ll5
-rw-r--r--test/Assembler/2003-04-25-UnresolvedGlobalReference.ll7
-rw-r--r--test/Assembler/2003-05-03-BytecodeReaderProblem.ll6
-rw-r--r--test/Assembler/2003-05-12-MinIntProblem.ll5
-rw-r--r--test/Assembler/2003-05-15-AssemblerProblem.ll14
-rw-r--r--test/Assembler/2003-05-15-SwitchBug.ll11
-rw-r--r--test/Assembler/2003-05-21-ConstantShiftExpr.ll4
-rw-r--r--test/Assembler/2003-05-21-EmptyStructTest.ll6
-rw-r--r--test/Assembler/2003-05-21-MalformedShiftCrash.ll5
-rw-r--r--test/Assembler/2003-05-21-MalformedStructCrash.ll5
-rw-r--r--test/Assembler/2003-08-20-ConstantExprGEP-Fold.ll16
-rw-r--r--test/Assembler/2003-08-21-ConstantExprCast-Fold.ll4
-rw-r--r--test/Assembler/2003-11-05-ConstantExprShift.ll5
-rw-r--r--test/Assembler/2003-11-11-ImplicitRename.ll8
-rw-r--r--test/Assembler/2003-11-12-ConstantExprCast.ll10
-rw-r--r--test/Assembler/2003-11-24-SymbolTableCrash.ll10
-rw-r--r--test/Assembler/2004-01-11-getelementptrfolding.ll12
-rw-r--r--test/Assembler/2004-01-20-MaxLongLong.ll4
-rw-r--r--test/Assembler/2004-02-01-NegativeZero.ll5
-rw-r--r--test/Assembler/2004-02-27-SelfUseAssertError.ll25
-rw-r--r--test/Assembler/2004-03-07-FunctionAddressAlignment.ll15
-rw-r--r--test/Assembler/2004-03-30-UnclosedFunctionCrash.ll3
-rw-r--r--test/Assembler/2004-04-04-GetElementPtrIndexTypes.ll10
-rw-r--r--test/Assembler/2004-06-07-VerifierBug.ll11
-rw-r--r--test/Assembler/2004-10-22-BCWriterUndefBug.ll5
-rw-r--r--test/Assembler/2004-11-28-InvalidTypeCrash.ll4
-rw-r--r--test/Assembler/2005-01-03-FPConstantDisassembly.ll6
-rw-r--r--test/Assembler/2005-01-31-CallingAggregateFunction.ll8
-rw-r--r--test/Assembler/2005-05-05-OpaqueUndefValues.ll4
-rw-r--r--test/Assembler/2005-12-21-ZeroInitVector.ll6
-rw-r--r--test/Assembler/2006-09-28-CrashOnInvalid.ll9
-rw-r--r--test/Assembler/2006-12-09-Cast-To-Bool.ll6
-rw-r--r--test/Assembler/2007-01-02-Undefined-Arg-Type.ll9
-rw-r--r--test/Assembler/2007-01-05-Cmp-ConstExpr.ll18
-rw-r--r--test/Assembler/2007-01-16-CrashOnBadCast.ll7
-rw-r--r--test/Assembler/2007-01-16-CrashOnBadCast2.ll4
-rw-r--r--test/Assembler/2007-03-18-InvalidNumberedVar.ll10
-rw-r--r--test/Assembler/2007-03-19-NegValue.ll7
-rw-r--r--test/Assembler/2007-04-20-AlignedLoad.ll7
-rw-r--r--test/Assembler/2007-04-20-AlignedStore.ll7
-rw-r--r--test/Assembler/2007-04-25-AssemblerFoldExternWeak.ll6
-rw-r--r--test/Assembler/2007-05-21-Escape.ll22
-rw-r--r--test/Assembler/2007-07-19-ParamAttrAmbiguity.ll9
-rw-r--r--test/Assembler/2007-08-06-AliasInvalid.ll10
-rw-r--r--test/Assembler/2007-09-10-AliasFwdRef.ll9
-rw-r--r--test/Assembler/2007-09-29-GC.ll12
-rw-r--r--test/Assembler/2007-11-26-AttributeOverload.ll4
-rw-r--r--test/Assembler/2007-12-11-AddressSpaces.ll25
-rw-r--r--test/Assembler/2008-01-11-VarargAttrs.ll10
-rw-r--r--test/Assembler/2008-02-18-IntPointerCrash.ll6
-rw-r--r--test/Assembler/2008-07-10-APInt.ll9
-rw-r--r--test/Assembler/2008-09-02-FunctionNotes.ll14
-rw-r--r--test/Assembler/2008-09-02-FunctionNotes2.ll6
-rw-r--r--test/Assembler/2008-09-29-RetAttr.ll13
-rw-r--r--test/Assembler/2008-10-14-QuoteInName.ll3
-rw-r--r--test/Assembler/2009-02-01-UnnamedForwardRef.ll6
-rw-r--r--test/Assembler/2009-02-28-CastOpc.ll7
-rw-r--r--test/Assembler/2009-02-28-StripOpaqueName.ll6
-rw-r--r--test/Assembler/2009-03-24-ZextConstantExpr.ll11
-rw-r--r--test/Assembler/2009-04-25-AliasGEP.ll8
-rw-r--r--test/Assembler/2009-07-24-ZeroArgGEP.ll5
-rw-r--r--test/Assembler/2010-02-05-FunctionLocalMetadataBecomesNull.ll25
-rw-r--r--test/Assembler/ConstantExprFold.ll31
-rw-r--r--test/Assembler/ConstantExprFoldCast.ll14
-rw-r--r--test/Assembler/MultipleReturnValueType.ll13
-rw-r--r--test/Assembler/aggregate-constant-values.ll50
-rw-r--r--test/Assembler/aggregate-return-single-value.ll8
-rw-r--r--test/Assembler/align-inst-alloca.ll6
-rw-r--r--test/Assembler/align-inst-load.ll6
-rw-r--r--test/Assembler/align-inst-store.ll6
-rw-r--r--test/Assembler/align-inst.ll10
-rw-r--r--test/Assembler/alignstack.ll36
-rw-r--r--test/Assembler/anon-functions.ll26
-rw-r--r--test/Assembler/atomic.ll26
-rw-r--r--test/Assembler/auto_upgrade_intrinsics.ll44
-rw-r--r--test/Assembler/bcwrap.ll11
-rw-r--r--test/Assembler/comment.ll19
-rw-r--r--test/Assembler/extractvalue-invalid-idx.ll10
-rw-r--r--test/Assembler/flags.ll276
-rw-r--r--test/Assembler/functionlocal-metadata.ll44
-rw-r--r--test/Assembler/getelementptr.ll22
-rw-r--r--test/Assembler/getelementptr_struct.ll15
-rw-r--r--test/Assembler/half-constprop.ll17
-rw-r--r--test/Assembler/half-conv.ll13
-rw-r--r--test/Assembler/half.ll8
-rw-r--r--test/Assembler/huge-array.ll7
-rw-r--r--test/Assembler/insertextractvalue.ll46
-rw-r--r--test/Assembler/insertvalue-invalid-idx.ll9
-rw-r--r--test/Assembler/invalid_cast.ll8
-rw-r--r--test/Assembler/invalid_cast2.ll8
-rw-r--r--test/Assembler/lit.local.cfg1
-rw-r--r--test/Assembler/metadata.ll19
-rw-r--r--test/Assembler/named-metadata.ll24
-rw-r--r--test/Assembler/numbered-values.ll16
-rw-r--r--test/Assembler/select.ll9
-rw-r--r--test/Assembler/tls-models.ll11
-rw-r--r--test/Assembler/unnamed-addr.ll18
-rw-r--r--test/Assembler/unnamed.ll51
-rw-r--r--test/Assembler/vbool-cmp.ll18
-rw-r--r--test/Assembler/vector-cmp.ll16
-rw-r--r--test/Assembler/vector-select.ll11
-rw-r--r--test/Assembler/vector-shift.ll45
-rw-r--r--test/Assembler/x86mmx.ll8
-rw-r--r--test/Bindings/Ocaml/analysis.ml51
-rw-r--r--test/Bindings/Ocaml/bitreader.ml76
-rw-r--r--test/Bindings/Ocaml/bitwriter.ml45
-rw-r--r--test/Bindings/Ocaml/executionengine.ml115
-rw-r--r--test/Bindings/Ocaml/ext_exc.ml17
-rw-r--r--test/Bindings/Ocaml/ipo_opts.ml73
-rw-r--r--test/Bindings/Ocaml/lit.local.cfg6
-rw-r--r--test/Bindings/Ocaml/scalar_opts.ml88
-rw-r--r--test/Bindings/Ocaml/target.ml59
-rw-r--r--test/Bindings/Ocaml/vmcore.ml1339
-rw-r--r--test/Bitcode/2006-12-11-Cast-ConstExpr.ll10
-rw-r--r--test/Bitcode/2009-06-11-FirstClassAggregateConstant.ll12
-rw-r--r--test/Bitcode/2012-05-07-SwitchInstRangesSupport.ll33
-rw-r--r--test/Bitcode/arm32_neon_vcnt_upgrade.ll21
-rw-r--r--test/Bitcode/attributes.ll164
-rw-r--r--test/Bitcode/blockaddress.ll30
-rw-r--r--test/Bitcode/extractelement.ll8
-rw-r--r--test/Bitcode/flags.ll27
-rw-r--r--test/Bitcode/lit.local.cfg1
-rw-r--r--test/Bitcode/metadata-2.ll87
-rw-r--r--test/Bitcode/metadata.ll6
-rw-r--r--test/Bitcode/null-type.ll5
-rw-r--r--test/Bitcode/null-type.ll.bcbin0 -> 312 bytes
-rw-r--r--test/Bitcode/ptest-new.ll22
-rw-r--r--test/Bitcode/ptest-old.ll22
-rw-r--r--test/Bitcode/shuffle.ll31
-rw-r--r--test/Bitcode/ssse3_palignr.ll82
-rw-r--r--test/BugPoint/crash-narrowfunctiontest.ll13
-rw-r--r--test/BugPoint/lit.local.cfg1
-rw-r--r--test/BugPoint/metadata.ll35
-rw-r--r--test/BugPoint/remove_arguments_test.ll18
-rw-r--r--test/CMakeLists.txt31
-rw-r--r--test/CodeGen/ARM/2006-11-10-CycleInDAG.ll20
-rw-r--r--test/CodeGen/ARM/2007-01-19-InfiniteLoop.ll108
-rw-r--r--test/CodeGen/ARM/2007-03-07-CombinerCrash.ll21
-rw-r--r--test/CodeGen/ARM/2007-03-13-InstrSched.ll51
-rw-r--r--test/CodeGen/ARM/2007-03-21-JoinIntervalsCrash.ll96
-rw-r--r--test/CodeGen/ARM/2007-03-27-RegScavengerAssert.ll35
-rw-r--r--test/CodeGen/ARM/2007-03-30-RegScavengerAssert.ll101
-rw-r--r--test/CodeGen/ARM/2007-04-02-RegScavengerAssert.ll55
-rw-r--r--test/CodeGen/ARM/2007-04-03-PEIBug.ll12
-rw-r--r--test/CodeGen/ARM/2007-04-03-UndefinedSymbol.ll99
-rw-r--r--test/CodeGen/ARM/2007-04-30-CombinerCrash.ll32
-rw-r--r--test/CodeGen/ARM/2007-05-03-BadPostIndexedLd.ll113
-rw-r--r--test/CodeGen/ARM/2007-05-07-tailmerge-1.ll65
-rw-r--r--test/CodeGen/ARM/2007-05-09-tailmerge-2.ll66
-rw-r--r--test/CodeGen/ARM/2007-05-14-InlineAsmCstCrash.ll6
-rw-r--r--test/CodeGen/ARM/2007-05-14-RegScavengerAssert.ll30
-rw-r--r--test/CodeGen/ARM/2007-05-22-tailmerge-3.ll68
-rw-r--r--test/CodeGen/ARM/2007-05-23-BadPreIndexedStore.ll34
-rw-r--r--test/CodeGen/ARM/2007-08-15-ReuseBug.ll106
-rw-r--r--test/CodeGen/ARM/2008-02-04-LocalRegAllocBug.ll19
-rw-r--r--test/CodeGen/ARM/2008-02-29-RegAllocLocal.ll21
-rw-r--r--test/CodeGen/ARM/2008-03-05-SxtInRegBug.ll14
-rw-r--r--test/CodeGen/ARM/2008-03-07-RegScavengerAssert.ll20
-rw-r--r--test/CodeGen/ARM/2008-04-04-ScavengerAssert.ll63
-rw-r--r--test/CodeGen/ARM/2008-04-10-ScavengerAssert.ll253
-rw-r--r--test/CodeGen/ARM/2008-04-11-PHIofImpDef.ll3544
-rw-r--r--test/CodeGen/ARM/2008-05-19-LiveIntervalsBug.ll55
-rw-r--r--test/CodeGen/ARM/2008-05-19-ScavengerAssert.ll22
-rw-r--r--test/CodeGen/ARM/2008-07-17-Fdiv.ll6
-rw-r--r--test/CodeGen/ARM/2008-07-24-CodeGenPrepCrash.ll9
-rw-r--r--test/CodeGen/ARM/2008-08-07-AsmPrintBug.ll13
-rw-r--r--test/CodeGen/ARM/2008-09-17-CoalescerBug.ll17
-rw-r--r--test/CodeGen/ARM/2008-11-18-ScavengerAssert.ll16
-rw-r--r--test/CodeGen/ARM/2009-02-16-SpillerBug.ll117
-rw-r--r--test/CodeGen/ARM/2009-02-22-SoftenFloatVaArg.ll20
-rw-r--r--test/CodeGen/ARM/2009-02-27-SpillerBug.ll229
-rw-r--r--test/CodeGen/ARM/2009-03-07-SpillerBug.ll79
-rw-r--r--test/CodeGen/ARM/2009-03-09-AddrModeBug.ll13
-rw-r--r--test/CodeGen/ARM/2009-04-06-AsmModifier.ll20
-rw-r--r--test/CodeGen/ARM/2009-04-08-AggregateAddr.ll18
-rw-r--r--test/CodeGen/ARM/2009-04-08-FREM.ll9
-rw-r--r--test/CodeGen/ARM/2009-04-08-FloatUndef.ll11
-rw-r--r--test/CodeGen/ARM/2009-04-09-RegScavengerAsm.ll14
-rw-r--r--test/CodeGen/ARM/2009-05-05-DAGCombineBug.ll11
-rw-r--r--test/CodeGen/ARM/2009-05-07-RegAllocLocal.ll12
-rw-r--r--test/CodeGen/ARM/2009-05-11-CodePlacementCrash.ll30
-rw-r--r--test/CodeGen/ARM/2009-05-18-InlineAsmMem.ll9
-rw-r--r--test/CodeGen/ARM/2009-06-02-ISelCrash.ll62
-rw-r--r--test/CodeGen/ARM/2009-06-04-MissingLiveIn.ll263
-rw-r--r--test/CodeGen/ARM/2009-06-15-RegScavengerAssert.ll344
-rw-r--r--test/CodeGen/ARM/2009-06-19-RegScavengerAssert.ll30
-rw-r--r--test/CodeGen/ARM/2009-06-22-CoalescerBug.ll43
-rw-r--r--test/CodeGen/ARM/2009-06-30-RegScavengerAssert.ll122
-rw-r--r--test/CodeGen/ARM/2009-06-30-RegScavengerAssert2.ll116
-rw-r--r--test/CodeGen/ARM/2009-06-30-RegScavengerAssert3.ll128
-rw-r--r--test/CodeGen/ARM/2009-06-30-RegScavengerAssert4.ll128
-rw-r--r--test/CodeGen/ARM/2009-06-30-RegScavengerAssert5.ll99
-rw-r--r--test/CodeGen/ARM/2009-07-01-CommuteBug.ll130
-rw-r--r--test/CodeGen/ARM/2009-07-09-asm-p-constraint.ll7
-rw-r--r--test/CodeGen/ARM/2009-07-18-RewriterBug.ll1323
-rw-r--r--test/CodeGen/ARM/2009-07-22-ScavengerAssert.ll94
-rw-r--r--test/CodeGen/ARM/2009-07-22-SchedulerAssert.ll95
-rw-r--r--test/CodeGen/ARM/2009-07-29-VFP3Registers.ll108
-rw-r--r--test/CodeGen/ARM/2009-08-02-RegScavengerAssert-Neon.ll29
-rw-r--r--test/CodeGen/ARM/2009-08-04-RegScavengerAssert-2.ll33
-rw-r--r--test/CodeGen/ARM/2009-08-04-RegScavengerAssert.ll25
-rw-r--r--test/CodeGen/ARM/2009-08-15-RegScavenger-EarlyClobber.ll42
-rw-r--r--test/CodeGen/ARM/2009-08-15-RegScavengerAssert.ll10
-rw-r--r--test/CodeGen/ARM/2009-08-21-PostRAKill.ll40
-rw-r--r--test/CodeGen/ARM/2009-08-21-PostRAKill2.ll38
-rw-r--r--test/CodeGen/ARM/2009-08-21-PostRAKill3.ll33
-rw-r--r--test/CodeGen/ARM/2009-08-23-linkerprivate.ll8
-rw-r--r--test/CodeGen/ARM/2009-08-26-ScalarToVector.ll27
-rw-r--r--test/CodeGen/ARM/2009-08-27-ScalarToVector.ll35
-rw-r--r--test/CodeGen/ARM/2009-08-29-ExtractEltf32.ll25
-rw-r--r--test/CodeGen/ARM/2009-08-29-TooLongSplat.ll23
-rw-r--r--test/CodeGen/ARM/2009-08-31-LSDA-Name.ll102
-rw-r--r--test/CodeGen/ARM/2009-08-31-TwoRegShuffle.ll9
-rw-r--r--test/CodeGen/ARM/2009-09-09-AllOnes.ll10
-rw-r--r--test/CodeGen/ARM/2009-09-09-fpcmp-ole.ll18
-rw-r--r--test/CodeGen/ARM/2009-09-10-postdec.ll11
-rw-r--r--test/CodeGen/ARM/2009-09-13-InvalidSubreg.ll61
-rw-r--r--test/CodeGen/ARM/2009-09-13-InvalidSuperReg.ll41
-rw-r--r--test/CodeGen/ARM/2009-09-20-LiveIntervalsBug.ll34
-rw-r--r--test/CodeGen/ARM/2009-09-21-LiveVariablesBug.ll14
-rw-r--r--test/CodeGen/ARM/2009-09-22-LiveVariablesBug.ll23
-rw-r--r--test/CodeGen/ARM/2009-09-23-LiveVariablesBug.ll21
-rw-r--r--test/CodeGen/ARM/2009-09-24-spill-align.ll17
-rw-r--r--test/CodeGen/ARM/2009-09-27-CoalescerBug.ll24
-rw-r--r--test/CodeGen/ARM/2009-09-28-LdStOptiBug.ll19
-rw-r--r--test/CodeGen/ARM/2009-10-02-NEONSubregsBug.ll63
-rw-r--r--test/CodeGen/ARM/2009-10-16-Scope.ll32
-rw-r--r--test/CodeGen/ARM/2009-10-21-InvalidFNeg.ll48
-rw-r--r--test/CodeGen/ARM/2009-10-27-double-align.ll15
-rw-r--r--test/CodeGen/ARM/2009-10-30.ll17
-rw-r--r--test/CodeGen/ARM/2009-11-01-NeonMoves.ll40
-rw-r--r--test/CodeGen/ARM/2009-11-02-NegativeLane.ll21
-rw-r--r--test/CodeGen/ARM/2009-11-07-SubRegAsmPrinting.ll66
-rw-r--r--test/CodeGen/ARM/2009-11-13-CoalescerCrash.ll20
-rw-r--r--test/CodeGen/ARM/2009-11-13-ScavengerAssert.ll42
-rw-r--r--test/CodeGen/ARM/2009-11-13-ScavengerAssert2.ll123
-rw-r--r--test/CodeGen/ARM/2009-11-13-VRRewriterCrash.ll113
-rw-r--r--test/CodeGen/ARM/2009-11-30-LiveVariablesBug.ll41
-rw-r--r--test/CodeGen/ARM/2009-12-02-vtrn-undef.ll33
-rw-r--r--test/CodeGen/ARM/2010-03-04-eabi-fp-spill.ll65
-rw-r--r--test/CodeGen/ARM/2010-03-04-stm-undef-addr.ll54
-rw-r--r--test/CodeGen/ARM/2010-03-18-ldm-rtrn.ll15
-rw-r--r--test/CodeGen/ARM/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/ARM/2010-04-09-NeonSelect.ll23
-rw-r--r--test/CodeGen/ARM/2010-04-13-v2f64SplitArg.ll7
-rw-r--r--test/CodeGen/ARM/2010-04-14-SplitVector.ll16
-rw-r--r--test/CodeGen/ARM/2010-04-15-ScavengerDebugValue.ll26
-rw-r--r--test/CodeGen/ARM/2010-05-14-IllegalType.ll10
-rw-r--r--test/CodeGen/ARM/2010-05-17-FastAllocCrash.ll105
-rw-r--r--test/CodeGen/ARM/2010-05-18-LocalAllocCrash.ll36
-rw-r--r--test/CodeGen/ARM/2010-05-18-PostIndexBug.ll25
-rw-r--r--test/CodeGen/ARM/2010-05-19-Shuffles.ll21
-rw-r--r--test/CodeGen/ARM/2010-05-20-NEONSpillCrash.ll45
-rw-r--r--test/CodeGen/ARM/2010-05-21-BuildVector.ll43
-rw-r--r--test/CodeGen/ARM/2010-06-11-vmovdrr-bitcast.ll19
-rw-r--r--test/CodeGen/ARM/2010-06-21-LdStMultipleBug.ll148
-rwxr-xr-xtest/CodeGen/ARM/2010-06-21-nondarwin-tc.ll146
-rw-r--r--test/CodeGen/ARM/2010-06-25-Thumb2ITInvalidIterator.ll75
-rw-r--r--test/CodeGen/ARM/2010-06-29-PartialRedefFastAlloc.ll25
-rw-r--r--test/CodeGen/ARM/2010-06-29-SubregImpDefs.ll15
-rw-r--r--test/CodeGen/ARM/2010-07-26-GlobalMerge.ll94
-rw-r--r--test/CodeGen/ARM/2010-08-04-EHCrash.ll63
-rw-r--r--test/CodeGen/ARM/2010-08-04-StackVariable.ll124
-rw-r--r--test/CodeGen/ARM/2010-09-21-OptCmpBug.ll84
-rw-r--r--test/CodeGen/ARM/2010-09-29-mc-asm-header-test.ll13
-rw-r--r--test/CodeGen/ARM/2010-10-19-mc-elf-objheader.ll37
-rw-r--r--test/CodeGen/ARM/2010-10-25-ifcvt-ldm.ll31
-rw-r--r--test/CodeGen/ARM/2010-11-15-SpillEarlyClobber.ll85
-rw-r--r--test/CodeGen/ARM/2010-11-29-PrologueBug.ll28
-rw-r--r--test/CodeGen/ARM/2010-11-30-reloc-movt.ll42
-rw-r--r--test/CodeGen/ARM/2010-12-07-PEIBug.ll16
-rw-r--r--test/CodeGen/ARM/2010-12-08-tpsoft.ll52
-rw-r--r--test/CodeGen/ARM/2010-12-15-elf-lcomm.ll36
-rw-r--r--test/CodeGen/ARM/2010-12-17-LocalStackSlotCrash.ll15
-rw-r--r--test/CodeGen/ARM/2011-01-19-MergedGlobalDbg.ll125
-rw-r--r--test/CodeGen/ARM/2011-02-04-AntidepMultidef.ll128
-rw-r--r--test/CodeGen/ARM/2011-02-07-AntidepClobber.ll89
-rw-r--r--test/CodeGen/ARM/2011-03-10-DAGCombineCrash.ll47
-rw-r--r--test/CodeGen/ARM/2011-03-15-LdStMultipleBug.ll49
-rw-r--r--test/CodeGen/ARM/2011-03-23-PeepholeBug.ll41
-rw-r--r--test/CodeGen/ARM/2011-04-07-schediv.ll32
-rw-r--r--test/CodeGen/ARM/2011-04-11-MachineLICMBug.ll34
-rw-r--r--test/CodeGen/ARM/2011-04-12-AlignBug.ll11
-rw-r--r--test/CodeGen/ARM/2011-04-12-FastRegAlloc.ll15
-rw-r--r--test/CodeGen/ARM/2011-04-15-AndVFlagPeepholeBug.ll22
-rw-r--r--test/CodeGen/ARM/2011-04-15-RegisterCmpPeephole.ll41
-rw-r--r--test/CodeGen/ARM/2011-04-26-SchedTweak.ll70
-rw-r--r--test/CodeGen/ARM/2011-04-27-IfCvtBug.ll59
-rw-r--r--test/CodeGen/ARM/2011-05-04-MultipleLandingPadSuccs.ll88
-rw-r--r--test/CodeGen/ARM/2011-06-09-TailCallByVal.ll40
-rw-r--r--test/CodeGen/ARM/2011-06-16-TailCallByVal.ll20
-rw-r--r--test/CodeGen/ARM/2011-06-29-MergeGlobalsAlign.ll10
-rw-r--r--test/CodeGen/ARM/2011-07-10-GlobalMergeBug.ll8
-rw-r--r--test/CodeGen/ARM/2011-08-02-MergedGlobalDbg.ll123
-rw-r--r--test/CodeGen/ARM/2011-08-12-vmovqqqq-pseudo.ll12
-rw-r--r--test/CodeGen/ARM/2011-08-25-ldmia_ret.ll100
-rw-r--r--test/CodeGen/ARM/2011-08-29-SchedCycle.ll45
-rw-r--r--test/CodeGen/ARM/2011-08-29-ldr_pre_imm.ll34
-rw-r--r--test/CodeGen/ARM/2011-09-09-OddVectorDivision.ll23
-rw-r--r--test/CodeGen/ARM/2011-09-19-cpsr.ll54
-rw-r--r--test/CodeGen/ARM/2011-09-28-CMovCombineBug.ll30
-rw-r--r--test/CodeGen/ARM/2011-10-26-ExpandUnalignedLoadCrash.ll22
-rw-r--r--test/CodeGen/ARM/2011-10-26-memset-inline.ll21
-rw-r--r--test/CodeGen/ARM/2011-10-26-memset-with-neon.ll20
-rw-r--r--test/CodeGen/ARM/2011-11-07-PromoteVectorLoadStore.ll24
-rw-r--r--test/CodeGen/ARM/2011-11-09-BitcastVectorDouble.ll15
-rw-r--r--test/CodeGen/ARM/2011-11-09-IllegalVectorFPIntConvert.ll37
-rw-r--r--test/CodeGen/ARM/2011-11-14-EarlyClobber.ll62
-rw-r--r--test/CodeGen/ARM/2011-11-28-DAGCombineBug.ll38
-rw-r--r--test/CodeGen/ARM/2011-11-29-128bitArithmetics.ll333
-rw-r--r--test/CodeGen/ARM/2011-11-30-MergeAlignment.ll24
-rw-r--r--test/CodeGen/ARM/2011-12-14-machine-sink.ll48
-rw-r--r--test/CodeGen/ARM/2011-12-19-sjlj-clobber.ll55
-rw-r--r--test/CodeGen/ARM/2012-01-23-PostRA-LICM.ll105
-rw-r--r--test/CodeGen/ARM/2012-01-24-RegSequenceLiveRange.ll75
-rw-r--r--test/CodeGen/ARM/2012-01-26-CoalescerBug.ll21
-rw-r--r--test/CodeGen/ARM/2012-01-26-CopyPropKills.ll121
-rw-r--r--test/CodeGen/ARM/2012-02-01-CoalescerBug.ll26
-rw-r--r--test/CodeGen/ARM/2012-03-05-FPSCR-bug.ll36
-rw-r--r--test/CodeGen/ARM/2012-03-13-DAGCombineBug.ll15
-rw-r--r--test/CodeGen/ARM/2012-03-26-FoldImmBug.ll33
-rw-r--r--test/CodeGen/ARM/2012-04-02-TwoAddrInstrCrash.ll24
-rw-r--r--test/CodeGen/ARM/2012-04-10-DAGCombine.ll31
-rw-r--r--test/CodeGen/ARM/2012-04-24-SplitEHCriticalEdge.ll71
-rw-r--r--test/CodeGen/ARM/2012-05-29-TailDupBug.ll140
-rw-r--r--test/CodeGen/ARM/2012-06-12-SchedMemLatency.ll41
-rw-r--r--test/CodeGen/ARM/2012-08-04-DtripleSpillReload.ll174
-rw-r--r--test/CodeGen/ARM/2012-08-08-legalize-unaligned.ll12
-rw-r--r--test/CodeGen/ARM/2012-08-09-neon-extload.ll102
-rw-r--r--test/CodeGen/ARM/2012-08-13-bfi.ll17
-rw-r--r--test/CodeGen/ARM/2012-08-27-CopyPhysRegCrash.ll129
-rw-r--r--test/CodeGen/ARM/2012-08-30-select.ll18
-rw-r--r--test/CodeGen/ARM/a15-mla.ll12
-rw-r--r--test/CodeGen/ARM/a15.ll6
-rw-r--r--test/CodeGen/ARM/addrmode.ll15
-rw-r--r--test/CodeGen/ARM/aliases.ll31
-rw-r--r--test/CodeGen/ARM/align.ll42
-rw-r--r--test/CodeGen/ARM/alloca.ll12
-rw-r--r--test/CodeGen/ARM/argaddr.ll19
-rw-r--r--test/CodeGen/ARM/arguments-nosplit-double.ll9
-rw-r--r--test/CodeGen/ARM/arguments-nosplit-i64.ll9
-rw-r--r--test/CodeGen/ARM/arguments.ll43
-rw-r--r--test/CodeGen/ARM/arguments2.ll9
-rw-r--r--test/CodeGen/ARM/arguments3.ll9
-rw-r--r--test/CodeGen/ARM/arguments4.ll9
-rw-r--r--test/CodeGen/ARM/arguments5.ll9
-rw-r--r--test/CodeGen/ARM/arguments6.ll9
-rw-r--r--test/CodeGen/ARM/arguments7.ll9
-rw-r--r--test/CodeGen/ARM/arguments8.ll9
-rw-r--r--test/CodeGen/ARM/arguments_f64_backfill.ll9
-rw-r--r--test/CodeGen/ARM/arm-and-tst-peephole.ll112
-rw-r--r--test/CodeGen/ARM/arm-asm.ll7
-rw-r--r--test/CodeGen/ARM/arm-frameaddr.ll17
-rw-r--r--test/CodeGen/ARM/arm-modifier.ll68
-rw-r--r--test/CodeGen/ARM/arm-negative-stride.ll47
-rw-r--r--test/CodeGen/ARM/arm-returnaddr.ll28
-rw-r--r--test/CodeGen/ARM/armv4.ll13
-rw-r--r--test/CodeGen/ARM/atomic-64bit.ll128
-rw-r--r--test/CodeGen/ARM/atomic-cmp.ll15
-rw-r--r--test/CodeGen/ARM/atomic-load-store.ll56
-rw-r--r--test/CodeGen/ARM/atomic-op.ll171
-rw-r--r--test/CodeGen/ARM/available_externally.ll16
-rw-r--r--test/CodeGen/ARM/avoid-cpsr-rmw.ll50
-rw-r--r--test/CodeGen/ARM/bfc.ll25
-rw-r--r--test/CodeGen/ARM/bfi.ll76
-rw-r--r--test/CodeGen/ARM/bfx.ll28
-rw-r--r--test/CodeGen/ARM/bic.ll17
-rw-r--r--test/CodeGen/ARM/bicZext.ll19
-rw-r--r--test/CodeGen/ARM/bits.ll41
-rw-r--r--test/CodeGen/ARM/bswap-inline-asm.ll9
-rw-r--r--test/CodeGen/ARM/bx_fold.ll31
-rw-r--r--test/CodeGen/ARM/call-tc.ll165
-rw-r--r--test/CodeGen/ARM/call.ll36
-rw-r--r--test/CodeGen/ARM/call_nolink.ll52
-rw-r--r--test/CodeGen/ARM/carry.ll47
-rw-r--r--test/CodeGen/ARM/clz.ll10
-rw-r--r--test/CodeGen/ARM/cmn.ll22
-rw-r--r--test/CodeGen/ARM/coalesce-subregs.ll116
-rw-r--r--test/CodeGen/ARM/code-placement.ll79
-rw-r--r--test/CodeGen/ARM/commute-movcc.ll67
-rw-r--r--test/CodeGen/ARM/compare-call.ll20
-rw-r--r--test/CodeGen/ARM/constants.ll69
-rw-r--r--test/CodeGen/ARM/crash-O0.ll28
-rw-r--r--test/CodeGen/ARM/crash-greedy-v6.ll32
-rw-r--r--test/CodeGen/ARM/crash-greedy.ll130
-rw-r--r--test/CodeGen/ARM/crash-shufflevector.ll10
-rw-r--r--test/CodeGen/ARM/crash.ll71
-rw-r--r--test/CodeGen/ARM/cse-call.ll31
-rw-r--r--test/CodeGen/ARM/cse-libcalls.ll30
-rw-r--r--test/CodeGen/ARM/ctor_order.ll30
-rw-r--r--test/CodeGen/ARM/ctors_dtors.ll25
-rw-r--r--test/CodeGen/ARM/ctz.ll11
-rw-r--r--test/CodeGen/ARM/dagcombine-anyexttozeroext.ll30
-rw-r--r--test/CodeGen/ARM/data-in-code-annotations.ll42
-rw-r--r--test/CodeGen/ARM/debug-info-arg.ll65
-rw-r--r--test/CodeGen/ARM/debug-info-blocks.ll245
-rw-r--r--test/CodeGen/ARM/debug-info-branch-folding.ll95
-rw-r--r--test/CodeGen/ARM/debug-info-d16-reg.ll105
-rw-r--r--test/CodeGen/ARM/debug-info-qreg.ll92
-rw-r--r--test/CodeGen/ARM/debug-info-s16-reg.ll115
-rw-r--r--test/CodeGen/ARM/debug-info-sreg2.ll61
-rw-r--r--test/CodeGen/ARM/div.ll34
-rw-r--r--test/CodeGen/ARM/divmod.ll72
-rw-r--r--test/CodeGen/ARM/domain-conv-vmovs.ll100
-rw-r--r--test/CodeGen/ARM/dyn-stackalloc.ll56
-rw-r--r--test/CodeGen/ARM/eh-resume-darwin.ll22
-rw-r--r--test/CodeGen/ARM/ehabi-unwind.ll16
-rw-r--r--test/CodeGen/ARM/elf-lcomm-align.ll14
-rw-r--r--test/CodeGen/ARM/extloadi1.ll20
-rw-r--r--test/CodeGen/ARM/fabss.ll29
-rw-r--r--test/CodeGen/ARM/fadds.ll23
-rw-r--r--test/CodeGen/ARM/fast-isel-GEP-coalesce.ll65
-rw-r--r--test/CodeGen/ARM/fast-isel-binary.ll116
-rw-r--r--test/CodeGen/ARM/fast-isel-br-const.ll48
-rw-r--r--test/CodeGen/ARM/fast-isel-br-phi.ll44
-rw-r--r--test/CodeGen/ARM/fast-isel-call-multi-reg-return.ll17
-rw-r--r--test/CodeGen/ARM/fast-isel-call.ll289
-rw-r--r--test/CodeGen/ARM/fast-isel-cmp-imm.ll250
-rw-r--r--test/CodeGen/ARM/fast-isel-conversion.ll242
-rw-r--r--test/CodeGen/ARM/fast-isel-crash.ll21
-rw-r--r--test/CodeGen/ARM/fast-isel-crash2.ll9
-rw-r--r--test/CodeGen/ARM/fast-isel-deadcode.ll22
-rw-r--r--test/CodeGen/ARM/fast-isel-fold.ll80
-rw-r--r--test/CodeGen/ARM/fast-isel-frameaddr.ll100
-rw-r--r--test/CodeGen/ARM/fast-isel-icmp.ll47
-rw-r--r--test/CodeGen/ARM/fast-isel-indirectbr.ll17
-rw-r--r--test/CodeGen/ARM/fast-isel-intrinsic.ll142
-rw-r--r--test/CodeGen/ARM/fast-isel-ldr-str-arm.ll55
-rw-r--r--test/CodeGen/ARM/fast-isel-ldr-str-thumb-neg-index.ll168
-rw-r--r--test/CodeGen/ARM/fast-isel-ldrh-strh-arm.ll149
-rw-r--r--test/CodeGen/ARM/fast-isel-mvn.ll107
-rw-r--r--test/CodeGen/ARM/fast-isel-pic.ll43
-rw-r--r--test/CodeGen/ARM/fast-isel-pred.ll58
-rw-r--r--test/CodeGen/ARM/fast-isel-redefinition.ll11
-rw-r--r--test/CodeGen/ARM/fast-isel-ret.ll57
-rw-r--r--test/CodeGen/ARM/fast-isel-select.ll99
-rw-r--r--test/CodeGen/ARM/fast-isel-shifter.ll50
-rw-r--r--test/CodeGen/ARM/fast-isel-static.ll30
-rw-r--r--test/CodeGen/ARM/fast-isel.ll240
-rw-r--r--test/CodeGen/ARM/fcopysign.ll60
-rw-r--r--test/CodeGen/ARM/fdivs.ll23
-rw-r--r--test/CodeGen/ARM/fixunsdfdi.ll29
-rw-r--r--test/CodeGen/ARM/flag-crash.ll27
-rw-r--r--test/CodeGen/ARM/floorf.ll29
-rw-r--r--test/CodeGen/ARM/fmacs.ll104
-rw-r--r--test/CodeGen/ARM/fmdrr-fmrrd.ll13
-rw-r--r--test/CodeGen/ARM/fmscs.ll35
-rw-r--r--test/CodeGen/ARM/fmuls.ll32
-rw-r--r--test/CodeGen/ARM/fnegs.ll53
-rw-r--r--test/CodeGen/ARM/fnmacs.ll35
-rw-r--r--test/CodeGen/ARM/fnmscs.ll72
-rw-r--r--test/CodeGen/ARM/fnmul.ll11
-rw-r--r--test/CodeGen/ARM/fnmuls.ll21
-rw-r--r--test/CodeGen/ARM/fold-const.ll14
-rw-r--r--test/CodeGen/ARM/formal.ll8
-rw-r--r--test/CodeGen/ARM/fp-arg-shuffle.ll11
-rw-r--r--test/CodeGen/ARM/fp-fast.ll60
-rw-r--r--test/CodeGen/ARM/fp.ll78
-rw-r--r--test/CodeGen/ARM/fp16.ll32
-rw-r--r--test/CodeGen/ARM/fp_convert.ll50
-rw-r--r--test/CodeGen/ARM/fparith.ll101
-rw-r--r--test/CodeGen/ARM/fpcmp-opt.ll80
-rw-r--r--test/CodeGen/ARM/fpcmp.ll71
-rw-r--r--test/CodeGen/ARM/fpcmp_ueq.ll16
-rw-r--r--test/CodeGen/ARM/fpconsts.ll33
-rw-r--r--test/CodeGen/ARM/fpconv.ll102
-rw-r--r--test/CodeGen/ARM/fpmem.ll41
-rw-r--r--test/CodeGen/ARM/fpow.ll9
-rw-r--r--test/CodeGen/ARM/fpowi.ll15
-rw-r--r--test/CodeGen/ARM/fptoint.ll49
-rw-r--r--test/CodeGen/ARM/fsubs.ll13
-rw-r--r--test/CodeGen/ARM/fusedMAC.ll224
-rw-r--r--test/CodeGen/ARM/global-merge.ll23
-rw-r--r--test/CodeGen/ARM/globals.ll74
-rw-r--r--test/CodeGen/ARM/gv-stubs-crash.ll36
-rw-r--r--test/CodeGen/ARM/hardfloat_neon.ll13
-rw-r--r--test/CodeGen/ARM/hello.ll14
-rw-r--r--test/CodeGen/ARM/hidden-vis-2.ll12
-rw-r--r--test/CodeGen/ARM/hidden-vis-3.ll17
-rw-r--r--test/CodeGen/ARM/hidden-vis.ll23
-rw-r--r--test/CodeGen/ARM/iabs.ll34
-rw-r--r--test/CodeGen/ARM/ifcvt1.ll17
-rw-r--r--test/CodeGen/ARM/ifcvt10.ll43
-rw-r--r--test/CodeGen/ARM/ifcvt11.ll59
-rw-r--r--test/CodeGen/ARM/ifcvt2.ll42
-rw-r--r--test/CodeGen/ARM/ifcvt3.ll24
-rw-r--r--test/CodeGen/ARM/ifcvt4.ll40
-rw-r--r--test/CodeGen/ARM/ifcvt5.ll25
-rw-r--r--test/CodeGen/ARM/ifcvt6.ll20
-rw-r--r--test/CodeGen/ARM/ifcvt7.ll32
-rw-r--r--test/CodeGen/ARM/ifcvt8.ll19
-rw-r--r--test/CodeGen/ARM/ifcvt9.ll12
-rw-r--r--test/CodeGen/ARM/illegal-vector-bitcast.ll14
-rw-r--r--test/CodeGen/ARM/imm.ll16
-rw-r--r--test/CodeGen/ARM/indirectbr.ll66
-rw-r--r--test/CodeGen/ARM/inlineasm-imm-arm.ll31
-rw-r--r--test/CodeGen/ARM/inlineasm.ll11
-rw-r--r--test/CodeGen/ARM/inlineasm2.ll11
-rw-r--r--test/CodeGen/ARM/inlineasm3.ll122
-rw-r--r--test/CodeGen/ARM/inlineasm4.ll17
-rw-r--r--test/CodeGen/ARM/insn-sched1.ll11
-rw-r--r--test/CodeGen/ARM/int-to-fp.ll19
-rw-r--r--test/CodeGen/ARM/integer_insertelement.ll35
-rw-r--r--test/CodeGen/ARM/intrinsics.ll39
-rw-r--r--test/CodeGen/ARM/ispositive.ll10
-rw-r--r--test/CodeGen/ARM/jumptable-label.ll33
-rw-r--r--test/CodeGen/ARM/large-stack.ll20
-rw-r--r--test/CodeGen/ARM/ldm.ll46
-rw-r--r--test/CodeGen/ARM/ldr.ll71
-rw-r--r--test/CodeGen/ARM/ldr_ext.ll37
-rw-r--r--test/CodeGen/ARM/ldr_frame.ll31
-rw-r--r--test/CodeGen/ARM/ldr_post.ll25
-rw-r--r--test/CodeGen/ARM/ldr_pre.ll23
-rw-r--r--test/CodeGen/ARM/ldrd-memoper.ll15
-rw-r--r--test/CodeGen/ARM/ldrd.ll69
-rw-r--r--test/CodeGen/ARM/ldst-f32-2-i32.ll28
-rw-r--r--test/CodeGen/ARM/ldstrexd.ll33
-rw-r--r--test/CodeGen/ARM/lit.local.cfg6
-rw-r--r--test/CodeGen/ARM/load-global.ll50
-rw-r--r--test/CodeGen/ARM/load.ll34
-rw-r--r--test/CodeGen/ARM/load_i1_select.ll19
-rw-r--r--test/CodeGen/ARM/log2_not_readnone.ll15
-rw-r--r--test/CodeGen/ARM/long-setcc.ll17
-rw-r--r--test/CodeGen/ARM/long.ll90
-rw-r--r--test/CodeGen/ARM/longMAC.ll44
-rw-r--r--test/CodeGen/ARM/long_shift.ll47
-rw-r--r--test/CodeGen/ARM/lsr-code-insertion.ll64
-rw-r--r--test/CodeGen/ARM/lsr-icmp-imm.ll33
-rw-r--r--test/CodeGen/ARM/lsr-scale-addr-mode.ll19
-rw-r--r--test/CodeGen/ARM/lsr-unfolded-offset.ll80
-rw-r--r--test/CodeGen/ARM/machine-cse-cmp.ll47
-rw-r--r--test/CodeGen/ARM/machine-licm.ll66
-rw-r--r--test/CodeGen/ARM/mem.ll14
-rw-r--r--test/CodeGen/ARM/memcpy-inline.ll18
-rw-r--r--test/CodeGen/ARM/memfunc.ll32
-rw-r--r--test/CodeGen/ARM/mls.ll16
-rw-r--r--test/CodeGen/ARM/movt-movw-global.ll39
-rw-r--r--test/CodeGen/ARM/movt.ll19
-rw-r--r--test/CodeGen/ARM/mul.ll22
-rw-r--r--test/CodeGen/ARM/mul_const.ll85
-rw-r--r--test/CodeGen/ARM/mulhi.ll54
-rw-r--r--test/CodeGen/ARM/mult-alt-generic-arm.ll323
-rw-r--r--test/CodeGen/ARM/mvn.ll74
-rw-r--r--test/CodeGen/ARM/neon_arith1.ll7
-rw-r--r--test/CodeGen/ARM/neon_div.ll48
-rw-r--r--test/CodeGen/ARM/neon_ld1.ll30
-rw-r--r--test/CodeGen/ARM/neon_ld2.ll32
-rw-r--r--test/CodeGen/ARM/neon_minmax.ll81
-rw-r--r--test/CodeGen/ARM/neon_shift.ll11
-rw-r--r--test/CodeGen/ARM/neon_spill.ll54
-rw-r--r--test/CodeGen/ARM/odr_comdat.ll16
-rw-r--r--test/CodeGen/ARM/opt-shuff-tstore.ll19
-rw-r--r--test/CodeGen/ARM/pack.ll88
-rw-r--r--test/CodeGen/ARM/peephole-bitcast.ll28
-rw-r--r--test/CodeGen/ARM/phi.ll23
-rw-r--r--test/CodeGen/ARM/pr13249.ll27
-rw-r--r--test/CodeGen/ARM/pr3502.ll24
-rw-r--r--test/CodeGen/ARM/prefetch.ll77
-rw-r--r--test/CodeGen/ARM/private.ll20
-rw-r--r--test/CodeGen/ARM/reg_asc_order.ll16
-rw-r--r--test/CodeGen/ARM/reg_sequence.ll350
-rw-r--r--test/CodeGen/ARM/ret0.ll5
-rw-r--r--test/CodeGen/ARM/ret_arg1.ll5
-rw-r--r--test/CodeGen/ARM/ret_arg2.ll6
-rw-r--r--test/CodeGen/ARM/ret_arg3.ll5
-rw-r--r--test/CodeGen/ARM/ret_arg4.ll5
-rw-r--r--test/CodeGen/ARM/ret_arg5.ll5
-rw-r--r--test/CodeGen/ARM/ret_f32_arg2.ll6
-rw-r--r--test/CodeGen/ARM/ret_f32_arg5.ll6
-rw-r--r--test/CodeGen/ARM/ret_f64_arg2.ll6
-rw-r--r--test/CodeGen/ARM/ret_f64_arg_reg_split.ll6
-rw-r--r--test/CodeGen/ARM/ret_f64_arg_split.ll6
-rw-r--r--test/CodeGen/ARM/ret_f64_arg_stack.ll6
-rw-r--r--test/CodeGen/ARM/ret_i128_arg2.ll6
-rw-r--r--test/CodeGen/ARM/ret_i64_arg2.ll6
-rw-r--r--test/CodeGen/ARM/ret_i64_arg3.ll6
-rw-r--r--test/CodeGen/ARM/ret_i64_arg_split.ll6
-rw-r--r--test/CodeGen/ARM/ret_void.ll6
-rw-r--r--test/CodeGen/ARM/rev.ll126
-rw-r--r--test/CodeGen/ARM/sbfx.ll47
-rw-r--r--test/CodeGen/ARM/section.ll6
-rw-r--r--test/CodeGen/ARM/select-imm.ll114
-rw-r--r--test/CodeGen/ARM/select.ll140
-rw-r--r--test/CodeGen/ARM/select_xform.ll224
-rw-r--r--test/CodeGen/ARM/shifter_operand.ll75
-rw-r--r--test/CodeGen/ARM/shuffle.ll18
-rw-r--r--test/CodeGen/ARM/smml.ll13
-rw-r--r--test/CodeGen/ARM/smul.ll36
-rw-r--r--test/CodeGen/ARM/spill-q.ll91
-rw-r--r--test/CodeGen/ARM/stack-frame.ll13
-rw-r--r--test/CodeGen/ARM/stm.ll16
-rw-r--r--test/CodeGen/ARM/str_post.ll22
-rw-r--r--test/CodeGen/ARM/str_pre-2.ll14
-rw-r--r--test/CodeGen/ARM/str_pre.ll18
-rw-r--r--test/CodeGen/ARM/str_trunc.ll16
-rw-r--r--test/CodeGen/ARM/struct_byval.ll46
-rw-r--r--test/CodeGen/ARM/sub-cmp-peephole.ll86
-rw-r--r--test/CodeGen/ARM/sub.ll50
-rw-r--r--test/CodeGen/ARM/subreg-remat.ll52
-rw-r--r--test/CodeGen/ARM/sxt_rot.ll30
-rw-r--r--test/CodeGen/ARM/t2-imm.ll9
-rw-r--r--test/CodeGen/ARM/tail-dup.ll44
-rw-r--r--test/CodeGen/ARM/tail-opts.ll67
-rw-r--r--test/CodeGen/ARM/test-sharedidx.ll96
-rw-r--r--test/CodeGen/ARM/thread_pointer.ll10
-rw-r--r--test/CodeGen/ARM/thumb1-varalloc.ll42
-rw-r--r--test/CodeGen/ARM/thumb2-it-block.ll20
-rw-r--r--test/CodeGen/ARM/tls-models.ll117
-rw-r--r--test/CodeGen/ARM/tls1.ll20
-rw-r--r--test/CodeGen/ARM/tls2.ll27
-rw-r--r--test/CodeGen/ARM/tls3.ll11
-rw-r--r--test/CodeGen/ARM/trap.ll17
-rw-r--r--test/CodeGen/ARM/trunc_ldr.ll24
-rw-r--r--test/CodeGen/ARM/truncstore-dag-combine.ll18
-rw-r--r--test/CodeGen/ARM/tst_teq.ll18
-rw-r--r--test/CodeGen/ARM/twoaddrinstr.ll21
-rw-r--r--test/CodeGen/ARM/uint64tof64.ll17
-rw-r--r--test/CodeGen/ARM/umulo-32.ll41
-rw-r--r--test/CodeGen/ARM/unaligned_load_store.ll77
-rw-r--r--test/CodeGen/ARM/unaligned_load_store_vector.ll487
-rw-r--r--test/CodeGen/ARM/undef-sext.ll14
-rw-r--r--test/CodeGen/ARM/unord.ll14
-rw-r--r--test/CodeGen/ARM/unsafe-fsub.ll18
-rw-r--r--test/CodeGen/ARM/uxt_rot.ll24
-rw-r--r--test/CodeGen/ARM/uxtb.ll74
-rw-r--r--test/CodeGen/ARM/va_arg.ll42
-rw-r--r--test/CodeGen/ARM/vaba.ll221
-rw-r--r--test/CodeGen/ARM/vabd.ll207
-rw-r--r--test/CodeGen/ARM/vabs.ll131
-rw-r--r--test/CodeGen/ARM/vadd.ll279
-rw-r--r--test/CodeGen/ARM/vargs.ll12
-rw-r--r--test/CodeGen/ARM/vargs_align.ll22
-rw-r--r--test/CodeGen/ARM/vbits.ll547
-rw-r--r--test/CodeGen/ARM/vbsl-constant.ll115
-rw-r--r--test/CodeGen/ARM/vbsl.ll105
-rw-r--r--test/CodeGen/ARM/vceq.ll92
-rw-r--r--test/CodeGen/ARM/vcge.ll203
-rw-r--r--test/CodeGen/ARM/vcgt.ll198
-rw-r--r--test/CodeGen/ARM/vcnt.ll133
-rw-r--r--test/CodeGen/ARM/vcombine.ll72
-rw-r--r--test/CodeGen/ARM/vcvt.ll158
-rw-r--r--test/CodeGen/ARM/vcvt_combine.ll99
-rw-r--r--test/CodeGen/ARM/vdiv_combine.ll102
-rw-r--r--test/CodeGen/ARM/vdup.ll297
-rw-r--r--test/CodeGen/ARM/vector-DAGCombine.ll135
-rw-r--r--test/CodeGen/ARM/vector-extend-narrow.ll75
-rw-r--r--test/CodeGen/ARM/vext.ll152
-rw-r--r--test/CodeGen/ARM/vfcmp.ll139
-rw-r--r--test/CodeGen/ARM/vfp.ll156
-rw-r--r--test/CodeGen/ARM/vget_lane.ll233
-rw-r--r--test/CodeGen/ARM/vhadd.ll249
-rw-r--r--test/CodeGen/ARM/vhsub.ll125
-rw-r--r--test/CodeGen/ARM/vicmp.ll113
-rw-r--r--test/CodeGen/ARM/vld1.ll141
-rw-r--r--test/CodeGen/ARM/vld2.ll155
-rw-r--r--test/CodeGen/ARM/vld3.ll159
-rw-r--r--test/CodeGen/ARM/vld4.ll160
-rw-r--r--test/CodeGen/ARM/vlddup.ll214
-rw-r--r--test/CodeGen/ARM/vldlane.ll521
-rw-r--r--test/CodeGen/ARM/vminmax.ll293
-rw-r--r--test/CodeGen/ARM/vmla.ll215
-rw-r--r--test/CodeGen/ARM/vmls.ll215
-rw-r--r--test/CodeGen/ARM/vmov.ll400
-rw-r--r--test/CodeGen/ARM/vmul.ll601
-rw-r--r--test/CodeGen/ARM/vneg.ll121
-rw-r--r--test/CodeGen/ARM/vpadal.ll125
-rw-r--r--test/CodeGen/ARM/vpadd.ll169
-rw-r--r--test/CodeGen/ARM/vpminmax.ll147
-rw-r--r--test/CodeGen/ARM/vqadd.ll165
-rw-r--r--test/CodeGen/ARM/vqdmul.ll280
-rw-r--r--test/CodeGen/ARM/vqshl.ll531
-rw-r--r--test/CodeGen/ARM/vqshrn.ll169
-rw-r--r--test/CodeGen/ARM/vqsub.ll165
-rw-r--r--test/CodeGen/ARM/vrec.ll119
-rw-r--r--test/CodeGen/ARM/vrev.ll180
-rw-r--r--test/CodeGen/ARM/vshift.ll432
-rw-r--r--test/CodeGen/ARM/vshiftins.ll155
-rw-r--r--test/CodeGen/ARM/vshl.ll654
-rw-r--r--test/CodeGen/ARM/vshll.ll83
-rw-r--r--test/CodeGen/ARM/vshrn.ll57
-rw-r--r--test/CodeGen/ARM/vsra.ll341
-rw-r--r--test/CodeGen/ARM/vst1.ll130
-rw-r--r--test/CodeGen/ARM/vst2.ll140
-rw-r--r--test/CodeGen/ARM/vst3.ll128
-rw-r--r--test/CodeGen/ARM/vst4.ll127
-rw-r--r--test/CodeGen/ARM/vstlane.ll375
-rw-r--r--test/CodeGen/ARM/vsub.ll279
-rw-r--r--test/CodeGen/ARM/vtbl.ll109
-rw-r--r--test/CodeGen/ARM/vtrn.ll124
-rw-r--r--test/CodeGen/ARM/vuzp.ll102
-rw-r--r--test/CodeGen/ARM/vzip.ll102
-rw-r--r--test/CodeGen/ARM/weak.ll16
-rw-r--r--test/CodeGen/ARM/weak2.ll18
-rw-r--r--test/CodeGen/ARM/widen-vmovs.ll36
-rw-r--r--test/CodeGen/CPP/2007-06-16-Funcname.ll8
-rw-r--r--test/CodeGen/CPP/2009-05-01-Long-Double.ll13
-rw-r--r--test/CodeGen/CPP/2009-05-04-CondBr.ll28
-rw-r--r--test/CodeGen/CPP/2012-02-05-UnitVarCrash.ll6
-rw-r--r--test/CodeGen/CPP/lit.local.cfg6
-rw-r--r--test/CodeGen/CellSPU/2009-01-01-BrCond.ll31
-rw-r--r--test/CodeGen/CellSPU/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/CellSPU/and_ops.ll282
-rw-r--r--test/CodeGen/CellSPU/arg_ret.ll34
-rw-r--r--test/CodeGen/CellSPU/bigstack.ll17
-rw-r--r--test/CodeGen/CellSPU/bss.ll11
-rw-r--r--test/CodeGen/CellSPU/call.ll49
-rw-r--r--test/CodeGen/CellSPU/crash.ll8
-rw-r--r--test/CodeGen/CellSPU/ctpop.ll30
-rw-r--r--test/CodeGen/CellSPU/div_ops.ll22
-rw-r--r--test/CodeGen/CellSPU/dp_farith.ll102
-rw-r--r--test/CodeGen/CellSPU/eqv.ll152
-rw-r--r--test/CodeGen/CellSPU/extract_elt.ll277
-rw-r--r--test/CodeGen/CellSPU/fcmp32.ll36
-rw-r--r--test/CodeGen/CellSPU/fcmp64.ll7
-rw-r--r--test/CodeGen/CellSPU/fdiv.ll22
-rw-r--r--test/CodeGen/CellSPU/fneg-fabs.ll42
-rw-r--r--test/CodeGen/CellSPU/i64ops.ll57
-rw-r--r--test/CodeGen/CellSPU/i8ops.ll25
-rw-r--r--test/CodeGen/CellSPU/icmp16.ll574
-rw-r--r--test/CodeGen/CellSPU/icmp32.ll575
-rw-r--r--test/CodeGen/CellSPU/icmp64.ll146
-rw-r--r--test/CodeGen/CellSPU/icmp8.ll446
-rw-r--r--test/CodeGen/CellSPU/immed16.ll40
-rw-r--r--test/CodeGen/CellSPU/immed32.ll83
-rw-r--r--test/CodeGen/CellSPU/immed64.ll95
-rw-r--r--test/CodeGen/CellSPU/int2fp.ll41
-rw-r--r--test/CodeGen/CellSPU/intrinsics_branch.ll150
-rw-r--r--test/CodeGen/CellSPU/intrinsics_float.ll94
-rw-r--r--test/CodeGen/CellSPU/intrinsics_logical.ll49
-rw-r--r--test/CodeGen/CellSPU/jumptable.ll21
-rw-r--r--test/CodeGen/CellSPU/lit.local.cfg6
-rw-r--r--test/CodeGen/CellSPU/loads.ll59
-rw-r--r--test/CodeGen/CellSPU/mul-with-overflow.ll15
-rw-r--r--test/CodeGen/CellSPU/mul_ops.ll88
-rw-r--r--test/CodeGen/CellSPU/nand.ll125
-rw-r--r--test/CodeGen/CellSPU/or_ops.ll278
-rw-r--r--test/CodeGen/CellSPU/private.ll19
-rw-r--r--test/CodeGen/CellSPU/rotate_ops.ll172
-rw-r--r--test/CodeGen/CellSPU/select_bits.ll572
-rw-r--r--test/CodeGen/CellSPU/sext128.ll71
-rw-r--r--test/CodeGen/CellSPU/shift_ops.ll348
-rw-r--r--test/CodeGen/CellSPU/shuffles.ll69
-rw-r--r--test/CodeGen/CellSPU/sp_farith.ll90
-rw-r--r--test/CodeGen/CellSPU/stores.ll181
-rw-r--r--test/CodeGen/CellSPU/storestruct.ll13
-rw-r--r--test/CodeGen/CellSPU/struct_1.ll147
-rw-r--r--test/CodeGen/CellSPU/sub_ops.ll26
-rw-r--r--test/CodeGen/CellSPU/trunc.ll94
-rw-r--r--test/CodeGen/CellSPU/useful-harnesses/README.txt5
-rw-r--r--test/CodeGen/CellSPU/useful-harnesses/i32operations.c69
-rw-r--r--test/CodeGen/CellSPU/useful-harnesses/i64operations.c673
-rw-r--r--test/CodeGen/CellSPU/useful-harnesses/i64operations.h43
-rw-r--r--test/CodeGen/CellSPU/useful-harnesses/lit.local.cfg1
-rw-r--r--test/CodeGen/CellSPU/useful-harnesses/vecoperations.c179
-rw-r--r--test/CodeGen/CellSPU/v2f32.ll78
-rw-r--r--test/CodeGen/CellSPU/v2i32.ll61
-rw-r--r--test/CodeGen/CellSPU/vec_const.ll154
-rw-r--r--test/CodeGen/CellSPU/vecinsert.ll131
-rw-r--r--test/CodeGen/Generic/2002-04-14-UnexpectedUnsignedType.ll13
-rw-r--r--test/CodeGen/Generic/2002-04-16-StackFrameSizeAlignment.ll14
-rw-r--r--test/CodeGen/Generic/2003-05-27-phifcmpd.ll19
-rw-r--r--test/CodeGen/Generic/2003-05-27-useboolinotherbb.ll13
-rw-r--r--test/CodeGen/Generic/2003-05-27-usefsubasbool.ll14
-rw-r--r--test/CodeGen/Generic/2003-05-28-ManyArgs.ll153
-rw-r--r--test/CodeGen/Generic/2003-05-30-BadFoldGEP.ll39
-rw-r--r--test/CodeGen/Generic/2003-05-30-BadPreselectPhi.ll33
-rw-r--r--test/CodeGen/Generic/2003-07-06-BadIntCmp.ll51
-rw-r--r--test/CodeGen/Generic/2003-07-07-BadLongConst.ll20
-rw-r--r--test/CodeGen/Generic/2003-07-08-BadCastToBool.ll34
-rw-r--r--test/CodeGen/Generic/2003-07-29-BadConstSbyte.ll40
-rw-r--r--test/CodeGen/Generic/2004-05-09-LiveVarPartialRegister.ll13
-rw-r--r--test/CodeGen/Generic/2005-01-18-SetUO-InfLoop.ll20
-rw-r--r--test/CodeGen/Generic/2005-04-09-GlobalInPHI.ll20
-rw-r--r--test/CodeGen/Generic/2005-10-18-ZeroSizeStackObject.ll6
-rw-r--r--test/CodeGen/Generic/2005-10-21-longlonggtu.ll16
-rw-r--r--test/CodeGen/Generic/2005-12-01-Crash.ll20
-rw-r--r--test/CodeGen/Generic/2005-12-12-ExpandSextInreg.ll7
-rw-r--r--test/CodeGen/Generic/2006-01-12-BadSetCCFold.ll35
-rw-r--r--test/CodeGen/Generic/2006-01-18-InvalidBranchOpcodeAssert.ll15
-rw-r--r--test/CodeGen/Generic/2006-02-12-InsertLibcall.ll60
-rw-r--r--test/CodeGen/Generic/2006-03-01-dagcombineinfloop.ll95
-rw-r--r--test/CodeGen/Generic/2006-04-26-SetCCAnd.ll40
-rw-r--r--test/CodeGen/Generic/2006-04-28-Sign-extend-bool.ll9
-rw-r--r--test/CodeGen/Generic/2006-05-06-GEP-Cast-Sink-Crash.ll29
-rw-r--r--test/CodeGen/Generic/2006-06-12-LowerSwitchCrash.ll10
-rw-r--r--test/CodeGen/Generic/2006-06-13-ComputeMaskedBitsCrash.ll35
-rw-r--r--test/CodeGen/Generic/2006-06-28-SimplifySetCCCrash.ll279
-rw-r--r--test/CodeGen/Generic/2006-07-03-schedulers.ll32
-rw-r--r--test/CodeGen/Generic/2006-08-30-CoalescerCrash.ll112
-rw-r--r--test/CodeGen/Generic/2006-09-02-LocalAllocCrash.ll117
-rw-r--r--test/CodeGen/Generic/2006-09-06-SwitchLowering.ll96
-rw-r--r--test/CodeGen/Generic/2006-10-27-CondFolding.ll21
-rw-r--r--test/CodeGen/Generic/2006-10-29-Crash.ll22
-rw-r--r--test/CodeGen/Generic/2006-11-20-DAGCombineCrash.ll41
-rw-r--r--test/CodeGen/Generic/2007-01-15-LoadSelectCycle.ll12
-rw-r--r--test/CodeGen/Generic/2007-02-25-invoke.ll16
-rw-r--r--test/CodeGen/Generic/2007-04-08-MultipleFrameIndices.ll11
-rw-r--r--test/CodeGen/Generic/2007-04-13-SwitchLowerBadPhi.ll24
-rw-r--r--test/CodeGen/Generic/2007-04-17-lsr-crash.ll35
-rw-r--r--test/CodeGen/Generic/2007-04-27-InlineAsm-X-Dest.ll8
-rw-r--r--test/CodeGen/Generic/2007-04-27-LargeMemObject.ll13
-rw-r--r--test/CodeGen/Generic/2007-04-30-LandingPadBranchFolding.ll63
-rw-r--r--test/CodeGen/Generic/2007-05-03-EHTypeInfo.ll12
-rw-r--r--test/CodeGen/Generic/2007-05-15-InfiniteRecursion.ll90
-rw-r--r--test/CodeGen/Generic/2007-12-17-InvokeAsm.ll17
-rw-r--r--test/CodeGen/Generic/2007-12-31-UnusedSelector.ll35
-rw-r--r--test/CodeGen/Generic/2008-01-25-dag-combine-mul.ll31
-rw-r--r--test/CodeGen/Generic/2008-01-30-LoadCrash.ll19
-rw-r--r--test/CodeGen/Generic/2008-02-04-Ctlz.ll21
-rw-r--r--test/CodeGen/Generic/2008-02-04-ExtractSubvector.ll14
-rw-r--r--test/CodeGen/Generic/2008-02-20-MatchingMem.ll9
-rw-r--r--test/CodeGen/Generic/2008-02-25-NegateZero.ll14
-rw-r--r--test/CodeGen/Generic/2008-02-26-NegatableCrash.ll50
-rw-r--r--test/CodeGen/Generic/2008-08-07-PtrToInt-SmallerInt.ll5
-rw-r--r--test/CodeGen/Generic/2009-03-17-LSR-APInt.ll92
-rw-r--r--test/CodeGen/Generic/2009-03-29-SoftFloatVectorExtract.ll10
-rw-r--r--test/CodeGen/Generic/2009-04-10-SinkCrash.ll16
-rw-r--r--test/CodeGen/Generic/2009-04-28-i128-cmp-crash.ll32
-rw-r--r--test/CodeGen/Generic/2009-11-16-BadKillsCrash.ll77
-rw-r--r--test/CodeGen/Generic/2010-07-27-DAGCombineCrash.ll6
-rw-r--r--test/CodeGen/Generic/2010-11-04-BigByval.ll11
-rw-r--r--test/CodeGen/Generic/2010-ZeroSizedArg.ll17
-rw-r--r--test/CodeGen/Generic/2011-01-06-BigNumberCrash.ll15
-rw-r--r--test/CodeGen/Generic/2011-07-07-ScheduleDAGCrash.ll19
-rw-r--r--test/CodeGen/Generic/2012-06-08-APIntCrash.ll9
-rw-r--r--test/CodeGen/Generic/2012-07-15-BuildVectorPromote.ll8
-rw-r--r--test/CodeGen/Generic/APIntLoadStore.ll2049
-rw-r--r--test/CodeGen/Generic/APIntParam.ll1537
-rw-r--r--test/CodeGen/Generic/APIntSextParam.ll1537
-rw-r--r--test/CodeGen/Generic/APIntZextParam.ll1537
-rw-r--r--test/CodeGen/Generic/BasicInstrs.ll54
-rw-r--r--test/CodeGen/Generic/ConstantExprLowering.ll22
-rw-r--r--test/CodeGen/Generic/MachineBranchProb.ll32
-rw-r--r--test/CodeGen/Generic/Makefile23
-rw-r--r--test/CodeGen/Generic/add-with-overflow-128.ll34
-rw-r--r--test/CodeGen/Generic/add-with-overflow-24.ll42
-rw-r--r--test/CodeGen/Generic/add-with-overflow.ll41
-rw-r--r--test/CodeGen/Generic/addr-label.ll81
-rw-r--r--test/CodeGen/Generic/asm-large-immediate.ll10
-rw-r--r--test/CodeGen/Generic/badCallArgLRLLVM.ll31
-rw-r--r--test/CodeGen/Generic/badFoldGEP.ll27
-rw-r--r--test/CodeGen/Generic/badarg6.ll32
-rw-r--r--test/CodeGen/Generic/bool-to-double.ll6
-rw-r--r--test/CodeGen/Generic/builtin-expect.ll223
-rw-r--r--test/CodeGen/Generic/call-ret0.ll10
-rw-r--r--test/CodeGen/Generic/call-ret42.ll10
-rw-r--r--test/CodeGen/Generic/call-void.ll11
-rw-r--r--test/CodeGen/Generic/call2-ret0.ll16
-rw-r--r--test/CodeGen/Generic/cast-fp.ll33
-rw-r--r--test/CodeGen/Generic/constindices.ll44
-rw-r--r--test/CodeGen/Generic/crash.ll68
-rw-r--r--test/CodeGen/Generic/dbg_value.ll13
-rw-r--r--test/CodeGen/Generic/div-neg-power-2.ll7
-rw-r--r--test/CodeGen/Generic/donothing.ll31
-rw-r--r--test/CodeGen/Generic/edge-bundles-blockIDs.ll81
-rw-r--r--test/CodeGen/Generic/empty-load-store.ll18
-rw-r--r--test/CodeGen/Generic/exception-handling.ll29
-rw-r--r--test/CodeGen/Generic/externally_available.ll10
-rw-r--r--test/CodeGen/Generic/fastcall.ll14
-rw-r--r--test/CodeGen/Generic/fneg-fabs.ll26
-rw-r--r--test/CodeGen/Generic/fp-to-int-invalid.ll18
-rw-r--r--test/CodeGen/Generic/fp_to_int.ll81
-rw-r--r--test/CodeGen/Generic/fpowi-promote.ll11
-rw-r--r--test/CodeGen/Generic/fwdtwice.ll29
-rw-r--r--test/CodeGen/Generic/global-ret0.ll8
-rw-r--r--test/CodeGen/Generic/hello.ll11
-rw-r--r--test/CodeGen/Generic/i128-addsub.ll39
-rw-r--r--test/CodeGen/Generic/i128-arith.ll11
-rw-r--r--test/CodeGen/Generic/inline-asm-special-strings.ll6
-rw-r--r--test/CodeGen/Generic/intrinsics.ll40
-rw-r--r--test/CodeGen/Generic/invalid-memcpy.ll17
-rw-r--r--test/CodeGen/Generic/isunord.ll9
-rw-r--r--test/CodeGen/Generic/lit.local.cfg1
-rw-r--r--test/CodeGen/Generic/llvm-ct-intrinsics.ll62
-rw-r--r--test/CodeGen/Generic/multiple-return-values-cross-block-with-invoke.ll21
-rw-r--r--test/CodeGen/Generic/negintconst.ll47
-rw-r--r--test/CodeGen/Generic/nested-select.ll19
-rw-r--r--test/CodeGen/Generic/overflow.ll220
-rw-r--r--test/CodeGen/Generic/pr12507.ll18
-rw-r--r--test/CodeGen/Generic/pr2625.ll17
-rw-r--r--test/CodeGen/Generic/pr3288.ll67
-rw-r--r--test/CodeGen/Generic/print-add.ll18
-rw-r--r--test/CodeGen/Generic/print-after.ll6
-rw-r--r--test/CodeGen/Generic/print-arith-fp.ll61
-rw-r--r--test/CodeGen/Generic/print-arith-int.ll84
-rw-r--r--test/CodeGen/Generic/print-int.ll13
-rw-r--r--test/CodeGen/Generic/print-machineinstrs.ll14
-rw-r--r--test/CodeGen/Generic/print-mul-exp.ll55
-rw-r--r--test/CodeGen/Generic/print-mul.ll32
-rw-r--r--test/CodeGen/Generic/print-shift.ll34
-rw-r--r--test/CodeGen/Generic/ret0.ll5
-rw-r--r--test/CodeGen/Generic/ret42.ll5
-rw-r--r--test/CodeGen/Generic/select-cc.ll9
-rw-r--r--test/CodeGen/Generic/select.ll195
-rw-r--r--test/CodeGen/Generic/shift-int64.ll12
-rw-r--r--test/CodeGen/Generic/stacksave-restore.ll14
-rw-r--r--test/CodeGen/Generic/stop-after.ll10
-rw-r--r--test/CodeGen/Generic/storetrunc-fp.ll8
-rw-r--r--test/CodeGen/Generic/switch-lower-feature.ll63
-rw-r--r--test/CodeGen/Generic/switch-lower.ll348
-rw-r--r--test/CodeGen/Generic/trap.ll9
-rw-r--r--test/CodeGen/Generic/undef-phi.ll26
-rw-r--r--test/CodeGen/Generic/v-split.ll11
-rw-r--r--test/CodeGen/Generic/vector-casts.ll45
-rw-r--r--test/CodeGen/Generic/vector-constantexpr.ll7
-rw-r--r--test/CodeGen/Generic/vector-identity-shuffle.ll17
-rw-r--r--test/CodeGen/Generic/vector.ll154
-rw-r--r--test/CodeGen/Generic/zero-sized-array.ll81
-rw-r--r--test/CodeGen/Hexagon/args.ll18
-rw-r--r--test/CodeGen/Hexagon/combine.ll17
-rw-r--r--test/CodeGen/Hexagon/convertdptoint.ll26
-rw-r--r--test/CodeGen/Hexagon/convertdptoll.ll27
-rw-r--r--test/CodeGen/Hexagon/convertsptoint.ll26
-rw-r--r--test/CodeGen/Hexagon/convertsptoll.ll27
-rw-r--r--test/CodeGen/Hexagon/dadd.ll19
-rw-r--r--test/CodeGen/Hexagon/dmul.ll18
-rw-r--r--test/CodeGen/Hexagon/double.ll22
-rw-r--r--test/CodeGen/Hexagon/doubleconvert-ieee-rnd-near.ll26
-rw-r--r--test/CodeGen/Hexagon/dsub.ll18
-rw-r--r--test/CodeGen/Hexagon/dualstore.ll17
-rw-r--r--test/CodeGen/Hexagon/fadd.ll18
-rw-r--r--test/CodeGen/Hexagon/fcmp.ll37
-rw-r--r--test/CodeGen/Hexagon/float.ll22
-rw-r--r--test/CodeGen/Hexagon/floatconvert-ieee-rnd-near.ll22
-rw-r--r--test/CodeGen/Hexagon/fmul.ll19
-rw-r--r--test/CodeGen/Hexagon/frame.ll23
-rw-r--r--test/CodeGen/Hexagon/fsub.ll18
-rw-r--r--test/CodeGen/Hexagon/fusedandshift.ll16
-rw-r--r--test/CodeGen/Hexagon/lit.local.cfg6
-rw-r--r--test/CodeGen/Hexagon/macint.ll14
-rw-r--r--test/CodeGen/Hexagon/mpy.ll19
-rw-r--r--test/CodeGen/Hexagon/newvaluejump.ll33
-rw-r--r--test/CodeGen/Hexagon/newvaluejump2.ll30
-rw-r--r--test/CodeGen/Hexagon/newvaluestore.ll22
-rw-r--r--test/CodeGen/Hexagon/opt-fabs.ll15
-rw-r--r--test/CodeGen/Hexagon/opt-fneg.ll26
-rw-r--r--test/CodeGen/Hexagon/remove_lsr.ll80
-rw-r--r--test/CodeGen/Hexagon/simpletailcall.ll14
-rw-r--r--test/CodeGen/Hexagon/static.ll20
-rw-r--r--test/CodeGen/Hexagon/struct_args.ll16
-rw-r--r--test/CodeGen/Hexagon/struct_args_large.ll16
-rw-r--r--test/CodeGen/Hexagon/vaddh.ll16
-rw-r--r--test/CodeGen/MBlaze/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/MBlaze/brind.ll72
-rw-r--r--test/CodeGen/MBlaze/callind.ll80
-rw-r--r--test/CodeGen/MBlaze/cc.ll266
-rw-r--r--test/CodeGen/MBlaze/div.ll75
-rw-r--r--test/CodeGen/MBlaze/fpu.ll66
-rw-r--r--test/CodeGen/MBlaze/fsl.ll319
-rw-r--r--test/CodeGen/MBlaze/imm.ll70
-rw-r--r--test/CodeGen/MBlaze/intr.ll48
-rw-r--r--test/CodeGen/MBlaze/jumptable.ll79
-rw-r--r--test/CodeGen/MBlaze/lit.local.cfg6
-rw-r--r--test/CodeGen/MBlaze/loop.ll44
-rw-r--r--test/CodeGen/MBlaze/mul.ll51
-rw-r--r--test/CodeGen/MBlaze/mul64.ll23
-rw-r--r--test/CodeGen/MBlaze/select.ll15
-rw-r--r--test/CodeGen/MBlaze/shift.ll115
-rw-r--r--test/CodeGen/MBlaze/svol.ll80
-rw-r--r--test/CodeGen/MSP430/2009-05-10-CyclicDAG.ll32
-rw-r--r--test/CodeGen/MSP430/2009-05-17-Rot.ll17
-rw-r--r--test/CodeGen/MSP430/2009-05-17-Shift.ll15
-rw-r--r--test/CodeGen/MSP430/2009-05-19-DoubleSplit.ll11
-rw-r--r--test/CodeGen/MSP430/2009-08-25-DynamicStackAlloc.ll30
-rw-r--r--test/CodeGen/MSP430/2009-09-18-AbsoluteAddr.ll22
-rw-r--r--test/CodeGen/MSP430/2009-10-10-OrImpDef.ll14
-rw-r--r--test/CodeGen/MSP430/2009-11-05-8BitLibcalls.ll22
-rw-r--r--test/CodeGen/MSP430/2009-11-08-InvalidResNo.ll64
-rw-r--r--test/CodeGen/MSP430/2009-11-20-NewNode.ll36
-rw-r--r--test/CodeGen/MSP430/2009-12-21-FrameAddr.ll13
-rw-r--r--test/CodeGen/MSP430/2009-12-22-InlineAsm.ll29
-rw-r--r--test/CodeGen/MSP430/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/MSP430/2010-05-01-CombinerAnd.ll27
-rw-r--r--test/CodeGen/MSP430/AddrMode-bis-rx.ll74
-rw-r--r--test/CodeGen/MSP430/AddrMode-bis-xr.ll81
-rw-r--r--test/CodeGen/MSP430/AddrMode-mov-rx.ll67
-rw-r--r--test/CodeGen/MSP430/AddrMode-mov-xr.ll67
-rw-r--r--test/CodeGen/MSP430/Inst16mi.ll48
-rw-r--r--test/CodeGen/MSP430/Inst16mm.ll69
-rw-r--r--test/CodeGen/MSP430/Inst16mr.ll58
-rw-r--r--test/CodeGen/MSP430/Inst16ri.ll37
-rw-r--r--test/CodeGen/MSP430/Inst16rm.ll46
-rw-r--r--test/CodeGen/MSP430/Inst16rr.ll45
-rw-r--r--test/CodeGen/MSP430/Inst8mi.ll48
-rw-r--r--test/CodeGen/MSP430/Inst8mm.ll55
-rw-r--r--test/CodeGen/MSP430/Inst8mr.ll58
-rw-r--r--test/CodeGen/MSP430/Inst8ri.ll37
-rw-r--r--test/CodeGen/MSP430/Inst8rm.ll46
-rw-r--r--test/CodeGen/MSP430/Inst8rr.ll46
-rw-r--r--test/CodeGen/MSP430/bit.ll166
-rw-r--r--test/CodeGen/MSP430/indirectbr.ll41
-rw-r--r--test/CodeGen/MSP430/indirectbr2.ll29
-rw-r--r--test/CodeGen/MSP430/inline-asm.ll26
-rw-r--r--test/CodeGen/MSP430/lit.local.cfg6
-rw-r--r--test/CodeGen/MSP430/mult-alt-generic-msp430.ll323
-rw-r--r--test/CodeGen/MSP430/postinc.ll114
-rw-r--r--test/CodeGen/MSP430/setcc.ll116
-rw-r--r--test/CodeGen/MSP430/shifts.ll51
-rw-r--r--test/CodeGen/Mips/2008-06-05-Carry.ll22
-rw-r--r--test/CodeGen/Mips/2008-07-03-SRet.ll18
-rw-r--r--test/CodeGen/Mips/2008-07-06-fadd64.ll8
-rw-r--r--test/CodeGen/Mips/2008-07-07-FPExtend.ll8
-rw-r--r--test/CodeGen/Mips/2008-07-07-Float2Int.ll17
-rw-r--r--test/CodeGen/Mips/2008-07-07-IntDoubleConvertions.ll34
-rw-r--r--test/CodeGen/Mips/2008-07-15-InternalConstant.ll23
-rw-r--r--test/CodeGen/Mips/2008-07-15-SmallSection.ll35
-rw-r--r--test/CodeGen/Mips/2008-07-16-SignExtInReg.ll17
-rw-r--r--test/CodeGen/Mips/2008-07-22-Cstpool.ll13
-rw-r--r--test/CodeGen/Mips/2008-07-23-fpcmp.ll38
-rw-r--r--test/CodeGen/Mips/2008-07-29-icmp.ll15
-rw-r--r--test/CodeGen/Mips/2008-07-31-fcopysign.ll18
-rw-r--r--test/CodeGen/Mips/2008-08-01-AsmInline.ll53
-rw-r--r--test/CodeGen/Mips/2008-08-03-ReturnDouble.ll18
-rw-r--r--test/CodeGen/Mips/2008-08-03-fabs64.ll18
-rw-r--r--test/CodeGen/Mips/2008-08-04-Bitconvert.ll15
-rw-r--r--test/CodeGen/Mips/2008-08-06-Alloca.ll15
-rw-r--r--test/CodeGen/Mips/2008-08-07-CC.ll12
-rw-r--r--test/CodeGen/Mips/2008-08-07-FPRound.ll8
-rw-r--r--test/CodeGen/Mips/2008-08-08-bswap.ll15
-rw-r--r--test/CodeGen/Mips/2008-08-08-ctlz.ll10
-rw-r--r--test/CodeGen/Mips/2008-10-13-LegalizerBug.ll29
-rw-r--r--test/CodeGen/Mips/2008-11-10-xint_to_fp.ll54
-rw-r--r--test/CodeGen/Mips/2009-11-16-CstPoolLoad.ll23
-rw-r--r--test/CodeGen/Mips/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/Mips/2010-07-20-Switch.ll67
-rw-r--r--test/CodeGen/Mips/2010-11-09-CountLeading.ll33
-rw-r--r--test/CodeGen/Mips/2010-11-09-Mul.ll15
-rw-r--r--test/CodeGen/Mips/2011-05-26-BranchKillsVreg.ll43
-rw-r--r--test/CodeGen/Mips/addc.ll13
-rw-r--r--test/CodeGen/Mips/alloca.ll89
-rw-r--r--test/CodeGen/Mips/analyzebranch.ll44
-rw-r--r--test/CodeGen/Mips/and1.ll17
-rw-r--r--test/CodeGen/Mips/asm-large-immediate.ll10
-rw-r--r--test/CodeGen/Mips/atomic.ll260
-rw-r--r--test/CodeGen/Mips/blockaddr.ll51
-rw-r--r--test/CodeGen/Mips/br-jmp.ll13
-rw-r--r--test/CodeGen/Mips/brdelayslot.ll21
-rw-r--r--test/CodeGen/Mips/bswap.ll25
-rw-r--r--test/CodeGen/Mips/buildpairextractelementf64.ll23
-rwxr-xr-xtest/CodeGen/Mips/cmov.ll61
-rw-r--r--test/CodeGen/Mips/constantfp0.ll11
-rw-r--r--test/CodeGen/Mips/cprestore.ll20
-rw-r--r--test/CodeGen/Mips/divrem.ll51
-rw-r--r--test/CodeGen/Mips/double2int.ll8
-rw-r--r--test/CodeGen/Mips/eh.ll67
-rw-r--r--test/CodeGen/Mips/extins.ll21
-rw-r--r--test/CodeGen/Mips/fabs.ll52
-rw-r--r--test/CodeGen/Mips/fastcc.ll253
-rw-r--r--test/CodeGen/Mips/fcopysign-f32-f64.ll50
-rw-r--r--test/CodeGen/Mips/fcopysign.ll59
-rw-r--r--test/CodeGen/Mips/fmadd1.ll88
-rw-r--r--test/CodeGen/Mips/fneg.ll17
-rw-r--r--test/CodeGen/Mips/fp-indexed-ls.ll98
-rw-r--r--test/CodeGen/Mips/fp-spill-reload.ll39
-rw-r--r--test/CodeGen/Mips/fpbr.ll119
-rw-r--r--test/CodeGen/Mips/frame-address.ll12
-rw-r--r--test/CodeGen/Mips/frem.ll13
-rw-r--r--test/CodeGen/Mips/global-address.ll46
-rw-r--r--test/CodeGen/Mips/global-pointer-reg.ll24
-rw-r--r--test/CodeGen/Mips/gprestore.ll34
-rw-r--r--test/CodeGen/Mips/helloworld.ll34
-rw-r--r--test/CodeGen/Mips/i64arg.ll34
-rw-r--r--test/CodeGen/Mips/imm.ll38
-rw-r--r--test/CodeGen/Mips/indirectcall.ll8
-rw-r--r--test/CodeGen/Mips/init-array.ll14
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-bad-I-1.ll15
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-bad-J.ll16
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-bad-K.ll16
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-bad-L.ll16
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-bad-N.ll17
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-bad-O.ll16
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-bad-P.ll16
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-reg.ll44
-rw-r--r--test/CodeGen/Mips/inlineasm-cnstrnt-reg64.ll20
-rw-r--r--test/CodeGen/Mips/inlineasm-operand-code.ll153
-rw-r--r--test/CodeGen/Mips/inlineasm64.ll17
-rw-r--r--test/CodeGen/Mips/inlineasm_constraint.ll55
-rw-r--r--test/CodeGen/Mips/inlineasmmemop.ll23
-rw-r--r--test/CodeGen/Mips/internalfunc.ll52
-rw-r--r--test/CodeGen/Mips/largeimm1.ll13
-rw-r--r--test/CodeGen/Mips/largeimmprinting.ll22
-rw-r--r--test/CodeGen/Mips/lb1.ll18
-rw-r--r--test/CodeGen/Mips/lbu1.ll19
-rw-r--r--test/CodeGen/Mips/lh1.ll18
-rw-r--r--test/CodeGen/Mips/lhu1.ll19
-rw-r--r--test/CodeGen/Mips/lit.local.cfg6
-rw-r--r--test/CodeGen/Mips/load-store-left-right.ll29
-rw-r--r--test/CodeGen/Mips/longbranch.ll31
-rw-r--r--test/CodeGen/Mips/machineverifier.ll21
-rw-r--r--test/CodeGen/Mips/madd-msub.ll65
-rw-r--r--test/CodeGen/Mips/memcpy.ll19
-rw-r--r--test/CodeGen/Mips/mips64-fp-indexed-ls.ll110
-rw-r--r--test/CodeGen/Mips/mips64countleading.ll19
-rw-r--r--test/CodeGen/Mips/mips64directive.ll11
-rw-r--r--test/CodeGen/Mips/mips64ext.ll26
-rw-r--r--test/CodeGen/Mips/mips64extins.ll55
-rw-r--r--test/CodeGen/Mips/mips64fpimm0.ll7
-rw-r--r--test/CodeGen/Mips/mips64fpldst.ll58
-rw-r--r--test/CodeGen/Mips/mips64imm.ll52
-rw-r--r--test/CodeGen/Mips/mips64instrs.ll143
-rw-r--r--test/CodeGen/Mips/mips64intldst.ll157
-rw-r--r--test/CodeGen/Mips/mips64lea.ll12
-rw-r--r--test/CodeGen/Mips/mips64load-store-left-right.ll73
-rw-r--r--test/CodeGen/Mips/mips64muldiv.ll49
-rw-r--r--test/CodeGen/Mips/mips64shift.ll104
-rw-r--r--test/CodeGen/Mips/mipslopat.ll19
-rw-r--r--test/CodeGen/Mips/neg1.ll15
-rw-r--r--test/CodeGen/Mips/not1.ll16
-rw-r--r--test/CodeGen/Mips/null.ll13
-rw-r--r--test/CodeGen/Mips/o32_cc.ll325
-rw-r--r--test/CodeGen/Mips/o32_cc_byval.ll127
-rw-r--r--test/CodeGen/Mips/o32_cc_vararg.ll270
-rw-r--r--test/CodeGen/Mips/or1.ll17
-rw-r--r--test/CodeGen/Mips/private.ll20
-rw-r--r--test/CodeGen/Mips/ra-allocatable.ll288
-rw-r--r--test/CodeGen/Mips/rdhwr-directives.ll15
-rw-r--r--test/CodeGen/Mips/return-vector-float4.ll12
-rw-r--r--test/CodeGen/Mips/return_address.ll23
-rw-r--r--test/CodeGen/Mips/rotate.ll40
-rw-r--r--test/CodeGen/Mips/sb1.ll20
-rw-r--r--test/CodeGen/Mips/select.ll164
-rw-r--r--test/CodeGen/Mips/selectcc.ll27
-rw-r--r--test/CodeGen/Mips/sh1.ll20
-rw-r--r--test/CodeGen/Mips/shift-parts.ll29
-rw-r--r--test/CodeGen/Mips/sitofp-selectcc-opt.ll22
-rw-r--r--test/CodeGen/Mips/sll1.ll19
-rw-r--r--test/CodeGen/Mips/sll2.ll19
-rw-r--r--test/CodeGen/Mips/small-section-reserve-gp.ll12
-rw-r--r--test/CodeGen/Mips/sra1.ll15
-rw-r--r--test/CodeGen/Mips/sra2.ll17
-rw-r--r--test/CodeGen/Mips/srl1.ll18
-rw-r--r--test/CodeGen/Mips/srl2.ll20
-rw-r--r--test/CodeGen/Mips/stacksize.ll9
-rw-r--r--test/CodeGen/Mips/sub1.ll15
-rw-r--r--test/CodeGen/Mips/sub2.ll17
-rw-r--r--test/CodeGen/Mips/swzero.ll20
-rw-r--r--test/CodeGen/Mips/tls-alias.ll10
-rw-r--r--test/CodeGen/Mips/tls-models.ll113
-rw-r--r--test/CodeGen/Mips/tls.ll75
-rw-r--r--test/CodeGen/Mips/uitofp.ll12
-rw-r--r--test/CodeGen/Mips/ul1.ll15
-rw-r--r--test/CodeGen/Mips/unalignedload.ll31
-rw-r--r--test/CodeGen/Mips/weak.ll12
-rw-r--r--test/CodeGen/Mips/xor1.ll17
-rw-r--r--test/CodeGen/Mips/zeroreg.ll25
-rw-r--r--test/CodeGen/NVPTX/annotations.ll55
-rw-r--r--test/CodeGen/NVPTX/arithmetic-fp-sm10.ll72
-rw-r--r--test/CodeGen/NVPTX/arithmetic-fp-sm20.ll72
-rw-r--r--test/CodeGen/NVPTX/arithmetic-int.ll295
-rw-r--r--test/CodeGen/NVPTX/calling-conv.ll32
-rw-r--r--test/CodeGen/NVPTX/compare-int.ll389
-rw-r--r--test/CodeGen/NVPTX/convert-fp.ll146
-rw-r--r--test/CodeGen/NVPTX/convert-int-sm10.ll55
-rw-r--r--test/CodeGen/NVPTX/convert-int-sm20.ll64
-rw-r--r--test/CodeGen/NVPTX/fma-disable.ll24
-rw-r--r--test/CodeGen/NVPTX/fma.ll17
-rw-r--r--test/CodeGen/NVPTX/intrinsic-old.ll284
-rw-r--r--test/CodeGen/NVPTX/intrinsics.ll21
-rw-r--r--test/CodeGen/NVPTX/ld-addrspace.ll173
-rw-r--r--test/CodeGen/NVPTX/ld-generic.ll63
-rw-r--r--test/CodeGen/NVPTX/lit.local.cfg5
-rw-r--r--test/CodeGen/NVPTX/simple-call.ll26
-rw-r--r--test/CodeGen/NVPTX/st-addrspace.ll179
-rw-r--r--test/CodeGen/NVPTX/st-generic.ll69
-rw-r--r--test/CodeGen/PowerPC/2004-11-29-ShrCrash.ll6
-rw-r--r--test/CodeGen/PowerPC/2004-11-30-shift-crash.ll7
-rw-r--r--test/CodeGen/PowerPC/2004-11-30-shr-var-crash.ll9
-rw-r--r--test/CodeGen/PowerPC/2004-12-12-ZeroSizeCommon.ll4
-rw-r--r--test/CodeGen/PowerPC/2005-01-14-SetSelectCrash.ll8
-rw-r--r--test/CodeGen/PowerPC/2005-01-14-UndefLong.ll5
-rw-r--r--test/CodeGen/PowerPC/2005-08-12-rlwimi-crash.ll13
-rw-r--r--test/CodeGen/PowerPC/2005-09-02-LegalizeDuplicatesCalls.ll11
-rw-r--r--test/CodeGen/PowerPC/2005-10-08-ArithmeticRotate.ll11
-rw-r--r--test/CodeGen/PowerPC/2005-11-30-vastart-crash.ll18
-rw-r--r--test/CodeGen/PowerPC/2006-01-11-darwin-fp-argument.ll10
-rw-r--r--test/CodeGen/PowerPC/2006-01-20-ShiftPartsCrash.ll19
-rw-r--r--test/CodeGen/PowerPC/2006-04-01-FloatDoubleExtend.ll9
-rw-r--r--test/CodeGen/PowerPC/2006-04-05-splat-ish.ll10
-rw-r--r--test/CodeGen/PowerPC/2006-04-19-vmaddfp-crash.ll58
-rw-r--r--test/CodeGen/PowerPC/2006-05-12-rlwimi-crash.ll55
-rw-r--r--test/CodeGen/PowerPC/2006-07-07-ComputeMaskedBits.ll17
-rw-r--r--test/CodeGen/PowerPC/2006-07-19-stwbrx-crash.ll11
-rw-r--r--test/CodeGen/PowerPC/2006-08-11-RetVector.ll8
-rw-r--r--test/CodeGen/PowerPC/2006-08-15-SelectionCrash.ll30
-rw-r--r--test/CodeGen/PowerPC/2006-09-28-shift_64.ll25
-rw-r--r--test/CodeGen/PowerPC/2006-10-13-Miscompile.ll16
-rw-r--r--test/CodeGen/PowerPC/2006-10-17-brcc-miscompile.ll20
-rw-r--r--test/CodeGen/PowerPC/2006-10-17-ppc64-alloca.ll7
-rw-r--r--test/CodeGen/PowerPC/2006-11-10-DAGCombineMiscompile.ll13
-rw-r--r--test/CodeGen/PowerPC/2006-11-29-AltivecFPSplat.ll10
-rw-r--r--test/CodeGen/PowerPC/2006-12-07-LargeAlloca.ll24
-rw-r--r--test/CodeGen/PowerPC/2006-12-07-SelectCrash.ll22
-rw-r--r--test/CodeGen/PowerPC/2007-01-04-ArgExtension.ll10
-rw-r--r--test/CodeGen/PowerPC/2007-01-15-AsmDialect.ll26
-rw-r--r--test/CodeGen/PowerPC/2007-01-29-lbrx-asm.ll7
-rw-r--r--test/CodeGen/PowerPC/2007-01-31-InlineAsmAddrMode.ll24
-rw-r--r--test/CodeGen/PowerPC/2007-02-16-AlignPacked.ll4
-rw-r--r--test/CodeGen/PowerPC/2007-02-16-InlineAsmNConstraint.ll11
-rw-r--r--test/CodeGen/PowerPC/2007-02-23-lr-saved-twice.ll14
-rw-r--r--test/CodeGen/PowerPC/2007-03-24-cntlzd.ll12
-rw-r--r--test/CodeGen/PowerPC/2007-03-30-SpillerCrash.ll1801
-rw-r--r--test/CodeGen/PowerPC/2007-04-24-InlineAsm-I-Modifier.ll14
-rw-r--r--test/CodeGen/PowerPC/2007-04-30-InlineAsmEarlyClobber.ll31
-rw-r--r--test/CodeGen/PowerPC/2007-05-03-InlineAsm-S-Constraint.ll12
-rw-r--r--test/CodeGen/PowerPC/2007-05-14-InlineAsmSelectCrash.ll25
-rw-r--r--test/CodeGen/PowerPC/2007-05-22-tailmerge-3.ll67
-rw-r--r--test/CodeGen/PowerPC/2007-05-30-dagcombine-miscomp.ll14
-rw-r--r--test/CodeGen/PowerPC/2007-06-28-BCCISelBug.ll85
-rw-r--r--test/CodeGen/PowerPC/2007-08-04-CoalescerAssert.ll28
-rw-r--r--test/CodeGen/PowerPC/2007-09-04-AltivecDST.ll15
-rw-r--r--test/CodeGen/PowerPC/2007-09-07-LoadStoreIdxForms.ll16
-rw-r--r--test/CodeGen/PowerPC/2007-09-08-unaligned.ll53
-rw-r--r--test/CodeGen/PowerPC/2007-09-11-RegCoalescerAssert.ll9
-rw-r--r--test/CodeGen/PowerPC/2007-09-12-LiveIntervalsAssert.ll15
-rw-r--r--test/CodeGen/PowerPC/2007-10-16-InlineAsmFrameOffset.ll14
-rw-r--r--test/CodeGen/PowerPC/2007-10-18-PtrArithmetic.ll22
-rw-r--r--test/CodeGen/PowerPC/2007-10-21-LocalRegAllocAssert.ll27
-rw-r--r--test/CodeGen/PowerPC/2007-10-21-LocalRegAllocAssert2.ll25
-rw-r--r--test/CodeGen/PowerPC/2007-11-04-CoalescerCrash.ll148
-rw-r--r--test/CodeGen/PowerPC/2007-11-16-landingpad-split.ll52
-rw-r--r--test/CodeGen/PowerPC/2007-11-19-VectorSplitting.ll16
-rw-r--r--test/CodeGen/PowerPC/2008-02-05-LiveIntervalsAssert.ll67
-rw-r--r--test/CodeGen/PowerPC/2008-02-09-LocalRegAllocAssert.ll10
-rw-r--r--test/CodeGen/PowerPC/2008-03-05-RegScavengerAssert.ll18
-rw-r--r--test/CodeGen/PowerPC/2008-03-17-RegScavengerCrash.ll31
-rw-r--r--test/CodeGen/PowerPC/2008-03-18-RegScavengerAssert.ll6
-rw-r--r--test/CodeGen/PowerPC/2008-03-24-AddressRegImm.ll25
-rw-r--r--test/CodeGen/PowerPC/2008-03-24-CoalescerBug.ll30
-rw-r--r--test/CodeGen/PowerPC/2008-03-26-CoalescerBug.ll28
-rw-r--r--test/CodeGen/PowerPC/2008-04-10-LiveIntervalCrash.ll100
-rw-r--r--test/CodeGen/PowerPC/2008-04-16-CoalescerBug.ll14
-rw-r--r--test/CodeGen/PowerPC/2008-04-23-CoalescerCrash.ll89
-rw-r--r--test/CodeGen/PowerPC/2008-05-01-ppc_fp128.ll15
-rw-r--r--test/CodeGen/PowerPC/2008-06-19-LegalizerCrash.ll6
-rw-r--r--test/CodeGen/PowerPC/2008-06-21-F128LoadStore.ll10
-rw-r--r--test/CodeGen/PowerPC/2008-06-23-LiveVariablesCrash.ll25
-rw-r--r--test/CodeGen/PowerPC/2008-07-10-SplatMiscompile.ll10
-rw-r--r--test/CodeGen/PowerPC/2008-07-15-Bswap.ll386
-rw-r--r--test/CodeGen/PowerPC/2008-07-15-Fabs.ll19
-rw-r--r--test/CodeGen/PowerPC/2008-07-15-SignExtendInreg.ll17
-rw-r--r--test/CodeGen/PowerPC/2008-07-17-Fneg.ll18
-rw-r--r--test/CodeGen/PowerPC/2008-07-24-PPC64-CCBug.ll11
-rw-r--r--test/CodeGen/PowerPC/2008-09-12-CoalescerBug.ll254
-rw-r--r--test/CodeGen/PowerPC/2008-10-17-AsmMatchingOperands.ll15
-rw-r--r--test/CodeGen/PowerPC/2008-10-28-UnprocessedNode.ll11
-rw-r--r--test/CodeGen/PowerPC/2008-10-28-f128-i32.ll33
-rw-r--r--test/CodeGen/PowerPC/2008-10-31-PPCF128Libcalls.ll44
-rw-r--r--test/CodeGen/PowerPC/2008-12-02-LegalizeTypeAssert.ll18
-rw-r--r--test/CodeGen/PowerPC/2008-12-12-EH.ll9
-rw-r--r--test/CodeGen/PowerPC/2009-01-16-DeclareISelBug.ll12
-rw-r--r--test/CodeGen/PowerPC/2009-03-17-LSRBug.ll51
-rw-r--r--test/CodeGen/PowerPC/2009-05-28-LegalizeBRCC.ll15
-rw-r--r--test/CodeGen/PowerPC/2009-07-16-InlineAsm-M-Operand.ll16
-rw-r--r--test/CodeGen/PowerPC/2009-08-17-inline-asm-addr-mode-breakage.ll25
-rw-r--r--test/CodeGen/PowerPC/2009-08-23-linkerprivate.ll8
-rw-r--r--test/CodeGen/PowerPC/2009-09-18-carrybit.ll62
-rw-r--r--test/CodeGen/PowerPC/2009-11-15-ProcImpDefsBug.ll105
-rw-r--r--test/CodeGen/PowerPC/2009-11-25-ImpDefBug.ll56
-rw-r--r--test/CodeGen/PowerPC/2010-02-04-EmptyGlobal.ll20
-rw-r--r--test/CodeGen/PowerPC/2010-02-12-saveCR.ll36
-rw-r--r--test/CodeGen/PowerPC/2010-03-09-indirect-call.ll20
-rw-r--r--test/CodeGen/PowerPC/2010-04-01-MachineCSEBug.ll70
-rw-r--r--test/CodeGen/PowerPC/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/PowerPC/2010-05-03-retaddr1.ll25
-rw-r--r--test/CodeGen/PowerPC/2010-10-11-Fast-Varargs.ll16
-rw-r--r--test/CodeGen/PowerPC/2010-12-18-PPCStackRefs.ll22
-rw-r--r--test/CodeGen/PowerPC/2011-12-05-NoSpillDupCR.ll191
-rw-r--r--test/CodeGen/PowerPC/2011-12-06-SpillAndRestoreCR.ll225
-rw-r--r--test/CodeGen/PowerPC/2011-12-08-DemandedBitsMiscompile.ll16
-rw-r--r--test/CodeGen/PowerPC/2012-09-16-TOC-entry-check.ll27
-rw-r--r--test/CodeGen/PowerPC/Atomics-32.ll699
-rw-r--r--test/CodeGen/PowerPC/Atomics-64.ll714
-rw-r--r--test/CodeGen/PowerPC/Frames-alloca.ll30
-rw-r--r--test/CodeGen/PowerPC/Frames-large.ll55
-rw-r--r--test/CodeGen/PowerPC/Frames-leaf.ll37
-rw-r--r--test/CodeGen/PowerPC/Frames-small.ll29
-rw-r--r--test/CodeGen/PowerPC/LargeAbsoluteAddr.ll17
-rw-r--r--test/CodeGen/PowerPC/a2-fp-basic.ll33
-rw-r--r--test/CodeGen/PowerPC/addc.ll33
-rw-r--r--test/CodeGen/PowerPC/addi-reassoc.ll19
-rw-r--r--test/CodeGen/PowerPC/align.ll46
-rw-r--r--test/CodeGen/PowerPC/and-branch.ll17
-rw-r--r--test/CodeGen/PowerPC/and-elim.ll18
-rw-r--r--test/CodeGen/PowerPC/and-imm.ll14
-rw-r--r--test/CodeGen/PowerPC/and_add.ll15
-rw-r--r--test/CodeGen/PowerPC/and_sext.ll28
-rw-r--r--test/CodeGen/PowerPC/and_sra.ll27
-rw-r--r--test/CodeGen/PowerPC/atomic-1.ll26
-rw-r--r--test/CodeGen/PowerPC/atomic-2.ll26
-rw-r--r--test/CodeGen/PowerPC/available-externally.ll71
-rw-r--r--test/CodeGen/PowerPC/big-endian-actual-args.ll9
-rw-r--r--test/CodeGen/PowerPC/big-endian-call-result.ll13
-rw-r--r--test/CodeGen/PowerPC/big-endian-formal-args.ll13
-rw-r--r--test/CodeGen/PowerPC/bl8_elf_nop.ll16
-rw-r--r--test/CodeGen/PowerPC/branch-opt.ll71
-rw-r--r--test/CodeGen/PowerPC/bswap-load-store.ll51
-rw-r--r--test/CodeGen/PowerPC/buildvec_canonicalize.ll24
-rw-r--r--test/CodeGen/PowerPC/calls.ll27
-rw-r--r--test/CodeGen/PowerPC/can-lower-ret.ll19
-rw-r--r--test/CodeGen/PowerPC/cmp-cmp.ll13
-rw-r--r--test/CodeGen/PowerPC/coalesce-ext.ll17
-rw-r--r--test/CodeGen/PowerPC/compare-duplicate.ll11
-rw-r--r--test/CodeGen/PowerPC/compare-simm.ll14
-rw-r--r--test/CodeGen/PowerPC/constants.ll52
-rw-r--r--test/CodeGen/PowerPC/cr1eq-no-extra-moves.ll26
-rw-r--r--test/CodeGen/PowerPC/cr1eq.ll18
-rw-r--r--test/CodeGen/PowerPC/cr_spilling.ll27
-rw-r--r--test/CodeGen/PowerPC/crsave.ll49
-rw-r--r--test/CodeGen/PowerPC/ctrloop-reg.ll87
-rw-r--r--test/CodeGen/PowerPC/ctrloop-s000.ll156
-rw-r--r--test/CodeGen/PowerPC/ctrloop-sums.ll134
-rw-r--r--test/CodeGen/PowerPC/ctrloops.ll79
-rw-r--r--test/CodeGen/PowerPC/cttz.ll11
-rw-r--r--test/CodeGen/PowerPC/darwin-labels.ll6
-rw-r--r--test/CodeGen/PowerPC/dbg.ll40
-rw-r--r--test/CodeGen/PowerPC/delete-node.ll22
-rw-r--r--test/CodeGen/PowerPC/div-2.ll30
-rw-r--r--test/CodeGen/PowerPC/empty-functions.ll12
-rw-r--r--test/CodeGen/PowerPC/eqv-andc-orc-nor.ll93
-rw-r--r--test/CodeGen/PowerPC/extsh.ll8
-rw-r--r--test/CodeGen/PowerPC/fabs.ll7
-rw-r--r--test/CodeGen/PowerPC/fma.ll54
-rw-r--r--test/CodeGen/PowerPC/fnabs.ll10
-rw-r--r--test/CodeGen/PowerPC/fneg.ll12
-rw-r--r--test/CodeGen/PowerPC/fold-li.ll15
-rw-r--r--test/CodeGen/PowerPC/fp-branch.ll21
-rw-r--r--test/CodeGen/PowerPC/fp-int-fp.ll27
-rw-r--r--test/CodeGen/PowerPC/fp_to_uint.ll8
-rw-r--r--test/CodeGen/PowerPC/fpcopy.ll7
-rw-r--r--test/CodeGen/PowerPC/frounds.ll19
-rw-r--r--test/CodeGen/PowerPC/fsl-e500mc.ll22
-rw-r--r--test/CodeGen/PowerPC/fsl-e5500.ll22
-rw-r--r--test/CodeGen/PowerPC/fsqrt.ll19
-rw-r--r--test/CodeGen/PowerPC/hello.ll12
-rw-r--r--test/CodeGen/PowerPC/hidden-vis-2.ll12
-rw-r--r--test/CodeGen/PowerPC/hidden-vis.ll9
-rw-r--r--test/CodeGen/PowerPC/i128-and-beyond.ll8
-rw-r--r--test/CodeGen/PowerPC/i64_fp.ll26
-rw-r--r--test/CodeGen/PowerPC/iabs.ll15
-rw-r--r--test/CodeGen/PowerPC/illegal-element-type.ll23
-rw-r--r--test/CodeGen/PowerPC/indirectbr.ll71
-rw-r--r--test/CodeGen/PowerPC/inlineasm-copy.ll21
-rw-r--r--test/CodeGen/PowerPC/int-fp-conv-0.ll17
-rw-r--r--test/CodeGen/PowerPC/int-fp-conv-1.ll11
-rw-r--r--test/CodeGen/PowerPC/inverted-bool-compares.ll13
-rw-r--r--test/CodeGen/PowerPC/isel.ll23
-rw-r--r--test/CodeGen/PowerPC/ispositive.ll10
-rw-r--r--test/CodeGen/PowerPC/itofp128.ll14
-rw-r--r--test/CodeGen/PowerPC/lbzux.ll49
-rw-r--r--test/CodeGen/PowerPC/lha.ll8
-rw-r--r--test/CodeGen/PowerPC/lit.local.cfg6
-rw-r--r--test/CodeGen/PowerPC/load-constant-addr.ll9
-rw-r--r--test/CodeGen/PowerPC/long-compare.ll9
-rw-r--r--test/CodeGen/PowerPC/longdbl-truncate.ll9
-rw-r--r--test/CodeGen/PowerPC/lsr-postinc-pos.ll32
-rw-r--r--test/CodeGen/PowerPC/mask64.ll27
-rw-r--r--test/CodeGen/PowerPC/mem-rr-addr-mode.ll18
-rw-r--r--test/CodeGen/PowerPC/mem_update.ll68
-rw-r--r--test/CodeGen/PowerPC/mul-neg-power-2.ll8
-rw-r--r--test/CodeGen/PowerPC/mul-with-overflow.ll15
-rw-r--r--test/CodeGen/PowerPC/mulhs.ll17
-rw-r--r--test/CodeGen/PowerPC/mult-alt-generic-powerpc.ll321
-rw-r--r--test/CodeGen/PowerPC/mult-alt-generic-powerpc64.ll321
-rw-r--r--test/CodeGen/PowerPC/neg.ll7
-rw-r--r--test/CodeGen/PowerPC/no-dead-strip.ll8
-rw-r--r--test/CodeGen/PowerPC/or-addressing-mode.ll22
-rw-r--r--test/CodeGen/PowerPC/ppc-prologue.ll26
-rw-r--r--test/CodeGen/PowerPC/ppc-vaarg-agg.ll46
-rw-r--r--test/CodeGen/PowerPC/ppc440-fp-basic.ll33
-rw-r--r--test/CodeGen/PowerPC/ppc440-msync.ll27
-rw-r--r--test/CodeGen/PowerPC/ppc64-32bit-addic.ll29
-rw-r--r--test/CodeGen/PowerPC/ppc64-calls.ll49
-rw-r--r--test/CodeGen/PowerPC/ppc64-crash.ll14
-rw-r--r--test/CodeGen/PowerPC/ppc64-cyclecounter.ll15
-rw-r--r--test/CodeGen/PowerPC/ppc64-ind-call.ll16
-rw-r--r--test/CodeGen/PowerPC/ppc64-linux-func-size.ll22
-rw-r--r--test/CodeGen/PowerPC/ppc64-prefetch.ll15
-rw-r--r--test/CodeGen/PowerPC/ppc64-toc.ll68
-rw-r--r--test/CodeGen/PowerPC/ppc64-vaarg-int.ll20
-rw-r--r--test/CodeGen/PowerPC/ppc64-zext.ll11
-rw-r--r--test/CodeGen/PowerPC/ppcf128-1-opt.ll29
-rw-r--r--test/CodeGen/PowerPC/ppcf128-1.ll92
-rw-r--r--test/CodeGen/PowerPC/ppcf128-2.ll14
-rw-r--r--test/CodeGen/PowerPC/ppcf128-3.ll32
-rw-r--r--test/CodeGen/PowerPC/ppcf128-4.ll10
-rw-r--r--test/CodeGen/PowerPC/pr13641.ll11
-rw-r--r--test/CodeGen/PowerPC/pr3711_widen_bit.ll18
-rw-r--r--test/CodeGen/PowerPC/private.ll24
-rw-r--r--test/CodeGen/PowerPC/reg-coalesce-simple.ll12
-rw-r--r--test/CodeGen/PowerPC/remat-imm.ll16
-rw-r--r--test/CodeGen/PowerPC/retaddr.ll15
-rw-r--r--test/CodeGen/PowerPC/return-val-i128.ll36
-rw-r--r--test/CodeGen/PowerPC/rlwimi-commute.ll34
-rw-r--r--test/CodeGen/PowerPC/rlwimi-keep-rsh.ll28
-rw-r--r--test/CodeGen/PowerPC/rlwimi.ll70
-rw-r--r--test/CodeGen/PowerPC/rlwimi2.ll29
-rw-r--r--test/CodeGen/PowerPC/rlwimi3.ll25
-rw-r--r--test/CodeGen/PowerPC/rlwinm.ll61
-rw-r--r--test/CodeGen/PowerPC/rlwinm2.ll28
-rw-r--r--test/CodeGen/PowerPC/rotl-2.ll38
-rw-r--r--test/CodeGen/PowerPC/rotl-64.ll20
-rw-r--r--test/CodeGen/PowerPC/rotl.ll37
-rw-r--r--test/CodeGen/PowerPC/sections.ll8
-rw-r--r--test/CodeGen/PowerPC/select-cc.ll9
-rw-r--r--test/CodeGen/PowerPC/select_lt0.ll50
-rw-r--r--test/CodeGen/PowerPC/setcc_no_zext.ll9
-rw-r--r--test/CodeGen/PowerPC/seteq-0.ll9
-rw-r--r--test/CodeGen/PowerPC/shift128.ll14
-rw-r--r--test/CodeGen/PowerPC/shl_elim.ll11
-rw-r--r--test/CodeGen/PowerPC/shl_sext.ll18
-rw-r--r--test/CodeGen/PowerPC/sign_ext_inreg1.ll12
-rw-r--r--test/CodeGen/PowerPC/small-arguments.ll52
-rw-r--r--test/CodeGen/PowerPC/stack-protector.ll25
-rw-r--r--test/CodeGen/PowerPC/stfiwx-2.ll11
-rw-r--r--test/CodeGen/PowerPC/stfiwx.ll24
-rw-r--r--test/CodeGen/PowerPC/store-load-fwd.ll8
-rw-r--r--test/CodeGen/PowerPC/stubs.ll22
-rw-r--r--test/CodeGen/PowerPC/stwu-gta.ll22
-rw-r--r--test/CodeGen/PowerPC/stwu8.ll28
-rw-r--r--test/CodeGen/PowerPC/stwux.ll47
-rw-r--r--test/CodeGen/PowerPC/subc.ll25
-rw-r--r--test/CodeGen/PowerPC/tailcall1-64.ll11
-rw-r--r--test/CodeGen/PowerPC/tailcall1.ll11
-rw-r--r--test/CodeGen/PowerPC/tailcallpic1.ll14
-rw-r--r--test/CodeGen/PowerPC/tls.ll16
-rw-r--r--test/CodeGen/PowerPC/trampoline.ll168
-rw-r--r--test/CodeGen/PowerPC/unsafe-math.ll10
-rw-r--r--test/CodeGen/PowerPC/varargs.ll22
-rw-r--r--test/CodeGen/PowerPC/vcmp-fold.ll22
-rw-r--r--test/CodeGen/PowerPC/vec_auto_constant.ll36
-rw-r--r--test/CodeGen/PowerPC/vec_br_cmp.ll22
-rw-r--r--test/CodeGen/PowerPC/vec_buildvector_loadstore.ll37
-rw-r--r--test/CodeGen/PowerPC/vec_call.ll11
-rw-r--r--test/CodeGen/PowerPC/vec_constants.ll44
-rw-r--r--test/CodeGen/PowerPC/vec_fneg.ll8
-rw-r--r--test/CodeGen/PowerPC/vec_insert.ll8
-rw-r--r--test/CodeGen/PowerPC/vec_misaligned.ll37
-rw-r--r--test/CodeGen/PowerPC/vec_mul.ll23
-rw-r--r--test/CodeGen/PowerPC/vec_perf_shuffle.ll36
-rw-r--r--test/CodeGen/PowerPC/vec_shift.ll10
-rw-r--r--test/CodeGen/PowerPC/vec_shuffle.ll504
-rw-r--r--test/CodeGen/PowerPC/vec_splat.ll71
-rw-r--r--test/CodeGen/PowerPC/vec_splat_constant.ll24
-rw-r--r--test/CodeGen/PowerPC/vec_vrsave.ll14
-rw-r--r--test/CodeGen/PowerPC/vec_zero.ll9
-rw-r--r--test/CodeGen/PowerPC/vector-identity-shuffle.ll17
-rw-r--r--test/CodeGen/PowerPC/vector.ll158
-rw-r--r--test/CodeGen/SPARC/2006-01-22-BitConvertLegalize.ll12
-rw-r--r--test/CodeGen/SPARC/2007-05-09-JumpTables.ll30
-rw-r--r--test/CodeGen/SPARC/2007-07-05-LiveIntervalAssert.ll11
-rw-r--r--test/CodeGen/SPARC/2008-10-10-InlineAsmMemoryOperand.ll16
-rw-r--r--test/CodeGen/SPARC/2008-10-10-InlineAsmRegOperand.ll14
-rw-r--r--test/CodeGen/SPARC/2009-08-28-PIC.ll9
-rw-r--r--test/CodeGen/SPARC/2009-08-28-WeakLinkage.ll6
-rw-r--r--test/CodeGen/SPARC/2010-04-07-DbgValueOtherTargets.ll28
-rwxr-xr-xtest/CodeGen/SPARC/2011-01-11-CC.ll105
-rw-r--r--test/CodeGen/SPARC/2011-01-11-Call.ll13
-rw-r--r--test/CodeGen/SPARC/2011-01-11-FrameAddr.ll66
-rw-r--r--test/CodeGen/SPARC/2011-01-19-DelaySlot.ll90
-rw-r--r--test/CodeGen/SPARC/2011-01-21-ByValArgs.ll18
-rw-r--r--test/CodeGen/SPARC/2011-01-22-SRet.ll36
-rw-r--r--test/CodeGen/SPARC/2011-12-03-TailDuplication.ll25
-rw-r--r--test/CodeGen/SPARC/2012-05-01-LowerArguments.ll13
-rw-r--r--test/CodeGen/SPARC/basictest.ll26
-rw-r--r--test/CodeGen/SPARC/ctpop.ll10
-rw-r--r--test/CodeGen/SPARC/lit.local.cfg6
-rw-r--r--test/CodeGen/SPARC/mult-alt-generic-sparc.ll323
-rw-r--r--test/CodeGen/SPARC/private.ll21
-rw-r--r--test/CodeGen/Thumb/2007-01-31-RegInfoAssert.ll16
-rw-r--r--test/CodeGen/Thumb/2007-02-02-JoinIntervalsCrash.ll27
-rw-r--r--test/CodeGen/Thumb/2007-05-05-InvalidPushPop.ll41
-rw-r--r--test/CodeGen/Thumb/2009-06-18-ThumbCommuteMul.ll8
-rw-r--r--test/CodeGen/Thumb/2009-07-20-TwoAddrBug.ll11
-rw-r--r--test/CodeGen/Thumb/2009-07-27-PEIAssert.ll26
-rw-r--r--test/CodeGen/Thumb/2009-08-12-ConstIslandAssert.ll737
-rw-r--r--test/CodeGen/Thumb/2009-08-12-RegInfoAssert.ll40
-rw-r--r--test/CodeGen/Thumb/2009-08-20-ISelBug.ll66
-rw-r--r--test/CodeGen/Thumb/2009-12-17-pre-regalloc-taildup.ll66
-rw-r--r--test/CodeGen/Thumb/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/Thumb/2010-06-18-SibCallCrash.ll8
-rw-r--r--test/CodeGen/Thumb/2010-07-01-FuncAlign.ll6
-rw-r--r--test/CodeGen/Thumb/2010-07-15-debugOrdering.ll147
-rw-r--r--test/CodeGen/Thumb/2011-05-11-DAGLegalizer.ll60
-rw-r--r--test/CodeGen/Thumb/2011-06-16-NoGPRs.ll24
-rw-r--r--test/CodeGen/Thumb/2011-EpilogueBug.ll17
-rw-r--r--test/CodeGen/Thumb/2012-04-26-M0ISelBug.ll12
-rw-r--r--test/CodeGen/Thumb/asmprinter-bug.ll288
-rw-r--r--test/CodeGen/Thumb/barrier.ll13
-rw-r--r--test/CodeGen/Thumb/dyn-stackalloc.ll77
-rw-r--r--test/CodeGen/Thumb/fpconv.ll61
-rw-r--r--test/CodeGen/Thumb/fpow.ll9
-rw-r--r--test/CodeGen/Thumb/frame_thumb.ll9
-rw-r--r--test/CodeGen/Thumb/iabs.ll22
-rw-r--r--test/CodeGen/Thumb/inlineasm-imm-thumb.ll43
-rw-r--r--test/CodeGen/Thumb/inlineasm-thumb.ll7
-rw-r--r--test/CodeGen/Thumb/ispositive.ll11
-rw-r--r--test/CodeGen/Thumb/large-stack.ll35
-rw-r--r--test/CodeGen/Thumb/ldr_ext.ll57
-rw-r--r--test/CodeGen/Thumb/ldr_frame.ll41
-rw-r--r--test/CodeGen/Thumb/lit.local.cfg6
-rw-r--r--test/CodeGen/Thumb/long-setcc.ll17
-rw-r--r--test/CodeGen/Thumb/long.ll76
-rw-r--r--test/CodeGen/Thumb/long_shift.ll26
-rw-r--r--test/CodeGen/Thumb/mul.ll22
-rw-r--r--test/CodeGen/Thumb/pop.ll13
-rw-r--r--test/CodeGen/Thumb/push.ll10
-rw-r--r--test/CodeGen/Thumb/rev.ll56
-rw-r--r--test/CodeGen/Thumb/select.ll82
-rw-r--r--test/CodeGen/Thumb/stack-frame.ll13
-rw-r--r--test/CodeGen/Thumb/thumb-imm.ll10
-rw-r--r--test/CodeGen/Thumb/thumb_jump24_fixup.ll23
-rw-r--r--test/CodeGen/Thumb/trap.ll12
-rw-r--r--test/CodeGen/Thumb/tst_teq.ll17
-rw-r--r--test/CodeGen/Thumb/unord.ll14
-rw-r--r--test/CodeGen/Thumb/vargs.ll36
-rw-r--r--test/CodeGen/Thumb2/2009-07-17-CrossRegClassCopy.ll35
-rw-r--r--test/CodeGen/Thumb2/2009-07-21-ISelBug.ll36
-rw-r--r--test/CodeGen/Thumb2/2009-07-23-CPIslandBug.ll22
-rw-r--r--test/CodeGen/Thumb2/2009-07-30-PEICrash.ll193
-rw-r--r--test/CodeGen/Thumb2/2009-08-01-WrongLDRBOpc.ll85
-rw-r--r--test/CodeGen/Thumb2/2009-08-02-CoalescerBug.ll46
-rw-r--r--test/CodeGen/Thumb2/2009-08-04-CoalescerAssert.ll29
-rw-r--r--test/CodeGen/Thumb2/2009-08-04-CoalescerBug.ll153
-rw-r--r--test/CodeGen/Thumb2/2009-08-04-ScavengerAssert.ll508
-rw-r--r--test/CodeGen/Thumb2/2009-08-04-SubregLoweringBug.ll33
-rw-r--r--test/CodeGen/Thumb2/2009-08-04-SubregLoweringBug2.ll42
-rw-r--r--test/CodeGen/Thumb2/2009-08-04-SubregLoweringBug3.ll54
-rw-r--r--test/CodeGen/Thumb2/2009-08-06-SpDecBug.ll29
-rw-r--r--test/CodeGen/Thumb2/2009-08-07-CoalescerBug.ll16
-rw-r--r--test/CodeGen/Thumb2/2009-08-07-NeonFPBug.ll80
-rw-r--r--test/CodeGen/Thumb2/2009-08-08-ScavengerAssert.ll20
-rw-r--r--test/CodeGen/Thumb2/2009-08-10-ISelBug.ll15
-rw-r--r--test/CodeGen/Thumb2/2009-08-21-PostRAKill4.ll26
-rw-r--r--test/CodeGen/Thumb2/2009-09-01-PostRAProlog.ll106
-rw-r--r--test/CodeGen/Thumb2/2009-09-28-ITBlockBug.ll152
-rw-r--r--test/CodeGen/Thumb2/2009-10-15-ITBlockBranch.ll42
-rw-r--r--test/CodeGen/Thumb2/2009-11-01-CopyReg2RegBug.ll29
-rw-r--r--test/CodeGen/Thumb2/2009-11-11-ScavengerAssert.ll85
-rw-r--r--test/CodeGen/Thumb2/2009-11-13-STRDBug.ll20
-rw-r--r--test/CodeGen/Thumb2/2009-12-01-LoopIVUsers.ll128
-rw-r--r--test/CodeGen/Thumb2/2010-01-06-TailDuplicateLabels.ll89
-rw-r--r--test/CodeGen/Thumb2/2010-01-19-RemovePredicates.ll53
-rw-r--r--test/CodeGen/Thumb2/2010-02-11-phi-cycle.ll76
-rw-r--r--test/CodeGen/Thumb2/2010-02-24-BigStack.ll15
-rw-r--r--test/CodeGen/Thumb2/2010-03-08-addi12-ccout.ll266
-rw-r--r--test/CodeGen/Thumb2/2010-03-15-AsmCCClobber.ll68
-rw-r--r--test/CodeGen/Thumb2/2010-04-15-DynAllocBug.ll18
-rw-r--r--test/CodeGen/Thumb2/2010-04-26-CopyRegCrash.ll73
-rw-r--r--test/CodeGen/Thumb2/2010-05-24-rsbs.ll9
-rw-r--r--test/CodeGen/Thumb2/2010-06-14-NEONCoalescer.ll42
-rw-r--r--test/CodeGen/Thumb2/2010-06-19-ITBlockCrash.ll35
-rw-r--r--test/CodeGen/Thumb2/2010-06-21-TailMergeBug.ll127
-rw-r--r--test/CodeGen/Thumb2/2010-08-10-VarSizedAllocaBug.ll59
-rw-r--r--test/CodeGen/Thumb2/2010-11-22-EpilogueBug.ll34
-rw-r--r--test/CodeGen/Thumb2/2010-12-03-AddSPNarrowing.ll11
-rw-r--r--test/CodeGen/Thumb2/2011-04-21-FILoweringBug.ll23
-rw-r--r--test/CodeGen/Thumb2/2011-06-07-TwoAddrEarlyClobber.ll34
-rw-r--r--test/CodeGen/Thumb2/2011-12-16-T2SizeReduceAssert.ll28
-rw-r--r--test/CodeGen/Thumb2/2012-01-13-CBNZBug.ll103
-rw-r--r--test/CodeGen/Thumb2/aligned-constants.ll26
-rw-r--r--test/CodeGen/Thumb2/aligned-spill.ll95
-rw-r--r--test/CodeGen/Thumb2/bfi.ll61
-rw-r--r--test/CodeGen/Thumb2/bfx.ll28
-rw-r--r--test/CodeGen/Thumb2/buildvector-crash.ll17
-rw-r--r--test/CodeGen/Thumb2/carry.ll22
-rw-r--r--test/CodeGen/Thumb2/constant-islands.ll1400
-rw-r--r--test/CodeGen/Thumb2/cortex-fp.ll24
-rw-r--r--test/CodeGen/Thumb2/crash.ll78
-rw-r--r--test/CodeGen/Thumb2/cross-rc-coalescing-1.ll52
-rw-r--r--test/CodeGen/Thumb2/cross-rc-coalescing-2.ll73
-rw-r--r--test/CodeGen/Thumb2/div.ll45
-rw-r--r--test/CodeGen/Thumb2/frameless.ll6
-rw-r--r--test/CodeGen/Thumb2/frameless2.ll12
-rw-r--r--test/CodeGen/Thumb2/ifcvt-neon.ll29
-rw-r--r--test/CodeGen/Thumb2/inflate-regs.ll49
-rw-r--r--test/CodeGen/Thumb2/inlineasm.ll9
-rw-r--r--test/CodeGen/Thumb2/large-call.ll30
-rw-r--r--test/CodeGen/Thumb2/large-stack.ll39
-rw-r--r--test/CodeGen/Thumb2/ldr-str-imm12.ll76
-rw-r--r--test/CodeGen/Thumb2/lit.local.cfg6
-rw-r--r--test/CodeGen/Thumb2/longMACt.ll44
-rw-r--r--test/CodeGen/Thumb2/lsr-deficiency.ll36
-rw-r--r--test/CodeGen/Thumb2/machine-licm.ll120
-rw-r--r--test/CodeGen/Thumb2/mul_const.ll18
-rw-r--r--test/CodeGen/Thumb2/pic-load.ll21
-rw-r--r--test/CodeGen/Thumb2/thumb2-adc.ll48
-rw-r--r--test/CodeGen/Thumb2/thumb2-add.ll83
-rw-r--r--test/CodeGen/Thumb2/thumb2-add2.ll41
-rw-r--r--test/CodeGen/Thumb2/thumb2-add3.ll9
-rw-r--r--test/CodeGen/Thumb2/thumb2-add4.ll46
-rw-r--r--test/CodeGen/Thumb2/thumb2-add5.ll42
-rw-r--r--test/CodeGen/Thumb2/thumb2-add6.ll9
-rw-r--r--test/CodeGen/Thumb2/thumb2-and.ll42
-rw-r--r--test/CodeGen/Thumb2/thumb2-and2.ll41
-rw-r--r--test/CodeGen/Thumb2/thumb2-asr.ll8
-rw-r--r--test/CodeGen/Thumb2/thumb2-asr2.ll8
-rw-r--r--test/CodeGen/Thumb2/thumb2-bcc.ll23
-rw-r--r--test/CodeGen/Thumb2/thumb2-bfc.ll32
-rw-r--r--test/CodeGen/Thumb2/thumb2-bic.ll105
-rw-r--r--test/CodeGen/Thumb2/thumb2-branch.ll72
-rw-r--r--test/CodeGen/Thumb2/thumb2-call-tc.ll38
-rw-r--r--test/CodeGen/Thumb2/thumb2-call.ll27
-rw-r--r--test/CodeGen/Thumb2/thumb2-cbnz.ll35
-rw-r--r--test/CodeGen/Thumb2/thumb2-clz.ll10
-rw-r--r--test/CodeGen/Thumb2/thumb2-cmn.ll85
-rw-r--r--test/CodeGen/Thumb2/thumb2-cmn2.ll33
-rw-r--r--test/CodeGen/Thumb2/thumb2-cmp.ll58
-rw-r--r--test/CodeGen/Thumb2/thumb2-cmp2.ll52
-rw-r--r--test/CodeGen/Thumb2/thumb2-eor.ll56
-rw-r--r--test/CodeGen/Thumb2/thumb2-eor2.ll41
-rw-r--r--test/CodeGen/Thumb2/thumb2-ifcvt1-tc.ll87
-rw-r--r--test/CodeGen/Thumb2/thumb2-ifcvt1.ll87
-rw-r--r--test/CodeGen/Thumb2/thumb2-ifcvt2.ll94
-rw-r--r--test/CodeGen/Thumb2/thumb2-ifcvt3.ll31
-rw-r--r--test/CodeGen/Thumb2/thumb2-jtb.ll134
-rw-r--r--test/CodeGen/Thumb2/thumb2-ldm.ll40
-rw-r--r--test/CodeGen/Thumb2/thumb2-ldr.ll72
-rw-r--r--test/CodeGen/Thumb2/thumb2-ldr_ext.ll28
-rw-r--r--test/CodeGen/Thumb2/thumb2-ldr_post.ll12
-rw-r--r--test/CodeGen/Thumb2/thumb2-ldr_pre.ll28
-rw-r--r--test/CodeGen/Thumb2/thumb2-ldrb.ll72
-rw-r--r--test/CodeGen/Thumb2/thumb2-ldrd.ll13
-rw-r--r--test/CodeGen/Thumb2/thumb2-ldrh.ll71
-rw-r--r--test/CodeGen/Thumb2/thumb2-lsl.ll8
-rw-r--r--test/CodeGen/Thumb2/thumb2-lsl2.ll8
-rw-r--r--test/CodeGen/Thumb2/thumb2-lsr.ll8
-rw-r--r--test/CodeGen/Thumb2/thumb2-lsr2.ll8
-rw-r--r--test/CodeGen/Thumb2/thumb2-lsr3.ll19
-rw-r--r--test/CodeGen/Thumb2/thumb2-mla.ll17
-rw-r--r--test/CodeGen/Thumb2/thumb2-mls.ll19
-rw-r--r--test/CodeGen/Thumb2/thumb2-mov.ll266
-rw-r--r--test/CodeGen/Thumb2/thumb2-mul.ll26
-rw-r--r--test/CodeGen/Thumb2/thumb2-mulhi.ll23
-rw-r--r--test/CodeGen/Thumb2/thumb2-mvn.ll33
-rw-r--r--test/CodeGen/Thumb2/thumb2-mvn2.ll49
-rw-r--r--test/CodeGen/Thumb2/thumb2-neg.ll8
-rw-r--r--test/CodeGen/Thumb2/thumb2-orn.ll72
-rw-r--r--test/CodeGen/Thumb2/thumb2-orn2.ll38
-rw-r--r--test/CodeGen/Thumb2/thumb2-orr.ll42
-rw-r--r--test/CodeGen/Thumb2/thumb2-orr2.ll42
-rw-r--r--test/CodeGen/Thumb2/thumb2-pack.ll97
-rw-r--r--test/CodeGen/Thumb2/thumb2-rev.ll23
-rw-r--r--test/CodeGen/Thumb2/thumb2-rev16.ll32
-rw-r--r--test/CodeGen/Thumb2/thumb2-ror.ll26
-rw-r--r--test/CodeGen/Thumb2/thumb2-rsb.ll35
-rw-r--r--test/CodeGen/Thumb2/thumb2-rsb2.ll41
-rw-r--r--test/CodeGen/Thumb2/thumb2-sbc.ll68
-rw-r--r--test/CodeGen/Thumb2/thumb2-select.ll98
-rw-r--r--test/CodeGen/Thumb2/thumb2-select_xform.ll39
-rw-r--r--test/CodeGen/Thumb2/thumb2-shifter.ll48
-rw-r--r--test/CodeGen/Thumb2/thumb2-smla.ll11
-rw-r--r--test/CodeGen/Thumb2/thumb2-smul.ll24
-rw-r--r--test/CodeGen/Thumb2/thumb2-spill-q.ll91
-rw-r--r--test/CodeGen/Thumb2/thumb2-str.ll76
-rw-r--r--test/CodeGen/Thumb2/thumb2-str_post.ll22
-rw-r--r--test/CodeGen/Thumb2/thumb2-str_pre.ll21
-rw-r--r--test/CodeGen/Thumb2/thumb2-strb.ll76
-rw-r--r--test/CodeGen/Thumb2/thumb2-strh.ll76
-rw-r--r--test/CodeGen/Thumb2/thumb2-sub.ll49
-rw-r--r--test/CodeGen/Thumb2/thumb2-sub2.ll8
-rw-r--r--test/CodeGen/Thumb2/thumb2-sub3.ll55
-rw-r--r--test/CodeGen/Thumb2/thumb2-sub4.ll42
-rw-r--r--test/CodeGen/Thumb2/thumb2-sub5.ll10
-rw-r--r--test/CodeGen/Thumb2/thumb2-sxt-uxt.ll29
-rw-r--r--test/CodeGen/Thumb2/thumb2-sxt_rot.ll31
-rw-r--r--test/CodeGen/Thumb2/thumb2-tbb.ll59
-rw-r--r--test/CodeGen/Thumb2/thumb2-tbh.ll84
-rw-r--r--test/CodeGen/Thumb2/thumb2-teq.ll57
-rw-r--r--test/CodeGen/Thumb2/thumb2-teq2.ll58
-rw-r--r--test/CodeGen/Thumb2/thumb2-tst.ll49
-rw-r--r--test/CodeGen/Thumb2/thumb2-tst2.ll58
-rw-r--r--test/CodeGen/Thumb2/thumb2-uxt_rot.ll35
-rw-r--r--test/CodeGen/Thumb2/thumb2-uxtb.ll141
-rw-r--r--test/CodeGen/Thumb2/tls1.ll20
-rw-r--r--test/CodeGen/Thumb2/tls2.ll29
-rw-r--r--test/CodeGen/X86/2003-08-03-CallArgLiveRanges.ll18
-rw-r--r--test/CodeGen/X86/2003-08-23-DeadBlockTest.ll12
-rw-r--r--test/CodeGen/X86/2003-11-03-GlobalBool.ll4
-rw-r--r--test/CodeGen/X86/2004-02-13-FrameReturnAddress.ll18
-rw-r--r--test/CodeGen/X86/2004-02-14-InefficientStackPointer.ll5
-rw-r--r--test/CodeGen/X86/2004-02-22-Casts.ll12
-rw-r--r--test/CodeGen/X86/2004-03-30-Select-Max.ll9
-rw-r--r--test/CodeGen/X86/2004-04-13-FPCMOV-Crash.ll7
-rw-r--r--test/CodeGen/X86/2004-06-10-StackifierCrash.ll6
-rw-r--r--test/CodeGen/X86/2004-10-08-SelectSetCCFold.ll8
-rw-r--r--test/CodeGen/X86/2005-01-17-CycleInDAG.ll17
-rw-r--r--test/CodeGen/X86/2005-02-14-IllegalAssembler.ll5
-rw-r--r--test/CodeGen/X86/2005-05-08-FPStackifierPHI.ll38
-rw-r--r--test/CodeGen/X86/2006-01-19-ISelFoldingBug.ll20
-rw-r--r--test/CodeGen/X86/2006-03-01-InstrSchedBug.ll12
-rw-r--r--test/CodeGen/X86/2006-03-02-InstrSchedBug.ll12
-rw-r--r--test/CodeGen/X86/2006-04-04-CrossBlockCrash.ll50
-rw-r--r--test/CodeGen/X86/2006-04-27-ISelFoldingBug.ll29
-rw-r--r--test/CodeGen/X86/2006-05-01-SchedCausingSpills.ll76
-rw-r--r--test/CodeGen/X86/2006-05-02-InstrSched1.ll23
-rw-r--r--test/CodeGen/X86/2006-05-02-InstrSched2.ll24
-rw-r--r--test/CodeGen/X86/2006-05-08-CoalesceSubRegClass.ll25
-rw-r--r--test/CodeGen/X86/2006-05-08-InstrSched.ll25
-rw-r--r--test/CodeGen/X86/2006-05-11-InstrSched.ll51
-rw-r--r--test/CodeGen/X86/2006-05-17-VectorArg.ll15
-rw-r--r--test/CodeGen/X86/2006-05-22-FPSetEQ.ll10
-rw-r--r--test/CodeGen/X86/2006-05-25-CycleInDAG.ll20
-rw-r--r--test/CodeGen/X86/2006-07-10-InlineAsmAConstraint.ll8
-rw-r--r--test/CodeGen/X86/2006-07-12-InlineAsmQConstraint.ll12
-rw-r--r--test/CodeGen/X86/2006-07-20-InlineAsm.ll23
-rw-r--r--test/CodeGen/X86/2006-07-28-AsmPrint-Long-As-Pointer.ll5
-rw-r--r--test/CodeGen/X86/2006-07-31-SingleRegClass.ll10
-rw-r--r--test/CodeGen/X86/2006-08-07-CycleInDAG.ll31
-rw-r--r--test/CodeGen/X86/2006-08-16-CycleInDAG.ll23
-rw-r--r--test/CodeGen/X86/2006-08-21-ExtraMovInst.ll17
-rw-r--r--test/CodeGen/X86/2006-09-01-CycleInDAG.ll131
-rw-r--r--test/CodeGen/X86/2006-10-02-BoolRetCrash.ll7
-rw-r--r--test/CodeGen/X86/2006-10-07-ScalarSSEMiscompile.ll15
-rw-r--r--test/CodeGen/X86/2006-10-09-CycleInDAG.ll11
-rw-r--r--test/CodeGen/X86/2006-10-10-FindModifiedNodeSlotBug.ll28
-rw-r--r--test/CodeGen/X86/2006-10-12-CycleInDAG.ll41
-rw-r--r--test/CodeGen/X86/2006-10-13-CycleInDAG.ll19
-rw-r--r--test/CodeGen/X86/2006-10-19-SwitchUnnecessaryBranching.ll29
-rw-r--r--test/CodeGen/X86/2006-11-12-CSRetCC.ll64
-rw-r--r--test/CodeGen/X86/2006-11-17-IllegalMove.ll42
-rw-r--r--test/CodeGen/X86/2006-11-27-SelectLegalize.ll9
-rw-r--r--test/CodeGen/X86/2006-12-16-InlineAsmCrash.ll30
-rw-r--r--test/CodeGen/X86/2006-12-19-IntelSyntax.ll86
-rw-r--r--test/CodeGen/X86/2007-01-08-InstrSched.ll22
-rw-r--r--test/CodeGen/X86/2007-01-08-X86-64-Pointer.ll22
-rw-r--r--test/CodeGen/X86/2007-01-13-StackPtrIndex.ll461
-rw-r--r--test/CodeGen/X86/2007-01-29-InlineAsm-ir.ll7
-rw-r--r--test/CodeGen/X86/2007-02-04-OrAddrMode.ll29
-rw-r--r--test/CodeGen/X86/2007-02-16-BranchFold.ll95
-rw-r--r--test/CodeGen/X86/2007-02-19-LiveIntervalAssert.ll21
-rw-r--r--test/CodeGen/X86/2007-02-23-DAGCombine-Miscompile.ll17
-rw-r--r--test/CodeGen/X86/2007-02-25-FastCCStack.ll5
-rw-r--r--test/CodeGen/X86/2007-03-01-SpillerCrash.ll86
-rw-r--r--test/CodeGen/X86/2007-03-15-GEP-Idx-Sink.ll73
-rw-r--r--test/CodeGen/X86/2007-03-16-InlineAsm.ll26
-rw-r--r--test/CodeGen/X86/2007-03-18-LiveIntervalAssert.ll7
-rw-r--r--test/CodeGen/X86/2007-03-24-InlineAsmMultiRegConstraint.ll11
-rw-r--r--test/CodeGen/X86/2007-03-24-InlineAsmPModifier.ll10
-rw-r--r--test/CodeGen/X86/2007-03-24-InlineAsmVectorOp.ll11
-rw-r--r--test/CodeGen/X86/2007-03-24-InlineAsmXConstraint.ll14
-rw-r--r--test/CodeGen/X86/2007-03-26-CoalescerBug.ll49
-rw-r--r--test/CodeGen/X86/2007-04-08-InlineAsmCrash.ll18
-rw-r--r--test/CodeGen/X86/2007-04-11-InlineAsmVectorResult.ll21
-rw-r--r--test/CodeGen/X86/2007-04-17-LiveIntervalAssert.ll42
-rw-r--r--test/CodeGen/X86/2007-04-24-Huge-Stack.ll19
-rw-r--r--test/CodeGen/X86/2007-04-24-VectorCrash.ll63
-rw-r--r--test/CodeGen/X86/2007-04-25-MMX-PADDQ.ll64
-rw-r--r--test/CodeGen/X86/2007-04-27-InlineAsm-IntMemInput.ll12
-rw-r--r--test/CodeGen/X86/2007-05-05-Personality.ll34
-rw-r--r--test/CodeGen/X86/2007-05-05-VecCastExpand.ll21
-rw-r--r--test/CodeGen/X86/2007-05-07-InvokeSRet.ll19
-rw-r--r--test/CodeGen/X86/2007-05-14-LiveIntervalAssert.ll27
-rw-r--r--test/CodeGen/X86/2007-05-15-maskmovq.ll14
-rw-r--r--test/CodeGen/X86/2007-05-17-ShuffleISelBug.ll23
-rw-r--r--test/CodeGen/X86/2007-06-04-X86-64-CtorAsmBugs.ll28
-rw-r--r--test/CodeGen/X86/2007-06-15-IntToMMX.ll16
-rw-r--r--test/CodeGen/X86/2007-06-28-X86-64-isel.ll16
-rw-r--r--test/CodeGen/X86/2007-06-29-DAGCombinerBug.ll50
-rw-r--r--test/CodeGen/X86/2007-06-29-VecFPConstantCSEBug.ll11
-rw-r--r--test/CodeGen/X86/2007-07-03-GR64ToVR64.ll20
-rw-r--r--test/CodeGen/X86/2007-07-10-StackerAssert.ll41
-rw-r--r--test/CodeGen/X86/2007-07-18-Vector-Extract.ll17
-rw-r--r--test/CodeGen/X86/2007-08-01-LiveVariablesBug.ll8
-rw-r--r--test/CodeGen/X86/2007-08-09-IllegalX86-64Asm.ll235
-rw-r--r--test/CodeGen/X86/2007-08-10-SignExtSubreg.ll10
-rw-r--r--test/CodeGen/X86/2007-08-13-AppendingLinkage.ll12
-rw-r--r--test/CodeGen/X86/2007-09-05-InvalidAsm.ll50
-rw-r--r--test/CodeGen/X86/2007-09-06-ExtWeakAliasee.ll4
-rw-r--r--test/CodeGen/X86/2007-09-17-ObjcFrameEH.ll67
-rw-r--r--test/CodeGen/X86/2007-09-18-ShuffleXformBug.ll30
-rw-r--r--test/CodeGen/X86/2007-09-27-LDIntrinsics.ll30
-rw-r--r--test/CodeGen/X86/2007-10-04-AvoidEFLAGSCopy.ll20
-rw-r--r--test/CodeGen/X86/2007-10-12-CoalesceExtSubReg.ll32
-rw-r--r--test/CodeGen/X86/2007-10-12-SpillerUnfold1.ll45
-rw-r--r--test/CodeGen/X86/2007-10-12-SpillerUnfold2.ll57
-rw-r--r--test/CodeGen/X86/2007-10-14-CoalescerCrash.ll28
-rw-r--r--test/CodeGen/X86/2007-10-15-CoalescerCrash.ll400
-rw-r--r--test/CodeGen/X86/2007-10-16-CoalescerCrash.ll31
-rw-r--r--test/CodeGen/X86/2007-10-17-IllegalAsm.ll87
-rw-r--r--test/CodeGen/X86/2007-10-19-SpillerUnfold.ll84
-rw-r--r--test/CodeGen/X86/2007-10-28-inlineasm-q-modifier.ll11
-rw-r--r--test/CodeGen/X86/2007-10-29-ExtendSetCC.ll17
-rw-r--r--test/CodeGen/X86/2007-10-30-LSRCrash.ll48
-rw-r--r--test/CodeGen/X86/2007-10-31-extractelement-i64.ll82
-rw-r--r--test/CodeGen/X86/2007-11-01-ISelCrash.ll12
-rw-r--r--test/CodeGen/X86/2007-11-03-x86-64-q-constraint.ll9
-rw-r--r--test/CodeGen/X86/2007-11-04-LiveIntervalCrash.ll37
-rw-r--r--test/CodeGen/X86/2007-11-04-LiveVariablesBug.ll16
-rw-r--r--test/CodeGen/X86/2007-11-04-rip-immediate-constant.ll11
-rw-r--r--test/CodeGen/X86/2007-11-06-InstrSched.ll25
-rw-r--r--test/CodeGen/X86/2007-11-07-MulBy4.ll129
-rw-r--r--test/CodeGen/X86/2007-11-30-LoadFolding-Bug.ll86
-rw-r--r--test/CodeGen/X86/2007-12-16-BURRSchedCrash.ll35
-rw-r--r--test/CodeGen/X86/2007-12-18-LoadCSEBug.ll28
-rw-r--r--test/CodeGen/X86/2008-01-08-IllegalCMP.ll17
-rw-r--r--test/CodeGen/X86/2008-01-08-SchedulerCrash.ll40
-rw-r--r--test/CodeGen/X86/2008-01-09-LongDoubleSin.ll11
-rw-r--r--test/CodeGen/X86/2008-01-16-FPStackifierAssert.ll35
-rw-r--r--test/CodeGen/X86/2008-01-16-InvalidDAGCombineXform.ll30
-rw-r--r--test/CodeGen/X86/2008-02-05-ISelCrash.ll12
-rw-r--r--test/CodeGen/X86/2008-02-06-LoadFoldingBug.ll20
-rw-r--r--test/CodeGen/X86/2008-02-08-LoadFoldingBug.ll99
-rw-r--r--test/CodeGen/X86/2008-02-14-BitMiscompile.ll8
-rw-r--r--test/CodeGen/X86/2008-02-18-TailMergingBug.ll219
-rw-r--r--test/CodeGen/X86/2008-02-20-InlineAsmClobber.ll24
-rw-r--r--test/CodeGen/X86/2008-02-22-LocalRegAllocBug.ll55
-rw-r--r--test/CodeGen/X86/2008-02-25-InlineAsmBug.ll33
-rw-r--r--test/CodeGen/X86/2008-02-25-X86-64-CoalescerBug.ll55
-rw-r--r--test/CodeGen/X86/2008-02-26-AsmDirectMemOp.ll17
-rw-r--r--test/CodeGen/X86/2008-02-27-DeadSlotElimBug.ll66
-rw-r--r--test/CodeGen/X86/2008-02-27-PEICrash.ll33
-rw-r--r--test/CodeGen/X86/2008-03-06-frem-fpstack.ll7
-rw-r--r--test/CodeGen/X86/2008-03-07-APIntBug.ll94
-rw-r--r--test/CodeGen/X86/2008-03-10-RegAllocInfLoop.ll14
-rw-r--r--test/CodeGen/X86/2008-03-12-ThreadLocalAlias.ll37
-rw-r--r--test/CodeGen/X86/2008-03-13-TwoAddrPassCrash.ll68
-rw-r--r--test/CodeGen/X86/2008-03-14-SpillerCrash.ll48
-rw-r--r--test/CodeGen/X86/2008-03-19-DAGCombinerBug.ll14
-rw-r--r--test/CodeGen/X86/2008-03-23-DarwinAsmComments.ll49
-rw-r--r--test/CodeGen/X86/2008-03-25-TwoAddrPassBug.ll24
-rw-r--r--test/CodeGen/X86/2008-03-31-SpillerFoldingBug.ll40
-rw-r--r--test/CodeGen/X86/2008-04-02-unnamedEH.ll16
-rw-r--r--test/CodeGen/X86/2008-04-08-CoalescerCrash.ll19
-rw-r--r--test/CodeGen/X86/2008-04-09-BranchFolding.ll48
-rw-r--r--test/CodeGen/X86/2008-04-15-LiveVariableBug.ll50
-rw-r--r--test/CodeGen/X86/2008-04-16-CoalescerBug.ll33
-rw-r--r--test/CodeGen/X86/2008-04-16-ReMatBug.ll46
-rw-r--r--test/CodeGen/X86/2008-04-17-CoalescerBug.ll177
-rw-r--r--test/CodeGen/X86/2008-04-24-MemCpyBug.ll12
-rw-r--r--test/CodeGen/X86/2008-04-24-pblendw-fold-crash.ll15
-rw-r--r--test/CodeGen/X86/2008-04-26-Asm-Optimize-Imm.ll15
-rw-r--r--test/CodeGen/X86/2008-04-28-CoalescerBug.ll167
-rw-r--r--test/CodeGen/X86/2008-04-28-CyclicSchedUnit.ll6
-rw-r--r--test/CodeGen/X86/2008-05-01-InvalidOrdCompare.ll15
-rw-r--r--test/CodeGen/X86/2008-05-09-PHIElimBug.ll25
-rw-r--r--test/CodeGen/X86/2008-05-09-ShuffleLoweringBug.ll10
-rw-r--r--test/CodeGen/X86/2008-05-12-tailmerge-5.ll145
-rw-r--r--test/CodeGen/X86/2008-05-21-CoalescerBug.ll98
-rw-r--r--test/CodeGen/X86/2008-05-22-FoldUnalignedLoad.ll11
-rw-r--r--test/CodeGen/X86/2008-05-28-CoalescerBug.ll10
-rw-r--r--test/CodeGen/X86/2008-05-28-LocalRegAllocBug.ll32
-rw-r--r--test/CodeGen/X86/2008-06-13-NotVolatileLoadStore.ll23
-rw-r--r--test/CodeGen/X86/2008-06-13-VolatileLoadStore.ll22
-rw-r--r--test/CodeGen/X86/2008-06-16-SubregsBug.ll14
-rw-r--r--test/CodeGen/X86/2008-06-18-BadShuffle.ll10
-rw-r--r--test/CodeGen/X86/2008-06-25-VecISelBug.ll9
-rw-r--r--test/CodeGen/X86/2008-07-07-DanglingDeadInsts.ll99
-rw-r--r--test/CodeGen/X86/2008-07-09-ELFSectionAttributes.ll13
-rw-r--r--test/CodeGen/X86/2008-07-11-SHLBy1.ll5
-rw-r--r--test/CodeGen/X86/2008-07-16-CoalescerCrash.ll34
-rw-r--r--test/CodeGen/X86/2008-07-19-movups-spills.ll639
-rw-r--r--test/CodeGen/X86/2008-07-22-CombinerCrash.ll16
-rw-r--r--test/CodeGen/X86/2008-07-23-VSetCC.ll32
-rw-r--r--test/CodeGen/X86/2008-08-06-CmpStride.ll23
-rw-r--r--test/CodeGen/X86/2008-08-06-RewriterBug.ll40
-rw-r--r--test/CodeGen/X86/2008-08-17-UComiCodeGenBug.ll9
-rw-r--r--test/CodeGen/X86/2008-08-19-SubAndFetch.ll12
-rw-r--r--test/CodeGen/X86/2008-08-23-64Bit-maskmovq.ll29
-rw-r--r--test/CodeGen/X86/2008-08-31-EH_RETURN32.ll38
-rw-r--r--test/CodeGen/X86/2008-08-31-EH_RETURN64.ll17
-rw-r--r--test/CodeGen/X86/2008-09-05-sinttofp-2xi32.ll35
-rw-r--r--test/CodeGen/X86/2008-09-09-LinearScanBug.ll65
-rw-r--r--test/CodeGen/X86/2008-09-11-CoalescerBug.ll38
-rw-r--r--test/CodeGen/X86/2008-09-11-CoalescerBug2.ll33
-rw-r--r--test/CodeGen/X86/2008-09-17-inline-asm-1.ll30
-rw-r--r--test/CodeGen/X86/2008-09-18-inline-asm-2.ll48
-rw-r--r--test/CodeGen/X86/2008-09-19-RegAllocBug.ll22
-rw-r--r--test/CodeGen/X86/2008-09-25-sseregparm-1.ll19
-rw-r--r--test/CodeGen/X86/2008-09-26-FrameAddrBug.ll16
-rw-r--r--test/CodeGen/X86/2008-09-29-ReMatBug.ll85
-rw-r--r--test/CodeGen/X86/2008-09-29-VolatileBug.ll15
-rw-r--r--test/CodeGen/X86/2008-10-06-MMXISelBug.ll12
-rw-r--r--test/CodeGen/X86/2008-10-06-x87ld-nan-1.ll13
-rw-r--r--test/CodeGen/X86/2008-10-06-x87ld-nan-2.ll18
-rw-r--r--test/CodeGen/X86/2008-10-07-SSEISelBug.ll22
-rw-r--r--test/CodeGen/X86/2008-10-11-CallCrash.ll21
-rw-r--r--test/CodeGen/X86/2008-10-13-CoalescerBug.ll42
-rw-r--r--test/CodeGen/X86/2008-10-16-VecUnaryOp.ll8
-rw-r--r--test/CodeGen/X86/2008-10-17-Asm64bitRConstraint.ll9
-rw-r--r--test/CodeGen/X86/2008-10-20-AsmDoubleInI32.ll11
-rw-r--r--test/CodeGen/X86/2008-10-24-FlippedCompare.ll17
-rw-r--r--test/CodeGen/X86/2008-10-27-CoalescerBug.ll51
-rw-r--r--test/CodeGen/X86/2008-10-27-StackRealignment.ll22
-rw-r--r--test/CodeGen/X86/2008-10-29-ExpandVAARG.ll10
-rw-r--r--test/CodeGen/X86/2008-11-03-F80VAARG.ll17
-rw-r--r--test/CodeGen/X86/2008-11-06-testb.ll26
-rw-r--r--test/CodeGen/X86/2008-11-13-inlineasm-3.ll19
-rw-r--r--test/CodeGen/X86/2008-11-29-ULT-Sign.ll22
-rw-r--r--test/CodeGen/X86/2008-12-01-SpillerAssert.ll15
-rw-r--r--test/CodeGen/X86/2008-12-01-loop-iv-used-outside-loop.ll30
-rw-r--r--test/CodeGen/X86/2008-12-02-IllegalResultType.ll37
-rw-r--r--test/CodeGen/X86/2008-12-02-dagcombine-1.ll19
-rw-r--r--test/CodeGen/X86/2008-12-02-dagcombine-2.ll17
-rw-r--r--test/CodeGen/X86/2008-12-02-dagcombine-3.ll18
-rw-r--r--test/CodeGen/X86/2008-12-12-PrivateEHSymbol.ll10
-rw-r--r--test/CodeGen/X86/2008-12-16-dagcombine-4.ll14
-rw-r--r--test/CodeGen/X86/2008-12-19-EarlyClobberBug.ll38
-rw-r--r--test/CodeGen/X86/2008-12-22-dagcombine-5.ll14
-rw-r--r--test/CodeGen/X86/2008-12-23-crazy-address.ll33
-rw-r--r--test/CodeGen/X86/2008-12-23-dagcombine-6.ll24
-rw-r--r--test/CodeGen/X86/2009-01-13-DoubleUpdate.ll21
-rw-r--r--test/CodeGen/X86/2009-01-16-SchedulerBug.ll50
-rw-r--r--test/CodeGen/X86/2009-01-16-UIntToFP.ll31
-rw-r--r--test/CodeGen/X86/2009-01-18-ConstantExprCrash.ll36
-rw-r--r--test/CodeGen/X86/2009-01-25-NoSSE.ll20
-rw-r--r--test/CodeGen/X86/2009-01-26-WrongCheck.ll16
-rw-r--r--test/CodeGen/X86/2009-01-27-NullStrings.ll7
-rw-r--r--test/CodeGen/X86/2009-01-31-BigShift.ll9
-rw-r--r--test/CodeGen/X86/2009-01-31-BigShift2.ll11
-rw-r--r--test/CodeGen/X86/2009-01-31-BigShift3.ll31
-rw-r--r--test/CodeGen/X86/2009-02-01-LargeMask.ll32
-rw-r--r--test/CodeGen/X86/2009-02-03-AnalyzedTwice.ll30
-rw-r--r--test/CodeGen/X86/2009-02-04-sext-i64-gep.ll9
-rw-r--r--test/CodeGen/X86/2009-02-08-CoalescerBug.ll22
-rw-r--r--test/CodeGen/X86/2009-02-09-ivs-different-sizes.ll33
-rw-r--r--test/CodeGen/X86/2009-02-11-codegenprepare-reuse.ll35
-rw-r--r--test/CodeGen/X86/2009-02-12-DebugInfoVLA.ll85
-rw-r--r--test/CodeGen/X86/2009-02-12-InlineAsm-nieZ-constraints.ll24
-rw-r--r--test/CodeGen/X86/2009-02-12-SpillerBug.ll29
-rw-r--r--test/CodeGen/X86/2009-02-21-ExtWeakInitializer.ll20
-rw-r--r--test/CodeGen/X86/2009-02-25-CommuteBug.ll14
-rw-r--r--test/CodeGen/X86/2009-02-26-MachineLICMBug.ll56
-rw-r--r--test/CodeGen/X86/2009-03-03-BTHang.ll37
-rw-r--r--test/CodeGen/X86/2009-03-03-BitcastLongDouble.ll14
-rw-r--r--test/CodeGen/X86/2009-03-05-burr-list-crash.ll35
-rw-r--r--test/CodeGen/X86/2009-03-07-FPConstSelect.ll12
-rw-r--r--test/CodeGen/X86/2009-03-09-APIntCrash.ll25
-rw-r--r--test/CodeGen/X86/2009-03-09-SpillerBug.ll18
-rw-r--r--test/CodeGen/X86/2009-03-10-CoalescerBug.ll28
-rw-r--r--test/CodeGen/X86/2009-03-12-CPAlignBug.ll37
-rw-r--r--test/CodeGen/X86/2009-03-13-PHIElimBug.ll36
-rw-r--r--test/CodeGen/X86/2009-03-16-PHIElimInLPad.ll28
-rw-r--r--test/CodeGen/X86/2009-03-23-LinearScanBug.ll23
-rw-r--r--test/CodeGen/X86/2009-03-23-MultiUseSched.ll242
-rw-r--r--test/CodeGen/X86/2009-03-23-i80-fp80.ll14
-rw-r--r--test/CodeGen/X86/2009-03-25-TestBug.ll25
-rw-r--r--test/CodeGen/X86/2009-03-26-NoImplicitFPBug.ll12
-rw-r--r--test/CodeGen/X86/2009-04-12-FastIselOverflowCrash.ll21
-rw-r--r--test/CodeGen/X86/2009-04-12-picrel.ll13
-rw-r--r--test/CodeGen/X86/2009-04-13-2AddrAssert-2.ll15
-rw-r--r--test/CodeGen/X86/2009-04-13-2AddrAssert.ll16
-rw-r--r--test/CodeGen/X86/2009-04-14-IllegalRegs.ll35
-rw-r--r--test/CodeGen/X86/2009-04-16-SpillerUnfold.ll141
-rw-r--r--test/CodeGen/X86/2009-04-21-NoReloadImpDef.ll30
-rw-r--r--test/CodeGen/X86/2009-04-24.ll12
-rw-r--r--test/CodeGen/X86/2009-04-25-CoalescerBug.ll19
-rw-r--r--test/CodeGen/X86/2009-04-27-CoalescerAssert.ll1457
-rw-r--r--test/CodeGen/X86/2009-04-27-LiveIntervalsAssert.ll24
-rw-r--r--test/CodeGen/X86/2009-04-27-LiveIntervalsAssert2.ll23
-rw-r--r--test/CodeGen/X86/2009-04-29-IndirectDestOperands.ll22
-rw-r--r--test/CodeGen/X86/2009-04-29-LinearScanBug.ll215
-rw-r--r--test/CodeGen/X86/2009-04-29-RegAllocAssert.ll117
-rw-r--r--test/CodeGen/X86/2009-04-scale.ll23
-rw-r--r--test/CodeGen/X86/2009-05-08-InlineAsmIOffset.ll17
-rw-r--r--test/CodeGen/X86/2009-05-11-tailmerge-crash.ll23
-rw-r--r--test/CodeGen/X86/2009-05-19-SingleElementExtractElement.ll16
-rw-r--r--test/CodeGen/X86/2009-05-23-available_externally.ll19
-rw-r--r--test/CodeGen/X86/2009-05-23-dagcombine-shifts.ll20
-rw-r--r--test/CodeGen/X86/2009-05-28-DAGCombineCrash.ll15
-rw-r--r--test/CodeGen/X86/2009-05-30-ISelBug.ll28
-rw-r--r--test/CodeGen/X86/2009-06-02-RewriterBug.ll362
-rw-r--r--test/CodeGen/X86/2009-06-03-Win64DisableRedZone.ll8
-rw-r--r--test/CodeGen/X86/2009-06-03-Win64SpillXMM.ll10
-rw-r--r--test/CodeGen/X86/2009-06-04-VirtualLiveIn.ll48
-rw-r--r--test/CodeGen/X86/2009-06-05-ScalarToVectorByteMMX.ll7
-rw-r--r--test/CodeGen/X86/2009-06-05-VZextByteShort.ll37
-rw-r--r--test/CodeGen/X86/2009-06-05-VariableIndexInsert.ll11
-rw-r--r--test/CodeGen/X86/2009-06-05-sitofpCrash.ll13
-rw-r--r--test/CodeGen/X86/2009-06-06-ConcatVectors.ll8
-rw-r--r--test/CodeGen/X86/2009-06-07-ExpandMMXBitcast.ll10
-rw-r--r--test/CodeGen/X86/2009-06-12-x86_64-tail-call-conv-out-of-sync-bug.ll15
-rw-r--r--test/CodeGen/X86/2009-06-15-not-a-tail-call.ll14
-rw-r--r--test/CodeGen/X86/2009-06-18-movlp-shuffle-register.ll10
-rw-r--r--test/CodeGen/X86/2009-07-06-TwoAddrAssert.ll137
-rw-r--r--test/CodeGen/X86/2009-07-07-SplitICmp.ll8
-rw-r--r--test/CodeGen/X86/2009-07-09-ExtractBoolFromVector.ll11
-rw-r--r--test/CodeGen/X86/2009-07-15-CoalescerBug.ll958
-rw-r--r--test/CodeGen/X86/2009-07-16-CoalescerBug.ll210
-rw-r--r--test/CodeGen/X86/2009-07-19-AsmExtraOperands.ll11
-rw-r--r--test/CodeGen/X86/2009-07-20-CoalescerBug.ll165
-rw-r--r--test/CodeGen/X86/2009-07-20-DAGCombineBug.ll29
-rw-r--r--test/CodeGen/X86/2009-08-02-mmx-scalar-to-vector.ll12
-rw-r--r--test/CodeGen/X86/2009-08-06-branchfolder-crash.ll140
-rw-r--r--test/CodeGen/X86/2009-08-06-inlineasm.ll30
-rw-r--r--test/CodeGen/X86/2009-08-08-CastError.ll9
-rw-r--r--test/CodeGen/X86/2009-08-12-badswitch.ll176
-rw-r--r--test/CodeGen/X86/2009-08-14-Win64MemoryIndirectArg.ll57
-rw-r--r--test/CodeGen/X86/2009-08-19-LoadNarrowingMiscompile.ll15
-rw-r--r--test/CodeGen/X86/2009-08-23-SubRegReuseUndo.ll69
-rw-r--r--test/CodeGen/X86/2009-08-23-linkerprivate.ll8
-rw-r--r--test/CodeGen/X86/2009-09-10-LoadFoldingBug.ll51
-rw-r--r--test/CodeGen/X86/2009-09-10-SpillComments.ll108
-rw-r--r--test/CodeGen/X86/2009-09-16-CoalescerBug.ll64
-rw-r--r--test/CodeGen/X86/2009-09-19-earlyclobber.ll15
-rw-r--r--test/CodeGen/X86/2009-09-21-NoSpillLoopCount.ll36
-rw-r--r--test/CodeGen/X86/2009-09-22-CoalescerBug.ll124
-rw-r--r--test/CodeGen/X86/2009-09-23-LiveVariablesBug.ll91
-rw-r--r--test/CodeGen/X86/2009-10-14-LiveVariablesBug.ll15
-rw-r--r--test/CodeGen/X86/2009-10-16-Scope.ll32
-rw-r--r--test/CodeGen/X86/2009-10-19-EmergencySpill.ll54
-rw-r--r--test/CodeGen/X86/2009-10-19-atomic-cmp-eflags.ll67
-rw-r--r--test/CodeGen/X86/2009-10-25-RewriterBug.ll171
-rw-r--r--test/CodeGen/X86/2009-11-04-SubregCoalescingBug.ll15
-rw-r--r--test/CodeGen/X86/2009-11-13-VirtRegRewriterBug.ll133
-rw-r--r--test/CodeGen/X86/2009-11-16-MachineLICM.ll42
-rw-r--r--test/CodeGen/X86/2009-11-16-UnfoldMemOpBug.ll28
-rw-r--r--test/CodeGen/X86/2009-11-17-UpdateTerminator.ll52
-rw-r--r--test/CodeGen/X86/2009-11-18-TwoAddrKill.ll29
-rw-r--r--test/CodeGen/X86/2009-11-25-ImpDefBug.ll120
-rw-r--r--test/CodeGen/X86/2009-12-01-EarlyClobberBug.ll41
-rw-r--r--test/CodeGen/X86/2009-12-11-TLSNoRedZone.ll63
-rw-r--r--test/CodeGen/X86/20090313-signext.ll19
-rw-r--r--test/CodeGen/X86/2010-01-05-ZExt-Shl.ll15
-rw-r--r--test/CodeGen/X86/2010-01-07-ISelBug.ll27
-rw-r--r--test/CodeGen/X86/2010-01-07-UAMemFeature.ll11
-rw-r--r--test/CodeGen/X86/2010-01-08-Atomic64Bug.ll23
-rw-r--r--test/CodeGen/X86/2010-01-11-ExtraPHIArg.ll97
-rw-r--r--test/CodeGen/X86/2010-01-13-OptExtBug.ll46
-rw-r--r--test/CodeGen/X86/2010-01-15-SelectionDAGCycle.ll28
-rw-r--r--test/CodeGen/X86/2010-01-18-DbgValue.ll48
-rw-r--r--test/CodeGen/X86/2010-01-19-OptExtBug.ll57
-rw-r--r--test/CodeGen/X86/2010-02-01-DbgValueCrash.ll33
-rw-r--r--test/CodeGen/X86/2010-02-01-TaillCallCrash.ll12
-rw-r--r--test/CodeGen/X86/2010-02-03-DualUndef.ll27
-rw-r--r--test/CodeGen/X86/2010-02-04-SchedulerBug.ll28
-rw-r--r--test/CodeGen/X86/2010-02-11-NonTemporal.ll22
-rw-r--r--test/CodeGen/X86/2010-02-12-CoalescerBug-Impdef.ll260
-rw-r--r--test/CodeGen/X86/2010-02-15-ImplicitDefBug.ll80
-rw-r--r--test/CodeGen/X86/2010-02-19-TailCallRetAddrBug.ll55
-rw-r--r--test/CodeGen/X86/2010-02-23-DAGCombineBug.ll18
-rw-r--r--test/CodeGen/X86/2010-02-23-DIV8rDefinesAX.ll20
-rw-r--r--test/CodeGen/X86/2010-02-23-RematImplicitSubreg.ll49
-rw-r--r--test/CodeGen/X86/2010-02-23-SingleDefPhiJoin.ll146
-rw-r--r--test/CodeGen/X86/2010-03-04-Mul8Bug.ll25
-rw-r--r--test/CodeGen/X86/2010-03-05-ConstantFoldCFG.ll42
-rw-r--r--test/CodeGen/X86/2010-03-05-EFLAGS-Redef.ll49
-rw-r--r--test/CodeGen/X86/2010-03-17-ISelBug.ll67
-rw-r--r--test/CodeGen/X86/2010-04-06-SSEDomainFixCrash.ll68
-rw-r--r--test/CodeGen/X86/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/X86/2010-04-08-CoalescerBug.ll26
-rw-r--r--test/CodeGen/X86/2010-04-13-AnalyzeBranchCrash.ll42
-rw-r--r--test/CodeGen/X86/2010-04-21-CoalescerBug.ll15
-rw-r--r--test/CodeGen/X86/2010-04-23-mmx-movdq2q.ll100
-rw-r--r--test/CodeGen/X86/2010-04-29-CoalescerCrash.ll142
-rw-r--r--test/CodeGen/X86/2010-04-30-LocalAlloc-LandingPad.ll140
-rw-r--r--test/CodeGen/X86/2010-05-03-CoalescerSubRegClobber.ll33
-rw-r--r--test/CodeGen/X86/2010-05-05-LocalAllocEarlyClobber.ll32
-rw-r--r--test/CodeGen/X86/2010-05-06-LocalInlineAsmClobber.ll10
-rw-r--r--test/CodeGen/X86/2010-05-07-ldconvert.ll27
-rw-r--r--test/CodeGen/X86/2010-05-10-DAGCombinerBug.ll11
-rw-r--r--test/CodeGen/X86/2010-05-12-FastAllocKills.ll59
-rw-r--r--test/CodeGen/X86/2010-05-16-nosseconversion.ll12
-rw-r--r--test/CodeGen/X86/2010-05-25-DotDebugLoc.ll245
-rw-r--r--test/CodeGen/X86/2010-05-26-DotDebugLoc.ll82
-rw-r--r--test/CodeGen/X86/2010-05-26-FP_TO_INT-crash.ll16
-rw-r--r--test/CodeGen/X86/2010-05-28-Crash.ll45
-rw-r--r--test/CodeGen/X86/2010-06-01-DeadArg-DbgInfo.ll54
-rw-r--r--test/CodeGen/X86/2010-06-09-FastAllocRegisters.ll17
-rw-r--r--test/CodeGen/X86/2010-06-14-fast-isel-fs-load.ll6
-rw-r--r--test/CodeGen/X86/2010-06-15-FastAllocEarlyCLobber.ll29
-rw-r--r--test/CodeGen/X86/2010-06-24-g-constraint-crash.ll15
-rw-r--r--test/CodeGen/X86/2010-06-25-CoalescerSubRegDefDead.ll39
-rw-r--r--test/CodeGen/X86/2010-06-25-asm-RA-crash.ll19
-rw-r--r--test/CodeGen/X86/2010-06-28-FastAllocTiedOperand.ll22
-rw-r--r--test/CodeGen/X86/2010-06-28-matched-g-constraint.ll11
-rw-r--r--test/CodeGen/X86/2010-07-02-UnfoldBug.ll99
-rw-r--r--test/CodeGen/X86/2010-07-02-asm-alignstack.ll31
-rw-r--r--test/CodeGen/X86/2010-07-06-DbgCrash.ll29
-rw-r--r--test/CodeGen/X86/2010-07-06-asm-RIP.ll21
-rw-r--r--test/CodeGen/X86/2010-07-11-FPStackLoneUse.ll28
-rw-r--r--test/CodeGen/X86/2010-07-13-indirectXconstraint.ll18
-rw-r--r--test/CodeGen/X86/2010-07-15-Crash.ll12
-rw-r--r--test/CodeGen/X86/2010-07-29-SetccSimplify.ll14
-rw-r--r--test/CodeGen/X86/2010-08-04-MaskedSignedCompare.ll36
-rw-r--r--test/CodeGen/X86/2010-08-04-MingWCrash.ll36
-rw-r--r--test/CodeGen/X86/2010-08-04-StackVariable.ll124
-rw-r--r--test/CodeGen/X86/2010-08-10-DbgConstant.ll25
-rw-r--r--test/CodeGen/X86/2010-09-01-RemoveCopyByCommutingDef.ll28
-rw-r--r--test/CodeGen/X86/2010-09-16-EmptyFilename.ll29
-rw-r--r--test/CodeGen/X86/2010-09-16-asmcrash.ll56
-rw-r--r--test/CodeGen/X86/2010-09-17-SideEffectsInChain.ll26
-rw-r--r--test/CodeGen/X86/2010-09-30-CMOV-JumpTable-PHI.ll71
-rw-r--r--test/CodeGen/X86/2010-10-08-cmpxchg8b.ll26
-rw-r--r--test/CodeGen/X86/2010-11-02-DbgParameter.ll35
-rw-r--r--test/CodeGen/X86/2010-11-09-MOVLPS.ll66
-rw-r--r--test/CodeGen/X86/2010-11-18-SelectOfExtload.ll15
-rw-r--r--test/CodeGen/X86/2010-12-02-MC-Set.ll22
-rw-r--r--test/CodeGen/X86/2011-01-07-LegalizeTypesCrash.ll19
-rw-r--r--test/CodeGen/X86/2011-01-10-DagCombineHang.ll15
-rw-r--r--test/CodeGen/X86/2011-01-24-DbgValue-Before-Use.ll103
-rw-r--r--test/CodeGen/X86/2011-02-04-FastRegallocNoFP.ll14
-rw-r--r--test/CodeGen/X86/2011-02-12-shuffle.ll32
-rw-r--r--test/CodeGen/X86/2011-02-21-VirtRegRewriter-KillSubReg.ll50
-rw-r--r--test/CodeGen/X86/2011-02-23-UnfoldBug.ll42
-rw-r--r--test/CodeGen/X86/2011-02-27-Fpextend.ll7
-rw-r--r--test/CodeGen/X86/2011-03-02-DAGCombiner.ll51
-rw-r--r--test/CodeGen/X86/2011-03-08-Sched-crash.ll56
-rw-r--r--test/CodeGen/X86/2011-03-09-Physreg-Coalescing.ll22
-rw-r--r--test/CodeGen/X86/2011-03-30-CreateFixedObjCrash.ll10
-rw-r--r--test/CodeGen/X86/2011-04-13-SchedCmpJmp.ll65
-rw-r--r--test/CodeGen/X86/2011-04-19-sclr-bb.ll21
-rw-r--r--test/CodeGen/X86/2011-05-09-loaduse.ll13
-rw-r--r--test/CodeGen/X86/2011-05-26-UnreachableBlockElim.ll53
-rw-r--r--test/CodeGen/X86/2011-05-27-CrossClassCoalescing.ll41
-rw-r--r--test/CodeGen/X86/2011-06-01-fildll.ll15
-rw-r--r--test/CodeGen/X86/2011-06-03-x87chain.ll31
-rw-r--r--test/CodeGen/X86/2011-06-06-fgetsign80bit.ll8
-rw-r--r--test/CodeGen/X86/2011-06-12-FastAllocSpill.ll52
-rw-r--r--test/CodeGen/X86/2011-06-14-PreschedRegalias.ll18
-rw-r--r--test/CodeGen/X86/2011-06-14-mmx-inlineasm.ll45
-rw-r--r--test/CodeGen/X86/2011-06-19-QuicksortCoalescerBug.ll31
-rw-r--r--test/CodeGen/X86/2011-07-13-BadFrameIndexDisplacement.ll20
-rw-r--r--test/CodeGen/X86/2011-08-23-PerformSubCombine128.ll18
-rw-r--r--test/CodeGen/X86/2011-08-23-Trampoline.ll16
-rw-r--r--test/CodeGen/X86/2011-08-29-BlockConstant.ll34
-rw-r--r--test/CodeGen/X86/2011-08-29-InitOrder.ll34
-rw-r--r--test/CodeGen/X86/2011-09-14-valcoalesce.ll174
-rw-r--r--test/CodeGen/X86/2011-09-18-sse2cmp.ll12
-rw-r--r--test/CodeGen/X86/2011-09-21-setcc-bug.ll27
-rw-r--r--test/CodeGen/X86/2011-10-11-SpillDead.ll19
-rw-r--r--test/CodeGen/X86/2011-10-11-srl.ll11
-rw-r--r--test/CodeGen/X86/2011-10-12-MachineCSE.ll116
-rw-r--r--test/CodeGen/X86/2011-10-18-FastISel-VectorParams.ll29
-rw-r--r--test/CodeGen/X86/2011-10-19-LegelizeLoad.ll28
-rw-r--r--test/CodeGen/X86/2011-10-19-widen_vselect.ll68
-rw-r--r--test/CodeGen/X86/2011-10-21-widen-cmp.ll45
-rw-r--r--test/CodeGen/X86/2011-10-27-tstore.ll16
-rw-r--r--test/CodeGen/X86/2011-10-30-padd.ll20
-rw-r--r--test/CodeGen/X86/2011-11-07-LegalizeBuildVector.ll14
-rw-r--r--test/CodeGen/X86/2011-11-22-AVX2-Domains.ll99
-rw-r--r--test/CodeGen/X86/2011-11-30-or.ll25
-rw-r--r--test/CodeGen/X86/2011-12-06-AVXVectorExtractCombine.ll18
-rw-r--r--test/CodeGen/X86/2011-12-06-BitcastVectorGlobal.ll5
-rw-r--r--test/CodeGen/X86/2011-12-08-AVXISelBugs.ll80
-rw-r--r--test/CodeGen/X86/2011-12-15-vec_shift.ll19
-rw-r--r--test/CodeGen/X86/2011-12-26-extractelement-duplicate-load.ll16
-rw-r--r--test/CodeGen/X86/2011-12-28-vselecti8.ll20
-rw-r--r--test/CodeGen/X86/2011-12-8-bitcastintprom.ll15
-rw-r--r--test/CodeGen/X86/2011-20-21-zext-ui2fp.ll19
-rw-r--r--test/CodeGen/X86/2012-01-10-UndefExceptionEdge.ll155
-rw-r--r--test/CodeGen/X86/2012-01-11-split-cv.ll12
-rw-r--r--test/CodeGen/X86/2012-01-12-extract-sv.ll12
-rw-r--r--test/CodeGen/X86/2012-01-16-mfence-nosse-flags.ll34
-rw-r--r--test/CodeGen/X86/2012-01-18-vbitcast.ll14
-rw-r--r--test/CodeGen/X86/2012-02-12-dagco.ll16
-rw-r--r--test/CodeGen/X86/2012-02-14-scalar.ll13
-rw-r--r--test/CodeGen/X86/2012-02-20-MachineCPBug.ll78
-rw-r--r--test/CodeGen/X86/2012-02-23-mmx-inlineasm.ll12
-rw-r--r--test/CodeGen/X86/2012-02-29-CoalescerBug.ll58
-rw-r--r--test/CodeGen/X86/2012-03-15-build_vector_wl.ll10
-rw-r--r--test/CodeGen/X86/2012-03-20-LargeConstantExpr.ll17
-rw-r--r--test/CodeGen/X86/2012-03-26-PostRALICMBug.ll59
-rw-r--r--test/CodeGen/X86/2012-04-09-TwoAddrPassBug.ll34
-rw-r--r--test/CodeGen/X86/2012-04-26-sdglue.ll47
-rw-r--r--test/CodeGen/X86/2012-05-17-TwoAddressBug.ll16
-rw-r--r--test/CodeGen/X86/2012-05-19-CoalescerCrash.ll122
-rw-r--r--test/CodeGen/X86/2012-05-19-avx2-store.ll13
-rw-r--r--test/CodeGen/X86/2012-07-10-extload64.ll32
-rw-r--r--test/CodeGen/X86/2012-07-10-shufnorm.ll17
-rw-r--r--test/CodeGen/X86/2012-07-15-broadcastfold.ll23
-rw-r--r--test/CodeGen/X86/2012-07-15-tconst_shl.ll9
-rw-r--r--test/CodeGen/X86/2012-07-15-vshl.ll31
-rw-r--r--test/CodeGen/X86/2012-07-16-LeaUndef.ll16
-rw-r--r--test/CodeGen/X86/2012-07-16-fp2ui-i1.ll12
-rw-r--r--test/CodeGen/X86/2012-07-17-vtrunc.ll16
-rw-r--r--test/CodeGen/X86/2012-07-23-select_cc.ll19
-rw-r--r--test/CodeGen/X86/2012-08-07-CmpISelBug.ll36
-rw-r--r--test/CodeGen/X86/2012-08-16-setcc.ll45
-rw-r--r--test/CodeGen/X86/2012-08-17-legalizer-crash.ll32
-rw-r--r--test/CodeGen/X86/2012-08-28-UnsafeMathCrash.ll20
-rw-r--r--test/CodeGen/X86/2012-09-13-dagco-fneg.ll21
-rw-r--r--test/CodeGen/X86/2012-1-10-buildvector.ll26
-rw-r--r--test/CodeGen/X86/3addr-16bit.ll95
-rw-r--r--test/CodeGen/X86/3addr-or.ll61
-rw-r--r--test/CodeGen/X86/3dnow-intrinsics.ll297
-rw-r--r--test/CodeGen/X86/4char-promote.ll18
-rw-r--r--test/CodeGen/X86/9601.ll12
-rw-r--r--test/CodeGen/X86/Atomics-64.ll950
-rw-r--r--test/CodeGen/X86/GC/alloc_loop.ll53
-rw-r--r--test/CodeGen/X86/GC/argpromotion.ll19
-rw-r--r--test/CodeGen/X86/GC/badreadproto.ll13
-rw-r--r--test/CodeGen/X86/GC/badrootproto.ll13
-rw-r--r--test/CodeGen/X86/GC/badwriteproto.ll22
-rw-r--r--test/CodeGen/X86/GC/cg-O0.ll17
-rw-r--r--test/CodeGen/X86/GC/deadargelim.ll16
-rw-r--r--test/CodeGen/X86/GC/fat.ll10
-rw-r--r--test/CodeGen/X86/GC/inline.ll23
-rw-r--r--test/CodeGen/X86/GC/inline2.ll24
-rw-r--r--test/CodeGen/X86/GC/lit.local.cfg6
-rw-r--r--test/CodeGen/X86/GC/lower_gcroot.ll11
-rw-r--r--test/CodeGen/X86/GC/outside.ll10
-rw-r--r--test/CodeGen/X86/MachineSink-CritEdge.ll58
-rw-r--r--test/CodeGen/X86/MachineSink-DbgValue.ll49
-rw-r--r--test/CodeGen/X86/MachineSink-PHIUse.ll39
-rw-r--r--test/CodeGen/X86/MachineSink-eflags.ll74
-rw-r--r--test/CodeGen/X86/StackColoring-dbg.ll30
-rw-r--r--test/CodeGen/X86/StackColoring.ll410
-rw-r--r--test/CodeGen/X86/SwitchLowering.ll28
-rw-r--r--test/CodeGen/X86/SwizzleShuff.ll68
-rw-r--r--test/CodeGen/X86/abi-isel.ll9660
-rw-r--r--test/CodeGen/X86/add-of-carry.ll33
-rw-r--r--test/CodeGen/X86/add.ll150
-rw-r--r--test/CodeGen/X86/adde-carry.ll20
-rw-r--r--test/CodeGen/X86/addr-label-difference.ll26
-rw-r--r--test/CodeGen/X86/aliases.ll36
-rw-r--r--test/CodeGen/X86/aligned-comm.ll6
-rw-r--r--test/CodeGen/X86/alignment-2.ll30
-rw-r--r--test/CodeGen/X86/alignment.ll43
-rw-r--r--test/CodeGen/X86/all-ones-vector.ll14
-rw-r--r--test/CodeGen/X86/alldiv-divdi3.ll17
-rw-r--r--test/CodeGen/X86/alloca-align-rounding-32.ll20
-rw-r--r--test/CodeGen/X86/alloca-align-rounding.ll20
-rw-r--r--test/CodeGen/X86/allrem-moddi3.ll19
-rw-r--r--test/CodeGen/X86/and-or-fold.ll26
-rw-r--r--test/CodeGen/X86/and-su.ll53
-rw-r--r--test/CodeGen/X86/andimm8.ll19
-rw-r--r--test/CodeGen/X86/anyext.ll18
-rw-r--r--test/CodeGen/X86/apm.ll35
-rw-r--r--test/CodeGen/X86/arg-cast.ll18
-rw-r--r--test/CodeGen/X86/asm-block-labels.ll41
-rw-r--r--test/CodeGen/X86/asm-global-imm.ll26
-rw-r--r--test/CodeGen/X86/asm-indirect-mem.ll11
-rw-r--r--test/CodeGen/X86/asm-label.ll40
-rw-r--r--test/CodeGen/X86/asm-label2.ll26
-rw-r--r--test/CodeGen/X86/asm-modifier-P.ll79
-rw-r--r--test/CodeGen/X86/asm-modifier.ll41
-rw-r--r--test/CodeGen/X86/asm-reg-type-mismatch.ll31
-rw-r--r--test/CodeGen/X86/atom-bypass-slow-division.ll112
-rw-r--r--test/CodeGen/X86/atom-lea-sp.ll48
-rw-r--r--test/CodeGen/X86/atom-sched.ll29
-rw-r--r--test/CodeGen/X86/atomic-load-store-wide.ll19
-rw-r--r--test/CodeGen/X86/atomic-load-store.ll23
-rw-r--r--test/CodeGen/X86/atomic-or.ll28
-rw-r--r--test/CodeGen/X86/atomic-pointer.ll22
-rw-r--r--test/CodeGen/X86/atomic_add.ll201
-rw-r--r--test/CodeGen/X86/atomic_op.ll139
-rw-r--r--test/CodeGen/X86/attribute-sections.ll18
-rw-r--r--test/CodeGen/X86/avoid-lea-scale2.ll10
-rw-r--r--test/CodeGen/X86/avoid-loop-align-2.ll49
-rw-r--r--test/CodeGen/X86/avoid-loop-align.ll39
-rw-r--r--test/CodeGen/X86/avx-arith.ll272
-rw-r--r--test/CodeGen/X86/avx-basic.ll123
-rw-r--r--test/CodeGen/X86/avx-bitcast.ll10
-rw-r--r--test/CodeGen/X86/avx-blend.ll104
-rw-r--r--test/CodeGen/X86/avx-cast.ll47
-rw-r--r--test/CodeGen/X86/avx-cmp.ll150
-rw-r--r--test/CodeGen/X86/avx-cvt.ll83
-rwxr-xr-xtest/CodeGen/X86/avx-fp2int.ll19
-rw-r--r--test/CodeGen/X86/avx-intrinsics-x86.ll2592
-rw-r--r--test/CodeGen/X86/avx-intrinsics-x86_64.ll50
-rw-r--r--test/CodeGen/X86/avx-load-store.ll111
-rw-r--r--test/CodeGen/X86/avx-logic.ll199
-rw-r--r--test/CodeGen/X86/avx-minmax.ll65
-rw-r--r--test/CodeGen/X86/avx-movdup.ll34
-rw-r--r--test/CodeGen/X86/avx-select.ll22
-rwxr-xr-xtest/CodeGen/X86/avx-sext.ll17
-rw-r--r--test/CodeGen/X86/avx-shift.ll138
-rwxr-xr-xtest/CodeGen/X86/avx-shuffle-x86_32.ll8
-rw-r--r--test/CodeGen/X86/avx-shuffle.ll248
-rw-r--r--test/CodeGen/X86/avx-splat.ll103
-rwxr-xr-xtest/CodeGen/X86/avx-trunc.ll15
-rw-r--r--test/CodeGen/X86/avx-unpack.ll161
-rw-r--r--test/CodeGen/X86/avx-varargs-x86_64.ll15
-rw-r--r--test/CodeGen/X86/avx-vbroadcast.ll143
-rw-r--r--test/CodeGen/X86/avx-vextractf128.ll104
-rw-r--r--test/CodeGen/X86/avx-vinsertf128.ll131
-rw-r--r--test/CodeGen/X86/avx-vmovddup.ll14
-rw-r--r--test/CodeGen/X86/avx-vperm2f128.ll69
-rw-r--r--test/CodeGen/X86/avx-vpermil.ll54
-rw-r--r--test/CodeGen/X86/avx-vshufp.ll157
-rw-r--r--test/CodeGen/X86/avx-vzeroupper.ll83
-rwxr-xr-xtest/CodeGen/X86/avx-win64-args.ll18
-rw-r--r--test/CodeGen/X86/avx-win64.ll47
-rwxr-xr-xtest/CodeGen/X86/avx-zext.ll30
-rw-r--r--test/CodeGen/X86/avx2-arith.ll76
-rw-r--r--test/CodeGen/X86/avx2-cmp.ll58
-rwxr-xr-xtest/CodeGen/X86/avx2-conversions.ll68
-rw-r--r--test/CodeGen/X86/avx2-intrinsics-x86.ll1157
-rw-r--r--test/CodeGen/X86/avx2-logic.ll96
-rw-r--r--test/CodeGen/X86/avx2-nontemporal.ll22
-rw-r--r--test/CodeGen/X86/avx2-palignr.ll57
-rw-r--r--test/CodeGen/X86/avx2-phaddsub.ll73
-rw-r--r--test/CodeGen/X86/avx2-shift.ll268
-rw-r--r--test/CodeGen/X86/avx2-shuffle.ll62
-rw-r--r--test/CodeGen/X86/avx2-unpack.ll86
-rw-r--r--test/CodeGen/X86/avx2-vbroadcast.ll357
-rwxr-xr-xtest/CodeGen/X86/avx2-vperm.ll34
-rw-r--r--test/CodeGen/X86/avx2-vperm2i128.ll47
-rw-r--r--test/CodeGen/X86/barrier-sse.ll11
-rw-r--r--test/CodeGen/X86/barrier.ll6
-rw-r--r--test/CodeGen/X86/basic-promote-integers.ll98
-rw-r--r--test/CodeGen/X86/bc-extract.ll27
-rw-r--r--test/CodeGen/X86/bigstructret.ll34
-rw-r--r--test/CodeGen/X86/bigstructret2.ll12
-rw-r--r--test/CodeGen/X86/bit-test-shift.ll13
-rw-r--r--test/CodeGen/X86/bitcast-i256.ll11
-rw-r--r--test/CodeGen/X86/bitcast-int-to-vector.ll10
-rw-r--r--test/CodeGen/X86/bitcast.ll24
-rw-r--r--test/CodeGen/X86/bitcast2.ll13
-rw-r--r--test/CodeGen/X86/blend-msb.ll37
-rw-r--r--test/CodeGen/X86/block-placement.ll1091
-rw-r--r--test/CodeGen/X86/bmi.ll199
-rw-r--r--test/CodeGen/X86/bool-simplify.ll58
-rw-r--r--test/CodeGen/X86/bool-zext.ll47
-rw-r--r--test/CodeGen/X86/br-fold.ll20
-rw-r--r--test/CodeGen/X86/brcond.ll110
-rw-r--r--test/CodeGen/X86/break-anti-dependencies.ll36
-rw-r--r--test/CodeGen/X86/break-sse-dep.ll62
-rw-r--r--test/CodeGen/X86/bss_pagealigned.ll21
-rw-r--r--test/CodeGen/X86/bswap-inline-asm.ll87
-rw-r--r--test/CodeGen/X86/bswap.ll59
-rw-r--r--test/CodeGen/X86/bt.ll442
-rw-r--r--test/CodeGen/X86/btq.ll35
-rw-r--r--test/CodeGen/X86/byval-align.ll59
-rw-r--r--test/CodeGen/X86/byval.ll17
-rw-r--r--test/CodeGen/X86/byval2.ll45
-rw-r--r--test/CodeGen/X86/byval3.ll53
-rw-r--r--test/CodeGen/X86/byval4.ll59
-rw-r--r--test/CodeGen/X86/byval5.ll67
-rw-r--r--test/CodeGen/X86/byval6.ll16
-rw-r--r--test/CodeGen/X86/byval7.ll21
-rw-r--r--test/CodeGen/X86/call-imm.ll18
-rw-r--r--test/CodeGen/X86/call-push.ll45
-rw-r--r--test/CodeGen/X86/cfstring.ll36
-rw-r--r--test/CodeGen/X86/change-compare-stride-1.ll96
-rw-r--r--test/CodeGen/X86/change-compare-stride-trickiness-0.ll29
-rw-r--r--test/CodeGen/X86/change-compare-stride-trickiness-1.ll31
-rw-r--r--test/CodeGen/X86/change-compare-stride-trickiness-2.ll58
-rw-r--r--test/CodeGen/X86/clz.ll141
-rw-r--r--test/CodeGen/X86/cmov-into-branch.ll63
-rw-r--r--test/CodeGen/X86/cmov.ll157
-rw-r--r--test/CodeGen/X86/cmp.ll153
-rw-r--r--test/CodeGen/X86/cmpxchg16b.ll13
-rw-r--r--test/CodeGen/X86/coalesce-esp.ll36
-rw-r--r--test/CodeGen/X86/coalescer-commute1.ll26
-rw-r--r--test/CodeGen/X86/coalescer-commute2.ll28
-rw-r--r--test/CodeGen/X86/coalescer-commute3.ll24
-rw-r--r--test/CodeGen/X86/coalescer-commute4.ll30
-rw-r--r--test/CodeGen/X86/coalescer-commute5.ll21
-rw-r--r--test/CodeGen/X86/coalescer-cross.ll45
-rw-r--r--test/CodeGen/X86/coalescer-dce.ll80
-rw-r--r--test/CodeGen/X86/coalescer-dce2.ll118
-rw-r--r--test/CodeGen/X86/coalescer-identity.ll82
-rw-r--r--test/CodeGen/X86/coalescer-remat.ll13
-rw-r--r--test/CodeGen/X86/code_placement.ll136
-rw-r--r--test/CodeGen/X86/code_placement_eh.ll45
-rw-r--r--test/CodeGen/X86/codegen-prepare-cast.ll24
-rw-r--r--test/CodeGen/X86/codegen-prepare-extload.ll21
-rw-r--r--test/CodeGen/X86/codemodel.ll67
-rw-r--r--test/CodeGen/X86/combine-lds.ll6
-rw-r--r--test/CodeGen/X86/combiner-aa-0.ll20
-rw-r--r--test/CodeGen/X86/combiner-aa-1.ll23
-rw-r--r--test/CodeGen/X86/commute-intrinsic.ll15
-rw-r--r--test/CodeGen/X86/commute-two-addr.ll62
-rw-r--r--test/CodeGen/X86/compare-add.ll8
-rw-r--r--test/CodeGen/X86/compare-inf.ll76
-rw-r--r--test/CodeGen/X86/compare_folding.ll11
-rw-r--r--test/CodeGen/X86/compiler_used.ll9
-rw-r--r--test/CodeGen/X86/complex-asm.ll17
-rw-r--r--test/CodeGen/X86/complex-fca.ll14
-rw-r--r--test/CodeGen/X86/conditional-indecrement.ll89
-rw-r--r--test/CodeGen/X86/constant-pool-remat-0.ll22
-rw-r--r--test/CodeGen/X86/constant-pool-sharing.ll20
-rw-r--r--test/CodeGen/X86/constpool.ll16
-rw-r--r--test/CodeGen/X86/constructor.ll27
-rw-r--r--test/CodeGen/X86/convert-2-addr-3-addr-inc64.ll26
-rw-r--r--test/CodeGen/X86/copysign-zero.ll14
-rw-r--r--test/CodeGen/X86/crash-O0.ll31
-rw-r--r--test/CodeGen/X86/crash-nosse.ll27
-rw-r--r--test/CodeGen/X86/crash.ll444
-rw-r--r--test/CodeGen/X86/critical-edge-split-2.ll29
-rw-r--r--test/CodeGen/X86/cstring.ll4
-rw-r--r--test/CodeGen/X86/ctpop-combine.ll40
-rw-r--r--test/CodeGen/X86/dag-rauw-cse.ll13
-rw-r--r--test/CodeGen/X86/dagcombine-buildvector.ll27
-rw-r--r--test/CodeGen/X86/dagcombine-cse.ll27
-rw-r--r--test/CodeGen/X86/darwin-bzero.ll8
-rw-r--r--test/CodeGen/X86/darwin-no-dead-strip.ll7
-rw-r--r--test/CodeGen/X86/darwin-quote.ll15
-rw-r--r--test/CodeGen/X86/darwin-stub.ll12
-rw-r--r--test/CodeGen/X86/dbg-at-specficiation.ll20
-rw-r--r--test/CodeGen/X86/dbg-byval-parameter.ll45
-rw-r--r--test/CodeGen/X86/dbg-const-int.ll29
-rw-r--r--test/CodeGen/X86/dbg-const.ll34
-rw-r--r--test/CodeGen/X86/dbg-declare-arg.ll123
-rw-r--r--test/CodeGen/X86/dbg-declare.ll57
-rw-r--r--test/CodeGen/X86/dbg-file-name.ll19
-rw-r--r--test/CodeGen/X86/dbg-i128-const.ll26
-rw-r--r--test/CodeGen/X86/dbg-large-unsigned-const.ll61
-rw-r--r--test/CodeGen/X86/dbg-merge-loc-entry.ll75
-rw-r--r--test/CodeGen/X86/dbg-prolog-end.ll55
-rw-r--r--test/CodeGen/X86/dbg-subrange.ll37
-rw-r--r--test/CodeGen/X86/dbg-value-dag-combine.ll48
-rw-r--r--test/CodeGen/X86/dbg-value-inlined-parameter.ll87
-rw-r--r--test/CodeGen/X86/dbg-value-isel.ll102
-rw-r--r--test/CodeGen/X86/dbg-value-location.ll70
-rw-r--r--test/CodeGen/X86/dbg-value-range.ll61
-rw-r--r--test/CodeGen/X86/discontiguous-loops.ll72
-rw-r--r--test/CodeGen/X86/div8.ll22
-rw-r--r--test/CodeGen/X86/divide-by-constant.ll94
-rw-r--r--test/CodeGen/X86/divrem.ll58
-rw-r--r--test/CodeGen/X86/dll-linkage.ll14
-rw-r--r--test/CodeGen/X86/dllexport.ll12
-rw-r--r--test/CodeGen/X86/dollar-name.ll18
-rw-r--r--test/CodeGen/X86/dwarf-comp-dir.ll16
-rw-r--r--test/CodeGen/X86/dyn-stackalloc.ll19
-rw-r--r--test/CodeGen/X86/dynamic-allocas-VLAs.ll237
-rw-r--r--test/CodeGen/X86/early-ifcvt.ll69
-rw-r--r--test/CodeGen/X86/eh_frame.ll14
-rw-r--r--test/CodeGen/X86/empty-functions.ll25
-rw-r--r--test/CodeGen/X86/empty-struct-return-type.ll15
-rw-r--r--test/CodeGen/X86/epilogue.ll13
-rw-r--r--test/CodeGen/X86/extend.ll18
-rw-r--r--test/CodeGen/X86/extern_weak.ll13
-rw-r--r--test/CodeGen/X86/extmul128.ll14
-rw-r--r--test/CodeGen/X86/extmul64.ll14
-rw-r--r--test/CodeGen/X86/extract-combine.ll15
-rw-r--r--test/CodeGen/X86/extract-extract.ll24
-rw-r--r--test/CodeGen/X86/extractelement-from-arg.ll7
-rw-r--r--test/CodeGen/X86/extractelement-load.ll25
-rw-r--r--test/CodeGen/X86/extractelement-shuffle.ll13
-rw-r--r--test/CodeGen/X86/extractps.ll27
-rw-r--r--test/CodeGen/X86/f16c-intrinsics.ll32
-rw-r--r--test/CodeGen/X86/fabs.ll54
-rw-r--r--test/CodeGen/X86/fast-cc-callee-pops.ll13
-rw-r--r--test/CodeGen/X86/fast-cc-merge-stack-adj.ll13
-rw-r--r--test/CodeGen/X86/fast-cc-pass-in-regs.ll29
-rw-r--r--test/CodeGen/X86/fast-isel-agg-constant.ll11
-rw-r--r--test/CodeGen/X86/fast-isel-atomic.ll15
-rw-r--r--test/CodeGen/X86/fast-isel-avoid-unnecessary-pic-base.ll23
-rw-r--r--test/CodeGen/X86/fast-isel-bail.ll14
-rw-r--r--test/CodeGen/X86/fast-isel-bc.ll23
-rw-r--r--test/CodeGen/X86/fast-isel-call.ll55
-rw-r--r--test/CodeGen/X86/fast-isel-cmp-branch.ll34
-rw-r--r--test/CodeGen/X86/fast-isel-constpool.ll17
-rw-r--r--test/CodeGen/X86/fast-isel-extract.ll48
-rw-r--r--test/CodeGen/X86/fast-isel-fneg.ll16
-rw-r--r--test/CodeGen/X86/fast-isel-gep.ll138
-rw-r--r--test/CodeGen/X86/fast-isel-gv.ll24
-rw-r--r--test/CodeGen/X86/fast-isel-i1.ll41
-rw-r--r--test/CodeGen/X86/fast-isel-mem.ll46
-rw-r--r--test/CodeGen/X86/fast-isel-ret-ext.ll38
-rw-r--r--test/CodeGen/X86/fast-isel-tailcall.ll13
-rw-r--r--test/CodeGen/X86/fast-isel-tls.ll26
-rw-r--r--test/CodeGen/X86/fast-isel-x86-64.ll293
-rw-r--r--test/CodeGen/X86/fast-isel-x86.ll62
-rw-r--r--test/CodeGen/X86/fast-isel.ll127
-rw-r--r--test/CodeGen/X86/fastcall-correct-mangling.ll9
-rw-r--r--test/CodeGen/X86/fastcc-2.ll10
-rw-r--r--test/CodeGen/X86/fastcc-byval.ll20
-rw-r--r--test/CodeGen/X86/fastcc-sret.ll23
-rw-r--r--test/CodeGen/X86/fastcc.ll20
-rw-r--r--test/CodeGen/X86/fastcc3struct.ll15
-rw-r--r--test/CodeGen/X86/fdiv.ll41
-rw-r--r--test/CodeGen/X86/field-extract-use-trunc.ll39
-rw-r--r--test/CodeGen/X86/fildll.ll12
-rw-r--r--test/CodeGen/X86/fltused.ll21
-rw-r--r--test/CodeGen/X86/fltused_function_pointer.ll19
-rw-r--r--test/CodeGen/X86/fma.ll39
-rwxr-xr-xtest/CodeGen/X86/fma3-intrinsics.ll134
-rw-r--r--test/CodeGen/X86/fma4-intrinsics-x86_64.ll296
-rw-r--r--test/CodeGen/X86/fma_patterns.ll212
-rw-r--r--test/CodeGen/X86/fmul-zero.ll9
-rw-r--r--test/CodeGen/X86/fold-add.ll30
-rw-r--r--test/CodeGen/X86/fold-and-shift.ll77
-rw-r--r--test/CodeGen/X86/fold-call-2.ll10
-rw-r--r--test/CodeGen/X86/fold-call-3.ll45
-rw-r--r--test/CodeGen/X86/fold-call.ll10
-rw-r--r--test/CodeGen/X86/fold-imm.ll14
-rw-r--r--test/CodeGen/X86/fold-load.ll73
-rw-r--r--test/CodeGen/X86/fold-mul-lohi.ll31
-rw-r--r--test/CodeGen/X86/fold-pcmpeqd-0.ll117
-rw-r--r--test/CodeGen/X86/fold-pcmpeqd-1.ll16
-rw-r--r--test/CodeGen/X86/fold-pcmpeqd-2.ll93
-rw-r--r--test/CodeGen/X86/fold-sext-trunc.ll20
-rw-r--r--test/CodeGen/X86/fold-xmm-zero.ll34
-rw-r--r--test/CodeGen/X86/fold-zext-trunc.ll23
-rw-r--r--test/CodeGen/X86/force-align-stack-alloca.ll70
-rw-r--r--test/CodeGen/X86/force-align-stack.ll21
-rw-r--r--test/CodeGen/X86/fp-elim.ll44
-rw-r--r--test/CodeGen/X86/fp-fast.ll37
-rw-r--r--test/CodeGen/X86/fp-immediate-shorten.ll9
-rw-r--r--test/CodeGen/X86/fp-in-intregs.ll22
-rw-r--r--test/CodeGen/X86/fp-stack-2results.ll66
-rw-r--r--test/CodeGen/X86/fp-stack-O0-crash.ll49
-rw-r--r--test/CodeGen/X86/fp-stack-O0.ll24
-rw-r--r--test/CodeGen/X86/fp-stack-compare-cmov.ll12
-rw-r--r--test/CodeGen/X86/fp-stack-compare.ll14
-rw-r--r--test/CodeGen/X86/fp-stack-direct-ret.ll11
-rw-r--r--test/CodeGen/X86/fp-stack-ret-conv.ll17
-rw-r--r--test/CodeGen/X86/fp-stack-ret-store.ll26
-rw-r--r--test/CodeGen/X86/fp-stack-ret.ll40
-rw-r--r--test/CodeGen/X86/fp-stack-retcopy.ll12
-rw-r--r--test/CodeGen/X86/fp-stack-set-st1.ll7
-rw-r--r--test/CodeGen/X86/fp-stack.ll25
-rw-r--r--test/CodeGen/X86/fp-trunc.ll35
-rw-r--r--test/CodeGen/X86/fp2sint.ll18
-rw-r--r--test/CodeGen/X86/fp_constant_op.ll46
-rw-r--r--test/CodeGen/X86/fp_load_cast_fold.ll20
-rw-r--r--test/CodeGen/X86/fp_load_fold.ll40
-rw-r--r--test/CodeGen/X86/fsgsbase.ll57
-rw-r--r--test/CodeGen/X86/fsxor-alignment.ll14
-rw-r--r--test/CodeGen/X86/full-lsr.ll42
-rw-r--r--test/CodeGen/X86/ga-offset.ll18
-rw-r--r--test/CodeGen/X86/gather-addresses.ll41
-rw-r--r--test/CodeGen/X86/gcc_except_table.ll27
-rw-r--r--test/CodeGen/X86/ghc-cc.ll45
-rw-r--r--test/CodeGen/X86/ghc-cc64.ll86
-rw-r--r--test/CodeGen/X86/global-sections-tls.ll14
-rw-r--r--test/CodeGen/X86/global-sections.ll160
-rw-r--r--test/CodeGen/X86/gs-fold.ll20
-rw-r--r--test/CodeGen/X86/h-register-addressing-32.ll53
-rw-r--r--test/CodeGen/X86/h-register-addressing-64.ll53
-rw-r--r--test/CodeGen/X86/h-register-store.ll47
-rw-r--r--test/CodeGen/X86/h-registers-0.ll106
-rw-r--r--test/CodeGen/X86/h-registers-1.ll39
-rw-r--r--test/CodeGen/X86/h-registers-2.ll20
-rw-r--r--test/CodeGen/X86/h-registers-3.ll12
-rw-r--r--test/CodeGen/X86/haddsub.ll285
-rw-r--r--test/CodeGen/X86/hidden-vis-2.ll10
-rw-r--r--test/CodeGen/X86/hidden-vis-3.ll19
-rw-r--r--test/CodeGen/X86/hidden-vis-4.ll12
-rw-r--r--test/CodeGen/X86/hidden-vis-pic.ll55
-rw-r--r--test/CodeGen/X86/hidden-vis.ll31
-rw-r--r--test/CodeGen/X86/hoist-common.ll28
-rw-r--r--test/CodeGen/X86/hoist-invariant-load.ll29
-rw-r--r--test/CodeGen/X86/i128-and-beyond.ll8
-rw-r--r--test/CodeGen/X86/i128-immediate.ll5
-rw-r--r--test/CodeGen/X86/i128-mul.ll12
-rw-r--r--test/CodeGen/X86/i128-ret.ll10
-rw-r--r--test/CodeGen/X86/i128-sdiv.ll24
-rw-r--r--test/CodeGen/X86/i256-add.ll18
-rw-r--r--test/CodeGen/X86/i2k.ll9
-rw-r--r--test/CodeGen/X86/i64-mem-copy.ll17
-rw-r--r--test/CodeGen/X86/iabs.ll20
-rw-r--r--test/CodeGen/X86/illegal-insert.ll18
-rw-r--r--test/CodeGen/X86/illegal-vector-args-return.ll14
-rw-r--r--test/CodeGen/X86/imul-lea-2.ll15
-rw-r--r--test/CodeGen/X86/imul-lea.ll10
-rw-r--r--test/CodeGen/X86/inline-asm-2addr.ll9
-rw-r--r--test/CodeGen/X86/inline-asm-R-constraint.ll18
-rw-r--r--test/CodeGen/X86/inline-asm-error.ll15
-rw-r--r--test/CodeGen/X86/inline-asm-flag-clobber.ll19
-rw-r--r--test/CodeGen/X86/inline-asm-fpstack.ll342
-rw-r--r--test/CodeGen/X86/inline-asm-h.ll12
-rw-r--r--test/CodeGen/X86/inline-asm-modifier-n.ll8
-rw-r--r--test/CodeGen/X86/inline-asm-mrv.ll35
-rw-r--r--test/CodeGen/X86/inline-asm-out-regs.ll40
-rw-r--r--test/CodeGen/X86/inline-asm-pic.ll10
-rw-r--r--test/CodeGen/X86/inline-asm-ptr-cast.ll27
-rw-r--r--test/CodeGen/X86/inline-asm-q-regs.ll37
-rw-r--r--test/CodeGen/X86/inline-asm-tied.ll30
-rw-r--r--test/CodeGen/X86/inline-asm-x-scalar.ll24
-rw-r--r--test/CodeGen/X86/inline-asm.ll54
-rw-r--r--test/CodeGen/X86/inreg.ll46
-rw-r--r--test/CodeGen/X86/ins_subreg_coalesce-1.ll30
-rw-r--r--test/CodeGen/X86/ins_subreg_coalesce-2.ll7
-rw-r--r--test/CodeGen/X86/ins_subreg_coalesce-3.ll92
-rw-r--r--test/CodeGen/X86/insert-positions.ll69
-rw-r--r--test/CodeGen/X86/insertelement-copytoregs.ll11
-rw-r--r--test/CodeGen/X86/insertelement-legalize.ll10
-rw-r--r--test/CodeGen/X86/int-intrinsic.ll20
-rw-r--r--test/CodeGen/X86/invalid-shift-immediate.ll30
-rw-r--r--test/CodeGen/X86/isel-sink.ll22
-rw-r--r--test/CodeGen/X86/isel-sink2.ll17
-rw-r--r--test/CodeGen/X86/isel-sink3.ll27
-rw-r--r--test/CodeGen/X86/isint.ll34
-rw-r--r--test/CodeGen/X86/isnan.ll9
-rw-r--r--test/CodeGen/X86/isnan2.ll11
-rw-r--r--test/CodeGen/X86/ispositive.ll9
-rw-r--r--test/CodeGen/X86/jump_sign.ll280
-rw-r--r--test/CodeGen/X86/label-redefinition.ll15
-rw-r--r--test/CodeGen/X86/large-gep-scale.ll12
-rw-r--r--test/CodeGen/X86/large-global.ll11
-rw-r--r--test/CodeGen/X86/ldzero.ll43
-rw-r--r--test/CodeGen/X86/lea-2.ll13
-rw-r--r--test/CodeGen/X86/lea-3.ll22
-rw-r--r--test/CodeGen/X86/lea-4.ll19
-rw-r--r--test/CodeGen/X86/lea-recursion.ll47
-rw-r--r--test/CodeGen/X86/lea.ll35
-rw-r--r--test/CodeGen/X86/leaf-fp-elim.ll30
-rw-r--r--test/CodeGen/X86/legalize-fmp-oeq-vector-select.ll11
-rw-r--r--test/CodeGen/X86/legalize-libcalls.ll35
-rw-r--r--test/CodeGen/X86/legalize-shift-64.ll56
-rw-r--r--test/CodeGen/X86/legalize-sub-zero-2.ll41
-rw-r--r--test/CodeGen/X86/legalize-sub-zero.ll35
-rw-r--r--test/CodeGen/X86/legalizedag_vec.ll17
-rw-r--r--test/CodeGen/X86/lfence.ll8
-rw-r--r--test/CodeGen/X86/licm-dominance.ll36
-rw-r--r--test/CodeGen/X86/licm-nested.ll89
-rw-r--r--test/CodeGen/X86/licm-symbol.ll39
-rw-r--r--test/CodeGen/X86/limited-prec.ll60
-rw-r--r--test/CodeGen/X86/lit.local.cfg6
-rw-r--r--test/CodeGen/X86/live-out-reg-info.ll20
-rw-r--r--test/CodeGen/X86/liveness-local-regalloc.ll92
-rw-r--r--test/CodeGen/X86/lock-inst-encoding.ll44
-rw-r--r--test/CodeGen/X86/log2_not_readnone.ll15
-rw-r--r--test/CodeGen/X86/long-setcc.ll18
-rw-r--r--test/CodeGen/X86/longlong-deadload.ll14
-rw-r--r--test/CodeGen/X86/loop-blocks.ll214
-rw-r--r--test/CodeGen/X86/loop-hoist.ll27
-rw-r--r--test/CodeGen/X86/loop-strength-reduce-2.ll45
-rw-r--r--test/CodeGen/X86/loop-strength-reduce-3.ll33
-rw-r--r--test/CodeGen/X86/loop-strength-reduce.ll33
-rw-r--r--test/CodeGen/X86/loop-strength-reduce2.ll30
-rw-r--r--test/CodeGen/X86/loop-strength-reduce4.ll63
-rw-r--r--test/CodeGen/X86/loop-strength-reduce5.ll23
-rw-r--r--test/CodeGen/X86/loop-strength-reduce6.ll66
-rw-r--r--test/CodeGen/X86/loop-strength-reduce7.ll44
-rw-r--r--test/CodeGen/X86/loop-strength-reduce8.ll84
-rw-r--r--test/CodeGen/X86/lsr-delayed-fold.ll178
-rw-r--r--test/CodeGen/X86/lsr-i386.ll44
-rw-r--r--test/CodeGen/X86/lsr-interesting-step.ll51
-rw-r--r--test/CodeGen/X86/lsr-loop-exit-cond.ll193
-rw-r--r--test/CodeGen/X86/lsr-negative-stride.ll51
-rw-r--r--test/CodeGen/X86/lsr-nonaffine.ll30
-rw-r--r--test/CodeGen/X86/lsr-normalization.ll99
-rw-r--r--test/CodeGen/X86/lsr-overflow.ll45
-rw-r--r--test/CodeGen/X86/lsr-quadratic-expand.ll22
-rw-r--r--test/CodeGen/X86/lsr-redundant-addressing.ll51
-rw-r--r--test/CodeGen/X86/lsr-reuse-trunc.ll62
-rw-r--r--test/CodeGen/X86/lsr-reuse.ll752
-rw-r--r--test/CodeGen/X86/lsr-sort.ll23
-rw-r--r--test/CodeGen/X86/lsr-static-addr.ll41
-rw-r--r--test/CodeGen/X86/lsr-wrap.ll37
-rw-r--r--test/CodeGen/X86/lzcnt.ll62
-rw-r--r--test/CodeGen/X86/machine-cp.ll36
-rw-r--r--test/CodeGen/X86/machine-cse.ll158
-rw-r--r--test/CodeGen/X86/masked-iv-safe.ll244
-rw-r--r--test/CodeGen/X86/masked-iv-unsafe.ll386
-rw-r--r--test/CodeGen/X86/maskmovdqu.ll11
-rw-r--r--test/CodeGen/X86/mcinst-avx-lowering.ll19
-rw-r--r--test/CodeGen/X86/mcinst-lowering.ll26
-rw-r--r--test/CodeGen/X86/mem-promote-integers.ll391
-rw-r--r--test/CodeGen/X86/membarrier.ll12
-rw-r--r--test/CodeGen/X86/memcmp.ll114
-rw-r--r--test/CodeGen/X86/memcpy-2.ll167
-rw-r--r--test/CodeGen/X86/memcpy.ll94
-rw-r--r--test/CodeGen/X86/memset-2.ll39
-rw-r--r--test/CodeGen/X86/memset-3.ll12
-rw-r--r--test/CodeGen/X86/memset.ll18
-rw-r--r--test/CodeGen/X86/memset64-on-x86-32.ll11
-rw-r--r--test/CodeGen/X86/mfence.ll8
-rw-r--r--test/CodeGen/X86/mingw-alloca.ll30
-rw-r--r--test/CodeGen/X86/misaligned-memset.ll15
-rw-r--r--test/CodeGen/X86/misched-new.ll27
-rw-r--r--test/CodeGen/X86/mmx-arg-passing.ll27
-rw-r--r--test/CodeGen/X86/mmx-arg-passing2.ll28
-rw-r--r--test/CodeGen/X86/mmx-arith.ll309
-rw-r--r--test/CodeGen/X86/mmx-bitcast-to-i64.ll31
-rw-r--r--test/CodeGen/X86/mmx-builtins.ll1325
-rw-r--r--test/CodeGen/X86/mmx-copy-gprs.ll17
-rw-r--r--test/CodeGen/X86/mmx-emms.ll11
-rw-r--r--test/CodeGen/X86/mmx-insert-element.ll9
-rw-r--r--test/CodeGen/X86/mmx-pinsrw.ll15
-rw-r--r--test/CodeGen/X86/mmx-punpckhdq.ll31
-rw-r--r--test/CodeGen/X86/mmx-s2v.ll15
-rw-r--r--test/CodeGen/X86/mmx-shift.ll32
-rw-r--r--test/CodeGen/X86/mmx-shuffle.ll31
-rw-r--r--test/CodeGen/X86/movbe.ll36
-rw-r--r--test/CodeGen/X86/movfs.ll8
-rw-r--r--test/CodeGen/X86/movgs.ll74
-rw-r--r--test/CodeGen/X86/movmsk.ll126
-rw-r--r--test/CodeGen/X86/movntdq-no-avx.ll12
-rw-r--r--test/CodeGen/X86/ms-inline-asm.ll26
-rw-r--r--test/CodeGen/X86/mul-legalize.ll24
-rw-r--r--test/CodeGen/X86/mul-remat.ll8
-rw-r--r--test/CodeGen/X86/mul-shift-reassoc.ll12
-rw-r--r--test/CodeGen/X86/mul128.ll6
-rw-r--r--test/CodeGen/X86/mul64.ll6
-rw-r--r--test/CodeGen/X86/muloti.ll81
-rw-r--r--test/CodeGen/X86/mult-alt-generic-i686.ll321
-rw-r--r--test/CodeGen/X86/mult-alt-generic-x86_64.ll321
-rw-r--r--test/CodeGen/X86/mult-alt-x86.ll358
-rw-r--r--test/CodeGen/X86/multiple-loop-post-inc.ll308
-rw-r--r--test/CodeGen/X86/multiple-return-values-cross-block.ll15
-rw-r--r--test/CodeGen/X86/nancvt.ll183
-rw-r--r--test/CodeGen/X86/narrow-shl-cst.ll101
-rw-r--r--test/CodeGen/X86/narrow-shl-load.ll83
-rw-r--r--test/CodeGen/X86/narrow_op-1.ll23
-rw-r--r--test/CodeGen/X86/neg-shl-add.ll17
-rw-r--r--test/CodeGen/X86/neg_cmp.ll22
-rw-r--r--test/CodeGen/X86/neg_fp.ll12
-rw-r--r--test/CodeGen/X86/negate-add-zero.ll1141
-rw-r--r--test/CodeGen/X86/negative-sin.ll12
-rw-r--r--test/CodeGen/X86/negative-stride-fptosi-user.ll25
-rw-r--r--test/CodeGen/X86/negative-subscript.ll10
-rw-r--r--test/CodeGen/X86/negative_zero.ll6
-rw-r--r--test/CodeGen/X86/no-cfi.ll34
-rw-r--r--test/CodeGen/X86/nobt.ll70
-rw-r--r--test/CodeGen/X86/non-lazy-bind.ll27
-rw-r--r--test/CodeGen/X86/nontemporal.ll22
-rw-r--r--test/CodeGen/X86/norex-subreg.ll80
-rw-r--r--test/CodeGen/X86/nosse-error1.ll33
-rw-r--r--test/CodeGen/X86/nosse-error2.ll33
-rw-r--r--test/CodeGen/X86/nosse-varargs.ll46
-rw-r--r--test/CodeGen/X86/null-streamer.ll11
-rw-r--r--test/CodeGen/X86/objc-gc-module-flags.ll13
-rw-r--r--test/CodeGen/X86/object-size.ll55
-rw-r--r--test/CodeGen/X86/odr_comdat.ll16
-rw-r--r--test/CodeGen/X86/opt-ext-uses.ll19
-rw-r--r--test/CodeGen/X86/opt-shuff-tstore.ll39
-rw-r--r--test/CodeGen/X86/optimize-max-0.ll461
-rw-r--r--test/CodeGen/X86/optimize-max-1.ll78
-rw-r--r--test/CodeGen/X86/optimize-max-2.ll30
-rw-r--r--test/CodeGen/X86/optimize-max-3.ll76
-rw-r--r--test/CodeGen/X86/or-address.ll90
-rw-r--r--test/CodeGen/X86/or-branch.ll19
-rw-r--r--test/CodeGen/X86/overlap-shift.ll19
-rw-r--r--test/CodeGen/X86/packed_struct.ll34
-rw-r--r--test/CodeGen/X86/palignr-2.ll28
-rw-r--r--test/CodeGen/X86/palignr.ll73
-rw-r--r--test/CodeGen/X86/pass-three.ll16
-rw-r--r--test/CodeGen/X86/peep-setb.ll82
-rw-r--r--test/CodeGen/X86/peep-test-0.ll22
-rw-r--r--test/CodeGen/X86/peep-test-1.ll23
-rw-r--r--test/CodeGen/X86/peep-test-2.ll17
-rw-r--r--test/CodeGen/X86/peep-test-3.ll89
-rw-r--r--test/CodeGen/X86/peep-vector-extract-concat.ll11
-rw-r--r--test/CodeGen/X86/peep-vector-extract-insert.ll12
-rw-r--r--test/CodeGen/X86/personality.ll55
-rw-r--r--test/CodeGen/X86/personality_size.ll28
-rw-r--r--test/CodeGen/X86/phaddsub.ll170
-rw-r--r--test/CodeGen/X86/phi-bit-propagation.ll55
-rw-r--r--test/CodeGen/X86/phi-immediate-factoring.ll54
-rw-r--r--test/CodeGen/X86/phielim-split.ll30
-rw-r--r--test/CodeGen/X86/phys-reg-local-regalloc.ll65
-rw-r--r--test/CodeGen/X86/phys_subreg_coalesce-2.ll31
-rw-r--r--test/CodeGen/X86/phys_subreg_coalesce-3.ll40
-rw-r--r--test/CodeGen/X86/phys_subreg_coalesce.ll24
-rw-r--r--test/CodeGen/X86/pic-load-remat.ll47
-rw-r--r--test/CodeGen/X86/pic.ll208
-rw-r--r--test/CodeGen/X86/pic_jumptable.ll86
-rw-r--r--test/CodeGen/X86/pmovext.ll22
-rw-r--r--test/CodeGen/X86/pmul.ll32
-rw-r--r--test/CodeGen/X86/pmulld.ll26
-rw-r--r--test/CodeGen/X86/pointer-vector.ll137
-rw-r--r--test/CodeGen/X86/popcnt.ll38
-rw-r--r--test/CodeGen/X86/postalloc-coalescing.ll35
-rw-r--r--test/CodeGen/X86/postra-licm.ll188
-rw-r--r--test/CodeGen/X86/powi.ll11
-rw-r--r--test/CodeGen/X86/pr10068.ll22
-rw-r--r--test/CodeGen/X86/pr10420.ll21
-rw-r--r--test/CodeGen/X86/pr11202.ll19
-rw-r--r--test/CodeGen/X86/pr11334.ll64
-rw-r--r--test/CodeGen/X86/pr11415.ll23
-rw-r--r--test/CodeGen/X86/pr11468.ll33
-rw-r--r--test/CodeGen/X86/pr11985.ll19
-rw-r--r--test/CodeGen/X86/pr12312.ll155
-rw-r--r--test/CodeGen/X86/pr12359.ll10
-rw-r--r--test/CodeGen/X86/pr12360.ll46
-rw-r--r--test/CodeGen/X86/pr12889.ll18
-rw-r--r--test/CodeGen/X86/pr13209.ll74
-rw-r--r--test/CodeGen/X86/pr13220.ll20
-rw-r--r--test/CodeGen/X86/pr13577.ll8
-rw-r--r--test/CodeGen/X86/pr13859.ll28
-rw-r--r--test/CodeGen/X86/pr1462.ll25
-rw-r--r--test/CodeGen/X86/pr1489.ll55
-rw-r--r--test/CodeGen/X86/pr1505.ll12
-rw-r--r--test/CodeGen/X86/pr1505b.ll80
-rw-r--r--test/CodeGen/X86/pr2177.ll35
-rw-r--r--test/CodeGen/X86/pr2182.ll31
-rw-r--r--test/CodeGen/X86/pr2326.ll24
-rw-r--r--test/CodeGen/X86/pr2656.ll23
-rw-r--r--test/CodeGen/X86/pr2659.ll45
-rw-r--r--test/CodeGen/X86/pr2849.ll38
-rw-r--r--test/CodeGen/X86/pr2924.ll24
-rw-r--r--test/CodeGen/X86/pr2982.ll26
-rw-r--r--test/CodeGen/X86/pr3154.ll104
-rw-r--r--test/CodeGen/X86/pr3216.ll18
-rw-r--r--test/CodeGen/X86/pr3241.ll29
-rw-r--r--test/CodeGen/X86/pr3243.ll15
-rw-r--r--test/CodeGen/X86/pr3244.ll26
-rw-r--r--test/CodeGen/X86/pr3250.ll17
-rw-r--r--test/CodeGen/X86/pr3317.ll46
-rw-r--r--test/CodeGen/X86/pr3366.ll21
-rw-r--r--test/CodeGen/X86/pr3457.ll16
-rw-r--r--test/CodeGen/X86/pr3522.ll34
-rw-r--r--test/CodeGen/X86/pr7882.ll17
-rw-r--r--test/CodeGen/X86/pr9127.ll13
-rw-r--r--test/CodeGen/X86/pr9743.ll17
-rw-r--r--test/CodeGen/X86/prefetch.ll19
-rw-r--r--test/CodeGen/X86/private-2.ll13
-rw-r--r--test/CodeGen/X86/private.ll18
-rw-r--r--test/CodeGen/X86/promote-assert-zext.ll22
-rw-r--r--test/CodeGen/X86/promote-i16.ll21
-rw-r--r--test/CodeGen/X86/promote-trunc.ll11
-rw-r--r--test/CodeGen/X86/promote.ll42
-rw-r--r--test/CodeGen/X86/ptr-rotate.ll11
-rw-r--r--test/CodeGen/X86/ptrtoint-constexpr.ll14
-rw-r--r--test/CodeGen/X86/rd-mod-wr-eflags.ll225
-rw-r--r--test/CodeGen/X86/rdrand.ll85
-rw-r--r--test/CodeGen/X86/rdtsc.ll8
-rw-r--r--test/CodeGen/X86/red-zone.ll25
-rw-r--r--test/CodeGen/X86/red-zone2.ll9
-rw-r--r--test/CodeGen/X86/reghinting.ll35
-rw-r--r--test/CodeGen/X86/regpressure.ll114
-rw-r--r--test/CodeGen/X86/rem-2.ll7
-rw-r--r--test/CodeGen/X86/rem.ll22
-rw-r--r--test/CodeGen/X86/remat-constant.ll15
-rw-r--r--test/CodeGen/X86/remat-fold-load.ll143
-rw-r--r--test/CodeGen/X86/remat-mov-0.ll34
-rw-r--r--test/CodeGen/X86/remat-scalar-zero.ll97
-rw-r--r--test/CodeGen/X86/ret-addr.ll22
-rw-r--r--test/CodeGen/X86/ret-i64-0.ll5
-rw-r--r--test/CodeGen/X86/ret-mmx.ll39
-rw-r--r--test/CodeGen/X86/reverse_branches.ll104
-rw-r--r--test/CodeGen/X86/rip-rel-address.ll14
-rw-r--r--test/CodeGen/X86/rodata-relocs.ll23
-rw-r--r--test/CodeGen/X86/rot16.ll85
-rw-r--r--test/CodeGen/X86/rot32.ll85
-rw-r--r--test/CodeGen/X86/rot64.ll73
-rw-r--r--test/CodeGen/X86/rotate.ll100
-rw-r--r--test/CodeGen/X86/rotate2.ll19
-rw-r--r--test/CodeGen/X86/rounding-ops.ll132
-rw-r--r--test/CodeGen/X86/scalar-extract.ll13
-rw-r--r--test/CodeGen/X86/scalar-min-max-fill-operand.ll27
-rw-r--r--test/CodeGen/X86/scalar_sse_minmax.ll44
-rw-r--r--test/CodeGen/X86/scalar_widen_div.ll195
-rw-r--r--test/CodeGen/X86/scalarize-bitcast.ll29
-rw-r--r--test/CodeGen/X86/scev-interchange.ll382
-rw-r--r--test/CodeGen/X86/sdiv-exact.ll18
-rw-r--r--test/CodeGen/X86/segmented-stacks-dynamic.ll64
-rw-r--r--test/CodeGen/X86/segmented-stacks.ll385
-rw-r--r--test/CodeGen/X86/select.ll346
-rw-r--r--test/CodeGen/X86/selectiondag-cse.ll69
-rw-r--r--test/CodeGen/X86/setcc.ll36
-rw-r--r--test/CodeGen/X86/setoeq.ll21
-rw-r--r--test/CodeGen/X86/setuge.ll13
-rw-r--r--test/CodeGen/X86/sext-i1.ll63
-rw-r--r--test/CodeGen/X86/sext-load.ll9
-rw-r--r--test/CodeGen/X86/sext-ret-val.ll16
-rw-r--r--test/CodeGen/X86/sext-setcc-self.ll55
-rw-r--r--test/CodeGen/X86/sext-subreg.ll17
-rw-r--r--test/CodeGen/X86/sext-trunc.ll9
-rw-r--r--test/CodeGen/X86/sfence.ll8
-rw-r--r--test/CodeGen/X86/shift-and.ll78
-rw-r--r--test/CodeGen/X86/shift-coalesce.ll15
-rw-r--r--test/CodeGen/X86/shift-codegen.ll38
-rw-r--r--test/CodeGen/X86/shift-combine.ll19
-rw-r--r--test/CodeGen/X86/shift-double.ll41
-rw-r--r--test/CodeGen/X86/shift-folding.ll70
-rw-r--r--test/CodeGen/X86/shift-i128.ll9
-rw-r--r--test/CodeGen/X86/shift-i256.ll9
-rw-r--r--test/CodeGen/X86/shift-one.ll10
-rw-r--r--test/CodeGen/X86/shift-pair.ll11
-rw-r--r--test/CodeGen/X86/shift-parts.ll22
-rw-r--r--test/CodeGen/X86/shl-anyext.ll40
-rw-r--r--test/CodeGen/X86/shl-i64.ll20
-rw-r--r--test/CodeGen/X86/shl_elim.ll13
-rw-r--r--test/CodeGen/X86/shl_undef.ll53
-rw-r--r--test/CodeGen/X86/shrink-compare.ll36
-rw-r--r--test/CodeGen/X86/shrink-fp-const1.ll7
-rw-r--r--test/CodeGen/X86/shrink-fp-const2.ll7
-rw-r--r--test/CodeGen/X86/sibcall-2.ll52
-rw-r--r--test/CodeGen/X86/sibcall-3.ll16
-rw-r--r--test/CodeGen/X86/sibcall-4.ll13
-rw-r--r--test/CodeGen/X86/sibcall-5.ll60
-rw-r--r--test/CodeGen/X86/sibcall-byval.ll31
-rw-r--r--test/CodeGen/X86/sibcall.ll331
-rw-r--r--test/CodeGen/X86/sincos.ll79
-rw-r--r--test/CodeGen/X86/sink-hoist.ll175
-rw-r--r--test/CodeGen/X86/sink-out-of-loop.ll54
-rw-r--r--test/CodeGen/X86/small-byval-memcpy.ll20
-rw-r--r--test/CodeGen/X86/smul-with-overflow.ll69
-rw-r--r--test/CodeGen/X86/soft-fp.ll27
-rw-r--r--test/CodeGen/X86/splat-scalar-load.ll17
-rw-r--r--test/CodeGen/X86/split-eh-lpad-edges.ll38
-rw-r--r--test/CodeGen/X86/split-vector-bitcast.ll12
-rw-r--r--test/CodeGen/X86/split-vector-rem.ll15
-rw-r--r--test/CodeGen/X86/sse-align-0.ll13
-rw-r--r--test/CodeGen/X86/sse-align-1.ll10
-rw-r--r--test/CodeGen/X86/sse-align-10.ll6
-rw-r--r--test/CodeGen/X86/sse-align-11.ll13
-rw-r--r--test/CodeGen/X86/sse-align-12.ll57
-rw-r--r--test/CodeGen/X86/sse-align-2.ll12
-rw-r--r--test/CodeGen/X86/sse-align-3.ll15
-rw-r--r--test/CodeGen/X86/sse-align-4.ll10
-rw-r--r--test/CodeGen/X86/sse-align-5.ll6
-rw-r--r--test/CodeGen/X86/sse-align-6.ll7
-rw-r--r--test/CodeGen/X86/sse-align-7.ll8
-rw-r--r--test/CodeGen/X86/sse-align-8.ll6
-rw-r--r--test/CodeGen/X86/sse-align-9.ll10
-rw-r--r--test/CodeGen/X86/sse-commute.ll20
-rw-r--r--test/CodeGen/X86/sse-domains.ll87
-rw-r--r--test/CodeGen/X86/sse-fcopysign.ll16
-rw-r--r--test/CodeGen/X86/sse-load-ret.ll19
-rw-r--r--test/CodeGen/X86/sse-minmax.ll948
-rw-r--r--test/CodeGen/X86/sse-varargs.ll9
-rw-r--r--test/CodeGen/X86/sse1.ll45
-rw-r--r--test/CodeGen/X86/sse2-blend.ll61
-rw-r--r--test/CodeGen/X86/sse2.ll224
-rw-r--r--test/CodeGen/X86/sse3.ll272
-rw-r--r--test/CodeGen/X86/sse41-blend.ll90
-rw-r--r--test/CodeGen/X86/sse41.ll251
-rw-r--r--test/CodeGen/X86/sse42.ll39
-rw-r--r--test/CodeGen/X86/sse42_64.ll21
-rw-r--r--test/CodeGen/X86/sse4a.ll56
-rw-r--r--test/CodeGen/X86/sse_reload_fold.ll134
-rw-r--r--test/CodeGen/X86/stack-align.ll51
-rw-r--r--test/CodeGen/X86/stack-align2.ll25
-rw-r--r--test/CodeGen/X86/stack-protector.ll28
-rw-r--r--test/CodeGen/X86/stdarg.ll21
-rw-r--r--test/CodeGen/X86/stdcall-notailcall.ll13
-rw-r--r--test/CodeGen/X86/stdcall.ll16
-rw-r--r--test/CodeGen/X86/store-empty-member.ll14
-rw-r--r--test/CodeGen/X86/store-fp-constant.ll19
-rw-r--r--test/CodeGen/X86/store-global-address.ll10
-rw-r--r--test/CodeGen/X86/store-narrow.ll168
-rw-r--r--test/CodeGen/X86/store_op_load_fold.ll13
-rw-r--r--test/CodeGen/X86/store_op_load_fold2.ll30
-rw-r--r--test/CodeGen/X86/storetrunc-fp.ll8
-rw-r--r--test/CodeGen/X86/stride-nine-with-base-reg.ll38
-rw-r--r--test/CodeGen/X86/stride-reuse.ll31
-rw-r--r--test/CodeGen/X86/sub-with-overflow.ll59
-rw-r--r--test/CodeGen/X86/sub.ll11
-rw-r--r--test/CodeGen/X86/subreg-to-reg-0.ll11
-rw-r--r--test/CodeGen/X86/subreg-to-reg-1.ll13
-rw-r--r--test/CodeGen/X86/subreg-to-reg-2.ll25
-rw-r--r--test/CodeGen/X86/subreg-to-reg-3.ll10
-rw-r--r--test/CodeGen/X86/subreg-to-reg-4.ll135
-rw-r--r--test/CodeGen/X86/subreg-to-reg-6.ll29
-rw-r--r--test/CodeGen/X86/switch-bt.ll101
-rw-r--r--test/CodeGen/X86/switch-crit-edge-constant.ll52
-rw-r--r--test/CodeGen/X86/switch-or.ll22
-rw-r--r--test/CodeGen/X86/switch-order-weight.ll37
-rw-r--r--test/CodeGen/X86/switch-zextload.ll34
-rw-r--r--test/CodeGen/X86/swizzle.ll19
-rw-r--r--test/CodeGen/X86/tail-call-got.ll24
-rw-r--r--test/CodeGen/X86/tail-dup-addr.ll28
-rw-r--r--test/CodeGen/X86/tail-opts.ll433
-rw-r--r--test/CodeGen/X86/tail-threshold.ll44
-rw-r--r--test/CodeGen/X86/tailcall-64.ll134
-rw-r--r--test/CodeGen/X86/tailcall-cgp-dup.ll87
-rw-r--r--test/CodeGen/X86/tailcall-disable.ll40
-rw-r--r--test/CodeGen/X86/tailcall-fastisel.ll19
-rw-r--r--test/CodeGen/X86/tailcall-largecode.ll71
-rw-r--r--test/CodeGen/X86/tailcall-returndup-void.ll37
-rw-r--r--test/CodeGen/X86/tailcall-ri64.ll24
-rw-r--r--test/CodeGen/X86/tailcall-stackalign.ll23
-rw-r--r--test/CodeGen/X86/tailcall-structret.ll6
-rw-r--r--test/CodeGen/X86/tailcall.ll52
-rw-r--r--test/CodeGen/X86/tailcallbyval.ll18
-rw-r--r--test/CodeGen/X86/tailcallbyval64.ll42
-rw-r--r--test/CodeGen/X86/tailcallfp.ll5
-rw-r--r--test/CodeGen/X86/tailcallfp2.ll27
-rw-r--r--test/CodeGen/X86/tailcallpic1.ll12
-rw-r--r--test/CodeGen/X86/tailcallpic2.ll12
-rw-r--r--test/CodeGen/X86/tailcallstack64.ll28
-rw-r--r--test/CodeGen/X86/targetLoweringGeneric.ll38
-rw-r--r--test/CodeGen/X86/test-nofold.ll42
-rw-r--r--test/CodeGen/X86/test-shrink-bug.ll23
-rw-r--r--test/CodeGen/X86/test-shrink.ll159
-rw-r--r--test/CodeGen/X86/testl-commute.ll72
-rw-r--r--test/CodeGen/X86/thiscall-struct-return.ll47
-rw-r--r--test/CodeGen/X86/tls-local-dynamic.ll59
-rw-r--r--test/CodeGen/X86/tls-models.ll166
-rw-r--r--test/CodeGen/X86/tls-pic.ll87
-rw-r--r--test/CodeGen/X86/tls-pie.ll73
-rw-r--r--test/CodeGen/X86/tls.ll329
-rw-r--r--test/CodeGen/X86/tlv-1.ll52
-rw-r--r--test/CodeGen/X86/tlv-2.ll32
-rw-r--r--test/CodeGen/X86/trap.ll21
-rw-r--r--test/CodeGen/X86/trunc-ext-ld-st.ll82
-rw-r--r--test/CodeGen/X86/trunc-to-bool.ll59
-rw-r--r--test/CodeGen/X86/twoaddr-coalesce-2.ll15
-rw-r--r--test/CodeGen/X86/twoaddr-coalesce.ll24
-rw-r--r--test/CodeGen/X86/twoaddr-lea.ll47
-rw-r--r--test/CodeGen/X86/twoaddr-pass-sink.ll29
-rw-r--r--test/CodeGen/X86/twoaddr-sink-terminator.ll43
-rw-r--r--test/CodeGen/X86/uint64-to-float.ll22
-rw-r--r--test/CodeGen/X86/uint_to_fp-2.ll33
-rw-r--r--test/CodeGen/X86/uint_to_fp.ll14
-rw-r--r--test/CodeGen/X86/umul-with-carry.ll26
-rw-r--r--test/CodeGen/X86/umul-with-overflow.ll38
-rw-r--r--test/CodeGen/X86/unaligned-load.ll37
-rw-r--r--test/CodeGen/X86/undef-label.ll19
-rw-r--r--test/CodeGen/X86/unknown-location.ll29
-rw-r--r--test/CodeGen/X86/unreachable-loop-sinking.ll30
-rw-r--r--test/CodeGen/X86/unwindraise.ll252
-rw-r--r--test/CodeGen/X86/urem-i8-constant.ll6
-rw-r--r--test/CodeGen/X86/use-add-flags.ll57
-rw-r--r--test/CodeGen/X86/utf16-cfstrings.ll35
-rw-r--r--test/CodeGen/X86/utf8.ll4
-rw-r--r--test/CodeGen/X86/v-binop-widen.ll12
-rw-r--r--test/CodeGen/X86/v-binop-widen2.ll47
-rw-r--r--test/CodeGen/X86/v2f32.ll115
-rw-r--r--test/CodeGen/X86/v4f32-immediate.ll5
-rw-r--r--test/CodeGen/X86/vararg_tailcall.ll98
-rw-r--r--test/CodeGen/X86/variable-sized-darwin-bzero.ll8
-rw-r--r--test/CodeGen/X86/variadic-node-pic.ll11
-rw-r--r--test/CodeGen/X86/vec-sign.ll30
-rw-r--r--test/CodeGen/X86/vec-trunc-store.ll15
-rw-r--r--test/CodeGen/X86/vec_add.ll7
-rw-r--r--test/CodeGen/X86/vec_align.ll35
-rw-r--r--test/CodeGen/X86/vec_anyext.ll77
-rw-r--r--test/CodeGen/X86/vec_call.ll13
-rw-r--r--test/CodeGen/X86/vec_cast.ll56
-rw-r--r--test/CodeGen/X86/vec_cast2.ll49
-rw-r--r--test/CodeGen/X86/vec_clear.ll13
-rw-r--r--test/CodeGen/X86/vec_compare-2.ll31
-rw-r--r--test/CodeGen/X86/vec_compare-sse4.ll35
-rw-r--r--test/CodeGen/X86/vec_compare.ll43
-rw-r--r--test/CodeGen/X86/vec_ctbits.ll18
-rw-r--r--test/CodeGen/X86/vec_ext_inreg.ll37
-rw-r--r--test/CodeGen/X86/vec_extract-sse4.ll31
-rw-r--r--test/CodeGen/X86/vec_extract.ll36
-rw-r--r--test/CodeGen/X86/vec_fabs.ll38
-rw-r--r--test/CodeGen/X86/vec_floor.ll38
-rw-r--r--test/CodeGen/X86/vec_fneg.ll11
-rw-r--r--test/CodeGen/X86/vec_fpext.ll38
-rw-r--r--test/CodeGen/X86/vec_i64.ll22
-rw-r--r--test/CodeGen/X86/vec_ins_extract-1.ll25
-rw-r--r--test/CodeGen/X86/vec_ins_extract.ll52
-rw-r--r--test/CodeGen/X86/vec_insert-2.ll42
-rw-r--r--test/CodeGen/X86/vec_insert-3.ll6
-rw-r--r--test/CodeGen/X86/vec_insert-4.ll11
-rw-r--r--test/CodeGen/X86/vec_insert-5.ll33
-rw-r--r--test/CodeGen/X86/vec_insert-6.ll8
-rw-r--r--test/CodeGen/X86/vec_insert-7.ll15
-rw-r--r--test/CodeGen/X86/vec_insert-8.ll15
-rw-r--r--test/CodeGen/X86/vec_insert-9.ll9
-rw-r--r--test/CodeGen/X86/vec_insert.ll19
-rw-r--r--test/CodeGen/X86/vec_loadsingles.ll12
-rw-r--r--test/CodeGen/X86/vec_logical.ll42
-rw-r--r--test/CodeGen/X86/vec_return.ll16
-rw-r--r--test/CodeGen/X86/vec_set-2.ll19
-rw-r--r--test/CodeGen/X86/vec_set-3.ll17
-rw-r--r--test/CodeGen/X86/vec_set-4.ll24
-rw-r--r--test/CodeGen/X86/vec_set-5.ll28
-rw-r--r--test/CodeGen/X86/vec_set-6.ll12
-rw-r--r--test/CodeGen/X86/vec_set-7.ll11
-rw-r--r--test/CodeGen/X86/vec_set-8.ll13
-rw-r--r--test/CodeGen/X86/vec_set-9.ll9
-rw-r--r--test/CodeGen/X86/vec_set-A.ll7
-rw-r--r--test/CodeGen/X86/vec_set-B.ll24
-rw-r--r--test/CodeGen/X86/vec_set-C.ll8
-rw-r--r--test/CodeGen/X86/vec_set-D.ll7
-rw-r--r--test/CodeGen/X86/vec_set-E.ll9
-rw-r--r--test/CodeGen/X86/vec_set-F.ll19
-rw-r--r--test/CodeGen/X86/vec_set-G.ll9
-rw-r--r--test/CodeGen/X86/vec_set-H.ll15
-rw-r--r--test/CodeGen/X86/vec_set-I.ll10
-rw-r--r--test/CodeGen/X86/vec_set-J.ll10
-rw-r--r--test/CodeGen/X86/vec_set.ll15
-rw-r--r--test/CodeGen/X86/vec_sext.ll69
-rw-r--r--test/CodeGen/X86/vec_shift.ll34
-rw-r--r--test/CodeGen/X86/vec_shift2.ll17
-rw-r--r--test/CodeGen/X86/vec_shift3.ll26
-rw-r--r--test/CodeGen/X86/vec_shift4.ll25
-rw-r--r--test/CodeGen/X86/vec_shuffle-11.ll11
-rw-r--r--test/CodeGen/X86/vec_shuffle-14.ll42
-rw-r--r--test/CodeGen/X86/vec_shuffle-15.ll81
-rw-r--r--test/CodeGen/X86/vec_shuffle-16.ll43
-rw-r--r--test/CodeGen/X86/vec_shuffle-17.ll16
-rw-r--r--test/CodeGen/X86/vec_shuffle-18.ll25
-rw-r--r--test/CodeGen/X86/vec_shuffle-19.ll8
-rw-r--r--test/CodeGen/X86/vec_shuffle-20.ll7
-rw-r--r--test/CodeGen/X86/vec_shuffle-22.ll15
-rw-r--r--test/CodeGen/X86/vec_shuffle-23.ll18
-rw-r--r--test/CodeGen/X86/vec_shuffle-24.ll18
-rw-r--r--test/CodeGen/X86/vec_shuffle-25.ll34
-rw-r--r--test/CodeGen/X86/vec_shuffle-26.ll68
-rw-r--r--test/CodeGen/X86/vec_shuffle-27.ll38
-rw-r--r--test/CodeGen/X86/vec_shuffle-28.ll12
-rw-r--r--test/CodeGen/X86/vec_shuffle-30.ll22
-rw-r--r--test/CodeGen/X86/vec_shuffle-31.ll8
-rw-r--r--test/CodeGen/X86/vec_shuffle-34.ll7
-rw-r--r--test/CodeGen/X86/vec_shuffle-35.ll20
-rw-r--r--test/CodeGen/X86/vec_shuffle-36.ll16
-rw-r--r--test/CodeGen/X86/vec_shuffle-37.ll47
-rw-r--r--test/CodeGen/X86/vec_shuffle-38.ll77
-rw-r--r--test/CodeGen/X86/vec_shuffle-39.ll86
-rw-r--r--test/CodeGen/X86/vec_shuffle.ll50
-rw-r--r--test/CodeGen/X86/vec_splat-2.ll26
-rw-r--r--test/CodeGen/X86/vec_splat-3.ll55
-rw-r--r--test/CodeGen/X86/vec_splat-4.ll104
-rw-r--r--test/CodeGen/X86/vec_splat.ll22
-rw-r--r--test/CodeGen/X86/vec_ss_load_fold.ll86
-rw-r--r--test/CodeGen/X86/vec_udiv_to_shift.ll15
-rw-r--r--test/CodeGen/X86/vec_uint_to_fp.ll11
-rw-r--r--test/CodeGen/X86/vec_zero-2.ll24
-rw-r--r--test/CodeGen/X86/vec_zero.ll30
-rw-r--r--test/CodeGen/X86/vec_zero_cse.ll35
-rw-r--r--test/CodeGen/X86/vec_zext.ll69
-rw-r--r--test/CodeGen/X86/vector-gep.ll88
-rw-r--r--test/CodeGen/X86/vector-intrinsics.ll52
-rw-r--r--test/CodeGen/X86/vector-rem.ll15
-rw-r--r--test/CodeGen/X86/vector-variable-idx.ll11
-rw-r--r--test/CodeGen/X86/vector-variable-idx2.ll26
-rw-r--r--test/CodeGen/X86/vector.ll156
-rw-r--r--test/CodeGen/X86/vfcmp.ll15
-rw-r--r--test/CodeGen/X86/visibility.ll14
-rw-r--r--test/CodeGen/X86/visibility2.ll18
-rw-r--r--test/CodeGen/X86/volatile.ll17
-rw-r--r--test/CodeGen/X86/vortex-bug.ll21
-rw-r--r--test/CodeGen/X86/vshift-1.ll79
-rw-r--r--test/CodeGen/X86/vshift-2.ll78
-rw-r--r--test/CodeGen/X86/vshift-3.ll67
-rw-r--r--test/CodeGen/X86/vshift-4.ll85
-rw-r--r--test/CodeGen/X86/vshift-5.ll56
-rw-r--r--test/CodeGen/X86/vshift_scalar.ll11
-rw-r--r--test/CodeGen/X86/vshift_split.ll8
-rw-r--r--test/CodeGen/X86/vshift_split2.ll11
-rw-r--r--test/CodeGen/X86/vsplit-and.ll25
-rw-r--r--test/CodeGen/X86/weak.ll4
-rw-r--r--test/CodeGen/X86/wide-integer-fold.ll12
-rw-r--r--test/CodeGen/X86/widen_arith-1.ll44
-rw-r--r--test/CodeGen/X86/widen_arith-2.ll59
-rw-r--r--test/CodeGen/X86/widen_arith-3.ll52
-rw-r--r--test/CodeGen/X86/widen_arith-4.ll49
-rw-r--r--test/CodeGen/X86/widen_arith-5.ll50
-rw-r--r--test/CodeGen/X86/widen_arith-6.ll49
-rw-r--r--test/CodeGen/X86/widen_cast-1.ll51
-rw-r--r--test/CodeGen/X86/widen_cast-2.ll46
-rw-r--r--test/CodeGen/X86/widen_cast-3.ll17
-rw-r--r--test/CodeGen/X86/widen_cast-4.ll57
-rw-r--r--test/CodeGen/X86/widen_cast-5.ll12
-rw-r--r--test/CodeGen/X86/widen_cast-6.ll10
-rw-r--r--test/CodeGen/X86/widen_conv-1.ll12
-rw-r--r--test/CodeGen/X86/widen_conv-2.ll12
-rw-r--r--test/CodeGen/X86/widen_conv-3.ll11
-rw-r--r--test/CodeGen/X86/widen_conv-4.ll11
-rw-r--r--test/CodeGen/X86/widen_extract-1.ll12
-rw-r--r--test/CodeGen/X86/widen_load-0.ll21
-rw-r--r--test/CodeGen/X86/widen_load-1.ll51
-rw-r--r--test/CodeGen/X86/widen_load-2.ll192
-rw-r--r--test/CodeGen/X86/widen_shuffle-1.ll69
-rw-r--r--test/CodeGen/X86/win32_sret.ll28
-rw-r--r--test/CodeGen/X86/win64_alloca_dynalloca.ll74
-rw-r--r--test/CodeGen/X86/win64_params.ll11
-rw-r--r--test/CodeGen/X86/win64_vararg.ll53
-rw-r--r--test/CodeGen/X86/win_chkstk.ll47
-rw-r--r--test/CodeGen/X86/win_ftol2.ll144
-rw-r--r--test/CodeGen/X86/x86-64-and-mask.ll49
-rw-r--r--test/CodeGen/X86/x86-64-arg.ll15
-rw-r--r--test/CodeGen/X86/x86-64-asm.ll12
-rw-r--r--test/CodeGen/X86/x86-64-dead-stack-adjust.ll12
-rw-r--r--test/CodeGen/X86/x86-64-disp.ll14
-rw-r--r--test/CodeGen/X86/x86-64-extend-shift.ll10
-rw-r--r--test/CodeGen/X86/x86-64-frameaddr.ll10
-rw-r--r--test/CodeGen/X86/x86-64-gv-offset.ll14
-rw-r--r--test/CodeGen/X86/x86-64-jumps.ll45
-rw-r--r--test/CodeGen/X86/x86-64-mem.ll36
-rw-r--r--test/CodeGen/X86/x86-64-pic-1.ll10
-rw-r--r--test/CodeGen/X86/x86-64-pic-10.ll12
-rw-r--r--test/CodeGen/X86/x86-64-pic-11.ll8
-rw-r--r--test/CodeGen/X86/x86-64-pic-2.ll11
-rw-r--r--test/CodeGen/X86/x86-64-pic-3.ll14
-rw-r--r--test/CodeGen/X86/x86-64-pic-4.ll10
-rw-r--r--test/CodeGen/X86/x86-64-pic-5.ll11
-rw-r--r--test/CodeGen/X86/x86-64-pic-6.ll11
-rw-r--r--test/CodeGen/X86/x86-64-pic-7.ll9
-rw-r--r--test/CodeGen/X86/x86-64-pic-8.ll10
-rw-r--r--test/CodeGen/X86/x86-64-pic-9.ll13
-rw-r--r--test/CodeGen/X86/x86-64-ret0.ll8
-rw-r--r--test/CodeGen/X86/x86-64-shortint.ll12
-rw-r--r--test/CodeGen/X86/x86-64-sret-return.ll63
-rw-r--r--test/CodeGen/X86/x86-64-tls-1.ll6
-rw-r--r--test/CodeGen/X86/x86-64-varargs.ll11
-rw-r--r--test/CodeGen/X86/x86-frameaddr.ll9
-rw-r--r--test/CodeGen/X86/x86-frameaddr2.ll9
-rw-r--r--test/CodeGen/X86/x86-shifts.ll192
-rw-r--r--test/CodeGen/X86/x86-store-gv-addr.ll10
-rw-r--r--test/CodeGen/X86/x86_64-mul-by-const.ll9
-rw-r--r--test/CodeGen/X86/xmm-r64.ll12
-rw-r--r--test/CodeGen/X86/xmulo.ll50
-rw-r--r--test/CodeGen/X86/xop-intrinsics-x86_64.ll1025
-rw-r--r--test/CodeGen/X86/xor-icmp.ll67
-rw-r--r--test/CodeGen/X86/xor.ll144
-rw-r--r--test/CodeGen/X86/zero-remat.ll40
-rw-r--r--test/CodeGen/X86/zext-extract_subreg.ll61
-rw-r--r--test/CodeGen/X86/zext-fold.ll41
-rw-r--r--test/CodeGen/X86/zext-inreg-0.ll66
-rw-r--r--test/CodeGen/X86/zext-inreg-1.ll18
-rw-r--r--test/CodeGen/X86/zext-sext.ll55
-rw-r--r--test/CodeGen/X86/zext-shl.ll25
-rw-r--r--test/CodeGen/X86/zext-trunc.ll13
-rw-r--r--test/CodeGen/XCore/2008-11-17-Shl64.ll6
-rw-r--r--test/CodeGen/XCore/2009-01-08-Crash.ll12
-rw-r--r--test/CodeGen/XCore/2009-01-14-Remat-Crash.ll18
-rw-r--r--test/CodeGen/XCore/2009-03-27-v2f64-param.ll6
-rw-r--r--test/CodeGen/XCore/2009-07-15-store192.ll7
-rw-r--r--test/CodeGen/XCore/2010-02-25-LSR-Crash.ll26
-rw-r--r--test/CodeGen/XCore/2010-04-07-DbgValueOtherTargets.ll28
-rw-r--r--test/CodeGen/XCore/2011-01-31-DAGCombineBug.ll10
-rw-r--r--test/CodeGen/XCore/2011-08-01-DynamicAllocBug.ll20
-rw-r--r--test/CodeGen/XCore/2011-08-01-VarargsBug.ll17
-rw-r--r--test/CodeGen/XCore/addsub64.ll59
-rw-r--r--test/CodeGen/XCore/ashr.ll76
-rw-r--r--test/CodeGen/XCore/basictest.ll6
-rw-r--r--test/CodeGen/XCore/bigstructret.ll43
-rw-r--r--test/CodeGen/XCore/constants.ll11
-rw-r--r--test/CodeGen/XCore/events.ll44
-rw-r--r--test/CodeGen/XCore/float-intrinsics.ll171
-rw-r--r--test/CodeGen/XCore/fneg.ll9
-rw-r--r--test/CodeGen/XCore/getid.ll10
-rw-r--r--test/CodeGen/XCore/global_negative_offset.ll25
-rw-r--r--test/CodeGen/XCore/globals.ll92
-rw-r--r--test/CodeGen/XCore/indirectbr.ll45
-rw-r--r--test/CodeGen/XCore/ladd_lsub_combine.ll67
-rw-r--r--test/CodeGen/XCore/licm-ldwcp.ll18
-rw-r--r--test/CodeGen/XCore/lit.local.cfg6
-rw-r--r--test/CodeGen/XCore/load.ll41
-rw-r--r--test/CodeGen/XCore/misc-intrinsics.ll75
-rw-r--r--test/CodeGen/XCore/mkmsk.ll11
-rw-r--r--test/CodeGen/XCore/mul64.ll50
-rw-r--r--test/CodeGen/XCore/private.ll21
-rw-r--r--test/CodeGen/XCore/ps-intrinsics.ll18
-rw-r--r--test/CodeGen/XCore/resources.ll241
-rw-r--r--test/CodeGen/XCore/scavenging.ll52
-rw-r--r--test/CodeGen/XCore/sext.ll32
-rw-r--r--test/CodeGen/XCore/sr-intrinsics.ll18
-rw-r--r--test/CodeGen/XCore/store.ll37
-rw-r--r--test/CodeGen/XCore/switch.ll24
-rw-r--r--test/CodeGen/XCore/switch_long.ll132
-rw-r--r--test/CodeGen/XCore/threads.ll67
-rw-r--r--test/CodeGen/XCore/tls.ll20
-rw-r--r--test/CodeGen/XCore/trampoline.ll39
-rw-r--r--test/CodeGen/XCore/trap.ll12
-rw-r--r--test/CodeGen/XCore/unaligned_load.ll31
-rw-r--r--test/CodeGen/XCore/unaligned_store.ll18
-rw-r--r--test/CodeGen/XCore/unaligned_store_combine.ll13
-rw-r--r--test/DebugInfo/2009-10-16-Phi.ll13
-rw-r--r--test/DebugInfo/2009-11-03-InsertExtractValue.ll11
-rw-r--r--test/DebugInfo/2009-11-05-DeadGlobalVariable.ll28
-rw-r--r--test/DebugInfo/2009-11-06-NamelessGlobalVariable.ll13
-rw-r--r--test/DebugInfo/2009-11-10-CurrentFn.ll32
-rw-r--r--test/DebugInfo/2010-01-05-DbgScope.ll18
-rw-r--r--test/DebugInfo/2010-01-19-DbgScope.ll28
-rw-r--r--test/DebugInfo/2010-03-12-llc-crash.ll20
-rw-r--r--test/DebugInfo/2010-03-19-DbgDeclare.ll12
-rw-r--r--test/DebugInfo/2010-03-24-MemberFn.ll62
-rw-r--r--test/DebugInfo/2010-03-30-InvalidDbgInfoCrash.ll30
-rw-r--r--test/DebugInfo/2010-04-06-NestedFnDbgInfo.ll89
-rw-r--r--test/DebugInfo/2010-04-19-FramePtr.ll30
-rw-r--r--test/DebugInfo/2010-05-03-DisableFramePtr.ll34
-rw-r--r--test/DebugInfo/2010-05-03-OriginDIE.ll86
-rw-r--r--test/DebugInfo/2010-05-10-MultipleCU.ll44
-rw-r--r--test/DebugInfo/2010-06-29-InlinedFnLocalVar.ll54
-rw-r--r--test/DebugInfo/2010-07-19-Crash.ll24
-rw-r--r--test/DebugInfo/2010-10-01-crash.ll21
-rwxr-xr-xtest/DebugInfo/Inputs/dwarfdump-inl-test.elf-x86-64bin0 -> 7468 bytes
-rwxr-xr-xtest/DebugInfo/Inputs/dwarfdump-test.elf-x86-64bin0 -> 10174 bytes
-rwxr-xr-xtest/DebugInfo/Inputs/dwarfdump-test2.elf-x86-64bin0 -> 7702 bytes
-rwxr-xr-xtest/DebugInfo/Inputs/dwarfdump-test3.elf-x86-64bin0 -> 7339 bytes
-rwxr-xr-xtest/DebugInfo/Inputs/dwarfdump-test4.elf-x86-64bin0 -> 7689 bytes
-rw-r--r--test/DebugInfo/X86/2010-04-13-PubType.ll47
-rw-r--r--test/DebugInfo/X86/2011-09-26-GlobalVarContext.ll47
-rw-r--r--test/DebugInfo/X86/2011-12-16-BadStructRef.ll172
-rw-r--r--test/DebugInfo/X86/DW_AT_byte_size.ll45
-rw-r--r--test/DebugInfo/X86/DW_AT_location-reference.ll111
-rw-r--r--test/DebugInfo/X86/DW_AT_object_pointer.ll79
-rw-r--r--test/DebugInfo/X86/DW_AT_specification.ll43
-rw-r--r--test/DebugInfo/X86/DW_TAG_friend.ll47
-rw-r--r--test/DebugInfo/X86/aligned_stack_var.ll42
-rw-r--r--test/DebugInfo/X86/block-capture.ll127
-rw-r--r--test/DebugInfo/X86/concrete_out_of_line.ll95
-rw-r--r--test/DebugInfo/X86/debug_frame.ll18
-rw-r--r--test/DebugInfo/X86/earlydup-crash.ll85
-rw-r--r--test/DebugInfo/X86/eh_symbol.ll18
-rw-r--r--test/DebugInfo/X86/ending-run.ll49
-rw-r--r--test/DebugInfo/X86/enum-class.ll45
-rw-r--r--test/DebugInfo/X86/enum-fwd-decl.ll22
-rw-r--r--test/DebugInfo/X86/linkage-name.ll56
-rw-r--r--test/DebugInfo/X86/lit.local.cfg5
-rw-r--r--test/DebugInfo/X86/low-pc-cu.ll31
-rw-r--r--test/DebugInfo/X86/objc-fwd-decl.ll27
-rw-r--r--test/DebugInfo/X86/op_deref.ll89
-rw-r--r--test/DebugInfo/X86/pointer-type-size.ll25
-rw-r--r--test/DebugInfo/X86/pr11300.ll65
-rw-r--r--test/DebugInfo/X86/pr12831.ll238
-rw-r--r--test/DebugInfo/X86/pr9951.ll23
-rw-r--r--test/DebugInfo/X86/rvalue-ref.ll40
-rw-r--r--test/DebugInfo/X86/stmt-list.ll19
-rw-r--r--test/DebugInfo/X86/stringpool.ll44
-rw-r--r--test/DebugInfo/X86/struct-loc.ll26
-rw-r--r--test/DebugInfo/X86/subreg.ll27
-rw-r--r--test/DebugInfo/array.ll34
-rw-r--r--test/DebugInfo/bug_null_debuginfo.ll6
-rw-r--r--test/DebugInfo/dwarfdump-inlining.test28
-rw-r--r--test/DebugInfo/dwarfdump-test.test56
-rw-r--r--test/DebugInfo/inheritance.ll151
-rw-r--r--test/DebugInfo/inlined-vars.ll57
-rw-r--r--test/DebugInfo/lit.local.cfg1
-rw-r--r--test/DebugInfo/printdbginfo2.ll66
-rw-r--r--test/ExecutionEngine/2002-12-16-ArgTest.ll37
-rw-r--r--test/ExecutionEngine/2003-01-04-ArgumentBug.ll14
-rw-r--r--test/ExecutionEngine/2003-01-04-LoopTest.ll21
-rw-r--r--test/ExecutionEngine/2003-01-04-PhiTest.ll12
-rw-r--r--test/ExecutionEngine/2003-01-09-SARTest.ll11
-rw-r--r--test/ExecutionEngine/2003-01-10-FUCOM.ll10
-rw-r--r--test/ExecutionEngine/2003-01-15-AlignmentTest.ll18
-rw-r--r--test/ExecutionEngine/2003-05-06-LivenessClobber.ll20
-rw-r--r--test/ExecutionEngine/2003-05-07-ArgumentTest.ll12
-rw-r--r--test/ExecutionEngine/2003-05-11-PHIRegAllocBug.ll15
-rw-r--r--test/ExecutionEngine/2003-06-04-bzip2-bug.ll19
-rw-r--r--test/ExecutionEngine/2003-06-05-PHIBug.ll17
-rw-r--r--test/ExecutionEngine/2003-08-15-AllocaAssertion.ll12
-rw-r--r--test/ExecutionEngine/2003-08-21-EnvironmentTest.ll22
-rw-r--r--test/ExecutionEngine/2003-08-23-RegisterAllocatePhysReg.ll35
-rw-r--r--test/ExecutionEngine/2003-10-18-PHINode-ConstantExpr-CondCode-Failure.ll24
-rw-r--r--test/ExecutionEngine/2005-12-02-TailCallBug.ll22
-rw-r--r--test/ExecutionEngine/2007-12-10-APIntLoadStore.ll19
-rw-r--r--test/ExecutionEngine/2008-06-05-APInt-OverAShr.ll59
-rw-r--r--test/ExecutionEngine/2010-01-15-UndefValue.ll8
-rw-r--r--test/ExecutionEngine/MCJIT/2002-12-16-ArgTest.ll37
-rw-r--r--test/ExecutionEngine/MCJIT/2003-01-04-ArgumentBug.ll13
-rw-r--r--test/ExecutionEngine/MCJIT/2003-01-04-LoopTest.ll20
-rw-r--r--test/ExecutionEngine/MCJIT/2003-01-04-PhiTest.ll12
-rw-r--r--test/ExecutionEngine/MCJIT/2003-01-09-SARTest.ll11
-rw-r--r--test/ExecutionEngine/MCJIT/2003-01-10-FUCOM.ll10
-rw-r--r--test/ExecutionEngine/MCJIT/2003-01-15-AlignmentTest.ll17
-rw-r--r--test/ExecutionEngine/MCJIT/2003-05-06-LivenessClobber.ll19
-rw-r--r--test/ExecutionEngine/MCJIT/2003-05-07-ArgumentTest.ll11
-rw-r--r--test/ExecutionEngine/MCJIT/2003-05-11-PHIRegAllocBug.ll15
-rw-r--r--test/ExecutionEngine/MCJIT/2003-06-04-bzip2-bug.ll19
-rw-r--r--test/ExecutionEngine/MCJIT/2003-06-05-PHIBug.ll17
-rw-r--r--test/ExecutionEngine/MCJIT/2003-08-15-AllocaAssertion.ll11
-rw-r--r--test/ExecutionEngine/MCJIT/2003-08-21-EnvironmentTest.ll21
-rw-r--r--test/ExecutionEngine/MCJIT/2003-08-23-RegisterAllocatePhysReg.ll34
-rw-r--r--test/ExecutionEngine/MCJIT/2003-10-18-PHINode-ConstantExpr-CondCode-Failure.ll23
-rw-r--r--test/ExecutionEngine/MCJIT/2005-12-02-TailCallBug.ll22
-rw-r--r--test/ExecutionEngine/MCJIT/2007-12-10-APIntLoadStore.ll19
-rw-r--r--test/ExecutionEngine/MCJIT/2008-06-05-APInt-OverAShr.ll59
-rw-r--r--test/ExecutionEngine/MCJIT/2010-01-15-UndefValue.ll8
-rw-r--r--test/ExecutionEngine/MCJIT/fpbitcast.ll20
-rw-r--r--test/ExecutionEngine/MCJIT/hello.ll11
-rw-r--r--test/ExecutionEngine/MCJIT/hello2.ll17
-rw-r--r--test/ExecutionEngine/MCJIT/lit.local.cfg20
-rw-r--r--test/ExecutionEngine/MCJIT/pr13727.ll88
-rw-r--r--test/ExecutionEngine/MCJIT/simplesttest.ll6
-rw-r--r--test/ExecutionEngine/MCJIT/simpletest.ll11
-rw-r--r--test/ExecutionEngine/MCJIT/stubs.ll35
-rw-r--r--test/ExecutionEngine/MCJIT/test-arith.ll34
-rw-r--r--test/ExecutionEngine/MCJIT/test-branch.ll12
-rw-r--r--test/ExecutionEngine/MCJIT/test-call-no-external-funcs.ll14
-rw-r--r--test/ExecutionEngine/MCJIT/test-call.ll21
-rw-r--r--test/ExecutionEngine/MCJIT/test-cast.ll109
-rw-r--r--test/ExecutionEngine/MCJIT/test-common-symbols.ll88
-rw-r--r--test/ExecutionEngine/MCJIT/test-constantexpr.ll12
-rw-r--r--test/ExecutionEngine/MCJIT/test-fp-no-external-funcs.ll21
-rw-r--r--test/ExecutionEngine/MCJIT/test-fp.ll23
-rw-r--r--test/ExecutionEngine/MCJIT/test-global-init-nonzero.ll34
-rw-r--r--test/ExecutionEngine/MCJIT/test-global.ll34
-rw-r--r--test/ExecutionEngine/MCJIT/test-loadstore.ll31
-rw-r--r--test/ExecutionEngine/MCJIT/test-local.ll34
-rw-r--r--test/ExecutionEngine/MCJIT/test-logical.ll18
-rw-r--r--test/ExecutionEngine/MCJIT/test-loop.ll14
-rw-r--r--test/ExecutionEngine/MCJIT/test-phi.ll34
-rw-r--r--test/ExecutionEngine/MCJIT/test-ret.ll46
-rw-r--r--test/ExecutionEngine/MCJIT/test-return.ll8
-rw-r--r--test/ExecutionEngine/MCJIT/test-setcond-fp.ll24
-rw-r--r--test/ExecutionEngine/MCJIT/test-setcond-int.ll69
-rw-r--r--test/ExecutionEngine/MCJIT/test-shift.ll32
-rw-r--r--test/ExecutionEngine/fpbitcast.ll20
-rw-r--r--test/ExecutionEngine/hello.ll12
-rw-r--r--test/ExecutionEngine/hello2.ll18
-rw-r--r--test/ExecutionEngine/lit.local.cfg1
-rw-r--r--test/ExecutionEngine/simplesttest.ll6
-rw-r--r--test/ExecutionEngine/simpletest.ll12
-rw-r--r--test/ExecutionEngine/stubs.ll36
-rw-r--r--test/ExecutionEngine/test-arith.ll34
-rw-r--r--test/ExecutionEngine/test-branch.ll12
-rw-r--r--test/ExecutionEngine/test-call-no-external-funcs.ll15
-rw-r--r--test/ExecutionEngine/test-call.ll22
-rw-r--r--test/ExecutionEngine/test-cast.ll109
-rw-r--r--test/ExecutionEngine/test-common-symbols.ll89
-rw-r--r--test/ExecutionEngine/test-constantexpr.ll12
-rw-r--r--test/ExecutionEngine/test-fp-no-external-funcs.ll21
-rw-r--r--test/ExecutionEngine/test-fp.ll23
-rw-r--r--test/ExecutionEngine/test-global-init-nonzero.ll35
-rw-r--r--test/ExecutionEngine/test-global.ll35
-rw-r--r--test/ExecutionEngine/test-loadstore.ll32
-rw-r--r--test/ExecutionEngine/test-local.ll35
-rw-r--r--test/ExecutionEngine/test-logical.ll18
-rw-r--r--test/ExecutionEngine/test-loop.ll14
-rw-r--r--test/ExecutionEngine/test-phi.ll34
-rw-r--r--test/ExecutionEngine/test-ret.ll46
-rw-r--r--test/ExecutionEngine/test-return.ll8
-rw-r--r--test/ExecutionEngine/test-setcond-fp.ll24
-rw-r--r--test/ExecutionEngine/test-setcond-int.ll69
-rw-r--r--test/ExecutionEngine/test-shift.ll32
-rw-r--r--test/Feature/NamedMDNode.ll9
-rw-r--r--test/Feature/NamedMDNode2.ll7
-rw-r--r--test/Feature/README.txt6
-rw-r--r--test/Feature/aliases.ll32
-rw-r--r--test/Feature/alignment.ll16
-rw-r--r--test/Feature/basictest.ll31
-rw-r--r--test/Feature/callingconventions.ll55
-rw-r--r--test/Feature/calltest.ll34
-rw-r--r--test/Feature/casttest.ll12
-rw-r--r--test/Feature/cfgstructures.ll53
-rw-r--r--test/Feature/const_pv.ll8
-rw-r--r--test/Feature/constexpr.ll80
-rw-r--r--test/Feature/constpointer.ll31
-rw-r--r--test/Feature/escaped_label.ll11
-rw-r--r--test/Feature/exception.ll27
-rw-r--r--test/Feature/float.ll7
-rw-r--r--test/Feature/fold-fpcast.ll18
-rw-r--r--test/Feature/forwardreftest.ll29
-rw-r--r--test/Feature/global_pv.ll14
-rw-r--r--test/Feature/global_section.ll10
-rw-r--r--test/Feature/globalredefinition3.ll4
-rw-r--r--test/Feature/globalvars.ll18
-rw-r--r--test/Feature/indirectcall.ll49
-rw-r--r--test/Feature/indirectcall2.ll22
-rw-r--r--test/Feature/inlineasm.ll13
-rw-r--r--test/Feature/instructions.ll24
-rw-r--r--test/Feature/intrinsics.ll70
-rw-r--r--test/Feature/linker_private_linkages.ll6
-rw-r--r--test/Feature/lit.local.cfg1
-rw-r--r--test/Feature/load_module.ll12
-rw-r--r--test/Feature/md_on_instruction.ll22
-rw-r--r--test/Feature/memorymarkers.ll36
-rw-r--r--test/Feature/metadata.ll17
-rw-r--r--test/Feature/newcasts.ll33
-rw-r--r--test/Feature/packed.ll15
-rw-r--r--test/Feature/packed_struct.ll33
-rw-r--r--test/Feature/paramattrs.ll24
-rw-r--r--test/Feature/ppcld.ll26
-rw-r--r--test/Feature/properties.ll7
-rw-r--r--test/Feature/prototype.ll11
-rw-r--r--test/Feature/recursivetype.ll103
-rw-r--r--test/Feature/simplecalltest.ll24
-rw-r--r--test/Feature/small.ll11
-rw-r--r--test/Feature/smallest.ll4
-rw-r--r--test/Feature/sparcld.ll24
-rw-r--r--test/Feature/terminators.ll43
-rw-r--r--test/Feature/testalloca.ll22
-rw-r--r--test/Feature/testconstants.ll29
-rw-r--r--test/Feature/testlogical.ll11
-rw-r--r--test/Feature/testtype.ll21
-rw-r--r--test/Feature/testvarargs.ll12
-rw-r--r--test/Feature/undefined.ll17
-rw-r--r--test/Feature/unreachable.ll15
-rw-r--r--test/Feature/varargs.ll29
-rw-r--r--test/Feature/varargs_new.ll38
-rw-r--r--test/Feature/vector-cast-constant-exprs.ll37
-rw-r--r--test/Feature/weak_constant.ll38
-rw-r--r--test/Feature/weirdnames.ll9
-rw-r--r--test/Feature/x86ld.ll26
-rw-r--r--test/Instrumentation/AddressSanitizer/X86/bug_11395.ll71
-rw-r--r--test/Instrumentation/AddressSanitizer/X86/lit.local.cfg13
-rw-r--r--test/Instrumentation/AddressSanitizer/asan-vs-gvn.ll56
-rw-r--r--test/Instrumentation/AddressSanitizer/basic.ll71
-rw-r--r--test/Instrumentation/AddressSanitizer/do-not-touch-odr-global.ll6
-rw-r--r--test/Instrumentation/AddressSanitizer/do-not-touch-threadlocal.ll6
-rw-r--r--test/Instrumentation/AddressSanitizer/instrument-no-return.ll17
-rw-r--r--test/Instrumentation/AddressSanitizer/instrument_global.ll20
-rw-r--r--test/Instrumentation/AddressSanitizer/instrument_initializer_metadata.ll36
-rw-r--r--test/Instrumentation/AddressSanitizer/instrument_load_then_store.ll25
-rw-r--r--test/Instrumentation/AddressSanitizer/lit.local.cfg1
-rw-r--r--test/Instrumentation/AddressSanitizer/test64.ll36
-rw-r--r--test/Instrumentation/BoundsChecking/lit.local.cfg1
-rw-r--r--test/Instrumentation/BoundsChecking/many-trap.ll16
-rw-r--r--test/Instrumentation/BoundsChecking/phi.ll52
-rw-r--r--test/Instrumentation/BoundsChecking/simple.ll128
-rw-r--r--test/Instrumentation/ThreadSanitizer/atomic.ll323
-rw-r--r--test/Instrumentation/ThreadSanitizer/lit.local.cfg1
-rw-r--r--test/Instrumentation/ThreadSanitizer/read_before_write.ll32
-rw-r--r--test/Instrumentation/ThreadSanitizer/read_from_global.ll61
-rw-r--r--test/Instrumentation/ThreadSanitizer/tsan_basic.ll22
-rw-r--r--test/Instrumentation/ThreadSanitizer/vptr_update.ll13
-rw-r--r--test/Integer/2007-01-19-TruncSext.ll29
-rw-r--r--test/Integer/BitPacked.ll21
-rw-r--r--test/Integer/basictest_bt.ll31
-rw-r--r--test/Integer/constexpr_bt.ll84
-rw-r--r--test/Integer/constpointer_bt.ll32
-rw-r--r--test/Integer/fold-fpcast_bt.ll33
-rw-r--r--test/Integer/instructions_bt.ll26
-rw-r--r--test/Integer/lit.local.cfg1
-rw-r--r--test/Integer/newcasts_bt.ll28
-rw-r--r--test/Integer/packed_bt.ll16
-rw-r--r--test/Integer/packed_struct_bt.ll33
-rw-r--r--test/Integer/properties_bt.ll9
-rw-r--r--test/Integer/undefined_bt.ll18
-rw-r--r--test/Integer/unreachable_bt.ll16
-rw-r--r--test/Linker/2002-07-17-GlobalFail.ll8
-rw-r--r--test/Linker/2002-07-17-LinkTest2.ll10
-rw-r--r--test/Linker/2002-08-20-ConstantExpr.ll9
-rw-r--r--test/Linker/2003-01-30-LinkerRename.ll9
-rw-r--r--test/Linker/2003-01-30-LinkerTypeRename.ll10
-rw-r--r--test/Linker/2003-04-23-LinkOnceLost.ll10
-rw-r--r--test/Linker/2003-04-26-NullPtrLinkProblem.ll17
-rw-r--r--test/Linker/2003-05-15-TypeProblem.ll10
-rw-r--r--test/Linker/2003-05-31-LinkerRename.ll17
-rw-r--r--test/Linker/2003-06-02-TypeResolveProblem.ll7
-rw-r--r--test/Linker/2003-06-02-TypeResolveProblem2.ll7
-rw-r--r--test/Linker/2003-08-20-OpaqueTypeResolve.ll8
-rw-r--r--test/Linker/2003-08-23-GlobalVarLinking.ll10
-rw-r--r--test/Linker/2003-08-23-RecursiveOpaqueTypeResolve.ll10
-rw-r--r--test/Linker/2003-08-24-InheritPtrSize.ll9
-rw-r--r--test/Linker/2003-08-28-TypeResolvesGlobal.ll12
-rw-r--r--test/Linker/2003-08-28-TypeResolvesGlobal2.ll18
-rw-r--r--test/Linker/2003-08-28-TypeResolvesGlobal3.ll15
-rw-r--r--test/Linker/2003-10-27-LinkOncePromote.ll8
-rw-r--r--test/Linker/2003-11-18-TypeResolution.ll20
-rw-r--r--test/Linker/2004-02-17-WeakStrongLinkage.ll7
-rw-r--r--test/Linker/2004-05-07-TypeResolution1.ll35
-rw-r--r--test/Linker/2004-05-07-TypeResolution2.ll15
-rw-r--r--test/Linker/2004-12-03-DisagreeingType.ll9
-rw-r--r--test/Linker/2005-02-12-ConstantGlobals-2.ll8
-rw-r--r--test/Linker/2005-02-12-ConstantGlobals.ll8
-rw-r--r--test/Linker/2005-12-06-AppendingZeroLengthArrays.ll10
-rw-r--r--test/Linker/2006-01-19-ConstantPacked.ll13
-rw-r--r--test/Linker/2006-06-15-GlobalVarAlignment.ll7
-rw-r--r--test/Linker/2008-03-05-AliasReference.ll17
-rw-r--r--test/Linker/2008-03-05-AliasReference2.ll11
-rw-r--r--test/Linker/2008-03-07-DroppedSection_a.ll11
-rw-r--r--test/Linker/2008-03-07-DroppedSection_b.ll10
-rw-r--r--test/Linker/2008-06-13-LinkOnceRedefinition.ll8
-rw-r--r--test/Linker/2008-06-26-AddressSpace.ll9
-rw-r--r--test/Linker/2008-07-06-AliasFnDecl.ll14
-rw-r--r--test/Linker/2008-07-06-AliasFnDecl2.ll13
-rw-r--r--test/Linker/2008-07-06-AliasWeakDest.ll18
-rw-r--r--test/Linker/2008-07-06-AliasWeakDest2.ll18
-rw-r--r--test/Linker/2009-09-03-mdnode.ll30
-rw-r--r--test/Linker/2009-09-03-mdnode2.ll25
-rw-r--r--test/Linker/2011-08-04-DebugLoc.ll26
-rw-r--r--test/Linker/2011-08-04-DebugLoc2.ll23
-rw-r--r--test/Linker/2011-08-04-Metadata.ll29
-rw-r--r--test/Linker/2011-08-04-Metadata2.ll29
-rw-r--r--test/Linker/2011-08-18-unique-class-type.ll35
-rw-r--r--test/Linker/2011-08-18-unique-class-type2.ll35
-rw-r--r--test/Linker/2011-08-18-unique-debug-type.ll26
-rw-r--r--test/Linker/2011-08-18-unique-debug-type2.ll25
-rw-r--r--test/Linker/2011-08-22-ResolveAlias.ll89
-rw-r--r--test/Linker/2011-08-22-ResolveAlias2.ll92
-rw-r--r--test/Linker/AppendingLinkage.ll15
-rw-r--r--test/Linker/AppendingLinkage2.ll8
-rw-r--r--test/Linker/ConstantGlobals1.ll9
-rw-r--r--test/Linker/ConstantGlobals2.ll9
-rw-r--r--test/Linker/ConstantGlobals3.ll8
-rw-r--r--test/Linker/Inputs/PR11464.a.ll3
-rw-r--r--test/Linker/Inputs/PR11464.b.ll13
-rw-r--r--test/Linker/Inputs/PR8300.a.ll2
-rw-r--r--test/Linker/Inputs/PR8300.b.ll9
-rw-r--r--test/Linker/Inputs/basiclink.a.ll2
-rw-r--r--test/Linker/Inputs/basiclink.b.ll6
-rw-r--r--test/Linker/Inputs/linkage.a.ll2
-rw-r--r--test/Linker/Inputs/linkage.b.ll10
-rw-r--r--test/Linker/LinkOnce.ll8
-rw-r--r--test/Linker/PR8300.ll1
-rw-r--r--test/Linker/available_externally_a.ll5
-rw-r--r--test/Linker/available_externally_b.ll4
-rw-r--r--test/Linker/basiclink.ll6
-rw-r--r--test/Linker/inlineasm.ll17
-rw-r--r--test/Linker/link-global-to-func.ll13
-rw-r--r--test/Linker/link-messages.ll10
-rw-r--r--test/Linker/link-type-names.ll10
-rw-r--r--test/Linker/linkage.ll3
-rw-r--r--test/Linker/linkmdnode.ll13
-rw-r--r--test/Linker/linkmdnode2.ll22
-rw-r--r--test/Linker/linknamedmdnode.ll6
-rw-r--r--test/Linker/linknamedmdnode2.ll6
-rw-r--r--test/Linker/lit.local.cfg1
-rw-r--r--test/Linker/metadata-a.ll15
-rw-r--r--test/Linker/metadata-b.ll9
-rw-r--r--test/Linker/module-flags-1-a.ll16
-rw-r--r--test/Linker/module-flags-1-b.ll8
-rw-r--r--test/Linker/module-flags-2-a.ll10
-rw-r--r--test/Linker/module-flags-2-b.ll6
-rw-r--r--test/Linker/module-flags-3-a.ll14
-rw-r--r--test/Linker/module-flags-3-b.ll8
-rw-r--r--test/Linker/module-flags-4-a.ll10
-rw-r--r--test/Linker/module-flags-4-b.ll8
-rw-r--r--test/Linker/module-flags-5-a.ll9
-rw-r--r--test/Linker/module-flags-5-b.ll6
-rw-r--r--test/Linker/module-flags-6-a.ll9
-rw-r--r--test/Linker/module-flags-6-b.ll6
-rw-r--r--test/Linker/multiple-merged-structs.ll2
-rw-r--r--test/Linker/partial-type-refinement-link.ll20
-rw-r--r--test/Linker/partial-type-refinement.ll24
-rw-r--r--test/Linker/redefinition.ll10
-rw-r--r--test/Linker/testlink1.ll95
-rw-r--r--test/Linker/testlink2.ll55
-rw-r--r--test/Linker/unnamed-addr1-a.ll27
-rw-r--r--test/Linker/unnamed-addr1-b.ll12
-rw-r--r--test/Linker/visibility1.ll46
-rw-r--r--test/Linker/visibility2.ll27
-rw-r--r--test/Linker/weakextern.ll11
-rw-r--r--test/MC/ARM/arm-aliases.s17
-rw-r--r--test/MC/ARM/arm-arithmetic-aliases.s126
-rw-r--r--test/MC/ARM/arm-it-block.s11
-rw-r--r--test/MC/ARM/arm-memory-instructions.s484
-rw-r--r--test/MC/ARM/arm_addrmode2.s34
-rw-r--r--test/MC/ARM/arm_addrmode3.s18
-rw-r--r--test/MC/ARM/arm_fixups.s22
-rw-r--r--test/MC/ARM/arm_instructions.s79
-rw-r--r--test/MC/ARM/arm_word_directive.s6
-rw-r--r--test/MC/ARM/basic-arm-instructions.s2853
-rw-r--r--test/MC/ARM/basic-thumb-instructions.s637
-rw-r--r--test/MC/ARM/basic-thumb2-instructions.s3511
-rw-r--r--test/MC/ARM/bracket-darwin.s5
-rw-r--r--test/MC/ARM/bracket-exprs.s15
-rw-r--r--test/MC/ARM/cxx-global-constructor.ll12
-rw-r--r--test/MC/ARM/diagnostics.s323
-rw-r--r--test/MC/ARM/dot-req.s11
-rw-r--r--test/MC/ARM/elf-eflags-eabi.s13
-rw-r--r--test/MC/ARM/elf-movt.s39
-rw-r--r--test/MC/ARM/elf-reloc-01.ll70
-rw-r--r--test/MC/ARM/elf-reloc-02.ll50
-rw-r--r--test/MC/ARM/elf-reloc-03.ll97
-rw-r--r--test/MC/ARM/elf-reloc-condcall.s33
-rw-r--r--test/MC/ARM/elf-thumbfunc-reloc.ll37
-rw-r--r--test/MC/ARM/elf-thumbfunc-reloc.s23
-rw-r--r--test/MC/ARM/elf-thumbfunc.s20
-rw-r--r--test/MC/ARM/full_line_comment.s8
-rw-r--r--test/MC/ARM/hilo-16bit-relocations.s20
-rw-r--r--test/MC/ARM/lit.local.cfg6
-rw-r--r--test/MC/ARM/mode-switch.s26
-rw-r--r--test/MC/ARM/neon-abs-encoding.s31
-rw-r--r--test/MC/ARM/neon-absdiff-encoding.s82
-rw-r--r--test/MC/ARM/neon-add-encoding.s274
-rw-r--r--test/MC/ARM/neon-bitcount-encoding.s31
-rw-r--r--test/MC/ARM/neon-bitwise-encoding.s274
-rw-r--r--test/MC/ARM/neon-cmp-encoding.s176
-rw-r--r--test/MC/ARM/neon-convert-encoding.s38
-rw-r--r--test/MC/ARM/neon-dup-encoding.s33
-rw-r--r--test/MC/ARM/neon-minmax-encoding.s124
-rw-r--r--test/MC/ARM/neon-mov-encoding.s130
-rw-r--r--test/MC/ARM/neon-mul-accum-encoding.s94
-rw-r--r--test/MC/ARM/neon-mul-encoding.s168
-rw-r--r--test/MC/ARM/neon-neg-encoding.s30
-rw-r--r--test/MC/ARM/neon-pairwise-encoding.s96
-rw-r--r--test/MC/ARM/neon-reciprocal-encoding.s26
-rw-r--r--test/MC/ARM/neon-reverse-encoding.s26
-rw-r--r--test/MC/ARM/neon-satshift-encoding.s150
-rw-r--r--test/MC/ARM/neon-shift-encoding.s535
-rw-r--r--test/MC/ARM/neon-shiftaccum-encoding.s209
-rw-r--r--test/MC/ARM/neon-shuffle-encoding.s136
-rw-r--r--test/MC/ARM/neon-sub-encoding.s175
-rw-r--r--test/MC/ARM/neon-table-encoding.s22
-rw-r--r--test/MC/ARM/neon-vld-encoding.s497
-rw-r--r--test/MC/ARM/neon-vst-encoding.s278
-rw-r--r--test/MC/ARM/neon-vswp.s7
-rw-r--r--test/MC/ARM/neont2-abs-encoding.s33
-rw-r--r--test/MC/ARM/neont2-absdiff-encoding.s91
-rw-r--r--test/MC/ARM/neont2-add-encoding.s138
-rw-r--r--test/MC/ARM/neont2-bitcount-encoding.s38
-rw-r--r--test/MC/ARM/neont2-bitwise-encoding.s55
-rw-r--r--test/MC/ARM/neont2-cmp-encoding.s36
-rw-r--r--test/MC/ARM/neont2-convert-encoding.s40
-rw-r--r--test/MC/ARM/neont2-dup-encoding.s43
-rw-r--r--test/MC/ARM/neont2-minmax-encoding.s126
-rw-r--r--test/MC/ARM/neont2-mov-encoding.s131
-rw-r--r--test/MC/ARM/neont2-mul-accum-encoding.s100
-rw-r--r--test/MC/ARM/neont2-mul-encoding.s78
-rw-r--r--test/MC/ARM/neont2-neg-encoding.s32
-rw-r--r--test/MC/ARM/neont2-pairwise-encoding.s100
-rw-r--r--test/MC/ARM/neont2-reciprocal-encoding.s28
-rw-r--r--test/MC/ARM/neont2-reverse-encoding.s26
-rw-r--r--test/MC/ARM/neont2-satshift-encoding.s152
-rw-r--r--test/MC/ARM/neont2-shift-encoding.s162
-rw-r--r--test/MC/ARM/neont2-shiftaccum-encoding.s212
-rw-r--r--test/MC/ARM/neont2-shuffle-encoding.s48
-rw-r--r--test/MC/ARM/neont2-sub-encoding.s46
-rw-r--r--test/MC/ARM/neont2-table-encoding.s24
-rw-r--r--test/MC/ARM/neont2-vld-encoding.s112
-rw-r--r--test/MC/ARM/neont2-vst-encoding.s107
-rw-r--r--test/MC/ARM/pr11877.s6
-rw-r--r--test/MC/ARM/simple-fp-encoding.s375
-rw-r--r--test/MC/ARM/thumb-diagnostics.s158
-rw-r--r--test/MC/ARM/thumb-nop.s9
-rw-r--r--test/MC/ARM/thumb.s51
-rw-r--r--test/MC/ARM/thumb2-diagnostics.s44
-rw-r--r--test/MC/ARM/thumb2-mclass.s98
-rw-r--r--test/MC/ARM/thumb2-narrow-dp.ll807
-rw-r--r--test/MC/ARM/vfp4.s54
-rw-r--r--test/MC/ARM/vpush-vpop.s34
-rw-r--r--test/MC/ARM/xscale-attributes.ll31
-rw-r--r--test/MC/AsmParser/assignment.s11
-rw-r--r--test/MC/AsmParser/bad-macro.s9
-rw-r--r--test/MC/AsmParser/cfi-unfinished-frame.s5
-rw-r--r--test/MC/AsmParser/conditional_asm.s12
-rw-r--r--test/MC/AsmParser/dash-n.s7
-rw-r--r--test/MC/AsmParser/directive_abort.s6
-rw-r--r--test/MC/AsmParser/directive_align.s16
-rw-r--r--test/MC/AsmParser/directive_ascii.s41
-rw-r--r--test/MC/AsmParser/directive_comm.s10
-rw-r--r--test/MC/AsmParser/directive_darwin_section.s4
-rw-r--r--test/MC/AsmParser/directive_desc.s8
-rw-r--r--test/MC/AsmParser/directive_elf_size.s8
-rw-r--r--test/MC/AsmParser/directive_file-errors.s9
-rw-r--r--test/MC/AsmParser/directive_file.s9
-rw-r--r--test/MC/AsmParser/directive_fill.s17
-rw-r--r--test/MC/AsmParser/directive_incbin.s6
-rw-r--r--test/MC/AsmParser/directive_include.s9
-rw-r--r--test/MC/AsmParser/directive_lcomm.s15
-rw-r--r--test/MC/AsmParser/directive_line.s5
-rw-r--r--test/MC/AsmParser/directive_loc.s8
-rw-r--r--test/MC/AsmParser/directive_lsym.s13
-rw-r--r--test/MC/AsmParser/directive_org.s11
-rw-r--r--test/MC/AsmParser/directive_seh.s48
-rw-r--r--test/MC/AsmParser/directive_set.s12
-rw-r--r--test/MC/AsmParser/directive_space.s16
-rw-r--r--test/MC/AsmParser/directive_subsections_via_symbols.s6
-rw-r--r--test/MC/AsmParser/directive_symbol_attrs.s7
-rw-r--r--test/MC/AsmParser/directive_tbss.s7
-rw-r--r--test/MC/AsmParser/directive_tdata.s9
-rw-r--r--test/MC/AsmParser/directive_thread_init_func.s7
-rw-r--r--test/MC/AsmParser/directive_tlv.s13
-rw-r--r--test/MC/AsmParser/directive_values.s65
-rw-r--r--test/MC/AsmParser/directive_zerofill.s14
-rw-r--r--test/MC/AsmParser/dollars-in-identifiers.s7
-rw-r--r--test/MC/AsmParser/dot-symbol.s12
-rw-r--r--test/MC/AsmParser/equ.s9
-rw-r--r--test/MC/AsmParser/expr_symbol_modifiers.s14
-rw-r--r--test/MC/AsmParser/exprs-invalid.s14
-rw-r--r--test/MC/AsmParser/exprs.s78
-rw-r--r--test/MC/AsmParser/extern.s4
-rw-r--r--test/MC/AsmParser/floating-literals.s44
-rw-r--r--test/MC/AsmParser/hello.s28
-rw-r--r--test/MC/AsmParser/ifb.s67
-rw-r--r--test/MC/AsmParser/ifc.s65
-rw-r--r--test/MC/AsmParser/ifdef.s29
-rw-r--r--test/MC/AsmParser/ifndef.s29
-rw-r--r--test/MC/AsmParser/incbin_abcd1
-rw-r--r--test/MC/AsmParser/labels.s56
-rw-r--r--test/MC/AsmParser/line_with_hash.s15
-rw-r--r--test/MC/AsmParser/lit.local.cfg6
-rw-r--r--test/MC/AsmParser/macro-args.s56
-rw-r--r--test/MC/AsmParser/macro-def-in-instantiation.s13
-rw-r--r--test/MC/AsmParser/macro-err1.s10
-rw-r--r--test/MC/AsmParser/macro-irp.s8
-rw-r--r--test/MC/AsmParser/macro-irpc.s9
-rw-r--r--test/MC/AsmParser/macro-rept-err1.s6
-rw-r--r--test/MC/AsmParser/macro-rept-err2.s7
-rw-r--r--test/MC/AsmParser/macro-rept.s22
-rw-r--r--test/MC/AsmParser/macros-parsing.s23
-rw-r--r--test/MC/AsmParser/macros.s60
-rw-r--r--test/MC/AsmParser/pr11865.s6
-rw-r--r--test/MC/AsmParser/purgem.s12
-rw-r--r--test/MC/AsmParser/rename.s14
-rw-r--r--test/MC/AsmParser/section.s107
-rw-r--r--test/MC/AsmParser/variables-invalid.s28
-rw-r--r--test/MC/AsmParser/variables.s15
-rw-r--r--test/MC/COFF/align-nops.s50
-rw-r--r--test/MC/COFF/basic-coff.s133
-rw-r--r--test/MC/COFF/bss.s15
-rw-r--r--test/MC/COFF/comm.ll13
-rw-r--r--test/MC/COFF/diff.s46
-rw-r--r--test/MC/COFF/global_ctors.ll28
-rw-r--r--test/MC/COFF/lit.local.cfg6
-rw-r--r--test/MC/COFF/module-asm.ll26
-rw-r--r--test/MC/COFF/secrel32.s14
-rw-r--r--test/MC/COFF/seh-section.s37
-rw-r--r--test/MC/COFF/seh.s59
-rw-r--r--test/MC/COFF/simple-fixups.s50
-rw-r--r--test/MC/COFF/switch-relocations.ll37
-rw-r--r--test/MC/COFF/symbol-alias.s62
-rw-r--r--test/MC/COFF/symbol-fragment-offset.s187
-rw-r--r--test/MC/COFF/symbol-mangling.ll17
-rw-r--r--test/MC/COFF/weak.s51
-rw-r--r--test/MC/Disassembler/ARM/arm-tests.txt326
-rw-r--r--test/MC/Disassembler/ARM/basic-arm-instructions.txt2398
-rw-r--r--test/MC/Disassembler/ARM/fp-encoding.txt240
-rw-r--r--test/MC/Disassembler/ARM/invalid-BFI-arm.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-Bcc-thumb.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-CPS2p-arm.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-CPS3p-arm.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-DMB-thumb.txt16
-rw-r--r--test/MC/Disassembler/ARM/invalid-DSB-arm.txt16
-rw-r--r--test/MC/Disassembler/ARM/invalid-IT-CBNZ-thumb.txt5
-rw-r--r--test/MC/Disassembler/ARM/invalid-IT-CC15.txt18
-rw-r--r--test/MC/Disassembler/ARM/invalid-IT-thumb.txt3
-rw-r--r--test/MC/Disassembler/ARM/invalid-LDC-form-arm.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-LDM-thumb.txt5
-rw-r--r--test/MC/Disassembler/ARM/invalid-LDRB_POST-arm.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-LDRD_PRE-thumb.txt13
-rw-r--r--test/MC/Disassembler/ARM/invalid-LDR_POST-arm.txt5
-rw-r--r--test/MC/Disassembler/ARM/invalid-LDR_PRE-arm.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-LDRrs-arm.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-MCR-arm.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-MOVTi16-arm.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-MOVr-arm.txt13
-rw-r--r--test/MC/Disassembler/ARM/invalid-MOVs-LSL-arm.txt9
-rw-r--r--test/MC/Disassembler/ARM/invalid-MOVs-arm.txt17
-rw-r--r--test/MC/Disassembler/ARM/invalid-MRRC2-arm.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-MSRi-arm.txt12
-rw-r--r--test/MC/Disassembler/ARM/invalid-RFEorLDMIA-arm.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-SBFX-arm.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-SMLAD-arm.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-SRS-arm.txt13
-rw-r--r--test/MC/Disassembler/ARM/invalid-STMIA_UPD-thumb.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-SXTB-arm.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-UMAAL-arm.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-VLD1DUPq8_UPD-arm.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-VLD1LNd32_UPD-thumb.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-VLD3DUPd32_UPD-thumb.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-VLD4DUPd32_UPD-thumb.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-VLD4LNd32_UPD-thumb.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-VLDMSDB_UPD-arm.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-VQADD-arm.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-VST1LNd32_UPD-thumb.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-VST1d8Twb_register-thumb.txt13
-rw-r--r--test/MC/Disassembler/ARM/invalid-VST2b32_UPD-arm.txt12
-rw-r--r--test/MC/Disassembler/ARM/invalid-VST4LNd32_UPD-thumb.txt4
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2Bcc-thumb.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2LDRBT-thumb.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2LDREXD-thumb.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2LDRSHi12-thumb.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2LDRSHi8-thumb.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2PUSH-thumb.txt5
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2STRD_PRE-thumb.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2STREXB-thumb.txt11
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2STREXD-thumb.txt10
-rw-r--r--test/MC/Disassembler/ARM/invalid-t2STR_POST-thumb.txt10
-rw-r--r--test/MC/Disassembler/ARM/ldrd-armv4.txt15
-rw-r--r--test/MC/Disassembler/ARM/lit.local.cfg6
-rw-r--r--test/MC/Disassembler/ARM/memory-arm-instructions.txt470
-rw-r--r--test/MC/Disassembler/ARM/neon-tests.txt91
-rw-r--r--test/MC/Disassembler/ARM/neon.txt2336
-rw-r--r--test/MC/Disassembler/ARM/neont-VLD-reencoding.txt77
-rw-r--r--test/MC/Disassembler/ARM/neont-VST-reencoding.txt77
-rw-r--r--test/MC/Disassembler/ARM/neont2.txt2054
-rw-r--r--test/MC/Disassembler/ARM/thumb-MSR-MClass.txt7
-rw-r--r--test/MC/Disassembler/ARM/thumb-printf.txt77
-rw-r--r--test/MC/Disassembler/ARM/thumb-tests.txt311
-rw-r--r--test/MC/Disassembler/ARM/thumb1.txt527
-rw-r--r--test/MC/Disassembler/ARM/thumb2.txt2600
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-ADC-arm.txt17
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-ADDREXT3-arm.txt16
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-AExtI-arm.txt62
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-AI1cmp-arm.txt30
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-LDR-arm.txt22
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-LDRD-arm.txt13
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-LSL-regform.txt13
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-MRRC2-arm.txt13
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-MRS-arm.txt18
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-MUL-arm.txt17
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-RSC-arm.txt11
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-SEL-arm.txt5
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-SHADD16-arm.txt7
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-SSAT-arm.txt13
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-STRBrs-arm.txt12
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-UQADD8-arm.txt16
-rw-r--r--test/MC/Disassembler/ARM/unpredictable-swp-arm.txt26
-rw-r--r--test/MC/Disassembler/ARM/unpredictables-thumb.txt5
-rw-r--r--test/MC/Disassembler/ARM/vfp4.txt37
-rw-r--r--test/MC/Disassembler/MBlaze/lit.local.cfg6
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_branch.txt119
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_fpu.txt47
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_fsl.txt338
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_imm.txt121
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_mbar.txt14
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_memory.txt65
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_operands.txt197
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_pattern.txt17
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_shift.txt29
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_special.txt105
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_typea.txt74
-rw-r--r--test/MC/Disassembler/MBlaze/mblaze_typeb.txt56
-rw-r--r--test/MC/Disassembler/Mips/lit.local.cfg6
-rw-r--r--test/MC/Disassembler/Mips/mips32.txt406
-rw-r--r--test/MC/Disassembler/Mips/mips32_le.txt406
-rw-r--r--test/MC/Disassembler/Mips/mips32r2.txt430
-rw-r--r--test/MC/Disassembler/Mips/mips32r2_le.txt430
-rw-r--r--test/MC/Disassembler/Mips/mips64.txt67
-rw-r--r--test/MC/Disassembler/Mips/mips64_le.txt67
-rw-r--r--test/MC/Disassembler/Mips/mips64r2.txt91
-rw-r--r--test/MC/Disassembler/Mips/mips64r2_le.txt91
-rw-r--r--test/MC/Disassembler/X86/enhanced.txt10
-rw-r--r--test/MC/Disassembler/X86/intel-syntax.txt112
-rw-r--r--test/MC/Disassembler/X86/invalid-VEX-vvvv.txt4
-rw-r--r--test/MC/Disassembler/X86/invalid-cmp-imm.txt10
-rw-r--r--test/MC/Disassembler/X86/lit.local.cfg6
-rw-r--r--test/MC/Disassembler/X86/simple-tests.txt755
-rw-r--r--test/MC/Disassembler/X86/truncated-input.txt4
-rw-r--r--test/MC/Disassembler/X86/x86-32.txt632
-rw-r--r--test/MC/Disassembler/X86/x86-64.txt81
-rw-r--r--test/MC/ELF/abs.s16
-rw-r--r--test/MC/ELF/alias-reloc.s52
-rw-r--r--test/MC/ELF/alias.s85
-rw-r--r--test/MC/ELF/align-bss.s17
-rw-r--r--test/MC/ELF/align-nops.s40
-rw-r--r--test/MC/ELF/align-size.s13
-rw-r--r--test/MC/ELF/align-text.s19
-rw-r--r--test/MC/ELF/align.s32
-rw-r--r--test/MC/ELF/bad-section.s9
-rw-r--r--test/MC/ELF/basic-elf-32.s78
-rw-r--r--test/MC/ELF/basic-elf-64.s82
-rw-r--r--test/MC/ELF/bracket-exprs.s15
-rw-r--r--test/MC/ELF/bracket.s8
-rw-r--r--test/MC/ELF/bss.ll8
-rw-r--r--test/MC/ELF/call-abs.s24
-rw-r--r--test/MC/ELF/cfi-adjust-cfa-offset.s46
-rw-r--r--test/MC/ELF/cfi-advance-loc2.s45
-rw-r--r--test/MC/ELF/cfi-def-cfa-offset.s46
-rw-r--r--test/MC/ELF/cfi-def-cfa-register.s41
-rw-r--r--test/MC/ELF/cfi-def-cfa.s42
-rw-r--r--test/MC/ELF/cfi-escape.s42
-rw-r--r--test/MC/ELF/cfi-offset.s42
-rw-r--r--test/MC/ELF/cfi-reg.s18
-rw-r--r--test/MC/ELF/cfi-rel-offset.s49
-rw-r--r--test/MC/ELF/cfi-rel-offset2.s41
-rw-r--r--test/MC/ELF/cfi-remember.s45
-rw-r--r--test/MC/ELF/cfi-restore.s42
-rw-r--r--test/MC/ELF/cfi-same-value.s42
-rw-r--r--test/MC/ELF/cfi-sections.s38
-rw-r--r--test/MC/ELF/cfi-signal-frame.s23
-rw-r--r--test/MC/ELF/cfi-zero-addr-delta.s48
-rw-r--r--test/MC/ELF/cfi.s674
-rw-r--r--test/MC/ELF/comdat.s86
-rw-r--r--test/MC/ELF/common.s88
-rw-r--r--test/MC/ELF/common2.s21
-rw-r--r--test/MC/ELF/debug-line.s22
-rw-r--r--test/MC/ELF/debug-loc.s32
-rw-r--r--test/MC/ELF/diff.s15
-rw-r--r--test/MC/ELF/diff2.s13
-rw-r--r--test/MC/ELF/elf_directive_previous.s13
-rw-r--r--test/MC/ELF/elf_directive_section.s23
-rw-r--r--test/MC/ELF/empty-dwarf-lines.s21
-rw-r--r--test/MC/ELF/empty.s70
-rw-r--r--test/MC/ELF/entsize.ll44
-rw-r--r--test/MC/ELF/entsize.s69
-rw-r--r--test/MC/ELF/fde.s28
-rw-r--r--test/MC/ELF/file.s23
-rw-r--r--test/MC/ELF/gen-dwarf.s70
-rw-r--r--test/MC/ELF/global-offset.s23
-rw-r--r--test/MC/ELF/got.s25
-rw-r--r--test/MC/ELF/ident.s17
-rw-r--r--test/MC/ELF/invalid-symver.s7
-rw-r--r--test/MC/ELF/lcomm.s21
-rw-r--r--test/MC/ELF/leb128.s19
-rw-r--r--test/MC/ELF/lit.local.cfg6
-rw-r--r--test/MC/ELF/local-reloc.s31
-rw-r--r--test/MC/ELF/many-section.s93319
-rw-r--r--test/MC/ELF/merge.s97
-rw-r--r--test/MC/ELF/n_bytes.s20
-rw-r--r--test/MC/ELF/no-fixup.s16
-rw-r--r--test/MC/ELF/noexec.s24
-rw-r--r--test/MC/ELF/norelocation.s18
-rw-r--r--test/MC/ELF/org.s13
-rw-r--r--test/MC/ELF/pic-diff.s29
-rw-r--r--test/MC/ELF/plt.s14
-rw-r--r--test/MC/ELF/pr9292.s26
-rw-r--r--test/MC/ELF/relax-arith.s75
-rw-r--r--test/MC/ELF/relax-crash.s11
-rw-r--r--test/MC/ELF/relax.s27
-rw-r--r--test/MC/ELF/relocation-386.s249
-rw-r--r--test/MC/ELF/relocation-pc.s33
-rw-r--r--test/MC/ELF/relocation.s121
-rw-r--r--test/MC/ELF/rename.s46
-rw-r--r--test/MC/ELF/section-quoting.s10
-rw-r--r--test/MC/ELF/section.s110
-rw-r--r--test/MC/ELF/set.s34
-rw-r--r--test/MC/ELF/sleb.s29
-rw-r--r--test/MC/ELF/symref.s165
-rw-r--r--test/MC/ELF/tls-i386.s145
-rw-r--r--test/MC/ELF/tls.s77
-rw-r--r--test/MC/ELF/type.s46
-rw-r--r--test/MC/ELF/uleb.s22
-rw-r--r--test/MC/ELF/undef.s46
-rw-r--r--test/MC/ELF/undef2.s10
-rw-r--r--test/MC/ELF/version.s17
-rw-r--r--test/MC/ELF/weak-relocation.s15
-rw-r--r--test/MC/ELF/weak.s30
-rw-r--r--test/MC/ELF/weakref-plt.s8
-rw-r--r--test/MC/ELF/weakref-reloc.s49
-rw-r--r--test/MC/ELF/weakref.s234
-rw-r--r--test/MC/ELF/x86_64-reloc-sizetest.s13
-rw-r--r--test/MC/ELF/zero.s16
-rw-r--r--test/MC/MBlaze/lit.local.cfg6
-rw-r--r--test/MC/MBlaze/mblaze_branch.s197
-rw-r--r--test/MC/MBlaze/mblaze_fpu.s77
-rw-r--r--test/MC/MBlaze/mblaze_fsl.s568
-rw-r--r--test/MC/MBlaze/mblaze_imm.s194
-rw-r--r--test/MC/MBlaze/mblaze_memory.s107
-rw-r--r--test/MC/MBlaze/mblaze_operands.s328
-rw-r--r--test/MC/MBlaze/mblaze_pattern.s22
-rw-r--r--test/MC/MBlaze/mblaze_shift.s47
-rw-r--r--test/MC/MBlaze/mblaze_special.s167
-rw-r--r--test/MC/MBlaze/mblaze_typea.s122
-rw-r--r--test/MC/MBlaze/mblaze_typeb.s92
-rw-r--r--test/MC/MachO/ARM/darwin-ARM-reloc.s173
-rw-r--r--test/MC/MachO/ARM/darwin-Thumb-reloc.s139
-rw-r--r--test/MC/MachO/ARM/data-in-code.s33
-rw-r--r--test/MC/MachO/ARM/empty-function-nop.ll15
-rw-r--r--test/MC/MachO/ARM/lit.local.cfg6
-rw-r--r--test/MC/MachO/ARM/llvm-objdump-macho-stripped.s5
-rw-r--r--test/MC/MachO/ARM/llvm-objdump-macho.s20
-rw-r--r--test/MC/MachO/ARM/no-subsections-reloc.s18
-rw-r--r--test/MC/MachO/ARM/nop-armv4-padding.s10
-rw-r--r--test/MC/MachO/ARM/nop-armv6t2-padding.s10
-rw-r--r--test/MC/MachO/ARM/nop-thumb-padding.s12
-rw-r--r--test/MC/MachO/ARM/nop-thumb2-padding.s12
-rw-r--r--test/MC/MachO/ARM/relax-thumb-ldr-literal.s13
-rw-r--r--test/MC/MachO/ARM/relax-thumb2-branches.s14
-rw-r--r--test/MC/MachO/ARM/static-movt-relocs.s23
-rw-r--r--test/MC/MachO/ARM/thumb-bl-jbits.s19
-rw-r--r--test/MC/MachO/ARM/thumb2-function-relative-load.s13
-rw-r--r--test/MC/MachO/ARM/thumb2-movt-fixup.s17
-rw-r--r--test/MC/MachO/ARM/thumb2-movw-fixup.s44
-rw-r--r--test/MC/MachO/absolute.s158
-rw-r--r--test/MC/MachO/absolutize.s213
-rw-r--r--test/MC/MachO/comm-1.s114
-rw-r--r--test/MC/MachO/darwin-complex-difference.s129
-rw-r--r--test/MC/MachO/darwin-x86_64-diff-reloc-assign.s27
-rw-r--r--test/MC/MachO/darwin-x86_64-diff-relocs.s329
-rw-r--r--test/MC/MachO/darwin-x86_64-nobase-relocs.s58
-rw-r--r--test/MC/MachO/darwin-x86_64-reloc-offsets.s343
-rw-r--r--test/MC/MachO/darwin-x86_64-reloc.s405
-rw-r--r--test/MC/MachO/data.s67
-rw-r--r--test/MC/MachO/debug_frame.s47
-rw-r--r--test/MC/MachO/diff-with-two-sections.s64
-rw-r--r--test/MC/MachO/direction_labels.s95
-rw-r--r--test/MC/MachO/empty-dwarf-lines.s25
-rw-r--r--test/MC/MachO/file.s22
-rw-r--r--test/MC/MachO/gen-dwarf.s122
-rw-r--r--test/MC/MachO/indirect-symbols.s188
-rw-r--r--test/MC/MachO/jcc.s106
-rw-r--r--test/MC/MachO/lcomm-attributes.s136
-rw-r--r--test/MC/MachO/lit.local.cfg6
-rw-r--r--test/MC/MachO/loc.s25
-rw-r--r--test/MC/MachO/pcrel-to-other-section.s107
-rw-r--r--test/MC/MachO/previous.s13
-rw-r--r--test/MC/MachO/pushsection.s16
-rw-r--r--test/MC/MachO/relax-jumps.s31
-rw-r--r--test/MC/MachO/relax-recompute-align.s37
-rw-r--r--test/MC/MachO/reloc-diff.s55
-rw-r--r--test/MC/MachO/reloc-pcrel-offset.s17
-rw-r--r--test/MC/MachO/reloc-pcrel.s65
-rw-r--r--test/MC/MachO/reloc.s292
-rw-r--r--test/MC/MachO/section-align-1.s87
-rw-r--r--test/MC/MachO/section-align-2.s137
-rw-r--r--test/MC/MachO/section-attributes.s7
-rw-r--r--test/MC/MachO/section-flags.s14
-rw-r--r--test/MC/MachO/string-table.s100
-rw-r--r--test/MC/MachO/symbol-diff.s122
-rw-r--r--test/MC/MachO/symbol-flags.s341
-rw-r--r--test/MC/MachO/symbol-indirect.s268
-rw-r--r--test/MC/MachO/symbols-1.s310
-rw-r--r--test/MC/MachO/tbss.s114
-rw-r--r--test/MC/MachO/tdata.s106
-rw-r--r--test/MC/MachO/temp-labels.s33
-rw-r--r--test/MC/MachO/thread_init_func.s63
-rw-r--r--test/MC/MachO/tls.s270
-rw-r--r--test/MC/MachO/tlv-reloc.s174
-rw-r--r--test/MC/MachO/tlv.s110
-rw-r--r--test/MC/MachO/values.s135
-rw-r--r--test/MC/MachO/variable-errors.s8
-rw-r--r--test/MC/MachO/variable-exprs.s446
-rw-r--r--test/MC/MachO/weakdef.s141
-rw-r--r--test/MC/MachO/x86_32-optimal_nop.s257
-rw-r--r--test/MC/MachO/x86_32-sections.s536
-rw-r--r--test/MC/MachO/x86_32-symbols.s1041
-rw-r--r--test/MC/MachO/x86_64-reloc-arithmetic.s21
-rw-r--r--test/MC/MachO/x86_64-sections.s561
-rw-r--r--test/MC/MachO/x86_64-symbols.s998
-rw-r--r--test/MC/MachO/zerofill-1.s121
-rw-r--r--test/MC/MachO/zerofill-2.s103
-rw-r--r--test/MC/MachO/zerofill-3.s141
-rw-r--r--test/MC/MachO/zerofill-4.s35
-rw-r--r--test/MC/MachO/zerofill-5.s109
-rw-r--r--test/MC/MachO/zerofill-sect-align.s15
-rw-r--r--test/MC/Mips/do_switch.ll39
-rw-r--r--test/MC/Mips/elf-N64.ll39
-rw-r--r--test/MC/Mips/elf-bigendian.ll47
-rw-r--r--test/MC/Mips/elf-objdump.s11
-rw-r--r--test/MC/Mips/elf-relsym.ll29
-rw-r--r--test/MC/Mips/elf-tls.ll36
-rw-r--r--test/MC/Mips/elf_basic.s35
-rw-r--r--test/MC/Mips/higher_highest.ll30
-rw-r--r--test/MC/Mips/lea_64.ll18
-rw-r--r--test/MC/Mips/lit.local.cfg6
-rw-r--r--test/MC/Mips/mips-alu-instructions.s100
-rw-r--r--test/MC/Mips/mips-fpu-instructions.s162
-rw-r--r--test/MC/Mips/mips-jump-instructions.s72
-rw-r--r--test/MC/Mips/mips-memory-instructions.s45
-rw-r--r--test/MC/Mips/mips-relocations.s41
-rw-r--r--test/MC/Mips/mips64extins.ll57
-rw-r--r--test/MC/Mips/mips64shift.ll48
-rw-r--r--test/MC/Mips/mips_directives.s10
-rw-r--r--test/MC/Mips/multi-64bit-func.ll23
-rw-r--r--test/MC/Mips/pr11877.s6
-rw-r--r--test/MC/Mips/r-mips-got-disp.ll18
-rw-r--r--test/MC/Mips/sext_64_32.ll20
-rw-r--r--test/MC/Mips/sym-offset.ll24
-rw-r--r--test/MC/X86/2011-09-06-NoNewline.s3
-rw-r--r--test/MC/X86/3DNow.s92
-rw-r--r--test/MC/X86/address-size.s13
-rw-r--r--test/MC/X86/intel-syntax-2.s9
-rw-r--r--test/MC/X86/intel-syntax-encoding.s57
-rw-r--r--test/MC/X86/intel-syntax.s68
-rw-r--r--test/MC/X86/lit.local.cfg12
-rw-r--r--test/MC/X86/padlock.s57
-rw-r--r--test/MC/X86/x86-32-avx.s3313
-rw-r--r--test/MC/X86/x86-32-coverage.s19654
-rw-r--r--test/MC/X86/x86-32-fma3.s674
-rw-r--r--test/MC/X86/x86-32.s1000
-rw-r--r--test/MC/X86/x86-64.s1230
-rw-r--r--test/MC/X86/x86_64-avx-clmul-encoding.s42
-rw-r--r--test/MC/X86/x86_64-avx-encoding.s4187
-rw-r--r--test/MC/X86/x86_64-bmi-encoding.s202
-rw-r--r--test/MC/X86/x86_64-encoding.s173
-rw-r--r--test/MC/X86/x86_64-fma3-encoding.s674
-rw-r--r--test/MC/X86/x86_64-fma4-encoding.s391
-rw-r--r--test/MC/X86/x86_64-imm-widths.s105
-rw-r--r--test/MC/X86/x86_64-sse4a.s25
-rw-r--r--test/MC/X86/x86_64-xop-encoding.s584
-rw-r--r--test/MC/X86/x86_directives.s6
-rw-r--r--test/MC/X86/x86_errors.s30
-rw-r--r--test/MC/X86/x86_nop.s7
-rw-r--r--test/MC/X86/x86_operands.s58
-rw-r--r--test/Makefile156
-rw-r--r--test/Makefile.tests80
-rw-r--r--test/Object/Inputs/COFF/i386.yaml83
-rw-r--r--test/Object/Inputs/COFF/x86-64.yaml83
-rw-r--r--test/Object/Inputs/archive-test.a-coff-i386bin0 -> 658 bytes
-rw-r--r--test/Object/Inputs/dext-test.elf-mips64r2bin0 -> 802 bytes
-rwxr-xr-xtest/Object/Inputs/elf-versioning-test.i386bin0 -> 4832 bytes
-rwxr-xr-xtest/Object/Inputs/elf-versioning-test.x86_64bin0 -> 5200 bytes
-rw-r--r--test/Object/Inputs/elfver.S31
-rw-r--r--test/Object/Inputs/elfver.script10
-rw-r--r--test/Object/Inputs/relocations.elf-x86-64bin0 -> 1032 bytes
-rw-r--r--test/Object/Inputs/shared-object-test.elf-i386bin0 -> 1848 bytes
-rw-r--r--test/Object/Inputs/shared-object-test.elf-x86-64bin0 -> 2760 bytes
-rw-r--r--test/Object/Inputs/shared.ll33
-rw-r--r--test/Object/Inputs/trivial-object-test.coff-i386bin0 -> 346 bytes
-rw-r--r--test/Object/Inputs/trivial-object-test.coff-x86-64bin0 -> 347 bytes
-rw-r--r--test/Object/Inputs/trivial-object-test.elf-hexagonbin0 -> 800 bytes
-rw-r--r--test/Object/Inputs/trivial-object-test.elf-i386bin0 -> 716 bytes
-rw-r--r--test/Object/Inputs/trivial-object-test.elf-x86-64bin0 -> 1024 bytes
-rw-r--r--test/Object/Inputs/trivial-object-test.macho-i386bin0 -> 552 bytes
-rw-r--r--test/Object/Inputs/trivial-object-test.macho-x86-64bin0 -> 552 bytes
-rw-r--r--test/Object/Inputs/trivial.ll12
-rw-r--r--test/Object/Mips/feature.test11
-rw-r--r--test/Object/Mips/lit.local.cfg5
-rw-r--r--test/Object/X86/lit.local.cfg6
-rw-r--r--test/Object/X86/objdump-disassembly-inline-relocations.test32
-rw-r--r--test/Object/X86/objdump-trivial-object.test54
-rw-r--r--test/Object/lit.local.cfg1
-rw-r--r--test/Object/nm-archive.test18
-rw-r--r--test/Object/nm-shared-object.test15
-rw-r--r--test/Object/nm-trivial-object.test33
-rw-r--r--test/Object/objdump-file-header.test17
-rw-r--r--test/Object/objdump-relocations.test51
-rw-r--r--test/Object/objdump-section-content.test19
-rw-r--r--test/Object/objdump-sectionheaders.test16
-rw-r--r--test/Object/objdump-symbol-table.test33
-rw-r--r--test/Object/readobj-elf-versioning.test15
-rw-r--r--test/Object/readobj-shared-object.test59
-rw-r--r--test/Other/2002-01-31-CallGraph.ll13
-rw-r--r--test/Other/2002-02-24-InlineBrokePHINodes.ll23
-rw-r--r--test/Other/2002-03-11-ConstPropCrash.ll24
-rw-r--r--test/Other/2003-02-19-LoopInfoNestingBug.ll29
-rw-r--r--test/Other/2004-08-16-PackedConstantInlineStore.ll8
-rw-r--r--test/Other/2004-08-16-PackedGlobalConstant.ll11
-rw-r--r--test/Other/2004-08-16-PackedSelect.ll13
-rw-r--r--test/Other/2004-08-16-PackedSimple.ll13
-rw-r--r--test/Other/2004-08-20-PackedControlFlow.ll22
-rw-r--r--test/Other/2006-02-05-PassManager.ll5
-rw-r--r--test/Other/2007-04-24-eliminate-mostly-empty-blocks.ll309
-rw-r--r--test/Other/2007-06-05-PassID.ll11
-rw-r--r--test/Other/2007-06-28-PassManager.ll7
-rw-r--r--test/Other/2007-09-10-PassManager.ll32
-rw-r--r--test/Other/2008-02-14-PassManager.ll5
-rw-r--r--test/Other/2008-06-04-FieldSizeInPacked.ll14
-rw-r--r--test/Other/2008-10-06-RemoveDeadPass.ll11
-rw-r--r--test/Other/2008-10-15-MissingSpace.ll12
-rw-r--r--test/Other/2009-03-31-CallGraph.ll34
-rw-r--r--test/Other/2009-06-05-no-implicit-float.ll4
-rw-r--r--test/Other/2009-09-14-function-elements.ll6
-rw-r--r--test/Other/2010-05-06-Printer.ll6
-rw-r--r--test/Other/X86/inline-asm-newline-terminator.ll6
-rw-r--r--test/Other/X86/lit.local.cfg6
-rw-r--r--test/Other/close-stderr.ll9
-rw-r--r--test/Other/constant-fold-gep.ll448
-rw-r--r--test/Other/extract.ll27
-rw-r--r--test/Other/invalid-commandline-option.ll3
-rw-r--r--test/Other/lint.ll167
-rw-r--r--test/Other/lit.local.cfg1
-rw-r--r--test/Other/llvm-nm-without-aliases.ll25
-rw-r--r--test/Other/optimize-options.ll8
-rw-r--r--test/Scripts/README.txt2
-rwxr-xr-xtest/Scripts/coff-dump.py590
-rw-r--r--test/Scripts/coff-dump.py.bat7
-rw-r--r--test/Scripts/common_dump.py48
-rwxr-xr-xtest/Scripts/elf-dump243
-rw-r--r--test/Scripts/elf-dump.bat7
-rwxr-xr-xtest/Scripts/ignore10
-rwxr-xr-xtest/Scripts/macho-dumpx294
-rw-r--r--test/Scripts/macho-dumpx.bat7
-rw-r--r--test/TableGen/2003-08-03-PassCode.td8
-rw-r--r--test/TableGen/2006-09-18-LargeInt.td6
-rw-r--r--test/TableGen/2010-03-24-PrematureDefaults.td44
-rw-r--r--test/TableGen/AnonDefinitionOnDemand.td13
-rw-r--r--test/TableGen/BitsInitOverflow.td5
-rw-r--r--test/TableGen/CStyleComment.td15
-rw-r--r--test/TableGen/Dag.td73
-rw-r--r--test/TableGen/DefmInherit.td33
-rw-r--r--test/TableGen/DefmInsideMultiClass.td25
-rw-r--r--test/TableGen/FieldAccess.td16
-rw-r--r--test/TableGen/ForeachList.td76
-rw-r--r--test/TableGen/ForeachLoop.td63
-rw-r--r--test/TableGen/ForwardRef.td16
-rw-r--r--test/TableGen/GeneralList.td9
-rw-r--r--test/TableGen/Include.inc4
-rw-r--r--test/TableGen/Include.td8
-rw-r--r--test/TableGen/IntBitInit.td6
-rw-r--r--test/TableGen/LazyChange.td11
-rw-r--r--test/TableGen/LetInsideMultiClasses.td29
-rw-r--r--test/TableGen/ListArgs.td12
-rw-r--r--test/TableGen/ListArgsSimple.td9
-rw-r--r--test/TableGen/ListConversion.td11
-rw-r--r--test/TableGen/ListManip.td12
-rw-r--r--test/TableGen/ListOfList.td14
-rw-r--r--test/TableGen/ListSlices.td19
-rw-r--r--test/TableGen/LoLoL.td18
-rw-r--r--test/TableGen/MultiClass.td26
-rw-r--r--test/TableGen/MultiClassDefName.td13
-rw-r--r--test/TableGen/MultiClassInherit.td65
-rw-r--r--test/TableGen/MultiPat.td121
-rw-r--r--test/TableGen/NestedForeach.td74
-rw-r--r--test/TableGen/Paste.td36
-rw-r--r--test/TableGen/SetTheory.td176
-rw-r--r--test/TableGen/SiblingForeach.td277
-rw-r--r--test/TableGen/Slice.td88
-rw-r--r--test/TableGen/String.td6
-rw-r--r--test/TableGen/SuperSubclassSameName.td21
-rw-r--r--test/TableGen/TargetInstrInfo.td148
-rw-r--r--test/TableGen/TargetInstrSpec.td98
-rw-r--r--test/TableGen/TemplateArgRename.td18
-rw-r--r--test/TableGen/Tree.td19
-rw-r--r--test/TableGen/TreeNames.td18
-rw-r--r--test/TableGen/TwoLevelName.td46
-rw-r--r--test/TableGen/UnsetBitInit.td11
-rw-r--r--test/TableGen/UnterminatedComment.td6
-rw-r--r--test/TableGen/cast.td91
-rw-r--r--test/TableGen/defmclass.td50
-rw-r--r--test/TableGen/eq.td14
-rw-r--r--test/TableGen/eqbit.td11
-rw-r--r--test/TableGen/foreach.td32
-rw-r--r--test/TableGen/if.td89
-rw-r--r--test/TableGen/ifbit.td11
-rw-r--r--test/TableGen/lisp.td22
-rw-r--r--test/TableGen/list-element-bitref.td15
-rw-r--r--test/TableGen/lit.local.cfg1
-rw-r--r--test/TableGen/nested-comment.td13
-rw-r--r--test/TableGen/pr8330.td29
-rw-r--r--test/TableGen/strconcat.td11
-rw-r--r--test/TableGen/subst.td30
-rw-r--r--test/TableGen/subst2.td16
-rw-r--r--test/TableGen/usevalname.td24
-rwxr-xr-xtest/TestRunner.sh5
-rw-r--r--test/Transforms/ADCE/2002-01-31-UseStuckAround.ll11
-rw-r--r--test/Transforms/ADCE/2002-05-22-PHITest.ll16
-rw-r--r--test/Transforms/ADCE/2002-05-23-ZeroArgPHITest.ll32
-rw-r--r--test/Transforms/ADCE/2002-05-28-Crash-distilled.ll17
-rw-r--r--test/Transforms/ADCE/2002-05-28-Crash.ll54
-rw-r--r--test/Transforms/ADCE/2002-07-17-AssertionFailure.ll13
-rw-r--r--test/Transforms/ADCE/2002-07-17-PHIAssertion.ll48
-rw-r--r--test/Transforms/ADCE/2002-07-29-Segfault.ll9
-rw-r--r--test/Transforms/ADCE/2003-01-22-PredecessorProblem.ll25
-rw-r--r--test/Transforms/ADCE/2003-04-25-PHIPostDominateProblem.ll35
-rw-r--r--test/Transforms/ADCE/2003-06-11-InvalidCFG.ll28
-rw-r--r--test/Transforms/ADCE/2003-06-24-BadSuccessor.ll91
-rw-r--r--test/Transforms/ADCE/2003-06-24-BasicFunctionality.ll41
-rw-r--r--test/Transforms/ADCE/2003-09-10-UnwindInstFail.ll22
-rw-r--r--test/Transforms/ADCE/2003-09-15-InfLoopCrash.ll9
-rw-r--r--test/Transforms/ADCE/2003-11-16-MissingPostDominanceInfo.ll18
-rw-r--r--test/Transforms/ADCE/2004-05-04-UnreachableBlock.ll16
-rw-r--r--test/Transforms/ADCE/2005-02-17-PHI-Invoke-Crash.ll52
-rw-r--r--test/Transforms/ADCE/basictest.ll19
-rw-r--r--test/Transforms/ADCE/basictest1.ll97
-rw-r--r--test/Transforms/ADCE/basictest2.ll97
-rw-r--r--test/Transforms/ADCE/dce_pure_call.ll8
-rw-r--r--test/Transforms/ADCE/dce_pure_invoke.ll19
-rw-r--r--test/Transforms/ADCE/lit.local.cfg1
-rw-r--r--test/Transforms/ADCE/unreachable-function.ll5
-rw-r--r--test/Transforms/ArgumentPromotion/2008-02-01-ReturnAttrs.ll15
-rw-r--r--test/Transforms/ArgumentPromotion/2008-07-02-array-indexing.ll25
-rw-r--r--test/Transforms/ArgumentPromotion/2008-09-07-CGUpdate.ll12
-rw-r--r--test/Transforms/ArgumentPromotion/2008-09-08-CGUpdateSelfEdge.ll25
-rw-r--r--test/Transforms/ArgumentPromotion/aggregate-promote.ll24
-rw-r--r--test/Transforms/ArgumentPromotion/attrs.ll25
-rw-r--r--test/Transforms/ArgumentPromotion/basictest.ll23
-rw-r--r--test/Transforms/ArgumentPromotion/byval-2.ll26
-rw-r--r--test/Transforms/ArgumentPromotion/byval.ll25
-rw-r--r--test/Transforms/ArgumentPromotion/callgraph-update.ll23
-rw-r--r--test/Transforms/ArgumentPromotion/chained.ll17
-rw-r--r--test/Transforms/ArgumentPromotion/control-flow.ll19
-rw-r--r--test/Transforms/ArgumentPromotion/control-flow2.ll22
-rw-r--r--test/Transforms/ArgumentPromotion/crash.ll59
-rw-r--r--test/Transforms/ArgumentPromotion/lit.local.cfg1
-rw-r--r--test/Transforms/ArgumentPromotion/pr3085.ll1944
-rw-r--r--test/Transforms/BBVectorize/cycle.ll112
-rw-r--r--test/Transforms/BBVectorize/func-alias.ll244
-rw-r--r--test/Transforms/BBVectorize/ld1.ll41
-rw-r--r--test/Transforms/BBVectorize/lit.local.cfg1
-rw-r--r--test/Transforms/BBVectorize/loop1.ll93
-rw-r--r--test/Transforms/BBVectorize/mem-op-depth.ll22
-rw-r--r--test/Transforms/BBVectorize/metadata.ll49
-rw-r--r--test/Transforms/BBVectorize/no-ldstr-conn.ll23
-rw-r--r--test/Transforms/BBVectorize/req-depth.ll17
-rw-r--r--test/Transforms/BBVectorize/search-limit.ll46
-rw-r--r--test/Transforms/BBVectorize/simple-int.ll103
-rw-r--r--test/Transforms/BBVectorize/simple-ldstr-ptrs.ll81
-rw-r--r--test/Transforms/BBVectorize/simple-ldstr.ll110
-rw-r--r--test/Transforms/BBVectorize/simple-sel.ll59
-rw-r--r--test/Transforms/BBVectorize/simple-tst.ll18
-rw-r--r--test/Transforms/BBVectorize/simple.ll151
-rw-r--r--test/Transforms/BBVectorize/simple3.ll35
-rw-r--r--test/Transforms/BlockPlacement/basictest.ll15
-rw-r--r--test/Transforms/BlockPlacement/lit.local.cfg1
-rw-r--r--test/Transforms/BranchFolding/2007-10-19-InlineAsmDirectives.ll18
-rw-r--r--test/Transforms/CodeExtractor/2004-03-13-LoopExtractorCrash.ll75
-rw-r--r--test/Transforms/CodeExtractor/2004-03-14-DominanceProblem.ll33
-rw-r--r--test/Transforms/CodeExtractor/2004-03-14-NoSwitchSupport.ll28
-rw-r--r--test/Transforms/CodeExtractor/2004-03-17-MissedLiveIns.ll47
-rw-r--r--test/Transforms/CodeExtractor/2004-03-17-UpdatePHIsOutsideRegion.ll23
-rw-r--r--test/Transforms/CodeExtractor/2004-03-18-InvokeHandling.ll198
-rw-r--r--test/Transforms/CodeExtractor/2004-08-12-BlockExtractPHI.ll26
-rw-r--r--test/Transforms/CodeExtractor/2004-11-12-InvokeExtract.ll18
-rw-r--r--test/Transforms/CodeExtractor/lit.local.cfg1
-rw-r--r--test/Transforms/CodeGenPrepare/2008-11-24-RAUW-Self.ll511
-rw-r--r--test/Transforms/CodeGenPrepare/basic.ll30
-rw-r--r--test/Transforms/CodeGenPrepare/lit.local.cfg1
-rw-r--r--test/Transforms/ConstProp/2002-05-03-DivideByZeroException.ll15
-rw-r--r--test/Transforms/ConstProp/2002-05-03-NotOperator.ll19
-rw-r--r--test/Transforms/ConstProp/2002-09-03-SetCC-Bools.ll20
-rw-r--r--test/Transforms/ConstProp/2003-05-12-DivideError.ll15
-rw-r--r--test/Transforms/ConstProp/2005-01-28-SetCCGEP.ll10
-rw-r--r--test/Transforms/ConstProp/2006-11-30-vector-cast.ll10
-rw-r--r--test/Transforms/ConstProp/2006-12-01-TruncBoolBug.ll7
-rw-r--r--test/Transforms/ConstProp/2006-12-01-bool-casts.ll15
-rw-r--r--test/Transforms/ConstProp/2007-02-05-BitCast.ll7
-rw-r--r--test/Transforms/ConstProp/2007-02-23-sdiv.ll5
-rw-r--r--test/Transforms/ConstProp/2007-11-23-cttz.ll8
-rw-r--r--test/Transforms/ConstProp/2008-07-07-VectorCompare.ll28
-rw-r--r--test/Transforms/ConstProp/2009-06-20-constexpr-zero-lhs.ll11
-rw-r--r--test/Transforms/ConstProp/2009-09-01-GEP-Crash.ll24
-rw-r--r--test/Transforms/ConstProp/basictest.ll53
-rw-r--r--test/Transforms/ConstProp/bitcast.ll10
-rw-r--r--test/Transforms/ConstProp/bswap.ll41
-rw-r--r--test/Transforms/ConstProp/calls.ll149
-rw-r--r--test/Transforms/ConstProp/constant-expr.ll111
-rw-r--r--test/Transforms/ConstProp/div-zero.ll12
-rw-r--r--test/Transforms/ConstProp/extractvalue.ll67
-rw-r--r--test/Transforms/ConstProp/float-to-ptr-cast.ll15
-rw-r--r--test/Transforms/ConstProp/insertvalue.ll67
-rw-r--r--test/Transforms/ConstProp/lit.local.cfg1
-rw-r--r--test/Transforms/ConstProp/loads.ll139
-rw-r--r--test/Transforms/ConstProp/logicaltest.ll35
-rw-r--r--test/Transforms/ConstProp/overflow-ops.ll207
-rw-r--r--test/Transforms/ConstProp/phi.ll17
-rw-r--r--test/Transforms/ConstProp/remtest.ll24
-rw-r--r--test/Transforms/ConstantMerge/2002-09-23-CPR-Update.ll13
-rw-r--r--test/Transforms/ConstantMerge/2003-10-28-MergeExternalConstants.ll7
-rw-r--r--test/Transforms/ConstantMerge/2011-01-15-EitherOrder.ll18
-rw-r--r--test/Transforms/ConstantMerge/dont-merge.ll44
-rw-r--r--test/Transforms/ConstantMerge/linker-private.ll23
-rw-r--r--test/Transforms/ConstantMerge/lit.local.cfg1
-rw-r--r--test/Transforms/ConstantMerge/merge-both.ll39
-rw-r--r--test/Transforms/ConstantMerge/unnamed-addr.ll40
-rw-r--r--test/Transforms/CorrelatedValuePropagation/2010-09-02-Trunc.ll25
-rw-r--r--test/Transforms/CorrelatedValuePropagation/2010-09-26-MergeConstantRange.ll82
-rw-r--r--test/Transforms/CorrelatedValuePropagation/basic.ll181
-rw-r--r--test/Transforms/CorrelatedValuePropagation/crash.ll37
-rw-r--r--test/Transforms/CorrelatedValuePropagation/lit.local.cfg1
-rw-r--r--test/Transforms/CorrelatedValuePropagation/non-null.ll103
-rw-r--r--test/Transforms/CorrelatedValuePropagation/range.ll167
-rw-r--r--test/Transforms/DeadArgElim/2006-06-27-struct-ret.ll11
-rw-r--r--test/Transforms/DeadArgElim/2007-02-07-FuncRename.ll11
-rw-r--r--test/Transforms/DeadArgElim/2007-10-18-VarargsReturn.ll12
-rw-r--r--test/Transforms/DeadArgElim/2007-12-20-ParamAttrs.ll20
-rw-r--r--test/Transforms/DeadArgElim/2008-01-16-VarargsParamAttrs.ll31
-rw-r--r--test/Transforms/DeadArgElim/2008-06-23-DeadAfterLive.ll23
-rw-r--r--test/Transforms/DeadArgElim/2009-03-17-MRE-Invoke.ll32
-rw-r--r--test/Transforms/DeadArgElim/2010-04-30-DbgInfo.ll68
-rw-r--r--test/Transforms/DeadArgElim/basictest.ll36
-rw-r--r--test/Transforms/DeadArgElim/canon.ll24
-rw-r--r--test/Transforms/DeadArgElim/dead_vaargs.ll12
-rw-r--r--test/Transforms/DeadArgElim/deadexternal.ll52
-rw-r--r--test/Transforms/DeadArgElim/deadretval.ll18
-rw-r--r--test/Transforms/DeadArgElim/deadretval2.ll59
-rw-r--r--test/Transforms/DeadArgElim/keepalive.ll30
-rw-r--r--test/Transforms/DeadArgElim/lit.local.cfg1
-rw-r--r--test/Transforms/DeadArgElim/multdeadretval.ll68
-rw-r--r--test/Transforms/DeadStoreElimination/2011-03-25-DSEMiscompile.ll23
-rw-r--r--test/Transforms/DeadStoreElimination/2011-09-06-EndOfFunction.ll27
-rw-r--r--test/Transforms/DeadStoreElimination/2011-09-06-MemCpy.ll85
-rw-r--r--test/Transforms/DeadStoreElimination/OverwriteStoreEnd.ll95
-rw-r--r--test/Transforms/DeadStoreElimination/PartialStore.ll71
-rw-r--r--test/Transforms/DeadStoreElimination/atomic.ll107
-rw-r--r--test/Transforms/DeadStoreElimination/const-pointers.ll39
-rw-r--r--test/Transforms/DeadStoreElimination/crash.ll74
-rw-r--r--test/Transforms/DeadStoreElimination/dominate.ll25
-rw-r--r--test/Transforms/DeadStoreElimination/free.ll70
-rw-r--r--test/Transforms/DeadStoreElimination/lifetime.ll37
-rw-r--r--test/Transforms/DeadStoreElimination/lit.local.cfg1
-rw-r--r--test/Transforms/DeadStoreElimination/memintrinsics.ll47
-rw-r--r--test/Transforms/DeadStoreElimination/no-targetdata.ll15
-rw-r--r--test/Transforms/DeadStoreElimination/pr11390.ll38
-rw-r--r--test/Transforms/DeadStoreElimination/simple.ll326
-rw-r--r--test/Transforms/EarlyCSE/basic.ll121
-rw-r--r--test/Transforms/EarlyCSE/instsimplify-dom.ll19
-rw-r--r--test/Transforms/EarlyCSE/lit.local.cfg1
-rw-r--r--test/Transforms/FunctionAttrs/2008-09-03-Mutual.ll11
-rw-r--r--test/Transforms/FunctionAttrs/2008-09-03-ReadNone.ll18
-rw-r--r--test/Transforms/FunctionAttrs/2008-09-03-ReadOnly.ll9
-rw-r--r--test/Transforms/FunctionAttrs/2008-09-13-VolatileRead.ll9
-rw-r--r--test/Transforms/FunctionAttrs/2008-12-29-Constant.ll8
-rw-r--r--test/Transforms/FunctionAttrs/2009-01-02-LocalStores.ll14
-rw-r--r--test/Transforms/FunctionAttrs/2010-10-30-volatile.ll10
-rw-r--r--test/Transforms/FunctionAttrs/atomic.ll21
-rw-r--r--test/Transforms/FunctionAttrs/lit.local.cfg1
-rw-r--r--test/Transforms/FunctionAttrs/nocapture.ll178
-rw-r--r--test/Transforms/GVN/2007-07-25-DominatedLoop.ll86
-rw-r--r--test/Transforms/GVN/2007-07-25-InfiniteLoop.ll14
-rw-r--r--test/Transforms/GVN/2007-07-25-Loop.ll15
-rw-r--r--test/Transforms/GVN/2007-07-25-NestedLoop.ll38
-rw-r--r--test/Transforms/GVN/2007-07-25-SinglePredecessor.ll29
-rw-r--r--test/Transforms/GVN/2007-07-26-InterlockingLoops.ll38
-rw-r--r--test/Transforms/GVN/2007-07-26-NonRedundant.ll16
-rw-r--r--test/Transforms/GVN/2007-07-26-PhiErasure.ll28
-rw-r--r--test/Transforms/GVN/2007-07-30-PredIDom.ll274
-rw-r--r--test/Transforms/GVN/2007-07-31-NoDomInherit.ll313
-rw-r--r--test/Transforms/GVN/2007-07-31-RedundantPhi.ll22
-rw-r--r--test/Transforms/GVN/2008-02-12-UndefLoad.ll20
-rw-r--r--test/Transforms/GVN/2008-02-13-NewPHI.ll22
-rw-r--r--test/Transforms/GVN/2008-07-02-Unreachable.ll37
-rw-r--r--test/Transforms/GVN/2008-12-09-SelfRemove.ll26
-rw-r--r--test/Transforms/GVN/2008-12-12-RLE-Crash.ll35
-rw-r--r--test/Transforms/GVN/2008-12-14-rle-reanalyze.ll18
-rw-r--r--test/Transforms/GVN/2008-12-15-CacheVisited.ll28
-rw-r--r--test/Transforms/GVN/2009-01-21-SortInvalidation.ll55
-rw-r--r--test/Transforms/GVN/2009-01-22-SortInvalidation.ll100
-rw-r--r--test/Transforms/GVN/2009-02-17-LoadPRECrash.ll193
-rw-r--r--test/Transforms/GVN/2009-03-10-PREOnVoid.ll82
-rw-r--r--test/Transforms/GVN/2009-06-17-InvalidPRE.ll72
-rw-r--r--test/Transforms/GVN/2009-07-13-MemDepSortFail.ll67
-rw-r--r--test/Transforms/GVN/2009-11-12-MemDepMallocBitCast.ll15
-rw-r--r--test/Transforms/GVN/2010-03-31-RedundantPHIs.ll42
-rw-r--r--test/Transforms/GVN/2010-05-08-OneBit.ll67
-rw-r--r--test/Transforms/GVN/2010-11-13-Simplify.ll15
-rw-r--r--test/Transforms/GVN/2011-04-27-phioperands.ll106
-rw-r--r--test/Transforms/GVN/2011-06-01-NonLocalMemdepMiscompile.ll61
-rw-r--r--test/Transforms/GVN/2011-07-07-MatchIntrinsicExtract.ll85
-rw-r--r--test/Transforms/GVN/2011-09-07-TypeIdFor.ll81
-rw-r--r--test/Transforms/GVN/2012-05-22-PreCrash.ll33
-rw-r--r--test/Transforms/GVN/atomic.ll80
-rw-r--r--test/Transforms/GVN/basic.ll10
-rw-r--r--test/Transforms/GVN/bitcast-of-call.ll12
-rw-r--r--test/Transforms/GVN/calls-nonlocal.ll49
-rw-r--r--test/Transforms/GVN/calls-readonly.ll29
-rw-r--r--test/Transforms/GVN/commute.ll23
-rw-r--r--test/Transforms/GVN/condprop.ll251
-rw-r--r--test/Transforms/GVN/crash-no-aa.ll16
-rw-r--r--test/Transforms/GVN/crash.ll165
-rw-r--r--test/Transforms/GVN/edge.ll60
-rw-r--r--test/Transforms/GVN/fpmath.ll45
-rw-r--r--test/Transforms/GVN/lifetime-simple.ll20
-rw-r--r--test/Transforms/GVN/lit.local.cfg1
-rw-r--r--test/Transforms/GVN/load-constant-mem.ll13
-rw-r--r--test/Transforms/GVN/load-pre-align.ll44
-rw-r--r--test/Transforms/GVN/load-pre-licm.ll39
-rw-r--r--test/Transforms/GVN/local-pre.ll18
-rw-r--r--test/Transforms/GVN/lpre-call-wrap-2.ll40
-rw-r--r--test/Transforms/GVN/lpre-call-wrap.ll55
-rw-r--r--test/Transforms/GVN/malloc-load-removal.ll31
-rw-r--r--test/Transforms/GVN/non-local-offset.ll59
-rw-r--r--test/Transforms/GVN/nonescaping-malloc.ll108
-rw-r--r--test/Transforms/GVN/null-aliases-nothing.ll20
-rw-r--r--test/Transforms/GVN/phi-translate-partial-alias.ll27
-rw-r--r--test/Transforms/GVN/phi-translate.ll31
-rw-r--r--test/Transforms/GVN/pr10820.ll18
-rw-r--r--test/Transforms/GVN/pr12979.ll79
-rw-r--r--test/Transforms/GVN/pre-basic-add.ll27
-rw-r--r--test/Transforms/GVN/pre-compare.ll68
-rw-r--r--test/Transforms/GVN/pre-load.ll391
-rw-r--r--test/Transforms/GVN/pre-single-pred.ll45
-rw-r--r--test/Transforms/GVN/preserve-tbaa.ll30
-rw-r--r--test/Transforms/GVN/range.ll101
-rw-r--r--test/Transforms/GVN/rle-must-alias.ll46
-rw-r--r--test/Transforms/GVN/rle-no-phi-translate.ll28
-rw-r--r--test/Transforms/GVN/rle-nonlocal.ll24
-rw-r--r--test/Transforms/GVN/rle-phi-translate.ll146
-rw-r--r--test/Transforms/GVN/rle-semidominated.ll19
-rw-r--r--test/Transforms/GVN/rle.ll678
-rw-r--r--test/Transforms/GVN/tbaa.ll81
-rw-r--r--test/Transforms/GlobalDCE/2002-07-17-CastRef.ll11
-rw-r--r--test/Transforms/GlobalDCE/2002-07-17-ConstantRef.ll13
-rw-r--r--test/Transforms/GlobalDCE/2002-08-17-FunctionDGE.ll17
-rw-r--r--test/Transforms/GlobalDCE/2002-08-17-WorkListTest.ll12
-rw-r--r--test/Transforms/GlobalDCE/2002-09-12-Redeletion.ll11
-rw-r--r--test/Transforms/GlobalDCE/2003-07-01-SelfReference.ll11
-rw-r--r--test/Transforms/GlobalDCE/2003-10-09-PreserveWeakGlobals.ll6
-rw-r--r--test/Transforms/GlobalDCE/2009-01-05-DeadAliases.ll8
-rw-r--r--test/Transforms/GlobalDCE/2009-02-17-AliasUsesAliasee.ll4
-rw-r--r--test/Transforms/GlobalDCE/basicvariabletest.ll5
-rw-r--r--test/Transforms/GlobalDCE/externally_available.ll10
-rw-r--r--test/Transforms/GlobalDCE/lit.local.cfg1
-rw-r--r--test/Transforms/GlobalOpt/2004-10-10-CastStoreOnce.ll17
-rw-r--r--test/Transforms/GlobalOpt/2005-06-15-LocalizeConstExprCrash.ll10
-rw-r--r--test/Transforms/GlobalOpt/2005-09-27-Crash.ll27
-rw-r--r--test/Transforms/GlobalOpt/2006-07-07-InlineAsmCrash.ll135
-rw-r--r--test/Transforms/GlobalOpt/2006-11-01-ShrinkGlobalPhiCrash.ll33
-rw-r--r--test/Transforms/GlobalOpt/2007-04-05-Crash.ll34
-rw-r--r--test/Transforms/GlobalOpt/2007-05-13-Crash.ll74
-rw-r--r--test/Transforms/GlobalOpt/2007-06-04-PackedStruct.ll36
-rw-r--r--test/Transforms/GlobalOpt/2007-11-09-GEP-GEP-Crash.ll19
-rw-r--r--test/Transforms/GlobalOpt/2008-01-03-Crash.ll26
-rw-r--r--test/Transforms/GlobalOpt/2008-01-13-OutOfRangeSROA.ll16
-rw-r--r--test/Transforms/GlobalOpt/2008-01-29-VolatileGlobal.ll9
-rw-r--r--test/Transforms/GlobalOpt/2008-04-26-SROA-Global-Align.ll32
-rw-r--r--test/Transforms/GlobalOpt/2008-07-17-addrspace.ll28
-rw-r--r--test/Transforms/GlobalOpt/2008-12-16-HeapSRACrash-2.ll28
-rw-r--r--test/Transforms/GlobalOpt/2008-12-16-HeapSRACrash.ll30
-rw-r--r--test/Transforms/GlobalOpt/2009-01-13-phi-user.ll35
-rw-r--r--test/Transforms/GlobalOpt/2009-02-15-BitcastAlias.ll10
-rw-r--r--test/Transforms/GlobalOpt/2009-02-15-ResolveAlias.ll24
-rw-r--r--test/Transforms/GlobalOpt/2009-03-05-dbg.ll76
-rw-r--r--test/Transforms/GlobalOpt/2009-03-06-Anonymous.ll11
-rw-r--r--test/Transforms/GlobalOpt/2009-03-07-PromotePtrToBool.ll17
-rw-r--r--test/Transforms/GlobalOpt/2009-06-01-RecursivePHI.ll122
-rw-r--r--test/Transforms/GlobalOpt/2009-11-16-BrokenPerformHeapAllocSRoA.ll26
-rw-r--r--test/Transforms/GlobalOpt/2009-11-16-MallocSingleStoreToGlobalVar.ll30
-rw-r--r--test/Transforms/GlobalOpt/2010-02-25-MallocPromote.ll18
-rw-r--r--test/Transforms/GlobalOpt/2010-02-26-MallocSROA.ll27
-rw-r--r--test/Transforms/GlobalOpt/2010-10-19-WeakOdr.ll16
-rw-r--r--test/Transforms/GlobalOpt/2011-04-09-EmptyGlobalCtors.ll5
-rw-r--r--test/Transforms/GlobalOpt/2012-05-11-blockaddress.ll16
-rw-r--r--test/Transforms/GlobalOpt/alias-resolve.ll19
-rw-r--r--test/Transforms/GlobalOpt/atomic.ll10
-rw-r--r--test/Transforms/GlobalOpt/basictest.ll9
-rw-r--r--test/Transforms/GlobalOpt/cleanup-pointer-root-users.ll49
-rw-r--r--test/Transforms/GlobalOpt/constantexpr-dangle.ll13
-rw-r--r--test/Transforms/GlobalOpt/constantfold-initializers.ll56
-rw-r--r--test/Transforms/GlobalOpt/crash.ll80
-rw-r--r--test/Transforms/GlobalOpt/ctor-list-opt-constexpr.ll34
-rw-r--r--test/Transforms/GlobalOpt/ctor-list-opt-inbounds.ll23
-rw-r--r--test/Transforms/GlobalOpt/ctor-list-opt.ll100
-rw-r--r--test/Transforms/GlobalOpt/cxx-dtor.ll33
-rw-r--r--test/Transforms/GlobalOpt/deadfunction.ll27
-rw-r--r--test/Transforms/GlobalOpt/deadglobal-2.ll11
-rw-r--r--test/Transforms/GlobalOpt/deadglobal.ll25
-rw-r--r--test/Transforms/GlobalOpt/globalsra-partial.ll24
-rw-r--r--test/Transforms/GlobalOpt/globalsra-unknown-index.ll41
-rw-r--r--test/Transforms/GlobalOpt/globalsra.ll24
-rw-r--r--test/Transforms/GlobalOpt/heap-sra-1.ll38
-rw-r--r--test/Transforms/GlobalOpt/heap-sra-2.ll38
-rw-r--r--test/Transforms/GlobalOpt/heap-sra-3.ll39
-rw-r--r--test/Transforms/GlobalOpt/heap-sra-4.ll39
-rw-r--r--test/Transforms/GlobalOpt/heap-sra-phi.ll43
-rw-r--r--test/Transforms/GlobalOpt/integer-bool.ll23
-rw-r--r--test/Transforms/GlobalOpt/invariant.ll59
-rw-r--r--test/Transforms/GlobalOpt/invoke.ll27
-rw-r--r--test/Transforms/GlobalOpt/iterate.ll11
-rw-r--r--test/Transforms/GlobalOpt/lit.local.cfg1
-rw-r--r--test/Transforms/GlobalOpt/load-store-global.ll15
-rw-r--r--test/Transforms/GlobalOpt/malloc-promote-1.ll24
-rw-r--r--test/Transforms/GlobalOpt/malloc-promote-2.ll19
-rw-r--r--test/Transforms/GlobalOpt/memcpy.ll13
-rw-r--r--test/Transforms/GlobalOpt/memset-null.ll29
-rw-r--r--test/Transforms/GlobalOpt/memset.ll18
-rw-r--r--test/Transforms/GlobalOpt/metadata.ll26
-rw-r--r--test/Transforms/GlobalOpt/phi-select.ll31
-rw-r--r--test/Transforms/GlobalOpt/storepointer-compare.ll30
-rw-r--r--test/Transforms/GlobalOpt/storepointer.ll19
-rw-r--r--test/Transforms/GlobalOpt/trivialstore.ll19
-rw-r--r--test/Transforms/GlobalOpt/undef-init.ll17
-rw-r--r--test/Transforms/GlobalOpt/unnamed-addr.ll68
-rw-r--r--test/Transforms/GlobalOpt/zeroinitializer-gep-load.ll11
-rw-r--r--test/Transforms/IPConstantProp/2008-06-09-WeakProp.ll15
-rw-r--r--test/Transforms/IPConstantProp/2009-09-24-byval-ptr.ll40
-rw-r--r--test/Transforms/IPConstantProp/dangling-block-address.ll42
-rw-r--r--test/Transforms/IPConstantProp/deadarg.ll6
-rw-r--r--test/Transforms/IPConstantProp/global.ll26
-rw-r--r--test/Transforms/IPConstantProp/lit.local.cfg1
-rw-r--r--test/Transforms/IPConstantProp/recursion.ll12
-rw-r--r--test/Transforms/IPConstantProp/return-argument.ll57
-rw-r--r--test/Transforms/IPConstantProp/return-constant.ll30
-rw-r--r--test/Transforms/IPConstantProp/return-constants.ll46
-rw-r--r--test/Transforms/IPConstantProp/user-with-multiple-uses.ll30
-rw-r--r--test/Transforms/IndVarSimplify/2002-09-09-PointerIndVar.ll17
-rw-r--r--test/Transforms/IndVarSimplify/2003-04-16-ExprAnalysis.ll17
-rw-r--r--test/Transforms/IndVarSimplify/2003-09-23-NotAtTop.ll20
-rw-r--r--test/Transforms/IndVarSimplify/2003-12-10-RemoveInstrCrash.ll18
-rw-r--r--test/Transforms/IndVarSimplify/2003-12-15-Crash.ll24
-rw-r--r--test/Transforms/IndVarSimplify/2004-03-10-PHIInsertionBug.ll26
-rw-r--r--test/Transforms/IndVarSimplify/2004-04-05-InvokeCastCrash.ll291
-rw-r--r--test/Transforms/IndVarSimplify/2004-04-07-ScalarEvolutionCrash.ll27
-rw-r--r--test/Transforms/IndVarSimplify/2005-02-11-InvokeCrash.ll27
-rw-r--r--test/Transforms/IndVarSimplify/2005-02-17-TruncateExprCrash.ll67
-rw-r--r--test/Transforms/IndVarSimplify/2005-02-26-ExitValueCompute.ll20
-rw-r--r--test/Transforms/IndVarSimplify/2005-06-15-InstMoveCrash.ll37
-rw-r--r--test/Transforms/IndVarSimplify/2005-11-18-Crash.ll17
-rw-r--r--test/Transforms/IndVarSimplify/2006-03-31-NegativeStride.ll22
-rw-r--r--test/Transforms/IndVarSimplify/2006-06-16-Indvar-LCSSA-Crash.ll22
-rw-r--r--test/Transforms/IndVarSimplify/2006-09-20-LFTR-Crash.ll44
-rw-r--r--test/Transforms/IndVarSimplify/2006-12-10-BitCast.ll33
-rw-r--r--test/Transforms/IndVarSimplify/2007-01-06-TripCount.ll38
-rw-r--r--test/Transforms/IndVarSimplify/2007-06-06-DeleteDanglesPtr.ll117
-rw-r--r--test/Transforms/IndVarSimplify/2007-11-23-BitcastCrash.ll20
-rw-r--r--test/Transforms/IndVarSimplify/2008-06-15-SCEVExpanderBug.ll17
-rw-r--r--test/Transforms/IndVarSimplify/2008-09-02-IVType.ll58
-rw-r--r--test/Transforms/IndVarSimplify/2008-10-03-CouldNotCompute.ll32
-rw-r--r--test/Transforms/IndVarSimplify/2008-11-25-APFloatAssert.ll11
-rw-r--r--test/Transforms/IndVarSimplify/2009-04-14-shorten_iv_vars.ll114
-rw-r--r--test/Transforms/IndVarSimplify/2009-04-15-shorten-iv-vars-2.ll160
-rw-r--r--test/Transforms/IndVarSimplify/2009-04-22-IndvarCrash.ll35
-rw-r--r--test/Transforms/IndVarSimplify/2009-04-27-Floating.ll19
-rw-r--r--test/Transforms/IndVarSimplify/2009-05-24-useafterfree.ll41
-rw-r--r--test/Transforms/IndVarSimplify/2011-09-10-widen-nsw.ll30
-rw-r--r--test/Transforms/IndVarSimplify/2011-09-19-vectoriv.ll16
-rw-r--r--test/Transforms/IndVarSimplify/2011-09-27-hoistsext.ll28
-rw-r--r--test/Transforms/IndVarSimplify/2011-10-27-lftrnull.ll59
-rw-r--r--test/Transforms/IndVarSimplify/2011-11-01-lftrptr.ll140
-rw-r--r--test/Transforms/IndVarSimplify/2011-11-15-multiexit.ll40
-rw-r--r--test/Transforms/IndVarSimplify/2011-11-17-selfphi.ll29
-rw-r--r--test/Transforms/IndVarSimplify/2012-07-17-lftr-undef.ll22
-rw-r--r--test/Transforms/IndVarSimplify/ada-loops.ll92
-rw-r--r--test/Transforms/IndVarSimplify/ashr-tripcount.ll107
-rw-r--r--test/Transforms/IndVarSimplify/avoid-i0.ll126
-rw-r--r--test/Transforms/IndVarSimplify/casted-argument.ll50
-rw-r--r--test/Transforms/IndVarSimplify/crash.ll89
-rw-r--r--test/Transforms/IndVarSimplify/dangling-use.ll41
-rw-r--r--test/Transforms/IndVarSimplify/divide-pointer.ll95
-rw-r--r--test/Transforms/IndVarSimplify/elim-extend.ll153
-rw-r--r--test/Transforms/IndVarSimplify/eliminate-comparison.ll108
-rw-r--r--test/Transforms/IndVarSimplify/eliminate-max.ll52
-rw-r--r--test/Transforms/IndVarSimplify/eliminate-rem.ll121
-rw-r--r--test/Transforms/IndVarSimplify/exit_value_tests.ll114
-rw-r--r--test/Transforms/IndVarSimplify/floating-point-iv.ll92
-rw-r--r--test/Transforms/IndVarSimplify/indirectbr.ll39
-rw-r--r--test/Transforms/IndVarSimplify/interesting-invoke-use.ll61
-rw-r--r--test/Transforms/IndVarSimplify/iterationCount_zext_or_trunc.ll25
-rw-r--r--test/Transforms/IndVarSimplify/iv-fold.ll56
-rw-r--r--test/Transforms/IndVarSimplify/iv-sext.ll149
-rw-r--r--test/Transforms/IndVarSimplify/iv-zext.ll33
-rw-r--r--test/Transforms/IndVarSimplify/lftr-other-uses.ll36
-rw-r--r--test/Transforms/IndVarSimplify/lftr-promote.ll38
-rw-r--r--test/Transforms/IndVarSimplify/lftr-reuse.ll233
-rw-r--r--test/Transforms/IndVarSimplify/lftr_simple.ll22
-rw-r--r--test/Transforms/IndVarSimplify/lit.local.cfg1
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate10.ll53
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate11.ll36
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate7.ll61
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate8.ll63
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate9.ll83
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate_1.ll21
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate_2.ll28
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate_3.ll19
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate_4.ll20
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate_5.ll32
-rw-r--r--test/Transforms/IndVarSimplify/loop_evaluate_6.ll31
-rw-r--r--test/Transforms/IndVarSimplify/masked-iv.ll26
-rw-r--r--test/Transforms/IndVarSimplify/no-iv-rewrite.ll392
-rw-r--r--test/Transforms/IndVarSimplify/phi-uses-value-multiple-times.ll37
-rw-r--r--test/Transforms/IndVarSimplify/polynomial-expand.ll38
-rw-r--r--test/Transforms/IndVarSimplify/preserve-signed-wrap.ll39
-rw-r--r--test/Transforms/IndVarSimplify/promote-iv-to-eliminate-casts.ll99
-rw-r--r--test/Transforms/IndVarSimplify/shrunk-constant.ll15
-rw-r--r--test/Transforms/IndVarSimplify/signed-trip-count.ll30
-rw-r--r--test/Transforms/IndVarSimplify/single-element-range.ll27
-rw-r--r--test/Transforms/IndVarSimplify/sink-alloca.ll56
-rw-r--r--test/Transforms/IndVarSimplify/sink-trapping.ll19
-rw-r--r--test/Transforms/IndVarSimplify/tripcount_compute.ll162
-rw-r--r--test/Transforms/IndVarSimplify/tripcount_infinite.ll38
-rw-r--r--test/Transforms/IndVarSimplify/udiv.ll162
-rw-r--r--test/Transforms/IndVarSimplify/uglygep.ll40
-rw-r--r--test/Transforms/IndVarSimplify/ult-sub-to-eq.ll42
-rw-r--r--test/Transforms/IndVarSimplify/variable-stride-ivs-0.ll43
-rw-r--r--test/Transforms/IndVarSimplify/variable-stride-ivs-1.ll43
-rw-r--r--test/Transforms/Inline/2003-09-14-InlineValue.ll25
-rw-r--r--test/Transforms/Inline/2003-09-22-PHINodeInlineFail.ll16
-rw-r--r--test/Transforms/Inline/2003-09-22-PHINodesInExceptionDest.ll32
-rw-r--r--test/Transforms/Inline/2003-09-22-PHINodesInNormalInvokeDest.ll23
-rw-r--r--test/Transforms/Inline/2003-10-13-AllocaDominanceProblem.ll19
-rw-r--r--test/Transforms/Inline/2004-04-15-InlineDeletesCall.ll20
-rw-r--r--test/Transforms/Inline/2004-04-20-InlineLinkOnce.ll11
-rw-r--r--test/Transforms/Inline/2004-10-17-InlineFunctionWithoutReturn.ll11
-rw-r--r--test/Transforms/Inline/2006-01-14-CallGraphUpdate.ll25
-rw-r--r--test/Transforms/Inline/2006-07-12-InlinePruneCGUpdate.ll840
-rw-r--r--test/Transforms/Inline/2006-11-09-InlineCGUpdate-2.ll253
-rw-r--r--test/Transforms/Inline/2006-11-09-InlineCGUpdate.ll344
-rw-r--r--test/Transforms/Inline/2007-04-15-InlineEH.ll53
-rw-r--r--test/Transforms/Inline/2007-06-25-WeakInline.ll14
-rw-r--r--test/Transforms/Inline/2007-12-19-InlineNoUnwind.ll19
-rw-r--r--test/Transforms/Inline/2008-09-02-NoInline.ll10
-rw-r--r--test/Transforms/Inline/2009-01-08-NoInlineDynamicAlloca.ll36
-rw-r--r--test/Transforms/Inline/2009-01-13-RecursiveInlineCrash.ll293
-rw-r--r--test/Transforms/Inline/2009-05-07-CallUsingSelfCrash.ll20
-rw-r--r--test/Transforms/Inline/2010-05-12-ValueMap.ll28
-rw-r--r--test/Transforms/Inline/2010-05-31-ByvalTailcall.ll24
-rw-r--r--test/Transforms/Inline/PR4909.ll15
-rw-r--r--test/Transforms/Inline/alloca-bonus.ll155
-rw-r--r--test/Transforms/Inline/alloca-in-scc.ll31
-rw-r--r--test/Transforms/Inline/alloca_test.ll23
-rw-r--r--test/Transforms/Inline/always-inline.ll124
-rw-r--r--test/Transforms/Inline/array_merge.ll26
-rw-r--r--test/Transforms/Inline/basictest.ll47
-rw-r--r--test/Transforms/Inline/blockaddress.ll27
-rw-r--r--test/Transforms/Inline/byval.ll106
-rw-r--r--test/Transforms/Inline/callgraph-update.ll36
-rw-r--r--test/Transforms/Inline/casts.ll19
-rw-r--r--test/Transforms/Inline/cfg_preserve_test.ll16
-rw-r--r--test/Transforms/Inline/crash.ll127
-rw-r--r--test/Transforms/Inline/crash2.ll29
-rw-r--r--test/Transforms/Inline/delete-call.ll22
-rw-r--r--test/Transforms/Inline/devirtualize-2.ll44
-rw-r--r--test/Transforms/Inline/devirtualize-3.ll79
-rw-r--r--test/Transforms/Inline/devirtualize.ll182
-rw-r--r--test/Transforms/Inline/dynamic_alloca_test.ll45
-rw-r--r--test/Transforms/Inline/externally_available.ll16
-rw-r--r--test/Transforms/Inline/gvn-inline-iteration.ll23
-rw-r--r--test/Transforms/Inline/inline-byval-bonus.ll193
-rw-r--r--test/Transforms/Inline/inline-invoke-tail.ll33
-rw-r--r--test/Transforms/Inline/inline-optsize.ll33
-rw-r--r--test/Transforms/Inline/inline-tail.ll15
-rw-r--r--test/Transforms/Inline/inline_cleanup.ll213
-rw-r--r--test/Transforms/Inline/inline_constprop.ll174
-rw-r--r--test/Transforms/Inline/inline_dce.ll25
-rw-r--r--test/Transforms/Inline/inline_invoke.ll342
-rw-r--r--test/Transforms/Inline/inline_prune.ll45
-rw-r--r--test/Transforms/Inline/inline_returns_twice.ll41
-rw-r--r--test/Transforms/Inline/invoke_test-1.ll28
-rw-r--r--test/Transforms/Inline/invoke_test-2.ll36
-rw-r--r--test/Transforms/Inline/invoke_test-3.ll38
-rw-r--r--test/Transforms/Inline/lifetime.ll78
-rw-r--r--test/Transforms/Inline/lit.local.cfg1
-rw-r--r--test/Transforms/Inline/nested-inline.ll111
-rw-r--r--test/Transforms/Inline/noinline-recursive-fn.ll110
-rw-r--r--test/Transforms/Inline/noinline.ll18
-rw-r--r--test/Transforms/Inline/ptr-diff.ll58
-rw-r--r--test/Transforms/InstCombine/2002-03-11-InstCombineHang.ll9
-rw-r--r--test/Transforms/InstCombine/2002-05-14-SubFailure.ll10
-rw-r--r--test/Transforms/InstCombine/2002-08-02-CastTest.ll11
-rw-r--r--test/Transforms/InstCombine/2002-12-05-MissedConstProp.ll11
-rw-r--r--test/Transforms/InstCombine/2003-05-26-CastMiscompile.ll8
-rw-r--r--test/Transforms/InstCombine/2003-05-27-ConstExprCrash.ll10
-rw-r--r--test/Transforms/InstCombine/2003-06-05-BranchInvertInfLoop.ll16
-rw-r--r--test/Transforms/InstCombine/2003-07-21-ExternalConstant.ll44
-rw-r--r--test/Transforms/InstCombine/2003-08-12-AllocaNonNull.ll20
-rw-r--r--test/Transforms/InstCombine/2003-09-09-VolatileLoadElim.ll7
-rw-r--r--test/Transforms/InstCombine/2003-10-29-CallSiteResolve.ll18
-rw-r--r--test/Transforms/InstCombine/2003-11-03-VarargsCallBug.ll13
-rw-r--r--test/Transforms/InstCombine/2004-01-13-InstCombineInvokePHI.ll31
-rw-r--r--test/Transforms/InstCombine/2004-02-23-ShiftShiftOverflow.ll15
-rw-r--r--test/Transforms/InstCombine/2004-03-13-InstCombineInfLoop.ll13
-rw-r--r--test/Transforms/InstCombine/2004-04-04-InstCombineReplaceAllUsesWith.ll10
-rw-r--r--test/Transforms/InstCombine/2004-05-07-UnsizedCastLoad.ll10
-rw-r--r--test/Transforms/InstCombine/2004-07-27-ConstantExprMul.ll9
-rw-r--r--test/Transforms/InstCombine/2004-08-09-RemInfLoop.ll9
-rw-r--r--test/Transforms/InstCombine/2004-08-10-BoolSetCC.ll8
-rw-r--r--test/Transforms/InstCombine/2004-09-20-BadLoadCombine.ll18
-rw-r--r--test/Transforms/InstCombine/2004-09-20-BadLoadCombine2.ll25
-rw-r--r--test/Transforms/InstCombine/2004-09-28-BadShiftAndSetCC.ll9
-rw-r--r--test/Transforms/InstCombine/2004-11-22-Missed-and-fold.ll10
-rw-r--r--test/Transforms/InstCombine/2004-11-27-SetCCForCastLargerAndConstant.ll192
-rw-r--r--test/Transforms/InstCombine/2004-12-08-RemInfiniteLoop.ll7
-rw-r--r--test/Transforms/InstCombine/2005-03-04-ShiftOverflow.ll9
-rw-r--r--test/Transforms/InstCombine/2005-04-07-UDivSelectCrash.ll8
-rw-r--r--test/Transforms/InstCombine/2005-06-15-DivSelectCrash.ll10
-rw-r--r--test/Transforms/InstCombine/2005-06-15-ShiftSetCCCrash.ll9
-rw-r--r--test/Transforms/InstCombine/2005-06-16-RangeCrash.ll9
-rw-r--r--test/Transforms/InstCombine/2005-06-16-SetCCOrSetCCMiscompile.ll14
-rw-r--r--test/Transforms/InstCombine/2005-07-07-DeadPHILoop.ll14
-rw-r--r--test/Transforms/InstCombine/2006-02-13-DemandedMiscompile.ll10
-rw-r--r--test/Transforms/InstCombine/2006-02-28-Crash.ll8
-rw-r--r--test/Transforms/InstCombine/2006-03-30-ExtractElement.ll8
-rw-r--r--test/Transforms/InstCombine/2006-04-28-ShiftShiftLongLong.ll13
-rw-r--r--test/Transforms/InstCombine/2006-05-04-DemandedBitCrash.ll51
-rw-r--r--test/Transforms/InstCombine/2006-09-15-CastToBool.ll14
-rw-r--r--test/Transforms/InstCombine/2006-10-19-SignedToUnsignedCastAndConst-2.ll10
-rw-r--r--test/Transforms/InstCombine/2006-10-20-mask.ll11
-rw-r--r--test/Transforms/InstCombine/2006-10-26-VectorReassoc.ll9
-rw-r--r--test/Transforms/InstCombine/2006-11-10-ashr-miscompile.ll9
-rw-r--r--test/Transforms/InstCombine/2006-12-01-BadFPVectorXform.ll9
-rw-r--r--test/Transforms/InstCombine/2006-12-05-fp-to-int-ext.ll12
-rw-r--r--test/Transforms/InstCombine/2006-12-08-Phi-ICmp-Op-Fold.ll51
-rw-r--r--test/Transforms/InstCombine/2006-12-08-Select-ICmp.ll41
-rw-r--r--test/Transforms/InstCombine/2006-12-15-Range-Test.ll31
-rw-r--r--test/Transforms/InstCombine/2006-12-23-Select-Cmp-Cmp.ll30
-rw-r--r--test/Transforms/InstCombine/2007-01-13-ExtCompareMiscompile.ll10
-rw-r--r--test/Transforms/InstCombine/2007-01-14-FcmpSelf.ll6
-rw-r--r--test/Transforms/InstCombine/2007-01-18-VectorInfLoop.ll7
-rw-r--r--test/Transforms/InstCombine/2007-01-27-AndICmp.ll8
-rw-r--r--test/Transforms/InstCombine/2007-02-01-LoadSinkAlloca.ll45
-rw-r--r--test/Transforms/InstCombine/2007-02-07-PointerCast.ll22
-rw-r--r--test/Transforms/InstCombine/2007-02-23-PhiFoldInfLoop.ll31
-rw-r--r--test/Transforms/InstCombine/2007-03-13-CompareMerge.ll9
-rw-r--r--test/Transforms/InstCombine/2007-03-19-BadTruncChangePR1261.ll10
-rw-r--r--test/Transforms/InstCombine/2007-03-21-SignedRangeTest.ll7
-rw-r--r--test/Transforms/InstCombine/2007-03-25-BadShiftMask.ll29
-rw-r--r--test/Transforms/InstCombine/2007-03-25-DoubleShift.ll9
-rw-r--r--test/Transforms/InstCombine/2007-03-26-BadShiftMask.ll35
-rw-r--r--test/Transforms/InstCombine/2007-04-08-SingleEltVectorCrash.ll7
-rw-r--r--test/Transforms/InstCombine/2007-05-10-icmp-or.ll8
-rw-r--r--test/Transforms/InstCombine/2007-05-14-Crash.ll18
-rw-r--r--test/Transforms/InstCombine/2007-05-18-CastFoldBug.ll10
-rw-r--r--test/Transforms/InstCombine/2007-06-06-AshrSignBit.ll22
-rw-r--r--test/Transforms/InstCombine/2007-06-21-DivCompareMiscomp.ll9
-rw-r--r--test/Transforms/InstCombine/2007-08-02-InfiniteLoop.ll10
-rw-r--r--test/Transforms/InstCombine/2007-09-10-AliasConstFold.ll13
-rw-r--r--test/Transforms/InstCombine/2007-09-17-AliasConstFold2.ll14
-rw-r--r--test/Transforms/InstCombine/2007-10-10-EliminateMemCpy.ll20
-rw-r--r--test/Transforms/InstCombine/2007-10-12-Crash.ll38
-rw-r--r--test/Transforms/InstCombine/2007-10-28-stacksave.ll47
-rw-r--r--test/Transforms/InstCombine/2007-10-31-RangeCrash.ll35
-rw-r--r--test/Transforms/InstCombine/2007-10-31-StringCrash.ll21
-rw-r--r--test/Transforms/InstCombine/2007-11-07-OpaqueAlignCrash.ll22
-rw-r--r--test/Transforms/InstCombine/2007-11-15-CompareMiscomp.ll10
-rw-r--r--test/Transforms/InstCombine/2007-11-22-IcmpCrash.ll16
-rw-r--r--test/Transforms/InstCombine/2007-11-25-CompatibleAttributes.ll12
-rw-r--r--test/Transforms/InstCombine/2007-12-10-ConstFoldCompare.ll9
-rw-r--r--test/Transforms/InstCombine/2007-12-12-GEPScale.ll10
-rw-r--r--test/Transforms/InstCombine/2007-12-16-AsmNoUnwind.ll7
-rw-r--r--test/Transforms/InstCombine/2007-12-18-AddSelCmpSub.ll29
-rw-r--r--test/Transforms/InstCombine/2007-12-28-IcmpSub2.ll89
-rw-r--r--test/Transforms/InstCombine/2008-01-06-BitCastAttributes.ll23
-rw-r--r--test/Transforms/InstCombine/2008-01-06-CastCrash.ll10
-rw-r--r--test/Transforms/InstCombine/2008-01-06-VoidCast.ll10
-rw-r--r--test/Transforms/InstCombine/2008-01-13-AndCmpCmp.ll9
-rw-r--r--test/Transforms/InstCombine/2008-01-13-NoBitCastAttributes.ll15
-rw-r--r--test/Transforms/InstCombine/2008-01-14-VarArgTrampoline.ll26
-rw-r--r--test/Transforms/InstCombine/2008-01-21-MismatchedCastAndCompare.ll20
-rw-r--r--test/Transforms/InstCombine/2008-01-21-MulTrunc.ll17
-rw-r--r--test/Transforms/InstCombine/2008-01-27-FloatSelect.ll7
-rw-r--r--test/Transforms/InstCombine/2008-01-29-AddICmp.ll20
-rw-r--r--test/Transforms/InstCombine/2008-02-13-MulURem.ll8
-rw-r--r--test/Transforms/InstCombine/2008-02-16-SDivOverflow.ll14
-rw-r--r--test/Transforms/InstCombine/2008-02-16-SDivOverflow2.ll9
-rw-r--r--test/Transforms/InstCombine/2008-02-23-MulSub.ll9
-rw-r--r--test/Transforms/InstCombine/2008-02-28-OrFCmpCrash.ll16
-rw-r--r--test/Transforms/InstCombine/2008-03-13-IntToPtr.ll9
-rw-r--r--test/Transforms/InstCombine/2008-04-22-ByValBitcast.ll15
-rw-r--r--test/Transforms/InstCombine/2008-04-28-VolatileStore.ll8
-rw-r--r--test/Transforms/InstCombine/2008-04-29-VolatileLoadDontMerge.ll25
-rw-r--r--test/Transforms/InstCombine/2008-04-29-VolatileLoadMerge.ll21
-rw-r--r--test/Transforms/InstCombine/2008-05-08-LiveStoreDelete.ll25
-rw-r--r--test/Transforms/InstCombine/2008-05-08-StrLenSink.ll32
-rw-r--r--test/Transforms/InstCombine/2008-05-09-SinkOfInvoke.ll37
-rw-r--r--test/Transforms/InstCombine/2008-05-17-InfLoop.ll23
-rw-r--r--test/Transforms/InstCombine/2008-05-18-FoldIntToPtr.ll13
-rw-r--r--test/Transforms/InstCombine/2008-05-22-IDivVector.ll6
-rw-r--r--test/Transforms/InstCombine/2008-05-22-NegValVector.ll8
-rw-r--r--test/Transforms/InstCombine/2008-05-23-CompareFold.ll11
-rw-r--r--test/Transforms/InstCombine/2008-05-31-AddBool.ll7
-rw-r--r--test/Transforms/InstCombine/2008-05-31-Bools.ll24
-rw-r--r--test/Transforms/InstCombine/2008-06-05-ashr-crash.ll7
-rw-r--r--test/Transforms/InstCombine/2008-06-08-ICmpPHI.ll47
-rw-r--r--test/Transforms/InstCombine/2008-06-13-InfiniteLoopStore.ll20
-rw-r--r--test/Transforms/InstCombine/2008-06-13-ReadOnlyCallStore.ll19
-rw-r--r--test/Transforms/InstCombine/2008-06-19-UncondLoad.ll16
-rw-r--r--test/Transforms/InstCombine/2008-06-21-CompareMiscomp.ll11
-rw-r--r--test/Transforms/InstCombine/2008-06-24-StackRestore.ll39
-rw-r--r--test/Transforms/InstCombine/2008-07-08-AndICmp.ll10
-rw-r--r--test/Transforms/InstCombine/2008-07-08-ShiftOneAndOne.ll10
-rw-r--r--test/Transforms/InstCombine/2008-07-08-SubAnd.ll9
-rw-r--r--test/Transforms/InstCombine/2008-07-08-VolatileLoadMerge.ll26
-rw-r--r--test/Transforms/InstCombine/2008-07-09-SubAndError.ll9
-rw-r--r--test/Transforms/InstCombine/2008-07-10-CastSextBool.ll17
-rw-r--r--test/Transforms/InstCombine/2008-07-10-ICmpBinOp.ll19
-rw-r--r--test/Transforms/InstCombine/2008-07-11-RemAnd.ll9
-rw-r--r--test/Transforms/InstCombine/2008-07-13-DivZero.ll16
-rw-r--r--test/Transforms/InstCombine/2008-07-16-fsub.ll8
-rw-r--r--test/Transforms/InstCombine/2008-07-16-sse2_storel_dq.ll13
-rw-r--r--test/Transforms/InstCombine/2008-08-05-And.ll23
-rw-r--r--test/Transforms/InstCombine/2008-08-17-ICmpXorSignbit.ll41
-rw-r--r--test/Transforms/InstCombine/2008-09-02-VectorCrash.ll27
-rw-r--r--test/Transforms/InstCombine/2008-09-29-FoldingOr.ll10
-rw-r--r--test/Transforms/InstCombine/2008-10-11-DivCompareFold.ll8
-rw-r--r--test/Transforms/InstCombine/2008-10-23-ConstFoldWithoutMask.ll8
-rw-r--r--test/Transforms/InstCombine/2008-11-01-SRemDemandedBits.ll8
-rw-r--r--test/Transforms/InstCombine/2008-11-08-FCmp.ll56
-rw-r--r--test/Transforms/InstCombine/2008-11-20-DivMulRem.ll67
-rw-r--r--test/Transforms/InstCombine/2008-11-27-IDivVector.ll11
-rw-r--r--test/Transforms/InstCombine/2008-11-27-MultiplyIntVec.ll11
-rw-r--r--test/Transforms/InstCombine/2008-11-27-UDivNegative.ll6
-rw-r--r--test/Transforms/InstCombine/2008-12-17-SRemNegConstVec.ll7
-rw-r--r--test/Transforms/InstCombine/2009-01-05-i128-crash.ll27
-rw-r--r--test/Transforms/InstCombine/2009-01-08-AlignAlloca.ll28
-rw-r--r--test/Transforms/InstCombine/2009-01-16-PointerAddrSpace.ll11
-rw-r--r--test/Transforms/InstCombine/2009-01-19-fmod-constant-float-specials.ll315
-rw-r--r--test/Transforms/InstCombine/2009-01-19-fmod-constant-float.ll75
-rw-r--r--test/Transforms/InstCombine/2009-01-24-EmptyStruct.ll18
-rw-r--r--test/Transforms/InstCombine/2009-01-31-InfIterate.ll22
-rw-r--r--test/Transforms/InstCombine/2009-01-31-Pressure.ll22
-rw-r--r--test/Transforms/InstCombine/2009-02-04-FPBitcast.ll12
-rw-r--r--test/Transforms/InstCombine/2009-02-20-InstCombine-SROA.ll279
-rw-r--r--test/Transforms/InstCombine/2009-02-21-LoadCST.ll12
-rw-r--r--test/Transforms/InstCombine/2009-02-25-CrashZeroSizeArray.ll38
-rw-r--r--test/Transforms/InstCombine/2009-03-18-vector-ashr-crash.ll11
-rw-r--r--test/Transforms/InstCombine/2009-03-20-AShrOverShift.ll9
-rw-r--r--test/Transforms/InstCombine/2009-03-24-InfLoop.ll9
-rw-r--r--test/Transforms/InstCombine/2009-04-07-MulPromoteToI96.ll13
-rw-r--r--test/Transforms/InstCombine/2009-05-23-FCmpToICmp.ll9
-rw-r--r--test/Transforms/InstCombine/2009-06-11-StoreAddrSpace.ll7
-rw-r--r--test/Transforms/InstCombine/2009-06-16-SRemDemandedBits.ll9
-rw-r--r--test/Transforms/InstCombine/2009-07-02-MaskedIntVector.ll15
-rw-r--r--test/Transforms/InstCombine/2009-12-17-CmpSelectNull.ll16
-rw-r--r--test/Transforms/InstCombine/2010-01-28-NegativeSRem.ll19
-rw-r--r--test/Transforms/InstCombine/2010-03-03-ExtElim.ll18
-rw-r--r--test/Transforms/InstCombine/2010-11-01-lshr-mask.ll46
-rw-r--r--test/Transforms/InstCombine/2010-11-21-SizeZeroTypeGEP.ll17
-rw-r--r--test/Transforms/InstCombine/2010-11-23-Distributed.ll23
-rw-r--r--test/Transforms/InstCombine/2011-02-14-InfLoop.ll19
-rw-r--r--test/Transforms/InstCombine/2011-03-08-SRemMinusOneBadOpt.ll12
-rw-r--r--test/Transforms/InstCombine/2011-05-02-VectorBoolean.ll15
-rw-r--r--test/Transforms/InstCombine/2011-05-13-InBoundsGEP.ll21
-rw-r--r--test/Transforms/InstCombine/2011-05-28-swapmulsub.ll57
-rw-r--r--test/Transforms/InstCombine/2011-06-13-nsw-alloca.ll63
-rw-r--r--test/Transforms/InstCombine/2011-09-03-Trampoline.ll87
-rw-r--r--test/Transforms/InstCombine/2011-10-07-AlignPromotion.ll20
-rw-r--r--test/Transforms/InstCombine/2012-01-11-OpaqueBitcastCrash.ll12
-rw-r--r--test/Transforms/InstCombine/2012-02-13-FCmp.ll35
-rw-r--r--test/Transforms/InstCombine/2012-02-28-ICmp.ll19
-rw-r--r--test/Transforms/InstCombine/2012-03-10-InstCombine.ll35
-rw-r--r--test/Transforms/InstCombine/2012-04-23-Neon-Intrinsics.ll68
-rw-r--r--test/Transforms/InstCombine/2012-04-24-vselect.ll13
-rw-r--r--test/Transforms/InstCombine/2012-04-30-SRem.ll12
-rw-r--r--test/Transforms/InstCombine/2012-05-27-Negative-Shift-Crash.ll61
-rw-r--r--test/Transforms/InstCombine/2012-05-28-select-hang.ll39
-rw-r--r--test/Transforms/InstCombine/2012-06-06-LoadOfPHIs.ll162
-rw-r--r--test/Transforms/InstCombine/2012-07-25-LoadPart.ll12
-rw-r--r--test/Transforms/InstCombine/2012-07-30-addrsp-bitcast.ll10
-rw-r--r--test/Transforms/InstCombine/2012-08-28-udiv_ashl.ll57
-rw-r--r--test/Transforms/InstCombine/2012-09-17-ZeroSizedAlloca.ll24
-rw-r--r--test/Transforms/InstCombine/2012-3-15-or-xor-constant.ll12
-rw-r--r--test/Transforms/InstCombine/2012-6-7-vselect-bitcast.ll11
-rw-r--r--test/Transforms/InstCombine/CPP_min_max.ll34
-rw-r--r--test/Transforms/InstCombine/ExtractCast.ll27
-rw-r--r--test/Transforms/InstCombine/IntPtrCast.ll10
-rw-r--r--test/Transforms/InstCombine/JavaCompare.ll14
-rw-r--r--test/Transforms/InstCombine/LandingPadClauses.ll233
-rw-r--r--test/Transforms/InstCombine/README.txt4
-rw-r--r--test/Transforms/InstCombine/add-shrink.ll14
-rw-r--r--test/Transforms/InstCombine/add-sitofp.ll9
-rw-r--r--test/Transforms/InstCombine/add.ll301
-rw-r--r--test/Transforms/InstCombine/add2.ll43
-rw-r--r--test/Transforms/InstCombine/add3.ll21
-rw-r--r--test/Transforms/InstCombine/addnegneg.ll12
-rw-r--r--test/Transforms/InstCombine/adjust-for-sminmax.ll85
-rw-r--r--test/Transforms/InstCombine/align-2d-gep.ll44
-rw-r--r--test/Transforms/InstCombine/align-addr.ll60
-rw-r--r--test/Transforms/InstCombine/align-external.ll29
-rw-r--r--test/Transforms/InstCombine/alloca.ll96
-rw-r--r--test/Transforms/InstCombine/and-compare.ll11
-rw-r--r--test/Transforms/InstCombine/and-fcmp.ll79
-rw-r--r--test/Transforms/InstCombine/and-not-or.ll34
-rw-r--r--test/Transforms/InstCombine/and-or-and.ll61
-rw-r--r--test/Transforms/InstCombine/and-or-not.ll46
-rw-r--r--test/Transforms/InstCombine/and-or.ll39
-rw-r--r--test/Transforms/InstCombine/and-xor-merge.ll19
-rw-r--r--test/Transforms/InstCombine/and-xor-or.ll24
-rw-r--r--test/Transforms/InstCombine/and.ll255
-rw-r--r--test/Transforms/InstCombine/and2.ll44
-rw-r--r--test/Transforms/InstCombine/apint-add1.ll34
-rw-r--r--test/Transforms/InstCombine/apint-add2.ll46
-rw-r--r--test/Transforms/InstCombine/apint-and-compare.ll16
-rw-r--r--test/Transforms/InstCombine/apint-and-or-and.ll50
-rw-r--r--test/Transforms/InstCombine/apint-and-xor-merge.ll22
-rw-r--r--test/Transforms/InstCombine/apint-and1.ll57
-rw-r--r--test/Transforms/InstCombine/apint-and2.ll82
-rw-r--r--test/Transforms/InstCombine/apint-call-cast-target.ll17
-rw-r--r--test/Transforms/InstCombine/apint-cast-and-cast.ll15
-rw-r--r--test/Transforms/InstCombine/apint-cast-cast-to-and.ll8
-rw-r--r--test/Transforms/InstCombine/apint-cast.ll30
-rw-r--r--test/Transforms/InstCombine/apint-div1.ll22
-rw-r--r--test/Transforms/InstCombine/apint-div2.ll22
-rw-r--r--test/Transforms/InstCombine/apint-mul1.ll11
-rw-r--r--test/Transforms/InstCombine/apint-mul2.ll12
-rw-r--r--test/Transforms/InstCombine/apint-not.ll42
-rw-r--r--test/Transforms/InstCombine/apint-or1.ll36
-rw-r--r--test/Transforms/InstCombine/apint-or2.ll35
-rw-r--r--test/Transforms/InstCombine/apint-rem1.ll22
-rw-r--r--test/Transforms/InstCombine/apint-rem2.ll22
-rw-r--r--test/Transforms/InstCombine/apint-select.ll44
-rw-r--r--test/Transforms/InstCombine/apint-shift-simplify.ll23
-rw-r--r--test/Transforms/InstCombine/apint-shift.ll251
-rw-r--r--test/Transforms/InstCombine/apint-shl-trunc.ll25
-rw-r--r--test/Transforms/InstCombine/apint-sub.ll141
-rw-r--r--test/Transforms/InstCombine/apint-xor1.ll50
-rw-r--r--test/Transforms/InstCombine/apint-xor2.ll51
-rw-r--r--test/Transforms/InstCombine/apint-zext1.ll11
-rw-r--r--test/Transforms/InstCombine/apint-zext2.ll11
-rw-r--r--test/Transforms/InstCombine/ashr-nop.ll8
-rw-r--r--test/Transforms/InstCombine/atomic.ll24
-rw-r--r--test/Transforms/InstCombine/badmalloc.ll41
-rw-r--r--test/Transforms/InstCombine/binop-cast.ll9
-rw-r--r--test/Transforms/InstCombine/bit-checks.ll372
-rw-r--r--test/Transforms/InstCombine/bit-tracking.ll26
-rw-r--r--test/Transforms/InstCombine/bitcast-sext-vector.ll11
-rw-r--r--test/Transforms/InstCombine/bitcast-store.ll21
-rw-r--r--test/Transforms/InstCombine/bitcast-vec-canon.ll22
-rw-r--r--test/Transforms/InstCombine/bitcast-vec-uniform.ll70
-rw-r--r--test/Transforms/InstCombine/bitcast-vector-fold.ll33
-rw-r--r--test/Transforms/InstCombine/bitcast.ll139
-rw-r--r--test/Transforms/InstCombine/bitcount.ll19
-rw-r--r--test/Transforms/InstCombine/bittest.ll30
-rw-r--r--test/Transforms/InstCombine/bswap-fold.ll71
-rw-r--r--test/Transforms/InstCombine/bswap.ll74
-rw-r--r--test/Transforms/InstCombine/call-cast-target.ll14
-rw-r--r--test/Transforms/InstCombine/call-intrinsics.ll19
-rw-r--r--test/Transforms/InstCombine/call.ll136
-rw-r--r--test/Transforms/InstCombine/call2.ll25
-rw-r--r--test/Transforms/InstCombine/canonicalize_branch.ll69
-rw-r--r--test/Transforms/InstCombine/cast-mul-select.ll41
-rw-r--r--test/Transforms/InstCombine/cast-set.ll65
-rw-r--r--test/Transforms/InstCombine/cast.ll696
-rw-r--r--test/Transforms/InstCombine/cast_ptr.ll79
-rw-r--r--test/Transforms/InstCombine/compare-signs.ll58
-rw-r--r--test/Transforms/InstCombine/constant-fold-compare.ll8
-rw-r--r--test/Transforms/InstCombine/constant-fold-gep.ll74
-rw-r--r--test/Transforms/InstCombine/crash.ll398
-rw-r--r--test/Transforms/InstCombine/dce-iterate.ll24
-rw-r--r--test/Transforms/InstCombine/deadcode.ll33
-rw-r--r--test/Transforms/InstCombine/debuginfo.ll57
-rw-r--r--test/Transforms/InstCombine/devirt.ll39
-rw-r--r--test/Transforms/InstCombine/div-shift.ll23
-rw-r--r--test/Transforms/InstCombine/div.ll134
-rw-r--r--test/Transforms/InstCombine/enforce-known-alignment.ll18
-rw-r--r--test/Transforms/InstCombine/exact.ll170
-rw-r--r--test/Transforms/InstCombine/extractvalue.ll107
-rw-r--r--test/Transforms/InstCombine/fcmp-select.ll53
-rw-r--r--test/Transforms/InstCombine/fcmp-special.ll155
-rw-r--r--test/Transforms/InstCombine/fcmp.ll161
-rw-r--r--test/Transforms/InstCombine/fdiv.ll25
-rw-r--r--test/Transforms/InstCombine/fold-bin-operand.ll17
-rw-r--r--test/Transforms/InstCombine/fold-calls.ll19
-rw-r--r--test/Transforms/InstCombine/fold-sqrt-sqrtf.ll17
-rw-r--r--test/Transforms/InstCombine/fold-vector-select.ll148
-rw-r--r--test/Transforms/InstCombine/fold-vector-zero.ll35
-rw-r--r--test/Transforms/InstCombine/fp-ret-bitcast.ll28
-rw-r--r--test/Transforms/InstCombine/fpcast.ll15
-rw-r--r--test/Transforms/InstCombine/fpextend.ll36
-rw-r--r--test/Transforms/InstCombine/fsub.ll23
-rw-r--r--test/Transforms/InstCombine/gep-addrspace.ll19
-rw-r--r--test/Transforms/InstCombine/gepgep.ll13
-rw-r--r--test/Transforms/InstCombine/getelementptr.ll494
-rw-r--r--test/Transforms/InstCombine/hoist_instr.ll18
-rw-r--r--test/Transforms/InstCombine/icmp.ll661
-rw-r--r--test/Transforms/InstCombine/idioms.ll32
-rw-r--r--test/Transforms/InstCombine/intrinsics.ll222
-rw-r--r--test/Transforms/InstCombine/invariant.ll16
-rw-r--r--test/Transforms/InstCombine/invoke.ll65
-rw-r--r--test/Transforms/InstCombine/known_align.ll27
-rw-r--r--test/Transforms/InstCombine/lit.local.cfg1
-rw-r--r--test/Transforms/InstCombine/load-cmp.ll112
-rw-r--r--test/Transforms/InstCombine/load-select.ll16
-rw-r--r--test/Transforms/InstCombine/load.ll98
-rw-r--r--test/Transforms/InstCombine/load3.ll27
-rw-r--r--test/Transforms/InstCombine/loadstore-alignment.ll67
-rw-r--r--test/Transforms/InstCombine/logical-select.ll68
-rw-r--r--test/Transforms/InstCombine/lshr-phi.ll35
-rw-r--r--test/Transforms/InstCombine/malloc-free-delete.ll93
-rw-r--r--test/Transforms/InstCombine/memcpy-from-global.ll136
-rw-r--r--test/Transforms/InstCombine/memcpy-to-load.ll13
-rw-r--r--test/Transforms/InstCombine/memcpy.ll27
-rw-r--r--test/Transforms/InstCombine/memmove.ll39
-rw-r--r--test/Transforms/InstCombine/memset.ll14
-rw-r--r--test/Transforms/InstCombine/memset2.ll15
-rw-r--r--test/Transforms/InstCombine/memset_chk.ll18
-rw-r--r--test/Transforms/InstCombine/merge-icmp.ll29
-rw-r--r--test/Transforms/InstCombine/mul-masked-bits.ll10
-rw-r--r--test/Transforms/InstCombine/mul.ll185
-rw-r--r--test/Transforms/InstCombine/multi-use-or.ll24
-rw-r--r--test/Transforms/InstCombine/narrow.ll18
-rw-r--r--test/Transforms/InstCombine/neon-intrinsics.ll25
-rw-r--r--test/Transforms/InstCombine/no-negzero.ll33
-rw-r--r--test/Transforms/InstCombine/not-fcmp.ll10
-rw-r--r--test/Transforms/InstCombine/not.ll54
-rw-r--r--test/Transforms/InstCombine/nothrow.ll8
-rw-r--r--test/Transforms/InstCombine/nsw.ll83
-rw-r--r--test/Transforms/InstCombine/objsize-64.ll39
-rw-r--r--test/Transforms/InstCombine/objsize.ll258
-rw-r--r--test/Transforms/InstCombine/odr-linkage.ll19
-rw-r--r--test/Transforms/InstCombine/or-fcmp.ll58
-rw-r--r--test/Transforms/InstCombine/or-to-xor.ll42
-rw-r--r--test/Transforms/InstCombine/or-xor.ll94
-rw-r--r--test/Transforms/InstCombine/or.ll411
-rw-r--r--test/Transforms/InstCombine/overflow.ll155
-rw-r--r--test/Transforms/InstCombine/phi-merge-gep.ll102
-rw-r--r--test/Transforms/InstCombine/phi.ll632
-rw-r--r--test/Transforms/InstCombine/pr12251.ll15
-rw-r--r--test/Transforms/InstCombine/pr12338.ll24
-rw-r--r--test/Transforms/InstCombine/pr2645-0.ll33
-rw-r--r--test/Transforms/InstCombine/pr2645-1.ll39
-rw-r--r--test/Transforms/InstCombine/pr2996.ll12
-rw-r--r--test/Transforms/InstCombine/pr8547.ll26
-rw-r--r--test/Transforms/InstCombine/preserve-sminmax.ll32
-rw-r--r--test/Transforms/InstCombine/ptr-int-cast.ll29
-rw-r--r--test/Transforms/InstCombine/rem.ll88
-rw-r--r--test/Transforms/InstCombine/sdiv-1.ll22
-rw-r--r--test/Transforms/InstCombine/sdiv-2.ll28
-rw-r--r--test/Transforms/InstCombine/select-2.ll18
-rw-r--r--test/Transforms/InstCombine/select-crash.ll49
-rw-r--r--test/Transforms/InstCombine/select-load-call.ll15
-rw-r--r--test/Transforms/InstCombine/select.ll831
-rw-r--r--test/Transforms/InstCombine/set.ll171
-rw-r--r--test/Transforms/InstCombine/setcc-strength-reduce.ll37
-rw-r--r--test/Transforms/InstCombine/sext.ll186
-rw-r--r--test/Transforms/InstCombine/shift-sra.ll78
-rw-r--r--test/Transforms/InstCombine/shift.ll661
-rw-r--r--test/Transforms/InstCombine/shufflemask-undef.ll109
-rw-r--r--test/Transforms/InstCombine/shufflevec-constant.ll14
-rw-r--r--test/Transforms/InstCombine/sign-test-and-or.ll179
-rw-r--r--test/Transforms/InstCombine/signed-comparison.ll28
-rw-r--r--test/Transforms/InstCombine/signext.ll87
-rw-r--r--test/Transforms/InstCombine/simplify-demanded-bits-pointer.ll84
-rw-r--r--test/Transforms/InstCombine/sink_instruction.ll56
-rw-r--r--test/Transforms/InstCombine/sitofp.ll55
-rw-r--r--test/Transforms/InstCombine/sqrt.ll54
-rw-r--r--test/Transforms/InstCombine/srem-simplify-bug.ll9
-rw-r--r--test/Transforms/InstCombine/srem.ll8
-rw-r--r--test/Transforms/InstCombine/srem1.ll18
-rw-r--r--test/Transforms/InstCombine/stack-overalign.ll29
-rw-r--r--test/Transforms/InstCombine/stacksaverestore.ll56
-rw-r--r--test/Transforms/InstCombine/store.ll85
-rw-r--r--test/Transforms/InstCombine/strcpy_chk-64.ll18
-rw-r--r--test/Transforms/InstCombine/strcpy_chk.ll13
-rw-r--r--test/Transforms/InstCombine/struct-assign-tbaa.ll26
-rw-r--r--test/Transforms/InstCombine/sub-xor.ll37
-rw-r--r--test/Transforms/InstCombine/sub.ll329
-rw-r--r--test/Transforms/InstCombine/trunc.ll120
-rw-r--r--test/Transforms/InstCombine/udiv-simplify-bug-0.ll14
-rw-r--r--test/Transforms/InstCombine/udiv-simplify-bug-1.ll20
-rw-r--r--test/Transforms/InstCombine/udiv_select_to_select_shift.ll17
-rw-r--r--test/Transforms/InstCombine/udivrem-change-width.ll62
-rw-r--r--test/Transforms/InstCombine/urem-simplify-bug.ll32
-rw-r--r--test/Transforms/InstCombine/urem.ll8
-rw-r--r--test/Transforms/InstCombine/vec_demanded_elts.ll212
-rw-r--r--test/Transforms/InstCombine/vec_extract_elt.ll9
-rw-r--r--test/Transforms/InstCombine/vec_insertelt.ll7
-rw-r--r--test/Transforms/InstCombine/vec_narrow.ll10
-rw-r--r--test/Transforms/InstCombine/vec_sext.ll22
-rw-r--r--test/Transforms/InstCombine/vec_shuffle.ll155
-rw-r--r--test/Transforms/InstCombine/vector-casts.ll151
-rw-r--r--test/Transforms/InstCombine/vector-srem.ll9
-rw-r--r--test/Transforms/InstCombine/vector_gep1.ll37
-rw-r--r--test/Transforms/InstCombine/volatile_store.ll14
-rw-r--r--test/Transforms/InstCombine/x86-crc32-demanded.ll17
-rw-r--r--test/Transforms/InstCombine/xor-undef.ll6
-rw-r--r--test/Transforms/InstCombine/xor.ll193
-rw-r--r--test/Transforms/InstCombine/xor2.ll53
-rw-r--r--test/Transforms/InstCombine/zero-point-zero-add.ll15
-rw-r--r--test/Transforms/InstCombine/zeroext-and-reduce.ll10
-rw-r--r--test/Transforms/InstCombine/zext-bool-add-sub.ll16
-rw-r--r--test/Transforms/InstCombine/zext-fold.ll12
-rw-r--r--test/Transforms/InstCombine/zext-or-icmp.ll35
-rw-r--r--test/Transforms/InstCombine/zext.ll11
-rw-r--r--test/Transforms/InstSimplify/2010-12-20-Boolean.ll29
-rw-r--r--test/Transforms/InstSimplify/2010-12-20-Distribute.ll62
-rw-r--r--test/Transforms/InstSimplify/2011-01-14-Thread.ll9
-rw-r--r--test/Transforms/InstSimplify/2011-02-01-Vector.ll8
-rw-r--r--test/Transforms/InstSimplify/2011-09-05-InsertExtractValue.ll29
-rw-r--r--test/Transforms/InstSimplify/2011-10-27-BinOpCrash.ll12
-rw-r--r--test/Transforms/InstSimplify/2011-11-23-MaskedBitsCrash.ll17
-rw-r--r--test/Transforms/InstSimplify/AndOrXor.ll22
-rw-r--r--test/Transforms/InstSimplify/compare.ll600
-rw-r--r--test/Transforms/InstSimplify/exact-nsw-nuw.ll44
-rw-r--r--test/Transforms/InstSimplify/fdiv.ll17
-rw-r--r--test/Transforms/InstSimplify/lit.local.cfg1
-rw-r--r--test/Transforms/InstSimplify/maxmin.ll269
-rw-r--r--test/Transforms/InstSimplify/phi.ll22
-rw-r--r--test/Transforms/InstSimplify/ptr_diff.ll48
-rw-r--r--test/Transforms/InstSimplify/reassociate.ll195
-rw-r--r--test/Transforms/InstSimplify/rem.ll17
-rw-r--r--test/Transforms/InstSimplify/undef.ll155
-rw-r--r--test/Transforms/InstSimplify/vector_gep.ll8
-rw-r--r--test/Transforms/Internalize/2008-05-09-AllButMain.ll27
-rw-r--r--test/Transforms/Internalize/2008-05-09-AllButMain.ll.apifile2
-rw-r--r--test/Transforms/Internalize/2009-01-05-InternalizeAliases.ll10
-rw-r--r--test/Transforms/Internalize/available_externally.ll16
-rw-r--r--test/Transforms/Internalize/lit.local.cfg1
-rw-r--r--test/Transforms/JumpThreading/2008-11-27-EntryMunge.ll13
-rw-r--r--test/Transforms/JumpThreading/2010-08-26-and.ll162
-rw-r--r--test/Transforms/JumpThreading/2011-04-02-SimplifyDeadBlock.ll32
-rw-r--r--test/Transforms/JumpThreading/2011-04-14-InfLoop.ll31
-rw-r--r--test/Transforms/JumpThreading/2012-07-19-NoSuccessorIndirectBr.ll8
-rw-r--r--test/Transforms/JumpThreading/and-and-cond.ll37
-rw-r--r--test/Transforms/JumpThreading/and-cond.ll35
-rw-r--r--test/Transforms/JumpThreading/basic.ll478
-rw-r--r--test/Transforms/JumpThreading/branch-no-const.ll21
-rw-r--r--test/Transforms/JumpThreading/compare.ll30
-rw-r--r--test/Transforms/JumpThreading/crash.ll513
-rw-r--r--test/Transforms/JumpThreading/degenerate-phi.ll24
-rw-r--r--test/Transforms/JumpThreading/indirectbr.ll94
-rw-r--r--test/Transforms/JumpThreading/lit.local.cfg1
-rw-r--r--test/Transforms/JumpThreading/lvi-load.ll49
-rw-r--r--test/Transforms/JumpThreading/no-irreducible-loops.ll38
-rw-r--r--test/Transforms/JumpThreading/or-undef.ll69
-rw-r--r--test/Transforms/JumpThreading/phi-eq.ll209
-rw-r--r--test/Transforms/JumpThreading/pr9331.ll50
-rw-r--r--test/Transforms/JumpThreading/select.ll159
-rw-r--r--test/Transforms/JumpThreading/thread-loads.ll81
-rw-r--r--test/Transforms/LCSSA/2006-06-03-IncorrectIDFPhis.ll21
-rw-r--r--test/Transforms/LCSSA/2006-06-12-MultipleExitsSameBlock.ll27
-rw-r--r--test/Transforms/LCSSA/2006-07-09-NoDominator.ll24
-rw-r--r--test/Transforms/LCSSA/2006-10-31-UnreachableBlock-2.ll145
-rw-r--r--test/Transforms/LCSSA/2006-10-31-UnreachableBlock.ll184
-rw-r--r--test/Transforms/LCSSA/2007-07-12-LICM-2.ll17
-rw-r--r--test/Transforms/LCSSA/2007-07-12-LICM-3.ll24
-rw-r--r--test/Transforms/LCSSA/2007-07-12-LICM.ll14
-rw-r--r--test/Transforms/LCSSA/basictest.ll24
-rw-r--r--test/Transforms/LCSSA/indirectbr.ll542
-rw-r--r--test/Transforms/LCSSA/invoke-dest.ll151
-rw-r--r--test/Transforms/LCSSA/lit.local.cfg1
-rw-r--r--test/Transforms/LCSSA/unreachable-use.ll27
-rw-r--r--test/Transforms/LCSSA/unused-phis.ll38
-rw-r--r--test/Transforms/LICM/2003-02-26-LoopExitNotDominated.ll18
-rw-r--r--test/Transforms/LICM/2003-02-27-NestedLoopExitBlocks.ll17
-rw-r--r--test/Transforms/LICM/2003-02-27-PreheaderExitNodeUpdate.ll16
-rw-r--r--test/Transforms/LICM/2003-02-27-PreheaderProblem.ll24
-rw-r--r--test/Transforms/LICM/2003-02-27-StoreSinkPHIs.ll15
-rw-r--r--test/Transforms/LICM/2003-02-28-PromoteDifferentType.ll15
-rw-r--r--test/Transforms/LICM/2003-05-02-LoadHoist.ll23
-rw-r--r--test/Transforms/LICM/2003-12-11-SinkingToPHI.ll16
-rw-r--r--test/Transforms/LICM/2004-09-14-AliasAnalysisInvalidate.ll19
-rw-r--r--test/Transforms/LICM/2004-11-17-UndefIndexCrash.ll20
-rw-r--r--test/Transforms/LICM/2006-09-12-DeadUserOfSunkInstr.ll148
-rw-r--r--test/Transforms/LICM/2007-05-22-VolatileSink.ll56
-rw-r--r--test/Transforms/LICM/2007-07-30-AliasSet.ll39
-rw-r--r--test/Transforms/LICM/2007-09-17-PromoteValue.ll61
-rw-r--r--test/Transforms/LICM/2007-09-24-PromoteNullValue.ll46
-rw-r--r--test/Transforms/LICM/2007-10-01-PromoteSafeValue.ll23
-rw-r--r--test/Transforms/LICM/2008-05-20-AliasSetVAArg.ll30
-rw-r--r--test/Transforms/LICM/2008-07-22-LoadGlobalConstant.ll39
-rw-r--r--test/Transforms/LICM/2009-12-10-LICM-Indbr-Crash.ll21
-rw-r--r--test/Transforms/LICM/2011-04-06-HoistMissedASTUpdate.ll32
-rw-r--r--test/Transforms/LICM/2011-04-06-PromoteResultOfPromotion.ll37
-rw-r--r--test/Transforms/LICM/2011-04-09-RAUW-AST.ll49
-rw-r--r--test/Transforms/LICM/2011-07-06-Alignment.ll26
-rw-r--r--test/Transforms/LICM/Preserve-LCSSA.ll25
-rw-r--r--test/Transforms/LICM/atomics.ll79
-rw-r--r--test/Transforms/LICM/basictest.ll15
-rw-r--r--test/Transforms/LICM/crash.ll74
-rw-r--r--test/Transforms/LICM/debug-value.ll62
-rw-r--r--test/Transforms/LICM/hoist-invariant-load.ll39
-rw-r--r--test/Transforms/LICM/hoisting.ll92
-rw-r--r--test/Transforms/LICM/lit.local.cfg1
-rw-r--r--test/Transforms/LICM/no-preheader-test.ll20
-rw-r--r--test/Transforms/LICM/promote-order.ll41
-rw-r--r--test/Transforms/LICM/scalar-promote-memmodel.ll37
-rw-r--r--test/Transforms/LICM/scalar_promote.ll150
-rw-r--r--test/Transforms/LICM/sinking.ll249
-rw-r--r--test/Transforms/LICM/speculate.ll189
-rw-r--r--test/Transforms/LoopDeletion/2007-07-23-InfiniteLoop.ll13
-rw-r--r--test/Transforms/LoopDeletion/2008-05-06-Phi.ll109
-rw-r--r--test/Transforms/LoopDeletion/2011-06-21-phioperands.ll182
-rw-r--r--test/Transforms/LoopDeletion/dcetest.ll36
-rw-r--r--test/Transforms/LoopDeletion/lit.local.cfg1
-rw-r--r--test/Transforms/LoopDeletion/multiple-exit-conditions.ll27
-rw-r--r--test/Transforms/LoopDeletion/multiple-exits.ll26
-rw-r--r--test/Transforms/LoopDeletion/simplify-then-delete.ll65
-rw-r--r--test/Transforms/LoopIdiom/basic.ll386
-rw-r--r--test/Transforms/LoopIdiom/debug-line.ll49
-rw-r--r--test/Transforms/LoopIdiom/lit.local.cfg1
-rw-r--r--test/Transforms/LoopIdiom/memset_noidiom.ll30
-rw-r--r--test/Transforms/LoopRotate/2009-01-25-SingleEntryPhi.ll21
-rw-r--r--test/Transforms/LoopRotate/PhiRename-1.ll95
-rw-r--r--test/Transforms/LoopRotate/PhiSelfRefernce-1.ll39
-rw-r--r--test/Transforms/LoopRotate/alloca.ll33
-rw-r--r--test/Transforms/LoopRotate/basic.ll35
-rw-r--r--test/Transforms/LoopRotate/crash.ll155
-rw-r--r--test/Transforms/LoopRotate/dbgvalue.ll99
-rw-r--r--test/Transforms/LoopRotate/indirectbr.ll43
-rw-r--r--test/Transforms/LoopRotate/lit.local.cfg1
-rw-r--r--test/Transforms/LoopRotate/multiple-exits.ll236
-rw-r--r--test/Transforms/LoopRotate/phi-duplicate.ll40
-rw-r--r--test/Transforms/LoopRotate/pr2639.ll38
-rw-r--r--test/Transforms/LoopRotate/preserve-scev.ll47
-rw-r--r--test/Transforms/LoopRotate/simplifylatch.ll39
-rw-r--r--test/Transforms/LoopSimplify/2003-04-25-AssertFail.ll20
-rw-r--r--test/Transforms/LoopSimplify/2003-05-12-PreheaderExitOfChild.ll42
-rw-r--r--test/Transforms/LoopSimplify/2003-08-15-PreheadersFail.ll52
-rw-r--r--test/Transforms/LoopSimplify/2003-12-10-ExitBlocksProblem.ll36
-rw-r--r--test/Transforms/LoopSimplify/2004-02-05-DominatorInfoCorruption.ll14
-rw-r--r--test/Transforms/LoopSimplify/2004-03-15-IncorrectDomUpdate.ll11
-rw-r--r--test/Transforms/LoopSimplify/2004-04-01-IncorrectDomUpdate.ll20
-rw-r--r--test/Transforms/LoopSimplify/2004-04-12-LoopSimplify-SwitchBackedges.ll18
-rw-r--r--test/Transforms/LoopSimplify/2004-04-13-LoopSimplifyUpdateDomFrontier.ll18
-rw-r--r--test/Transforms/LoopSimplify/2007-10-28-InvokeCrash.ll29
-rw-r--r--test/Transforms/LoopSimplify/2010-07-15-IncorrectDomFrontierUpdate.ll20
-rw-r--r--test/Transforms/LoopSimplify/2010-12-26-PHIInfiniteLoop.ll43
-rw-r--r--test/Transforms/LoopSimplify/2011-12-14-LandingpadHeader.ll45
-rw-r--r--test/Transforms/LoopSimplify/2012-03-20-indirectbr.ll41
-rw-r--r--test/Transforms/LoopSimplify/basictest.ll16
-rw-r--r--test/Transforms/LoopSimplify/hardertest.ll15
-rw-r--r--test/Transforms/LoopSimplify/indirectbr-backedge.ll35
-rw-r--r--test/Transforms/LoopSimplify/indirectbr.ll100
-rw-r--r--test/Transforms/LoopSimplify/lit.local.cfg1
-rw-r--r--test/Transforms/LoopSimplify/merge-exits.ll44
-rw-r--r--test/Transforms/LoopSimplify/phi-node-simplify.ll55
-rw-r--r--test/Transforms/LoopSimplify/preserve-scev.ll138
-rw-r--r--test/Transforms/LoopSimplify/single-backedge.ll23
-rw-r--r--test/Transforms/LoopSimplify/unreachable-loop-pred.ll20
-rw-r--r--test/Transforms/LoopStrengthReduce/2005-08-15-AddRecIV.ll57
-rw-r--r--test/Transforms/LoopStrengthReduce/2005-08-17-OutOfLoopVariant.ll17
-rw-r--r--test/Transforms/LoopStrengthReduce/2005-09-12-UsesOutOutsideOfLoop.ll32
-rw-r--r--test/Transforms/LoopStrengthReduce/2007-04-23-UseIterator.ll71
-rw-r--r--test/Transforms/LoopStrengthReduce/2008-08-13-CmpStride.ll31
-rw-r--r--test/Transforms/LoopStrengthReduce/2008-08-14-ShadowIV.ll99
-rw-r--r--test/Transforms/LoopStrengthReduce/2008-09-09-Overflow.ll48
-rw-r--r--test/Transforms/LoopStrengthReduce/2009-01-13-nonconstant-stride-outside-loop.ll39
-rw-r--r--test/Transforms/LoopStrengthReduce/2009-04-28-no-reduce-mul.ll48
-rw-r--r--test/Transforms/LoopStrengthReduce/2011-07-19-CritEdgeBreakCrash.ll52
-rw-r--r--test/Transforms/LoopStrengthReduce/2011-07-20-DoubleIV.ll43
-rw-r--r--test/Transforms/LoopStrengthReduce/2011-10-03-CritEdgeMerge.ll81
-rw-r--r--test/Transforms/LoopStrengthReduce/2011-10-06-ReusePhi.ll53
-rw-r--r--test/Transforms/LoopStrengthReduce/2011-10-13-SCEVChain.ll111
-rw-r--r--test/Transforms/LoopStrengthReduce/2011-10-14-IntPtr.ll27
-rw-r--r--test/Transforms/LoopStrengthReduce/2011-12-19-PostincQuadratic.ll39
-rw-r--r--test/Transforms/LoopStrengthReduce/2012-01-02-nopreheader.ll88
-rw-r--r--test/Transforms/LoopStrengthReduce/2012-01-16-nopreheader.ll113
-rw-r--r--test/Transforms/LoopStrengthReduce/2012-03-15-nopreheader.ll155
-rw-r--r--test/Transforms/LoopStrengthReduce/2012-03-26-constexpr.ll49
-rw-r--r--test/Transforms/LoopStrengthReduce/2012-07-13-ExpandUDiv.ll90
-rw-r--r--test/Transforms/LoopStrengthReduce/2012-07-18-LimitReassociate.ll517
-rw-r--r--test/Transforms/LoopStrengthReduce/ARM/2012-06-15-lsr-noaddrmode.ll102
-rw-r--r--test/Transforms/LoopStrengthReduce/ARM/ivchain-ARM.ll292
-rw-r--r--test/Transforms/LoopStrengthReduce/ARM/lit.local.cfg6
-rw-r--r--test/Transforms/LoopStrengthReduce/X86/2009-11-10-LSRCrash.ll130
-rw-r--r--test/Transforms/LoopStrengthReduce/X86/2011-11-29-postincphi.ll36
-rw-r--r--test/Transforms/LoopStrengthReduce/X86/2011-12-04-loserreg.ll96
-rw-r--r--test/Transforms/LoopStrengthReduce/X86/2012-01-13-phielim.ll148
-rw-r--r--test/Transforms/LoopStrengthReduce/X86/ivchain-X86.ll300
-rw-r--r--test/Transforms/LoopStrengthReduce/X86/ivchain-stress-X86.ll96
-rw-r--r--test/Transforms/LoopStrengthReduce/X86/lit.local.cfg6
-rw-r--r--test/Transforms/LoopStrengthReduce/addrec-gep.ll82
-rw-r--r--test/Transforms/LoopStrengthReduce/count-to-zero.ll42
-rw-r--r--test/Transforms/LoopStrengthReduce/dead-phi.ll21
-rw-r--r--test/Transforms/LoopStrengthReduce/different-type-ivs.ll25
-rw-r--r--test/Transforms/LoopStrengthReduce/dominate-assert.ll70
-rw-r--r--test/Transforms/LoopStrengthReduce/dont-hoist-simple-loop-constants.ll23
-rw-r--r--test/Transforms/LoopStrengthReduce/dont_insert_redundant_ops.ll36
-rw-r--r--test/Transforms/LoopStrengthReduce/dont_reduce_bytes.ll22
-rw-r--r--test/Transforms/LoopStrengthReduce/dont_reverse.ll21
-rw-r--r--test/Transforms/LoopStrengthReduce/exit_compare_live_range.ll21
-rw-r--r--test/Transforms/LoopStrengthReduce/hoist-parent-preheader.ll32
-rw-r--r--test/Transforms/LoopStrengthReduce/invariant_value_first.ll24
-rw-r--r--test/Transforms/LoopStrengthReduce/invariant_value_first_arg.ll21
-rw-r--r--test/Transforms/LoopStrengthReduce/ivchain.ll43
-rw-r--r--test/Transforms/LoopStrengthReduce/lit.local.cfg1
-rw-r--r--test/Transforms/LoopStrengthReduce/nested-reduce.ll49
-rw-r--r--test/Transforms/LoopStrengthReduce/nonlinear-postinc.ll44
-rw-r--r--test/Transforms/LoopStrengthReduce/ops_after_indvar.ll26
-rw-r--r--test/Transforms/LoopStrengthReduce/phi_node_update_multiple_preds.ll28
-rw-r--r--test/Transforms/LoopStrengthReduce/post-inc-icmpzero.ll91
-rw-r--r--test/Transforms/LoopStrengthReduce/pr12018.ll38
-rw-r--r--test/Transforms/LoopStrengthReduce/pr12048.ll38
-rw-r--r--test/Transforms/LoopStrengthReduce/pr12691.ll34
-rw-r--r--test/Transforms/LoopStrengthReduce/pr2537.ll21
-rw-r--r--test/Transforms/LoopStrengthReduce/pr2570.ll287
-rw-r--r--test/Transforms/LoopStrengthReduce/pr3086.ll29
-rw-r--r--test/Transforms/LoopStrengthReduce/pr3399.ll32
-rw-r--r--test/Transforms/LoopStrengthReduce/pr3571.ll27
-rw-r--r--test/Transforms/LoopStrengthReduce/preserve-gep-loop-variant.ll42
-rw-r--r--test/Transforms/LoopStrengthReduce/quadradic-exit-value.ll18
-rw-r--r--test/Transforms/LoopStrengthReduce/related_indvars.ll27
-rw-r--r--test/Transforms/LoopStrengthReduce/remove_indvar.ll21
-rw-r--r--test/Transforms/LoopStrengthReduce/share_code_in_preheader.ll27
-rw-r--r--test/Transforms/LoopStrengthReduce/share_ivs.ll24
-rw-r--r--test/Transforms/LoopStrengthReduce/uglygep.ll66
-rw-r--r--test/Transforms/LoopStrengthReduce/use_postinc_value_outside_loop.ll29
-rw-r--r--test/Transforms/LoopStrengthReduce/var_stride_used_by_compare.ll41
-rw-r--r--test/Transforms/LoopStrengthReduce/variable_stride.ll18
-rw-r--r--test/Transforms/LoopUnroll/2004-05-13-DontUnrollTooMuch.ll14
-rw-r--r--test/Transforms/LoopUnroll/2005-03-06-BadLoopInfoUpdate.ll22
-rw-r--r--test/Transforms/LoopUnroll/2006-08-24-MultiBlockLoop.ll16
-rw-r--r--test/Transforms/LoopUnroll/2007-04-16-PhiUpdate.ll17
-rw-r--r--test/Transforms/LoopUnroll/2007-05-05-UnrollMiscomp.ll36
-rw-r--r--test/Transforms/LoopUnroll/2007-05-09-UnknownTripCount.ll18
-rw-r--r--test/Transforms/LoopUnroll/2007-11-05-Crash.ll295
-rw-r--r--test/Transforms/LoopUnroll/2011-08-08-PhiUpdate.ll103
-rw-r--r--test/Transforms/LoopUnroll/2011-08-09-IVSimplify.ll41
-rw-r--r--test/Transforms/LoopUnroll/2011-08-09-PhiUpdate.ll62
-rw-r--r--test/Transforms/LoopUnroll/2011-10-01-NoopTrunc.ll36
-rw-r--r--test/Transforms/LoopUnroll/2012-04-09-unroll-indirectbr.ll40
-rw-r--r--test/Transforms/LoopUnroll/basic.ll24
-rw-r--r--test/Transforms/LoopUnroll/lit.local.cfg1
-rw-r--r--test/Transforms/LoopUnroll/partial-unroll-optsize.ll35
-rw-r--r--test/Transforms/LoopUnroll/pr10813.ll29
-rw-r--r--test/Transforms/LoopUnroll/pr11361.ll42
-rw-r--r--test/Transforms/LoopUnroll/runtime-loop.ll109
-rw-r--r--test/Transforms/LoopUnroll/runtime-loop1.ll30
-rw-r--r--test/Transforms/LoopUnroll/runtime-loop2.ll31
-rw-r--r--test/Transforms/LoopUnroll/runtime-loop3.ll44
-rw-r--r--test/Transforms/LoopUnroll/scevunroll.ll172
-rw-r--r--test/Transforms/LoopUnroll/shifted-tripcount.ll28
-rw-r--r--test/Transforms/LoopUnroll/unloop.ll470
-rw-r--r--test/Transforms/LoopUnswitch/2006-06-13-SingleEntryPHI.ll35
-rw-r--r--test/Transforms/LoopUnswitch/2006-06-27-DeadSwitchCase.ll25
-rw-r--r--test/Transforms/LoopUnswitch/2007-05-09-Unreachable.ll28
-rw-r--r--test/Transforms/LoopUnswitch/2007-05-09-tl.ll95
-rw-r--r--test/Transforms/LoopUnswitch/2007-07-12-ExitDomInfo.ll45
-rw-r--r--test/Transforms/LoopUnswitch/2007-07-13-DomInfo.ll27
-rw-r--r--test/Transforms/LoopUnswitch/2007-07-18-DomInfo.ll66
-rw-r--r--test/Transforms/LoopUnswitch/2007-08-01-Dom.ll30
-rw-r--r--test/Transforms/LoopUnswitch/2007-08-01-LCSSA.ll55
-rw-r--r--test/Transforms/LoopUnswitch/2007-10-04-DomFrontier.ll29
-rw-r--r--test/Transforms/LoopUnswitch/2008-06-02-DomInfo.ll26
-rw-r--r--test/Transforms/LoopUnswitch/2008-06-17-DomFrontier.ll22
-rw-r--r--test/Transforms/LoopUnswitch/2008-11-03-Invariant.ll36
-rw-r--r--test/Transforms/LoopUnswitch/2010-11-18-LCSSA.ll28
-rw-r--r--test/Transforms/LoopUnswitch/2011-06-02-CritSwitch.ll28
-rw-r--r--test/Transforms/LoopUnswitch/2011-09-26-EHCrash.ll67
-rw-r--r--test/Transforms/LoopUnswitch/2011-11-18-SimpleSwitch.ll91
-rw-r--r--test/Transforms/LoopUnswitch/2011-11-18-TwoSwitches-Threshold.ll84
-rw-r--r--test/Transforms/LoopUnswitch/2011-11-18-TwoSwitches.ll138
-rw-r--r--test/Transforms/LoopUnswitch/2012-04-02-IndirectBr.ll41
-rw-r--r--test/Transforms/LoopUnswitch/2012-04-30-LoopUnswitch-LPad-Crash.ll101
-rw-r--r--test/Transforms/LoopUnswitch/2012-05-20-Phi.ll25
-rw-r--r--test/Transforms/LoopUnswitch/basictest.ll31
-rw-r--r--test/Transforms/LoopUnswitch/crash.ll66
-rw-r--r--test/Transforms/LoopUnswitch/infinite-loop.ll53
-rw-r--r--test/Transforms/LoopUnswitch/lit.local.cfg1
-rw-r--r--test/Transforms/LoopUnswitch/preserve-analyses.ll129
-rw-r--r--test/Transforms/LowerAtomic/atomic-load.ll36
-rw-r--r--test/Transforms/LowerAtomic/atomic-swap.ll23
-rw-r--r--test/Transforms/LowerAtomic/barrier.ll8
-rw-r--r--test/Transforms/LowerAtomic/lit.local.cfg1
-rw-r--r--test/Transforms/LowerExpectIntrinsic/basic.ll251
-rw-r--r--test/Transforms/LowerExpectIntrinsic/lit.local.cfg1
-rw-r--r--test/Transforms/LowerInvoke/2003-12-10-Crash.ll22
-rw-r--r--test/Transforms/LowerInvoke/2004-02-29-PHICrash.ll15
-rw-r--r--test/Transforms/LowerInvoke/2005-08-03-InvokeWithPHI.ll17
-rw-r--r--test/Transforms/LowerInvoke/2005-08-03-InvokeWithPHIUse.ll15
-rw-r--r--test/Transforms/LowerInvoke/2008-02-14-CritEdgePhiCrash.ll14
-rw-r--r--test/Transforms/LowerInvoke/basictest.ll30
-rw-r--r--test/Transforms/LowerInvoke/lit.local.cfg1
-rw-r--r--test/Transforms/LowerSwitch/2003-05-01-PHIProblem.ll15
-rw-r--r--test/Transforms/LowerSwitch/2003-08-23-EmptySwitch.ll9
-rw-r--r--test/Transforms/LowerSwitch/2004-03-13-SwitchIsDefaultCrash.ll19
-rw-r--r--test/Transforms/LowerSwitch/feature.ll140
-rw-r--r--test/Transforms/LowerSwitch/lit.local.cfg1
-rw-r--r--test/Transforms/Mem2Reg/2002-03-28-UninitializedVal.ll11
-rw-r--r--test/Transforms/Mem2Reg/2002-05-01-ShouldNotPromoteThisAlloca.ll12
-rw-r--r--test/Transforms/Mem2Reg/2003-04-10-DFNotFound.ll10
-rw-r--r--test/Transforms/Mem2Reg/2003-04-18-DeadBlockProblem.ll16
-rw-r--r--test/Transforms/Mem2Reg/2003-04-24-MultipleIdenticalSuccessors.ll16
-rw-r--r--test/Transforms/Mem2Reg/2003-06-26-IterativePromote.ll16
-rw-r--r--test/Transforms/Mem2Reg/2003-10-05-DeadPHIInsertion.ll22
-rw-r--r--test/Transforms/Mem2Reg/2005-06-30-ReadBeforeWrite.ll47
-rw-r--r--test/Transforms/Mem2Reg/2005-11-28-Crash.ll62
-rw-r--r--test/Transforms/Mem2Reg/2007-08-27-VolatileLoadsStores.ll47
-rw-r--r--test/Transforms/Mem2Reg/ConvertDebugInfo.ll45
-rw-r--r--test/Transforms/Mem2Reg/ConvertDebugInfo2.ll52
-rw-r--r--test/Transforms/Mem2Reg/PromoteMemToRegister.ll18
-rw-r--r--test/Transforms/Mem2Reg/UndefValuesMerge.ll13
-rw-r--r--test/Transforms/Mem2Reg/atomic.ll12
-rw-r--r--test/Transforms/Mem2Reg/crash.ll44
-rw-r--r--test/Transforms/Mem2Reg/ignore-lifetime.ll26
-rw-r--r--test/Transforms/Mem2Reg/lit.local.cfg1
-rw-r--r--test/Transforms/MemCpyOpt/2008-02-24-MultipleUseofSRet.ll36
-rw-r--r--test/Transforms/MemCpyOpt/2008-03-13-ReturnSlotBitcast.ll22
-rw-r--r--test/Transforms/MemCpyOpt/2011-06-02-CallSlotOverwritten.ll36
-rw-r--r--test/Transforms/MemCpyOpt/align.ll19
-rw-r--r--test/Transforms/MemCpyOpt/atomic.ll41
-rw-r--r--test/Transforms/MemCpyOpt/crash.ll58
-rw-r--r--test/Transforms/MemCpyOpt/form-memset.ll274
-rw-r--r--test/Transforms/MemCpyOpt/lit.local.cfg1
-rw-r--r--test/Transforms/MemCpyOpt/loadstore-sret.ll25
-rw-r--r--test/Transforms/MemCpyOpt/memcpy-to-memset.ll19
-rw-r--r--test/Transforms/MemCpyOpt/memcpy.ll172
-rw-r--r--test/Transforms/MemCpyOpt/memmove.ll40
-rw-r--r--test/Transforms/MemCpyOpt/smaller.ll28
-rw-r--r--test/Transforms/MemCpyOpt/sret.ll30
-rw-r--r--test/Transforms/MergeFunc/2011-02-08-RemoveEqual.ll276
-rw-r--r--test/Transforms/MergeFunc/fold-weak.ll17
-rw-r--r--test/Transforms/MergeFunc/lit.local.cfg1
-rw-r--r--test/Transforms/MergeFunc/phi-speculation1.ll29
-rw-r--r--test/Transforms/MergeFunc/phi-speculation2.ll29
-rw-r--r--test/Transforms/MergeFunc/vector.ll76
-rw-r--r--test/Transforms/MergeFunc/vectors-and-arrays.ll18
-rw-r--r--test/Transforms/MetaRenamer/lit.local.cfg1
-rw-r--r--test/Transforms/MetaRenamer/metarenamer.ll96
-rw-r--r--test/Transforms/ObjCARC/apelim.ll53
-rw-r--r--test/Transforms/ObjCARC/basic.ll2226
-rw-r--r--test/Transforms/ObjCARC/cfg-hazards.ll397
-rw-r--r--test/Transforms/ObjCARC/contract-marker.ll23
-rw-r--r--test/Transforms/ObjCARC/contract-storestrong-ivar.ll31
-rw-r--r--test/Transforms/ObjCARC/contract-storestrong.ll169
-rw-r--r--test/Transforms/ObjCARC/contract-testcases.ll90
-rw-r--r--test/Transforms/ObjCARC/contract.ll163
-rw-r--r--test/Transforms/ObjCARC/empty-block.ll59
-rw-r--r--test/Transforms/ObjCARC/escape.ll131
-rw-r--r--test/Transforms/ObjCARC/expand.ll28
-rw-r--r--test/Transforms/ObjCARC/gvn.ll21
-rw-r--r--test/Transforms/ObjCARC/invoke.ll218
-rw-r--r--test/Transforms/ObjCARC/lit.local.cfg1
-rw-r--r--test/Transforms/ObjCARC/move-and-form-retain-autorelease.ll221
-rw-r--r--test/Transforms/ObjCARC/move-and-merge-autorelease.ll108
-rw-r--r--test/Transforms/ObjCARC/nested.ll822
-rw-r--r--test/Transforms/ObjCARC/no-objc-arc-exceptions.ll122
-rw-r--r--test/Transforms/ObjCARC/path-overflow.ll329
-rw-r--r--test/Transforms/ObjCARC/pointer-types.ll31
-rw-r--r--test/Transforms/ObjCARC/post-inlining.ll48
-rw-r--r--test/Transforms/ObjCARC/pr12270.ll21
-rw-r--r--test/Transforms/ObjCARC/retain-block-alloca.ll90
-rw-r--r--test/Transforms/ObjCARC/retain-block-load.ll51
-rw-r--r--test/Transforms/ObjCARC/retain-block-side-effects.ll39
-rw-r--r--test/Transforms/ObjCARC/retain-block.ll138
-rw-r--r--test/Transforms/ObjCARC/retain-not-declared.ll67
-rw-r--r--test/Transforms/ObjCARC/rle-s2l.ll135
-rw-r--r--test/Transforms/ObjCARC/rv.ll342
-rw-r--r--test/Transforms/ObjCARC/split-backedge.ll48
-rw-r--r--test/Transforms/ObjCARC/weak-contract.ll14
-rw-r--r--test/Transforms/ObjCARC/weak-copies.ll87
-rw-r--r--test/Transforms/ObjCARC/weak-dce.ll46
-rw-r--r--test/Transforms/ObjCARC/weak.ll57
-rw-r--r--test/Transforms/PhaseOrdering/2010-03-22-empty-baseclass.ll162
-rw-r--r--test/Transforms/PhaseOrdering/PR6627.ll93
-rw-r--r--test/Transforms/PhaseOrdering/basic.ll51
-rw-r--r--test/Transforms/PhaseOrdering/lit.local.cfg1
-rw-r--r--test/Transforms/PhaseOrdering/scev.ll64
-rw-r--r--test/Transforms/PruneEH/2003-11-21-PHIUpdate.ll15
-rw-r--r--test/Transforms/PruneEH/2008-06-02-Weak.ll12
-rw-r--r--test/Transforms/PruneEH/lit.local.cfg1
-rw-r--r--test/Transforms/PruneEH/recursivetest.ll20
-rw-r--r--test/Transforms/PruneEH/simplenoreturntest.ll13
-rw-r--r--test/Transforms/PruneEH/simpletest.ll19
-rw-r--r--test/Transforms/Reassociate/2002-05-15-AgressiveSubMove.ll9
-rw-r--r--test/Transforms/Reassociate/2002-05-15-MissedTree.ll9
-rw-r--r--test/Transforms/Reassociate/2002-05-15-SubReassociate.ll12
-rw-r--r--test/Transforms/Reassociate/2002-05-15-SubReassociate2.ll13
-rw-r--r--test/Transforms/Reassociate/2002-07-09-DominanceProblem.ll10
-rw-r--r--test/Transforms/Reassociate/2003-08-12-InfiniteLoop.ll9
-rw-r--r--test/Transforms/Reassociate/2005-09-01-ArrayOutOfBounds.ll23
-rw-r--r--test/Transforms/Reassociate/2006-04-27-ReassociateVector.ll8
-rw-r--r--test/Transforms/Reassociate/2011-01-26-UseAfterFree.ll33
-rw-r--r--test/Transforms/Reassociate/2012-05-08-UndefLeak.ll85
-rw-r--r--test/Transforms/Reassociate/2012-06-08-InfiniteLoop.ll21
-rw-r--r--test/Transforms/Reassociate/absorption.ll11
-rw-r--r--test/Transforms/Reassociate/basictest.ll216
-rw-r--r--test/Transforms/Reassociate/crash.ll146
-rw-r--r--test/Transforms/Reassociate/fp-commute.ll18
-rw-r--r--test/Transforms/Reassociate/inverses.ll34
-rw-r--r--test/Transforms/Reassociate/lit.local.cfg1
-rw-r--r--test/Transforms/Reassociate/looptest.ll50
-rw-r--r--test/Transforms/Reassociate/mightymul.ll35
-rw-r--r--test/Transforms/Reassociate/mulfactor.ll134
-rw-r--r--test/Transforms/Reassociate/multistep.ll31
-rw-r--r--test/Transforms/Reassociate/negation.ll21
-rw-r--r--test/Transforms/Reassociate/no-op.ll38
-rw-r--r--test/Transforms/Reassociate/optional-flags.ll29
-rw-r--r--test/Transforms/Reassociate/otherops.ll28
-rw-r--r--test/Transforms/Reassociate/pr12245.ll50
-rw-r--r--test/Transforms/Reassociate/repeats.ll252
-rw-r--r--test/Transforms/Reassociate/secondary.ll24
-rw-r--r--test/Transforms/Reassociate/shift-factor.ll12
-rw-r--r--test/Transforms/Reassociate/shifttest.ll12
-rw-r--r--test/Transforms/Reassociate/subtest.ll11
-rw-r--r--test/Transforms/Reassociate/subtest2.ll13
-rw-r--r--test/Transforms/SCCP/2002-05-02-MissSecondInst.ll8
-rw-r--r--test/Transforms/SCCP/2002-05-20-MissedIncomingValue.ll19
-rw-r--r--test/Transforms/SCCP/2002-05-21-InvalidSimplify.ll33
-rw-r--r--test/Transforms/SCCP/2002-08-30-GetElementPtrTest.ll9
-rw-r--r--test/Transforms/SCCP/2003-06-24-OverdefinedPHIValue.ll30
-rw-r--r--test/Transforms/SCCP/2003-08-26-InvokeHandling.ll23
-rw-r--r--test/Transforms/SCCP/2004-11-16-DeadInvoke.ll18
-rw-r--r--test/Transforms/SCCP/2004-12-10-UndefBranchBug.ll12
-rw-r--r--test/Transforms/SCCP/2006-10-23-IPSCCP-Crash.ll103
-rw-r--r--test/Transforms/SCCP/2006-12-04-PackedType.ll140
-rw-r--r--test/Transforms/SCCP/2006-12-19-UndefBug.ll8
-rw-r--r--test/Transforms/SCCP/2007-05-16-InvokeCrash.ll45
-rw-r--r--test/Transforms/SCCP/2008-01-27-UndefCorrelate.ll36
-rw-r--r--test/Transforms/SCCP/2008-04-22-multiple-ret-sccp.ll11
-rw-r--r--test/Transforms/SCCP/2008-05-23-UndefCallFold.ll14
-rw-r--r--test/Transforms/SCCP/2009-01-14-IPSCCP-Invoke.ll26
-rw-r--r--test/Transforms/SCCP/2009-05-27-VectorOperandZero.ll10
-rw-r--r--test/Transforms/SCCP/apint-array.ll23
-rw-r--r--test/Transforms/SCCP/apint-basictest.ll16
-rw-r--r--test/Transforms/SCCP/apint-basictest2.ll17
-rw-r--r--test/Transforms/SCCP/apint-basictest3.ll23
-rw-r--r--test/Transforms/SCCP/apint-basictest4.ll25
-rw-r--r--test/Transforms/SCCP/apint-bigarray.ll23
-rw-r--r--test/Transforms/SCCP/apint-bigint.ll9
-rw-r--r--test/Transforms/SCCP/apint-bigint2.ll18
-rw-r--r--test/Transforms/SCCP/apint-ipsccp1.ll24
-rw-r--r--test/Transforms/SCCP/apint-ipsccp2.ll19
-rw-r--r--test/Transforms/SCCP/apint-ipsccp3.ll23
-rw-r--r--test/Transforms/SCCP/apint-ipsccp4.ll49
-rw-r--r--test/Transforms/SCCP/apint-load.ll36
-rw-r--r--test/Transforms/SCCP/apint-phi.ll19
-rw-r--r--test/Transforms/SCCP/apint-select.ll21
-rw-r--r--test/Transforms/SCCP/atomic-load-store.ll30
-rw-r--r--test/Transforms/SCCP/calltest.ll21
-rw-r--r--test/Transforms/SCCP/crash.ll29
-rw-r--r--test/Transforms/SCCP/ipsccp-addr-taken.ll28
-rw-r--r--test/Transforms/SCCP/ipsccp-basic.ll229
-rw-r--r--test/Transforms/SCCP/lit.local.cfg1
-rw-r--r--test/Transforms/SCCP/loadtest.ll33
-rw-r--r--test/Transforms/SCCP/logical-nuke.ll9
-rw-r--r--test/Transforms/SCCP/retvalue-undef.ll32
-rw-r--r--test/Transforms/SCCP/sccptest.ll58
-rw-r--r--test/Transforms/SCCP/select.ll12
-rw-r--r--test/Transforms/SCCP/switch.ll13
-rw-r--r--test/Transforms/SCCP/undef-resolve.ll172
-rw-r--r--test/Transforms/SCCP/vector-bitcast.ll20
-rw-r--r--test/Transforms/SROA/basictest.ll756
-rw-r--r--test/Transforms/SROA/fca.ll49
-rw-r--r--test/Transforms/SROA/lit.local.cfg1
-rw-r--r--test/Transforms/SROA/phi-and-select.ll325
-rw-r--r--test/Transforms/SROA/vector-promotion.ll191
-rw-r--r--test/Transforms/ScalarRepl/2003-05-29-ArrayFail.ll13
-rw-r--r--test/Transforms/ScalarRepl/2003-09-12-IncorrectPromote.ll13
-rw-r--r--test/Transforms/ScalarRepl/2003-10-29-ArrayProblem.ll16
-rw-r--r--test/Transforms/ScalarRepl/2006-11-07-InvalidArrayPromote.ll20
-rw-r--r--test/Transforms/ScalarRepl/2007-05-29-MemcpyPreserve.ll24
-rw-r--r--test/Transforms/ScalarRepl/2007-11-03-bigendian_apint.ll30
-rw-r--r--test/Transforms/ScalarRepl/2008-01-29-PromoteBug.ll21
-rw-r--r--test/Transforms/ScalarRepl/2008-02-28-SubElementExtractCrash.ll16
-rw-r--r--test/Transforms/ScalarRepl/2008-06-05-loadstore-agg.ll33
-rw-r--r--test/Transforms/ScalarRepl/2008-06-22-LargeArray.ll17
-rw-r--r--test/Transforms/ScalarRepl/2008-08-22-out-of-range-array-promote.ll23
-rw-r--r--test/Transforms/ScalarRepl/2008-09-22-vector-gep.ll25
-rw-r--r--test/Transforms/ScalarRepl/2009-02-02-ScalarPromoteOutOfRange.ll16
-rw-r--r--test/Transforms/ScalarRepl/2009-02-05-LoadFCA.ll20
-rw-r--r--test/Transforms/ScalarRepl/2009-03-04-MemCpyAlign.ll19
-rw-r--r--test/Transforms/ScalarRepl/2009-12-11-NeonTypes.ll90
-rw-r--r--test/Transforms/ScalarRepl/2010-01-18-SelfCopy.ll18
-rw-r--r--test/Transforms/ScalarRepl/2011-05-06-CapturedAlloca.ll26
-rw-r--r--test/Transforms/ScalarRepl/2011-06-08-VectorExtractValue.ll75
-rw-r--r--test/Transforms/ScalarRepl/2011-06-17-VectorPartialMemset.ll37
-rw-r--r--test/Transforms/ScalarRepl/2011-09-22-PHISpeculateInvoke.ll40
-rw-r--r--test/Transforms/ScalarRepl/2011-10-11-VectorMemset.ll22
-rw-r--r--test/Transforms/ScalarRepl/2011-10-22-VectorCrash.ll19
-rw-r--r--test/Transforms/ScalarRepl/2011-11-11-EmptyStruct.ll26
-rw-r--r--test/Transforms/ScalarRepl/AggregatePromote.ll51
-rw-r--r--test/Transforms/ScalarRepl/DifferingTypes.ll16
-rw-r--r--test/Transforms/ScalarRepl/address-space.ll35
-rw-r--r--test/Transforms/ScalarRepl/arraytest.ll11
-rw-r--r--test/Transforms/ScalarRepl/badarray.ll57
-rw-r--r--test/Transforms/ScalarRepl/basictest.ll30
-rw-r--r--test/Transforms/ScalarRepl/bitfield-sroa.ll17
-rw-r--r--test/Transforms/ScalarRepl/copy-aggregate.ll107
-rw-r--r--test/Transforms/ScalarRepl/crash.ll286
-rw-r--r--test/Transforms/ScalarRepl/debuginfo-preserved.ll61
-rw-r--r--test/Transforms/ScalarRepl/dynamic-vector-gep.ll167
-rw-r--r--test/Transforms/ScalarRepl/inline-vector.ll53
-rw-r--r--test/Transforms/ScalarRepl/lifetime.ll139
-rw-r--r--test/Transforms/ScalarRepl/lit.local.cfg1
-rw-r--r--test/Transforms/ScalarRepl/load-store-aggregate.ll31
-rw-r--r--test/Transforms/ScalarRepl/memcpy-align.ll32
-rw-r--r--test/Transforms/ScalarRepl/memset-aggregate-byte-leader.ll23
-rw-r--r--test/Transforms/ScalarRepl/memset-aggregate.ll67
-rw-r--r--test/Transforms/ScalarRepl/negative-memset.ll20
-rw-r--r--test/Transforms/ScalarRepl/nonzero-first-index.ll53
-rw-r--r--test/Transforms/ScalarRepl/not-a-vector.ll20
-rw-r--r--test/Transforms/ScalarRepl/only-memcpy-uses.ll27
-rw-r--r--test/Transforms/ScalarRepl/phi-cycle.ll77
-rw-r--r--test/Transforms/ScalarRepl/phi-select.ll153
-rw-r--r--test/Transforms/ScalarRepl/phinodepromote.ll34
-rw-r--r--test/Transforms/ScalarRepl/select_promote.ll18
-rw-r--r--test/Transforms/ScalarRepl/sroa-fca.ll21
-rw-r--r--test/Transforms/ScalarRepl/sroa_two.ll13
-rw-r--r--test/Transforms/ScalarRepl/union-fp-int.ll14
-rw-r--r--test/Transforms/ScalarRepl/union-packed.ll14
-rw-r--r--test/Transforms/ScalarRepl/union-pointer.ll41
-rw-r--r--test/Transforms/ScalarRepl/vector_memcpy.ll30
-rw-r--r--test/Transforms/ScalarRepl/vector_promote.ll113
-rw-r--r--test/Transforms/ScalarRepl/vectors-with-mismatched-elements.ll27
-rw-r--r--test/Transforms/ScalarRepl/volatile.ll12
-rw-r--r--test/Transforms/SimplifyCFG/2002-05-05-EmptyBlockMerge.ll22
-rw-r--r--test/Transforms/SimplifyCFG/2002-05-21-PHIElimination.ll19
-rw-r--r--test/Transforms/SimplifyCFG/2002-06-24-PHINode.ll14
-rw-r--r--test/Transforms/SimplifyCFG/2002-09-24-PHIAssertion.ll13
-rw-r--r--test/Transforms/SimplifyCFG/2003-03-07-DominateProblem.ll17
-rw-r--r--test/Transforms/SimplifyCFG/2003-08-05-InvokeCrash.ll16
-rw-r--r--test/Transforms/SimplifyCFG/2003-08-17-BranchFold.ll22
-rw-r--r--test/Transforms/SimplifyCFG/2003-08-17-BranchFoldOrdering.ll26
-rw-r--r--test/Transforms/SimplifyCFG/2003-08-17-FoldSwitch-dbg.ll58
-rw-r--r--test/Transforms/SimplifyCFG/2003-08-17-FoldSwitch.ll80
-rw-r--r--test/Transforms/SimplifyCFG/2004-12-10-SimplifyCFGCrash.ll40
-rw-r--r--test/Transforms/SimplifyCFG/2005-06-16-PHICrash.ll95
-rw-r--r--test/Transforms/SimplifyCFG/2005-08-01-PHIUpdateFail.ll71
-rw-r--r--test/Transforms/SimplifyCFG/2005-10-02-InvokeSimplify.ll18
-rw-r--r--test/Transforms/SimplifyCFG/2005-12-03-IncorrectPHIFold.ll124
-rw-r--r--test/Transforms/SimplifyCFG/2006-02-17-InfiniteUnroll.ll27
-rw-r--r--test/Transforms/SimplifyCFG/2006-06-12-InfLoop.ll413
-rw-r--r--test/Transforms/SimplifyCFG/2006-08-03-Crash.ll96
-rw-r--r--test/Transforms/SimplifyCFG/2006-10-19-UncondDiv.ll28
-rw-r--r--test/Transforms/SimplifyCFG/2006-12-08-Ptr-ICmp-Branch.ll131
-rw-r--r--test/Transforms/SimplifyCFG/2007-11-22-InvokeNoUnwind.ll14
-rw-r--r--test/Transforms/SimplifyCFG/2007-12-21-Crash.ll37
-rw-r--r--test/Transforms/SimplifyCFG/2008-01-02-hoist-fp-add.ll26
-rw-r--r--test/Transforms/SimplifyCFG/2008-05-16-PHIBlockMerge.ll131
-rw-r--r--test/Transforms/SimplifyCFG/2008-07-13-InfLoopMiscompile.ll36
-rw-r--r--test/Transforms/SimplifyCFG/2008-09-08-MultiplePred.ll60
-rw-r--r--test/Transforms/SimplifyCFG/2008-09-17-SpeculativeHoist.ll18
-rw-r--r--test/Transforms/SimplifyCFG/2008-10-03-SpeculativelyExecuteBeforePHI.ll36
-rw-r--r--test/Transforms/SimplifyCFG/2008-12-06-SingleEntryPhi.ll13
-rw-r--r--test/Transforms/SimplifyCFG/2008-12-16-DCECond.ll46
-rw-r--r--test/Transforms/SimplifyCFG/2009-01-18-PHIPropCrash.ll30
-rw-r--r--test/Transforms/SimplifyCFG/2009-01-19-UnconditionalTrappingConstantExpr.ll41
-rw-r--r--test/Transforms/SimplifyCFG/2009-05-12-externweak.ll47
-rw-r--r--test/Transforms/SimplifyCFG/2010-03-30-InvokeCrash.ll22
-rw-r--r--test/Transforms/SimplifyCFG/2011-03-08-UnreachableUse.ll31
-rw-r--r--test/Transforms/SimplifyCFG/2011-09-05-TrivialLPad.ll22
-rw-r--r--test/Transforms/SimplifyCFG/BrUnwind.ll15
-rw-r--r--test/Transforms/SimplifyCFG/DeadSetCC.ll28
-rw-r--r--test/Transforms/SimplifyCFG/EqualPHIEdgeBlockMerge.ll18
-rw-r--r--test/Transforms/SimplifyCFG/ForwardSwitchConditionToPHI.ll36
-rw-r--r--test/Transforms/SimplifyCFG/HoistCode.ll11
-rw-r--r--test/Transforms/SimplifyCFG/MagicPointer.ll75
-rw-r--r--test/Transforms/SimplifyCFG/PR9946.ll18
-rw-r--r--test/Transforms/SimplifyCFG/PhiBlockMerge.ll26
-rw-r--r--test/Transforms/SimplifyCFG/PhiBlockMerge2.ll27
-rw-r--r--test/Transforms/SimplifyCFG/PhiEliminate.ll27
-rw-r--r--test/Transforms/SimplifyCFG/PhiEliminate2.ll17
-rw-r--r--test/Transforms/SimplifyCFG/PhiEliminate3.ll34
-rw-r--r--test/Transforms/SimplifyCFG/PhiNoEliminate.ll27
-rw-r--r--test/Transforms/SimplifyCFG/SpeculativeExec.ll46
-rw-r--r--test/Transforms/SimplifyCFG/UncondBranchToReturn.ll33
-rw-r--r--test/Transforms/SimplifyCFG/UnreachableEliminate.ll73
-rw-r--r--test/Transforms/SimplifyCFG/basictest.ll43
-rw-r--r--test/Transforms/SimplifyCFG/branch-cond-merge.ll19
-rw-r--r--test/Transforms/SimplifyCFG/branch-cond-prop.ll17
-rw-r--r--test/Transforms/SimplifyCFG/branch-fold-dbg.ll58
-rw-r--r--test/Transforms/SimplifyCFG/branch-fold-test.ll17
-rw-r--r--test/Transforms/SimplifyCFG/branch-fold.ll70
-rw-r--r--test/Transforms/SimplifyCFG/branch-phi-thread.ll66
-rw-r--r--test/Transforms/SimplifyCFG/dbginfo.ll71
-rw-r--r--test/Transforms/SimplifyCFG/dce-cond-after-folding-terminator.ll52
-rw-r--r--test/Transforms/SimplifyCFG/duplicate-phis.ll21
-rw-r--r--test/Transforms/SimplifyCFG/hoist-common-code.ll18
-rw-r--r--test/Transforms/SimplifyCFG/hoist-dbgvalue.ll53
-rw-r--r--test/Transforms/SimplifyCFG/indirectbr.ll251
-rw-r--r--test/Transforms/SimplifyCFG/invoke.ll139
-rw-r--r--test/Transforms/SimplifyCFG/invoke_unwind.ll20
-rw-r--r--test/Transforms/SimplifyCFG/iterative-simplify.ll100
-rw-r--r--test/Transforms/SimplifyCFG/lifetime.ll29
-rw-r--r--test/Transforms/SimplifyCFG/lit.local.cfg1
-rw-r--r--test/Transforms/SimplifyCFG/multiple-phis.ll39
-rw-r--r--test/Transforms/SimplifyCFG/noreturn-call.ll11
-rw-r--r--test/Transforms/SimplifyCFG/phi-undef-loadstore.ll87
-rw-r--r--test/Transforms/SimplifyCFG/preserve-branchweights-partial.ll37
-rw-r--r--test/Transforms/SimplifyCFG/preserve-branchweights-switch-create.ll140
-rw-r--r--test/Transforms/SimplifyCFG/preserve-branchweights.ll316
-rw-r--r--test/Transforms/SimplifyCFG/return-merge.ll19
-rw-r--r--test/Transforms/SimplifyCFG/select-gep.ll40
-rw-r--r--test/Transforms/SimplifyCFG/speculate-with-offset.ll94
-rw-r--r--test/Transforms/SimplifyCFG/switch-masked-bits.ll38
-rw-r--r--test/Transforms/SimplifyCFG/switch-on-const-select.ll138
-rw-r--r--test/Transforms/SimplifyCFG/switch-simplify-crash.ll108
-rw-r--r--test/Transforms/SimplifyCFG/switch-to-icmp.ll39
-rw-r--r--test/Transforms/SimplifyCFG/switch_create.ll482
-rw-r--r--test/Transforms/SimplifyCFG/switch_switch_fold.ll47
-rw-r--r--test/Transforms/SimplifyCFG/switch_thread.ll79
-rw-r--r--test/Transforms/SimplifyCFG/switch_to_lookup_table.ll140
-rw-r--r--test/Transforms/SimplifyCFG/trap-debugloc.ll19
-rw-r--r--test/Transforms/SimplifyCFG/trapping-load-unreachable.ll87
-rw-r--r--test/Transforms/SimplifyCFG/two-entry-phi-return.ll15
-rw-r--r--test/Transforms/SimplifyCFG/unreachable-blocks.ll28
-rw-r--r--test/Transforms/SimplifyLibCalls/2005-05-20-sprintf-crash.ll11
-rw-r--r--test/Transforms/SimplifyLibCalls/2007-04-06-strchr-miscompile.ll29
-rw-r--r--test/Transforms/SimplifyLibCalls/2008-05-19-memcmp.ll14
-rw-r--r--test/Transforms/SimplifyLibCalls/2009-01-04-Annotate.ll12
-rw-r--r--test/Transforms/SimplifyLibCalls/2009-02-11-NotInitialized.ll13
-rw-r--r--test/Transforms/SimplifyLibCalls/2009-02-12-StrTo.ll14
-rw-r--r--test/Transforms/SimplifyLibCalls/2009-05-30-memcmp-byte.ll14
-rw-r--r--test/Transforms/SimplifyLibCalls/2009-07-28-Exit.ll22
-rw-r--r--test/Transforms/SimplifyLibCalls/2009-07-29-Exit2.ll24
-rw-r--r--test/Transforms/SimplifyLibCalls/2010-05-30-memcpy-Struct.ll20
-rw-r--r--test/Transforms/SimplifyLibCalls/FFS.ll36
-rw-r--r--test/Transforms/SimplifyLibCalls/FPrintF.ll28
-rw-r--r--test/Transforms/SimplifyLibCalls/FPuts.ll29
-rw-r--r--test/Transforms/SimplifyLibCalls/IsDigit.ll21
-rw-r--r--test/Transforms/SimplifyLibCalls/MemCpy.ll19
-rw-r--r--test/Transforms/SimplifyLibCalls/PR7357.ll16
-rw-r--r--test/Transforms/SimplifyLibCalls/Printf.ll37
-rw-r--r--test/Transforms/SimplifyLibCalls/Puts.ll15
-rw-r--r--test/Transforms/SimplifyLibCalls/SPrintF.ll40
-rw-r--r--test/Transforms/SimplifyLibCalls/StpCpy.ll43
-rw-r--r--test/Transforms/SimplifyLibCalls/StrCat.ll33
-rw-r--r--test/Transforms/SimplifyLibCalls/StrChr.ll26
-rw-r--r--test/Transforms/SimplifyLibCalls/StrCmp.ll65
-rw-r--r--test/Transforms/SimplifyLibCalls/StrCpy.ll37
-rw-r--r--test/Transforms/SimplifyLibCalls/StrLen.ll62
-rw-r--r--test/Transforms/SimplifyLibCalls/StrNCat.ll31
-rw-r--r--test/Transforms/SimplifyLibCalls/StrNCmp.ll78
-rw-r--r--test/Transforms/SimplifyLibCalls/StrNCpy.ll29
-rw-r--r--test/Transforms/SimplifyLibCalls/StrPBrk.ll25
-rw-r--r--test/Transforms/SimplifyLibCalls/StrRChr.ll23
-rw-r--r--test/Transforms/SimplifyLibCalls/StrSpn.ll41
-rw-r--r--test/Transforms/SimplifyLibCalls/StrStr.ll60
-rw-r--r--test/Transforms/SimplifyLibCalls/ToAscii.ll21
-rw-r--r--test/Transforms/SimplifyLibCalls/abs.ll11
-rw-r--r--test/Transforms/SimplifyLibCalls/cos.ll14
-rw-r--r--test/Transforms/SimplifyLibCalls/debug-line.ll24
-rw-r--r--test/Transforms/SimplifyLibCalls/double-float-shrink.ll333
-rw-r--r--test/Transforms/SimplifyLibCalls/exp2.ll38
-rw-r--r--test/Transforms/SimplifyLibCalls/float-shrink-compare.ll179
-rw-r--r--test/Transforms/SimplifyLibCalls/floor.ll85
-rw-r--r--test/Transforms/SimplifyLibCalls/fwrite.ll13
-rw-r--r--test/Transforms/SimplifyLibCalls/iprintf.ll71
-rw-r--r--test/Transforms/SimplifyLibCalls/lit.local.cfg1
-rw-r--r--test/Transforms/SimplifyLibCalls/memcmp.ll35
-rw-r--r--test/Transforms/SimplifyLibCalls/memmove.ll12
-rw-r--r--test/Transforms/SimplifyLibCalls/memset-64.ll12
-rw-r--r--test/Transforms/SimplifyLibCalls/memset.ll12
-rw-r--r--test/Transforms/SimplifyLibCalls/osx-names.ll30
-rw-r--r--test/Transforms/SimplifyLibCalls/pow-to-sqrt.ll33
-rw-r--r--test/Transforms/SimplifyLibCalls/pow2.ll37
-rw-r--r--test/Transforms/SimplifyLibCalls/weak-symbols.ll26
-rw-r--r--test/Transforms/SimplifyLibCalls/win-math.ll275
-rw-r--r--test/Transforms/Sink/basic.ll64
-rw-r--r--test/Transforms/Sink/lit.local.cfg1
-rw-r--r--test/Transforms/StripSymbols/2007-01-15-llvm.used.ll15
-rw-r--r--test/Transforms/StripSymbols/2010-06-30-StripDebug.ll28
-rw-r--r--test/Transforms/StripSymbols/2010-07-01-DeadDbgInfo.ll47
-rw-r--r--test/Transforms/StripSymbols/2010-08-25-crash.ll19
-rw-r--r--test/Transforms/StripSymbols/block-address.ll23
-rw-r--r--test/Transforms/StripSymbols/lit.local.cfg1
-rw-r--r--test/Transforms/TailCallElim/2010-06-26-MultipleReturnValues.ll20
-rw-r--r--test/Transforms/TailCallElim/accum_recursion.ll74
-rw-r--r--test/Transforms/TailCallElim/ackermann.ll25
-rw-r--r--test/Transforms/TailCallElim/dont-tce-tail-marked-call.ll13
-rw-r--r--test/Transforms/TailCallElim/dont_reorder_load.ll64
-rw-r--r--test/Transforms/TailCallElim/dup_tail.ll23
-rw-r--r--test/Transforms/TailCallElim/inf-recursion.ll33
-rw-r--r--test/Transforms/TailCallElim/intervening-inst.ll17
-rw-r--r--test/Transforms/TailCallElim/lit.local.cfg1
-rw-r--r--test/Transforms/TailCallElim/move_alloca_for_tail_call.ll15
-rw-r--r--test/Transforms/TailCallElim/nocapture.ll25
-rw-r--r--test/Transforms/TailCallElim/reorder_load.ll101
-rw-r--r--test/Transforms/TailCallElim/return_constant.ll17
-rw-r--r--test/Transforms/TailCallElim/setjmp.ll29
-rw-r--r--test/Transforms/TailCallElim/trivial_codegen_tailcall.ll11
-rw-r--r--test/Transforms/TailDup/2008-06-11-AvoidDupLoopHeader.ll27
-rw-r--r--test/Transforms/TailDup/X86/lit.local.cfg6
-rw-r--r--test/Transforms/TailDup/lit.local.cfg5
-rw-r--r--test/Unit/lit.cfg83
-rw-r--r--test/Unit/lit.site.cfg.in21
-rw-r--r--test/Verifier/2002-04-13-RetTypes.ll9
-rw-r--r--test/Verifier/2002-11-05-GetelementptrPointers.ll9
-rw-r--r--test/Verifier/2004-05-21-SwitchConstantMismatch.ll13
-rw-r--r--test/Verifier/2006-07-11-StoreStruct.ll11
-rw-r--r--test/Verifier/2006-10-15-AddrLabel.ll9
-rw-r--r--test/Verifier/2006-12-12-IntrinsicDefine.ll7
-rw-r--r--test/Verifier/2007-12-21-InvokeParamAttrs.ll10
-rw-r--r--test/Verifier/2008-01-11-VarargAttrs.ll10
-rw-r--r--test/Verifier/2008-03-01-AllocaSized.ll8
-rw-r--r--test/Verifier/2008-08-22-MemCpyAlignment.ll11
-rw-r--r--test/Verifier/2008-11-15-RetVoid.ll5
-rw-r--r--test/Verifier/2009-05-29-InvokeResult1.ll15
-rw-r--r--test/Verifier/2009-05-29-InvokeResult2.ll16
-rw-r--r--test/Verifier/2009-05-29-InvokeResult3.ll19
-rw-r--r--test/Verifier/2010-08-07-PointerIntrinsic.ll21
-rw-r--r--test/Verifier/AmbiguousPhi.ll10
-rw-r--r--test/Verifier/PhiGrouping.ll17
-rw-r--r--test/Verifier/README.txt3
-rw-r--r--test/Verifier/SelfReferential.ll9
-rw-r--r--test/Verifier/aliasing-chain.ll6
-rw-r--r--test/Verifier/byval-1.ll2
-rw-r--r--test/Verifier/byval-4.ll4
-rw-r--r--test/Verifier/cttz-undef-arg.ll16
-rw-r--r--test/Verifier/dominates.ll57
-rw-r--r--test/Verifier/fpmath.ll31
-rw-r--r--test/Verifier/gcread-ptrptr.ll13
-rw-r--r--test/Verifier/gcroot-alloca.ll14
-rw-r--r--test/Verifier/gcroot-meta.ll16
-rw-r--r--test/Verifier/gcroot-ptrptr.ll14
-rw-r--r--test/Verifier/gcwrite-ptrptr.ll13
-rw-r--r--test/Verifier/invoke.ll79
-rw-r--r--test/Verifier/lit.local.cfg1
-rw-r--r--test/Verifier/range-1.ll142
-rw-r--r--test/Verifier/range-2.ll36
-rw-r--r--test/YAMLParser/LICENSE.txt19
-rw-r--r--test/YAMLParser/bool.data6
-rw-r--r--test/YAMLParser/construct-bool.data11
-rw-r--r--test/YAMLParser/construct-custom.data28
-rw-r--r--test/YAMLParser/construct-float.data8
-rw-r--r--test/YAMLParser/construct-int.data8
-rw-r--r--test/YAMLParser/construct-map.data8
-rw-r--r--test/YAMLParser/construct-merge.data29
-rw-r--r--test/YAMLParser/construct-null.data20
-rw-r--r--test/YAMLParser/construct-omap.data10
-rw-r--r--test/YAMLParser/construct-pairs.data9
-rw-r--r--test/YAMLParser/construct-seq.data17
-rw-r--r--test/YAMLParser/construct-set.data9
-rw-r--r--test/YAMLParser/construct-str-ascii.data3
-rw-r--r--test/YAMLParser/construct-str.data3
-rw-r--r--test/YAMLParser/construct-timestamp.data7
-rw-r--r--test/YAMLParser/construct-value.data12
-rw-r--r--test/YAMLParser/duplicate-key.former-loader-error.data5
-rw-r--r--test/YAMLParser/duplicate-mapping-key.former-loader-error.data8
-rw-r--r--test/YAMLParser/duplicate-merge-key.former-loader-error.data6
-rw-r--r--test/YAMLParser/duplicate-value-key.former-loader-error.data6
-rw-r--r--test/YAMLParser/emit-block-scalar-in-simple-key-context-bug.data6
-rw-r--r--test/YAMLParser/empty-document-bug.data2
-rw-r--r--test/YAMLParser/float.data8
-rw-r--r--test/YAMLParser/int.data8
-rw-r--r--test/YAMLParser/invalid-single-quote-bug.data4
-rw-r--r--test/YAMLParser/merge.data3
-rw-r--r--test/YAMLParser/more-floats.data3
-rw-r--r--test/YAMLParser/negative-float-bug.data3
-rw-r--r--test/YAMLParser/null.data5
-rw-r--r--test/YAMLParser/resolver.data32
-rw-r--r--test/YAMLParser/run-parser-crash-bug.data10
-rw-r--r--test/YAMLParser/scan-document-end-bug.data5
-rw-r--r--test/YAMLParser/scan-line-break-bug.data5
-rw-r--r--test/YAMLParser/single-dot-is-not-float-bug.data3
-rw-r--r--test/YAMLParser/sloppy-indentation.data19
-rw-r--r--test/YAMLParser/spec-02-01.data5
-rw-r--r--test/YAMLParser/spec-02-02.data5
-rw-r--r--test/YAMLParser/spec-02-03.data10
-rw-r--r--test/YAMLParser/spec-02-04.data10
-rw-r--r--test/YAMLParser/spec-02-05.data5
-rw-r--r--test/YAMLParser/spec-02-06.data7
-rw-r--r--test/YAMLParser/spec-02-07.data12
-rw-r--r--test/YAMLParser/spec-02-08.data12
-rw-r--r--test/YAMLParser/spec-02-09.data10
-rw-r--r--test/YAMLParser/spec-02-10.data10
-rw-r--r--test/YAMLParser/spec-02-11.data11
-rw-r--r--test/YAMLParser/spec-02-12.data10
-rw-r--r--test/YAMLParser/spec-02-13.data6
-rw-r--r--test/YAMLParser/spec-02-14.data6
-rw-r--r--test/YAMLParser/spec-02-15.data10
-rw-r--r--test/YAMLParser/spec-02-16.data9
-rw-r--r--test/YAMLParser/spec-02-17.data16
-rw-r--r--test/YAMLParser/spec-02-18.data8
-rw-r--r--test/YAMLParser/spec-02-19.data7
-rw-r--r--test/YAMLParser/spec-02-20.data8
-rw-r--r--test/YAMLParser/spec-02-21.data6
-rw-r--r--test/YAMLParser/spec-02-22.data6
-rw-r--r--test/YAMLParser/spec-02-23.data15
-rw-r--r--test/YAMLParser/spec-02-24.data16
-rw-r--r--test/YAMLParser/spec-02-25.data9
-rw-r--r--test/YAMLParser/spec-02-26.data9
-rw-r--r--test/YAMLParser/spec-02-27.data31
-rw-r--r--test/YAMLParser/spec-02-28.data28
-rw-r--r--test/YAMLParser/spec-05-01-utf8.data3
-rw-r--r--test/YAMLParser/spec-05-02-utf8.data7
-rw-r--r--test/YAMLParser/spec-05-03.data9
-rw-r--r--test/YAMLParser/spec-05-04.data4
-rw-r--r--test/YAMLParser/spec-05-05.data3
-rw-r--r--test/YAMLParser/spec-05-06.data4
-rw-r--r--test/YAMLParser/spec-05-07.data6
-rw-r--r--test/YAMLParser/spec-05-08.data4
-rw-r--r--test/YAMLParser/spec-05-09.data4
-rw-r--r--test/YAMLParser/spec-05-10.data6
-rw-r--r--test/YAMLParser/spec-05-11.data5
-rw-r--r--test/YAMLParser/spec-05-12.data16
-rw-r--r--test/YAMLParser/spec-05-13.data5
-rw-r--r--test/YAMLParser/spec-05-14.data9
-rw-r--r--test/YAMLParser/spec-05-15.data7
-rw-r--r--test/YAMLParser/spec-06-01.data16
-rw-r--r--test/YAMLParser/spec-06-02.data5
-rw-r--r--test/YAMLParser/spec-06-03.data4
-rw-r--r--test/YAMLParser/spec-06-04.data6
-rw-r--r--test/YAMLParser/spec-06-05.data8
-rw-r--r--test/YAMLParser/spec-06-06.data9
-rw-r--r--test/YAMLParser/spec-06-07.data10
-rw-r--r--test/YAMLParser/spec-06-08.data4
-rw-r--r--test/YAMLParser/spec-07-01.data5
-rw-r--r--test/YAMLParser/spec-07-02.data6
-rw-r--r--test/YAMLParser/spec-07-03.data7
-rw-r--r--test/YAMLParser/spec-07-04.data5
-rw-r--r--test/YAMLParser/spec-07-05.data10
-rw-r--r--test/YAMLParser/spec-07-06.data7
-rw-r--r--test/YAMLParser/spec-07-07a.data4
-rw-r--r--test/YAMLParser/spec-07-07b.data6
-rw-r--r--test/YAMLParser/spec-07-08.data11
-rw-r--r--test/YAMLParser/spec-07-09.data13
-rw-r--r--test/YAMLParser/spec-07-10.data13
-rw-r--r--test/YAMLParser/spec-07-11.data4
-rw-r--r--test/YAMLParser/spec-07-12a.data5
-rw-r--r--test/YAMLParser/spec-07-12b.data6
-rw-r--r--test/YAMLParser/spec-07-13.data11
-rw-r--r--test/YAMLParser/spec-08-01.data4
-rw-r--r--test/YAMLParser/spec-08-02.data4
-rw-r--r--test/YAMLParser/spec-08-03.data4
-rw-r--r--test/YAMLParser/spec-08-04.data9
-rw-r--r--test/YAMLParser/spec-08-05.data7
-rw-r--r--test/YAMLParser/spec-08-06.data12
-rw-r--r--test/YAMLParser/spec-08-07.data6
-rw-r--r--test/YAMLParser/spec-08-08.data15
-rw-r--r--test/YAMLParser/spec-08-09.data13
-rw-r--r--test/YAMLParser/spec-08-10.data17
-rw-r--r--test/YAMLParser/spec-08-11.data4
-rw-r--r--test/YAMLParser/spec-08-12.data10
-rw-r--r--test/YAMLParser/spec-08-13.data6
-rw-r--r--test/YAMLParser/spec-08-14.data7
-rw-r--r--test/YAMLParser/spec-08-15.data7
-rw-r--r--test/YAMLParser/spec-09-01.data8
-rw-r--r--test/YAMLParser/spec-09-02.data14
-rw-r--r--test/YAMLParser/spec-09-03.data8
-rw-r--r--test/YAMLParser/spec-09-04.data6
-rw-r--r--test/YAMLParser/spec-09-05.data10
-rw-r--r--test/YAMLParser/spec-09-06.data3
-rw-r--r--test/YAMLParser/spec-09-07.data8
-rw-r--r--test/YAMLParser/spec-09-08.data3
-rw-r--r--test/YAMLParser/spec-09-09.data8
-rw-r--r--test/YAMLParser/spec-09-10.data5
-rw-r--r--test/YAMLParser/spec-09-11.data7
-rw-r--r--test/YAMLParser/spec-09-12.data10
-rw-r--r--test/YAMLParser/spec-09-13.data8
-rw-r--r--test/YAMLParser/spec-09-14.data21
-rw-r--r--test/YAMLParser/spec-09-15.data15
-rw-r--r--test/YAMLParser/spec-09-16.data5
-rw-r--r--test/YAMLParser/spec-09-17.data5
-rw-r--r--test/YAMLParser/spec-09-18.data11
-rw-r--r--test/YAMLParser/spec-09-19.data6
-rw-r--r--test/YAMLParser/spec-09-20.data13
-rw-r--r--test/YAMLParser/spec-09-21.data12
-rw-r--r--test/YAMLParser/spec-09-22.data6
-rw-r--r--test/YAMLParser/spec-09-23.data13
-rw-r--r--test/YAMLParser/spec-09-24.data8
-rw-r--r--test/YAMLParser/spec-09-25.data5
-rw-r--r--test/YAMLParser/spec-09-26.data10
-rw-r--r--test/YAMLParser/spec-09-27.data10
-rw-r--r--test/YAMLParser/spec-09-28.data10
-rw-r--r--test/YAMLParser/spec-09-29.data6
-rw-r--r--test/YAMLParser/spec-09-30.data16
-rw-r--r--test/YAMLParser/spec-09-31.data16
-rw-r--r--test/YAMLParser/spec-09-32.data16
-rw-r--r--test/YAMLParser/spec-09-33.data16
-rw-r--r--test/YAMLParser/spec-10-01.data4
-rw-r--r--test/YAMLParser/spec-10-02.data10
-rw-r--r--test/YAMLParser/spec-10-03.data6
-rw-r--r--test/YAMLParser/spec-10-04.data6
-rw-r--r--test/YAMLParser/spec-10-05.data9
-rw-r--r--test/YAMLParser/spec-10-06.data4
-rw-r--r--test/YAMLParser/spec-10-07.data9
-rw-r--r--test/YAMLParser/spec-10-08.data13
-rw-r--r--test/YAMLParser/spec-10-09.data6
-rw-r--r--test/YAMLParser/spec-10-10.data10
-rw-r--r--test/YAMLParser/spec-10-11.data9
-rw-r--r--test/YAMLParser/spec-10-12.data5
-rw-r--r--test/YAMLParser/spec-10-13.data7
-rw-r--r--test/YAMLParser/spec-10-14.data6
-rw-r--r--test/YAMLParser/spec-10-15.data5
-rw-r--r--test/YAMLParser/str.data3
-rw-r--r--test/YAMLParser/timestamp-bugs.data8
-rw-r--r--test/YAMLParser/timestamp.data7
-rw-r--r--test/YAMLParser/utf8-implicit.data3
-rw-r--r--test/YAMLParser/utf8.data3
-rw-r--r--test/YAMLParser/value.data3
-rw-r--r--test/YAMLParser/yaml.data5
-rw-r--r--test/lit.cfg244
-rw-r--r--test/lit.site.cfg.in28
-rw-r--r--tools/CMakeLists.txt55
-rw-r--r--tools/LLVMBuild.txt24
-rw-r--r--tools/Makefile74
-rw-r--r--tools/bugpoint-passes/CMakeLists.txt5
-rw-r--r--tools/bugpoint-passes/Makefile23
-rw-r--r--tools/bugpoint-passes/TestPasses.cpp75
-rw-r--r--tools/bugpoint-passes/bugpoint.exports0
-rw-r--r--tools/bugpoint/BugDriver.cpp247
-rw-r--r--tools/bugpoint/BugDriver.h330
-rw-r--r--tools/bugpoint/CMakeLists.txt14
-rw-r--r--tools/bugpoint/CrashDebugger.cpp672
-rw-r--r--tools/bugpoint/ExecutionDriver.cpp472
-rw-r--r--tools/bugpoint/ExtractFunction.cpp418
-rw-r--r--tools/bugpoint/FindBugs.cpp113
-rw-r--r--tools/bugpoint/LLVMBuild.txt22
-rw-r--r--tools/bugpoint/ListReducer.h201
-rw-r--r--tools/bugpoint/Makefile15
-rw-r--r--tools/bugpoint/Miscompilation.cpp1079
-rw-r--r--tools/bugpoint/OptimizerDriver.cpp267
-rw-r--r--tools/bugpoint/ToolRunner.cpp890
-rw-r--r--tools/bugpoint/ToolRunner.h248
-rw-r--r--tools/bugpoint/bugpoint.cpp210
-rw-r--r--tools/gold/CMakeLists.txt46
-rw-r--r--tools/gold/Makefile31
-rw-r--r--tools/gold/README.txt21
-rw-r--r--tools/gold/gold-plugin.cpp477
-rw-r--r--tools/gold/gold.exports1
-rw-r--r--tools/llc/CMakeLists.txt5
-rw-r--r--tools/llc/LLVMBuild.txt22
-rw-r--r--tools/llc/Makefile15
-rw-r--r--tools/llc/llc.cpp566
-rw-r--r--tools/lli/CMakeLists.txt24
-rw-r--r--tools/lli/LLVMBuild.txt22
-rw-r--r--tools/lli/Makefile29
-rw-r--r--tools/lli/RecordingMemoryManager.cpp87
-rw-r--r--tools/lli/RecordingMemoryManager.h78
-rw-r--r--tools/lli/RemoteTarget.cpp61
-rw-r--r--tools/lli/RemoteTarget.h101
-rw-r--r--tools/lli/lli.cpp689
-rw-r--r--tools/llvm-ar/CMakeLists.txt8
-rw-r--r--tools/llvm-ar/LLVMBuild.txt22
-rw-r--r--tools/llvm-ar/Makefile18
-rw-r--r--tools/llvm-ar/llvm-ar.cpp774
-rw-r--r--tools/llvm-as/CMakeLists.txt6
-rw-r--r--tools/llvm-as/LLVMBuild.txt22
-rw-r--r--tools/llvm-as/Makefile17
-rw-r--r--tools/llvm-as/llvm-as.cpp119
-rw-r--r--tools/llvm-bcanalyzer/CMakeLists.txt6
-rw-r--r--tools/llvm-bcanalyzer/LLVMBuild.txt22
-rw-r--r--tools/llvm-bcanalyzer/Makefile17
-rw-r--r--tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp628
-rw-r--r--tools/llvm-config/BuildVariables.inc.in27
-rw-r--r--tools/llvm-config/CMakeLists.txt42
-rw-r--r--tools/llvm-config/Makefile67
-rw-r--r--tools/llvm-config/llvm-config.cpp356
-rw-r--r--tools/llvm-cov/CMakeLists.txt5
-rw-r--r--tools/llvm-cov/LLVMBuild.txt22
-rw-r--r--tools/llvm-cov/Makefile17
-rw-r--r--tools/llvm-cov/llvm-cov.cpp78
-rw-r--r--tools/llvm-diff/CMakeLists.txt8
-rw-r--r--tools/llvm-diff/DiffConsumer.cpp215
-rw-r--r--tools/llvm-diff/DiffConsumer.h91
-rw-r--r--tools/llvm-diff/DiffLog.cpp53
-rw-r--r--tools/llvm-diff/DiffLog.h80
-rw-r--r--tools/llvm-diff/DifferenceEngine.cpp683
-rw-r--r--tools/llvm-diff/DifferenceEngine.h92
-rw-r--r--tools/llvm-diff/LLVMBuild.txt22
-rw-r--r--tools/llvm-diff/Makefile17
-rw-r--r--tools/llvm-diff/llvm-diff.cpp98
-rw-r--r--tools/llvm-dis/CMakeLists.txt6
-rw-r--r--tools/llvm-dis/LLVMBuild.txt22
-rw-r--r--tools/llvm-dis/Makefile17
-rw-r--r--tools/llvm-dis/llvm-dis.cpp191
-rw-r--r--tools/llvm-dwarfdump/CMakeLists.txt8
-rw-r--r--tools/llvm-dwarfdump/LLVMBuild.txt22
-rw-r--r--tools/llvm-dwarfdump/Makefile17
-rw-r--r--tools/llvm-dwarfdump/llvm-dwarfdump.cpp155
-rw-r--r--tools/llvm-extract/CMakeLists.txt5
-rw-r--r--tools/llvm-extract/LLVMBuild.txt22
-rw-r--r--tools/llvm-extract/Makefile17
-rw-r--r--tools/llvm-extract/llvm-extract.cpp238
-rw-r--r--tools/llvm-link/CMakeLists.txt5
-rw-r--r--tools/llvm-link/LLVMBuild.txt22
-rw-r--r--tools/llvm-link/Makefile17
-rw-r--r--tools/llvm-link/llvm-link.cpp142
-rw-r--r--tools/llvm-mc/CMakeLists.txt6
-rw-r--r--tools/llvm-mc/Disassembler.cpp343
-rw-r--r--tools/llvm-mc/Disassembler.h47
-rw-r--r--tools/llvm-mc/LLVMBuild.txt22
-rw-r--r--tools/llvm-mc/Makefile17
-rw-r--r--tools/llvm-mc/llvm-mc.cpp451
-rw-r--r--tools/llvm-nm/CMakeLists.txt5
-rw-r--r--tools/llvm-nm/LLVMBuild.txt22
-rw-r--r--tools/llvm-nm/Makefile17
-rw-r--r--tools/llvm-nm/llvm-nm.cpp415
-rw-r--r--tools/llvm-objdump/CMakeLists.txt14
-rw-r--r--tools/llvm-objdump/LLVMBuild.txt22
-rw-r--r--tools/llvm-objdump/MCFunction.cpp138
-rw-r--r--tools/llvm-objdump/MCFunction.h100
-rw-r--r--tools/llvm-objdump/MachODump.cpp664
-rw-r--r--tools/llvm-objdump/Makefile17
-rw-r--r--tools/llvm-objdump/llvm-objdump.cpp671
-rw-r--r--tools/llvm-objdump/llvm-objdump.h46
-rw-r--r--tools/llvm-prof/CMakeLists.txt5
-rw-r--r--tools/llvm-prof/LLVMBuild.txt22
-rw-r--r--tools/llvm-prof/Makefile17
-rw-r--r--tools/llvm-prof/llvm-prof.cpp293
-rw-r--r--tools/llvm-ranlib/CMakeLists.txt6
-rw-r--r--tools/llvm-ranlib/LLVMBuild.txt22
-rw-r--r--tools/llvm-ranlib/Makefile18
-rw-r--r--tools/llvm-ranlib/llvm-ranlib.cpp101
-rw-r--r--tools/llvm-readobj/CMakeLists.txt5
-rw-r--r--tools/llvm-readobj/LLVMBuild.txt22
-rw-r--r--tools/llvm-readobj/Makefile18
-rw-r--r--tools/llvm-readobj/llvm-readobj.cpp218
-rw-r--r--tools/llvm-rtdyld/CMakeLists.txt5
-rw-r--r--tools/llvm-rtdyld/LLVMBuild.txt22
-rw-r--r--tools/llvm-rtdyld/Makefile17
-rw-r--r--tools/llvm-rtdyld/llvm-rtdyld.cpp177
-rw-r--r--tools/llvm-shlib/Makefile126
-rw-r--r--tools/llvm-size/CMakeLists.txt5
-rw-r--r--tools/llvm-size/LLVMBuild.txt22
-rw-r--r--tools/llvm-size/Makefile17
-rw-r--r--tools/llvm-size/llvm-size.cpp311
-rw-r--r--tools/llvm-stress/CMakeLists.txt5
-rw-r--r--tools/llvm-stress/LLVMBuild.txt22
-rw-r--r--tools/llvm-stress/Makefile18
-rw-r--r--tools/llvm-stress/llvm-stress.cpp716
-rw-r--r--tools/lto/CMakeLists.txt27
-rw-r--r--tools/lto/LTOCodeGenerator.cpp417
-rw-r--r--tools/lto/LTOCodeGenerator.h82
-rw-r--r--tools/lto/LTOModule.cpp894
-rw-r--r--tools/lto/LTOModule.h191
-rw-r--r--tools/lto/Makefile52
-rw-r--r--tools/lto/lto.cpp214
-rw-r--r--tools/lto/lto.exports32
-rw-r--r--tools/macho-dump/CMakeLists.txt5
-rw-r--r--tools/macho-dump/LLVMBuild.txt22
-rw-r--r--tools/macho-dump/Makefile17
-rw-r--r--tools/macho-dump/macho-dump.cpp432
-rw-r--r--tools/opt/AnalysisWrappers.cpp94
-rw-r--r--tools/opt/CMakeLists.txt8
-rw-r--r--tools/opt/GraphPrinters.cpp118
-rw-r--r--tools/opt/LLVMBuild.txt22
-rw-r--r--tools/opt/Makefile14
-rw-r--r--tools/opt/PrintSCC.cpp112
-rw-r--r--tools/opt/opt.cpp748
-rw-r--r--unittests/ADT/APFloatTest.cpp723
-rw-r--r--unittests/ADT/APIntTest.cpp517
-rw-r--r--unittests/ADT/BitVectorTest.cpp285
-rw-r--r--unittests/ADT/CMakeLists.txt46
-rw-r--r--unittests/ADT/DAGDeltaAlgorithmTest.cpp105
-rw-r--r--unittests/ADT/DeltaAlgorithmTest.cpp100
-rw-r--r--unittests/ADT/DenseMapTest.cpp333
-rw-r--r--unittests/ADT/DenseSetTest.cpp30
-rw-r--r--unittests/ADT/FoldingSet.cpp39
-rw-r--r--unittests/ADT/HashingTest.cpp424
-rw-r--r--unittests/ADT/ImmutableSetTest.cpp201
-rw-r--r--unittests/ADT/IntEqClassesTest.cpp107
-rw-r--r--unittests/ADT/IntervalMapTest.cpp716
-rw-r--r--unittests/ADT/IntrusiveRefCntPtrTest.cpp64
-rw-r--r--unittests/ADT/Makefile23
-rw-r--r--unittests/ADT/PackedVectorTest.cpp115
-rw-r--r--unittests/ADT/SCCIteratorTest.cpp346
-rw-r--r--unittests/ADT/SmallPtrSetTest.cpp72
-rw-r--r--unittests/ADT/SmallStringTest.cpp196
-rw-r--r--unittests/ADT/SmallVectorTest.cpp489
-rw-r--r--unittests/ADT/SparseBitVectorTest.cpp36
-rw-r--r--unittests/ADT/SparseSetTest.cpp186
-rw-r--r--unittests/ADT/StringMapTest.cpp223
-rw-r--r--unittests/ADT/StringRefTest.cpp459
-rw-r--r--unittests/ADT/TinyPtrVectorTest.cpp448
-rw-r--r--unittests/ADT/TripleTest.cpp458
-rw-r--r--unittests/ADT/TwineTest.cpp87
-rw-r--r--unittests/ADT/VariadicFunctionTest.cpp110
-rw-r--r--unittests/ADT/ilistTest.cpp44
-rw-r--r--unittests/Analysis/CMakeLists.txt7
-rw-r--r--unittests/Analysis/Makefile15
-rw-r--r--unittests/Analysis/ScalarEvolutionTest.cpp234
-rw-r--r--unittests/Bitcode/BitReaderTest.cpp65
-rw-r--r--unittests/Bitcode/CMakeLists.txt8
-rw-r--r--unittests/Bitcode/Makefile15
-rw-r--r--unittests/CMakeLists.txt14
-rw-r--r--unittests/ExecutionEngine/CMakeLists.txt9
-rw-r--r--unittests/ExecutionEngine/ExecutionEngineTest.cpp131
-rw-r--r--unittests/ExecutionEngine/JIT/CMakeLists.txt57
-rw-r--r--unittests/ExecutionEngine/JIT/IntelJITEventListenerTest.cpp110
-rw-r--r--unittests/ExecutionEngine/JIT/JITEventListenerTest.cpp238
-rw-r--r--unittests/ExecutionEngine/JIT/JITEventListenerTestCommon.h209
-rw-r--r--unittests/ExecutionEngine/JIT/JITMemoryManagerTest.cpp280
-rw-r--r--unittests/ExecutionEngine/JIT/JITTest.cpp799
-rw-r--r--unittests/ExecutionEngine/JIT/JITTests.def4
-rw-r--r--unittests/ExecutionEngine/JIT/Makefile42
-rw-r--r--unittests/ExecutionEngine/JIT/MultiJITTest.cpp181
-rw-r--r--unittests/ExecutionEngine/JIT/OProfileJITEventListenerTest.cpp166
-rw-r--r--unittests/ExecutionEngine/Makefile16
-rw-r--r--unittests/Makefile17
-rw-r--r--unittests/Makefile.unittest62
-rw-r--r--unittests/Support/AlignOfTest.cpp304
-rw-r--r--unittests/Support/AllocatorTest.cpp151
-rw-r--r--unittests/Support/BlockFrequencyTest.cpp85
-rw-r--r--unittests/Support/CMakeLists.txt28
-rw-r--r--unittests/Support/Casting.cpp155
-rw-r--r--unittests/Support/CommandLineTest.cpp71
-rw-r--r--unittests/Support/ConstantRangeTest.cpp510
-rw-r--r--unittests/Support/DataExtractorTest.cpp120
-rw-r--r--unittests/Support/EndianTest.cpp72
-rw-r--r--unittests/Support/FileOutputBufferTest.cpp137
-rw-r--r--unittests/Support/IntegersSubsetTest.cpp328
-rw-r--r--unittests/Support/LeakDetectorTest.cpp31
-rw-r--r--unittests/Support/Makefile15
-rw-r--r--unittests/Support/ManagedStatic.cpp44
-rw-r--r--unittests/Support/MathExtrasTest.cpp104
-rw-r--r--unittests/Support/Path.cpp390
-rw-r--r--unittests/Support/RegexTest.cpp94
-rw-r--r--unittests/Support/SwapByteOrderTest.cpp128
-rw-r--r--unittests/Support/TimeValue.cpp23
-rw-r--r--unittests/Support/ValueHandleTest.cpp411
-rw-r--r--unittests/Support/YAMLParserTest.cpp185
-rw-r--r--unittests/Support/formatted_raw_ostream_test.cpp33
-rw-r--r--unittests/Support/raw_ostream_test.cpp146
-rw-r--r--unittests/Transforms/CMakeLists.txt1
-rw-r--r--unittests/Transforms/Makefile17
-rw-r--r--unittests/Transforms/Utils/CMakeLists.txt8
-rw-r--r--unittests/Transforms/Utils/Cloning.cpp146
-rw-r--r--unittests/Transforms/Utils/Local.cpp61
-rw-r--r--unittests/Transforms/Utils/Makefile15
-rw-r--r--unittests/VMCore/CMakeLists.txt35
-rw-r--r--unittests/VMCore/ConstantsTest.cpp122
-rw-r--r--unittests/VMCore/DominatorTreeTest.cpp195
-rw-r--r--unittests/VMCore/IRBuilderTest.cpp99
-rw-r--r--unittests/VMCore/InstructionsTest.cpp247
-rw-r--r--unittests/VMCore/MDBuilderTest.cpp107
-rw-r--r--unittests/VMCore/Makefile15
-rw-r--r--unittests/VMCore/MetadataTest.cpp152
-rw-r--r--unittests/VMCore/PassManagerTest.cpp548
-rw-r--r--unittests/VMCore/TypeBuilderTest.cpp254
-rw-r--r--unittests/VMCore/TypesTest.cpp30
-rw-r--r--unittests/VMCore/ValueMapTest.cpp295
-rw-r--r--unittests/VMCore/VerifierTest.cpp64
-rwxr-xr-xutils/DSAclean.py32
-rw-r--r--utils/DSAextract.py111
-rw-r--r--utils/FileCheck/CMakeLists.txt11
-rw-r--r--utils/FileCheck/FileCheck.cpp762
-rw-r--r--utils/FileCheck/Makefile21
-rw-r--r--utils/FileUpdate/CMakeLists.txt11
-rw-r--r--utils/FileUpdate/FileUpdate.cpp87
-rw-r--r--utils/FileUpdate/Makefile21
-rwxr-xr-xutils/GenLibDeps.pl384
-rwxr-xr-xutils/GetRepositoryPath27
-rwxr-xr-xutils/GetSourceVersion27
-rw-r--r--utils/KillTheDoctor/CMakeLists.txt5
-rw-r--r--utils/KillTheDoctor/KillTheDoctor.cpp550
-rw-r--r--utils/LLVMBuild.txt29
-rw-r--r--utils/Makefile19
-rwxr-xr-xutils/Misc/zkill276
-rw-r--r--utils/PerfectShuffle/Makefile18
-rw-r--r--utils/PerfectShuffle/PerfectShuffle.cpp572
-rw-r--r--utils/TableGen/AsmMatcherEmitter.cpp2949
-rw-r--r--utils/TableGen/AsmWriterEmitter.cpp1004
-rw-r--r--utils/TableGen/AsmWriterInst.cpp233
-rw-r--r--utils/TableGen/AsmWriterInst.h113
-rw-r--r--utils/TableGen/CMakeLists.txt37
-rw-r--r--utils/TableGen/CallingConvEmitter.cpp236
-rw-r--r--utils/TableGen/CodeEmitterGen.cpp339
-rw-r--r--utils/TableGen/CodeGenDAGPatterns.cpp3457
-rw-r--r--utils/TableGen/CodeGenDAGPatterns.h812
-rw-r--r--utils/TableGen/CodeGenInstruction.cpp620
-rw-r--r--utils/TableGen/CodeGenInstruction.h339
-rw-r--r--utils/TableGen/CodeGenIntrinsics.h93
-rw-r--r--utils/TableGen/CodeGenRegisters.cpp1873
-rw-r--r--utils/TableGen/CodeGenRegisters.h640
-rw-r--r--utils/TableGen/CodeGenSchedule.cpp1353
-rw-r--r--utils/TableGen/CodeGenSchedule.h381
-rw-r--r--utils/TableGen/CodeGenTarget.cpp546
-rw-r--r--utils/TableGen/CodeGenTarget.h211
-rw-r--r--utils/TableGen/DAGISelEmitter.cpp175
-rw-r--r--utils/TableGen/DAGISelMatcher.cpp415
-rw-r--r--utils/TableGen/DAGISelMatcher.h1119
-rw-r--r--utils/TableGen/DAGISelMatcherEmitter.cpp812
-rw-r--r--utils/TableGen/DAGISelMatcherGen.cpp957
-rw-r--r--utils/TableGen/DAGISelMatcherOpt.cpp513
-rw-r--r--utils/TableGen/DFAPacketizerEmitter.cpp515
-rw-r--r--utils/TableGen/DisassemblerEmitter.cpp147
-rw-r--r--utils/TableGen/EDEmitter.cpp1010
-rw-r--r--utils/TableGen/FastISelEmitter.cpp877
-rw-r--r--utils/TableGen/FixedLenDecoderEmitter.cpp2092
-rw-r--r--utils/TableGen/InstrInfoEmitter.cpp420
-rw-r--r--utils/TableGen/IntrinsicEmitter.cpp753
-rw-r--r--utils/TableGen/LLVMBuild.txt22
-rw-r--r--utils/TableGen/Makefile20
-rw-r--r--utils/TableGen/PseudoLoweringEmitter.cpp297
-rw-r--r--utils/TableGen/RegisterInfoEmitter.cpp1194
-rw-r--r--utils/TableGen/SequenceToOffsetTable.h141
-rw-r--r--utils/TableGen/SetTheory.cpp313
-rw-r--r--utils/TableGen/SetTheory.h140
-rw-r--r--utils/TableGen/StringToOffsetTable.h83
-rw-r--r--utils/TableGen/SubtargetEmitter.cpp1392
-rw-r--r--utils/TableGen/TGValueTypes.cpp105
-rw-r--r--utils/TableGen/TableGen.cpp182
-rw-r--r--utils/TableGen/TableGenBackends.h78
-rw-r--r--utils/TableGen/X86DisassemblerShared.h39
-rw-r--r--utils/TableGen/X86DisassemblerTables.cpp718
-rw-r--r--utils/TableGen/X86DisassemblerTables.h298
-rw-r--r--utils/TableGen/X86ModRMFilters.cpp26
-rw-r--r--utils/TableGen/X86ModRMFilters.h199
-rw-r--r--utils/TableGen/X86RecognizableInstr.cpp1276
-rw-r--r--utils/TableGen/X86RecognizableInstr.h266
-rw-r--r--utils/Target/ARM/analyze-match-table.py61
-rwxr-xr-xutils/UpdateCMakeLists.pl118
-rw-r--r--utils/bugpoint/RemoteRunSafely.sh105
-rw-r--r--utils/buildit/GNUmakefile132
-rwxr-xr-xutils/buildit/build_llvm316
-rwxr-xr-xutils/check-each-file150
-rwxr-xr-xutils/clang-parse-diagnostics-file78
-rwxr-xr-xutils/codegen-diff135
-rw-r--r--utils/count/CMakeLists.txt3
-rw-r--r--utils/count/Makefile20
-rw-r--r--utils/count/count.c50
-rwxr-xr-xutils/countloc.sh40
-rw-r--r--utils/crosstool/ARM/README37
-rwxr-xr-xutils/crosstool/ARM/build-install-linux.sh200
-rwxr-xr-xutils/crosstool/create-snapshots.sh41
-rw-r--r--utils/emacs/README27
-rw-r--r--utils/emacs/emacs.el39
-rw-r--r--utils/emacs/llvm-mode.el133
-rw-r--r--utils/emacs/tablegen-mode.el122
-rwxr-xr-xutils/findmisopt177
-rwxr-xr-xutils/findoptdiff101
-rwxr-xr-xutils/findsym.pl33
-rw-r--r--utils/fpcmp/Makefile16
-rw-r--r--utils/fpcmp/fpcmp.cpp43
-rwxr-xr-xutils/getsrcs.sh34
-rwxr-xr-xutils/git/find-rev50
-rw-r--r--utils/jedit/README14
-rw-r--r--utils/jedit/tablegen.xml39
-rw-r--r--utils/kate/README12
-rw-r--r--utils/kate/llvm.xml255
-rw-r--r--utils/lint/common_lint.py97
-rwxr-xr-xutils/lint/cpp_lint.py94
-rwxr-xr-xutils/lint/generic_lint.py24
-rwxr-xr-xutils/lint/remove_trailing_whitespace.sh6
-rw-r--r--utils/lit/TODO9
-rwxr-xr-xutils/lit/lit.py5
-rw-r--r--utils/lit/lit/ExampleTests.ObjDir/lit.site.cfg15
-rw-r--r--utils/lit/lit/ExampleTests/Clang/fsyntax-only.c4
-rw-r--r--utils/lit/lit/ExampleTests/Clang/lit.cfg47
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.InTree/test/Bar/bar-test.ll3
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.InTree/test/Bar/dg.exp6
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.InTree/test/lit.cfg137
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.InTree/test/lit.site.cfg10
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.InTree/test/site.exp10
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.OutOfTree/lit.local.cfg1
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.OutOfTree/obj/test/Foo/lit.local.cfg0
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.OutOfTree/obj/test/lit.site.cfg11
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.OutOfTree/obj/test/site.exp10
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.OutOfTree/src/test/Foo/data.txt1
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.OutOfTree/src/test/Foo/dg.exp6
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.OutOfTree/src/test/Foo/pct-S.ll1
-rw-r--r--utils/lit/lit/ExampleTests/LLVM.OutOfTree/src/test/lit.cfg137
-rw-r--r--utils/lit/lit/ExampleTests/ShExternal/lit.local.cfg6
-rw-r--r--utils/lit/lit/ExampleTests/ShInternal/lit.local.cfg6
-rw-r--r--utils/lit/lit/ExampleTests/TclTest/lit.local.cfg5
-rw-r--r--utils/lit/lit/ExampleTests/TclTest/stderr-pipe.ll1
-rw-r--r--utils/lit/lit/ExampleTests/TclTest/tcl-redir-1.ll7
-rw-r--r--utils/lit/lit/ExampleTests/fail.c2
-rw-r--r--utils/lit/lit/ExampleTests/lit.cfg26
-rw-r--r--utils/lit/lit/ExampleTests/pass.c1
-rw-r--r--utils/lit/lit/ExampleTests/required-and-missing.c4
-rw-r--r--utils/lit/lit/ExampleTests/required-and-present.c2
-rw-r--r--utils/lit/lit/ExampleTests/xfail.c2
-rw-r--r--utils/lit/lit/ExampleTests/xpass.c2
-rw-r--r--utils/lit/lit/LitConfig.py134
-rw-r--r--utils/lit/lit/LitFormats.py3
-rw-r--r--utils/lit/lit/LitTestCase.py30
-rw-r--r--utils/lit/lit/ProgressBar.py280
-rw-r--r--utils/lit/lit/ShCommands.py85
-rw-r--r--utils/lit/lit/ShUtil.py353
-rw-r--r--utils/lit/lit/TclUtil.py322
-rw-r--r--utils/lit/lit/Test.py79
-rw-r--r--utils/lit/lit/TestFormats.py232
-rw-r--r--utils/lit/lit/TestRunner.py611
-rw-r--r--utils/lit/lit/TestingConfig.py125
-rw-r--r--utils/lit/lit/Util.py141
-rw-r--r--utils/lit/lit/__init__.py10
-rwxr-xr-xutils/lit/lit/main.py669
-rw-r--r--utils/lit/setup.py70
-rw-r--r--utils/lldbDataFormatters.py53
-rw-r--r--utils/llvm-build/README.txt5
-rwxr-xr-xutils/llvm-build/llvm-build6
-rw-r--r--utils/llvm-build/llvmbuild/__init__.py1
-rw-r--r--utils/llvm-build/llvmbuild/componentinfo.py468
-rw-r--r--utils/llvm-build/llvmbuild/configutil.py66
-rw-r--r--utils/llvm-build/llvmbuild/main.py891
-rw-r--r--utils/llvm-build/llvmbuild/util.py13
-rwxr-xr-xutils/llvm-compilers-check577
-rw-r--r--utils/llvm-lit/CMakeLists.txt12
-rw-r--r--utils/llvm-lit/Makefile22
-rwxr-xr-xutils/llvm-lit/llvm-lit.in33
-rwxr-xr-xutils/llvm-native-gcc249
-rwxr-xr-xutils/llvm-native-gxx249
-rw-r--r--utils/llvm.grm421
-rwxr-xr-xutils/llvmdo184
-rwxr-xr-xutils/llvmgrep39
-rwxr-xr-xutils/makellvm145
-rw-r--r--utils/not/CMakeLists.txt11
-rw-r--r--utils/not/Makefile21
-rw-r--r--utils/not/not.cpp27
-rw-r--r--utils/obj2yaml/CMakeLists.txt7
-rw-r--r--utils/obj2yaml/Makefile20
-rw-r--r--utils/obj2yaml/coff2yaml.cpp362
-rw-r--r--utils/obj2yaml/obj2yaml.cpp89
-rw-r--r--utils/obj2yaml/obj2yaml.h35
-rwxr-xr-xutils/profile.pl74
-rwxr-xr-xutils/release/findRegressions-nightly.py130
-rwxr-xr-xutils/release/findRegressions-simple.py158
-rwxr-xr-xutils/release/merge.sh74
-rwxr-xr-xutils/release/tag.sh109
-rwxr-xr-xutils/release/test-release.sh519
-rwxr-xr-xutils/test_debuginfo.pl61
-rw-r--r--utils/unittest/CMakeLists.txt48
-rw-r--r--utils/unittest/LLVMBuild.txt30
-rw-r--r--utils/unittest/Makefile13
-rw-r--r--utils/unittest/UnitTestMain/Makefile32
-rw-r--r--utils/unittest/UnitTestMain/TestMain.cpp42
-rw-r--r--utils/unittest/googletest/LICENSE.TXT28
-rw-r--r--utils/unittest/googletest/Makefile39
-rw-r--r--utils/unittest/googletest/README.LLVM33
-rw-r--r--utils/unittest/googletest/gtest-death-test.cc1233
-rw-r--r--utils/unittest/googletest/gtest-filepath.cc380
-rw-r--r--utils/unittest/googletest/gtest-port.cc750
-rw-r--r--utils/unittest/googletest/gtest-printers.cc356
-rw-r--r--utils/unittest/googletest/gtest-test-part.cc110
-rw-r--r--utils/unittest/googletest/gtest-typed-test.cc110
-rw-r--r--utils/unittest/googletest/gtest.cc4866
-rw-r--r--utils/unittest/googletest/include/gtest/gtest-death-test.h283
-rw-r--r--utils/unittest/googletest/include/gtest/gtest-message.h230
-rw-r--r--utils/unittest/googletest/include/gtest/gtest-param-test.h1426
-rw-r--r--utils/unittest/googletest/include/gtest/gtest-printers.h796
-rw-r--r--utils/unittest/googletest/include/gtest/gtest-spi.h232
-rw-r--r--utils/unittest/googletest/include/gtest/gtest-test-part.h176
-rw-r--r--utils/unittest/googletest/include/gtest/gtest-typed-test.h259
-rw-r--r--utils/unittest/googletest/include/gtest/gtest.h2157
-rw-r--r--utils/unittest/googletest/include/gtest/gtest_pred_impl.h358
-rw-r--r--utils/unittest/googletest/include/gtest/gtest_prod.h58
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h306
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-filepath.h210
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-internal-inl.h1037
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-internal.h1245
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h233
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h4822
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-param-util.h619
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-port.h1780
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-string.h350
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-tuple.h968
-rw-r--r--utils/unittest/googletest/include/gtest/internal/gtest-type-util.h3330
-rw-r--r--utils/valgrind/i386-pc-linux-gnu.supp48
-rw-r--r--utils/valgrind/x86_64-pc-linux-gnu.supp64
-rw-r--r--utils/vim/README43
-rw-r--r--utils/vim/llvm.vim110
-rw-r--r--utils/vim/tablegen.vim54
-rw-r--r--utils/vim/vimrc221
-rw-r--r--utils/yaml-bench/CMakeLists.txt5
-rw-r--r--utils/yaml-bench/Makefile20
-rw-r--r--utils/yaml-bench/YAMLBench.cpp203
-rw-r--r--utils/yaml2obj/CMakeLists.txt5
-rw-r--r--utils/yaml2obj/Makefile20
-rw-r--r--utils/yaml2obj/yaml2obj.cpp879
9284 files changed, 1644106 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000000..4e9e1376143
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,47 @@
+#==============================================================================#
+# This file specifies intentionally untracked files that git should ignore.
+# See: http://www.kernel.org/pub/software/scm/git/docs/gitignore.html
+#
+# This file is intentionally different from the output of `git svn show-ignore`,
+# as most of those are useless.
+#==============================================================================#
+
+#==============================================================================#
+# File extensions to be ignored anywhere in the tree.
+#==============================================================================#
+# Temp files created by most text editors.
+*~
+# Merge files created by git.
+*.orig
+# Byte compiled python modules.
+*.pyc
+# vim swap files
+.*.swp
+
+#==============================================================================#
+# Explicit files to ignore (only matches one).
+#==============================================================================#
+.gitusers
+autom4te.cache
+cscope.files
+cscope.out
+autoconf/aclocal.m4
+autoconf/autom4te.cache
+compile_commands.json
+
+#==============================================================================#
+# Directories to ignore (do not add trailing '/'s, they skip symlinks).
+#==============================================================================#
+# External projects that are tracked independently.
+projects/*
+!projects/sample
+!projects/CMakeLists.txt
+!projects/Makefile
+# Clang, which is tracked independently.
+tools/clang
+# LLDB, which is tracked independently.
+tools/lldb
+# lld, which is tracked independently.
+tools/lld
+# Sphinx build tree, if building in-source dir.
+docs/_build
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 00000000000..df781f52cdd
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,502 @@
+# See docs/CMake.html for instructions about how to build LLVM with CMake.
+
+project(LLVM)
+cmake_minimum_required(VERSION 2.8)
+
+# Add path for custom modules
+set(CMAKE_MODULE_PATH
+ ${CMAKE_MODULE_PATH}
+ "${CMAKE_CURRENT_SOURCE_DIR}/cmake"
+ "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules"
+ )
+
+set(LLVM_VERSION_MAJOR 3)
+set(LLVM_VERSION_MINOR 2)
+
+set(PACKAGE_VERSION "${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}svn")
+
+option(LLVM_USE_FOLDERS "Enable solution folders in Visual Studio. Disable for Express versions." ON)
+if ( LLVM_USE_FOLDERS )
+ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
+endif()
+
+include(VersionFromVCS)
+
+option(LLVM_APPEND_VC_REV
+ "Append the version control system revision id to LLVM version" OFF)
+
+if( LLVM_APPEND_VC_REV )
+ add_version_info_from_vcs(PACKAGE_VERSION)
+endif()
+
+set(PACKAGE_NAME LLVM)
+set(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}")
+set(PACKAGE_BUGREPORT "http://llvm.org/bugs/")
+
+# Sanity check our source directory to make sure that we are not trying to
+# generate an in-tree build (unless on MSVC_IDE, where it is ok), and to make
+# sure that we don't have any stray generated files lying around in the tree
+# (which would end up getting picked up by header search, instead of the correct
+# versions).
+if( CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR AND NOT MSVC_IDE )
+ message(FATAL_ERROR "In-source builds are not allowed.
+CMake would overwrite the makefiles distributed with LLVM.
+Please create a directory and run cmake from there, passing the path
+to this source directory as the last argument.
+This process created the file `CMakeCache.txt' and the directory `CMakeFiles'.
+Please delete them.")
+endif()
+if( NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR )
+ file(GLOB_RECURSE
+ tablegenned_files_on_include_dir
+ "${CMAKE_CURRENT_SOURCE_DIR}/include/llvm/*.gen")
+ file(GLOB_RECURSE
+ tablegenned_files_on_lib_dir
+ "${CMAKE_CURRENT_SOURCE_DIR}/lib/Target/*.inc")
+ if( tablegenned_files_on_include_dir OR tablegenned_files_on_lib_dir)
+ message(FATAL_ERROR "Apparently there is a previous in-source build,
+probably as the result of running `configure' and `make' on
+${CMAKE_CURRENT_SOURCE_DIR}.
+This may cause problems. The suspicious files are:
+${tablegenned_files_on_lib_dir}
+${tablegenned_files_on_include_dir}
+Please clean the source directory.")
+ endif()
+endif()
+
+string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE)
+
+set(LLVM_MAIN_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR})
+set(LLVM_MAIN_INCLUDE_DIR ${LLVM_MAIN_SRC_DIR}/include)
+set(LLVM_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR})
+set(LLVM_TOOLS_BINARY_DIR ${LLVM_BINARY_DIR}/bin)
+set(LLVM_EXAMPLES_BINARY_DIR ${LLVM_BINARY_DIR}/examples)
+set(LLVM_LIBDIR_SUFFIX "" CACHE STRING "Define suffix of library directory name (32/64)" )
+
+set(LLVM_ALL_TARGETS
+ ARM
+ CellSPU
+ CppBackend
+ Hexagon
+ Mips
+ MBlaze
+ MSP430
+ NVPTX
+ PowerPC
+ Sparc
+ X86
+ XCore
+ )
+
+# List of targets with JIT support:
+set(LLVM_TARGETS_WITH_JIT X86 PowerPC ARM Mips)
+
+if( MSVC )
+ set(LLVM_TARGETS_TO_BUILD X86
+ CACHE STRING "Semicolon-separated list of targets to build, or \"all\".")
+else( MSVC )
+ set(LLVM_TARGETS_TO_BUILD "all"
+ CACHE STRING "Semicolon-separated list of targets to build, or \"all\".")
+endif( MSVC )
+
+set(LLVM_EXPERIMENTAL_TARGETS_TO_BUILD ""
+ CACHE STRING "Semicolon-separated list of experimental targets to build.")
+
+option(BUILD_SHARED_LIBS
+ "Build all libraries as shared libraries instead of static" OFF)
+
+option(LLVM_ENABLE_CBE_PRINTF_A "Set to ON if CBE is enabled for printf %a output" ON)
+if(LLVM_ENABLE_CBE_PRINTF_A)
+ set(ENABLE_CBE_PRINTF_A 1)
+endif()
+
+option(LLVM_ENABLE_TIMESTAMPS "Enable embedding timestamp information in build" ON)
+if(LLVM_ENABLE_TIMESTAMPS)
+ set(ENABLE_TIMESTAMPS 1)
+endif()
+
+option(LLVM_ENABLE_FFI "Use libffi to call external functions from the interpreter" OFF)
+set(FFI_LIBRARY_DIR "" CACHE PATH "Additional directory, where CMake should search for libffi.so")
+set(FFI_INCLUDE_DIR "" CACHE PATH "Additional directory, where CMake should search for ffi.h or ffi/ffi.h")
+
+set(LLVM_TARGET_ARCH "host"
+ CACHE STRING "Set target to use for LLVM JIT or use \"host\" for automatic detection.")
+
+option(LLVM_ENABLE_THREADS "Use threads if available." ON)
+
+if( LLVM_TARGETS_TO_BUILD STREQUAL "all" )
+ set( LLVM_TARGETS_TO_BUILD ${LLVM_ALL_TARGETS} )
+endif()
+
+set(LLVM_TARGETS_TO_BUILD
+ ${LLVM_TARGETS_TO_BUILD}
+ ${LLVM_EXPERIMENTAL_TARGETS_TO_BUILD})
+
+set(LLVM_ENUM_TARGETS "")
+foreach(c ${LLVM_TARGETS_TO_BUILD})
+ list(FIND LLVM_ALL_TARGETS ${c} idx)
+ list(FIND LLVM_EXPERIMENTAL_TARGETS_TO_BUILD ${c} idy)
+ if( idx LESS 0 AND idy LESS 0 )
+ message(FATAL_ERROR "The target `${c}' does not exist.
+ It should be one of\n${LLVM_ALL_TARGETS}")
+ else()
+ set(LLVM_ENUM_TARGETS "${LLVM_ENUM_TARGETS}LLVM_TARGET(${c})\n")
+ endif()
+endforeach(c)
+
+set(llvm_builded_incs_dir ${LLVM_BINARY_DIR}/include/llvm)
+
+include(AddLLVMDefinitions)
+
+option(LLVM_ENABLE_PIC "Build Position-Independent Code" ON)
+
+# MSVC has a gazillion warnings with this.
+if( MSVC )
+ option(LLVM_ENABLE_WARNINGS "Enable compiler warnings." OFF)
+else( MSVC )
+ option(LLVM_ENABLE_WARNINGS "Enable compiler warnings." ON)
+endif()
+
+option(LLVM_ENABLE_PEDANTIC "Compile with pedantic enabled." ON)
+option(LLVM_ENABLE_WERROR "Fail and stop if a warning is triggered." OFF)
+
+if( uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE" )
+ option(LLVM_ENABLE_ASSERTIONS "Enable assertions" OFF)
+else()
+ option(LLVM_ENABLE_ASSERTIONS "Enable assertions" ON)
+endif()
+
+option(LLVM_USE_INTEL_JITEVENTS
+ "Use Intel JIT API to inform Intel(R) VTune(TM) Amplifier XE 2011 about JIT code"
+ OFF)
+
+if( LLVM_USE_INTEL_JITEVENTS )
+ # Verify we are on a supported platform
+ if( CMAKE_SYSTEM_NAME MATCHES "Windows" OR CMAKE_SYSTEM_NAME MATCHES "Linux" )
+ # Directory where Intel Parallel Amplifier XE 2011 is installed.
+ if ( WIN32 )
+ set(LLVM_INTEL_JITEVENTS_DIR $ENV{VTUNE_AMPLIFIER_XE_2011_DIR})
+ else ( WIN32 )
+ set(LLVM_INTEL_JITEVENTS_DIR "/opt/intel/vtune_amplifier_xe_2011")
+ endif ( WIN32 )
+
+ # Set include and library search paths for Intel JIT Events API
+ set(LLVM_INTEL_JITEVENTS_INCDIR "${LLVM_INTEL_JITEVENTS_DIR}/include")
+
+ if ( CMAKE_SIZEOF_VOID_P EQUAL 8 )
+ set(LLVM_INTEL_JITEVENTS_LIBDIR "${LLVM_INTEL_JITEVENTS_DIR}/lib64")
+ else ( CMAKE_SIZEOF_VOID_P EQUAL 8 )
+ set(LLVM_INTEL_JITEVENTS_LIBDIR "${LLVM_INTEL_JITEVENTS_DIR}/lib32")
+ endif ( CMAKE_SIZEOF_VOID_P EQUAL 8 )
+ else()
+ message(FATAL_ERROR
+ "Intel JIT API support is available on Linux and Windows only.")
+ endif()
+endif( LLVM_USE_INTEL_JITEVENTS )
+
+option(LLVM_USE_OPROFILE
+ "Use opagent JIT interface to inform OProfile about JIT code" OFF)
+
+# If enabled, ierify we are on a platform that supports oprofile.
+if( LLVM_USE_OPROFILE )
+ if( NOT CMAKE_SYSTEM_NAME MATCHES "Linux" )
+ message(FATAL_ERROR "OProfile support is available on Linux only.")
+ endif( NOT CMAKE_SYSTEM_NAME MATCHES "Linux" )
+endif( LLVM_USE_OPROFILE )
+
+# Define an option controlling whether we should build for 32-bit on 64-bit
+# platforms, where supported.
+if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
+ # TODO: support other platforms and toolchains.
+ option(LLVM_BUILD_32_BITS "Build 32 bits executables and libraries." OFF)
+endif()
+
+# Define the default arguments to use with 'lit', and an option for the user to
+# override.
+set(LIT_ARGS_DEFAULT "-sv")
+if (MSVC OR XCODE)
+ set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --no-progress-bar")
+endif()
+set(LLVM_LIT_ARGS "${LIT_ARGS_DEFAULT}" CACHE STRING "Default options for lit")
+
+# On Win32 hosts, provide an option to specify the path to the GnuWin32 tools.
+if( WIN32 AND NOT CYGWIN )
+ set(LLVM_LIT_TOOLS_DIR "" CACHE PATH "Path to GnuWin32 tools")
+endif()
+
+# Define options to control the inclusion and default build behavior for
+# components which may not strictly be necessary (tools, runtime, examples, and
+# tests).
+#
+# This is primarily to support building smaller or faster project files.
+option(LLVM_INCLUDE_TOOLS "Generate build targets for the LLVM tools." ON)
+option(LLVM_BUILD_TOOLS
+ "Build the LLVM tools. If OFF, just generate build targets." ON)
+
+option(LLVM_INCLUDE_RUNTIME "Generate build targets for the LLVM runtimes" ON)
+option(LLVM_BUILD_RUNTIME
+ "Build the LLVM runtime libraries. If OFF, just generate build targets." ON)
+
+option(LLVM_BUILD_EXAMPLES
+ "Build the LLVM example programs. If OFF, just generate build targets." OFF)
+option(LLVM_INCLUDE_EXAMPLES "Generate build targets for the LLVM examples" ON)
+
+option(LLVM_BUILD_TESTS
+ "Build LLVM unit tests. If OFF, just generate build targets." OFF)
+option(LLVM_INCLUDE_TESTS "Generate build targets for the LLVM unit tests." ON)
+
+# All options referred to from HandleLLVMOptions have to be specified
+# BEFORE this include, otherwise options will not be correctly set on
+# first cmake run
+include(config-ix)
+
+# By default, we target the host, but this can be overridden at CMake
+# invocation time.
+set(LLVM_DEFAULT_TARGET_TRIPLE "${LLVM_HOST_TRIPLE}" CACHE STRING
+ "Default target for which LLVM will generate code." )
+set(TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}" CACHE STRING
+ "Default target for which LLVM will generate code." )
+
+include(HandleLLVMOptions)
+
+# Verify that we can find a Python interpreter,
+include(FindPythonInterp)
+if( NOT PYTHONINTERP_FOUND )
+ message(FATAL_ERROR
+"Unable to find Python interpreter, required for builds and testing.
+
+Please install Python or specify the PYTHON_EXECUTABLE CMake variable.")
+endif()
+
+######
+# LLVMBuild Integration
+#
+# We use llvm-build to generate all the data required by the CMake based
+# build system in one swoop:
+#
+# - We generate a file (a CMake fragment) in the object root which contains
+# all the definitions that are required by CMake.
+#
+# - We generate the library table used by llvm-config.
+#
+# - We generate the dependencies for the CMake fragment, so that we will
+# automatically reconfigure outselves.
+
+set(LLVMBUILDTOOL "${LLVM_MAIN_SRC_DIR}/utils/llvm-build/llvm-build")
+set(LLVMCONFIGLIBRARYDEPENDENCIESINC
+ "${LLVM_BINARY_DIR}/tools/llvm-config/LibraryDependencies.inc")
+set(LLVMBUILDCMAKEFRAG
+ "${LLVM_BINARY_DIR}/LLVMBuild.cmake")
+
+# Create the list of optional components that are enabled
+if (LLVM_USE_INTEL_JITEVENTS)
+ set(LLVMOPTIONALCOMPONENTS IntelJITEvents)
+endif (LLVM_USE_INTEL_JITEVENTS)
+if (LLVM_USE_OPROFILE)
+ set(LLVMOPTIONALCOMPONENTS ${LLVMOPTIONALCOMPONENTS} OProfileJIT)
+endif (LLVM_USE_OPROFILE)
+
+message(STATUS "Constructing LLVMBuild project information")
+execute_process(
+ COMMAND ${PYTHON_EXECUTABLE} ${LLVMBUILDTOOL}
+ --native-target "${LLVM_NATIVE_ARCH}"
+ --enable-targets "${LLVM_TARGETS_TO_BUILD}"
+ --enable-optional-components "${LLVMOPTIONALCOMPONENTS}"
+ --write-library-table ${LLVMCONFIGLIBRARYDEPENDENCIESINC}
+ --write-cmake-fragment ${LLVMBUILDCMAKEFRAG}
+ ERROR_VARIABLE LLVMBUILDOUTPUT
+ ERROR_VARIABLE LLVMBUILDERRORS
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ ERROR_STRIP_TRAILING_WHITESPACE
+ RESULT_VARIABLE LLVMBUILDRESULT)
+
+# On Win32, CMake doesn't properly handle piping the default output/error
+# streams into the GUI console. So, we explicitly catch and report them.
+if( NOT "${LLVMBUILDOUTPUT}" STREQUAL "")
+ message(STATUS "llvm-build output: ${LLVMBUILDOUTPUT}")
+endif()
+if( NOT "${LLVMBUILDRESULT}" STREQUAL "0" )
+ message(FATAL_ERROR
+ "Unexpected failure executing llvm-build: ${LLVMBUILDERRORS}")
+endif()
+
+# Include the generated CMake fragment. This will define properties from the
+# LLVMBuild files in a format which is easy to consume from CMake, and will add
+# the dependencies so that CMake will reconfigure properly when the LLVMBuild
+# files change.
+include(${LLVMBUILDCMAKEFRAG})
+
+######
+
+# Configure all of the various header file fragments LLVM uses which depend on
+# configuration variables.
+set(LLVM_ENUM_ASM_PRINTERS "")
+set(LLVM_ENUM_ASM_PARSERS "")
+set(LLVM_ENUM_DISASSEMBLERS "")
+foreach(t ${LLVM_TARGETS_TO_BUILD})
+ set( td ${LLVM_MAIN_SRC_DIR}/lib/Target/${t} )
+ file(GLOB asmp_file "${td}/*AsmPrinter.cpp")
+ if( asmp_file )
+ set(LLVM_ENUM_ASM_PRINTERS
+ "${LLVM_ENUM_ASM_PRINTERS}LLVM_ASM_PRINTER(${t})\n")
+ endif()
+ if( EXISTS ${td}/AsmParser/CMakeLists.txt )
+ set(LLVM_ENUM_ASM_PARSERS
+ "${LLVM_ENUM_ASM_PARSERS}LLVM_ASM_PARSER(${t})\n")
+ endif()
+ if( EXISTS ${td}/Disassembler/CMakeLists.txt )
+ set(LLVM_ENUM_DISASSEMBLERS
+ "${LLVM_ENUM_DISASSEMBLERS}LLVM_DISASSEMBLER(${t})\n")
+ endif()
+endforeach(t)
+
+# Produce the target definition files, which provide a way for clients to easily
+# include various classes of targets.
+configure_file(
+ ${LLVM_MAIN_INCLUDE_DIR}/llvm/Config/AsmPrinters.def.in
+ ${LLVM_BINARY_DIR}/include/llvm/Config/AsmPrinters.def
+ )
+configure_file(
+ ${LLVM_MAIN_INCLUDE_DIR}/llvm/Config/AsmParsers.def.in
+ ${LLVM_BINARY_DIR}/include/llvm/Config/AsmParsers.def
+ )
+configure_file(
+ ${LLVM_MAIN_INCLUDE_DIR}/llvm/Config/Disassemblers.def.in
+ ${LLVM_BINARY_DIR}/include/llvm/Config/Disassemblers.def
+ )
+configure_file(
+ ${LLVM_MAIN_INCLUDE_DIR}/llvm/Config/Targets.def.in
+ ${LLVM_BINARY_DIR}/include/llvm/Config/Targets.def
+ )
+
+# Configure the three LLVM configuration header files.
+configure_file(
+ ${LLVM_MAIN_INCLUDE_DIR}/llvm/Config/config.h.cmake
+ ${LLVM_BINARY_DIR}/include/llvm/Config/config.h)
+configure_file(
+ ${LLVM_MAIN_INCLUDE_DIR}/llvm/Config/llvm-config.h.cmake
+ ${LLVM_BINARY_DIR}/include/llvm/Config/llvm-config.h)
+configure_file(
+ ${LLVM_MAIN_INCLUDE_DIR}/llvm/Support/DataTypes.h.cmake
+ ${LLVM_BINARY_DIR}/include/llvm/Support/DataTypes.h)
+
+set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LLVM_TOOLS_BINARY_DIR} )
+set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${LLVM_BINARY_DIR}/lib )
+set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LLVM_BINARY_DIR}/lib )
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+
+include_directories( ${LLVM_BINARY_DIR}/include ${LLVM_MAIN_INCLUDE_DIR})
+
+if( ${CMAKE_SYSTEM_NAME} MATCHES SunOS )
+ SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -include llvm/Support/Solaris.h")
+endif( ${CMAKE_SYSTEM_NAME} MATCHES SunOS )
+
+include(AddLLVM)
+include(TableGen)
+
+if( MINGW )
+ # People report that -O3 is unreliable on MinGW. The traditional
+ # build also uses -O2 for that reason:
+ llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELEASE "-O3" "-O2")
+endif()
+
+# Put this before tblgen. Else we have a circular dependence.
+add_subdirectory(lib/Support)
+add_subdirectory(lib/TableGen)
+
+add_subdirectory(utils/TableGen)
+
+add_subdirectory(include/llvm)
+
+add_subdirectory(lib)
+
+add_subdirectory(utils/FileCheck)
+add_subdirectory(utils/FileUpdate)
+add_subdirectory(utils/count)
+add_subdirectory(utils/not)
+add_subdirectory(utils/llvm-lit)
+add_subdirectory(utils/yaml-bench)
+add_subdirectory(utils/obj2yaml)
+add_subdirectory(utils/yaml2obj)
+
+add_subdirectory(projects)
+
+if( LLVM_INCLUDE_TOOLS )
+ add_subdirectory(tools)
+endif()
+
+if( LLVM_INCLUDE_RUNTIME )
+ add_subdirectory(runtime)
+endif()
+
+if( LLVM_INCLUDE_EXAMPLES )
+ add_subdirectory(examples)
+endif()
+
+if( LLVM_INCLUDE_TESTS )
+ add_subdirectory(test)
+ add_subdirectory(utils/unittest)
+ add_subdirectory(unittests)
+ if (MSVC)
+ # This utility is used to prevent chrashing tests from calling Dr. Watson on
+ # Windows.
+ add_subdirectory(utils/KillTheDoctor)
+ endif()
+
+ # Add a global check rule now that all subdirectories have been traversed
+ # and we know the total set of lit testsuites.
+ get_property(LLVM_LIT_TESTSUITES GLOBAL PROPERTY LLVM_LIT_TESTSUITES)
+ get_property(LLVM_LIT_PARAMS GLOBAL PROPERTY LLVM_LIT_PARAMS)
+ get_property(LLVM_LIT_DEPENDS GLOBAL PROPERTY LLVM_LIT_DEPENDS)
+ get_property(LLVM_LIT_EXTRA_ARGS GLOBAL PROPERTY LLVM_LIT_EXTRA_ARGS)
+ add_lit_target(check-all
+ "Running all regression tests"
+ ${LLVM_LIT_TESTSUITES}
+ PARAMS ${LLVM_LIT_PARAMS}
+ DEPENDS ${LLVM_LIT_DEPENDS}
+ ARGS ${LLVM_LIT_EXTRA_ARGS}
+ )
+endif()
+
+add_subdirectory(cmake/modules)
+
+install(DIRECTORY include/
+ DESTINATION include
+ FILES_MATCHING
+ PATTERN "*.def"
+ PATTERN "*.h"
+ PATTERN "*.td"
+ PATTERN "*.inc"
+ PATTERN "LICENSE.TXT"
+ PATTERN ".svn" EXCLUDE
+ )
+
+install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/include/
+ DESTINATION include
+ FILES_MATCHING
+ PATTERN "*.def"
+ PATTERN "*.h"
+ PATTERN "*.gen"
+ PATTERN "*.inc"
+ # Exclude include/llvm/CMakeFiles/intrinsics_gen.dir, matched by "*.def"
+ PATTERN "CMakeFiles" EXCLUDE
+ PATTERN ".svn" EXCLUDE
+ )
+
+# TODO: make and install documentation.
+
+set(CPACK_PACKAGE_VENDOR "LLVM")
+set(CPACK_PACKAGE_VERSION_MAJOR ${LLVM_VERSION_MAJOR})
+set(CPACK_PACKAGE_VERSION_MINOR ${LLVM_VERSION_MINOR})
+add_version_info_from_vcs(CPACK_PACKAGE_VERSION_PATCH)
+include(CPack)
+
+# Workaround for MSVS10 to avoid the Dialog Hell
+# FIXME: This could be removed with future version of CMake.
+if(MSVC_VERSION EQUAL 1600)
+ set(LLVM_SLN_FILENAME "${CMAKE_CURRENT_BINARY_DIR}/LLVM.sln")
+ if( EXISTS "${LLVM_SLN_FILENAME}" )
+ file(APPEND "${LLVM_SLN_FILENAME}" "\n# This should be regenerated!\n")
+ endif()
+endif()
diff --git a/CODE_OWNERS.TXT b/CODE_OWNERS.TXT
new file mode 100644
index 00000000000..fd7bcda3b76
--- /dev/null
+++ b/CODE_OWNERS.TXT
@@ -0,0 +1,51 @@
+This file is a list of the people responsible for ensuring that patches for a
+particular part of LLVM are reviewed, either by themself or by someone else.
+They are also the gatekeepers for their part of LLVM, with the final word on
+what goes in or not.
+
+The list is sorted by surname and formatted to allow easy grepping and
+beautification by scripts. The fields are: name (N), email (E), web-address
+(W), PGP key ID and fingerprint (P), description (D), and snail-mail address
+(S).
+
+N: Evan Cheng
+E: evan.cheng@apple.com
+D: Code generator and all targets
+
+N: Greg Clayton
+D: LLDB
+
+N: Peter Collingbourne
+D: libclc
+
+N: Doug Gregor
+D: Clang Frontend Libraries
+
+N: Tobias Grosser
+D: Polly
+
+N: Howard Hinnant
+D: libc++
+
+N: Anton Korobeynikov
+E: asl@math.spbu.ru
+D: Exception handling, debug information, and Windows codegen
+
+N: Ted Kremenek
+D: Clang Static Analyzer
+
+N: Chris Lattner
+E: sabre@nondot.org
+W: http://nondot.org/~sabre/
+D: Everything not covered by someone else
+
+N: John McCall
+E: rjmccall@apple.com
+D: Clang LLVM IR generation
+
+N: Jakob Olesen
+D: Register allocators and TableGen
+
+N: Duncan Sands
+E: baldrick@free.fr
+D: DragonEgg
diff --git a/CREDITS.TXT b/CREDITS.TXT
new file mode 100644
index 00000000000..b5aa2580e14
--- /dev/null
+++ b/CREDITS.TXT
@@ -0,0 +1,425 @@
+This file is a partial list of people who have contributed to the LLVM
+project. If you have contributed a patch or made some other contribution to
+LLVM, please submit a patch to this file to add yourself, and it will be
+done!
+
+The list is sorted by surname and formatted to allow easy grepping and
+beautification by scripts. The fields are: name (N), email (E), web-address
+(W), PGP key ID and fingerprint (P), description (D), snail-mail address
+(S), and (I) IRC handle.
+
+
+N: Vikram Adve
+E: vadve@cs.uiuc.edu
+W: http://www.cs.uiuc.edu/~vadve/
+D: The Sparc64 backend, provider of much wisdom, and motivator for LLVM
+
+N: Owen Anderson
+E: resistor@mac.com
+D: LCSSA pass and related LoopUnswitch work
+D: GVNPRE pass, TargetData refactoring, random improvements
+
+N: Henrik Bach
+D: MingW Win32 API portability layer
+
+N: Aaron Ballman
+E: aaron@aaronballman.com
+D: __declspec attributes, Windows support, general bug fixing
+
+N: Nate Begeman
+E: natebegeman@mac.com
+D: PowerPC backend developer
+D: Target-independent code generator and analysis improvements
+
+N: Daniel Berlin
+E: dberlin@dberlin.org
+D: ET-Forest implementation.
+D: Sparse bitmap
+
+N: David Blaikie
+E: dblaikie@gmail.com
+D: General bug fixing/fit & finish, mostly in Clang
+
+N: Neil Booth
+E: neil@daikokuya.co.uk
+D: APFloat implementation.
+
+N: Misha Brukman
+E: brukman+llvm@uiuc.edu
+W: http://misha.brukman.net
+D: Portions of X86 and Sparc JIT compilers, PowerPC backend
+D: Incremental bitcode loader
+
+N: Cameron Buschardt
+E: buschard@uiuc.edu
+D: The `mem2reg' pass - promotes values stored in memory to registers
+
+N: Brendon Cahoon
+E: bcahoon@codeaurora.org
+D: Loop unrolling with run-time trip counts.
+
+N: Chandler Carruth
+E: chandlerc@gmail.com
+D: Hashing algorithms and interfaces
+D: Inline cost analysis
+D: Machine block placement pass
+
+N: Casey Carter
+E: ccarter@uiuc.edu
+D: Fixes to the Reassociation pass, various improvement patches
+
+N: Evan Cheng
+E: evan.cheng@apple.com
+D: ARM and X86 backends
+D: Instruction scheduler improvements
+D: Register allocator improvements
+D: Loop optimizer improvements
+D: Target-independent code generator improvements
+
+N: Dan Villiom Podlaski Christiansen
+E: danchr@gmail.com
+E: danchr@cs.au.dk
+W: http://villiom.dk
+D: LLVM Makefile improvements
+D: Clang diagnostic & driver tweaks
+S: Aarhus, Denmark
+
+N: Jeff Cohen
+E: jeffc@jolt-lang.org
+W: http://jolt-lang.org
+D: Native Win32 API portability layer
+
+N: John T. Criswell
+E: criswell@uiuc.edu
+D: Original Autoconf support, documentation improvements, bug fixes
+
+N: Anshuman Dasgupta
+E: adasgupt@codeaurora.org
+D: Deterministic finite automaton based infrastructure for VLIW packetization
+
+N: Stefanus Du Toit
+E: stefanus.dutoit@rapidmind.com
+D: Bug fixes and minor improvements
+
+N: Rafael Avila de Espindola
+E: rafael.espindola@gmail.com
+D: The ARM backend
+
+N: Alkis Evlogimenos
+E: alkis@evlogimenos.com
+D: Linear scan register allocator, many codegen improvements, Java frontend
+
+N: Hal Finkel
+E: hfinkel@anl.gov
+D: Basic-block autovectorization, PowerPC backend improvements
+
+N: Ryan Flynn
+E: pizza@parseerror.com
+D: Miscellaneous bug fixes
+
+N: Brian Gaeke
+E: gaeke@uiuc.edu
+W: http://www.students.uiuc.edu/~gaeke/
+D: Portions of X86 static and JIT compilers; initial SparcV8 backend
+D: Dynamic trace optimizer
+D: FreeBSD/X86 compatibility fixes, the llvm-nm tool
+
+N: Nicolas Geoffray
+E: nicolas.geoffray@lip6.fr
+W: http://www-src.lip6.fr/homepages/Nicolas.Geoffray/
+D: PPC backend fixes for Linux
+
+N: Louis Gerbarg
+D: Portions of the PowerPC backend
+
+N: Saem Ghani
+E: saemghani@gmail.com
+D: Callgraph class cleanups
+
+N: Mikhail Glushenkov
+E: foldr@codedgers.com
+D: Author of llvmc2
+
+N: Dan Gohman
+E: gohman@apple.com
+D: Miscellaneous bug fixes
+
+N: David Goodwin
+E: david@goodwinz.net
+D: Thumb-2 code generator
+
+N: David Greene
+E: greened@obbligato.org
+D: Miscellaneous bug fixes
+D: Register allocation refactoring
+
+N: Gabor Greif
+E: ggreif@gmail.com
+D: Improvements for space efficiency
+
+N: James Grosbach
+E: grosbach@apple.com
+D: SjLj exception handling support
+D: General fixes and improvements for the ARM back-end
+D: MCJIT
+D: ARM integrated assembler and assembly parser
+
+N: Lang Hames
+E: lhames@gmail.com
+D: PBQP-based register allocator
+
+N: Gordon Henriksen
+E: gordonhenriksen@mac.com
+D: Pluggable GC support
+D: C interface
+D: Ocaml bindings
+
+N: Raul Fernandes Herbster
+E: raul@dsc.ufcg.edu.br
+D: JIT support for ARM
+
+N: Paolo Invernizzi
+E: arathorn@fastwebnet.it
+D: Visual C++ compatibility fixes
+
+N: Patrick Jenkins
+E: patjenk@wam.umd.edu
+D: Nightly Tester
+
+N: Dale Johannesen
+E: dalej@apple.com
+D: ARM constant islands improvements
+D: Tail merging improvements
+D: Rewrite X87 back end
+D: Use APFloat for floating point constants widely throughout compiler
+D: Implement X87 long double
+
+N: Brad Jones
+E: kungfoomaster@nondot.org
+D: Support for packed types
+
+N: Rod Kay
+E: rkay@auroraux.org
+D: Author of LLVM Ada bindings
+
+N: Eric Kidd
+W: http://randomhacks.net/
+D: llvm-config script
+
+N: Anton Korobeynikov
+E: asl@math.spbu.ru
+D: Mingw32 fixes, cross-compiling support, stdcall/fastcall calling conv.
+D: x86/linux PIC codegen, aliases, regparm/visibility attributes
+D: Switch lowering refactoring
+
+N: Sumant Kowshik
+E: kowshik@uiuc.edu
+D: Author of the original C backend
+
+N: Benjamin Kramer
+E: benny.kra@gmail.com
+D: Miscellaneous bug fixes
+
+N: Sundeep Kushwaha
+E: sundeepk@codeaurora.org
+D: Implemented DFA-based target independent VLIW packetizer
+
+N: Christopher Lamb
+E: christopher.lamb@gmail.com
+D: aligned load/store support, parts of noalias and restrict support
+D: vreg subreg infrastructure, X86 codegen improvements based on subregs
+D: address spaces
+
+N: Jim Laskey
+E: jlaskey@apple.com
+D: Improvements to the PPC backend, instruction scheduling
+D: Debug and Dwarf implementation
+D: Auto upgrade mangler
+D: llvm-gcc4 svn wrangler
+
+N: Chris Lattner
+E: sabre@nondot.org
+W: http://nondot.org/~sabre/
+D: Primary architect of LLVM
+
+N: Tanya Lattner (Tanya Brethour)
+E: tonic@nondot.org
+W: http://nondot.org/~tonic/
+D: The initial llvm-ar tool, converted regression testsuite to dejagnu
+D: Modulo scheduling in the SparcV9 backend
+D: Release manager (1.7+)
+
+N: Andrew Lenharth
+E: alenhar2@cs.uiuc.edu
+W: http://www.lenharth.org/~andrewl/
+D: Alpha backend
+D: Sampling based profiling
+
+N: Nick Lewycky
+E: nicholas@mxc.ca
+D: PredicateSimplifier pass
+
+N: Tony Linthicum, et. al.
+E: tlinth@codeaurora.org
+D: Backend for Qualcomm's Hexagon VLIW processor.
+
+N: Bruno Cardoso Lopes
+E: bruno.cardoso@gmail.com
+W: http://www.brunocardoso.org
+D: The Mips backend
+
+N: Duraid Madina
+E: duraid@octopus.com.au
+W: http://kinoko.c.u-tokyo.ac.jp/~duraid/
+D: IA64 backend, BigBlock register allocator
+
+N: John McCall
+E: rjmccall@apple.com
+D: Clang semantic analysis and IR generation
+
+N: Michael McCracken
+E: michael.mccracken@gmail.com
+D: Line number support for llvmgcc
+
+N: Vladimir Merzliakov
+E: wanderer@rsu.ru
+D: Test suite fixes for FreeBSD
+
+N: Scott Michel
+E: scottm@aero.org
+D: Added STI Cell SPU backend.
+
+N: Kai Nacke
+E: kai@redstar.de
+D: Support for implicit TLS model used with MS VC runtime
+
+N: Takumi Nakamura
+E: geek4civic@gmail.com
+E: chapuni@hf.rim.or.jp
+D: Cygwin and MinGW support.
+D: Win32 tweaks.
+S: Yokohama, Japan
+
+N: Edward O'Callaghan
+E: eocallaghan@auroraux.org
+W: http://www.auroraux.org
+D: Add Clang support with various other improvements to utils/NewNightlyTest.pl
+D: Fix and maintain Solaris & AuroraUX support for llvm, various build warnings
+D: and error clean ups.
+
+N: Morten Ofstad
+E: morten@hue.no
+D: Visual C++ compatibility fixes
+
+N: Jakob Stoklund Olesen
+E: stoklund@2pi.dk
+D: Machine code verifier
+D: Blackfin backend
+D: Fast register allocator
+D: Greedy register allocator
+
+N: Richard Osborne
+E: richard@xmos.com
+D: XCore backend
+
+N: Devang Patel
+E: dpatel@apple.com
+D: LTO tool, PassManager rewrite, Loop Pass Manager, Loop Rotate
+D: GCC PCH Integration (llvm-gcc), llvm-gcc improvements
+D: Optimizer improvements, Loop Index Split
+
+N: Wesley Peck
+E: peckw@wesleypeck.com
+W: http://wesleypeck.com/
+D: MicroBlaze backend
+
+N: Francois Pichet
+E: pichet2000@gmail.com
+D: MSVC support
+
+N: Vladimir Prus
+W: http://vladimir_prus.blogspot.com
+E: ghost@cs.msu.su
+D: Made inst_iterator behave like a proper iterator, LowerConstantExprs pass
+
+N: Kalle Raiskila
+E: kalle.rasikila@nokia.com
+D: Some bugfixes to CellSPU
+
+N: Xerxes Ranby
+E: xerxes@zafena.se
+D: Cmake dependency chain and various bug fixes
+
+N: Alex Rosenberg
+E: alexr@leftfield.org
+I: arosenberg
+D: ARM calling conventions rewrite, hard float support
+
+N: Chad Rosier
+E: mcrosier@apple.com
+D: ARM fast-isel improvements
+D: Performance monitoring
+
+N: Nadav Rotem
+E: nadav.rotem@intel.com
+D: Vector code generation improvements.
+
+N: Roman Samoilov
+E: roman@codedgers.com
+D: MSIL backend
+
+N: Duncan Sands
+E: baldrick@free.fr
+I: baldrick
+D: Ada support in llvm-gcc
+D: Dragonegg plugin
+D: Exception handling improvements
+D: Type legalizer rewrite
+
+N: Ruchira Sasanka
+E: sasanka@uiuc.edu
+D: Graph coloring register allocator for the Sparc64 backend
+
+N: Arnold Schwaighofer
+E: arnold.schwaighofer@gmail.com
+D: Tail call optimization for the x86 backend
+
+N: Shantonu Sen
+E: ssen@apple.com
+D: Miscellaneous bug fixes
+
+N: Anand Shukla
+E: ashukla@cs.uiuc.edu
+D: The `paths' pass
+
+N: Michael J. Spencer
+E: bigcheesegs@gmail.com
+D: Shepherding Windows COFF support into MC.
+D: Lots of Windows stuff.
+
+N: Reid Spencer
+E: rspencer@reidspencer.com
+W: http://reidspencer.com/
+D: Lots of stuff, see: http://wiki.llvm.org/index.php/User:Reid
+
+N: Edwin Torok
+E: edwintorok@gmail.com
+D: Miscellaneous bug fixes
+
+N: Adam Treat
+E: manyoso@yahoo.com
+D: C++ bugs filed, and C++ front-end bug fixes.
+
+N: Lauro Ramos Venancio
+E: lauro.venancio@indt.org.br
+D: ARM backend improvements
+D: Thread Local Storage implementation
+
+N: Bill Wendling
+E: wendling@apple.com
+D: Exception handling
+D: Bunches of stuff
+
+N: Bob Wilson
+E: bob.wilson@acm.org
+D: Advanced SIMD (NEON) support in the ARM backend
diff --git a/LICENSE.TXT b/LICENSE.TXT
new file mode 100644
index 00000000000..00cf6011694
--- /dev/null
+++ b/LICENSE.TXT
@@ -0,0 +1,70 @@
+==============================================================================
+LLVM Release License
+==============================================================================
+University of Illinois/NCSA
+Open Source License
+
+Copyright (c) 2003-2012 University of Illinois at Urbana-Champaign.
+All rights reserved.
+
+Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal with
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+SOFTWARE.
+
+==============================================================================
+Copyrights and Licenses for Third Party Software Distributed with LLVM:
+==============================================================================
+The LLVM software contains code written by third parties. Such software will
+have its own individual LICENSE.TXT file in the directory in which it appears.
+This file will describe the copyrights, license, and restrictions which apply
+to that code.
+
+The disclaimer of warranty in the University of Illinois Open Source License
+applies to all code in the LLVM Distribution, and nothing in any of the
+other licenses gives permission to use the names of the LLVM Team or the
+University of Illinois to endorse or promote products derived from this
+Software.
+
+The following pieces of software have additional or alternate copyrights,
+licenses, and/or restrictions:
+
+Program Directory
+------- ---------
+Autoconf llvm/autoconf
+ llvm/projects/ModuleMaker/autoconf
+ llvm/projects/sample/autoconf
+CellSPU backend llvm/lib/Target/CellSPU/README.txt
+Google Test llvm/utils/unittest/googletest
+OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}
+pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}
diff --git a/LLVMBuild.txt b/LLVMBuild.txt
new file mode 100644
index 00000000000..e763fd2afee
--- /dev/null
+++ b/LLVMBuild.txt
@@ -0,0 +1,24 @@
+;===- ./LLVMBuild.txt ------------------------------------------*- Conf -*--===;
+;
+; The LLVM Compiler Infrastructure
+;
+; This file is distributed under the University of Illinois Open Source
+; License. See LICENSE.TXT for details.
+;
+;===------------------------------------------------------------------------===;
+;
+; This is an LLVMBuild description file for the components in this subdirectory.
+;
+; For more information on the LLVMBuild system, please see:
+;
+; http://llvm.org/docs/LLVMBuild.html
+;
+;===------------------------------------------------------------------------===;
+
+[common]
+subdirectories = bindings docs examples lib projects runtime tools utils
+
+[component_0]
+type = Group
+name = Miscellaneous
+parent = $ROOT
diff --git a/Makefile b/Makefile
new file mode 100644
index 00000000000..a935df469c6
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,269 @@
+#===- ./Makefile -------------------------------------------*- Makefile -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+
+LEVEL := .
+
+# Top-Level LLVM Build Stages:
+# 1. Build lib/Support and lib/TableGen, which are used by utils (tblgen).
+# 2. Build utils, which is used by VMCore.
+# 3. Build VMCore, which builds the Intrinsics.inc file used by libs.
+# 4. Build libs, which are needed by llvm-config.
+# 5. Build llvm-config, which determines inter-lib dependencies for tools.
+# 6. Build tools, runtime, docs.
+#
+# When cross-compiling, there are some things (tablegen) that need to
+# be build for the build system first.
+
+# If "RC_ProjectName" exists in the environment, and its value is
+# "llvmCore", then this is an "Apple-style" build; search for
+# "Apple-style" in the comments for more info. Anything else is a
+# normal build.
+ifneq ($(findstring llvmCore, $(RC_ProjectName)),llvmCore) # Normal build (not "Apple-style").
+
+ifeq ($(BUILD_DIRS_ONLY),1)
+ DIRS := lib/Support lib/TableGen utils tools/llvm-config
+ OPTIONAL_DIRS := tools/clang/utils/TableGen
+else
+ DIRS := lib/Support lib/TableGen utils lib/VMCore lib tools/llvm-shlib \
+ tools/llvm-config tools runtime docs unittests
+ OPTIONAL_DIRS := projects bindings
+endif
+
+ifeq ($(BUILD_EXAMPLES),1)
+ OPTIONAL_DIRS += examples
+endif
+
+EXTRA_DIST := test unittests llvm.spec include win32 Xcode
+
+include $(LEVEL)/Makefile.config
+
+ifneq ($(ENABLE_SHARED),1)
+ DIRS := $(filter-out tools/llvm-shlib, $(DIRS))
+endif
+
+ifneq ($(ENABLE_DOCS),1)
+ DIRS := $(filter-out docs, $(DIRS))
+endif
+
+ifeq ($(MAKECMDGOALS),libs-only)
+ DIRS := $(filter-out tools runtime docs, $(DIRS))
+ OPTIONAL_DIRS :=
+endif
+
+ifeq ($(MAKECMDGOALS),install-libs)
+ DIRS := $(filter-out tools runtime docs, $(DIRS))
+ OPTIONAL_DIRS := $(filter bindings, $(OPTIONAL_DIRS))
+endif
+
+ifeq ($(MAKECMDGOALS),tools-only)
+ DIRS := $(filter-out runtime docs, $(DIRS))
+ OPTIONAL_DIRS :=
+endif
+
+ifeq ($(MAKECMDGOALS),install-clang)
+ DIRS := tools/clang/tools/driver tools/clang/lib/Headers \
+ tools/clang/tools/libclang tools/clang/tools/c-index-test \
+ tools/clang/include/clang-c \
+ tools/clang/runtime tools/clang/docs \
+ tools/lto runtime
+ OPTIONAL_DIRS :=
+ NO_INSTALL = 1
+endif
+
+ifeq ($(MAKECMDGOALS),clang-only)
+ DIRS := $(filter-out tools docs unittests, $(DIRS)) \
+ tools/clang tools/lto
+ OPTIONAL_DIRS :=
+endif
+
+ifeq ($(MAKECMDGOALS),unittests)
+ DIRS := $(filter-out tools runtime docs, $(DIRS)) utils unittests
+ OPTIONAL_DIRS :=
+endif
+
+# Use NO_INSTALL define of the Makefile of each directory for deciding
+# if the directory is installed or not
+ifeq ($(MAKECMDGOALS),install)
+ OPTIONAL_DIRS := $(filter bindings, $(OPTIONAL_DIRS))
+endif
+
+# Don't build unittests when ONLY_TOOLS is set.
+ifneq ($(ONLY_TOOLS),)
+ DIRS := $(filter-out unittests, $(DIRS))
+endif
+
+# If we're cross-compiling, build the build-hosted tools first
+ifeq ($(LLVM_CROSS_COMPILING),1)
+all:: cross-compile-build-tools
+
+clean::
+ $(Verb) rm -rf BuildTools
+
+cross-compile-build-tools:
+ $(Verb) if [ ! -f BuildTools/Makefile ]; then \
+ $(MKDIR) BuildTools; \
+ cd BuildTools ; \
+ unset CFLAGS ; \
+ unset CXXFLAGS ; \
+ unset SDKROOT ; \
+ $(PROJ_SRC_DIR)/configure --build=$(BUILD_TRIPLE) \
+ --host=$(BUILD_TRIPLE) --target=$(BUILD_TRIPLE) \
+ --disable-polly ; \
+ cd .. ; \
+ fi; \
+ (unset SDKROOT; \
+ $(MAKE) -C BuildTools \
+ BUILD_DIRS_ONLY=1 \
+ UNIVERSAL= \
+ TARGET_NATIVE_ARCH="$(TARGET_NATIVE_ARCH)" \
+ TARGETS_TO_BUILD="$(TARGETS_TO_BUILD)" \
+ ENABLE_OPTIMIZED=$(ENABLE_OPTIMIZED) \
+ ENABLE_PROFILING=$(ENABLE_PROFILING) \
+ ENABLE_COVERAGE=$(ENABLE_COVERAGE) \
+ DISABLE_ASSERTIONS=$(DISABLE_ASSERTIONS) \
+ ENABLE_EXPENSIVE_CHECKS=$(ENABLE_EXPENSIVE_CHECKS) \
+ ENABLE_LIBCPP=$(ENABLE_LIBCPP) \
+ CFLAGS= \
+ CXXFLAGS= \
+ ) || exit 1;
+endif
+
+# Include the main makefile machinery.
+include $(LLVM_SRC_ROOT)/Makefile.rules
+
+# Specify options to pass to configure script when we're
+# running the dist-check target
+DIST_CHECK_CONFIG_OPTIONS = --with-llvmgccdir=$(LLVMGCCDIR)
+
+.PHONY: debug-opt-prof
+debug-opt-prof:
+ $(Echo) Building Debug Version
+ $(Verb) $(MAKE)
+ $(Echo)
+ $(Echo) Building Optimized Version
+ $(Echo)
+ $(Verb) $(MAKE) ENABLE_OPTIMIZED=1
+ $(Echo)
+ $(Echo) Building Profiling Version
+ $(Echo)
+ $(Verb) $(MAKE) ENABLE_PROFILING=1
+
+dist-hook::
+ $(Echo) Eliminating files constructed by configure
+ $(Verb) $(RM) -f \
+ $(TopDistDir)/include/llvm/Config/config.h \
+ $(TopDistDir)/include/llvm/Support/DataTypes.h
+
+clang-only: all
+tools-only: all
+libs-only: all
+install-clang: install
+install-libs: install
+
+# If SHOW_DIAGNOSTICS is enabled, clear the diagnostics file first.
+ifeq ($(SHOW_DIAGNOSTICS),1)
+clean-diagnostics:
+ $(Verb) rm -f $(LLVM_OBJ_ROOT)/$(BuildMode)/diags
+.PHONY: clean-diagnostics
+
+all-local:: clean-diagnostics
+endif
+
+#------------------------------------------------------------------------
+# Make sure the generated files are up-to-date. This must be kept in
+# sync with the AC_CONFIG_HEADER and AC_CONFIG_FILE invocations in
+# autoconf/configure.ac.
+# Note that Makefile.config is covered by its own separate rule
+# in Makefile.rules where it can be reused by sub-projects.
+#------------------------------------------------------------------------
+FilesToConfig := \
+ bindings/ocaml/llvm/META.llvm \
+ docs/doxygen.cfg \
+ llvm.spec \
+ include/llvm/Config/config.h \
+ include/llvm/Config/llvm-config.h \
+ include/llvm/Config/Targets.def \
+ include/llvm/Config/AsmPrinters.def \
+ include/llvm/Config/AsmParsers.def \
+ include/llvm/Config/Disassemblers.def \
+ include/llvm/Support/DataTypes.h
+FilesToConfigPATH := $(addprefix $(LLVM_OBJ_ROOT)/,$(FilesToConfig))
+
+all-local:: $(FilesToConfigPATH)
+$(FilesToConfigPATH) : $(LLVM_OBJ_ROOT)/% : $(LLVM_SRC_ROOT)/%.in
+ $(Echo) Regenerating $*
+ $(Verb) cd $(LLVM_OBJ_ROOT) && $(ConfigStatusScript) $*
+.PRECIOUS: $(FilesToConfigPATH)
+
+# NOTE: This needs to remain as the last target definition in this file so
+# that it gets executed last.
+ifneq ($(BUILD_DIRS_ONLY),1)
+all::
+ $(Echo) '*****' Completed $(BuildMode) Build
+ifneq ($(ENABLE_OPTIMIZED),1)
+ $(Echo) '*****' Note: Debug build can be 10 times slower than an
+ $(Echo) '*****' optimized build. Use 'make ENABLE_OPTIMIZED=1' to
+ $(Echo) '*****' make an optimized build. Alternatively you can
+ $(Echo) '*****' configure with --enable-optimized.
+ifeq ($(SHOW_DIAGNOSTICS),1)
+ $(Verb) if test -s $(LLVM_OBJ_ROOT)/$(BuildMode)/diags; then \
+ $(LLVM_SRC_ROOT)/utils/clang-parse-diagnostics-file -a \
+ $(LLVM_OBJ_ROOT)/$(BuildMode)/diags; \
+ fi
+endif
+endif
+endif
+
+check-llvm2cpp:
+ $(Verb)$(MAKE) check TESTSUITE=Feature RUNLLVM2CPP=1
+
+srpm: $(LLVM_OBJ_ROOT)/llvm.spec
+ rpmbuild -bs $(LLVM_OBJ_ROOT)/llvm.spec
+
+rpm: $(LLVM_OBJ_ROOT)/llvm.spec
+ rpmbuild -bb --target $(TARGET_TRIPLE) $(LLVM_OBJ_ROOT)/llvm.spec
+
+show-footprint:
+ $(Verb) du -sk $(LibDir)
+ $(Verb) du -sk $(ToolDir)
+ $(Verb) du -sk $(ExmplDir)
+ $(Verb) du -sk $(ObjDir)
+
+build-for-llvm-top:
+ $(Verb) if test ! -f ./config.status ; then \
+ ./configure --prefix="$(LLVM_TOP)/install" \
+ --with-llvm-gcc="$(LLVM_TOP)/llvm-gcc" ; \
+ fi
+ $(Verb) $(MAKE) tools-only
+
+SVN = svn
+SVN-UPDATE-OPTIONS =
+AWK = awk
+SUB-SVN-DIRS = $(AWK) '/I|\? / {print $$2}' \
+ | LC_ALL=C xargs $(SVN) info 2>/dev/null \
+ | $(AWK) '/^Path:\ / {print $$2}'
+
+update:
+ $(SVN) $(SVN-UPDATE-OPTIONS) update $(LLVM_SRC_ROOT)
+ @ $(SVN) status --no-ignore $(LLVM_SRC_ROOT) | $(SUB-SVN-DIRS) | xargs $(SVN) $(SVN-UPDATE-OPTIONS) update
+
+happiness: update all check-all
+
+.PHONY: srpm rpm update happiness
+
+# declare all targets at this level to be serial:
+
+.NOTPARALLEL:
+
+else # Building "Apple-style."
+# In an Apple-style build, once configuration is done, lines marked
+# "Apple-style" are removed with sed! Please don't remove these!
+# Look for the string "Apple-style" in utils/buildit/build_llvm.
+include $(shell find . -name GNUmakefile) # Building "Apple-style."
+endif # Building "Apple-style."
diff --git a/Makefile.common b/Makefile.common
new file mode 100644
index 00000000000..55e2b63434c
--- /dev/null
+++ b/Makefile.common
@@ -0,0 +1,69 @@
+#===-- Makefile.common - Common make rules for LLVM --------*- Makefile -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+#
+# This file is included by all of the LLVM makefiles. This file defines common
+# rules to do things like compile a .cpp file or generate dependency info.
+# These are platform dependent, so this is the file used to specify these
+# system dependent operations.
+#
+# The following functionality can be set by setting incoming variables.
+# The variable $(LEVEL) *must* be set:
+#
+# 1. LEVEL - The level of the current subdirectory from the top of the
+# source directory. This level should be expressed as a path, for
+# example, ../.. for two levels deep.
+#
+# 2. DIRS - A list of subdirectories to be built. Fake targets are set up
+# so that each of the targets "all", "install", and "clean" each build
+# the subdirectories before the local target. DIRS are guaranteed to be
+# built in order.
+#
+# 3. PARALLEL_DIRS - A list of subdirectories to be built, but that may be
+# built in any order. All DIRS are built in order before PARALLEL_DIRS are
+# built, which are then built in any order.
+#
+# 4. Source - If specified, this sets the source code filenames. If this
+# is not set, it defaults to be all of the .cpp, .c, .y, and .l files
+# in the current directory.
+#
+# 5. SourceDir - If specified, this specifies a directory that the source files
+# are in, if they are not in the current directory. This should include a
+# trailing / character.
+#
+# 6. LLVM_SRC_ROOT - If specified, points to the top of the LLVM source tree.
+#
+# 8. PROJ_SRC_DIR - The directory which contains the current set of Makefiles
+# and usually the source code too (unless SourceDir is set).
+#
+# 9. PROJ_SRC_ROOT - The root directory of the source code being compiled.
+#
+# 10. PROJ_OBJ_DIR - The directory where object code should be placed.
+#
+# 11. PROJ_OBJ_ROOT - The root directory for where object code should be
+# placed.
+#
+# For building,
+# LLVM, LLVM_SRC_ROOT = PROJ_SRC_ROOT
+#
+#===-----------------------------------------------------------------------====
+
+#
+# Configuration file to set paths specific to local installation of LLVM
+#
+ifndef LLVM_OBJ_ROOT
+include $(LEVEL)/Makefile.config
+else
+include $(LLVM_OBJ_ROOT)/Makefile.config
+endif
+
+#
+# Include all of the build rules used for making LLVM
+#
+include $(LLVM_SRC_ROOT)/Makefile.rules
+
diff --git a/Makefile.config.in b/Makefile.config.in
new file mode 100644
index 00000000000..e3bd2a207a5
--- /dev/null
+++ b/Makefile.config.in
@@ -0,0 +1,375 @@
+#===-- Makefile.config - Local configuration for LLVM ------*- Makefile -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+#
+# This file is included by Makefile.common. It defines paths and other
+# values specific to a particular installation of LLVM.
+#
+#===------------------------------------------------------------------------===#
+
+# Define LLVM specific info and directories based on the autoconf variables
+LLVMPackageName := @PACKAGE_TARNAME@
+LLVMVersion := @PACKAGE_VERSION@
+LLVM_CONFIGTIME := @LLVM_CONFIGTIME@
+
+###########################################################################
+# Directory Configuration
+# This section of the Makefile determines what is where. To be
+# specific, there are several locations that need to be defined:
+#
+# o LLVM_SRC_ROOT : The root directory of the LLVM source code.
+# o LLVM_OBJ_ROOT : The root directory containing the built LLVM code.
+#
+# o PROJ_SRC_DIR : The directory containing the code to build.
+# o PROJ_SRC_ROOT : The root directory of the code to build.
+#
+# o PROJ_OBJ_DIR : The directory in which compiled code will be placed.
+# o PROJ_OBJ_ROOT : The root directory in which compiled code is placed.
+#
+###########################################################################
+
+PWD := @BINPWD@
+# Set the project name to LLVM if its not defined
+ifndef PROJECT_NAME
+PROJECT_NAME := $(LLVMPackageName)
+endif
+
+# The macro below is expanded when 'realpath' is not built-in.
+# Built-in 'realpath' is available on GNU Make 3.81.
+realpath = $(shell cd $(1); $(PWD))
+
+PROJ_OBJ_DIR := $(call realpath, .)
+PROJ_OBJ_ROOT := $(call realpath, $(PROJ_OBJ_DIR)/$(LEVEL))
+
+CLANG_SRC_ROOT := @CLANG_SRC_ROOT@
+
+ifeq ($(PROJECT_NAME),$(LLVMPackageName))
+LLVM_SRC_ROOT := $(call realpath, @abs_top_srcdir@)
+LLVM_OBJ_ROOT := $(call realpath, @abs_top_builddir@)
+PROJ_SRC_ROOT := $(LLVM_SRC_ROOT)
+PROJ_SRC_DIR := $(LLVM_SRC_ROOT)$(patsubst $(PROJ_OBJ_ROOT)%,%,$(PROJ_OBJ_DIR))
+
+ifneq ($(CLANG_SRC_ROOT),)
+ CLANG_SRC_ROOT:= $(call realpath, $(CLANG_SRC_ROOT))
+ PROJ_SRC_DIR := $(patsubst $(LLVM_SRC_ROOT)/tools/clang%,$(CLANG_SRC_ROOT)%,$(PROJ_SRC_DIR))
+endif
+
+prefix := @prefix@
+PROJ_prefix := $(prefix)
+PROJ_VERSION := $(LLVMVersion)
+else
+ifndef PROJ_SRC_ROOT
+$(error Projects must define PROJ_SRC_ROOT)
+endif
+ifndef PROJ_OBJ_ROOT
+$(error Projects must define PROJ_OBJ_ROOT)
+endif
+ifndef PROJ_INSTALL_ROOT
+$(error Projects must define PROJ_INSTALL_ROOT)
+endif
+ifndef LLVM_SRC_ROOT
+$(error Projects must define LLVM_SRC_ROOT)
+endif
+ifndef LLVM_OBJ_ROOT
+$(error Projects must define LLVM_OBJ_ROOT)
+endif
+PROJ_SRC_DIR := $(call realpath, $(PROJ_SRC_ROOT)/$(patsubst $(PROJ_OBJ_ROOT)%,%,$(PROJ_OBJ_DIR)))
+prefix := $(PROJ_INSTALL_ROOT)
+PROJ_prefix := $(prefix)
+ifndef PROJ_VERSION
+PROJ_VERSION := 1.0
+endif
+endif
+
+INTERNAL_PREFIX := @INTERNAL_PREFIX@
+ifneq ($(INTERNAL_PREFIX),)
+PROJ_internal_prefix := $(INTERNAL_PREFIX)
+else
+PROJ_internal_prefix := $(prefix)
+endif
+
+PROJ_bindir := $(PROJ_prefix)/bin
+PROJ_libdir := $(PROJ_prefix)/lib
+PROJ_datadir := $(PROJ_prefix)/share
+PROJ_docsdir := $(PROJ_prefix)/docs/llvm
+PROJ_etcdir := $(PROJ_prefix)/etc/llvm
+PROJ_includedir := $(PROJ_prefix)/include
+PROJ_infodir := $(PROJ_prefix)/info
+PROJ_mandir := $(PROJ_prefix)/share/man
+
+# Determine if we're on a unix type operating system
+LLVM_ON_UNIX:=@LLVM_ON_UNIX@
+LLVM_ON_WIN32:=@LLVM_ON_WIN32@
+
+# Host operating system for which LLVM will be run.
+OS=@OS@
+HOST_OS=@HOST_OS@
+# Target operating system for which LLVM will compile for.
+TARGET_OS=@TARGET_OS@
+
+# Host hardware architecture
+HOST_ARCH=@HOST_ARCH@
+# Target hardware architecture
+ARCH=@ARCH@
+TARGET_NATIVE_ARCH := $(ARCH)
+
+# Indicates, whether we're cross-compiling LLVM or not
+LLVM_CROSS_COMPILING=@LLVM_CROSS_COMPILING@
+
+# Executable file extension for build platform (mainly for
+# tablegen call if we're cross-compiling).
+BUILD_EXEEXT=@BUILD_EXEEXT@
+
+# Compilers for the build platflorm (mainly for tablegen
+# call if we're cross-compiling).
+BUILD_CC=@BUILD_CC@
+BUILD_CXX=@BUILD_CXX@
+
+# Triple for configuring build tools when cross-compiling
+BUILD_TRIPLE=@build@
+
+# Target triple (cpu-vendor-os) for which we should generate code
+TARGET_TRIPLE=@target@
+
+# Extra options to compile LLVM with
+EXTRA_OPTIONS=@EXTRA_OPTIONS@
+
+# Extra options to link LLVM with
+EXTRA_LD_OPTIONS=@EXTRA_LD_OPTIONS@
+
+# Endian-ness of the target
+ENDIAN=@ENDIAN@
+
+# Path to the C++ compiler to use. This is an optional setting, which defaults
+# to whatever your gmake defaults to.
+CXX = @CXX@
+
+# Path to the CC binary, which use used by testcases for native builds.
+CC := @CC@
+
+# Linker flags.
+LDFLAGS+=@LDFLAGS@
+
+# Path to the library archiver program.
+AR_PATH = @AR@
+AR = @AR@
+
+# Path to the nm program
+NM_PATH = @NM@
+
+# The pathnames of the programs we require to build
+CMP := @CMP@
+CP := @CP@
+DATE := @DATE@
+FIND := @FIND@
+GREP := @GREP@
+INSTALL := @INSTALL@
+MKDIR := $(LLVM_SRC_ROOT)/autoconf/mkinstalldirs
+MV := @MV@
+RANLIB := @RANLIB@
+RM := @RM@
+SED := @SED@
+TAR := @TAR@
+
+# Paths to miscellaneous programs we hope are present but might not be
+BZIP2 := @BZIP2@
+CAT := @CAT@
+DOT := @DOT@
+DOXYGEN := @DOXYGEN@
+GROFF := @GROFF@
+GZIPBIN := @GZIPBIN@
+OCAMLC := @OCAMLC@
+OCAMLOPT := @OCAMLOPT@
+OCAMLDEP := @OCAMLDEP@
+OCAMLDOC := @OCAMLDOC@
+GAS := @GAS@
+POD2HTML := @POD2HTML@
+POD2MAN := @POD2MAN@
+PDFROFF := @PDFROFF@
+ZIP := @ZIP@
+
+HAVE_PTHREAD := @HAVE_PTHREAD@
+
+LIBS := @LIBS@
+
+# Targets that we should build
+TARGETS_TO_BUILD=@TARGETS_TO_BUILD@
+
+# Path to directory where object files should be stored during a build.
+# Set OBJ_ROOT to "." if you do not want to use a separate place for
+# object files.
+OBJ_ROOT := .
+
+# What to pass as rpath flag to g++
+RPATH := @RPATH@
+
+# What to pass as -rdynamic flag to g++
+RDYNAMIC := @RDYNAMIC@
+
+# These are options that can either be enabled here, or can be enabled on the
+# make command line (ie, make ENABLE_PROFILING=1):
+
+# When ENABLE_LIBCPP is enabled, LLVM uses libc++ by default to build.
+#ENABLE_LIBCPP = 0
+ENABLE_LIBCPP = @ENABLE_LIBCPP@
+
+# When ENABLE_CXX11 is enabled, LLVM uses c++11 mode by default to build.
+ENABLE_CXX11 = @ENABLE_CXX11@
+
+# When ENABLE_WERROR is enabled, we'll pass -Werror on the command line
+ENABLE_WERROR = @ENABLE_WERROR@
+
+# When ENABLE_OPTIMIZED is enabled, LLVM code is optimized and output is put
+# into the "Release" directories. Otherwise, LLVM code is not optimized and
+# output is put in the "Debug" directories.
+#ENABLE_OPTIMIZED = 1
+@ENABLE_OPTIMIZED@
+
+# When ENABLE_PROFILING is enabled, profile instrumentation is done
+# and output is put into the "<Flavor>+Profile" directories, where
+# <Flavor> is either Debug or Release depending on how other build
+# flags are set. Otherwise, output is put in the <Flavor>
+# directories.
+#ENABLE_PROFILING = 1
+@ENABLE_PROFILING@
+
+# When DISABLE_ASSERTIONS is enabled, builds of all of the LLVM code will
+# exclude assertion checks, otherwise they are included.
+#DISABLE_ASSERTIONS = 1
+@DISABLE_ASSERTIONS@
+
+# When ENABLE_EXPENSIVE_CHECKS is enabled, builds of all of the LLVM
+# code will include expensive checks, otherwise they are excluded.
+#ENABLE_EXPENSIVE_CHECKS = 0
+@ENABLE_EXPENSIVE_CHECKS@
+
+# When DEBUG_RUNTIME is enabled, the runtime libraries will retain debug
+# symbols.
+#DEBUG_RUNTIME = 1
+@DEBUG_RUNTIME@
+
+# When DEBUG_SYMBOLS is enabled, the compiler libraries will retain debug
+# symbols.
+#DEBUG_SYMBOLS = 1
+@DEBUG_SYMBOLS@
+
+# When KEEP_SYMBOLS is enabled, installed executables will never have their
+# symbols stripped.
+#KEEP_SYMBOLS = 1
+@KEEP_SYMBOLS@
+
+# The compiler flags to use for optimized builds.
+OPTIMIZE_OPTION := @OPTIMIZE_OPTION@
+
+# When ENABLE_PROFILING is enabled, the llvm source base is built with profile
+# information to allow gprof to be used to get execution frequencies.
+#ENABLE_PROFILING = 1
+
+# When ENABLE_DOCS is disabled, docs/ will not be built.
+ENABLE_DOCS = @ENABLE_DOCS@
+
+# When ENABLE_DOXYGEN is enabled, the doxygen documentation will be built
+ENABLE_DOXYGEN = @ENABLE_DOXYGEN@
+
+# Do we want to enable threads?
+ENABLE_THREADS := @ENABLE_THREADS@
+
+# Do we want to build with position independent code?
+ENABLE_PIC := @ENABLE_PIC@
+
+# Do we want to build a shared library and link the tools with it?
+ENABLE_SHARED := @ENABLE_SHARED@
+
+# Do we want to link the stdc++ into a shared library? (Cygming)
+ENABLE_EMBED_STDCXX := @ENABLE_EMBED_STDCXX@
+
+# Use -fvisibility-inlines-hidden?
+ENABLE_VISIBILITY_INLINES_HIDDEN := @ENABLE_VISIBILITY_INLINES_HIDDEN@
+
+# Do we want to allow timestamping information into builds?
+ENABLE_TIMESTAMPS := @ENABLE_TIMESTAMPS@
+
+# This option tells the Makefiles to produce verbose output.
+# It essentially prints the commands that make is executing
+#VERBOSE = 1
+
+# Enable JIT for this platform
+TARGET_HAS_JIT = @TARGET_HAS_JIT@
+
+# Environment variable to set to change the runtime shared library search path.
+SHLIBPATH_VAR = @SHLIBPATH_VAR@
+
+# Shared library extension for host platform.
+SHLIBEXT = @SHLIBEXT@
+
+# Executable file extension for host platform.
+EXEEXT = @EXEEXT@
+
+# Things we just assume are "there"
+ECHO := echo
+
+# Get the options for causing archives to link all their content instead of
+# just missing symbols, and the inverse of that. This is used for certain LLVM
+# tools that permit loadable modules. It ensures that the LLVM symbols will be
+# available to those loadable modules.
+LINKALL := @LINKALL@
+NOLINKALL := @NOLINKALL@
+
+# Get the value of HUGE_VAL_SANITY which will be either "yes" or "no" depending
+# on the check.
+HUGE_VAL_SANITY = @HUGE_VAL_SANITY@
+
+# Bindings that we should build
+BINDINGS_TO_BUILD := @BINDINGS_TO_BUILD@
+ALL_BINDINGS := @ALL_BINDINGS@
+OCAML_LIBDIR := @OCAML_LIBDIR@
+
+# When compiling under Mingw/Cygwin, executables such as tblgen
+# expect Windows paths, whereas the build system uses Unix paths.
+# The function SYSPATH transforms Unix paths into Windows paths.
+ifneq (,$(findstring -mno-cygwin, $(CXX)))
+ SYSPATH = $(shell echo $(1) | cygpath -m -f -)
+else
+ SYSPATH = $(1)
+endif
+
+# Location of the plugin header file for gold.
+BINUTILS_INCDIR := @BINUTILS_INCDIR@
+
+# Optional flags supported by the compiler
+# -Wno-missing-field-initializers
+NO_MISSING_FIELD_INITIALIZERS = @NO_MISSING_FIELD_INITIALIZERS@
+# -Wno-variadic-macros
+NO_VARIADIC_MACROS = @NO_VARIADIC_MACROS@
+# -Wcovered-switch-default
+COVERED_SWITCH_DEFAULT = @COVERED_SWITCH_DEFAULT@
+
+# Was polly found in tools/polly?
+LLVM_HAS_POLLY = @LLVM_HAS_POLLY@
+# Flags supported by the linker.
+# bfd ld / gold --version-script=file
+HAVE_LINK_VERSION_SCRIPT = @HAVE_LINK_VERSION_SCRIPT@
+
+# Flags to control using libxml2
+LIBXML2_LIBS := @LIBXML2_LIBS@
+LIBXML2_INC := @LIBXML2_INC@
+
+# Flags to control building support for Intel JIT Events API
+USE_INTEL_JITEVENTS := @USE_INTEL_JITEVENTS@
+INTEL_JITEVENTS_INCDIR := @INTEL_JITEVENTS_INCDIR@
+INTEL_JITEVENTS_LIBDIR := @INTEL_JITEVENTS_LIBDIR@
+
+# Flags to control building support for OProfile JIT API
+USE_OPROFILE := @USE_OPROFILE@
+
+ifeq ($(USE_INTEL_JITEVENTS), 1)
+ OPTIONAL_COMPONENTS += IntelJITEvents
+endif
+ifeq ($(USE_OPROFILE), 1)
+ OPTIONAL_COMPONENTS += OProfileJIT
+endif
diff --git a/Makefile.rules b/Makefile.rules
new file mode 100644
index 00000000000..289adc2be42
--- /dev/null
+++ b/Makefile.rules
@@ -0,0 +1,2344 @@
+#===-- Makefile.rules - Common make rules for LLVM ---------*- Makefile -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+#
+# This file is included by all of the LLVM makefiles. For details on how to use
+# it properly, please see the document MakefileGuide.html in the docs directory.
+#
+#===-----------------------------------------------------------------------====#
+
+################################################################################
+# TARGETS: Define standard targets that can be invoked
+################################################################################
+
+#--------------------------------------------------------------------
+# Define the various target sets
+#--------------------------------------------------------------------
+RecursiveTargets := all clean clean-all install uninstall install-bytecode \
+ unitcheck
+LocalTargets := all-local clean-local clean-all-local check-local \
+ install-local printvars uninstall-local \
+ install-bytecode-local
+TopLevelTargets := check dist dist-check dist-clean dist-gzip dist-bzip2 \
+ dist-zip unittests
+UserTargets := $(RecursiveTargets) $(LocalTargets) $(TopLevelTargets)
+InternalTargets := preconditions distdir dist-hook
+
+################################################################################
+# INITIALIZATION: Basic things the makefile needs
+################################################################################
+
+#--------------------------------------------------------------------
+# Set the VPATH so that we can find source files.
+#--------------------------------------------------------------------
+VPATH=$(PROJ_SRC_DIR)
+
+#--------------------------------------------------------------------
+# Reset the list of suffixes we know how to build.
+#--------------------------------------------------------------------
+.SUFFIXES:
+.SUFFIXES: .c .cpp .cc .h .hpp .o .a .bc .td .ps .dot .ll .m .mm
+.SUFFIXES: $(SHLIBEXT) $(SUFFIXES)
+
+#--------------------------------------------------------------------
+# Mark all of these targets as phony to avoid implicit rule search
+#--------------------------------------------------------------------
+.PHONY: $(UserTargets) $(InternalTargets)
+
+#--------------------------------------------------------------------
+# Make sure all the user-target rules are double colon rules and
+# they are defined first.
+#--------------------------------------------------------------------
+
+$(UserTargets)::
+
+#------------------------------------------------------------------------
+# LLVMBuild Integration
+#------------------------------------------------------------------------
+#
+# We use llvm-build to generate all the data required by the Makefile based
+# build system in one swoop:
+#
+# - We generate a file (a Makefile fragment) in the object root which contains
+# all the definitions that are required by Makefiles across the entire
+# project.
+#
+# - We generate the library table used by llvm-config.
+#
+# - We generate the dependencies for the Makefile fragment, so that we will
+# automatically reconfigure outselves.
+
+# The path to the llvm-build tool itself.
+LLVMBuildTool := $(PROJ_SRC_ROOT)/utils/llvm-build/llvm-build
+
+# The files we are going to generate using llvm-build.
+LLVMBuildMakeFrag := $(PROJ_OBJ_ROOT)/Makefile.llvmbuild
+LLVMConfigLibraryDependenciesInc := \
+ $(PROJ_OBJ_ROOT)/tools/llvm-config/LibraryDependencies.inc
+
+# This is for temporary backwards compatibility.
+ifndef TARGET_NATIVE_ARCH
+TARGET_NATIVE_ARCH := $(ARCH)
+endif
+
+# The rule to create the LLVMBuild Makefile fragment as well as the llvm-config
+# library table.
+#
+# Note that this target gets its real dependencies generated for us by
+# llvm-build.
+#
+# We include a dependency on this Makefile to ensure that changes to the
+# generation command get picked up.
+$(LLVMBuildMakeFrag): $(PROJ_SRC_ROOT)/Makefile.rules \
+ $(PROJ_OBJ_ROOT)/Makefile.config
+ $(Echo) Constructing LLVMBuild project information.
+ $(Verb) $(LLVMBuildTool) \
+ --native-target "$(TARGET_NATIVE_ARCH)" \
+ --enable-targets "$(TARGETS_TO_BUILD)" \
+ --enable-optional-components "$(OPTIONAL_COMPONENTS)" \
+ --write-library-table $(LLVMConfigLibraryDependenciesInc) \
+ --write-make-fragment $(LLVMBuildMakeFrag)
+
+# For completeness, let Make know how the extra files are generated.
+$(LLVMConfigLibraryDependenciesInc): $(LLVMBuildMakeFrag)
+
+# Include the generated Makefile fragment.
+#
+# We currently only include the dependencies for the fragment itself if we are
+# at the top-level. Otherwise, recursive invocations would ends up doing
+# substantially more redundant stat'ing.
+#
+# This means that we won't properly regenerate things for developers used to
+# building from a subdirectory, but that is always somewhat unreliable.
+ifeq ($(LEVEL),.)
+LLVMBUILD_INCLUDE_DEPENDENCIES := 1
+
+# Clean the generated makefile fragment at the top-level.
+clean-local::
+ -$(Verb) $(RM) -f $(LLVMBuildMakeFrag)
+endif
+-include $(LLVMBuildMakeFrag)
+
+################################################################################
+# PRECONDITIONS: that which must be built/checked first
+################################################################################
+
+SrcMakefiles := $(filter %Makefile %Makefile.tests,\
+ $(wildcard $(PROJ_SRC_DIR)/Makefile*))
+ObjMakefiles := $(subst $(PROJ_SRC_DIR),$(PROJ_OBJ_DIR),$(SrcMakefiles))
+ConfigureScript := $(PROJ_SRC_ROOT)/configure
+ConfigStatusScript := $(PROJ_OBJ_ROOT)/config.status
+MakefileConfigIn := $(strip $(wildcard $(PROJ_SRC_ROOT)/Makefile.config.in))
+MakefileCommonIn := $(strip $(wildcard $(PROJ_SRC_ROOT)/Makefile.common.in))
+MakefileConfig := $(PROJ_OBJ_ROOT)/Makefile.config
+MakefileCommon := $(PROJ_OBJ_ROOT)/Makefile.common
+PreConditions := $(ConfigStatusScript) $(ObjMakefiles)
+ifneq ($(MakefileCommonIn),)
+PreConditions += $(MakefileCommon)
+endif
+
+ifneq ($(MakefileConfigIn),)
+PreConditions += $(MakefileConfig)
+endif
+
+preconditions: $(PreConditions)
+
+#------------------------------------------------------------------------
+# Make sure the BUILT_SOURCES are built first
+#------------------------------------------------------------------------
+$(filter-out clean clean-local,$(UserTargets)):: $(BUILT_SOURCES)
+
+clean-all-local::
+ifneq ($(strip $(BUILT_SOURCES)),)
+ -$(Verb) $(RM) -f $(BUILT_SOURCES)
+endif
+
+ifneq ($(PROJ_OBJ_ROOT),$(PROJ_SRC_ROOT))
+spotless:
+ $(Verb) if test -x config.status ; then \
+ $(EchoCmd) Wiping out $(PROJ_OBJ_ROOT) ; \
+ $(MKDIR) .spotless.save ; \
+ $(MV) config.status .spotless.save ; \
+ $(MV) mklib .spotless.save ; \
+ $(MV) projects .spotless.save ; \
+ $(RM) -rf * ; \
+ $(MV) .spotless.save/config.status . ; \
+ $(MV) .spotless.save/mklib . ; \
+ $(MV) .spotless.save/projects . ; \
+ $(RM) -rf .spotless.save ; \
+ $(EchoCmd) Rebuilding configuration of $(PROJ_OBJ_ROOT) ; \
+ $(ConfigStatusScript) --recheck $(ConfigureScriptFLAGS) && \
+ $(ConfigStatusScript) ; \
+ else \
+ $(EchoCmd) "make spotless" can only be run from $(PROJ_OBJ_ROOT); \
+ fi
+else
+spotless:
+ $(EchoCmd) "spotless target not supported for objdir == srcdir"
+endif
+
+$(BUILT_SOURCES) : $(ObjMakefiles)
+
+#------------------------------------------------------------------------
+# Make sure we're not using a stale configuration
+#------------------------------------------------------------------------
+reconfigure:
+ $(Echo) Reconfiguring $(PROJ_OBJ_ROOT)
+ $(Verb) cd $(PROJ_OBJ_ROOT) && \
+ $(ConfigStatusScript) --recheck $(ConfigureScriptFLAGS) && \
+ $(ConfigStatusScript)
+
+.PRECIOUS: $(ConfigStatusScript)
+$(ConfigStatusScript): $(ConfigureScript)
+ $(Echo) Reconfiguring with $<
+ $(Verb) cd $(PROJ_OBJ_ROOT) && \
+ $(ConfigStatusScript) --recheck $(ConfigureScriptFLAGS) && \
+ $(ConfigStatusScript)
+
+#------------------------------------------------------------------------
+# Make sure the configuration makefile is up to date
+#------------------------------------------------------------------------
+ifneq ($(MakefileConfigIn),)
+$(MakefileConfig): $(MakefileConfigIn) $(ConfigStatusScript)
+ $(Echo) Regenerating $@
+ $(Verb) cd $(PROJ_OBJ_ROOT) ; $(ConfigStatusScript) Makefile.config
+endif
+
+ifneq ($(MakefileCommonIn),)
+$(MakefileCommon): $(MakefileCommonIn) $(ConfigStatusScript)
+ $(Echo) Regenerating $@
+ $(Verb) cd $(PROJ_OBJ_ROOT) ; $(ConfigStatusScript) Makefile.common
+endif
+
+#------------------------------------------------------------------------
+# If the Makefile in the source tree has been updated, copy it over into the
+# build tree. But, only do this if the source and object makefiles differ
+#------------------------------------------------------------------------
+ifndef PROJ_MAKEFILE
+PROJ_MAKEFILE := $(PROJ_SRC_DIR)/Makefile
+endif
+
+ifneq ($(PROJ_OBJ_DIR),$(PROJ_SRC_DIR))
+
+Makefile: $(PROJ_MAKEFILE) $(ExtraMakefiles)
+ $(Echo) "Updating Makefile"
+ $(Verb) $(MKDIR) $(@D)
+ $(Verb) $(CP) -f $< $@
+
+# Copy the Makefile.* files unless we're in the root directory which avoids
+# the copying of Makefile.config.in or other things that should be explicitly
+# taken care of.
+$(PROJ_OBJ_DIR)/Makefile% : $(PROJ_MAKEFILE)%
+ @case '$?' in \
+ *Makefile.rules) ;; \
+ *.in) ;; \
+ *) $(EchoCmd) "Updating $(@F)" ; \
+ $(MKDIR) $(@D) ; \
+ $(CP) -f $< $@ ;; \
+ esac
+
+endif
+
+#------------------------------------------------------------------------
+# Set up the basic dependencies
+#------------------------------------------------------------------------
+$(UserTargets):: $(PreConditions)
+
+all:: all-local
+clean:: clean-local
+clean-all:: clean-local clean-all-local
+install:: install-local
+uninstall:: uninstall-local
+install-local:: all-local
+install-bytecode:: install-bytecode-local
+
+###############################################################################
+# VARIABLES: Set up various variables based on configuration data
+###############################################################################
+
+# Variable for if this make is for a "cleaning" target
+ifneq ($(strip $(filter clean clean-local dist-clean,$(MAKECMDGOALS))),)
+ IS_CLEANING_TARGET=1
+endif
+
+#--------------------------------------------------------------------
+# Variables derived from configuration we are building
+#--------------------------------------------------------------------
+
+CPP.Defines :=
+ifeq ($(ENABLE_OPTIMIZED),1)
+ BuildMode := Release
+ # Don't use -fomit-frame-pointer on Darwin or FreeBSD.
+ ifneq ($(HOST_OS),FreeBSD)
+ ifneq ($(HOST_OS),Darwin)
+ OmitFramePointer := -fomit-frame-pointer
+ endif
+ endif
+
+ # Darwin requires -fstrict-aliasing to be explicitly enabled.
+ # Avoid -fstrict-aliasing on Darwin for now, there are unresolved issues
+ # with -fstrict-aliasing and ipa-type-escape radr://6756684
+ #ifeq ($(HOST_OS),Darwin)
+ # EXTRA_OPTIONS += -fstrict-aliasing -Wstrict-aliasing
+ #endif
+ CXX.Flags += $(OPTIMIZE_OPTION) $(OmitFramePointer)
+ C.Flags += $(OPTIMIZE_OPTION) $(OmitFramePointer)
+ LD.Flags += $(OPTIMIZE_OPTION)
+ ifdef DEBUG_SYMBOLS
+ BuildMode := $(BuildMode)+Debug
+ CXX.Flags += -g
+ C.Flags += -g
+ LD.Flags += -g
+ KEEP_SYMBOLS := 1
+ endif
+else
+ ifdef NO_DEBUG_SYMBOLS
+ BuildMode := Unoptimized
+ CXX.Flags +=
+ C.Flags +=
+ LD.Flags +=
+ KEEP_SYMBOLS := 1
+ else
+ BuildMode := Debug
+ CXX.Flags += -g
+ C.Flags += -g
+ LD.Flags += -g
+ KEEP_SYMBOLS := 1
+ endif
+endif
+
+ifeq ($(ENABLE_LIBCPP),1)
+ CXX.Flags += -stdlib=libc++
+ LD.Flags += -stdlib=libc++
+endif
+
+ifeq ($(ENABLE_CXX11),1)
+ CXX.Flags += -std=c++11
+endif
+
+ifeq ($(ENABLE_WERROR),1)
+ CXX.Flags += -Werror
+ C.Flags += -Werror
+endif
+
+ifeq ($(ENABLE_PROFILING),1)
+ BuildMode := $(BuildMode)+Profile
+ CXX.Flags := $(filter-out -fomit-frame-pointer,$(CXX.Flags)) -pg -g
+ C.Flags := $(filter-out -fomit-frame-pointer,$(C.Flags)) -pg -g
+ LD.Flags := $(filter-out -fomit-frame-pointer,$(LD.Flags)) -pg -g
+ KEEP_SYMBOLS := 1
+endif
+
+ifeq ($(ENABLE_VISIBILITY_INLINES_HIDDEN),1)
+ CXX.Flags += -fvisibility-inlines-hidden
+endif
+
+ifdef ENABLE_EXPENSIVE_CHECKS
+ # GNU libstdc++ uses RTTI if you define _GLIBCXX_DEBUG, which we did above.
+ # See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40160
+ REQUIRES_RTTI := 1
+endif
+
+# IF REQUIRES_EH=1 is specified then don't disable exceptions
+ifndef REQUIRES_EH
+ CXX.Flags += -fno-exceptions
+else
+ # If the library requires EH, it also requires RTTI.
+ REQUIRES_RTTI := 1
+endif
+
+ifdef REQUIRES_FRAME_POINTER
+ CXX.Flags := $(filter-out -fomit-frame-pointer,$(CXX.Flags))
+ C.Flags := $(filter-out -fomit-frame-pointer,$(C.Flags))
+ LD.Flags := $(filter-out -fomit-frame-pointer,$(LD.Flags))
+endif
+
+# If REQUIRES_RTTI=1 is specified then don't disable run-time type id.
+ifneq ($(REQUIRES_RTTI), 1)
+ CXX.Flags += -fno-rtti
+endif
+
+ifeq ($(ENABLE_COVERAGE),1)
+ BuildMode := $(BuildMode)+Coverage
+ CXX.Flags += -ftest-coverage -fprofile-arcs
+ C.Flags += -ftest-coverage -fprofile-arcs
+endif
+
+# If DISABLE_ASSERTIONS=1 is specified (make command line or configured),
+# then disable assertions by defining the appropriate preprocessor symbols.
+ifeq ($(DISABLE_ASSERTIONS),1)
+ CPP.Defines += -DNDEBUG
+else
+ BuildMode := $(BuildMode)+Asserts
+ CPP.Defines += -D_DEBUG
+endif
+
+# If ENABLE_EXPENSIVE_CHECKS=1 is specified (make command line or
+# configured), then enable expensive checks by defining the
+# appropriate preprocessor symbols.
+ifeq ($(ENABLE_EXPENSIVE_CHECKS),1)
+ BuildMode := $(BuildMode)+Checks
+ CPP.Defines += -D_GLIBCXX_DEBUG -DXDEBUG
+endif
+
+# LOADABLE_MODULE implies several other things so we force them to be
+# defined/on.
+ifdef LOADABLE_MODULE
+ SHARED_LIBRARY := 1
+ LINK_LIBS_IN_SHARED := 1
+endif
+
+ifdef SHARED_LIBRARY
+ ENABLE_PIC := 1
+ PIC_FLAG = "(PIC)"
+endif
+
+ifeq ($(ENABLE_PIC),1)
+ ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+ # Nothing. Win32 defaults to PIC and warns when given -fPIC
+ else
+ ifeq ($(HOST_OS),Darwin)
+ # Common symbols not allowed in dylib files
+ CXX.Flags += -fno-common
+ C.Flags += -fno-common
+ else
+ # Linux and others; pass -fPIC
+ CXX.Flags += -fPIC
+ C.Flags += -fPIC
+ endif
+ endif
+else
+ ifeq ($(HOST_OS),Darwin)
+ CXX.Flags += -mdynamic-no-pic
+ C.Flags += -mdynamic-no-pic
+ endif
+endif
+
+# Support makefile variable to disable any kind of timestamp/non-deterministic
+# info from being used in the build.
+ifeq ($(ENABLE_TIMESTAMPS),1)
+ DOTDIR_TIMESTAMP_COMMAND := $(DATE)
+else
+ DOTDIR_TIMESTAMP_COMMAND := echo 'Created.'
+endif
+
+ifeq ($(HOST_OS),MingW)
+ # Work around PR4957
+ CPP.Defines += -D__NO_CTYPE_INLINE
+ ifeq ($(LLVM_CROSS_COMPILING),1)
+ # Work around http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=525016
+ ifdef TOOLNAME
+ LD.Flags += -Wl,--allow-multiple-definition
+ endif
+ endif
+endif
+
+CXX.Flags += -Woverloaded-virtual
+CPP.BaseFlags += $(CPP.Defines)
+AR.Flags := cru
+
+# Make Floating point IEEE compliant on Alpha.
+ifeq ($(ARCH),Alpha)
+ CXX.Flags += -mieee
+ CPP.BaseFlags += -mieee
+ifeq ($(ENABLE_PIC),0)
+ CXX.Flags += -fPIC
+ CPP.BaseFlags += -fPIC
+endif
+
+ LD.Flags += -Wl,--no-relax
+endif
+
+# GNU ld/PECOFF accepts but ignores them below;
+# --version-script
+# --export-dynamic
+# --rpath
+# FIXME: autoconf should be aware of them.
+ifneq (,$(filter $(HOST_OS),Cygwin MingW))
+ HAVE_LINK_VERSION_SCRIPT := 0
+ RPATH :=
+ RDYNAMIC := -Wl,--export-all-symbols
+endif
+
+#--------------------------------------------------------------------
+# Directory locations
+#--------------------------------------------------------------------
+TargetMode :=
+ifeq ($(LLVM_CROSS_COMPILING),1)
+ BuildLLVMToolDir := $(LLVM_OBJ_ROOT)/BuildTools/$(BuildMode)/bin
+endif
+
+ObjRootDir := $(PROJ_OBJ_DIR)/$(BuildMode)
+ObjDir := $(ObjRootDir)
+LibDir := $(PROJ_OBJ_ROOT)/$(BuildMode)/lib
+ToolDir := $(PROJ_OBJ_ROOT)/$(BuildMode)/bin
+ExmplDir := $(PROJ_OBJ_ROOT)/$(BuildMode)/examples
+LLVMLibDir := $(LLVM_OBJ_ROOT)/$(BuildMode)/lib
+LLVMToolDir := $(LLVM_OBJ_ROOT)/$(BuildMode)/bin
+LLVMExmplDir:= $(LLVM_OBJ_ROOT)/$(BuildMode)/examples
+
+#--------------------------------------------------------------------
+# Locations of shared libraries
+#--------------------------------------------------------------------
+
+SharedPrefix := lib
+SharedLibDir := $(LibDir)
+LLVMSharedLibDir := $(LLVMLibDir)
+
+# Win32.DLL prefers to be located on the "PATH" of binaries.
+ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+ SharedLibDir := $(ToolDir)
+ LLVMSharedLibDir := $(LLVMToolDir)
+
+ ifeq ($(HOST_OS),Cygwin)
+ SharedPrefix := cyg
+ else
+ SharedPrefix :=
+ endif
+endif
+
+#--------------------------------------------------------------------
+# LLVM Capable Compiler
+#--------------------------------------------------------------------
+
+ifneq ($(findstring llvm-gcc,$(LLVMCC_OPTION)),)
+ LLVMCC := $(LLVMGCC)
+ LLVMCXX := $(LLVMGXX)
+else
+ ifneq ($(findstring clang,$(LLVMCC_OPTION)),)
+ ifneq ($(CLANGPATH),)
+ LLVMCC := $(CLANGPATH)
+ LLVMCXX := $(CLANGXXPATH)
+ else
+ ifeq ($(ENABLE_BUILT_CLANG),1)
+ LLVMCC := $(LLVMToolDir)/clang
+ LLVMCXX := $(LLVMToolDir)/clang++
+ endif
+ endif
+ endif
+endif
+
+#--------------------------------------------------------------------
+# Full Paths To Compiled Tools and Utilities
+#--------------------------------------------------------------------
+EchoCmd := $(ECHO) llvm[$(MAKELEVEL)]:
+ifdef BUILD_DIRS_ONLY
+EchoCmd := $(EchoCmd) "(build tools)":
+endif
+
+Echo := @$(EchoCmd)
+ifndef LLVMAS
+LLVMAS := $(LLVMToolDir)/llvm-as$(EXEEXT)
+endif
+ifndef LLVM_TBLGEN
+ ifeq ($(LLVM_CROSS_COMPILING),1)
+ LLVM_TBLGEN := $(BuildLLVMToolDir)/llvm-tblgen$(BUILD_EXEEXT)
+ else
+ LLVM_TBLGEN := $(LLVMToolDir)/llvm-tblgen$(EXEEXT)
+ endif
+endif
+ifeq ($(LLVM_CROSS_COMPILING),1)
+ LLVM_CONFIG := $(BuildLLVMToolDir)/llvm-config$(BUILD_EXEEXT)
+else
+ LLVM_CONFIG := $(LLVMToolDir)/llvm-config$(EXEEXT)
+endif
+ifndef LLVMDIS
+LLVMDIS := $(LLVMToolDir)/llvm-dis$(EXEEXT)
+endif
+ifndef LLI
+LLI := $(LLVMToolDir)/lli$(EXEEXT)
+endif
+ifndef LLC
+LLC := $(LLVMToolDir)/llc$(EXEEXT)
+endif
+ifndef LOPT
+LOPT := $(LLVMToolDir)/opt$(EXEEXT)
+endif
+ifndef LBUGPOINT
+LBUGPOINT := $(LLVMToolDir)/bugpoint$(EXEEXT)
+endif
+ifndef LLVMLINK
+LLVMLINK := $(LLVMToolDir)/llvm-link$(EXEEXT)
+endif
+
+#--------------------------------------------------------------------
+# Adjust to user's request
+#--------------------------------------------------------------------
+
+ifeq ($(HOST_OS),Darwin)
+ DARWIN_VERSION := `sw_vers -productVersion`
+ # Strip a number like 10.4.7 to 10.4
+ DARWIN_VERSION := $(shell echo $(DARWIN_VERSION)| sed -E 's/(10.[0-9]).*/\1/')
+ # Get "4" out of 10.4 for later pieces in the makefile.
+ DARWIN_MAJVERS := $(shell echo $(DARWIN_VERSION)| sed -E 's/10.([0-9]).*/\1/')
+
+ LoadableModuleOptions := -Wl,-flat_namespace -Wl,-undefined,suppress
+ SharedLinkOptions := -dynamiclib
+ ifneq ($(ARCH),ARM)
+ SharedLinkOptions += -mmacosx-version-min=$(DARWIN_VERSION)
+ endif
+else
+ SharedLinkOptions=-shared
+endif
+
+ifeq ($(TARGET_OS),Darwin)
+ ifneq ($(ARCH),ARM)
+ TargetCommonOpts += -mmacosx-version-min=$(DARWIN_VERSION)
+ endif
+endif
+
+ifdef SHARED_LIBRARY
+ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+ifneq ($(HOST_OS),Darwin)
+ LD.Flags += $(RPATH) -Wl,'$$ORIGIN'
+endif
+endif
+endif
+
+ifdef TOOL_VERBOSE
+ C.Flags += -v
+ CXX.Flags += -v
+ LD.Flags += -v
+ VERBOSE := 1
+endif
+
+# Adjust settings for verbose mode
+ifndef VERBOSE
+ Verb := @
+ AR.Flags += >/dev/null 2>/dev/null
+ ConfigureScriptFLAGS += >$(PROJ_OBJ_DIR)/configure.out 2>&1
+else
+ ConfigureScriptFLAGS :=
+endif
+
+# By default, strip symbol information from executable
+ifndef KEEP_SYMBOLS
+ Strip := $(PLATFORMSTRIPOPTS)
+ StripWarnMsg := "(without symbols)"
+ Install.StripFlag += -s
+endif
+
+ifdef TOOL_NO_EXPORTS
+ DynamicFlags :=
+else
+ DynamicFlag := $(RDYNAMIC)
+endif
+
+# Adjust linker flags for building an executable
+ifneq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+ifneq ($(HOST_OS), Darwin)
+ifdef TOOLNAME
+ LD.Flags += $(RPATH) -Wl,'$$ORIGIN/../lib'
+ ifdef EXAMPLE_TOOL
+ LD.Flags += $(RPATH) -Wl,$(ExmplDir) $(DynamicFlag)
+ else
+ LD.Flags += $(RPATH) -Wl,$(ToolDir) $(DynamicFlag)
+ endif
+endif
+else
+ifneq ($(DARWIN_MAJVERS),4)
+ LD.Flags += $(RPATH) -Wl,@executable_path/../lib
+endif
+endif
+endif
+
+
+#----------------------------------------------------------
+# Options To Invoke Tools
+#----------------------------------------------------------
+
+ifdef EXTRA_LD_OPTIONS
+LD.Flags += $(EXTRA_LD_OPTIONS)
+endif
+
+ifndef NO_PEDANTIC
+CompileCommonOpts += -pedantic -Wno-long-long
+endif
+CompileCommonOpts += -Wall -W -Wno-unused-parameter -Wwrite-strings \
+ $(EXTRA_OPTIONS) $(COVERED_SWITCH_DEFAULT)
+# Enable cast-qual for C++; the workaround is to use const_cast.
+CXX.Flags += -Wcast-qual
+
+ifeq ($(HOST_OS),HP-UX)
+ CompileCommonOpts := -D_REENTRANT -D_HPUX_SOURCE
+endif
+
+# If we are building a universal binary on Mac OS/X, pass extra options. This
+# is useful to people that want to link the LLVM libraries into their universal
+# apps.
+#
+# The following can be optionally specified:
+# UNIVERSAL_SDK_PATH variable can be specified as a path to the SDK to use.
+# For Mac OS/X 10.4 Intel machines, the traditional one is:
+# UNIVERSAL_SDK_PATH=/Developer/SDKs/MacOSX10.4u.sdk/
+# UNIVERSAL_ARCH can be optionally specified to be a list of architectures
+# to build for, e.g. UNIVERSAL_ARCH="i386 ppc ppc64". This defaults to
+# i386/ppc only.
+ifdef UNIVERSAL
+ ifndef UNIVERSAL_ARCH
+ UNIVERSAL_ARCH := i386 ppc
+ endif
+ UNIVERSAL_ARCH_OPTIONS := $(UNIVERSAL_ARCH:%=-arch %)
+ CompileCommonOpts += $(UNIVERSAL_ARCH_OPTIONS)
+ ifdef UNIVERSAL_SDK_PATH
+ CompileCommonOpts += -isysroot $(UNIVERSAL_SDK_PATH)
+ endif
+
+ # Building universal cannot compute dependencies automatically.
+ DISABLE_AUTO_DEPENDENCIES=1
+else
+ ifeq ($(TARGET_OS),Darwin)
+ ifeq ($(ARCH),x86_64)
+ TargetCommonOpts = -m64
+ else
+ ifeq ($(ARCH),x86)
+ TargetCommonOpts = -m32
+ endif
+ endif
+ endif
+endif
+
+ifeq ($(HOST_OS),SunOS)
+CPP.BaseFlags += -include llvm/Support/Solaris.h
+endif
+
+ifeq ($(HOST_OS),AuroraUX)
+CPP.BaseFlags += -include llvm/Support/Solaris.h
+endif # !HOST_OS - AuroraUX.
+
+# On Windows, SharedLibDir != LibDir. The order is important.
+ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+ LD.Flags += -L$(SharedLibDir) -L$(LibDir) -L$(LLVMToolDir) -L$(LLVMLibDir)
+else
+ LD.Flags += -L$(LibDir) -L$(LLVMLibDir)
+endif
+
+CPP.BaseFlags += -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS
+# All -I flags should go here, so that they don't confuse llvm-config.
+CPP.Flags += $(sort -I$(PROJ_OBJ_DIR) -I$(PROJ_SRC_DIR) \
+ $(patsubst %,-I%/include,\
+ $(PROJ_OBJ_ROOT) $(PROJ_SRC_ROOT) \
+ $(LLVM_OBJ_ROOT) $(LLVM_SRC_ROOT))) \
+ $(CPP.BaseFlags)
+
+ifeq ($(INCLUDE_BUILD_DIR),1)
+ CPP.Flags += -I$(ObjDir)
+endif
+
+# SHOW_DIAGNOSTICS support.
+ifeq ($(SHOW_DIAGNOSTICS),1)
+ Compile.Wrapper := env CC_LOG_DIAGNOSTICS=1 \
+ CC_LOG_DIAGNOSTICS_FILE="$(LLVM_OBJ_ROOT)/$(BuildMode)/diags"
+else
+ Compile.Wrapper :=
+endif
+
+Compile.C = $(Compile.Wrapper) \
+ $(CC) $(CPP.Flags) $(C.Flags) $(CFLAGS) $(CPPFLAGS) \
+ $(TargetCommonOpts) $(CompileCommonOpts) -c
+Compile.CXX = $(Compile.Wrapper) \
+ $(CXX) $(CPP.Flags) $(CXX.Flags) $(CXXFLAGS) $(CPPFLAGS) \
+ $(TargetCommonOpts) $(CompileCommonOpts) -c
+Preprocess.CXX= $(Compile.Wrapper) \
+ $(CXX) $(CPP.Flags) $(TargetCommonOpts) $(CPPFLAGS) \
+ $(CompileCommonOpts) $(CXX.Flags) -E
+Link = $(Compile.Wrapper) \
+ $(CXX) $(CPP.Flags) $(CXX.Flags) $(CXXFLAGS) $(LD.Flags) \
+ $(LDFLAGS) $(TargetCommonOpts) $(CompileCommonOpts) $(Strip)
+
+BCCompile.C = $(LLVMCC) $(CPP.Flags) $(C.Flags) $(CFLAGS) $(CPPFLAGS) \
+ $(TargetCommonOpts) $(CompileCommonOpts)
+Preprocess.C = $(CC) $(CPP.Flags) $(C.Flags) $(CPPFLAGS) \
+ $(TargetCommonOpts) $(CompileCommonOpts) -E
+
+BCCompile.CXX = $(LLVMCXX) $(CPP.Flags) $(CXX.Flags) $(CXXFLAGS) $(CPPFLAGS) \
+ $(TargetCommonOpts) $(CompileCommonOpts)
+
+ProgInstall = $(INSTALL) $(Install.StripFlag) -m 0755
+ScriptInstall = $(INSTALL) -m 0755
+DataInstall = $(INSTALL) -m 0644
+
+# When compiling under Mingw/Cygwin, the tblgen tool expects Windows
+# paths. In this case, the SYSPATH function (defined in
+# Makefile.config) transforms Unix paths into Windows paths.
+TableGen.Flags= -I $(call SYSPATH, $(PROJ_SRC_DIR)) \
+ -I $(call SYSPATH, $(LLVM_SRC_ROOT)/include) \
+ -I $(call SYSPATH, $(PROJ_SRC_ROOT)/include) \
+ -I $(call SYSPATH, $(PROJ_SRC_ROOT)/lib/Target)
+LLVMTableGen = $(LLVM_TBLGEN) $(TableGen.Flags)
+
+Archive = $(AR) $(AR.Flags)
+LArchive = $(LLVMToolDir)/llvm-ar rcsf
+ifdef RANLIB
+Ranlib = $(RANLIB)
+else
+Ranlib = ranlib
+endif
+
+AliasTool = ln -s
+
+#----------------------------------------------------------
+# Get the list of source files and compute object file
+# names from them.
+#----------------------------------------------------------
+
+ifndef SOURCES
+ Sources := $(notdir $(wildcard $(PROJ_SRC_DIR)/*.cpp \
+ $(PROJ_SRC_DIR)/*.cc $(PROJ_SRC_DIR)/*.c))
+else
+ Sources := $(SOURCES)
+endif
+
+ifdef BUILT_SOURCES
+Sources += $(filter %.cpp %.c %.cc,$(BUILT_SOURCES))
+endif
+
+BaseNameSources := $(sort $(basename $(Sources)))
+
+ObjectsO := $(BaseNameSources:%=$(ObjDir)/%.o)
+ObjectsBC := $(BaseNameSources:%=$(ObjDir)/%.bc)
+
+#----------------------------------------------------------
+# For Mingw MSYS bash and Python/w32:
+#
+# $(ECHOPATH) prints DOSish pathstring.
+# ex) $(ECHOPATH) /include/sys/types.h
+# --> C:/mingw/include/sys/types.h
+# built-in "echo" does not transform path to DOSish path.
+#
+# FIXME: It would not be needed when MSYS's python
+# were provided.
+#----------------------------------------------------------
+
+ifeq (-mingw32,$(findstring -mingw32,$(BUILD_TRIPLE)))
+ ECHOPATH := $(Verb)python -u -c "import sys;print ' '.join(sys.argv[1:])"
+else
+ ECHOPATH := $(Verb)$(ECHO)
+endif
+
+###############################################################################
+# DIRECTORIES: Handle recursive descent of directory structure
+###############################################################################
+
+#---------------------------------------------------------
+# Provide rules to make install dirs. This must be early
+# in the file so they get built before dependencies
+#---------------------------------------------------------
+
+$(DESTDIR)$(PROJ_bindir) $(DESTDIR)$(PROJ_libdir) $(DESTDIR)$(PROJ_includedir) $(DESTDIR)$(PROJ_etcdir)::
+ $(Verb) $(MKDIR) $@
+
+# To create other directories, as needed, and timestamp their creation
+%/.dir:
+ $(Verb) $(MKDIR) $* > /dev/null
+ $(Verb) $(DOTDIR_TIMESTAMP_COMMAND) > $@
+
+.PRECIOUS: $(ObjDir)/.dir $(LibDir)/.dir $(ToolDir)/.dir $(ExmplDir)/.dir
+.PRECIOUS: $(LLVMLibDir)/.dir $(LLVMToolDir)/.dir $(LLVMExmplDir)/.dir
+
+#---------------------------------------------------------
+# Handle the DIRS options for sequential construction
+#---------------------------------------------------------
+
+SubDirs :=
+ifdef DIRS
+SubDirs += $(DIRS)
+
+ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT))
+$(RecursiveTargets)::
+ $(Verb) for dir in $(DIRS); do \
+ if ([ ! -f $$dir/Makefile ] || \
+ command test $$dir/Makefile -ot $(PROJ_SRC_DIR)/$$dir/Makefile ); then \
+ $(MKDIR) $$dir; \
+ $(CP) $(PROJ_SRC_DIR)/$$dir/Makefile $$dir/Makefile; \
+ fi; \
+ ($(MAKE) -C $$dir $@ ) || exit 1; \
+ done
+else
+$(RecursiveTargets)::
+ $(Verb) for dir in $(DIRS); do \
+ ($(MAKE) -C $$dir $@ ) || exit 1; \
+ done
+endif
+
+endif
+
+#---------------------------------------------------------
+# Handle the EXPERIMENTAL_DIRS options ensuring success
+# after each directory is built.
+#---------------------------------------------------------
+ifdef EXPERIMENTAL_DIRS
+$(RecursiveTargets)::
+ $(Verb) for dir in $(EXPERIMENTAL_DIRS); do \
+ if ([ ! -f $$dir/Makefile ] || \
+ command test $$dir/Makefile -ot $(PROJ_SRC_DIR)/$$dir/Makefile ); then \
+ $(MKDIR) $$dir; \
+ $(CP) $(PROJ_SRC_DIR)/$$dir/Makefile $$dir/Makefile; \
+ fi; \
+ ($(MAKE) -C $$dir $@ ) || exit 0; \
+ done
+endif
+
+#-----------------------------------------------------------
+# Handle the OPTIONAL_PARALLEL_DIRS options for optional parallel construction
+#-----------------------------------------------------------
+ifdef OPTIONAL_PARALLEL_DIRS
+ PARALLEL_DIRS += $(foreach T,$(OPTIONAL_PARALLEL_DIRS),$(shell test -d $(PROJ_SRC_DIR)/$(T) -o -f $(T)/Makefile && echo "$(T)"))
+endif
+
+#-----------------------------------------------------------
+# Handle the PARALLEL_DIRS options for parallel construction
+#-----------------------------------------------------------
+ifdef PARALLEL_DIRS
+
+SubDirs += $(PARALLEL_DIRS)
+
+# Unfortunately, this list must be maintained if new recursive targets are added
+all :: $(addsuffix /.makeall ,$(PARALLEL_DIRS))
+clean :: $(addsuffix /.makeclean ,$(PARALLEL_DIRS))
+clean-all:: $(addsuffix /.makeclean-all,$(PARALLEL_DIRS))
+install :: $(addsuffix /.makeinstall ,$(PARALLEL_DIRS))
+uninstall:: $(addsuffix /.makeuninstall,$(PARALLEL_DIRS))
+install-bytecode :: $(addsuffix /.makeinstall-bytecode,$(PARALLEL_DIRS))
+unitcheck:: $(addsuffix /.makeunitcheck,$(PARALLEL_DIRS))
+
+ParallelTargets := $(foreach T,$(RecursiveTargets),%/.make$(T))
+
+$(ParallelTargets) :
+ $(Verb) \
+ SD=$(PROJ_SRC_DIR)/$(@D); \
+ DD=$(@D); \
+ if [ ! -f $$SD/Makefile ]; then \
+ SD=$(@D); \
+ DD=$(notdir $(@D)); \
+ fi; \
+ if ([ ! -f $$DD/Makefile ] || \
+ command test $$DD/Makefile -ot \
+ $$SD/Makefile ); then \
+ $(MKDIR) $$DD; \
+ $(CP) $$SD/Makefile $$DD/Makefile; \
+ fi; \
+ $(MAKE) -C $$DD $(subst $(@D)/.make,,$@)
+endif
+
+#---------------------------------------------------------
+# Handle the OPTIONAL_DIRS options for directores that may
+# or may not exist.
+#---------------------------------------------------------
+ifdef OPTIONAL_DIRS
+
+SubDirs += $(OPTIONAL_DIRS)
+
+ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT))
+$(RecursiveTargets)::
+ $(Verb) for dir in $(OPTIONAL_DIRS); do \
+ if [ -d $(PROJ_SRC_DIR)/$$dir ]; then\
+ if ([ ! -f $$dir/Makefile ] || \
+ command test $$dir/Makefile -ot $(PROJ_SRC_DIR)/$$dir/Makefile ); then \
+ $(MKDIR) $$dir; \
+ $(CP) $(PROJ_SRC_DIR)/$$dir/Makefile $$dir/Makefile; \
+ fi; \
+ ($(MAKE) -C$$dir $@ ) || exit 1; \
+ fi \
+ done
+else
+$(RecursiveTargets)::
+ $(Verb) for dir in $(OPTIONAL_DIRS); do \
+ if [ -d $(PROJ_SRC_DIR)/$$dir ]; then\
+ ($(MAKE) -C$$dir $@ ) || exit 1; \
+ fi \
+ done
+endif
+endif
+
+#---------------------------------------------------------
+# Handle the CONFIG_FILES options
+#---------------------------------------------------------
+ifdef CONFIG_FILES
+
+ifdef NO_INSTALL
+install-local::
+ $(Echo) Install circumvented with NO_INSTALL
+uninstall-local::
+ $(Echo) UnInstall circumvented with NO_INSTALL
+else
+install-local:: $(DESTDIR)$(PROJ_etcdir) $(CONFIG_FILES)
+ $(Echo) Installing Configuration Files To $(DESTDIR)$(PROJ_etcdir)
+ $(Verb)for file in $(CONFIG_FILES); do \
+ if test -f $(PROJ_OBJ_DIR)/$${file} ; then \
+ $(DataInstall) $(PROJ_OBJ_DIR)/$${file} $(DESTDIR)$(PROJ_etcdir) ; \
+ elif test -f $(PROJ_SRC_DIR)/$${file} ; then \
+ $(DataInstall) $(PROJ_SRC_DIR)/$${file} $(DESTDIR)$(PROJ_etcdir) ; \
+ else \
+ $(ECHO) Error: cannot find config file $${file}. ; \
+ fi \
+ done
+
+uninstall-local::
+ $(Echo) Uninstalling Configuration Files From $(DESTDIR)$(PROJ_etcdir)
+ $(Verb)for file in $(CONFIG_FILES); do \
+ $(RM) -f $(DESTDIR)$(PROJ_etcdir)/$${file} ; \
+ done
+endif
+
+endif
+
+###############################################################################
+# Set up variables for building libraries
+###############################################################################
+
+#---------------------------------------------------------
+# Define various command line options pertaining to the
+# libraries needed when linking. There are "Proj" libs
+# (defined by the user's project) and "LLVM" libs (defined
+# by the LLVM project).
+#---------------------------------------------------------
+
+ifdef USEDLIBS
+ProjLibsOptions := $(patsubst %.a.o, -l%, $(addsuffix .o, $(USEDLIBS)))
+ProjLibsOptions := $(patsubst %.o, $(LibDir)/%.o, $(ProjLibsOptions))
+ProjUsedLibs := $(patsubst %.a.o, lib%.a, $(addsuffix .o, $(USEDLIBS)))
+ProjLibsPaths := $(addprefix $(LibDir)/,$(ProjUsedLibs))
+endif
+
+ifdef LLVMLIBS
+LLVMLibsOptions := $(patsubst %.a.o, -l%, $(addsuffix .o, $(LLVMLIBS)))
+LLVMLibsOptions := $(patsubst %.o, $(LLVMLibDir)/%.o, $(LLVMLibsOptions))
+LLVMUsedLibs := $(patsubst %.a.o, lib%.a, $(addsuffix .o, $(LLVMLIBS)))
+LLVMLibsPaths := $(addprefix $(LLVMLibDir)/,$(LLVMUsedLibs))
+endif
+
+# Loadable module for Win32 requires all symbols resolved for linking.
+# Then all symbols in LLVM.dll will be available.
+ifeq ($(ENABLE_SHARED),1)
+ ifdef LOADABLE_MODULE
+ ifneq (,$(filter $(HOST_OS),Cygwin MingW))
+ LINK_COMPONENTS += all
+ endif
+ endif
+endif
+
+ifndef IS_CLEANING_TARGET
+ifdef LINK_COMPONENTS
+
+# If LLVM_CONFIG doesn't exist, build it. This can happen if you do a make
+# clean in tools, then do a make in tools (instead of at the top level).
+$(LLVM_CONFIG):
+ @echo "*** llvm-config doesn't exist - rebuilding it."
+ @$(MAKE) -C $(PROJ_OBJ_ROOT)/tools/llvm-config
+
+$(ToolDir)/$(strip $(TOOLNAME))$(EXEEXT): $(LLVM_CONFIG)
+
+ifeq ($(ENABLE_SHARED), 1)
+# We can take the "auto-import" feature to get rid of using dllimport.
+ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+LLVMLibsOptions += -Wl,--enable-auto-import,--enable-runtime-pseudo-reloc \
+ -L $(SharedLibDir)
+endif
+LLVMLibsOptions += -lLLVM-$(LLVMVersion)
+LLVMLibsPaths += $(SharedLibDir)/$(SharedPrefix)LLVM-$(LLVMVersion)$(SHLIBEXT)
+else
+
+ifndef NO_LLVM_CONFIG
+LLVMConfigLibs := $(shell $(LLVM_CONFIG) --libs $(LINK_COMPONENTS) || echo Error)
+ifeq ($(LLVMConfigLibs),Error)
+$(error llvm-config --libs failed)
+endif
+LLVMLibsOptions += $(LLVMConfigLibs)
+LLVMConfigLibfiles := $(shell $(LLVM_CONFIG) --libfiles $(LINK_COMPONENTS) || echo Error)
+ifeq ($(LLVMConfigLibfiles),Error)
+$(error llvm-config --libfiles failed)
+endif
+LLVMLibsPaths += $(LLVM_CONFIG) $(LLVMConfigLibfiles)
+endif
+
+endif
+endif
+endif
+
+# Set up the library exports file.
+ifdef EXPORTED_SYMBOL_FILE
+
+# First, set up the native export file, which may differ from the source
+# export file.
+
+ifeq ($(HOST_OS),Darwin)
+# Darwin convention prefixes symbols with underscores.
+NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE)).sed
+$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir
+ $(Verb) sed -e 's/^/_/' < $< > $@
+clean-local::
+ -$(Verb) $(RM) -f $(NativeExportsFile)
+else
+ifeq ($(HAVE_LINK_VERSION_SCRIPT),1)
+# Gold and BFD ld require a version script rather than a plain list.
+NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE)).map
+$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir
+ $(Verb) echo "{" > $@
+ $(Verb) grep -q '[[:alnum:]_]' $< && echo " global:" >> $@ || :
+ $(Verb) sed -e 's/$$/;/' -e 's/^/ /' < $< >> $@
+ifneq ($(HOST_OS),OpenBSD)
+ $(Verb) echo " local: *;" >> $@
+endif
+ $(Verb) echo "};" >> $@
+clean-local::
+ -$(Verb) $(RM) -f $(NativeExportsFile)
+else
+ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+# GNU ld Win32 accepts .DEF files that contain "DATA" entries.
+NativeExportsFile := $(ObjDir)/$(notdir $(EXPORTED_SYMBOL_FILE:.exports=.def))
+$(NativeExportsFile): $(EXPORTED_SYMBOL_FILE) $(ObjDir)/.dir
+ $(Echo) Generating $(notdir $@)
+ $(Verb) $(ECHO) "EXPORTS" > $@
+ $(Verb) $(CAT) $< >> $@
+clean-local::
+ -$(Verb) $(RM) -f $(NativeExportsFile)
+else
+# Default behavior: just use the exports file verbatim.
+NativeExportsFile := $(EXPORTED_SYMBOL_FILE)
+endif
+endif
+endif
+
+# Now add the linker command-line options to use the native export file.
+
+# Darwin
+ifeq ($(HOST_OS),Darwin)
+LLVMLibsOptions += -Wl,-exported_symbols_list,$(NativeExportsFile)
+endif
+
+# gold, bfd ld, etc.
+ifeq ($(HAVE_LINK_VERSION_SCRIPT),1)
+LLVMLibsOptions += -Wl,--version-script,$(NativeExportsFile)
+endif
+
+# Windows
+ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+# LLVMLibsOptions is invalidated at processing tools/llvm-shlib.
+SharedLinkOptions += $(NativeExportsFile)
+endif
+
+endif
+
+###############################################################################
+# Library Build Rules: Four ways to build a library
+###############################################################################
+
+#---------------------------------------------------------
+# Bytecode Module Targets:
+# If the user set MODULE_NAME then they want to build a
+# bytecode module from the sources. We compile all the
+# sources and link it together into a single bytecode
+# module.
+#---------------------------------------------------------
+
+ifdef MODULE_NAME
+ifeq ($(strip $(LLVMCC)),)
+$(warning Modules require LLVM capable compiler but none is available ****)
+else
+
+Module := $(LibDir)/$(MODULE_NAME).bc
+LinkModule := $(LLVMLINK)
+
+
+ifdef EXPORTED_SYMBOL_FILE
+LinkModule += -internalize-public-api-file=$(EXPORTED_SYMBOL_FILE)
+endif
+
+$(Module): $(BUILT_SOURCES) $(ObjectsBC) $(LibDir)/.dir $(LLVMLINK)
+ $(Echo) Building $(BuildMode) Bytecode Module $(notdir $@)
+ $(Verb) $(LinkModule) -o $@ $(ObjectsBC)
+
+all-local:: $(Module)
+
+clean-local::
+ifneq ($(strip $(Module)),)
+ -$(Verb) $(RM) -f $(Module)
+endif
+
+ifdef BYTECODE_DESTINATION
+ModuleDestDir := $(BYTECODE_DESTINATION)
+else
+ModuleDestDir := $(DESTDIR)$(PROJ_libdir)
+endif
+
+ifdef NO_INSTALL
+install-local::
+ $(Echo) Install circumvented with NO_INSTALL
+uninstall-local::
+ $(Echo) Uninstall circumvented with NO_INSTALL
+else
+DestModule := $(ModuleDestDir)/$(MODULE_NAME).bc
+
+install-module:: $(DestModule)
+install-local:: $(DestModule)
+
+$(DestModule): $(ModuleDestDir) $(Module)
+ $(Echo) Installing $(BuildMode) Bytecode Module $(DestModule)
+ $(Verb) $(DataInstall) $(Module) $(DestModule)
+
+uninstall-local::
+ $(Echo) Uninstalling $(BuildMode) Bytecode Module $(DestModule)
+ -$(Verb) $(RM) -f $(DestModule)
+endif
+
+endif
+endif
+
+# if we're building a library ...
+ifdef LIBRARYNAME
+
+# Make sure there isn't any extraneous whitespace on the LIBRARYNAME option
+LIBRARYNAME := $(strip $(LIBRARYNAME))
+ifdef LOADABLE_MODULE
+BaseLibName.A := $(LIBRARYNAME).a
+BaseLibName.SO := $(LIBRARYNAME)$(SHLIBEXT)
+else
+BaseLibName.A := lib$(LIBRARYNAME).a
+BaseLibName.SO := $(SharedPrefix)$(LIBRARYNAME)$(SHLIBEXT)
+endif
+LibName.A := $(LibDir)/$(BaseLibName.A)
+LibName.SO := $(SharedLibDir)/$(BaseLibName.SO)
+LibName.O := $(LibDir)/$(LIBRARYNAME).o
+LibName.BCA:= $(LibDir)/lib$(LIBRARYNAME).bca
+
+#---------------------------------------------------------
+# Shared Library Targets:
+# If the user asked for a shared library to be built
+# with the SHARED_LIBRARY variable, then we provide
+# targets for building them.
+#---------------------------------------------------------
+ifdef SHARED_LIBRARY
+
+all-local:: $(LibName.SO)
+
+ifdef EXPORTED_SYMBOL_FILE
+$(LibName.SO): $(NativeExportsFile)
+endif
+
+ifdef LINK_LIBS_IN_SHARED
+ifdef LOADABLE_MODULE
+SharedLibKindMessage := "Loadable Module"
+SharedLinkOptions := $(LoadableModuleOptions) $(SharedLinkOptions)
+else
+SharedLibKindMessage := "Shared Library"
+endif
+$(LibName.SO): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths) $(SharedLibDir)/.dir
+ $(Echo) Linking $(BuildMode) $(SharedLibKindMessage) \
+ $(notdir $@)
+ $(Verb) $(Link) $(SharedLinkOptions) -o $@ $(ObjectsO) \
+ $(ProjLibsOptions) $(LLVMLibsOptions) $(LIBS)
+else
+$(LibName.SO): $(ObjectsO) $(SharedLibDir)/.dir
+ $(Echo) Linking $(BuildMode) Shared Library $(notdir $@)
+ $(Verb) $(Link) $(SharedLinkOptions) -o $@ $(ObjectsO)
+endif
+
+clean-local::
+ifneq ($(strip $(LibName.SO)),)
+ -$(Verb) $(RM) -f $(LibName.SO)
+endif
+
+ifdef NO_INSTALL
+install-local::
+ $(Echo) Install circumvented with NO_INSTALL
+uninstall-local::
+ $(Echo) Uninstall circumvented with NO_INSTALL
+else
+
+# Win32.DLL prefers to be located on the "PATH" of binaries.
+ifeq ($(HOST_OS), $(filter $(HOST_OS), Cygwin MingW))
+DestSharedLibDir := $(DESTDIR)$(PROJ_bindir)
+else
+DestSharedLibDir := $(DESTDIR)$(PROJ_libdir)
+endif
+DestSharedLib := $(DestSharedLibDir)/$(BaseLibName.SO)
+
+install-local:: $(DestSharedLib)
+
+$(DestSharedLib): $(LibName.SO) $(DestSharedLibDir)
+ $(Echo) Installing $(BuildMode) Shared Library $(DestSharedLib)
+ $(Verb) $(INSTALL) $(LibName.SO) $(DestSharedLib)
+
+uninstall-local::
+ $(Echo) Uninstalling $(BuildMode) Shared Library $(DestSharedLib)
+ -$(Verb) $(RM) -f $(DestSharedLibDir)/$(SharedPrefix)$(LIBRARYNAME).*
+endif
+endif
+
+#---------------------------------------------------------
+# Bytecode Library Targets:
+# If the user asked for a bytecode library to be built
+# with the BYTECODE_LIBRARY variable, then we provide
+# targets for building them.
+#---------------------------------------------------------
+ifdef BYTECODE_LIBRARY
+ifeq ($(strip $(LLVMCC)),)
+$(warning Bytecode libraries require LLVM capable compiler but none is available ****)
+else
+
+all-local:: $(LibName.BCA)
+
+ifdef EXPORTED_SYMBOL_FILE
+BCLinkLib = $(LLVMLINK) -internalize-public-api-file=$(EXPORTED_SYMBOL_FILE)
+
+$(LibName.BCA): $(ObjectsBC) $(LibDir)/.dir $(LLVMLINK) \
+ $(LLVMToolDir)/llvm-ar
+ $(Echo) Building $(BuildMode) Bytecode Archive $(notdir $@) \
+ "(internalize)"
+ $(Verb) $(BCLinkLib) -o $(ObjDir)/$(LIBRARYNAME).internalize $(ObjectsBC)
+ $(Verb) $(RM) -f $@
+ $(Verb) $(LArchive) $@ $(ObjDir)/$(LIBRARYNAME).internalize.bc
+else
+$(LibName.BCA): $(ObjectsBC) $(LibDir)/.dir \
+ $(LLVMToolDir)/llvm-ar
+ $(Echo) Building $(BuildMode) Bytecode Archive $(notdir $@)
+ $(Verb) $(RM) -f $@
+ $(Verb) $(LArchive) $@ $(ObjectsBC)
+
+endif
+
+clean-local::
+ifneq ($(strip $(LibName.BCA)),)
+ -$(Verb) $(RM) -f $(LibName.BCA)
+endif
+
+ifdef BYTECODE_DESTINATION
+BytecodeDestDir := $(BYTECODE_DESTINATION)
+else
+BytecodeDestDir := $(DESTDIR)$(PROJ_libdir)
+endif
+
+DestBytecodeLib = $(BytecodeDestDir)/lib$(LIBRARYNAME).bca
+
+install-bytecode-local:: $(DestBytecodeLib)
+
+ifdef NO_INSTALL
+install-local::
+ $(Echo) Install circumvented with NO_INSTALL
+uninstall-local::
+ $(Echo) Uninstall circumvented with NO_INSTALL
+else
+install-local:: $(DestBytecodeLib)
+
+$(DestBytecodeLib): $(LibName.BCA) $(BytecodeDestDir)
+ $(Echo) Installing $(BuildMode) Bytecode Archive $(DestBytecodeLib)
+ $(Verb) $(DataInstall) $(LibName.BCA) $(DestBytecodeLib)
+
+uninstall-local::
+ $(Echo) Uninstalling $(BuildMode) Bytecode Archive $(DestBytecodeLib)
+ -$(Verb) $(RM) -f $(DestBytecodeLib)
+endif
+endif
+endif
+
+#---------------------------------------------------------
+# Library Targets:
+# If neither BUILD_ARCHIVE or LOADABLE_MODULE are specified, default to
+# building an archive.
+#---------------------------------------------------------
+ifndef NO_BUILD_ARCHIVE
+ifndef BUILD_ARCHIVE
+ifndef LOADABLE_MODULE
+BUILD_ARCHIVE = 1
+endif
+endif
+endif
+
+#---------------------------------------------------------
+# Archive Library Targets:
+# If the user wanted a regular archive library built,
+# then we provide targets for building them.
+#---------------------------------------------------------
+ifdef BUILD_ARCHIVE
+
+all-local:: $(LibName.A)
+
+$(LibName.A): $(ObjectsO) $(LibDir)/.dir
+ $(Echo) Building $(BuildMode) Archive Library $(notdir $@)
+ -$(Verb) $(RM) -f $@
+ $(Verb) $(Archive) $@ $(ObjectsO)
+ $(Verb) $(Ranlib) $@
+
+clean-local::
+ifneq ($(strip $(LibName.A)),)
+ -$(Verb) $(RM) -f $(LibName.A)
+endif
+
+ifdef NO_INSTALL
+install-local::
+ $(Echo) Install circumvented with NO_INSTALL
+uninstall-local::
+ $(Echo) Uninstall circumvented with NO_INSTALL
+else
+ifdef NO_INSTALL_ARCHIVES
+install-local::
+ $(Echo) Install circumvented with NO_INSTALL
+uninstall-local::
+ $(Echo) Uninstall circumvented with NO_INSTALL
+else
+DestArchiveLib := $(DESTDIR)$(PROJ_libdir)/lib$(LIBRARYNAME).a
+
+install-local:: $(DestArchiveLib)
+
+$(DestArchiveLib): $(LibName.A) $(DESTDIR)$(PROJ_libdir)
+ $(Echo) Installing $(BuildMode) Archive Library $(DestArchiveLib)
+ $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_libdir)
+ $(Verb) $(INSTALL) $(LibName.A) $(DestArchiveLib)
+
+uninstall-local::
+ $(Echo) Uninstalling $(BuildMode) Archive Library $(DestArchiveLib)
+ -$(Verb) $(RM) -f $(DestArchiveLib)
+endif
+endif
+endif
+
+# endif LIBRARYNAME
+endif
+
+###############################################################################
+# Tool Build Rules: Build executable tool based on TOOLNAME option
+###############################################################################
+
+ifdef TOOLNAME
+
+#---------------------------------------------------------
+# Set up variables for building a tool.
+#---------------------------------------------------------
+TOOLEXENAME := $(strip $(TOOLNAME))$(EXEEXT)
+ifdef EXAMPLE_TOOL
+ToolBuildPath := $(ExmplDir)/$(TOOLEXENAME)
+else
+ToolBuildPath := $(ToolDir)/$(TOOLEXENAME)
+endif
+
+# TOOLALIAS is a name to symlink (or copy) the tool to.
+ifdef TOOLALIAS
+ifdef EXAMPLE_TOOL
+ToolAliasBuildPath := $(ExmplDir)/$(strip $(TOOLALIAS))$(EXEEXT)
+else
+ToolAliasBuildPath := $(ToolDir)/$(strip $(TOOLALIAS))$(EXEEXT)
+endif
+endif
+
+#---------------------------------------------------------
+# Prune Exports
+#---------------------------------------------------------
+
+# If the tool opts in with TOOL_NO_EXPORTS, optimize startup time of the app by
+# not exporting all of the weak symbols from the binary. This reduces dyld
+# startup time by 4x on darwin in some cases.
+ifdef TOOL_NO_EXPORTS
+ifeq ($(HOST_OS),Darwin)
+
+# Tiger tools don't support this.
+ifneq ($(DARWIN_MAJVERS),4)
+LD.Flags += -Wl,-exported_symbol,_main
+endif
+endif
+
+ifeq ($(HOST_OS), $(filter $(HOST_OS), Linux NetBSD FreeBSD GNU))
+ifneq ($(ARCH), Mips)
+ LD.Flags += -Wl,--version-script=$(LLVM_SRC_ROOT)/autoconf/ExportMap.map
+endif
+endif
+endif
+
+#---------------------------------------------------------
+# Tool Order File Support
+#---------------------------------------------------------
+
+ifeq ($(HOST_OS),Darwin)
+ifdef TOOL_ORDER_FILE
+
+LD.Flags += -Wl,-order_file,$(TOOL_ORDER_FILE)
+
+endif
+endif
+
+#---------------------------------------------------------
+# Tool Version Info Support
+#---------------------------------------------------------
+
+ifeq ($(HOST_OS),Darwin)
+ifdef TOOL_INFO_PLIST
+
+LD.Flags += -Wl,-sectcreate,__TEXT,__info_plist,$(ObjDir)/$(TOOL_INFO_PLIST)
+
+$(ToolBuildPath): $(ObjDir)/$(TOOL_INFO_PLIST)
+
+$(ObjDir)/$(TOOL_INFO_PLIST): $(PROJ_SRC_DIR)/$(TOOL_INFO_PLIST).in $(ObjDir)/.dir
+ $(Echo) "Creating $(TOOLNAME) '$(TOOL_INFO_PLIST)' file..."
+ $(Verb)sed -e "s#@TOOL_INFO_UTI@#$(TOOL_INFO_UTI)#g" \
+ -e "s#@TOOL_INFO_NAME@#$(TOOL_INFO_NAME)#g" \
+ -e "s#@TOOL_INFO_VERSION@#$(TOOL_INFO_VERSION)#g" \
+ -e "s#@TOOL_INFO_BUILD_VERSION@#$(TOOL_INFO_BUILD_VERSION)#g" \
+ $< > $@
+
+endif
+endif
+
+#---------------------------------------------------------
+# Provide targets for building the tools
+#---------------------------------------------------------
+all-local:: $(ToolBuildPath) $(ToolAliasBuildPath)
+
+clean-local::
+ifneq ($(strip $(ToolBuildPath)),)
+ -$(Verb) $(RM) -f $(ToolBuildPath)
+endif
+ifneq ($(strip $(ToolAliasBuildPath)),)
+ -$(Verb) $(RM) -f $(ToolAliasBuildPath)
+endif
+
+ifdef EXAMPLE_TOOL
+$(ToolBuildPath): $(ExmplDir)/.dir
+else
+$(ToolBuildPath): $(ToolDir)/.dir
+endif
+
+ifdef CODESIGN_TOOLS
+$(ToolBuildPath): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths)
+ $(Echo) Linking $(BuildMode) executable $(TOOLNAME) $(StripWarnMsg)
+ $(Verb) $(Link) -o $@ $(TOOLLINKOPTS) $(ObjectsO) $(ProjLibsOptions) \
+ $(LLVMLibsOptions) $(ExtraLibs) $(TOOLLINKOPTSB) $(LIBS)
+ $(Echo) ======= Finished Linking $(BuildMode) Executable $(TOOLNAME) \
+ $(StripWarnMsg)
+ $(Echo) ======= Code-Signing $(BuildMode) Executable $(TOOLNAME)
+ $(Verb) codesign -s - $@
+else
+$(ToolBuildPath): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths)
+ $(Echo) Linking $(BuildMode) executable $(TOOLNAME) $(StripWarnMsg)
+ $(Verb) $(Link) -o $@ $(TOOLLINKOPTS) $(ObjectsO) $(ProjLibsOptions) \
+ $(LLVMLibsOptions) $(ExtraLibs) $(TOOLLINKOPTSB) $(LIBS)
+ $(Echo) ======= Finished Linking $(BuildMode) Executable $(TOOLNAME) \
+ $(StripWarnMsg)
+endif
+
+ifneq ($(strip $(ToolAliasBuildPath)),)
+$(ToolAliasBuildPath): $(ToolBuildPath)
+ $(Echo) Creating $(BuildMode) Alias $(TOOLALIAS) $(StripWarnMsg)
+ $(Verb) $(RM) -f $(ToolAliasBuildPath)
+ $(Verb) $(AliasTool) $(TOOLEXENAME) $(ToolAliasBuildPath)
+ $(Echo) ======= Finished Creating $(BuildMode) Alias $(TOOLALIAS) \
+ $(StripWarnMsg)
+endif
+
+ifdef NO_INSTALL
+install-local::
+ $(Echo) Install circumvented with NO_INSTALL
+uninstall-local::
+ $(Echo) Uninstall circumvented with NO_INSTALL
+else
+
+ifdef INTERNAL_TOOL
+ToolBinDir = $(DESTDIR)$(PROJ_internal_prefix)/bin
+else
+ToolBinDir = $(DESTDIR)$(PROJ_bindir)
+endif
+DestTool = $(ToolBinDir)/$(TOOLEXENAME)
+
+install-local:: $(DestTool)
+
+$(DestTool): $(ToolBuildPath)
+ $(Echo) Installing $(BuildMode) $(DestTool)
+ $(Verb) $(MKDIR) $(ToolBinDir)
+ $(Verb) $(ProgInstall) $(ToolBuildPath) $(DestTool)
+
+uninstall-local::
+ $(Echo) Uninstalling $(BuildMode) $(DestTool)
+ -$(Verb) $(RM) -f $(DestTool)
+
+# TOOLALIAS install.
+ifdef TOOLALIAS
+DestToolAlias = $(ToolBinDir)/$(TOOLALIAS)$(EXEEXT)
+
+install-local:: $(DestToolAlias)
+
+$(DestToolAlias): $(DestTool)
+ $(Echo) Installing $(BuildMode) $(DestToolAlias)
+ $(Verb) $(RM) -f $(DestToolAlias)
+ $(Verb) $(AliasTool) $(TOOLEXENAME) $(DestToolAlias)
+
+uninstall-local::
+ $(Echo) Uninstalling $(BuildMode) $(DestToolAlias)
+ -$(Verb) $(RM) -f $(DestToolAlias)
+endif
+
+endif
+endif
+
+###############################################################################
+# Object Build Rules: Build object files based on sources
+###############################################################################
+
+# FIXME: This should be checking for "if not GCC or ICC", not for "if HP-UX"
+ifeq ($(HOST_OS),HP-UX)
+ DISABLE_AUTO_DEPENDENCIES=1
+endif
+
+# Provide rule sets for when dependency generation is enabled
+ifndef DISABLE_AUTO_DEPENDENCIES
+
+#---------------------------------------------------------
+# Create .o files in the ObjDir directory from the .cpp and .c files...
+#---------------------------------------------------------
+
+DEPEND_OPTIONS = -MMD -MP -MF "$(ObjDir)/$*.d.tmp" \
+ -MT "$(ObjDir)/$*.o" -MT "$(ObjDir)/$*.d"
+
+# If the build succeeded, move the dependency file over, otherwise
+# remove it.
+DEPEND_MOVEFILE = then $(MV) -f "$(ObjDir)/$*.d.tmp" "$(ObjDir)/$*.d"; \
+ else $(RM) "$(ObjDir)/$*.d.tmp"; exit 1; fi
+
+$(ObjDir)/%.o: %.cpp $(ObjDir)/.dir $(BUILT_SOURCES) $(PROJ_MAKEFILE)
+ $(Echo) "Compiling $*.cpp for $(BuildMode) build" $(PIC_FLAG)
+ $(Verb) if $(Compile.CXX) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
+ $(DEPEND_MOVEFILE)
+
+$(ObjDir)/%.o: %.mm $(ObjDir)/.dir $(BUILT_SOURCES) $(PROJ_MAKEFILE)
+ $(Echo) "Compiling $*.mm for $(BuildMode) build" $(PIC_FLAG)
+ $(Verb) if $(Compile.CXX) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
+ $(DEPEND_MOVEFILE)
+
+$(ObjDir)/%.o: %.cc $(ObjDir)/.dir $(BUILT_SOURCES) $(PROJ_MAKEFILE)
+ $(Echo) "Compiling $*.cc for $(BuildMode) build" $(PIC_FLAG)
+ $(Verb) if $(Compile.CXX) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
+ $(DEPEND_MOVEFILE)
+
+$(ObjDir)/%.o: %.c $(ObjDir)/.dir $(BUILT_SOURCES) $(PROJ_MAKEFILE)
+ $(Echo) "Compiling $*.c for $(BuildMode) build" $(PIC_FLAG)
+ $(Verb) if $(Compile.C) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
+ $(DEPEND_MOVEFILE)
+
+$(ObjDir)/%.o: %.m $(ObjDir)/.dir $(BUILT_SOURCES) $(PROJ_MAKEFILE)
+ $(Echo) "Compiling $*.m for $(BuildMode) build" $(PIC_FLAG)
+ $(Verb) if $(Compile.C) $(DEPEND_OPTIONS) $< -o $(ObjDir)/$*.o ; \
+ $(DEPEND_MOVEFILE)
+
+#---------------------------------------------------------
+# Create .bc files in the ObjDir directory from .cpp .cc and .c files...
+#---------------------------------------------------------
+
+BC_DEPEND_OPTIONS = -MMD -MP -MF "$(ObjDir)/$*.bc.d.tmp" \
+ -MT "$(ObjDir)/$*.ll" -MT "$(ObjDir)/$*.bc.d"
+
+# If the build succeeded, move the dependency file over, otherwise
+# remove it.
+BC_DEPEND_MOVEFILE = then $(MV) -f "$(ObjDir)/$*.bc.d.tmp" "$(ObjDir)/$*.bc.d"; \
+ else $(RM) "$(ObjDir)/$*.bc.d.tmp"; exit 1; fi
+
+$(ObjDir)/%.ll: %.cpp $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCXX)
+ $(Echo) "Compiling $*.cpp for $(BuildMode) build (bytecode)"
+ $(Verb) if $(BCCompile.CXX) $(BC_DEPEND_OPTIONS) \
+ $< -o $(ObjDir)/$*.ll -S $(LLVMCC_EMITIR_FLAG) ; \
+ $(BC_DEPEND_MOVEFILE)
+
+$(ObjDir)/%.ll: %.mm $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCXX)
+ $(Echo) "Compiling $*.mm for $(BuildMode) build (bytecode)"
+ $(Verb) if $(BCCompile.CXX) $(BC_DEPEND_OPTIONS) \
+ $< -o $(ObjDir)/$*.ll -S $(LLVMCC_EMITIR_FLAG) ; \
+ $(BC_DEPEND_MOVEFILE)
+
+$(ObjDir)/%.ll: %.cc $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCXX)
+ $(Echo) "Compiling $*.cc for $(BuildMode) build (bytecode)"
+ $(Verb) if $(BCCompile.CXX) $(BC_DEPEND_OPTIONS) \
+ $< -o $(ObjDir)/$*.ll -S $(LLVMCC_EMITIR_FLAG) ; \
+ $(BC_DEPEND_MOVEFILE)
+
+$(ObjDir)/%.ll: %.c $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCC)
+ $(Echo) "Compiling $*.c for $(BuildMode) build (bytecode)"
+ $(Verb) if $(BCCompile.C) $(BC_DEPEND_OPTIONS) \
+ $< -o $(ObjDir)/$*.ll -S $(LLVMCC_EMITIR_FLAG) ; \
+ $(BC_DEPEND_MOVEFILE)
+
+$(ObjDir)/%.ll: %.m $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCC)
+ $(Echo) "Compiling $*.m for $(BuildMode) build (bytecode)"
+ $(Verb) if $(BCCompile.C) $(BC_DEPEND_OPTIONS) \
+ $< -o $(ObjDir)/$*.ll -S $(LLVMCC_EMITIR_FLAG) ; \
+ $(BC_DEPEND_MOVEFILE)
+
+# Provide alternate rule sets if dependencies are disabled
+else
+
+$(ObjDir)/%.o: %.cpp $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.cpp for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.CXX) $< -o $@
+
+$(ObjDir)/%.o: %.mm $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.mm for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.CXX) $< -o $@
+
+$(ObjDir)/%.o: %.cc $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.cc for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.CXX) $< -o $@
+
+$(ObjDir)/%.o: %.c $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.c for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.C) $< -o $@
+
+$(ObjDir)/%.o: %.m $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.m for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.C) $< -o $@
+
+$(ObjDir)/%.ll: %.cpp $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCXX)
+ $(Echo) "Compiling $*.cpp for $(BuildMode) build (bytecode)"
+ $(BCCompile.CXX) $< -o $@ -S $(LLVMCC_EMITIR_FLAG)
+
+$(ObjDir)/%.ll: %.mm $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCXX)
+ $(Echo) "Compiling $*.mm for $(BuildMode) build (bytecode)"
+ $(BCCompile.CXX) $< -o $@ -S $(LLVMCC_EMITIR_FLAG)
+
+$(ObjDir)/%.ll: %.cc $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCXX)
+ $(Echo) "Compiling $*.cc for $(BuildMode) build (bytecode)"
+ $(BCCompile.CXX) $< -o $@ -S $(LLVMCC_EMITIR_FLAG)
+
+$(ObjDir)/%.ll: %.c $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCC)
+ $(Echo) "Compiling $*.c for $(BuildMode) build (bytecode)"
+ $(BCCompile.C) $< -o $@ -S $(LLVMCC_EMITIR_FLAG)
+
+$(ObjDir)/%.ll: %.m $(ObjDir)/.dir $(BUILT_SOURCES) $(LLVMCC)
+ $(Echo) "Compiling $*.m for $(BuildMode) build (bytecode)"
+ $(BCCompile.C) $< -o $@ -S $(LLVMCC_EMITIR_FLAG)
+
+endif
+
+
+## Rules for building preprocessed (.i/.ii) outputs.
+$(BuildMode)/%.ii: %.cpp $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.cpp for $(BuildMode) build to .ii file"
+ $(Verb) $(Preprocess.CXX) $< -o $@
+
+$(BuildMode)/%.ii: %.mm $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.mm for $(BuildMode) build to .ii file"
+ $(Verb) $(Preprocess.CXX) $< -o $@
+
+$(BuildMode)/%.ii: %.cc $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.cc for $(BuildMode) build to .ii file"
+ $(Verb) $(Preprocess.CXX) $< -o $@
+
+$(BuildMode)/%.i: %.c $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.c for $(BuildMode) build to .i file"
+ $(Verb) $(Preprocess.C) $< -o $@
+
+$(BuildMode)/%.i: %.m $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.m for $(BuildMode) build to .i file"
+ $(Verb) $(Preprocess.C) $< -o $@
+
+
+$(ObjDir)/%.s: %.cpp $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.cpp to asm for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.CXX) $< -o $@ -S
+
+$(ObjDir)/%.s: %.mm $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.mm to asm for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.CXX) $< -o $@ -S
+
+$(ObjDir)/%.s: %.cc $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.cc to asm for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.CXX) $< -o $@ -S
+
+$(ObjDir)/%.s: %.c $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.c to asm for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.C) $< -o $@ -S
+
+$(ObjDir)/%.s: %.m $(ObjDir)/.dir $(BUILT_SOURCES)
+ $(Echo) "Compiling $*.m to asm for $(BuildMode) build" $(PIC_FLAG)
+ $(Compile.C) $< -o $@ -S
+
+
+# make the C and C++ compilers strip debug info out of bytecode libraries.
+ifdef DEBUG_RUNTIME
+$(ObjectsBC): $(ObjDir)/%.bc: $(ObjDir)/%.ll $(LOPT)
+ $(Echo) "Compiling $*.ll to $*.bc for $(BuildMode) build (bytecode)"
+ $(Verb) $(LOPT) $< -std-compile-opts -o $@
+else
+$(ObjectsBC): $(ObjDir)/%.bc: $(ObjDir)/%.ll $(LOPT)
+ $(Echo) "Compiling $*.ll to $*.bc for $(BuildMode) build (bytecode)"
+ $(Verb) $(LOPT) $< -std-compile-opts -strip-debug -o $@
+endif
+
+
+#---------------------------------------------------------
+# Provide rule to build .bc files from .ll sources,
+# regardless of dependencies
+#---------------------------------------------------------
+$(ObjDir)/%.bc: %.ll $(ObjDir)/.dir $(LLVMAS)
+ $(Echo) "Compiling $*.ll for $(BuildMode) build"
+ $(Verb) $(LLVMAS) $< -f -o $@
+
+###############################################################################
+# TABLEGEN: Provide rules for running tblgen to produce *.inc files
+###############################################################################
+
+ifdef TARGET
+TABLEGEN_INC_FILES_COMMON = 1
+endif
+
+ifdef TABLEGEN_INC_FILES_COMMON
+
+INCFiles := $(filter %.inc,$(BUILT_SOURCES))
+INCTMPFiles := $(INCFiles:%=$(ObjDir)/%.tmp)
+.PRECIOUS: $(INCTMPFiles) $(INCFiles)
+
+# INCFiles rule: All of the tblgen generated files are emitted to
+# $(ObjDir)/%.inc.tmp, instead of emitting them directly to %.inc. This allows
+# us to only "touch" the real file if the contents of it change. IOW, if
+# tblgen is modified, all of the .inc.tmp files are regenerated, but no
+# dependencies of the .inc files are, unless the contents of the .inc file
+# changes.
+$(INCFiles) : %.inc : $(ObjDir)/%.inc.tmp
+ $(Verb) $(CMP) -s $@ $< || $(CP) $< $@
+
+endif # TABLEGEN_INC_FILES_COMMON
+
+ifdef TARGET
+
+TDFiles := $(strip $(wildcard $(PROJ_SRC_DIR)/*.td) \
+ $(LLVM_SRC_ROOT)/include/llvm/Target/Target.td \
+ $(LLVM_SRC_ROOT)/include/llvm/Target/TargetCallingConv.td \
+ $(LLVM_SRC_ROOT)/include/llvm/Target/TargetSchedule.td \
+ $(LLVM_SRC_ROOT)/include/llvm/Target/TargetSelectionDAG.td \
+ $(LLVM_SRC_ROOT)/include/llvm/CodeGen/ValueTypes.td) \
+ $(wildcard $(LLVM_SRC_ROOT)/include/llvm/Intrinsics*.td)
+
+# All .inc.tmp files depend on the .td files.
+$(INCTMPFiles) : $(TDFiles)
+
+$(TARGET:%=$(ObjDir)/%GenRegisterInfo.inc.tmp): \
+$(ObjDir)/%GenRegisterInfo.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) register info implementation with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-register-info -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenInstrInfo.inc.tmp): \
+$(ObjDir)/%GenInstrInfo.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) instruction information with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-instr-info -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenAsmWriter.inc.tmp): \
+$(ObjDir)/%GenAsmWriter.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) assembly writer with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-asm-writer -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenAsmWriter1.inc.tmp): \
+$(ObjDir)/%GenAsmWriter1.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) assembly writer #1 with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-asm-writer -asmwriternum=1 -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenAsmMatcher.inc.tmp): \
+$(ObjDir)/%GenAsmMatcher.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) assembly matcher with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-asm-matcher -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenMCCodeEmitter.inc.tmp): \
+$(ObjDir)/%GenMCCodeEmitter.inc.tmp: %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) MC code emitter with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-emitter -mc-emitter -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenMCPseudoLowering.inc.tmp): \
+$(ObjDir)/%GenMCPseudoLowering.inc.tmp: %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) MC Pseudo instruction expander with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-pseudo-lowering -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenCodeEmitter.inc.tmp): \
+$(ObjDir)/%GenCodeEmitter.inc.tmp: %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) code emitter with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-emitter -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenDAGISel.inc.tmp): \
+$(ObjDir)/%GenDAGISel.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) DAG instruction selector implementation with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-dag-isel -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenDisassemblerTables.inc.tmp): \
+$(ObjDir)/%GenDisassemblerTables.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) disassembly tables with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-disassembler -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenEDInfo.inc.tmp): \
+$(ObjDir)/%GenEDInfo.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) enhanced disassembly information with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-enhanced-disassembly-info -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenFastISel.inc.tmp): \
+$(ObjDir)/%GenFastISel.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) \"fast\" instruction selector implementation with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-fast-isel -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenSubtargetInfo.inc.tmp): \
+$(ObjDir)/%GenSubtargetInfo.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) subtarget information with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-subtarget -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenCallingConv.inc.tmp): \
+$(ObjDir)/%GenCallingConv.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) calling convention information with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-callingconv -o $(call SYSPATH, $@) $<
+
+$(TARGET:%=$(ObjDir)/%GenIntrinsics.inc.tmp): \
+$(ObjDir)/%GenIntrinsics.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) intrinsics information with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-tgt-intrinsic -o $(call SYSPATH, $@) $<
+
+$(ObjDir)/ARMGenDecoderTables.inc.tmp : ARM.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) decoder tables with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-arm-decoder -o $(call SYSPATH, $@) $<
+
+$(ObjDir)/%GenDFAPacketizer.inc.tmp : %.td $(ObjDir)/.dir $(LLVM_TBLGEN)
+ $(Echo) "Building $(<F) DFA packetizer tables with tblgen"
+ $(Verb) $(LLVMTableGen) -gen-dfa-packetizer -o $(call SYSPATH, $@) $<
+
+clean-local::
+ -$(Verb) $(RM) -f $(INCFiles)
+
+endif # TARGET
+
+###############################################################################
+# OTHER RULES: Other rules needed
+###############################################################################
+
+# To create postscript files from dot files...
+ifneq ($(DOT),false)
+%.ps: %.dot
+ $(DOT) -Tps < $< > $@
+else
+%.ps: %.dot
+ $(Echo) "Cannot build $@: The program dot is not installed"
+endif
+
+# This rules ensures that header files that are removed still have a rule for
+# which they can be "generated." This allows make to ignore them and
+# reproduce the dependency lists.
+%.h:: ;
+%.hpp:: ;
+
+# Define clean-local to clean the current directory. Note that this uses a
+# very conservative approach ensuring that empty variables do not cause
+# errors or disastrous removal.
+clean-local::
+ifneq ($(strip $(ObjRootDir)),)
+ -$(Verb) $(RM) -rf $(ObjRootDir)
+endif
+ifneq ($(strip $(SHLIBEXT)),) # Extra paranoia - make real sure SHLIBEXT is set
+ -$(Verb) $(RM) -f *$(SHLIBEXT)
+endif
+
+clean-all-local::
+ -$(Verb) $(RM) -rf Debug Release Profile
+
+
+###############################################################################
+# DEPENDENCIES: Include the dependency files if we should
+###############################################################################
+ifndef DISABLE_AUTO_DEPENDENCIES
+
+# If its not one of the cleaning targets
+ifndef IS_CLEANING_TARGET
+
+# Get the list of dependency files
+DependSourceFiles := $(basename $(filter %.cpp %.c %.cc %.m %.mm, $(Sources)))
+DependFiles := $(DependSourceFiles:%=$(PROJ_OBJ_DIR)/$(BuildMode)/%.d)
+
+# Include bitcode dependency files if using bitcode libraries
+ifdef BYTECODE_LIBRARY
+DependFiles += $(DependSourceFiles:%=$(PROJ_OBJ_DIR)/$(BuildMode)/%.bc.d)
+endif
+
+-include $(DependFiles) ""
+
+endif
+
+endif
+
+###############################################################################
+# CHECK: Running the test suite
+###############################################################################
+
+check::
+ $(Verb) if test -d "$(PROJ_OBJ_ROOT)/test" ; then \
+ if test -f "$(PROJ_OBJ_ROOT)/test/Makefile" ; then \
+ $(EchoCmd) Running test suite ; \
+ $(MAKE) -C $(PROJ_OBJ_ROOT)/test check-local \
+ TESTSUITE=$(TESTSUITE) ; \
+ else \
+ $(EchoCmd) No Makefile in test directory ; \
+ fi ; \
+ else \
+ $(EchoCmd) No test directory ; \
+ fi
+
+# An alias dating from when both lit and DejaGNU test runners were used.
+check-lit:: check
+
+check-all::
+ $(Verb) if test -d "$(PROJ_OBJ_ROOT)/test" ; then \
+ if test -f "$(PROJ_OBJ_ROOT)/test/Makefile" ; then \
+ $(EchoCmd) Running test suite ; \
+ $(MAKE) -C $(PROJ_OBJ_ROOT)/test check-local-all ; \
+ else \
+ $(EchoCmd) No Makefile in test directory ; \
+ fi ; \
+ else \
+ $(EchoCmd) No test directory ; \
+ fi
+
+###############################################################################
+# UNITTESTS: Running the unittests test suite
+###############################################################################
+
+unittests::
+ $(Verb) if test -d "$(PROJ_OBJ_ROOT)/unittests" ; then \
+ if test -f "$(PROJ_OBJ_ROOT)/unittests/Makefile" ; then \
+ $(EchoCmd) Running unittests test suite ; \
+ $(MAKE) -C $(PROJ_OBJ_ROOT)/unittests unitcheck; \
+ else \
+ $(EchoCmd) No Makefile in unittests directory ; \
+ fi ; \
+ else \
+ $(EchoCmd) No unittests directory ; \
+ fi
+
+###############################################################################
+# DISTRIBUTION: Handle construction of a distribution tarball
+###############################################################################
+
+#------------------------------------------------------------------------
+# Define distribution related variables
+#------------------------------------------------------------------------
+DistName := $(PROJECT_NAME)-$(PROJ_VERSION)
+DistDir := $(PROJ_OBJ_ROOT)/$(DistName)
+TopDistDir := $(PROJ_OBJ_ROOT)/$(DistName)
+DistTarGZip := $(PROJ_OBJ_ROOT)/$(DistName).tar.gz
+DistZip := $(PROJ_OBJ_ROOT)/$(DistName).zip
+DistTarBZ2 := $(PROJ_OBJ_ROOT)/$(DistName).tar.bz2
+DistAlways := CREDITS.TXT LICENSE.TXT README.txt README AUTHORS COPYING \
+ ChangeLog INSTALL NEWS Makefile Makefile.common Makefile.rules \
+ Makefile.config.in configure autoconf
+DistOther := $(notdir $(wildcard \
+ $(PROJ_SRC_DIR)/*.h \
+ $(PROJ_SRC_DIR)/*.td \
+ $(PROJ_SRC_DIR)/*.def \
+ $(PROJ_SRC_DIR)/*.ll \
+ $(PROJ_SRC_DIR)/*.in))
+DistSubDirs := $(SubDirs)
+DistSources = $(Sources) $(EXTRA_DIST)
+DistFiles = $(DistAlways) $(DistSources) $(DistOther)
+
+#------------------------------------------------------------------------
+# We MUST build distribution with OBJ_DIR != SRC_DIR
+#------------------------------------------------------------------------
+ifeq ($(PROJ_SRC_DIR),$(PROJ_OBJ_DIR))
+dist dist-check dist-clean dist-gzip dist-bzip2 dist-zip ::
+ $(Echo) ERROR: Target $@ only available with OBJ_DIR != SRC_DIR
+
+else
+
+#------------------------------------------------------------------------
+# Prevent attempt to run dist targets from anywhere but the top level
+#------------------------------------------------------------------------
+ifneq ($(LEVEL),.)
+dist dist-check dist-clean dist-gzip dist-bzip2 dist-zip ::
+ $(Echo) ERROR: You must run $@ from $(PROJ_OBJ_ROOT)
+else
+
+#------------------------------------------------------------------------
+# Provide the top level targets
+#------------------------------------------------------------------------
+
+dist-gzip:: $(DistTarGZip)
+
+$(DistTarGZip) : $(TopDistDir)/.makedistdir
+ $(Echo) Packing gzipped distribution tar file.
+ $(Verb) cd $(PROJ_OBJ_ROOT) ; $(TAR) chf - "$(DistName)" | \
+ $(GZIP) -c > "$(DistTarGZip)"
+
+dist-bzip2:: $(DistTarBZ2)
+
+$(DistTarBZ2) : $(TopDistDir)/.makedistdir
+ $(Echo) Packing bzipped distribution tar file.
+ $(Verb) cd $(PROJ_OBJ_ROOT) ; $(TAR) chf - $(DistName) | \
+ $(BZIP2) -c >$(DistTarBZ2)
+
+dist-zip:: $(DistZip)
+
+$(DistZip) : $(TopDistDir)/.makedistdir
+ $(Echo) Packing zipped distribution file.
+ $(Verb) rm -f $(DistZip)
+ $(Verb) cd $(PROJ_OBJ_ROOT) ; $(ZIP) -rq $(DistZip) $(DistName)
+
+dist :: $(DistTarGZip) $(DistTarBZ2) $(DistZip)
+ $(Echo) ===== DISTRIBUTION PACKAGING SUCCESSFUL =====
+
+DistCheckDir := $(PROJ_OBJ_ROOT)/_distcheckdir
+
+dist-check:: $(DistTarGZip)
+ $(Echo) Checking distribution tar file.
+ $(Verb) if test -d $(DistCheckDir) ; then \
+ $(RM) -rf $(DistCheckDir) ; \
+ fi
+ $(Verb) $(MKDIR) $(DistCheckDir)
+ $(Verb) cd $(DistCheckDir) && \
+ $(MKDIR) $(DistCheckDir)/build && \
+ $(MKDIR) $(DistCheckDir)/install && \
+ gunzip -c $(DistTarGZip) | $(TAR) xf - && \
+ cd build && \
+ ../$(DistName)/configure --prefix="$(DistCheckDir)/install" \
+ --srcdir=../$(DistName) $(DIST_CHECK_CONFIG_OPTIONS) && \
+ $(MAKE) all && \
+ $(MAKE) check && \
+ $(MAKE) unittests && \
+ $(MAKE) install && \
+ $(MAKE) uninstall && \
+ $(MAKE) dist-clean && \
+ $(EchoCmd) ===== $(DistTarGZip) Ready For Distribution =====
+
+dist-clean::
+ $(Echo) Cleaning distribution files
+ -$(Verb) $(RM) -rf $(DistTarGZip) $(DistTarBZ2) $(DistZip) $(DistName) \
+ $(DistCheckDir)
+
+endif
+
+#------------------------------------------------------------------------
+# Provide the recursive distdir target for building the distribution directory
+#------------------------------------------------------------------------
+distdir: $(DistDir)/.makedistdir
+$(DistDir)/.makedistdir: $(DistSources)
+ $(Verb) if test "$(DistDir)" = "$(TopDistDir)" ; then \
+ if test -d "$(DistDir)" ; then \
+ find $(DistDir) -type d ! -perm -200 -exec chmod u+w {} ';' || \
+ exit 1 ; \
+ fi ; \
+ $(EchoCmd) Removing old $(DistDir) ; \
+ $(RM) -rf $(DistDir); \
+ $(EchoCmd) Making 'all' to verify build ; \
+ $(MAKE) ENABLE_OPTIMIZED=1 all ; \
+ fi
+ $(Echo) Building Distribution Directory $(DistDir)
+ $(Verb) $(MKDIR) $(DistDir)
+ $(Verb) srcdirstrip=`echo "$(PROJ_SRC_DIR)" | sed 's|.|.|g'`; \
+ srcrootstrip=`echo "$(PROJ_SRC_ROOT)" | sed 's|.|.|g'`; \
+ for file in $(DistFiles) ; do \
+ case "$$file" in \
+ $(PROJ_SRC_DIR)/*) \
+ file=`echo "$$file" | sed "s#^$$srcdirstrip/##"` \
+ ;; \
+ $(PROJ_SRC_ROOT)/*) \
+ file=`echo "$$file" | \
+ sed "s#^$$srcrootstrip/##"` \
+ ;; \
+ esac; \
+ if test -f "$(PROJ_SRC_DIR)/$$file" || \
+ test -d "$(PROJ_SRC_DIR)/$$file" ; then \
+ from_dir="$(PROJ_SRC_DIR)" ; \
+ elif test -f "$$file" || test -d "$$file" ; then \
+ from_dir=. ; \
+ fi ; \
+ to_dir=`echo "$$file" | sed -e 's#/[^/]*$$##'` ; \
+ if test "$$to_dir" != "$$file" && test "$$to_dir" != "."; then \
+ to_dir="$(DistDir)/$$dir"; \
+ $(MKDIR) "$$to_dir" ; \
+ else \
+ to_dir="$(DistDir)"; \
+ fi; \
+ mid_dir=`echo "$$file" | sed -n -e 's#^\(.*\)/[^/]*$$#\1#p'`; \
+ if test -n "$$mid_dir" ; then \
+ $(MKDIR) "$$to_dir/$$mid_dir" || exit 1; \
+ fi ; \
+ if test -d "$$from_dir/$$file"; then \
+ if test -d "$(PROJ_SRC_DIR)/$$file" && \
+ test "$$from_dir" != "$(PROJ_SRC_DIR)" ; then \
+ cd $(PROJ_SRC_DIR) ; \
+ $(TAR) cf - $$file --exclude .svn --exclude CVS | \
+ ( cd $$to_dir ; $(TAR) xf - ) ; \
+ cd $(PROJ_OBJ_DIR) ; \
+ else \
+ cd $$from_dir ; \
+ $(TAR) cf - $$file --exclude .svn --exclude CVS | \
+ ( cd $$to_dir ; $(TAR) xf - ) ; \
+ cd $(PROJ_OBJ_DIR) ; \
+ fi; \
+ elif test -f "$$from_dir/$$file" ; then \
+ $(CP) -p "$$from_dir/$$file" "$(DistDir)/$$file" || exit 1; \
+ elif test -L "$$from_dir/$$file" ; then \
+ $(CP) -pd "$$from_dir/$$file" $(DistDir)/$$file || exit 1; \
+ elif echo "$(DistAlways)" | grep -v "$$file" >/dev/null ; then \
+ $(EchoCmd) "===== WARNING: Distribution Source " \
+ "$$from_dir/$$file Not Found!" ; \
+ elif test "$(Verb)" != '@' ; then \
+ $(EchoCmd) "Skipping non-existent $$from_dir/$$file" ; \
+ fi; \
+ done
+ $(Verb) for subdir in $(DistSubDirs) ; do \
+ if test "$$subdir" \!= "." ; then \
+ new_distdir="$(DistDir)/$$subdir" ; \
+ test -d "$$new_distdir" || $(MKDIR) "$$new_distdir" || exit 1; \
+ ( cd $$subdir && $(MAKE) ENABLE_OPTIMIZED=1 \
+ DistDir="$$new_distdir" distdir ) || exit 1; \
+ fi; \
+ done
+ $(Verb) if test "$(DistDir)" = "$(TopDistDir)" ; then \
+ $(EchoCmd) Eliminating CVS/.svn directories from distribution ; \
+ $(RM) -rf `find $(TopDistDir) -type d \( -name CVS -o \
+ -name .svn \) -print` ;\
+ $(MAKE) dist-hook ; \
+ $(FIND) $(TopDistDir) -type d ! -perm -777 -exec chmod a+rwx {} \; \
+ -o ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; \
+ -o ! -type d ! -perm -400 -exec chmod a+r {} \; \
+ -o ! -type d ! -perm -444 -exec \
+ $(SHELL) $(INSTALL_SH) -c -m a+r {} {} \; \
+ || chmod -R a+r $(DistDir) ; \
+ fi
+
+# This is invoked by distdir target, define it as a no-op to avoid errors if not
+# defined by user.
+dist-hook::
+
+endif
+
+###############################################################################
+# TOP LEVEL - targets only to apply at the top level directory
+###############################################################################
+
+ifeq ($(LEVEL),.)
+
+#------------------------------------------------------------------------
+# Install support for the project's include files:
+#------------------------------------------------------------------------
+ifdef NO_INSTALL
+install-local::
+ $(Echo) Install circumvented with NO_INSTALL
+uninstall-local::
+ $(Echo) Uninstall circumvented with NO_INSTALL
+else
+install-local::
+ $(Echo) Installing include files
+ $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_includedir)
+ $(Verb) if test -d "$(PROJ_SRC_ROOT)/include" ; then \
+ cd $(PROJ_SRC_ROOT)/include && \
+ for hdr in `find . -type f \
+ '(' -name LICENSE.TXT \
+ -o -name '*.def' \
+ -o -name '*.h' \
+ -o -name '*.inc' \
+ -o -name '*.td' \
+ ')' -print | grep -v CVS | \
+ grep -v .svn` ; do \
+ instdir=`dirname "$(DESTDIR)$(PROJ_includedir)/$$hdr"` ; \
+ if test \! -d "$$instdir" ; then \
+ $(EchoCmd) Making install directory $$instdir ; \
+ $(MKDIR) $$instdir ;\
+ fi ; \
+ $(DataInstall) $$hdr $(DESTDIR)$(PROJ_includedir)/$$hdr ; \
+ done ; \
+ fi
+ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT))
+ $(Verb) if test -d "$(PROJ_OBJ_ROOT)/include" ; then \
+ cd $(PROJ_OBJ_ROOT)/include && \
+ for hdr in `find . -type f \
+ '(' -name LICENSE.TXT \
+ -o -name '*.def' \
+ -o -name '*.h' \
+ -o -name '*.inc' \
+ -o -name '*.td' \
+ ')' -print | grep -v CVS | \
+ grep -v .svn` ; do \
+ instdir=`dirname "$(DESTDIR)$(PROJ_includedir)/$$hdr"` ; \
+ if test \! -d "$$instdir" ; then \
+ $(EchoCmd) Making install directory $$instdir ; \
+ $(MKDIR) $$instdir ;\
+ fi ; \
+ $(DataInstall) $$hdr $(DESTDIR)$(PROJ_includedir)/$$hdr ; \
+ done ; \
+ fi
+endif
+
+uninstall-local::
+ $(Echo) Uninstalling include files
+ $(Verb) if [ -d "$(PROJ_SRC_ROOT)/include" ] ; then \
+ cd $(PROJ_SRC_ROOT)/include && \
+ $(RM) -f `find . -path '*/Internal' -prune -o '(' -type f \
+ '!' '(' -name '*~' -o -name '.#*' \
+ -o -name '*.in' ')' -print ')' | \
+ grep -v CVS | sed 's#^#$(DESTDIR)$(PROJ_includedir)/#'` ; \
+ cd $(PROJ_SRC_ROOT)/include && \
+ $(RM) -f `find . -path '*/Internal' -prune -o '(' -type f -name '*.in' \
+ -print ')' | sed 's#\.in$$##;s#^#$(DESTDIR)$(PROJ_includedir)/#'` ; \
+ fi
+endif
+endif
+
+check-line-length:
+ @echo searching for overlength lines in files: $(Sources)
+ @echo
+ @echo
+ egrep -n '.{81}' $(Sources) /dev/null
+
+check-for-tabs:
+ @echo searching for tabs in files: $(Sources)
+ @echo
+ @echo
+ egrep -n ' ' $(Sources) /dev/null
+
+check-footprint:
+ @ls -l $(LibDir) | awk '\
+ BEGIN { sum = 0; } \
+ { sum += $$5; } \
+ END { printf("Libraries: %6.3f MBytes\n", sum/(1024.0*1024.0)); }'
+ @ls -l $(ToolDir) | awk '\
+ BEGIN { sum = 0; } \
+ { sum += $$5; } \
+ END { printf("Programs: %6.3f MBytes\n", sum/(1024.0*1024.0)); }'
+#------------------------------------------------------------------------
+# Print out the directories used for building
+#------------------------------------------------------------------------
+printvars::
+ $(Echo) "BuildMode : " '$(BuildMode)'
+ $(Echo) "PROJ_SRC_ROOT: " '$(PROJ_SRC_ROOT)'
+ $(Echo) "PROJ_SRC_DIR : " '$(PROJ_SRC_DIR)'
+ $(Echo) "PROJ_OBJ_ROOT: " '$(PROJ_OBJ_ROOT)'
+ $(Echo) "PROJ_OBJ_DIR : " '$(PROJ_OBJ_DIR)'
+ $(Echo) "LLVM_SRC_ROOT: " '$(LLVM_SRC_ROOT)'
+ $(Echo) "LLVM_OBJ_ROOT: " '$(LLVM_OBJ_ROOT)'
+ $(Echo) "PROJ_prefix : " '$(PROJ_prefix)'
+ $(Echo) "PROJ_internal_prefix : " '$(PROJ_internal_prefix)'
+ $(Echo) "PROJ_bindir : " '$(PROJ_bindir)'
+ $(Echo) "PROJ_libdir : " '$(PROJ_libdir)'
+ $(Echo) "PROJ_etcdir : " '$(PROJ_etcdir)'
+ $(Echo) "PROJ_includedir : " '$(PROJ_includedir)'
+ $(Echo) "UserTargets : " '$(UserTargets)'
+ $(Echo) "ObjMakefiles : " '$(ObjMakefiles)'
+ $(Echo) "SrcMakefiles : " '$(SrcMakefiles)'
+ $(Echo) "ObjDir : " '$(ObjDir)'
+ $(Echo) "LibDir : " '$(LibDir)'
+ $(Echo) "ToolDir : " '$(ToolDir)'
+ $(Echo) "ExmplDir : " '$(ExmplDir)'
+ $(Echo) "Sources : " '$(Sources)'
+ $(Echo) "TDFiles : " '$(TDFiles)'
+ $(Echo) "INCFiles : " '$(INCFiles)'
+ $(Echo) "INCTMPFiles : " '$(INCTMPFiles)'
+ $(Echo) "PreConditions: " '$(PreConditions)'
+ $(Echo) "Compile.CXX : " '$(Compile.CXX)'
+ $(Echo) "Compile.C : " '$(Compile.C)'
+ $(Echo) "Archive : " '$(Archive)'
+ $(Echo) "YaccFiles : " '$(YaccFiles)'
+ $(Echo) "LexFiles : " '$(LexFiles)'
+ $(Echo) "Module : " '$(Module)'
+ $(Echo) "FilesToConfig: " '$(FilesToConfigPATH)'
+ $(Echo) "SubDirs : " '$(SubDirs)'
+ $(Echo) "ProjLibsPaths: " '$(ProjLibsPaths)'
+ $(Echo) "ProjLibsOptions: " '$(ProjLibsOptions)'
+
+###
+# Debugging
+
+# General debugging rule, use 'make dbg-print-XXX' to print the
+# definition, value and origin of XXX.
+make-print-%:
+ $(error PRINT: $(value $*) = "$($*)" (from $(origin $*)))
diff --git a/README.txt b/README.txt
new file mode 100644
index 00000000000..0d39ed6934b
--- /dev/null
+++ b/README.txt
@@ -0,0 +1,17 @@
+Low Level Virtual Machine (LLVM)
+================================
+
+This directory and its subdirectories contain source code for the Low Level
+Virtual Machine, a toolkit for the construction of highly optimized compilers,
+optimizers, and runtime environments.
+
+LLVM is open source software. You may freely distribute it under the terms of
+the license agreement found in LICENSE.txt.
+
+Please see the HTML documentation provided in docs/index.html for further
+assistance with LLVM.
+
+If you're writing a package for LLVM, see docs/Packaging.html for our
+suggestions.
+
+
diff --git a/autoconf/AutoRegen.sh b/autoconf/AutoRegen.sh
new file mode 100755
index 00000000000..7809667ac5f
--- /dev/null
+++ b/autoconf/AutoRegen.sh
@@ -0,0 +1,58 @@
+#!/bin/bash
+
+die() {
+ echo "$@" 1>&2
+ exit 1
+}
+
+clean() {
+ echo $1 | sed -e 's/\\//g'
+}
+
+### NOTE: ############################################################
+### These variables specify the tool versions we want to use.
+### Periods should be escaped with backslash for use by grep.
+###
+### If you update these, please also update docs/GettingStarted.html
+want_autoconf_version='2\.60'
+want_autoheader_version=$want_autoconf_version
+want_aclocal_version='1\.9\.6'
+want_libtool_version='1\.5\.22'
+### END NOTE #########################################################
+
+outfile=configure
+configfile=configure.ac
+
+want_autoconf_version_clean=$(clean $want_autoconf_version)
+want_autoheader_version_clean=$(clean $want_autoheader_version)
+want_aclocal_version_clean=$(clean $want_aclocal_version)
+want_libtool_version_clean=$(clean $want_libtool_version)
+
+test -d autoconf && test -f autoconf/$configfile && cd autoconf
+test -f $configfile || die "Can't find 'autoconf' dir; please cd into it first"
+autoconf --version | grep $want_autoconf_version > /dev/null
+test $? -eq 0 || die "Your autoconf was not detected as being $want_autoconf_version_clean"
+aclocal --version | grep '^aclocal.*'$want_aclocal_version > /dev/null
+test $? -eq 0 || die "Your aclocal was not detected as being $want_aclocal_version_clean"
+autoheader --version | grep '^autoheader.*'$want_autoheader_version > /dev/null
+test $? -eq 0 || die "Your autoheader was not detected as being $want_autoheader_version_clean"
+libtool --version | grep $want_libtool_version > /dev/null
+test $? -eq 0 || die "Your libtool was not detected as being $want_libtool_version_clean"
+echo ""
+echo "### NOTE: ############################################################"
+echo "### If you get *any* warnings from autoconf below you MUST fix the"
+echo "### scripts in the m4 directory because there are future forward"
+echo "### compatibility or platform support issues at risk. Please do NOT"
+echo "### commit any configure script that was generated with warnings"
+echo "### present. You should get just three 'Regenerating..' lines."
+echo "######################################################################"
+echo ""
+echo "Regenerating aclocal.m4 with aclocal $want_aclocal_version_clean"
+cwd=`pwd`
+aclocal --force -I $cwd/m4 || die "aclocal failed"
+echo "Regenerating configure with autoconf $want_autoconf_version_clean"
+autoconf --force --warnings=all -o ../$outfile $configfile || die "autoconf failed"
+cd ..
+echo "Regenerating config.h.in with autoheader $want_autoheader_version_clean"
+autoheader --warnings=all -I autoconf -I autoconf/m4 autoconf/$configfile || die "autoheader failed"
+exit 0
diff --git a/autoconf/ExportMap.map b/autoconf/ExportMap.map
new file mode 100644
index 00000000000..17b185fed91
--- /dev/null
+++ b/autoconf/ExportMap.map
@@ -0,0 +1,7 @@
+{
+ global: main;
+ __progname;
+ environ;
+
+ local: *;
+};
diff --git a/autoconf/LICENSE.TXT b/autoconf/LICENSE.TXT
new file mode 100644
index 00000000000..72fdd39edcc
--- /dev/null
+++ b/autoconf/LICENSE.TXT
@@ -0,0 +1,24 @@
+------------------------------------------------------------------------------
+Autoconf Files
+------------------------------------------------------------------------------
+All autoconf files are licensed under the LLVM license with the following
+additions:
+
+llvm/autoconf/install-sh:
+ This script is licensed under the LLVM license, with the following
+ additional copyrights and restrictions:
+
+ Copyright 1991 by the Massachusetts Institute of Technology
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation, and that the name of M.I.T. not be used in advertising or
+ publicity pertaining to distribution of the software without specific,
+ written prior permission. M.I.T. makes no representations about the
+ suitability of this software for any purpose. It is provided "as is"
+ without express or implied warranty.
+
+Please see the source files for additional copyrights.
+
diff --git a/autoconf/README.TXT b/autoconf/README.TXT
new file mode 100644
index 00000000000..3dabdf7b879
--- /dev/null
+++ b/autoconf/README.TXT
@@ -0,0 +1,49 @@
+Upgrading Libtool
+===============================================================================
+
+If you are in the mood to upgrade libtool, you must do the following:
+
+ 1. Get the new version of libtool and put it in <SRC>
+ 2. configure/build/install libtool with --prefix=<PFX>
+ 3. Copy <SRC>/ltdl.m4 to llvm/autoconf/m4
+ 4. Copy <PFX>/share/aclocal/libtool.m4 to llvm/autoconf/m4/libtool.m4
+ 5. Copy <PFX>/share/libtool/ltmain.sh to llvm/autoconf/ltmain.sh
+ 6. Copy <PFX>/share/libtool/libltdl/ltdl.c to llvm/lib/System
+ 7. Copy <PFX>/share/libtool/libltdl/ltdl.h to llvm/lib/System
+ 8. Edit the ltdl.h file to #include "llvm/Config/config.h" at the very top. You
+ might also need to resolve some compiler warnings (typically about
+ comparison of signed vs. unsigned values). But, you won't find out about
+ those until you build LLVM (step 13).
+ 9. Edit the llvm/autoconf/m4/libtool.m4 file so that:
+ a) in AC_PROB_LIBTOOL macro, the value of LIBTOOL is set to
+ $(top_builddir)/mklib, not $(top_builddir)/libtool
+ b) in AC_LIBTOOL_SETUP macro, the variable default_ofile is set to
+ "mklib" instead of "libtool"
+ c) s/AC_ENABLE_SHARED_DEFAULT/enable_shared_default/g
+ d) s/AC_ENABLE_STATIC_DEFAULT/enable_static_default/g
+ e) s/AC_ENABLE_FAST_INSTALL_DEFAULT/enable_fast_install_default/g
+10. Run "autoupdate libtool.m4 ltdl.m4" in the llvm/autoconf/m4 directory.
+ This should correctly update the macro definitions in the libtool m4
+ files to match the version of autoconf that LLVM uses. This converts
+ AC_HELP_STRING to AS_HELP_STRING and AC_TRY_LINK to AC_LINK_IFELSE, amongst
+ other things. You may need to manually adjust the files.
+11. Run AutoRegen.sh to get the new macros into configure script
+12. If there are any warnings from AutoRegen.sh, go to step 9.
+13. Rebuild LLVM, making sure it reconfigures
+14. Test the JIT which uses libltdl
+15. If it all works, only THEN commit the changes.
+
+Upgrading autoconf
+===============================================================================
+
+If you are in the mood to upgrade autoconf, you should:
+
+ 1. Consider not upgrading.
+ 2. No really, this is a hassle, you don't want to do it.
+ 3. Get the new version of autoconf and put it in <SRC>
+ 4. configure/build/install autoconf with --prefix=<PFX>
+ 5. Run autoupdate on all the m4 macros in llvm/autoconf/m4
+ 6. Run autoupdate on llvm/autoconf/configure.ac
+ 7. Regenerate configure script with AutoRegen.sh
+ 8. If there are any warnings from AutoRegen.sh, fix them and go to step 7.
+ 9. Test, test, test.
diff --git a/autoconf/config.guess b/autoconf/config.guess
new file mode 100755
index 00000000000..dd6dcb3d92a
--- /dev/null
+++ b/autoconf/config.guess
@@ -0,0 +1,1520 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+# 2011 Free Software Foundation, Inc.
+
+timestamp='2011-08-20'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Originally written by Per Bothner. Please send patches (context
+# diff format) to <config-patches@gnu.org> and include a ChangeLog
+# entry.
+#
+# This script attempts to guess a canonical system name similar to
+# config.sub. If it succeeds, it prints the system name on stdout, and
+# exits with 0. Otherwise, it exits with 1.
+#
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
+2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free
+Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit ;;
+ --version | -v )
+ echo "$version" ; exit ;;
+ --help | --h* | -h )
+ echo "$usage"; exit ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help" >&2
+ exit 1 ;;
+ * )
+ break ;;
+ esac
+done
+
+if test $# != 0; then
+ echo "$me: too many arguments$help" >&2
+ exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,) echo "int x;" > $dummy.c ;
+ for c in cc gcc c89 c99 ; do
+ if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+ CC_FOR_BUILD="$c"; break ;
+ fi ;
+ done ;
+ if test x"$CC_FOR_BUILD" = x ; then
+ CC_FOR_BUILD=no_compiler_found ;
+ fi
+ ;;
+ ,,*) CC_FOR_BUILD=$CC ;;
+ ,*,*) CC_FOR_BUILD=$HOST_CC ;;
+esac ; set_cc_for_build= ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi@noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+ PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+ *:NetBSD:*:*)
+ # NetBSD (nbsd) targets should (where applicable) match one or
+ # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
+ # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently
+ # switched to ELF, *-*-netbsd* would select the old
+ # object file format. This provides both forward
+ # compatibility and a consistent mechanism for selecting the
+ # object file format.
+ #
+ # Note: NetBSD doesn't particularly care about the vendor
+ # portion of the name. We always set it to "unknown".
+ sysctl="sysctl -n hw.machine_arch"
+ UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+ /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+ case "${UNAME_MACHINE_ARCH}" in
+ armeb) machine=armeb-unknown ;;
+ arm*) machine=arm-unknown ;;
+ sh3el) machine=shl-unknown ;;
+ sh3eb) machine=sh-unknown ;;
+ sh5el) machine=sh5le-unknown ;;
+ *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+ esac
+ # The Operating System including object format, if it has switched
+ # to ELF recently, or will in the future.
+ case "${UNAME_MACHINE_ARCH}" in
+ arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+ eval $set_cc_for_build
+ if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ELF__
+ then
+ # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+ # Return netbsd for either. FIX?
+ os=netbsd
+ else
+ os=netbsdelf
+ fi
+ ;;
+ *)
+ os=netbsd
+ ;;
+ esac
+ # The OS release
+ # Debian GNU/NetBSD machines have a different userland, and
+ # thus, need a distinct triplet. However, they do not need
+ # kernel version information, so it can be replaced with a
+ # suitable tag, in the style of linux-gnu.
+ case "${UNAME_VERSION}" in
+ Debian*)
+ release='-gnu'
+ ;;
+ *)
+ release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+ ;;
+ esac
+ # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+ # contains redundant information, the shorter form:
+ # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+ echo "${machine}-${os}${release}"
+ exit ;;
+ *:OpenBSD:*:*)
+ UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+ echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+ exit ;;
+ *:Bitrig:*:*)
+ UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
+ echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE}
+ exit ;;
+ *:ekkoBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+ exit ;;
+ *:SolidBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+ exit ;;
+ macppc:MirBSD:*:*)
+ echo powerpc-unknown-mirbsd${UNAME_RELEASE}
+ exit ;;
+ *:MirBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+ exit ;;
+ alpha:OSF1:*:*)
+ case $UNAME_RELEASE in
+ *4.0)
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+ ;;
+ *5.*)
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+ ;;
+ esac
+ # According to Compaq, /usr/sbin/psrinfo has been available on
+ # OSF/1 and Tru64 systems produced since 1995. I hope that
+ # covers most systems running today. This code pipes the CPU
+ # types through head -n 1, so we only detect the type of CPU 0.
+ ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+ case "$ALPHA_CPU_TYPE" in
+ "EV4 (21064)")
+ UNAME_MACHINE="alpha" ;;
+ "EV4.5 (21064)")
+ UNAME_MACHINE="alpha" ;;
+ "LCA4 (21066/21068)")
+ UNAME_MACHINE="alpha" ;;
+ "EV5 (21164)")
+ UNAME_MACHINE="alphaev5" ;;
+ "EV5.6 (21164A)")
+ UNAME_MACHINE="alphaev56" ;;
+ "EV5.6 (21164PC)")
+ UNAME_MACHINE="alphapca56" ;;
+ "EV5.7 (21164PC)")
+ UNAME_MACHINE="alphapca57" ;;
+ "EV6 (21264)")
+ UNAME_MACHINE="alphaev6" ;;
+ "EV6.7 (21264A)")
+ UNAME_MACHINE="alphaev67" ;;
+ "EV6.8CB (21264C)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.8AL (21264B)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.8CX (21264D)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.9A (21264/EV69A)")
+ UNAME_MACHINE="alphaev69" ;;
+ "EV7 (21364)")
+ UNAME_MACHINE="alphaev7" ;;
+ "EV7.9 (21364A)")
+ UNAME_MACHINE="alphaev79" ;;
+ esac
+ # A Pn.n version is a patched version.
+ # A Vn.n version is a released version.
+ # A Tn.n version is a released field test version.
+ # A Xn.n version is an unreleased experimental baselevel.
+ # 1.2 uses "1.2" for uname -r.
+ echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+ # Reset EXIT trap before exiting to avoid spurious non-zero exit code.
+ exitcode=$?
+ trap '' 0
+ exit $exitcode ;;
+ Alpha\ *:Windows_NT*:*)
+ # How do we know it's Interix rather than the generic POSIX subsystem?
+ # Should we change UNAME_MACHINE based on the output of uname instead
+ # of the specific Alpha model?
+ echo alpha-pc-interix
+ exit ;;
+ 21064:Windows_NT:50:3)
+ echo alpha-dec-winnt3.5
+ exit ;;
+ Amiga*:UNIX_System_V:4.0:*)
+ echo m68k-unknown-sysv4
+ exit ;;
+ *:[Aa]miga[Oo][Ss]:*:*)
+ echo ${UNAME_MACHINE}-unknown-amigaos
+ exit ;;
+ *:[Mm]orph[Oo][Ss]:*:*)
+ echo ${UNAME_MACHINE}-unknown-morphos
+ exit ;;
+ *:OS/390:*:*)
+ echo i370-ibm-openedition
+ exit ;;
+ *:z/VM:*:*)
+ echo s390-ibm-zvmoe
+ exit ;;
+ *:OS400:*:*)
+ echo powerpc-ibm-os400
+ exit ;;
+ arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+ echo arm-acorn-riscix${UNAME_RELEASE}
+ exit ;;
+ arm:riscos:*:*|arm:RISCOS:*:*)
+ echo arm-unknown-riscos
+ exit ;;
+ SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+ echo hppa1.1-hitachi-hiuxmpp
+ exit ;;
+ Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+ # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+ if test "`(/bin/universe) 2>/dev/null`" = att ; then
+ echo pyramid-pyramid-sysv3
+ else
+ echo pyramid-pyramid-bsd
+ fi
+ exit ;;
+ NILE*:*:*:dcosx)
+ echo pyramid-pyramid-svr4
+ exit ;;
+ DRS?6000:unix:4.0:6*)
+ echo sparc-icl-nx6
+ exit ;;
+ DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+ case `/usr/bin/uname -p` in
+ sparc) echo sparc-icl-nx7; exit ;;
+ esac ;;
+ s390x:SunOS:*:*)
+ echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4H:SunOS:5.*:*)
+ echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+ echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+ echo i386-pc-auroraux${UNAME_RELEASE}
+ exit ;;
+ i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+ eval $set_cc_for_build
+ SUN_ARCH="i386"
+ # If there is a compiler, see if it is configured for 64-bit objects.
+ # Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+ # This test works for both compilers.
+ if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+ if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+ grep IS_64BIT_ARCH >/dev/null
+ then
+ SUN_ARCH="x86_64"
+ fi
+ fi
+ echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:6*:*)
+ # According to config.sub, this is the proper way to canonicalize
+ # SunOS6. Hard to guess exactly what SunOS6 will be like, but
+ # it's likely to be more like Solaris than SunOS4.
+ echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:*:*)
+ case "`/usr/bin/arch -k`" in
+ Series*|S4*)
+ UNAME_RELEASE=`uname -v`
+ ;;
+ esac
+ # Japanese Language versions have a version number like `4.1.3-JL'.
+ echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+ exit ;;
+ sun3*:SunOS:*:*)
+ echo m68k-sun-sunos${UNAME_RELEASE}
+ exit ;;
+ sun*:*:4.2BSD:*)
+ UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+ test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+ case "`/bin/arch`" in
+ sun3)
+ echo m68k-sun-sunos${UNAME_RELEASE}
+ ;;
+ sun4)
+ echo sparc-sun-sunos${UNAME_RELEASE}
+ ;;
+ esac
+ exit ;;
+ aushp:SunOS:*:*)
+ echo sparc-auspex-sunos${UNAME_RELEASE}
+ exit ;;
+ # The situation for MiNT is a little confusing. The machine name
+ # can be virtually everything (everything which is not
+ # "atarist" or "atariste" at least should have a processor
+ # > m68000). The system name ranges from "MiNT" over "FreeMiNT"
+ # to the lowercase version "mint" (or "freemint"). Finally
+ # the system name "TOS" denotes a system which is actually not
+ # MiNT. But MiNT is downward compatible to TOS, so this should
+ # be no problem.
+ atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+ echo m68k-milan-mint${UNAME_RELEASE}
+ exit ;;
+ hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+ echo m68k-hades-mint${UNAME_RELEASE}
+ exit ;;
+ *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+ echo m68k-unknown-mint${UNAME_RELEASE}
+ exit ;;
+ m68k:machten:*:*)
+ echo m68k-apple-machten${UNAME_RELEASE}
+ exit ;;
+ powerpc:machten:*:*)
+ echo powerpc-apple-machten${UNAME_RELEASE}
+ exit ;;
+ RISC*:Mach:*:*)
+ echo mips-dec-mach_bsd4.3
+ exit ;;
+ RISC*:ULTRIX:*:*)
+ echo mips-dec-ultrix${UNAME_RELEASE}
+ exit ;;
+ VAX*:ULTRIX*:*:*)
+ echo vax-dec-ultrix${UNAME_RELEASE}
+ exit ;;
+ 2020:CLIX:*:* | 2430:CLIX:*:*)
+ echo clipper-intergraph-clix${UNAME_RELEASE}
+ exit ;;
+ mips:*:*:UMIPS | mips:*:*:RISCos)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h> /* for printf() prototype */
+ int main (int argc, char *argv[]) {
+#else
+ int main (argc, argv) int argc; char *argv[]; {
+#endif
+ #if defined (host_mips) && defined (MIPSEB)
+ #if defined (SYSTYPE_SYSV)
+ printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_SVR4)
+ printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+ printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+ #endif
+ #endif
+ exit (-1);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c &&
+ dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+ SYSTEM_NAME=`$dummy $dummyarg` &&
+ { echo "$SYSTEM_NAME"; exit; }
+ echo mips-mips-riscos${UNAME_RELEASE}
+ exit ;;
+ Motorola:PowerMAX_OS:*:*)
+ echo powerpc-motorola-powermax
+ exit ;;
+ Motorola:*:4.3:PL8-*)
+ echo powerpc-harris-powermax
+ exit ;;
+ Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+ echo powerpc-harris-powermax
+ exit ;;
+ Night_Hawk:Power_UNIX:*:*)
+ echo powerpc-harris-powerunix
+ exit ;;
+ m88k:CX/UX:7*:*)
+ echo m88k-harris-cxux7
+ exit ;;
+ m88k:*:4*:R4*)
+ echo m88k-motorola-sysv4
+ exit ;;
+ m88k:*:3*:R3*)
+ echo m88k-motorola-sysv3
+ exit ;;
+ AViiON:dgux:*:*)
+ # DG/UX returns AViiON for all architectures
+ UNAME_PROCESSOR=`/usr/bin/uname -p`
+ if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+ then
+ if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+ [ ${TARGET_BINARY_INTERFACE}x = x ]
+ then
+ echo m88k-dg-dgux${UNAME_RELEASE}
+ else
+ echo m88k-dg-dguxbcs${UNAME_RELEASE}
+ fi
+ else
+ echo i586-dg-dgux${UNAME_RELEASE}
+ fi
+ exit ;;
+ M88*:DolphinOS:*:*) # DolphinOS (SVR3)
+ echo m88k-dolphin-sysv3
+ exit ;;
+ M88*:*:R3*:*)
+ # Delta 88k system running SVR3
+ echo m88k-motorola-sysv3
+ exit ;;
+ XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+ echo m88k-tektronix-sysv3
+ exit ;;
+ Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+ echo m68k-tektronix-bsd
+ exit ;;
+ *:IRIX*:*:*)
+ echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+ exit ;;
+ ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+ echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id
+ exit ;; # Note that: echo "'`uname -s`'" gives 'AIX '
+ i*86:AIX:*:*)
+ echo i386-ibm-aix
+ exit ;;
+ ia64:AIX:*:*)
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+ fi
+ echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+ exit ;;
+ *:AIX:2:3)
+ if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <sys/systemcfg.h>
+
+ main()
+ {
+ if (!__power_pc())
+ exit(1);
+ puts("powerpc-ibm-aix3.2.5");
+ exit(0);
+ }
+EOF
+ if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+ then
+ echo "$SYSTEM_NAME"
+ else
+ echo rs6000-ibm-aix3.2.5
+ fi
+ elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+ echo rs6000-ibm-aix3.2.4
+ else
+ echo rs6000-ibm-aix3.2
+ fi
+ exit ;;
+ *:AIX:*:[4567])
+ IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+ if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+ IBM_ARCH=rs6000
+ else
+ IBM_ARCH=powerpc
+ fi
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+ fi
+ echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+ exit ;;
+ *:AIX:*:*)
+ echo rs6000-ibm-aix
+ exit ;;
+ ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+ echo romp-ibm-bsd4.4
+ exit ;;
+ ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
+ echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to
+ exit ;; # report: romp-ibm BSD 4.3
+ *:BOSX:*:*)
+ echo rs6000-bull-bosx
+ exit ;;
+ DPX/2?00:B.O.S.:*:*)
+ echo m68k-bull-sysv3
+ exit ;;
+ 9000/[34]??:4.3bsd:1.*:*)
+ echo m68k-hp-bsd
+ exit ;;
+ hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+ echo m68k-hp-bsd4.4
+ exit ;;
+ 9000/[34678]??:HP-UX:*:*)
+ HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+ case "${UNAME_MACHINE}" in
+ 9000/31? ) HP_ARCH=m68000 ;;
+ 9000/[34]?? ) HP_ARCH=m68k ;;
+ 9000/[678][0-9][0-9])
+ if [ -x /usr/bin/getconf ]; then
+ sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+ sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+ case "${sc_cpu_version}" in
+ 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+ 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+ 532) # CPU_PA_RISC2_0
+ case "${sc_kernel_bits}" in
+ 32) HP_ARCH="hppa2.0n" ;;
+ 64) HP_ARCH="hppa2.0w" ;;
+ '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20
+ esac ;;
+ esac
+ fi
+ if [ "${HP_ARCH}" = "" ]; then
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+
+ #define _HPUX_SOURCE
+ #include <stdlib.h>
+ #include <unistd.h>
+
+ int main ()
+ {
+ #if defined(_SC_KERNEL_BITS)
+ long bits = sysconf(_SC_KERNEL_BITS);
+ #endif
+ long cpu = sysconf (_SC_CPU_VERSION);
+
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+ case CPU_PA_RISC2_0:
+ #if defined(_SC_KERNEL_BITS)
+ switch (bits)
+ {
+ case 64: puts ("hppa2.0w"); break;
+ case 32: puts ("hppa2.0n"); break;
+ default: puts ("hppa2.0"); break;
+ } break;
+ #else /* !defined(_SC_KERNEL_BITS) */
+ puts ("hppa2.0"); break;
+ #endif
+ default: puts ("hppa1.0"); break;
+ }
+ exit (0);
+ }
+EOF
+ (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+ test -z "$HP_ARCH" && HP_ARCH=hppa
+ fi ;;
+ esac
+ if [ ${HP_ARCH} = "hppa2.0w" ]
+ then
+ eval $set_cc_for_build
+
+ # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+ # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler
+ # generating 64-bit code. GNU and HP use different nomenclature:
+ #
+ # $ CC_FOR_BUILD=cc ./config.guess
+ # => hppa2.0w-hp-hpux11.23
+ # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+ # => hppa64-hp-hpux11.23
+
+ if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+ grep -q __LP64__
+ then
+ HP_ARCH="hppa2.0w"
+ else
+ HP_ARCH="hppa64"
+ fi
+ fi
+ echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+ exit ;;
+ ia64:HP-UX:*:*)
+ HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+ echo ia64-hp-hpux${HPUX_REV}
+ exit ;;
+ 3050*:HI-UX:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <unistd.h>
+ int
+ main ()
+ {
+ long cpu = sysconf (_SC_CPU_VERSION);
+ /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+ true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct
+ results, however. */
+ if (CPU_IS_PA_RISC (cpu))
+ {
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+ default: puts ("hppa-hitachi-hiuxwe2"); break;
+ }
+ }
+ else if (CPU_IS_HP_MC68K (cpu))
+ puts ("m68k-hitachi-hiuxwe2");
+ else puts ("unknown-hitachi-hiuxwe2");
+ exit (0);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+ { echo "$SYSTEM_NAME"; exit; }
+ echo unknown-hitachi-hiuxwe2
+ exit ;;
+ 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+ echo hppa1.1-hp-bsd
+ exit ;;
+ 9000/8??:4.3bsd:*:*)
+ echo hppa1.0-hp-bsd
+ exit ;;
+ *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+ echo hppa1.0-hp-mpeix
+ exit ;;
+ hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+ echo hppa1.1-hp-osf
+ exit ;;
+ hp8??:OSF1:*:*)
+ echo hppa1.0-hp-osf
+ exit ;;
+ i*86:OSF1:*:*)
+ if [ -x /usr/sbin/sysversion ] ; then
+ echo ${UNAME_MACHINE}-unknown-osf1mk
+ else
+ echo ${UNAME_MACHINE}-unknown-osf1
+ fi
+ exit ;;
+ parisc*:Lites*:*:*)
+ echo hppa1.1-hp-lites
+ exit ;;
+ C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+ echo c1-convex-bsd
+ exit ;;
+ C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit ;;
+ C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+ echo c34-convex-bsd
+ exit ;;
+ C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+ echo c38-convex-bsd
+ exit ;;
+ C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+ echo c4-convex-bsd
+ exit ;;
+ CRAY*Y-MP:*:*:*)
+ echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*[A-Z]90:*:*:*)
+ echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+ -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*TS:*:*:*)
+ echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*T3E:*:*:*)
+ echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*SV1:*:*:*)
+ echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ *:UNICOS/mp:*:*)
+ echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+ FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+ FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+ FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+ echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit ;;
+ 5000:UNIX_System_V:4.*:*)
+ FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+ FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+ echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit ;;
+ i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+ echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+ exit ;;
+ sparc*:BSD/OS:*:*)
+ echo sparc-unknown-bsdi${UNAME_RELEASE}
+ exit ;;
+ *:BSD/OS:*:*)
+ echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+ exit ;;
+ *:FreeBSD:*:*)
+ UNAME_PROCESSOR=`/usr/bin/uname -p`
+ case ${UNAME_PROCESSOR} in
+ amd64)
+ echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+ *)
+ echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+ esac
+ exit ;;
+ i*:CYGWIN*:*)
+ echo ${UNAME_MACHINE}-pc-cygwin
+ exit ;;
+ *:MINGW*:*)
+ echo ${UNAME_MACHINE}-pc-mingw32
+ exit ;;
+ i*:windows32*:*)
+ # uname -m includes "-pc" on this system.
+ echo ${UNAME_MACHINE}-mingw32
+ exit ;;
+ i*:PW*:*)
+ echo ${UNAME_MACHINE}-pc-pw32
+ exit ;;
+ *:Interix*:*)
+ case ${UNAME_MACHINE} in
+ x86)
+ echo i586-pc-interix${UNAME_RELEASE}
+ exit ;;
+ authenticamd | genuineintel | EM64T)
+ echo x86_64-unknown-interix${UNAME_RELEASE}
+ exit ;;
+ IA64)
+ echo ia64-unknown-interix${UNAME_RELEASE}
+ exit ;;
+ esac ;;
+ [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+ echo i${UNAME_MACHINE}-pc-mks
+ exit ;;
+ 8664:Windows_NT:*)
+ echo x86_64-pc-mks
+ exit ;;
+ i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+ # How do we know it's Interix rather than the generic POSIX subsystem?
+ # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+ # UNAME_MACHINE based on the output of uname instead of i386?
+ echo i586-pc-interix
+ exit ;;
+ i*:UWIN*:*)
+ echo ${UNAME_MACHINE}-pc-uwin
+ exit ;;
+ amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+ echo x86_64-unknown-cygwin
+ exit ;;
+ p*:CYGWIN*:*)
+ echo powerpcle-unknown-cygwin
+ exit ;;
+ prep*:SunOS:5.*:*)
+ echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ *:GNU:*:*)
+ # the GNU system
+ echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+ exit ;;
+ *:GNU/*:*:*)
+ # other systems with GNU libc and userland
+ echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+ exit ;;
+ i*86:Minix:*:*)
+ echo ${UNAME_MACHINE}-pc-minix
+ exit ;;
+ alpha:Linux:*:*)
+ case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+ EV5) UNAME_MACHINE=alphaev5 ;;
+ EV56) UNAME_MACHINE=alphaev56 ;;
+ PCA56) UNAME_MACHINE=alphapca56 ;;
+ PCA57) UNAME_MACHINE=alphapca56 ;;
+ EV6) UNAME_MACHINE=alphaev6 ;;
+ EV67) UNAME_MACHINE=alphaev67 ;;
+ EV68*) UNAME_MACHINE=alphaev68 ;;
+ esac
+ objdump --private-headers /bin/sh | grep -q ld.so.1
+ if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
+ echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+ exit ;;
+ arm*:Linux:*:*)
+ eval $set_cc_for_build
+ if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ARM_EABI__
+ then
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ else
+ if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ARM_PCS_VFP
+ then
+ echo ${UNAME_MACHINE}-unknown-linux-gnueabi
+ else
+ echo ${UNAME_MACHINE}-unknown-linux-gnueabihf
+ fi
+ fi
+ exit ;;
+ avr32*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ cris:Linux:*:*)
+ echo cris-axis-linux-gnu
+ exit ;;
+ crisv32:Linux:*:*)
+ echo crisv32-axis-linux-gnu
+ exit ;;
+ frv:Linux:*:*)
+ echo frv-unknown-linux-gnu
+ exit ;;
+ i*86:Linux:*:*)
+ LIBC=gnu
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #ifdef __dietlibc__
+ LIBC=dietlibc
+ #endif
+EOF
+ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
+ echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+ exit ;;
+ ia64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ m32r*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ m68*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ mips:Linux:*:* | mips64:Linux:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #undef CPU
+ #undef ${UNAME_MACHINE}
+ #undef ${UNAME_MACHINE}el
+ #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+ CPU=${UNAME_MACHINE}el
+ #else
+ #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+ CPU=${UNAME_MACHINE}
+ #else
+ CPU=
+ #endif
+ #endif
+EOF
+ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
+ test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+ ;;
+ or32:Linux:*:*)
+ echo or32-unknown-linux-gnu
+ exit ;;
+ padre:Linux:*:*)
+ echo sparc-unknown-linux-gnu
+ exit ;;
+ parisc64:Linux:*:* | hppa64:Linux:*:*)
+ echo hppa64-unknown-linux-gnu
+ exit ;;
+ parisc:Linux:*:* | hppa:Linux:*:*)
+ # Look for CPU level
+ case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+ PA7*) echo hppa1.1-unknown-linux-gnu ;;
+ PA8*) echo hppa2.0-unknown-linux-gnu ;;
+ *) echo hppa-unknown-linux-gnu ;;
+ esac
+ exit ;;
+ ppc64:Linux:*:*)
+ echo powerpc64-unknown-linux-gnu
+ exit ;;
+ ppc:Linux:*:*)
+ echo powerpc-unknown-linux-gnu
+ exit ;;
+ s390:Linux:*:* | s390x:Linux:*:*)
+ echo ${UNAME_MACHINE}-ibm-linux
+ exit ;;
+ sh64*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ sh*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ sparc:Linux:*:* | sparc64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ tile*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ vax:Linux:*:*)
+ echo ${UNAME_MACHINE}-dec-linux-gnu
+ exit ;;
+ x86_64:Linux:*:*)
+ echo x86_64-unknown-linux-gnu
+ exit ;;
+ xtensa*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ i*86:DYNIX/ptx:4*:*)
+ # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+ # earlier versions are messed up and put the nodename in both
+ # sysname and nodename.
+ echo i386-sequent-sysv4
+ exit ;;
+ i*86:UNIX_SV:4.2MP:2.*)
+ # Unixware is an offshoot of SVR4, but it has its own version
+ # number series starting with 2...
+ # I am not positive that other SVR4 systems won't match this,
+ # I just have to hope. -- rms.
+ # Use sysv4.2uw... so that sysv4* matches it.
+ echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+ exit ;;
+ i*86:OS/2:*:*)
+ # If we were able to find `uname', then EMX Unix compatibility
+ # is probably installed.
+ echo ${UNAME_MACHINE}-pc-os2-emx
+ exit ;;
+ i*86:XTS-300:*:STOP)
+ echo ${UNAME_MACHINE}-unknown-stop
+ exit ;;
+ i*86:atheos:*:*)
+ echo ${UNAME_MACHINE}-unknown-atheos
+ exit ;;
+ i*86:syllable:*:*)
+ echo ${UNAME_MACHINE}-pc-syllable
+ exit ;;
+ i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
+ echo i386-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ i*86:*DOS:*:*)
+ echo ${UNAME_MACHINE}-pc-msdosdjgpp
+ exit ;;
+ i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+ UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+ if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+ echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+ else
+ echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+ fi
+ exit ;;
+ i*86:*:5:[678]*)
+ # UnixWare 7.x, OpenUNIX and OpenServer 6.
+ case `/bin/uname -X | grep "^Machine"` in
+ *486*) UNAME_MACHINE=i486 ;;
+ *Pentium) UNAME_MACHINE=i586 ;;
+ *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+ esac
+ echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+ exit ;;
+ i*86:*:3.2:*)
+ if test -f /usr/options/cb.name; then
+ UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+ echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+ elif /bin/uname -X 2>/dev/null >/dev/null ; then
+ UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+ (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+ (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+ && UNAME_MACHINE=i586
+ (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+ && UNAME_MACHINE=i686
+ (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+ && UNAME_MACHINE=i686
+ echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+ else
+ echo ${UNAME_MACHINE}-pc-sysv32
+ fi
+ exit ;;
+ pc:*:*:*)
+ # Left here for compatibility:
+ # uname -m prints for DJGPP always 'pc', but it prints nothing about
+ # the processor, so we play safe by assuming i586.
+ # Note: whatever this is, it MUST be the same as what config.sub
+ # prints for the "djgpp" host, or else GDB configury will decide that
+ # this is a cross-build.
+ echo i586-pc-msdosdjgpp
+ exit ;;
+ Intel:Mach:3*:*)
+ echo i386-pc-mach3
+ exit ;;
+ paragon:*:*:*)
+ echo i860-intel-osf1
+ exit ;;
+ i860:*:4.*:*) # i860-SVR4
+ if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+ echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+ else # Add other i860-SVR4 vendors below as they are discovered.
+ echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4
+ fi
+ exit ;;
+ mini*:CTIX:SYS*5:*)
+ # "miniframe"
+ echo m68010-convergent-sysv
+ exit ;;
+ mc68k:UNIX:SYSTEM5:3.51m)
+ echo m68k-convergent-sysv
+ exit ;;
+ M680?0:D-NIX:5.3:*)
+ echo m68k-diab-dnix
+ exit ;;
+ M68*:*:R3V[5678]*:*)
+ test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+ 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+ OS_REL=''
+ test -r /etc/.relid \
+ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+ 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4; exit; } ;;
+ NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+ OS_REL='.3'
+ test -r /etc/.relid \
+ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+ && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+ m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+ echo m68k-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ mc68030:UNIX_System_V:4.*:*)
+ echo m68k-atari-sysv4
+ exit ;;
+ TSUNAMI:LynxOS:2.*:*)
+ echo sparc-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ rs6000:LynxOS:2.*:*)
+ echo rs6000-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
+ echo powerpc-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ SM[BE]S:UNIX_SV:*:*)
+ echo mips-dde-sysv${UNAME_RELEASE}
+ exit ;;
+ RM*:ReliantUNIX-*:*:*)
+ echo mips-sni-sysv4
+ exit ;;
+ RM*:SINIX-*:*:*)
+ echo mips-sni-sysv4
+ exit ;;
+ *:SINIX-*:*:*)
+ if uname -p 2>/dev/null >/dev/null ; then
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ echo ${UNAME_MACHINE}-sni-sysv4
+ else
+ echo ns32k-sni-sysv
+ fi
+ exit ;;
+ PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+ # says <Richard.M.Bartel@ccMail.Census.GOV>
+ echo i586-unisys-sysv4
+ exit ;;
+ *:UNIX_System_V:4*:FTX*)
+ # From Gerald Hewes <hewes@openmarket.com>.
+ # How about differentiating between stratus architectures? -djm
+ echo hppa1.1-stratus-sysv4
+ exit ;;
+ *:*:*:FTX*)
+ # From seanf@swdc.stratus.com.
+ echo i860-stratus-sysv4
+ exit ;;
+ i*86:VOS:*:*)
+ # From Paul.Green@stratus.com.
+ echo ${UNAME_MACHINE}-stratus-vos
+ exit ;;
+ *:VOS:*:*)
+ # From Paul.Green@stratus.com.
+ echo hppa1.1-stratus-vos
+ exit ;;
+ mc68*:A/UX:*:*)
+ echo m68k-apple-aux${UNAME_RELEASE}
+ exit ;;
+ news*:NEWS-OS:6*:*)
+ echo mips-sony-newsos6
+ exit ;;
+ R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+ if [ -d /usr/nec ]; then
+ echo mips-nec-sysv${UNAME_RELEASE}
+ else
+ echo mips-unknown-sysv${UNAME_RELEASE}
+ fi
+ exit ;;
+ BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
+ echo powerpc-be-beos
+ exit ;;
+ BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
+ echo powerpc-apple-beos
+ exit ;;
+ BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
+ echo i586-pc-beos
+ exit ;;
+ BePC:Haiku:*:*) # Haiku running on Intel PC compatible.
+ echo i586-pc-haiku
+ exit ;;
+ SX-4:SUPER-UX:*:*)
+ echo sx4-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-5:SUPER-UX:*:*)
+ echo sx5-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-6:SUPER-UX:*:*)
+ echo sx6-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-7:SUPER-UX:*:*)
+ echo sx7-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-8:SUPER-UX:*:*)
+ echo sx8-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-8R:SUPER-UX:*:*)
+ echo sx8r-nec-superux${UNAME_RELEASE}
+ exit ;;
+ Power*:Rhapsody:*:*)
+ echo powerpc-apple-rhapsody${UNAME_RELEASE}
+ exit ;;
+ *:Rhapsody:*:*)
+ echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+ exit ;;
+ *:Darwin:*:*)
+ UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+ case $UNAME_PROCESSOR in
+ i386)
+ eval $set_cc_for_build
+ if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+ if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+ grep IS_64BIT_ARCH >/dev/null
+ then
+ UNAME_PROCESSOR="x86_64"
+ fi
+ fi ;;
+ unknown) UNAME_PROCESSOR=powerpc ;;
+ esac
+ echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+ exit ;;
+ *:procnto*:*:* | *:QNX:[0123456789]*:*)
+ UNAME_PROCESSOR=`uname -p`
+ if test "$UNAME_PROCESSOR" = "x86"; then
+ UNAME_PROCESSOR=i386
+ UNAME_MACHINE=pc
+ fi
+ echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+ exit ;;
+ *:QNX:*:4*)
+ echo i386-pc-qnx
+ exit ;;
+ NEO-?:NONSTOP_KERNEL:*:*)
+ echo neo-tandem-nsk${UNAME_RELEASE}
+ exit ;;
+ NSE-?:NONSTOP_KERNEL:*:*)
+ echo nse-tandem-nsk${UNAME_RELEASE}
+ exit ;;
+ NSR-?:NONSTOP_KERNEL:*:*)
+ echo nsr-tandem-nsk${UNAME_RELEASE}
+ exit ;;
+ *:NonStop-UX:*:*)
+ echo mips-compaq-nonstopux
+ exit ;;
+ BS2000:POSIX*:*:*)
+ echo bs2000-siemens-sysv
+ exit ;;
+ DS/*:UNIX_System_V:*:*)
+ echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+ exit ;;
+ *:Plan9:*:*)
+ # "uname -m" is not consistent, so use $cputype instead. 386
+ # is converted to i386 for consistency with other x86
+ # operating systems.
+ if test "$cputype" = "386"; then
+ UNAME_MACHINE=i386
+ else
+ UNAME_MACHINE="$cputype"
+ fi
+ echo ${UNAME_MACHINE}-unknown-plan9
+ exit ;;
+ *:TOPS-10:*:*)
+ echo pdp10-unknown-tops10
+ exit ;;
+ *:TENEX:*:*)
+ echo pdp10-unknown-tenex
+ exit ;;
+ KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+ echo pdp10-dec-tops20
+ exit ;;
+ XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+ echo pdp10-xkl-tops20
+ exit ;;
+ *:TOPS-20:*:*)
+ echo pdp10-unknown-tops20
+ exit ;;
+ *:ITS:*:*)
+ echo pdp10-unknown-its
+ exit ;;
+ SEI:*:*:SEIUX)
+ echo mips-sei-seiux${UNAME_RELEASE}
+ exit ;;
+ *:DragonFly:*:*)
+ echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+ exit ;;
+ *:*VMS:*:*)
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ case "${UNAME_MACHINE}" in
+ A*) echo alpha-dec-vms ; exit ;;
+ I*) echo ia64-dec-vms ; exit ;;
+ V*) echo vax-dec-vms ; exit ;;
+ esac ;;
+ *:XENIX:*:SysV)
+ echo i386-pc-xenix
+ exit ;;
+ i*86:skyos:*:*)
+ echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+ exit ;;
+ i*86:rdos:*:*)
+ echo ${UNAME_MACHINE}-pc-rdos
+ exit ;;
+ i*86:AROS:*:*)
+ echo ${UNAME_MACHINE}-pc-aros
+ exit ;;
+esac
+
+#echo '(No uname command or uname output not recognized.)' 1>&2
+#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
+
+eval $set_cc_for_build
+cat >$dummy.c <<EOF
+#ifdef _SEQUENT_
+# include <sys/types.h>
+# include <sys/utsname.h>
+#endif
+main ()
+{
+#if defined (sony)
+#if defined (MIPSEB)
+ /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed,
+ I don't know.... */
+ printf ("mips-sony-bsd\n"); exit (0);
+#else
+#include <sys/param.h>
+ printf ("m68k-sony-newsos%s\n",
+#ifdef NEWSOS4
+ "4"
+#else
+ ""
+#endif
+ ); exit (0);
+#endif
+#endif
+
+#if defined (__arm) && defined (__acorn) && defined (__unix)
+ printf ("arm-acorn-riscix\n"); exit (0);
+#endif
+
+#if defined (hp300) && !defined (hpux)
+ printf ("m68k-hp-bsd\n"); exit (0);
+#endif
+
+#if defined (NeXT)
+#if !defined (__ARCHITECTURE__)
+#define __ARCHITECTURE__ "m68k"
+#endif
+ int version;
+ version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
+ if (version < 4)
+ printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
+ else
+ printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
+ exit (0);
+#endif
+
+#if defined (MULTIMAX) || defined (n16)
+#if defined (UMAXV)
+ printf ("ns32k-encore-sysv\n"); exit (0);
+#else
+#if defined (CMU)
+ printf ("ns32k-encore-mach\n"); exit (0);
+#else
+ printf ("ns32k-encore-bsd\n"); exit (0);
+#endif
+#endif
+#endif
+
+#if defined (__386BSD__)
+ printf ("i386-pc-bsd\n"); exit (0);
+#endif
+
+#if defined (sequent)
+#if defined (i386)
+ printf ("i386-sequent-dynix\n"); exit (0);
+#endif
+#if defined (ns32000)
+ printf ("ns32k-sequent-dynix\n"); exit (0);
+#endif
+#endif
+
+#if defined (_SEQUENT_)
+ struct utsname un;
+
+ uname(&un);
+
+ if (strncmp(un.version, "V2", 2) == 0) {
+ printf ("i386-sequent-ptx2\n"); exit (0);
+ }
+ if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
+ printf ("i386-sequent-ptx1\n"); exit (0);
+ }
+ printf ("i386-sequent-ptx\n"); exit (0);
+
+#endif
+
+#if defined (vax)
+# if !defined (ultrix)
+# include <sys/param.h>
+# if defined (BSD)
+# if BSD == 43
+ printf ("vax-dec-bsd4.3\n"); exit (0);
+# else
+# if BSD == 199006
+ printf ("vax-dec-bsd4.3reno\n"); exit (0);
+# else
+ printf ("vax-dec-bsd\n"); exit (0);
+# endif
+# endif
+# else
+ printf ("vax-dec-bsd\n"); exit (0);
+# endif
+# else
+ printf ("vax-dec-ultrix\n"); exit (0);
+# endif
+#endif
+
+#if defined (alliant) && defined (i860)
+ printf ("i860-alliant-bsd\n"); exit (0);
+#endif
+
+ exit (1);
+}
+EOF
+
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
+ { echo "$SYSTEM_NAME"; exit; }
+
+# Apollos put the system type in the environment.
+
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
+
+# Convex versions that predate uname can use getsysinfo(1)
+
+if [ -x /usr/convex/getsysinfo ]
+then
+ case `getsysinfo -f cpu_type` in
+ c1*)
+ echo c1-convex-bsd
+ exit ;;
+ c2*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit ;;
+ c34*)
+ echo c34-convex-bsd
+ exit ;;
+ c38*)
+ echo c38-convex-bsd
+ exit ;;
+ c4*)
+ echo c4-convex-bsd
+ exit ;;
+ esac
+fi
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+ http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+and
+ http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches@gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo = `(hostinfo) 2>/dev/null`
+/bin/universe = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/autoconf/config.sub b/autoconf/config.sub
new file mode 100755
index 00000000000..9942491533e
--- /dev/null
+++ b/autoconf/config.sub
@@ -0,0 +1,1766 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+# 2011 Free Software Foundation, Inc.
+
+timestamp='2011-11-02'
+
+# This file is (in principle) common to ALL GNU software.
+# The presence of a machine in this file suggests that SOME GNU software
+# can handle that machine. It does not imply ALL GNU software can.
+#
+# This file is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Please send patches to <config-patches@gnu.org>. Submit a context
+# diff and a properly formatted GNU ChangeLog entry.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support. The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+ $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
+2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free
+Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit ;;
+ --version | -v )
+ echo "$version" ; exit ;;
+ --help | --h* | -h )
+ echo "$usage"; exit ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help"
+ exit 1 ;;
+
+ *local*)
+ # First pass through any local machine types.
+ echo $1
+ exit ;;
+
+ * )
+ break ;;
+ esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+ exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+ exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+ nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
+ linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
+ knetbsd*-gnu* | netbsd*-gnu* | \
+ kopensolaris*-gnu* | \
+ storm-chaos* | os2-emx* | rtmk-nova*)
+ os=-$maybe_os
+ basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+ ;;
+ *)
+ basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+ if [ $basic_machine != $1 ]
+ then os=`echo $1 | sed 's/.*-/-/'`
+ else os=; fi
+ ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work. We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+ -sun*os*)
+ # Prevent following clause from handling this invalid input.
+ ;;
+ -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+ -apple | -axis | -knuth | -cray | -microblaze)
+ os=
+ basic_machine=$1
+ ;;
+ -bluegene*)
+ os=-cnk
+ ;;
+ -sim | -cisco | -oki | -wec | -winbond)
+ os=
+ basic_machine=$1
+ ;;
+ -scout)
+ ;;
+ -wrs)
+ os=-vxworks
+ basic_machine=$1
+ ;;
+ -chorusos*)
+ os=-chorusos
+ basic_machine=$1
+ ;;
+ -chorusrdb)
+ os=-chorusrdb
+ basic_machine=$1
+ ;;
+ -hiux*)
+ os=-hiuxwe2
+ ;;
+ -sco6)
+ os=-sco5v6
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco5)
+ os=-sco3.2v5
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco4)
+ os=-sco3.2v4
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2.[4-9]*)
+ os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2v[4-9]*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco5v6*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco*)
+ os=-sco3.2v2
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -udk*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -isc)
+ os=-isc2.2
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -clix*)
+ basic_machine=clipper-intergraph
+ ;;
+ -isc*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -lynx*)
+ os=-lynxos
+ ;;
+ -ptx*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+ ;;
+ -windowsnt*)
+ os=`echo $os | sed -e 's/windowsnt/winnt/'`
+ ;;
+ -psos*)
+ os=-psos
+ ;;
+ -mint | -mint[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+ # Recognize the basic CPU types without company name.
+ # Some are omitted here because they have special meanings below.
+ 1750a | 580 \
+ | a29k \
+ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+ | am33_2.0 \
+ | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
+ | be32 | be64 \
+ | bfin \
+ | c4x | clipper \
+ | d10v | d30v | dlx | dsp16xx \
+ | fido | fr30 | frv \
+ | hexagon \
+ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+ | i370 | i860 | i960 | ia64 \
+ | ip2k | iq2000 \
+ | le32 | le64 \
+ | lm32 \
+ | m32c | m32r | m32rle | m68000 | m68k | m88k \
+ | maxq | mb | microblaze | mcore | mep | metag \
+ | mips | mipsbe | mipseb | mipsel | mipsle \
+ | mips16 \
+ | mips64 | mips64el \
+ | mips64octeon | mips64octeonel \
+ | mips64orion | mips64orionel \
+ | mips64r5900 | mips64r5900el \
+ | mips64vr | mips64vrel \
+ | mips64vr4100 | mips64vr4100el \
+ | mips64vr4300 | mips64vr4300el \
+ | mips64vr5000 | mips64vr5000el \
+ | mips64vr5900 | mips64vr5900el \
+ | mipsisa32 | mipsisa32el \
+ | mipsisa32r2 | mipsisa32r2el \
+ | mipsisa64 | mipsisa64el \
+ | mipsisa64r2 | mipsisa64r2el \
+ | mipsisa64sb1 | mipsisa64sb1el \
+ | mipsisa64sr71k | mipsisa64sr71kel \
+ | mipstx39 | mipstx39el \
+ | mn10200 | mn10300 \
+ | moxie \
+ | mt \
+ | msp430 \
+ | nds32 | nds32le | nds32be \
+ | nios | nios2 \
+ | ns16k | ns32k \
+ | open8 \
+ | or32 \
+ | pdp10 | pdp11 | pj | pjl \
+ | powerpc | powerpc64 | powerpc64le | powerpcle \
+ | pyramid \
+ | rx \
+ | score \
+ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+ | sh64 | sh64le \
+ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+ | spu \
+ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
+ | ubicom32 \
+ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+ | we32k \
+ | x86 | xc16x | xstormy16 | xtensa \
+ | z8k | z80)
+ basic_machine=$basic_machine-unknown
+ ;;
+ c54x)
+ basic_machine=tic54x-unknown
+ ;;
+ c55x)
+ basic_machine=tic55x-unknown
+ ;;
+ c6x)
+ basic_machine=tic6x-unknown
+ ;;
+ m6811 | m68hc11 | m6812 | m68hc12 | picochip)
+ # Motorola 68HC11/12.
+ basic_machine=$basic_machine-unknown
+ os=-none
+ ;;
+ m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+ ;;
+ ms1)
+ basic_machine=mt-unknown
+ ;;
+
+ strongarm | thumb | xscale)
+ basic_machine=arm-unknown
+ ;;
+
+ xscaleeb)
+ basic_machine=armeb-unknown
+ ;;
+
+ xscaleel)
+ basic_machine=armel-unknown
+ ;;
+
+ # We use `pc' rather than `unknown'
+ # because (1) that's what they normally are, and
+ # (2) the word "unknown" tends to confuse beginning users.
+ i*86 | x86_64)
+ basic_machine=$basic_machine-pc
+ ;;
+ # Object if more than one company name word.
+ *-*-*)
+ echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+ exit 1
+ ;;
+ # Recognize the basic CPU types with company name.
+ 580-* \
+ | a29k-* \
+ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \
+ | avr-* | avr32-* \
+ | be32-* | be64-* \
+ | bfin-* | bs2000-* \
+ | c[123]* | c30-* | [cjt]90-* | c4x-* \
+ | clipper-* | craynv-* | cydra-* \
+ | d10v-* | d30v-* | dlx-* \
+ | elxsi-* \
+ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+ | h8300-* | h8500-* \
+ | hexagon-* \
+ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+ | i*86-* | i860-* | i960-* | ia64-* \
+ | ip2k-* | iq2000-* \
+ | le32-* | le64-* \
+ | lm32-* \
+ | m32c-* | m32r-* | m32rle-* \
+ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \
+ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+ | mips16-* \
+ | mips64-* | mips64el-* \
+ | mips64octeon-* | mips64octeonel-* \
+ | mips64orion-* | mips64orionel-* \
+ | mips64r5900-* | mips64r5900el-* \
+ | mips64vr-* | mips64vrel-* \
+ | mips64vr4100-* | mips64vr4100el-* \
+ | mips64vr4300-* | mips64vr4300el-* \
+ | mips64vr5000-* | mips64vr5000el-* \
+ | mips64vr5900-* | mips64vr5900el-* \
+ | mipsisa32-* | mipsisa32el-* \
+ | mipsisa32r2-* | mipsisa32r2el-* \
+ | mipsisa64-* | mipsisa64el-* \
+ | mipsisa64r2-* | mipsisa64r2el-* \
+ | mipsisa64sb1-* | mipsisa64sb1el-* \
+ | mipsisa64sr71k-* | mipsisa64sr71kel-* \
+ | mipstx39-* | mipstx39el-* \
+ | mmix-* \
+ | mt-* \
+ | msp430-* \
+ | nds32-* | nds32le-* | nds32be-* \
+ | nios-* | nios2-* \
+ | none-* | np1-* | ns16k-* | ns32k-* \
+ | open8-* \
+ | orion-* \
+ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+ | pyramid-* \
+ | romp-* | rs6000-* | rx-* \
+ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+ | sparclite-* \
+ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
+ | tahoe-* \
+ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+ | tile*-* \
+ | tron-* \
+ | ubicom32-* \
+ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
+ | vax-* \
+ | we32k-* \
+ | x86-* | x86_64-* | xc16x-* | xps100-* \
+ | xstormy16-* | xtensa*-* \
+ | ymp-* \
+ | z8k-* | z80-*)
+ ;;
+ # Recognize the basic CPU types without company name, with glob match.
+ xtensa*)
+ basic_machine=$basic_machine-unknown
+ ;;
+ # Recognize the various machine names and aliases which stand
+ # for a CPU type and a company and sometimes even an OS.
+ 386bsd)
+ basic_machine=i386-unknown
+ os=-bsd
+ ;;
+ 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+ basic_machine=m68000-att
+ ;;
+ 3b*)
+ basic_machine=we32k-att
+ ;;
+ a29khif)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ abacus)
+ basic_machine=abacus-unknown
+ ;;
+ adobe68k)
+ basic_machine=m68010-adobe
+ os=-scout
+ ;;
+ alliant | fx80)
+ basic_machine=fx80-alliant
+ ;;
+ altos | altos3068)
+ basic_machine=m68k-altos
+ ;;
+ am29k)
+ basic_machine=a29k-none
+ os=-bsd
+ ;;
+ amd64)
+ basic_machine=x86_64-pc
+ ;;
+ amd64-*)
+ basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ amdahl)
+ basic_machine=580-amdahl
+ os=-sysv
+ ;;
+ amiga | amiga-*)
+ basic_machine=m68k-unknown
+ ;;
+ amigaos | amigados)
+ basic_machine=m68k-unknown
+ os=-amigaos
+ ;;
+ amigaunix | amix)
+ basic_machine=m68k-unknown
+ os=-sysv4
+ ;;
+ apollo68)
+ basic_machine=m68k-apollo
+ os=-sysv
+ ;;
+ apollo68bsd)
+ basic_machine=m68k-apollo
+ os=-bsd
+ ;;
+ aros)
+ basic_machine=i386-pc
+ os=-aros
+ ;;
+ aux)
+ basic_machine=m68k-apple
+ os=-aux
+ ;;
+ balance)
+ basic_machine=ns32k-sequent
+ os=-dynix
+ ;;
+ blackfin)
+ basic_machine=bfin-unknown
+ os=-linux
+ ;;
+ blackfin-*)
+ basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ bluegene*)
+ basic_machine=powerpc-ibm
+ os=-cnk
+ ;;
+ c54x-*)
+ basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ c55x-*)
+ basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ c6x-*)
+ basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ c90)
+ basic_machine=c90-cray
+ os=-unicos
+ ;;
+ cegcc)
+ basic_machine=arm-unknown
+ os=-cegcc
+ ;;
+ convex-c1)
+ basic_machine=c1-convex
+ os=-bsd
+ ;;
+ convex-c2)
+ basic_machine=c2-convex
+ os=-bsd
+ ;;
+ convex-c32)
+ basic_machine=c32-convex
+ os=-bsd
+ ;;
+ convex-c34)
+ basic_machine=c34-convex
+ os=-bsd
+ ;;
+ convex-c38)
+ basic_machine=c38-convex
+ os=-bsd
+ ;;
+ cray | j90)
+ basic_machine=j90-cray
+ os=-unicos
+ ;;
+ craynv)
+ basic_machine=craynv-cray
+ os=-unicosmp
+ ;;
+ cr16 | cr16-*)
+ basic_machine=cr16-unknown
+ os=-elf
+ ;;
+ crds | unos)
+ basic_machine=m68k-crds
+ ;;
+ crisv32 | crisv32-* | etraxfs*)
+ basic_machine=crisv32-axis
+ ;;
+ cris | cris-* | etrax*)
+ basic_machine=cris-axis
+ ;;
+ crx)
+ basic_machine=crx-unknown
+ os=-elf
+ ;;
+ da30 | da30-*)
+ basic_machine=m68k-da30
+ ;;
+ decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+ basic_machine=mips-dec
+ ;;
+ decsystem10* | dec10*)
+ basic_machine=pdp10-dec
+ os=-tops10
+ ;;
+ decsystem20* | dec20*)
+ basic_machine=pdp10-dec
+ os=-tops20
+ ;;
+ delta | 3300 | motorola-3300 | motorola-delta \
+ | 3300-motorola | delta-motorola)
+ basic_machine=m68k-motorola
+ ;;
+ delta88)
+ basic_machine=m88k-motorola
+ os=-sysv3
+ ;;
+ dicos)
+ basic_machine=i686-pc
+ os=-dicos
+ ;;
+ djgpp)
+ basic_machine=i586-pc
+ os=-msdosdjgpp
+ ;;
+ dpx20 | dpx20-*)
+ basic_machine=rs6000-bull
+ os=-bosx
+ ;;
+ dpx2* | dpx2*-bull)
+ basic_machine=m68k-bull
+ os=-sysv3
+ ;;
+ ebmon29k)
+ basic_machine=a29k-amd
+ os=-ebmon
+ ;;
+ elxsi)
+ basic_machine=elxsi-elxsi
+ os=-bsd
+ ;;
+ encore | umax | mmax)
+ basic_machine=ns32k-encore
+ ;;
+ es1800 | OSE68k | ose68k | ose | OSE)
+ basic_machine=m68k-ericsson
+ os=-ose
+ ;;
+ fx2800)
+ basic_machine=i860-alliant
+ ;;
+ genix)
+ basic_machine=ns32k-ns
+ ;;
+ gmicro)
+ basic_machine=tron-gmicro
+ os=-sysv
+ ;;
+ go32)
+ basic_machine=i386-pc
+ os=-go32
+ ;;
+ h3050r* | hiux*)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ h8300hms)
+ basic_machine=h8300-hitachi
+ os=-hms
+ ;;
+ h8300xray)
+ basic_machine=h8300-hitachi
+ os=-xray
+ ;;
+ h8500hms)
+ basic_machine=h8500-hitachi
+ os=-hms
+ ;;
+ harris)
+ basic_machine=m88k-harris
+ os=-sysv3
+ ;;
+ hp300-*)
+ basic_machine=m68k-hp
+ ;;
+ hp300bsd)
+ basic_machine=m68k-hp
+ os=-bsd
+ ;;
+ hp300hpux)
+ basic_machine=m68k-hp
+ os=-hpux
+ ;;
+ hp3k9[0-9][0-9] | hp9[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k2[0-9][0-9] | hp9k31[0-9])
+ basic_machine=m68000-hp
+ ;;
+ hp9k3[2-9][0-9])
+ basic_machine=m68k-hp
+ ;;
+ hp9k6[0-9][0-9] | hp6[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k7[0-79][0-9] | hp7[0-79][0-9])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k78[0-9] | hp78[0-9])
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][13679] | hp8[0-9][13679])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][0-9] | hp8[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hppa-next)
+ os=-nextstep3
+ ;;
+ hppaosf)
+ basic_machine=hppa1.1-hp
+ os=-osf
+ ;;
+ hppro)
+ basic_machine=hppa1.1-hp
+ os=-proelf
+ ;;
+ i370-ibm* | ibm*)
+ basic_machine=i370-ibm
+ ;;
+# I'm not sure what "Sysv32" means. Should this be sysv3.2?
+ i*86v32)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv32
+ ;;
+ i*86v4*)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv4
+ ;;
+ i*86v)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv
+ ;;
+ i*86sol2)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-solaris2
+ ;;
+ i386mach)
+ basic_machine=i386-mach
+ os=-mach
+ ;;
+ i386-vsta | vsta)
+ basic_machine=i386-unknown
+ os=-vsta
+ ;;
+ iris | iris4d)
+ basic_machine=mips-sgi
+ case $os in
+ -irix*)
+ ;;
+ *)
+ os=-irix4
+ ;;
+ esac
+ ;;
+ isi68 | isi)
+ basic_machine=m68k-isi
+ os=-sysv
+ ;;
+ m68knommu)
+ basic_machine=m68k-unknown
+ os=-linux
+ ;;
+ m68knommu-*)
+ basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ m88k-omron*)
+ basic_machine=m88k-omron
+ ;;
+ magnum | m3230)
+ basic_machine=mips-mips
+ os=-sysv
+ ;;
+ merlin)
+ basic_machine=ns32k-utek
+ os=-sysv
+ ;;
+ microblaze)
+ basic_machine=microblaze-xilinx
+ ;;
+ mingw32)
+ basic_machine=i386-pc
+ os=-mingw32
+ ;;
+ mingw32ce)
+ basic_machine=arm-unknown
+ os=-mingw32ce
+ ;;
+ miniframe)
+ basic_machine=m68000-convergent
+ ;;
+ *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+ mips3*-*)
+ basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+ ;;
+ mips3*)
+ basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+ ;;
+ monitor)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ morphos)
+ basic_machine=powerpc-unknown
+ os=-morphos
+ ;;
+ msdos)
+ basic_machine=i386-pc
+ os=-msdos
+ ;;
+ ms1-*)
+ basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+ ;;
+ mvs)
+ basic_machine=i370-ibm
+ os=-mvs
+ ;;
+ nacl)
+ basic_machine=le32-unknown
+ os=-nacl
+ ;;
+ ncr3000)
+ basic_machine=i486-ncr
+ os=-sysv4
+ ;;
+ netbsd386)
+ basic_machine=i386-unknown
+ os=-netbsd
+ ;;
+ netwinder)
+ basic_machine=armv4l-rebel
+ os=-linux
+ ;;
+ news | news700 | news800 | news900)
+ basic_machine=m68k-sony
+ os=-newsos
+ ;;
+ news1000)
+ basic_machine=m68030-sony
+ os=-newsos
+ ;;
+ news-3600 | risc-news)
+ basic_machine=mips-sony
+ os=-newsos
+ ;;
+ necv70)
+ basic_machine=v70-nec
+ os=-sysv
+ ;;
+ next | m*-next )
+ basic_machine=m68k-next
+ case $os in
+ -nextstep* )
+ ;;
+ -ns2*)
+ os=-nextstep2
+ ;;
+ *)
+ os=-nextstep3
+ ;;
+ esac
+ ;;
+ nh3000)
+ basic_machine=m68k-harris
+ os=-cxux
+ ;;
+ nh[45]000)
+ basic_machine=m88k-harris
+ os=-cxux
+ ;;
+ nindy960)
+ basic_machine=i960-intel
+ os=-nindy
+ ;;
+ mon960)
+ basic_machine=i960-intel
+ os=-mon960
+ ;;
+ nonstopux)
+ basic_machine=mips-compaq
+ os=-nonstopux
+ ;;
+ np1)
+ basic_machine=np1-gould
+ ;;
+ neo-tandem)
+ basic_machine=neo-tandem
+ ;;
+ nse-tandem)
+ basic_machine=nse-tandem
+ ;;
+ nsr-tandem)
+ basic_machine=nsr-tandem
+ ;;
+ op50n-* | op60c-*)
+ basic_machine=hppa1.1-oki
+ os=-proelf
+ ;;
+ openrisc | openrisc-*)
+ basic_machine=or32-unknown
+ ;;
+ os400)
+ basic_machine=powerpc-ibm
+ os=-os400
+ ;;
+ OSE68000 | ose68000)
+ basic_machine=m68000-ericsson
+ os=-ose
+ ;;
+ os68k)
+ basic_machine=m68k-none
+ os=-os68k
+ ;;
+ pa-hitachi)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ paragon)
+ basic_machine=i860-intel
+ os=-osf
+ ;;
+ parisc)
+ basic_machine=hppa-unknown
+ os=-linux
+ ;;
+ parisc-*)
+ basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ pbd)
+ basic_machine=sparc-tti
+ ;;
+ pbb)
+ basic_machine=m68k-tti
+ ;;
+ pc532 | pc532-*)
+ basic_machine=ns32k-pc532
+ ;;
+ pc98)
+ basic_machine=i386-pc
+ ;;
+ pc98-*)
+ basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentium | p5 | k5 | k6 | nexgen | viac3)
+ basic_machine=i586-pc
+ ;;
+ pentiumpro | p6 | 6x86 | athlon | athlon_*)
+ basic_machine=i686-pc
+ ;;
+ pentiumii | pentium2 | pentiumiii | pentium3)
+ basic_machine=i686-pc
+ ;;
+ pentium4)
+ basic_machine=i786-pc
+ ;;
+ pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+ basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentiumpro-* | p6-* | 6x86-* | athlon-*)
+ basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+ basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentium4-*)
+ basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pn)
+ basic_machine=pn-gould
+ ;;
+ power) basic_machine=power-ibm
+ ;;
+ ppc | ppcbe) basic_machine=powerpc-unknown
+ ;;
+ ppc-* | ppcbe-*)
+ basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppcle | powerpclittle | ppc-le | powerpc-little)
+ basic_machine=powerpcle-unknown
+ ;;
+ ppcle-* | powerpclittle-*)
+ basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppc64) basic_machine=powerpc64-unknown
+ ;;
+ ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+ basic_machine=powerpc64le-unknown
+ ;;
+ ppc64le-* | powerpc64little-*)
+ basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ps2)
+ basic_machine=i386-ibm
+ ;;
+ pw32)
+ basic_machine=i586-unknown
+ os=-pw32
+ ;;
+ rdos)
+ basic_machine=i386-pc
+ os=-rdos
+ ;;
+ rom68k)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ rm[46]00)
+ basic_machine=mips-siemens
+ ;;
+ rtpc | rtpc-*)
+ basic_machine=romp-ibm
+ ;;
+ s390 | s390-*)
+ basic_machine=s390-ibm
+ ;;
+ s390x | s390x-*)
+ basic_machine=s390x-ibm
+ ;;
+ sa29200)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ sb1)
+ basic_machine=mipsisa64sb1-unknown
+ ;;
+ sb1el)
+ basic_machine=mipsisa64sb1el-unknown
+ ;;
+ sde)
+ basic_machine=mipsisa32-sde
+ os=-elf
+ ;;
+ sei)
+ basic_machine=mips-sei
+ os=-seiux
+ ;;
+ sequent)
+ basic_machine=i386-sequent
+ ;;
+ sh)
+ basic_machine=sh-hitachi
+ os=-hms
+ ;;
+ sh5el)
+ basic_machine=sh5le-unknown
+ ;;
+ sh64)
+ basic_machine=sh64-unknown
+ ;;
+ sparclite-wrs | simso-wrs)
+ basic_machine=sparclite-wrs
+ os=-vxworks
+ ;;
+ sps7)
+ basic_machine=m68k-bull
+ os=-sysv2
+ ;;
+ spur)
+ basic_machine=spur-unknown
+ ;;
+ st2000)
+ basic_machine=m68k-tandem
+ ;;
+ stratus)
+ basic_machine=i860-stratus
+ os=-sysv4
+ ;;
+ strongarm-* | thumb-*)
+ basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ sun2)
+ basic_machine=m68000-sun
+ ;;
+ sun2os3)
+ basic_machine=m68000-sun
+ os=-sunos3
+ ;;
+ sun2os4)
+ basic_machine=m68000-sun
+ os=-sunos4
+ ;;
+ sun3os3)
+ basic_machine=m68k-sun
+ os=-sunos3
+ ;;
+ sun3os4)
+ basic_machine=m68k-sun
+ os=-sunos4
+ ;;
+ sun4os3)
+ basic_machine=sparc-sun
+ os=-sunos3
+ ;;
+ sun4os4)
+ basic_machine=sparc-sun
+ os=-sunos4
+ ;;
+ sun4sol2)
+ basic_machine=sparc-sun
+ os=-solaris2
+ ;;
+ sun3 | sun3-*)
+ basic_machine=m68k-sun
+ ;;
+ sun4)
+ basic_machine=sparc-sun
+ ;;
+ sun386 | sun386i | roadrunner)
+ basic_machine=i386-sun
+ ;;
+ sv1)
+ basic_machine=sv1-cray
+ os=-unicos
+ ;;
+ symmetry)
+ basic_machine=i386-sequent
+ os=-dynix
+ ;;
+ t3e)
+ basic_machine=alphaev5-cray
+ os=-unicos
+ ;;
+ t90)
+ basic_machine=t90-cray
+ os=-unicos
+ ;;
+ tile*)
+ basic_machine=$basic_machine-unknown
+ os=-linux-gnu
+ ;;
+ tx39)
+ basic_machine=mipstx39-unknown
+ ;;
+ tx39el)
+ basic_machine=mipstx39el-unknown
+ ;;
+ toad1)
+ basic_machine=pdp10-xkl
+ os=-tops20
+ ;;
+ tower | tower-32)
+ basic_machine=m68k-ncr
+ ;;
+ tpf)
+ basic_machine=s390x-ibm
+ os=-tpf
+ ;;
+ udi29k)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ ultra3)
+ basic_machine=a29k-nyu
+ os=-sym1
+ ;;
+ v810 | necv810)
+ basic_machine=v810-nec
+ os=-none
+ ;;
+ vaxv)
+ basic_machine=vax-dec
+ os=-sysv
+ ;;
+ vms)
+ basic_machine=vax-dec
+ os=-vms
+ ;;
+ vpp*|vx|vx-*)
+ basic_machine=f301-fujitsu
+ ;;
+ vxworks960)
+ basic_machine=i960-wrs
+ os=-vxworks
+ ;;
+ vxworks68)
+ basic_machine=m68k-wrs
+ os=-vxworks
+ ;;
+ vxworks29k)
+ basic_machine=a29k-wrs
+ os=-vxworks
+ ;;
+ w65*)
+ basic_machine=w65-wdc
+ os=-none
+ ;;
+ w89k-*)
+ basic_machine=hppa1.1-winbond
+ os=-proelf
+ ;;
+ xbox)
+ basic_machine=i686-pc
+ os=-mingw32
+ ;;
+ xps | xps100)
+ basic_machine=xps100-honeywell
+ ;;
+ xscale-* | xscalee[bl]-*)
+ basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
+ ;;
+ ymp)
+ basic_machine=ymp-cray
+ os=-unicos
+ ;;
+ z8k-*-coff)
+ basic_machine=z8k-unknown
+ os=-sim
+ ;;
+ z80-*-coff)
+ basic_machine=z80-unknown
+ os=-sim
+ ;;
+ none)
+ basic_machine=none-none
+ os=-none
+ ;;
+
+# Here we handle the default manufacturer of certain CPU types. It is in
+# some cases the only manufacturer, in others, it is the most popular.
+ w89k)
+ basic_machine=hppa1.1-winbond
+ ;;
+ op50n)
+ basic_machine=hppa1.1-oki
+ ;;
+ op60c)
+ basic_machine=hppa1.1-oki
+ ;;
+ romp)
+ basic_machine=romp-ibm
+ ;;
+ mmix)
+ basic_machine=mmix-knuth
+ ;;
+ rs6000)
+ basic_machine=rs6000-ibm
+ ;;
+ vax)
+ basic_machine=vax-dec
+ ;;
+ pdp10)
+ # there are many clones, so DEC is not a safe bet
+ basic_machine=pdp10-unknown
+ ;;
+ pdp11)
+ basic_machine=pdp11-dec
+ ;;
+ we32k)
+ basic_machine=we32k-att
+ ;;
+ sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
+ basic_machine=sh-unknown
+ ;;
+ sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
+ basic_machine=sparc-sun
+ ;;
+ cydra)
+ basic_machine=cydra-cydrome
+ ;;
+ orion)
+ basic_machine=orion-highlevel
+ ;;
+ orion105)
+ basic_machine=clipper-highlevel
+ ;;
+ mac | mpw | mac-mpw)
+ basic_machine=m68k-apple
+ ;;
+ pmac | pmac-mpw)
+ basic_machine=powerpc-apple
+ ;;
+ *-unknown)
+ # Make sure to match an already-canonicalized machine name.
+ ;;
+ *)
+ echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+ *-digital*)
+ basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+ ;;
+ *-commodore*)
+ basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+ ;;
+ *)
+ ;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+ # First match some system type aliases
+ # that might get confused with valid system types.
+ # -solaris* is a basic system type, with this one exception.
+ -auroraux)
+ os=-auroraux
+ ;;
+ -solaris1 | -solaris1.*)
+ os=`echo $os | sed -e 's|solaris1|sunos4|'`
+ ;;
+ -solaris)
+ os=-solaris2
+ ;;
+ -svr4*)
+ os=-sysv4
+ ;;
+ -unixware*)
+ os=-sysv4.2uw
+ ;;
+ -gnu/linux*)
+ os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+ ;;
+ # First accept the basic system types.
+ # The portable systems comes first.
+ # Each alternative MUST END IN A *, to match a version number.
+ # -sysv* is not here because it comes later, after sysvr4.
+ -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
+ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
+ | -sym* | -kopensolaris* \
+ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+ | -aos* | -aros* \
+ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+ | -openbsd* | -solidbsd* \
+ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+ | -chorusos* | -chorusrdb* | -cegcc* \
+ | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+ | -mingw32* | -linux-gnu* | -linux-android* \
+ | -linux-newlib* | -linux-uclibc* \
+ | -uxpv* | -beos* | -mpeix* | -udk* \
+ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
+ # Remember, each alternative MUST END IN *, to match a version number.
+ ;;
+ -qnx*)
+ case $basic_machine in
+ x86-* | i*86-*)
+ ;;
+ *)
+ os=-nto$os
+ ;;
+ esac
+ ;;
+ -nto-qnx*)
+ ;;
+ -nto*)
+ os=`echo $os | sed -e 's|nto|nto-qnx|'`
+ ;;
+ -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+ ;;
+ -mac*)
+ os=`echo $os | sed -e 's|mac|macos|'`
+ ;;
+ -linux-dietlibc)
+ os=-linux-dietlibc
+ ;;
+ -linux*)
+ os=`echo $os | sed -e 's|linux|linux-gnu|'`
+ ;;
+ -sunos5*)
+ os=`echo $os | sed -e 's|sunos5|solaris2|'`
+ ;;
+ -sunos6*)
+ os=`echo $os | sed -e 's|sunos6|solaris3|'`
+ ;;
+ -opened*)
+ os=-openedition
+ ;;
+ -os400*)
+ os=-os400
+ ;;
+ -wince*)
+ os=-wince
+ ;;
+ -osfrose*)
+ os=-osfrose
+ ;;
+ -osf*)
+ os=-osf
+ ;;
+ -utek*)
+ os=-bsd
+ ;;
+ -dynix*)
+ os=-bsd
+ ;;
+ -acis*)
+ os=-aos
+ ;;
+ -atheos*)
+ os=-atheos
+ ;;
+ -syllable*)
+ os=-syllable
+ ;;
+ -386bsd)
+ os=-bsd
+ ;;
+ -ctix* | -uts*)
+ os=-sysv
+ ;;
+ -nova*)
+ os=-rtmk-nova
+ ;;
+ -ns2 )
+ os=-nextstep2
+ ;;
+ -nsk*)
+ os=-nsk
+ ;;
+ # Preserve the version number of sinix5.
+ -sinix5.*)
+ os=`echo $os | sed -e 's|sinix|sysv|'`
+ ;;
+ -sinix*)
+ os=-sysv4
+ ;;
+ -tpf*)
+ os=-tpf
+ ;;
+ -triton*)
+ os=-sysv3
+ ;;
+ -oss*)
+ os=-sysv3
+ ;;
+ -svr4)
+ os=-sysv4
+ ;;
+ -svr3)
+ os=-sysv3
+ ;;
+ -sysvr4)
+ os=-sysv4
+ ;;
+ # This must come after -sysvr4.
+ -sysv*)
+ ;;
+ -ose*)
+ os=-ose
+ ;;
+ -es1800*)
+ os=-ose
+ ;;
+ -xenix)
+ os=-xenix
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ os=-mint
+ ;;
+ -aros*)
+ os=-aros
+ ;;
+ -kaos*)
+ os=-kaos
+ ;;
+ -zvmoe)
+ os=-zvmoe
+ ;;
+ -dicos*)
+ os=-dicos
+ ;;
+ -nacl*)
+ ;;
+ -none)
+ ;;
+ *)
+ # Get rid of the `-' at the beginning of $os.
+ os=`echo $os | sed 's/[^-]*-//'`
+ echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system. Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+ score-*)
+ os=-elf
+ ;;
+ spu-*)
+ os=-elf
+ ;;
+ *-acorn)
+ os=-riscix1.2
+ ;;
+ arm*-rebel)
+ os=-linux
+ ;;
+ arm*-semi)
+ os=-aout
+ ;;
+ c4x-* | tic4x-*)
+ os=-coff
+ ;;
+ tic54x-*)
+ os=-coff
+ ;;
+ tic55x-*)
+ os=-coff
+ ;;
+ tic6x-*)
+ os=-coff
+ ;;
+ # This must come before the *-dec entry.
+ pdp10-*)
+ os=-tops20
+ ;;
+ pdp11-*)
+ os=-none
+ ;;
+ *-dec | vax-*)
+ os=-ultrix4.2
+ ;;
+ m68*-apollo)
+ os=-domain
+ ;;
+ i386-sun)
+ os=-sunos4.0.2
+ ;;
+ m68000-sun)
+ os=-sunos3
+ # This also exists in the configure program, but was not the
+ # default.
+ # os=-sunos4
+ ;;
+ m68*-cisco)
+ os=-aout
+ ;;
+ mep-*)
+ os=-elf
+ ;;
+ mips*-cisco)
+ os=-elf
+ ;;
+ mips*-*)
+ os=-elf
+ ;;
+ or32-*)
+ os=-coff
+ ;;
+ *-tti) # must be before sparc entry or we get the wrong os.
+ os=-sysv3
+ ;;
+ sparc-* | *-sun)
+ os=-sunos4.1.1
+ ;;
+ *-be)
+ os=-beos
+ ;;
+ *-haiku)
+ os=-haiku
+ ;;
+ *-ibm)
+ os=-aix
+ ;;
+ *-knuth)
+ os=-mmixware
+ ;;
+ *-wec)
+ os=-proelf
+ ;;
+ *-winbond)
+ os=-proelf
+ ;;
+ *-oki)
+ os=-proelf
+ ;;
+ *-hp)
+ os=-hpux
+ ;;
+ *-hitachi)
+ os=-hiux
+ ;;
+ i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+ os=-sysv
+ ;;
+ *-cbm)
+ os=-amigaos
+ ;;
+ *-dg)
+ os=-dgux
+ ;;
+ *-dolphin)
+ os=-sysv3
+ ;;
+ m68k-ccur)
+ os=-rtu
+ ;;
+ m88k-omron*)
+ os=-luna
+ ;;
+ *-next )
+ os=-nextstep
+ ;;
+ *-sequent)
+ os=-ptx
+ ;;
+ *-crds)
+ os=-unos
+ ;;
+ *-ns)
+ os=-genix
+ ;;
+ i370-*)
+ os=-mvs
+ ;;
+ *-next)
+ os=-nextstep3
+ ;;
+ *-gould)
+ os=-sysv
+ ;;
+ *-highlevel)
+ os=-bsd
+ ;;
+ *-encore)
+ os=-bsd
+ ;;
+ *-sgi)
+ os=-irix
+ ;;
+ *-siemens)
+ os=-sysv4
+ ;;
+ *-masscomp)
+ os=-rtu
+ ;;
+ f30[01]-fujitsu | f700-fujitsu)
+ os=-uxpv
+ ;;
+ *-rom68k)
+ os=-coff
+ ;;
+ *-*bug)
+ os=-coff
+ ;;
+ *-apple)
+ os=-macos
+ ;;
+ *-atari*)
+ os=-mint
+ ;;
+ *)
+ os=-none
+ ;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer. We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+ *-unknown)
+ case $os in
+ -riscix*)
+ vendor=acorn
+ ;;
+ -sunos*)
+ vendor=sun
+ ;;
+ -cnk*|-aix*)
+ vendor=ibm
+ ;;
+ -beos*)
+ vendor=be
+ ;;
+ -hpux*)
+ vendor=hp
+ ;;
+ -mpeix*)
+ vendor=hp
+ ;;
+ -hiux*)
+ vendor=hitachi
+ ;;
+ -unos*)
+ vendor=crds
+ ;;
+ -dgux*)
+ vendor=dg
+ ;;
+ -luna*)
+ vendor=omron
+ ;;
+ -genix*)
+ vendor=ns
+ ;;
+ -mvs* | -opened*)
+ vendor=ibm
+ ;;
+ -os400*)
+ vendor=ibm
+ ;;
+ -ptx*)
+ vendor=sequent
+ ;;
+ -tpf*)
+ vendor=ibm
+ ;;
+ -vxsim* | -vxworks* | -windiss*)
+ vendor=wrs
+ ;;
+ -aux*)
+ vendor=apple
+ ;;
+ -hms*)
+ vendor=hitachi
+ ;;
+ -mpw* | -macos*)
+ vendor=apple
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ vendor=atari
+ ;;
+ -vos*)
+ vendor=stratus
+ ;;
+ esac
+ basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+ ;;
+esac
+
+echo $basic_machine$os
+exit
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/autoconf/configure.ac b/autoconf/configure.ac
new file mode 100644
index 00000000000..7fa883e9cc5
--- /dev/null
+++ b/autoconf/configure.ac
@@ -0,0 +1,1737 @@
+dnl === configure.ac --------------------------------------------------------===
+dnl The LLVM Compiler Infrastructure
+dnl
+dnl This file is distributed under the University of Illinois Open Source
+dnl License. See LICENSE.TXT for details.
+dnl
+dnl===-----------------------------------------------------------------------===
+dnl This is the LLVM configuration script. It is processed by the autoconf
+dnl program to produce a script named configure. This script contains the
+dnl configuration checks that LLVM needs in order to support multiple platforms.
+dnl This file is composed of 10 sections per the recommended organization of
+dnl autoconf input defined in the autoconf documentation. As this file evolves,
+dnl please keep the various types of checks within their sections. The sections
+dnl are as follows:
+dnl
+dnl SECTION 1: Initialization & Setup
+dnl SECTION 2: Architecture, target, and host checks
+dnl SECTION 3: Command line arguments for the configure script.
+dnl SECTION 4: Check for programs we need and that they are the right version
+dnl SECTION 5: Check for libraries
+dnl SECTION 6: Check for header files
+dnl SECTION 7: Check for types and structures
+dnl SECTION 8: Check for specific functions needed
+dnl SECTION 9: Additional checks, variables, etc.
+dnl SECTION 10: Specify the output files and generate it
+dnl
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 1: Initialization & Setup
+dnl===
+dnl===-----------------------------------------------------------------------===
+dnl Initialize autoconf and define the package name, version number and
+dnl address for reporting bugs.
+AC_INIT([LLVM],[3.2svn],[http://llvm.org/bugs/])
+AC_DEFINE([LLVM_VERSION_MAJOR], [3], [Major version of the LLVM API])
+AC_DEFINE([LLVM_VERSION_MINOR], [2], [Minor version of the LLVM API])
+
+dnl Provide a copyright substitution and ensure the copyright notice is included
+dnl in the output of --version option of the generated configure script.
+AC_SUBST(LLVM_COPYRIGHT,["Copyright (c) 2003-2012 University of Illinois at Urbana-Champaign."])
+AC_COPYRIGHT([Copyright (c) 2003-2012 University of Illinois at Urbana-Champaign.])
+
+dnl Indicate that we require autoconf 2.60 or later.
+AC_PREREQ(2.60)
+
+dnl Verify that the source directory is valid. This makes sure that we are
+dnl configuring LLVM and not some other package (it validates --srcdir argument)
+AC_CONFIG_SRCDIR([lib/VMCore/Module.cpp])
+
+dnl Place all of the extra autoconf files into the config subdirectory. Tell
+dnl various tools where the m4 autoconf macros are.
+AC_CONFIG_AUX_DIR([autoconf])
+
+dnl Quit if the source directory has already been configured.
+dnl NOTE: This relies upon undocumented autoconf behavior.
+if test ${srcdir} != "." ; then
+ if test -f ${srcdir}/include/llvm/Config/config.h ; then
+ AC_MSG_ERROR([Already configured in ${srcdir}])
+ fi
+fi
+
+dnl We need to check for the compiler up here to avoid anything else
+dnl starting with a different one.
+AC_PROG_CC(clang llvm-gcc gcc)
+AC_PROG_CXX(clang++ llvm-g++ g++)
+AC_PROG_CPP
+
+dnl Configure all of the projects present in our source tree. While we could
+dnl just AC_CONFIG_SUBDIRS on the set of directories in projects that have a
+dnl configure script, that usage of the AC_CONFIG_SUBDIRS macro is deprecated.
+dnl Instead we match on the known projects.
+
+dnl
+dnl One tricky part of doing this is that some projects depend upon other
+dnl projects. For example, several projects rely upon the LLVM test suite.
+dnl We want to configure those projects first so that their object trees are
+dnl created before running the configure scripts of projects that depend upon
+dnl them.
+dnl
+
+dnl Several projects use llvm-gcc, so configure that first
+if test -d ${srcdir}/projects/llvm-gcc ; then
+ AC_CONFIG_SUBDIRS([projects/llvm-gcc])
+fi
+
+dnl Several projects use the LLVM test suite, so configure it next.
+if test -d ${srcdir}/projects/test-suite ; then
+ AC_CONFIG_SUBDIRS([projects/test-suite])
+fi
+
+dnl llvm-test is the old name of the test-suite, kept here for backwards
+dnl compatibility
+if test -d ${srcdir}/projects/llvm-test ; then
+ AC_CONFIG_SUBDIRS([projects/llvm-test])
+fi
+
+dnl Some projects use poolalloc; configure that next
+if test -d ${srcdir}/projects/poolalloc ; then
+ AC_CONFIG_SUBDIRS([projects/poolalloc])
+fi
+
+if test -d ${srcdir}/projects/llvm-poolalloc ; then
+ AC_CONFIG_SUBDIRS([projects/llvm-poolalloc])
+fi
+
+dnl Check for all other projects
+for i in `ls ${srcdir}/projects`
+do
+ if test -d ${srcdir}/projects/${i} ; then
+ case ${i} in
+ sample) AC_CONFIG_SUBDIRS([projects/sample]) ;;
+ privbracket) AC_CONFIG_SUBDIRS([projects/privbracket]) ;;
+ llvm-stacker) AC_CONFIG_SUBDIRS([projects/llvm-stacker]) ;;
+ llvm-reopt) AC_CONFIG_SUBDIRS([projects/llvm-reopt]);;
+ llvm-java) AC_CONFIG_SUBDIRS([projects/llvm-java]) ;;
+ llvm-tv) AC_CONFIG_SUBDIRS([projects/llvm-tv]) ;;
+ safecode) AC_CONFIG_SUBDIRS([projects/safecode]) ;;
+ llvm-kernel) AC_CONFIG_SUBDIRS([projects/llvm-kernel]) ;;
+ compiler-rt) ;;
+ llvm-gcc) ;;
+ test-suite) ;;
+ llvm-test) ;;
+ poolalloc) ;;
+ llvm-poolalloc) ;;
+ *)
+ AC_MSG_WARN([Unknown project (${i}) won't be configured automatically])
+ ;;
+ esac
+ fi
+done
+
+dnl Disable the build of polly, even if it is checked out into tools/polly.
+AC_ARG_ENABLE(polly,
+ AS_HELP_STRING([--enable-polly],
+ [Use polly if available (default is YES)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_POLLY,[1]) ;;
+ no) AC_SUBST(ENABLE_POLLY,[0]) ;;
+ default) AC_SUBST(ENABLE_POLLY,[1]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-polly. Use "yes" or "no"]) ;;
+esac
+
+
+dnl Check if polly is checked out into tools/polly and configure it if
+dnl available.
+if (test -d ${srcdir}/tools/polly) && (test $ENABLE_POLLY -eq 1) ; then
+ AC_SUBST(LLVM_HAS_POLLY,1)
+ AC_CONFIG_SUBDIRS([tools/polly])
+fi
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 2: Architecture, target, and host checks
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+dnl Check the target for which we're compiling and the host that will do the
+dnl compilations. This will tell us which LLVM compiler will be used for
+dnl compiling SSA into object code. This needs to be done early because
+dnl following tests depend on it.
+AC_CANONICAL_TARGET
+
+dnl Determine the platform type and cache its value. This helps us configure
+dnl the System library to the correct build platform.
+AC_CACHE_CHECK([type of operating system we're going to host on],
+ [llvm_cv_os_type],
+[case $host in
+ *-*-aix*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="AIX"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-irix*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="IRIX"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-cygwin*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Cygwin"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-darwin*)
+ llvm_cv_link_all_option="-Wl,-all_load"
+ llvm_cv_no_link_all_option="-Wl,-noall_load"
+ llvm_cv_os_type="Darwin"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-minix*)
+ llvm_cv_link_all_option="-Wl,-all_load"
+ llvm_cv_no_link_all_option="-Wl,-noall_load"
+ llvm_cv_os_type="Minix"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-freebsd* | *-*-kfreebsd-gnu)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="FreeBSD"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-openbsd*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="OpenBSD"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-netbsd*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="NetBSD"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-dragonfly*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="DragonFly"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-hpux*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="HP-UX"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-interix*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Interix"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-linux*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Linux"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-gnu*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="GNU"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-solaris*)
+ llvm_cv_link_all_option="-Wl,-z,allextract"
+ llvm_cv_no_link_all_option="-Wl,-z,defaultextract"
+ llvm_cv_os_type="SunOS"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-auroraux*)
+ llvm_cv_link_all_option="-Wl,-z,allextract"
+ llvm_cv_link_all_option="-Wl,-z,defaultextract"
+ llvm_cv_os_type="AuroraUX"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-win32*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Win32"
+ llvm_cv_platform_type="Win32" ;;
+ *-*-mingw*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="MingW"
+ llvm_cv_platform_type="Win32" ;;
+ *-*-haiku*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Haiku"
+ llvm_cv_platform_type="Unix" ;;
+ *-unknown-eabi*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Freestanding"
+ llvm_cv_platform_type="Unix" ;;
+ *-unknown-elf*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Freestanding"
+ llvm_cv_platform_type="Unix" ;;
+ *)
+ llvm_cv_link_all_option=""
+ llvm_cv_no_link_all_option=""
+ llvm_cv_os_type="Unknown"
+ llvm_cv_platform_type="Unknown" ;;
+esac])
+
+AC_CACHE_CHECK([type of operating system we're going to target],
+ [llvm_cv_target_os_type],
+[case $target in
+ *-*-aix*)
+ llvm_cv_target_os_type="AIX" ;;
+ *-*-irix*)
+ llvm_cv_target_os_type="IRIX" ;;
+ *-*-cygwin*)
+ llvm_cv_target_os_type="Cygwin" ;;
+ *-*-darwin*)
+ llvm_cv_target_os_type="Darwin" ;;
+ *-*-minix*)
+ llvm_cv_target_os_type="Minix" ;;
+ *-*-freebsd* | *-*-kfreebsd-gnu)
+ llvm_cv_target_os_type="FreeBSD" ;;
+ *-*-openbsd*)
+ llvm_cv_target_os_type="OpenBSD" ;;
+ *-*-netbsd*)
+ llvm_cv_target_os_type="NetBSD" ;;
+ *-*-dragonfly*)
+ llvm_cv_target_os_type="DragonFly" ;;
+ *-*-hpux*)
+ llvm_cv_target_os_type="HP-UX" ;;
+ *-*-interix*)
+ llvm_cv_target_os_type="Interix" ;;
+ *-*-linux*)
+ llvm_cv_target_os_type="Linux" ;;
+ *-*-gnu*)
+ llvm_cv_target_os_type="GNU" ;;
+ *-*-solaris*)
+ llvm_cv_target_os_type="SunOS" ;;
+ *-*-auroraux*)
+ llvm_cv_target_os_type="AuroraUX" ;;
+ *-*-win32*)
+ llvm_cv_target_os_type="Win32" ;;
+ *-*-mingw*)
+ llvm_cv_target_os_type="MingW" ;;
+ *-*-haiku*)
+ llvm_cv_target_os_type="Haiku" ;;
+ *-*-rtems*)
+ llvm_cv_target_os_type="RTEMS" ;;
+ *-*-nacl*)
+ llvm_cv_target_os_type="NativeClient" ;;
+ *-unknown-eabi*)
+ llvm_cv_target_os_type="Freestanding" ;;
+ *)
+ llvm_cv_target_os_type="Unknown" ;;
+esac])
+
+dnl Make sure we aren't attempting to configure for an unknown system
+if test "$llvm_cv_os_type" = "Unknown" ; then
+ AC_MSG_ERROR([Operating system is unknown, configure can't continue])
+fi
+
+dnl Set the "OS" Makefile variable based on the platform type so the
+dnl makefile can configure itself to specific build hosts
+AC_SUBST(OS,$llvm_cv_os_type)
+AC_SUBST(HOST_OS,$llvm_cv_os_type)
+AC_SUBST(TARGET_OS,$llvm_cv_target_os_type)
+
+dnl Set the LINKALL and NOLINKALL Makefile variables based on the platform
+AC_SUBST(LINKALL,$llvm_cv_link_all_option)
+AC_SUBST(NOLINKALL,$llvm_cv_no_link_all_option)
+
+dnl Set the "LLVM_ON_*" variables based on llvm_cv_platform_type
+dnl This is used by lib/Support to determine the basic kind of implementation
+dnl to use.
+case $llvm_cv_platform_type in
+ Unix)
+ AC_DEFINE([LLVM_ON_UNIX],[1],[Define if this is Unixish platform])
+ AC_SUBST(LLVM_ON_UNIX,[1])
+ AC_SUBST(LLVM_ON_WIN32,[0])
+ ;;
+ Win32)
+ AC_DEFINE([LLVM_ON_WIN32],[1],[Define if this is Win32ish platform])
+ AC_SUBST(LLVM_ON_UNIX,[0])
+ AC_SUBST(LLVM_ON_WIN32,[1])
+ ;;
+esac
+
+dnl Determine what our target architecture is and configure accordingly.
+dnl This will allow Makefiles to make a distinction between the hardware and
+dnl the OS.
+AC_CACHE_CHECK([target architecture],[llvm_cv_target_arch],
+[case $target in
+ i?86-*) llvm_cv_target_arch="x86" ;;
+ amd64-* | x86_64-*) llvm_cv_target_arch="x86_64" ;;
+ sparc*-*) llvm_cv_target_arch="Sparc" ;;
+ powerpc*-*) llvm_cv_target_arch="PowerPC" ;;
+ arm*-*) llvm_cv_target_arch="ARM" ;;
+ mips-*) llvm_cv_target_arch="Mips" ;;
+ mipsel-*) llvm_cv_target_arch="Mips" ;;
+ xcore-*) llvm_cv_target_arch="XCore" ;;
+ msp430-*) llvm_cv_target_arch="MSP430" ;;
+ hexagon-*) llvm_cv_target_arch="Hexagon" ;;
+ mblaze-*) llvm_cv_target_arch="MBlaze" ;;
+ nvptx-*) llvm_cv_target_arch="NVPTX" ;;
+ *) llvm_cv_target_arch="Unknown" ;;
+esac])
+
+if test "$llvm_cv_target_arch" = "Unknown" ; then
+ AC_MSG_WARN([Configuring LLVM for an unknown target archicture])
+fi
+
+dnl Determine the LLVM native architecture for the target
+case "$llvm_cv_target_arch" in
+ x86) LLVM_NATIVE_ARCH="X86" ;;
+ x86_64) LLVM_NATIVE_ARCH="X86" ;;
+ *) LLVM_NATIVE_ARCH="$llvm_cv_target_arch" ;;
+esac
+
+dnl Define a substitution, ARCH, for the target architecture
+AC_SUBST(ARCH,$llvm_cv_target_arch)
+
+dnl Determine what our host architecture.
+dnl This will allow MCJIT regress tests runs only for supported
+dnl platforms.
+case $host in
+ i?86-*) host_arch="x86" ;;
+ amd64-* | x86_64-*) host_arch="x86_64" ;;
+ sparc*-*) host_arch="Sparc" ;;
+ powerpc*-*) host_arch="PowerPC" ;;
+ arm*-*) host_arch="ARM" ;;
+ mips-*) host_arch="Mips" ;;
+ mipsel-*) host_arch="Mips" ;;
+ xcore-*) host_arch="XCore" ;;
+ msp430-*) host_arch="MSP430" ;;
+ hexagon-*) host_arch="Hexagon" ;;
+ mblaze-*) host_arch="MBlaze" ;;
+ *) host_arch="Unknown" ;;
+esac
+
+if test "$host_arch" = "Unknown" ; then
+ AC_MSG_WARN([Configuring LLVM for an unknown host archicture])
+fi
+
+AC_SUBST(HOST_ARCH,$host_arch)
+
+dnl Check for the endianness of the target
+AC_C_BIGENDIAN(AC_SUBST([ENDIAN],[big]),AC_SUBST([ENDIAN],[little]))
+
+dnl Check for build platform executable suffix if we're cross-compiling
+if test "$cross_compiling" = yes; then
+ AC_SUBST(LLVM_CROSS_COMPILING, [1])
+ AC_BUILD_EXEEXT
+ ac_build_prefix=${build_alias}-
+ AC_CHECK_PROG(BUILD_CXX, ${ac_build_prefix}g++, ${ac_build_prefix}g++)
+ if test -z "$BUILD_CXX"; then
+ AC_CHECK_PROG(BUILD_CXX, g++, g++)
+ if test -z "$BUILD_CXX"; then
+ AC_CHECK_PROG(BUILD_CXX, c++, c++, , , /usr/ucb/c++)
+ fi
+ fi
+else
+ AC_SUBST(LLVM_CROSS_COMPILING, [0])
+fi
+
+dnl Check to see if there's a .svn or .git directory indicating that this
+dnl build is being done from a checkout. This sets up several defaults for
+dnl the command line switches. When we build with a checkout directory,
+dnl we get a debug with assertions turned on. Without, we assume a source
+dnl release and we get an optimized build without assertions.
+dnl See --enable-optimized and --enable-assertions below
+if test -d ".svn" -o -d "${srcdir}/.svn" -o -d ".git" -o -d "${srcdir}/.git"; then
+ cvsbuild="yes"
+ optimize="no"
+ AC_SUBST(CVSBUILD,[[CVSBUILD=1]])
+else
+ cvsbuild="no"
+ optimize="yes"
+fi
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 3: Command line arguments for the configure script.
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+dnl --enable-libcpp : check whether or not to use libc++ on the command line
+AC_ARG_ENABLE(libcpp,
+ AS_HELP_STRING([--enable-libcpp],
+ [Use libc++ if available (default is NO)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_LIBCPP,[1]) ;;
+ no) AC_SUBST(ENABLE_LIBCPP,[0]) ;;
+ default) AC_SUBST(ENABLE_LIBCPP,[0]);;
+ *) AC_MSG_ERROR([Invalid setting for --enable-libcpp. Use "yes" or "no"]) ;;
+esac
+
+dnl --enable-cxx11 : check whether or not to use -std=c++11 on the command line
+AC_ARG_ENABLE(cxx11,
+ AS_HELP_STRING([--enable-cxx11],
+ [Use c++11 if available (default is NO)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_CXX11,[1]) ;;
+ no) AC_SUBST(ENABLE_CXX11,[0]) ;;
+ default) AC_SUBST(ENABLE_CXX11,[0]);;
+ *) AC_MSG_ERROR([Invalid setting for --enable-cxx11. Use "yes" or "no"]) ;;
+esac
+
+dnl --enable-optimized : check whether they want to do an optimized build:
+AC_ARG_ENABLE(optimized, AS_HELP_STRING(
+ --enable-optimized,[Compile with optimizations enabled (default is NO)]),,enableval=$optimize)
+if test ${enableval} = "no" ; then
+ AC_SUBST(ENABLE_OPTIMIZED,[[]])
+else
+ AC_SUBST(ENABLE_OPTIMIZED,[[ENABLE_OPTIMIZED=1]])
+fi
+
+dnl --enable-profiling : check whether they want to do a profile build:
+AC_ARG_ENABLE(profiling, AS_HELP_STRING(
+ --enable-profiling,[Compile with profiling enabled (default is NO)]),,enableval="no")
+if test ${enableval} = "no" ; then
+ AC_SUBST(ENABLE_PROFILING,[[]])
+else
+ AC_SUBST(ENABLE_PROFILING,[[ENABLE_PROFILING=1]])
+fi
+
+dnl --enable-assertions : check whether they want to turn on assertions or not:
+AC_ARG_ENABLE(assertions,AS_HELP_STRING(
+ --enable-assertions,[Compile with assertion checks enabled (default is YES)]),, enableval="yes")
+if test ${enableval} = "yes" ; then
+ AC_SUBST(DISABLE_ASSERTIONS,[[]])
+else
+ AC_SUBST(DISABLE_ASSERTIONS,[[DISABLE_ASSERTIONS=1]])
+fi
+
+dnl --enable-werror : check whether we want Werror on by default
+AC_ARG_ENABLE(werror,AS_HELP_STRING(
+ --enable-werror,[Compile with -Werror enabled (default is NO)]),, enableval="no")
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_WERROR,[1]) ;;
+ no) AC_SUBST(ENABLE_WERROR,[0]) ;;
+ default) AC_SUBST(ENABLE_WERROR,[0]);;
+ *) AC_MSG_ERROR([Invalid setting for --enable-werror. Use "yes" or "no"]) ;;
+esac
+
+dnl --enable-expensive-checks : check whether they want to turn on expensive debug checks:
+AC_ARG_ENABLE(expensive-checks,AS_HELP_STRING(
+ --enable-expensive-checks,[Compile with expensive debug checks enabled (default is NO)]),, enableval="no")
+if test ${enableval} = "yes" ; then
+ AC_SUBST(ENABLE_EXPENSIVE_CHECKS,[[ENABLE_EXPENSIVE_CHECKS=1]])
+ AC_SUBST(EXPENSIVE_CHECKS,[[yes]])
+else
+ AC_SUBST(ENABLE_EXPENSIVE_CHECKS,[[]])
+ AC_SUBST(EXPENSIVE_CHECKS,[[no]])
+fi
+
+dnl --enable-debug-runtime : should runtime libraries have debug symbols?
+AC_ARG_ENABLE(debug-runtime,
+ AS_HELP_STRING(--enable-debug-runtime,[Build runtime libs with debug symbols (default is NO)]),,enableval=no)
+if test ${enableval} = "no" ; then
+ AC_SUBST(DEBUG_RUNTIME,[[]])
+else
+ AC_SUBST(DEBUG_RUNTIME,[[DEBUG_RUNTIME=1]])
+fi
+
+dnl --enable-debug-symbols : should even optimized compiler libraries
+dnl have debug symbols?
+AC_ARG_ENABLE(debug-symbols,
+ AS_HELP_STRING(--enable-debug-symbols,[Build compiler with debug symbols (default is NO if optimization is on and YES if it's off)]),,enableval=no)
+if test ${enableval} = "no" ; then
+ AC_SUBST(DEBUG_SYMBOLS,[[]])
+else
+ AC_SUBST(DEBUG_SYMBOLS,[[DEBUG_SYMBOLS=1]])
+fi
+
+dnl --enable-keep-symbols : do not strip installed executables
+AC_ARG_ENABLE(keep-symbols,
+ AS_HELP_STRING(--enable-keep-symbols,[Do not strip installed executables)]),,enableval=no)
+if test ${enableval} = "no" ; then
+ AC_SUBST(KEEP_SYMBOLS,[[]])
+else
+ AC_SUBST(KEEP_SYMBOLS,[[KEEP_SYMBOLS=1]])
+fi
+
+dnl --enable-jit: check whether they want to enable the jit
+AC_ARG_ENABLE(jit,
+ AS_HELP_STRING(--enable-jit,
+ [Enable Just In Time Compiling (default is YES)]),,
+ enableval=default)
+if test ${enableval} = "no"
+then
+ AC_SUBST(JIT,[[]])
+else
+ case "$llvm_cv_target_arch" in
+ x86) AC_SUBST(TARGET_HAS_JIT,1) ;;
+ Sparc) AC_SUBST(TARGET_HAS_JIT,0) ;;
+ PowerPC) AC_SUBST(TARGET_HAS_JIT,1) ;;
+ x86_64) AC_SUBST(TARGET_HAS_JIT,1) ;;
+ ARM) AC_SUBST(TARGET_HAS_JIT,1) ;;
+ Mips) AC_SUBST(TARGET_HAS_JIT,1) ;;
+ XCore) AC_SUBST(TARGET_HAS_JIT,0) ;;
+ MSP430) AC_SUBST(TARGET_HAS_JIT,0) ;;
+ Hexagon) AC_SUBST(TARGET_HAS_JIT,0) ;;
+ MBlaze) AC_SUBST(TARGET_HAS_JIT,0) ;;
+ NVPTX) AC_SUBST(TARGET_HAS_JIT,0) ;;
+ *) AC_SUBST(TARGET_HAS_JIT,0) ;;
+ esac
+fi
+
+dnl Allow enablement of building and installing docs
+AC_ARG_ENABLE(docs,
+ AS_HELP_STRING([--enable-docs],
+ [Build documents (default is YES)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_DOCS,[1]) ;;
+ no) AC_SUBST(ENABLE_DOCS,[0]) ;;
+ default) AC_SUBST(ENABLE_DOCS,[1]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-docs. Use "yes" or "no"]) ;;
+esac
+
+dnl Allow enablement of doxygen generated documentation
+AC_ARG_ENABLE(doxygen,
+ AS_HELP_STRING([--enable-doxygen],
+ [Build doxygen documentation (default is NO)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_DOXYGEN,[1]) ;;
+ no) AC_SUBST(ENABLE_DOXYGEN,[0]) ;;
+ default) AC_SUBST(ENABLE_DOXYGEN,[0]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-doxygen. Use "yes" or "no"]) ;;
+esac
+
+dnl Allow disablement of threads
+AC_ARG_ENABLE(threads,
+ AS_HELP_STRING([--enable-threads],
+ [Use threads if available (default is YES)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(LLVM_ENABLE_THREADS,[1]) ;;
+ no) AC_SUBST(LLVM_ENABLE_THREADS,[0]) ;;
+ default) AC_SUBST(LLVM_ENABLE_THREADS,[1]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-threads. Use "yes" or "no"]) ;;
+esac
+AC_DEFINE_UNQUOTED([LLVM_ENABLE_THREADS],$LLVM_ENABLE_THREADS,
+ [Define if threads enabled])
+
+dnl Allow disablement of pthread.h
+AC_ARG_ENABLE(pthreads,
+ AS_HELP_STRING([--enable-pthreads],
+ [Use pthreads if available (default is YES)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_PTHREADS,[1]) ;;
+ no) AC_SUBST(ENABLE_PTHREADS,[0]) ;;
+ default) AC_SUBST(ENABLE_PTHREADS,[1]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-pthreads. Use "yes" or "no"]) ;;
+esac
+
+dnl Allow building without position independent code
+AC_ARG_ENABLE(pic,
+ AS_HELP_STRING([--enable-pic],
+ [Build LLVM with Position Independent Code (default is YES)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_PIC,[1]) ;;
+ no) AC_SUBST(ENABLE_PIC,[0]) ;;
+ default) AC_SUBST(ENABLE_PIC,[1]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-pic. Use "yes" or "no"]) ;;
+esac
+AC_DEFINE_UNQUOTED([ENABLE_PIC],$ENABLE_PIC,
+ [Define if position independent code is enabled])
+
+dnl Allow building a shared library and linking tools against it.
+AC_ARG_ENABLE(shared,
+ AS_HELP_STRING([--enable-shared],
+ [Build a shared library and link tools against it (default is NO)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_SHARED,[1]) ;;
+ no) AC_SUBST(ENABLE_SHARED,[0]) ;;
+ default) AC_SUBST(ENABLE_SHARED,[0]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-shared. Use "yes" or "no"]) ;;
+esac
+
+dnl Allow libstdc++ is embedded in LLVM.dll.
+AC_ARG_ENABLE(embed-stdcxx,
+ AS_HELP_STRING([--enable-embed-stdcxx],
+ [Build a shared library with embedded libstdc++ for Win32 DLL (default is NO)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_EMBED_STDCXX,[1]) ;;
+ no) AC_SUBST(ENABLE_EMBED_STDCXX,[0]) ;;
+ default) AC_SUBST(ENABLE_EMBED_STDCXX,[0]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-embed-stdcxx. Use "yes" or "no"]) ;;
+esac
+
+dnl Enable embedding timestamp information into build.
+AC_ARG_ENABLE(timestamps,
+ AS_HELP_STRING([--enable-timestamps],
+ [Enable embedding timestamp information in build (default is YES)]),,
+ enableval=default)
+case "$enableval" in
+ yes) AC_SUBST(ENABLE_TIMESTAMPS,[1]) ;;
+ no) AC_SUBST(ENABLE_TIMESTAMPS,[0]) ;;
+ default) AC_SUBST(ENABLE_TIMESTAMPS,[1]) ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-timestamps. Use "yes" or "no"]) ;;
+esac
+AC_DEFINE_UNQUOTED([ENABLE_TIMESTAMPS],$ENABLE_TIMESTAMPS,
+ [Define if timestamp information (e.g., __DATE__) is allowed])
+
+dnl Allow specific targets to be specified for building (or not)
+TARGETS_TO_BUILD=""
+AC_ARG_ENABLE([targets],AS_HELP_STRING([--enable-targets],
+ [Build specific host targets: all or target1,target2,... Valid targets are:
+ host, x86, x86_64, sparc, powerpc, arm, mips, spu, hexagon,
+ xcore, msp430, nvptx, and cpp (default=all)]),,
+ enableval=all)
+if test "$enableval" = host-only ; then
+ enableval=host
+fi
+case "$enableval" in
+ all) TARGETS_TO_BUILD="X86 Sparc PowerPC ARM Mips CellSPU XCore MSP430 CppBackend MBlaze NVPTX Hexagon" ;;
+ *)for a_target in `echo $enableval|sed -e 's/,/ /g' ` ; do
+ case "$a_target" in
+ x86) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
+ x86_64) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
+ sparc) TARGETS_TO_BUILD="Sparc $TARGETS_TO_BUILD" ;;
+ powerpc) TARGETS_TO_BUILD="PowerPC $TARGETS_TO_BUILD" ;;
+ arm) TARGETS_TO_BUILD="ARM $TARGETS_TO_BUILD" ;;
+ mips) TARGETS_TO_BUILD="Mips $TARGETS_TO_BUILD" ;;
+ mipsel) TARGETS_TO_BUILD="Mips $TARGETS_TO_BUILD" ;;
+ spu) TARGETS_TO_BUILD="CellSPU $TARGETS_TO_BUILD" ;;
+ xcore) TARGETS_TO_BUILD="XCore $TARGETS_TO_BUILD" ;;
+ msp430) TARGETS_TO_BUILD="MSP430 $TARGETS_TO_BUILD" ;;
+ cpp) TARGETS_TO_BUILD="CppBackend $TARGETS_TO_BUILD" ;;
+ hexagon) TARGETS_TO_BUILD="Hexagon $TARGETS_TO_BUILD" ;;
+ mblaze) TARGETS_TO_BUILD="MBlaze $TARGETS_TO_BUILD" ;;
+ nvptx) TARGETS_TO_BUILD="NVPTX $TARGETS_TO_BUILD" ;;
+ host) case "$llvm_cv_target_arch" in
+ x86) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
+ x86_64) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
+ Sparc) TARGETS_TO_BUILD="Sparc $TARGETS_TO_BUILD" ;;
+ PowerPC) TARGETS_TO_BUILD="PowerPC $TARGETS_TO_BUILD" ;;
+ ARM) TARGETS_TO_BUILD="ARM $TARGETS_TO_BUILD" ;;
+ Mips) TARGETS_TO_BUILD="Mips $TARGETS_TO_BUILD" ;;
+ MBlaze) TARGETS_TO_BUILD="MBlaze $TARGETS_TO_BUILD" ;;
+ CellSPU|SPU) TARGETS_TO_BUILD="CellSPU $TARGETS_TO_BUILD" ;;
+ XCore) TARGETS_TO_BUILD="XCore $TARGETS_TO_BUILD" ;;
+ MSP430) TARGETS_TO_BUILD="MSP430 $TARGETS_TO_BUILD" ;;
+ Hexagon) TARGETS_TO_BUILD="Hexagon $TARGETS_TO_BUILD" ;;
+ NVPTX) TARGETS_TO_BUILD="NVPTX $TARGETS_TO_BUILD" ;;
+ *) AC_MSG_ERROR([Can not set target to build]) ;;
+ esac ;;
+ *) AC_MSG_ERROR([Unrecognized target $a_target]) ;;
+ esac
+ done
+ ;;
+esac
+
+AC_ARG_ENABLE([experimental-targets],AS_HELP_STRING([--enable-experimental-targets],
+ [Build experimental host targets: disable or target1,target2,...
+ (default=disable)]),,
+ enableval=disable)
+
+if test ${enableval} != "disable"
+then
+ TARGETS_TO_BUILD="$enableval $TARGETS_TO_BUILD"
+fi
+
+AC_SUBST(TARGETS_TO_BUILD,$TARGETS_TO_BUILD)
+
+dnl Determine whether we are building LLVM support for the native architecture.
+dnl If so, define LLVM_NATIVE_ARCH to that LLVM target.
+for a_target in $TARGETS_TO_BUILD; do
+ if test "$a_target" = "$LLVM_NATIVE_ARCH"; then
+ AC_DEFINE_UNQUOTED(LLVM_NATIVE_ARCH, $LLVM_NATIVE_ARCH,
+ [LLVM architecture name for the native architecture, if available])
+ LLVM_NATIVE_TARGET="LLVMInitialize${LLVM_NATIVE_ARCH}Target"
+ LLVM_NATIVE_TARGETINFO="LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo"
+ LLVM_NATIVE_TARGETMC="LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC"
+ LLVM_NATIVE_ASMPRINTER="LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter"
+ if test -f ${srcdir}/lib/Target/${LLVM_NATIVE_ARCH}/AsmParser/Makefile ; then
+ LLVM_NATIVE_ASMPARSER="LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser"
+ fi
+ if test -f ${srcdir}/lib/Target/${LLVM_NATIVE_ARCH}/Disassembler/Makefile ; then
+ LLVM_NATIVE_DISASSEMBLER="LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler"
+ fi
+ AC_DEFINE_UNQUOTED(LLVM_NATIVE_TARGET, $LLVM_NATIVE_TARGET,
+ [LLVM name for the native Target init function, if available])
+ AC_DEFINE_UNQUOTED(LLVM_NATIVE_TARGETINFO, $LLVM_NATIVE_TARGETINFO,
+ [LLVM name for the native TargetInfo init function, if available])
+ AC_DEFINE_UNQUOTED(LLVM_NATIVE_TARGETMC, $LLVM_NATIVE_TARGETMC,
+ [LLVM name for the native target MC init function, if available])
+ AC_DEFINE_UNQUOTED(LLVM_NATIVE_ASMPRINTER, $LLVM_NATIVE_ASMPRINTER,
+ [LLVM name for the native AsmPrinter init function, if available])
+ if test -f ${srcdir}/lib/Target/${LLVM_NATIVE_ARCH}/AsmParser/Makefile ; then
+ AC_DEFINE_UNQUOTED(LLVM_NATIVE_ASMPARSER, $LLVM_NATIVE_ASMPARSER,
+ [LLVM name for the native AsmParser init function, if available])
+ fi
+ if test -f ${srcdir}/lib/Target/${LLVM_NATIVE_ARCH}/Disassembler/Makefile ; then
+ AC_DEFINE_UNQUOTED(LLVM_NATIVE_DISASSEMBLER, $LLVM_NATIVE_DISASSEMBLER,
+ [LLVM name for the native Disassembler init function, if available])
+ fi
+ fi
+done
+
+dnl Build the LLVM_TARGET and LLVM_... macros for Targets.def and the individual
+dnl target feature def files.
+LLVM_ENUM_TARGETS=""
+LLVM_ENUM_ASM_PRINTERS=""
+LLVM_ENUM_ASM_PARSERS=""
+LLVM_ENUM_DISASSEMBLERS=""
+for target_to_build in $TARGETS_TO_BUILD; do
+ LLVM_ENUM_TARGETS="LLVM_TARGET($target_to_build) $LLVM_ENUM_TARGETS"
+ if test -f ${srcdir}/lib/Target/${target_to_build}/*AsmPrinter.cpp ; then
+ LLVM_ENUM_ASM_PRINTERS="LLVM_ASM_PRINTER($target_to_build) $LLVM_ENUM_ASM_PRINTERS";
+ fi
+ if test -f ${srcdir}/lib/Target/${target_to_build}/AsmParser/Makefile ; then
+ LLVM_ENUM_ASM_PARSERS="LLVM_ASM_PARSER($target_to_build) $LLVM_ENUM_ASM_PARSERS";
+ fi
+ if test -f ${srcdir}/lib/Target/${target_to_build}/Disassembler/Makefile ; then
+ LLVM_ENUM_DISASSEMBLERS="LLVM_DISASSEMBLER($target_to_build) $LLVM_ENUM_DISASSEMBLERS";
+ fi
+done
+AC_SUBST(LLVM_ENUM_TARGETS)
+AC_SUBST(LLVM_ENUM_ASM_PRINTERS)
+AC_SUBST(LLVM_ENUM_ASM_PARSERS)
+AC_SUBST(LLVM_ENUM_DISASSEMBLERS)
+
+dnl Override the option to use for optimized builds.
+AC_ARG_WITH(optimize-option,
+ AS_HELP_STRING([--with-optimize-option],
+ [Select the compiler options to use for optimized builds]),,
+ withval=default)
+AC_MSG_CHECKING([optimization flags])
+case "$withval" in
+ default)
+ case "$llvm_cv_os_type" in
+ FreeBSD) optimize_option=-O2 ;;
+ MingW) optimize_option=-O2 ;;
+ *) optimize_option=-O3 ;;
+ esac ;;
+ *) optimize_option="$withval" ;;
+esac
+AC_SUBST(OPTIMIZE_OPTION,$optimize_option)
+AC_MSG_RESULT([$optimize_option])
+
+dnl Specify extra build options
+AC_ARG_WITH(extra-options,
+ AS_HELP_STRING([--with-extra-options],
+ [Specify additional options to compile LLVM with]),,
+ withval=default)
+case "$withval" in
+ default) EXTRA_OPTIONS= ;;
+ *) EXTRA_OPTIONS=$withval ;;
+esac
+AC_SUBST(EXTRA_OPTIONS,$EXTRA_OPTIONS)
+
+dnl Specify extra linker build options
+AC_ARG_WITH(extra-ld-options,
+ AS_HELP_STRING([--with-extra-ld-options],
+ [Specify additional options to link LLVM with]),,
+ withval=default)
+case "$withval" in
+ default) EXTRA_LD_OPTIONS= ;;
+ *) EXTRA_LD_OPTIONS=$withval ;;
+esac
+AC_SUBST(EXTRA_LD_OPTIONS,$EXTRA_LD_OPTIONS)
+
+dnl Allow specific bindings to be specified for building (or not)
+AC_ARG_ENABLE([bindings],AS_HELP_STRING([--enable-bindings],
+ [Build specific language bindings: all,auto,none,{binding-name} (default=auto)]),,
+ enableval=default)
+BINDINGS_TO_BUILD=""
+case "$enableval" in
+ yes | default | auto) BINDINGS_TO_BUILD="auto" ;;
+ all ) BINDINGS_TO_BUILD="ocaml" ;;
+ none | no) BINDINGS_TO_BUILD="" ;;
+ *)for a_binding in `echo $enableval|sed -e 's/,/ /g' ` ; do
+ case "$a_binding" in
+ ocaml) BINDINGS_TO_BUILD="ocaml $BINDINGS_TO_BUILD" ;;
+ *) AC_MSG_ERROR([Unrecognized binding $a_binding]) ;;
+ esac
+ done
+ ;;
+esac
+
+dnl Allow the ocaml libdir to be overridden. This could go in a configure
+dnl script for bindings/ocaml/configure, except that its auto value depends on
+dnl OCAMLC, which is found here to support tests.
+AC_ARG_WITH([ocaml-libdir],
+ [AS_HELP_STRING([--with-ocaml-libdir],
+ [Specify install location for ocaml bindings (default is stdlib)])],
+ [],
+ [withval=auto])
+case "$withval" in
+ auto) with_ocaml_libdir="$withval" ;;
+ /* | [[A-Za-z]]:[[\\/]]*) with_ocaml_libdir="$withval" ;;
+ *) AC_MSG_ERROR([Invalid path for --with-ocaml-libdir. Provide full path]) ;;
+esac
+
+AC_ARG_WITH(clang-srcdir,
+ AS_HELP_STRING([--with-clang-srcdir],
+ [Directory to the out-of-tree Clang source]),,
+ withval="-")
+case "$withval" in
+ -) clang_src_root="" ;;
+ /* | [[A-Za-z]]:[[\\/]]*) clang_src_root="$withval" ;;
+ *) clang_src_root="$ac_pwd/$withval" ;;
+esac
+AC_SUBST(CLANG_SRC_ROOT,[$clang_src_root])
+
+AC_ARG_WITH(clang-resource-dir,
+ AS_HELP_STRING([--with-clang-resource-dir],
+ [Relative directory from the Clang binary for resource files]),,
+ withval="")
+AC_DEFINE_UNQUOTED(CLANG_RESOURCE_DIR,"$withval",
+ [Relative directory for resource files])
+
+AC_ARG_WITH(c-include-dirs,
+ AS_HELP_STRING([--with-c-include-dirs],
+ [Colon separated list of directories clang will search for headers]),,
+ withval="")
+AC_DEFINE_UNQUOTED(C_INCLUDE_DIRS,"$withval",
+ [Directories clang will search for headers])
+
+# Clang normally uses the system c++ headers and libraries. With this option,
+# clang will use the ones provided by a gcc installation instead. This option should
+# be passed the same value that was used with --prefix when configuring gcc.
+AC_ARG_WITH(gcc-toolchain,
+ AS_HELP_STRING([--with-gcc-toolchain],
+ [Directory where gcc is installed.]),,
+ withval="")
+AC_DEFINE_UNQUOTED(GCC_INSTALL_PREFIX,"$withval",
+ [Directory where gcc is installed.])
+
+AC_ARG_WITH(default-sysroot,
+ AS_HELP_STRING([--with-default-sysroot],
+ [Add --sysroot=<path> to all compiler invocations.]),,
+ withval="")
+AC_DEFINE_UNQUOTED(DEFAULT_SYSROOT,"$withval",
+ [Default <path> to all compiler invocations for --sysroot=<path>.])
+
+dnl Allow linking of LLVM with GPLv3 binutils code.
+AC_ARG_WITH(binutils-include,
+ AS_HELP_STRING([--with-binutils-include],
+ [Specify path to binutils/include/ containing plugin-api.h file for gold plugin.]),,
+ withval=default)
+case "$withval" in
+ default) WITH_BINUTILS_INCDIR=default ;;
+ /* | [[A-Za-z]]:[[\\/]]*) WITH_BINUTILS_INCDIR=$withval ;;
+ *) AC_MSG_ERROR([Invalid path for --with-binutils-include. Provide full path]) ;;
+esac
+if test "x$WITH_BINUTILS_INCDIR" != xdefault ; then
+ AC_SUBST(BINUTILS_INCDIR,$WITH_BINUTILS_INCDIR)
+ if test ! -f "$WITH_BINUTILS_INCDIR/plugin-api.h"; then
+ echo "$WITH_BINUTILS_INCDIR/plugin-api.h"
+ AC_MSG_ERROR([Invalid path to directory containing plugin-api.h.]);
+ fi
+fi
+
+dnl Specify the URL where bug reports should be submitted.
+AC_ARG_WITH(bug-report-url,
+ AS_HELP_STRING([--with-bug-report-url],
+ [Specify the URL where bug reports should be submitted (default=http://llvm.org/bugs/)]),,
+ withval="http://llvm.org/bugs/")
+AC_DEFINE_UNQUOTED(BUG_REPORT_URL,"$withval",
+ [Bug report URL.])
+
+dnl --enable-libffi : check whether the user wants to turn off libffi:
+AC_ARG_ENABLE(libffi,AS_HELP_STRING(
+ --enable-libffi,[Check for the presence of libffi (default is NO)]),
+ [case "$enableval" in
+ yes) llvm_cv_enable_libffi="yes" ;;
+ no) llvm_cv_enable_libffi="no" ;;
+ *) AC_MSG_ERROR([Invalid setting for --enable-libffi. Use "yes" or "no"]) ;;
+ esac],
+ llvm_cv_enable_libffi=no)
+
+AC_ARG_WITH(internal-prefix,
+ AS_HELP_STRING([--with-internal-prefix],
+ [Installation directory for internal files]),,
+ withval="")
+AC_SUBST(INTERNAL_PREFIX,[$withval])
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 4: Check for programs we need and that they are the right version
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+AC_PROG_NM
+AC_SUBST(NM)
+
+dnl Check for the tools that the makefiles require
+AC_CHECK_GNU_MAKE
+AC_PROG_LN_S
+AC_PATH_PROG(CMP, [cmp], [cmp])
+AC_PATH_PROG(CP, [cp], [cp])
+AC_PATH_PROG(DATE, [date], [date])
+AC_PATH_PROG(FIND, [find], [find])
+AC_PATH_PROG(GREP, [grep], [grep])
+AC_PATH_PROG(MKDIR,[mkdir],[mkdir])
+AC_PATH_PROG(MV, [mv], [mv])
+AC_PROG_RANLIB
+AC_CHECK_TOOL(AR, ar, false)
+AC_PATH_PROG(RM, [rm], [rm])
+AC_PATH_PROG(SED, [sed], [sed])
+AC_PATH_PROG(TAR, [tar], [gtar])
+AC_PATH_PROG(BINPWD,[pwd], [pwd])
+
+dnl Looking for misc. graph plotting software
+AC_PATH_PROG(GRAPHVIZ, [Graphviz], [echo Graphviz])
+if test "$GRAPHVIZ" != "echo Graphviz" ; then
+ AC_DEFINE([HAVE_GRAPHVIZ],[1],[Define if the Graphviz program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ GRAPHVIZ=`echo $GRAPHVIZ | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_GRAPHVIZ],"$GRAPHVIZ${EXEEXT}",
+ [Define to path to Graphviz program if found or 'echo Graphviz' otherwise])
+fi
+AC_PATH_PROG(DOT, [dot], [echo dot])
+if test "$DOT" != "echo dot" ; then
+ AC_DEFINE([HAVE_DOT],[1],[Define if the dot program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ DOT=`echo $DOT | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_DOT],"$DOT${EXEEXT}",
+ [Define to path to dot program if found or 'echo dot' otherwise])
+fi
+AC_PATH_PROG(FDP, [fdp], [echo fdp])
+if test "$FDP" != "echo fdp" ; then
+ AC_DEFINE([HAVE_FDP],[1],[Define if the neat program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ FDP=`echo $FDP | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_FDP],"$FDP${EXEEXT}",
+ [Define to path to fdp program if found or 'echo fdp' otherwise])
+fi
+AC_PATH_PROG(NEATO, [neato], [echo neato])
+if test "$NEATO" != "echo neato" ; then
+ AC_DEFINE([HAVE_NEATO],[1],[Define if the neat program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ NEATO=`echo $NEATO | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_NEATO],"$NEATO${EXEEXT}",
+ [Define to path to neato program if found or 'echo neato' otherwise])
+fi
+AC_PATH_PROG(TWOPI, [twopi], [echo twopi])
+if test "$TWOPI" != "echo twopi" ; then
+ AC_DEFINE([HAVE_TWOPI],[1],[Define if the neat program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ TWOPI=`echo $TWOPI | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_TWOPI],"$TWOPI${EXEEXT}",
+ [Define to path to twopi program if found or 'echo twopi' otherwise])
+fi
+AC_PATH_PROG(CIRCO, [circo], [echo circo])
+if test "$CIRCO" != "echo circo" ; then
+ AC_DEFINE([HAVE_CIRCO],[1],[Define if the neat program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ CIRCO=`echo $CIRCO | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_CIRCO],"$CIRCO${EXEEXT}",
+ [Define to path to circo program if found or 'echo circo' otherwise])
+fi
+AC_PATH_PROGS(GV, [gv gsview32], [echo gv])
+if test "$GV" != "echo gv" ; then
+ AC_DEFINE([HAVE_GV],[1],[Define if the gv program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ GV=`echo $GV | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_GV],"$GV${EXEEXT}",
+ [Define to path to gv program if found or 'echo gv' otherwise])
+fi
+AC_PATH_PROG(DOTTY, [dotty], [echo dotty])
+if test "$DOTTY" != "echo dotty" ; then
+ AC_DEFINE([HAVE_DOTTY],[1],[Define if the dotty program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ DOTTY=`echo $DOTTY | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_DOTTY],"$DOTTY${EXEEXT}",
+ [Define to path to dotty program if found or 'echo dotty' otherwise])
+fi
+AC_PATH_PROG(XDOT_PY, [xdot.py], [echo xdot.py])
+if test "$XDOT_PY" != "echo xdot.py" ; then
+ AC_DEFINE([HAVE_XDOT_PY],[1],[Define if the xdot.py program is available])
+ dnl If we're targeting for mingw we should emit windows paths, not msys
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ XDOT_PY=`echo $XDOT_PY | sed 's/^\/\([[A-Za-z]]\)\//\1:\//' `
+ fi
+ AC_DEFINE_UNQUOTED([LLVM_PATH_XDOT_PY],"$XDOT_PY${EXEEXT}",
+ [Define to path to xdot.py program if found or 'echo xdot.py' otherwise])
+fi
+
+dnl Find the install program
+AC_PROG_INSTALL
+dnl Prepend src dir to install path dir if it's a relative path
+dnl This is a hack for installs that take place in something other
+dnl than the top level.
+case "$INSTALL" in
+ [[\\/$]]* | ?:[[\\/]]* ) ;;
+ *) INSTALL="\\\$(TOPSRCDIR)/$INSTALL" ;;
+esac
+
+dnl Checks for documentation and testing tools that we can do without. If these
+dnl are not found then they are set to "true" which always succeeds but does
+dnl nothing. This just lets the build output show that we could have done
+dnl something if the tool was available.
+AC_PATH_PROG(BZIP2, [bzip2])
+AC_PATH_PROG(CAT, [cat])
+AC_PATH_PROG(DOXYGEN, [doxygen])
+AC_PATH_PROG(GROFF, [groff])
+AC_PATH_PROG(GZIPBIN, [gzip])
+AC_PATH_PROG(PDFROFF, [pdfroff])
+AC_PATH_PROG(ZIP, [zip])
+AC_PATH_PROGS(OCAMLC, [ocamlc])
+AC_PATH_PROGS(OCAMLOPT, [ocamlopt])
+AC_PATH_PROGS(OCAMLDEP, [ocamldep])
+AC_PATH_PROGS(OCAMLDOC, [ocamldoc])
+AC_PATH_PROGS(GAS, [gas as])
+
+dnl Get the version of the linker in use.
+AC_LINK_GET_VERSION
+
+dnl Determine whether the linker supports the -R option.
+AC_LINK_USE_R
+
+dnl Determine whether the linker supports the -export-dynamic option.
+AC_LINK_EXPORT_DYNAMIC
+
+dnl Determine whether the linker supports the --version-script option.
+AC_LINK_VERSION_SCRIPT
+
+dnl Check for libtool and the library that has dlopen function (which must come
+dnl before the AC_PROG_LIBTOOL check in order to enable dlopening libraries with
+dnl libtool).
+AC_LIBTOOL_DLOPEN
+AC_LIB_LTDL
+
+AC_MSG_CHECKING([tool compatibility])
+
+dnl Ensure that compilation tools are GCC or a GNU compatible compiler such as
+dnl ICC; we use GCC specific options in the makefiles so the compiler needs
+dnl to support those options.
+dnl "icc" emits gcc signatures
+dnl "icc -no-gcc" emits no gcc signature BUT is still compatible
+ICC=no
+IXX=no
+case $CC in
+ icc*|icpc*)
+ ICC=yes
+ IXX=yes
+ ;;
+ *)
+ ;;
+esac
+
+if test "$GCC" != "yes" && test "$ICC" != "yes"
+then
+ AC_MSG_ERROR([gcc|icc required but not found])
+fi
+
+dnl Ensure that compilation tools are compatible with GCC extensions
+if test "$GXX" != "yes" && test "$IXX" != "yes"
+then
+ AC_MSG_ERROR([g++|clang++|icc required but not found])
+fi
+
+dnl Verify that GCC is version 3.0 or higher
+if test "$GCC" = "yes"
+then
+ AC_COMPILE_IFELSE([[#if !defined(__GNUC__) || __GNUC__ < 3
+#error Unsupported GCC version
+#endif
+]], [], [AC_MSG_ERROR([gcc 3.x required, but you have a lower version])])
+fi
+
+dnl Check for GNU Make. We use its extensions, so don't build without it
+if test -z "$llvm_cv_gnu_make_command"
+then
+ AC_MSG_ERROR([GNU Make required but not found])
+fi
+
+dnl Tool compatibility is okay if we make it here.
+AC_MSG_RESULT([ok])
+
+dnl Check optional compiler flags.
+AC_MSG_CHECKING([optional compiler flags])
+CXX_FLAG_CHECK(NO_VARIADIC_MACROS, [-Wno-variadic-macros])
+CXX_FLAG_CHECK(NO_MISSING_FIELD_INITIALIZERS, [-Wno-missing-field-initializers])
+CXX_FLAG_CHECK(COVERED_SWITCH_DEFAULT, [-Wcovered-switch-default])
+AC_MSG_RESULT([$NO_VARIADIC_MACROS $NO_MISSING_FIELD_INITIALIZERS $COVERED_SWITCH_DEFAULT])
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 5: Check for libraries
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+AC_CHECK_LIB(m,sin)
+if test "$llvm_cv_os_type" = "MingW" ; then
+ AC_CHECK_LIB(imagehlp, main)
+ AC_CHECK_LIB(psapi, main)
+fi
+
+dnl dlopen() is required for plugin support.
+AC_SEARCH_LIBS(dlopen,dl,AC_DEFINE([HAVE_DLOPEN],[1],
+ [Define if dlopen() is available on this platform.]),
+ AC_MSG_WARN([dlopen() not found - disabling plugin support]))
+
+dnl libffi is optional; used to call external functions from the interpreter
+if test "$llvm_cv_enable_libffi" = "yes" ; then
+ AC_SEARCH_LIBS(ffi_call,ffi,AC_DEFINE([HAVE_FFI_CALL],[1],
+ [Define if libffi is available on this platform.]),
+ AC_MSG_ERROR([libffi not found - configure without --enable-libffi to compile without it]))
+fi
+
+dnl mallinfo is optional; the code can compile (minus features) without it
+AC_SEARCH_LIBS(mallinfo,malloc,AC_DEFINE([HAVE_MALLINFO],[1],
+ [Define if mallinfo() is available on this platform.]))
+
+dnl pthread locking functions are optional - but llvm will not be thread-safe
+dnl without locks.
+if test "$LLVM_ENABLE_THREADS" -eq 1 && test "$ENABLE_PTHREADS" -eq 1 ; then
+ AC_CHECK_LIB(pthread, pthread_mutex_init)
+ AC_SEARCH_LIBS(pthread_mutex_lock,pthread,
+ AC_DEFINE([HAVE_PTHREAD_MUTEX_LOCK],[1],
+ [Have pthread_mutex_lock]))
+ AC_SEARCH_LIBS(pthread_rwlock_init,pthread,
+ AC_DEFINE([HAVE_PTHREAD_RWLOCK_INIT],[1],
+ [Have pthread_rwlock_init]))
+ AC_SEARCH_LIBS(pthread_getspecific,pthread,
+ AC_DEFINE([HAVE_PTHREAD_GETSPECIFIC],[1],
+ [Have pthread_getspecific]))
+fi
+
+dnl Allow extra x86-disassembler library
+AC_ARG_WITH(udis86,
+ AS_HELP_STRING([--with-udis86=<path>],
+ [Use udis86 external x86 disassembler library]),
+ [
+ AC_SUBST(USE_UDIS86, [1])
+ case "$withval" in
+ /usr/lib|yes) ;;
+ *) LDFLAGS="$LDFLAGS -L${withval}" ;;
+ esac
+ AC_CHECK_LIB(udis86, ud_init, [], [
+ echo "Error! You need to have libudis86 around."
+ exit -1
+ ])
+ ],
+ AC_SUBST(USE_UDIS86, [0]))
+AC_DEFINE_UNQUOTED([USE_UDIS86],$USE_UDIS86,
+ [Define if use udis86 library])
+
+dnl Allow OProfile support for JIT output.
+AC_ARG_WITH(oprofile,
+ AS_HELP_STRING([--with-oprofile=<prefix>],
+ [Tell OProfile >= 0.9.4 how to symbolize JIT output]),
+ [
+ AC_SUBST(USE_OPROFILE, [1])
+ case "$withval" in
+ /usr|yes) llvm_cv_oppath=/usr/lib/oprofile ;;
+ no) llvm_cv_oppath=
+ AC_SUBST(USE_OPROFILE, [0]) ;;
+ *) llvm_cv_oppath="${withval}/lib/oprofile"
+ CPPFLAGS="-I${withval}/include";;
+ esac
+ case $llvm_cv_os_type in
+ Linux)
+ if test -n "$llvm_cv_oppath" ; then
+ LIBS="$LIBS -lopagent -L${llvm_cv_oppath} -Wl,-rpath,${llvm_cv_oppath}"
+ dnl Work around http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=537744:
+ dnl libbfd is not included properly in libopagent in some Debian
+ dnl versions. If libbfd isn't found at all, we assume opagent works
+ dnl anyway.
+ AC_SEARCH_LIBS(bfd_init, bfd, [], [])
+ AC_SEARCH_LIBS(op_open_agent, opagent, [], [
+ echo "Error! You need to have libopagent around."
+ exit -1
+ ])
+ AC_CHECK_HEADER([opagent.h], [], [
+ echo "Error! You need to have opagent.h around."
+ exit -1
+ ])
+ fi ;;
+ *)
+ AC_MSG_ERROR([OProfile support is available on Linux only.]) ;;
+ esac
+ ],
+ [
+ AC_SUBST(USE_OPROFILE, [0])
+ ])
+AC_DEFINE_UNQUOTED([LLVM_USE_OPROFILE],$USE_OPROFILE,
+ [Define if we have the oprofile JIT-support library])
+
+dnl Enable support for Intel JIT Events API.
+AC_ARG_WITH(intel-jitevents,
+ AS_HELP_STRING([--with-intel-jitevents=<vtune-amplifier-dir>],
+ [Specify location of run-time support library for Intel JIT API (default=/opt/intel/vtune_amplifier_xe_2011)]),
+ [
+ case $llvm_cv_os_type in
+ Linux|Win32|Cygwin|MingW) ;;
+ *)
+ AC_MSG_ERROR([
+ Intel JIT API support is available on Linux and Windows only."]) ;;
+ esac
+
+ AC_SUBST(USE_INTEL_JITEVENTS, [1])
+ case "$llvm_cv_target_arch" in
+ x86) llvm_intel_jitevents_archdir="lib32";;
+ x86_64) llvm_intel_jitevents_archdir="lib64";;
+ *) echo "Target architecture $llvm_cv_target_arch does not support Intel JIT Events API"
+ exit -1;;
+ esac
+ INTEL_JITEVENTS_INCDIR="/opt/intel/vtune_amplifier_xe_2011/include"
+ INTEL_JITEVENTS_LIBDIR="/opt/intel/vtune_amplifier_xe_2011/$llvm_intel_jitevents_archdir"
+ case "$withval" in
+ /* | [[A-Za-z]]:[[\\/]]*) INTEL_JITEVENTS_INCDIR=$withval/include
+ INTEL_JITEVENTS_LIBDIR=$withval/$llvm_intel_jitevents_archdir ;;
+ *) ;;
+ esac
+
+ AC_SUBST(INTEL_JITEVENTS_INCDIR)
+ AC_SUBST(INTEL_JITEVENTS_LIBDIR)
+
+ LIBS="$LIBS -L${INTEL_JITEVENTS_LIBDIR}"
+ CPPFLAGS="$CPPFLAGS -I$INTEL_JITEVENTS_INCDIR"
+
+ AC_SEARCH_LIBS(iJIT_IsProfilingActive, jitprofiling, [], [
+ echo "Error! Cannot find libjitprofiling.a. Please check path specified in flag --with-intel-jitevents"
+ exit -1
+ ])
+ AC_CHECK_HEADER([jitprofiling.h], [], [
+ echo "Error! Cannot find jitprofiling.h. Please check path specified in flag --with-intel-jitevents"
+ exit -1
+ ])
+
+ ],
+ [
+ AC_SUBST(USE_INTEL_JITEVENTS, [0])
+ ])
+AC_DEFINE_UNQUOTED([LLVM_USE_INTEL_JITEVENTS],$USE_INTEL_JITEVENTS,
+ [Define if we have the Intel JIT API runtime support library])
+
+dnl Check for libxml2
+dnl Right now we're just checking for the existence, we could also check for a
+dnl particular version via --version on xml2-config
+AC_CHECK_PROGS(XML2CONFIG, xml2-config)
+
+AC_MSG_CHECKING(for libxml2 includes)
+if test "x$XML2CONFIG" = "x"; then
+ AC_MSG_RESULT(xml2-config not found)
+else
+ LIBXML2_INC=`$XML2CONFIG --cflags`
+ AC_MSG_RESULT($LIBXML2_INC)
+ AC_CHECK_LIB(xml2, xmlReadFile,[AC_DEFINE([CLANG_HAVE_LIBXML],1,[Define if we have libxml2])
+ LIBXML2_LIBS="-lxml2"])
+fi
+AC_SUBST(LIBXML2_LIBS)
+AC_SUBST(LIBXML2_INC)
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 6: Check for header files
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+dnl First, use autoconf provided macros for specific headers that we need
+dnl We don't check for ancient stuff or things that are guaranteed to be there
+dnl by the C++ standard. We always use the <cfoo> versions of <foo.h> C headers.
+dnl Generally we're looking for POSIX headers.
+AC_HEADER_DIRENT
+AC_HEADER_MMAP_ANONYMOUS
+AC_HEADER_STAT
+AC_HEADER_SYS_WAIT
+AC_HEADER_TIME
+
+AC_CHECK_HEADERS([dlfcn.h execinfo.h fcntl.h inttypes.h limits.h link.h])
+AC_CHECK_HEADERS([malloc.h setjmp.h signal.h stdint.h termios.h unistd.h])
+AC_CHECK_HEADERS([utime.h windows.h])
+AC_CHECK_HEADERS([sys/mman.h sys/param.h sys/resource.h sys/time.h sys/uio.h])
+AC_CHECK_HEADERS([sys/types.h sys/ioctl.h malloc/malloc.h mach/mach.h])
+AC_CHECK_HEADERS([valgrind/valgrind.h])
+AC_CHECK_HEADERS([fenv.h])
+if test "$LLVM_ENABLE_THREADS" -eq 1 && test "$ENABLE_PTHREADS" -eq 1 ; then
+ AC_CHECK_HEADERS(pthread.h,
+ AC_SUBST(HAVE_PTHREAD, 1),
+ AC_SUBST(HAVE_PTHREAD, 0))
+else
+ AC_SUBST(HAVE_PTHREAD, 0)
+fi
+
+dnl Try to find ffi.h.
+if test "$llvm_cv_enable_libffi" = "yes" ; then
+ AC_CHECK_HEADERS([ffi.h ffi/ffi.h])
+fi
+
+dnl Try to find Darwin specific crash reporting libraries.
+AC_CHECK_HEADERS([CrashReporterClient.h])
+
+dnl Try to find Darwin specific crash reporting global.
+AC_MSG_CHECKING([__crashreporter_info__])
+AC_LINK_IFELSE(
+ AC_LANG_SOURCE(
+ [[extern const char *__crashreporter_info__;
+ int main() {
+ __crashreporter_info__ = "test";
+ return 0;
+ }
+ ]]),
+ AC_MSG_RESULT(yes)
+ AC_DEFINE(HAVE_CRASHREPORTER_INFO, 1, Can use __crashreporter_info__),
+ AC_MSG_RESULT(no)
+ AC_DEFINE(HAVE_CRASHREPORTER_INFO, 0,
+ Define if __crashreporter_info__ exists.))
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 7: Check for types and structures
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+AC_HUGE_VAL_CHECK
+AC_TYPE_PID_T
+AC_TYPE_SIZE_T
+AC_DEFINE_UNQUOTED([RETSIGTYPE],[void],[Define as the return type of signal handlers (`int' or `void').])
+AC_STRUCT_TM
+AC_CHECK_TYPES([int64_t],,AC_MSG_ERROR([Type int64_t required but not found]))
+AC_CHECK_TYPES([uint64_t],,
+ AC_CHECK_TYPES([u_int64_t],,
+ AC_MSG_ERROR([Type uint64_t or u_int64_t required but not found])))
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 8: Check for specific functions needed
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+AC_CHECK_FUNCS([backtrace ceilf floorf roundf rintf nearbyintf getcwd ])
+AC_CHECK_FUNCS([powf fmodf strtof round ])
+AC_CHECK_FUNCS([getpagesize getrusage getrlimit setrlimit gettimeofday ])
+AC_CHECK_FUNCS([isatty mkdtemp mkstemp ])
+AC_CHECK_FUNCS([mktemp posix_spawn pread realpath sbrk setrlimit strdup ])
+AC_CHECK_FUNCS([strerror strerror_r setenv arc4random ])
+AC_CHECK_FUNCS([strtoll strtoq sysconf malloc_zone_statistics ])
+AC_CHECK_FUNCS([setjmp longjmp sigsetjmp siglongjmp writev])
+AC_C_PRINTF_A
+AC_FUNC_RAND48
+
+dnl Check the declaration "Secure API" on Windows environments.
+AC_CHECK_DECLS([strerror_s])
+
+dnl Check symbols in libgcc.a for JIT on Mingw.
+if test "$llvm_cv_os_type" = "MingW" ; then
+ AC_CHECK_LIB(gcc,_alloca,AC_DEFINE([HAVE__ALLOCA],[1],[Have host's _alloca]))
+ AC_CHECK_LIB(gcc,__alloca,AC_DEFINE([HAVE___ALLOCA],[1],[Have host's __alloca]))
+ AC_CHECK_LIB(gcc,__chkstk,AC_DEFINE([HAVE___CHKSTK],[1],[Have host's __chkstk]))
+ AC_CHECK_LIB(gcc,___chkstk,AC_DEFINE([HAVE____CHKSTK],[1],[Have host's ___chkstk]))
+
+ AC_CHECK_LIB(gcc,__ashldi3,AC_DEFINE([HAVE___ASHLDI3],[1],[Have host's __ashldi3]))
+ AC_CHECK_LIB(gcc,__ashrdi3,AC_DEFINE([HAVE___ASHRDI3],[1],[Have host's __ashrdi3]))
+ AC_CHECK_LIB(gcc,__divdi3,AC_DEFINE([HAVE___DIVDI3],[1],[Have host's __divdi3]))
+ AC_CHECK_LIB(gcc,__fixdfdi,AC_DEFINE([HAVE___FIXDFDI],[1],[Have host's __fixdfdi]))
+ AC_CHECK_LIB(gcc,__fixsfdi,AC_DEFINE([HAVE___FIXSFDI],[1],[Have host's __fixsfdi]))
+ AC_CHECK_LIB(gcc,__floatdidf,AC_DEFINE([HAVE___FLOATDIDF],[1],[Have host's __floatdidf]))
+ AC_CHECK_LIB(gcc,__lshrdi3,AC_DEFINE([HAVE___LSHRDI3],[1],[Have host's __lshrdi3]))
+ AC_CHECK_LIB(gcc,__moddi3,AC_DEFINE([HAVE___MODDI3],[1],[Have host's __moddi3]))
+ AC_CHECK_LIB(gcc,__udivdi3,AC_DEFINE([HAVE___UDIVDI3],[1],[Have host's __udivdi3]))
+ AC_CHECK_LIB(gcc,__umoddi3,AC_DEFINE([HAVE___UMODDI3],[1],[Have host's __umoddi3]))
+
+ AC_CHECK_LIB(gcc,__main,AC_DEFINE([HAVE___MAIN],[1],[Have host's __main]))
+ AC_CHECK_LIB(gcc,__cmpdi2,AC_DEFINE([HAVE___CMPDI2],[1],[Have host's __cmpdi2]))
+fi
+
+dnl Check Win32 API EnumerateLoadedModules.
+if test "$llvm_cv_os_type" = "MingW" ; then
+ AC_MSG_CHECKING([whether EnumerateLoadedModules() accepts new decl])
+ AC_COMPILE_IFELSE([[#include <windows.h>
+#include <imagehlp.h>
+extern void foo(PENUMLOADED_MODULES_CALLBACK);
+extern void foo(BOOL(CALLBACK*)(PCSTR,ULONG_PTR,ULONG,PVOID));]],
+[
+ AC_MSG_RESULT([yes])
+ llvm_cv_win32_elmcb_pcstr="PCSTR"
+],
+[
+ AC_MSG_RESULT([no])
+ llvm_cv_win32_elmcb_pcstr="PSTR"
+])
+ AC_DEFINE_UNQUOTED([WIN32_ELMCB_PCSTR],$llvm_cv_win32_elmcb_pcstr,[Type of 1st arg on ELM Callback])
+fi
+
+dnl Check for variations in the Standard C++ library and STL. These macros are
+dnl provided by LLVM in the autoconf/m4 directory.
+AC_FUNC_ISNAN
+AC_FUNC_ISINF
+
+dnl Check for mmap support.We also need to know if /dev/zero is required to
+dnl be opened for allocating RWX memory.
+dnl Make sure we aren't attempting to configure for an unknown system
+if test "$llvm_cv_platform_type" = "Unix" ; then
+ AC_FUNC_MMAP
+ AC_FUNC_MMAP_FILE
+ AC_NEED_DEV_ZERO_FOR_MMAP
+
+ if test "$ac_cv_func_mmap_fixed_mapped" = "no"
+ then
+ AC_MSG_WARN([mmap() of a fixed address required but not supported])
+ fi
+ if test "$ac_cv_func_mmap_file" = "no"
+ then
+ AC_MSG_WARN([mmap() of files required but not found])
+ fi
+fi
+
+dnl atomic builtins are required for threading support.
+AC_MSG_CHECKING(for GCC atomic builtins)
+dnl Since we'll be using these atomic builtins in C++ files we should test
+dnl the C++ compiler.
+AC_LANG_PUSH([C++])
+AC_LINK_IFELSE(
+ AC_LANG_SOURCE(
+ [[int main() {
+ volatile unsigned long val = 1;
+ __sync_synchronize();
+ __sync_val_compare_and_swap(&val, 1, 0);
+ __sync_add_and_fetch(&val, 1);
+ __sync_sub_and_fetch(&val, 1);
+ return 0;
+ }
+ ]]),
+ AC_LANG_POP([C++])
+ AC_MSG_RESULT(yes)
+ AC_DEFINE(LLVM_HAS_ATOMICS, 1, Has gcc/MSVC atomic intrinsics),
+ AC_MSG_RESULT(no)
+ AC_DEFINE(LLVM_HAS_ATOMICS, 0, Has gcc/MSVC atomic intrinsics)
+ AC_MSG_WARN([LLVM will be built thread-unsafe because atomic builtins are missing]))
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 9: Additional checks, variables, etc.
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+dnl Handle 32-bit linux systems running a 64-bit kernel.
+dnl This has to come after section 4 because it invokes the compiler.
+if test "$llvm_cv_os_type" = "Linux" -a "$llvm_cv_target_arch" = "x86_64" ; then
+ AC_IS_LINUX_MIXED
+ if test "$llvm_cv_linux_mixed" = "yes"; then
+ llvm_cv_target_arch="x86"
+ ARCH="x86"
+ fi
+fi
+
+dnl Check whether __dso_handle is present
+AC_CHECK_FUNCS([__dso_handle])
+
+dnl Propagate the shared library extension that the libltdl checks did to
+dnl the Makefiles so we can use it there too
+AC_SUBST(SHLIBEXT,$libltdl_cv_shlibext)
+
+dnl Propagate the run-time library path variable that the libltdl
+dnl checks found to the Makefiles so we can use it there too
+AC_SUBST(SHLIBPATH_VAR,$libltdl_cv_shlibpath_var)
+
+dnl Translate the various configuration directories and other basic
+dnl information into substitutions that will end up in Makefile.config.in
+dnl that these configured values can be used by the makefiles
+if test "${prefix}" = "NONE" ; then
+ prefix="/usr/local"
+fi
+eval LLVM_PREFIX="${prefix}";
+eval LLVM_BINDIR="${prefix}/bin";
+eval LLVM_LIBDIR="${prefix}/lib";
+eval LLVM_DATADIR="${prefix}/share/llvm";
+eval LLVM_DOCSDIR="${prefix}/share/doc/llvm";
+eval LLVM_ETCDIR="${prefix}/etc/llvm";
+eval LLVM_INCLUDEDIR="${prefix}/include";
+eval LLVM_INFODIR="${prefix}/info";
+eval LLVM_MANDIR="${prefix}/man";
+LLVM_CONFIGTIME=`date`
+AC_SUBST(LLVM_PREFIX)
+AC_SUBST(LLVM_BINDIR)
+AC_SUBST(LLVM_LIBDIR)
+AC_SUBST(LLVM_DATADIR)
+AC_SUBST(LLVM_DOCSDIR)
+AC_SUBST(LLVM_ETCDIR)
+AC_SUBST(LLVM_INCLUDEDIR)
+AC_SUBST(LLVM_INFODIR)
+AC_SUBST(LLVM_MANDIR)
+AC_SUBST(LLVM_CONFIGTIME)
+
+dnl Disable embedding timestamps in the build directory, with ENABLE_TIMESTAMPS.
+if test "${ENABLE_TIMESTAMPS}" = "0"; then
+ LLVM_CONFIGTIME="(timestamp not enabled)"
+fi
+
+dnl Place the various directories into the config.h file as #defines so that we
+dnl can know about the installation paths within LLVM.
+AC_DEFINE_UNQUOTED(LLVM_PREFIX,"$LLVM_PREFIX",
+ [Installation prefix directory])
+AC_DEFINE_UNQUOTED(LLVM_BINDIR, "$LLVM_BINDIR",
+ [Installation directory for binary executables])
+AC_DEFINE_UNQUOTED(LLVM_LIBDIR, "$LLVM_LIBDIR",
+ [Installation directory for libraries])
+AC_DEFINE_UNQUOTED(LLVM_DATADIR, "$LLVM_DATADIR",
+ [Installation directory for data files])
+AC_DEFINE_UNQUOTED(LLVM_DOCSDIR, "$LLVM_DOCSDIR",
+ [Installation directory for documentation])
+AC_DEFINE_UNQUOTED(LLVM_ETCDIR, "$LLVM_ETCDIR",
+ [Installation directory for config files])
+AC_DEFINE_UNQUOTED(LLVM_INCLUDEDIR, "$LLVM_INCLUDEDIR",
+ [Installation directory for include files])
+AC_DEFINE_UNQUOTED(LLVM_INFODIR, "$LLVM_INFODIR",
+ [Installation directory for .info files])
+AC_DEFINE_UNQUOTED(LLVM_MANDIR, "$LLVM_MANDIR",
+ [Installation directory for man pages])
+AC_DEFINE_UNQUOTED(LLVM_CONFIGTIME, "$LLVM_CONFIGTIME",
+ [Time at which LLVM was configured])
+AC_DEFINE_UNQUOTED(LLVM_HOSTTRIPLE, "$host",
+ [Host triple LLVM will be executed on])
+AC_DEFINE_UNQUOTED(LLVM_DEFAULT_TARGET_TRIPLE, "$target",
+ [Target triple LLVM will generate code for by default])
+
+dnl Determine which bindings to build.
+if test "$BINDINGS_TO_BUILD" = auto ; then
+ BINDINGS_TO_BUILD=""
+ if test "x$OCAMLC" != x -a "x$OCAMLDEP" != x ; then
+ BINDINGS_TO_BUILD="ocaml $BINDINGS_TO_BUILD"
+ fi
+fi
+AC_SUBST(BINDINGS_TO_BUILD,$BINDINGS_TO_BUILD)
+
+dnl This isn't really configurey, but it avoids having to repeat the list in
+dnl other files.
+AC_SUBST(ALL_BINDINGS,ocaml)
+
+dnl Do any work necessary to ensure that bindings have what they need.
+binding_prereqs_failed=0
+for a_binding in $BINDINGS_TO_BUILD ; do
+ case "$a_binding" in
+ ocaml)
+ if test "x$OCAMLC" = x ; then
+ AC_MSG_WARN([--enable-bindings=ocaml specified, but ocamlc not found. Try configure OCAMLC=/path/to/ocamlc])
+ binding_prereqs_failed=1
+ fi
+ if test "x$OCAMLDEP" = x ; then
+ AC_MSG_WARN([--enable-bindings=ocaml specified, but ocamldep not found. Try configure OCAMLDEP=/path/to/ocamldep])
+ binding_prereqs_failed=1
+ fi
+ if test "x$OCAMLOPT" = x ; then
+ AC_MSG_WARN([--enable-bindings=ocaml specified, but ocamlopt not found. Try configure OCAMLOPT=/path/to/ocamlopt])
+ dnl ocamlopt is optional!
+ fi
+ if test "x$with_ocaml_libdir" != xauto ; then
+ AC_SUBST(OCAML_LIBDIR,$with_ocaml_libdir)
+ else
+ ocaml_stdlib="`"$OCAMLC" -where`"
+ if test "$LLVM_PREFIX" '<' "$ocaml_stdlib" -a "$ocaml_stdlib" '<' "$LLVM_PREFIX~"
+ then
+ # ocaml stdlib is beneath our prefix; use stdlib
+ AC_SUBST(OCAML_LIBDIR,$ocaml_stdlib)
+ else
+ # ocaml stdlib is outside our prefix; use libdir/ocaml
+ AC_SUBST(OCAML_LIBDIR,$LLVM_LIBDIR/ocaml)
+ fi
+ fi
+ ;;
+ esac
+done
+if test "$binding_prereqs_failed" = 1 ; then
+ AC_MSG_ERROR([Prequisites for bindings not satisfied. Fix them or use configure --disable-bindings.])
+fi
+
+dnl Determine whether the compiler supports -fvisibility-inlines-hidden.
+AC_CXX_USE_VISIBILITY_INLINES_HIDDEN
+
+dnl Determine linker rpath flag
+if test "$llvm_cv_link_use_r" = "yes" ; then
+ RPATH="-Wl,-R"
+else
+ RPATH="-Wl,-rpath"
+fi
+AC_SUBST(RPATH)
+
+dnl Determine linker rdynamic flag
+if test "$llvm_cv_link_use_export_dynamic" = "yes" ; then
+ RDYNAMIC="-Wl,-export-dynamic"
+else
+ RDYNAMIC=""
+fi
+AC_SUBST(RDYNAMIC)
+
+dnl===-----------------------------------------------------------------------===
+dnl===
+dnl=== SECTION 10: Specify the output files and generate it
+dnl===
+dnl===-----------------------------------------------------------------------===
+
+dnl Configure header files
+dnl WARNING: dnl If you add or remove any of the following config headers, then
+dnl you MUST also update Makefile so that the variable FilesToConfig
+dnl contains the same list of files as AC_CONFIG_HEADERS below. This ensures the
+dnl files can be updated automatically when their *.in sources change.
+AC_CONFIG_HEADERS([include/llvm/Config/config.h include/llvm/Config/llvm-config.h])
+AH_TOP([#ifndef CONFIG_H
+#define CONFIG_H])
+AH_BOTTOM([#endif])
+
+AC_CONFIG_FILES([include/llvm/Config/Targets.def])
+AC_CONFIG_FILES([include/llvm/Config/AsmPrinters.def])
+AC_CONFIG_FILES([include/llvm/Config/AsmParsers.def])
+AC_CONFIG_FILES([include/llvm/Config/Disassemblers.def])
+AC_CONFIG_HEADERS([include/llvm/Support/DataTypes.h])
+
+dnl Configure the makefile's configuration data
+AC_CONFIG_FILES([Makefile.config])
+
+dnl Configure the RPM spec file for LLVM
+AC_CONFIG_FILES([llvm.spec])
+
+dnl Configure doxygen's configuration file
+AC_CONFIG_FILES([docs/doxygen.cfg])
+
+dnl Configure clang, if present
+if test "${clang_src_root}" = ""; then
+ clang_src_root="$srcdir/tools/clang"
+fi
+if test -f ${clang_src_root}/README.txt; then
+ dnl Use variables to stay under 80 columns.
+ configh="include/clang/Config/config.h"
+ doxy="docs/doxygen.cfg"
+ AC_CONFIG_HEADERS([tools/clang/${configh}:${clang_src_root}/${configh}.in])
+ AC_CONFIG_FILES([tools/clang/${doxy}:${clang_src_root}/${doxy}.in])
+fi
+
+dnl OCaml findlib META file
+AC_CONFIG_FILES([bindings/ocaml/llvm/META.llvm])
+
+dnl Do special configuration of Makefiles
+AC_CONFIG_COMMANDS([setup],,[llvm_src="${srcdir}"])
+AC_CONFIG_MAKEFILE(Makefile)
+AC_CONFIG_MAKEFILE(Makefile.common)
+AC_CONFIG_MAKEFILE(examples/Makefile)
+AC_CONFIG_MAKEFILE(lib/Makefile)
+AC_CONFIG_MAKEFILE(runtime/Makefile)
+AC_CONFIG_MAKEFILE(test/Makefile)
+AC_CONFIG_MAKEFILE(test/Makefile.tests)
+AC_CONFIG_MAKEFILE(unittests/Makefile)
+AC_CONFIG_MAKEFILE(tools/Makefile)
+AC_CONFIG_MAKEFILE(utils/Makefile)
+AC_CONFIG_MAKEFILE(projects/Makefile)
+AC_CONFIG_MAKEFILE(bindings/Makefile)
+AC_CONFIG_MAKEFILE(bindings/ocaml/Makefile.ocaml)
+
+dnl Finally, crank out the output
+AC_OUTPUT
diff --git a/autoconf/depcomp b/autoconf/depcomp
new file mode 100755
index 00000000000..11e2d3bfe1c
--- /dev/null
+++ b/autoconf/depcomp
@@ -0,0 +1,522 @@
+#! /bin/sh
+# depcomp - compile a program generating dependencies as side-effects
+
+scriptversion=2004-05-31.23
+
+# Copyright (C) 1999, 2000, 2003, 2004 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+# 02111-1307, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
+
+case $1 in
+ '')
+ echo "$0: No command. Try \`$0 --help' for more information." 1>&2
+ exit 1;
+ ;;
+ -h | --h*)
+ cat <<\EOF
+Usage: depcomp [--help] [--version] PROGRAM [ARGS]
+
+Run PROGRAMS ARGS to compile a file, generating dependencies
+as side-effects.
+
+Environment variables:
+ depmode Dependency tracking mode.
+ source Source file read by `PROGRAMS ARGS'.
+ object Object file output by `PROGRAMS ARGS'.
+ DEPDIR directory where to store dependencies.
+ depfile Dependency file to output.
+ tmpdepfile Temporary file to use when outputing dependencies.
+ libtool Whether libtool is used (yes/no).
+
+Report bugs to <bug-automake@gnu.org>.
+EOF
+ exit 0
+ ;;
+ -v | --v*)
+ echo "depcomp $scriptversion"
+ exit 0
+ ;;
+esac
+
+if test -z "$depmode" || test -z "$source" || test -z "$object"; then
+ echo "depcomp: Variables source, object and depmode must be set" 1>&2
+ exit 1
+fi
+
+# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
+depfile=${depfile-`echo "$object" |
+ sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
+tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
+
+rm -f "$tmpdepfile"
+
+# Some modes work just like other modes, but use different flags. We
+# parameterize here, but still list the modes in the big case below,
+# to make depend.m4 easier to write. Note that we *cannot* use a case
+# here, because this file can only contain one case statement.
+if test "$depmode" = hp; then
+ # HP compiler uses -M and no extra arg.
+ gccflag=-M
+ depmode=gcc
+fi
+
+if test "$depmode" = dashXmstdout; then
+ # This is just like dashmstdout with a different argument.
+ dashmflag=-xM
+ depmode=dashmstdout
+fi
+
+case "$depmode" in
+gcc3)
+## gcc 3 implements dependency tracking that does exactly what
+## we want. Yay! Note: for some reason libtool 1.4 doesn't like
+## it if -MD -MP comes after the -MF stuff. Hmm.
+ "$@" -MT "$object" -MD -MP -MF "$tmpdepfile"
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+ mv "$tmpdepfile" "$depfile"
+ ;;
+
+gcc)
+## There are various ways to get dependency output from gcc. Here's
+## why we pick this rather obscure method:
+## - Don't want to use -MD because we'd like the dependencies to end
+## up in a subdir. Having to rename by hand is ugly.
+## (We might end up doing this anyway to support other compilers.)
+## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
+## -MM, not -M (despite what the docs say).
+## - Using -M directly means running the compiler twice (even worse
+## than renaming).
+ if test -z "$gccflag"; then
+ gccflag=-MD,
+ fi
+ "$@" -Wp,"$gccflag$tmpdepfile"
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+ rm -f "$depfile"
+ echo "$object : \\" > "$depfile"
+ alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
+## The second -e expression handles DOS-style file names with drive letters.
+ sed -e 's/^[^:]*: / /' \
+ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
+## This next piece of magic avoids the `deleted header file' problem.
+## The problem is that when a header file which appears in a .P file
+## is deleted, the dependency causes make to die (because there is
+## typically no way to rebuild the header). We avoid this by adding
+## dummy dependencies for each header file. Too bad gcc doesn't do
+## this for us directly.
+ tr ' ' '
+' < "$tmpdepfile" |
+## Some versions of gcc put a space before the `:'. On the theory
+## that the space means something, we add a space to the output as
+## well.
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly. Breaking it into two sed invocations is a workaround.
+ sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+hp)
+ # This case exists only to let depend.m4 do its work. It works by
+ # looking at the text of this script. This case will never be run,
+ # since it is checked for above.
+ exit 1
+ ;;
+
+sgi)
+ if test "$libtool" = yes; then
+ "$@" "-Wp,-MDupdate,$tmpdepfile"
+ else
+ "$@" -MDupdate "$tmpdepfile"
+ fi
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+ rm -f "$depfile"
+
+ if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
+ echo "$object : \\" > "$depfile"
+
+ # Clip off the initial element (the dependent). Don't try to be
+ # clever and replace this with sed code, as IRIX sed won't handle
+ # lines with more than a fixed number of characters (4096 in
+ # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
+ # the IRIX cc adds comments like `#:fec' to the end of the
+ # dependency line.
+ tr ' ' '
+' < "$tmpdepfile" \
+ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
+ tr '
+' ' ' >> $depfile
+ echo >> $depfile
+
+ # The second pass generates a dummy entry for each header file.
+ tr ' ' '
+' < "$tmpdepfile" \
+ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
+ >> $depfile
+ else
+ # The sourcefile does not contain any dependencies, so just
+ # store a dummy comment line, to avoid errors with the Makefile
+ # "include basename.Plo" scheme.
+ echo "#dummy" > "$depfile"
+ fi
+ rm -f "$tmpdepfile"
+ ;;
+
+aix)
+ # The C for AIX Compiler uses -M and outputs the dependencies
+ # in a .u file. In older versions, this file always lives in the
+ # current directory. Also, the AIX compiler puts `$object:' at the
+ # start of each line; $object doesn't have directory information.
+ # Version 6 uses the directory in both cases.
+ stripped=`echo "$object" | sed 's/\(.*\)\..*$/\1/'`
+ tmpdepfile="$stripped.u"
+ if test "$libtool" = yes; then
+ "$@" -Wc,-M
+ else
+ "$@" -M
+ fi
+ stat=$?
+
+ if test -f "$tmpdepfile"; then :
+ else
+ stripped=`echo "$stripped" | sed 's,^.*/,,'`
+ tmpdepfile="$stripped.u"
+ fi
+
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+
+ if test -f "$tmpdepfile"; then
+ outname="$stripped.o"
+ # Each line is of the form `foo.o: dependent.h'.
+ # Do two passes, one to just change these to
+ # `$object: dependent.h' and one to simply `dependent.h:'.
+ sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile"
+ sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile"
+ else
+ # The sourcefile does not contain any dependencies, so just
+ # store a dummy comment line, to avoid errors with the Makefile
+ # "include basename.Plo" scheme.
+ echo "#dummy" > "$depfile"
+ fi
+ rm -f "$tmpdepfile"
+ ;;
+
+icc)
+ # Intel's C compiler understands `-MD -MF file'. However on
+ # icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c
+ # ICC 7.0 will fill foo.d with something like
+ # foo.o: sub/foo.c
+ # foo.o: sub/foo.h
+ # which is wrong. We want:
+ # sub/foo.o: sub/foo.c
+ # sub/foo.o: sub/foo.h
+ # sub/foo.c:
+ # sub/foo.h:
+ # ICC 7.1 will output
+ # foo.o: sub/foo.c sub/foo.h
+ # and will wrap long lines using \ :
+ # foo.o: sub/foo.c ... \
+ # sub/foo.h ... \
+ # ...
+
+ "$@" -MD -MF "$tmpdepfile"
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+ rm -f "$depfile"
+ # Each line is of the form `foo.o: dependent.h',
+ # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
+ # Do two passes, one to just change these to
+ # `$object: dependent.h' and one to simply `dependent.h:'.
+ sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
+ # Some versions of the HPUX 10.20 sed can't process this invocation
+ # correctly. Breaking it into two sed invocations is a workaround.
+ sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" |
+ sed -e 's/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+tru64)
+ # The Tru64 compiler uses -MD to generate dependencies as a side
+ # effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
+ # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
+ # dependencies in `foo.d' instead, so we check for that too.
+ # Subdirectories are respected.
+ dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
+ test "x$dir" = "x$object" && dir=
+ base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
+
+ if test "$libtool" = yes; then
+ # Dependencies are output in .lo.d with libtool 1.4.
+ # With libtool 1.5 they are output both in $dir.libs/$base.o.d
+ # and in $dir.libs/$base.o.d and $dir$base.o.d. We process the
+ # latter, because the former will be cleaned when $dir.libs is
+ # erased.
+ tmpdepfile1="$dir.libs/$base.lo.d"
+ tmpdepfile2="$dir$base.o.d"
+ tmpdepfile3="$dir.libs/$base.d"
+ "$@" -Wc,-MD
+ else
+ tmpdepfile1="$dir$base.o.d"
+ tmpdepfile2="$dir$base.d"
+ tmpdepfile3="$dir$base.d"
+ "$@" -MD
+ fi
+
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
+ exit $stat
+ fi
+
+ if test -f "$tmpdepfile1"; then
+ tmpdepfile="$tmpdepfile1"
+ elif test -f "$tmpdepfile2"; then
+ tmpdepfile="$tmpdepfile2"
+ else
+ tmpdepfile="$tmpdepfile3"
+ fi
+ if test -f "$tmpdepfile"; then
+ sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
+ # That's a tab and a space in the [].
+ sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
+ else
+ echo "#dummy" > "$depfile"
+ fi
+ rm -f "$tmpdepfile"
+ ;;
+
+#nosideeffect)
+ # This comment above is used by automake to tell side-effect
+ # dependency tracking mechanisms from slower ones.
+
+dashmstdout)
+ # Important note: in order to support this mode, a compiler *must*
+ # always write the preprocessed file to stdout, regardless of -o.
+ "$@" || exit $?
+
+ # Remove the call to Libtool.
+ if test "$libtool" = yes; then
+ while test $1 != '--mode=compile'; do
+ shift
+ done
+ shift
+ fi
+
+ # Remove `-o $object'.
+ IFS=" "
+ for arg
+ do
+ case $arg in
+ -o)
+ shift
+ ;;
+ $object)
+ shift
+ ;;
+ *)
+ set fnord "$@" "$arg"
+ shift # fnord
+ shift # $arg
+ ;;
+ esac
+ done
+
+ test -z "$dashmflag" && dashmflag=-M
+ # Require at least two characters before searching for `:'
+ # in the target name. This is to cope with DOS-style filenames:
+ # a dependency such as `c:/foo/bar' could be seen as target `c' otherwise.
+ "$@" $dashmflag |
+ sed 's:^[ ]*[^: ][^:][^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile"
+ rm -f "$depfile"
+ cat < "$tmpdepfile" > "$depfile"
+ tr ' ' '
+' < "$tmpdepfile" | \
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly. Breaking it into two sed invocations is a workaround.
+ sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+dashXmstdout)
+ # This case only exists to satisfy depend.m4. It is never actually
+ # run, as this mode is specially recognized in the preamble.
+ exit 1
+ ;;
+
+makedepend)
+ "$@" || exit $?
+ # Remove any Libtool call
+ if test "$libtool" = yes; then
+ while test $1 != '--mode=compile'; do
+ shift
+ done
+ shift
+ fi
+ # X makedepend
+ shift
+ cleared=no
+ for arg in "$@"; do
+ case $cleared in
+ no)
+ set ""; shift
+ cleared=yes ;;
+ esac
+ case "$arg" in
+ -D*|-I*)
+ set fnord "$@" "$arg"; shift ;;
+ # Strip any option that makedepend may not understand. Remove
+ # the object too, otherwise makedepend will parse it as a source file.
+ -*|$object)
+ ;;
+ *)
+ set fnord "$@" "$arg"; shift ;;
+ esac
+ done
+ obj_suffix="`echo $object | sed 's/^.*\././'`"
+ touch "$tmpdepfile"
+ ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
+ rm -f "$depfile"
+ cat < "$tmpdepfile" > "$depfile"
+ sed '1,2d' "$tmpdepfile" | tr ' ' '
+' | \
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly. Breaking it into two sed invocations is a workaround.
+ sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile" "$tmpdepfile".bak
+ ;;
+
+cpp)
+ # Important note: in order to support this mode, a compiler *must*
+ # always write the preprocessed file to stdout.
+ "$@" || exit $?
+
+ # Remove the call to Libtool.
+ if test "$libtool" = yes; then
+ while test $1 != '--mode=compile'; do
+ shift
+ done
+ shift
+ fi
+
+ # Remove `-o $object'.
+ IFS=" "
+ for arg
+ do
+ case $arg in
+ -o)
+ shift
+ ;;
+ $object)
+ shift
+ ;;
+ *)
+ set fnord "$@" "$arg"
+ shift # fnord
+ shift # $arg
+ ;;
+ esac
+ done
+
+ "$@" -E |
+ sed -n '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
+ sed '$ s: \\$::' > "$tmpdepfile"
+ rm -f "$depfile"
+ echo "$object : \\" > "$depfile"
+ cat < "$tmpdepfile" >> "$depfile"
+ sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+msvisualcpp)
+ # Important note: in order to support this mode, a compiler *must*
+ # always write the preprocessed file to stdout, regardless of -o,
+ # because we must use -o when running libtool.
+ "$@" || exit $?
+ IFS=" "
+ for arg
+ do
+ case "$arg" in
+ "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
+ set fnord "$@"
+ shift
+ shift
+ ;;
+ *)
+ set fnord "$@" "$arg"
+ shift
+ shift
+ ;;
+ esac
+ done
+ "$@" -E |
+ sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile"
+ rm -f "$depfile"
+ echo "$object : \\" > "$depfile"
+ . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile"
+ echo " " >> "$depfile"
+ . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+none)
+ exec "$@"
+ ;;
+
+*)
+ echo "Unknown depmode $depmode" 1>&2
+ exit 1
+ ;;
+esac
+
+exit 0
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
diff --git a/autoconf/install-sh b/autoconf/install-sh
new file mode 100755
index 00000000000..dd97db7aa1c
--- /dev/null
+++ b/autoconf/install-sh
@@ -0,0 +1,322 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2004-09-10.20
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# `make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch. It can only install one file at a time, a restriction
+# shared with many OS's install programs.
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit="${DOITPROG-}"
+
+# put in absolute paths if you don't have them in your path; or use env. vars.
+
+mvprog="${MVPROG-mv}"
+cpprog="${CPPROG-cp}"
+chmodprog="${CHMODPROG-chmod}"
+chownprog="${CHOWNPROG-chown}"
+chgrpprog="${CHGRPPROG-chgrp}"
+stripprog="${STRIPPROG-strip}"
+rmprog="${RMPROG-rm}"
+mkdirprog="${MKDIRPROG-mkdir}"
+
+chmodcmd="$chmodprog 0755"
+chowncmd=
+chgrpcmd=
+stripcmd=
+rmcmd="$rmprog -f"
+mvcmd="$mvprog"
+src=
+dst=
+dir_arg=
+dstarg=
+no_target_directory=
+
+usage="Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+ or: $0 [OPTION]... SRCFILES... DIRECTORY
+ or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+ or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+-c (ignored)
+-d create directories instead of installing files.
+-g GROUP $chgrpprog installed files to GROUP.
+-m MODE $chmodprog installed files to MODE.
+-o USER $chownprog installed files to USER.
+-s $stripprog installed files.
+-t DIRECTORY install into DIRECTORY.
+-T report an error if DSTFILE is a directory.
+--help display this help and exit.
+--version display version info and exit.
+
+Environment variables override the default commands:
+ CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG
+"
+
+while test -n "$1"; do
+ case $1 in
+ -c) shift
+ continue;;
+
+ -d) dir_arg=true
+ shift
+ continue;;
+
+ -g) chgrpcmd="$chgrpprog $2"
+ shift
+ shift
+ continue;;
+
+ --help) echo "$usage"; exit 0;;
+
+ -m) chmodcmd="$chmodprog $2"
+ shift
+ shift
+ continue;;
+
+ -o) chowncmd="$chownprog $2"
+ shift
+ shift
+ continue;;
+
+ -s) stripcmd=$stripprog
+ shift
+ continue;;
+
+ -t) dstarg=$2
+ shift
+ shift
+ continue;;
+
+ -T) no_target_directory=true
+ shift
+ continue;;
+
+ --version) echo "$0 $scriptversion"; exit 0;;
+
+ *) # When -d is used, all remaining arguments are directories to create.
+ # When -t is used, the destination is already specified.
+ test -n "$dir_arg$dstarg" && break
+ # Otherwise, the last argument is the destination. Remove it from $@.
+ for arg
+ do
+ if test -n "$dstarg"; then
+ # $@ is not empty: it contains at least $arg.
+ set fnord "$@" "$dstarg"
+ shift # fnord
+ fi
+ shift # arg
+ dstarg=$arg
+ done
+ break;;
+ esac
+done
+
+if test -z "$1"; then
+ if test -z "$dir_arg"; then
+ echo "$0: no input file specified." >&2
+ exit 1
+ fi
+ # It's OK to call `install-sh -d' without argument.
+ # This can happen when creating conditional directories.
+ exit 0
+fi
+
+for src
+do
+ # Protect names starting with `-'.
+ case $src in
+ -*) src=./$src ;;
+ esac
+
+ if test -n "$dir_arg"; then
+ dst=$src
+ src=
+
+ if test -d "$dst"; then
+ mkdircmd=:
+ chmodcmd=
+ else
+ mkdircmd=$mkdirprog
+ fi
+ else
+ # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+ # might cause directories to be created, which would be especially bad
+ # if $src (and thus $dsttmp) contains '*'.
+ if test ! -f "$src" && test ! -d "$src"; then
+ echo "$0: $src does not exist." >&2
+ exit 1
+ fi
+
+ if test -z "$dstarg"; then
+ echo "$0: no destination specified." >&2
+ exit 1
+ fi
+
+ dst=$dstarg
+ # Protect names starting with `-'.
+ case $dst in
+ -*) dst=./$dst ;;
+ esac
+
+ # If destination is a directory, append the input filename; won't work
+ # if double slashes aren't ignored.
+ if test -d "$dst"; then
+ if test -n "$no_target_directory"; then
+ echo "$0: $dstarg: Is a directory" >&2
+ exit 1
+ fi
+ dst=$dst/`basename "$src"`
+ fi
+ fi
+
+ # This sed command emulates the dirname command.
+ dstdir=`echo "$dst" | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
+
+ # Make sure that the destination directory exists.
+
+ # Skip lots of stat calls in the usual case.
+ if test ! -d "$dstdir"; then
+ defaultIFS='
+ '
+ IFS="${IFS-$defaultIFS}"
+
+ oIFS=$IFS
+ # Some sh's can't handle IFS=/ for some reason.
+ IFS='%'
+ set - `echo "$dstdir" | sed -e 's@/@%@g' -e 's@^%@/@'`
+ IFS=$oIFS
+
+ pathcomp=
+
+ while test $# -ne 0 ; do
+ pathcomp=$pathcomp$1
+ shift
+ if test ! -d "$pathcomp"; then
+ $mkdirprog "$pathcomp"
+ # mkdir can fail with a `File exist' error in case several
+ # install-sh are creating the directory concurrently. This
+ # is OK.
+ test -d "$pathcomp" || exit
+ fi
+ pathcomp=$pathcomp/
+ done
+ fi
+
+ if test -n "$dir_arg"; then
+ $doit $mkdircmd "$dst" \
+ && { test -z "$chowncmd" || $doit $chowncmd "$dst"; } \
+ && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } \
+ && { test -z "$stripcmd" || $doit $stripcmd "$dst"; } \
+ && { test -z "$chmodcmd" || $doit $chmodcmd "$dst"; }
+
+ else
+ dstfile=`basename "$dst"`
+
+ # Make a couple of temp file names in the proper directory.
+ dsttmp=$dstdir/_inst.$$_
+ rmtmp=$dstdir/_rm.$$_
+
+ # Trap to clean up those temp files at exit.
+ trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+ trap '(exit $?); exit' 1 2 13 15
+
+ # Copy the file name to the temp name.
+ $doit $cpprog "$src" "$dsttmp" &&
+
+ # and set any options; do chmod last to preserve setuid bits.
+ #
+ # If any of these fail, we abort the whole thing. If we want to
+ # ignore errors from any of these, just make sure not to ignore
+ # errors from the above "$doit $cpprog $src $dsttmp" command.
+ #
+ { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \
+ && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \
+ && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \
+ && { test -z "$chmodcmd" || $doit $chmodcmd "$dsttmp"; } &&
+
+ # Now rename the file to the real destination.
+ { $doit $mvcmd -f "$dsttmp" "$dstdir/$dstfile" 2>/dev/null \
+ || {
+ # The rename failed, perhaps because mv can't rename something else
+ # to itself, or perhaps because mv is so ancient that it does not
+ # support -f.
+
+ # Now remove or move aside any old file at destination location.
+ # We try this two ways since rm can't unlink itself on some
+ # systems and the destination file might be busy for other
+ # reasons. In this case, the final cleanup might fail but the new
+ # file should still install successfully.
+ {
+ if test -f "$dstdir/$dstfile"; then
+ $doit $rmcmd -f "$dstdir/$dstfile" 2>/dev/null \
+ || $doit $mvcmd -f "$dstdir/$dstfile" "$rmtmp" 2>/dev/null \
+ || {
+ echo "$0: cannot unlink or rename $dstdir/$dstfile" >&2
+ (exit 1); exit
+ }
+ else
+ :
+ fi
+ } &&
+
+ # Now rename the file to the real destination.
+ $doit $mvcmd "$dsttmp" "$dstdir/$dstfile"
+ }
+ }
+ fi || { (exit 1); exit; }
+done
+
+# The final little trick to "correctly" pass the exit status to the exit trap.
+{
+ (exit 0); exit
+}
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
diff --git a/autoconf/ltmain.sh b/autoconf/ltmain.sh
new file mode 100644
index 00000000000..21ace012443
--- /dev/null
+++ b/autoconf/ltmain.sh
@@ -0,0 +1,6863 @@
+# ltmain.sh - Provide generalized library-building support services.
+# NOTE: Changing this file will not affect anything until you rerun configure.
+#
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
+# Free Software Foundation, Inc.
+# Originally by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+basename="s,^.*/,,g"
+
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
+
+# The name of this program:
+progname=`echo "$progpath" | $SED $basename`
+modename="$progname"
+
+# Global variables:
+EXIT_SUCCESS=0
+EXIT_FAILURE=1
+
+PROGRAM=ltmain.sh
+PACKAGE=libtool
+VERSION=1.5.22
+TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)"
+
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes.
+if test -n "${ZSH_VERSION+set}" ; then
+ setopt NO_GLOB_SUBST
+fi
+
+# Check that we have a working $echo.
+if test "X$1" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+elif test "X$1" = X--fallback-echo; then
+ # Avoid inline document here, it may be left over
+ :
+elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then
+ # Yippee, $echo works!
+ :
+else
+ # Restart under the correct shell, and then maybe $echo will work.
+ exec $SHELL "$progpath" --no-reexec ${1+"$@"}
+fi
+
+if test "X$1" = X--fallback-echo; then
+ # used as fallback echo
+ shift
+ cat <<EOF
+$*
+EOF
+ exit $EXIT_SUCCESS
+fi
+
+default_mode=
+help="Try \`$progname --help' for more information."
+magic="%%%MAGIC variable%%%"
+mkdir="mkdir"
+mv="mv -f"
+rm="rm -f"
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed="${SED}"' -e 1s/^X//'
+sed_quote_subst='s/\([\\`\\"$\\\\]\)/\\\1/g'
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+ # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+ SP2NL='tr \040 \012'
+ NL2SP='tr \015\012 \040\040'
+ ;;
+ *) # EBCDIC based system
+ SP2NL='tr \100 \n'
+ NL2SP='tr \r\n \100\100'
+ ;;
+esac
+
+# NLS nuisances.
+# Only set LANG and LC_ALL to C if already set.
+# These must not be set unconditionally because not all systems understand
+# e.g. LANG=C (notably SCO).
+# We save the old values to restore during execute mode.
+if test "${LC_ALL+set}" = set; then
+ save_LC_ALL="$LC_ALL"; LC_ALL=C; export LC_ALL
+fi
+if test "${LANG+set}" = set; then
+ save_LANG="$LANG"; LANG=C; export LANG
+fi
+
+# Make sure IFS has a sensible default
+lt_nl='
+'
+IFS=" $lt_nl"
+
+if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+ $echo "$modename: not configured to build any kind of library" 1>&2
+ $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit $EXIT_FAILURE
+fi
+
+# Global variables.
+mode=$default_mode
+nonopt=
+prev=
+prevopt=
+run=
+show="$echo"
+show_help=
+execute_dlfiles=
+duplicate_deps=no
+preserve_args=
+lo2o="s/\\.lo\$/.${objext}/"
+o2lo="s/\\.${objext}\$/.lo/"
+
+#####################################
+# Shell function definitions:
+# This seems to be the best place for them
+
+# func_mktempdir [string]
+# Make a temporary directory that won't clash with other running
+# libtool processes, and avoids race conditions if possible. If
+# given, STRING is the basename for that directory.
+func_mktempdir ()
+{
+ my_template="${TMPDIR-/tmp}/${1-$progname}"
+
+ if test "$run" = ":"; then
+ # Return a directory name, but don't create it in dry-run mode
+ my_tmpdir="${my_template}-$$"
+ else
+
+ # If mktemp works, use that first and foremost
+ my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
+
+ if test ! -d "$my_tmpdir"; then
+ # Failing that, at least try and use $RANDOM to avoid a race
+ my_tmpdir="${my_template}-${RANDOM-0}$$"
+
+ save_mktempdir_umask=`umask`
+ umask 0077
+ $mkdir "$my_tmpdir"
+ umask $save_mktempdir_umask
+ fi
+
+ # If we're not in dry-run mode, bomb out on failure
+ test -d "$my_tmpdir" || {
+ $echo "cannot create temporary directory \`$my_tmpdir'" 1>&2
+ exit $EXIT_FAILURE
+ }
+ fi
+
+ $echo "X$my_tmpdir" | $Xsed
+}
+
+
+# func_win32_libid arg
+# return the library type of file 'arg'
+#
+# Need a lot of goo to handle *both* DLLs and import libs
+# Has to be a shell function in order to 'eat' the argument
+# that is supplied when $file_magic_command is called.
+func_win32_libid ()
+{
+ win32_libid_type="unknown"
+ win32_fileres=`file -L $1 2>/dev/null`
+ case $win32_fileres in
+ *ar\ archive\ import\ library*) # definitely import
+ win32_libid_type="x86 archive import"
+ ;;
+ *ar\ archive*) # could be an import, or static
+ if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \
+ $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
+ win32_nmres=`eval $NM -f posix -A $1 | \
+ $SED -n -e '1,100{/ I /{s,.*,import,;p;q;};}'`
+ case $win32_nmres in
+ import*) win32_libid_type="x86 archive import";;
+ *) win32_libid_type="x86 archive static";;
+ esac
+ fi
+ ;;
+ *DLL*)
+ win32_libid_type="x86 DLL"
+ ;;
+ *executable*) # but shell scripts are "executable" too...
+ case $win32_fileres in
+ *MS\ Windows\ PE\ Intel*)
+ win32_libid_type="x86 DLL"
+ ;;
+ esac
+ ;;
+ esac
+ $echo $win32_libid_type
+}
+
+
+# func_infer_tag arg
+# Infer tagged configuration to use if any are available and
+# if one wasn't chosen via the "--tag" command line option.
+# Only attempt this if the compiler in the base compile
+# command doesn't match the default compiler.
+# arg is usually of the form 'gcc ...'
+func_infer_tag ()
+{
+ if test -n "$available_tags" && test -z "$tagname"; then
+ CC_quoted=
+ for arg in $CC; do
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ CC_quoted="$CC_quoted $arg"
+ done
+ case $@ in
+ # Blanks in the command may have been stripped by the calling shell,
+ # but not from the CC environment variable when configure was run.
+ " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;;
+ # Blanks at the start of $base_compile will cause this to fail
+ # if we don't check for them as well.
+ *)
+ for z in $available_tags; do
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
+ # Evaluate the configuration.
+ eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
+ CC_quoted=
+ for arg in $CC; do
+ # Double-quote args containing other shell metacharacters.
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ CC_quoted="$CC_quoted $arg"
+ done
+ case "$@ " in
+ " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*)
+ # The compiler in the base compile command matches
+ # the one in the tagged configuration.
+ # Assume this is the tagged configuration we want.
+ tagname=$z
+ break
+ ;;
+ esac
+ fi
+ done
+ # If $tagname still isn't set, then no tagged configuration
+ # was found and let the user know that the "--tag" command
+ # line option must be used.
+ if test -z "$tagname"; then
+ $echo "$modename: unable to infer tagged configuration"
+ $echo "$modename: specify a tag with \`--tag'" 1>&2
+ exit $EXIT_FAILURE
+# else
+# $echo "$modename: using $tagname tagged configuration"
+ fi
+ ;;
+ esac
+ fi
+}
+
+
+# func_extract_an_archive dir oldlib
+func_extract_an_archive ()
+{
+ f_ex_an_ar_dir="$1"; shift
+ f_ex_an_ar_oldlib="$1"
+
+ $show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)"
+ $run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit $?
+ if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
+ :
+ else
+ $echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" 1>&2
+ exit $EXIT_FAILURE
+ fi
+}
+
+# func_extract_archives gentop oldlib ...
+func_extract_archives ()
+{
+ my_gentop="$1"; shift
+ my_oldlibs=${1+"$@"}
+ my_oldobjs=""
+ my_xlib=""
+ my_xabs=""
+ my_xdir=""
+ my_status=""
+
+ $show "${rm}r $my_gentop"
+ $run ${rm}r "$my_gentop"
+ $show "$mkdir $my_gentop"
+ $run $mkdir "$my_gentop"
+ my_status=$?
+ if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then
+ exit $my_status
+ fi
+
+ for my_xlib in $my_oldlibs; do
+ # Extract the objects.
+ case $my_xlib in
+ [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
+ *) my_xabs=`pwd`"/$my_xlib" ;;
+ esac
+ my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'`
+ my_xdir="$my_gentop/$my_xlib"
+
+ $show "${rm}r $my_xdir"
+ $run ${rm}r "$my_xdir"
+ $show "$mkdir $my_xdir"
+ $run $mkdir "$my_xdir"
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then
+ exit $exit_status
+ fi
+ case $host in
+ *-darwin*)
+ $show "Extracting $my_xabs"
+ # Do not bother doing anything if just a dry run
+ if test -z "$run"; then
+ darwin_orig_dir=`pwd`
+ cd $my_xdir || exit $?
+ darwin_archive=$my_xabs
+ darwin_curdir=`pwd`
+ darwin_base_archive=`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'`
+ darwin_arches=`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Architectures 2>/dev/null`
+ if test -n "$darwin_arches"; then
+ darwin_arches=`echo "$darwin_arches" | $SED -e 's/.*are://'`
+ darwin_arch=
+ $show "$darwin_base_archive has multiple architectures $darwin_arches"
+ for darwin_arch in $darwin_arches ; do
+ mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+ lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
+ cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+ func_extract_an_archive "`pwd`" "${darwin_base_archive}"
+ cd "$darwin_curdir"
+ $rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
+ done # $darwin_arches
+ ## Okay now we have a bunch of thin objects, gotta fatten them up :)
+ darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print| xargs basename | sort -u | $NL2SP`
+ darwin_file=
+ darwin_files=
+ for darwin_file in $darwin_filelist; do
+ darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`
+ lipo -create -output "$darwin_file" $darwin_files
+ done # $darwin_filelist
+ ${rm}r unfat-$$
+ cd "$darwin_orig_dir"
+ else
+ cd "$darwin_orig_dir"
+ func_extract_an_archive "$my_xdir" "$my_xabs"
+ fi # $darwin_arches
+ fi # $run
+ ;;
+ *)
+ func_extract_an_archive "$my_xdir" "$my_xabs"
+ ;;
+ esac
+ my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
+ done
+ func_extract_archives_result="$my_oldobjs"
+}
+# End of Shell function definitions
+#####################################
+
+# Darwin sucks
+eval std_shrext=\"$shrext_cmds\"
+
+disable_libs=no
+
+# Parse our command line options once, thoroughly.
+while test "$#" -gt 0
+do
+ arg="$1"
+ shift
+
+ case $arg in
+ -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;;
+ *) optarg= ;;
+ esac
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ case $prev in
+ execute_dlfiles)
+ execute_dlfiles="$execute_dlfiles $arg"
+ ;;
+ tag)
+ tagname="$arg"
+ preserve_args="${preserve_args}=$arg"
+
+ # Check whether tagname contains only valid characters
+ case $tagname in
+ *[!-_A-Za-z0-9,/]*)
+ $echo "$progname: invalid tag name: $tagname" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $tagname in
+ CC)
+ # Don't test for the "default" C tag, as we know, it's there, but
+ # not specially marked.
+ ;;
+ *)
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then
+ taglist="$taglist $tagname"
+ # Evaluate the configuration.
+ eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`"
+ else
+ $echo "$progname: ignoring unknown tag $tagname" 1>&2
+ fi
+ ;;
+ esac
+ ;;
+ *)
+ eval "$prev=\$arg"
+ ;;
+ esac
+
+ prev=
+ prevopt=
+ continue
+ fi
+
+ # Have we seen a non-optional argument yet?
+ case $arg in
+ --help)
+ show_help=yes
+ ;;
+
+ --version)
+ $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP"
+ $echo
+ $echo "Copyright (C) 2005 Free Software Foundation, Inc."
+ $echo "This is free software; see the source for copying conditions. There is NO"
+ $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+ exit $?
+ ;;
+
+ --config)
+ ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath
+ # Now print the configurations for the tags.
+ for tagname in $taglist; do
+ ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath"
+ done
+ exit $?
+ ;;
+
+ --debug)
+ $echo "$progname: enabling shell trace mode"
+ set -x
+ preserve_args="$preserve_args $arg"
+ ;;
+
+ --dry-run | -n)
+ run=:
+ ;;
+
+ --features)
+ $echo "host: $host"
+ if test "$build_libtool_libs" = yes; then
+ $echo "enable shared libraries"
+ else
+ $echo "disable shared libraries"
+ fi
+ if test "$build_old_libs" = yes; then
+ $echo "enable static libraries"
+ else
+ $echo "disable static libraries"
+ fi
+ exit $?
+ ;;
+
+ --finish) mode="finish" ;;
+
+ --mode) prevopt="--mode" prev=mode ;;
+ --mode=*) mode="$optarg" ;;
+
+ --preserve-dup-deps) duplicate_deps="yes" ;;
+
+ --quiet | --silent)
+ show=:
+ preserve_args="$preserve_args $arg"
+ ;;
+
+ --tag)
+ prevopt="--tag"
+ prev=tag
+ preserve_args="$preserve_args --tag"
+ ;;
+ --tag=*)
+ set tag "$optarg" ${1+"$@"}
+ shift
+ prev=tag
+ preserve_args="$preserve_args --tag"
+ ;;
+
+ -dlopen)
+ prevopt="-dlopen"
+ prev=execute_dlfiles
+ ;;
+
+ -*)
+ $echo "$modename: unrecognized option \`$arg'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+
+ *)
+ nonopt="$arg"
+ break
+ ;;
+ esac
+done
+
+if test -n "$prevopt"; then
+ $echo "$modename: option \`$prevopt' requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+fi
+
+case $disable_libs in
+no)
+ ;;
+shared)
+ build_libtool_libs=no
+ build_old_libs=yes
+ ;;
+static)
+ build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
+ ;;
+esac
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end. This prevents here-documents from being
+# left over by shells.
+exec_cmd=
+
+if test -z "$show_help"; then
+
+ # Infer the operation mode.
+ if test -z "$mode"; then
+ $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2
+ $echo "*** Future versions of Libtool will require --mode=MODE be specified." 1>&2
+ case $nonopt in
+ *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*)
+ mode=link
+ for arg
+ do
+ case $arg in
+ -c)
+ mode=compile
+ break
+ ;;
+ esac
+ done
+ ;;
+ *db | *dbx | *strace | *truss)
+ mode=execute
+ ;;
+ *install*|cp|mv)
+ mode=install
+ ;;
+ *rm)
+ mode=uninstall
+ ;;
+ *)
+ # If we have no mode, but dlfiles were specified, then do execute mode.
+ test -n "$execute_dlfiles" && mode=execute
+
+ # Just use the default operation mode.
+ if test -z "$mode"; then
+ if test -n "$nonopt"; then
+ $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2
+ else
+ $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2
+ fi
+ fi
+ ;;
+ esac
+ fi
+
+ # Only execute mode is allowed to have -dlopen flags.
+ if test -n "$execute_dlfiles" && test "$mode" != execute; then
+ $echo "$modename: unrecognized option \`-dlopen'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Change the help message to a mode-specific one.
+ generic_help="$help"
+ help="Try \`$modename --help --mode=$mode' for more information."
+
+ # These modes are in order of execution frequency so that they run quickly.
+ case $mode in
+ # libtool compile mode
+ compile)
+ modename="$modename: compile"
+ # Get the compilation command and the source file.
+ base_compile=
+ srcfile="$nonopt" # always keep a non-empty value in "srcfile"
+ suppress_opt=yes
+ suppress_output=
+ arg_mode=normal
+ libobj=
+ later=
+
+ for arg
+ do
+ case $arg_mode in
+ arg )
+ # do not "continue". Instead, add this to base_compile
+ lastarg="$arg"
+ arg_mode=normal
+ ;;
+
+ target )
+ libobj="$arg"
+ arg_mode=normal
+ continue
+ ;;
+
+ normal )
+ # Accept any command-line options.
+ case $arg in
+ -o)
+ if test -n "$libobj" ; then
+ $echo "$modename: you cannot specify \`-o' more than once" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ arg_mode=target
+ continue
+ ;;
+
+ -static | -prefer-pic | -prefer-non-pic)
+ later="$later $arg"
+ continue
+ ;;
+
+ -no-suppress)
+ suppress_opt=no
+ continue
+ ;;
+
+ -Xcompiler)
+ arg_mode=arg # the next one goes into the "base_compile" arg list
+ continue # The current "srcfile" will either be retained or
+ ;; # replaced later. I would guess that would be a bug.
+
+ -Wc,*)
+ args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"`
+ lastarg=
+ save_ifs="$IFS"; IFS=','
+ for arg in $args; do
+ IFS="$save_ifs"
+
+ # Double-quote args containing other shell metacharacters.
+ # Many Bourne shells cannot handle close brackets correctly
+ # in scan sets, so we specify it separately.
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ lastarg="$lastarg $arg"
+ done
+ IFS="$save_ifs"
+ lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"`
+
+ # Add the arguments to base_compile.
+ base_compile="$base_compile $lastarg"
+ continue
+ ;;
+
+ * )
+ # Accept the current argument as the source file.
+ # The previous "srcfile" becomes the current argument.
+ #
+ lastarg="$srcfile"
+ srcfile="$arg"
+ ;;
+ esac # case $arg
+ ;;
+ esac # case $arg_mode
+
+ # Aesthetically quote the previous argument.
+ lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"`
+
+ case $lastarg in
+ # Double-quote args containing other shell metacharacters.
+ # Many Bourne shells cannot handle close brackets correctly
+ # in scan sets, and some SunOS ksh mistreat backslash-escaping
+ # in scan sets (worked around with variable expansion),
+ # and furthermore cannot handle '|' '&' '(' ')' in scan sets
+ # at all, so we specify them separately.
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ lastarg="\"$lastarg\""
+ ;;
+ esac
+
+ base_compile="$base_compile $lastarg"
+ done # for arg
+
+ case $arg_mode in
+ arg)
+ $echo "$modename: you must specify an argument for -Xcompile"
+ exit $EXIT_FAILURE
+ ;;
+ target)
+ $echo "$modename: you must specify a target with \`-o'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ *)
+ # Get the name of the library object.
+ [ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'`
+ ;;
+ esac
+
+ # Recognize several different file suffixes.
+ # If the user specifies -o file.o, it is replaced with file.lo
+ xform='[cCFSifmso]'
+ case $libobj in
+ *.ada) xform=ada ;;
+ *.adb) xform=adb ;;
+ *.ads) xform=ads ;;
+ *.asm) xform=asm ;;
+ *.c++) xform=c++ ;;
+ *.cc) xform=cc ;;
+ *.ii) xform=ii ;;
+ *.class) xform=class ;;
+ *.cpp) xform=cpp ;;
+ *.cxx) xform=cxx ;;
+ *.f90) xform=f90 ;;
+ *.for) xform=for ;;
+ *.java) xform=java ;;
+ esac
+
+ libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"`
+
+ case $libobj in
+ *.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;;
+ *)
+ $echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ func_infer_tag $base_compile
+
+ for arg in $later; do
+ case $arg in
+ -static)
+ build_old_libs=yes
+ continue
+ ;;
+
+ -prefer-pic)
+ pic_mode=yes
+ continue
+ ;;
+
+ -prefer-non-pic)
+ pic_mode=no
+ continue
+ ;;
+ esac
+ done
+
+ qlibobj=`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"`
+ case $qlibobj in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qlibobj="\"$qlibobj\"" ;;
+ esac
+ test "X$libobj" != "X$qlibobj" \
+ && $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' &()|`$[]' \
+ && $echo "$modename: libobj name \`$libobj' may not contain shell special characters."
+ objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
+ xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$obj"; then
+ xdir=
+ else
+ xdir=$xdir/
+ fi
+ lobj=${xdir}$objdir/$objname
+
+ if test -z "$base_compile"; then
+ $echo "$modename: you must specify a compilation command" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Delete any leftover library objects.
+ if test "$build_old_libs" = yes; then
+ removelist="$obj $lobj $libobj ${libobj}T"
+ else
+ removelist="$lobj $libobj ${libobj}T"
+ fi
+
+ $run $rm $removelist
+ trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
+
+ # On Cygwin there's no "real" PIC flag so we must build both object types
+ case $host_os in
+ cygwin* | mingw* | pw32* | os2*)
+ pic_mode=default
+ ;;
+ esac
+ if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
+ # non-PIC code in shared libraries is not supported
+ pic_mode=default
+ fi
+
+ # Calculate the filename of the output object if compiler does
+ # not support -o with -c
+ if test "$compiler_c_o" = no; then
+ output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext}
+ lockfile="$output_obj.lock"
+ removelist="$removelist $output_obj $lockfile"
+ trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
+ else
+ output_obj=
+ need_locks=no
+ lockfile=
+ fi
+
+ # Lock this critical section if it is needed
+ # We use this script file to make the link, it avoids creating a new file
+ if test "$need_locks" = yes; then
+ until $run ln "$progpath" "$lockfile" 2>/dev/null; do
+ $show "Waiting for $lockfile to be removed"
+ sleep 2
+ done
+ elif test "$need_locks" = warn; then
+ if test -f "$lockfile"; then
+ $echo "\
+*** ERROR, $lockfile exists and contains:
+`cat $lockfile 2>/dev/null`
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+ $echo "$srcfile" > "$lockfile"
+ fi
+
+ if test -n "$fix_srcfile_path"; then
+ eval srcfile=\"$fix_srcfile_path\"
+ fi
+ qsrcfile=`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"`
+ case $qsrcfile in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qsrcfile="\"$qsrcfile\"" ;;
+ esac
+
+ $run $rm "$libobj" "${libobj}T"
+
+ # Create a libtool object file (analogous to a ".la" file),
+ # but don't create it if we're doing a dry run.
+ test -z "$run" && cat > ${libobj}T <<EOF
+# $libobj - a libtool object file
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# Name of the PIC object.
+EOF
+
+ # Only build a PIC object if we are building libtool libraries.
+ if test "$build_libtool_libs" = yes; then
+ # Without this assignment, base_compile gets emptied.
+ fbsd_hideous_sh_bug=$base_compile
+
+ if test "$pic_mode" != no; then
+ command="$base_compile $qsrcfile $pic_flag"
+ else
+ # Don't build PIC code
+ command="$base_compile $qsrcfile"
+ fi
+
+ if test ! -d "${xdir}$objdir"; then
+ $show "$mkdir ${xdir}$objdir"
+ $run $mkdir ${xdir}$objdir
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "${xdir}$objdir"; then
+ exit $exit_status
+ fi
+ fi
+
+ if test -z "$output_obj"; then
+ # Place PIC objects in $objdir
+ command="$command -o $lobj"
+ fi
+
+ $run $rm "$lobj" "$output_obj"
+
+ $show "$command"
+ if $run eval "$command"; then :
+ else
+ test -n "$output_obj" && $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$need_locks" = warn &&
+ test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+ $echo "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ # Just move the object if needed, then go on to compile the next one
+ if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
+ $show "$mv $output_obj $lobj"
+ if $run $mv $output_obj $lobj; then :
+ else
+ error=$?
+ $run $rm $removelist
+ exit $error
+ fi
+ fi
+
+ # Append the name of the PIC object to the libtool object file.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+pic_object='$objdir/$objname'
+
+EOF
+
+ # Allow error messages only from the first compilation.
+ if test "$suppress_opt" = yes; then
+ suppress_output=' >/dev/null 2>&1'
+ fi
+ else
+ # No PIC object so indicate it doesn't exist in the libtool
+ # object file.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+pic_object=none
+
+EOF
+ fi
+
+ # Only build a position-dependent object if we build old libraries.
+ if test "$build_old_libs" = yes; then
+ if test "$pic_mode" != yes; then
+ # Don't build PIC code
+ command="$base_compile $qsrcfile"
+ else
+ command="$base_compile $qsrcfile $pic_flag"
+ fi
+ if test "$compiler_c_o" = yes; then
+ command="$command -o $obj"
+ fi
+
+ # Suppress compiler output if we already did a PIC compilation.
+ command="$command$suppress_output"
+ $run $rm "$obj" "$output_obj"
+ $show "$command"
+ if $run eval "$command"; then :
+ else
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$need_locks" = warn &&
+ test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+ $echo "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ # Just move the object if needed
+ if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
+ $show "$mv $output_obj $obj"
+ if $run $mv $output_obj $obj; then :
+ else
+ error=$?
+ $run $rm $removelist
+ exit $error
+ fi
+ fi
+
+ # Append the name of the non-PIC object the libtool object file.
+ # Only append if the libtool object file exists.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+# Name of the non-PIC object.
+non_pic_object='$objname'
+
+EOF
+ else
+ # Append the name of the non-PIC object the libtool object file.
+ # Only append if the libtool object file exists.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+# Name of the non-PIC object.
+non_pic_object=none
+
+EOF
+ fi
+
+ $run $mv "${libobj}T" "${libobj}"
+
+ # Unlock the critical section if it was locked
+ if test "$need_locks" != no; then
+ $run $rm "$lockfile"
+ fi
+
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool link mode
+ link | relink)
+ modename="$modename: link"
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ # It is impossible to link a dll without this setting, and
+ # we shouldn't force the makefile maintainer to figure out
+ # which system we are compiling for in order to pass an extra
+ # flag for every libtool invocation.
+ # allow_undefined=no
+
+ # FIXME: Unfortunately, there are problems with the above when trying
+ # to make a dll which has undefined symbols, in which case not
+ # even a static library is built. For now, we need to specify
+ # -no-undefined on the libtool link line when we can be certain
+ # that all symbols are satisfied, otherwise we get a static library.
+ allow_undefined=yes
+ ;;
+ *)
+ allow_undefined=yes
+ ;;
+ esac
+ libtool_args="$nonopt"
+ base_compile="$nonopt $@"
+ compile_command="$nonopt"
+ finalize_command="$nonopt"
+
+ compile_rpath=
+ finalize_rpath=
+ compile_shlibpath=
+ finalize_shlibpath=
+ convenience=
+ old_convenience=
+ deplibs=
+ old_deplibs=
+ compiler_flags=
+ linker_flags=
+ dllsearchpath=
+ lib_search_path=`pwd`
+ inst_prefix_dir=
+
+ avoid_version=no
+ dlfiles=
+ dlprefiles=
+ dlself=no
+ export_dynamic=no
+ export_symbols=
+ export_symbols_regex=
+ generated=
+ libobjs=
+ ltlibs=
+ module=no
+ no_install=no
+ objs=
+ non_pic_objects=
+ notinst_path= # paths that contain not-installed libtool libraries
+ precious_files_regex=
+ prefer_static_libs=no
+ preload=no
+ prev=
+ prevarg=
+ release=
+ rpath=
+ xrpath=
+ perm_rpath=
+ temp_rpath=
+ thread_safe=no
+ vinfo=
+ vinfo_number=no
+
+ func_infer_tag $base_compile
+
+ # We need to know -static, to get the right output filenames.
+ for arg
+ do
+ case $arg in
+ -all-static | -static)
+ if test "X$arg" = "X-all-static"; then
+ if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
+ $echo "$modename: warning: complete static linking is impossible in this configuration" 1>&2
+ fi
+ if test -n "$link_static_flag"; then
+ dlopen_self=$dlopen_self_static
+ fi
+ prefer_static_libs=yes
+ else
+ if test -z "$pic_flag" && test -n "$link_static_flag"; then
+ dlopen_self=$dlopen_self_static
+ fi
+ prefer_static_libs=built
+ fi
+ build_libtool_libs=no
+ build_old_libs=yes
+ break
+ ;;
+ esac
+ done
+
+ # See if our shared archives depend on static archives.
+ test -n "$old_archive_from_new_cmds" && build_old_libs=yes
+
+ # Go through the arguments, transforming them on the way.
+ while test "$#" -gt 0; do
+ arg="$1"
+ shift
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test
+ ;;
+ *) qarg=$arg ;;
+ esac
+ libtool_args="$libtool_args $qarg"
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ case $prev in
+ output)
+ compile_command="$compile_command @OUTPUT@"
+ finalize_command="$finalize_command @OUTPUT@"
+ ;;
+ esac
+
+ case $prev in
+ dlfiles|dlprefiles)
+ if test "$preload" = no; then
+ # Add the symbol object into the linking commands.
+ compile_command="$compile_command @SYMFILE@"
+ finalize_command="$finalize_command @SYMFILE@"
+ preload=yes
+ fi
+ case $arg in
+ *.la | *.lo) ;; # We handle these cases below.
+ force)
+ if test "$dlself" = no; then
+ dlself=needless
+ export_dynamic=yes
+ fi
+ prev=
+ continue
+ ;;
+ self)
+ if test "$prev" = dlprefiles; then
+ dlself=yes
+ elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
+ dlself=yes
+ else
+ dlself=needless
+ export_dynamic=yes
+ fi
+ prev=
+ continue
+ ;;
+ *)
+ if test "$prev" = dlfiles; then
+ dlfiles="$dlfiles $arg"
+ else
+ dlprefiles="$dlprefiles $arg"
+ fi
+ prev=
+ continue
+ ;;
+ esac
+ ;;
+ expsyms)
+ export_symbols="$arg"
+ if test ! -f "$arg"; then
+ $echo "$modename: symbol file \`$arg' does not exist"
+ exit $EXIT_FAILURE
+ fi
+ prev=
+ continue
+ ;;
+ expsyms_regex)
+ export_symbols_regex="$arg"
+ prev=
+ continue
+ ;;
+ inst_prefix)
+ inst_prefix_dir="$arg"
+ prev=
+ continue
+ ;;
+ precious_regex)
+ precious_files_regex="$arg"
+ prev=
+ continue
+ ;;
+ release)
+ release="-$arg"
+ prev=
+ continue
+ ;;
+ objectlist)
+ if test -f "$arg"; then
+ save_arg=$arg
+ moreargs=
+ for fil in `cat $save_arg`
+ do
+# moreargs="$moreargs $fil"
+ arg=$fil
+ # A libtool-controlled object.
+
+ # Check to see that this really is a libtool object.
+ if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ pic_object=
+ non_pic_object=
+
+ # Read the .lo file
+ # If there is no directory component, then add one.
+ case $arg in
+ */* | *\\*) . $arg ;;
+ *) . ./$arg ;;
+ esac
+
+ if test -z "$pic_object" || \
+ test -z "$non_pic_object" ||
+ test "$pic_object" = none && \
+ test "$non_pic_object" = none; then
+ $echo "$modename: cannot find name of object for \`$arg'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ if test "$pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ pic_object="$xdir$pic_object"
+
+ if test "$prev" = dlfiles; then
+ if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+ dlfiles="$dlfiles $pic_object"
+ prev=
+ continue
+ else
+ # If libtool objects are unsupported, then we need to preload.
+ prev=dlprefiles
+ fi
+ fi
+
+ # CHECK ME: I think I busted this. -Ossama
+ if test "$prev" = dlprefiles; then
+ # Preload the old-style object.
+ dlprefiles="$dlprefiles $pic_object"
+ prev=
+ fi
+
+ # A PIC object.
+ libobjs="$libobjs $pic_object"
+ arg="$pic_object"
+ fi
+
+ # Non-PIC object.
+ if test "$non_pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ non_pic_object="$xdir$non_pic_object"
+
+ # A standard non-PIC object
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ if test -z "$pic_object" || test "$pic_object" = none ; then
+ arg="$non_pic_object"
+ fi
+ else
+ # If the PIC object exists, use it instead.
+ # $xdir was prepended to $pic_object above.
+ non_pic_object="$pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ else
+ # Only an error if not doing a dry-run.
+ if test -z "$run"; then
+ $echo "$modename: \`$arg' is not a valid libtool object" 1>&2
+ exit $EXIT_FAILURE
+ else
+ # Dry-run case.
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
+ non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
+ libobjs="$libobjs $pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ fi
+ done
+ else
+ $echo "$modename: link input file \`$save_arg' does not exist"
+ exit $EXIT_FAILURE
+ fi
+ arg=$save_arg
+ prev=
+ continue
+ ;;
+ rpath | xrpath)
+ # We need an absolute path.
+ case $arg in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ $echo "$modename: only absolute run-paths are allowed" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ if test "$prev" = rpath; then
+ case "$rpath " in
+ *" $arg "*) ;;
+ *) rpath="$rpath $arg" ;;
+ esac
+ else
+ case "$xrpath " in
+ *" $arg "*) ;;
+ *) xrpath="$xrpath $arg" ;;
+ esac
+ fi
+ prev=
+ continue
+ ;;
+ xcompiler)
+ compiler_flags="$compiler_flags $qarg"
+ prev=
+ compile_command="$compile_command $qarg"
+ finalize_command="$finalize_command $qarg"
+ continue
+ ;;
+ xlinker)
+ linker_flags="$linker_flags $qarg"
+ compiler_flags="$compiler_flags $wl$qarg"
+ prev=
+ compile_command="$compile_command $wl$qarg"
+ finalize_command="$finalize_command $wl$qarg"
+ continue
+ ;;
+ xcclinker)
+ linker_flags="$linker_flags $qarg"
+ compiler_flags="$compiler_flags $qarg"
+ prev=
+ compile_command="$compile_command $qarg"
+ finalize_command="$finalize_command $qarg"
+ continue
+ ;;
+ shrext)
+ shrext_cmds="$arg"
+ prev=
+ continue
+ ;;
+ darwin_framework|darwin_framework_skip)
+ test "$prev" = "darwin_framework" && compiler_flags="$compiler_flags $arg"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ prev=
+ continue
+ ;;
+ *)
+ eval "$prev=\"\$arg\""
+ prev=
+ continue
+ ;;
+ esac
+ fi # test -n "$prev"
+
+ prevarg="$arg"
+
+ case $arg in
+ -all-static)
+ if test -n "$link_static_flag"; then
+ compile_command="$compile_command $link_static_flag"
+ finalize_command="$finalize_command $link_static_flag"
+ fi
+ continue
+ ;;
+
+ -allow-undefined)
+ # FIXME: remove this flag sometime in the future.
+ $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2
+ continue
+ ;;
+
+ -avoid-version)
+ avoid_version=yes
+ continue
+ ;;
+
+ -dlopen)
+ prev=dlfiles
+ continue
+ ;;
+
+ -dlpreopen)
+ prev=dlprefiles
+ continue
+ ;;
+
+ -export-dynamic)
+ export_dynamic=yes
+ continue
+ ;;
+
+ -export-symbols | -export-symbols-regex)
+ if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+ $echo "$modename: more than one -exported-symbols argument is not allowed"
+ exit $EXIT_FAILURE
+ fi
+ if test "X$arg" = "X-export-symbols"; then
+ prev=expsyms
+ else
+ prev=expsyms_regex
+ fi
+ continue
+ ;;
+
+ -framework|-arch|-isysroot)
+ case " $CC " in
+ *" ${arg} ${1} "* | *" ${arg} ${1} "*)
+ prev=darwin_framework_skip ;;
+ *) compiler_flags="$compiler_flags $arg"
+ prev=darwin_framework ;;
+ esac
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ continue
+ ;;
+
+ -inst-prefix-dir)
+ prev=inst_prefix
+ continue
+ ;;
+
+ # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
+ # so, if we see these flags be careful not to treat them like -L
+ -L[A-Z][A-Z]*:*)
+ case $with_gcc/$host in
+ no/*-*-irix* | /*-*-irix*)
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ ;;
+ esac
+ continue
+ ;;
+
+ -L*)
+ dir=`$echo "X$arg" | $Xsed -e 's/^-L//'`
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ absdir=`cd "$dir" && pwd`
+ if test -z "$absdir"; then
+ $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2
+ absdir="$dir"
+ notinst_path="$notinst_path $dir"
+ fi
+ dir="$absdir"
+ ;;
+ esac
+ case "$deplibs " in
+ *" -L$dir "*) ;;
+ *)
+ deplibs="$deplibs -L$dir"
+ lib_search_path="$lib_search_path $dir"
+ ;;
+ esac
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ testbindir=`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'`
+ case :$dllsearchpath: in
+ *":$dir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$dir";;
+ esac
+ case :$dllsearchpath: in
+ *":$testbindir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$testbindir";;
+ esac
+ ;;
+ esac
+ continue
+ ;;
+
+ -l*)
+ if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*)
+ # These systems don't actually have a C or math library (as such)
+ continue
+ ;;
+ *-*-os2*)
+ # These systems don't actually have a C library (as such)
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)
+ # Do not include libc due to us having libc/libc_r.
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # Rhapsody C and math libraries are in the System framework
+ deplibs="$deplibs -framework System"
+ continue
+ ;;
+ *-*-sco3.2v5* | *-*-sco5v6*)
+ # Causes problems with __ctype
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+ # Compiler inserts libc in the correct place for threads to work
+ test "X$arg" = "X-lc" && continue
+ ;;
+ esac
+ elif test "X$arg" = "X-lc_r"; then
+ case $host in
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | -*-*-bitrig*)
+ # Do not include libc_r directly, use -pthread flag.
+ continue
+ ;;
+ esac
+ fi
+ deplibs="$deplibs $arg"
+ continue
+ ;;
+
+ # Tru64 UNIX uses -model [arg] to determine the layout of C++
+ # classes, name mangling, and exception handling.
+ -model)
+ compile_command="$compile_command $arg"
+ compiler_flags="$compiler_flags $arg"
+ finalize_command="$finalize_command $arg"
+ prev=xcompiler
+ continue
+ ;;
+
+ -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
+ compiler_flags="$compiler_flags $arg"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ continue
+ ;;
+
+ -module)
+ module=yes
+ continue
+ ;;
+
+ # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
+ # -r[0-9][0-9]* specifies the processor on the SGI compiler
+ # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
+ # +DA*, +DD* enable 64-bit mode on the HP compiler
+ # -q* pass through compiler args for the IBM compiler
+ # -m* pass through architecture-specific compiler args for GCC
+ # -m*, -t[45]*, -txscale* pass through architecture-specific
+ # compiler args for GCC
+ # -pg pass through profiling flag for GCC
+ # @file GCC response files
+ -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*|-pg| \
+ -t[45]*|-txscale*|@*)
+
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ compiler_flags="$compiler_flags $arg"
+ continue
+ ;;
+
+ -shrext)
+ prev=shrext
+ continue
+ ;;
+
+ -no-fast-install)
+ fast_install=no
+ continue
+ ;;
+
+ -no-install)
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ # The PATH hackery in wrapper scripts is required on Windows
+ # in order for the loader to find any dlls it needs.
+ $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2
+ $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2
+ fast_install=no
+ ;;
+ *) no_install=yes ;;
+ esac
+ continue
+ ;;
+
+ -no-undefined)
+ allow_undefined=no
+ continue
+ ;;
+
+ -objectlist)
+ prev=objectlist
+ continue
+ ;;
+
+ -o) prev=output ;;
+
+ -precious-files-regex)
+ prev=precious_regex
+ continue
+ ;;
+
+ -release)
+ prev=release
+ continue
+ ;;
+
+ -rpath)
+ prev=rpath
+ continue
+ ;;
+
+ -R)
+ prev=xrpath
+ continue
+ ;;
+
+ -R*)
+ dir=`$echo "X$arg" | $Xsed -e 's/^-R//'`
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ $echo "$modename: only absolute run-paths are allowed" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ case "$xrpath " in
+ *" $dir "*) ;;
+ *) xrpath="$xrpath $dir" ;;
+ esac
+ continue
+ ;;
+
+ -static)
+ # The effects of -static are defined in a previous loop.
+ # We used to do the same as -all-static on platforms that
+ # didn't have a PIC flag, but the assumption that the effects
+ # would be equivalent was wrong. It would break on at least
+ # Digital Unix and AIX.
+ continue
+ ;;
+
+ -thread-safe)
+ thread_safe=yes
+ continue
+ ;;
+
+ -version-info)
+ prev=vinfo
+ continue
+ ;;
+ -version-number)
+ prev=vinfo
+ vinfo_number=yes
+ continue
+ ;;
+
+ -Wc,*)
+ args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'`
+ arg=
+ save_ifs="$IFS"; IFS=','
+ for flag in $args; do
+ IFS="$save_ifs"
+ case $flag in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ flag="\"$flag\""
+ ;;
+ esac
+ arg="$arg $wl$flag"
+ compiler_flags="$compiler_flags $flag"
+ done
+ IFS="$save_ifs"
+ arg=`$echo "X$arg" | $Xsed -e "s/^ //"`
+ ;;
+
+ -Wl,*)
+ args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'`
+ arg=
+ save_ifs="$IFS"; IFS=','
+ for flag in $args; do
+ IFS="$save_ifs"
+ case $flag in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ flag="\"$flag\""
+ ;;
+ esac
+ arg="$arg $wl$flag"
+ compiler_flags="$compiler_flags $wl$flag"
+ linker_flags="$linker_flags $flag"
+ done
+ IFS="$save_ifs"
+ arg=`$echo "X$arg" | $Xsed -e "s/^ //"`
+ ;;
+
+ -Xcompiler)
+ prev=xcompiler
+ continue
+ ;;
+
+ -Xlinker)
+ prev=xlinker
+ continue
+ ;;
+
+ -XCClinker)
+ prev=xcclinker
+ continue
+ ;;
+
+ # Some other compiler flag.
+ -* | +*)
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ ;;
+
+ *.$objext)
+ # A standard object.
+ objs="$objs $arg"
+ ;;
+
+ *.lo)
+ # A libtool-controlled object.
+
+ # Check to see that this really is a libtool object.
+ if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ pic_object=
+ non_pic_object=
+
+ # Read the .lo file
+ # If there is no directory component, then add one.
+ case $arg in
+ */* | *\\*) . $arg ;;
+ *) . ./$arg ;;
+ esac
+
+ if test -z "$pic_object" || \
+ test -z "$non_pic_object" ||
+ test "$pic_object" = none && \
+ test "$non_pic_object" = none; then
+ $echo "$modename: cannot find name of object for \`$arg'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ if test "$pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ pic_object="$xdir$pic_object"
+
+ if test "$prev" = dlfiles; then
+ if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+ dlfiles="$dlfiles $pic_object"
+ prev=
+ continue
+ else
+ # If libtool objects are unsupported, then we need to preload.
+ prev=dlprefiles
+ fi
+ fi
+
+ # CHECK ME: I think I busted this. -Ossama
+ if test "$prev" = dlprefiles; then
+ # Preload the old-style object.
+ dlprefiles="$dlprefiles $pic_object"
+ prev=
+ fi
+
+ # A PIC object.
+ libobjs="$libobjs $pic_object"
+ arg="$pic_object"
+ fi
+
+ # Non-PIC object.
+ if test "$non_pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ non_pic_object="$xdir$non_pic_object"
+
+ # A standard non-PIC object
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ if test -z "$pic_object" || test "$pic_object" = none ; then
+ arg="$non_pic_object"
+ fi
+ else
+ # If the PIC object exists, use it instead.
+ # $xdir was prepended to $pic_object above.
+ non_pic_object="$pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ else
+ # Only an error if not doing a dry-run.
+ if test -z "$run"; then
+ $echo "$modename: \`$arg' is not a valid libtool object" 1>&2
+ exit $EXIT_FAILURE
+ else
+ # Dry-run case.
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
+ non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
+ libobjs="$libobjs $pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ fi
+ ;;
+
+ *.$libext)
+ # An archive.
+ deplibs="$deplibs $arg"
+ old_deplibs="$old_deplibs $arg"
+ continue
+ ;;
+
+ *.la)
+ # A libtool-controlled library.
+
+ if test "$prev" = dlfiles; then
+ # This library was specified with -dlopen.
+ dlfiles="$dlfiles $arg"
+ prev=
+ elif test "$prev" = dlprefiles; then
+ # The library was specified with -dlpreopen.
+ dlprefiles="$dlprefiles $arg"
+ prev=
+ else
+ deplibs="$deplibs $arg"
+ fi
+ continue
+ ;;
+
+ # Some other compiler argument.
+ *)
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ ;;
+ esac # arg
+
+ # Now actually substitute the argument into the commands.
+ if test -n "$arg"; then
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ fi
+ done # argument parsing loop
+
+ if test -n "$prev"; then
+ $echo "$modename: the \`$prevarg' option requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
+ eval arg=\"$export_dynamic_flag_spec\"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ fi
+
+ oldlibs=
+ # calculate the name of the file, without its directory
+ outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'`
+ libobjs_save="$libobjs"
+
+ if test -n "$shlibpath_var"; then
+ # get the directories listed in $shlibpath_var
+ eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\`
+ else
+ shlib_search_path=
+ fi
+ eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
+ eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
+
+ output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$output_objdir" = "X$output"; then
+ output_objdir="$objdir"
+ else
+ output_objdir="$output_objdir/$objdir"
+ fi
+ # Create the object directory.
+ if test ! -d "$output_objdir"; then
+ $show "$mkdir $output_objdir"
+ $run $mkdir $output_objdir
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then
+ exit $exit_status
+ fi
+ fi
+
+ # Determine the type of output
+ case $output in
+ "")
+ $echo "$modename: you must specify an output file" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ *.$libext) linkmode=oldlib ;;
+ *.lo | *.$objext) linkmode=obj ;;
+ *.la) linkmode=lib ;;
+ *) linkmode=prog ;; # Anything else should be a program.
+ esac
+
+ case $host in
+ *cygwin* | *mingw* | *pw32*)
+ # don't eliminate duplications in $postdeps and $predeps
+ duplicate_compiler_generated_deps=yes
+ ;;
+ *)
+ duplicate_compiler_generated_deps=$duplicate_deps
+ ;;
+ esac
+ specialdeplibs=
+
+ libs=
+ # Find all interdependent deplibs by searching for libraries
+ # that are linked more than once (e.g. -la -lb -la)
+ for deplib in $deplibs; do
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ libs="$libs $deplib"
+ done
+
+ if test "$linkmode" = lib; then
+ libs="$predeps $libs $compiler_lib_search_path $postdeps"
+
+ # Compute libraries that are listed more than once in $predeps
+ # $postdeps and mark them as special (i.e., whose duplicates are
+ # not to be eliminated).
+ pre_post_deps=
+ if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then
+ for pre_post_dep in $predeps $postdeps; do
+ case "$pre_post_deps " in
+ *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;;
+ esac
+ pre_post_deps="$pre_post_deps $pre_post_dep"
+ done
+ fi
+ pre_post_deps=
+ fi
+
+ deplibs=
+ newdependency_libs=
+ newlib_search_path=
+ need_relink=no # whether we're linking any uninstalled libtool libraries
+ notinst_deplibs= # not-installed libtool libraries
+ case $linkmode in
+ lib)
+ passes="conv link"
+ for file in $dlfiles $dlprefiles; do
+ case $file in
+ *.la) ;;
+ *)
+ $echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ done
+ ;;
+ prog)
+ compile_deplibs=
+ finalize_deplibs=
+ alldeplibs=no
+ newdlfiles=
+ newdlprefiles=
+ passes="conv scan dlopen dlpreopen link"
+ ;;
+ *) passes="conv"
+ ;;
+ esac
+ for pass in $passes; do
+ if test "$linkmode,$pass" = "lib,link" ||
+ test "$linkmode,$pass" = "prog,scan"; then
+ libs="$deplibs"
+ deplibs=
+ fi
+ if test "$linkmode" = prog; then
+ case $pass in
+ dlopen) libs="$dlfiles" ;;
+ dlpreopen) libs="$dlprefiles" ;;
+ link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
+ esac
+ fi
+ if test "$pass" = dlopen; then
+ # Collect dlpreopened libraries
+ save_deplibs="$deplibs"
+ deplibs=
+ fi
+ for deplib in $libs; do
+ lib=
+ found=no
+ case $deplib in
+ -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ compiler_flags="$compiler_flags $deplib"
+ fi
+ continue
+ ;;
+ -l*)
+ if test "$linkmode" != lib && test "$linkmode" != prog; then
+ $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2
+ continue
+ fi
+ name=`$echo "X$deplib" | $Xsed -e 's/^-l//'`
+ for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ for search_ext in .la $std_shrext .so .a; do
+ # Search the libtool library
+ lib="$searchdir/lib${name}${search_ext}"
+ if test -f "$lib"; then
+ if test "$search_ext" = ".la"; then
+ found=yes
+ else
+ found=no
+ fi
+ break 2
+ fi
+ done
+ done
+ if test "$found" != yes; then
+ # deplib doesn't seem to be a libtool library
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ deplibs="$deplib $deplibs"
+ test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+ fi
+ continue
+ else # deplib is a libtool library
+ # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
+ # We need to do some special things here, and not later.
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $deplib "*)
+ if (${SED} -e '2q' $lib |
+ grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ library_names=
+ old_library=
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+ for l in $old_library $library_names; do
+ ll="$l"
+ done
+ if test "X$ll" = "X$old_library" ; then # only static version available
+ found=no
+ ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$ladir" = "X$lib" && ladir="."
+ lib=$ladir/$old_library
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ deplibs="$deplib $deplibs"
+ test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+ fi
+ continue
+ fi
+ fi
+ ;;
+ *) ;;
+ esac
+ fi
+ fi
+ ;; # -l
+ -L*)
+ case $linkmode in
+ lib)
+ deplibs="$deplib $deplibs"
+ test "$pass" = conv && continue
+ newdependency_libs="$deplib $newdependency_libs"
+ newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`
+ ;;
+ prog)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ continue
+ fi
+ if test "$pass" = scan; then
+ deplibs="$deplib $deplibs"
+ else
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ fi
+ newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`
+ ;;
+ *)
+ $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2
+ ;;
+ esac # linkmode
+ continue
+ ;; # -L
+ -R*)
+ if test "$pass" = link; then
+ dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'`
+ # Make sure the xrpath contains only unique directories.
+ case "$xrpath " in
+ *" $dir "*) ;;
+ *) xrpath="$xrpath $dir" ;;
+ esac
+ fi
+ deplibs="$deplib $deplibs"
+ continue
+ ;;
+ *.la) lib="$deplib" ;;
+ *.$libext)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ continue
+ fi
+ case $linkmode in
+ lib)
+ valid_a_lib=no
+ case $deplibs_check_method in
+ match_pattern*)
+ set dummy $deplibs_check_method
+ match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ if eval $echo \"$deplib\" 2>/dev/null \
+ | $SED 10q \
+ | $EGREP "$match_pattern_regex" > /dev/null; then
+ valid_a_lib=yes
+ fi
+ ;;
+ pass_all)
+ valid_a_lib=yes
+ ;;
+ esac
+ if test "$valid_a_lib" != yes; then
+ $echo
+ $echo "*** Warning: Trying to link with static lib archive $deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because the file extensions .$libext of this argument makes me believe"
+ $echo "*** that it is just a static archive that I should not used here."
+ else
+ $echo
+ $echo "*** Warning: Linking the shared library $output against the"
+ $echo "*** static library $deplib is not portable!"
+ deplibs="$deplib $deplibs"
+ fi
+ continue
+ ;;
+ prog)
+ if test "$pass" != link; then
+ deplibs="$deplib $deplibs"
+ else
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ fi
+ continue
+ ;;
+ esac # linkmode
+ ;; # *.$libext
+ *.lo | *.$objext)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ elif test "$linkmode" = prog; then
+ if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
+ # If there is no dlopen support or we're linking statically,
+ # we need to preload.
+ newdlprefiles="$newdlprefiles $deplib"
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ newdlfiles="$newdlfiles $deplib"
+ fi
+ fi
+ continue
+ ;;
+ %DEPLIBS%)
+ alldeplibs=yes
+ continue
+ ;;
+ esac # case $deplib
+ if test "$found" = yes || test -f "$lib"; then :
+ else
+ $echo "$modename: cannot find the library \`$lib' or unhandled argument \`$deplib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$ladir" = "X$lib" && ladir="."
+
+ dlname=
+ dlopen=
+ dlpreopen=
+ libdir=
+ library_names=
+ old_library=
+ # If the library was installed with an old release of libtool,
+ # it will not redefine variables installed, or shouldnotlink
+ installed=yes
+ shouldnotlink=no
+ avoidtemprpath=
+
+
+ # Read the .la file
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+
+ if test "$linkmode,$pass" = "lib,link" ||
+ test "$linkmode,$pass" = "prog,scan" ||
+ { test "$linkmode" != prog && test "$linkmode" != lib; }; then
+ test -n "$dlopen" && dlfiles="$dlfiles $dlopen"
+ test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen"
+ fi
+
+ if test "$pass" = conv; then
+ # Only check for convenience libraries
+ deplibs="$lib $deplibs"
+ if test -z "$libdir"; then
+ if test -z "$old_library"; then
+ $echo "$modename: cannot find name of link library for \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ # It is a libtool convenience library, so add in its objects.
+ convenience="$convenience $ladir/$objdir/$old_library"
+ old_convenience="$old_convenience $ladir/$objdir/$old_library"
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ deplibs="$deplib $deplibs"
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done
+ elif test "$linkmode" != prog && test "$linkmode" != lib; then
+ $echo "$modename: \`$lib' is not a convenience library" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ continue
+ fi # $pass = conv
+
+
+ # Get the name of the library we link against.
+ linklib=
+ for l in $old_library $library_names; do
+ linklib="$l"
+ done
+ if test -z "$linklib"; then
+ $echo "$modename: cannot find name of link library for \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # This library was specified with -dlopen.
+ if test "$pass" = dlopen; then
+ if test -z "$libdir"; then
+ $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test -z "$dlname" ||
+ test "$dlopen_support" != yes ||
+ test "$build_libtool_libs" = no; then
+ # If there is no dlname, no dlopen support or we're linking
+ # statically, we need to preload. We also need to preload any
+ # dependent libraries so libltdl's deplib preloader doesn't
+ # bomb out in the load deplibs phase.
+ dlprefiles="$dlprefiles $lib $dependency_libs"
+ else
+ newdlfiles="$newdlfiles $lib"
+ fi
+ continue
+ fi # $pass = dlopen
+
+ # We need an absolute path.
+ case $ladir in
+ [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
+ *)
+ abs_ladir=`cd "$ladir" && pwd`
+ if test -z "$abs_ladir"; then
+ $echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2
+ $echo "$modename: passing it literally to the linker, although it might fail" 1>&2
+ abs_ladir="$ladir"
+ fi
+ ;;
+ esac
+ laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+
+ # Find the relevant object directory and library name.
+ if test "X$installed" = Xyes; then
+ if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+ $echo "$modename: warning: library \`$lib' was moved." 1>&2
+ dir="$ladir"
+ absdir="$abs_ladir"
+ libdir="$abs_ladir"
+ else
+ dir="$libdir"
+ absdir="$libdir"
+ fi
+ test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+ else
+ if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+ dir="$ladir"
+ absdir="$abs_ladir"
+ # Remove this search path later
+ notinst_path="$notinst_path $abs_ladir"
+ else
+ dir="$ladir/$objdir"
+ absdir="$abs_ladir/$objdir"
+ # Remove this search path later
+ notinst_path="$notinst_path $abs_ladir"
+ fi
+ fi # $installed = yes
+ name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+
+ # This library was specified with -dlpreopen.
+ if test "$pass" = dlpreopen; then
+ if test -z "$libdir"; then
+ $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ # Prefer using a static library (so that no silly _DYNAMIC symbols
+ # are required to link).
+ if test -n "$old_library"; then
+ newdlprefiles="$newdlprefiles $dir/$old_library"
+ # Otherwise, use the dlname, so that lt_dlopen finds it.
+ elif test -n "$dlname"; then
+ newdlprefiles="$newdlprefiles $dir/$dlname"
+ else
+ newdlprefiles="$newdlprefiles $dir/$linklib"
+ fi
+ fi # $pass = dlpreopen
+
+ if test -z "$libdir"; then
+ # Link the convenience library
+ if test "$linkmode" = lib; then
+ deplibs="$dir/$old_library $deplibs"
+ elif test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$dir/$old_library $compile_deplibs"
+ finalize_deplibs="$dir/$old_library $finalize_deplibs"
+ else
+ deplibs="$lib $deplibs" # used for prog,scan pass
+ fi
+ continue
+ fi
+
+
+ if test "$linkmode" = prog && test "$pass" != link; then
+ newlib_search_path="$newlib_search_path $ladir"
+ deplibs="$lib $deplibs"
+
+ linkalldeplibs=no
+ if test "$link_all_deplibs" != no || test -z "$library_names" ||
+ test "$build_libtool_libs" = no; then
+ linkalldeplibs=yes
+ fi
+
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ case $deplib in
+ -L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test
+ esac
+ # Need to link against all dependency_libs?
+ if test "$linkalldeplibs" = yes; then
+ deplibs="$deplib $deplibs"
+ else
+ # Need to hardcode shared library paths
+ # or/and link against static libraries
+ newdependency_libs="$deplib $newdependency_libs"
+ fi
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done # for deplib
+ continue
+ fi # $linkmode = prog...
+
+ if test "$linkmode,$pass" = "prog,link"; then
+ if test -n "$library_names" &&
+ { test "$prefer_static_libs" = no || test -z "$old_library"; }; then
+ # We need to hardcode the library path
+ if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
+ # Make sure the rpath contains only unique directories.
+ case "$temp_rpath " in
+ *" $dir "*) ;;
+ *" $absdir "*) ;;
+ *) temp_rpath="$temp_rpath $absdir" ;;
+ esac
+ fi
+
+ # Hardcode the library path.
+ # Skip directories that are in the system default run-time
+ # search path.
+ case " $sys_lib_dlsearch_path " in
+ *" $absdir "*) ;;
+ *)
+ case "$compile_rpath " in
+ *" $absdir "*) ;;
+ *) compile_rpath="$compile_rpath $absdir"
+ esac
+ ;;
+ esac
+ case " $sys_lib_dlsearch_path " in
+ *" $libdir "*) ;;
+ *)
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir"
+ esac
+ ;;
+ esac
+ fi # $linkmode,$pass = prog,link...
+
+ if test "$alldeplibs" = yes &&
+ { test "$deplibs_check_method" = pass_all ||
+ { test "$build_libtool_libs" = yes &&
+ test -n "$library_names"; }; }; then
+ # We only need to search for static libraries
+ continue
+ fi
+ fi
+
+ link_static=no # Whether the deplib will be linked statically
+ use_static_libs=$prefer_static_libs
+ if test "$use_static_libs" = built && test "$installed" = yes ; then
+ use_static_libs=no
+ fi
+ if test -n "$library_names" &&
+ { test "$use_static_libs" = no || test -z "$old_library"; }; then
+ if test "$installed" = no; then
+ notinst_deplibs="$notinst_deplibs $lib"
+ need_relink=yes
+ fi
+ # This is a shared library
+
+ # Warn about portability, can't link against -module's on
+ # some systems (darwin)
+ if test "$shouldnotlink" = yes && test "$pass" = link ; then
+ $echo
+ if test "$linkmode" = prog; then
+ $echo "*** Warning: Linking the executable $output against the loadable module"
+ else
+ $echo "*** Warning: Linking the shared library $output against the loadable module"
+ fi
+ $echo "*** $linklib is not portable!"
+ fi
+ if test "$linkmode" = lib &&
+ test "$hardcode_into_libs" = yes; then
+ # Hardcode the library path.
+ # Skip directories that are in the system default run-time
+ # search path.
+ case " $sys_lib_dlsearch_path " in
+ *" $absdir "*) ;;
+ *)
+ case "$compile_rpath " in
+ *" $absdir "*) ;;
+ *) compile_rpath="$compile_rpath $absdir"
+ esac
+ ;;
+ esac
+ case " $sys_lib_dlsearch_path " in
+ *" $libdir "*) ;;
+ *)
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir"
+ esac
+ ;;
+ esac
+ fi
+
+ if test -n "$old_archive_from_expsyms_cmds"; then
+ # figure out the soname
+ set dummy $library_names
+ realname="$2"
+ shift; shift
+ libname=`eval \\$echo \"$libname_spec\"`
+ # use dlname if we got it. it's perfectly good, no?
+ if test -n "$dlname"; then
+ soname="$dlname"
+ elif test -n "$soname_spec"; then
+ # bleh windows
+ case $host in
+ *cygwin* | mingw*)
+ major=`expr $current - $age`
+ versuffix="-$major"
+ ;;
+ esac
+ eval soname=\"$soname_spec\"
+ else
+ soname="$realname"
+ fi
+
+ # Make a new name for the extract_expsyms_cmds to use
+ soroot="$soname"
+ soname=`$echo $soroot | ${SED} -e 's/^.*\///'`
+ newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a"
+
+ # If the library has no export list, then create one now
+ if test -f "$output_objdir/$soname-def"; then :
+ else
+ $show "extracting exported symbol list from \`$soname'"
+ save_ifs="$IFS"; IFS='~'
+ cmds=$extract_expsyms_cmds
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+
+ # Create $newlib
+ if test -f "$output_objdir/$newlib"; then :; else
+ $show "generating import library for \`$soname'"
+ save_ifs="$IFS"; IFS='~'
+ cmds=$old_archive_from_expsyms_cmds
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+ # make sure the library variables are pointing to the new library
+ dir=$output_objdir
+ linklib=$newlib
+ fi # test -n "$old_archive_from_expsyms_cmds"
+
+ if test "$linkmode" = prog || test "$mode" != relink; then
+ add_shlibpath=
+ add_dir=
+ add=
+ lib_linked=yes
+ case $hardcode_action in
+ immediate | unsupported)
+ if test "$hardcode_direct" = no; then
+ add="$dir/$linklib"
+ case $host in
+ *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
+ *-*-sysv4*uw2*) add_dir="-L$dir" ;;
+ *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
+ *-*-unixware7*) add_dir="-L$dir" ;;
+ *-*-darwin* )
+ # if the lib is a module then we can not link against
+ # it, someone is ignoring the new warnings I added
+ if /usr/bin/file -L $add 2> /dev/null |
+ $EGREP ": [^:]* bundle" >/dev/null ; then
+ $echo "** Warning, lib $linklib is a module, not a shared library"
+ if test -z "$old_library" ; then
+ $echo
+ $echo "** And there doesn't seem to be a static archive available"
+ $echo "** The link will probably fail, sorry"
+ else
+ add="$dir/$old_library"
+ fi
+ fi
+ esac
+ elif test "$hardcode_minus_L" = no; then
+ case $host in
+ *-*-sunos*) add_shlibpath="$dir" ;;
+ esac
+ add_dir="-L$dir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = no; then
+ add_shlibpath="$dir"
+ add="-l$name"
+ else
+ lib_linked=no
+ fi
+ ;;
+ relink)
+ if test "$hardcode_direct" = yes; then
+ add="$dir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+ add_dir="-L$dir"
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+ [\\/]*)
+ add_dir="$add_dir -L$inst_prefix_dir$libdir"
+ ;;
+ esac
+ fi
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ add_shlibpath="$dir"
+ add="-l$name"
+ else
+ lib_linked=no
+ fi
+ ;;
+ *) lib_linked=no ;;
+ esac
+
+ if test "$lib_linked" != yes; then
+ $echo "$modename: configuration error: unsupported hardcode properties"
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$add_shlibpath"; then
+ case :$compile_shlibpath: in
+ *":$add_shlibpath:"*) ;;
+ *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;;
+ esac
+ fi
+ if test "$linkmode" = prog; then
+ test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
+ test -n "$add" && compile_deplibs="$add $compile_deplibs"
+ else
+ test -n "$add_dir" && deplibs="$add_dir $deplibs"
+ test -n "$add" && deplibs="$add $deplibs"
+ if test "$hardcode_direct" != yes && \
+ test "$hardcode_minus_L" != yes && \
+ test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+ *":$libdir:"*) ;;
+ *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+ esac
+ fi
+ fi
+ fi
+
+ if test "$linkmode" = prog || test "$mode" = relink; then
+ add_shlibpath=
+ add_dir=
+ add=
+ # Finalize command for both is simple: just hardcode it.
+ if test "$hardcode_direct" = yes; then
+ add="$libdir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+ add_dir="-L$libdir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+ *":$libdir:"*) ;;
+ *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+ esac
+ add="-l$name"
+ elif test "$hardcode_automatic" = yes; then
+ if test -n "$inst_prefix_dir" &&
+ test -f "$inst_prefix_dir$libdir/$linklib" ; then
+ add="$inst_prefix_dir$libdir/$linklib"
+ else
+ add="$libdir/$linklib"
+ fi
+ else
+ # We cannot seem to hardcode it, guess we'll fake it.
+ add_dir="-L$libdir"
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+ [\\/]*)
+ add_dir="$add_dir -L$inst_prefix_dir$libdir"
+ ;;
+ esac
+ fi
+ add="-l$name"
+ fi
+
+ if test "$linkmode" = prog; then
+ test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
+ test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
+ else
+ test -n "$add_dir" && deplibs="$add_dir $deplibs"
+ test -n "$add" && deplibs="$add $deplibs"
+ fi
+ fi
+ elif test "$linkmode" = prog; then
+ # Here we assume that one of hardcode_direct or hardcode_minus_L
+ # is not unsupported. This is valid on all known static and
+ # shared platforms.
+ if test "$hardcode_direct" != unsupported; then
+ test -n "$old_library" && linklib="$old_library"
+ compile_deplibs="$dir/$linklib $compile_deplibs"
+ finalize_deplibs="$dir/$linklib $finalize_deplibs"
+ else
+ compile_deplibs="-l$name -L$dir $compile_deplibs"
+ finalize_deplibs="-l$name -L$dir $finalize_deplibs"
+ fi
+ elif test "$build_libtool_libs" = yes; then
+ # Not a shared library
+ if test "$deplibs_check_method" != pass_all; then
+ # We're trying link a shared library against a static one
+ # but the system doesn't support it.
+
+ # Just print a warning and add the library to dependency_libs so
+ # that the program can be linked against the static library.
+ $echo
+ $echo "*** Warning: This system can not link to static lib archive $lib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have."
+ if test "$module" = yes; then
+ $echo "*** But as you try to build a module library, libtool will still create "
+ $echo "*** a static module, that should work as long as the dlopening application"
+ $echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
+ if test -z "$global_symbol_pipe"; then
+ $echo
+ $echo "*** However, this would only work if libtool was able to extract symbol"
+ $echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+ $echo "*** not find such a program. So, this module is probably useless."
+ $echo "*** \`nm' from GNU binutils and a full rebuild may help."
+ fi
+ if test "$build_old_libs" = no; then
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ fi
+ else
+ deplibs="$dir/$old_library $deplibs"
+ link_static=yes
+ fi
+ fi # link shared/static library?
+
+ if test "$linkmode" = lib; then
+ if test -n "$dependency_libs" &&
+ { test "$hardcode_into_libs" != yes ||
+ test "$build_old_libs" = yes ||
+ test "$link_static" = yes; }; then
+ # Extract -R from dependency_libs
+ temp_deplibs=
+ for libdir in $dependency_libs; do
+ case $libdir in
+ -R*) temp_xrpath=`$echo "X$libdir" | $Xsed -e 's/^-R//'`
+ case " $xrpath " in
+ *" $temp_xrpath "*) ;;
+ *) xrpath="$xrpath $temp_xrpath";;
+ esac;;
+ *) temp_deplibs="$temp_deplibs $libdir";;
+ esac
+ done
+ dependency_libs="$temp_deplibs"
+ fi
+
+ newlib_search_path="$newlib_search_path $absdir"
+ # Link against this library
+ test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
+ # ... and its dependency_libs
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ newdependency_libs="$deplib $newdependency_libs"
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done
+
+ if test "$link_all_deplibs" != no; then
+ # Add the search paths of all dependency libraries
+ for deplib in $dependency_libs; do
+ case $deplib in
+ -L*) path="$deplib" ;;
+ *.la)
+ dir=`$echo "X$deplib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$deplib" && dir="."
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
+ *)
+ absdir=`cd "$dir" && pwd`
+ if test -z "$absdir"; then
+ $echo "$modename: warning: cannot determine absolute directory name of \`$dir'" 1>&2
+ absdir="$dir"
+ fi
+ ;;
+ esac
+ if grep "^installed=no" $deplib > /dev/null; then
+ path="$absdir/$objdir"
+ else
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test "$absdir" != "$libdir"; then
+ $echo "$modename: warning: \`$deplib' seems to be moved" 1>&2
+ fi
+ path="$absdir"
+ fi
+ depdepl=
+ case $host in
+ *-*-darwin*)
+ # we do not want to link against static libs,
+ # but need to link against shared
+ eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
+ if test -n "$deplibrary_names" ; then
+ for tmp in $deplibrary_names ; do
+ depdepl=$tmp
+ done
+ if test -f "$path/$depdepl" ; then
+ depdepl="$path/$depdepl"
+ fi
+ # do not add paths which are already there
+ case " $newlib_search_path " in
+ *" $path "*) ;;
+ *) newlib_search_path="$newlib_search_path $path";;
+ esac
+ fi
+ path=""
+ ;;
+ *)
+ path="-L$path"
+ ;;
+ esac
+ ;;
+ -l*)
+ case $host in
+ *-*-darwin*)
+ # Again, we only want to link against shared libraries
+ eval tmp_libs=`$echo "X$deplib" | $Xsed -e "s,^\-l,,"`
+ for tmp in $newlib_search_path ; do
+ if test -f "$tmp/lib$tmp_libs.dylib" ; then
+ eval depdepl="$tmp/lib$tmp_libs.dylib"
+ break
+ fi
+ done
+ path=""
+ ;;
+ *) continue ;;
+ esac
+ ;;
+ *) continue ;;
+ esac
+ case " $deplibs " in
+ *" $path "*) ;;
+ *) deplibs="$path $deplibs" ;;
+ esac
+ case " $deplibs " in
+ *" $depdepl "*) ;;
+ *) deplibs="$depdepl $deplibs" ;;
+ esac
+ done
+ fi # link_all_deplibs != no
+ fi # linkmode = lib
+ done # for deplib in $libs
+ dependency_libs="$newdependency_libs"
+ if test "$pass" = dlpreopen; then
+ # Link the dlpreopened libraries before other libraries
+ for deplib in $save_deplibs; do
+ deplibs="$deplib $deplibs"
+ done
+ fi
+ if test "$pass" != dlopen; then
+ if test "$pass" != conv; then
+ # Make sure lib_search_path contains only unique directories.
+ lib_search_path=
+ for dir in $newlib_search_path; do
+ case "$lib_search_path " in
+ *" $dir "*) ;;
+ *) lib_search_path="$lib_search_path $dir" ;;
+ esac
+ done
+ newlib_search_path=
+ fi
+
+ if test "$linkmode,$pass" != "prog,link"; then
+ vars="deplibs"
+ else
+ vars="compile_deplibs finalize_deplibs"
+ fi
+ for var in $vars dependency_libs; do
+ # Add libraries to $var in reverse order
+ eval tmp_libs=\"\$$var\"
+ new_libs=
+ for deplib in $tmp_libs; do
+ # FIXME: Pedantically, this is the right thing to do, so
+ # that some nasty dependency loop isn't accidentally
+ # broken:
+ #new_libs="$deplib $new_libs"
+ # Pragmatically, this seems to cause very few problems in
+ # practice:
+ case $deplib in
+ -L*) new_libs="$deplib $new_libs" ;;
+ -R*) ;;
+ *)
+ # And here is the reason: when a library appears more
+ # than once as an explicit dependence of a library, or
+ # is implicitly linked in more than once by the
+ # compiler, it is considered special, and multiple
+ # occurrences thereof are not removed. Compare this
+ # with having the same library being listed as a
+ # dependency of multiple other libraries: in this case,
+ # we know (pedantically, we assume) the library does not
+ # need to be listed more than once, so we keep only the
+ # last copy. This is not always right, but it is rare
+ # enough that we require users that really mean to play
+ # such unportable linking tricks to link the library
+ # using -Wl,-lname, so that libtool does not consider it
+ # for duplicate removal.
+ case " $specialdeplibs " in
+ *" $deplib "*) new_libs="$deplib $new_libs" ;;
+ *)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$deplib $new_libs" ;;
+ esac
+ ;;
+ esac
+ ;;
+ esac
+ done
+ tmp_libs=
+ for deplib in $new_libs; do
+ case $deplib in
+ -L*)
+ case " $tmp_libs " in
+ *" $deplib "*) ;;
+ *) tmp_libs="$tmp_libs $deplib" ;;
+ esac
+ ;;
+ *) tmp_libs="$tmp_libs $deplib" ;;
+ esac
+ done
+ eval $var=\"$tmp_libs\"
+ done # for var
+ fi
+ # Last step: remove runtime libs from dependency_libs
+ # (they stay in deplibs)
+ tmp_libs=
+ for i in $dependency_libs ; do
+ case " $predeps $postdeps $compiler_lib_search_path " in
+ *" $i "*)
+ i=""
+ ;;
+ esac
+ if test -n "$i" ; then
+ tmp_libs="$tmp_libs $i"
+ fi
+ done
+ dependency_libs=$tmp_libs
+ done # for pass
+ if test "$linkmode" = prog; then
+ dlfiles="$newdlfiles"
+ dlprefiles="$newdlprefiles"
+ fi
+
+ case $linkmode in
+ oldlib)
+ if test -n "$deplibs"; then
+ $echo "$modename: warning: \`-l' and \`-L' are ignored for archives" 1>&2
+ fi
+
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$rpath"; then
+ $echo "$modename: warning: \`-rpath' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$xrpath"; then
+ $echo "$modename: warning: \`-R' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info/-version-number' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+ $echo "$modename: warning: \`-export-symbols' is ignored for archives" 1>&2
+ fi
+
+ # Now set the variables for building old libraries.
+ build_libtool_libs=no
+ oldlibs="$output"
+ objs="$objs$old_deplibs"
+ ;;
+
+ lib)
+ # Make sure we only generate libraries of the form `libNAME.la'.
+ case $outputname in
+ lib*)
+ name=`$echo "X$outputname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+ eval shared_ext=\"$shrext_cmds\"
+ eval libname=\"$libname_spec\"
+ ;;
+ *)
+ if test "$module" = no; then
+ $echo "$modename: libtool library \`$output' must begin with \`lib'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test "$need_lib_prefix" != no; then
+ # Add the "lib" prefix for modules if required
+ name=`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
+ eval shared_ext=\"$shrext_cmds\"
+ eval libname=\"$libname_spec\"
+ else
+ libname=`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
+ fi
+ ;;
+ esac
+
+ if test -n "$objs"; then
+ if test "$deplibs_check_method" != pass_all; then
+ $echo "$modename: cannot build libtool library \`$output' from non-libtool objects on this host:$objs" 2>&1
+ exit $EXIT_FAILURE
+ else
+ $echo
+ $echo "*** Warning: Linking the shared library $output against the non-libtool"
+ $echo "*** objects $objs is not portable!"
+ libobjs="$libobjs $objs"
+ fi
+ fi
+
+ if test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen self' is ignored for libtool libraries" 1>&2
+ fi
+
+ set dummy $rpath
+ if test "$#" -gt 2; then
+ $echo "$modename: warning: ignoring multiple \`-rpath's for a libtool library" 1>&2
+ fi
+ install_libdir="$2"
+
+ oldlibs=
+ if test -z "$rpath"; then
+ if test "$build_libtool_libs" = yes; then
+ # Building a libtool convenience library.
+ # Some compilers have problems with a `.al' extension so
+ # convenience libraries should have the same extension an
+ # archive normally would.
+ oldlibs="$output_objdir/$libname.$libext $oldlibs"
+ build_libtool_libs=convenience
+ build_old_libs=yes
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info/-version-number' is ignored for convenience libraries" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for convenience libraries" 1>&2
+ fi
+ else
+
+ # Parse the version information argument.
+ save_ifs="$IFS"; IFS=':'
+ set dummy $vinfo 0 0 0
+ IFS="$save_ifs"
+
+ if test -n "$8"; then
+ $echo "$modename: too many parameters to \`-version-info'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # convert absolute version numbers to libtool ages
+ # this retains compatibility with .la files and attempts
+ # to make the code below a bit more comprehensible
+
+ case $vinfo_number in
+ yes)
+ number_major="$2"
+ number_minor="$3"
+ number_revision="$4"
+ #
+ # There are really only two kinds -- those that
+ # use the current revision as the major version
+ # and those that subtract age and use age as
+ # a minor version. But, then there is irix
+ # which has an extra 1 added just for fun
+ #
+ case $version_type in
+ darwin|linux|osf|windows)
+ current=`expr $number_major + $number_minor`
+ age="$number_minor"
+ revision="$number_revision"
+ ;;
+ freebsd-aout|freebsd-elf|sunos)
+ current="$number_major"
+ revision="$number_minor"
+ age="0"
+ ;;
+ irix|nonstopux)
+ current=`expr $number_major + $number_minor - 1`
+ age="$number_minor"
+ revision="$number_minor"
+ ;;
+ esac
+ ;;
+ no)
+ current="$2"
+ revision="$3"
+ age="$4"
+ ;;
+ esac
+
+ # Check that each of the things are valid numbers.
+ case $current in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: CURRENT \`$current' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $revision in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: REVISION \`$revision' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $age in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: AGE \`$age' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ if test "$age" -gt "$current"; then
+ $echo "$modename: AGE \`$age' is greater than the current interface number \`$current'" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Calculate the version variables.
+ major=
+ versuffix=
+ verstring=
+ case $version_type in
+ none) ;;
+
+ darwin)
+ # Like Linux, but with the current version available in
+ # verstring for coding it into the library header
+ major=.`expr $current - $age`
+ versuffix="$major.$age.$revision"
+ # Darwin ld doesn't like 0 for these options...
+ minor_current=`expr $current + 1`
+ verstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
+ ;;
+
+ freebsd-aout)
+ major=".$current"
+ versuffix=".$current.$revision";
+ ;;
+
+ freebsd-elf)
+ major=".$current"
+ versuffix=".$current";
+ ;;
+
+ irix | nonstopux)
+ major=`expr $current - $age + 1`
+
+ case $version_type in
+ nonstopux) verstring_prefix=nonstopux ;;
+ *) verstring_prefix=sgi ;;
+ esac
+ verstring="$verstring_prefix$major.$revision"
+
+ # Add in all the interfaces that we are compatible with.
+ loop=$revision
+ while test "$loop" -ne 0; do
+ iface=`expr $revision - $loop`
+ loop=`expr $loop - 1`
+ verstring="$verstring_prefix$major.$iface:$verstring"
+ done
+
+ # Before this point, $major must not contain `.'.
+ major=.$major
+ versuffix="$major.$revision"
+ ;;
+
+ linux)
+ major=.`expr $current - $age`
+ versuffix="$major.$age.$revision"
+ ;;
+
+ osf)
+ major=.`expr $current - $age`
+ versuffix=".$current.$age.$revision"
+ verstring="$current.$age.$revision"
+
+ # Add in all the interfaces that we are compatible with.
+ loop=$age
+ while test "$loop" -ne 0; do
+ iface=`expr $current - $loop`
+ loop=`expr $loop - 1`
+ verstring="$verstring:${iface}.0"
+ done
+
+ # Make executables depend on our current version.
+ verstring="$verstring:${current}.0"
+ ;;
+
+ sunos)
+ major=".$current"
+ versuffix=".$current.$revision"
+ ;;
+
+ windows)
+ # Use '-' rather than '.', since we only want one
+ # extension on DOS 8.3 filesystems.
+ major=`expr $current - $age`
+ versuffix="-$major"
+ ;;
+
+ *)
+ $echo "$modename: unknown library version type \`$version_type'" 1>&2
+ $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ # Clear the version info if we defaulted, and they specified a release.
+ if test -z "$vinfo" && test -n "$release"; then
+ major=
+ case $version_type in
+ darwin)
+ # we can't check for "0.0" in archive_cmds due to quoting
+ # problems, so we reset it completely
+ verstring=
+ ;;
+ *)
+ verstring="0.0"
+ ;;
+ esac
+ if test "$need_version" = no; then
+ versuffix=
+ else
+ versuffix=".0.0"
+ fi
+ fi
+
+ # Remove version info from name if versioning should be avoided
+ if test "$avoid_version" = yes && test "$need_version" = no; then
+ major=
+ versuffix=
+ verstring=""
+ fi
+
+ # Check to see if the archive will have undefined symbols.
+ if test "$allow_undefined" = yes; then
+ if test "$allow_undefined_flag" = unsupported; then
+ $echo "$modename: warning: undefined symbols not allowed in $host shared libraries" 1>&2
+ build_libtool_libs=no
+ build_old_libs=yes
+ fi
+ else
+ # Don't allow undefined symbols.
+ allow_undefined_flag="$no_undefined_flag"
+ fi
+ fi
+
+ if test "$mode" != relink; then
+ # Remove our outputs, but don't remove object files since they
+ # may have been created when compiling PIC objects.
+ removelist=
+ tempremovelist=`$echo "$output_objdir/*"`
+ for p in $tempremovelist; do
+ case $p in
+ *.$objext)
+ ;;
+ $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
+ if test "X$precious_files_regex" != "X"; then
+ if echo $p | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
+ then
+ continue
+ fi
+ fi
+ removelist="$removelist $p"
+ ;;
+ *) ;;
+ esac
+ done
+ if test -n "$removelist"; then
+ $show "${rm}r $removelist"
+ $run ${rm}r $removelist
+ fi
+ fi
+
+ # Now set the variables for building old libraries.
+ if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
+ oldlibs="$oldlibs $output_objdir/$libname.$libext"
+
+ # Transform .lo files to .o files.
+ oldobjs="$objs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP`
+ fi
+
+ # Eliminate all temporary directories.
+ for path in $notinst_path; do
+ lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"`
+ deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"`
+ dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"`
+ done
+
+ if test -n "$xrpath"; then
+ # If the user specified any rpath flags, then add them.
+ temp_xrpath=
+ for libdir in $xrpath; do
+ temp_xrpath="$temp_xrpath -R$libdir"
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir" ;;
+ esac
+ done
+ if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
+ dependency_libs="$temp_xrpath $dependency_libs"
+ fi
+ fi
+
+ # Make sure dlfiles contains only unique files that won't be dlpreopened
+ old_dlfiles="$dlfiles"
+ dlfiles=
+ for lib in $old_dlfiles; do
+ case " $dlprefiles $dlfiles " in
+ *" $lib "*) ;;
+ *) dlfiles="$dlfiles $lib" ;;
+ esac
+ done
+
+ # Make sure dlprefiles contains only unique files
+ old_dlprefiles="$dlprefiles"
+ dlprefiles=
+ for lib in $old_dlprefiles; do
+ case "$dlprefiles " in
+ *" $lib "*) ;;
+ *) dlprefiles="$dlprefiles $lib" ;;
+ esac
+ done
+
+ if test "$build_libtool_libs" = yes; then
+ if test -n "$rpath"; then
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*)
+ # these systems don't actually have a c library (as such)!
+ ;;
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # Rhapsody C library is in the System framework
+ deplibs="$deplibs -framework System"
+ ;;
+ *-*-netbsd*)
+ # Don't link with libc until the a.out ld.so is fixed.
+ ;;
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)
+ # Do not include libc due to us having libc/libc_r.
+ ;;
+ *-*-sco3.2v5* | *-*-sco5v6*)
+ # Causes problems with __ctype
+ ;;
+ *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+ # Compiler inserts libc in the correct place for threads to work
+ ;;
+ *)
+ # Add libc to deplibs on all other systems if necessary.
+ if test "$build_libtool_need_lc" = "yes"; then
+ deplibs="$deplibs -lc"
+ fi
+ ;;
+ esac
+ fi
+
+ # Transform deplibs into only deplibs that can be linked in shared.
+ name_save=$name
+ libname_save=$libname
+ release_save=$release
+ versuffix_save=$versuffix
+ major_save=$major
+ # I'm not sure if I'm treating the release correctly. I think
+ # release should show up in the -l (ie -lgmp5) so we don't want to
+ # add it in twice. Is that correct?
+ release=""
+ versuffix=""
+ major=""
+ newdeplibs=
+ droppeddeps=no
+ case $deplibs_check_method in
+ pass_all)
+ # Don't check for shared/static. Everything works.
+ # This might be a little naive. We might want to check
+ # whether the library exists or not. But this is on
+ # osf3 & osf4 and I'm not really sure... Just
+ # implementing what was already the behavior.
+ newdeplibs=$deplibs
+ ;;
+ test_compile)
+ # This code stresses the "libraries are programs" paradigm to its
+ # limits. Maybe even breaks it. We compile a program, linking it
+ # against the deplibs as a proxy for the library. Then we can check
+ # whether they linked in statically or dynamically with ldd.
+ $rm conftest.c
+ cat > conftest.c <<EOF
+ int main() { return 0; }
+EOF
+ $rm conftest
+ $LTCC $LTCFLAGS -o conftest conftest.c $deplibs
+ if test "$?" -eq 0 ; then
+ ldd_output=`ldd conftest`
+ for i in $deplibs; do
+ name=`expr $i : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" -ne "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $i "*)
+ newdeplibs="$newdeplibs $i"
+ i=""
+ ;;
+ esac
+ fi
+ if test -n "$i" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ deplib_matches=`eval \\$echo \"$library_names_spec\"`
+ set dummy $deplib_matches
+ deplib_match=$2
+ if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+ newdeplibs="$newdeplibs $i"
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: dynamic linker does not accept needed library $i."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which I believe you do not have"
+ $echo "*** because a test_compile did reveal that the linker did not use it for"
+ $echo "*** its dynamic dependency list that programs get resolved with at runtime."
+ fi
+ fi
+ else
+ newdeplibs="$newdeplibs $i"
+ fi
+ done
+ else
+ # Error occurred in the first compile. Let's try to salvage
+ # the situation: Compile a separate program for each library.
+ for i in $deplibs; do
+ name=`expr $i : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" != "0"; then
+ $rm conftest
+ $LTCC $LTCFLAGS -o conftest conftest.c $i
+ # Did it work?
+ if test "$?" -eq 0 ; then
+ ldd_output=`ldd conftest`
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $i "*)
+ newdeplibs="$newdeplibs $i"
+ i=""
+ ;;
+ esac
+ fi
+ if test -n "$i" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ deplib_matches=`eval \\$echo \"$library_names_spec\"`
+ set dummy $deplib_matches
+ deplib_match=$2
+ if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+ newdeplibs="$newdeplibs $i"
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: dynamic linker does not accept needed library $i."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because a test_compile did reveal that the linker did not use this one"
+ $echo "*** as a dynamic dependency that programs can get resolved with at runtime."
+ fi
+ fi
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning! Library $i is needed by this library but I was not able to"
+ $echo "*** make it link in! You will probably need to install it or some"
+ $echo "*** library that it depends on before this library will be fully"
+ $echo "*** functional. Installing it before continuing would be even better."
+ fi
+ else
+ newdeplibs="$newdeplibs $i"
+ fi
+ done
+ fi
+ ;;
+ file_magic*)
+ set dummy $deplibs_check_method
+ file_magic_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ for a_deplib in $deplibs; do
+ name=`expr $a_deplib : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" != "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $a_deplib "*)
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ ;;
+ esac
+ fi
+ if test -n "$a_deplib" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+ for potent_lib in $potential_libs; do
+ # Follow soft links.
+ if ls -lLd "$potent_lib" 2>/dev/null \
+ | grep " -> " >/dev/null; then
+ continue
+ fi
+ # The statement above tries to avoid entering an
+ # endless loop below, in case of cyclic links.
+ # We might still enter an endless loop, since a link
+ # loop can be closed while we follow links,
+ # but so what?
+ potlib="$potent_lib"
+ while test -h "$potlib" 2>/dev/null; do
+ potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
+ case $potliblink in
+ [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
+ *) potlib=`$echo "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
+ esac
+ done
+ if eval $file_magic_cmd \"\$potlib\" 2>/dev/null \
+ | ${SED} 10q \
+ | $EGREP "$file_magic_regex" > /dev/null; then
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ break 2
+ fi
+ done
+ done
+ fi
+ if test -n "$a_deplib" ; then
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: linker path does not have real file for library $a_deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because I did check the linker path looking for a file starting"
+ if test -z "$potlib" ; then
+ $echo "*** with $libname but no candidates were found. (...for file magic test)"
+ else
+ $echo "*** with $libname and none of the candidates passed a file format test"
+ $echo "*** using a file magic. Last file checked: $potlib"
+ fi
+ fi
+ else
+ # Add a -L argument.
+ newdeplibs="$newdeplibs $a_deplib"
+ fi
+ done # Gone through all deplibs.
+ ;;
+ match_pattern*)
+ set dummy $deplibs_check_method
+ match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ for a_deplib in $deplibs; do
+ name=`expr $a_deplib : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test -n "$name" && test "$name" != "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $a_deplib "*)
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ ;;
+ esac
+ fi
+ if test -n "$a_deplib" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+ for potent_lib in $potential_libs; do
+ potlib="$potent_lib" # see symlink-check above in file_magic test
+ if eval $echo \"$potent_lib\" 2>/dev/null \
+ | ${SED} 10q \
+ | $EGREP "$match_pattern_regex" > /dev/null; then
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ break 2
+ fi
+ done
+ done
+ fi
+ if test -n "$a_deplib" ; then
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: linker path does not have real file for library $a_deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because I did check the linker path looking for a file starting"
+ if test -z "$potlib" ; then
+ $echo "*** with $libname but no candidates were found. (...for regex pattern test)"
+ else
+ $echo "*** with $libname and none of the candidates passed a file format test"
+ $echo "*** using a regex pattern. Last file checked: $potlib"
+ fi
+ fi
+ else
+ # Add a -L argument.
+ newdeplibs="$newdeplibs $a_deplib"
+ fi
+ done # Gone through all deplibs.
+ ;;
+ none | unknown | *)
+ newdeplibs=""
+ tmp_deplibs=`$echo "X $deplibs" | $Xsed -e 's/ -lc$//' \
+ -e 's/ -[LR][^ ]*//g'`
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ for i in $predeps $postdeps ; do
+ # can't use Xsed below, because $i might contain '/'
+ tmp_deplibs=`$echo "X $tmp_deplibs" | ${SED} -e "1s,^X,," -e "s,$i,,"`
+ done
+ fi
+ if $echo "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' \
+ | grep . >/dev/null; then
+ $echo
+ if test "X$deplibs_check_method" = "Xnone"; then
+ $echo "*** Warning: inter-library dependencies are not supported in this platform."
+ else
+ $echo "*** Warning: inter-library dependencies are not known to be supported."
+ fi
+ $echo "*** All declared inter-library dependencies are being dropped."
+ droppeddeps=yes
+ fi
+ ;;
+ esac
+ versuffix=$versuffix_save
+ major=$major_save
+ release=$release_save
+ libname=$libname_save
+ name=$name_save
+
+ case $host in
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # On Rhapsody replace the C library is the System framework
+ newdeplibs=`$echo "X $newdeplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ ;;
+ esac
+
+ if test "$droppeddeps" = yes; then
+ if test "$module" = yes; then
+ $echo
+ $echo "*** Warning: libtool could not satisfy all declared inter-library"
+ $echo "*** dependencies of module $libname. Therefore, libtool will create"
+ $echo "*** a static module, that should work as long as the dlopening"
+ $echo "*** application is linked with the -dlopen flag."
+ if test -z "$global_symbol_pipe"; then
+ $echo
+ $echo "*** However, this would only work if libtool was able to extract symbol"
+ $echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+ $echo "*** not find such a program. So, this module is probably useless."
+ $echo "*** \`nm' from GNU binutils and a full rebuild may help."
+ fi
+ if test "$build_old_libs" = no; then
+ oldlibs="$output_objdir/$libname.$libext"
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ else
+ $echo "*** The inter-library dependencies that have been dropped here will be"
+ $echo "*** automatically added whenever a program is linked with this library"
+ $echo "*** or is declared to -dlopen it."
+
+ if test "$allow_undefined" = no; then
+ $echo
+ $echo "*** Since this library must not contain undefined symbols,"
+ $echo "*** because either the platform does not support them or"
+ $echo "*** it was explicitly requested with -no-undefined,"
+ $echo "*** libtool will only create a static version of it."
+ if test "$build_old_libs" = no; then
+ oldlibs="$output_objdir/$libname.$libext"
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ fi
+ fi
+ fi
+ # Done checking deplibs!
+ deplibs=$newdeplibs
+ fi
+
+
+ # move library search paths that coincide with paths to not yet
+ # installed libraries to the beginning of the library search list
+ new_libs=
+ for path in $notinst_path; do
+ case " $new_libs " in
+ *" -L$path/$objdir "*) ;;
+ *)
+ case " $deplibs " in
+ *" -L$path/$objdir "*)
+ new_libs="$new_libs -L$path/$objdir" ;;
+ esac
+ ;;
+ esac
+ done
+ for deplib in $deplibs; do
+ case $deplib in
+ -L*)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ done
+ deplibs="$new_libs"
+
+
+ # All the library-specific variables (install_libdir is set above).
+ library_names=
+ old_library=
+ dlname=
+
+ # Test again, we may have decided not to build it any more
+ if test "$build_libtool_libs" = yes; then
+ if test "$hardcode_into_libs" = yes; then
+ # Hardcode the library paths
+ hardcode_libdirs=
+ dep_rpath=
+ rpath="$finalize_rpath"
+ test "$mode" != relink && rpath="$compile_rpath$rpath"
+ for libdir in $rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ dep_rpath="$dep_rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+ *) perm_rpath="$perm_rpath $libdir" ;;
+ esac
+ fi
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ if test -n "$hardcode_libdir_flag_spec_ld"; then
+ eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\"
+ else
+ eval dep_rpath=\"$hardcode_libdir_flag_spec\"
+ fi
+ fi
+ if test -n "$runpath_var" && test -n "$perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
+ fi
+ test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
+ fi
+
+ shlibpath="$finalize_shlibpath"
+ test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+ if test -n "$shlibpath"; then
+ eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
+ fi
+
+ # Get the real and link names of the library.
+ eval shared_ext=\"$shrext_cmds\"
+ eval library_names=\"$library_names_spec\"
+ set dummy $library_names
+ realname="$2"
+ shift; shift
+
+ if test -n "$soname_spec"; then
+ eval soname=\"$soname_spec\"
+ else
+ soname="$realname"
+ fi
+ if test -z "$dlname"; then
+ dlname=$soname
+ fi
+
+ lib="$output_objdir/$realname"
+ linknames=
+ for link
+ do
+ linknames="$linknames $link"
+ done
+
+ # Use standard objects if they are pic
+ test -z "$pic_flag" && libobjs=`$echo "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+
+ # Prepare the list of exported symbols
+ if test -z "$export_symbols"; then
+ if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
+ $show "generating symbol list for \`$libname.la'"
+ export_symbols="$output_objdir/$libname.exp"
+ $run $rm $export_symbols
+ cmds=$export_symbols_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ if len=`expr "X$cmd" : ".*"` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ skipped_export=false
+ else
+ # The command line is too long to execute in one step.
+ $show "using reloadable object file for export list..."
+ skipped_export=:
+ # Break out early, otherwise skipped_export may be
+ # set to false by a later but shorter cmd.
+ break
+ fi
+ done
+ IFS="$save_ifs"
+ if test -n "$export_symbols_regex"; then
+ $show "$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\""
+ $run eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+ $show "$mv \"${export_symbols}T\" \"$export_symbols\""
+ $run eval '$mv "${export_symbols}T" "$export_symbols"'
+ fi
+ fi
+ fi
+
+ if test -n "$export_symbols" && test -n "$include_expsyms"; then
+ $run eval '$echo "X$include_expsyms" | $SP2NL >> "$export_symbols"'
+ fi
+
+ tmp_deplibs=
+ for test_deplib in $deplibs; do
+ case " $convenience " in
+ *" $test_deplib "*) ;;
+ *)
+ tmp_deplibs="$tmp_deplibs $test_deplib"
+ ;;
+ esac
+ done
+ deplibs="$tmp_deplibs"
+
+ if test -n "$convenience"; then
+ if test -n "$whole_archive_flag_spec"; then
+ save_libobjs=$libobjs
+ eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+ else
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $convenience
+ libobjs="$libobjs $func_extract_archives_result"
+ fi
+ fi
+
+ if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
+ eval flag=\"$thread_safe_flag_spec\"
+ linker_flags="$linker_flags $flag"
+ fi
+
+ # Make a backup of the uninstalled library when relinking
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}U && $mv $realname ${realname}U)' || exit $?
+ fi
+
+ # Do each of the archive commands.
+ if test "$module" = yes && test -n "$module_cmds" ; then
+ if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+ eval test_cmds=\"$module_expsym_cmds\"
+ cmds=$module_expsym_cmds
+ else
+ eval test_cmds=\"$module_cmds\"
+ cmds=$module_cmds
+ fi
+ else
+ if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+ eval test_cmds=\"$archive_expsym_cmds\"
+ cmds=$archive_expsym_cmds
+ else
+ eval test_cmds=\"$archive_cmds\"
+ cmds=$archive_cmds
+ fi
+ fi
+
+ if test "X$skipped_export" != "X:" &&
+ len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ :
+ else
+ # The command line is too long to link in one step, link piecewise.
+ $echo "creating reloadable object files..."
+
+ # Save the value of $output and $libobjs because we want to
+ # use them later. If we have whole_archive_flag_spec, we
+ # want to use save_libobjs as it was before
+ # whole_archive_flag_spec was expanded, because we can't
+ # assume the linker understands whole_archive_flag_spec.
+ # This may have to be revisited, in case too many
+ # convenience libraries get linked in and end up exceeding
+ # the spec.
+ if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
+ save_libobjs=$libobjs
+ fi
+ save_output=$output
+ output_la=`$echo "X$output" | $Xsed -e "$basename"`
+
+ # Clear the reloadable object creation command queue and
+ # initialize k to one.
+ test_cmds=
+ concat_cmds=
+ objlist=
+ delfiles=
+ last_robj=
+ k=1
+ output=$output_objdir/$output_la-${k}.$objext
+ # Loop over the list of objects to be linked.
+ for obj in $save_libobjs
+ do
+ eval test_cmds=\"$reload_cmds $objlist $last_robj\"
+ if test "X$objlist" = X ||
+ { len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len"; }; then
+ objlist="$objlist $obj"
+ else
+ # The command $test_cmds is almost too long, add a
+ # command to the queue.
+ if test "$k" -eq 1 ; then
+ # The first file doesn't have a previous command to add.
+ eval concat_cmds=\"$reload_cmds $objlist $last_robj\"
+ else
+ # All subsequent reloadable object files will link in
+ # the last one created.
+ eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj\"
+ fi
+ last_robj=$output_objdir/$output_la-${k}.$objext
+ k=`expr $k + 1`
+ output=$output_objdir/$output_la-${k}.$objext
+ objlist=$obj
+ len=1
+ fi
+ done
+ # Handle the remaining objects by creating one last
+ # reloadable object file. All subsequent reloadable object
+ # files will link in the last one created.
+ test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+ eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
+
+ if ${skipped_export-false}; then
+ $show "generating symbol list for \`$libname.la'"
+ export_symbols="$output_objdir/$libname.exp"
+ $run $rm $export_symbols
+ libobjs=$output
+ # Append the command to create the export file.
+ eval concat_cmds=\"\$concat_cmds~$export_symbols_cmds\"
+ fi
+
+ # Set up a command to remove the reloadable object files
+ # after they are used.
+ i=0
+ while test "$i" -lt "$k"
+ do
+ i=`expr $i + 1`
+ delfiles="$delfiles $output_objdir/$output_la-${i}.$objext"
+ done
+
+ $echo "creating a temporary reloadable object file: $output"
+
+ # Loop through the commands generated above and execute them.
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $concat_cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+
+ libobjs=$output
+ # Restore the value of output.
+ output=$save_output
+
+ if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
+ eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+ fi
+ # Expand the library linking commands again to reset the
+ # value of $libobjs for piecewise linking.
+
+ # Do each of the archive commands.
+ if test "$module" = yes && test -n "$module_cmds" ; then
+ if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+ cmds=$module_expsym_cmds
+ else
+ cmds=$module_cmds
+ fi
+ else
+ if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+ cmds=$archive_expsym_cmds
+ else
+ cmds=$archive_cmds
+ fi
+ fi
+
+ # Append the command to remove the reloadable object files
+ # to the just-reset $cmds.
+ eval cmds=\"\$cmds~\$rm $delfiles\"
+ fi
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || {
+ lt_exit=$?
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
+ fi
+
+ exit $lt_exit
+ }
+ done
+ IFS="$save_ifs"
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${realname}T && $mv "$realname"U $realname)' || exit $?
+
+ if test -n "$convenience"; then
+ if test -z "$whole_archive_flag_spec"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r "$gentop"
+ fi
+ fi
+
+ exit $EXIT_SUCCESS
+ fi
+
+ # Create links to the real library.
+ for linkname in $linknames; do
+ if test "$realname" != "$linkname"; then
+ $show "(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)"
+ $run eval '(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)' || exit $?
+ fi
+ done
+
+ # If -module or -export-dynamic was specified, set the dlname.
+ if test "$module" = yes || test "$export_dynamic" = yes; then
+ # On all known operating systems, these are identical.
+ dlname="$soname"
+ fi
+ fi
+ ;;
+
+ obj)
+ if test -n "$deplibs"; then
+ $echo "$modename: warning: \`-l' and \`-L' are ignored for objects" 1>&2
+ fi
+
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$rpath"; then
+ $echo "$modename: warning: \`-rpath' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$xrpath"; then
+ $echo "$modename: warning: \`-R' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for objects" 1>&2
+ fi
+
+ case $output in
+ *.lo)
+ if test -n "$objs$old_deplibs"; then
+ $echo "$modename: cannot build library object \`$output' from non-libtool objects" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ libobj="$output"
+ obj=`$echo "X$output" | $Xsed -e "$lo2o"`
+ ;;
+ *)
+ libobj=
+ obj="$output"
+ ;;
+ esac
+
+ # Delete the old objects.
+ $run $rm $obj $libobj
+
+ # Objects from convenience libraries. This assumes
+ # single-version convenience libraries. Whenever we create
+ # different ones for PIC/non-PIC, this we'll have to duplicate
+ # the extraction.
+ reload_conv_objs=
+ gentop=
+ # reload_cmds runs $LD directly, so let us get rid of
+ # -Wl from whole_archive_flag_spec
+ wl=
+
+ if test -n "$convenience"; then
+ if test -n "$whole_archive_flag_spec"; then
+ eval reload_conv_objs=\"\$reload_objs $whole_archive_flag_spec\"
+ else
+ gentop="$output_objdir/${obj}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $convenience
+ reload_conv_objs="$reload_objs $func_extract_archives_result"
+ fi
+ fi
+
+ # Create the old-style object.
+ reload_objs="$objs$old_deplibs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+
+ output="$obj"
+ cmds=$reload_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+
+ # Exit if we aren't doing a library object file.
+ if test -z "$libobj"; then
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ exit $EXIT_SUCCESS
+ fi
+
+ if test "$build_libtool_libs" != yes; then
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ # Create an invalid libtool object if no PIC, so that we don't
+ # accidentally link it into a program.
+ # $show "echo timestamp > $libobj"
+ # $run eval "echo timestamp > $libobj" || exit $?
+ exit $EXIT_SUCCESS
+ fi
+
+ if test -n "$pic_flag" || test "$pic_mode" != default; then
+ # Only do commands if we really have different PIC objects.
+ reload_objs="$libobjs $reload_conv_objs"
+ output="$libobj"
+ cmds=$reload_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ exit $EXIT_SUCCESS
+ ;;
+
+ prog)
+ case $host in
+ *cygwin*) output=`$echo $output | ${SED} -e 's,.exe$,,;s,$,.exe,'` ;;
+ esac
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info' is ignored for programs" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for programs" 1>&2
+ fi
+
+ if test "$preload" = yes; then
+ if test "$dlopen_support" = unknown && test "$dlopen_self" = unknown &&
+ test "$dlopen_self_static" = unknown; then
+ $echo "$modename: warning: \`AC_LIBTOOL_DLOPEN' not used. Assuming no dlopen support."
+ fi
+ fi
+
+ case $host in
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # On Rhapsody replace the C library is the System framework
+ compile_deplibs=`$echo "X $compile_deplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ finalize_deplibs=`$echo "X $finalize_deplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ ;;
+ esac
+
+ case $host in
+ *darwin*)
+ # Don't allow lazy linking, it breaks C++ global constructors
+ if test "$tagname" = CXX ; then
+ compile_command="$compile_command ${wl}-bind_at_load"
+ finalize_command="$finalize_command ${wl}-bind_at_load"
+ fi
+ ;;
+ esac
+
+
+ # move library search paths that coincide with paths to not yet
+ # installed libraries to the beginning of the library search list
+ new_libs=
+ for path in $notinst_path; do
+ case " $new_libs " in
+ *" -L$path/$objdir "*) ;;
+ *)
+ case " $compile_deplibs " in
+ *" -L$path/$objdir "*)
+ new_libs="$new_libs -L$path/$objdir" ;;
+ esac
+ ;;
+ esac
+ done
+ for deplib in $compile_deplibs; do
+ case $deplib in
+ -L*)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ done
+ compile_deplibs="$new_libs"
+
+
+ compile_command="$compile_command $compile_deplibs"
+ finalize_command="$finalize_command $finalize_deplibs"
+
+ if test -n "$rpath$xrpath"; then
+ # If the user specified any rpath flags, then add them.
+ for libdir in $rpath $xrpath; do
+ # This is the magic to use -rpath.
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir" ;;
+ esac
+ done
+ fi
+
+ # Now hardcode the library paths
+ rpath=
+ hardcode_libdirs=
+ for libdir in $compile_rpath $finalize_rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ rpath="$rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+ *) perm_rpath="$perm_rpath $libdir" ;;
+ esac
+ fi
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ testbindir=`$echo "X$libdir" | $Xsed -e 's*/lib$*/bin*'`
+ case :$dllsearchpath: in
+ *":$libdir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$libdir";;
+ esac
+ case :$dllsearchpath: in
+ *":$testbindir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$testbindir";;
+ esac
+ ;;
+ esac
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ eval rpath=\" $hardcode_libdir_flag_spec\"
+ fi
+ compile_rpath="$rpath"
+
+ rpath=
+ hardcode_libdirs=
+ for libdir in $finalize_rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ rpath="$rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$finalize_perm_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;;
+ esac
+ fi
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ eval rpath=\" $hardcode_libdir_flag_spec\"
+ fi
+ finalize_rpath="$rpath"
+
+ if test -n "$libobjs" && test "$build_old_libs" = yes; then
+ # Transform all the library objects into standard objects.
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ fi
+
+ dlsyms=
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ if test -n "$NM" && test -n "$global_symbol_pipe"; then
+ dlsyms="${outputname}S.c"
+ else
+ $echo "$modename: not configured to extract global symbols from dlpreopened files" 1>&2
+ fi
+ fi
+
+ if test -n "$dlsyms"; then
+ case $dlsyms in
+ "") ;;
+ *.c)
+ # Discover the nlist of each of the dlfiles.
+ nlist="$output_objdir/${outputname}.nm"
+
+ $show "$rm $nlist ${nlist}S ${nlist}T"
+ $run $rm "$nlist" "${nlist}S" "${nlist}T"
+
+ # Parse the name list into a source file.
+ $show "creating $output_objdir/$dlsyms"
+
+ test -z "$run" && $echo > "$output_objdir/$dlsyms" "\
+/* $dlsyms - symbol resolution table for \`$outputname' dlsym emulation. */
+/* Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP */
+
+#ifdef __cplusplus
+extern \"C\" {
+#endif
+
+/* Prevent the only kind of declaration conflicts we can make. */
+#define lt_preloaded_symbols some_other_symbol
+
+/* External symbol declarations for the compiler. */\
+"
+
+ if test "$dlself" = yes; then
+ $show "generating symbol list for \`$output'"
+
+ test -z "$run" && $echo ': @PROGRAM@ ' > "$nlist"
+
+ # Add our own program objects to the symbol list.
+ progfiles=`$echo "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ for arg in $progfiles; do
+ $show "extracting global C symbols from \`$arg'"
+ $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
+ done
+
+ if test -n "$exclude_expsyms"; then
+ $run eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
+ $run eval '$mv "$nlist"T "$nlist"'
+ fi
+
+ if test -n "$export_symbols_regex"; then
+ $run eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
+ $run eval '$mv "$nlist"T "$nlist"'
+ fi
+
+ # Prepare the list of exported symbols
+ if test -z "$export_symbols"; then
+ export_symbols="$output_objdir/$outputname.exp"
+ $run $rm $export_symbols
+ $run eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+ case $host in
+ *cygwin* | *mingw* )
+ $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+ $run eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+ ;;
+ esac
+ else
+ $run eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
+ $run eval 'grep -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
+ $run eval 'mv "$nlist"T "$nlist"'
+ case $host in
+ *cygwin* | *mingw* )
+ $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+ $run eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+ ;;
+ esac
+ fi
+ fi
+
+ for arg in $dlprefiles; do
+ $show "extracting global C symbols from \`$arg'"
+ name=`$echo "$arg" | ${SED} -e 's%^.*/%%'`
+ $run eval '$echo ": $name " >> "$nlist"'
+ $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
+ done
+
+ if test -z "$run"; then
+ # Make sure we have at least an empty file.
+ test -f "$nlist" || : > "$nlist"
+
+ if test -n "$exclude_expsyms"; then
+ $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
+ $mv "$nlist"T "$nlist"
+ fi
+
+ # Try sorting and uniquifying the output.
+ if grep -v "^: " < "$nlist" |
+ if sort -k 3 </dev/null >/dev/null 2>&1; then
+ sort -k 3
+ else
+ sort +2
+ fi |
+ uniq > "$nlist"S; then
+ :
+ else
+ grep -v "^: " < "$nlist" > "$nlist"S
+ fi
+
+ if test -f "$nlist"S; then
+ eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$dlsyms"'
+ else
+ $echo '/* NONE */' >> "$output_objdir/$dlsyms"
+ fi
+
+ $echo >> "$output_objdir/$dlsyms" "\
+
+#undef lt_preloaded_symbols
+
+#if defined (__STDC__) && __STDC__
+# define lt_ptr void *
+#else
+# define lt_ptr char *
+# define const
+#endif
+
+/* The mapping between symbol names and symbols. */
+"
+
+ case $host in
+ *cygwin* | *mingw* )
+ $echo >> "$output_objdir/$dlsyms" "\
+/* DATA imports from DLLs on WIN32 can't be const, because
+ runtime relocations are performed -- see ld's documentation
+ on pseudo-relocs */
+struct {
+"
+ ;;
+ * )
+ $echo >> "$output_objdir/$dlsyms" "\
+const struct {
+"
+ ;;
+ esac
+
+
+ $echo >> "$output_objdir/$dlsyms" "\
+ const char *name;
+ lt_ptr address;
+}
+lt_preloaded_symbols[] =
+{\
+"
+
+ eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$dlsyms"
+
+ $echo >> "$output_objdir/$dlsyms" "\
+ {0, (lt_ptr) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+ return lt_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif\
+"
+ fi
+
+ pic_flag_for_symtable=
+ case $host in
+ # compiling the symbol table file with pic_flag works around
+ # a FreeBSD bug that causes programs to crash when -lm is
+ # linked before any other PIC object. But we must not use
+ # pic_flag when linking with -static. The problem exists in
+ # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
+ *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+ case "$compile_command " in
+ *" -static "*) ;;
+ *) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND";;
+ esac;;
+ *-*-hpux*)
+ case "$compile_command " in
+ *" -static "*) ;;
+ *) pic_flag_for_symtable=" $pic_flag";;
+ esac
+ esac
+
+ # Now compile the dynamic symbol file.
+ $show "(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")"
+ $run eval '(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $?
+
+ # Clean up the generated files.
+ $show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T"
+ $run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T"
+
+ # Transform the symbol file into the correct name.
+ case $host in
+ *cygwin* | *mingw* )
+ if test -f "$output_objdir/${outputname}.def" ; then
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"`
+ else
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+ fi
+ ;;
+ * )
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
+ ;;
+ esac
+ ;;
+ *)
+ $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ else
+ # We keep going just in case the user didn't refer to
+ # lt_preloaded_symbols. The linker will fail if global_symbol_pipe
+ # really was required.
+
+ # Nullify the symbol file.
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"`
+ fi
+
+ if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
+ # Replace the output file specification.
+ compile_command=`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+ link_command="$compile_command$compile_rpath"
+
+ # We have no uninstalled library dependencies, so finalize right now.
+ $show "$link_command"
+ $run eval "$link_command"
+ exit_status=$?
+
+ # Delete the generated files.
+ if test -n "$dlsyms"; then
+ $show "$rm $output_objdir/${outputname}S.${objext}"
+ $run $rm "$output_objdir/${outputname}S.${objext}"
+ fi
+
+ exit $exit_status
+ fi
+
+ if test -n "$shlibpath_var"; then
+ # We should set the shlibpath_var
+ rpath=
+ for dir in $temp_rpath; do
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*)
+ # Absolute path.
+ rpath="$rpath$dir:"
+ ;;
+ *)
+ # Relative path: add a thisdir entry.
+ rpath="$rpath\$thisdir/$dir:"
+ ;;
+ esac
+ done
+ temp_rpath="$rpath"
+ fi
+
+ if test -n "$compile_shlibpath$finalize_shlibpath"; then
+ compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
+ fi
+ if test -n "$finalize_shlibpath"; then
+ finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
+ fi
+
+ compile_var=
+ finalize_var=
+ if test -n "$runpath_var"; then
+ if test -n "$perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
+ fi
+ if test -n "$finalize_perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $finalize_perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
+ fi
+ fi
+
+ if test "$no_install" = yes; then
+ # We don't need to create a wrapper script.
+ link_command="$compile_var$compile_command$compile_rpath"
+ # Replace the output file specification.
+ link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+ # Delete the old output file.
+ $run $rm $output
+ # Link the executable and exit
+ $show "$link_command"
+ $run eval "$link_command" || exit $?
+ exit $EXIT_SUCCESS
+ fi
+
+ if test "$hardcode_action" = relink; then
+ # Fast installation is not supported
+ link_command="$compile_var$compile_command$compile_rpath"
+ relink_command="$finalize_var$finalize_command$finalize_rpath"
+
+ $echo "$modename: warning: this platform does not like uninstalled shared libraries" 1>&2
+ $echo "$modename: \`$output' will be relinked during installation" 1>&2
+ else
+ if test "$fast_install" != no; then
+ link_command="$finalize_var$compile_command$finalize_rpath"
+ if test "$fast_install" = yes; then
+ relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'`
+ else
+ # fast_install is set to needless
+ relink_command=
+ fi
+ else
+ link_command="$compile_var$compile_command$compile_rpath"
+ relink_command="$finalize_var$finalize_command$finalize_rpath"
+ fi
+ fi
+
+ # Replace the output file specification.
+ link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
+
+ # Delete the old output files.
+ $run $rm $output $output_objdir/$outputname $output_objdir/lt-$outputname
+
+ $show "$link_command"
+ $run eval "$link_command" || exit $?
+
+ # Now create the wrapper script.
+ $show "creating $output"
+
+ # Quote the relink command for shipping.
+ if test -n "$relink_command"; then
+ # Preserve any variables that may affect compiler behavior
+ for var in $variables_saved_for_relink; do
+ if eval test -z \"\${$var+set}\"; then
+ relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command"
+ elif eval var_value=\$$var; test -z "$var_value"; then
+ relink_command="$var=; export $var; $relink_command"
+ else
+ var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
+ relink_command="$var=\"$var_value\"; export $var; $relink_command"
+ fi
+ done
+ relink_command="(cd `pwd`; $relink_command)"
+ relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"`
+ fi
+
+ # Quote $echo for shipping.
+ if test "X$echo" = "X$SHELL $progpath --fallback-echo"; then
+ case $progpath in
+ [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";;
+ *) qecho="$SHELL `pwd`/$progpath --fallback-echo";;
+ esac
+ qecho=`$echo "X$qecho" | $Xsed -e "$sed_quote_subst"`
+ else
+ qecho=`$echo "X$echo" | $Xsed -e "$sed_quote_subst"`
+ fi
+
+ # Only actually do things if our run command is non-null.
+ if test -z "$run"; then
+ # win32 will think the script is a binary if it has
+ # a .exe suffix, so we strip it off here.
+ case $output in
+ *.exe) output=`$echo $output|${SED} 's,.exe$,,'` ;;
+ esac
+ # test for cygwin because mv fails w/o .exe extensions
+ case $host in
+ *cygwin*)
+ exeext=.exe
+ outputname=`$echo $outputname|${SED} 's,.exe$,,'` ;;
+ *) exeext= ;;
+ esac
+ case $host in
+ *cygwin* | *mingw* )
+ output_name=`basename $output`
+ output_path=`dirname $output`
+ cwrappersource="$output_path/$objdir/lt-$output_name.c"
+ cwrapper="$output_path/$output_name.exe"
+ $rm $cwrappersource $cwrapper
+ trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
+
+ cat > $cwrappersource <<EOF
+
+/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
+ Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+
+ The $output program cannot be directly executed until all the libtool
+ libraries that it depends on are installed.
+
+ This wrapper executable should never be moved out of the build directory.
+ If it is, it will not operate correctly.
+
+ Currently, it simply execs the wrapper *script* "/bin/sh $output",
+ but could eventually absorb all of the scripts functionality and
+ exec $objdir/$outputname directly.
+*/
+EOF
+ cat >> $cwrappersource<<"EOF"
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <malloc.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <sys/stat.h>
+
+#if defined(PATH_MAX)
+# define LT_PATHMAX PATH_MAX
+#elif defined(MAXPATHLEN)
+# define LT_PATHMAX MAXPATHLEN
+#else
+# define LT_PATHMAX 1024
+#endif
+
+#ifndef DIR_SEPARATOR
+# define DIR_SEPARATOR '/'
+# define PATH_SEPARATOR ':'
+#endif
+
+#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
+ defined (__OS2__)
+# define HAVE_DOS_BASED_FILE_SYSTEM
+# ifndef DIR_SEPARATOR_2
+# define DIR_SEPARATOR_2 '\\'
+# endif
+# ifndef PATH_SEPARATOR_2
+# define PATH_SEPARATOR_2 ';'
+# endif
+#endif
+
+#ifndef DIR_SEPARATOR_2
+# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
+#else /* DIR_SEPARATOR_2 */
+# define IS_DIR_SEPARATOR(ch) \
+ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
+#endif /* DIR_SEPARATOR_2 */
+
+#ifndef PATH_SEPARATOR_2
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
+#else /* PATH_SEPARATOR_2 */
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
+#endif /* PATH_SEPARATOR_2 */
+
+#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type)))
+#define XFREE(stale) do { \
+ if (stale) { free ((void *) stale); stale = 0; } \
+} while (0)
+
+/* -DDEBUG is fairly common in CFLAGS. */
+#undef DEBUG
+#if defined DEBUGWRAPPER
+# define DEBUG(format, ...) fprintf(stderr, format, __VA_ARGS__)
+#else
+# define DEBUG(format, ...)
+#endif
+
+const char *program_name = NULL;
+
+void * xmalloc (size_t num);
+char * xstrdup (const char *string);
+const char * base_name (const char *name);
+char * find_executable(const char *wrapper);
+int check_executable(const char *path);
+char * strendzap(char *str, const char *pat);
+void lt_fatal (const char *message, ...);
+
+int
+main (int argc, char *argv[])
+{
+ char **newargz;
+ int i;
+
+ program_name = (char *) xstrdup (base_name (argv[0]));
+ DEBUG("(main) argv[0] : %s\n",argv[0]);
+ DEBUG("(main) program_name : %s\n",program_name);
+ newargz = XMALLOC(char *, argc+2);
+EOF
+
+ cat >> $cwrappersource <<EOF
+ newargz[0] = (char *) xstrdup("$SHELL");
+EOF
+
+ cat >> $cwrappersource <<"EOF"
+ newargz[1] = find_executable(argv[0]);
+ if (newargz[1] == NULL)
+ lt_fatal("Couldn't find %s", argv[0]);
+ DEBUG("(main) found exe at : %s\n",newargz[1]);
+ /* we know the script has the same name, without the .exe */
+ /* so make sure newargz[1] doesn't end in .exe */
+ strendzap(newargz[1],".exe");
+ for (i = 1; i < argc; i++)
+ newargz[i+1] = xstrdup(argv[i]);
+ newargz[argc+1] = NULL;
+
+ for (i=0; i<argc+1; i++)
+ {
+ DEBUG("(main) newargz[%d] : %s\n",i,newargz[i]);
+ ;
+ }
+
+EOF
+
+ case $host_os in
+ mingw*)
+ cat >> $cwrappersource <<EOF
+ execv("$SHELL",(char const **)newargz);
+EOF
+ ;;
+ *)
+ cat >> $cwrappersource <<EOF
+ execv("$SHELL",newargz);
+EOF
+ ;;
+ esac
+
+ cat >> $cwrappersource <<"EOF"
+ return 127;
+}
+
+void *
+xmalloc (size_t num)
+{
+ void * p = (void *) malloc (num);
+ if (!p)
+ lt_fatal ("Memory exhausted");
+
+ return p;
+}
+
+char *
+xstrdup (const char *string)
+{
+ return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL
+;
+}
+
+const char *
+base_name (const char *name)
+{
+ const char *base;
+
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ /* Skip over the disk name in MSDOS pathnames. */
+ if (isalpha ((unsigned char)name[0]) && name[1] == ':')
+ name += 2;
+#endif
+
+ for (base = name; *name; name++)
+ if (IS_DIR_SEPARATOR (*name))
+ base = name + 1;
+ return base;
+}
+
+int
+check_executable(const char * path)
+{
+ struct stat st;
+
+ DEBUG("(check_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!");
+ if ((!path) || (!*path))
+ return 0;
+
+ if ((stat (path, &st) >= 0) &&
+ (
+ /* MinGW & native WIN32 do not support S_IXOTH or S_IXGRP */
+#if defined (S_IXOTH)
+ ((st.st_mode & S_IXOTH) == S_IXOTH) ||
+#endif
+#if defined (S_IXGRP)
+ ((st.st_mode & S_IXGRP) == S_IXGRP) ||
+#endif
+ ((st.st_mode & S_IXUSR) == S_IXUSR))
+ )
+ return 1;
+ else
+ return 0;
+}
+
+/* Searches for the full path of the wrapper. Returns
+ newly allocated full path name if found, NULL otherwise */
+char *
+find_executable (const char* wrapper)
+{
+ int has_slash = 0;
+ const char* p;
+ const char* p_next;
+ /* static buffer for getcwd */
+ char tmp[LT_PATHMAX + 1];
+ int tmp_len;
+ char* concat_name;
+
+ DEBUG("(find_executable) : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!");
+
+ if ((wrapper == NULL) || (*wrapper == '\0'))
+ return NULL;
+
+ /* Absolute path? */
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ if (isalpha ((unsigned char)wrapper[0]) && wrapper[1] == ':')
+ {
+ concat_name = xstrdup (wrapper);
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+ else
+ {
+#endif
+ if (IS_DIR_SEPARATOR (wrapper[0]))
+ {
+ concat_name = xstrdup (wrapper);
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ }
+#endif
+
+ for (p = wrapper; *p; p++)
+ if (*p == '/')
+ {
+ has_slash = 1;
+ break;
+ }
+ if (!has_slash)
+ {
+ /* no slashes; search PATH */
+ const char* path = getenv ("PATH");
+ if (path != NULL)
+ {
+ for (p = path; *p; p = p_next)
+ {
+ const char* q;
+ size_t p_len;
+ for (q = p; *q; q++)
+ if (IS_PATH_SEPARATOR(*q))
+ break;
+ p_len = q - p;
+ p_next = (*q == '\0' ? q : q + 1);
+ if (p_len == 0)
+ {
+ /* empty path: current directory */
+ if (getcwd (tmp, LT_PATHMAX) == NULL)
+ lt_fatal ("getcwd failed");
+ tmp_len = strlen(tmp);
+ concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, tmp, tmp_len);
+ concat_name[tmp_len] = '/';
+ strcpy (concat_name + tmp_len + 1, wrapper);
+ }
+ else
+ {
+ concat_name = XMALLOC(char, p_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, p, p_len);
+ concat_name[p_len] = '/';
+ strcpy (concat_name + p_len + 1, wrapper);
+ }
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+ }
+ /* not found in PATH; assume curdir */
+ }
+ /* Relative path | not found in path: prepend cwd */
+ if (getcwd (tmp, LT_PATHMAX) == NULL)
+ lt_fatal ("getcwd failed");
+ tmp_len = strlen(tmp);
+ concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, tmp, tmp_len);
+ concat_name[tmp_len] = '/';
+ strcpy (concat_name + tmp_len + 1, wrapper);
+
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ return NULL;
+}
+
+char *
+strendzap(char *str, const char *pat)
+{
+ size_t len, patlen;
+
+ assert(str != NULL);
+ assert(pat != NULL);
+
+ len = strlen(str);
+ patlen = strlen(pat);
+
+ if (patlen <= len)
+ {
+ str += len - patlen;
+ if (strcmp(str, pat) == 0)
+ *str = '\0';
+ }
+ return str;
+}
+
+static void
+lt_error_core (int exit_status, const char * mode,
+ const char * message, va_list ap)
+{
+ fprintf (stderr, "%s: %s: ", program_name, mode);
+ vfprintf (stderr, message, ap);
+ fprintf (stderr, ".\n");
+
+ if (exit_status >= 0)
+ exit (exit_status);
+}
+
+void
+lt_fatal (const char *message, ...)
+{
+ va_list ap;
+ va_start (ap, message);
+ lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
+ va_end (ap);
+}
+EOF
+ # we should really use a build-platform specific compiler
+ # here, but OTOH, the wrappers (shell script and this C one)
+ # are only useful if you want to execute the "real" binary.
+ # Since the "real" binary is built for $host, then this
+ # wrapper might as well be built for $host, too.
+ $run $LTCC $LTCFLAGS -s -o $cwrapper $cwrappersource
+ ;;
+ esac
+ $rm $output
+ trap "$rm $output; exit $EXIT_FAILURE" 1 2 15
+
+ $echo > $output "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='${SED} -e 1s/^X//'
+sed_quote_subst='$sed_quote_subst'
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+ # install mode needs the following variable:
+ notinst_deplibs='$notinst_deplibs'
+else
+ # When we are sourced in execute mode, \$file and \$echo are already set.
+ if test \"\$libtool_execute_magic\" != \"$magic\"; then
+ echo=\"$qecho\"
+ file=\"\$0\"
+ # Make sure echo works.
+ if test \"X\$1\" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+ elif test \"X\`(\$echo '\t') 2>/dev/null\`\" = 'X\t'; then
+ # Yippee, \$echo works!
+ :
+ else
+ # Restart under the correct shell, and then maybe \$echo will work.
+ exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
+ fi
+ fi\
+"
+ $echo >> $output "\
+
+ # Find the directory that this script lives in.
+ thisdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
+ test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+ # Follow symbolic links until we get to the real thisdir.
+ file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
+ while test -n \"\$file\"; do
+ destdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
+
+ # If there was a directory component, then change thisdir.
+ if test \"x\$destdir\" != \"x\$file\"; then
+ case \"\$destdir\" in
+ [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+ *) thisdir=\"\$thisdir/\$destdir\" ;;
+ esac
+ fi
+
+ file=\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
+ file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
+ done
+
+ # Try to get the absolute directory name.
+ absdir=\`cd \"\$thisdir\" && pwd\`
+ test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+ if test "$fast_install" = yes; then
+ $echo >> $output "\
+ program=lt-'$outputname'$exeext
+ progdir=\"\$thisdir/$objdir\"
+
+ if test ! -f \"\$progdir/\$program\" || \\
+ { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+ test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+ file=\"\$\$-\$program\"
+
+ if test ! -d \"\$progdir\"; then
+ $mkdir \"\$progdir\"
+ else
+ $rm \"\$progdir/\$file\"
+ fi"
+
+ $echo >> $output "\
+
+ # relink executable if necessary
+ if test -n \"\$relink_command\"; then
+ if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+ else
+ $echo \"\$relink_command_output\" >&2
+ $rm \"\$progdir/\$file\"
+ exit $EXIT_FAILURE
+ fi
+ fi
+
+ $mv \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+ { $rm \"\$progdir/\$program\";
+ $mv \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+ $rm \"\$progdir/\$file\"
+ fi"
+ else
+ $echo >> $output "\
+ program='$outputname'
+ progdir=\"\$thisdir/$objdir\"
+"
+ fi
+
+ $echo >> $output "\
+
+ if test -f \"\$progdir/\$program\"; then"
+
+ # Export our shlibpath_var if we have one.
+ if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+ $echo >> $output "\
+ # Add our own library path to $shlibpath_var
+ $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+ # Some systems cannot cope with colon-terminated $shlibpath_var
+ # The second colon is a workaround for a bug in BeOS R4 sed
+ $shlibpath_var=\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\`
+
+ export $shlibpath_var
+"
+ fi
+
+ # fixup the dll searchpath if we need to.
+ if test -n "$dllsearchpath"; then
+ $echo >> $output "\
+ # Add the dll search path components to the executable PATH
+ PATH=$dllsearchpath:\$PATH
+"
+ fi
+
+ $echo >> $output "\
+ if test \"\$libtool_execute_magic\" != \"$magic\"; then
+ # Run the actual program with our arguments.
+"
+ case $host in
+ # Backslashes separate directories on plain windows
+ *-*-mingw | *-*-os2*)
+ $echo >> $output "\
+ exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+ ;;
+
+ *)
+ $echo >> $output "\
+ exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+ ;;
+ esac
+ $echo >> $output "\
+ \$echo \"\$0: cannot exec \$program \${1+\"\$@\"}\"
+ exit $EXIT_FAILURE
+ fi
+ else
+ # The program doesn't exist.
+ \$echo \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+ \$echo \"This script is just a wrapper for \$program.\" 1>&2
+ $echo \"See the $PACKAGE documentation for more information.\" 1>&2
+ exit $EXIT_FAILURE
+ fi
+fi\
+"
+ chmod +x $output
+ fi
+ exit $EXIT_SUCCESS
+ ;;
+ esac
+
+ # See if we need to build an old-fashioned archive.
+ for oldlib in $oldlibs; do
+
+ if test "$build_libtool_libs" = convenience; then
+ oldobjs="$libobjs_save"
+ addlibs="$convenience"
+ build_libtool_libs=no
+ else
+ if test "$build_libtool_libs" = module; then
+ oldobjs="$libobjs_save"
+ build_libtool_libs=no
+ else
+ oldobjs="$old_deplibs $non_pic_objects"
+ fi
+ addlibs="$old_convenience"
+ fi
+
+ if test -n "$addlibs"; then
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $addlibs
+ oldobjs="$oldobjs $func_extract_archives_result"
+ fi
+
+ # Do each command in the archive commands.
+ if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
+ cmds=$old_archive_from_new_cmds
+ else
+ # POSIX demands no paths to be encoded in archives. We have
+ # to avoid creating archives with duplicate basenames if we
+ # might have to extract them afterwards, e.g., when creating a
+ # static archive out of a convenience library, or when linking
+ # the entirety of a libtool archive into another (currently
+ # not supported by libtool).
+ if (for obj in $oldobjs
+ do
+ $echo "X$obj" | $Xsed -e 's%^.*/%%'
+ done | sort | sort -uc >/dev/null 2>&1); then
+ :
+ else
+ $echo "copying selected object files to avoid basename conflicts..."
+
+ if test -z "$gentop"; then
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ $show "${rm}r $gentop"
+ $run ${rm}r "$gentop"
+ $show "$mkdir $gentop"
+ $run $mkdir "$gentop"
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$gentop"; then
+ exit $exit_status
+ fi
+ fi
+
+ save_oldobjs=$oldobjs
+ oldobjs=
+ counter=1
+ for obj in $save_oldobjs
+ do
+ objbase=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
+ case " $oldobjs " in
+ " ") oldobjs=$obj ;;
+ *[\ /]"$objbase "*)
+ while :; do
+ # Make sure we don't pick an alternate name that also
+ # overlaps.
+ newobj=lt$counter-$objbase
+ counter=`expr $counter + 1`
+ case " $oldobjs " in
+ *[\ /]"$newobj "*) ;;
+ *) if test ! -f "$gentop/$newobj"; then break; fi ;;
+ esac
+ done
+ $show "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
+ $run ln "$obj" "$gentop/$newobj" ||
+ $run cp "$obj" "$gentop/$newobj"
+ oldobjs="$oldobjs $gentop/$newobj"
+ ;;
+ *) oldobjs="$oldobjs $obj" ;;
+ esac
+ done
+ fi
+
+ eval cmds=\"$old_archive_cmds\"
+
+ if len=`expr "X$cmds" : ".*"` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ cmds=$old_archive_cmds
+ else
+ # the command line is too long to link in one step, link in parts
+ $echo "using piecewise archive linking..."
+ save_RANLIB=$RANLIB
+ RANLIB=:
+ objlist=
+ concat_cmds=
+ save_oldobjs=$oldobjs
+
+ # Is there a better way of finding the last object in the list?
+ for obj in $save_oldobjs
+ do
+ last_oldobj=$obj
+ done
+ for obj in $save_oldobjs
+ do
+ oldobjs="$objlist $obj"
+ objlist="$objlist $obj"
+ eval test_cmds=\"$old_archive_cmds\"
+ if len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len"; then
+ :
+ else
+ # the above command should be used before it gets too long
+ oldobjs=$objlist
+ if test "$obj" = "$last_oldobj" ; then
+ RANLIB=$save_RANLIB
+ fi
+ test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
+ objlist=
+ fi
+ done
+ RANLIB=$save_RANLIB
+ oldobjs=$objlist
+ if test "X$oldobjs" = "X" ; then
+ eval cmds=\"\$concat_cmds\"
+ else
+ eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
+ fi
+ fi
+ fi
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ eval cmd=\"$cmd\"
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ done
+
+ if test -n "$generated"; then
+ $show "${rm}r$generated"
+ $run ${rm}r$generated
+ fi
+
+ # Now create the libtool archive.
+ case $output in
+ *.la)
+ old_library=
+ test "$build_old_libs" = yes && old_library="$libname.$libext"
+ $show "creating $output"
+
+ # Preserve any variables that may affect compiler behavior
+ for var in $variables_saved_for_relink; do
+ if eval test -z \"\${$var+set}\"; then
+ relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command"
+ elif eval var_value=\$$var; test -z "$var_value"; then
+ relink_command="$var=; export $var; $relink_command"
+ else
+ var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
+ relink_command="$var=\"$var_value\"; export $var; $relink_command"
+ fi
+ done
+ # Quote the link command for shipping.
+ relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
+ relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"`
+ if test "$hardcode_automatic" = yes ; then
+ relink_command=
+ fi
+
+
+ # Only create the output if not a dry run.
+ if test -z "$run"; then
+ for installed in no yes; do
+ if test "$installed" = yes; then
+ if test -z "$install_libdir"; then
+ break
+ fi
+ output="$output_objdir/$outputname"i
+ # Replace all uninstalled libtool libraries with the installed ones
+ newdependency_libs=
+ for deplib in $dependency_libs; do
+ case $deplib in
+ *.la)
+ name=`$echo "X$deplib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdependency_libs="$newdependency_libs $libdir/$name"
+ ;;
+ *) newdependency_libs="$newdependency_libs $deplib" ;;
+ esac
+ done
+ dependency_libs="$newdependency_libs"
+ newdlfiles=
+ for lib in $dlfiles; do
+ name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdlfiles="$newdlfiles $libdir/$name"
+ done
+ dlfiles="$newdlfiles"
+ newdlprefiles=
+ for lib in $dlprefiles; do
+ name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdlprefiles="$newdlprefiles $libdir/$name"
+ done
+ dlprefiles="$newdlprefiles"
+ else
+ newdlfiles=
+ for lib in $dlfiles; do
+ case $lib in
+ [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+ *) abs=`pwd`"/$lib" ;;
+ esac
+ newdlfiles="$newdlfiles $abs"
+ done
+ dlfiles="$newdlfiles"
+ newdlprefiles=
+ for lib in $dlprefiles; do
+ case $lib in
+ [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+ *) abs=`pwd`"/$lib" ;;
+ esac
+ newdlprefiles="$newdlprefiles $abs"
+ done
+ dlprefiles="$newdlprefiles"
+ fi
+ $rm $output
+ # place dlname in correct position for cygwin
+ tdlname=$dlname
+ case $host,$output,$installed,$module,$dlname in
+ *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;
+ esac
+ $echo > $output "\
+# $outputname - a libtool library file
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# The name that we can dlopen(3).
+dlname='$tdlname'
+
+# Names of this library.
+library_names='$library_names'
+
+# The name of the static archive.
+old_library='$old_library'
+
+# Libraries that this one depends upon.
+dependency_libs='$dependency_libs'
+
+# Version information for $libname.
+current=$current
+age=$age
+revision=$revision
+
+# Is this an already installed library?
+installed=$installed
+
+# Should we warn about portability when linking against -modules?
+shouldnotlink=$module
+
+# Files to dlopen/dlpreopen
+dlopen='$dlfiles'
+dlpreopen='$dlprefiles'
+
+# Directory that this library needs to be installed in:
+libdir='$install_libdir'"
+ if test "$installed" = no && test "$need_relink" = yes; then
+ $echo >> $output "\
+relink_command=\"$relink_command\""
+ fi
+ done
+ fi
+
+ # Do a symbolic link so that the libtool archive can be found in
+ # LD_LIBRARY_PATH before the program is installed.
+ $show "(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)"
+ $run eval '(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)' || exit $?
+ ;;
+ esac
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool install mode
+ install)
+ modename="$modename: install"
+
+ # There may be an optional sh(1) argument at the beginning of
+ # install_prog (especially on Windows NT).
+ if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
+ # Allow the use of GNU shtool's install command.
+ $echo "X$nonopt" | grep shtool > /dev/null; then
+ # Aesthetically quote it.
+ arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$arg "
+ arg="$1"
+ shift
+ else
+ install_prog=
+ arg=$nonopt
+ fi
+
+ # The real first argument should be the name of the installation program.
+ # Aesthetically quote it.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$install_prog$arg"
+
+ # We need to accept at least all the BSD install flags.
+ dest=
+ files=
+ opts=
+ prev=
+ install_type=
+ isdir=no
+ stripme=
+ for arg
+ do
+ if test -n "$dest"; then
+ files="$files $dest"
+ dest=$arg
+ continue
+ fi
+
+ case $arg in
+ -d) isdir=yes ;;
+ -f)
+ case " $install_prog " in
+ *[\\\ /]cp\ *) ;;
+ *) prev=$arg ;;
+ esac
+ ;;
+ -g | -m | -o) prev=$arg ;;
+ -s)
+ stripme=" -s"
+ continue
+ ;;
+ -*)
+ ;;
+ *)
+ # If the previous option needed an argument, then skip it.
+ if test -n "$prev"; then
+ prev=
+ else
+ dest=$arg
+ continue
+ fi
+ ;;
+ esac
+
+ # Aesthetically quote the argument.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$install_prog $arg"
+ done
+
+ if test -z "$install_prog"; then
+ $echo "$modename: you must specify an install program" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$prev"; then
+ $echo "$modename: the \`$prev' option requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -z "$files"; then
+ if test -z "$dest"; then
+ $echo "$modename: no file or destination specified" 1>&2
+ else
+ $echo "$modename: you must specify a destination" 1>&2
+ fi
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Strip any trailing slash from the destination.
+ dest=`$echo "X$dest" | $Xsed -e 's%/$%%'`
+
+ # Check to see that the destination is a directory.
+ test -d "$dest" && isdir=yes
+ if test "$isdir" = yes; then
+ destdir="$dest"
+ destname=
+ else
+ destdir=`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$destdir" = "X$dest" && destdir=.
+ destname=`$echo "X$dest" | $Xsed -e 's%^.*/%%'`
+
+ # Not a directory, so check to see that there is only one file specified.
+ set dummy $files
+ if test "$#" -gt 2; then
+ $echo "$modename: \`$dest' is not a directory" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ fi
+ case $destdir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ for file in $files; do
+ case $file in
+ *.lo) ;;
+ *)
+ $echo "$modename: \`$destdir' must be an absolute directory name" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ done
+ ;;
+ esac
+
+ # This variable tells wrapper scripts just to set variables rather
+ # than running their programs.
+ libtool_install_magic="$magic"
+
+ staticlibs=
+ future_libdirs=
+ current_libdirs=
+ for file in $files; do
+
+ # Do each installation.
+ case $file in
+ *.$libext)
+ # Do the static libraries later.
+ staticlibs="$staticlibs $file"
+ ;;
+
+ *.la)
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$file' is not a valid libtool archive" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ library_names=
+ old_library=
+ relink_command=
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Add the libdir to current_libdirs if it is the destination.
+ if test "X$destdir" = "X$libdir"; then
+ case "$current_libdirs " in
+ *" $libdir "*) ;;
+ *) current_libdirs="$current_libdirs $libdir" ;;
+ esac
+ else
+ # Note the libdir as a future libdir.
+ case "$future_libdirs " in
+ *" $libdir "*) ;;
+ *) future_libdirs="$future_libdirs $libdir" ;;
+ esac
+ fi
+
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/
+ test "X$dir" = "X$file/" && dir=
+ dir="$dir$objdir"
+
+ if test -n "$relink_command"; then
+ # Determine the prefix the user has applied to our future dir.
+ inst_prefix_dir=`$echo "$destdir" | $SED "s%$libdir\$%%"`
+
+ # Don't allow the user to place us outside of our expected
+ # location b/c this prevents finding dependent libraries that
+ # are installed to the same prefix.
+ # At present, this check doesn't affect windows .dll's that
+ # are installed into $libdir/../bin (currently, that works fine)
+ # but it's something to keep an eye on.
+ if test "$inst_prefix_dir" = "$destdir"; then
+ $echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$inst_prefix_dir"; then
+ # Stick the inst_prefix_dir data into the link command.
+ relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
+ else
+ relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
+ fi
+
+ $echo "$modename: warning: relinking \`$file'" 1>&2
+ $show "$relink_command"
+ if $run eval "$relink_command"; then :
+ else
+ $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ fi
+
+ # See the names of the shared library.
+ set dummy $library_names
+ if test -n "$2"; then
+ realname="$2"
+ shift
+ shift
+
+ srcname="$realname"
+ test -n "$relink_command" && srcname="$realname"T
+
+ # Install the shared library and build the symlinks.
+ $show "$install_prog $dir/$srcname $destdir/$realname"
+ $run eval "$install_prog $dir/$srcname $destdir/$realname" || exit $?
+ if test -n "$stripme" && test -n "$striplib"; then
+ $show "$striplib $destdir/$realname"
+ $run eval "$striplib $destdir/$realname" || exit $?
+ fi
+
+ if test "$#" -gt 0; then
+ # Delete the old symlinks, and create new ones.
+ # Try `ln -sf' first, because the `ln' binary might depend on
+ # the symlink we replace! Solaris /bin/ln does not understand -f,
+ # so we also need to try rm && ln -s.
+ for linkname
+ do
+ if test "$linkname" != "$realname"; then
+ $show "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
+ $run eval "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
+ fi
+ done
+ fi
+
+ # Do each command in the postinstall commands.
+ lib="$destdir/$realname"
+ cmds=$postinstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || {
+ lt_exit=$?
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
+ fi
+
+ exit $lt_exit
+ }
+ done
+ IFS="$save_ifs"
+ fi
+
+ # Install the pseudo-library for information purposes.
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ instname="$dir/$name"i
+ $show "$install_prog $instname $destdir/$name"
+ $run eval "$install_prog $instname $destdir/$name" || exit $?
+
+ # Maybe install the static library, too.
+ test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library"
+ ;;
+
+ *.lo)
+ # Install (i.e. copy) a libtool object.
+
+ # Figure out destination file name, if it wasn't already specified.
+ if test -n "$destname"; then
+ destfile="$destdir/$destname"
+ else
+ destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ destfile="$destdir/$destfile"
+ fi
+
+ # Deduce the name of the destination old-style object file.
+ case $destfile in
+ *.lo)
+ staticdest=`$echo "X$destfile" | $Xsed -e "$lo2o"`
+ ;;
+ *.$objext)
+ staticdest="$destfile"
+ destfile=
+ ;;
+ *)
+ $echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ # Install the libtool object if requested.
+ if test -n "$destfile"; then
+ $show "$install_prog $file $destfile"
+ $run eval "$install_prog $file $destfile" || exit $?
+ fi
+
+ # Install the old object if enabled.
+ if test "$build_old_libs" = yes; then
+ # Deduce the name of the old-style object file.
+ staticobj=`$echo "X$file" | $Xsed -e "$lo2o"`
+
+ $show "$install_prog $staticobj $staticdest"
+ $run eval "$install_prog \$staticobj \$staticdest" || exit $?
+ fi
+ exit $EXIT_SUCCESS
+ ;;
+
+ *)
+ # Figure out destination file name, if it wasn't already specified.
+ if test -n "$destname"; then
+ destfile="$destdir/$destname"
+ else
+ destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ destfile="$destdir/$destfile"
+ fi
+
+ # If the file is missing, and there is a .exe on the end, strip it
+ # because it is most likely a libtool script we actually want to
+ # install
+ stripped_ext=""
+ case $file in
+ *.exe)
+ if test ! -f "$file"; then
+ file=`$echo $file|${SED} 's,.exe$,,'`
+ stripped_ext=".exe"
+ fi
+ ;;
+ esac
+
+ # Do a test to see if this is really a libtool program.
+ case $host in
+ *cygwin*|*mingw*)
+ wrapper=`$echo $file | ${SED} -e 's,.exe$,,'`
+ ;;
+ *)
+ wrapper=$file
+ ;;
+ esac
+ if (${SED} -e '4q' $wrapper | grep "^# Generated by .*$PACKAGE")>/dev/null 2>&1; then
+ notinst_deplibs=
+ relink_command=
+
+ # Note that it is not necessary on cygwin/mingw to append a dot to
+ # foo even if both foo and FILE.exe exist: automatic-append-.exe
+ # behavior happens only for exec(3), not for open(2)! Also, sourcing
+ # `FILE.' does not work on cygwin managed mounts.
+ #
+ # If there is no directory component, then add one.
+ case $wrapper in
+ */* | *\\*) . ${wrapper} ;;
+ *) . ./${wrapper} ;;
+ esac
+
+ # Check the variables that should have been set.
+ if test -z "$notinst_deplibs"; then
+ $echo "$modename: invalid libtool wrapper script \`$wrapper'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ finalize=yes
+ for lib in $notinst_deplibs; do
+ # Check to see that each library is installed.
+ libdir=
+ if test -f "$lib"; then
+ # If there is no directory component, then add one.
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+ fi
+ libfile="$libdir/"`$echo "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test
+ if test -n "$libdir" && test ! -f "$libfile"; then
+ $echo "$modename: warning: \`$lib' has not been installed in \`$libdir'" 1>&2
+ finalize=no
+ fi
+ done
+
+ relink_command=
+ # Note that it is not necessary on cygwin/mingw to append a dot to
+ # foo even if both foo and FILE.exe exist: automatic-append-.exe
+ # behavior happens only for exec(3), not for open(2)! Also, sourcing
+ # `FILE.' does not work on cygwin managed mounts.
+ #
+ # If there is no directory component, then add one.
+ case $wrapper in
+ */* | *\\*) . ${wrapper} ;;
+ *) . ./${wrapper} ;;
+ esac
+
+ outputname=
+ if test "$fast_install" = no && test -n "$relink_command"; then
+ if test "$finalize" = yes && test -z "$run"; then
+ tmpdir=`func_mktempdir`
+ file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'`
+ outputname="$tmpdir/$file"
+ # Replace the output file specification.
+ relink_command=`$echo "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'`
+
+ $show "$relink_command"
+ if $run eval "$relink_command"; then :
+ else
+ $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
+ ${rm}r "$tmpdir"
+ continue
+ fi
+ file="$outputname"
+ else
+ $echo "$modename: warning: cannot relink \`$file'" 1>&2
+ fi
+ else
+ # Install the binary that we compiled earlier.
+ file=`$echo "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"`
+ fi
+ fi
+
+ # remove .exe since cygwin /usr/bin/install will append another
+ # one anyway
+ case $install_prog,$host in
+ */usr/bin/install*,*cygwin*)
+ case $file:$destfile in
+ *.exe:*.exe)
+ # this is ok
+ ;;
+ *.exe:*)
+ destfile=$destfile.exe
+ ;;
+ *:*.exe)
+ destfile=`$echo $destfile | ${SED} -e 's,.exe$,,'`
+ ;;
+ esac
+ ;;
+ esac
+ $show "$install_prog$stripme $file $destfile"
+ $run eval "$install_prog\$stripme \$file \$destfile" || exit $?
+ test -n "$outputname" && ${rm}r "$tmpdir"
+ ;;
+ esac
+ done
+
+ for file in $staticlibs; do
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+
+ # Set up the ranlib parameters.
+ oldlib="$destdir/$name"
+
+ $show "$install_prog $file $oldlib"
+ $run eval "$install_prog \$file \$oldlib" || exit $?
+
+ if test -n "$stripme" && test -n "$old_striplib"; then
+ $show "$old_striplib $oldlib"
+ $run eval "$old_striplib $oldlib" || exit $?
+ fi
+
+ # Do each command in the postinstall commands.
+ cmds=$old_postinstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ done
+
+ if test -n "$future_libdirs"; then
+ $echo "$modename: warning: remember to run \`$progname --finish$future_libdirs'" 1>&2
+ fi
+
+ if test -n "$current_libdirs"; then
+ # Maybe just do a dry run.
+ test -n "$run" && current_libdirs=" -n$current_libdirs"
+ exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
+ else
+ exit $EXIT_SUCCESS
+ fi
+ ;;
+
+ # libtool finish mode
+ finish)
+ modename="$modename: finish"
+ libdirs="$nonopt"
+ admincmds=
+
+ if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+ for dir
+ do
+ libdirs="$libdirs $dir"
+ done
+
+ for libdir in $libdirs; do
+ if test -n "$finish_cmds"; then
+ # Do each command in the finish commands.
+ cmds=$finish_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || admincmds="$admincmds
+ $cmd"
+ done
+ IFS="$save_ifs"
+ fi
+ if test -n "$finish_eval"; then
+ # Do the single finish_eval.
+ eval cmds=\"$finish_eval\"
+ $run eval "$cmds" || admincmds="$admincmds
+ $cmds"
+ fi
+ done
+ fi
+
+ # Exit here if they wanted silent mode.
+ test "$show" = : && exit $EXIT_SUCCESS
+
+ $echo "X----------------------------------------------------------------------" | $Xsed
+ $echo "Libraries have been installed in:"
+ for libdir in $libdirs; do
+ $echo " $libdir"
+ done
+ $echo
+ $echo "If you ever happen to want to link against installed libraries"
+ $echo "in a given directory, LIBDIR, you must either use libtool, and"
+ $echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+ $echo "flag during linking and do at least one of the following:"
+ if test -n "$shlibpath_var"; then
+ $echo " - add LIBDIR to the \`$shlibpath_var' environment variable"
+ $echo " during execution"
+ fi
+ if test -n "$runpath_var"; then
+ $echo " - add LIBDIR to the \`$runpath_var' environment variable"
+ $echo " during linking"
+ fi
+ if test -n "$hardcode_libdir_flag_spec"; then
+ libdir=LIBDIR
+ eval flag=\"$hardcode_libdir_flag_spec\"
+
+ $echo " - use the \`$flag' linker flag"
+ fi
+ if test -n "$admincmds"; then
+ $echo " - have your system administrator run these commands:$admincmds"
+ fi
+ if test -f /etc/ld.so.conf; then
+ $echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+ fi
+ $echo
+ $echo "See any operating system documentation about shared libraries for"
+ $echo "more information, such as the ld(1) and ld.so(8) manual pages."
+ $echo "X----------------------------------------------------------------------" | $Xsed
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool execute mode
+ execute)
+ modename="$modename: execute"
+
+ # The first argument is the command name.
+ cmd="$nonopt"
+ if test -z "$cmd"; then
+ $echo "$modename: you must specify a COMMAND" 1>&2
+ $echo "$help"
+ exit $EXIT_FAILURE
+ fi
+
+ # Handle -dlopen flags immediately.
+ for file in $execute_dlfiles; do
+ if test ! -f "$file"; then
+ $echo "$modename: \`$file' is not a file" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ dir=
+ case $file in
+ *.la)
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Read the libtool library.
+ dlname=
+ library_names=
+
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Skip this library if it cannot be dlopened.
+ if test -z "$dlname"; then
+ # Warn if it was a shared library.
+ test -n "$library_names" && $echo "$modename: warning: \`$file' was not linked with \`-export-dynamic'"
+ continue
+ fi
+
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+
+ if test -f "$dir/$objdir/$dlname"; then
+ dir="$dir/$objdir"
+ else
+ $echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ ;;
+
+ *.lo)
+ # Just add the directory containing the .lo file.
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+ ;;
+
+ *)
+ $echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries and objects" 1>&2
+ continue
+ ;;
+ esac
+
+ # Get the absolute pathname.
+ absdir=`cd "$dir" && pwd`
+ test -n "$absdir" && dir="$absdir"
+
+ # Now add the directory to shlibpath_var.
+ if eval "test -z \"\$$shlibpath_var\""; then
+ eval "$shlibpath_var=\"\$dir\""
+ else
+ eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
+ fi
+ done
+
+ # This variable tells wrapper scripts just to set shlibpath_var
+ # rather than running their programs.
+ libtool_execute_magic="$magic"
+
+ # Check if any of the arguments is a wrapper script.
+ args=
+ for file
+ do
+ case $file in
+ -*) ;;
+ *)
+ # Do a test to see if this is really a libtool program.
+ if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Transform arg to wrapped name.
+ file="$progdir/$program"
+ fi
+ ;;
+ esac
+ # Quote arguments (to preserve shell metacharacters).
+ file=`$echo "X$file" | $Xsed -e "$sed_quote_subst"`
+ args="$args \"$file\""
+ done
+
+ if test -z "$run"; then
+ if test -n "$shlibpath_var"; then
+ # Export the shlibpath_var.
+ eval "export $shlibpath_var"
+ fi
+
+ # Restore saved environment variables
+ if test "${save_LC_ALL+set}" = set; then
+ LC_ALL="$save_LC_ALL"; export LC_ALL
+ fi
+ if test "${save_LANG+set}" = set; then
+ LANG="$save_LANG"; export LANG
+ fi
+
+ # Now prepare to actually exec the command.
+ exec_cmd="\$cmd$args"
+ else
+ # Display what would be done.
+ if test -n "$shlibpath_var"; then
+ eval "\$echo \"\$shlibpath_var=\$$shlibpath_var\""
+ $echo "export $shlibpath_var"
+ fi
+ $echo "$cmd$args"
+ exit $EXIT_SUCCESS
+ fi
+ ;;
+
+ # libtool clean and uninstall mode
+ clean | uninstall)
+ modename="$modename: $mode"
+ rm="$nonopt"
+ files=
+ rmforce=
+ exit_status=0
+
+ # This variable tells wrapper scripts just to set variables rather
+ # than running their programs.
+ libtool_install_magic="$magic"
+
+ for arg
+ do
+ case $arg in
+ -f) rm="$rm $arg"; rmforce=yes ;;
+ -*) rm="$rm $arg" ;;
+ *) files="$files $arg" ;;
+ esac
+ done
+
+ if test -z "$rm"; then
+ $echo "$modename: you must specify an RM program" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ rmdirs=
+
+ origobjdir="$objdir"
+ for file in $files; do
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$dir" = "X$file"; then
+ dir=.
+ objdir="$origobjdir"
+ else
+ objdir="$dir/$origobjdir"
+ fi
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ test "$mode" = uninstall && objdir="$dir"
+
+ # Remember objdir for removal later, being careful to avoid duplicates
+ if test "$mode" = clean; then
+ case " $rmdirs " in
+ *" $objdir "*) ;;
+ *) rmdirs="$rmdirs $objdir" ;;
+ esac
+ fi
+
+ # Don't error if the file doesn't exist and rm -f was used.
+ if (test -L "$file") >/dev/null 2>&1 \
+ || (test -h "$file") >/dev/null 2>&1 \
+ || test -f "$file"; then
+ :
+ elif test -d "$file"; then
+ exit_status=1
+ continue
+ elif test "$rmforce" = yes; then
+ continue
+ fi
+
+ rmfiles="$file"
+
+ case $name in
+ *.la)
+ # Possibly a libtool archive, so verify it.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ . $dir/$name
+
+ # Delete the libtool libraries and symlinks.
+ for n in $library_names; do
+ rmfiles="$rmfiles $objdir/$n"
+ done
+ test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"
+
+ case "$mode" in
+ clean)
+ case " $library_names " in
+ # " " in the beginning catches empty $dlname
+ *" $dlname "*) ;;
+ *) rmfiles="$rmfiles $objdir/$dlname" ;;
+ esac
+ test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
+ ;;
+ uninstall)
+ if test -n "$library_names"; then
+ # Do each command in the postuninstall commands.
+ cmds=$postuninstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd"
+ if test "$?" -ne 0 && test "$rmforce" != yes; then
+ exit_status=1
+ fi
+ done
+ IFS="$save_ifs"
+ fi
+
+ if test -n "$old_library"; then
+ # Do each command in the old_postuninstall commands.
+ cmds=$old_postuninstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd"
+ if test "$?" -ne 0 && test "$rmforce" != yes; then
+ exit_status=1
+ fi
+ done
+ IFS="$save_ifs"
+ fi
+ # FIXME: should reinstall the best remaining shared library.
+ ;;
+ esac
+ fi
+ ;;
+
+ *.lo)
+ # Possibly a libtool object, so verify it.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+
+ # Read the .lo file
+ . $dir/$name
+
+ # Add PIC object to the list of files to remove.
+ if test -n "$pic_object" \
+ && test "$pic_object" != none; then
+ rmfiles="$rmfiles $dir/$pic_object"
+ fi
+
+ # Add non-PIC object to the list of files to remove.
+ if test -n "$non_pic_object" \
+ && test "$non_pic_object" != none; then
+ rmfiles="$rmfiles $dir/$non_pic_object"
+ fi
+ fi
+ ;;
+
+ *)
+ if test "$mode" = clean ; then
+ noexename=$name
+ case $file in
+ *.exe)
+ file=`$echo $file|${SED} 's,.exe$,,'`
+ noexename=`$echo $name|${SED} 's,.exe$,,'`
+ # $file with .exe has already been added to rmfiles,
+ # add $file without .exe
+ rmfiles="$rmfiles $file"
+ ;;
+ esac
+ # Do a test to see if this is a libtool program.
+ if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ relink_command=
+ . $dir/$noexename
+
+ # note $name still contains .exe if it was in $file originally
+ # as does the version of $file that was added into $rmfiles
+ rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}"
+ if test "$fast_install" = yes && test -n "$relink_command"; then
+ rmfiles="$rmfiles $objdir/lt-$name"
+ fi
+ if test "X$noexename" != "X$name" ; then
+ rmfiles="$rmfiles $objdir/lt-${noexename}.c"
+ fi
+ fi
+ fi
+ ;;
+ esac
+ $show "$rm $rmfiles"
+ $run $rm $rmfiles || exit_status=1
+ done
+ objdir="$origobjdir"
+
+ # Try to remove the ${objdir}s in the directories where we deleted files
+ for dir in $rmdirs; do
+ if test -d "$dir"; then
+ $show "rmdir $dir"
+ $run rmdir $dir >/dev/null 2>&1
+ fi
+ done
+
+ exit $exit_status
+ ;;
+
+ "")
+ $echo "$modename: you must specify a MODE" 1>&2
+ $echo "$generic_help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ if test -z "$exec_cmd"; then
+ $echo "$modename: invalid operation mode \`$mode'" 1>&2
+ $echo "$generic_help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+fi # test -z "$show_help"
+
+if test -n "$exec_cmd"; then
+ eval exec $exec_cmd
+ exit $EXIT_FAILURE
+fi
+
+# We need to display help for each of the modes.
+case $mode in
+"") $echo \
+"Usage: $modename [OPTION]... [MODE-ARG]...
+
+Provide generalized library-building support services.
+
+ --config show all configuration variables
+ --debug enable verbose shell tracing
+-n, --dry-run display commands without modifying any files
+ --features display basic configuration information and exit
+ --finish same as \`--mode=finish'
+ --help display this help message and exit
+ --mode=MODE use operation mode MODE [default=inferred from MODE-ARGS]
+ --quiet same as \`--silent'
+ --silent don't print informational messages
+ --tag=TAG use configuration variables from tag TAG
+ --version print version information
+
+MODE must be one of the following:
+
+ clean remove files from the build directory
+ compile compile a source file into a libtool object
+ execute automatically set library path, then run a program
+ finish complete the installation of libtool libraries
+ install install libraries or executables
+ link create a library or an executable
+ uninstall remove libraries from an installed directory
+
+MODE-ARGS vary depending on the MODE. Try \`$modename --help --mode=MODE' for
+a more detailed description of MODE.
+
+Report bugs to <bug-libtool@gnu.org>."
+ exit $EXIT_SUCCESS
+ ;;
+
+clean)
+ $echo \
+"Usage: $modename [OPTION]... --mode=clean RM [RM-OPTION]... FILE...
+
+Remove files from the build directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, object or program, all the files associated
+with it are deleted. Otherwise, only FILE itself is deleted using RM."
+ ;;
+
+compile)
+ $echo \
+"Usage: $modename [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
+
+Compile a source file into a libtool library object.
+
+This mode accepts the following additional options:
+
+ -o OUTPUT-FILE set the output file name to OUTPUT-FILE
+ -prefer-pic try to building PIC objects only
+ -prefer-non-pic try to building non-PIC objects only
+ -static always build a \`.o' file suitable for static linking
+
+COMPILE-COMMAND is a command to be used in creating a \`standard' object file
+from the given SOURCEFILE.
+
+The output file name is determined by removing the directory component from
+SOURCEFILE, then substituting the C source code suffix \`.c' with the
+library object suffix, \`.lo'."
+ ;;
+
+execute)
+ $echo \
+"Usage: $modename [OPTION]... --mode=execute COMMAND [ARGS]...
+
+Automatically set library path, then run a program.
+
+This mode accepts the following additional options:
+
+ -dlopen FILE add the directory containing FILE to the library path
+
+This mode sets the library path environment variable according to \`-dlopen'
+flags.
+
+If any of the ARGS are libtool executable wrappers, then they are translated
+into their corresponding uninstalled binary, and any of their required library
+directories are added to the library path.
+
+Then, COMMAND is executed, with ARGS as arguments."
+ ;;
+
+finish)
+ $echo \
+"Usage: $modename [OPTION]... --mode=finish [LIBDIR]...
+
+Complete the installation of libtool libraries.
+
+Each LIBDIR is a directory that contains libtool libraries.
+
+The commands that this mode executes may require superuser privileges. Use
+the \`--dry-run' option if you just want to see what would be executed."
+ ;;
+
+install)
+ $echo \
+"Usage: $modename [OPTION]... --mode=install INSTALL-COMMAND...
+
+Install executables or libraries.
+
+INSTALL-COMMAND is the installation command. The first component should be
+either the \`install' or \`cp' program.
+
+The rest of the components are interpreted as arguments to that command (only
+BSD-compatible install options are recognized)."
+ ;;
+
+link)
+ $echo \
+"Usage: $modename [OPTION]... --mode=link LINK-COMMAND...
+
+Link object files or libraries together to form another library, or to
+create an executable program.
+
+LINK-COMMAND is a command using the C compiler that you would use to create
+a program from several object files.
+
+The following components of LINK-COMMAND are treated specially:
+
+ -all-static do not do any dynamic linking at all
+ -avoid-version do not add a version suffix if possible
+ -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime
+ -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols
+ -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
+ -export-symbols SYMFILE
+ try to export only the symbols listed in SYMFILE
+ -export-symbols-regex REGEX
+ try to export only the symbols matching REGEX
+ -LLIBDIR search LIBDIR for required installed libraries
+ -lNAME OUTPUT-FILE requires the installed library libNAME
+ -module build a library that can dlopened
+ -no-fast-install disable the fast-install mode
+ -no-install link a not-installable executable
+ -no-undefined declare that a library does not refer to external symbols
+ -o OUTPUT-FILE create OUTPUT-FILE from the specified objects
+ -objectlist FILE Use a list of object files found in FILE to specify objects
+ -precious-files-regex REGEX
+ don't remove output files matching REGEX
+ -release RELEASE specify package release information
+ -rpath LIBDIR the created library will eventually be installed in LIBDIR
+ -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries
+ -static do not do any dynamic linking of libtool libraries
+ -version-info CURRENT[:REVISION[:AGE]]
+ specify library version info [each variable defaults to 0]
+
+All other options (arguments beginning with \`-') are ignored.
+
+Every other argument is treated as a filename. Files ending in \`.la' are
+treated as uninstalled libtool libraries, other files are standard or library
+object files.
+
+If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
+only library objects (\`.lo' files) may be specified, and \`-rpath' is
+required, except when creating a convenience library.
+
+If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
+using \`ar' and \`ranlib', or on Windows using \`lib'.
+
+If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
+is created, otherwise an executable program is created."
+ ;;
+
+uninstall)
+ $echo \
+"Usage: $modename [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
+
+Remove libraries from an installation directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, all the files associated with it are deleted.
+Otherwise, only FILE itself is deleted using RM."
+ ;;
+
+*)
+ $echo "$modename: invalid operation mode \`$mode'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+esac
+
+$echo
+$echo "Try \`$modename --help' for more information about other modes."
+
+exit $?
+
+# The TAGs below are defined such that we never get into a situation
+# in which we disable both kinds of libraries. Given conflicting
+# choices, we go for a static library, that is the most portable,
+# since we can't tell whether shared libraries were disabled because
+# the user asked for that or because the platform doesn't support
+# them. This is particularly important on AIX, because we don't
+# support having both static and shared libraries enabled at the same
+# time on that platform, so we default to a shared-only configuration.
+# If a disable-shared tag is given, we'll fallback to a static-only
+# configuration. But we'll never go from static-only to shared-only.
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
+disable_libs=shared
+# ### END LIBTOOL TAG CONFIG: disable-shared
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-static
+disable_libs=static
+# ### END LIBTOOL TAG CONFIG: disable-static
+
+# Local Variables:
+# mode:shell-script
+# sh-indentation:2
+# End:
diff --git a/autoconf/m4/build_exeext.m4 b/autoconf/m4/build_exeext.m4
new file mode 100644
index 00000000000..1bdecc1ba57
--- /dev/null
+++ b/autoconf/m4/build_exeext.m4
@@ -0,0 +1,42 @@
+# Check for the extension used for executables on build platform.
+# This is necessary for cross-compiling where the build platform
+# may differ from the host platform.
+AC_DEFUN([AC_BUILD_EXEEXT],
+[
+AC_MSG_CHECKING([for executable suffix on build platform])
+AC_CACHE_VAL(ac_cv_build_exeext,
+[if test "$CYGWIN" = yes || test "$MINGW32" = yes; then
+ ac_cv_build_exeext=.exe
+else
+ ac_build_prefix=${build_alias}-
+
+ AC_CHECK_PROG(BUILD_CC, ${ac_build_prefix}gcc, ${ac_build_prefix}gcc)
+ if test -z "$BUILD_CC"; then
+ AC_CHECK_PROG(BUILD_CC, gcc, gcc)
+ if test -z "$BUILD_CC"; then
+ AC_CHECK_PROG(BUILD_CC, cc, cc, , , /usr/ucb/cc)
+ fi
+ fi
+ test -z "$BUILD_CC" && AC_MSG_ERROR([no acceptable cc found in \$PATH])
+ ac_build_link='${BUILD_CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&AS_MESSAGE_LOG_FD'
+ rm -f conftest*
+ echo 'int main () { return 0; }' > conftest.$ac_ext
+ ac_cv_build_exeext=
+ if AC_TRY_EVAL(ac_build_link); then
+ for file in conftest.*; do
+ case $file in
+ *.c | *.o | *.obj | *.dSYM) ;;
+ *) ac_cv_build_exeext=`echo $file | sed -e s/conftest//` ;;
+ esac
+ done
+ else
+ AC_MSG_ERROR([installation or configuration problem: compiler cannot create executables.])
+ fi
+ rm -f conftest*
+ test x"${ac_cv_build_exeext}" = x && ac_cv_build_exeext=blank
+fi])
+BUILD_EXEEXT=""
+test x"${ac_cv_build_exeext}" != xblank && BUILD_EXEEXT=${ac_cv_build_exeext}
+AC_MSG_RESULT(${ac_cv_build_exeext})
+ac_build_exeext=$BUILD_EXEEXT
+AC_SUBST(BUILD_EXEEXT)])
diff --git a/autoconf/m4/c_printf_a.m4 b/autoconf/m4/c_printf_a.m4
new file mode 100644
index 00000000000..61bac8c9dd1
--- /dev/null
+++ b/autoconf/m4/c_printf_a.m4
@@ -0,0 +1,31 @@
+#
+# Determine if the printf() functions have the %a format character.
+# This is modified from:
+# http://www.gnu.org/software/ac-archive/htmldoc/ac_cxx_have_ext_slist.html
+AC_DEFUN([AC_C_PRINTF_A],
+[AC_CACHE_CHECK([if printf has the %a format character],[llvm_cv_c_printf_a],
+[AC_LANG_PUSH([C])
+ AC_RUN_IFELSE([
+ AC_LANG_PROGRAM([[
+#include <stdio.h>
+#include <stdlib.h>
+]],[[
+volatile double A, B;
+char Buffer[100];
+A = 1;
+A /= 10.0;
+sprintf(Buffer, "%a", A);
+B = atof(Buffer);
+if (A != B)
+ return (1);
+if (A != 0x1.999999999999ap-4)
+ return (1);
+return (0);]])],
+ llvm_cv_c_printf_a=yes,
+ llvmac_cv_c_printf_a=no,
+ llvmac_cv_c_printf_a=no)
+ AC_LANG_POP([C])])
+ if test "$llvm_cv_c_printf_a" = "yes"; then
+ AC_DEFINE([HAVE_PRINTF_A],[1],[Define to have the %a format string])
+ fi
+])
diff --git a/autoconf/m4/check_gnu_make.m4 b/autoconf/m4/check_gnu_make.m4
new file mode 100644
index 00000000000..7355e1c85bb
--- /dev/null
+++ b/autoconf/m4/check_gnu_make.m4
@@ -0,0 +1,26 @@
+#
+# Check for GNU Make. This is originally from
+# http://www.gnu.org/software/ac-archive/htmldoc/check_gnu_make.html
+#
+AC_DEFUN([AC_CHECK_GNU_MAKE],
+[AC_CACHE_CHECK([for GNU make],[llvm_cv_gnu_make_command],
+dnl Search all the common names for GNU make
+[llvm_cv_gnu_make_command=''
+ for a in "$MAKE" make gmake gnumake ; do
+ if test -z "$a" ; then continue ; fi ;
+ if ( sh -c "$a --version" 2> /dev/null | grep GNU 2>&1 > /dev/null )
+ then
+ llvm_cv_gnu_make_command=$a ;
+ break;
+ fi
+ done])
+dnl If there was a GNU version, then set @ifGNUmake@ to the empty string,
+dnl '#' otherwise
+ if test "x$llvm_cv_gnu_make_command" != "x" ; then
+ ifGNUmake='' ;
+ else
+ ifGNUmake='#' ;
+ AC_MSG_RESULT("Not found");
+ fi
+ AC_SUBST(ifGNUmake)
+])
diff --git a/autoconf/m4/config_makefile.m4 b/autoconf/m4/config_makefile.m4
new file mode 100644
index 00000000000..b1eaffdcd85
--- /dev/null
+++ b/autoconf/m4/config_makefile.m4
@@ -0,0 +1,9 @@
+#
+# Configure a Makefile without clobbering it if it exists and is not out of
+# date. This macro is unique to LLVM.
+#
+AC_DEFUN([AC_CONFIG_MAKEFILE],
+[AC_CONFIG_COMMANDS($1,
+ [${llvm_src}/autoconf/mkinstalldirs `dirname $1`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/$1 $1])
+])
diff --git a/autoconf/m4/config_project.m4 b/autoconf/m4/config_project.m4
new file mode 100644
index 00000000000..eea7faf165c
--- /dev/null
+++ b/autoconf/m4/config_project.m4
@@ -0,0 +1,14 @@
+#
+# Provide the arguments and other processing needed for an LLVM project
+#
+AC_DEFUN([LLVM_CONFIG_PROJECT],
+ [AC_ARG_WITH([llvmsrc],
+ AS_HELP_STRING([--with-llvmsrc],[Location of LLVM Source Code]),
+ [llvm_src="$withval"],[llvm_src="]$1["])
+ AC_SUBST(LLVM_SRC,$llvm_src)
+ AC_ARG_WITH([llvmobj],
+ AS_HELP_STRING([--with-llvmobj],[Location of LLVM Object Code]),
+ [llvm_obj="$withval"],[llvm_obj="]$2["])
+ AC_SUBST(LLVM_OBJ,$llvm_obj)
+ AC_CONFIG_COMMANDS([setup],,[llvm_src="${LLVM_SRC}"])
+])
diff --git a/autoconf/m4/cxx_flag_check.m4 b/autoconf/m4/cxx_flag_check.m4
new file mode 100644
index 00000000000..62454b7147f
--- /dev/null
+++ b/autoconf/m4/cxx_flag_check.m4
@@ -0,0 +1,2 @@
+AC_DEFUN([CXX_FLAG_CHECK],
+ [AC_SUBST($1, `$CXX -Werror $2 -fsyntax-only -xc /dev/null 2>/dev/null && echo $2`)])
diff --git a/autoconf/m4/find_std_program.m4 b/autoconf/m4/find_std_program.m4
new file mode 100644
index 00000000000..c789df8e641
--- /dev/null
+++ b/autoconf/m4/find_std_program.m4
@@ -0,0 +1,118 @@
+dnl Check for a standard program that has a bin, include and lib directory
+dnl
+dnl Parameters:
+dnl $1 - prefix directory to check
+dnl $2 - program name to check
+dnl $3 - header file to check
+dnl $4 - library file to check
+AC_DEFUN([CHECK_STD_PROGRAM],
+[m4_define([allcapsname],translit($2,a-z,A-Z))
+if test -n "$1" -a -d "$1" -a -n "$2" -a -d "$1/bin" -a -x "$1/bin/$2" ; then
+ AC_SUBST([USE_]allcapsname(),["USE_]allcapsname()[ = 1"])
+ AC_SUBST(allcapsname(),[$1/bin/$2])
+ AC_SUBST(allcapsname()[_BIN],[$1/bin])
+ AC_SUBST(allcapsname()[_DIR],[$1])
+ if test -n "$3" -a -d "$1/include" -a -f "$1/include/$3" ; then
+ AC_SUBST(allcapsname()[_INC],[$1/include])
+ fi
+ if test -n "$4" -a -d "$1/lib" -a -f "$1/lib/$4" ; then
+ AC_SUBST(allcapsname()[_LIB],[$1/lib])
+ fi
+fi
+])
+
+dnl Find a program via --with options, in the path, or well known places
+dnl
+dnl Parameters:
+dnl $1 - program's executable name
+dnl $2 - header file name to check (optional)
+dnl $3 - library file name to check (optional)
+dnl $4 - alternate (long) name for the program
+AC_DEFUN([FIND_STD_PROGRAM],
+[m4_define([allcapsname],translit($1,a-z,A-Z))
+m4_define([stdprog_long_name],ifelse($4,,translit($1,[ !@#$%^&*()-+={}[]:;"',./?],[-]),translit($4,[ !@#$%^&*()-+={}[]:;"',./?],[-])))
+AC_MSG_CHECKING([for ]stdprog_long_name()[ bin/lib/include locations])
+AC_ARG_WITH($1,
+ AS_HELP_STRING([--with-]stdprog_long_name()[=DIR],
+ [Specify that the ]stdprog_long_name()[ install prefix is DIR]),
+ $1[pfxdir=$withval],$1[pfxdir=nada])
+AC_ARG_WITH($1[-bin],
+ AS_HELP_STRING([--with-]stdprog_long_name()[-bin=DIR],
+ [Specify that the ]stdprog_long_name()[ binary is in DIR]),
+ $1[bindir=$withval],$1[bindir=nada])
+AC_ARG_WITH($1[-lib],
+ AS_HELP_STRING([--with-]stdprog_long_name()[-lib=DIR],
+ [Specify that ]stdprog_long_name()[ libraries are in DIR]),
+ $1[libdir=$withval],$1[libdir=nada])
+AC_ARG_WITH($1[-inc],
+ AS_HELP_STRING([--with-]stdprog_long_name()[-inc=DIR],
+ [Specify that the ]stdprog_long_name()[ includes are in DIR]),
+ $1[incdir=$withval],$1[incdir=nada])
+eval pfxval=\$\{$1pfxdir\}
+eval binval=\$\{$1bindir\}
+eval incval=\$\{$1incdir\}
+eval libval=\$\{$1libdir\}
+if test "${pfxval}" != "nada" ; then
+ CHECK_STD_PROGRAM(${pfxval},$1,$2,$3)
+elif test "${binval}" != "nada" ; then
+ if test "${libval}" != "nada" ; then
+ if test "${incval}" != "nada" ; then
+ if test -d "${binval}" ; then
+ if test -d "${incval}" ; then
+ if test -d "${libval}" ; then
+ AC_SUBST(allcapsname(),${binval}/$1)
+ AC_SUBST(allcapsname()[_BIN],${binval})
+ AC_SUBST(allcapsname()[_INC],${incval})
+ AC_SUBST(allcapsname()[_LIB],${libval})
+ AC_SUBST([USE_]allcapsname(),["USE_]allcapsname()[ = 1"])
+ AC_MSG_RESULT([found via --with options])
+ else
+ AC_MSG_RESULT([failed])
+ AC_MSG_ERROR([The --with-]$1[-libdir value must be a directory])
+ fi
+ else
+ AC_MSG_RESULT([failed])
+ AC_MSG_ERROR([The --with-]$1[-incdir value must be a directory])
+ fi
+ else
+ AC_MSG_RESULT([failed])
+ AC_MSG_ERROR([The --with-]$1[-bindir value must be a directory])
+ fi
+ else
+ AC_MSG_RESULT([failed])
+ AC_MSG_ERROR([The --with-]$1[-incdir option must be specified])
+ fi
+ else
+ AC_MSG_RESULT([failed])
+ AC_MSG_ERROR([The --with-]$1[-libdir option must be specified])
+ fi
+else
+ tmppfxdir=`which $1 2>&1`
+ if test -n "$tmppfxdir" -a -d "${tmppfxdir%*$1}" -a \
+ -d "${tmppfxdir%*$1}/.." ; then
+ tmppfxdir=`cd "${tmppfxdir%*$1}/.." ; pwd`
+ CHECK_STD_PROGRAM($tmppfxdir,$1,$2,$3)
+ AC_MSG_RESULT([found in PATH at ]$tmppfxdir)
+ else
+ checkresult="yes"
+ eval checkval=\$\{"USE_"allcapsname()\}
+ CHECK_STD_PROGRAM([/usr],$1,$2,$3)
+ if test -z "${checkval}" ; then
+ CHECK_STD_PROGRAM([/usr/local],$1,$2,$3)
+ if test -z "${checkval}" ; then
+ CHECK_STD_PROGRAM([/sw],$1,$2,$3)
+ if test -z "${checkval}" ; then
+ CHECK_STD_PROGRAM([/opt],$1,$2,$3)
+ if test -z "${checkval}" ; then
+ CHECK_STD_PROGRAM([/],$1,$2,$3)
+ if test -z "${checkval}" ; then
+ checkresult="no"
+ fi
+ fi
+ fi
+ fi
+ fi
+ AC_MSG_RESULT($checkresult)
+ fi
+fi
+])
diff --git a/autoconf/m4/func_isinf.m4 b/autoconf/m4/func_isinf.m4
new file mode 100644
index 00000000000..22ba81d54d5
--- /dev/null
+++ b/autoconf/m4/func_isinf.m4
@@ -0,0 +1,36 @@
+#
+# This function determins if the isinf function isavailable on this
+# platform.
+#
+AC_DEFUN([AC_FUNC_ISINF],[
+AC_SINGLE_CXX_CHECK([ac_cv_func_isinf_in_math_h],
+ [isinf], [<math.h>],
+ [float f; isinf(f);])
+if test "$ac_cv_func_isinf_in_math_h" = "yes" ; then
+ AC_DEFINE([HAVE_ISINF_IN_MATH_H],1,[Set to 1 if the isinf function is found in <math.h>])
+fi
+
+AC_SINGLE_CXX_CHECK([ac_cv_func_isinf_in_cmath],
+ [isinf], [<cmath>],
+ [float f; isinf(f);])
+if test "$ac_cv_func_isinf_in_cmath" = "yes" ; then
+ AC_DEFINE([HAVE_ISINF_IN_CMATH],1,[Set to 1 if the isinf function is found in <cmath>])
+fi
+
+AC_SINGLE_CXX_CHECK([ac_cv_func_std_isinf_in_cmath],
+ [std::isinf], [<cmath>],
+ [float f; std::isinf(f);])
+if test "$ac_cv_func_std_isinf_in_cmath" = "yes" ; then
+ AC_DEFINE([HAVE_STD_ISINF_IN_CMATH],1,[Set to 1 if the std::isinf function is found in <cmath>])
+fi
+
+AC_SINGLE_CXX_CHECK([ac_cv_func_finite_in_ieeefp_h],
+ [finite], [<ieeefp.h>],
+ [float f; finite(f);])
+if test "$ac_cv_func_finite_in_ieeefp_h" = "yes" ; then
+ AC_DEFINE([HAVE_FINITE_IN_IEEEFP_H],1,[Set to 1 if the finite function is found in <ieeefp.h>])
+fi
+
+])
+
+
diff --git a/autoconf/m4/func_isnan.m4 b/autoconf/m4/func_isnan.m4
new file mode 100644
index 00000000000..eb5ca0daeb5
--- /dev/null
+++ b/autoconf/m4/func_isnan.m4
@@ -0,0 +1,27 @@
+#
+# This function determines if the isnan function is available on this
+# platform.
+#
+AC_DEFUN([AC_FUNC_ISNAN],[
+AC_SINGLE_CXX_CHECK([ac_cv_func_isnan_in_math_h],
+ [isnan], [<math.h>],
+ [float f; isnan(f);])
+
+if test "$ac_cv_func_isnan_in_math_h" = "yes" ; then
+ AC_DEFINE([HAVE_ISNAN_IN_MATH_H],1,[Set to 1 if the isnan function is found in <math.h>])
+fi
+
+AC_SINGLE_CXX_CHECK([ac_cv_func_isnan_in_cmath],
+ [isnan], [<cmath>],
+ [float f; isnan(f);])
+if test "$ac_cv_func_isnan_in_cmath" = "yes" ; then
+ AC_DEFINE([HAVE_ISNAN_IN_CMATH],1,[Set to 1 if the isnan function is found in <cmath>])
+fi
+
+AC_SINGLE_CXX_CHECK([ac_cv_func_std_isnan_in_cmath],
+ [std::isnan], [<cmath>],
+ [float f; std::isnan(f);])
+if test "$ac_cv_func_std_isnan_in_cmath" = "yes" ; then
+ AC_DEFINE([HAVE_STD_ISNAN_IN_CMATH],1,[Set to 1 if the std::isnan function is found in <cmath>])
+fi
+])
diff --git a/autoconf/m4/func_mmap_file.m4 b/autoconf/m4/func_mmap_file.m4
new file mode 100644
index 00000000000..372c87fbe5c
--- /dev/null
+++ b/autoconf/m4/func_mmap_file.m4
@@ -0,0 +1,26 @@
+#
+# Check for the ability to mmap a file.
+#
+AC_DEFUN([AC_FUNC_MMAP_FILE],
+[AC_CACHE_CHECK(for mmap of files,
+ac_cv_func_mmap_file,
+[ AC_LANG_PUSH([C])
+ AC_RUN_IFELSE([
+ AC_LANG_PROGRAM([[
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <fcntl.h>
+]],[[
+ int fd;
+ fd = creat ("foo",0777);
+ fd = (int) mmap (0, 1, PROT_READ, MAP_SHARED, fd, 0);
+ unlink ("foo");
+ return (fd != (int) MAP_FAILED);]])],
+ [ac_cv_func_mmap_file=yes],[ac_cv_func_mmap_file=no],[ac_cv_func_mmap_file=no])
+ AC_LANG_POP([C])
+])
+if test "$ac_cv_func_mmap_file" = yes; then
+ AC_DEFINE([HAVE_MMAP_FILE],[],[Define if mmap() can map files into memory])
+ AC_SUBST(MMAP_FILE,[yes])
+fi
+])
diff --git a/autoconf/m4/header_mmap_anonymous.m4 b/autoconf/m4/header_mmap_anonymous.m4
new file mode 100644
index 00000000000..2270d29557b
--- /dev/null
+++ b/autoconf/m4/header_mmap_anonymous.m4
@@ -0,0 +1,21 @@
+#
+# Check for anonymous mmap macros. This is modified from
+# http://www.gnu.org/software/ac-archive/htmldoc/ac_cxx_have_ext_slist.html
+#
+AC_DEFUN([AC_HEADER_MMAP_ANONYMOUS],
+[AC_CACHE_CHECK(for MAP_ANONYMOUS vs. MAP_ANON,
+ac_cv_header_mmap_anon,
+[ AC_LANG_PUSH([C])
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+ [[#include <sys/mman.h>
+#include <unistd.h>
+#include <fcntl.h>]],
+ [[mmap (0, 1, PROT_READ, MAP_ANONYMOUS, -1, 0); return (0);]])],
+ ac_cv_header_mmap_anon=yes,
+ ac_cv_header_mmap_anon=no)
+ AC_LANG_POP([C])
+])
+if test "$ac_cv_header_mmap_anon" = yes; then
+ AC_DEFINE([HAVE_MMAP_ANONYMOUS],[1],[Define if mmap() uses MAP_ANONYMOUS to map anonymous pages, or undefine if it uses MAP_ANON])
+fi
+])
diff --git a/autoconf/m4/huge_val.m4 b/autoconf/m4/huge_val.m4
new file mode 100644
index 00000000000..6c9a22eab00
--- /dev/null
+++ b/autoconf/m4/huge_val.m4
@@ -0,0 +1,20 @@
+#
+# This function determins if the HUGE_VAL macro is compilable with the
+# -pedantic switch or not. XCode < 2.4.1 doesn't get it right.
+#
+AC_DEFUN([AC_HUGE_VAL_CHECK],[
+ AC_CACHE_CHECK([for HUGE_VAL sanity], [ac_cv_huge_val_sanity],[
+ AC_LANG_PUSH([C++])
+ ac_save_CXXFLAGS=$CXXFLAGS
+ CXXFLAGS="$CXXFLAGS -pedantic"
+ AC_RUN_IFELSE(
+ AC_LANG_PROGRAM(
+ [#include <math.h>],
+ [double x = HUGE_VAL; return x != x; ]),
+ [ac_cv_huge_val_sanity=yes],[ac_cv_huge_val_sanity=no],
+ [ac_cv_huge_val_sanity=yes])
+ CXXFLAGS=$ac_save_CXXFLAGS
+ AC_LANG_POP([C++])
+ ])
+ AC_SUBST(HUGE_VAL_SANITY,$ac_cv_huge_val_sanity)
+])
diff --git a/autoconf/m4/libtool.m4 b/autoconf/m4/libtool.m4
new file mode 100644
index 00000000000..05af7a2ee3f
--- /dev/null
+++ b/autoconf/m4/libtool.m4
@@ -0,0 +1,6389 @@
+# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
+## Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
+## Free Software Foundation, Inc.
+## Originally by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
+##
+## This file is free software; the Free Software Foundation gives
+## unlimited permission to copy and/or distribute it, with or without
+## modifications, as long as this notice is preserved.
+
+# serial 48 AC_PROG_LIBTOOL
+
+
+# AC_PROVIDE_IFELSE(MACRO-NAME, IF-PROVIDED, IF-NOT-PROVIDED)
+# -----------------------------------------------------------
+# If this macro is not defined by Autoconf, define it here.
+m4_ifdef([AC_PROVIDE_IFELSE],
+ [],
+ [m4_define([AC_PROVIDE_IFELSE],
+ [m4_ifdef([AC_PROVIDE_$1],
+ [$2], [$3])])])
+
+
+# AC_PROG_LIBTOOL
+# ---------------
+AC_DEFUN([AC_PROG_LIBTOOL],
+[AC_REQUIRE([_AC_PROG_LIBTOOL])dnl
+dnl If AC_PROG_CXX has already been expanded, run AC_LIBTOOL_CXX
+dnl immediately, otherwise, hook it in at the end of AC_PROG_CXX.
+ AC_PROVIDE_IFELSE([AC_PROG_CXX],
+ [AC_LIBTOOL_CXX],
+ [define([AC_PROG_CXX], defn([AC_PROG_CXX])[AC_LIBTOOL_CXX
+ ])])
+dnl And a similar setup for Fortran 77 support
+ AC_PROVIDE_IFELSE([AC_PROG_F77],
+ [AC_LIBTOOL_F77],
+ [define([AC_PROG_F77], defn([AC_PROG_F77])[AC_LIBTOOL_F77
+])])
+
+dnl Quote A][M_PROG_GCJ so that aclocal doesn't bring it in needlessly.
+dnl If either AC_PROG_GCJ or A][M_PROG_GCJ have already been expanded, run
+dnl AC_LIBTOOL_GCJ immediately, otherwise, hook it in at the end of both.
+ AC_PROVIDE_IFELSE([AC_PROG_GCJ],
+ [AC_LIBTOOL_GCJ],
+ [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
+ [AC_LIBTOOL_GCJ],
+ [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ],
+ [AC_LIBTOOL_GCJ],
+ [ifdef([AC_PROG_GCJ],
+ [define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[AC_LIBTOOL_GCJ])])
+ ifdef([A][M_PROG_GCJ],
+ [define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[AC_LIBTOOL_GCJ])])
+ ifdef([LT_AC_PROG_GCJ],
+ [define([LT_AC_PROG_GCJ],
+ defn([LT_AC_PROG_GCJ])[AC_LIBTOOL_GCJ])])])])
+])])# AC_PROG_LIBTOOL
+
+
+# _AC_PROG_LIBTOOL
+# ----------------
+AC_DEFUN([_AC_PROG_LIBTOOL],
+[AC_REQUIRE([AC_LIBTOOL_SETUP])dnl
+AC_BEFORE([$0],[AC_LIBTOOL_CXX])dnl
+AC_BEFORE([$0],[AC_LIBTOOL_F77])dnl
+AC_BEFORE([$0],[AC_LIBTOOL_GCJ])dnl
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ac_aux_dir/ltmain.sh"
+
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/mklib'
+AC_SUBST(LIBTOOL)dnl
+
+# Prevent multiple expansion
+define([AC_PROG_LIBTOOL], [])
+])# _AC_PROG_LIBTOOL
+
+
+# AC_LIBTOOL_SETUP
+# ----------------
+AC_DEFUN([AC_LIBTOOL_SETUP],
+[AC_PREREQ(2.60)dnl
+AC_REQUIRE([AC_ENABLE_SHARED])dnl
+AC_REQUIRE([AC_ENABLE_STATIC])dnl
+AC_REQUIRE([AC_ENABLE_FAST_INSTALL])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_PROG_LD])dnl
+AC_REQUIRE([AC_PROG_LD_RELOAD_FLAG])dnl
+AC_REQUIRE([AC_PROG_NM])dnl
+
+AC_REQUIRE([AC_PROG_LN_S])dnl
+AC_REQUIRE([AC_DEPLIBS_CHECK_METHOD])dnl
+# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers!
+AC_REQUIRE([AC_OBJEXT])dnl
+AC_REQUIRE([AC_EXEEXT])dnl
+dnl
+
+AC_LIBTOOL_SYS_MAX_CMD_LEN
+AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
+AC_LIBTOOL_OBJDIR
+
+AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
+_LT_AC_PROG_ECHO_BACKSLASH
+
+case $host_os in
+aix3*)
+ # AIX sometimes has problems with the GCC collect2 program. For some
+ # reason, if we set the COLLECT_NAMES environment variable, the problems
+ # vanish in a puff of smoke.
+ if test "X${COLLECT_NAMES+set}" != Xset; then
+ COLLECT_NAMES=
+ export COLLECT_NAMES
+ fi
+ ;;
+esac
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='sed -e 1s/^X//'
+[sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g']
+
+# Same as above, but do not quote variable references.
+[double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g']
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+
+# Constants:
+rm="rm -f"
+
+# Global variables:
+default_ofile=mklib
+can_build_shared=yes
+
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+ltmain="$ac_aux_dir/ltmain.sh"
+ofile="$default_ofile"
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+AC_CHECK_TOOL(AR, ar, false)
+AC_CHECK_TOOL(RANLIB, ranlib, :)
+AC_CHECK_TOOL(STRIP, strip, :)
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$AR" && AR=ar
+test -z "$AR_FLAGS" && AR_FLAGS=cru
+test -z "$AS" && AS=as
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+test -z "$LD" && LD=ld
+test -z "$LN_S" && LN_S="ln -s"
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+test -z "$NM" && NM=nm
+test -z "$SED" && SED=sed
+test -z "$OBJDUMP" && OBJDUMP=objdump
+test -z "$RANLIB" && RANLIB=:
+test -z "$STRIP" && STRIP=:
+test -z "$ac_objext" && ac_objext=o
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+ case $host_os in
+ openbsd* | bitrig*)
+ old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+ ;;
+ *)
+ old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
+ ;;
+ esac
+ old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
+fi
+
+_LT_CC_BASENAME([$compiler])
+
+# Only perform the check for file, if the check method requires it
+case $deplibs_check_method in
+file_magic*)
+ if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+ AC_PATH_MAGIC
+ fi
+ ;;
+esac
+
+AC_PROVIDE_IFELSE([AC_LIBTOOL_DLOPEN], enable_dlopen=yes, enable_dlopen=no)
+AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL],
+enable_win32_dll=yes, enable_win32_dll=no)
+
+AC_ARG_ENABLE([libtool-lock],
+ [AS_HELP_STRING([--disable-libtool-lock],[avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+AC_ARG_WITH([pic],
+ [AS_HELP_STRING([--with-pic],[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
+ [pic_mode="$withval"],
+ [pic_mode=default])
+test -z "$pic_mode" && pic_mode=default
+
+# Use C for the default configuration in the libtool script
+tagname=
+AC_LIBTOOL_LANG_C_CONFIG
+_LT_AC_TAGCONFIG
+])# AC_LIBTOOL_SETUP
+
+
+# _LT_AC_SYS_COMPILER
+# -------------------
+AC_DEFUN([_LT_AC_SYS_COMPILER],
+[AC_REQUIRE([AC_PROG_CC])dnl
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+])# _LT_AC_SYS_COMPILER
+
+
+# _LT_CC_BASENAME(CC)
+# -------------------
+# Calculate cc_basename. Skip known compiler wrappers and cross-prefix.
+AC_DEFUN([_LT_CC_BASENAME],
+[for cc_temp in $1""; do
+ case $cc_temp in
+ compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
+ distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+])
+
+
+# _LT_COMPILER_BOILERPLATE
+# ------------------------
+# Check for compiler boilerplate output or warnings with
+# the simple compiler test code.
+AC_DEFUN([_LT_COMPILER_BOILERPLATE],
+[ac_outfile=conftest.$ac_objext
+printf "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$rm conftest*
+])# _LT_COMPILER_BOILERPLATE
+
+
+# _LT_LINKER_BOILERPLATE
+# ----------------------
+# Check for linker boilerplate output or warnings with
+# the simple link test code.
+AC_DEFUN([_LT_LINKER_BOILERPLATE],
+[ac_outfile=conftest.$ac_objext
+printf "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$rm conftest*
+])# _LT_LINKER_BOILERPLATE
+
+
+# _LT_AC_SYS_LIBPATH_AIX
+# ----------------------
+# Links a minimal program and checks the executable
+# for the system default hardcoded library path. In most cases,
+# this is /usr/lib:/lib, but when the MPI compilers are used
+# the location of the communication and MPI libs are included too.
+# If we don't find anything, use the default library path according
+# to the aix ld manual.
+AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX],
+[AC_LINK_IFELSE(AC_LANG_PROGRAM,[
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi],[])
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+])# _LT_AC_SYS_LIBPATH_AIX
+
+
+# _LT_AC_SHELL_INIT(ARG)
+# ----------------------
+AC_DEFUN([_LT_AC_SHELL_INIT],
+[ifdef([AC_DIVERSION_NOTICE],
+ [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)],
+ [AC_DIVERT_PUSH(NOTICE)])
+$1
+AC_DIVERT_POP
+])# _LT_AC_SHELL_INIT
+
+
+# _LT_AC_PROG_ECHO_BACKSLASH
+# --------------------------
+# Add some code to the start of the generated configure script which
+# will find an echo command which doesn't interpret backslashes.
+AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH],
+[_LT_AC_SHELL_INIT([
+# Check that we are running under the correct shell.
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+case X$ECHO in
+X*--fallback-echo)
+ # Remove one level of quotation (which was required for Make).
+ ECHO=`echo "$ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','`
+ ;;
+esac
+
+echo=${ECHO-echo}
+if test "X[$]1" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+elif test "X[$]1" = X--fallback-echo; then
+ # Avoid inline document here, it may be left over
+ :
+elif test "X`($echo '\t') 2>/dev/null`" = 'X\t' ; then
+ # Yippee, $echo works!
+ :
+else
+ # Restart under the correct shell.
+ exec $SHELL "[$]0" --no-reexec ${1+"[$]@"}
+fi
+
+if test "X[$]1" = X--fallback-echo; then
+ # used as fallback echo
+ shift
+ cat <<EOF
+[$]*
+EOF
+ exit 0
+fi
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test -z "$ECHO"; then
+if test "X${echo_test_string+set}" != Xset; then
+# find a string as large as possible, as long as the shell can cope with it
+ for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do
+ # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
+ if (echo_test_string=`eval $cmd`) 2>/dev/null &&
+ echo_test_string=`eval $cmd` &&
+ (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null
+ then
+ break
+ fi
+ done
+fi
+
+if test "X`($echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ :
+else
+ # The Solaris, AIX, and Digital Unix default echo programs unquote
+ # backslashes. This makes it impossible to quote backslashes using
+ # echo "$something" | sed 's/\\/\\\\/g'
+ #
+ # So, first we look for a working echo in the user's PATH.
+
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for dir in $PATH /usr/ucb; do
+ IFS="$lt_save_ifs"
+ if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
+ test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ echo="$dir/echo"
+ break
+ fi
+ done
+ IFS="$lt_save_ifs"
+
+ if test "X$echo" = Xecho; then
+ # We didn't find a better echo, so look for alternatives.
+ if test "X`(print -r '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`(print -r "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ # This shell has a builtin print -r that does the trick.
+ echo='print -r'
+ elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) &&
+ test "X$CONFIG_SHELL" != X/bin/ksh; then
+ # If we have ksh, try running configure again with it.
+ ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh}
+ export ORIGINAL_CONFIG_SHELL
+ CONFIG_SHELL=/bin/ksh
+ export CONFIG_SHELL
+ exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"}
+ else
+ # Try using printf.
+ echo='printf %s\n'
+ if test "X`($echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ # Cool, printf works
+ :
+ elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
+ test "X$echo_testing_string" = 'X\t' &&
+ echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL
+ export CONFIG_SHELL
+ SHELL="$CONFIG_SHELL"
+ export SHELL
+ echo="$CONFIG_SHELL [$]0 --fallback-echo"
+ elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
+ test "X$echo_testing_string" = 'X\t' &&
+ echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ echo="$CONFIG_SHELL [$]0 --fallback-echo"
+ else
+ # maybe with a smaller string...
+ prev=:
+
+ for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do
+ if (test "X$echo_test_string" = "X`eval $cmd`") 2>/dev/null
+ then
+ break
+ fi
+ prev="$cmd"
+ done
+
+ if test "$prev" != 'sed 50q "[$]0"'; then
+ echo_test_string=`eval $prev`
+ export echo_test_string
+ exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"}
+ else
+ # Oops. We lost completely, so just stick with echo.
+ echo=echo
+ fi
+ fi
+ fi
+ fi
+fi
+fi
+
+# Copy echo and quote the copy suitably for passing to libtool from
+# the Makefile, instead of quoting the original, which is used later.
+ECHO=$echo
+if test "X$ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then
+ ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo"
+fi
+
+AC_SUBST(ECHO)
+])])# _LT_AC_PROG_ECHO_BACKSLASH
+
+
+# _LT_AC_LOCK
+# -----------
+AC_DEFUN([_LT_AC_LOCK],
+[AC_ARG_ENABLE([libtool-lock],
+ [AS_HELP_STRING([--disable-libtool-lock],[avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *ELF-32*)
+ HPUX_IA64_MODE="32"
+ ;;
+ *ELF-64*)
+ HPUX_IA64_MODE="64"
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+*-*-irix6*)
+ # Find out which ABI we are using.
+ echo '[#]line __oline__ "configure"' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *32-bit*)
+ LD="${LD-ld} -melf32bsmip"
+ ;;
+ *N32*)
+ LD="${LD-ld} -melf32bmipn32"
+ ;;
+ *64-bit*)
+ LD="${LD-ld} -melf64bmip"
+ ;;
+ esac
+ else
+ case `/usr/bin/file conftest.$ac_objext` in
+ *32-bit*)
+ LD="${LD-ld} -32"
+ ;;
+ *N32*)
+ LD="${LD-ld} -n32"
+ ;;
+ *64-bit*)
+ LD="${LD-ld} -64"
+ ;;
+ esac
+ fi
+ fi
+ rm -rf conftest*
+ ;;
+
+x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*|s390*-*linux*|sparc*-*linux*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ case `/usr/bin/file conftest.o` in
+ *32-bit*)
+ case $host in
+ x86_64-*linux*)
+ LD="${LD-ld} -m elf_i386"
+ ;;
+ ppc64-*linux*|powerpc64-*linux*)
+ LD="${LD-ld} -m elf32ppclinux"
+ ;;
+ s390x-*linux*)
+ LD="${LD-ld} -m elf_s390"
+ ;;
+ sparc64-*linux*)
+ LD="${LD-ld} -m elf32_sparc"
+ ;;
+ esac
+ ;;
+ *64-bit*)
+ case $host in
+ x86_64-*linux*)
+ LD="${LD-ld} -m elf_x86_64"
+ ;;
+ ppc*-*linux*|powerpc*-*linux*)
+ LD="${LD-ld} -m elf64ppc"
+ ;;
+ s390*-*linux*)
+ LD="${LD-ld} -m elf64_s390"
+ ;;
+ sparc*-*linux*)
+ LD="${LD-ld} -m elf64_sparc"
+ ;;
+ esac
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+
+*-*-sco3.2v5*)
+ # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+ SAVE_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS -belf"
+ AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
+ [AC_LANG_PUSH(C)
+ AC_LINK_IFELSE([AC_LANG_PROGRAM([[]], [[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
+ AC_LANG_POP])
+ if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+ # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+ CFLAGS="$SAVE_CFLAGS"
+ fi
+ ;;
+sparc*-*solaris*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ case `/usr/bin/file conftest.o` in
+ *64-bit*)
+ case $lt_cv_prog_gnu_ld in
+ yes*) LD="${LD-ld} -m elf64_sparc" ;;
+ *) LD="${LD-ld} -64" ;;
+ esac
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+
+AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL],
+[*-*-cygwin* | *-*-mingw* | *-*-pw32*)
+ AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+ AC_CHECK_TOOL(AS, as, false)
+ AC_CHECK_TOOL(OBJDUMP, objdump, false)
+ ;;
+ ])
+esac
+
+need_locks="$enable_libtool_lock"
+
+])# _LT_AC_LOCK
+
+
+# AC_LIBTOOL_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+# [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION],
+[AC_REQUIRE([LT_AC_PROG_SED])
+AC_CACHE_CHECK([$1], [$2],
+ [$2=no
+ ifelse([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+ lt_compiler_flag="$3"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ # The option is referenced via a variable to avoid confusing sed.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+ (eval "$lt_compile" 2>conftest.err)
+ ac_status=$?
+ cat conftest.err >&AS_MESSAGE_LOG_FD
+ echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+ if (exit $ac_status) && test -s "$ac_outfile"; then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings other than the usual output.
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+ $2=yes
+ fi
+ fi
+ $rm conftest*
+])
+
+if test x"[$]$2" = xyes; then
+ ifelse([$5], , :, [$5])
+else
+ ifelse([$6], , :, [$6])
+fi
+])# AC_LIBTOOL_COMPILER_OPTION
+
+
+# AC_LIBTOOL_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+# [ACTION-SUCCESS], [ACTION-FAILURE])
+# ------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([AC_LIBTOOL_LINKER_OPTION],
+[AC_CACHE_CHECK([$1], [$2],
+ [$2=no
+ save_LDFLAGS="$LDFLAGS"
+ LDFLAGS="$LDFLAGS $3"
+ printf "$lt_simple_link_test_code" > conftest.$ac_ext
+ if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+ # The linker can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ if test -s conftest.err; then
+ # Append any errors to the config.log.
+ cat conftest.err 1>&AS_MESSAGE_LOG_FD
+ $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if diff conftest.exp conftest.er2 >/dev/null; then
+ $2=yes
+ fi
+ else
+ $2=yes
+ fi
+ fi
+ $rm conftest*
+ LDFLAGS="$save_LDFLAGS"
+])
+
+if test x"[$]$2" = xyes; then
+ ifelse([$4], , :, [$4])
+else
+ ifelse([$5], , :, [$5])
+fi
+])# AC_LIBTOOL_LINKER_OPTION
+
+
+# AC_LIBTOOL_SYS_MAX_CMD_LEN
+# --------------------------
+AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN],
+[# find the maximum length of command line arguments
+AC_MSG_CHECKING([the maximum length of command line arguments])
+AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
+ i=0
+ teststring="ABCD"
+
+ case $build_os in
+ msdosdjgpp*)
+ # On DJGPP, this test can blow up pretty badly due to problems in libc
+ # (any single argument exceeding 2000 bytes causes a buffer overrun
+ # during glob expansion). Even if it were fixed, the result of this
+ # check would be larger than it should be.
+ lt_cv_sys_max_cmd_len=12288; # 12K is about right
+ ;;
+
+ gnu*)
+ # Under GNU Hurd, this test is not required because there is
+ # no limit to the length of command line arguments.
+ # Libtool will interpret -1 as no limit whatsoever
+ lt_cv_sys_max_cmd_len=-1;
+ ;;
+
+ cygwin* | mingw*)
+ # On Win9x/ME, this test blows up -- it succeeds, but takes
+ # about 5 minutes as the teststring grows exponentially.
+ # Worse, since 9x/ME are not pre-emptively multitasking,
+ # you end up with a "frozen" computer, even though with patience
+ # the test eventually succeeds (with a max line length of 256k).
+ # Instead, let's just punt: use the minimum linelength reported by
+ # all of the supported platforms: 8192 (on NT/2K/XP).
+ lt_cv_sys_max_cmd_len=8192;
+ ;;
+
+ amigaos*)
+ # On AmigaOS with pdksh, this test takes hours, literally.
+ # So we just punt and use a minimum line length of 8192.
+ lt_cv_sys_max_cmd_len=8192;
+ ;;
+
+ netbsd* | freebsd* | openbsd* | darwin* | dragonfly* | bitrig*)
+ # This has been around since 386BSD, at least. Likely further.
+ if test -x /sbin/sysctl; then
+ lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+ elif test -x /usr/sbin/sysctl; then
+ lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+ else
+ lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs
+ fi
+ # And add a safety zone
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+ ;;
+
+ interix*)
+ # We know the value 262144 and hardcode it with a safety zone (like BSD)
+ lt_cv_sys_max_cmd_len=196608
+ ;;
+
+ osf*)
+ # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+ # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+ # nice to cause kernel panics so lets avoid the loop below.
+ # First set a reasonable default.
+ lt_cv_sys_max_cmd_len=16384
+ #
+ if test -x /sbin/sysconfig; then
+ case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+ *1*) lt_cv_sys_max_cmd_len=-1 ;;
+ esac
+ fi
+ ;;
+ sco3.2v5*)
+ lt_cv_sys_max_cmd_len=102400
+ ;;
+ sysv5* | sco5v6* | sysv4.2uw2*)
+ kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+ if test -n "$kargmax"; then
+ lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'`
+ else
+ lt_cv_sys_max_cmd_len=32768
+ fi
+ ;;
+ *)
+ # If test is not a shell built-in, we'll probably end up computing a
+ # maximum length that is only half of the actual maximum length, but
+ # we can't tell.
+ SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+ while (test "X"`$SHELL [$]0 --fallback-echo "X$teststring" 2>/dev/null` \
+ = "XX$teststring") >/dev/null 2>&1 &&
+ new_result=`expr "X$teststring" : ".*" 2>&1` &&
+ lt_cv_sys_max_cmd_len=$new_result &&
+ test $i != 17 # 1/2 MB should be enough
+ do
+ i=`expr $i + 1`
+ teststring=$teststring$teststring
+ done
+ teststring=
+ # Add a significant safety factor because C++ compilers can tack on massive
+ # amounts of additional arguments before passing them to the linker.
+ # It appears as though 1/2 is a usable value.
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+ ;;
+ esac
+])
+if test -n $lt_cv_sys_max_cmd_len ; then
+ AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
+else
+ AC_MSG_RESULT(none)
+fi
+])# AC_LIBTOOL_SYS_MAX_CMD_LEN
+
+
+# _LT_AC_CHECK_DLFCN
+# ------------------
+AC_DEFUN([_LT_AC_CHECK_DLFCN],
+[AC_CHECK_HEADERS(dlfcn.h)dnl
+])# _LT_AC_CHECK_DLFCN
+
+
+# _LT_AC_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
+# ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
+# ---------------------------------------------------------------------
+AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF],
+[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl
+if test "$cross_compiling" = yes; then :
+ [$4]
+else
+ lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+ lt_status=$lt_dlunknown
+ cat > conftest.$ac_ext <<EOF
+[#line __oline__ "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+# define LT_DLGLOBAL RTLD_GLOBAL
+#else
+# ifdef DL_GLOBAL
+# define LT_DLGLOBAL DL_GLOBAL
+# else
+# define LT_DLGLOBAL 0
+# endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+ find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+# ifdef RTLD_LAZY
+# define LT_DLLAZY_OR_NOW RTLD_LAZY
+# else
+# ifdef DL_LAZY
+# define LT_DLLAZY_OR_NOW DL_LAZY
+# else
+# ifdef RTLD_NOW
+# define LT_DLLAZY_OR_NOW RTLD_NOW
+# else
+# ifdef DL_NOW
+# define LT_DLLAZY_OR_NOW DL_NOW
+# else
+# define LT_DLLAZY_OR_NOW 0
+# endif
+# endif
+# endif
+# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
+
+void fnord() { int i=42;}
+int main ()
+{
+ void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+ int status = $lt_dlunknown;
+
+ if (self)
+ {
+ if (dlsym (self,"fnord")) status = $lt_dlno_uscore;
+ else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+ /* dlclose (self); */
+ }
+ else
+ puts (dlerror ());
+
+ exit (status);
+}]
+EOF
+ if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
+ (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
+ lt_status=$?
+ case x$lt_status in
+ x$lt_dlno_uscore) $1 ;;
+ x$lt_dlneed_uscore) $2 ;;
+ x$lt_dlunknown|x*) $3 ;;
+ esac
+ else :
+ # compilation failed
+ $3
+ fi
+fi
+rm -fr conftest*
+])# _LT_AC_TRY_DLOPEN_SELF
+
+
+# AC_LIBTOOL_DLOPEN_SELF
+# ----------------------
+AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF],
+[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl
+if test "x$enable_dlopen" != xyes; then
+ enable_dlopen=unknown
+ enable_dlopen_self=unknown
+ enable_dlopen_self_static=unknown
+else
+ lt_cv_dlopen=no
+ lt_cv_dlopen_libs=
+
+ case $host_os in
+ beos*)
+ lt_cv_dlopen="load_add_on"
+ lt_cv_dlopen_libs=
+ lt_cv_dlopen_self=yes
+ ;;
+
+ mingw* | pw32*)
+ lt_cv_dlopen="LoadLibrary"
+ lt_cv_dlopen_libs=
+ ;;
+
+ cygwin*)
+ lt_cv_dlopen="dlopen"
+ lt_cv_dlopen_libs=
+ ;;
+
+ darwin*)
+ # if libdl is installed we need to link against it
+ AC_CHECK_LIB([dl], [dlopen],
+ [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
+ lt_cv_dlopen="dyld"
+ lt_cv_dlopen_libs=
+ lt_cv_dlopen_self=yes
+ ])
+ ;;
+
+ *)
+ AC_CHECK_FUNC([shl_load],
+ [lt_cv_dlopen="shl_load"],
+ [AC_CHECK_LIB([dld], [shl_load],
+ [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld"],
+ [AC_CHECK_FUNC([dlopen],
+ [lt_cv_dlopen="dlopen"],
+ [AC_CHECK_LIB([dl], [dlopen],
+ [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
+ [AC_CHECK_LIB([svld], [dlopen],
+ [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
+ [AC_CHECK_LIB([dld], [dld_link],
+ [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld"])
+ ])
+ ])
+ ])
+ ])
+ ])
+ ;;
+ esac
+
+ if test "x$lt_cv_dlopen" != xno; then
+ enable_dlopen=yes
+ else
+ enable_dlopen=no
+ fi
+
+ case $lt_cv_dlopen in
+ dlopen)
+ save_CPPFLAGS="$CPPFLAGS"
+ test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+ save_LDFLAGS="$LDFLAGS"
+ wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+ save_LIBS="$LIBS"
+ LIBS="$lt_cv_dlopen_libs $LIBS"
+
+ AC_CACHE_CHECK([whether a program can dlopen itself],
+ lt_cv_dlopen_self, [dnl
+ _LT_AC_TRY_DLOPEN_SELF(
+ lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
+ lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
+ ])
+
+ if test "x$lt_cv_dlopen_self" = xyes; then
+ wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+ AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
+ lt_cv_dlopen_self_static, [dnl
+ _LT_AC_TRY_DLOPEN_SELF(
+ lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
+ lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross)
+ ])
+ fi
+
+ CPPFLAGS="$save_CPPFLAGS"
+ LDFLAGS="$save_LDFLAGS"
+ LIBS="$save_LIBS"
+ ;;
+ esac
+
+ case $lt_cv_dlopen_self in
+ yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+ *) enable_dlopen_self=unknown ;;
+ esac
+
+ case $lt_cv_dlopen_self_static in
+ yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+ *) enable_dlopen_self_static=unknown ;;
+ esac
+fi
+])# AC_LIBTOOL_DLOPEN_SELF
+
+
+# AC_LIBTOOL_PROG_CC_C_O([TAGNAME])
+# ---------------------------------
+# Check to see if options -c and -o are simultaneously supported by compiler
+AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O],
+[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
+AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
+ [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
+ [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
+ $rm -r conftest 2>/dev/null
+ mkdir conftest
+ cd conftest
+ mkdir out
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ lt_compiler_flag="-o out/conftest2.$ac_objext"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+ (eval "$lt_compile" 2>out/conftest.err)
+ ac_status=$?
+ cat out/conftest.err >&AS_MESSAGE_LOG_FD
+ echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+ if (exit $ac_status) && test -s out/conftest2.$ac_objext
+ then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+ $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+ if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+ _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+ fi
+ fi
+ chmod u+w . 2>&AS_MESSAGE_LOG_FD
+ $rm conftest*
+ # SGI C++ compiler will create directory out/ii_files/ for
+ # template instantiation
+ test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
+ $rm out/* && rmdir out
+ cd ..
+ rmdir conftest
+ $rm conftest*
+])
+])# AC_LIBTOOL_PROG_CC_C_O
+
+
+# AC_LIBTOOL_SYS_HARD_LINK_LOCKS([TAGNAME])
+# -----------------------------------------
+# Check to see if we can do hard links to lock some files if needed
+AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS],
+[AC_REQUIRE([_LT_AC_LOCK])dnl
+
+hard_links="nottested"
+if test "$_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
+ # do not overwrite the value of need_locks provided by the user
+ AC_MSG_CHECKING([if we can lock with hard links])
+ hard_links=yes
+ $rm conftest*
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ touch conftest.a
+ ln conftest.a conftest.b 2>&5 || hard_links=no
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ AC_MSG_RESULT([$hard_links])
+ if test "$hard_links" = no; then
+ AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
+ need_locks=warn
+ fi
+else
+ need_locks=no
+fi
+])# AC_LIBTOOL_SYS_HARD_LINK_LOCKS
+
+
+# AC_LIBTOOL_OBJDIR
+# -----------------
+AC_DEFUN([AC_LIBTOOL_OBJDIR],
+[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
+[rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+ lt_cv_objdir=.libs
+else
+ # MS-DOS does not allow filenames that begin with a dot.
+ lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null])
+objdir=$lt_cv_objdir
+])# AC_LIBTOOL_OBJDIR
+
+
+# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH([TAGNAME])
+# ----------------------------------------------
+# Check hardcoding attributes.
+AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH],
+[AC_MSG_CHECKING([how to hardcode library paths into programs])
+_LT_AC_TAGVAR(hardcode_action, $1)=
+if test -n "$_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)" || \
+ test -n "$_LT_AC_TAGVAR(runpath_var, $1)" || \
+ test "X$_LT_AC_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
+
+ # We can hardcode non-existent directories.
+ if test "$_LT_AC_TAGVAR(hardcode_direct, $1)" != no &&
+ # If the only mechanism to avoid hardcoding is shlibpath_var, we
+ # have to relink, otherwise we might link with an installed library
+ # when we should be linking with a yet-to-be-installed one
+ ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
+ test "$_LT_AC_TAGVAR(hardcode_minus_L, $1)" != no; then
+ # Linking always hardcodes the temporary library directory.
+ _LT_AC_TAGVAR(hardcode_action, $1)=relink
+ else
+ # We can link without hardcoding, and we can hardcode nonexisting dirs.
+ _LT_AC_TAGVAR(hardcode_action, $1)=immediate
+ fi
+else
+ # We cannot hardcode anything, or else we can only hardcode existing
+ # directories.
+ _LT_AC_TAGVAR(hardcode_action, $1)=unsupported
+fi
+AC_MSG_RESULT([$_LT_AC_TAGVAR(hardcode_action, $1)])
+
+if test "$_LT_AC_TAGVAR(hardcode_action, $1)" = relink; then
+ # Fast installation is not supported
+ enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+ test "$enable_shared" = no; then
+ # Fast installation is not necessary
+ enable_fast_install=needless
+fi
+])# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH
+
+
+# AC_LIBTOOL_SYS_LIB_STRIP
+# ------------------------
+AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP],
+[striplib=
+old_striplib=
+AC_MSG_CHECKING([whether stripping libraries is possible])
+if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
+ test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+ test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+ AC_MSG_RESULT([yes])
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+ case $host_os in
+ darwin*)
+ if test -n "$STRIP" ; then
+ striplib="$STRIP -x"
+ AC_MSG_RESULT([yes])
+ else
+ AC_MSG_RESULT([no])
+fi
+ ;;
+ *)
+ AC_MSG_RESULT([no])
+ ;;
+ esac
+fi
+])# AC_LIBTOOL_SYS_LIB_STRIP
+
+
+# AC_LIBTOOL_SYS_DYNAMIC_LINKER
+# -----------------------------
+# PORTME Fill in your ld.so characteristics
+AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER],
+[AC_MSG_CHECKING([dynamic linker characteristics])
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
+ # if the path contains ";" then we assume it to be the separator
+ # otherwise default to the standard path separator (i.e. ":") - it is
+ # assumed that no part of a normal pathname contains ";" but that should
+ # okay in the real world where ";" in dirpaths is itself problematic.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+else
+ sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+ shlibpath_var=LIBPATH
+
+ # AIX 3 has no versioning support, so we append a major version to the name.
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+
+aix4* | aix5*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ hardcode_into_libs=yes
+ if test "$host_cpu" = ia64; then
+ # AIX 5 supports IA64
+ library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ else
+ # With GCC up to 2.95.x, collect2 would create an import file
+ # for dependence libraries. The import file would start with
+ # the line `#! .'. This would cause the generated library to
+ # depend on `.', always an invalid library. This was fixed in
+ # development snapshots of GCC prior to 3.0.
+ case $host_os in
+ aix4 | aix4.[[01]] | aix4.[[01]].*)
+ if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+ echo ' yes '
+ echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+ :
+ else
+ can_build_shared=no
+ fi
+ ;;
+ esac
+ # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+ # soname into executable. Probably we can add versioning support to
+ # collect2, so additional links can be useful in future.
+ if test "$aix_use_runtimelinking" = yes; then
+ # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+ # instead of lib<name>.a to let people know that these are not
+ # typical AIX shared libraries.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ else
+ # We preserve .a as extension for shared libraries through AIX4.2
+ # and later when we are not doing run time linking.
+ library_names_spec='${libname}${release}.a $libname.a'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ fi
+ shlibpath_var=LIBPATH
+ fi
+ ;;
+
+amigaos*)
+ library_names_spec='$libname.ixlibrary $libname.a'
+ # Create ${libname}_ixlibrary.a entries in /sys/libs.
+ finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+ ;;
+
+beos*)
+ library_names_spec='${libname}${shared_ext}'
+ dynamic_linker="$host_os ld.so"
+ shlibpath_var=LIBRARY_PATH
+ ;;
+
+bsdi[[45]]*)
+ version_type=linux
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+ sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+ # the default ld.so.conf also contains /usr/contrib/lib and
+ # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+ # libtool to hard-code these into programs
+ ;;
+
+cygwin* | mingw* | pw32*)
+ version_type=windows
+ shrext_cmds=".dll"
+ need_version=no
+ need_lib_prefix=no
+
+ case $GCC,$host_os in
+ yes,cygwin* | yes,mingw* | yes,pw32*)
+ library_names_spec='$libname.dll.a'
+ # DLL is installed to $(libdir)/../bin by postinstall_cmds
+ postinstall_cmds='base_file=`basename \${file}`~
+ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
+ dldir=$destdir/`dirname \$dlpath`~
+ test -d \$dldir || mkdir -p \$dldir~
+ $install_prog $dir/$dlname \$dldir/$dlname~
+ chmod a+x \$dldir/$dlname'
+ postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+ dlpath=$dir/\$dldll~
+ $rm \$dlpath'
+ shlibpath_overrides_runpath=yes
+
+ case $host_os in
+ cygwin*)
+ # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+ soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+ ;;
+ mingw*)
+ # MinGW DLLs use traditional 'lib' prefix
+ soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | [grep ';[c-zC-Z]:/' >/dev/null]; then
+ # It is most probably a Windows format PATH printed by
+ # mingw gcc, but we are running on Cygwin. Gcc prints its search
+ # path with ; separators, and with drive letters. We can handle the
+ # drive letters (cygwin fileutils understands them), so leave them,
+ # especially as we might pass files found there to a mingw objdump,
+ # which wouldn't understand a cygwinified path. Ahh.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+ ;;
+ pw32*)
+ # pw32 DLLs use 'pw' prefix rather than 'lib'
+ library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+ ;;
+ esac
+ ;;
+
+ *)
+ library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+ ;;
+ esac
+ dynamic_linker='Win32 ld.exe'
+ # FIXME: first we should search . and the directory the executable is in
+ shlibpath_var=PATH
+ ;;
+
+darwin* | rhapsody*)
+ dynamic_linker="$host_os dyld"
+ version_type=darwin
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+ soname_spec='${libname}${release}${major}$shared_ext'
+ shlibpath_overrides_runpath=yes
+ shlibpath_var=DYLD_LIBRARY_PATH
+ shrext_cmds='.dylib'
+ # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
+ if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
+ else
+ sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
+ fi
+ sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+ ;;
+
+dgux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+freebsd1.*)
+ dynamic_linker=no
+ ;;
+
+kfreebsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+freebsd* | dragonfly*)
+ # DragonFly does not have aout. When/if they implement a new
+ # versioning mechanism, adjust this.
+ if test -x /usr/bin/objformat; then
+ objformat=`/usr/bin/objformat`
+ else
+ case $host_os in
+ freebsd[[123]].*) objformat=aout ;;
+ *) objformat=elf ;;
+ esac
+ fi
+ version_type=freebsd-$objformat
+ case $version_type in
+ freebsd-elf*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ need_version=no
+ need_lib_prefix=no
+ ;;
+ freebsd-*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+ need_version=yes
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_os in
+ freebsd2.*)
+ shlibpath_overrides_runpath=yes
+ ;;
+ freebsd3.[[01]]* | freebsdelf3.[[01]]*)
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
+ freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+ freebsd*) # from 4.6 on
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ esac
+ ;;
+
+gnu*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ ;;
+
+hpux9* | hpux10* | hpux11*)
+ # Give a soname corresponding to the major version so that dld.sl refuses to
+ # link against other versions.
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ case $host_cpu in
+ ia64*)
+ shrext_cmds='.so'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.so"
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ if test "X$HPUX_IA64_MODE" = X32; then
+ sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+ else
+ sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+ fi
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ hppa*64*)
+ shrext_cmds='.sl'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ *)
+ shrext_cmds='.sl'
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=SHLIB_PATH
+ shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+ esac
+ # HP-UX runs *really* slowly unless shared libraries are mode 555.
+ postinstall_cmds='chmod 555 $lib'
+ ;;
+
+interix3*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $host_os in
+ nonstopux*) version_type=nonstopux ;;
+ *)
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ version_type=linux
+ else
+ version_type=irix
+ fi ;;
+ esac
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+ case $host_os in
+ irix5* | nonstopux*)
+ libsuff= shlibsuff=
+ ;;
+ *)
+ case $LD in # libtool.m4 will add one of these switches to LD
+ *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+ libsuff= shlibsuff= libmagic=32-bit;;
+ *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+ libsuff=32 shlibsuff=N32 libmagic=N32;;
+ *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+ libsuff=64 shlibsuff=64 libmagic=64-bit;;
+ *) libsuff= shlibsuff= libmagic=never-match;;
+ esac
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+ sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+ hardcode_into_libs=yes
+ ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+ dynamic_linker=no
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ # This implies no fast_install, which is unacceptable.
+ # Some rework will be needed to allow for fast_install
+ # before this can be enabled.
+ hardcode_into_libs=yes
+
+ # Append ld.so.conf contents to the search path
+ if test -f /etc/ld.so.conf; then
+ lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+ sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+ fi
+
+ # We used to test for /lib/ld.so.1 and disable shared libraries on
+ # powerpc, because MkLinux only supported shared libraries with the
+ # GNU dynamic linker. Since this was broken with cross compilers,
+ # most powerpc-linux boxes support dynamic linking these days and
+ # people can always --disable-shared, the test was removed, and we
+ # assume the GNU/Linux dynamic linker is in use.
+ dynamic_linker='GNU/Linux ld.so'
+ ;;
+
+knetbsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+netbsd*)
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ dynamic_linker='NetBSD (a.out) ld.so'
+ else
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='NetBSD ld.elf_so'
+ fi
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+
+newsos6)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+nto-qnx*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+openbsd* | bitrig*)
+ version_type=sunos
+ sys_lib_dlsearch_path_spec="/usr/lib"
+ need_lib_prefix=no
+ # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+ case $host_os in
+ openbsd3.3 | openbsd3.3.*) need_version=yes ;;
+ *) need_version=no ;;
+ esac
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ case $host_os in
+ openbsd2.[[89]] | openbsd2.[[89]].*)
+ shlibpath_overrides_runpath=no
+ ;;
+ *)
+ shlibpath_overrides_runpath=yes
+ ;;
+ esac
+ else
+ shlibpath_overrides_runpath=yes
+ fi
+ ;;
+
+os2*)
+ libname_spec='$name'
+ shrext_cmds=".dll"
+ need_lib_prefix=no
+ library_names_spec='$libname${shared_ext} $libname.a'
+ dynamic_linker='OS/2 ld.exe'
+ shlibpath_var=LIBPATH
+ ;;
+
+osf3* | osf4* | osf5*)
+ version_type=osf
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+ sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+ ;;
+
+solaris*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ # ldd complains unless libraries are executable
+ postinstall_cmds='chmod +x $lib'
+ ;;
+
+sunos4*)
+ version_type=sunos
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ if test "$with_gnu_ld" = yes; then
+ need_lib_prefix=no
+ fi
+ need_version=yes
+ ;;
+
+sysv4 | sysv4.3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_vendor in
+ sni)
+ shlibpath_overrides_runpath=no
+ need_lib_prefix=no
+ export_dynamic_flag_spec='${wl}-Blargedynsym'
+ runpath_var=LD_RUN_PATH
+ ;;
+ siemens)
+ need_lib_prefix=no
+ ;;
+ motorola)
+ need_lib_prefix=no
+ need_version=no
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+ ;;
+ esac
+ ;;
+
+sysv4*MP*)
+ if test -d /usr/nec ;then
+ version_type=linux
+ library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+ soname_spec='$libname${shared_ext}.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ fi
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ version_type=freebsd-elf
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ if test "$with_gnu_ld" = yes; then
+ sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+ shlibpath_overrides_runpath=no
+ else
+ sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+ shlibpath_overrides_runpath=yes
+ case $host_os in
+ sco3.2v5*)
+ sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+ ;;
+ esac
+ fi
+ sys_lib_dlsearch_path_spec='/usr/lib'
+ ;;
+
+uts4*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+*)
+ dynamic_linker=no
+ ;;
+esac
+AC_MSG_RESULT([$dynamic_linker])
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+ variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+])# AC_LIBTOOL_SYS_DYNAMIC_LINKER
+
+
+# _LT_AC_TAGCONFIG
+# ----------------
+AC_DEFUN([_LT_AC_TAGCONFIG],
+[AC_ARG_WITH([tags],
+ [AS_HELP_STRING([--with-tags@<:@=TAGS@:>@],[include additional configurations @<:@automatic@:>@])],
+ [tagnames="$withval"])
+
+if test -f "$ltmain" && test -n "$tagnames"; then
+ if test ! -f "${ofile}"; then
+ AC_MSG_WARN([output file `$ofile' does not exist])
+ fi
+
+ if test -z "$LTCC"; then
+ eval "`$SHELL ${ofile} --config | grep '^LTCC='`"
+ if test -z "$LTCC"; then
+ AC_MSG_WARN([output file `$ofile' does not look like a libtool script])
+ else
+ AC_MSG_WARN([using `LTCC=$LTCC', extracted from `$ofile'])
+ fi
+ fi
+ if test -z "$LTCFLAGS"; then
+ eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS='`"
+ fi
+
+ # Extract list of available tagged configurations in $ofile.
+ # Note that this assumes the entire list is on one line.
+ available_tags=`grep "^available_tags=" "${ofile}" | $SED -e 's/available_tags=\(.*$\)/\1/' -e 's/\"//g'`
+
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for tagname in $tagnames; do
+ IFS="$lt_save_ifs"
+ # Check whether tagname contains only valid characters
+ case `$echo "X$tagname" | $Xsed -e 's:[[-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,/]]::g'` in
+ "") ;;
+ *) AC_MSG_ERROR([invalid tag name: $tagname])
+ ;;
+ esac
+
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /dev/null
+ then
+ AC_MSG_ERROR([tag name "$tagname" already exists])
+ fi
+
+ # Update the list of available tags.
+ if test -n "$tagname"; then
+ echo appending configuration tag \"$tagname\" to $ofile
+
+ case $tagname in
+ CXX)
+ if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+ ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+ (test "X$CXX" != "Xg++"))) ; then
+ AC_LIBTOOL_LANG_CXX_CONFIG
+ else
+ tagname=""
+ fi
+ ;;
+
+ F77)
+ if test -n "$F77" && test "X$F77" != "Xno"; then
+ AC_LIBTOOL_LANG_F77_CONFIG
+ else
+ tagname=""
+ fi
+ ;;
+
+ GCJ)
+ if test -n "$GCJ" && test "X$GCJ" != "Xno"; then
+ AC_LIBTOOL_LANG_GCJ_CONFIG
+ else
+ tagname=""
+ fi
+ ;;
+
+ RC)
+ AC_LIBTOOL_LANG_RC_CONFIG
+ ;;
+
+ *)
+ AC_MSG_ERROR([Unsupported tag name: $tagname])
+ ;;
+ esac
+
+ # Append the new tag name to the list of available tags.
+ if test -n "$tagname" ; then
+ available_tags="$available_tags $tagname"
+ fi
+ fi
+ done
+ IFS="$lt_save_ifs"
+
+ # Now substitute the updated list of available tags.
+ if eval "sed -e 's/^available_tags=.*\$/available_tags=\"$available_tags\"/' \"$ofile\" > \"${ofile}T\""; then
+ mv "${ofile}T" "$ofile"
+ chmod +x "$ofile"
+ else
+ rm -f "${ofile}T"
+ AC_MSG_ERROR([unable to update list of available tagged configurations.])
+ fi
+fi
+])# _LT_AC_TAGCONFIG
+
+
+# AC_LIBTOOL_DLOPEN
+# -----------------
+# enable checks for dlopen support
+AC_DEFUN([AC_LIBTOOL_DLOPEN],
+ [AC_BEFORE([$0],[AC_LIBTOOL_SETUP])
+])# AC_LIBTOOL_DLOPEN
+
+
+# AC_LIBTOOL_WIN32_DLL
+# --------------------
+# declare package support for building win32 DLLs
+AC_DEFUN([AC_LIBTOOL_WIN32_DLL],
+[AC_BEFORE([$0], [AC_LIBTOOL_SETUP])
+])# AC_LIBTOOL_WIN32_DLL
+
+
+# AC_ENABLE_SHARED([DEFAULT])
+# ---------------------------
+# implement the --enable-shared flag
+# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'.
+AC_DEFUN([AC_ENABLE_SHARED],
+[define([enable_shared_default], ifelse($1, no, no, yes))dnl
+AC_ARG_ENABLE([shared],
+ AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],[build shared libraries @<:@default=enable_shared_default@:>@]),
+ [p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_shared=yes ;;
+ no) enable_shared=no ;;
+ *)
+ enable_shared=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_shared=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac],
+ [enable_shared=]enable_shared_default)
+])# AC_ENABLE_SHARED
+
+
+# AC_DISABLE_SHARED
+# -----------------
+# set the default shared flag to --disable-shared
+AC_DEFUN([AC_DISABLE_SHARED],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+AC_ENABLE_SHARED(no)
+])# AC_DISABLE_SHARED
+
+
+# AC_ENABLE_STATIC([DEFAULT])
+# ---------------------------
+# implement the --enable-static flag
+# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'.
+AC_DEFUN([AC_ENABLE_STATIC],
+[define([enable_static_default], ifelse($1, no, no, yes))dnl
+AC_ARG_ENABLE([static],
+ AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],[build static libraries @<:@default=enable_static_default@:>@]),
+ [p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_static=yes ;;
+ no) enable_static=no ;;
+ *)
+ enable_static=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_static=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac],
+ [enable_static=]enable_static_default)
+])# AC_ENABLE_STATIC
+
+
+# AC_DISABLE_STATIC
+# -----------------
+# set the default static flag to --disable-static
+AC_DEFUN([AC_DISABLE_STATIC],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+AC_ENABLE_STATIC(no)
+])# AC_DISABLE_STATIC
+
+
+# AC_ENABLE_FAST_INSTALL([DEFAULT])
+# ---------------------------------
+# implement the --enable-fast-install flag
+# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'.
+AC_DEFUN([AC_ENABLE_FAST_INSTALL],
+[define([enable_Fast_install_default], ifelse($1, no, no, yes))dnl
+AC_ARG_ENABLE([fast-install],
+ AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],[optimize for fast installation @<:@default=enable_Fast_install_default@:>@]),
+ [p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_fast_install=yes ;;
+ no) enable_fast_install=no ;;
+ *)
+ enable_fast_install=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_fast_install=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac],
+ [enable_fast_install=]enable_Fast_install_default)
+])# AC_ENABLE_FAST_INSTALL
+
+
+# AC_DISABLE_FAST_INSTALL
+# -----------------------
+# set the default to --disable-fast-install
+AC_DEFUN([AC_DISABLE_FAST_INSTALL],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+AC_ENABLE_FAST_INSTALL(no)
+])# AC_DISABLE_FAST_INSTALL
+
+
+# AC_LIBTOOL_PICMODE([MODE])
+# --------------------------
+# implement the --with-pic flag
+# MODE is either `yes' or `no'. If omitted, it defaults to `both'.
+AC_DEFUN([AC_LIBTOOL_PICMODE],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+pic_mode=ifelse($#,1,$1,default)
+])# AC_LIBTOOL_PICMODE
+
+
+# AC_PROG_EGREP
+# -------------
+# This is predefined starting with Autoconf 2.54, so this conditional
+# definition can be removed once we require Autoconf 2.54 or later.
+m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP],
+[AC_CACHE_CHECK([for egrep], [ac_cv_prog_egrep],
+ [if echo a | (grep -E '(a|b)') >/dev/null 2>&1
+ then ac_cv_prog_egrep='grep -E'
+ else ac_cv_prog_egrep='egrep'
+ fi])
+ EGREP=$ac_cv_prog_egrep
+ AC_SUBST([EGREP])
+])])
+
+
+# AC_PATH_TOOL_PREFIX
+# -------------------
+# find a file program which can recognise shared library
+AC_DEFUN([AC_PATH_TOOL_PREFIX],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_MSG_CHECKING([for $1])
+AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
+[case $MAGIC_CMD in
+[[\\/*] | ?:[\\/]*])
+ lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+ ;;
+*)
+ lt_save_MAGIC_CMD="$MAGIC_CMD"
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+dnl $ac_dummy forces splitting on constant user-supplied paths.
+dnl POSIX.2 word splitting is done only on the output of word expansions,
+dnl not every word. This closes a longstanding sh security hole.
+ ac_dummy="ifelse([$2], , $PATH, [$2])"
+ for ac_dir in $ac_dummy; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ if test -f $ac_dir/$1; then
+ lt_cv_path_MAGIC_CMD="$ac_dir/$1"
+ if test -n "$file_magic_test_file"; then
+ case $deplibs_check_method in
+ "file_magic "*)
+ file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+ MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+ if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+ $EGREP "$file_magic_regex" > /dev/null; then
+ :
+ else
+ cat <<EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such. This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem. Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool@gnu.org
+
+EOF
+ fi ;;
+ esac
+ fi
+ break
+ fi
+ done
+ IFS="$lt_save_ifs"
+ MAGIC_CMD="$lt_save_MAGIC_CMD"
+ ;;
+esac])
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+ AC_MSG_RESULT($MAGIC_CMD)
+else
+ AC_MSG_RESULT(no)
+fi
+])# AC_PATH_TOOL_PREFIX
+
+
+# AC_PATH_MAGIC
+# -------------
+# find a file program which can recognise a shared library
+AC_DEFUN([AC_PATH_MAGIC],
+[AC_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+ if test -n "$ac_tool_prefix"; then
+ AC_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
+ else
+ MAGIC_CMD=:
+ fi
+fi
+])# AC_PATH_MAGIC
+
+
+# AC_PROG_LD
+# ----------
+# find the pathname to the GNU or non-GNU linker
+AC_DEFUN([AC_PROG_LD],
+[AC_ARG_WITH([gnu-ld],
+ [AS_HELP_STRING([--with-gnu-ld],[assume the C compiler uses GNU ld @<:@default=no@:>@])],
+ [test "$withval" = no || with_gnu_ld=yes],
+ [with_gnu_ld=no])
+AC_REQUIRE([LT_AC_PROG_SED])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+ac_prog=ld
+if test "$GCC" = yes; then
+ # Check if gcc -print-prog-name=ld gives a path.
+ AC_MSG_CHECKING([for ld used by $CC])
+ case $host in
+ *-*-mingw*)
+ # gcc leaves a trailing carriage return which upsets mingw
+ ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+ *)
+ ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+ esac
+ case $ac_prog in
+ # Accept absolute paths.
+ [[\\/]]* | ?:[[\\/]]*)
+ re_direlt='/[[^/]][[^/]]*/\.\./'
+ # Canonicalize the pathname of ld
+ ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'`
+ while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
+ ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"`
+ done
+ test -z "$LD" && LD="$ac_prog"
+ ;;
+ "")
+ # If it fails, then pretend we aren't using GCC.
+ ac_prog=ld
+ ;;
+ *)
+ # If it is relative, then search for the first ld in PATH.
+ with_gnu_ld=unknown
+ ;;
+ esac
+elif test "$with_gnu_ld" = yes; then
+ AC_MSG_CHECKING([for GNU ld])
+else
+ AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(lt_cv_path_LD,
+[if test -z "$LD"; then
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for ac_dir in $PATH; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+ lt_cv_path_LD="$ac_dir/$ac_prog"
+ # Check to see if the program is GNU ld. I'd rather use --version,
+ # but apparently some variants of GNU ld only accept -v.
+ # Break only if it was the GNU/non-GNU ld that we prefer.
+ case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+ *GNU* | *'with BFD'*)
+ test "$with_gnu_ld" != no && break
+ ;;
+ *)
+ test "$with_gnu_ld" != yes && break
+ ;;
+ esac
+ fi
+ done
+ IFS="$lt_save_ifs"
+else
+ lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+ AC_MSG_RESULT($LD)
+else
+ AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+AC_PROG_LD_GNU
+])# AC_PROG_LD
+
+
+# AC_PROG_LD_GNU
+# --------------
+AC_DEFUN([AC_PROG_LD_GNU],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+ lt_cv_prog_gnu_ld=yes
+ ;;
+*)
+ lt_cv_prog_gnu_ld=no
+ ;;
+esac])
+with_gnu_ld=$lt_cv_prog_gnu_ld
+])# AC_PROG_LD_GNU
+
+
+# AC_PROG_LD_RELOAD_FLAG
+# ----------------------
+# find reload flag for linker
+# -- PORTME Some linkers may need a different reload flag.
+AC_DEFUN([AC_PROG_LD_RELOAD_FLAG],
+[AC_CACHE_CHECK([for $LD option to reload object files],
+ lt_cv_ld_reload_flag,
+ [lt_cv_ld_reload_flag='-r'])
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+ darwin*)
+ if test "$GCC" = yes; then
+ reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r $compiler_flags -o $output$reload_objs'
+ else
+ reload_cmds='$LD$reload_flag -o $output$reload_objs'
+ fi
+ ;;
+esac
+])# AC_PROG_LD_RELOAD_FLAG
+
+
+# AC_DEPLIBS_CHECK_METHOD
+# -----------------------
+# how to check for library dependencies
+# -- PORTME fill in with the dynamic library characteristics
+AC_DEFUN([AC_DEPLIBS_CHECK_METHOD],
+[AC_CACHE_CHECK([how to recognise dependent libraries],
+lt_cv_deplibs_check_method,
+[lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
+
+case $host_os in
+aix4* | aix5*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+beos*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+bsdi[[45]]*)
+ lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
+ lt_cv_file_magic_cmd='/usr/bin/file -L'
+ lt_cv_file_magic_test_file=/shlib/libc.so
+ ;;
+
+cygwin*)
+ # func_win32_libid is a shell function defined in ltmain.sh
+ lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+ lt_cv_file_magic_cmd='func_win32_libid'
+ ;;
+
+mingw* | pw32*)
+ # Base MSYS/MinGW do not provide the 'file' command needed by
+ # func_win32_libid shell function, so use a weaker test based on 'objdump'.
+ lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?'
+ lt_cv_file_magic_cmd='$OBJDUMP -f'
+ ;;
+
+darwin* | rhapsody*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+freebsd* | kfreebsd*-gnu | dragonfly*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
+ case $host_cpu in
+ i*86 )
+ # Not sure whether the presence of OpenBSD here was a mistake.
+ # Let's accept both of them until this is cleared up.
+ lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
+ lt_cv_file_magic_cmd=/usr/bin/file
+ lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+ ;;
+ esac
+ else
+ lt_cv_deplibs_check_method=pass_all
+ fi
+ ;;
+
+gnu*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+hpux10.20* | hpux11*)
+ lt_cv_file_magic_cmd=/usr/bin/file
+ case $host_cpu in
+ ia64*)
+ lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
+ lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+ ;;
+ hppa*64*)
+ [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]']
+ lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+ ;;
+ *)
+ lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library'
+ lt_cv_file_magic_test_file=/usr/lib/libc.sl
+ ;;
+ esac
+ ;;
+
+interix3*)
+ # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $LD in
+ *-32|*"-32 ") libmagic=32-bit;;
+ *-n32|*"-n32 ") libmagic=N32;;
+ *-64|*"-64 ") libmagic=64-bit;;
+ *) libmagic=never-match;;
+ esac
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+ else
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
+ fi
+ ;;
+
+newos6*)
+ lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
+ lt_cv_file_magic_cmd=/usr/bin/file
+ lt_cv_file_magic_test_file=/usr/lib/libnls.so
+ ;;
+
+nto-qnx*)
+ lt_cv_deplibs_check_method=unknown
+ ;;
+
+openbsd*)
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
+ else
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+ fi
+ ;;
+
+osf3* | osf4* | osf5*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+solaris*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+sysv4 | sysv4.3*)
+ case $host_vendor in
+ motorola)
+ lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
+ lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+ ;;
+ ncr)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ sequent)
+ lt_cv_file_magic_cmd='/bin/file'
+ lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
+ ;;
+ sni)
+ lt_cv_file_magic_cmd='/bin/file'
+ lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
+ lt_cv_file_magic_test_file=/lib/libc.so
+ ;;
+ siemens)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ pc)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ esac
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+esac
+])
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
+])# AC_DEPLIBS_CHECK_METHOD
+
+
+# AC_PROG_NM
+# ----------
+# find the pathname to a BSD-compatible name lister
+AC_DEFUN([AC_PROG_NM],
+[AC_CACHE_CHECK([for BSD-compatible nm], lt_cv_path_NM,
+[if test -n "$NM"; then
+ # Let the user override the test.
+ lt_cv_path_NM="$NM"
+else
+ lt_nm_to_check="${ac_tool_prefix}nm"
+ if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+ lt_nm_to_check="$lt_nm_to_check nm"
+ fi
+ for lt_tmp_nm in $lt_nm_to_check; do
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ tmp_nm="$ac_dir/$lt_tmp_nm"
+ if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+ # Check to see if the nm accepts a BSD-compat flag.
+ # Adding the `sed 1q' prevents false positives on HP-UX, which says:
+ # nm: unknown option "B" ignored
+ # Tru64's nm complains that /dev/null is an invalid object file
+ case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+ */dev/null* | *'Invalid file or object type'*)
+ lt_cv_path_NM="$tmp_nm -B"
+ break
+ ;;
+ *)
+ case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+ */dev/null*)
+ lt_cv_path_NM="$tmp_nm -p"
+ break
+ ;;
+ *)
+ lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+ continue # so that we can try to find one that supports BSD flags
+ ;;
+ esac
+ ;;
+ esac
+ fi
+ done
+ IFS="$lt_save_ifs"
+ done
+ test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm
+fi])
+NM="$lt_cv_path_NM"
+])# AC_PROG_NM
+
+
+# AC_CHECK_LIBM
+# -------------
+# check for math library
+AC_DEFUN([AC_CHECK_LIBM],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+LIBM=
+case $host in
+*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*)
+ # These system don't have libm, or don't need it
+ ;;
+*-ncr-sysv4.3*)
+ AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
+ AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
+ ;;
+*)
+ AC_CHECK_LIB(m, cos, LIBM="-lm")
+ ;;
+esac
+])# AC_CHECK_LIBM
+
+
+# AC_LIBLTDL_CONVENIENCE([DIRECTORY])
+# -----------------------------------
+# sets LIBLTDL to the link flags for the libltdl convenience library and
+# LTDLINCL to the include flags for the libltdl header and adds
+# --enable-ltdl-convenience to the configure arguments. Note that
+# AC_CONFIG_SUBDIRS is not called here. If DIRECTORY is not provided,
+# it is assumed to be `libltdl'. LIBLTDL will be prefixed with
+# '${top_builddir}/' and LTDLINCL will be prefixed with '${top_srcdir}/'
+# (note the single quotes!). If your package is not flat and you're not
+# using automake, define top_builddir and top_srcdir appropriately in
+# the Makefiles.
+AC_DEFUN([AC_LIBLTDL_CONVENIENCE],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+ case $enable_ltdl_convenience in
+ no) AC_MSG_ERROR([this package needs a convenience libltdl]) ;;
+ "") enable_ltdl_convenience=yes
+ ac_configure_args="$ac_configure_args --enable-ltdl-convenience" ;;
+ esac
+ LIBLTDL='${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdlc.la
+ LTDLINCL='-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl'])
+ # For backwards non-gettext consistent compatibility...
+ INCLTDL="$LTDLINCL"
+])# AC_LIBLTDL_CONVENIENCE
+
+
+# AC_LIBLTDL_INSTALLABLE([DIRECTORY])
+# -----------------------------------
+# sets LIBLTDL to the link flags for the libltdl installable library and
+# LTDLINCL to the include flags for the libltdl header and adds
+# --enable-ltdl-install to the configure arguments. Note that
+# AC_CONFIG_SUBDIRS is not called here. If DIRECTORY is not provided,
+# and an installed libltdl is not found, it is assumed to be `libltdl'.
+# LIBLTDL will be prefixed with '${top_builddir}/'# and LTDLINCL with
+# '${top_srcdir}/' (note the single quotes!). If your package is not
+# flat and you're not using automake, define top_builddir and top_srcdir
+# appropriately in the Makefiles.
+# In the future, this macro may have to be called after AC_PROG_LIBTOOL.
+AC_DEFUN([AC_LIBLTDL_INSTALLABLE],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+ AC_CHECK_LIB(ltdl, lt_dlinit,
+ [test x"$enable_ltdl_install" != xyes && enable_ltdl_install=no],
+ [if test x"$enable_ltdl_install" = xno; then
+ AC_MSG_WARN([libltdl not installed, but installation disabled])
+ else
+ enable_ltdl_install=yes
+ fi
+ ])
+ if test x"$enable_ltdl_install" = x"yes"; then
+ ac_configure_args="$ac_configure_args --enable-ltdl-install"
+ LIBLTDL='${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdl.la
+ LTDLINCL='-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl'])
+ else
+ ac_configure_args="$ac_configure_args --enable-ltdl-install=no"
+ LIBLTDL="-lltdl"
+ LTDLINCL=
+ fi
+ # For backwards non-gettext consistent compatibility...
+ INCLTDL="$LTDLINCL"
+])# AC_LIBLTDL_INSTALLABLE
+
+
+# AC_LIBTOOL_CXX
+# --------------
+# enable support for C++ libraries
+AC_DEFUN([AC_LIBTOOL_CXX],
+[AC_REQUIRE([_LT_AC_LANG_CXX])
+])# AC_LIBTOOL_CXX
+
+
+# _LT_AC_LANG_CXX
+# ---------------
+AC_DEFUN([_LT_AC_LANG_CXX],
+[AC_REQUIRE([AC_PROG_CXX])
+AC_REQUIRE([_LT_AC_PROG_CXXCPP])
+_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}CXX])
+])# _LT_AC_LANG_CXX
+
+# _LT_AC_PROG_CXXCPP
+# ------------------
+AC_DEFUN([_LT_AC_PROG_CXXCPP],
+[
+AC_REQUIRE([AC_PROG_CXX])
+if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+ ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+ (test "X$CXX" != "Xg++"))) ; then
+ AC_PROG_CXXCPP
+fi
+])# _LT_AC_PROG_CXXCPP
+
+# AC_LIBTOOL_F77
+# --------------
+# enable support for Fortran 77 libraries
+AC_DEFUN([AC_LIBTOOL_F77],
+[AC_REQUIRE([_LT_AC_LANG_F77])
+])# AC_LIBTOOL_F77
+
+
+# _LT_AC_LANG_F77
+# ---------------
+AC_DEFUN([_LT_AC_LANG_F77],
+[AC_REQUIRE([AC_PROG_F77])
+_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}F77])
+])# _LT_AC_LANG_F77
+
+
+# AC_LIBTOOL_GCJ
+# --------------
+# enable support for GCJ libraries
+AC_DEFUN([AC_LIBTOOL_GCJ],
+[AC_REQUIRE([_LT_AC_LANG_GCJ])
+])# AC_LIBTOOL_GCJ
+
+
+# _LT_AC_LANG_GCJ
+# ---------------
+AC_DEFUN([_LT_AC_LANG_GCJ],
+[AC_PROVIDE_IFELSE([AC_PROG_GCJ],[],
+ [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],[],
+ [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ],[],
+ [ifdef([AC_PROG_GCJ],[AC_REQUIRE([AC_PROG_GCJ])],
+ [ifdef([A][M_PROG_GCJ],[AC_REQUIRE([A][M_PROG_GCJ])],
+ [AC_REQUIRE([A][C_PROG_GCJ_OR_A][M_PROG_GCJ])])])])])])
+_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}GCJ])
+])# _LT_AC_LANG_GCJ
+
+
+# AC_LIBTOOL_RC
+# -------------
+# enable support for Windows resource files
+AC_DEFUN([AC_LIBTOOL_RC],
+[AC_REQUIRE([LT_AC_PROG_RC])
+_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}RC])
+])# AC_LIBTOOL_RC
+
+
+# AC_LIBTOOL_LANG_C_CONFIG
+# ------------------------
+# Ensure that the configuration vars for the C compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG], [_LT_AC_LANG_C_CONFIG])
+AC_DEFUN([_LT_AC_LANG_C_CONFIG],
+[lt_save_CC="$CC"
+AC_LANG_PUSH(C)
+
+# Source file extension for C test sources.
+ac_ext=c
+
+# Object file extension for compiled C test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}\n'
+
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1)
+AC_LIBTOOL_PROG_COMPILER_PIC($1)
+AC_LIBTOOL_PROG_CC_C_O($1)
+AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
+AC_LIBTOOL_PROG_LD_SHLIBS($1)
+AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
+AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+AC_LIBTOOL_SYS_LIB_STRIP
+AC_LIBTOOL_DLOPEN_SELF
+
+# Report which library types will actually be built
+AC_MSG_CHECKING([if libtool supports shared libraries])
+AC_MSG_RESULT([$can_build_shared])
+
+AC_MSG_CHECKING([whether to build shared libraries])
+test "$can_build_shared" = "no" && enable_shared=no
+
+# On AIX, shared libraries and static libraries use the same namespace, and
+# are all built from PIC.
+case $host_os in
+aix3*)
+ test "$enable_shared" = yes && enable_static=no
+ if test -n "$RANLIB"; then
+ archive_cmds="$archive_cmds~\$RANLIB \$lib"
+ postinstall_cmds='$RANLIB $lib'
+ fi
+ ;;
+
+aix4* | aix5*)
+ if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+ test "$enable_shared" = yes && enable_static=no
+ fi
+ ;;
+esac
+AC_MSG_RESULT([$enable_shared])
+
+AC_MSG_CHECKING([whether to build static libraries])
+# Make sure either enable_shared or enable_static is yes.
+test "$enable_shared" = yes || enable_static=yes
+AC_MSG_RESULT([$enable_static])
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_POP
+CC="$lt_save_CC"
+])# AC_LIBTOOL_LANG_C_CONFIG
+
+
+# AC_LIBTOOL_LANG_CXX_CONFIG
+# --------------------------
+# Ensure that the configuration vars for the C compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG], [_LT_AC_LANG_CXX_CONFIG(CXX)])
+AC_DEFUN([_LT_AC_LANG_CXX_CONFIG],
+[AC_LANG_PUSH(C++)
+AC_REQUIRE([AC_PROG_CXX])
+AC_REQUIRE([_LT_AC_PROG_CXXCPP])
+
+_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_AC_TAGVAR(allow_undefined_flag, $1)=
+_LT_AC_TAGVAR(always_export_symbols, $1)=no
+_LT_AC_TAGVAR(archive_expsym_cmds, $1)=
+_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_AC_TAGVAR(hardcode_direct, $1)=no
+_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_AC_TAGVAR(hardcode_minus_L, $1)=no
+_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+_LT_AC_TAGVAR(hardcode_automatic, $1)=no
+_LT_AC_TAGVAR(module_cmds, $1)=
+_LT_AC_TAGVAR(module_expsym_cmds, $1)=
+_LT_AC_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_AC_TAGVAR(no_undefined_flag, $1)=
+_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Dependencies to place before and after the object being linked:
+_LT_AC_TAGVAR(predep_objects, $1)=
+_LT_AC_TAGVAR(postdep_objects, $1)=
+_LT_AC_TAGVAR(predeps, $1)=
+_LT_AC_TAGVAR(postdeps, $1)=
+_LT_AC_TAGVAR(compiler_lib_search_path, $1)=
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }\n'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_LD=$LD
+lt_save_GCC=$GCC
+GCC=$GXX
+lt_save_with_gnu_ld=$with_gnu_ld
+lt_save_path_LD=$lt_cv_path_LD
+if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+ lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+else
+ $as_unset lt_cv_prog_gnu_ld
+fi
+if test -n "${lt_cv_path_LDCXX+set}"; then
+ lt_cv_path_LD=$lt_cv_path_LDCXX
+else
+ $as_unset lt_cv_path_LD
+fi
+test -z "${LDCXX+set}" || LD=$LDCXX
+CC=${CXX-"c++"}
+compiler=$CC
+_LT_AC_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+
+# We don't want -fno-exception wen compiling C++ code, so set the
+# no_builtin_flag separately
+if test "$GXX" = yes; then
+ _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+else
+ _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+fi
+
+if test "$GXX" = yes; then
+ # Set up default GNU C++ configuration
+
+ AC_PROG_LD
+
+ # Check if GNU C++ uses GNU ld as the underlying linker, since the
+ # archiving commands below assume that GNU ld is being used.
+ if test "$with_gnu_ld" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+ # If archive_cmds runs LD, not CC, wlarc should be empty
+ # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+ # investigate it a little bit more. (MM)
+ wlarc='${wl}'
+
+ # ancient GNU ld didn't support --whole-archive et. al.
+ if eval "`$CC -print-prog-name=ld` --help 2>&1" | \
+ grep 'no-whole-archive' > /dev/null; then
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ else
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+ fi
+ else
+ with_gnu_ld=no
+ wlarc=
+
+ # A generic and very simple default shared library creation
+ # command for GNU C++ for the case where it uses the native
+ # linker, instead of GNU ld. If possible, this setting should
+ # overridden to take advantage of the native linker features on
+ # the platform it is being used on.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+ fi
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+else
+ GXX=no
+ with_gnu_ld=no
+ wlarc=
+fi
+
+# PORTME: fill in a description of your system's C++ link characteristics
+AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+_LT_AC_TAGVAR(ld_shlibs, $1)=yes
+case $host_os in
+ aix3*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ aix4* | aix5*)
+ if test "$host_cpu" = ia64; then
+ # On IA64, the linker does run time linking by default, so we don't
+ # have to do anything special.
+ aix_use_runtimelinking=no
+ exp_sym_flag='-Bexport'
+ no_entry_flag=""
+ else
+ aix_use_runtimelinking=no
+
+ # Test if we are trying to use run time linking or normal
+ # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+ # need to do runtime linking.
+ case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*)
+ for ld_flag in $LDFLAGS; do
+ case $ld_flag in
+ *-brtl*)
+ aix_use_runtimelinking=yes
+ break
+ ;;
+ esac
+ done
+ ;;
+ esac
+
+ exp_sym_flag='-bexport'
+ no_entry_flag='-bnoentry'
+ fi
+
+ # When large executables or shared objects are built, AIX ld can
+ # have problems creating the table of contents. If linking a library
+ # or program results in "error TOC overflow" add -mminimal-toc to
+ # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not
+ # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+ _LT_AC_TAGVAR(archive_cmds, $1)=''
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+
+ if test "$GXX" = yes; then
+ case $host_os in aix4.[[012]]|aix4.[[012]].*)
+ # We only want to do this on AIX 4.2 and lower, the check
+ # below for broken collect2 doesn't work under 4.3+
+ collect2name=`${CC} -print-prog-name=collect2`
+ if test -f "$collect2name" && \
+ strings "$collect2name" | grep resolve_lib_name >/dev/null
+ then
+ # We have reworked collect2
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ else
+ # We have old collect2
+ _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported
+ # It fails to find uninstalled libraries when the uninstalled
+ # path is not listed in the libpath. Setting hardcode_minus_L
+ # to unsupported forces relinking
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+ fi
+ ;;
+ esac
+ shared_flag='-shared'
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag="$shared_flag "'${wl}-G'
+ fi
+ else
+ # not using gcc
+ if test "$host_cpu" = ia64; then
+ # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+ # chokes on -Wl,-G. The following line is correct:
+ shared_flag='-G'
+ else
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag='${wl}-G'
+ else
+ shared_flag='${wl}-bM:SRE'
+ fi
+ fi
+ fi
+
+ # It seems that -bexpall does not export symbols beginning with
+ # underscore (_), so it is better to generate a list of symbols to export.
+ _LT_AC_TAGVAR(always_export_symbols, $1)=yes
+ if test "$aix_use_runtimelinking" = yes; then
+ # Warning - without using the other runtime loading flags (-brtl),
+ # -berok will link without error, but may produce a broken library.
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='-berok'
+ # Determine the default libpath from the value encoded in an empty executable.
+ _LT_AC_SYS_LIBPATH_AIX
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+ else
+ if test "$host_cpu" = ia64; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+ else
+ # Determine the default libpath from the value encoded in an empty executable.
+ _LT_AC_SYS_LIBPATH_AIX
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+ # Warning - without using the other run time loading flags,
+ # -berok will link without error, but may produce a broken library.
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+ # Exported symbols can be pulled into shared objects from archives
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
+ # This is similar to how AIX traditionally builds its shared libraries.
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+ fi
+ fi
+ ;;
+
+ beos*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
+ # support --undefined. This deserves some investigation. FIXME
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ chorus*)
+ case $cc_basename in
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+ # as there is no search path for DLLs.
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ _LT_AC_TAGVAR(always_export_symbols, $1)=no
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+
+ if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ # If the export-symbols file already is a .def file (1st line
+ # is EXPORTS), use it as is; otherwise, prepend...
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+ cp $export_symbols $output_objdir/$soname.def;
+ else
+ echo EXPORTS > $output_objdir/$soname.def;
+ cat $export_symbols >> $output_objdir/$soname.def;
+ fi~
+ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ darwin* | rhapsody*)
+ case $host_os in
+ rhapsody* | darwin1.[[012]])
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}suppress'
+ ;;
+ *) # Darwin 1.3 on
+ if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ else
+ case ${MACOSX_DEPLOYMENT_TARGET} in
+ 10.[[012]])
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ ;;
+ 10.*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}dynamic_lookup'
+ ;;
+ esac
+ fi
+ ;;
+ esac
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_automatic, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=''
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+
+ if test "$GXX" = yes ; then
+ lt_int_apple_cc_single_mod=no
+ output_verbose_link_cmd='echo'
+ if $CC -dumpspecs 2>&1 | $EGREP 'single_module' >/dev/null ; then
+ lt_int_apple_cc_single_mod=yes
+ fi
+ if test "X$lt_int_apple_cc_single_mod" = Xyes ; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ fi
+ _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ if test "X$lt_int_apple_cc_single_mod" = Xyes ; then
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ fi
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ case $cc_basename in
+ xlc*)
+ output_verbose_link_cmd='echo'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+ _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ ;;
+ *)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ fi
+ ;;
+
+ dgux*)
+ case $cc_basename in
+ ec++*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ ghcx*)
+ # Green Hills C++ Compiler
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+ freebsd[[12]].*)
+ # C++ shared libraries reported to be fairly broken before switch to ELF
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ freebsd-elf*)
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ ;;
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+ # conventions
+ _LT_AC_TAGVAR(ld_shlibs, $1)=yes
+ ;;
+ gnu*)
+ ;;
+ hpux9*)
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+ # but as the default
+ # location of the library.
+
+ case $cc_basename in
+ CC*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ aCC*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "[[-]]L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ else
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+ hpux10*|hpux11*)
+ if test $with_gnu_ld = no; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ case $host_cpu in
+ hppa*64*|ia64*)
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
+ ;;
+ *)
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ ;;
+ esac
+ fi
+ case $host_cpu in
+ hppa*64*|ia64*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+ *)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+ # but as the default
+ # location of the library.
+ ;;
+ esac
+
+ case $cc_basename in
+ CC*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ aCC*)
+ case $host_cpu in
+ hppa*64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ ia64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ esac
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ if test $with_gnu_ld = no; then
+ case $host_cpu in
+ hppa*64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ ia64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ esac
+ fi
+ else
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+ interix3*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+ # Instead, shared libraries are loaded at an image base (0x10000000 by
+ # default) and relocated if they conflict, which is a slow very memory
+ # consuming and fragmenting process. To avoid this, we pick a random,
+ # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+ # time. Moving up from 0x10000000 also allows more sbrk(2) space.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ ;;
+ irix5* | irix6*)
+ case $cc_basename in
+ CC*)
+ # SGI C++
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+
+ # Archives containing C++ object files must be created using
+ # "CC -ar", where "CC" is the IRIX C++ compiler. This is
+ # necessary to make sure instantiated templates are included
+ # in the archive.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ if test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib'
+ fi
+ fi
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ ;;
+ esac
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ ;;
+ linux*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+ # Archives containing C++ object files must be created using
+ # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+ ;;
+ icpc*)
+ # Intel C++
+ with_gnu_ld=yes
+ # version 8.0 and above of icpc choke on multiply defined symbols
+ # if we add $predep_objects and $postdep_objects, however 7.1 and
+ # earlier do not add the objects themselves.
+ case `$CC -V 2>&1` in
+ *"Version 7."*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ ;;
+ *) # Version 8.0 or newer
+ tmp_idyn=
+ case $host_cpu in
+ ia64*) tmp_idyn=' -i_dynamic';;
+ esac
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ ;;
+ esac
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+ ;;
+ pgCC*)
+ # Portland Group C++ compiler
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ ;;
+ cxx*)
+ # Compaq C++
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+ runpath_var=LD_RUN_PATH
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ esac
+ ;;
+ lynxos*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ m88k*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ mvs*)
+ case $cc_basename in
+ cxx*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+ wlarc=
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ fi
+ # Workaround some broken pre-1.5 toolchains
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+ ;;
+ openbsd2*)
+ # C++ shared libraries are fairly broken
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ openbsd* | bitrig*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ fi
+ output_verbose_link_cmd='echo'
+ ;;
+ osf3*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Archives containing C++ object files must be created using
+ # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ cxx*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+ else
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+ osf4* | osf5*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Archives containing C++ object files must be created using
+ # the KAI C++ compiler.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs'
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ cxx*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+ echo "-hidden">> $lib.exp~
+ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~
+ $rm $lib.exp'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+ else
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+ psos*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ sunos4*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.x
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ lcc*)
+ # Lucid
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+ solaris*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.2, 5.x and Centerline C++
+ _LT_AC_TAGVAR(archive_cmds_need_lc,$1)=yes
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ case $host_os in
+ solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+ *)
+ # The C++ compiler is used as linker so we must use $wl
+ # flag to pass the commands to the underlying system
+ # linker. We must also pass each convience library through
+ # to the system linker between allextract/defaultextract.
+ # The C++ compiler will combine linker options so we
+ # cannot just pass the convience library names through
+ # without $wl.
+ # Supported since Solaris 2.6 (maybe 2.5.1?)
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract'
+ ;;
+ esac
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+
+ output_verbose_link_cmd='echo'
+
+ # Archives containing C++ object files must be created using
+ # "CC -xar", where "CC" is the Sun C++ compiler. This is
+ # necessary to make sure instantiated templates are included
+ # in the archive.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+ ;;
+ gcx*)
+ # Green Hills C++ Compiler
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+ # The C++ compiler must be used to create the archive.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+ ;;
+ *)
+ # GNU C++ compiler with Solaris linker
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
+ if $CC --version | grep -v '^2\.7' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd="$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\""
+ else
+ # g++ 2.7 appears to require `-G' NOT `-shared' on this
+ # platform.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd="$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\""
+ fi
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
+ fi
+ ;;
+ esac
+ ;;
+ sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+ _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ runpath_var='LD_RUN_PATH'
+
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ ;;
+ sysv5* | sco3.2v5* | sco5v6*)
+ # Note: We can NOT use -z defs as we might desire, because we do not
+ # link with -lc, and that would cause any symbols used from libc to
+ # always be unresolved, which means just about no library would
+ # ever link correctly. If we're not using GNU ld we use -z text
+ # though, which does catch some bad symbols but isn't as heavy-handed
+ # as -z defs.
+ # For security reasons, it is highly recommended that you always
+ # use absolute paths for naming shared libraries, and exclude the
+ # DT_RUNPATH tag from executables and libraries. But doing so
+ # requires that you compile everything twice, which is a pain.
+ # So that behaviour is only enabled if SCOABSPATH is set to a
+ # non-empty value in the environment. Most likely only useful for
+ # creating official distributions of packages.
+ # This is a hack until libtool officially supports absolute path
+ # names for shared libraries.
+ _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+ runpath_var='LD_RUN_PATH'
+
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ ;;
+ tandem*)
+ case $cc_basename in
+ NCC*)
+ # NonStop-UX NCC 3.20
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+ vxworks*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+esac
+AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)])
+test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+_LT_AC_TAGVAR(GCC, $1)="$GXX"
+_LT_AC_TAGVAR(LD, $1)="$LD"
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+AC_LIBTOOL_POSTDEP_PREDEP($1)
+AC_LIBTOOL_PROG_COMPILER_PIC($1)
+AC_LIBTOOL_PROG_CC_C_O($1)
+AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
+AC_LIBTOOL_PROG_LD_SHLIBS($1)
+AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
+AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_POP
+CC=$lt_save_CC
+LDCXX=$LD
+LD=$lt_save_LD
+GCC=$lt_save_GCC
+with_gnu_ldcxx=$with_gnu_ld
+with_gnu_ld=$lt_save_with_gnu_ld
+lt_cv_path_LDCXX=$lt_cv_path_LD
+lt_cv_path_LD=$lt_save_path_LD
+lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+])# AC_LIBTOOL_LANG_CXX_CONFIG
+
+# AC_LIBTOOL_POSTDEP_PREDEP([TAGNAME])
+# ------------------------------------
+# Figure out "hidden" library dependencies from verbose
+# compiler output when linking a shared library.
+# Parse the compiler output and extract the necessary
+# objects, libraries and library flags.
+AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP],[
+dnl we can't use the lt_simple_compile_test_code here,
+dnl because it contains code intended for an executable,
+dnl not a library. It's possible we should let each
+dnl tag define a new lt_????_link_test_code variable,
+dnl but it's only used here...
+ifelse([$1],[],[cat > conftest.$ac_ext <<EOF
+int a;
+void foo (void) { a = 0; }
+EOF
+],[$1],[CXX],[cat > conftest.$ac_ext <<EOF
+class Foo
+{
+public:
+ Foo (void) { a = 0; }
+private:
+ int a;
+};
+EOF
+],[$1],[F77],[cat > conftest.$ac_ext <<EOF
+ subroutine foo
+ implicit none
+ integer*4 a
+ a=0
+ return
+ end
+EOF
+],[$1],[GCJ],[cat > conftest.$ac_ext <<EOF
+public class foo {
+ private int a;
+ public void bar (void) {
+ a = 0;
+ }
+};
+EOF
+])
+dnl Parse the compiler output and extract the necessary
+dnl objects, libraries and library flags.
+if AC_TRY_EVAL(ac_compile); then
+ # Parse the compiler output and extract the necessary
+ # objects, libraries and library flags.
+
+ # Sentinel used to keep track of whether or not we are before
+ # the conftest object file.
+ pre_test_object_deps_done=no
+
+ # The `*' in the case matches for architectures that use `case' in
+ # $output_verbose_cmd can trigger glob expansion during the loop
+ # eval without this substitution.
+ output_verbose_link_cmd=`$echo "X$output_verbose_link_cmd" | $Xsed -e "$no_glob_subst"`
+
+ for p in `eval $output_verbose_link_cmd`; do
+ case $p in
+
+ -L* | -R* | -l*)
+ # Some compilers place space between "-{L,R}" and the path.
+ # Remove the space.
+ if test $p = "-L" \
+ || test $p = "-R"; then
+ prev=$p
+ continue
+ else
+ prev=
+ fi
+
+ if test "$pre_test_object_deps_done" = no; then
+ case $p in
+ -L* | -R*)
+ # Internal compiler library paths should come after those
+ # provided the user. The postdeps already come after the
+ # user supplied libs so there is no need to process them.
+ if test -z "$_LT_AC_TAGVAR(compiler_lib_search_path, $1)"; then
+ _LT_AC_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
+ else
+ _LT_AC_TAGVAR(compiler_lib_search_path, $1)="${_LT_AC_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
+ fi
+ ;;
+ # The "-l" case would never come before the object being
+ # linked, so don't bother handling this case.
+ esac
+ else
+ if test -z "$_LT_AC_TAGVAR(postdeps, $1)"; then
+ _LT_AC_TAGVAR(postdeps, $1)="${prev}${p}"
+ else
+ _LT_AC_TAGVAR(postdeps, $1)="${_LT_AC_TAGVAR(postdeps, $1)} ${prev}${p}"
+ fi
+ fi
+ ;;
+
+ *.$objext)
+ # This assumes that the test object file only shows up
+ # once in the compiler output.
+ if test "$p" = "conftest.$objext"; then
+ pre_test_object_deps_done=yes
+ continue
+ fi
+
+ if test "$pre_test_object_deps_done" = no; then
+ if test -z "$_LT_AC_TAGVAR(predep_objects, $1)"; then
+ _LT_AC_TAGVAR(predep_objects, $1)="$p"
+ else
+ _LT_AC_TAGVAR(predep_objects, $1)="$_LT_AC_TAGVAR(predep_objects, $1) $p"
+ fi
+ else
+ if test -z "$_LT_AC_TAGVAR(postdep_objects, $1)"; then
+ _LT_AC_TAGVAR(postdep_objects, $1)="$p"
+ else
+ _LT_AC_TAGVAR(postdep_objects, $1)="$_LT_AC_TAGVAR(postdep_objects, $1) $p"
+ fi
+ fi
+ ;;
+
+ *) ;; # Ignore the rest.
+
+ esac
+ done
+
+ # Clean up.
+ rm -f a.out a.exe
+else
+ echo "libtool.m4: error: problem compiling $1 test program"
+fi
+
+$rm -f confest.$objext
+
+# PORTME: override above test on systems where it is broken
+ifelse([$1],[CXX],
+[case $host_os in
+interix3*)
+ # Interix 3.5 installs completely hosed .la files for C++, so rather than
+ # hack all around it, let's just trust "g++" to DTRT.
+ _LT_AC_TAGVAR(predep_objects,$1)=
+ _LT_AC_TAGVAR(postdep_objects,$1)=
+ _LT_AC_TAGVAR(postdeps,$1)=
+ ;;
+
+solaris*)
+ case $cc_basename in
+ CC*)
+ # Adding this requires a known-good setup of shared libraries for
+ # Sun compiler versions before 5.6, else PIC objects from an old
+ # archive will be linked into the output, leading to subtle bugs.
+ _LT_AC_TAGVAR(postdeps,$1)='-lCstd -lCrun'
+ ;;
+ esac
+ ;;
+esac
+])
+
+case " $_LT_AC_TAGVAR(postdeps, $1) " in
+*" -lc "*) _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no ;;
+esac
+])# AC_LIBTOOL_POSTDEP_PREDEP
+
+# AC_LIBTOOL_LANG_F77_CONFIG
+# --------------------------
+# Ensure that the configuration vars for the C compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG], [_LT_AC_LANG_F77_CONFIG(F77)])
+AC_DEFUN([_LT_AC_LANG_F77_CONFIG],
+[AC_REQUIRE([AC_PROG_F77])
+AC_LANG_PUSH(Fortran 77)
+
+_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_AC_TAGVAR(allow_undefined_flag, $1)=
+_LT_AC_TAGVAR(always_export_symbols, $1)=no
+_LT_AC_TAGVAR(archive_expsym_cmds, $1)=
+_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_AC_TAGVAR(hardcode_direct, $1)=no
+_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_AC_TAGVAR(hardcode_minus_L, $1)=no
+_LT_AC_TAGVAR(hardcode_automatic, $1)=no
+_LT_AC_TAGVAR(module_cmds, $1)=
+_LT_AC_TAGVAR(module_expsym_cmds, $1)=
+_LT_AC_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_AC_TAGVAR(no_undefined_flag, $1)=
+_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for f77 test sources.
+ac_ext=f
+
+# Object file extension for compiled f77 test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code=" subroutine t\n return\n end\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code=" program t\n end\n"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${F77-"f77"}
+compiler=$CC
+_LT_AC_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+
+AC_MSG_CHECKING([if libtool supports shared libraries])
+AC_MSG_RESULT([$can_build_shared])
+
+AC_MSG_CHECKING([whether to build shared libraries])
+test "$can_build_shared" = "no" && enable_shared=no
+
+# On AIX, shared libraries and static libraries use the same namespace, and
+# are all built from PIC.
+case $host_os in
+aix3*)
+ test "$enable_shared" = yes && enable_static=no
+ if test -n "$RANLIB"; then
+ archive_cmds="$archive_cmds~\$RANLIB \$lib"
+ postinstall_cmds='$RANLIB $lib'
+ fi
+ ;;
+aix4* | aix5*)
+ if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+ test "$enable_shared" = yes && enable_static=no
+ fi
+ ;;
+esac
+AC_MSG_RESULT([$enable_shared])
+
+AC_MSG_CHECKING([whether to build static libraries])
+# Make sure either enable_shared or enable_static is yes.
+test "$enable_shared" = yes || enable_static=yes
+AC_MSG_RESULT([$enable_static])
+
+_LT_AC_TAGVAR(GCC, $1)="$G77"
+_LT_AC_TAGVAR(LD, $1)="$LD"
+
+AC_LIBTOOL_PROG_COMPILER_PIC($1)
+AC_LIBTOOL_PROG_CC_C_O($1)
+AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
+AC_LIBTOOL_PROG_LD_SHLIBS($1)
+AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
+AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_POP
+CC="$lt_save_CC"
+])# AC_LIBTOOL_LANG_F77_CONFIG
+
+
+# AC_LIBTOOL_LANG_GCJ_CONFIG
+# --------------------------
+# Ensure that the configuration vars for the C compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG], [_LT_AC_LANG_GCJ_CONFIG(GCJ)])
+AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG],
+[AC_LANG_PUSH(C)
+
+# Source file extension for Java test sources.
+ac_ext=java
+
+# Object file extension for compiled Java test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="class foo {}\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }\n'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${GCJ-"gcj"}
+compiler=$CC
+_LT_AC_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+
+# GCJ did not exist at the time GCC didn't implicitly link libc in.
+_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1)
+AC_LIBTOOL_PROG_COMPILER_PIC($1)
+AC_LIBTOOL_PROG_CC_C_O($1)
+AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
+AC_LIBTOOL_PROG_LD_SHLIBS($1)
+AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
+AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_POP([])
+CC="$lt_save_CC"
+])# AC_LIBTOOL_LANG_GCJ_CONFIG
+
+
+# AC_LIBTOOL_LANG_RC_CONFIG
+# -------------------------
+# Ensure that the configuration vars for the Windows resource compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG], [_LT_AC_LANG_RC_CONFIG(RC)])
+AC_DEFUN([_LT_AC_LANG_RC_CONFIG],
+[AC_LANG_PUSH(C)
+
+# Source file extension for RC test sources.
+ac_ext=rc
+
+# Object file extension for compiled RC test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }\n'
+
+# Code to be used in simple link tests
+lt_simple_link_test_code="$lt_simple_compile_test_code"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${RC-"windres"}
+compiler=$CC
+_LT_AC_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_POP([])
+CC="$lt_save_CC"
+])# AC_LIBTOOL_LANG_RC_CONFIG
+
+
+# AC_LIBTOOL_CONFIG([TAGNAME])
+# ----------------------------
+# If TAGNAME is not passed, then create an initial libtool script
+# with a default configuration from the untagged config vars. Otherwise
+# add code to config.status for appending the configuration named by
+# TAGNAME from the matching tagged config vars.
+AC_DEFUN([AC_LIBTOOL_CONFIG],
+[# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+ # See if we are running on zsh, and set the options which allow our commands through
+ # without removal of \ escapes.
+ if test -n "${ZSH_VERSION+set}" ; then
+ setopt NO_GLOB_SUBST
+ fi
+ # Now quote all the things that may contain metacharacters while being
+ # careful not to overquote the AC_SUBSTed values. We take copies of the
+ # variables and quote the copies for generation of the libtool script.
+ for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+ SED SHELL STRIP \
+ libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+ old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+ deplibs_check_method reload_flag reload_cmds need_locks \
+ lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+ lt_cv_sys_global_symbol_to_c_name_address \
+ sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+ old_postinstall_cmds old_postuninstall_cmds \
+ _LT_AC_TAGVAR(compiler, $1) \
+ _LT_AC_TAGVAR(CC, $1) \
+ _LT_AC_TAGVAR(LD, $1) \
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1) \
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1) \
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1) \
+ _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) \
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1) \
+ _LT_AC_TAGVAR(thread_safe_flag_spec, $1) \
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1) \
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1) \
+ _LT_AC_TAGVAR(old_archive_cmds, $1) \
+ _LT_AC_TAGVAR(old_archive_from_new_cmds, $1) \
+ _LT_AC_TAGVAR(predep_objects, $1) \
+ _LT_AC_TAGVAR(postdep_objects, $1) \
+ _LT_AC_TAGVAR(predeps, $1) \
+ _LT_AC_TAGVAR(postdeps, $1) \
+ _LT_AC_TAGVAR(compiler_lib_search_path, $1) \
+ _LT_AC_TAGVAR(archive_cmds, $1) \
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1) \
+ _LT_AC_TAGVAR(postinstall_cmds, $1) \
+ _LT_AC_TAGVAR(postuninstall_cmds, $1) \
+ _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) \
+ _LT_AC_TAGVAR(allow_undefined_flag, $1) \
+ _LT_AC_TAGVAR(no_undefined_flag, $1) \
+ _LT_AC_TAGVAR(export_symbols_cmds, $1) \
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) \
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1) \
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1) \
+ _LT_AC_TAGVAR(hardcode_automatic, $1) \
+ _LT_AC_TAGVAR(module_cmds, $1) \
+ _LT_AC_TAGVAR(module_expsym_cmds, $1) \
+ _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1) \
+ _LT_AC_TAGVAR(exclude_expsyms, $1) \
+ _LT_AC_TAGVAR(include_expsyms, $1); do
+
+ case $var in
+ _LT_AC_TAGVAR(old_archive_cmds, $1) | \
+ _LT_AC_TAGVAR(old_archive_from_new_cmds, $1) | \
+ _LT_AC_TAGVAR(archive_cmds, $1) | \
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1) | \
+ _LT_AC_TAGVAR(module_cmds, $1) | \
+ _LT_AC_TAGVAR(module_expsym_cmds, $1) | \
+ _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) | \
+ _LT_AC_TAGVAR(export_symbols_cmds, $1) | \
+ extract_expsyms_cmds | reload_cmds | finish_cmds | \
+ postinstall_cmds | postuninstall_cmds | \
+ old_postinstall_cmds | old_postuninstall_cmds | \
+ sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+ # Double-quote double-evaled strings.
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+ ;;
+ *)
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+ ;;
+ esac
+ done
+
+ case $lt_echo in
+ *'\[$]0 --fallback-echo"')
+ lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\[$]0 --fallback-echo"[$]/[$]0 --fallback-echo"/'`
+ ;;
+ esac
+
+ifelse([$1], [],
+ [cfgfile="${ofile}T"
+ trap "$rm \"$cfgfile\"; exit 1" 1 2 15
+ $rm -f "$cfgfile"
+ AC_MSG_NOTICE([creating $ofile])],
+ [cfgfile="$ofile"])
+
+ cat <<__EOF__ >> "$cfgfile"
+ifelse([$1], [],
+[#! $SHELL
+
+# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP)
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
+# Free Software Foundation, Inc.
+#
+# This file is part of GNU Libtool:
+# Originally by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# A sed program that does not truncate output.
+SED=$lt_SED
+
+# Sed that helps us avoid accidentally triggering echo(1) options like -n.
+Xsed="$SED -e 1s/^X//"
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+# The names of the tagged configurations supported by this script.
+available_tags=
+
+# ### BEGIN LIBTOOL CONFIG],
+[# ### BEGIN LIBTOOL TAG CONFIG: $tagname])
+
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
+
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
+
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
+
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)
+
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)
+
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
+
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
+
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
+
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
+
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
+
+# A C compiler.
+LTCC=$lt_LTCC
+
+# LTCC compiler flags.
+LTCFLAGS=$lt_LTCFLAGS
+
+# A language-specific compiler.
+CC=$lt_[]_LT_AC_TAGVAR(compiler, $1)
+
+# Is the compiler the GNU C compiler?
+with_gcc=$_LT_AC_TAGVAR(GCC, $1)
+
+# An ERE matcher.
+EGREP=$lt_EGREP
+
+# The linker used to build libraries.
+LD=$lt_[]_LT_AC_TAGVAR(LD, $1)
+
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
+
+# A BSD-compatible nm program.
+NM=$lt_NM
+
+# A symbol stripping program
+STRIP=$lt_STRIP
+
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
+
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
+
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
+
+# Used on cygwin: assembler.
+AS="$AS"
+
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
+
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
+
+# How to pass a linker flag through the compiler.
+wl=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)
+
+# Object file suffix (normally "o").
+objext="$ac_objext"
+
+# Old archive suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
+
+# Executable file suffix (normally "").
+exeext="$exeext"
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)
+pic_mode=$pic_mode
+
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_[]_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)
+
+# Must we lock files when doing compilation?
+need_locks=$lt_need_locks
+
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=$need_version
+
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_static, $1)
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_[]_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_[]_LT_AC_TAGVAR(whole_archive_flag_spec, $1)
+
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_[]_LT_AC_TAGVAR(thread_safe_flag_spec, $1)
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
+
+# List of archive names. First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
+
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_cmds, $1)
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_from_new_cmds, $1)
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1)
+
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_[]_LT_AC_TAGVAR(archive_cmds, $1)
+archive_expsym_cmds=$lt_[]_LT_AC_TAGVAR(archive_expsym_cmds, $1)
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
+
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_[]_LT_AC_TAGVAR(module_cmds, $1)
+module_expsym_cmds=$lt_[]_LT_AC_TAGVAR(module_expsym_cmds, $1)
+
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=$lt_[]_LT_AC_TAGVAR(predep_objects, $1)
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=$lt_[]_LT_AC_TAGVAR(postdep_objects, $1)
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_[]_LT_AC_TAGVAR(predeps, $1)
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_[]_LT_AC_TAGVAR(postdeps, $1)
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=$lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $1)
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_[]_LT_AC_TAGVAR(allow_undefined_flag, $1)
+
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_[]_LT_AC_TAGVAR(no_undefined_flag, $1)
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
+
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
+
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
+
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$_LT_AC_TAGVAR(hardcode_action, $1)
+
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)
+
+# If ld is used when linking, flag to hardcode \$libdir into
+# a binary during linking. This must work even if \$libdir does
+# not exist.
+hardcode_libdir_flag_spec_ld=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_separator, $1)
+
+# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$_LT_AC_TAGVAR(hardcode_direct, $1)
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$_LT_AC_TAGVAR(hardcode_minus_L, $1)
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)
+
+# Set to yes if building a shared library automatically hardcodes DIR into the library
+# and all subsequent libraries and executables linked against it.
+hardcode_automatic=$_LT_AC_TAGVAR(hardcode_automatic, $1)
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at relink time.
+variables_saved_for_relink="$variables_saved_for_relink"
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$_LT_AC_TAGVAR(link_all_deplibs, $1)
+
+# Compile-time system search path for libraries
+sys_lib_search_path_spec=$lt_sys_lib_search_path_spec
+
+# Run-time system search path for libraries
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+
+# Fix the shell variable \$srcfile for the compiler.
+fix_srcfile_path="$_LT_AC_TAGVAR(fix_srcfile_path, $1)"
+
+# Set to yes if exported symbols are required.
+always_export_symbols=$_LT_AC_TAGVAR(always_export_symbols, $1)
+
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_[]_LT_AC_TAGVAR(export_symbols_cmds, $1)
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_[]_LT_AC_TAGVAR(exclude_expsyms, $1)
+
+# Symbols that must always be exported.
+include_expsyms=$lt_[]_LT_AC_TAGVAR(include_expsyms, $1)
+
+ifelse([$1],[],
+[# ### END LIBTOOL CONFIG],
+[# ### END LIBTOOL TAG CONFIG: $tagname])
+
+__EOF__
+
+ifelse([$1],[], [
+ case $host_os in
+ aix3*)
+ cat <<\EOF >> "$cfgfile"
+
+# AIX sometimes has problems with the GCC collect2 program. For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+ COLLECT_NAMES=
+ export COLLECT_NAMES
+fi
+EOF
+ ;;
+ esac
+
+ # We use sed instead of cat because bash on DJGPP gets confused if
+ # if finds mixed CR/LF and LF-only lines. Since sed operates in
+ # text mode, it properly converts lines to CR/LF. This bash problem
+ # is reportedly fixed, but why not run on old versions too?
+ sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1)
+
+ mv -f "$cfgfile" "$ofile" || \
+ (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+ chmod +x "$ofile"
+])
+else
+ # If there is no Makefile yet, we rely on a make rule to execute
+ # `config.status --recheck' to rerun these tests and create the
+ # libtool script then.
+ ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
+ if test -f "$ltmain_in"; then
+ test -f Makefile && make "$ltmain"
+ fi
+fi
+])# AC_LIBTOOL_CONFIG
+
+
+# AC_LIBTOOL_PROG_COMPILER_NO_RTTI([TAGNAME])
+# -------------------------------------------
+AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI],
+[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
+
+_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+
+if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+
+ AC_LIBTOOL_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
+ lt_cv_prog_compiler_rtti_exceptions,
+ [-fno-rtti -fno-exceptions], [],
+ [_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
+fi
+])# AC_LIBTOOL_PROG_COMPILER_NO_RTTI
+
+
+# AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
+# ---------------------------------
+AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE],
+[AC_REQUIRE([AC_CANONICAL_HOST])
+AC_REQUIRE([AC_PROG_NM])
+AC_REQUIRE([AC_OBJEXT])
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+AC_MSG_CHECKING([command to parse $NM output from $compiler object])
+AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
+[
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix. What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[[BCDEGRST]]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
+
+# Transform an extracted symbol line into a proper C declaration
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^. .* \(.*\)$/extern int \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+ symcode='[[BCDT]]'
+ ;;
+cygwin* | mingw* | pw32*)
+ symcode='[[ABCDGISTW]]'
+ ;;
+hpux*) # Its linker distinguishes data from code symbols
+ if test "$host_cpu" = ia64; then
+ symcode='[[ABCDEGRST]]'
+ fi
+ lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+ lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+ ;;
+linux*)
+ if test "$host_cpu" = ia64; then
+ symcode='[[ABCDGIRSTW]]'
+ lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+ lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+ fi
+ ;;
+irix* | nonstopux*)
+ symcode='[[BCDEGRST]]'
+ ;;
+osf*)
+ symcode='[[BCDEGQRST]]'
+ ;;
+solaris*)
+ symcode='[[BDRT]]'
+ ;;
+sco3.2v5*)
+ symcode='[[DT]]'
+ ;;
+sysv4.2uw2*)
+ symcode='[[DT]]'
+ ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+ symcode='[[ABDT]]'
+ ;;
+sysv4)
+ symcode='[[DFNSTU]]'
+ ;;
+esac
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+ opt_cr=`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+ ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+ symcode='[[ABCDGIRSTW]]' ;;
+esac
+
+# Try without a prefix undercore, then with it.
+for ac_symprfx in "" "_"; do
+
+ # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+ symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+ # Write the raw and C identifiers.
+ lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+
+ # Check to see that the pipe works correctly.
+ pipe_works=no
+
+ rm -f conftest*
+ cat > conftest.$ac_ext <<EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+EOF
+
+ if AC_TRY_EVAL(ac_compile); then
+ # Now try to grab the symbols.
+ nlist=conftest.nm
+ if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) && test -s "$nlist"; then
+ # Try sorting and uniquifying the output.
+ if sort "$nlist" | uniq > "$nlist"T; then
+ mv -f "$nlist"T "$nlist"
+ else
+ rm -f "$nlist"T
+ fi
+
+ # Make sure that we snagged all the symbols we need.
+ if grep ' nm_test_var$' "$nlist" >/dev/null; then
+ if grep ' nm_test_func$' "$nlist" >/dev/null; then
+ cat <<EOF > conftest.$ac_ext
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+EOF
+ # Now generate the symbol file.
+ eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> conftest.$ac_ext'
+
+ cat <<EOF >> conftest.$ac_ext
+#if defined (__STDC__) && __STDC__
+# define lt_ptr_t void *
+#else
+# define lt_ptr_t char *
+# define const
+#endif
+
+/* The mapping between symbol names and symbols. */
+const struct {
+ const char *name;
+ lt_ptr_t address;
+}
+lt_preloaded_symbols[[]] =
+{
+EOF
+ $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (lt_ptr_t) \&\2},/" < "$nlist" | grep -v main >> conftest.$ac_ext
+ cat <<\EOF >> conftest.$ac_ext
+ {0, (lt_ptr_t) 0}
+};
+
+#ifdef __cplusplus
+}
+#endif
+EOF
+ # Now try linking the two files.
+ mv conftest.$ac_objext conftstm.$ac_objext
+ lt_save_LIBS="$LIBS"
+ lt_save_CFLAGS="$CFLAGS"
+ LIBS="conftstm.$ac_objext"
+ CFLAGS="$CFLAGS$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
+ if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
+ pipe_works=yes
+ fi
+ LIBS="$lt_save_LIBS"
+ CFLAGS="$lt_save_CFLAGS"
+ else
+ echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
+ fi
+ else
+ echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
+ fi
+ else
+ echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+ fi
+ else
+ echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
+ cat conftest.$ac_ext >&5
+ fi
+ rm -f conftest* conftst*
+
+ # Do not use the global_symbol_pipe unless it works.
+ if test "$pipe_works" = yes; then
+ break
+ else
+ lt_cv_sys_global_symbol_pipe=
+ fi
+done
+])
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+ lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+ AC_MSG_RESULT(failed)
+else
+ AC_MSG_RESULT(ok)
+fi
+]) # AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
+
+
+# AC_LIBTOOL_PROG_COMPILER_PIC([TAGNAME])
+# ---------------------------------------
+AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC],
+[_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=
+_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=
+
+AC_MSG_CHECKING([for $compiler option to produce PIC])
+ ifelse([$1],[CXX],[
+ # C++ specific cases for pic, static, wl, etc.
+ if test "$GXX" = yes; then
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+ case $host_os in
+ aix*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ fi
+ ;;
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+ ;;
+ beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+ # PIC is the default for these OSes.
+ ;;
+ mingw* | os2* | pw32*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'
+ ;;
+ darwin* | rhapsody*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+ ;;
+ *djgpp*)
+ # DJGPP does not support shared libraries at all
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ ;;
+ interix3*)
+ # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+ # Instead, we relocate shared libraries at runtime.
+ ;;
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+ fi
+ ;;
+ hpux*)
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ esac
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ esac
+ else
+ case $host_os in
+ aix4* | aix5*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ else
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+ fi
+ ;;
+ chorus*)
+ case $cc_basename in
+ cxch68*)
+ # Green Hills C++ Compiler
+ # _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+ ;;
+ esac
+ ;;
+ darwin*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ case $cc_basename in
+ xlc*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-qnocommon'
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ ;;
+ esac
+ ;;
+ dgux*)
+ case $cc_basename in
+ ec++*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ ;;
+ ghcx*)
+ # Green Hills C++ Compiler
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ # FreeBSD uses GNU C++
+ ;;
+ hpux9* | hpux10* | hpux11*)
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+ if test "$host_cpu" != ia64; then
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+ fi
+ ;;
+ aCC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+ ;;
+ esac
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ interix*)
+ # This is c89, which is MS Visual C++ (no shared libs)
+ # Anyone wants to do a port?
+ ;;
+ irix5* | irix6* | nonstopux*)
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ # CC pic flag -KPIC is the default.
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ linux*)
+ case $cc_basename in
+ KCC*)
+ # KAI C++ Compiler
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ icpc* | ecpc*)
+ # Intel C++
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
+ ;;
+ pgCC*)
+ # Portland Group C++ compiler.
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+ cxx*)
+ # Compaq C++
+ # Make sure the PIC flag is empty. It appears that all Alpha
+ # Linux and Compaq Tru64 Unix objects are PIC.
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ lynxos*)
+ ;;
+ m88k*)
+ ;;
+ mvs*)
+ case $cc_basename in
+ cxx*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ netbsd*)
+ ;;
+ osf3* | osf4* | osf5*)
+ case $cc_basename in
+ KCC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ ;;
+ cxx*)
+ # Digital/Compaq C++
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # Make sure the PIC flag is empty. It appears that all Alpha
+ # Linux and Compaq Tru64 Unix objects are PIC.
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ psos*)
+ ;;
+ solaris*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.2, 5.x and Centerline C++
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+ ;;
+ gcx*)
+ # Green Hills C++ Compiler
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ sunos4*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.x
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+ lcc*)
+ # Lucid
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ tandem*)
+ case $cc_basename in
+ NCC*)
+ # NonStop-UX NCC 3.20
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+ esac
+ ;;
+ vxworks*)
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+ ;;
+ esac
+ fi
+],
+[
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+ case $host_os in
+ aix*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ fi
+ ;;
+
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+ ;;
+
+ beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+ # PIC is the default for these OSes.
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'
+ ;;
+
+ darwin* | rhapsody*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+ ;;
+
+ interix3*)
+ # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+ # Instead, we relocate shared libraries at runtime.
+ ;;
+
+ msdosdjgpp*)
+ # Just because we use GCC doesn't mean we suddenly get shared libraries
+ # on systems that don't support them.
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+ enable_shared=no
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+ fi
+ ;;
+
+ hpux*)
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ esac
+ ;;
+
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ esac
+ else
+ # PORTME Check for flag to pass linker flags through the system compiler.
+ case $host_os in
+ aix*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ else
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+ fi
+ ;;
+ darwin*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ case $cc_basename in
+ xlc*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-qnocommon'
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ ;;
+ esac
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'
+ ;;
+
+ hpux9* | hpux10* | hpux11*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+ ;;
+ esac
+ # Is there a better lt_prog_compiler_static that works with the bundled CC?
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # PIC (with -KPIC) is the default.
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+
+ newsos6)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ linux*)
+ case $cc_basename in
+ icc* | ecc*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
+ ;;
+ pgcc* | pgf77* | pgf90* | pgf95*)
+ # Portland Group compilers (*not* the Pentium gcc compiler,
+ # which looks to be a dead project)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+ ccc*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # All Alpha code is PIC.
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+ esac
+ ;;
+
+ osf3* | osf4* | osf5*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # All OSF/1 code is PIC.
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+
+ solaris*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ case $cc_basename in
+ f77* | f90* | f95*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
+ esac
+ ;;
+
+ sunos4*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ sysv4 | sysv4.2uw2* | sysv4.3*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec ;then
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ fi
+ ;;
+
+ sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ unicos*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+ ;;
+
+ uts4*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+ ;;
+ esac
+ fi
+])
+AC_MSG_RESULT([$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)])
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)"; then
+ AC_LIBTOOL_COMPILER_OPTION([if $compiler PIC flag $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) works],
+ _LT_AC_TAGVAR(lt_prog_compiler_pic_works, $1),
+ [$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])], [],
+ [case $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) in
+ "" | " "*) ;;
+ *) _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)" ;;
+ esac],
+ [_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
+fi
+case $host_os in
+ # For platforms which do not support PIC, -DPIC is meaningless:
+ *djgpp*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])"
+ ;;
+esac
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_AC_TAGVAR(lt_prog_compiler_static, $1)\"
+AC_LIBTOOL_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
+ _LT_AC_TAGVAR(lt_prog_compiler_static_works, $1),
+ $lt_tmp_static_flag,
+ [],
+ [_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=])
+])
+
+
+# AC_LIBTOOL_PROG_LD_SHLIBS([TAGNAME])
+# ------------------------------------
+# See if the linker supports building shared libraries.
+AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS],
+[AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+ifelse([$1],[CXX],[
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ case $host_os in
+ aix4* | aix5*)
+ # If we're using GNU nm, then we don't want the "-C" option.
+ # -C means demangle to AIX nm, but means don't demangle with GNU nm
+ if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols'
+ else
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols'
+ fi
+ ;;
+ pw32*)
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
+ ;;
+ cygwin* | mingw*)
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]] /s/.* \([[^ ]]*\)/\1 DATA/;/^.* __nm__/s/^.* __nm__\([[^ ]]*\) [[^ ]]*/\1 DATA/;/^I /d;/^[[AITW]] /s/.* //'\'' | sort | uniq > $export_symbols'
+ ;;
+ *)
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ ;;
+ esac
+],[
+ runpath_var=
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+ _LT_AC_TAGVAR(archive_cmds, $1)=
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)=
+ _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)=
+ _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1)=
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+ _LT_AC_TAGVAR(thread_safe_flag_spec, $1)=
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=unknown
+ _LT_AC_TAGVAR(hardcode_automatic, $1)=no
+ _LT_AC_TAGVAR(module_cmds, $1)=
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)=
+ _LT_AC_TAGVAR(always_export_symbols, $1)=no
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ # include_expsyms should be a list of space-separated symbols to be *always*
+ # included in the symbol list
+ _LT_AC_TAGVAR(include_expsyms, $1)=
+ # exclude_expsyms can be an extended regexp of symbols to exclude
+ # it will be wrapped by ` (' and `)$', so one must not match beginning or
+ # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+ # as well as any symbol that contains `d'.
+ _LT_AC_TAGVAR(exclude_expsyms, $1)="_GLOBAL_OFFSET_TABLE_"
+ # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+ # platforms (ab)use it in PIC code, but their linkers get confused if
+ # the symbol is explicitly referenced. Since portable code cannot
+ # rely on this symbol name, it's probably fine to never include it in
+ # preloaded symbol tables.
+ extract_expsyms_cmds=
+ # Just being paranoid about ensuring that cc_basename is set.
+ _LT_CC_BASENAME([$compiler])
+ case $host_os in
+ cygwin* | mingw* | pw32*)
+ # FIXME: the MSVC++ port hasn't been tested in a loooong time
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ if test "$GCC" != yes; then
+ with_gnu_ld=no
+ fi
+ ;;
+ interix*)
+ # we just hope/assume this is gcc and not c89 (= MSVC++)
+ with_gnu_ld=yes
+ ;;
+ openbsd*)
+ with_gnu_ld=no
+ ;;
+ esac
+
+ _LT_AC_TAGVAR(ld_shlibs, $1)=yes
+ if test "$with_gnu_ld" = yes; then
+ # If archive_cmds runs LD, not CC, wlarc should be empty
+ wlarc='${wl}'
+
+ # Set some defaults for GNU ld with shared library support. These
+ # are reset later if shared libraries are not supported. Putting them
+ # here allows them to be overridden if necessary.
+ runpath_var=LD_RUN_PATH
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+ # ancient GNU ld didn't support --whole-archive et. al.
+ if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ else
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+ fi
+ supports_anon_versioning=no
+ case `$LD -v 2>/dev/null` in
+ *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
+ *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+ *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+ *\ 2.11.*) ;; # other 2.11 versions
+ *) supports_anon_versioning=yes ;;
+ esac
+
+ # See if GNU ld supports shared libraries.
+ case $host_os in
+ aix3* | aix4* | aix5*)
+ # On AIX/PPC, the GNU linker is very broken
+ if test "$host_cpu" != ia64; then
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ cat <<EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support. If you
+*** really care for shared libraries, you may want to modify your PATH
+*** so that a non-GNU linker is found, and then restart.
+
+EOF
+ fi
+ ;;
+
+ amigaos*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+
+ # Samuel A. Falvo II <kc5tja@dolphin.openprojects.net> reports
+ # that the semantics of dynamic libraries on AmigaOS, at least up
+ # to version 4, is to share data among multiple programs linked
+ # with the same dynamic library. Since this doesn't match the
+ # behavior of shared libraries on other platforms, we can't use
+ # them.
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+
+ beos*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
+ # support --undefined. This deserves some investigation. FIXME
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+ # as there is no search path for DLLs.
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ _LT_AC_TAGVAR(always_export_symbols, $1)=no
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]] /s/.* \([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]] /s/.* //'\'' | sort | uniq > $export_symbols'
+
+ if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ # If the export-symbols file already is a .def file (1st line
+ # is EXPORTS), use it as is; otherwise, prepend...
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+ cp $export_symbols $output_objdir/$soname.def;
+ else
+ echo EXPORTS > $output_objdir/$soname.def;
+ cat $export_symbols >> $output_objdir/$soname.def;
+ fi~
+ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ interix3*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+ # Instead, shared libraries are loaded at an image base (0x10000000 by
+ # default) and relocated if they conflict, which is a slow very memory
+ # consuming and fragmenting process. To avoid this, we pick a random,
+ # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+ # time. Moving up from 0x10000000 also allows more sbrk(2) space.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ ;;
+
+ linux*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ tmp_addflag=
+ case $cc_basename,$host_cpu in
+ pgcc*) # Portland Group C compiler
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag'
+ ;;
+ pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag -Mnomain' ;;
+ ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64
+ tmp_addflag=' -i_dynamic' ;;
+ efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64
+ tmp_addflag=' -i_dynamic -nofor_main' ;;
+ ifc* | ifort*) # Intel Fortran compiler
+ tmp_addflag=' -nofor_main' ;;
+ esac
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+ if test $supports_anon_versioning = yes; then
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $output_objdir/$libname.ver~
+ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+ $echo "local: *; };" >> $output_objdir/$libname.ver~
+ $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+ fi
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+ wlarc=
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ fi
+ ;;
+
+ solaris*)
+ if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ cat <<EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+EOF
+ elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+ case `$LD -v 2>&1` in
+ *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+ ;;
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+
+ sunos4*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ wlarc=
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+
+ if test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no; then
+ runpath_var=
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+ fi
+ else
+ # PORTME fill in a description of your system's linker (not GNU ld)
+ case $host_os in
+ aix3*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ _LT_AC_TAGVAR(always_export_symbols, $1)=yes
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+ # Note: this linker hardcodes the directories in LIBPATH if there
+ # are no directories specified by -L.
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+ # Neither direct hardcoding nor static linking is supported with a
+ # broken collect2.
+ _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported
+ fi
+ ;;
+
+ aix4* | aix5*)
+ if test "$host_cpu" = ia64; then
+ # On IA64, the linker does run time linking by default, so we don't
+ # have to do anything special.
+ aix_use_runtimelinking=no
+ exp_sym_flag='-Bexport'
+ no_entry_flag=""
+ else
+ # If we're using GNU nm, then we don't want the "-C" option.
+ # -C means demangle to AIX nm, but means don't demangle with GNU nm
+ if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols'
+ else
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols'
+ fi
+ aix_use_runtimelinking=no
+
+ # Test if we are trying to use run time linking or normal
+ # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+ # need to do runtime linking.
+ case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*)
+ for ld_flag in $LDFLAGS; do
+ if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+ aix_use_runtimelinking=yes
+ break
+ fi
+ done
+ ;;
+ esac
+
+ exp_sym_flag='-bexport'
+ no_entry_flag='-bnoentry'
+ fi
+
+ # When large executables or shared objects are built, AIX ld can
+ # have problems creating the table of contents. If linking a library
+ # or program results in "error TOC overflow" add -mminimal-toc to
+ # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not
+ # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+ _LT_AC_TAGVAR(archive_cmds, $1)=''
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+
+ if test "$GCC" = yes; then
+ case $host_os in aix4.[[012]]|aix4.[[012]].*)
+ # We only want to do this on AIX 4.2 and lower, the check
+ # below for broken collect2 doesn't work under 4.3+
+ collect2name=`${CC} -print-prog-name=collect2`
+ if test -f "$collect2name" && \
+ strings "$collect2name" | grep resolve_lib_name >/dev/null
+ then
+ # We have reworked collect2
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ else
+ # We have old collect2
+ _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported
+ # It fails to find uninstalled libraries when the uninstalled
+ # path is not listed in the libpath. Setting hardcode_minus_L
+ # to unsupported forces relinking
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+ fi
+ ;;
+ esac
+ shared_flag='-shared'
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag="$shared_flag "'${wl}-G'
+ fi
+ else
+ # not using gcc
+ if test "$host_cpu" = ia64; then
+ # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+ # chokes on -Wl,-G. The following line is correct:
+ shared_flag='-G'
+ else
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag='${wl}-G'
+ else
+ shared_flag='${wl}-bM:SRE'
+ fi
+ fi
+ fi
+
+ # It seems that -bexpall does not export symbols beginning with
+ # underscore (_), so it is better to generate a list of symbols to export.
+ _LT_AC_TAGVAR(always_export_symbols, $1)=yes
+ if test "$aix_use_runtimelinking" = yes; then
+ # Warning - without using the other runtime loading flags (-brtl),
+ # -berok will link without error, but may produce a broken library.
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='-berok'
+ # Determine the default libpath from the value encoded in an empty executable.
+ _LT_AC_SYS_LIBPATH_AIX
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+ else
+ if test "$host_cpu" = ia64; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+ else
+ # Determine the default libpath from the value encoded in an empty executable.
+ _LT_AC_SYS_LIBPATH_AIX
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+ # Warning - without using the other run time loading flags,
+ # -berok will link without error, but may produce a broken library.
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+ # Exported symbols can be pulled into shared objects from archives
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
+ # This is similar to how AIX traditionally builds its shared libraries.
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+ fi
+ fi
+ ;;
+
+ amigaos*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ # see comment about different semantics on the GNU ld section
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+
+ bsdi[[45]]*)
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ # hardcode_libdir_flag_spec is actually meaningless, as there is
+ # no search path for DLLs.
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ # Tell ltmain to make .lib files, not .a files.
+ libext=lib
+ # Tell ltmain to make .dll files, not .so files.
+ shrext_cmds=".dll"
+ # FIXME: Setting linknames here is a bad hack.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames='
+ # The linker will automatically build a .lib file if we build a DLL.
+ _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)='true'
+ # FIXME: Should let the user specify the lib program.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='lib /OUT:$oldlib$oldobjs$old_deplibs'
+ _LT_AC_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`'
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+ ;;
+
+ darwin* | rhapsody*)
+ case $host_os in
+ rhapsody* | darwin1.[[012]])
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}suppress'
+ ;;
+ *) # Darwin 1.3 on
+ if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ else
+ case ${MACOSX_DEPLOYMENT_TARGET} in
+ 10.[[012]])
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ ;;
+ 10.*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}dynamic_lookup'
+ ;;
+ esac
+ fi
+ ;;
+ esac
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_automatic, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=''
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ if test "$GCC" = yes ; then
+ output_verbose_link_cmd='echo'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ case $cc_basename in
+ xlc*)
+ output_verbose_link_cmd='echo'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+ _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ ;;
+ *)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ fi
+ ;;
+
+ dgux*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ freebsd1.*)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+
+ # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+ # support. Future versions do this automatically, but an explicit c++rt0.o
+ # does not break anything, and helps significantly (at the cost of a little
+ # extra space).
+ freebsd2.2*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+ freebsd2.*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ hpux9*)
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ ;;
+
+ hpux10*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ if test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ fi
+ ;;
+
+ hpux11*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ case $host_cpu in
+ hppa*64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ else
+ case $host_cpu in
+ hppa*64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ fi
+ if test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ case $host_cpu in
+ hppa*64*|ia64*)
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+ *)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ ;;
+ esac
+ fi
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ newsos6)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ openbsd* | bitrig*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ else
+ case $host_os in
+ openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ ;;
+ esac
+ fi
+ ;;
+
+ os2*)
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ _LT_AC_TAGVAR(archive_cmds, $1)='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+ _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+ ;;
+
+ osf3*)
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ ;;
+
+ osf4* | osf5*) # as osf3* with the addition of -msym flag
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ else
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
+ $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+
+ # Both c and cxx compiler support -rpath directly
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ ;;
+
+ solaris*)
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' -z text'
+ if test "$GCC" = yes; then
+ wlarc='${wl}'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
+ else
+ wlarc=''
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ case $host_os in
+ solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+ *)
+ # The compiler driver will combine linker options so we
+ # cannot just pass the convience library names through
+ # without $wl, iff we do not link with $LD.
+ # Luckily, gcc supports the same syntax we need for Sun Studio.
+ # Supported since Solaris 2.6 (maybe 2.5.1?)
+ case $wlarc in
+ '')
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;;
+ *)
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
+ esac ;;
+ esac
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ ;;
+
+ sunos4*)
+ if test "x$host_vendor" = xsequent; then
+ # Use $CC to link under sequent, because it throws in some extra .o
+ # files that make .init and .fini sections work.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ sysv4)
+ case $host_vendor in
+ sni)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes # is this really true???
+ ;;
+ siemens)
+ ## LD is ld it makes a PLAMLIB
+ ## CC just makes a GrossModule.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ ;;
+ motorola)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
+ ;;
+ esac
+ runpath_var='LD_RUN_PATH'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ sysv4.3*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ runpath_var=LD_RUN_PATH
+ hardcode_runpath_var=yes
+ _LT_AC_TAGVAR(ld_shlibs, $1)=yes
+ fi
+ ;;
+
+ sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7*)
+ _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6*)
+ # Note: We can NOT use -z defs as we might desire, because we do not
+ # link with -lc, and that would cause any symbols used from libc to
+ # always be unresolved, which means just about no library would
+ # ever link correctly. If we're not using GNU ld we use -z text
+ # though, which does catch some bad symbols but isn't as heavy-handed
+ # as -z defs.
+ _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ uts4*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ *)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ fi
+])
+AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)])
+test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)" in
+x|xyes)
+ # Assume -lc should be added
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
+
+ if test "$enable_shared" = yes && test "$GCC" = yes; then
+ case $_LT_AC_TAGVAR(archive_cmds, $1) in
+ *'~'*)
+ # FIXME: we may have to deal with multi-command sequences.
+ ;;
+ '$CC '*)
+ # Test whether the compiler implicitly links with -lc since on some
+ # systems, -lgcc has to come before -lc. If gcc already passes -lc
+ # to ld, don't add -lc before -lgcc.
+ AC_MSG_CHECKING([whether -lc should be explicitly linked in])
+ $rm conftest*
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
+ soname=conftest
+ lib=conftest
+ libobjs=conftest.$ac_objext
+ deplibs=
+ wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)
+ pic_flag=$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)
+ compiler_flags=-v
+ linker_flags=-v
+ verstring=
+ output_objdir=.
+ libname=conftest
+ lt_save_allow_undefined_flag=$_LT_AC_TAGVAR(allow_undefined_flag, $1)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=
+ if AC_TRY_EVAL(_LT_AC_TAGVAR(archive_cmds, $1) 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1)
+ then
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ else
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
+ fi
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
+ else
+ cat conftest.err 1>&5
+ fi
+ $rm conftest*
+ AC_MSG_RESULT([$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)])
+ ;;
+ esac
+ fi
+ ;;
+esac
+])# AC_LIBTOOL_PROG_LD_SHLIBS
+
+
+# _LT_AC_FILE_LTDLL_C
+# -------------------
+# Be careful that the start marker always follows a newline.
+AC_DEFUN([_LT_AC_FILE_LTDLL_C], [
+# /* ltdll.c starts here */
+# #define WIN32_LEAN_AND_MEAN
+# #include <windows.h>
+# #undef WIN32_LEAN_AND_MEAN
+# #include <stdio.h>
+#
+# #ifndef __CYGWIN__
+# # ifdef __CYGWIN32__
+# # define __CYGWIN__ __CYGWIN32__
+# # endif
+# #endif
+#
+# #ifdef __cplusplus
+# extern "C" {
+# #endif
+# BOOL APIENTRY DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved);
+# #ifdef __cplusplus
+# }
+# #endif
+#
+# #ifdef __CYGWIN__
+# #include <cygwin/cygwin_dll.h>
+# DECLARE_CYGWIN_DLL( DllMain );
+# #endif
+# HINSTANCE __hDllInstance_base;
+#
+# BOOL APIENTRY
+# DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved)
+# {
+# __hDllInstance_base = hInst;
+# return TRUE;
+# }
+# /* ltdll.c ends here */
+])# _LT_AC_FILE_LTDLL_C
+
+
+# _LT_AC_TAGVAR(VARNAME, [TAGNAME])
+# ---------------------------------
+AC_DEFUN([_LT_AC_TAGVAR], [ifelse([$2], [], [$1], [$1_$2])])
+
+
+# old names
+AC_DEFUN([AM_PROG_LIBTOOL], [AC_PROG_LIBTOOL])
+AC_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
+AC_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
+AC_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
+AC_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
+AC_DEFUN([AM_PROG_LD], [AC_PROG_LD])
+AC_DEFUN([AM_PROG_NM], [AC_PROG_NM])
+
+# This is just to silence aclocal about the macro not being used
+ifelse([AC_DISABLE_FAST_INSTALL])
+
+AC_DEFUN([LT_AC_PROG_GCJ],
+[AC_CHECK_TOOL(GCJ, gcj, no)
+ test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
+ AC_SUBST(GCJFLAGS)
+])
+
+AC_DEFUN([LT_AC_PROG_RC],
+[AC_CHECK_TOOL(RC, windres, no)
+])
+
+############################################################
+# NOTE: This macro has been submitted for inclusion into #
+# GNU Autoconf as AC_PROG_SED. When it is available in #
+# a released version of Autoconf we should remove this #
+# macro and use it instead. #
+############################################################
+# LT_AC_PROG_SED
+# --------------
+# Check for a fully-functional sed program, that truncates
+# as few characters as possible. Prefer GNU sed if found.
+AC_DEFUN([LT_AC_PROG_SED],
+[AC_MSG_CHECKING([for a sed that does not truncate output])
+AC_CACHE_VAL(lt_cv_path_SED,
+[# Loop through the user's path and test for sed and gsed.
+# Then use that list of sed's as ones to test for truncation.
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for lt_ac_prog in sed gsed; do
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
+ lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
+ fi
+ done
+ done
+done
+lt_ac_max=0
+lt_ac_count=0
+# Add /usr/xpg4/bin/sed as it is typically found on Solaris
+# along with /bin/sed that truncates output.
+for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
+ test ! -f $lt_ac_sed && continue
+ cat /dev/null > conftest.in
+ lt_ac_count=0
+ echo $ECHO_N "0123456789$ECHO_C" >conftest.in
+ # Check for GNU sed and select it if it is found.
+ if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
+ lt_cv_path_SED=$lt_ac_sed
+ break
+ fi
+ while true; do
+ cat conftest.in conftest.in >conftest.tmp
+ mv conftest.tmp conftest.in
+ cp conftest.in conftest.nl
+ echo >>conftest.nl
+ $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
+ cmp -s conftest.out conftest.nl || break
+ # 10000 chars as input seems more than enough
+ test $lt_ac_count -gt 10 && break
+ lt_ac_count=`expr $lt_ac_count + 1`
+ if test $lt_ac_count -gt $lt_ac_max; then
+ lt_ac_max=$lt_ac_count
+ lt_cv_path_SED=$lt_ac_sed
+ fi
+ done
+done
+])
+SED=$lt_cv_path_SED
+AC_MSG_RESULT([$SED])
+])
diff --git a/autoconf/m4/link_options.m4 b/autoconf/m4/link_options.m4
new file mode 100644
index 00000000000..57da4a0d926
--- /dev/null
+++ b/autoconf/m4/link_options.m4
@@ -0,0 +1,108 @@
+#
+# Get the linker version string.
+#
+# This macro is specific to LLVM.
+#
+AC_DEFUN([AC_LINK_GET_VERSION],
+ [AC_CACHE_CHECK([for linker version],[llvm_cv_link_version],
+ [
+ version_string="$(ld -v 2>&1 | head -1)"
+
+ # Check for ld64.
+ if (echo "$version_string" | grep -q "ld64"); then
+ llvm_cv_link_version=$(echo "$version_string" | sed -e "s#.*ld64-\([^ ]*\)\( (.*)\)\{0,1\}#\1#")
+ else
+ llvm_cv_link_version=$(echo "$version_string" | sed -e "s#[^0-9]*\([0-9.]*\).*#\1#")
+ fi
+ ])
+ AC_DEFINE_UNQUOTED([HOST_LINK_VERSION],"$llvm_cv_link_version",
+ [Linker version detected at compile time.])
+])
+
+#
+# Determine if the system can handle the -R option being passed to the linker.
+#
+# This macro is specific to LLVM.
+#
+AC_DEFUN([AC_LINK_USE_R],
+[AC_CACHE_CHECK([for compiler -Wl,-R<path> option],[llvm_cv_link_use_r],
+[ AC_LANG_PUSH([C])
+ oldcflags="$CFLAGS"
+ CFLAGS="$CFLAGS -Wl,-R."
+ AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],
+ [llvm_cv_link_use_r=yes],[llvm_cv_link_use_r=no])
+ CFLAGS="$oldcflags"
+ AC_LANG_POP([C])
+])
+if test "$llvm_cv_link_use_r" = yes ; then
+ AC_DEFINE([HAVE_LINK_R],[1],[Define if you can use -Wl,-R. to pass -R. to the linker, in order to add the current directory to the dynamic linker search path.])
+ fi
+])
+
+#
+# Determine if the system can handle the -R option being passed to the linker.
+#
+# This macro is specific to LLVM.
+#
+AC_DEFUN([AC_LINK_EXPORT_DYNAMIC],
+[AC_CACHE_CHECK([for compiler -Wl,-export-dynamic option],
+ [llvm_cv_link_use_export_dynamic],
+[ AC_LANG_PUSH([C])
+ oldcflags="$CFLAGS"
+ CFLAGS="$CFLAGS -Wl,-export-dynamic"
+ AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],
+ [llvm_cv_link_use_export_dynamic=yes],[llvm_cv_link_use_export_dynamic=no])
+ CFLAGS="$oldcflags"
+ AC_LANG_POP([C])
+])
+if test "$llvm_cv_link_use_export_dynamic" = yes ; then
+ AC_DEFINE([HAVE_LINK_EXPORT_DYNAMIC],[1],[Define if you can use -Wl,-export-dynamic.])
+ fi
+])
+
+#
+# Determine if the system can handle the --version-script option being
+# passed to the linker.
+#
+# This macro is specific to LLVM.
+#
+AC_DEFUN([AC_LINK_VERSION_SCRIPT],
+[AC_CACHE_CHECK([for compiler -Wl,--version-script option],
+ [llvm_cv_link_use_version_script],
+[ AC_LANG_PUSH([C])
+ oldcflags="$CFLAGS"
+
+ # The following code is from the autoconf manual,
+ # "11.13: Limitations of Usual Tools".
+ # Create a temporary directory $tmp in $TMPDIR (default /tmp).
+ # Use mktemp if possible; otherwise fall back on mkdir,
+ # with $RANDOM to make collisions less likely.
+ : ${TMPDIR=/tmp}
+ {
+ tmp=`
+ (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
+ ` &&
+ test -n "$tmp" && test -d "$tmp"
+ } || {
+ tmp=$TMPDIR/foo$$-$RANDOM
+ (umask 077 && mkdir "$tmp")
+ } || exit $?
+
+ echo "{" > "$tmp/export.map"
+ echo " global: main;" >> "$tmp/export.map"
+ echo " local: *;" >> "$tmp/export.map"
+ echo "};" >> "$tmp/export.map"
+
+ CFLAGS="$CFLAGS -Wl,--version-script=$tmp/export.map"
+ AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],
+ [llvm_cv_link_use_version_script=yes],[llvm_cv_link_use_version_script=no])
+ rm "$tmp/export.map"
+ rmdir "$tmp"
+ CFLAGS="$oldcflags"
+ AC_LANG_POP([C])
+])
+if test "$llvm_cv_link_use_version_script" = yes ; then
+ AC_SUBST(HAVE_LINK_VERSION_SCRIPT,1)
+ fi
+])
+
diff --git a/autoconf/m4/linux_mixed_64_32.m4 b/autoconf/m4/linux_mixed_64_32.m4
new file mode 100644
index 00000000000..123491f87e5
--- /dev/null
+++ b/autoconf/m4/linux_mixed_64_32.m4
@@ -0,0 +1,17 @@
+#
+# Some Linux machines run a 64-bit kernel with a 32-bit userspace. 'uname -m'
+# shows these as x86_64. Ask the system 'gcc' what it thinks.
+#
+AC_DEFUN([AC_IS_LINUX_MIXED],
+[AC_CACHE_CHECK(for 32-bit userspace on 64-bit system,llvm_cv_linux_mixed,
+[ AC_LANG_PUSH([C])
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+ [[#ifndef __x86_64__
+ error: Not x86-64 even if uname says so!
+ #endif
+ ]])],
+ [llvm_cv_linux_mixed=no],
+ [llvm_cv_linux_mixed=yes])
+ AC_LANG_POP([C])
+])
+])
diff --git a/autoconf/m4/ltdl.m4 b/autoconf/m4/ltdl.m4
new file mode 100644
index 00000000000..407a16e2d69
--- /dev/null
+++ b/autoconf/m4/ltdl.m4
@@ -0,0 +1,418 @@
+## ltdl.m4 - Configure ltdl for the target system. -*-Autoconf-*-
+## Copyright (C) 1999-2000 Free Software Foundation, Inc.
+##
+## This file is free software; the Free Software Foundation gives
+## unlimited permission to copy and/or distribute it, with or without
+## modifications, as long as this notice is preserved.
+
+# serial 7 AC_LIB_LTDL
+
+# AC_WITH_LTDL
+# ------------
+# Clients of libltdl can use this macro to allow the installer to
+# choose between a shipped copy of the ltdl sources or a preinstalled
+# version of the library.
+AC_DEFUN([AC_WITH_LTDL],
+[AC_REQUIRE([AC_LIB_LTDL])
+AC_SUBST([LIBLTDL])
+AC_SUBST([INCLTDL])
+
+# Unless the user asks us to check, assume no installed ltdl exists.
+use_installed_libltdl=no
+
+AC_ARG_WITH([included_ltdl],
+ [ --with-included-ltdl use the GNU ltdl sources included here])
+
+if test "x$with_included_ltdl" != xyes; then
+ # We are not being forced to use the included libltdl sources, so
+ # decide whether there is a useful installed version we can use.
+ AC_CHECK_HEADER([ltdl.h],
+ [AC_CHECK_LIB([ltdl], [lt_dlcaller_register],
+ [with_included_ltdl=no],
+ [with_included_ltdl=yes])
+ ])
+fi
+
+if test "x$enable_ltdl_install" != xyes; then
+ # If the user did not specify an installable libltdl, then default
+ # to a convenience lib.
+ AC_LIBLTDL_CONVENIENCE
+fi
+
+if test "x$with_included_ltdl" = xno; then
+ # If the included ltdl is not to be used. then Use the
+ # preinstalled libltdl we found.
+ AC_DEFINE([HAVE_LTDL], [1],
+ [Define this if a modern libltdl is already installed])
+ LIBLTDL=-lltdl
+fi
+
+# Report our decision...
+AC_MSG_CHECKING([whether to use included libltdl])
+AC_MSG_RESULT([$with_included_ltdl])
+
+AC_CONFIG_SUBDIRS([libltdl])
+])# AC_WITH_LTDL
+
+
+# AC_LIB_LTDL
+# -----------
+# Perform all the checks necessary for compilation of the ltdl objects
+# -- including compiler checks and header checks.
+AC_DEFUN([AC_LIB_LTDL],
+[AC_PREREQ(2.60)
+AC_REQUIRE([AC_PROG_CC])
+AC_REQUIRE([AC_C_CONST])
+AC_REQUIRE([AC_HEADER_STDC])
+AC_REQUIRE([AC_HEADER_DIRENT])
+AC_REQUIRE([_LT_AC_CHECK_DLFCN])
+AC_REQUIRE([AC_LTDL_ENABLE_INSTALL])
+AC_REQUIRE([AC_LTDL_SHLIBEXT])
+AC_REQUIRE([AC_LTDL_SHLIBPATH])
+AC_REQUIRE([AC_LTDL_SYSSEARCHPATH])
+AC_REQUIRE([AC_LTDL_OBJDIR])
+AC_REQUIRE([AC_LTDL_DLPREOPEN])
+AC_REQUIRE([AC_LTDL_DLLIB])
+AC_REQUIRE([AC_LTDL_SYMBOL_USCORE])
+AC_REQUIRE([AC_LTDL_DLSYM_USCORE])
+AC_REQUIRE([AC_LTDL_SYS_DLOPEN_DEPLIBS])
+AC_REQUIRE([AC_LTDL_FUNC_ARGZ])
+
+AC_CHECK_HEADERS([assert.h ctype.h errno.h malloc.h memory.h stdlib.h \
+ stdio.h unistd.h])
+AC_CHECK_HEADERS([dl.h sys/dl.h dld.h mach-o/dyld.h])
+AC_CHECK_HEADERS([string.h strings.h], [break])
+
+AC_CHECK_FUNCS([strchr index], [break])
+AC_CHECK_FUNCS([strrchr rindex], [break])
+AC_CHECK_FUNCS([memcpy bcopy], [break])
+AC_CHECK_FUNCS([memmove strcmp])
+AC_CHECK_FUNCS([closedir opendir readdir])
+])# AC_LIB_LTDL
+
+
+# AC_LTDL_ENABLE_INSTALL
+# ----------------------
+AC_DEFUN([AC_LTDL_ENABLE_INSTALL],
+[AC_ARG_ENABLE([ltdl-install],
+ [AS_HELP_STRING([--enable-ltdl-install],[install libltdl])])
+
+AM_CONDITIONAL(INSTALL_LTDL, test x"${enable_ltdl_install-no}" != xno)
+AM_CONDITIONAL(CONVENIENCE_LTDL, test x"${enable_ltdl_convenience-no}" != xno)
+])# AC_LTDL_ENABLE_INSTALL
+
+
+# AC_LTDL_SYS_DLOPEN_DEPLIBS
+# --------------------------
+AC_DEFUN([AC_LTDL_SYS_DLOPEN_DEPLIBS],
+[AC_REQUIRE([AC_CANONICAL_HOST])
+AC_CACHE_CHECK([whether deplibs are loaded by dlopen],
+ [libltdl_cv_sys_dlopen_deplibs],
+ [# PORTME does your system automatically load deplibs for dlopen?
+ # or its logical equivalent (e.g. shl_load for HP-UX < 11)
+ # For now, we just catch OSes we know something about -- in the
+ # future, we'll try test this programmatically.
+ libltdl_cv_sys_dlopen_deplibs=unknown
+ case "$host_os" in
+ aix3*|aix4.1.*|aix4.2.*)
+ # Unknown whether this is true for these versions of AIX, but
+ # we want this `case' here to explicitly catch those versions.
+ libltdl_cv_sys_dlopen_deplibs=unknown
+ ;;
+ aix[[45]]*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ darwin*)
+ # Assuming the user has installed a libdl from somewhere, this is true
+ # If you are looking for one http://www.opendarwin.org/projects/dlcompat
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ gnu* | linux* | kfreebsd*-gnu | knetbsd*-gnu)
+ # GNU and its variants, using gnu ld.so (Glibc)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ hpux10*|hpux11*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ interix*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ irix[[12345]]*|irix6.[[01]]*)
+ # Catch all versions of IRIX before 6.2, and indicate that we don't
+ # know how it worked for any of those versions.
+ libltdl_cv_sys_dlopen_deplibs=unknown
+ ;;
+ irix*)
+ # The case above catches anything before 6.2, and it's known that
+ # at 6.2 and later dlopen does load deplibs.
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ netbsd*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ openbsd*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ osf[[1234]]*)
+ # dlopen did load deplibs (at least at 4.x), but until the 5.x series,
+ # it did *not* use an RPATH in a shared library to find objects the
+ # library depends on, so we explicitly say `no'.
+ libltdl_cv_sys_dlopen_deplibs=no
+ ;;
+ osf5.0|osf5.0a|osf5.1)
+ # dlopen *does* load deplibs and with the right loader patch applied
+ # it even uses RPATH in a shared library to search for shared objects
+ # that the library depends on, but there's no easy way to know if that
+ # patch is installed. Since this is the case, all we can really
+ # say is unknown -- it depends on the patch being installed. If
+ # it is, this changes to `yes'. Without it, it would be `no'.
+ libltdl_cv_sys_dlopen_deplibs=unknown
+ ;;
+ osf*)
+ # the two cases above should catch all versions of osf <= 5.1. Read
+ # the comments above for what we know about them.
+ # At > 5.1, deplibs are loaded *and* any RPATH in a shared library
+ # is used to find them so we can finally say `yes'.
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ solaris*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ esac
+ ])
+if test "$libltdl_cv_sys_dlopen_deplibs" != yes; then
+ AC_DEFINE([LTDL_DLOPEN_DEPLIBS], [1],
+ [Define if the OS needs help to load dependent libraries for dlopen().])
+fi
+])# AC_LTDL_SYS_DLOPEN_DEPLIBS
+
+
+# AC_LTDL_SHLIBEXT
+# ----------------
+AC_DEFUN([AC_LTDL_SHLIBEXT],
+[AC_REQUIRE([AC_LIBTOOL_SYS_DYNAMIC_LINKER])
+AC_CACHE_CHECK([which extension is used for loadable modules],
+ [libltdl_cv_shlibext],
+[
+module=yes
+eval libltdl_cv_shlibext=$shrext_cmds
+ ])
+if test -n "$libltdl_cv_shlibext"; then
+ AC_DEFINE_UNQUOTED([LTDL_SHLIB_EXT], ["$libltdl_cv_shlibext"],
+ [Define to the extension used for shared libraries, say, ".so".])
+fi
+])# AC_LTDL_SHLIBEXT
+
+
+# AC_LTDL_SHLIBPATH
+# -----------------
+AC_DEFUN([AC_LTDL_SHLIBPATH],
+[AC_REQUIRE([AC_LIBTOOL_SYS_DYNAMIC_LINKER])
+AC_CACHE_CHECK([which variable specifies run-time library path],
+ [libltdl_cv_shlibpath_var], [libltdl_cv_shlibpath_var="$shlibpath_var"])
+if test -n "$libltdl_cv_shlibpath_var"; then
+ AC_DEFINE_UNQUOTED([LTDL_SHLIBPATH_VAR], ["$libltdl_cv_shlibpath_var"],
+ [Define to the name of the environment variable that determines the dynamic library search path.])
+fi
+])# AC_LTDL_SHLIBPATH
+
+
+# AC_LTDL_SYSSEARCHPATH
+# ---------------------
+AC_DEFUN([AC_LTDL_SYSSEARCHPATH],
+[AC_REQUIRE([AC_LIBTOOL_SYS_DYNAMIC_LINKER])
+AC_CACHE_CHECK([for the default library search path],
+ [libltdl_cv_sys_search_path],
+ [libltdl_cv_sys_search_path="$sys_lib_dlsearch_path_spec"])
+if test -n "$libltdl_cv_sys_search_path"; then
+ sys_search_path=
+ for dir in $libltdl_cv_sys_search_path; do
+ if test -z "$sys_search_path"; then
+ sys_search_path="$dir"
+ else
+ sys_search_path="$sys_search_path$PATH_SEPARATOR$dir"
+ fi
+ done
+ AC_DEFINE_UNQUOTED([LTDL_SYSSEARCHPATH], ["$sys_search_path"],
+ [Define to the system default library search path.])
+fi
+])# AC_LTDL_SYSSEARCHPATH
+
+
+# AC_LTDL_OBJDIR
+# --------------
+AC_DEFUN([AC_LTDL_OBJDIR],
+[AC_CACHE_CHECK([for objdir],
+ [libltdl_cv_objdir],
+ [libltdl_cv_objdir="$objdir"
+ if test -n "$objdir"; then
+ :
+ else
+ rm -f .libs 2>/dev/null
+ mkdir .libs 2>/dev/null
+ if test -d .libs; then
+ libltdl_cv_objdir=.libs
+ else
+ # MS-DOS does not allow filenames that begin with a dot.
+ libltdl_cv_objdir=_libs
+ fi
+ rmdir .libs 2>/dev/null
+ fi
+ ])
+AC_DEFINE_UNQUOTED([LTDL_OBJDIR], ["$libltdl_cv_objdir/"],
+ [Define to the sub-directory in which libtool stores uninstalled libraries.])
+])# AC_LTDL_OBJDIR
+
+
+# AC_LTDL_DLPREOPEN
+# -----------------
+AC_DEFUN([AC_LTDL_DLPREOPEN],
+[AC_REQUIRE([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])
+AC_CACHE_CHECK([whether libtool supports -dlopen/-dlpreopen],
+ [libltdl_cv_preloaded_symbols],
+ [if test -n "$lt_cv_sys_global_symbol_pipe"; then
+ libltdl_cv_preloaded_symbols=yes
+ else
+ libltdl_cv_preloaded_symbols=no
+ fi
+ ])
+if test x"$libltdl_cv_preloaded_symbols" = xyes; then
+ AC_DEFINE([HAVE_PRELOADED_SYMBOLS], [1],
+ [Define if libtool can extract symbol lists from object files.])
+fi
+])# AC_LTDL_DLPREOPEN
+
+
+# AC_LTDL_DLLIB
+# -------------
+AC_DEFUN([AC_LTDL_DLLIB],
+[LIBADD_DL=
+AC_SUBST(LIBADD_DL)
+AC_LANG_PUSH([C])
+
+AC_CHECK_FUNC([shl_load],
+ [AC_DEFINE([HAVE_SHL_LOAD], [1],
+ [Define if you have the shl_load function.])],
+ [AC_CHECK_LIB([dld], [shl_load],
+ [AC_DEFINE([HAVE_SHL_LOAD], [1],
+ [Define if you have the shl_load function.])
+ LIBADD_DL="$LIBADD_DL -ldld"],
+ [AC_CHECK_LIB([dl], [dlopen],
+ [AC_DEFINE([HAVE_LIBDL], [1],
+ [Define if you have the libdl library or equivalent.])
+ LIBADD_DL="-ldl" libltdl_cv_lib_dl_dlopen="yes"],
+ [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#if HAVE_DLFCN_H
+# include <dlfcn.h>
+#endif
+ ]], [[dlopen(0, 0);]])],[AC_DEFINE([HAVE_LIBDL], [1],
+ [Define if you have the libdl library or equivalent.]) libltdl_cv_func_dlopen="yes"],[AC_CHECK_LIB([svld], [dlopen],
+ [AC_DEFINE([HAVE_LIBDL], [1],
+ [Define if you have the libdl library or equivalent.])
+ LIBADD_DL="-lsvld" libltdl_cv_func_dlopen="yes"],
+ [AC_CHECK_LIB([dld], [dld_link],
+ [AC_DEFINE([HAVE_DLD], [1],
+ [Define if you have the GNU dld library.])
+ LIBADD_DL="$LIBADD_DL -ldld"],
+ [AC_CHECK_FUNC([_dyld_func_lookup],
+ [AC_DEFINE([HAVE_DYLD], [1],
+ [Define if you have the _dyld_func_lookup function.])])
+ ])
+ ])
+ ])
+ ])
+ ])
+])
+
+if test x"$libltdl_cv_func_dlopen" = xyes || test x"$libltdl_cv_lib_dl_dlopen" = xyes
+then
+ lt_save_LIBS="$LIBS"
+ LIBS="$LIBS $LIBADD_DL"
+ AC_CHECK_FUNCS([dlerror])
+ LIBS="$lt_save_LIBS"
+fi
+AC_LANG_POP
+])# AC_LTDL_DLLIB
+
+
+# AC_LTDL_SYMBOL_USCORE
+# ---------------------
+# does the compiler prefix global symbols with an underscore?
+AC_DEFUN([AC_LTDL_SYMBOL_USCORE],
+[AC_REQUIRE([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])
+AC_CACHE_CHECK([for _ prefix in compiled symbols],
+ [ac_cv_sys_symbol_underscore],
+ [ac_cv_sys_symbol_underscore=no
+ cat > conftest.$ac_ext <<EOF
+void nm_test_func(){}
+int main(){nm_test_func;return 0;}
+EOF
+ if AC_TRY_EVAL(ac_compile); then
+ # Now try to grab the symbols.
+ ac_nlist=conftest.nm
+ if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $ac_nlist) && test -s "$ac_nlist"; then
+ # See whether the symbols have a leading underscore.
+ if grep '^. _nm_test_func' "$ac_nlist" >/dev/null; then
+ ac_cv_sys_symbol_underscore=yes
+ else
+ if grep '^. nm_test_func ' "$ac_nlist" >/dev/null; then
+ :
+ else
+ echo "configure: cannot find nm_test_func in $ac_nlist" >&AS_MESSAGE_LOG_FD
+ fi
+ fi
+ else
+ echo "configure: cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+ fi
+ else
+ echo "configure: failed program was:" >&AS_MESSAGE_LOG_FD
+ cat conftest.c >&AS_MESSAGE_LOG_FD
+ fi
+ rm -rf conftest*
+ ])
+])# AC_LTDL_SYMBOL_USCORE
+
+
+# AC_LTDL_DLSYM_USCORE
+# --------------------
+AC_DEFUN([AC_LTDL_DLSYM_USCORE],
+[AC_REQUIRE([AC_LTDL_SYMBOL_USCORE])
+if test x"$ac_cv_sys_symbol_underscore" = xyes; then
+ if test x"$libltdl_cv_func_dlopen" = xyes ||
+ test x"$libltdl_cv_lib_dl_dlopen" = xyes ; then
+ AC_CACHE_CHECK([whether we have to add an underscore for dlsym],
+ [libltdl_cv_need_uscore],
+ [libltdl_cv_need_uscore=unknown
+ save_LIBS="$LIBS"
+ LIBS="$LIBS $LIBADD_DL"
+ _LT_AC_TRY_DLOPEN_SELF(
+ [libltdl_cv_need_uscore=no], [libltdl_cv_need_uscore=yes],
+ [], [libltdl_cv_need_uscore=cross])
+ LIBS="$save_LIBS"
+ ])
+ fi
+fi
+
+if test x"$libltdl_cv_need_uscore" = xyes; then
+ AC_DEFINE([NEED_USCORE], [1],
+ [Define if dlsym() requires a leading underscore in symbol names.])
+fi
+])# AC_LTDL_DLSYM_USCORE
+
+# AC_LTDL_FUNC_ARGZ
+# -----------------
+AC_DEFUN([AC_LTDL_FUNC_ARGZ],
+[AC_CHECK_HEADERS([argz.h])
+
+AC_CHECK_TYPES([error_t],
+ [],
+ [AC_DEFINE([error_t], [int],
+ [Define to a type to use for `error_t' if it is not otherwise available.])],
+ [#if HAVE_ARGZ_H
+# include <argz.h>
+#endif])
+
+AC_CHECK_FUNCS([argz_append argz_create_sep argz_insert argz_next argz_stringify])
+])# AC_LTDL_FUNC_ARGZ
diff --git a/autoconf/m4/need_dev_zero_for_mmap.m4 b/autoconf/m4/need_dev_zero_for_mmap.m4
new file mode 100644
index 00000000000..57b32283017
--- /dev/null
+++ b/autoconf/m4/need_dev_zero_for_mmap.m4
@@ -0,0 +1,17 @@
+#
+# When allocating RWX memory, check whether we need to use /dev/zero
+# as the file descriptor or not.
+#
+AC_DEFUN([AC_NEED_DEV_ZERO_FOR_MMAP],
+[AC_CACHE_CHECK([if /dev/zero is needed for mmap],
+ac_cv_need_dev_zero_for_mmap,
+[if test "$llvm_cv_os_type" = "Interix" ; then
+ ac_cv_need_dev_zero_for_mmap=yes
+ else
+ ac_cv_need_dev_zero_for_mmap=no
+ fi
+])
+if test "$ac_cv_need_dev_zero_for_mmap" = yes; then
+ AC_DEFINE([NEED_DEV_ZERO_FOR_MMAP],[1],
+ [Define if /dev/zero should be used when mapping RWX memory, or undefine if its not necessary])
+fi])
diff --git a/autoconf/m4/path_tclsh.m4 b/autoconf/m4/path_tclsh.m4
new file mode 100644
index 00000000000..85433de71cc
--- /dev/null
+++ b/autoconf/m4/path_tclsh.m4
@@ -0,0 +1,39 @@
+dnl This macro checks for tclsh which is required to run dejagnu. On some
+dnl platforms (notably FreeBSD), tclsh is named tclshX.Y - this handles
+dnl that for us so we can get the latest installed tclsh version.
+dnl
+AC_DEFUN([DJ_AC_PATH_TCLSH], [
+no_itcl=true
+AC_MSG_CHECKING(for the tclsh program in tclinclude directory)
+AC_ARG_WITH(tclinclude,
+ AS_HELP_STRING([--with-tclinclude],
+ [directory where tcl headers are]),
+ [with_tclinclude=${withval}],[with_tclinclude=''])
+AC_CACHE_VAL(ac_cv_path_tclsh,[
+dnl first check to see if --with-itclinclude was specified
+if test x"${with_tclinclude}" != x ; then
+ if test -f ${with_tclinclude}/tclsh ; then
+ ac_cv_path_tclsh=`(cd ${with_tclinclude}; pwd)`
+ elif test -f ${with_tclinclude}/src/tclsh ; then
+ ac_cv_path_tclsh=`(cd ${with_tclinclude}/src; pwd)`
+ else
+ AC_MSG_ERROR([${with_tclinclude} directory doesn't contain tclsh])
+ fi
+fi])
+
+dnl see if one is installed
+if test x"${ac_cv_path_tclsh}" = x ; then
+ AC_MSG_RESULT(none)
+ AC_PATH_PROGS([TCLSH],[tclsh8.4 tclsh8.4.8 tclsh8.4.7 tclsh8.4.6 tclsh8.4.5 tclsh8.4.4 tclsh8.4.3 tclsh8.4.2 tclsh8.4.1 tclsh8.4.0 tclsh8.3 tclsh8.3.5 tclsh8.3.4 tclsh8.3.3 tclsh8.3.2 tclsh8.3.1 tclsh8.3.0 tclsh])
+ if test x"${TCLSH}" = x ; then
+ ac_cv_path_tclsh='';
+ else
+ ac_cv_path_tclsh="${TCLSH}";
+ fi
+else
+ AC_MSG_RESULT(${ac_cv_path_tclsh})
+ TCLSH="${ac_cv_path_tclsh}"
+ AC_SUBST(TCLSH)
+fi
+])
+
diff --git a/autoconf/m4/rand48.m4 b/autoconf/m4/rand48.m4
new file mode 100644
index 00000000000..76f08faad28
--- /dev/null
+++ b/autoconf/m4/rand48.m4
@@ -0,0 +1,12 @@
+#
+# This function determins if the srand48,drand48,lrand48 functions are
+# available on this platform.
+#
+AC_DEFUN([AC_FUNC_RAND48],[
+AC_SINGLE_CXX_CHECK([ac_cv_func_rand48],
+ [srand48/lrand48/drand48], [<stdlib.h>],
+ [srand48(0);lrand48();drand48();])
+if test "$ac_cv_func_rand48" = "yes" ; then
+AC_DEFINE([HAVE_RAND48],1,[Define to 1 if srand48/lrand48/drand48 exist in <stdlib.h>])
+fi
+])
diff --git a/autoconf/m4/sanity_check.m4 b/autoconf/m4/sanity_check.m4
new file mode 100644
index 00000000000..639fccca246
--- /dev/null
+++ b/autoconf/m4/sanity_check.m4
@@ -0,0 +1,31 @@
+dnl Check a program for version sanity. The test runs a program, passes it an
+dnl argument to make it print out some identification string, and filters that
+dnl output with a regular expression. If the output is non-empty, the program
+dnl passes the sanity check.
+dnl $1 - Name or full path of the program to run
+dnl $2 - Argument to pass to print out identification string
+dnl $3 - grep RE to match identification string
+dnl $4 - set to 1 to make errors only a warning
+AC_DEFUN([CHECK_PROGRAM_SANITY],
+[
+AC_MSG_CHECKING([sanity for program ]$1)
+sanity="0"
+sanity_path=`which $1 2>/dev/null`
+if test "$?" -eq 0 -a -x "$sanity_path" ; then
+ sanity=`$1 $2 2>&1 | grep "$3"`
+ if test -z "$sanity" ; then
+ AC_MSG_RESULT([no])
+ sanity="0"
+ if test "$4" -eq 1 ; then
+ AC_MSG_WARN([Program ]$1[ failed to pass sanity check.])
+ else
+ AC_MSG_ERROR([Program ]$1[ failed to pass sanity check.])
+ fi
+ else
+ AC_MSG_RESULT([yes])
+ sanity="1"
+ fi
+else
+ AC_MSG_RESULT([not found])
+fi
+])
diff --git a/autoconf/m4/single_cxx_check.m4 b/autoconf/m4/single_cxx_check.m4
new file mode 100644
index 00000000000..21efa4bed35
--- /dev/null
+++ b/autoconf/m4/single_cxx_check.m4
@@ -0,0 +1,10 @@
+dnl AC_SINGLE_CXX_CHECK(CACHEVAR, FUNCTION, HEADER, PROGRAM)
+dnl $1, $2, $3, $4,
+dnl
+AC_DEFUN([AC_SINGLE_CXX_CHECK],
+ [AC_CACHE_CHECK([for $2 in $3], [$1],
+ [AC_LANG_PUSH([C++])
+ AC_COMPILE_IFELSE(AC_LANG_PROGRAM([#include $3],[$4]),[$1=yes],[$1=no])
+ AC_LANG_POP([C++])])
+ ])
+
diff --git a/autoconf/m4/visibility_inlines_hidden.m4 b/autoconf/m4/visibility_inlines_hidden.m4
new file mode 100644
index 00000000000..b1cc42aa5f5
--- /dev/null
+++ b/autoconf/m4/visibility_inlines_hidden.m4
@@ -0,0 +1,24 @@
+#
+# Determine if the compiler accepts -fvisibility-inlines-hidden
+#
+# This macro is specific to LLVM.
+#
+AC_DEFUN([AC_CXX_USE_VISIBILITY_INLINES_HIDDEN],
+[AC_CACHE_CHECK([for compiler -fvisibility-inlines-hidden option],
+ [llvm_cv_cxx_visibility_inlines_hidden],
+[ AC_LANG_PUSH([C++])
+ oldcxxflags="$CXXFLAGS"
+ CXXFLAGS="$CXXFLAGS -O0 -fvisibility-inlines-hidden -Werror"
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+ [template <typename T> struct X { void __attribute__((noinline)) f() {} };],
+ [X<int>().f();])],
+ [llvm_cv_cxx_visibility_inlines_hidden=yes],[llvm_cv_cxx_visibility_inlines_hidden=no])
+ CXXFLAGS="$oldcxxflags"
+ AC_LANG_POP([C++])
+])
+if test "$llvm_cv_cxx_visibility_inlines_hidden" = yes ; then
+ AC_SUBST([ENABLE_VISIBILITY_INLINES_HIDDEN],[1])
+else
+ AC_SUBST([ENABLE_VISIBILITY_INLINES_HIDDEN],[0])
+fi
+])
diff --git a/autoconf/missing b/autoconf/missing
new file mode 100755
index 00000000000..64b5f901dd5
--- /dev/null
+++ b/autoconf/missing
@@ -0,0 +1,353 @@
+#! /bin/sh
+# Common stub for a few missing GNU programs while installing.
+
+scriptversion=2004-09-07.08
+
+# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004
+# Free Software Foundation, Inc.
+# Originally by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+# 02111-1307, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+if test $# -eq 0; then
+ echo 1>&2 "Try \`$0 --help' for more information"
+ exit 1
+fi
+
+run=:
+
+# In the cases where this matters, `missing' is being run in the
+# srcdir already.
+if test -f configure.ac; then
+ configure_ac=configure.ac
+else
+ configure_ac=configure.in
+fi
+
+msg="missing on your system"
+
+case "$1" in
+--run)
+ # Try to run requested program, and just exit if it succeeds.
+ run=
+ shift
+ "$@" && exit 0
+ # Exit code 63 means version mismatch. This often happens
+ # when the user try to use an ancient version of a tool on
+ # a file that requires a minimum version. In this case we
+ # we should proceed has if the program had been absent, or
+ # if --run hadn't been passed.
+ if test $? = 63; then
+ run=:
+ msg="probably too old"
+ fi
+ ;;
+
+ -h|--h|--he|--hel|--help)
+ echo "\
+$0 [OPTION]... PROGRAM [ARGUMENT]...
+
+Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an
+error status if there is no known handling for PROGRAM.
+
+Options:
+ -h, --help display this help and exit
+ -v, --version output version information and exit
+ --run try to run the given command, and emulate it if it fails
+
+Supported PROGRAM values:
+ aclocal touch file \`aclocal.m4'
+ autoconf touch file \`configure'
+ autoheader touch file \`config.h.in'
+ automake touch all \`Makefile.in' files
+ bison create \`y.tab.[ch]', if possible, from existing .[ch]
+ flex create \`lex.yy.c', if possible, from existing .c
+ help2man touch the output file
+ lex create \`lex.yy.c', if possible, from existing .c
+ makeinfo touch the output file
+ tar try tar, gnutar, gtar, then tar without non-portable flags
+ yacc create \`y.tab.[ch]', if possible, from existing .[ch]
+
+Send bug reports to <bug-automake@gnu.org>."
+ exit 0
+ ;;
+
+ -v|--v|--ve|--ver|--vers|--versi|--versio|--version)
+ echo "missing $scriptversion (GNU Automake)"
+ exit 0
+ ;;
+
+ -*)
+ echo 1>&2 "$0: Unknown \`$1' option"
+ echo 1>&2 "Try \`$0 --help' for more information"
+ exit 1
+ ;;
+
+esac
+
+# Now exit if we have it, but it failed. Also exit now if we
+# don't have it and --version was passed (most likely to detect
+# the program).
+case "$1" in
+ lex|yacc)
+ # Not GNU programs, they don't have --version.
+ ;;
+
+ tar)
+ if test -n "$run"; then
+ echo 1>&2 "ERROR: \`tar' requires --run"
+ exit 1
+ elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
+ exit 1
+ fi
+ ;;
+
+ *)
+ if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+ # We have it, but it failed.
+ exit 1
+ elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
+ # Could not run --version or --help. This is probably someone
+ # running `$TOOL --version' or `$TOOL --help' to check whether
+ # $TOOL exists and not knowing $TOOL uses missing.
+ exit 1
+ fi
+ ;;
+esac
+
+# If it does not exist, or fails to run (possibly an outdated version),
+# try to emulate it.
+case "$1" in
+ aclocal*)
+ echo 1>&2 "\
+WARNING: \`$1' is $msg. You should only need it if
+ you modified \`acinclude.m4' or \`${configure_ac}'. You might want
+ to install the \`Automake' and \`Perl' packages. Grab them from
+ any GNU archive site."
+ touch aclocal.m4
+ ;;
+
+ autoconf)
+ echo 1>&2 "\
+WARNING: \`$1' is $msg. You should only need it if
+ you modified \`${configure_ac}'. You might want to install the
+ \`Autoconf' and \`GNU m4' packages. Grab them from any GNU
+ archive site."
+ touch configure
+ ;;
+
+ autoheader)
+ echo 1>&2 "\
+WARNING: \`$1' is $msg. You should only need it if
+ you modified \`acconfig.h' or \`${configure_ac}'. You might want
+ to install the \`Autoconf' and \`GNU m4' packages. Grab them
+ from any GNU archive site."
+ files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}`
+ test -z "$files" && files="config.h"
+ touch_files=
+ for f in $files; do
+ case "$f" in
+ *:*) touch_files="$touch_files "`echo "$f" |
+ sed -e 's/^[^:]*://' -e 's/:.*//'`;;
+ *) touch_files="$touch_files $f.in";;
+ esac
+ done
+ touch $touch_files
+ ;;
+
+ automake*)
+ echo 1>&2 "\
+WARNING: \`$1' is $msg. You should only need it if
+ you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'.
+ You might want to install the \`Automake' and \`Perl' packages.
+ Grab them from any GNU archive site."
+ find . -type f -name Makefile.am -print |
+ sed 's/\.am$/.in/' |
+ while read f; do touch "$f"; done
+ ;;
+
+ autom4te)
+ echo 1>&2 "\
+WARNING: \`$1' is needed, but is $msg.
+ You might have modified some files without having the
+ proper tools for further handling them.
+ You can get \`$1' as part of \`Autoconf' from any GNU
+ archive site."
+
+ file=`echo "$*" | sed -n 's/.*--output[ =]*\([^ ]*\).*/\1/p'`
+ test -z "$file" && file=`echo "$*" | sed -n 's/.*-o[ ]*\([^ ]*\).*/\1/p'`
+ if test -f "$file"; then
+ touch $file
+ else
+ test -z "$file" || exec >$file
+ echo "#! /bin/sh"
+ echo "# Created by GNU Automake missing as a replacement of"
+ echo "# $ $@"
+ echo "exit 0"
+ chmod +x $file
+ exit 1
+ fi
+ ;;
+
+ bison|yacc)
+ echo 1>&2 "\
+WARNING: \`$1' $msg. You should only need it if
+ you modified a \`.y' file. You may need the \`Bison' package
+ in order for those modifications to take effect. You can get
+ \`Bison' from any GNU archive site."
+ rm -f y.tab.c y.tab.h
+ if [ $# -ne 1 ]; then
+ eval LASTARG="\${$#}"
+ case "$LASTARG" in
+ *.y)
+ SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" y.tab.c
+ fi
+ SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" y.tab.h
+ fi
+ ;;
+ esac
+ fi
+ if [ ! -f y.tab.h ]; then
+ echo >y.tab.h
+ fi
+ if [ ! -f y.tab.c ]; then
+ echo 'main() { return 0; }' >y.tab.c
+ fi
+ ;;
+
+ lex|flex)
+ echo 1>&2 "\
+WARNING: \`$1' is $msg. You should only need it if
+ you modified a \`.l' file. You may need the \`Flex' package
+ in order for those modifications to take effect. You can get
+ \`Flex' from any GNU archive site."
+ rm -f lex.yy.c
+ if [ $# -ne 1 ]; then
+ eval LASTARG="\${$#}"
+ case "$LASTARG" in
+ *.l)
+ SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" lex.yy.c
+ fi
+ ;;
+ esac
+ fi
+ if [ ! -f lex.yy.c ]; then
+ echo 'main() { return 0; }' >lex.yy.c
+ fi
+ ;;
+
+ help2man)
+ echo 1>&2 "\
+WARNING: \`$1' is $msg. You should only need it if
+ you modified a dependency of a manual page. You may need the
+ \`Help2man' package in order for those modifications to take
+ effect. You can get \`Help2man' from any GNU archive site."
+
+ file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
+ if test -z "$file"; then
+ file=`echo "$*" | sed -n 's/.*--output=\([^ ]*\).*/\1/p'`
+ fi
+ if [ -f "$file" ]; then
+ touch $file
+ else
+ test -z "$file" || exec >$file
+ echo ".ab help2man is required to generate this page"
+ exit 1
+ fi
+ ;;
+
+ makeinfo)
+ echo 1>&2 "\
+WARNING: \`$1' is $msg. You should only need it if
+ you modified a \`.texi' or \`.texinfo' file, or any other file
+ indirectly affecting the aspect of the manual. The spurious
+ call might also be the consequence of using a buggy \`make' (AIX,
+ DU, IRIX). You might want to install the \`Texinfo' package or
+ the \`GNU make' package. Grab either from any GNU archive site."
+ file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
+ if test -z "$file"; then
+ file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
+ file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file`
+ fi
+ touch $file
+ ;;
+
+ tar)
+ shift
+
+ # We have already tried tar in the generic part.
+ # Look for gnutar/gtar before invocation to avoid ugly error
+ # messages.
+ if (gnutar --version > /dev/null 2>&1); then
+ gnutar "$@" && exit 0
+ fi
+ if (gtar --version > /dev/null 2>&1); then
+ gtar "$@" && exit 0
+ fi
+ firstarg="$1"
+ if shift; then
+ case "$firstarg" in
+ *o*)
+ firstarg=`echo "$firstarg" | sed s/o//`
+ tar "$firstarg" "$@" && exit 0
+ ;;
+ esac
+ case "$firstarg" in
+ *h*)
+ firstarg=`echo "$firstarg" | sed s/h//`
+ tar "$firstarg" "$@" && exit 0
+ ;;
+ esac
+ fi
+
+ echo 1>&2 "\
+WARNING: I can't seem to be able to run \`tar' with the given arguments.
+ You may want to install GNU tar or Free paxutils, or check the
+ command line arguments."
+ exit 1
+ ;;
+
+ *)
+ echo 1>&2 "\
+WARNING: \`$1' is needed, and is $msg.
+ You might have modified some files without having the
+ proper tools for further handling them. Check the \`README' file,
+ it often tells you about the needed prerequisites for installing
+ this package. You may also peek at any GNU archive site, in case
+ some other package would contain this missing \`$1' program."
+ exit 1
+ ;;
+esac
+
+exit 0
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
diff --git a/autoconf/mkinstalldirs b/autoconf/mkinstalldirs
new file mode 100755
index 00000000000..1ee2d580177
--- /dev/null
+++ b/autoconf/mkinstalldirs
@@ -0,0 +1,150 @@
+#! /bin/sh
+# mkinstalldirs --- make directory hierarchy
+
+scriptversion=2004-02-15.20
+
+# Original author: Noah Friedman <friedman@prep.ai.mit.edu>
+# Created: 1993-05-16
+# Public domain.
+#
+# This file is maintained in Automake, please report
+# bugs to <bug-automake@gnu.org> or send patches to
+# <automake-patches@gnu.org>.
+
+errstatus=0
+dirmode=""
+
+usage="\
+Usage: mkinstalldirs [-h] [--help] [--version] [-m MODE] DIR ...
+
+Create each directory DIR (with mode MODE, if specified), including all
+leading file name components.
+
+Report bugs to <bug-automake@gnu.org>."
+
+# process command line arguments
+while test $# -gt 0 ; do
+ case $1 in
+ -h | --help | --h*) # -h for help
+ echo "$usage"
+ exit 0
+ ;;
+ -m) # -m PERM arg
+ shift
+ test $# -eq 0 && { echo "$usage" 1>&2; exit 1; }
+ dirmode=$1
+ shift
+ ;;
+ --version)
+ echo "$0 $scriptversion"
+ exit 0
+ ;;
+ --) # stop option processing
+ shift
+ break
+ ;;
+ -*) # unknown option
+ echo "$usage" 1>&2
+ exit 1
+ ;;
+ *) # first non-opt arg
+ break
+ ;;
+ esac
+done
+
+for file
+do
+ if test -d "$file"; then
+ shift
+ else
+ break
+ fi
+done
+
+case $# in
+ 0) exit 0 ;;
+esac
+
+# Solaris 8's mkdir -p isn't thread-safe. If you mkdir -p a/b and
+# mkdir -p a/c at the same time, both will detect that a is missing,
+# one will create a, then the other will try to create a and die with
+# a "File exists" error. This is a problem when calling mkinstalldirs
+# from a parallel make. We use --version in the probe to restrict
+# ourselves to GNU mkdir, which is thread-safe.
+case $dirmode in
+ '')
+ if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then
+ # echo "mkdir -p -- $*"
+ exec mkdir -p -- "$@"
+ else
+ # On NextStep and OpenStep, the `mkdir' command does not
+ # recognize any option. It will interpret all options as
+ # directories to create, and then abort because `.' already
+ # exists.
+ test -d ./-p && rmdir ./-p
+ test -d ./--version && rmdir ./--version
+ fi
+ ;;
+ *)
+ if mkdir -m "$dirmode" -p --version . >/dev/null 2>&1 &&
+ test ! -d ./--version; then
+ # echo "mkdir -m $dirmode -p -- $*"
+ exec mkdir -m "$dirmode" -p -- "$@"
+ else
+ # Clean up after NextStep and OpenStep mkdir.
+ for d in ./-m ./-p ./--version "./$dirmode";
+ do
+ test -d $d && rmdir $d
+ done
+ fi
+ ;;
+esac
+
+for file
+do
+ set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'`
+ shift
+
+ pathcomp=
+ for d
+ do
+ pathcomp="$pathcomp$d"
+ case $pathcomp in
+ -*) pathcomp=./$pathcomp ;;
+ esac
+
+ if test ! -d "$pathcomp"; then
+ # echo "mkdir $pathcomp"
+
+ mkdir "$pathcomp" || lasterr=$?
+
+ if test ! -d "$pathcomp"; then
+ errstatus=$lasterr
+ else
+ if test ! -z "$dirmode"; then
+ # echo "chmod $dirmode $pathcomp"
+ lasterr=""
+ chmod "$dirmode" "$pathcomp" || lasterr=$?
+
+ if test ! -z "$lasterr"; then
+ errstatus=$lasterr
+ fi
+ fi
+ fi
+ fi
+
+ pathcomp="$pathcomp/"
+ done
+done
+
+exit $errstatus
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
diff --git a/bindings/LLVMBuild.txt b/bindings/LLVMBuild.txt
new file mode 100644
index 00000000000..241ac0964f3
--- /dev/null
+++ b/bindings/LLVMBuild.txt
@@ -0,0 +1,21 @@
+;===- ./bindings/LLVMBuild.txt ---------------------------------*- Conf -*--===;
+;
+; The LLVM Compiler Infrastructure
+;
+; This file is distributed under the University of Illinois Open Source
+; License. See LICENSE.TXT for details.
+;
+;===------------------------------------------------------------------------===;
+;
+; This is an LLVMBuild description file for the components in this subdirectory.
+;
+; For more information on the LLVMBuild system, please see:
+;
+; http://llvm.org/docs/LLVMBuild.html
+;
+;===------------------------------------------------------------------------===;
+
+[component_0]
+type = Group
+name = Bindings
+parent = $ROOT
diff --git a/bindings/Makefile b/bindings/Makefile
new file mode 100644
index 00000000000..c545b28854c
--- /dev/null
+++ b/bindings/Makefile
@@ -0,0 +1,16 @@
+##===- bindings/Makefile -----------------------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ..
+
+include $(LEVEL)/Makefile.config
+
+PARALLEL_DIRS = $(BINDINGS_TO_BUILD)
+
+include $(LEVEL)/Makefile.common
diff --git a/bindings/README.txt b/bindings/README.txt
new file mode 100644
index 00000000000..7693cb2cead
--- /dev/null
+++ b/bindings/README.txt
@@ -0,0 +1,3 @@
+This directory contains bindings for the LLVM compiler infrastructure to allow
+programs written in languages other than C or C++ to take advantage of the LLVM
+infrastructure--for instance, a self-hosted compiler front-end.
diff --git a/bindings/ocaml/Makefile b/bindings/ocaml/Makefile
new file mode 100644
index 00000000000..a89caefb4de
--- /dev/null
+++ b/bindings/ocaml/Makefile
@@ -0,0 +1,19 @@
+##===- bindings/ocaml/Makefile -----------------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../..
+DIRS = llvm bitreader bitwriter analysis target executionengine transforms
+ExtraMakefiles = $(PROJ_OBJ_DIR)/Makefile.ocaml
+
+ocamldoc:
+ $(Verb) for i in $(DIRS) ; do \
+ $(MAKE) -C $$i ocamldoc; \
+ done
+
+include $(LEVEL)/Makefile.common
diff --git a/bindings/ocaml/Makefile.ocaml b/bindings/ocaml/Makefile.ocaml
new file mode 100644
index 00000000000..a2a8b02eac7
--- /dev/null
+++ b/bindings/ocaml/Makefile.ocaml
@@ -0,0 +1,415 @@
+##===- tools/ml/Makefile -----------------------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# An ocaml library is a unique project type in the context of LLVM, so rules are
+# here rather than in Makefile.rules.
+#
+# Reference materials on installing ocaml libraries:
+#
+# https://fedoraproject.org/wiki/Packaging/OCaml
+# http://pkg-ocaml-maint.alioth.debian.org/ocaml_packaging_policy.txt
+#
+##===----------------------------------------------------------------------===##
+
+include $(LEVEL)/Makefile.config
+
+# CFLAGS needs to be set before Makefile.rules is included.
+CXX.Flags += -I"$(shell $(OCAMLC) -where)"
+C.Flags += -I"$(shell $(OCAMLC) -where)"
+
+include $(LEVEL)/Makefile.common
+
+# Intentionally ignore PROJ_prefix here. We want the ocaml stdlib. However, the
+# user can override this with OCAML_LIBDIR or configure --with-ocaml-libdir=.
+PROJ_libocamldir := $(DESTDIR)$(OCAML_LIBDIR)
+OcamlDir := $(LibDir)/ocaml
+
+# Info from llvm-config and similar
+ifndef IS_CLEANING_TARGET
+ifdef UsedComponents
+UsedLibs = $(shell $(LLVM_CONFIG) --libs $(UsedComponents))
+UsedLibNames = $(shell $(LLVM_CONFIG) --libnames $(UsedComponents))
+endif
+endif
+
+# Tools
+OCAMLCFLAGS += -I $(ObjDir) -I $(OcamlDir)
+ifndef IS_CLEANING_TARGET
+ifneq ($(ObjectsO),)
+OCAMLAFLAGS += $(patsubst %,-cclib %, \
+ $(filter-out -L$(LibDir),-l$(LIBRARYNAME) \
+ $(shell $(LLVM_CONFIG) --ldflags)) \
+ $(UsedLibs))
+else
+OCAMLAFLAGS += $(patsubst %,-cclib %, \
+ $(filter-out -L$(LibDir),$(shell $(LLVM_CONFIG) --ldflags)) \
+ $(UsedLibs))
+endif
+endif
+
+# -g was introduced in 3.10.0.
+#ifneq ($(ENABLE_OPTIMIZED),1)
+# OCAMLDEBUGFLAG := -g
+#endif
+
+Compile.CMI := $(strip $(OCAMLC) -c $(OCAMLCFLAGS) $(OCAMLDEBUGFLAG) -o)
+Compile.CMO := $(strip $(OCAMLC) -c $(OCAMLCFLAGS) $(OCAMLDEBUGFLAG) -o)
+Archive.CMA := $(strip $(OCAMLC) -a -custom $(OCAMLAFLAGS) $(OCAMLDEBUGFLAG) \
+ -o)
+
+Compile.CMX := $(strip $(OCAMLOPT) -c $(OCAMLCFLAGS) $(OCAMLDEBUGFLAG) -o)
+Archive.CMXA := $(strip $(OCAMLOPT) -a $(OCAMLAFLAGS) $(OCAMLDEBUGFLAG) -o)
+
+ifdef OCAMLOPT
+Archive.EXE := $(strip $(OCAMLOPT) -cc $(CXX) $(OCAMLCFLAGS) $(UsedOcamLibs:%=%.cmxa) $(OCAMLDEBUGFLAG) -o)
+else
+Archive.EXE := $(strip $(OCAMLC) -cc $(CXX) $(OCAMLCFLAGS) $(OCAMLDEBUGFLAG:%=%.cma) -o)
+endif
+
+# Source files
+ifndef OcamlSources1
+OcamlSources1 := $(sort $(wildcard $(PROJ_SRC_DIR)/*.ml))
+endif
+
+ifndef OcamlHeaders1
+OcamlHeaders1 := $(sort $(wildcard $(PROJ_SRC_DIR)/*.mli))
+endif
+
+OcamlSources2 := $(filter-out $(ExcludeSources),$(OcamlSources1))
+OcamlHeaders2 := $(filter-out $(ExcludeHeaders),$(OcamlHeaders1))
+
+OcamlSources := $(OcamlSources2:$(PROJ_SRC_DIR)/%=$(ObjDir)/%)
+OcamlHeaders := $(OcamlHeaders2:$(PROJ_SRC_DIR)/%=$(ObjDir)/%)
+
+# Intermediate files
+ObjectsCMI := $(OcamlSources:%.ml=%.cmi)
+ObjectsCMO := $(OcamlSources:%.ml=%.cmo)
+ObjectsCMX := $(OcamlSources:%.ml=%.cmx)
+
+ifdef LIBRARYNAME
+LibraryCMA := $(ObjDir)/$(LIBRARYNAME).cma
+LibraryCMXA := $(ObjDir)/$(LIBRARYNAME).cmxa
+endif
+
+ifdef TOOLNAME
+ToolEXE := $(ObjDir)/$(TOOLNAME)$(EXEEXT)
+endif
+
+# Output files
+# The .cmo files are the only intermediates; all others are to be installed.
+OutputsCMI := $(ObjectsCMI:$(ObjDir)/%.cmi=$(OcamlDir)/%.cmi)
+OutputsCMX := $(ObjectsCMX:$(ObjDir)/%.cmx=$(OcamlDir)/%.cmx)
+OutputLibs := $(UsedLibNames:%=$(OcamlDir)/%)
+
+ifdef LIBRARYNAME
+LibraryA := $(OcamlDir)/lib$(LIBRARYNAME).a
+OutputCMA := $(LibraryCMA:$(ObjDir)/%.cma=$(OcamlDir)/%.cma)
+OutputCMXA := $(LibraryCMXA:$(ObjDir)/%.cmxa=$(OcamlDir)/%.cmxa)
+endif
+
+ifdef TOOLNAME
+ifdef EXAMPLE_TOOL
+OutputEXE := $(ExmplDir)/$(strip $(TOOLNAME))$(EXEEXT)
+else
+OutputEXE := $(ToolDir)/$(strip $(TOOLNAME))$(EXEEXT)
+endif
+endif
+
+# Installation targets
+DestLibs := $(UsedLibNames:%=$(PROJ_libocamldir)/%)
+
+ifdef LIBRARYNAME
+DestA := $(PROJ_libocamldir)/lib$(LIBRARYNAME).a
+DestCMA := $(PROJ_libocamldir)/$(LIBRARYNAME).cma
+DestCMXA := $(PROJ_libocamldir)/$(LIBRARYNAME).cmxa
+endif
+
+##===- Dependencies -------------------------------------------------------===##
+# Copy the sources into the intermediate directory because older ocamlc doesn't
+# support -o except when linking (outputs are placed next to inputs).
+
+$(ObjDir)/%.mli: $(PROJ_SRC_DIR)/%.mli $(ObjDir)/.dir
+ $(Verb) $(CP) -f $< $@
+
+$(ObjDir)/%.ml: $(PROJ_SRC_DIR)/%.ml $(ObjDir)/.dir
+ $(Verb) $(CP) -f $< $@
+
+$(ObjectsCMI): $(UsedOcamlInterfaces:%=$(OcamlDir)/%.cmi)
+
+ifdef LIBRARYNAME
+$(ObjDir)/$(LIBRARYNAME).ocamldep: $(OcamlSources) $(OcamlHeaders) \
+ $(OcamlDir)/.dir $(ObjDir)/.dir
+ $(Verb) $(OCAMLDEP) $(OCAMLCFLAGS) $(OcamlSources) $(OcamlHeaders) > $@
+
+-include $(ObjDir)/$(LIBRARYNAME).ocamldep
+endif
+
+ifdef TOOLNAME
+$(ObjDir)/$(TOOLNAME).ocamldep: $(OcamlSources) $(OcamlHeaders) \
+ $(OcamlDir)/.dir $(ObjDir)/.dir
+ $(Verb) $(OCAMLDEP) $(OCAMLCFLAGS) $(OcamlSources) $(OcamlHeaders) > $@
+
+-include $(ObjDir)/$(TOOLNAME).ocamldep
+endif
+
+##===- Build static library from C sources --------------------------------===##
+
+ifdef LibraryA
+all-local:: $(LibraryA)
+clean-local:: clean-a
+install-local:: install-a
+uninstall-local:: uninstall-a
+
+$(LibraryA): $(ObjectsO) $(OcamlDir)/.dir
+ $(Echo) "Building $(BuildMode) $(notdir $@)"
+ -$(Verb) $(RM) -f $@
+ $(Verb) $(Archive) $@ $(ObjectsO)
+ $(Verb) $(Ranlib) $@
+
+clean-a::
+ -$(Verb) $(RM) -f $(LibraryA)
+
+install-a:: $(LibraryA)
+ $(Echo) "Installing $(BuildMode) $(DestA)"
+ $(Verb) $(MKDIR) $(PROJ_libocamldir)
+ $(Verb) $(INSTALL) $(LibraryA) $(DestA)
+ $(Verb)
+
+uninstall-a::
+ $(Echo) "Uninstalling $(DestA)"
+ -$(Verb) $(RM) -f $(DestA)
+endif
+
+
+##===- Deposit dependent libraries adjacent to Ocaml libs -----------------===##
+
+all-local:: build-deplibs
+clean-local:: clean-deplibs
+install-local:: install-deplibs
+uninstall-local:: uninstall-deplibs
+
+build-deplibs: $(OutputLibs)
+
+$(OcamlDir)/%.a: $(LibDir)/%.a
+ $(Verb) ln -sf $< $@
+
+$(OcamlDir)/%.o: $(LibDir)/%.o
+ $(Verb) ln -sf $< $@
+
+clean-deplibs:
+ $(Verb) $(RM) -f $(OutputLibs)
+
+install-deplibs:
+ $(Verb) $(MKDIR) $(PROJ_libocamldir)
+ $(Verb) for i in $(DestLibs:$(PROJ_libocamldir)/%=%); do \
+ ln -sf "$(PROJ_libdir)/$$i" "$(PROJ_libocamldir)/$$i"; \
+ done
+
+uninstall-deplibs:
+ $(Verb) $(RM) -f $(DestLibs)
+
+
+##===- Build ocaml interfaces (.mli's -> .cmi's) --------------------------===##
+
+ifneq ($(OcamlHeaders),)
+all-local:: build-cmis
+clean-local:: clean-cmis
+install-local:: install-cmis
+uninstall-local:: uninstall-cmis
+
+build-cmis: $(OutputsCMI)
+
+$(OcamlDir)/%.cmi: $(ObjDir)/%.cmi $(OcamlDir)/.dir
+ $(Verb) $(CP) -f $< $@
+
+$(ObjDir)/%.cmi: $(ObjDir)/%.mli $(ObjDir)/.dir
+ $(Echo) "Compiling $(notdir $<) for $(BuildMode) build"
+ $(Verb) $(Compile.CMI) $@ $<
+
+clean-cmis::
+ -$(Verb) $(RM) -f $(OutputsCMI)
+
+# Also install the .mli's (headers) as documentation.
+install-cmis: $(OutputsCMI) $(OcamlHeaders)
+ $(Verb) $(MKDIR) $(PROJ_libocamldir)
+ $(Verb) for i in $(OcamlHeaders:$(ObjDir)/%=%); do \
+ $(EchoCmd) "Installing $(BuildMode) $(PROJ_libocamldir)/$$i"; \
+ $(DataInstall) $(ObjDir)/$$i "$(PROJ_libocamldir)/$$i"; \
+ done
+ $(Verb) for i in $(OutputsCMI:$(OcamlDir)/%=%); do \
+ $(EchoCmd) "Installing $(BuildMode) $(PROJ_libocamldir)/$$i"; \
+ $(DataInstall) $(OcamlDir)/$$i "$(PROJ_libocamldir)/$$i"; \
+ done
+
+uninstall-cmis::
+ $(Verb) for i in $(OutputsCMI:$(OcamlDir)/%=%); do \
+ $(EchoCmd) "Uninstalling $(PROJ_libocamldir)/$$i"; \
+ $(RM) -f "$(PROJ_libocamldir)/$$i"; \
+ done
+ $(Verb) for i in $(OcamlHeaders:$(ObjDir)/%=%); do \
+ $(EchoCmd) "Uninstalling $(PROJ_libocamldir)/$$i"; \
+ $(RM) -f "$(PROJ_libocamldir)/$$i"; \
+ done
+endif
+
+
+##===- Build ocaml bytecode archive (.ml's -> .cmo's -> .cma) -------------===##
+
+$(ObjDir)/%.cmo: $(ObjDir)/%.ml
+ $(Echo) "Compiling $(notdir $<) for $(BuildMode) build"
+ $(Verb) $(Compile.CMO) $@ $<
+
+ifdef LIBRARYNAME
+all-local:: $(OutputCMA)
+clean-local:: clean-cma
+install-local:: install-cma
+uninstall-local:: uninstall-cma
+
+$(OutputCMA): $(LibraryCMA) $(OcamlDir)/.dir
+ $(Verb) $(CP) -f $< $@
+
+$(LibraryCMA): $(ObjectsCMO) $(OcamlDir)/.dir
+ $(Echo) "Archiving $(notdir $@) for $(BuildMode) build"
+ $(Verb) $(Archive.CMA) $@ $(ObjectsCMO)
+
+clean-cma::
+ $(Verb) $(RM) -f $(OutputCMA) $(UsedLibNames:%=$(OcamlDir)/%)
+
+install-cma:: $(OutputCMA)
+ $(Echo) "Installing $(BuildMode) $(DestCMA)"
+ $(Verb) $(MKDIR) $(PROJ_libocamldir)
+ $(Verb) $(DataInstall) $(OutputCMA) "$(DestCMA)"
+
+uninstall-cma::
+ $(Echo) "Uninstalling $(DestCMA)"
+ -$(Verb) $(RM) -f $(DestCMA)
+endif
+
+##===- Build optimized ocaml archive (.ml's -> .cmx's -> .cmxa, .a) -------===##
+
+# The ocamlopt compiler is supported on a set of targets disjoint from LLVM's.
+# If unavailable, 'configure' will not define OCAMLOPT in Makefile.config.
+ifdef OCAMLOPT
+
+$(OcamlDir)/%.cmx: $(ObjDir)/%.cmx
+ $(Verb) $(CP) -f $< $@
+
+$(ObjDir)/%.cmx: $(ObjDir)/%.ml
+ $(Echo) "Compiling optimized $(notdir $<) for $(BuildMode) build"
+ $(Verb) $(Compile.CMX) $@ $<
+
+ifdef LIBRARYNAME
+all-local:: $(OutputCMXA) $(OutputsCMX)
+clean-local:: clean-cmxa
+install-local:: install-cmxa
+uninstall-local:: uninstall-cmxa
+
+$(OutputCMXA): $(LibraryCMXA)
+ $(Verb) $(CP) -f $< $@
+ $(Verb) $(CP) -f $(<:.cmxa=.a) $(@:.cmxa=.a)
+
+$(LibraryCMXA): $(ObjectsCMX)
+ $(Echo) "Archiving $(notdir $@) for $(BuildMode) build"
+ $(Verb) $(Archive.CMXA) $@ $(ObjectsCMX)
+ $(Verb) $(RM) -f $(@:.cmxa=.o)
+
+clean-cmxa::
+ $(Verb) $(RM) -f $(OutputCMXA) $(OutputCMXA:.cmxa=.a) $(OutputsCMX)
+
+install-cmxa:: $(OutputCMXA) $(OutputsCMX)
+ $(Verb) $(MKDIR) $(PROJ_libocamldir)
+ $(Echo) "Installing $(BuildMode) $(DestCMXA)"
+ $(Verb) $(DataInstall) $(OutputCMXA) $(DestCMXA)
+ $(Echo) "Installing $(BuildMode) $(DestCMXA:.cmxa=.a)"
+ $(Verb) $(DataInstall) $(OutputCMXA:.cmxa=.a) $(DestCMXA:.cmxa=.a)
+ $(Verb) for i in $(OutputsCMX:$(OcamlDir)/%=%); do \
+ $(EchoCmd) "Installing $(BuildMode) $(PROJ_libocamldir)/$$i"; \
+ $(DataInstall) $(OcamlDir)/$$i "$(PROJ_libocamldir)/$$i"; \
+ done
+
+uninstall-cmxa::
+ $(Echo) "Uninstalling $(DestCMXA)"
+ $(Verb) $(RM) -f $(DestCMXA)
+ $(Echo) "Uninstalling $(DestCMXA:.cmxa=.a)"
+ $(Verb) $(RM) -f $(DestCMXA:.cmxa=.a)
+ $(Verb) for i in $(OutputsCMX:$(OcamlDir)/%=%); do \
+ $(EchoCmd) "Uninstalling $(PROJ_libocamldir)/$$i"; \
+ $(RM) -f $(PROJ_libocamldir)/$$i; \
+ done
+endif
+endif
+
+##===- Build executables --------------------------------------------------===##
+
+ifdef TOOLNAME
+all-local:: $(OutputEXE)
+clean-local:: clean-exe
+
+$(OutputEXE): $(ToolEXE) $(OcamlDir)/.dir
+ $(Verb) $(CP) -f $< $@
+
+ifndef OCAMLOPT
+$(ToolEXE): $(ObjectsCMO) $(OcamlDir)/.dir
+ $(Echo) "Archiving $(notdir $@) for $(BuildMode) build"
+ $(Verb) $(Archive.EXE) $@ $(ObjectsCMO)
+else
+$(ToolEXE): $(ObjectsCMX) $(OcamlDir)/.dir
+ $(Echo) "Archiving $(notdir $@) for $(BuildMode) build"
+ $(Verb) $(Archive.EXE) $@ $(ObjectsCMX)
+endif
+endif
+
+##===- Generate documentation ---------------------------------------------===##
+
+$(ObjDir)/$(LIBRARYNAME).odoc: $(ObjectsCMI)
+ $(Echo) "Documenting $(notdir $@)"
+ $(Verb) $(OCAMLDOC) -I $(ObjDir) -I $(OcamlDir) -dump $@ $(OcamlHeaders)
+
+ocamldoc: $(ObjDir)/$(LIBRARYNAME).odoc
+
+##===- Debugging gunk -----------------------------------------------------===##
+printvars:: printcamlvars
+
+printcamlvars::
+ $(Echo) "LLVM_CONFIG : " '$(LLVM_CONFIG)'
+ $(Echo) "OCAMLCFLAGS : " '$(OCAMLCFLAGS)'
+ $(Echo) "OCAMLAFLAGS : " '$(OCAMLAFLAGS)'
+ $(Echo) "OCAMLC : " '$(OCAMLC)'
+ $(Echo) "OCAMLOPT : " '$(OCAMLOPT)'
+ $(Echo) "OCAMLDEP : " '$(OCAMLDEP)'
+ $(Echo) "Compile.CMI : " '$(Compile.CMI)'
+ $(Echo) "Compile.CMO : " '$(Compile.CMO)'
+ $(Echo) "Archive.CMA : " '$(Archive.CMA)'
+ $(Echo) "Compile.CMX : " '$(Compile.CMX)'
+ $(Echo) "Archive.CMXA : " '$(Archive.CMXA)'
+ $(Echo) "CAML_LIBDIR : " '$(CAML_LIBDIR)'
+ $(Echo) "LibraryCMA : " '$(LibraryCMA)'
+ $(Echo) "LibraryCMXA : " '$(LibraryCMXA)'
+ $(Echo) "OcamlSources1: " '$(OcamlSources1)'
+ $(Echo) "OcamlSources2: " '$(OcamlSources2)'
+ $(Echo) "OcamlSources : " '$(OcamlSources)'
+ $(Echo) "OcamlHeaders1: " '$(OcamlHeaders1)'
+ $(Echo) "OcamlHeaders2: " '$(OcamlHeaders2)'
+ $(Echo) "OcamlHeaders : " '$(OcamlHeaders)'
+ $(Echo) "ObjectsCMI : " '$(ObjectsCMI)'
+ $(Echo) "ObjectsCMO : " '$(ObjectsCMO)'
+ $(Echo) "ObjectsCMX : " '$(ObjectsCMX)'
+ $(Echo) "OCAML_LIBDIR : " '$(OCAML_LIBDIR)'
+ $(Echo) "DestA : " '$(DestA)'
+ $(Echo) "DestCMA : " '$(DestCMA)'
+ $(Echo) "DestCMXA : " '$(DestCMXA)'
+ $(Echo) "UsedLibs : " '$(UsedLibs)'
+ $(Echo) "UsedLibNames : " '$(UsedLibNames)'
+
+.PHONY: printcamlvars build-cmis \
+ clean-a clean-cmis clean-cma clean-cmxa \
+ install-a install-cmis install-cma install-cmxa \
+ install-exe \
+ uninstall-a uninstall-cmis uninstall-cma uninstall-cmxa \
+ uninstall-exe
diff --git a/bindings/ocaml/analysis/Makefile b/bindings/ocaml/analysis/Makefile
new file mode 100644
index 00000000000..cbfcb246704
--- /dev/null
+++ b/bindings/ocaml/analysis/Makefile
@@ -0,0 +1,19 @@
+##===- bindings/ocaml/analysis/Makefile --------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml Llvm_analysis interface.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+LIBRARYNAME := llvm_analysis
+UsedComponents := analysis
+UsedOcamlInterfaces := llvm
+
+include ../Makefile.ocaml
diff --git a/bindings/ocaml/analysis/analysis_ocaml.c b/bindings/ocaml/analysis/analysis_ocaml.c
new file mode 100644
index 00000000000..97167055f70
--- /dev/null
+++ b/bindings/ocaml/analysis/analysis_ocaml.c
@@ -0,0 +1,72 @@
+/*===-- analysis_ocaml.c - LLVM Ocaml Glue ----------------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file glues LLVM's ocaml interface to its C interface. These functions *|
+|* are by and large transparent wrappers to the corresponding C functions. *|
+|* *|
+|* Note that these functions intentionally take liberties with the CAMLparamX *|
+|* macros, since most of the parameters are not GC heap objects. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#include "llvm-c/Analysis.h"
+#include "caml/alloc.h"
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+
+
+/* Llvm.llmodule -> string option */
+CAMLprim value llvm_verify_module(LLVMModuleRef M) {
+ CAMLparam0();
+ CAMLlocal2(String, Option);
+
+ char *Message;
+ int Result = LLVMVerifyModule(M, LLVMReturnStatusAction, &Message);
+
+ if (0 == Result) {
+ Option = Val_int(0);
+ } else {
+ Option = alloc(1, 0);
+ String = copy_string(Message);
+ Store_field(Option, 0, String);
+ }
+
+ LLVMDisposeMessage(Message);
+
+ CAMLreturn(Option);
+}
+
+/* Llvm.llvalue -> bool */
+CAMLprim value llvm_verify_function(LLVMValueRef Fn) {
+ return Val_bool(LLVMVerifyFunction(Fn, LLVMReturnStatusAction) == 0);
+}
+
+/* Llvm.llmodule -> unit */
+CAMLprim value llvm_assert_valid_module(LLVMModuleRef M) {
+ LLVMVerifyModule(M, LLVMAbortProcessAction, 0);
+ return Val_unit;
+}
+
+/* Llvm.llvalue -> unit */
+CAMLprim value llvm_assert_valid_function(LLVMValueRef Fn) {
+ LLVMVerifyFunction(Fn, LLVMAbortProcessAction);
+ return Val_unit;
+}
+
+/* Llvm.llvalue -> unit */
+CAMLprim value llvm_view_function_cfg(LLVMValueRef Fn) {
+ LLVMViewFunctionCFG(Fn);
+ return Val_unit;
+}
+
+/* Llvm.llvalue -> unit */
+CAMLprim value llvm_view_function_cfg_only(LLVMValueRef Fn) {
+ LLVMViewFunctionCFGOnly(Fn);
+ return Val_unit;
+}
diff --git a/bindings/ocaml/analysis/llvm_analysis.ml b/bindings/ocaml/analysis/llvm_analysis.ml
new file mode 100644
index 00000000000..fc4d2037074
--- /dev/null
+++ b/bindings/ocaml/analysis/llvm_analysis.ml
@@ -0,0 +1,22 @@
+(*===-- llvm_analysis.ml - LLVM Ocaml Interface -----------------*- C++ -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+
+external verify_module : Llvm.llmodule -> string option = "llvm_verify_module"
+
+external verify_function : Llvm.llvalue -> bool = "llvm_verify_function"
+
+external assert_valid_module : Llvm.llmodule -> unit
+ = "llvm_assert_valid_module"
+
+external assert_valid_function : Llvm.llvalue -> unit
+ = "llvm_assert_valid_function"
+external view_function_cfg : Llvm.llvalue -> unit = "llvm_view_function_cfg"
+external view_function_cfg_only : Llvm.llvalue -> unit
+ = "llvm_view_function_cfg_only"
diff --git a/bindings/ocaml/analysis/llvm_analysis.mli b/bindings/ocaml/analysis/llvm_analysis.mli
new file mode 100644
index 00000000000..793f482e3c6
--- /dev/null
+++ b/bindings/ocaml/analysis/llvm_analysis.mli
@@ -0,0 +1,46 @@
+(*===-- llvm_analysis.mli - LLVM Ocaml Interface ----------------*- C++ -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** Intermediate representation analysis.
+
+ This interface provides an ocaml API for LLVM IR analyses, the classes in
+ the Analysis library. *)
+
+(** [verify_module m] returns [None] if the module [m] is valid, and
+ [Some reason] if it is invalid. [reason] is a string containing a
+ human-readable validation report. See [llvm::verifyModule]. *)
+external verify_module : Llvm.llmodule -> string option = "llvm_verify_module"
+
+(** [verify_function f] returns [None] if the function [f] is valid, and
+ [Some reason] if it is invalid. [reason] is a string containing a
+ human-readable validation report. See [llvm::verifyFunction]. *)
+external verify_function : Llvm.llvalue -> bool = "llvm_verify_function"
+
+(** [verify_module m] returns if the module [m] is valid, but prints a
+ validation report to [stderr] and aborts the program if it is invalid. See
+ [llvm::verifyModule]. *)
+external assert_valid_module : Llvm.llmodule -> unit
+ = "llvm_assert_valid_module"
+
+(** [verify_function f] returns if the function [f] is valid, but prints a
+ validation report to [stderr] and aborts the program if it is invalid. See
+ [llvm::verifyFunction]. *)
+external assert_valid_function : Llvm.llvalue -> unit
+ = "llvm_assert_valid_function"
+
+(** [view_function_cfg f] opens up a ghostscript window displaying the CFG of
+ the current function with the code for each basic block inside.
+ See [llvm::Function::viewCFG]. *)
+external view_function_cfg : Llvm.llvalue -> unit = "llvm_view_function_cfg"
+
+(** [view_function_cfg_only f] works just like [view_function_cfg], but does not
+ include the contents of basic blocks into the nodes.
+ See [llvm::Function::viewCFGOnly]. *)
+external view_function_cfg_only : Llvm.llvalue -> unit
+ = "llvm_view_function_cfg_only"
diff --git a/bindings/ocaml/bitreader/Makefile b/bindings/ocaml/bitreader/Makefile
new file mode 100644
index 00000000000..a1c7de895cf
--- /dev/null
+++ b/bindings/ocaml/bitreader/Makefile
@@ -0,0 +1,19 @@
+##===- bindings/ocaml/bitreader/Makefile -------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml Llvm_bitreader interface.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+LIBRARYNAME := llvm_bitreader
+UsedComponents := bitreader
+UsedOcamlInterfaces := llvm
+
+include ../Makefile.ocaml
diff --git a/bindings/ocaml/bitreader/bitreader_ocaml.c b/bindings/ocaml/bitreader/bitreader_ocaml.c
new file mode 100644
index 00000000000..ef72ce213d8
--- /dev/null
+++ b/bindings/ocaml/bitreader/bitreader_ocaml.c
@@ -0,0 +1,73 @@
+/*===-- bitwriter_ocaml.c - LLVM Ocaml Glue ---------------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file glues LLVM's ocaml interface to its C interface. These functions *|
+|* are by and large transparent wrappers to the corresponding C functions. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#include "llvm-c/BitReader.h"
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+
+
+/* Can't use the recommended caml_named_value mechanism for backwards
+ compatibility reasons. This is largely equivalent. */
+static value llvm_bitreader_error_exn;
+
+CAMLprim value llvm_register_bitreader_exns(value Error) {
+ llvm_bitreader_error_exn = Field(Error, 0);
+ register_global_root(&llvm_bitreader_error_exn);
+ return Val_unit;
+}
+
+static void llvm_raise(value Prototype, char *Message) {
+ CAMLparam1(Prototype);
+ CAMLlocal1(CamlMessage);
+
+ CamlMessage = copy_string(Message);
+ LLVMDisposeMessage(Message);
+
+ raise_with_arg(Prototype, CamlMessage);
+ abort(); /* NOTREACHED */
+#ifdef CAMLnoreturn
+ CAMLnoreturn; /* Silences warnings, but is missing in some versions. */
+#endif
+}
+
+
+/*===-- Modules -----------------------------------------------------------===*/
+
+/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */
+CAMLprim value llvm_get_module(LLVMContextRef C, LLVMMemoryBufferRef MemBuf) {
+ CAMLparam0();
+ CAMLlocal2(Variant, MessageVal);
+ char *Message;
+
+ LLVMModuleRef M;
+ if (LLVMGetBitcodeModuleInContext(C, MemBuf, &M, &Message))
+ llvm_raise(llvm_bitreader_error_exn, Message);
+
+ CAMLreturn((value) M);
+}
+
+/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */
+CAMLprim value llvm_parse_bitcode(LLVMContextRef C,
+ LLVMMemoryBufferRef MemBuf) {
+ CAMLparam0();
+ CAMLlocal2(Variant, MessageVal);
+ LLVMModuleRef M;
+ char *Message;
+
+ if (LLVMParseBitcodeInContext(C, MemBuf, &M, &Message))
+ llvm_raise(llvm_bitreader_error_exn, Message);
+
+ CAMLreturn((value) M);
+}
diff --git a/bindings/ocaml/bitreader/llvm_bitreader.ml b/bindings/ocaml/bitreader/llvm_bitreader.ml
new file mode 100644
index 00000000000..8b9d01d8fb0
--- /dev/null
+++ b/bindings/ocaml/bitreader/llvm_bitreader.ml
@@ -0,0 +1,20 @@
+(*===-- llvm_bitreader.ml - LLVM Ocaml Interface ----------------*- C++ -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+
+exception Error of string
+
+external register_exns : exn -> unit = "llvm_register_bitreader_exns"
+let _ = register_exns (Error "")
+
+external get_module : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule
+ = "llvm_get_module"
+
+external parse_bitcode : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule
+ = "llvm_parse_bitcode"
diff --git a/bindings/ocaml/bitreader/llvm_bitreader.mli b/bindings/ocaml/bitreader/llvm_bitreader.mli
new file mode 100644
index 00000000000..573de5e9830
--- /dev/null
+++ b/bindings/ocaml/bitreader/llvm_bitreader.mli
@@ -0,0 +1,28 @@
+(*===-- llvm_bitreader.mli - LLVM Ocaml Interface ---------------*- C++ -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** Bitcode reader.
+
+ This interface provides an ocaml API for the LLVM bitcode reader, the
+ classes in the Bitreader library. *)
+
+exception Error of string
+
+(** [get_module context mb] reads the bitcode for a new module [m] from the
+ memory buffer [mb] in the context [context]. Returns [m] if successful, or
+ raises [Error msg] otherwise, where [msg] is a description of the error
+ encountered. See the function [llvm::getBitcodeModule]. *)
+val get_module : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule
+
+
+(** [parse_bitcode context mb] parses the bitcode for a new module [m] from the
+ memory buffer [mb] in the context [context]. Returns [m] if successful, or
+ raises [Error msg] otherwise, where [msg] is a description of the error
+ encountered. See the function [llvm::ParseBitcodeFile]. *)
+val parse_bitcode : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule
diff --git a/bindings/ocaml/bitwriter/Makefile b/bindings/ocaml/bitwriter/Makefile
new file mode 100644
index 00000000000..cec0a59c31b
--- /dev/null
+++ b/bindings/ocaml/bitwriter/Makefile
@@ -0,0 +1,19 @@
+##===- bindings/ocaml/bitwriter/Makefile -------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml Llvm_bitwriter interface.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+LIBRARYNAME := llvm_bitwriter
+UsedComponents := bitwriter
+UsedOcamlInterfaces := llvm
+
+include ../Makefile.ocaml
diff --git a/bindings/ocaml/bitwriter/bitwriter_ocaml.c b/bindings/ocaml/bitwriter/bitwriter_ocaml.c
new file mode 100644
index 00000000000..53c93cbdfe9
--- /dev/null
+++ b/bindings/ocaml/bitwriter/bitwriter_ocaml.c
@@ -0,0 +1,45 @@
+/*===-- bitwriter_ocaml.c - LLVM Ocaml Glue ---------------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file glues LLVM's ocaml interface to its C interface. These functions *|
+|* are by and large transparent wrappers to the corresponding C functions. *|
+|* *|
+|* Note that these functions intentionally take liberties with the CAMLparamX *|
+|* macros, since most of the parameters are not GC heap objects. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#include "llvm-c/BitWriter.h"
+#include "llvm-c/Core.h"
+#include "caml/alloc.h"
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+
+/*===-- Modules -----------------------------------------------------------===*/
+
+/* Llvm.llmodule -> string -> bool */
+CAMLprim value llvm_write_bitcode_file(value M, value Path) {
+ int res = LLVMWriteBitcodeToFile((LLVMModuleRef) M, String_val(Path));
+ return Val_bool(res == 0);
+}
+
+/* ?unbuffered:bool -> Llvm.llmodule -> Unix.file_descr -> bool */
+CAMLprim value llvm_write_bitcode_to_fd(value U, value M, value FD) {
+ int Unbuffered;
+ int res;
+
+ if (U == Val_int(0)) {
+ Unbuffered = 0;
+ } else {
+ Unbuffered = Bool_val(Field(U,0));
+ }
+
+ res = LLVMWriteBitcodeToFD((LLVMModuleRef) M, Int_val(FD), 0, Unbuffered);
+ return Val_bool(res == 0);
+}
diff --git a/bindings/ocaml/bitwriter/llvm_bitwriter.ml b/bindings/ocaml/bitwriter/llvm_bitwriter.ml
new file mode 100644
index 00000000000..3e69a3cc8fb
--- /dev/null
+++ b/bindings/ocaml/bitwriter/llvm_bitwriter.ml
@@ -0,0 +1,25 @@
+(*===-- llvm_bitwriter.ml - LLVM Ocaml Interface ----------------*- C++ -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===
+ *
+ * This interface provides an ocaml API for the LLVM intermediate
+ * representation, the classes in the VMCore library.
+ *
+ *===----------------------------------------------------------------------===*)
+
+
+(* Writes the bitcode for module the given path. Returns true if successful. *)
+external write_bitcode_file : Llvm.llmodule -> string -> bool
+ = "llvm_write_bitcode_file"
+
+external write_bitcode_to_fd : ?unbuffered:bool -> Llvm.llmodule
+ -> Unix.file_descr -> bool
+ = "llvm_write_bitcode_to_fd"
+
+let output_bitcode ?unbuffered channel m =
+ write_bitcode_to_fd ?unbuffered m (Unix.descr_of_out_channel channel)
diff --git a/bindings/ocaml/bitwriter/llvm_bitwriter.mli b/bindings/ocaml/bitwriter/llvm_bitwriter.mli
new file mode 100644
index 00000000000..ea9a87600a7
--- /dev/null
+++ b/bindings/ocaml/bitwriter/llvm_bitwriter.mli
@@ -0,0 +1,30 @@
+(*===-- llvm_bitwriter.mli - LLVM Ocaml Interface ---------------*- C++ -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** Bitcode writer.
+
+ This interface provides an ocaml API for the LLVM bitcode writer, the
+ classes in the Bitwriter library. *)
+
+(** [write_bitcode_file m path] writes the bitcode for module [m] to the file at
+ [path]. Returns [true] if successful, [false] otherwise. *)
+external write_bitcode_file : Llvm.llmodule -> string -> bool
+ = "llvm_write_bitcode_file"
+
+(** [write_bitcode_to_fd ~unbuffered fd m] writes the bitcode for module
+ [m] to the channel [c]. If [unbuffered] is [true], after every write the fd
+ will be flushed. Returns [true] if successful, [false] otherwise. *)
+external write_bitcode_to_fd : ?unbuffered:bool -> Llvm.llmodule
+ -> Unix.file_descr -> bool
+ = "llvm_write_bitcode_to_fd"
+
+(** [output_bitcode ~unbuffered c m] writes the bitcode for module [m]
+ to the channel [c]. If [unbuffered] is [true], after every write the fd
+ will be flushed. Returns [true] if successful, [false] otherwise. *)
+val output_bitcode : ?unbuffered:bool -> out_channel -> Llvm.llmodule -> bool
diff --git a/bindings/ocaml/executionengine/Makefile b/bindings/ocaml/executionengine/Makefile
new file mode 100644
index 00000000000..5fa3f22048f
--- /dev/null
+++ b/bindings/ocaml/executionengine/Makefile
@@ -0,0 +1,19 @@
+##===- bindings/ocaml/executionengine/Makefile --------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml Llvm_executionengine interface.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+LIBRARYNAME := llvm_executionengine
+UsedComponents := executionengine jit interpreter native
+UsedOcamlInterfaces := llvm llvm_target
+
+include ../Makefile.ocaml
diff --git a/bindings/ocaml/executionengine/executionengine_ocaml.c b/bindings/ocaml/executionengine/executionengine_ocaml.c
new file mode 100644
index 00000000000..02e03060572
--- /dev/null
+++ b/bindings/ocaml/executionengine/executionengine_ocaml.c
@@ -0,0 +1,326 @@
+/*===-- executionengine_ocaml.c - LLVM Ocaml Glue ---------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file glues LLVM's ocaml interface to its C interface. These functions *|
+|* are by and large transparent wrappers to the corresponding C functions. *|
+|* *|
+|* Note that these functions intentionally take liberties with the CAMLparamX *|
+|* macros, since most of the parameters are not GC heap objects. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#include "llvm-c/ExecutionEngine.h"
+#include "llvm-c/Target.h"
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include <string.h>
+#include <assert.h>
+
+/* Force the LLVM interpreter and JIT to be linked in. */
+void llvm_initialize(void) {
+ LLVMLinkInInterpreter();
+ LLVMLinkInJIT();
+}
+
+/* unit -> bool */
+CAMLprim value llvm_initialize_native_target(value Unit) {
+ return Val_bool(LLVMInitializeNativeTarget());
+}
+
+/* Can't use the recommended caml_named_value mechanism for backwards
+ compatibility reasons. This is largely equivalent. */
+static value llvm_ee_error_exn;
+
+CAMLprim value llvm_register_ee_exns(value Error) {
+ llvm_ee_error_exn = Field(Error, 0);
+ register_global_root(&llvm_ee_error_exn);
+ return Val_unit;
+}
+
+static void llvm_raise(value Prototype, char *Message) {
+ CAMLparam1(Prototype);
+ CAMLlocal1(CamlMessage);
+
+ CamlMessage = copy_string(Message);
+ LLVMDisposeMessage(Message);
+
+ raise_with_arg(Prototype, CamlMessage);
+ abort(); /* NOTREACHED */
+#ifdef CAMLnoreturn
+ CAMLnoreturn; /* Silences warnings, but is missing in some versions. */
+#endif
+}
+
+
+/*--... Operations on generic values .......................................--*/
+
+#define Genericvalue_val(v) (*(LLVMGenericValueRef *)(Data_custom_val(v)))
+
+static void llvm_finalize_generic_value(value GenVal) {
+ LLVMDisposeGenericValue(Genericvalue_val(GenVal));
+}
+
+static struct custom_operations generic_value_ops = {
+ (char *) "LLVMGenericValue",
+ llvm_finalize_generic_value,
+ custom_compare_default,
+ custom_hash_default,
+ custom_serialize_default,
+ custom_deserialize_default
+#ifdef custom_compare_ext_default
+ , custom_compare_ext_default
+#endif
+};
+
+static value alloc_generic_value(LLVMGenericValueRef Ref) {
+ value Val = alloc_custom(&generic_value_ops, sizeof(LLVMGenericValueRef), 0, 1);
+ Genericvalue_val(Val) = Ref;
+ return Val;
+}
+
+/* Llvm.lltype -> float -> t */
+CAMLprim value llvm_genericvalue_of_float(LLVMTypeRef Ty, value N) {
+ CAMLparam1(N);
+ CAMLreturn(alloc_generic_value(
+ LLVMCreateGenericValueOfFloat(Ty, Double_val(N))));
+}
+
+/* 'a -> t */
+CAMLprim value llvm_genericvalue_of_pointer(value V) {
+ CAMLparam1(V);
+ CAMLreturn(alloc_generic_value(LLVMCreateGenericValueOfPointer(Op_val(V))));
+}
+
+/* Llvm.lltype -> int -> t */
+CAMLprim value llvm_genericvalue_of_int(LLVMTypeRef Ty, value Int) {
+ return alloc_generic_value(LLVMCreateGenericValueOfInt(Ty, Int_val(Int), 1));
+}
+
+/* Llvm.lltype -> int32 -> t */
+CAMLprim value llvm_genericvalue_of_int32(LLVMTypeRef Ty, value Int32) {
+ CAMLparam1(Int32);
+ CAMLreturn(alloc_generic_value(
+ LLVMCreateGenericValueOfInt(Ty, Int32_val(Int32), 1)));
+}
+
+/* Llvm.lltype -> nativeint -> t */
+CAMLprim value llvm_genericvalue_of_nativeint(LLVMTypeRef Ty, value NatInt) {
+ CAMLparam1(NatInt);
+ CAMLreturn(alloc_generic_value(
+ LLVMCreateGenericValueOfInt(Ty, Nativeint_val(NatInt), 1)));
+}
+
+/* Llvm.lltype -> int64 -> t */
+CAMLprim value llvm_genericvalue_of_int64(LLVMTypeRef Ty, value Int64) {
+ CAMLparam1(Int64);
+ CAMLreturn(alloc_generic_value(
+ LLVMCreateGenericValueOfInt(Ty, Int64_val(Int64), 1)));
+}
+
+/* Llvm.lltype -> t -> float */
+CAMLprim value llvm_genericvalue_as_float(LLVMTypeRef Ty, value GenVal) {
+ CAMLparam1(GenVal);
+ CAMLreturn(copy_double(
+ LLVMGenericValueToFloat(Ty, Genericvalue_val(GenVal))));
+}
+
+/* t -> 'a */
+CAMLprim value llvm_genericvalue_as_pointer(value GenVal) {
+ return Val_op(LLVMGenericValueToPointer(Genericvalue_val(GenVal)));
+}
+
+/* t -> int */
+CAMLprim value llvm_genericvalue_as_int(value GenVal) {
+ assert(LLVMGenericValueIntWidth(Genericvalue_val(GenVal)) <= 8 * sizeof(value)
+ && "Generic value too wide to treat as an int!");
+ return Val_int(LLVMGenericValueToInt(Genericvalue_val(GenVal), 1));
+}
+
+/* t -> int32 */
+CAMLprim value llvm_genericvalue_as_int32(value GenVal) {
+ CAMLparam1(GenVal);
+ assert(LLVMGenericValueIntWidth(Genericvalue_val(GenVal)) <= 32
+ && "Generic value too wide to treat as an int32!");
+ CAMLreturn(copy_int32(LLVMGenericValueToInt(Genericvalue_val(GenVal), 1)));
+}
+
+/* t -> int64 */
+CAMLprim value llvm_genericvalue_as_int64(value GenVal) {
+ CAMLparam1(GenVal);
+ assert(LLVMGenericValueIntWidth(Genericvalue_val(GenVal)) <= 64
+ && "Generic value too wide to treat as an int64!");
+ CAMLreturn(copy_int64(LLVMGenericValueToInt(Genericvalue_val(GenVal), 1)));
+}
+
+/* t -> nativeint */
+CAMLprim value llvm_genericvalue_as_nativeint(value GenVal) {
+ CAMLparam1(GenVal);
+ assert(LLVMGenericValueIntWidth(Genericvalue_val(GenVal)) <= 8 * sizeof(value)
+ && "Generic value too wide to treat as a nativeint!");
+ CAMLreturn(copy_nativeint(LLVMGenericValueToInt(Genericvalue_val(GenVal),1)));
+}
+
+
+/*--... Operations on execution engines ....................................--*/
+
+/* llmodule -> ExecutionEngine.t */
+CAMLprim LLVMExecutionEngineRef llvm_ee_create(LLVMModuleRef M) {
+ LLVMExecutionEngineRef Interp;
+ char *Error;
+ if (LLVMCreateExecutionEngineForModule(&Interp, M, &Error))
+ llvm_raise(llvm_ee_error_exn, Error);
+ return Interp;
+}
+
+/* llmodule -> ExecutionEngine.t */
+CAMLprim LLVMExecutionEngineRef
+llvm_ee_create_interpreter(LLVMModuleRef M) {
+ LLVMExecutionEngineRef Interp;
+ char *Error;
+ if (LLVMCreateInterpreterForModule(&Interp, M, &Error))
+ llvm_raise(llvm_ee_error_exn, Error);
+ return Interp;
+}
+
+/* llmodule -> int -> ExecutionEngine.t */
+CAMLprim LLVMExecutionEngineRef
+llvm_ee_create_jit(LLVMModuleRef M, value OptLevel) {
+ LLVMExecutionEngineRef JIT;
+ char *Error;
+ if (LLVMCreateJITCompilerForModule(&JIT, M, Int_val(OptLevel), &Error))
+ llvm_raise(llvm_ee_error_exn, Error);
+ return JIT;
+}
+
+/* ExecutionEngine.t -> unit */
+CAMLprim value llvm_ee_dispose(LLVMExecutionEngineRef EE) {
+ LLVMDisposeExecutionEngine(EE);
+ return Val_unit;
+}
+
+/* llmodule -> ExecutionEngine.t -> unit */
+CAMLprim value llvm_ee_add_module(LLVMModuleRef M, LLVMExecutionEngineRef EE) {
+ LLVMAddModule(EE, M);
+ return Val_unit;
+}
+
+/* llmodule -> ExecutionEngine.t -> llmodule */
+CAMLprim LLVMModuleRef llvm_ee_remove_module(LLVMModuleRef M,
+ LLVMExecutionEngineRef EE) {
+ LLVMModuleRef RemovedModule;
+ char *Error;
+ if (LLVMRemoveModule(EE, M, &RemovedModule, &Error))
+ llvm_raise(llvm_ee_error_exn, Error);
+ return RemovedModule;
+}
+
+/* string -> ExecutionEngine.t -> llvalue option */
+CAMLprim value llvm_ee_find_function(value Name, LLVMExecutionEngineRef EE) {
+ CAMLparam1(Name);
+ CAMLlocal1(Option);
+ LLVMValueRef Found;
+ if (LLVMFindFunction(EE, String_val(Name), &Found))
+ CAMLreturn(Val_unit);
+ Option = alloc(1, 0);
+ Field(Option, 0) = Val_op(Found);
+ CAMLreturn(Option);
+}
+
+/* llvalue -> GenericValue.t array -> ExecutionEngine.t -> GenericValue.t */
+CAMLprim value llvm_ee_run_function(LLVMValueRef F, value Args,
+ LLVMExecutionEngineRef EE) {
+ unsigned NumArgs;
+ LLVMGenericValueRef Result, *GVArgs;
+ unsigned I;
+
+ NumArgs = Wosize_val(Args);
+ GVArgs = (LLVMGenericValueRef*) malloc(NumArgs * sizeof(LLVMGenericValueRef));
+ for (I = 0; I != NumArgs; ++I)
+ GVArgs[I] = Genericvalue_val(Field(Args, I));
+
+ Result = LLVMRunFunction(EE, F, NumArgs, GVArgs);
+
+ free(GVArgs);
+ return alloc_generic_value(Result);
+}
+
+/* ExecutionEngine.t -> unit */
+CAMLprim value llvm_ee_run_static_ctors(LLVMExecutionEngineRef EE) {
+ LLVMRunStaticConstructors(EE);
+ return Val_unit;
+}
+
+/* ExecutionEngine.t -> unit */
+CAMLprim value llvm_ee_run_static_dtors(LLVMExecutionEngineRef EE) {
+ LLVMRunStaticDestructors(EE);
+ return Val_unit;
+}
+
+/* llvalue -> string array -> (string * string) array -> ExecutionEngine.t ->
+ int */
+CAMLprim value llvm_ee_run_function_as_main(LLVMValueRef F,
+ value Args, value Env,
+ LLVMExecutionEngineRef EE) {
+ CAMLparam2(Args, Env);
+ int I, NumArgs, NumEnv, EnvSize, Result;
+ const char **CArgs, **CEnv;
+ char *CEnvBuf, *Pos;
+
+ NumArgs = Wosize_val(Args);
+ NumEnv = Wosize_val(Env);
+
+ /* Build the environment. */
+ CArgs = (const char **) malloc(NumArgs * sizeof(char*));
+ for (I = 0; I != NumArgs; ++I)
+ CArgs[I] = String_val(Field(Args, I));
+
+ /* Compute the size of the environment string buffer. */
+ for (I = 0, EnvSize = 0; I != NumEnv; ++I) {
+ EnvSize += strlen(String_val(Field(Field(Env, I), 0))) + 1;
+ EnvSize += strlen(String_val(Field(Field(Env, I), 1))) + 1;
+ }
+
+ /* Build the environment. */
+ CEnv = (const char **) malloc((NumEnv + 1) * sizeof(char*));
+ CEnvBuf = (char*) malloc(EnvSize);
+ Pos = CEnvBuf;
+ for (I = 0; I != NumEnv; ++I) {
+ char *Name = String_val(Field(Field(Env, I), 0)),
+ *Value = String_val(Field(Field(Env, I), 1));
+ int NameLen = strlen(Name),
+ ValueLen = strlen(Value);
+
+ CEnv[I] = Pos;
+ memcpy(Pos, Name, NameLen);
+ Pos += NameLen;
+ *Pos++ = '=';
+ memcpy(Pos, Value, ValueLen);
+ Pos += ValueLen;
+ *Pos++ = '\0';
+ }
+ CEnv[NumEnv] = NULL;
+
+ Result = LLVMRunFunctionAsMain(EE, F, NumArgs, CArgs, CEnv);
+
+ free(CArgs);
+ free(CEnv);
+ free(CEnvBuf);
+
+ CAMLreturn(Val_int(Result));
+}
+
+/* llvalue -> ExecutionEngine.t -> unit */
+CAMLprim value llvm_ee_free_machine_code(LLVMValueRef F,
+ LLVMExecutionEngineRef EE) {
+ LLVMFreeMachineCodeForFunction(EE, F);
+ return Val_unit;
+}
+
diff --git a/bindings/ocaml/executionengine/llvm_executionengine.ml b/bindings/ocaml/executionengine/llvm_executionengine.ml
new file mode 100644
index 00000000000..a8535b24640
--- /dev/null
+++ b/bindings/ocaml/executionengine/llvm_executionengine.ml
@@ -0,0 +1,112 @@
+(*===-- llvm_executionengine.ml - LLVM Ocaml Interface ----------*- C++ -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+
+exception Error of string
+
+external register_exns: exn -> unit
+ = "llvm_register_ee_exns"
+
+
+module GenericValue = struct
+ type t
+
+ external of_float: Llvm.lltype -> float -> t
+ = "llvm_genericvalue_of_float"
+ external of_pointer: 'a -> t
+ = "llvm_genericvalue_of_pointer"
+ external of_int32: Llvm.lltype -> int32 -> t
+ = "llvm_genericvalue_of_int32"
+ external of_int: Llvm.lltype -> int -> t
+ = "llvm_genericvalue_of_int"
+ external of_nativeint: Llvm.lltype -> nativeint -> t
+ = "llvm_genericvalue_of_nativeint"
+ external of_int64: Llvm.lltype -> int64 -> t
+ = "llvm_genericvalue_of_int64"
+
+ external as_float: Llvm.lltype -> t -> float
+ = "llvm_genericvalue_as_float"
+ external as_pointer: t -> 'a
+ = "llvm_genericvalue_as_pointer"
+ external as_int32: t -> int32
+ = "llvm_genericvalue_as_int32"
+ external as_int: t -> int
+ = "llvm_genericvalue_as_int"
+ external as_nativeint: t -> nativeint
+ = "llvm_genericvalue_as_nativeint"
+ external as_int64: t -> int64
+ = "llvm_genericvalue_as_int64"
+end
+
+
+module ExecutionEngine = struct
+ type t
+
+ (* FIXME: Ocaml is not running this setup code unless we use 'val' in the
+ interface, which causes the emission of a stub for each function;
+ using 'external' in the module allows direct calls into
+ ocaml_executionengine.c. This is hardly fatal, but it is unnecessary
+ overhead on top of the two stubs that are already invoked for each
+ call into LLVM. *)
+ let _ = register_exns (Error "")
+
+ external create: Llvm.llmodule -> t
+ = "llvm_ee_create"
+ external create_interpreter: Llvm.llmodule -> t
+ = "llvm_ee_create_interpreter"
+ external create_jit: Llvm.llmodule -> int -> t
+ = "llvm_ee_create_jit"
+ external dispose: t -> unit
+ = "llvm_ee_dispose"
+ external add_module: Llvm.llmodule -> t -> unit
+ = "llvm_ee_add_module"
+ external remove_module: Llvm.llmodule -> t -> Llvm.llmodule
+ = "llvm_ee_remove_module"
+ external find_function: string -> t -> Llvm.llvalue option
+ = "llvm_ee_find_function"
+ external run_function: Llvm.llvalue -> GenericValue.t array -> t ->
+ GenericValue.t
+ = "llvm_ee_run_function"
+ external run_static_ctors: t -> unit
+ = "llvm_ee_run_static_ctors"
+ external run_static_dtors: t -> unit
+ = "llvm_ee_run_static_dtors"
+ external run_function_as_main: Llvm.llvalue -> string array ->
+ (string * string) array -> t -> int
+ = "llvm_ee_run_function_as_main"
+ external free_machine_code: Llvm.llvalue -> t -> unit
+ = "llvm_ee_free_machine_code"
+
+ external target_data: t -> Llvm_target.TargetData.t
+ = "LLVMGetExecutionEngineTargetData"
+
+ (* The following are not bound. Patches are welcome.
+
+ get_target_data: t -> lltargetdata
+ add_global_mapping: llvalue -> llgenericvalue -> t -> unit
+ clear_all_global_mappings: t -> unit
+ update_global_mapping: llvalue -> llgenericvalue -> t -> unit
+ get_pointer_to_global_if_available: llvalue -> t -> llgenericvalue
+ get_pointer_to_global: llvalue -> t -> llgenericvalue
+ get_pointer_to_function: llvalue -> t -> llgenericvalue
+ get_pointer_to_function_or_stub: llvalue -> t -> llgenericvalue
+ get_global_value_at_address: llgenericvalue -> t -> llvalue option
+ store_value_to_memory: llgenericvalue -> llgenericvalue -> lltype -> unit
+ initialize_memory: llvalue -> llgenericvalue -> t -> unit
+ recompile_and_relink_function: llvalue -> t -> llgenericvalue
+ get_or_emit_global_variable: llvalue -> t -> llgenericvalue
+ disable_lazy_compilation: t -> unit
+ lazy_compilation_enabled: t -> bool
+ install_lazy_function_creator: (string -> llgenericvalue) -> t -> unit
+
+ *)
+end
+
+external initialize_native_target : unit -> bool
+ = "llvm_initialize_native_target"
diff --git a/bindings/ocaml/executionengine/llvm_executionengine.mli b/bindings/ocaml/executionengine/llvm_executionengine.mli
new file mode 100644
index 00000000000..166b7bcddca
--- /dev/null
+++ b/bindings/ocaml/executionengine/llvm_executionengine.mli
@@ -0,0 +1,163 @@
+(*===-- llvm_executionengine.mli - LLVM Ocaml Interface ---------*- C++ -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** JIT Interpreter.
+
+ This interface provides an ocaml API for LLVM execution engine (JIT/
+ interpreter), the classes in the ExecutionEngine library. *)
+
+exception Error of string
+
+module GenericValue: sig
+ (** [GenericValue.t] is a boxed union type used to portably pass arguments to
+ and receive values from the execution engine. It supports only a limited
+ selection of types; for more complex argument types, it is necessary to
+ generate a stub function by hand or to pass parameters by reference.
+ See the struct [llvm::GenericValue]. *)
+ type t
+
+ (** [of_float fpty n] boxes the float [n] in a float-valued generic value
+ according to the floating point type [fpty]. See the fields
+ [llvm::GenericValue::DoubleVal] and [llvm::GenericValue::FloatVal]. *)
+ val of_float : Llvm.lltype -> float -> t
+
+ (** [of_pointer v] boxes the pointer value [v] in a generic value. See the
+ field [llvm::GenericValue::PointerVal]. *)
+ val of_pointer : 'a -> t
+
+ (** [of_int32 n w] boxes the int32 [i] in a generic value with the bitwidth
+ [w]. See the field [llvm::GenericValue::IntVal]. *)
+ val of_int32 : Llvm.lltype -> int32 -> t
+
+ (** [of_int n w] boxes the int [i] in a generic value with the bitwidth
+ [w]. See the field [llvm::GenericValue::IntVal]. *)
+ val of_int : Llvm.lltype -> int -> t
+
+ (** [of_natint n w] boxes the native int [i] in a generic value with the
+ bitwidth [w]. See the field [llvm::GenericValue::IntVal]. *)
+ val of_nativeint : Llvm.lltype -> nativeint -> t
+
+
+ (** [of_int64 n w] boxes the int64 [i] in a generic value with the bitwidth
+ [w]. See the field [llvm::GenericValue::IntVal]. *)
+ val of_int64 : Llvm.lltype -> int64 -> t
+
+ (** [as_float fpty gv] unboxes the floating point-valued generic value [gv] of
+ floating point type [fpty]. See the fields [llvm::GenericValue::DoubleVal]
+ and [llvm::GenericValue::FloatVal]. *)
+ val as_float : Llvm.lltype -> t -> float
+
+ (** [as_pointer gv] unboxes the pointer-valued generic value [gv]. See the
+ field [llvm::GenericValue::PointerVal]. *)
+ val as_pointer : t -> 'a
+
+ (** [as_int32 gv] unboxes the integer-valued generic value [gv] as an [int32].
+ Is invalid if [gv] has a bitwidth greater than 32 bits. See the field
+ [llvm::GenericValue::IntVal]. *)
+ val as_int32 : t -> int32
+
+ (** [as_int gv] unboxes the integer-valued generic value [gv] as an [int].
+ Is invalid if [gv] has a bitwidth greater than the host bit width (but the
+ most significant bit may be lost). See the field
+ [llvm::GenericValue::IntVal]. *)
+ val as_int : t -> int
+
+ (** [as_natint gv] unboxes the integer-valued generic value [gv] as a
+ [nativeint]. Is invalid if [gv] has a bitwidth greater than
+ [nativeint]. See the field [llvm::GenericValue::IntVal]. *)
+ val as_nativeint : t -> nativeint
+
+ (** [as_int64 gv] returns the integer-valued generic value [gv] as an [int64].
+ Is invalid if [gv] has a bitwidth greater than [int64]. See the field
+ [llvm::GenericValue::IntVal]. *)
+ val as_int64 : t -> int64
+end
+
+
+module ExecutionEngine: sig
+ (** An execution engine is either a JIT compiler or an interpreter, capable of
+ directly loading an LLVM module and executing its functions without first
+ invoking a static compiler and generating a native executable. *)
+ type t
+
+ (** [create m] creates a new execution engine, taking ownership of the
+ module [m] if successful. Creates a JIT if possible, else falls back to an
+ interpreter. Raises [Error msg] if an error occurrs. The execution engine
+ is not garbage collected and must be destroyed with [dispose ee].
+ See the function [llvm::EngineBuilder::create]. *)
+ val create : Llvm.llmodule -> t
+
+ (** [create_interpreter m] creates a new interpreter, taking ownership of the
+ module [m] if successful. Raises [Error msg] if an error occurrs. The
+ execution engine is not garbage collected and must be destroyed with
+ [dispose ee].
+ See the function [llvm::EngineBuilder::create]. *)
+ val create_interpreter : Llvm.llmodule -> t
+
+ (** [create_jit m optlevel] creates a new JIT (just-in-time compiler), taking
+ ownership of the module [m] if successful with the desired optimization
+ level [optlevel]. Raises [Error msg] if an error occurrs. The execution
+ engine is not garbage collected and must be destroyed with [dispose ee].
+ See the function [llvm::EngineBuilder::create]. *)
+ val create_jit : Llvm.llmodule -> int -> t
+
+ (** [dispose ee] releases the memory used by the execution engine and must be
+ invoked to avoid memory leaks. *)
+ val dispose : t -> unit
+
+ (** [add_module m ee] adds the module [m] to the execution engine [ee]. *)
+ val add_module : Llvm.llmodule -> t -> unit
+
+ (** [remove_module m ee] removes the module [m] from the execution engine
+ [ee], disposing of [m] and the module referenced by [mp]. Raises
+ [Error msg] if an error occurs. *)
+ val remove_module : Llvm.llmodule -> t -> Llvm.llmodule
+
+
+ (** [find_function n ee] finds the function named [n] defined in any of the
+ modules owned by the execution engine [ee]. Returns [None] if the function
+ is not found and [Some f] otherwise. *)
+ val find_function : string -> t -> Llvm.llvalue option
+
+
+ (** [run_function f args ee] synchronously executes the function [f] with the
+ arguments [args], which must be compatible with the parameter types. *)
+ val run_function : Llvm.llvalue -> GenericValue.t array -> t ->
+ GenericValue.t
+
+
+ (** [run_static_ctors ee] executes the static constructors of each module in
+ the execution engine [ee]. *)
+ val run_static_ctors : t -> unit
+
+ (** [run_static_dtors ee] executes the static destructors of each module in
+ the execution engine [ee]. *)
+ val run_static_dtors : t -> unit
+
+ (** [run_function_as_main f args env ee] executes the function [f] as a main
+ function, passing it [argv] and [argc] according to the string array
+ [args], and [envp] as specified by the array [env]. Returns the integer
+ return value of the function. *)
+ val run_function_as_main : Llvm.llvalue -> string array ->
+ (string * string) array -> t -> int
+
+
+ (** [free_machine_code f ee] releases the memory in the execution engine [ee]
+ used to store the machine code for the function [f]. *)
+ val free_machine_code : Llvm.llvalue -> t -> unit
+
+
+ (** [target_data ee] is the target data owned by the execution engine
+ [ee]. *)
+ val target_data : t -> Llvm_target.TargetData.t
+
+end
+
+val initialize_native_target : unit -> bool
+
diff --git a/bindings/ocaml/llvm/META.llvm.in b/bindings/ocaml/llvm/META.llvm.in
new file mode 100644
index 00000000000..fdb32538237
--- /dev/null
+++ b/bindings/ocaml/llvm/META.llvm.in
@@ -0,0 +1,63 @@
+name = "llvm"
+version = "@PACKAGE_VERSION@"
+description = "LLVM OCaml bindings"
+archive(byte) = "llvm.cma"
+archive(native) = "llvm.cmxa"
+directory = "."
+linkopts = "-ccopt -lstdc++"
+
+package "analysis" (
+ requires = "llvm"
+ version = "@PACKAGE_VERSION@"
+ description = "Intermediate representation analysis for LLVM"
+ archive(byte) = "llvm_analysis.cma"
+ archive(native) = "llvm_analysis.cmxa"
+)
+
+package "bitreader" (
+ requires = "llvm"
+ version = "@PACKAGE_VERSION@"
+ description = "Bitcode reader for LLVM"
+ archive(byte) = "llvm_bitreader.cma"
+ archive(native) = "llvm_bitreader.cmxa"
+)
+
+package "bitwriter" (
+ requires = "llvm,unix"
+ version = "@PACKAGE_VERSION@"
+ description = "Bitcode writer for LLVM"
+ archive(byte) = "llvm_bitwriter.cma"
+ archive(native) = "llvm_bitwriter.cmxa"
+)
+
+package "executionengine" (
+ requires = "llvm,llvm.target"
+ version = "@PACKAGE_VERSION@"
+ description = "JIT and Interpreter for LLVM"
+ archive(byte) = "llvm_executionengine.cma"
+ archive(native) = "llvm_executionengine.cmxa"
+)
+
+package "ipo" (
+ requires = "llvm"
+ version = "@PACKAGE_VERSION@"
+ description = "IPO Transforms for LLVM"
+ archive(byte) = "llvm_ipo.cma"
+ archive(native) = "llvm_ipo.cmxa"
+)
+
+package "scalar_opts" (
+ requires = "llvm"
+ version = "@PACKAGE_VERSION@"
+ description = "Scalar Transforms for LLVM"
+ archive(byte) = "llvm_scalar_opts.cma"
+ archive(native) = "llvm_scalar_opts.cmxa"
+)
+
+package "target" (
+ requires = "llvm"
+ version = "@PACKAGE_VERSION@"
+ description = "Target Information for LLVM"
+ archive(byte) = "llvm_target.cma"
+ archive(native) = "llvm_target.cmxa"
+)
diff --git a/bindings/ocaml/llvm/Makefile b/bindings/ocaml/llvm/Makefile
new file mode 100644
index 00000000000..203075a9bdd
--- /dev/null
+++ b/bindings/ocaml/llvm/Makefile
@@ -0,0 +1,42 @@
+##===- bindings/ocaml/llvm/Makefile ------------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml Llvm interface.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+LIBRARYNAME := llvm
+UsedComponents := core
+UsedOcamLibs := llvm
+
+include ../Makefile.ocaml
+
+all-local:: copy-meta
+install-local:: install-meta
+uninstall-local:: uninstall-meta
+
+DestMETA := $(PROJ_libocamldir)/META.llvm
+
+# Easy way of generating META in the objdir
+copy-meta: $(OcamlDir)/META.llvm
+
+$(OcamlDir)/META.llvm: META.llvm
+ $(Verb) $(CP) -f $< $@
+
+install-meta:: $(OcamlDir)/META.llvm
+ $(Echo) "Install $(BuildMode) $(DestMETA)"
+ $(Verb) $(MKDIR) $(PROJ_libocamldir)
+ $(Verb) $(DataInstall) $< "$(DestMETA)"
+
+uninstall-meta::
+ $(Echo) "Uninstalling $(DestMETA)"
+ -$(Verb) $(RM) -f "$(DestMETA)"
+
+.PHONY: copy-meta install-meta uninstall-meta
diff --git a/bindings/ocaml/llvm/llvm.ml b/bindings/ocaml/llvm/llvm.ml
new file mode 100644
index 00000000000..b169b85bc99
--- /dev/null
+++ b/bindings/ocaml/llvm/llvm.ml
@@ -0,0 +1,1240 @@
+(*===-- llvm/llvm.ml - LLVM Ocaml Interface --------------------------------===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+
+type llcontext
+type llmodule
+type lltype
+type llvalue
+type lluse
+type llbasicblock
+type llbuilder
+type llmemorybuffer
+
+module TypeKind = struct
+ type t =
+ | Void
+ | Half
+ | Float
+ | Double
+ | X86fp80
+ | Fp128
+ | Ppc_fp128
+ | Label
+ | Integer
+ | Function
+ | Struct
+ | Array
+ | Pointer
+ | Vector
+ | Metadata
+end
+
+module Linkage = struct
+ type t =
+ | External
+ | Available_externally
+ | Link_once
+ | Link_once_odr
+ | Weak
+ | Weak_odr
+ | Appending
+ | Internal
+ | Private
+ | Dllimport
+ | Dllexport
+ | External_weak
+ | Ghost
+ | Common
+ | Linker_private
+end
+
+module Visibility = struct
+ type t =
+ | Default
+ | Hidden
+ | Protected
+end
+
+module CallConv = struct
+ let c = 0
+ let fast = 8
+ let cold = 9
+ let x86_stdcall = 64
+ let x86_fastcall = 65
+end
+
+module Attribute = struct
+ type t =
+ | Zext
+ | Sext
+ | Noreturn
+ | Inreg
+ | Structret
+ | Nounwind
+ | Noalias
+ | Byval
+ | Nest
+ | Readnone
+ | Readonly
+ | Noinline
+ | Alwaysinline
+ | Optsize
+ | Ssp
+ | Sspreq
+ | Alignment of int
+ | Nocapture
+ | Noredzone
+ | Noimplicitfloat
+ | Naked
+ | Inlinehint
+ | Stackalignment of int
+ | ReturnsTwice
+ | UWTable
+ | NonLazyBind
+end
+
+module Icmp = struct
+ type t =
+ | Eq
+ | Ne
+ | Ugt
+ | Uge
+ | Ult
+ | Ule
+ | Sgt
+ | Sge
+ | Slt
+ | Sle
+end
+
+module Fcmp = struct
+ type t =
+ | False
+ | Oeq
+ | Ogt
+ | Oge
+ | Olt
+ | Ole
+ | One
+ | Ord
+ | Uno
+ | Ueq
+ | Ugt
+ | Uge
+ | Ult
+ | Ule
+ | Une
+ | True
+end
+
+module Opcode = struct
+ type t =
+ | Invalid (* not an instruction *)
+ (* Terminator Instructions *)
+ | Ret
+ | Br
+ | Switch
+ | IndirectBr
+ | Invoke
+ | Invalid2
+ | Unreachable
+ (* Standard Binary Operators *)
+ | Add
+ | FAdd
+ | Sub
+ | FSub
+ | Mul
+ | FMul
+ | UDiv
+ | SDiv
+ | FDiv
+ | URem
+ | SRem
+ | FRem
+ (* Logical Operators *)
+ | Shl
+ | LShr
+ | AShr
+ | And
+ | Or
+ | Xor
+ (* Memory Operators *)
+ | Alloca
+ | Load
+ | Store
+ | GetElementPtr
+ (* Cast Operators *)
+ | Trunc
+ | ZExt
+ | SExt
+ | FPToUI
+ | FPToSI
+ | UIToFP
+ | SIToFP
+ | FPTrunc
+ | FPExt
+ | PtrToInt
+ | IntToPtr
+ | BitCast
+ (* Other Operators *)
+ | ICmp
+ | FCmp
+ | PHI
+ | Call
+ | Select
+ | UserOp1
+ | UserOp2
+ | VAArg
+ | ExtractElement
+ | InsertElement
+ | ShuffleVector
+ | ExtractValue
+ | InsertValue
+ | Fence
+ | AtomicCmpXchg
+ | AtomicRMW
+ | Resume
+ | LandingPad
+ | Unwind
+end
+
+module ValueKind = struct
+ type t =
+ | NullValue
+ | Argument
+ | BasicBlock
+ | InlineAsm
+ | MDNode
+ | MDString
+ | BlockAddress
+ | ConstantAggregateZero
+ | ConstantArray
+ | ConstantExpr
+ | ConstantFP
+ | ConstantInt
+ | ConstantPointerNull
+ | ConstantStruct
+ | ConstantVector
+ | Function
+ | GlobalAlias
+ | GlobalVariable
+ | UndefValue
+ | Instruction of Opcode.t
+end
+
+exception IoError of string
+
+external register_exns : exn -> unit = "llvm_register_core_exns"
+let _ = register_exns (IoError "")
+
+type ('a, 'b) llpos =
+| At_end of 'a
+| Before of 'b
+
+type ('a, 'b) llrev_pos =
+| At_start of 'a
+| After of 'b
+
+(*===-- Contexts ----------------------------------------------------------===*)
+external create_context : unit -> llcontext = "llvm_create_context"
+external dispose_context : llcontext -> unit = "llvm_dispose_context"
+external global_context : unit -> llcontext = "llvm_global_context"
+external mdkind_id : llcontext -> string -> int = "llvm_mdkind_id"
+
+(*===-- Modules -----------------------------------------------------------===*)
+external create_module : llcontext -> string -> llmodule = "llvm_create_module"
+external dispose_module : llmodule -> unit = "llvm_dispose_module"
+external target_triple: llmodule -> string
+ = "llvm_target_triple"
+external set_target_triple: string -> llmodule -> unit
+ = "llvm_set_target_triple"
+external data_layout: llmodule -> string
+ = "llvm_data_layout"
+external set_data_layout: string -> llmodule -> unit
+ = "llvm_set_data_layout"
+external dump_module : llmodule -> unit = "llvm_dump_module"
+external set_module_inline_asm : llmodule -> string -> unit
+ = "llvm_set_module_inline_asm"
+external module_context : llmodule -> llcontext = "LLVMGetModuleContext"
+
+(*===-- Types -------------------------------------------------------------===*)
+external classify_type : lltype -> TypeKind.t = "llvm_classify_type"
+external type_context : lltype -> llcontext = "llvm_type_context"
+external type_is_sized : lltype -> bool = "llvm_type_is_sized"
+
+(*--... Operations on integer types ........................................--*)
+external i1_type : llcontext -> lltype = "llvm_i1_type"
+external i8_type : llcontext -> lltype = "llvm_i8_type"
+external i16_type : llcontext -> lltype = "llvm_i16_type"
+external i32_type : llcontext -> lltype = "llvm_i32_type"
+external i64_type : llcontext -> lltype = "llvm_i64_type"
+
+external integer_type : llcontext -> int -> lltype = "llvm_integer_type"
+external integer_bitwidth : lltype -> int = "llvm_integer_bitwidth"
+
+(*--... Operations on real types ...........................................--*)
+external float_type : llcontext -> lltype = "llvm_float_type"
+external double_type : llcontext -> lltype = "llvm_double_type"
+external x86fp80_type : llcontext -> lltype = "llvm_x86fp80_type"
+external fp128_type : llcontext -> lltype = "llvm_fp128_type"
+external ppc_fp128_type : llcontext -> lltype = "llvm_ppc_fp128_type"
+
+(*--... Operations on function types .......................................--*)
+external function_type : lltype -> lltype array -> lltype = "llvm_function_type"
+external var_arg_function_type : lltype -> lltype array -> lltype
+ = "llvm_var_arg_function_type"
+external is_var_arg : lltype -> bool = "llvm_is_var_arg"
+external return_type : lltype -> lltype = "LLVMGetReturnType"
+external param_types : lltype -> lltype array = "llvm_param_types"
+
+(*--... Operations on struct types .........................................--*)
+external struct_type : llcontext -> lltype array -> lltype = "llvm_struct_type"
+external packed_struct_type : llcontext -> lltype array -> lltype
+ = "llvm_packed_struct_type"
+external struct_name : lltype -> string option = "llvm_struct_name"
+external named_struct_type : llcontext -> string -> lltype =
+ "llvm_named_struct_type"
+external struct_set_body : lltype -> lltype array -> bool -> unit =
+ "llvm_struct_set_body"
+external struct_element_types : lltype -> lltype array
+ = "llvm_struct_element_types"
+external is_packed : lltype -> bool = "llvm_is_packed"
+external is_opaque : lltype -> bool = "llvm_is_opaque"
+
+(*--... Operations on pointer, vector, and array types .....................--*)
+external array_type : lltype -> int -> lltype = "llvm_array_type"
+external pointer_type : lltype -> lltype = "llvm_pointer_type"
+external qualified_pointer_type : lltype -> int -> lltype
+ = "llvm_qualified_pointer_type"
+external vector_type : lltype -> int -> lltype = "llvm_vector_type"
+
+external element_type : lltype -> lltype = "LLVMGetElementType"
+external array_length : lltype -> int = "llvm_array_length"
+external address_space : lltype -> int = "llvm_address_space"
+external vector_size : lltype -> int = "llvm_vector_size"
+
+(*--... Operations on other types ..........................................--*)
+external void_type : llcontext -> lltype = "llvm_void_type"
+external label_type : llcontext -> lltype = "llvm_label_type"
+external type_by_name : llmodule -> string -> lltype option = "llvm_type_by_name"
+
+external classify_value : llvalue -> ValueKind.t = "llvm_classify_value"
+(*===-- Values ------------------------------------------------------------===*)
+external type_of : llvalue -> lltype = "llvm_type_of"
+external value_name : llvalue -> string = "llvm_value_name"
+external set_value_name : string -> llvalue -> unit = "llvm_set_value_name"
+external dump_value : llvalue -> unit = "llvm_dump_value"
+external replace_all_uses_with : llvalue -> llvalue -> unit
+ = "LLVMReplaceAllUsesWith"
+
+(*--... Operations on uses .................................................--*)
+external use_begin : llvalue -> lluse option = "llvm_use_begin"
+external use_succ : lluse -> lluse option = "llvm_use_succ"
+external user : lluse -> llvalue = "llvm_user"
+external used_value : lluse -> llvalue = "llvm_used_value"
+
+let iter_uses f v =
+ let rec aux = function
+ | None -> ()
+ | Some u ->
+ f u;
+ aux (use_succ u)
+ in
+ aux (use_begin v)
+
+let fold_left_uses f init v =
+ let rec aux init u =
+ match u with
+ | None -> init
+ | Some u -> aux (f init u) (use_succ u)
+ in
+ aux init (use_begin v)
+
+let fold_right_uses f v init =
+ let rec aux u init =
+ match u with
+ | None -> init
+ | Some u -> f u (aux (use_succ u) init)
+ in
+ aux (use_begin v) init
+
+
+(*--... Operations on users ................................................--*)
+external operand : llvalue -> int -> llvalue = "llvm_operand"
+external set_operand : llvalue -> int -> llvalue -> unit = "llvm_set_operand"
+external num_operands : llvalue -> int = "llvm_num_operands"
+
+(*--... Operations on constants of (mostly) any type .......................--*)
+external is_constant : llvalue -> bool = "llvm_is_constant"
+external const_null : lltype -> llvalue = "LLVMConstNull"
+external const_all_ones : (*int|vec*)lltype -> llvalue = "LLVMConstAllOnes"
+external const_pointer_null : lltype -> llvalue = "LLVMConstPointerNull"
+external undef : lltype -> llvalue = "LLVMGetUndef"
+external is_null : llvalue -> bool = "llvm_is_null"
+external is_undef : llvalue -> bool = "llvm_is_undef"
+external constexpr_opcode : llvalue -> Opcode.t = "llvm_constexpr_get_opcode"
+
+(*--... Operations on instructions .........................................--*)
+external has_metadata : llvalue -> bool = "llvm_has_metadata"
+external metadata : llvalue -> int -> llvalue option = "llvm_metadata"
+external set_metadata : llvalue -> int -> llvalue -> unit = "llvm_set_metadata"
+external clear_metadata : llvalue -> int -> unit = "llvm_clear_metadata"
+
+(*--... Operations on metadata .......,.....................................--*)
+external mdstring : llcontext -> string -> llvalue = "llvm_mdstring"
+external mdnode : llcontext -> llvalue array -> llvalue = "llvm_mdnode"
+external get_mdstring : llvalue -> string option = "llvm_get_mdstring"
+external get_named_metadata : llmodule -> string -> llvalue array = "llvm_get_namedmd"
+
+(*--... Operations on scalar constants .....................................--*)
+external const_int : lltype -> int -> llvalue = "llvm_const_int"
+external const_of_int64 : lltype -> Int64.t -> bool -> llvalue
+ = "llvm_const_of_int64"
+external int64_of_const : llvalue -> Int64.t option
+ = "llvm_int64_of_const"
+external const_int_of_string : lltype -> string -> int -> llvalue
+ = "llvm_const_int_of_string"
+external const_float : lltype -> float -> llvalue = "llvm_const_float"
+external const_float_of_string : lltype -> string -> llvalue
+ = "llvm_const_float_of_string"
+
+(*--... Operations on composite constants ..................................--*)
+external const_string : llcontext -> string -> llvalue = "llvm_const_string"
+external const_stringz : llcontext -> string -> llvalue = "llvm_const_stringz"
+external const_array : lltype -> llvalue array -> llvalue = "llvm_const_array"
+external const_struct : llcontext -> llvalue array -> llvalue
+ = "llvm_const_struct"
+external const_named_struct : lltype -> llvalue array -> llvalue
+ = "llvm_const_named_struct"
+external const_packed_struct : llcontext -> llvalue array -> llvalue
+ = "llvm_const_packed_struct"
+external const_vector : llvalue array -> llvalue = "llvm_const_vector"
+
+(*--... Constant expressions ...............................................--*)
+external align_of : lltype -> llvalue = "LLVMAlignOf"
+external size_of : lltype -> llvalue = "LLVMSizeOf"
+external const_neg : llvalue -> llvalue = "LLVMConstNeg"
+external const_nsw_neg : llvalue -> llvalue = "LLVMConstNSWNeg"
+external const_nuw_neg : llvalue -> llvalue = "LLVMConstNUWNeg"
+external const_fneg : llvalue -> llvalue = "LLVMConstFNeg"
+external const_not : llvalue -> llvalue = "LLVMConstNot"
+external const_add : llvalue -> llvalue -> llvalue = "LLVMConstAdd"
+external const_nsw_add : llvalue -> llvalue -> llvalue = "LLVMConstNSWAdd"
+external const_nuw_add : llvalue -> llvalue -> llvalue = "LLVMConstNUWAdd"
+external const_fadd : llvalue -> llvalue -> llvalue = "LLVMConstFAdd"
+external const_sub : llvalue -> llvalue -> llvalue = "LLVMConstSub"
+external const_nsw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNSWSub"
+external const_nuw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNUWSub"
+external const_fsub : llvalue -> llvalue -> llvalue = "LLVMConstFSub"
+external const_mul : llvalue -> llvalue -> llvalue = "LLVMConstMul"
+external const_nsw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNSWMul"
+external const_nuw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNUWMul"
+external const_fmul : llvalue -> llvalue -> llvalue = "LLVMConstFMul"
+external const_udiv : llvalue -> llvalue -> llvalue = "LLVMConstUDiv"
+external const_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstSDiv"
+external const_exact_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstExactSDiv"
+external const_fdiv : llvalue -> llvalue -> llvalue = "LLVMConstFDiv"
+external const_urem : llvalue -> llvalue -> llvalue = "LLVMConstURem"
+external const_srem : llvalue -> llvalue -> llvalue = "LLVMConstSRem"
+external const_frem : llvalue -> llvalue -> llvalue = "LLVMConstFRem"
+external const_and : llvalue -> llvalue -> llvalue = "LLVMConstAnd"
+external const_or : llvalue -> llvalue -> llvalue = "LLVMConstOr"
+external const_xor : llvalue -> llvalue -> llvalue = "LLVMConstXor"
+external const_icmp : Icmp.t -> llvalue -> llvalue -> llvalue
+ = "llvm_const_icmp"
+external const_fcmp : Fcmp.t -> llvalue -> llvalue -> llvalue
+ = "llvm_const_fcmp"
+external const_shl : llvalue -> llvalue -> llvalue = "LLVMConstShl"
+external const_lshr : llvalue -> llvalue -> llvalue = "LLVMConstLShr"
+external const_ashr : llvalue -> llvalue -> llvalue = "LLVMConstAShr"
+external const_gep : llvalue -> llvalue array -> llvalue = "llvm_const_gep"
+external const_in_bounds_gep : llvalue -> llvalue array -> llvalue
+ = "llvm_const_in_bounds_gep"
+external const_trunc : llvalue -> lltype -> llvalue = "LLVMConstTrunc"
+external const_sext : llvalue -> lltype -> llvalue = "LLVMConstSExt"
+external const_zext : llvalue -> lltype -> llvalue = "LLVMConstZExt"
+external const_fptrunc : llvalue -> lltype -> llvalue = "LLVMConstFPTrunc"
+external const_fpext : llvalue -> lltype -> llvalue = "LLVMConstFPExt"
+external const_uitofp : llvalue -> lltype -> llvalue = "LLVMConstUIToFP"
+external const_sitofp : llvalue -> lltype -> llvalue = "LLVMConstSIToFP"
+external const_fptoui : llvalue -> lltype -> llvalue = "LLVMConstFPToUI"
+external const_fptosi : llvalue -> lltype -> llvalue = "LLVMConstFPToSI"
+external const_ptrtoint : llvalue -> lltype -> llvalue = "LLVMConstPtrToInt"
+external const_inttoptr : llvalue -> lltype -> llvalue = "LLVMConstIntToPtr"
+external const_bitcast : llvalue -> lltype -> llvalue = "LLVMConstBitCast"
+external const_zext_or_bitcast : llvalue -> lltype -> llvalue
+ = "LLVMConstZExtOrBitCast"
+external const_sext_or_bitcast : llvalue -> lltype -> llvalue
+ = "LLVMConstSExtOrBitCast"
+external const_trunc_or_bitcast : llvalue -> lltype -> llvalue
+ = "LLVMConstTruncOrBitCast"
+external const_pointercast : llvalue -> lltype -> llvalue
+ = "LLVMConstPointerCast"
+external const_intcast : llvalue -> lltype -> llvalue = "LLVMConstIntCast"
+external const_fpcast : llvalue -> lltype -> llvalue = "LLVMConstFPCast"
+external const_select : llvalue -> llvalue -> llvalue -> llvalue
+ = "LLVMConstSelect"
+external const_extractelement : llvalue -> llvalue -> llvalue
+ = "LLVMConstExtractElement"
+external const_insertelement : llvalue -> llvalue -> llvalue -> llvalue
+ = "LLVMConstInsertElement"
+external const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue
+ = "LLVMConstShuffleVector"
+external const_extractvalue : llvalue -> int array -> llvalue
+ = "llvm_const_extractvalue"
+external const_insertvalue : llvalue -> llvalue -> int array -> llvalue
+ = "llvm_const_insertvalue"
+external const_inline_asm : lltype -> string -> string -> bool -> bool ->
+ llvalue
+ = "llvm_const_inline_asm"
+external block_address : llvalue -> llbasicblock -> llvalue = "LLVMBlockAddress"
+
+(*--... Operations on global variables, functions, and aliases (globals) ...--*)
+external global_parent : llvalue -> llmodule = "LLVMGetGlobalParent"
+external is_declaration : llvalue -> bool = "llvm_is_declaration"
+external linkage : llvalue -> Linkage.t = "llvm_linkage"
+external set_linkage : Linkage.t -> llvalue -> unit = "llvm_set_linkage"
+external section : llvalue -> string = "llvm_section"
+external set_section : string -> llvalue -> unit = "llvm_set_section"
+external visibility : llvalue -> Visibility.t = "llvm_visibility"
+external set_visibility : Visibility.t -> llvalue -> unit = "llvm_set_visibility"
+external alignment : llvalue -> int = "llvm_alignment"
+external set_alignment : int -> llvalue -> unit = "llvm_set_alignment"
+external is_global_constant : llvalue -> bool = "llvm_is_global_constant"
+external set_global_constant : bool -> llvalue -> unit
+ = "llvm_set_global_constant"
+
+(*--... Operations on global variables .....................................--*)
+external declare_global : lltype -> string -> llmodule -> llvalue
+ = "llvm_declare_global"
+external declare_qualified_global : lltype -> string -> int -> llmodule ->
+ llvalue
+ = "llvm_declare_qualified_global"
+external define_global : string -> llvalue -> llmodule -> llvalue
+ = "llvm_define_global"
+external define_qualified_global : string -> llvalue -> int -> llmodule ->
+ llvalue
+ = "llvm_define_qualified_global"
+external lookup_global : string -> llmodule -> llvalue option
+ = "llvm_lookup_global"
+external delete_global : llvalue -> unit = "llvm_delete_global"
+external global_initializer : llvalue -> llvalue = "LLVMGetInitializer"
+external set_initializer : llvalue -> llvalue -> unit = "llvm_set_initializer"
+external remove_initializer : llvalue -> unit = "llvm_remove_initializer"
+external is_thread_local : llvalue -> bool = "llvm_is_thread_local"
+external set_thread_local : bool -> llvalue -> unit = "llvm_set_thread_local"
+external global_begin : llmodule -> (llmodule, llvalue) llpos
+ = "llvm_global_begin"
+external global_succ : llvalue -> (llmodule, llvalue) llpos
+ = "llvm_global_succ"
+external global_end : llmodule -> (llmodule, llvalue) llrev_pos
+ = "llvm_global_end"
+external global_pred : llvalue -> (llmodule, llvalue) llrev_pos
+ = "llvm_global_pred"
+
+let rec iter_global_range f i e =
+ if i = e then () else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid global variable range.")
+ | Before bb ->
+ f bb;
+ iter_global_range f (global_succ bb) e
+
+let iter_globals f m =
+ iter_global_range f (global_begin m) (At_end m)
+
+let rec fold_left_global_range f init i e =
+ if i = e then init else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid global variable range.")
+ | Before bb -> fold_left_global_range f (f init bb) (global_succ bb) e
+
+let fold_left_globals f init m =
+ fold_left_global_range f init (global_begin m) (At_end m)
+
+let rec rev_iter_global_range f i e =
+ if i = e then () else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid global variable range.")
+ | After bb ->
+ f bb;
+ rev_iter_global_range f (global_pred bb) e
+
+let rev_iter_globals f m =
+ rev_iter_global_range f (global_end m) (At_start m)
+
+let rec fold_right_global_range f i e init =
+ if i = e then init else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid global variable range.")
+ | After bb -> fold_right_global_range f (global_pred bb) e (f bb init)
+
+let fold_right_globals f m init =
+ fold_right_global_range f (global_end m) (At_start m) init
+
+(*--... Operations on aliases ..............................................--*)
+external add_alias : llmodule -> lltype -> llvalue -> string -> llvalue
+ = "llvm_add_alias"
+
+(*--... Operations on functions ............................................--*)
+external declare_function : string -> lltype -> llmodule -> llvalue
+ = "llvm_declare_function"
+external define_function : string -> lltype -> llmodule -> llvalue
+ = "llvm_define_function"
+external lookup_function : string -> llmodule -> llvalue option
+ = "llvm_lookup_function"
+external delete_function : llvalue -> unit = "llvm_delete_function"
+external is_intrinsic : llvalue -> bool = "llvm_is_intrinsic"
+external function_call_conv : llvalue -> int = "llvm_function_call_conv"
+external set_function_call_conv : int -> llvalue -> unit
+ = "llvm_set_function_call_conv"
+external gc : llvalue -> string option = "llvm_gc"
+external set_gc : string option -> llvalue -> unit = "llvm_set_gc"
+external function_begin : llmodule -> (llmodule, llvalue) llpos
+ = "llvm_function_begin"
+external function_succ : llvalue -> (llmodule, llvalue) llpos
+ = "llvm_function_succ"
+external function_end : llmodule -> (llmodule, llvalue) llrev_pos
+ = "llvm_function_end"
+external function_pred : llvalue -> (llmodule, llvalue) llrev_pos
+ = "llvm_function_pred"
+
+let rec iter_function_range f i e =
+ if i = e then () else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid function range.")
+ | Before fn ->
+ f fn;
+ iter_function_range f (function_succ fn) e
+
+let iter_functions f m =
+ iter_function_range f (function_begin m) (At_end m)
+
+let rec fold_left_function_range f init i e =
+ if i = e then init else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid function range.")
+ | Before fn -> fold_left_function_range f (f init fn) (function_succ fn) e
+
+let fold_left_functions f init m =
+ fold_left_function_range f init (function_begin m) (At_end m)
+
+let rec rev_iter_function_range f i e =
+ if i = e then () else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid function range.")
+ | After fn ->
+ f fn;
+ rev_iter_function_range f (function_pred fn) e
+
+let rev_iter_functions f m =
+ rev_iter_function_range f (function_end m) (At_start m)
+
+let rec fold_right_function_range f i e init =
+ if i = e then init else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid function range.")
+ | After fn -> fold_right_function_range f (function_pred fn) e (f fn init)
+
+let fold_right_functions f m init =
+ fold_right_function_range f (function_end m) (At_start m) init
+
+external llvm_add_function_attr : llvalue -> int32 -> unit
+ = "llvm_add_function_attr"
+external llvm_remove_function_attr : llvalue -> int32 -> unit
+ = "llvm_remove_function_attr"
+external llvm_function_attr : llvalue -> int32 = "llvm_function_attr"
+
+let pack_attr (attr:Attribute.t) : int32 =
+ match attr with
+ Attribute.Zext -> Int32.shift_left 1l 0
+ | Attribute.Sext -> Int32.shift_left 1l 1
+ | Attribute.Noreturn -> Int32.shift_left 1l 2
+ | Attribute.Inreg -> Int32.shift_left 1l 3
+ | Attribute.Structret -> Int32.shift_left 1l 4
+ | Attribute.Nounwind -> Int32.shift_left 1l 5
+ | Attribute.Noalias -> Int32.shift_left 1l 6
+ | Attribute.Byval -> Int32.shift_left 1l 7
+ | Attribute.Nest -> Int32.shift_left 1l 8
+ | Attribute.Readnone -> Int32.shift_left 1l 9
+ | Attribute.Readonly -> Int32.shift_left 1l 10
+ | Attribute.Noinline -> Int32.shift_left 1l 11
+ | Attribute.Alwaysinline -> Int32.shift_left 1l 12
+ | Attribute.Optsize -> Int32.shift_left 1l 13
+ | Attribute.Ssp -> Int32.shift_left 1l 14
+ | Attribute.Sspreq -> Int32.shift_left 1l 15
+ | Attribute.Alignment n -> Int32.shift_left (Int32.of_int n) 16
+ | Attribute.Nocapture -> Int32.shift_left 1l 21
+ | Attribute.Noredzone -> Int32.shift_left 1l 22
+ | Attribute.Noimplicitfloat -> Int32.shift_left 1l 23
+ | Attribute.Naked -> Int32.shift_left 1l 24
+ | Attribute.Inlinehint -> Int32.shift_left 1l 25
+ | Attribute.Stackalignment n -> Int32.shift_left (Int32.of_int n) 26
+ | Attribute.ReturnsTwice -> Int32.shift_left 1l 29
+ | Attribute.UWTable -> Int32.shift_left 1l 30
+ | Attribute.NonLazyBind -> Int32.shift_left 1l 31
+
+let unpack_attr (a : int32) : Attribute.t list =
+ let l = ref [] in
+ let check attr =
+ Int32.logand (pack_attr attr) a in
+ let checkattr attr =
+ if (check attr) <> 0l then begin
+ l := attr :: !l
+ end
+ in
+ checkattr Attribute.Zext;
+ checkattr Attribute.Sext;
+ checkattr Attribute.Noreturn;
+ checkattr Attribute.Inreg;
+ checkattr Attribute.Structret;
+ checkattr Attribute.Nounwind;
+ checkattr Attribute.Noalias;
+ checkattr Attribute.Byval;
+ checkattr Attribute.Nest;
+ checkattr Attribute.Readnone;
+ checkattr Attribute.Readonly;
+ checkattr Attribute.Noinline;
+ checkattr Attribute.Alwaysinline;
+ checkattr Attribute.Optsize;
+ checkattr Attribute.Ssp;
+ checkattr Attribute.Sspreq;
+ let align = Int32.logand (Int32.shift_right_logical a 16) 31l in
+ if align <> 0l then
+ l := Attribute.Alignment (Int32.to_int align) :: !l;
+ checkattr Attribute.Nocapture;
+ checkattr Attribute.Noredzone;
+ checkattr Attribute.Noimplicitfloat;
+ checkattr Attribute.Naked;
+ checkattr Attribute.Inlinehint;
+ let stackalign = Int32.logand (Int32.shift_right_logical a 26) 7l in
+ if stackalign <> 0l then
+ l := Attribute.Stackalignment (Int32.to_int stackalign) :: !l;
+ checkattr Attribute.ReturnsTwice;
+ checkattr Attribute.UWTable;
+ checkattr Attribute.NonLazyBind;
+ !l;;
+
+let add_function_attr llval attr =
+ llvm_add_function_attr llval (pack_attr attr)
+
+let remove_function_attr llval attr =
+ llvm_remove_function_attr llval (pack_attr attr)
+
+let function_attr f = unpack_attr (llvm_function_attr f)
+
+(*--... Operations on params ...............................................--*)
+external params : llvalue -> llvalue array = "llvm_params"
+external param : llvalue -> int -> llvalue = "llvm_param"
+external llvm_param_attr : llvalue -> int32 = "llvm_param_attr"
+let param_attr p = unpack_attr (llvm_param_attr p)
+external param_parent : llvalue -> llvalue = "LLVMGetParamParent"
+external param_begin : llvalue -> (llvalue, llvalue) llpos = "llvm_param_begin"
+external param_succ : llvalue -> (llvalue, llvalue) llpos = "llvm_param_succ"
+external param_end : llvalue -> (llvalue, llvalue) llrev_pos = "llvm_param_end"
+external param_pred : llvalue -> (llvalue, llvalue) llrev_pos ="llvm_param_pred"
+
+let rec iter_param_range f i e =
+ if i = e then () else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid parameter range.")
+ | Before p ->
+ f p;
+ iter_param_range f (param_succ p) e
+
+let iter_params f fn =
+ iter_param_range f (param_begin fn) (At_end fn)
+
+let rec fold_left_param_range f init i e =
+ if i = e then init else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid parameter range.")
+ | Before p -> fold_left_param_range f (f init p) (param_succ p) e
+
+let fold_left_params f init fn =
+ fold_left_param_range f init (param_begin fn) (At_end fn)
+
+let rec rev_iter_param_range f i e =
+ if i = e then () else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid parameter range.")
+ | After p ->
+ f p;
+ rev_iter_param_range f (param_pred p) e
+
+let rev_iter_params f fn =
+ rev_iter_param_range f (param_end fn) (At_start fn)
+
+let rec fold_right_param_range f init i e =
+ if i = e then init else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid parameter range.")
+ | After p -> fold_right_param_range f (f p init) (param_pred p) e
+
+let fold_right_params f fn init =
+ fold_right_param_range f init (param_end fn) (At_start fn)
+
+external llvm_add_param_attr : llvalue -> int32 -> unit
+ = "llvm_add_param_attr"
+external llvm_remove_param_attr : llvalue -> int32 -> unit
+ = "llvm_remove_param_attr"
+
+let add_param_attr llval attr =
+ llvm_add_param_attr llval (pack_attr attr)
+
+let remove_param_attr llval attr =
+ llvm_remove_param_attr llval (pack_attr attr)
+
+external set_param_alignment : llvalue -> int -> unit
+ = "llvm_set_param_alignment"
+
+(*--... Operations on basic blocks .........................................--*)
+external value_of_block : llbasicblock -> llvalue = "LLVMBasicBlockAsValue"
+external value_is_block : llvalue -> bool = "llvm_value_is_block"
+external block_of_value : llvalue -> llbasicblock = "LLVMValueAsBasicBlock"
+external block_parent : llbasicblock -> llvalue = "LLVMGetBasicBlockParent"
+external basic_blocks : llvalue -> llbasicblock array = "llvm_basic_blocks"
+external entry_block : llvalue -> llbasicblock = "LLVMGetEntryBasicBlock"
+external delete_block : llbasicblock -> unit = "llvm_delete_block"
+external append_block : llcontext -> string -> llvalue -> llbasicblock
+ = "llvm_append_block"
+external insert_block : llcontext -> string -> llbasicblock -> llbasicblock
+ = "llvm_insert_block"
+external block_begin : llvalue -> (llvalue, llbasicblock) llpos
+ = "llvm_block_begin"
+external block_succ : llbasicblock -> (llvalue, llbasicblock) llpos
+ = "llvm_block_succ"
+external block_end : llvalue -> (llvalue, llbasicblock) llrev_pos
+ = "llvm_block_end"
+external block_pred : llbasicblock -> (llvalue, llbasicblock) llrev_pos
+ = "llvm_block_pred"
+external block_terminator : llbasicblock -> llvalue option =
+ "llvm_block_terminator"
+
+let rec iter_block_range f i e =
+ if i = e then () else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid block range.")
+ | Before bb ->
+ f bb;
+ iter_block_range f (block_succ bb) e
+
+let iter_blocks f fn =
+ iter_block_range f (block_begin fn) (At_end fn)
+
+let rec fold_left_block_range f init i e =
+ if i = e then init else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid block range.")
+ | Before bb -> fold_left_block_range f (f init bb) (block_succ bb) e
+
+let fold_left_blocks f init fn =
+ fold_left_block_range f init (block_begin fn) (At_end fn)
+
+let rec rev_iter_block_range f i e =
+ if i = e then () else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid block range.")
+ | After bb ->
+ f bb;
+ rev_iter_block_range f (block_pred bb) e
+
+let rev_iter_blocks f fn =
+ rev_iter_block_range f (block_end fn) (At_start fn)
+
+let rec fold_right_block_range f init i e =
+ if i = e then init else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid block range.")
+ | After bb -> fold_right_block_range f (f bb init) (block_pred bb) e
+
+let fold_right_blocks f fn init =
+ fold_right_block_range f init (block_end fn) (At_start fn)
+
+(*--... Operations on instructions .........................................--*)
+external instr_parent : llvalue -> llbasicblock = "LLVMGetInstructionParent"
+external instr_begin : llbasicblock -> (llbasicblock, llvalue) llpos
+ = "llvm_instr_begin"
+external instr_succ : llvalue -> (llbasicblock, llvalue) llpos
+ = "llvm_instr_succ"
+external instr_end : llbasicblock -> (llbasicblock, llvalue) llrev_pos
+ = "llvm_instr_end"
+external instr_pred : llvalue -> (llbasicblock, llvalue) llrev_pos
+ = "llvm_instr_pred"
+
+external instr_opcode : llvalue -> Opcode.t = "llvm_instr_get_opcode"
+external icmp_predicate : llvalue -> Icmp.t option = "llvm_instr_icmp_predicate"
+
+external icmp_predicate : llvalue -> Icmp.t option = "llvm_instr_icmp_predicate"
+
+let rec iter_instrs_range f i e =
+ if i = e then () else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid instruction range.")
+ | Before i ->
+ f i;
+ iter_instrs_range f (instr_succ i) e
+
+let iter_instrs f bb =
+ iter_instrs_range f (instr_begin bb) (At_end bb)
+
+let rec fold_left_instrs_range f init i e =
+ if i = e then init else
+ match i with
+ | At_end _ -> raise (Invalid_argument "Invalid instruction range.")
+ | Before i -> fold_left_instrs_range f (f init i) (instr_succ i) e
+
+let fold_left_instrs f init bb =
+ fold_left_instrs_range f init (instr_begin bb) (At_end bb)
+
+let rec rev_iter_instrs_range f i e =
+ if i = e then () else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid instruction range.")
+ | After i ->
+ f i;
+ rev_iter_instrs_range f (instr_pred i) e
+
+let rev_iter_instrs f bb =
+ rev_iter_instrs_range f (instr_end bb) (At_start bb)
+
+let rec fold_right_instr_range f i e init =
+ if i = e then init else
+ match i with
+ | At_start _ -> raise (Invalid_argument "Invalid instruction range.")
+ | After i -> fold_right_instr_range f (instr_pred i) e (f i init)
+
+let fold_right_instrs f bb init =
+ fold_right_instr_range f (instr_end bb) (At_start bb) init
+
+
+(*--... Operations on call sites ...........................................--*)
+external instruction_call_conv: llvalue -> int
+ = "llvm_instruction_call_conv"
+external set_instruction_call_conv: int -> llvalue -> unit
+ = "llvm_set_instruction_call_conv"
+
+external llvm_add_instruction_param_attr : llvalue -> int -> int32 -> unit
+ = "llvm_add_instruction_param_attr"
+external llvm_remove_instruction_param_attr : llvalue -> int -> int32 -> unit
+ = "llvm_remove_instruction_param_attr"
+
+let add_instruction_param_attr llval i attr =
+ llvm_add_instruction_param_attr llval i (pack_attr attr)
+
+let remove_instruction_param_attr llval i attr =
+ llvm_remove_instruction_param_attr llval i (pack_attr attr)
+
+(*--... Operations on call instructions (only) .............................--*)
+external is_tail_call : llvalue -> bool = "llvm_is_tail_call"
+external set_tail_call : bool -> llvalue -> unit = "llvm_set_tail_call"
+
+(*--... Operations on phi nodes ............................................--*)
+external add_incoming : (llvalue * llbasicblock) -> llvalue -> unit
+ = "llvm_add_incoming"
+external incoming : llvalue -> (llvalue * llbasicblock) list = "llvm_incoming"
+
+external delete_instruction : llvalue -> unit = "llvm_delete_instruction"
+
+(*===-- Instruction builders ----------------------------------------------===*)
+external builder : llcontext -> llbuilder = "llvm_builder"
+external position_builder : (llbasicblock, llvalue) llpos -> llbuilder -> unit
+ = "llvm_position_builder"
+external insertion_block : llbuilder -> llbasicblock = "llvm_insertion_block"
+external insert_into_builder : llvalue -> string -> llbuilder -> unit
+ = "llvm_insert_into_builder"
+
+let builder_at context ip =
+ let b = builder context in
+ position_builder ip b;
+ b
+
+let builder_before context i = builder_at context (Before i)
+let builder_at_end context bb = builder_at context (At_end bb)
+
+let position_before i = position_builder (Before i)
+let position_at_end bb = position_builder (At_end bb)
+
+
+(*--... Metadata ...........................................................--*)
+external set_current_debug_location : llbuilder -> llvalue -> unit
+ = "llvm_set_current_debug_location"
+external clear_current_debug_location : llbuilder -> unit
+ = "llvm_clear_current_debug_location"
+external current_debug_location : llbuilder -> llvalue option
+ = "llvm_current_debug_location"
+external set_inst_debug_location : llbuilder -> llvalue -> unit
+ = "llvm_set_inst_debug_location"
+
+
+(*--... Terminators ........................................................--*)
+external build_ret_void : llbuilder -> llvalue = "llvm_build_ret_void"
+external build_ret : llvalue -> llbuilder -> llvalue = "llvm_build_ret"
+external build_aggregate_ret : llvalue array -> llbuilder -> llvalue
+ = "llvm_build_aggregate_ret"
+external build_br : llbasicblock -> llbuilder -> llvalue = "llvm_build_br"
+external build_cond_br : llvalue -> llbasicblock -> llbasicblock -> llbuilder ->
+ llvalue = "llvm_build_cond_br"
+external build_switch : llvalue -> llbasicblock -> int -> llbuilder -> llvalue
+ = "llvm_build_switch"
+external build_malloc : lltype -> string -> llbuilder -> llvalue =
+ "llvm_build_malloc"
+external build_array_malloc : lltype -> llvalue -> string -> llbuilder ->
+ llvalue = "llvm_build_array_malloc"
+external build_free : llvalue -> llbuilder -> llvalue = "llvm_build_free"
+external add_case : llvalue -> llvalue -> llbasicblock -> unit
+ = "llvm_add_case"
+external switch_default_dest : llvalue -> llbasicblock =
+ "LLVMGetSwitchDefaultDest"
+external build_indirect_br : llvalue -> int -> llbuilder -> llvalue
+ = "llvm_build_indirect_br"
+external add_destination : llvalue -> llbasicblock -> unit
+ = "llvm_add_destination"
+external build_invoke : llvalue -> llvalue array -> llbasicblock ->
+ llbasicblock -> string -> llbuilder -> llvalue
+ = "llvm_build_invoke_bc" "llvm_build_invoke_nat"
+external build_landingpad : lltype -> llvalue -> int -> string -> llbuilder ->
+ llvalue = "llvm_build_landingpad"
+external set_cleanup : llvalue -> bool -> unit = "llvm_set_cleanup"
+external add_clause : llvalue -> llvalue -> unit = "llvm_add_clause"
+external build_resume : llvalue -> llbuilder -> llvalue = "llvm_build_resume"
+external build_unreachable : llbuilder -> llvalue = "llvm_build_unreachable"
+
+(*--... Arithmetic .........................................................--*)
+external build_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_add"
+external build_nsw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_nsw_add"
+external build_nuw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_nuw_add"
+external build_fadd : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_fadd"
+external build_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_sub"
+external build_nsw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_nsw_sub"
+external build_nuw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_nuw_sub"
+external build_fsub : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_fsub"
+external build_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_mul"
+external build_nsw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_nsw_mul"
+external build_nuw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_nuw_mul"
+external build_fmul : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_fmul"
+external build_udiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_udiv"
+external build_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_sdiv"
+external build_exact_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_exact_sdiv"
+external build_fdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_fdiv"
+external build_urem : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_urem"
+external build_srem : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_srem"
+external build_frem : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_frem"
+external build_shl : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_shl"
+external build_lshr : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_lshr"
+external build_ashr : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_ashr"
+external build_and : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_and"
+external build_or : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_or"
+external build_xor : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_xor"
+external build_neg : llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_neg"
+external build_nsw_neg : llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_nsw_neg"
+external build_nuw_neg : llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_nuw_neg"
+external build_fneg : llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_fneg"
+external build_not : llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_not"
+
+(*--... Memory .............................................................--*)
+external build_alloca : lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_alloca"
+external build_array_alloca : lltype -> llvalue -> string -> llbuilder ->
+ llvalue = "llvm_build_array_alloca"
+external build_load : llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_load"
+external build_store : llvalue -> llvalue -> llbuilder -> llvalue
+ = "llvm_build_store"
+external build_gep : llvalue -> llvalue array -> string -> llbuilder -> llvalue
+ = "llvm_build_gep"
+external build_in_bounds_gep : llvalue -> llvalue array -> string ->
+ llbuilder -> llvalue = "llvm_build_in_bounds_gep"
+external build_struct_gep : llvalue -> int -> string -> llbuilder -> llvalue
+ = "llvm_build_struct_gep"
+
+external build_global_string : string -> string -> llbuilder -> llvalue
+ = "llvm_build_global_string"
+external build_global_stringptr : string -> string -> llbuilder -> llvalue
+ = "llvm_build_global_stringptr"
+
+(*--... Casts ..............................................................--*)
+external build_trunc : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_trunc"
+external build_zext : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_zext"
+external build_sext : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_sext"
+external build_fptoui : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_fptoui"
+external build_fptosi : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_fptosi"
+external build_uitofp : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_uitofp"
+external build_sitofp : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_sitofp"
+external build_fptrunc : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_fptrunc"
+external build_fpext : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_fpext"
+external build_ptrtoint : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_prttoint"
+external build_inttoptr : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_inttoptr"
+external build_bitcast : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_bitcast"
+external build_zext_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
+ llvalue = "llvm_build_zext_or_bitcast"
+external build_sext_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
+ llvalue = "llvm_build_sext_or_bitcast"
+external build_trunc_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
+ llvalue = "llvm_build_trunc_or_bitcast"
+external build_pointercast : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_pointercast"
+external build_intcast : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_intcast"
+external build_fpcast : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_fpcast"
+
+(*--... Comparisons ........................................................--*)
+external build_icmp : Icmp.t -> llvalue -> llvalue -> string ->
+ llbuilder -> llvalue = "llvm_build_icmp"
+external build_fcmp : Fcmp.t -> llvalue -> llvalue -> string ->
+ llbuilder -> llvalue = "llvm_build_fcmp"
+
+(*--... Miscellaneous instructions .........................................--*)
+external build_phi : (llvalue * llbasicblock) list -> string -> llbuilder ->
+ llvalue = "llvm_build_phi"
+external build_call : llvalue -> llvalue array -> string -> llbuilder -> llvalue
+ = "llvm_build_call"
+external build_select : llvalue -> llvalue -> llvalue -> string -> llbuilder ->
+ llvalue = "llvm_build_select"
+external build_va_arg : llvalue -> lltype -> string -> llbuilder -> llvalue
+ = "llvm_build_va_arg"
+external build_extractelement : llvalue -> llvalue -> string -> llbuilder ->
+ llvalue = "llvm_build_extractelement"
+external build_insertelement : llvalue -> llvalue -> llvalue -> string ->
+ llbuilder -> llvalue = "llvm_build_insertelement"
+external build_shufflevector : llvalue -> llvalue -> llvalue -> string ->
+ llbuilder -> llvalue = "llvm_build_shufflevector"
+external build_extractvalue : llvalue -> int -> string -> llbuilder -> llvalue
+ = "llvm_build_extractvalue"
+external build_insertvalue : llvalue -> llvalue -> int -> string -> llbuilder ->
+ llvalue = "llvm_build_insertvalue"
+
+external build_is_null : llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_is_null"
+external build_is_not_null : llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_is_not_null"
+external build_ptrdiff : llvalue -> llvalue -> string -> llbuilder -> llvalue
+ = "llvm_build_ptrdiff"
+
+
+(*===-- Memory buffers ----------------------------------------------------===*)
+
+module MemoryBuffer = struct
+ external of_file : string -> llmemorybuffer = "llvm_memorybuffer_of_file"
+ external of_stdin : unit -> llmemorybuffer = "llvm_memorybuffer_of_stdin"
+ external dispose : llmemorybuffer -> unit = "llvm_memorybuffer_dispose"
+end
+
+
+(*===-- Pass Manager ------------------------------------------------------===*)
+
+module PassManager = struct
+ type 'a t
+ type any = [ `Module | `Function ]
+ external create : unit -> [ `Module ] t = "llvm_passmanager_create"
+ external create_function : llmodule -> [ `Function ] t
+ = "LLVMCreateFunctionPassManager"
+ external run_module : llmodule -> [ `Module ] t -> bool
+ = "llvm_passmanager_run_module"
+ external initialize : [ `Function ] t -> bool = "llvm_passmanager_initialize"
+ external run_function : llvalue -> [ `Function ] t -> bool
+ = "llvm_passmanager_run_function"
+ external finalize : [ `Function ] t -> bool = "llvm_passmanager_finalize"
+ external dispose : [< any ] t -> unit = "llvm_passmanager_dispose"
+end
+
+
+(*===-- Non-Externs -------------------------------------------------------===*)
+(* These functions are built using the externals, so must be declared late. *)
+
+let concat2 sep arr =
+ let s = ref "" in
+ if 0 < Array.length arr then begin
+ s := !s ^ arr.(0);
+ for i = 1 to (Array.length arr) - 1 do
+ s := !s ^ sep ^ arr.(i)
+ done
+ end;
+ !s
+
+let rec string_of_lltype ty =
+ (* FIXME: stop infinite recursion! :) *)
+ match classify_type ty with
+ TypeKind.Integer -> "i" ^ string_of_int (integer_bitwidth ty)
+ | TypeKind.Pointer ->
+ (let ety = element_type ty in
+ match classify_type ety with
+ | TypeKind.Struct ->
+ (match struct_name ety with
+ | None -> (string_of_lltype ety)
+ | Some s -> s) ^ "*"
+ | _ -> (string_of_lltype (element_type ty)) ^ "*")
+ | TypeKind.Struct ->
+ let s = "{ " ^ (concat2 ", " (
+ Array.map string_of_lltype (struct_element_types ty)
+ )) ^ " }" in
+ if is_packed ty
+ then "<" ^ s ^ ">"
+ else s
+ | TypeKind.Array -> "[" ^ (string_of_int (array_length ty)) ^
+ " x " ^ (string_of_lltype (element_type ty)) ^ "]"
+ | TypeKind.Vector -> "<" ^ (string_of_int (vector_size ty)) ^
+ " x " ^ (string_of_lltype (element_type ty)) ^ ">"
+ | TypeKind.Function -> string_of_lltype (return_type ty) ^
+ " (" ^ (concat2 ", " (
+ Array.map string_of_lltype (param_types ty)
+ )) ^ ")"
+ | TypeKind.Label -> "label"
+ | TypeKind.Ppc_fp128 -> "ppc_fp128"
+ | TypeKind.Fp128 -> "fp128"
+ | TypeKind.X86fp80 -> "x86_fp80"
+ | TypeKind.Double -> "double"
+ | TypeKind.Float -> "float"
+ | TypeKind.Half -> "half"
+ | TypeKind.Void -> "void"
+ | TypeKind.Metadata -> "metadata"
diff --git a/bindings/ocaml/llvm/llvm.mli b/bindings/ocaml/llvm/llvm.mli
new file mode 100644
index 00000000000..96448ccd960
--- /dev/null
+++ b/bindings/ocaml/llvm/llvm.mli
@@ -0,0 +1,2405 @@
+(*===-- llvm/llvm.mli - LLVM Ocaml Interface -------------------------------===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** Core API.
+
+ This interface provides an ocaml API for the LLVM intermediate
+ representation, the classes in the VMCore library. *)
+
+
+(** {6 Abstract types}
+
+ These abstract types correlate directly to the LLVM VMCore classes. *)
+
+(** The top-level container for all LLVM global data. See the
+ [llvm::LLVMContext] class. *)
+type llcontext
+
+(** The top-level container for all other LLVM Intermediate Representation (IR)
+ objects. See the [llvm::Module] class. *)
+type llmodule
+
+(** Each value in the LLVM IR has a type, an instance of [lltype]. See the
+ [llvm::Type] class. *)
+type lltype
+
+(** Any value in the LLVM IR. Functions, instructions, global variables,
+ constants, and much more are all [llvalues]. See the [llvm::Value] class.
+ This type covers a wide range of subclasses. *)
+type llvalue
+
+(** Used to store users and usees of values. See the [llvm::Use] class. *)
+type lluse
+
+(** A basic block in LLVM IR. See the [llvm::BasicBlock] class. *)
+type llbasicblock
+
+(** Used to generate instructions in the LLVM IR. See the [llvm::LLVMBuilder]
+ class. *)
+type llbuilder
+
+(** Used to efficiently handle large buffers of read-only binary data.
+ See the [llvm::MemoryBuffer] class. *)
+type llmemorybuffer
+
+(** The kind of an [lltype], the result of [classify_type ty]. See the
+ [llvm::Type::TypeID] enumeration. *)
+module TypeKind : sig
+ type t =
+ Void
+ | Half
+ | Float
+ | Double
+ | X86fp80
+ | Fp128
+ | Ppc_fp128
+ | Label
+ | Integer
+ | Function
+ | Struct
+ | Array
+ | Pointer
+ | Vector
+ | Metadata
+end
+
+(** The linkage of a global value, accessed with {!linkage} and
+ {!set_linkage}. See [llvm::GlobalValue::LinkageTypes]. *)
+module Linkage : sig
+ type t =
+ External
+ | Available_externally
+ | Link_once
+ | Link_once_odr
+ | Weak
+ | Weak_odr
+ | Appending
+ | Internal
+ | Private
+ | Dllimport
+ | Dllexport
+ | External_weak
+ | Ghost
+ | Common
+ | Linker_private
+end
+
+(** The linker visibility of a global value, accessed with {!visibility} and
+ {!set_visibility}. See [llvm::GlobalValue::VisibilityTypes]. *)
+module Visibility : sig
+ type t =
+ Default
+ | Hidden
+ | Protected
+end
+
+(** The following calling convention values may be accessed with
+ {!function_call_conv} and {!set_function_call_conv}. Calling
+ conventions are open-ended. *)
+module CallConv : sig
+ val c : int (** [c] is the C calling convention. *)
+ val fast : int (** [fast] is the calling convention to allow LLVM
+ maximum optimization opportunities. Use only with
+ internal linkage. *)
+ val cold : int (** [cold] is the calling convention for
+ callee-save. *)
+ val x86_stdcall : int (** [x86_stdcall] is the familiar stdcall calling
+ convention from C. *)
+ val x86_fastcall : int (** [x86_fastcall] is the familiar fastcall calling
+ convention from C. *)
+end
+
+module Attribute : sig
+ type t =
+ | Zext
+ | Sext
+ | Noreturn
+ | Inreg
+ | Structret
+ | Nounwind
+ | Noalias
+ | Byval
+ | Nest
+ | Readnone
+ | Readonly
+ | Noinline
+ | Alwaysinline
+ | Optsize
+ | Ssp
+ | Sspreq
+ | Alignment of int
+ | Nocapture
+ | Noredzone
+ | Noimplicitfloat
+ | Naked
+ | Inlinehint
+ | Stackalignment of int
+ | ReturnsTwice
+ | UWTable
+ | NonLazyBind
+end
+
+(** The predicate for an integer comparison ([icmp]) instruction.
+ See the [llvm::ICmpInst::Predicate] enumeration. *)
+module Icmp : sig
+ type t =
+ | Eq
+ | Ne
+ | Ugt
+ | Uge
+ | Ult
+ | Ule
+ | Sgt
+ | Sge
+ | Slt
+ | Sle
+end
+
+(** The predicate for a floating-point comparison ([fcmp]) instruction.
+ See the [llvm::FCmpInst::Predicate] enumeration. *)
+module Fcmp : sig
+ type t =
+ | False
+ | Oeq
+ | Ogt
+ | Oge
+ | Olt
+ | Ole
+ | One
+ | Ord
+ | Uno
+ | Ueq
+ | Ugt
+ | Uge
+ | Ult
+ | Ule
+ | Une
+ | True
+end
+
+(** The opcodes for LLVM instructions and constant expressions. *)
+module Opcode : sig
+ type t =
+ | Invalid (* not an instruction *)
+ (* Terminator Instructions *)
+ | Ret
+ | Br
+ | Switch
+ | IndirectBr
+ | Invoke
+ | Invalid2
+ | Unreachable
+ (* Standard Binary Operators *)
+ | Add
+ | FAdd
+ | Sub
+ | FSub
+ | Mul
+ | FMul
+ | UDiv
+ | SDiv
+ | FDiv
+ | URem
+ | SRem
+ | FRem
+ (* Logical Operators *)
+ | Shl
+ | LShr
+ | AShr
+ | And
+ | Or
+ | Xor
+ (* Memory Operators *)
+ | Alloca
+ | Load
+ | Store
+ | GetElementPtr
+ (* Cast Operators *)
+ | Trunc
+ | ZExt
+ | SExt
+ | FPToUI
+ | FPToSI
+ | UIToFP
+ | SIToFP
+ | FPTrunc
+ | FPExt
+ | PtrToInt
+ | IntToPtr
+ | BitCast
+ (* Other Operators *)
+ | ICmp
+ | FCmp
+ | PHI
+ | Call
+ | Select
+ | UserOp1
+ | UserOp2
+ | VAArg
+ | ExtractElement
+ | InsertElement
+ | ShuffleVector
+ | ExtractValue
+ | InsertValue
+ | Fence
+ | AtomicCmpXchg
+ | AtomicRMW
+ | Resume
+ | LandingPad
+ | Unwind
+end
+
+(** The kind of an [llvalue], the result of [classify_value v].
+ * See the various [LLVMIsA*] functions. *)
+module ValueKind : sig
+ type t =
+ | NullValue
+ | Argument
+ | BasicBlock
+ | InlineAsm
+ | MDNode
+ | MDString
+ | BlockAddress
+ | ConstantAggregateZero
+ | ConstantArray
+ | ConstantExpr
+ | ConstantFP
+ | ConstantInt
+ | ConstantPointerNull
+ | ConstantStruct
+ | ConstantVector
+ | Function
+ | GlobalAlias
+ | GlobalVariable
+ | UndefValue
+ | Instruction of Opcode.t
+end
+
+(** {6 Iteration} *)
+
+(** [Before b] and [At_end a] specify positions from the start of the ['b] list
+ of [a]. [llpos] is used to specify positions in and for forward iteration
+ through the various value lists maintained by the LLVM IR. *)
+type ('a, 'b) llpos =
+| At_end of 'a
+| Before of 'b
+
+(** [After b] and [At_start a] specify positions from the end of the ['b] list
+ of [a]. [llrev_pos] is used for reverse iteration through the various value
+ lists maintained by the LLVM IR. *)
+type ('a, 'b) llrev_pos =
+| At_start of 'a
+| After of 'b
+
+
+(** {6 Exceptions} *)
+
+exception IoError of string
+
+
+(** {6 Contexts} *)
+
+(** [create_context ()] creates a context for storing the "global" state in
+ LLVM. See the constructor [llvm::LLVMContext]. *)
+val create_context : unit -> llcontext
+
+(** [destroy_context ()] destroys a context. See the destructor
+ [llvm::LLVMContext::~LLVMContext]. *)
+val dispose_context : llcontext -> unit
+
+(** See the function [llvm::getGlobalContext]. *)
+val global_context : unit -> llcontext
+
+(** [mdkind_id context name] returns the MDKind ID that corresponds to the
+ name [name] in the context [context]. See the function
+ [llvm::LLVMContext::getMDKindID]. *)
+val mdkind_id : llcontext -> string -> int
+
+
+(** {6 Modules} *)
+
+(** [create_module context id] creates a module with the supplied module ID in
+ the context [context]. Modules are not garbage collected; it is mandatory
+ to call {!dispose_module} to free memory. See the constructor
+ [llvm::Module::Module]. *)
+val create_module : llcontext -> string -> llmodule
+
+(** [dispose_module m] destroys a module [m] and all of the IR objects it
+ contained. All references to subordinate objects are invalidated;
+ referencing them will invoke undefined behavior. See the destructor
+ [llvm::Module::~Module]. *)
+val dispose_module : llmodule -> unit
+
+(** [target_triple m] is the target specifier for the module [m], something like
+ [i686-apple-darwin8]. See the method [llvm::Module::getTargetTriple]. *)
+val target_triple: llmodule -> string
+
+
+(** [target_triple triple m] changes the target specifier for the module [m] to
+ the string [triple]. See the method [llvm::Module::setTargetTriple]. *)
+val set_target_triple: string -> llmodule -> unit
+
+
+(** [data_layout m] is the data layout specifier for the module [m], something
+ like [e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-...-a0:0:64-f80:128:128]. See the
+ method [llvm::Module::getDataLayout]. *)
+val data_layout: llmodule -> string
+
+
+(** [set_data_layout s m] changes the data layout specifier for the module [m]
+ to the string [s]. See the method [llvm::Module::setDataLayout]. *)
+val set_data_layout: string -> llmodule -> unit
+
+(** [dump_module m] prints the .ll representation of the module [m] to standard
+ error. See the method [llvm::Module::dump]. *)
+val dump_module : llmodule -> unit
+
+(** [set_module_inline_asm m asm] sets the inline assembler for the module. See
+ the method [llvm::Module::setModuleInlineAsm]. *)
+val set_module_inline_asm : llmodule -> string -> unit
+
+(** [module_context m] returns the context of the specified module.
+ * See the method [llvm::Module::getContext] *)
+val module_context : llmodule -> llcontext
+
+(** {6 Types} *)
+
+(** [classify_type ty] returns the {!TypeKind.t} corresponding to the type [ty].
+ See the method [llvm::Type::getTypeID]. *)
+val classify_type : lltype -> TypeKind.t
+
+(** [type_is_sized ty] returns whether the type has a size or not.
+ * If it doesn't then it is not safe to call the [TargetData::] methods on it.
+ * *)
+val type_is_sized : lltype -> bool
+
+(** [type_context ty] returns the {!llcontext} corresponding to the type [ty].
+ See the method [llvm::Type::getContext]. *)
+val type_context : lltype -> llcontext
+
+(** [string_of_lltype ty] returns a string describing the type [ty]. *)
+val string_of_lltype : lltype -> string
+
+(** {7 Operations on integer types} *)
+
+(** [i1_type c] returns an integer type of bitwidth 1 in the context [c]. See
+ [llvm::Type::Int1Ty]. *)
+val i1_type : llcontext -> lltype
+
+(** [i8_type c] returns an integer type of bitwidth 8 in the context [c]. See
+ [llvm::Type::Int8Ty]. *)
+val i8_type : llcontext -> lltype
+
+(** [i16_type c] returns an integer type of bitwidth 16 in the context [c]. See
+ [llvm::Type::Int16Ty]. *)
+val i16_type : llcontext -> lltype
+
+(** [i32_type c] returns an integer type of bitwidth 32 in the context [c]. See
+ [llvm::Type::Int32Ty]. *)
+val i32_type : llcontext -> lltype
+
+(** [i64_type c] returns an integer type of bitwidth 64 in the context [c]. See
+ [llvm::Type::Int64Ty]. *)
+val i64_type : llcontext -> lltype
+
+(** [integer_type c n] returns an integer type of bitwidth [n] in the context
+ [c]. See the method [llvm::IntegerType::get]. *)
+val integer_type : llcontext -> int -> lltype
+
+(** [integer_bitwidth c ty] returns the number of bits in the integer type [ty]
+ in the context [c]. See the method [llvm::IntegerType::getBitWidth]. *)
+val integer_bitwidth : lltype -> int
+
+
+(** {7 Operations on real types} *)
+
+(** [float_type c] returns the IEEE 32-bit floating point type in the context
+ [c]. See [llvm::Type::FloatTy]. *)
+val float_type : llcontext -> lltype
+
+(** [double_type c] returns the IEEE 64-bit floating point type in the context
+ [c]. See [llvm::Type::DoubleTy]. *)
+val double_type : llcontext -> lltype
+
+(** [x86fp80_type c] returns the x87 80-bit floating point type in the context
+ [c]. See [llvm::Type::X86_FP80Ty]. *)
+val x86fp80_type : llcontext -> lltype
+
+(** [fp128_type c] returns the IEEE 128-bit floating point type in the context
+ [c]. See [llvm::Type::FP128Ty]. *)
+val fp128_type : llcontext -> lltype
+
+(** [ppc_fp128_type c] returns the PowerPC 128-bit floating point type in the
+ context [c]. See [llvm::Type::PPC_FP128Ty]. *)
+val ppc_fp128_type : llcontext -> lltype
+
+
+(** {7 Operations on function types} *)
+
+(** [function_type ret_ty param_tys] returns the function type returning
+ [ret_ty] and taking [param_tys] as parameters.
+ See the method [llvm::FunctionType::get]. *)
+val function_type : lltype -> lltype array -> lltype
+
+(** [var_arg_function_type ret_ty param_tys] is just like
+ [function_type ret_ty param_tys] except that it returns the function type
+ which also takes a variable number of arguments.
+ See the method [llvm::FunctionType::get]. *)
+val var_arg_function_type : lltype -> lltype array -> lltype
+
+
+(** [is_var_arg fty] returns [true] if [fty] is a varargs function type, [false]
+ otherwise. See the method [llvm::FunctionType::isVarArg]. *)
+val is_var_arg : lltype -> bool
+
+(** [return_type fty] gets the return type of the function type [fty].
+ See the method [llvm::FunctionType::getReturnType]. *)
+val return_type : lltype -> lltype
+
+(** [param_types fty] gets the parameter types of the function type [fty].
+ See the method [llvm::FunctionType::getParamType]. *)
+val param_types : lltype -> lltype array
+
+
+(** {7 Operations on struct types} *)
+
+(** [struct_type context tys] returns the structure type in the context
+ [context] containing in the types in the array [tys]. See the method
+ [llvm::StructType::get]. *)
+val struct_type : llcontext -> lltype array -> lltype
+
+
+(** [packed_struct_type context ys] returns the packed structure type in the
+ context [context] containing in the types in the array [tys]. See the method
+ [llvm::StructType::get]. *)
+val packed_struct_type : llcontext -> lltype array -> lltype
+
+(** [struct_name ty] returns the name of the named structure type [ty],
+ * or None if the structure type is not named *)
+val struct_name : lltype -> string option
+
+(** [named_struct_type context name] returns the named structure type [name]
+ * in the context [context].
+ * See the method [llvm::StructType::get]. *)
+val named_struct_type : llcontext -> string -> lltype
+
+(** [struct_set_body ty elts ispacked] sets the body of the named struct [ty]
+ * to the [elts] elements.
+ * See the moethd [llvm::StructType::setBody]. *)
+val struct_set_body : lltype -> lltype array -> bool -> unit
+
+(** [struct_element_types sty] returns the constituent types of the struct type
+ [sty]. See the method [llvm::StructType::getElementType]. *)
+val struct_element_types : lltype -> lltype array
+
+
+(** [is_packed sty] returns [true] if the structure type [sty] is packed,
+ [false] otherwise. See the method [llvm::StructType::isPacked]. *)
+val is_packed : lltype -> bool
+
+(** [is_opaque sty] returns [true] if the structure type [sty] is opaque.
+ [false] otherwise. See the method [llvm::StructType::isOpaque]. *)
+val is_opaque : lltype -> bool
+
+(** {7 Operations on pointer, vector, and array types} *)
+
+(** [array_type ty n] returns the array type containing [n] elements of type
+ [ty]. See the method [llvm::ArrayType::get]. *)
+val array_type : lltype -> int -> lltype
+
+(** [pointer_type ty] returns the pointer type referencing objects of type
+ [ty] in the default address space (0).
+ See the method [llvm::PointerType::getUnqual]. *)
+val pointer_type : lltype -> lltype
+
+(** [qualified_pointer_type ty as] returns the pointer type referencing objects
+ of type [ty] in address space [as].
+ See the method [llvm::PointerType::get]. *)
+val qualified_pointer_type : lltype -> int -> lltype
+
+
+(** [vector_type ty n] returns the array type containing [n] elements of the
+ primitive type [ty]. See the method [llvm::ArrayType::get]. *)
+val vector_type : lltype -> int -> lltype
+
+(** [element_type ty] returns the element type of the pointer, vector, or array
+ type [ty]. See the method [llvm::SequentialType::get]. *)
+val element_type : lltype -> lltype
+
+(** [element_type aty] returns the element count of the array type [aty].
+ See the method [llvm::ArrayType::getNumElements]. *)
+val array_length : lltype -> int
+
+(** [address_space pty] returns the address space qualifier of the pointer type
+ [pty]. See the method [llvm::PointerType::getAddressSpace]. *)
+val address_space : lltype -> int
+
+(** [element_type ty] returns the element count of the vector type [ty].
+ See the method [llvm::VectorType::getNumElements]. *)
+val vector_size : lltype -> int
+
+
+(** {7 Operations on other types} *)
+
+(** [void_type c] creates a type of a function which does not return any
+ value in the context [c]. See [llvm::Type::VoidTy]. *)
+val void_type : llcontext -> lltype
+
+(** [label_type c] creates a type of a basic block in the context [c]. See
+ [llvm::Type::LabelTy]. *)
+val label_type : llcontext -> lltype
+
+(** [type_by_name m name] returns the specified type from the current module
+ * if it exists.
+ * See the method [llvm::Module::getTypeByName] *)
+val type_by_name : llmodule -> string -> lltype option
+
+(* {6 Values} *)
+
+(** [type_of v] returns the type of the value [v].
+ See the method [llvm::Value::getType]. *)
+val type_of : llvalue -> lltype
+
+val classify_value : llvalue -> ValueKind.t
+
+(** [value_name v] returns the name of the value [v]. For global values, this is
+ the symbol name. For instructions and basic blocks, it is the SSA register
+ name. It is meaningless for constants.
+ See the method [llvm::Value::getName]. *)
+val value_name : llvalue -> string
+
+(** [set_value_name n v] sets the name of the value [v] to [n]. See the method
+ [llvm::Value::setName]. *)
+val set_value_name : string -> llvalue -> unit
+
+(** [dump_value v] prints the .ll representation of the value [v] to standard
+ error. See the method [llvm::Value::dump]. *)
+val dump_value : llvalue -> unit
+
+(** [replace_all_uses_with old new] replaces all uses of the value [old]
+ * with the value [new]. See the method [llvm::Value::replaceAllUsesWith]. *)
+val replace_all_uses_with : llvalue -> llvalue -> unit
+
+
+
+(* {6 Uses} *)
+
+(** [use_begin v] returns the first position in the use list for the value [v].
+ [use_begin] and [use_succ] can e used to iterate over the use list in order.
+ See the method [llvm::Value::use_begin]. *)
+val use_begin : llvalue -> lluse option
+
+(** [use_succ u] returns the use list position succeeding [u].
+ See the method [llvm::use_value_iterator::operator++]. *)
+val use_succ : lluse -> lluse option
+
+(** [user u] returns the user of the use [u].
+ See the method [llvm::Use::getUser]. *)
+val user : lluse -> llvalue
+
+(** [used_value u] returns the usee of the use [u].
+ See the method [llvm::Use::getUsedValue]. *)
+val used_value : lluse -> llvalue
+
+(** [iter_uses f v] applies function [f] to each of the users of the value [v]
+ in order. Tail recursive. *)
+val iter_uses : (lluse -> unit) -> llvalue -> unit
+
+(** [fold_left_uses f init v] is [f (... (f init u1) ...) uN] where
+ [u1,...,uN] are the users of the value [v]. Tail recursive. *)
+val fold_left_uses : ('a -> lluse -> 'a) -> 'a -> llvalue -> 'a
+
+(** [fold_right_uses f v init] is [f u1 (... (f uN init) ...)] where
+ [u1,...,uN] are the users of the value [v]. Not tail recursive. *)
+val fold_right_uses : (lluse -> 'a -> 'a) -> llvalue -> 'a -> 'a
+
+
+(* {6 Users} *)
+
+(** [operand v i] returns the operand at index [i] for the value [v]. See the
+ method [llvm::User::getOperand]. *)
+val operand : llvalue -> int -> llvalue
+
+(** [set_operand v i o] sets the operand of the value [v] at the index [i] to
+ the value [o].
+ See the method [llvm::User::setOperand]. *)
+val set_operand : llvalue -> int -> llvalue -> unit
+
+(** [num_operands v] returns the number of operands for the value [v].
+ See the method [llvm::User::getNumOperands]. *)
+val num_operands : llvalue -> int
+
+(** {7 Operations on constants of (mostly) any type} *)
+
+(** [is_constant v] returns [true] if the value [v] is a constant, [false]
+ otherwise. Similar to [llvm::isa<Constant>]. *)
+val is_constant : llvalue -> bool
+
+(** [const_null ty] returns the constant null (zero) of the type [ty].
+ See the method [llvm::Constant::getNullValue]. *)
+val const_null : lltype -> llvalue
+
+(** [const_all_ones ty] returns the constant '-1' of the integer or vector type
+ [ty]. See the method [llvm::Constant::getAllOnesValue]. *)
+val const_all_ones : (*int|vec*)lltype -> llvalue
+
+(** [const_pointer_null ty] returns the constant null (zero) pointer of the type
+ [ty]. See the method [llvm::ConstantPointerNull::get]. *)
+val const_pointer_null : lltype -> llvalue
+
+(** [undef ty] returns the undefined value of the type [ty].
+ See the method [llvm::UndefValue::get]. *)
+val undef : lltype -> llvalue
+
+(** [is_null v] returns [true] if the value [v] is the null (zero) value.
+ See the method [llvm::Constant::isNullValue]. *)
+val is_null : llvalue -> bool
+
+(** [is_undef v] returns [true] if the value [v] is an undefined value, [false]
+ otherwise. Similar to [llvm::isa<UndefValue>]. *)
+val is_undef : llvalue -> bool
+
+val constexpr_opcode : llvalue -> Opcode.t
+(** {7 Operations on instructions} *)
+
+(** [has_metadata i] returns whether or not the instruction [i] has any
+ metadata attached to it. See the function
+ [llvm::Instruction::hasMetadata]. *)
+val has_metadata : llvalue -> bool
+
+(** [metadata i kind] optionally returns the metadata associated with the
+ kind [kind] in the instruction [i] See the function
+ [llvm::Instruction::getMetadata]. *)
+val metadata : llvalue -> int -> llvalue option
+
+(** [set_metadata i kind md] sets the metadata [md] of kind [kind] in the
+ instruction [i]. See the function [llvm::Instruction::setMetadata]. *)
+val set_metadata : llvalue -> int -> llvalue -> unit
+
+(** [clear_metadata i kind] clears the metadata of kind [kind] in the
+ instruction [i]. See the function [llvm::Instruction::setMetadata]. *)
+val clear_metadata : llvalue -> int -> unit
+
+
+(** {7 Operations on metadata} *)
+
+(** [mdstring c s] returns the MDString of the string [s] in the context [c].
+ See the method [llvm::MDNode::get]. *)
+val mdstring : llcontext -> string -> llvalue
+
+(** [mdnode c elts] returns the MDNode containing the values [elts] in the
+ context [c].
+ See the method [llvm::MDNode::get]. *)
+val mdnode : llcontext -> llvalue array -> llvalue
+
+(** [get_mdstring v] returns the MDString.
+ * See the method [llvm::MDString::getString] *)
+val get_mdstring : llvalue -> string option
+
+(** [get_named_metadata m name] return all the MDNodes belonging to the named
+ * metadata (if any).
+ * See the method [llvm::NamedMDNode::getOperand]. *)
+val get_named_metadata : llmodule -> string -> llvalue array
+
+(** {7 Operations on scalar constants} *)
+
+(** [const_int ty i] returns the integer constant of type [ty] and value [i].
+ See the method [llvm::ConstantInt::get]. *)
+val const_int : lltype -> int -> llvalue
+
+(** [const_of_int64 ty i] returns the integer constant of type [ty] and value
+ [i]. See the method [llvm::ConstantInt::get]. *)
+val const_of_int64 : lltype -> Int64.t -> bool -> llvalue
+
+(** [int64_of_const c] returns the int64 value of the [c] constant integer.
+ * None is returned if this is not an integer constant, or bitwidth exceeds 64.
+ * See the method [llvm::ConstantInt::getSExtValue].*)
+val int64_of_const : llvalue -> Int64.t option
+
+(** [const_int_of_string ty s r] returns the integer constant of type [ty] and
+ * value [s], with the radix [r]. See the method [llvm::ConstantInt::get]. *)
+val const_int_of_string : lltype -> string -> int -> llvalue
+
+
+(** [const_float ty n] returns the floating point constant of type [ty] and
+ value [n]. See the method [llvm::ConstantFP::get]. *)
+val const_float : lltype -> float -> llvalue
+
+(** [const_float_of_string ty s] returns the floating point constant of type
+ [ty] and value [n]. See the method [llvm::ConstantFP::get]. *)
+val const_float_of_string : lltype -> string -> llvalue
+
+
+
+(** {7 Operations on composite constants} *)
+
+(** [const_string c s] returns the constant [i8] array with the values of the
+ characters in the string [s] in the context [c]. The array is not
+ null-terminated (but see {!const_stringz}). This value can in turn be used
+ as the initializer for a global variable. See the method
+ [llvm::ConstantArray::get]. *)
+val const_string : llcontext -> string -> llvalue
+
+(** [const_stringz c s] returns the constant [i8] array with the values of the
+ characters in the string [s] and a null terminator in the context [c]. This
+ value can in turn be used as the initializer for a global variable.
+ See the method [llvm::ConstantArray::get]. *)
+val const_stringz : llcontext -> string -> llvalue
+
+(** [const_array ty elts] returns the constant array of type
+ [array_type ty (Array.length elts)] and containing the values [elts].
+ This value can in turn be used as the initializer for a global variable.
+ See the method [llvm::ConstantArray::get]. *)
+val const_array : lltype -> llvalue array -> llvalue
+
+(** [const_struct context elts] returns the structured constant of type
+ [struct_type (Array.map type_of elts)] and containing the values [elts]
+ in the context [context]. This value can in turn be used as the initializer
+ for a global variable. See the method [llvm::ConstantStruct::getAnon]. *)
+val const_struct : llcontext -> llvalue array -> llvalue
+
+(** [const_named_struct namedty elts] returns the structured constant of type
+ [namedty] (which must be a named structure type) and containing the values [elts].
+ This value can in turn be used as the initializer
+ for a global variable. See the method [llvm::ConstantStruct::get]. *)
+val const_named_struct : lltype -> llvalue array -> llvalue
+
+(** [const_packed_struct context elts] returns the structured constant of
+ type {!packed_struct_type} [(Array.map type_of elts)] and containing the
+ values [elts] in the context [context]. This value can in turn be used as
+ the initializer for a global variable. See the method
+ [llvm::ConstantStruct::get]. *)
+val const_packed_struct : llcontext -> llvalue array -> llvalue
+
+
+(** [const_vector elts] returns the vector constant of type
+ [vector_type (type_of elts.(0)) (Array.length elts)] and containing the
+ values [elts]. See the method [llvm::ConstantVector::get]. *)
+val const_vector : llvalue array -> llvalue
+
+
+(** {7 Constant expressions} *)
+
+(** [align_of ty] returns the alignof constant for the type [ty]. This is
+ equivalent to [const_ptrtoint (const_gep (const_null (pointer_type {i8,ty}))
+ (const_int i32_type 0) (const_int i32_type 1)) i32_type], but considerably
+ more readable. See the method [llvm::ConstantExpr::getAlignOf]. *)
+val align_of : lltype -> llvalue
+
+(** [size_of ty] returns the sizeof constant for the type [ty]. This is
+ equivalent to [const_ptrtoint (const_gep (const_null (pointer_type ty))
+ (const_int i32_type 1)) i64_type], but considerably more readable.
+ See the method [llvm::ConstantExpr::getSizeOf]. *)
+val size_of : lltype -> llvalue
+
+(** [const_neg c] returns the arithmetic negation of the constant [c].
+ See the method [llvm::ConstantExpr::getNeg]. *)
+val const_neg : llvalue -> llvalue
+
+(** [const_nsw_neg c] returns the arithmetic negation of the constant [c] with
+ no signed wrapping. The result is undefined if the negation overflows.
+ See the method [llvm::ConstantExpr::getNSWNeg]. *)
+val const_nsw_neg : llvalue -> llvalue
+
+(** [const_nuw_neg c] returns the arithmetic negation of the constant [c] with
+ no unsigned wrapping. The result is undefined if the negation overflows.
+ See the method [llvm::ConstantExpr::getNUWNeg]. *)
+val const_nuw_neg : llvalue -> llvalue
+
+(** [const_fneg c] returns the arithmetic negation of the constant float [c].
+ See the method [llvm::ConstantExpr::getFNeg]. *)
+val const_fneg : llvalue -> llvalue
+
+(** [const_not c] returns the bitwise inverse of the constant [c].
+ See the method [llvm::ConstantExpr::getNot]. *)
+val const_not : llvalue -> llvalue
+
+(** [const_add c1 c2] returns the constant sum of two constants.
+ See the method [llvm::ConstantExpr::getAdd]. *)
+val const_add : llvalue -> llvalue -> llvalue
+
+(** [const_nsw_add c1 c2] returns the constant sum of two constants with no
+ signed wrapping. The result is undefined if the sum overflows.
+ See the method [llvm::ConstantExpr::getNSWAdd]. *)
+val const_nsw_add : llvalue -> llvalue -> llvalue
+
+(** [const_nuw_add c1 c2] returns the constant sum of two constants with no
+ unsigned wrapping. The result is undefined if the sum overflows.
+ See the method [llvm::ConstantExpr::getNSWAdd]. *)
+val const_nuw_add : llvalue -> llvalue -> llvalue
+
+(** [const_fadd c1 c2] returns the constant sum of two constant floats.
+ See the method [llvm::ConstantExpr::getFAdd]. *)
+val const_fadd : llvalue -> llvalue -> llvalue
+
+(** [const_sub c1 c2] returns the constant difference, [c1 - c2], of two
+ constants. See the method [llvm::ConstantExpr::getSub]. *)
+val const_sub : llvalue -> llvalue -> llvalue
+
+(** [const_nsw_sub c1 c2] returns the constant difference of two constants with
+ no signed wrapping. The result is undefined if the sum overflows.
+ See the method [llvm::ConstantExpr::getNSWSub]. *)
+val const_nsw_sub : llvalue -> llvalue -> llvalue
+
+(** [const_nuw_sub c1 c2] returns the constant difference of two constants with
+ no unsigned wrapping. The result is undefined if the sum overflows.
+ See the method [llvm::ConstantExpr::getNSWSub]. *)
+val const_nuw_sub : llvalue -> llvalue -> llvalue
+
+(** [const_fsub c1 c2] returns the constant difference, [c1 - c2], of two
+ constant floats. See the method [llvm::ConstantExpr::getFSub]. *)
+val const_fsub : llvalue -> llvalue -> llvalue
+
+(** [const_mul c1 c2] returns the constant product of two constants.
+ See the method [llvm::ConstantExpr::getMul]. *)
+val const_mul : llvalue -> llvalue -> llvalue
+
+(** [const_nsw_mul c1 c2] returns the constant product of two constants with
+ no signed wrapping. The result is undefined if the sum overflows.
+ See the method [llvm::ConstantExpr::getNSWMul]. *)
+val const_nsw_mul : llvalue -> llvalue -> llvalue
+
+(** [const_nuw_mul c1 c2] returns the constant product of two constants with
+ no unsigned wrapping. The result is undefined if the sum overflows.
+ See the method [llvm::ConstantExpr::getNSWMul]. *)
+val const_nuw_mul : llvalue -> llvalue -> llvalue
+
+(** [const_fmul c1 c2] returns the constant product of two constants floats.
+ See the method [llvm::ConstantExpr::getFMul]. *)
+val const_fmul : llvalue -> llvalue -> llvalue
+
+(** [const_udiv c1 c2] returns the constant quotient [c1 / c2] of two unsigned
+ integer constants.
+ See the method [llvm::ConstantExpr::getUDiv]. *)
+val const_udiv : llvalue -> llvalue -> llvalue
+
+(** [const_sdiv c1 c2] returns the constant quotient [c1 / c2] of two signed
+ integer constants.
+ See the method [llvm::ConstantExpr::getSDiv]. *)
+val const_sdiv : llvalue -> llvalue -> llvalue
+
+(** [const_exact_sdiv c1 c2] returns the constant quotient [c1 / c2] of two
+ signed integer constants. The result is undefined if the result is rounded
+ or overflows. See the method [llvm::ConstantExpr::getExactSDiv]. *)
+val const_exact_sdiv : llvalue -> llvalue -> llvalue
+
+(** [const_fdiv c1 c2] returns the constant quotient [c1 / c2] of two floating
+ point constants.
+ See the method [llvm::ConstantExpr::getFDiv]. *)
+val const_fdiv : llvalue -> llvalue -> llvalue
+
+(** [const_urem c1 c2] returns the constant remainder [c1 MOD c2] of two
+ unsigned integer constants.
+ See the method [llvm::ConstantExpr::getURem]. *)
+val const_urem : llvalue -> llvalue -> llvalue
+
+(** [const_srem c1 c2] returns the constant remainder [c1 MOD c2] of two
+ signed integer constants.
+ See the method [llvm::ConstantExpr::getSRem]. *)
+val const_srem : llvalue -> llvalue -> llvalue
+
+(** [const_frem c1 c2] returns the constant remainder [c1 MOD c2] of two
+ signed floating point constants.
+ See the method [llvm::ConstantExpr::getFRem]. *)
+val const_frem : llvalue -> llvalue -> llvalue
+
+(** [const_and c1 c2] returns the constant bitwise [AND] of two integer
+ constants.
+ See the method [llvm::ConstantExpr::getAnd]. *)
+val const_and : llvalue -> llvalue -> llvalue
+
+(** [const_or c1 c2] returns the constant bitwise [OR] of two integer
+ constants.
+ See the method [llvm::ConstantExpr::getOr]. *)
+val const_or : llvalue -> llvalue -> llvalue
+
+(** [const_xor c1 c2] returns the constant bitwise [XOR] of two integer
+ constants.
+ See the method [llvm::ConstantExpr::getXor]. *)
+val const_xor : llvalue -> llvalue -> llvalue
+
+(** [const_icmp pred c1 c2] returns the constant comparison of two integer
+ constants, [c1 pred c2].
+ See the method [llvm::ConstantExpr::getICmp]. *)
+val const_icmp : Icmp.t -> llvalue -> llvalue -> llvalue
+
+
+(** [const_fcmp pred c1 c2] returns the constant comparison of two floating
+ point constants, [c1 pred c2].
+ See the method [llvm::ConstantExpr::getFCmp]. *)
+val const_fcmp : Fcmp.t -> llvalue -> llvalue -> llvalue
+
+
+(** [const_shl c1 c2] returns the constant integer [c1] left-shifted by the
+ constant integer [c2].
+ See the method [llvm::ConstantExpr::getShl]. *)
+val const_shl : llvalue -> llvalue -> llvalue
+
+(** [const_lshr c1 c2] returns the constant integer [c1] right-shifted by the
+ constant integer [c2] with zero extension.
+ See the method [llvm::ConstantExpr::getLShr]. *)
+val const_lshr : llvalue -> llvalue -> llvalue
+
+(** [const_ashr c1 c2] returns the constant integer [c1] right-shifted by the
+ constant integer [c2] with sign extension.
+ See the method [llvm::ConstantExpr::getAShr]. *)
+val const_ashr : llvalue -> llvalue -> llvalue
+
+(** [const_gep pc indices] returns the constant [getElementPtr] of [p1] with the
+ constant integers indices from the array [indices].
+ See the method [llvm::ConstantExpr::getGetElementPtr]. *)
+val const_gep : llvalue -> llvalue array -> llvalue
+
+(** [const_in_bounds_gep pc indices] returns the constant [getElementPtr] of [p1]
+ with the constant integers indices from the array [indices].
+ See the method [llvm::ConstantExpr::getInBoundsGetElementPtr]. *)
+val const_in_bounds_gep : llvalue -> llvalue array -> llvalue
+
+
+(** [const_trunc c ty] returns the constant truncation of integer constant [c]
+ to the smaller integer type [ty].
+ See the method [llvm::ConstantExpr::getTrunc]. *)
+val const_trunc : llvalue -> lltype -> llvalue
+
+(** [const_sext c ty] returns the constant sign extension of integer constant
+ [c] to the larger integer type [ty].
+ See the method [llvm::ConstantExpr::getSExt]. *)
+val const_sext : llvalue -> lltype -> llvalue
+
+(** [const_zext c ty] returns the constant zero extension of integer constant
+ [c] to the larger integer type [ty].
+ See the method [llvm::ConstantExpr::getZExt]. *)
+val const_zext : llvalue -> lltype -> llvalue
+
+(** [const_fptrunc c ty] returns the constant truncation of floating point
+ constant [c] to the smaller floating point type [ty].
+ See the method [llvm::ConstantExpr::getFPTrunc]. *)
+val const_fptrunc : llvalue -> lltype -> llvalue
+
+(** [const_fpext c ty] returns the constant extension of floating point constant
+ [c] to the larger floating point type [ty].
+ See the method [llvm::ConstantExpr::getFPExt]. *)
+val const_fpext : llvalue -> lltype -> llvalue
+
+(** [const_uitofp c ty] returns the constant floating point conversion of
+ unsigned integer constant [c] to the floating point type [ty].
+ See the method [llvm::ConstantExpr::getUIToFP]. *)
+val const_uitofp : llvalue -> lltype -> llvalue
+
+(** [const_sitofp c ty] returns the constant floating point conversion of
+ signed integer constant [c] to the floating point type [ty].
+ See the method [llvm::ConstantExpr::getSIToFP]. *)
+val const_sitofp : llvalue -> lltype -> llvalue
+
+(** [const_fptoui c ty] returns the constant unsigned integer conversion of
+ floating point constant [c] to integer type [ty].
+ See the method [llvm::ConstantExpr::getFPToUI]. *)
+val const_fptoui : llvalue -> lltype -> llvalue
+
+(** [const_fptoui c ty] returns the constant unsigned integer conversion of
+ floating point constant [c] to integer type [ty].
+ See the method [llvm::ConstantExpr::getFPToSI]. *)
+val const_fptosi : llvalue -> lltype -> llvalue
+
+(** [const_ptrtoint c ty] returns the constant integer conversion of
+ pointer constant [c] to integer type [ty].
+ See the method [llvm::ConstantExpr::getPtrToInt]. *)
+val const_ptrtoint : llvalue -> lltype -> llvalue
+
+(** [const_inttoptr c ty] returns the constant pointer conversion of
+ integer constant [c] to pointer type [ty].
+ See the method [llvm::ConstantExpr::getIntToPtr]. *)
+val const_inttoptr : llvalue -> lltype -> llvalue
+
+(** [const_bitcast c ty] returns the constant bitwise conversion of constant [c]
+ to type [ty] of equal size.
+ See the method [llvm::ConstantExpr::getBitCast]. *)
+val const_bitcast : llvalue -> lltype -> llvalue
+
+(** [const_zext_or_bitcast c ty] returns a constant zext or bitwise cast
+ conversion of constant [c] to type [ty].
+ See the method [llvm::ConstantExpr::getZExtOrBitCast]. *)
+val const_zext_or_bitcast : llvalue -> lltype -> llvalue
+
+
+(** [const_sext_or_bitcast c ty] returns a constant sext or bitwise cast
+ conversion of constant [c] to type [ty].
+ See the method [llvm::ConstantExpr::getSExtOrBitCast]. *)
+val const_sext_or_bitcast : llvalue -> lltype -> llvalue
+
+
+(** [const_trunc_or_bitcast c ty] returns a constant trunc or bitwise cast
+ conversion of constant [c] to type [ty].
+ See the method [llvm::ConstantExpr::getTruncOrBitCast]. *)
+val const_trunc_or_bitcast : llvalue -> lltype -> llvalue
+
+
+(** [const_pointercast c ty] returns a constant bitcast or a pointer-to-int
+ cast conversion of constant [c] to type [ty] of equal size.
+ See the method [llvm::ConstantExpr::getPointerCast]. *)
+val const_pointercast : llvalue -> lltype -> llvalue
+
+
+(** [const_intcast c ty] returns a constant zext, bitcast, or trunc for integer
+ -> integer casts of constant [c] to type [ty].
+ See the method [llvm::ConstantExpr::getIntCast]. *)
+val const_intcast : llvalue -> lltype -> llvalue
+
+
+(** [const_fpcast c ty] returns a constant fpext, bitcast, or fptrunc for fp ->
+ fp casts of constant [c] to type [ty].
+ See the method [llvm::ConstantExpr::getFPCast]. *)
+val const_fpcast : llvalue -> lltype -> llvalue
+
+
+(** [const_select cond t f] returns the constant conditional which returns value
+ [t] if the boolean constant [cond] is true and the value [f] otherwise.
+ See the method [llvm::ConstantExpr::getSelect]. *)
+val const_select : llvalue -> llvalue -> llvalue -> llvalue
+
+
+(** [const_extractelement vec i] returns the constant [i]th element of
+ constant vector [vec]. [i] must be a constant [i32] value unsigned less than
+ the size of the vector.
+ See the method [llvm::ConstantExpr::getExtractElement]. *)
+val const_extractelement : llvalue -> llvalue -> llvalue
+
+
+(** [const_insertelement vec v i] returns the constant vector with the same
+ elements as constant vector [v] but the [i]th element replaced by the
+ constant [v]. [v] must be a constant value with the type of the vector
+ elements. [i] must be a constant [i32] value unsigned less than the size
+ of the vector.
+ See the method [llvm::ConstantExpr::getInsertElement]. *)
+val const_insertelement : llvalue -> llvalue -> llvalue -> llvalue
+
+
+(** [const_shufflevector a b mask] returns a constant [shufflevector].
+ See the LLVM Language Reference for details on the [shufflevector]
+ instruction.
+ See the method [llvm::ConstantExpr::getShuffleVector]. *)
+val const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue
+
+
+(** [const_extractvalue agg idxs] returns the constant [idxs]th value of
+ constant aggregate [agg]. Each [idxs] must be less than the size of the
+ aggregate. See the method [llvm::ConstantExpr::getExtractValue]. *)
+val const_extractvalue : llvalue -> int array -> llvalue
+
+
+(** [const_insertvalue agg val idxs] inserts the value [val] in the specified
+ indexs [idxs] in the aggegate [agg]. Each [idxs] must be less than the size
+ of the aggregate. See the method [llvm::ConstantExpr::getInsertValue]. *)
+val const_insertvalue : llvalue -> llvalue -> int array -> llvalue
+
+
+(** [const_inline_asm ty asm con side align] inserts a inline assembly string.
+ See the method [llvm::InlineAsm::get]. *)
+val const_inline_asm : lltype -> string -> string -> bool -> bool ->
+ llvalue
+
+
+(** [block_address f bb] returns the address of the basic block [bb] in the
+ function [f]. See the method [llvm::BasicBlock::get]. *)
+val block_address : llvalue -> llbasicblock -> llvalue
+
+
+(** {7 Operations on global variables, functions, and aliases (globals)} *)
+
+(** [global_parent g] is the enclosing module of the global value [g].
+ See the method [llvm::GlobalValue::getParent]. *)
+val global_parent : llvalue -> llmodule
+
+(** [is_declaration g] returns [true] if the global value [g] is a declaration
+ only. Returns [false] otherwise.
+ See the method [llvm::GlobalValue::isDeclaration]. *)
+val is_declaration : llvalue -> bool
+
+(** [linkage g] returns the linkage of the global value [g].
+ See the method [llvm::GlobalValue::getLinkage]. *)
+val linkage : llvalue -> Linkage.t
+
+(** [set_linkage l g] sets the linkage of the global value [g] to [l].
+ See the method [llvm::GlobalValue::setLinkage]. *)
+val set_linkage : Linkage.t -> llvalue -> unit
+
+(** [section g] returns the linker section of the global value [g].
+ See the method [llvm::GlobalValue::getSection]. *)
+val section : llvalue -> string
+
+(** [set_section s g] sets the linker section of the global value [g] to [s].
+ See the method [llvm::GlobalValue::setSection]. *)
+val set_section : string -> llvalue -> unit
+
+(** [visibility g] returns the linker visibility of the global value [g].
+ See the method [llvm::GlobalValue::getVisibility]. *)
+val visibility : llvalue -> Visibility.t
+
+(** [set_visibility v g] sets the linker visibility of the global value [g] to
+ [v]. See the method [llvm::GlobalValue::setVisibility]. *)
+val set_visibility : Visibility.t -> llvalue -> unit
+
+
+(** [alignment g] returns the required alignment of the global value [g].
+ See the method [llvm::GlobalValue::getAlignment]. *)
+val alignment : llvalue -> int
+
+(** [set_alignment n g] sets the required alignment of the global value [g] to
+ [n] bytes. See the method [llvm::GlobalValue::setAlignment]. *)
+val set_alignment : int -> llvalue -> unit
+
+
+(** {7 Operations on global variables} *)
+
+(** [declare_global ty name m] returns a new global variable of type [ty] and
+ with name [name] in module [m] in the default address space (0). If such a
+ global variable already exists, it is returned. If the type of the existing
+ global differs, then a bitcast to [ty] is returned. *)
+val declare_global : lltype -> string -> llmodule -> llvalue
+
+
+(** [declare_qualified_global ty name addrspace m] returns a new global variable
+ of type [ty] and with name [name] in module [m] in the address space
+ [addrspace]. If such a global variable already exists, it is returned. If
+ the type of the existing global differs, then a bitcast to [ty] is
+ returned. *)
+val declare_qualified_global : lltype -> string -> int -> llmodule ->
+ llvalue
+
+
+(** [define_global name init m] returns a new global with name [name] and
+ initializer [init] in module [m] in the default address space (0). If the
+ named global already exists, it is renamed.
+ See the constructor of [llvm::GlobalVariable]. *)
+val define_global : string -> llvalue -> llmodule -> llvalue
+
+
+(** [define_qualified_global name init addrspace m] returns a new global with
+ name [name] and initializer [init] in module [m] in the address space
+ [addrspace]. If the named global already exists, it is renamed.
+ See the constructor of [llvm::GlobalVariable]. *)
+val define_qualified_global : string -> llvalue -> int -> llmodule ->
+ llvalue
+
+
+(** [lookup_global name m] returns [Some g] if a global variable with name
+ [name] exists in module [m]. If no such global exists, returns [None].
+ See the [llvm::GlobalVariable] constructor. *)
+val lookup_global : string -> llmodule -> llvalue option
+
+
+(** [delete_global gv] destroys the global variable [gv].
+ See the method [llvm::GlobalVariable::eraseFromParent]. *)
+val delete_global : llvalue -> unit
+
+(** [global_begin m] returns the first position in the global variable list of
+ the module [m]. [global_begin] and [global_succ] can be used to iterate
+ over the global list in order.
+ See the method [llvm::Module::global_begin]. *)
+val global_begin : llmodule -> (llmodule, llvalue) llpos
+
+
+(** [global_succ gv] returns the global variable list position succeeding
+ [Before gv].
+ See the method [llvm::Module::global_iterator::operator++]. *)
+val global_succ : llvalue -> (llmodule, llvalue) llpos
+
+
+(** [iter_globals f m] applies function [f] to each of the global variables of
+ module [m] in order. Tail recursive. *)
+val iter_globals : (llvalue -> unit) -> llmodule -> unit
+
+(** [fold_left_globals f init m] is [f (... (f init g1) ...) gN] where
+ [g1,...,gN] are the global variables of module [m]. Tail recursive. *)
+val fold_left_globals : ('a -> llvalue -> 'a) -> 'a -> llmodule -> 'a
+
+(** [global_end m] returns the last position in the global variable list of the
+ module [m]. [global_end] and [global_pred] can be used to iterate over the
+ global list in reverse.
+ See the method [llvm::Module::global_end]. *)
+val global_end : llmodule -> (llmodule, llvalue) llrev_pos
+
+
+(** [global_pred gv] returns the global variable list position preceding
+ [After gv].
+ See the method [llvm::Module::global_iterator::operator--]. *)
+val global_pred : llvalue -> (llmodule, llvalue) llrev_pos
+
+
+(** [rev_iter_globals f m] applies function [f] to each of the global variables
+ of module [m] in reverse order. Tail recursive. *)
+val rev_iter_globals : (llvalue -> unit) -> llmodule -> unit
+
+(** [fold_right_globals f m init] is [f g1 (... (f gN init) ...)] where
+ [g1,...,gN] are the global variables of module [m]. Tail recursive. *)
+val fold_right_globals : (llvalue -> 'a -> 'a) -> llmodule -> 'a -> 'a
+
+(** [is_global_constant gv] returns [true] if the global variabile [gv] is a
+ constant. Returns [false] otherwise.
+ See the method [llvm::GlobalVariable::isConstant]. *)
+val is_global_constant : llvalue -> bool
+
+(** [set_global_constant c gv] sets the global variable [gv] to be a constant if
+ [c] is [true] and not if [c] is [false].
+ See the method [llvm::GlobalVariable::setConstant]. *)
+val set_global_constant : bool -> llvalue -> unit
+
+
+(** [global_initializer gv] returns the initializer for the global variable
+ [gv]. See the method [llvm::GlobalVariable::getInitializer]. *)
+val global_initializer : llvalue -> llvalue
+
+(** [set_initializer c gv] sets the initializer for the global variable
+ [gv] to the constant [c].
+ See the method [llvm::GlobalVariable::setInitializer]. *)
+val set_initializer : llvalue -> llvalue -> unit
+
+(** [remove_initializer gv] unsets the initializer for the global variable
+ [gv].
+ See the method [llvm::GlobalVariable::setInitializer]. *)
+val remove_initializer : llvalue -> unit
+
+(** [is_thread_local gv] returns [true] if the global variable [gv] is
+ thread-local and [false] otherwise.
+ See the method [llvm::GlobalVariable::isThreadLocal]. *)
+val is_thread_local : llvalue -> bool
+
+(** [set_thread_local c gv] sets the global variable [gv] to be thread local if
+ [c] is [true] and not otherwise.
+ See the method [llvm::GlobalVariable::setThreadLocal]. *)
+val set_thread_local : bool -> llvalue -> unit
+
+
+(** {7 Operations on aliases} *)
+
+(** [add_alias m t a n] inserts an alias in the module [m] with the type [t] and
+ the aliasee [a] with the name [n].
+ See the constructor for [llvm::GlobalAlias]. *)
+val add_alias : llmodule -> lltype -> llvalue -> string -> llvalue
+
+
+
+(** {7 Operations on functions} *)
+
+(** [declare_function name ty m] returns a new function of type [ty] and
+ with name [name] in module [m]. If such a function already exists,
+ it is returned. If the type of the existing function differs, then a bitcast
+ to [ty] is returned. *)
+val declare_function : string -> lltype -> llmodule -> llvalue
+
+
+(** [define_function name ty m] creates a new function with name [name] and
+ type [ty] in module [m]. If the named function already exists, it is
+ renamed. An entry basic block is created in the function.
+ See the constructor of [llvm::GlobalVariable]. *)
+val define_function : string -> lltype -> llmodule -> llvalue
+
+
+(** [lookup_function name m] returns [Some f] if a function with name
+ [name] exists in module [m]. If no such function exists, returns [None].
+ See the method [llvm::Module] constructor. *)
+val lookup_function : string -> llmodule -> llvalue option
+
+
+(** [delete_function f] destroys the function [f].
+ See the method [llvm::Function::eraseFromParent]. *)
+val delete_function : llvalue -> unit
+
+(** [function_begin m] returns the first position in the function list of the
+ module [m]. [function_begin] and [function_succ] can be used to iterate over
+ the function list in order.
+ See the method [llvm::Module::begin]. *)
+val function_begin : llmodule -> (llmodule, llvalue) llpos
+
+
+(** [function_succ gv] returns the function list position succeeding
+ [Before gv].
+ See the method [llvm::Module::iterator::operator++]. *)
+val function_succ : llvalue -> (llmodule, llvalue) llpos
+
+
+(** [iter_functions f m] applies function [f] to each of the functions of module
+ [m] in order. Tail recursive. *)
+val iter_functions : (llvalue -> unit) -> llmodule -> unit
+
+(** [fold_left_function f init m] is [f (... (f init f1) ...) fN] where
+ [f1,...,fN] are the functions of module [m]. Tail recursive. *)
+val fold_left_functions : ('a -> llvalue -> 'a) -> 'a -> llmodule -> 'a
+
+(** [function_end m] returns the last position in the function list of
+ the module [m]. [function_end] and [function_pred] can be used to iterate
+ over the function list in reverse.
+ See the method [llvm::Module::end]. *)
+val function_end : llmodule -> (llmodule, llvalue) llrev_pos
+
+
+(** [function_pred gv] returns the function list position preceding [After gv].
+ See the method [llvm::Module::iterator::operator--]. *)
+val function_pred : llvalue -> (llmodule, llvalue) llrev_pos
+
+
+(** [rev_iter_functions f fn] applies function [f] to each of the functions of
+ module [m] in reverse order. Tail recursive. *)
+val rev_iter_functions : (llvalue -> unit) -> llmodule -> unit
+
+(** [fold_right_functions f m init] is [f (... (f init fN) ...) f1] where
+ [f1,...,fN] are the functions of module [m]. Tail recursive. *)
+val fold_right_functions : (llvalue -> 'a -> 'a) -> llmodule -> 'a -> 'a
+
+(** [is_intrinsic f] returns true if the function [f] is an intrinsic.
+ See the method [llvm::Function::isIntrinsic]. *)
+val is_intrinsic : llvalue -> bool
+
+(** [function_call_conv f] returns the calling convention of the function [f].
+ See the method [llvm::Function::getCallingConv]. *)
+val function_call_conv : llvalue -> int
+
+(** [set_function_call_conv cc f] sets the calling convention of the function
+ [f] to the calling convention numbered [cc].
+ See the method [llvm::Function::setCallingConv]. *)
+val set_function_call_conv : int -> llvalue -> unit
+
+
+(** [gc f] returns [Some name] if the function [f] has a garbage
+ collection algorithm specified and [None] otherwise.
+ See the method [llvm::Function::getGC]. *)
+val gc : llvalue -> string option
+
+(** [set_gc gc f] sets the collection algorithm for the function [f] to
+ [gc]. See the method [llvm::Function::setGC]. *)
+val set_gc : string option -> llvalue -> unit
+
+(** [add_function_attr f a] adds attribute [a] to the return type of function
+ [f]. *)
+val add_function_attr : llvalue -> Attribute.t -> unit
+
+(** [function_attr f] returns the function attribute for the function [f].
+ * See the method [llvm::Function::getAttributes] *)
+val function_attr : llvalue -> Attribute.t list
+
+(** [remove_function_attr f a] removes attribute [a] from the return type of
+ function [f]. *)
+val remove_function_attr : llvalue -> Attribute.t -> unit
+
+(** {7 Operations on params} *)
+
+(** [params f] returns the parameters of function [f].
+ See the method [llvm::Function::getArgumentList]. *)
+val params : llvalue -> llvalue array
+
+(** [param f n] returns the [n]th parameter of function [f].
+ See the method [llvm::Function::getArgumentList]. *)
+val param : llvalue -> int -> llvalue
+
+(** [param_attr p] returns the attributes of parameter [p].
+ * See the methods [llvm::Function::getAttributes] and
+ * [llvm::Attributes::getParamAttributes] *)
+val param_attr : llvalue -> Attribute.t list
+
+(** [param_parent p] returns the parent function that owns the parameter.
+ See the method [llvm::Argument::getParent]. *)
+val param_parent : llvalue -> llvalue
+
+(** [param_begin f] returns the first position in the parameter list of the
+ function [f]. [param_begin] and [param_succ] can be used to iterate over
+ the parameter list in order.
+ See the method [llvm::Function::arg_begin]. *)
+val param_begin : llvalue -> (llvalue, llvalue) llpos
+
+(** [param_succ bb] returns the parameter list position succeeding
+ [Before bb].
+ See the method [llvm::Function::arg_iterator::operator++]. *)
+val param_succ : llvalue -> (llvalue, llvalue) llpos
+
+(** [iter_params f fn] applies function [f] to each of the parameters
+ of function [fn] in order. Tail recursive. *)
+val iter_params : (llvalue -> unit) -> llvalue -> unit
+
+(** [fold_left_params f init fn] is [f (... (f init b1) ...) bN] where
+ [b1,...,bN] are the parameters of function [fn]. Tail recursive. *)
+val fold_left_params : ('a -> llvalue -> 'a) -> 'a -> llvalue -> 'a
+
+(** [param_end f] returns the last position in the parameter list of
+ the function [f]. [param_end] and [param_pred] can be used to iterate
+ over the parameter list in reverse.
+ See the method [llvm::Function::arg_end]. *)
+val param_end : llvalue -> (llvalue, llvalue) llrev_pos
+
+(** [param_pred gv] returns the function list position preceding [After gv].
+ See the method [llvm::Function::arg_iterator::operator--]. *)
+val param_pred : llvalue -> (llvalue, llvalue) llrev_pos
+
+
+(** [rev_iter_params f fn] applies function [f] to each of the parameters
+ of function [fn] in reverse order. Tail recursive. *)
+val rev_iter_params : (llvalue -> unit) -> llvalue -> unit
+
+(** [fold_right_params f fn init] is [f (... (f init bN) ...) b1] where
+ [b1,...,bN] are the parameters of function [fn]. Tail recursive. *)
+val fold_right_params : (llvalue -> 'a -> 'a) -> llvalue -> 'a -> 'a
+
+(** [add_param p a] adds attribute [a] to parameter [p]. *)
+val add_param_attr : llvalue -> Attribute.t -> unit
+
+(** [remove_param_attr p a] removes attribute [a] from parameter [p]. *)
+val remove_param_attr : llvalue -> Attribute.t -> unit
+
+(** [set_param_alignment p a] set the alignment of parameter [p] to [a]. *)
+val set_param_alignment : llvalue -> int -> unit
+
+
+(** {7 Operations on basic blocks} *)
+
+(** [basic_blocks fn] returns the basic blocks of the function [f].
+ See the method [llvm::Function::getBasicBlockList]. *)
+val basic_blocks : llvalue -> llbasicblock array
+
+(** [entry_block fn] returns the entry basic block of the function [f].
+ See the method [llvm::Function::getEntryBlock]. *)
+val entry_block : llvalue -> llbasicblock
+
+(** [delete_block bb] deletes the basic block [bb].
+ See the method [llvm::BasicBlock::eraseFromParent]. *)
+val delete_block : llbasicblock -> unit
+
+(** [append_block c name f] creates a new basic block named [name] at the end of
+ function [f] in the context [c].
+ See the constructor of [llvm::BasicBlock]. *)
+val append_block : llcontext -> string -> llvalue -> llbasicblock
+
+
+(** [insert_block c name bb] creates a new basic block named [name] before the
+ basic block [bb] in the context [c].
+ See the constructor of [llvm::BasicBlock]. *)
+val insert_block : llcontext -> string -> llbasicblock -> llbasicblock
+
+
+(** [block_parent bb] returns the parent function that owns the basic block.
+ See the method [llvm::BasicBlock::getParent]. *)
+val block_parent : llbasicblock -> llvalue
+
+(** [block_begin f] returns the first position in the basic block list of the
+ function [f]. [block_begin] and [block_succ] can be used to iterate over
+ the basic block list in order.
+ See the method [llvm::Function::begin]. *)
+val block_begin : llvalue -> (llvalue, llbasicblock) llpos
+
+
+(** [block_succ bb] returns the basic block list position succeeding
+ [Before bb].
+ See the method [llvm::Function::iterator::operator++]. *)
+val block_succ : llbasicblock -> (llvalue, llbasicblock) llpos
+
+
+(** [iter_blocks f fn] applies function [f] to each of the basic blocks
+ of function [fn] in order. Tail recursive. *)
+val iter_blocks : (llbasicblock -> unit) -> llvalue -> unit
+
+(** [fold_left_blocks f init fn] is [f (... (f init b1) ...) bN] where
+ [b1,...,bN] are the basic blocks of function [fn]. Tail recursive. *)
+val fold_left_blocks : ('a -> llbasicblock -> 'a) -> 'a -> llvalue -> 'a
+
+(** [block_end f] returns the last position in the basic block list of
+ the function [f]. [block_end] and [block_pred] can be used to iterate
+ over the basic block list in reverse.
+ See the method [llvm::Function::end]. *)
+val block_end : llvalue -> (llvalue, llbasicblock) llrev_pos
+
+
+(** [block_pred gv] returns the function list position preceding [After gv].
+ See the method [llvm::Function::iterator::operator--]. *)
+val block_pred : llbasicblock -> (llvalue, llbasicblock) llrev_pos
+
+val block_terminator : llbasicblock -> llvalue option
+
+(** [rev_iter_blocks f fn] applies function [f] to each of the basic blocks
+ of function [fn] in reverse order. Tail recursive. *)
+val rev_iter_blocks : (llbasicblock -> unit) -> llvalue -> unit
+
+(** [fold_right_blocks f fn init] is [f (... (f init bN) ...) b1] where
+ [b1,...,bN] are the basic blocks of function [fn]. Tail recursive. *)
+val fold_right_blocks : (llbasicblock -> 'a -> 'a) -> llvalue -> 'a -> 'a
+
+(** [value_of_block bb] losslessly casts [bb] to an [llvalue]. *)
+val value_of_block : llbasicblock -> llvalue
+
+(** [value_is_block v] returns [true] if the value [v] is a basic block and
+ [false] otherwise.
+ Similar to [llvm::isa<BasicBlock>]. *)
+val value_is_block : llvalue -> bool
+
+(** [block_of_value v] losslessly casts [v] to an [llbasicblock]. *)
+val block_of_value : llvalue -> llbasicblock
+
+
+(** {7 Operations on instructions} *)
+
+(** [instr_parent i] is the enclosing basic block of the instruction [i].
+ See the method [llvm::Instruction::getParent]. *)
+val instr_parent : llvalue -> llbasicblock
+
+(** [instr_begin bb] returns the first position in the instruction list of the
+ basic block [bb]. [instr_begin] and [instr_succ] can be used to iterate over
+ the instruction list in order.
+ See the method [llvm::BasicBlock::begin]. *)
+val instr_begin : llbasicblock -> (llbasicblock, llvalue) llpos
+
+
+(** [instr_succ i] returns the instruction list position succeeding [Before i].
+ See the method [llvm::BasicBlock::iterator::operator++]. *)
+val instr_succ : llvalue -> (llbasicblock, llvalue) llpos
+
+
+(** [iter_instrs f bb] applies function [f] to each of the instructions of basic
+ block [bb] in order. Tail recursive. *)
+val iter_instrs: (llvalue -> unit) -> llbasicblock -> unit
+
+(** [fold_left_instrs f init bb] is [f (... (f init g1) ...) gN] where
+ [g1,...,gN] are the instructions of basic block [bb]. Tail recursive. *)
+val fold_left_instrs: ('a -> llvalue -> 'a) -> 'a -> llbasicblock -> 'a
+
+(** [instr_end bb] returns the last position in the instruction list of the
+ basic block [bb]. [instr_end] and [instr_pred] can be used to iterate over
+ the instruction list in reverse.
+ See the method [llvm::BasicBlock::end]. *)
+val instr_end : llbasicblock -> (llbasicblock, llvalue) llrev_pos
+
+
+(** [instr_pred i] returns the instruction list position preceding [After i].
+ See the method [llvm::BasicBlock::iterator::operator--]. *)
+val instr_pred : llvalue -> (llbasicblock, llvalue) llrev_pos
+
+
+(** [fold_right_instrs f bb init] is [f (... (f init fN) ...) f1] where
+ [f1,...,fN] are the instructions of basic block [bb]. Tail recursive. *)
+val fold_right_instrs: (llvalue -> 'a -> 'a) -> llbasicblock -> 'a -> 'a
+
+val instr_opcode : llvalue -> Opcode.t
+
+val icmp_predicate : llvalue -> Icmp.t option
+
+(** {7 Operations on call sites} *)
+
+(** [instruction_call_conv ci] is the calling convention for the call or invoke
+ instruction [ci], which may be one of the values from the module
+ {!CallConv}. See the method [llvm::CallInst::getCallingConv] and
+ [llvm::InvokeInst::getCallingConv]. *)
+val instruction_call_conv: llvalue -> int
+
+
+(** [set_instruction_call_conv cc ci] sets the calling convention for the call
+ or invoke instruction [ci] to the integer [cc], which can be one of the
+ values from the module {!CallConv}.
+ See the method [llvm::CallInst::setCallingConv]
+ and [llvm::InvokeInst::setCallingConv]. *)
+val set_instruction_call_conv: int -> llvalue -> unit
+
+
+(** [add_instruction_param_attr ci i a] adds attribute [a] to the [i]th
+ parameter of the call or invoke instruction [ci]. [i]=0 denotes the return
+ value. *)
+val add_instruction_param_attr : llvalue -> int -> Attribute.t -> unit
+
+(** [remove_instruction_param_attr ci i a] removes attribute [a] from the
+ [i]th parameter of the call or invoke instruction [ci]. [i]=0 denotes the
+ return value. *)
+val remove_instruction_param_attr : llvalue -> int -> Attribute.t -> unit
+
+(** {Operations on call instructions (only)} *)
+
+(** [is_tail_call ci] is [true] if the call instruction [ci] is flagged as
+ eligible for tail call optimization, [false] otherwise.
+ See the method [llvm::CallInst::isTailCall]. *)
+val is_tail_call : llvalue -> bool
+
+(** [set_tail_call tc ci] flags the call instruction [ci] as eligible for tail
+ call optimization if [tc] is [true], clears otherwise.
+ See the method [llvm::CallInst::setTailCall]. *)
+val set_tail_call : bool -> llvalue -> unit
+
+(** {7 Operations on phi nodes} *)
+
+(** [add_incoming (v, bb) pn] adds the value [v] to the phi node [pn] for use
+ with branches from [bb]. See the method [llvm::PHINode::addIncoming]. *)
+val add_incoming : (llvalue * llbasicblock) -> llvalue -> unit
+
+
+(** [incoming pn] returns the list of value-block pairs for phi node [pn].
+ See the method [llvm::PHINode::getIncomingValue]. *)
+val incoming : llvalue -> (llvalue * llbasicblock) list
+
+(** [delete_instruction i] deletes the instruction [i].
+ * See the method [llvm::Instruction::eraseFromParent]. *)
+val delete_instruction : llvalue -> unit
+
+(** {6 Instruction builders} *)
+
+(** [builder context] creates an instruction builder with no position in
+ the context [context]. It is invalid to use this builder until its position
+ is set with {!position_before} or {!position_at_end}. See the constructor
+ for [llvm::LLVMBuilder]. *)
+val builder : llcontext -> llbuilder
+
+(** [builder_at ip] creates an instruction builder positioned at [ip].
+ See the constructor for [llvm::LLVMBuilder]. *)
+val builder_at : llcontext -> (llbasicblock, llvalue) llpos -> llbuilder
+
+(** [builder_before ins] creates an instruction builder positioned before the
+ instruction [isn]. See the constructor for [llvm::LLVMBuilder]. *)
+val builder_before : llcontext -> llvalue -> llbuilder
+
+(** [builder_at_end bb] creates an instruction builder positioned at the end of
+ the basic block [bb]. See the constructor for [llvm::LLVMBuilder]. *)
+val builder_at_end : llcontext -> llbasicblock -> llbuilder
+
+(** [position_builder ip bb] moves the instruction builder [bb] to the position
+ [ip].
+ See the constructor for [llvm::LLVMBuilder]. *)
+val position_builder : (llbasicblock, llvalue) llpos -> llbuilder -> unit
+
+
+(** [position_before ins b] moves the instruction builder [b] to before the
+ instruction [isn]. See the method [llvm::LLVMBuilder::SetInsertPoint]. *)
+val position_before : llvalue -> llbuilder -> unit
+
+(** [position_at_end bb b] moves the instruction builder [b] to the end of the
+ basic block [bb]. See the method [llvm::LLVMBuilder::SetInsertPoint]. *)
+val position_at_end : llbasicblock -> llbuilder -> unit
+
+(** [insertion_block b] returns the basic block that the builder [b] is
+ positioned to insert into. Raises [Not_Found] if the instruction builder is
+ uninitialized.
+ See the method [llvm::LLVMBuilder::GetInsertBlock]. *)
+val insertion_block : llbuilder -> llbasicblock
+
+(** [insert_into_builder i name b] inserts the specified instruction [i] at the
+ position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::Insert]. *)
+val insert_into_builder : llvalue -> string -> llbuilder -> unit
+
+
+(** {7 Metadata} *)
+
+(** [set_current_debug_location b md] sets the current debug location [md] in
+ the builder [b].
+ See the method [llvm::IRBuilder::SetDebugLocation]. *)
+val set_current_debug_location : llbuilder -> llvalue -> unit
+
+
+(** [clear_current_debug_location b] clears the current debug location in the
+ builder [b]. *)
+val clear_current_debug_location : llbuilder -> unit
+
+
+(** [current_debug_location b] returns the current debug location, or None
+ if none is currently set.
+ See the method [llvm::IRBuilder::GetDebugLocation]. *)
+val current_debug_location : llbuilder -> llvalue option
+
+
+(** [set_inst_debug_location b i] sets the current debug location of the builder
+ [b] to the instruction [i].
+ See the method [llvm::IRBuilder::SetInstDebugLocation]. *)
+val set_inst_debug_location : llbuilder -> llvalue -> unit
+
+
+(** {7 Terminators} *)
+
+(** [build_ret_void b] creates a
+ [ret void]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateRetVoid]. *)
+val build_ret_void : llbuilder -> llvalue
+
+(** [build_ret v b] creates a
+ [ret %v]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateRet]. *)
+val build_ret : llvalue -> llbuilder -> llvalue
+
+(** [build_aggregate_ret vs b] creates a
+ [ret {...} { %v1, %v2, ... } ]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateAggregateRet]. *)
+val build_aggregate_ret : llvalue array -> llbuilder -> llvalue
+
+
+(** [build_br bb b] creates a
+ [br %bb]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateBr]. *)
+val build_br : llbasicblock -> llbuilder -> llvalue
+
+(** [build_cond_br cond tbb fbb b] creates a
+ [br %cond, %tbb, %fbb]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateCondBr]. *)
+val build_cond_br : llvalue -> llbasicblock -> llbasicblock -> llbuilder ->
+ llvalue
+
+(** [build_switch case elsebb count b] creates an empty
+ [switch %case, %elsebb]
+ instruction at the position specified by the instruction builder [b] with
+ space reserved for [count] cases.
+ See the method [llvm::LLVMBuilder::CreateSwitch]. *)
+val build_switch : llvalue -> llbasicblock -> int -> llbuilder -> llvalue
+
+(** [build_malloc ty name b] creates an [malloc]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::CallInst::CreateMalloc]. *)
+val build_malloc : lltype -> string -> llbuilder -> llvalue
+
+(** [build_array_malloc ty val name b] creates an [array malloc]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::CallInst::CreateArrayMalloc]. *)
+val build_array_malloc : lltype -> llvalue -> string -> llbuilder -> llvalue
+
+(** [build_free p b] creates a [free]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFree]. *)
+val build_free : llvalue -> llbuilder -> llvalue
+
+(** [add_case sw onval bb] causes switch instruction [sw] to branch to [bb]
+ when its input matches the constant [onval].
+ See the method [llvm::SwitchInst::addCase]. **)
+val add_case : llvalue -> llvalue -> llbasicblock -> unit
+
+(** [switch_default_dest sw] returns the default destination of the [switch]
+ * instruction.
+ * See the method [llvm:;SwitchInst::getDefaultDest]. **)
+val switch_default_dest : llvalue -> llbasicblock
+
+(** [build_indirect_br addr count b] creates a
+ [indirectbr %addr]
+ instruction at the position specified by the instruction builder [b] with
+ space reserved for [count] destinations.
+ See the method [llvm::LLVMBuilder::CreateIndirectBr]. *)
+val build_indirect_br : llvalue -> int -> llbuilder -> llvalue
+
+
+(** [add_destination br bb] adds the basic block [bb] as a possible branch
+ location for the indirectbr instruction [br].
+ See the method [llvm::IndirectBrInst::addDestination]. **)
+val add_destination : llvalue -> llbasicblock -> unit
+
+
+(** [build_invoke fn args tobb unwindbb name b] creates an
+ [%name = invoke %fn(args) to %tobb unwind %unwindbb]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateInvoke]. *)
+val build_invoke : llvalue -> llvalue array -> llbasicblock ->
+ llbasicblock -> string -> llbuilder -> llvalue
+
+(** [build_landingpad ty persfn numclauses name b] creates an
+ [landingpad]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateLandingPad]. *)
+val build_landingpad : lltype -> llvalue -> int -> string -> llbuilder ->
+ llvalue
+
+(** [set_cleanup lp] sets the cleanup flag in the [landingpad]instruction.
+ See the method [llvm::LandingPadInst::setCleanup]. *)
+val set_cleanup : llvalue -> bool -> unit
+
+(** [add_clause lp clause] adds the clause to the [landingpad]instruction.
+ See the method [llvm::LandingPadInst::addClause]. *)
+val add_clause : llvalue -> llvalue -> unit
+
+(* [build_resume exn b] builds a [resume exn] instruction
+ * at the position specified by the instruction builder [b].
+ * See the method [llvm::LLVMBuilder::CreateResume] *)
+val build_resume : llvalue -> llbuilder -> llvalue
+
+(** [build_unreachable b] creates an
+ [unreachable]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateUnwind]. *)
+val build_unreachable : llbuilder -> llvalue
+
+
+(** {7 Arithmetic} *)
+
+(** [build_add x y name b] creates a
+ [%name = add %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateAdd]. *)
+val build_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_nsw_add x y name b] creates a
+ [%name = nsw add %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateNSWAdd]. *)
+val build_nsw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_nuw_add x y name b] creates a
+ [%name = nuw add %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateNUWAdd]. *)
+val build_nuw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_fadd x y name b] creates a
+ [%name = fadd %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFAdd]. *)
+val build_fadd : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_sub x y name b] creates a
+ [%name = sub %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateSub]. *)
+val build_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_nsw_sub x y name b] creates a
+ [%name = nsw sub %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateNSWSub]. *)
+val build_nsw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_nuw_sub x y name b] creates a
+ [%name = nuw sub %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateNUWSub]. *)
+val build_nuw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_fsub x y name b] creates a
+ [%name = fsub %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFSub]. *)
+val build_fsub : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_mul x y name b] creates a
+ [%name = mul %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateMul]. *)
+val build_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_nsw_mul x y name b] creates a
+ [%name = nsw mul %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateNSWMul]. *)
+val build_nsw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_nuw_mul x y name b] creates a
+ [%name = nuw mul %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateNUWMul]. *)
+val build_nuw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_fmul x y name b] creates a
+ [%name = fmul %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFMul]. *)
+val build_fmul : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_udiv x y name b] creates a
+ [%name = udiv %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateUDiv]. *)
+val build_udiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_sdiv x y name b] creates a
+ [%name = sdiv %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateSDiv]. *)
+val build_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_exact_sdiv x y name b] creates a
+ [%name = exact sdiv %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateExactSDiv]. *)
+val build_exact_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_fdiv x y name b] creates a
+ [%name = fdiv %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFDiv]. *)
+val build_fdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_urem x y name b] creates a
+ [%name = urem %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateURem]. *)
+val build_urem : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_SRem x y name b] creates a
+ [%name = srem %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateSRem]. *)
+val build_srem : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_frem x y name b] creates a
+ [%name = frem %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFRem]. *)
+val build_frem : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_shl x y name b] creates a
+ [%name = shl %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateShl]. *)
+val build_shl : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_lshr x y name b] creates a
+ [%name = lshr %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateLShr]. *)
+val build_lshr : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_ashr x y name b] creates a
+ [%name = ashr %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateAShr]. *)
+val build_ashr : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_and x y name b] creates a
+ [%name = and %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateAnd]. *)
+val build_and : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_or x y name b] creates a
+ [%name = or %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateOr]. *)
+val build_or : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_xor x y name b] creates a
+ [%name = xor %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateXor]. *)
+val build_xor : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_neg x name b] creates a
+ [%name = sub 0, %x]
+ instruction at the position specified by the instruction builder [b].
+ [-0.0] is used for floating point types to compute the correct sign.
+ See the method [llvm::LLVMBuilder::CreateNeg]. *)
+val build_neg : llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_nsw_neg x name b] creates a
+ [%name = nsw sub 0, %x]
+ instruction at the position specified by the instruction builder [b].
+ [-0.0] is used for floating point types to compute the correct sign.
+ See the method [llvm::LLVMBuilder::CreateNeg]. *)
+val build_nsw_neg : llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_nuw_neg x name b] creates a
+ [%name = nuw sub 0, %x]
+ instruction at the position specified by the instruction builder [b].
+ [-0.0] is used for floating point types to compute the correct sign.
+ See the method [llvm::LLVMBuilder::CreateNeg]. *)
+val build_nuw_neg : llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_fneg x name b] creates a
+ [%name = fsub 0, %x]
+ instruction at the position specified by the instruction builder [b].
+ [-0.0] is used for floating point types to compute the correct sign.
+ See the method [llvm::LLVMBuilder::CreateFNeg]. *)
+val build_fneg : llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_xor x name b] creates a
+ [%name = xor %x, -1]
+ instruction at the position specified by the instruction builder [b].
+ [-1] is the correct "all ones" value for the type of [x].
+ See the method [llvm::LLVMBuilder::CreateXor]. *)
+val build_not : llvalue -> string -> llbuilder -> llvalue
+
+
+
+(** {7 Memory} *)
+
+(** [build_alloca ty name b] creates a
+ [%name = alloca %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateAlloca]. *)
+val build_alloca : lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_array_alloca ty n name b] creates a
+ [%name = alloca %ty, %n]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateAlloca]. *)
+val build_array_alloca : lltype -> llvalue -> string -> llbuilder ->
+ llvalue
+
+(** [build_load v name b] creates a
+ [%name = load %v]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateLoad]. *)
+val build_load : llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_store v p b] creates a
+ [store %v, %p]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateStore]. *)
+val build_store : llvalue -> llvalue -> llbuilder -> llvalue
+
+
+(** [build_gep p indices name b] creates a
+ [%name = getelementptr %p, indices...]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateGetElementPtr]. *)
+val build_gep : llvalue -> llvalue array -> string -> llbuilder -> llvalue
+
+
+(** [build_in_bounds_gep p indices name b] creates a
+ [%name = gelementptr inbounds %p, indices...]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateInBoundsGetElementPtr]. *)
+val build_in_bounds_gep : llvalue -> llvalue array -> string -> llbuilder ->
+ llvalue
+
+(** [build_struct_gep p idx name b] creates a
+ [%name = getelementptr %p, 0, idx]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateStructGetElementPtr]. *)
+val build_struct_gep : llvalue -> int -> string -> llbuilder ->
+ llvalue
+
+(** [build_global_string str name b] creates a series of instructions that adds
+ a global string at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateGlobalString]. *)
+val build_global_string : string -> string -> llbuilder -> llvalue
+
+
+(** [build_global_stringptr str name b] creates a series of instructions that
+ adds a global string pointer at the position specified by the instruction
+ builder [b].
+ See the method [llvm::LLVMBuilder::CreateGlobalStringPtr]. *)
+val build_global_stringptr : string -> string -> llbuilder -> llvalue
+
+
+
+(** {7 Casts} *)
+
+(** [build_trunc v ty name b] creates a
+ [%name = trunc %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateTrunc]. *)
+val build_trunc : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_zext v ty name b] creates a
+ [%name = zext %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateZExt]. *)
+val build_zext : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_sext v ty name b] creates a
+ [%name = sext %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateSExt]. *)
+val build_sext : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_fptoui v ty name b] creates a
+ [%name = fptoui %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFPToUI]. *)
+val build_fptoui : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_fptosi v ty name b] creates a
+ [%name = fptosi %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFPToSI]. *)
+val build_fptosi : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_uitofp v ty name b] creates a
+ [%name = uitofp %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateUIToFP]. *)
+val build_uitofp : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_sitofp v ty name b] creates a
+ [%name = sitofp %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateSIToFP]. *)
+val build_sitofp : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_fptrunc v ty name b] creates a
+ [%name = fptrunc %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFPTrunc]. *)
+val build_fptrunc : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_fpext v ty name b] creates a
+ [%name = fpext %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFPExt]. *)
+val build_fpext : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_ptrtoint v ty name b] creates a
+ [%name = prtotint %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreatePtrToInt]. *)
+val build_ptrtoint : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_inttoptr v ty name b] creates a
+ [%name = inttoptr %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateIntToPtr]. *)
+val build_inttoptr : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_bitcast v ty name b] creates a
+ [%name = bitcast %p to %ty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateBitCast]. *)
+val build_bitcast : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_zext_or_bitcast v ty name b] creates a zext or bitcast
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateZExtOrBitCast]. *)
+val build_zext_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
+ llvalue
+
+(** [build_sext_or_bitcast v ty name b] creates a sext or bitcast
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateSExtOrBitCast]. *)
+val build_sext_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
+ llvalue
+
+(** [build_trunc_or_bitcast v ty name b] creates a trunc or bitcast
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateZExtOrBitCast]. *)
+val build_trunc_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
+ llvalue
+
+(** [build_pointercast v ty name b] creates a bitcast or pointer-to-int
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreatePointerCast]. *)
+val build_pointercast : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_intcast v ty name b] creates a zext, bitcast, or trunc
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateIntCast]. *)
+val build_intcast : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_fpcast v ty name b] creates a fpext, bitcast, or fptrunc
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFPCast]. *)
+val build_fpcast : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+
+(** {7 Comparisons} *)
+
+(** [build_icmp pred x y name b] creates a
+ [%name = icmp %pred %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateICmp]. *)
+val build_icmp : Icmp.t -> llvalue -> llvalue -> string ->
+ llbuilder -> llvalue
+
+(** [build_fcmp pred x y name b] creates a
+ [%name = fcmp %pred %x, %y]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateFCmp]. *)
+val build_fcmp : Fcmp.t -> llvalue -> llvalue -> string ->
+ llbuilder -> llvalue
+
+
+(** {7 Miscellaneous instructions} *)
+
+(** [build_phi incoming name b] creates a
+ [%name = phi %incoming]
+ instruction at the position specified by the instruction builder [b].
+ [incoming] is a list of [(llvalue, llbasicblock)] tuples.
+ See the method [llvm::LLVMBuilder::CreatePHI]. *)
+val build_phi : (llvalue * llbasicblock) list -> string -> llbuilder ->
+ llvalue
+
+(** [build_call fn args name b] creates a
+ [%name = call %fn(args...)]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateCall]. *)
+val build_call : llvalue -> llvalue array -> string -> llbuilder -> llvalue
+
+
+(** [build_select cond thenv elsev name b] creates a
+ [%name = select %cond, %thenv, %elsev]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateSelect]. *)
+val build_select : llvalue -> llvalue -> llvalue -> string -> llbuilder ->
+ llvalue
+
+(** [build_va_arg valist argty name b] creates a
+ [%name = va_arg %valist, %argty]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateVAArg]. *)
+val build_va_arg : llvalue -> lltype -> string -> llbuilder -> llvalue
+
+
+(** [build_extractelement vec i name b] creates a
+ [%name = extractelement %vec, %i]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateExtractElement]. *)
+val build_extractelement : llvalue -> llvalue -> string -> llbuilder ->
+ llvalue
+
+(** [build_insertelement vec elt i name b] creates a
+ [%name = insertelement %vec, %elt, %i]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateInsertElement]. *)
+val build_insertelement : llvalue -> llvalue -> llvalue -> string ->
+ llbuilder -> llvalue
+
+(** [build_shufflevector veca vecb mask name b] creates a
+ [%name = shufflevector %veca, %vecb, %mask]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateShuffleVector]. *)
+val build_shufflevector : llvalue -> llvalue -> llvalue -> string ->
+ llbuilder -> llvalue
+
+(** [build_insertvalue agg idx name b] creates a
+ [%name = extractvalue %agg, %idx]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateExtractValue]. *)
+val build_extractvalue : llvalue -> int -> string -> llbuilder -> llvalue
+
+
+(** [build_insertvalue agg val idx name b] creates a
+ [%name = insertvalue %agg, %val, %idx]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateInsertValue]. *)
+val build_insertvalue : llvalue -> llvalue -> int -> string -> llbuilder ->
+ llvalue
+
+(** [build_is_null val name b] creates a
+ [%name = icmp eq %val, null]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateIsNull]. *)
+val build_is_null : llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_is_not_null val name b] creates a
+ [%name = icmp ne %val, null]
+ instruction at the position specified by the instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreateIsNotNull]. *)
+val build_is_not_null : llvalue -> string -> llbuilder -> llvalue
+
+
+(** [build_ptrdiff lhs rhs name b] creates a series of instructions that measure
+ the difference between two pointer values at the position specified by the
+ instruction builder [b].
+ See the method [llvm::LLVMBuilder::CreatePtrDiff]. *)
+val build_ptrdiff : llvalue -> llvalue -> string -> llbuilder -> llvalue
+
+
+
+(** {6 Memory buffers} *)
+
+module MemoryBuffer : sig
+ (** [of_file p] is the memory buffer containing the contents of the file at
+ path [p]. If the file could not be read, then [IoError msg] is
+ raised. *)
+ val of_file : string -> llmemorybuffer
+
+ (** [stdin ()] is the memory buffer containing the contents of standard input.
+ If standard input is empty, then [IoError msg] is raised. *)
+ val of_stdin : unit -> llmemorybuffer
+
+ (** Disposes of a memory buffer. *)
+ val dispose : llmemorybuffer -> unit
+end
+
+
+(** {6 Pass Managers} *)
+
+module PassManager : sig
+ (** *)
+ type 'a t
+ type any = [ `Module | `Function ]
+
+ (** [PassManager.create ()] constructs a new whole-module pass pipeline. This
+ type of pipeline is suitable for link-time optimization and whole-module
+ transformations.
+ See the constructor of [llvm::PassManager]. *)
+ val create : unit -> [ `Module ] t
+
+ (** [PassManager.create_function m] constructs a new function-by-function
+ pass pipeline over the module [m]. It does not take ownership of [m].
+ This type of pipeline is suitable for code generation and JIT compilation
+ tasks.
+ See the constructor of [llvm::FunctionPassManager]. *)
+ val create_function : llmodule -> [ `Function ] t
+
+
+ (** [run_module m pm] initializes, executes on the module [m], and finalizes
+ all of the passes scheduled in the pass manager [pm]. Returns [true] if
+ any of the passes modified the module, [false] otherwise.
+ See the [llvm::PassManager::run] method. *)
+ val run_module : llmodule -> [ `Module ] t -> bool
+
+
+ (** [initialize fpm] initializes all of the function passes scheduled in the
+ function pass manager [fpm]. Returns [true] if any of the passes modified
+ the module, [false] otherwise.
+ See the [llvm::FunctionPassManager::doInitialization] method. *)
+ val initialize : [ `Function ] t -> bool
+
+ (** [run_function f fpm] executes all of the function passes scheduled in the
+ function pass manager [fpm] over the function [f]. Returns [true] if any
+ of the passes modified [f], [false] otherwise.
+ See the [llvm::FunctionPassManager::run] method. *)
+ val run_function : llvalue -> [ `Function ] t -> bool
+
+
+ (** [finalize fpm] finalizes all of the function passes scheduled in in the
+ function pass manager [fpm]. Returns [true] if any of the passes
+ modified the module, [false] otherwise.
+ See the [llvm::FunctionPassManager::doFinalization] method. *)
+ val finalize : [ `Function ] t -> bool
+
+ (** Frees the memory of a pass pipeline. For function pipelines, does not free
+ the module.
+ See the destructor of [llvm::BasePassManager]. *)
+ val dispose : [< any ] t -> unit
+end
diff --git a/bindings/ocaml/llvm/llvm_ocaml.c b/bindings/ocaml/llvm/llvm_ocaml.c
new file mode 100644
index 00000000000..c984bd154cc
--- /dev/null
+++ b/bindings/ocaml/llvm/llvm_ocaml.c
@@ -0,0 +1,2031 @@
+/*===-- llvm_ocaml.c - LLVM Ocaml Glue --------------------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file glues LLVM's ocaml interface to its C interface. These functions *|
+|* are by and large transparent wrappers to the corresponding C functions. *|
+|* *|
+|* Note that these functions intentionally take liberties with the CAMLparamX *|
+|* macros, since most of the parameters are not GC heap objects. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#include "llvm-c/Core.h"
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/memory.h"
+#include "caml/fail.h"
+#include "caml/callback.h"
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+
+
+/* Can't use the recommended caml_named_value mechanism for backwards
+ compatibility reasons. This is largely equivalent. */
+static value llvm_ioerror_exn;
+
+CAMLprim value llvm_register_core_exns(value IoError) {
+ llvm_ioerror_exn = Field(IoError, 0);
+ register_global_root(&llvm_ioerror_exn);
+ return Val_unit;
+}
+
+static void llvm_raise(value Prototype, char *Message) {
+ CAMLparam1(Prototype);
+ CAMLlocal1(CamlMessage);
+
+ CamlMessage = copy_string(Message);
+ LLVMDisposeMessage(Message);
+
+ raise_with_arg(Prototype, CamlMessage);
+ abort(); /* NOTREACHED */
+#ifdef CAMLnoreturn
+ CAMLnoreturn; /* Silences warnings, but is missing in some versions. */
+#endif
+}
+
+static value alloc_variant(int tag, void *Value) {
+ value Iter = alloc_small(1, tag);
+ Field(Iter, 0) = Val_op(Value);
+ return Iter;
+}
+
+/* Macro to convert the C first/next/last/prev idiom to the Ocaml llpos/
+ llrev_pos idiom. */
+#define DEFINE_ITERATORS(camlname, cname, pty, cty, pfun) \
+ /* llmodule -> ('a, 'b) llpos */ \
+ CAMLprim value llvm_##camlname##_begin(pty Mom) { \
+ cty First = LLVMGetFirst##cname(Mom); \
+ if (First) \
+ return alloc_variant(1, First); \
+ return alloc_variant(0, Mom); \
+ } \
+ \
+ /* llvalue -> ('a, 'b) llpos */ \
+ CAMLprim value llvm_##camlname##_succ(cty Kid) { \
+ cty Next = LLVMGetNext##cname(Kid); \
+ if (Next) \
+ return alloc_variant(1, Next); \
+ return alloc_variant(0, pfun(Kid)); \
+ } \
+ \
+ /* llmodule -> ('a, 'b) llrev_pos */ \
+ CAMLprim value llvm_##camlname##_end(pty Mom) { \
+ cty Last = LLVMGetLast##cname(Mom); \
+ if (Last) \
+ return alloc_variant(1, Last); \
+ return alloc_variant(0, Mom); \
+ } \
+ \
+ /* llvalue -> ('a, 'b) llrev_pos */ \
+ CAMLprim value llvm_##camlname##_pred(cty Kid) { \
+ cty Prev = LLVMGetPrevious##cname(Kid); \
+ if (Prev) \
+ return alloc_variant(1, Prev); \
+ return alloc_variant(0, pfun(Kid)); \
+ }
+
+
+/*===-- Contexts ----------------------------------------------------------===*/
+
+/* unit -> llcontext */
+CAMLprim LLVMContextRef llvm_create_context(value Unit) {
+ return LLVMContextCreate();
+}
+
+/* llcontext -> unit */
+CAMLprim value llvm_dispose_context(LLVMContextRef C) {
+ LLVMContextDispose(C);
+ return Val_unit;
+}
+
+/* unit -> llcontext */
+CAMLprim LLVMContextRef llvm_global_context(value Unit) {
+ return LLVMGetGlobalContext();
+}
+
+/* llcontext -> string -> int */
+CAMLprim value llvm_mdkind_id(LLVMContextRef C, value Name) {
+ unsigned MDKindID = LLVMGetMDKindIDInContext(C, String_val(Name),
+ caml_string_length(Name));
+ return Val_int(MDKindID);
+}
+
+/*===-- Modules -----------------------------------------------------------===*/
+
+/* llcontext -> string -> llmodule */
+CAMLprim LLVMModuleRef llvm_create_module(LLVMContextRef C, value ModuleID) {
+ return LLVMModuleCreateWithNameInContext(String_val(ModuleID), C);
+}
+
+/* llmodule -> unit */
+CAMLprim value llvm_dispose_module(LLVMModuleRef M) {
+ LLVMDisposeModule(M);
+ return Val_unit;
+}
+
+/* llmodule -> string */
+CAMLprim value llvm_target_triple(LLVMModuleRef M) {
+ return copy_string(LLVMGetTarget(M));
+}
+
+/* string -> llmodule -> unit */
+CAMLprim value llvm_set_target_triple(value Trip, LLVMModuleRef M) {
+ LLVMSetTarget(M, String_val(Trip));
+ return Val_unit;
+}
+
+/* llmodule -> string */
+CAMLprim value llvm_data_layout(LLVMModuleRef M) {
+ return copy_string(LLVMGetDataLayout(M));
+}
+
+/* string -> llmodule -> unit */
+CAMLprim value llvm_set_data_layout(value Layout, LLVMModuleRef M) {
+ LLVMSetDataLayout(M, String_val(Layout));
+ return Val_unit;
+}
+
+/* llmodule -> unit */
+CAMLprim value llvm_dump_module(LLVMModuleRef M) {
+ LLVMDumpModule(M);
+ return Val_unit;
+}
+
+/* llmodule -> string -> unit */
+CAMLprim value llvm_set_module_inline_asm(LLVMModuleRef M, value Asm) {
+ LLVMSetModuleInlineAsm(M, String_val(Asm));
+ return Val_unit;
+}
+
+/*===-- Types -------------------------------------------------------------===*/
+
+/* lltype -> TypeKind.t */
+CAMLprim value llvm_classify_type(LLVMTypeRef Ty) {
+ return Val_int(LLVMGetTypeKind(Ty));
+}
+
+CAMLprim value llvm_type_is_sized(LLVMTypeRef Ty) {
+ return Val_bool(LLVMTypeIsSized(Ty));
+}
+
+/* lltype -> llcontext */
+CAMLprim LLVMContextRef llvm_type_context(LLVMTypeRef Ty) {
+ return LLVMGetTypeContext(Ty);
+}
+
+/*--... Operations on integer types ........................................--*/
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_i1_type (LLVMContextRef Context) {
+ return LLVMInt1TypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_i8_type (LLVMContextRef Context) {
+ return LLVMInt8TypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_i16_type (LLVMContextRef Context) {
+ return LLVMInt16TypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_i32_type (LLVMContextRef Context) {
+ return LLVMInt32TypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_i64_type (LLVMContextRef Context) {
+ return LLVMInt64TypeInContext(Context);
+}
+
+/* llcontext -> int -> lltype */
+CAMLprim LLVMTypeRef llvm_integer_type(LLVMContextRef Context, value Width) {
+ return LLVMIntTypeInContext(Context, Int_val(Width));
+}
+
+/* lltype -> int */
+CAMLprim value llvm_integer_bitwidth(LLVMTypeRef IntegerTy) {
+ return Val_int(LLVMGetIntTypeWidth(IntegerTy));
+}
+
+/*--... Operations on real types ...........................................--*/
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_float_type(LLVMContextRef Context) {
+ return LLVMFloatTypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_double_type(LLVMContextRef Context) {
+ return LLVMDoubleTypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_x86fp80_type(LLVMContextRef Context) {
+ return LLVMX86FP80TypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_fp128_type(LLVMContextRef Context) {
+ return LLVMFP128TypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_ppc_fp128_type(LLVMContextRef Context) {
+ return LLVMPPCFP128TypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_x86mmx_type(LLVMContextRef Context) {
+ return LLVMX86MMXTypeInContext(Context);
+}
+
+/*--... Operations on function types .......................................--*/
+
+/* lltype -> lltype array -> lltype */
+CAMLprim LLVMTypeRef llvm_function_type(LLVMTypeRef RetTy, value ParamTys) {
+ return LLVMFunctionType(RetTy, (LLVMTypeRef *) ParamTys,
+ Wosize_val(ParamTys), 0);
+}
+
+/* lltype -> lltype array -> lltype */
+CAMLprim LLVMTypeRef llvm_var_arg_function_type(LLVMTypeRef RetTy,
+ value ParamTys) {
+ return LLVMFunctionType(RetTy, (LLVMTypeRef *) ParamTys,
+ Wosize_val(ParamTys), 1);
+}
+
+/* lltype -> bool */
+CAMLprim value llvm_is_var_arg(LLVMTypeRef FunTy) {
+ return Val_bool(LLVMIsFunctionVarArg(FunTy));
+}
+
+/* lltype -> lltype array */
+CAMLprim value llvm_param_types(LLVMTypeRef FunTy) {
+ value Tys = alloc(LLVMCountParamTypes(FunTy), 0);
+ LLVMGetParamTypes(FunTy, (LLVMTypeRef *) Tys);
+ return Tys;
+}
+
+/*--... Operations on struct types .........................................--*/
+
+/* llcontext -> lltype array -> lltype */
+CAMLprim LLVMTypeRef llvm_struct_type(LLVMContextRef C, value ElementTypes) {
+ return LLVMStructTypeInContext(C, (LLVMTypeRef *) ElementTypes,
+ Wosize_val(ElementTypes), 0);
+}
+
+/* llcontext -> lltype array -> lltype */
+CAMLprim LLVMTypeRef llvm_packed_struct_type(LLVMContextRef C,
+ value ElementTypes) {
+ return LLVMStructTypeInContext(C, (LLVMTypeRef *) ElementTypes,
+ Wosize_val(ElementTypes), 1);
+}
+
+/* llcontext -> string -> lltype */
+CAMLprim LLVMTypeRef llvm_named_struct_type(LLVMContextRef C,
+ value Name) {
+ return LLVMStructCreateNamed(C, String_val(Name));
+}
+
+CAMLprim value llvm_struct_set_body(LLVMTypeRef Ty,
+ value ElementTypes,
+ value Packed) {
+ LLVMStructSetBody(Ty, (LLVMTypeRef *) ElementTypes,
+ Wosize_val(ElementTypes), Bool_val(Packed));
+ return Val_unit;
+}
+
+/* lltype -> string option */
+CAMLprim value llvm_struct_name(LLVMTypeRef Ty)
+{
+ CAMLparam0();
+ const char *C = LLVMGetStructName(Ty);
+ if (C) {
+ CAMLlocal1(result);
+ result = caml_alloc_small(1, 0);
+ Store_field(result, 0, caml_copy_string(C));
+ CAMLreturn(result);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* lltype -> lltype array */
+CAMLprim value llvm_struct_element_types(LLVMTypeRef StructTy) {
+ value Tys = alloc(LLVMCountStructElementTypes(StructTy), 0);
+ LLVMGetStructElementTypes(StructTy, (LLVMTypeRef *) Tys);
+ return Tys;
+}
+
+/* lltype -> bool */
+CAMLprim value llvm_is_packed(LLVMTypeRef StructTy) {
+ return Val_bool(LLVMIsPackedStruct(StructTy));
+}
+
+/* lltype -> bool */
+CAMLprim value llvm_is_opaque(LLVMTypeRef StructTy) {
+ return Val_bool(LLVMIsOpaqueStruct(StructTy));
+}
+
+/*--... Operations on array, pointer, and vector types .....................--*/
+
+/* lltype -> int -> lltype */
+CAMLprim LLVMTypeRef llvm_array_type(LLVMTypeRef ElementTy, value Count) {
+ return LLVMArrayType(ElementTy, Int_val(Count));
+}
+
+/* lltype -> lltype */
+CAMLprim LLVMTypeRef llvm_pointer_type(LLVMTypeRef ElementTy) {
+ return LLVMPointerType(ElementTy, 0);
+}
+
+/* lltype -> int -> lltype */
+CAMLprim LLVMTypeRef llvm_qualified_pointer_type(LLVMTypeRef ElementTy,
+ value AddressSpace) {
+ return LLVMPointerType(ElementTy, Int_val(AddressSpace));
+}
+
+/* lltype -> int -> lltype */
+CAMLprim LLVMTypeRef llvm_vector_type(LLVMTypeRef ElementTy, value Count) {
+ return LLVMVectorType(ElementTy, Int_val(Count));
+}
+
+/* lltype -> int */
+CAMLprim value llvm_array_length(LLVMTypeRef ArrayTy) {
+ return Val_int(LLVMGetArrayLength(ArrayTy));
+}
+
+/* lltype -> int */
+CAMLprim value llvm_address_space(LLVMTypeRef PtrTy) {
+ return Val_int(LLVMGetPointerAddressSpace(PtrTy));
+}
+
+/* lltype -> int */
+CAMLprim value llvm_vector_size(LLVMTypeRef VectorTy) {
+ return Val_int(LLVMGetVectorSize(VectorTy));
+}
+
+/*--... Operations on other types ..........................................--*/
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_void_type (LLVMContextRef Context) {
+ return LLVMVoidTypeInContext(Context);
+}
+
+/* llcontext -> lltype */
+CAMLprim LLVMTypeRef llvm_label_type(LLVMContextRef Context) {
+ return LLVMLabelTypeInContext(Context);
+}
+
+CAMLprim value llvm_type_by_name(LLVMModuleRef M, value Name)
+{
+ CAMLparam1(Name);
+ LLVMTypeRef Ty = LLVMGetTypeByName(M, String_val(Name));
+ if (Ty) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = (value) Ty;
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/*===-- VALUES ------------------------------------------------------------===*/
+
+/* llvalue -> lltype */
+CAMLprim LLVMTypeRef llvm_type_of(LLVMValueRef Val) {
+ return LLVMTypeOf(Val);
+}
+
+/* keep in sync with ValueKind.t */
+enum ValueKind {
+ NullValue=0,
+ Argument,
+ BasicBlock,
+ InlineAsm,
+ MDNode,
+ MDString,
+ BlockAddress,
+ ConstantAggregateZero,
+ ConstantArray,
+ ConstantExpr,
+ ConstantFP,
+ ConstantInt,
+ ConstantPointerNull,
+ ConstantStruct,
+ ConstantVector,
+ Function,
+ GlobalAlias,
+ GlobalVariable,
+ UndefValue,
+ Instruction
+};
+
+/* llvalue -> ValueKind.t */
+#define DEFINE_CASE(Val, Kind) \
+ do {if (LLVMIsA##Kind(Val)) CAMLreturn(Val_int(Kind));} while(0)
+
+CAMLprim value llvm_classify_value(LLVMValueRef Val) {
+ CAMLparam0();
+ if (!Val)
+ CAMLreturn(Val_int(NullValue));
+ if (LLVMIsAConstant(Val)) {
+ DEFINE_CASE(Val, BlockAddress);
+ DEFINE_CASE(Val, ConstantAggregateZero);
+ DEFINE_CASE(Val, ConstantArray);
+ DEFINE_CASE(Val, ConstantExpr);
+ DEFINE_CASE(Val, ConstantFP);
+ DEFINE_CASE(Val, ConstantInt);
+ DEFINE_CASE(Val, ConstantPointerNull);
+ DEFINE_CASE(Val, ConstantStruct);
+ DEFINE_CASE(Val, ConstantVector);
+ }
+ if (LLVMIsAInstruction(Val)) {
+ CAMLlocal1(result);
+ result = caml_alloc_small(1, 0);
+ Store_field(result, 0, Val_int(LLVMGetInstructionOpcode(Val)));
+ CAMLreturn(result);
+ }
+ if (LLVMIsAGlobalValue(Val)) {
+ DEFINE_CASE(Val, Function);
+ DEFINE_CASE(Val, GlobalAlias);
+ DEFINE_CASE(Val, GlobalVariable);
+ }
+ DEFINE_CASE(Val, Argument);
+ DEFINE_CASE(Val, BasicBlock);
+ DEFINE_CASE(Val, InlineAsm);
+ DEFINE_CASE(Val, MDNode);
+ DEFINE_CASE(Val, MDString);
+ DEFINE_CASE(Val, UndefValue);
+ failwith("Unknown Value class");
+}
+
+/* llvalue -> string */
+CAMLprim value llvm_value_name(LLVMValueRef Val) {
+ return copy_string(LLVMGetValueName(Val));
+}
+
+/* string -> llvalue -> unit */
+CAMLprim value llvm_set_value_name(value Name, LLVMValueRef Val) {
+ LLVMSetValueName(Val, String_val(Name));
+ return Val_unit;
+}
+
+/* llvalue -> unit */
+CAMLprim value llvm_dump_value(LLVMValueRef Val) {
+ LLVMDumpValue(Val);
+ return Val_unit;
+}
+
+/*--... Operations on users ................................................--*/
+
+/* llvalue -> int -> llvalue */
+CAMLprim LLVMValueRef llvm_operand(LLVMValueRef V, value I) {
+ return LLVMGetOperand(V, Int_val(I));
+}
+
+/* llvalue -> int -> llvalue -> unit */
+CAMLprim value llvm_set_operand(LLVMValueRef U, value I, LLVMValueRef V) {
+ LLVMSetOperand(U, Int_val(I), V);
+ return Val_unit;
+}
+
+/* llvalue -> int */
+CAMLprim value llvm_num_operands(LLVMValueRef V) {
+ return Val_int(LLVMGetNumOperands(V));
+}
+
+/*--... Operations on constants of (mostly) any type .......................--*/
+
+/* llvalue -> bool */
+CAMLprim value llvm_is_constant(LLVMValueRef Val) {
+ return Val_bool(LLVMIsConstant(Val));
+}
+
+/* llvalue -> bool */
+CAMLprim value llvm_is_null(LLVMValueRef Val) {
+ return Val_bool(LLVMIsNull(Val));
+}
+
+/* llvalue -> bool */
+CAMLprim value llvm_is_undef(LLVMValueRef Val) {
+ return Val_bool(LLVMIsUndef(Val));
+}
+
+/* llvalue -> Opcode.t */
+CAMLprim value llvm_constexpr_get_opcode(LLVMValueRef Val) {
+ return LLVMIsAConstantExpr(Val) ?
+ Val_int(LLVMGetConstOpcode(Val)) : Val_int(0);
+}
+
+/*--... Operations on instructions .........................................--*/
+
+/* llvalue -> bool */
+CAMLprim value llvm_has_metadata(LLVMValueRef Val) {
+ return Val_bool(LLVMHasMetadata(Val));
+}
+
+/* llvalue -> int -> llvalue option */
+CAMLprim value llvm_metadata(LLVMValueRef Val, value MDKindID) {
+ CAMLparam1(MDKindID);
+ LLVMValueRef MD;
+ if ((MD = LLVMGetMetadata(Val, Int_val(MDKindID)))) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = (value) MD;
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* llvalue -> int -> llvalue -> unit */
+CAMLprim value llvm_set_metadata(LLVMValueRef Val, value MDKindID,
+ LLVMValueRef MD) {
+ LLVMSetMetadata(Val, Int_val(MDKindID), MD);
+ return Val_unit;
+}
+
+/* llvalue -> int -> unit */
+CAMLprim value llvm_clear_metadata(LLVMValueRef Val, value MDKindID) {
+ LLVMSetMetadata(Val, Int_val(MDKindID), NULL);
+ return Val_unit;
+}
+
+
+/*--... Operations on metadata .............................................--*/
+
+/* llcontext -> string -> llvalue */
+CAMLprim LLVMValueRef llvm_mdstring(LLVMContextRef C, value S) {
+ return LLVMMDStringInContext(C, String_val(S), caml_string_length(S));
+}
+
+/* llcontext -> llvalue array -> llvalue */
+CAMLprim LLVMValueRef llvm_mdnode(LLVMContextRef C, value ElementVals) {
+ return LLVMMDNodeInContext(C, (LLVMValueRef*) Op_val(ElementVals),
+ Wosize_val(ElementVals));
+}
+
+/* llvalue -> string option */
+CAMLprim value llvm_get_mdstring(LLVMValueRef V) {
+ CAMLparam0();
+ const char *S;
+ unsigned Len;
+
+ if ((S = LLVMGetMDString(V, &Len))) {
+ CAMLlocal2(Option, Str);
+
+ Str = caml_alloc_string(Len);
+ memcpy(String_val(Str), S, Len);
+ Option = alloc(1,0);
+ Store_field(Option, 0, Str);
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+CAMLprim value llvm_get_namedmd(LLVMModuleRef M, value name)
+{
+ CAMLparam1(name);
+ CAMLlocal1(Nodes);
+ Nodes = alloc(LLVMGetNamedMetadataNumOperands(M, String_val(name)), 0);
+ LLVMGetNamedMetadataOperands(M, String_val(name), (LLVMValueRef *) Nodes);
+ CAMLreturn(Nodes);
+}
+/*--... Operations on scalar constants .....................................--*/
+
+/* lltype -> int -> llvalue */
+CAMLprim LLVMValueRef llvm_const_int(LLVMTypeRef IntTy, value N) {
+ return LLVMConstInt(IntTy, (long long) Int_val(N), 1);
+}
+
+/* lltype -> Int64.t -> bool -> llvalue */
+CAMLprim LLVMValueRef llvm_const_of_int64(LLVMTypeRef IntTy, value N,
+ value SExt) {
+ return LLVMConstInt(IntTy, Int64_val(N), Bool_val(SExt));
+}
+
+/* llvalue -> Int64.t */
+CAMLprim value llvm_int64_of_const(LLVMValueRef Const)
+{
+ CAMLparam0();
+ if (LLVMIsAConstantInt(Const) &&
+ LLVMGetIntTypeWidth(LLVMTypeOf(Const)) <= 64) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = caml_copy_int64(LLVMConstIntGetSExtValue(Const));
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* lltype -> string -> int -> llvalue */
+CAMLprim LLVMValueRef llvm_const_int_of_string(LLVMTypeRef IntTy, value S,
+ value Radix) {
+ return LLVMConstIntOfStringAndSize(IntTy, String_val(S), caml_string_length(S),
+ Int_val(Radix));
+}
+
+/* lltype -> float -> llvalue */
+CAMLprim LLVMValueRef llvm_const_float(LLVMTypeRef RealTy, value N) {
+ return LLVMConstReal(RealTy, Double_val(N));
+}
+
+/* lltype -> string -> llvalue */
+CAMLprim LLVMValueRef llvm_const_float_of_string(LLVMTypeRef RealTy, value S) {
+ return LLVMConstRealOfStringAndSize(RealTy, String_val(S),
+ caml_string_length(S));
+}
+
+/*--... Operations on composite constants ..................................--*/
+
+/* llcontext -> string -> llvalue */
+CAMLprim LLVMValueRef llvm_const_string(LLVMContextRef Context, value Str,
+ value NullTerminate) {
+ return LLVMConstStringInContext(Context, String_val(Str), string_length(Str),
+ 1);
+}
+
+/* llcontext -> string -> llvalue */
+CAMLprim LLVMValueRef llvm_const_stringz(LLVMContextRef Context, value Str,
+ value NullTerminate) {
+ return LLVMConstStringInContext(Context, String_val(Str), string_length(Str),
+ 0);
+}
+
+/* lltype -> llvalue array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_array(LLVMTypeRef ElementTy,
+ value ElementVals) {
+ return LLVMConstArray(ElementTy, (LLVMValueRef*) Op_val(ElementVals),
+ Wosize_val(ElementVals));
+}
+
+/* llcontext -> llvalue array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_struct(LLVMContextRef C, value ElementVals) {
+ return LLVMConstStructInContext(C, (LLVMValueRef *) Op_val(ElementVals),
+ Wosize_val(ElementVals), 0);
+}
+
+/* lltype -> llvalue array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_named_struct(LLVMTypeRef Ty, value ElementVals) {
+ return LLVMConstNamedStruct(Ty, (LLVMValueRef *) Op_val(ElementVals), Wosize_val(ElementVals));
+}
+
+/* llcontext -> llvalue array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_packed_struct(LLVMContextRef C,
+ value ElementVals) {
+ return LLVMConstStructInContext(C, (LLVMValueRef *) Op_val(ElementVals),
+ Wosize_val(ElementVals), 1);
+}
+
+/* llvalue array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_vector(value ElementVals) {
+ return LLVMConstVector((LLVMValueRef*) Op_val(ElementVals),
+ Wosize_val(ElementVals));
+}
+
+/*--... Constant expressions ...............................................--*/
+
+/* Icmp.t -> llvalue -> llvalue -> llvalue */
+CAMLprim LLVMValueRef llvm_const_icmp(value Pred,
+ LLVMValueRef LHSConstant,
+ LLVMValueRef RHSConstant) {
+ return LLVMConstICmp(Int_val(Pred) + LLVMIntEQ, LHSConstant, RHSConstant);
+}
+
+/* Fcmp.t -> llvalue -> llvalue -> llvalue */
+CAMLprim LLVMValueRef llvm_const_fcmp(value Pred,
+ LLVMValueRef LHSConstant,
+ LLVMValueRef RHSConstant) {
+ return LLVMConstFCmp(Int_val(Pred), LHSConstant, RHSConstant);
+}
+
+/* llvalue -> llvalue array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_gep(LLVMValueRef ConstantVal, value Indices) {
+ return LLVMConstGEP(ConstantVal, (LLVMValueRef*) Op_val(Indices),
+ Wosize_val(Indices));
+}
+
+/* llvalue -> llvalue array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_in_bounds_gep(LLVMValueRef ConstantVal,
+ value Indices) {
+ return LLVMConstInBoundsGEP(ConstantVal, (LLVMValueRef*) Op_val(Indices),
+ Wosize_val(Indices));
+}
+
+/* llvalue -> int array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_extractvalue(LLVMValueRef Aggregate,
+ value Indices) {
+ CAMLparam1(Indices);
+ int size = Wosize_val(Indices);
+ int i;
+ LLVMValueRef result;
+
+ unsigned* idxs = (unsigned*)malloc(size * sizeof(unsigned));
+ for (i = 0; i < size; i++) {
+ idxs[i] = Int_val(Field(Indices, i));
+ }
+
+ result = LLVMConstExtractValue(Aggregate, idxs, size);
+ free(idxs);
+ CAMLreturnT(LLVMValueRef, result);
+}
+
+/* llvalue -> llvalue -> int array -> llvalue */
+CAMLprim LLVMValueRef llvm_const_insertvalue(LLVMValueRef Aggregate,
+ LLVMValueRef Val, value Indices) {
+ CAMLparam1(Indices);
+ int size = Wosize_val(Indices);
+ int i;
+ LLVMValueRef result;
+
+ unsigned* idxs = (unsigned*)malloc(size * sizeof(unsigned));
+ for (i = 0; i < size; i++) {
+ idxs[i] = Int_val(Field(Indices, i));
+ }
+
+ result = LLVMConstInsertValue(Aggregate, Val, idxs, size);
+ free(idxs);
+ CAMLreturnT(LLVMValueRef, result);
+}
+
+/* lltype -> string -> string -> bool -> bool -> llvalue */
+CAMLprim LLVMValueRef llvm_const_inline_asm(LLVMTypeRef Ty, value Asm,
+ value Constraints, value HasSideEffects,
+ value IsAlignStack) {
+ return LLVMConstInlineAsm(Ty, String_val(Asm), String_val(Constraints),
+ Bool_val(HasSideEffects), Bool_val(IsAlignStack));
+}
+
+/*--... Operations on global variables, functions, and aliases (globals) ...--*/
+
+/* llvalue -> bool */
+CAMLprim value llvm_is_declaration(LLVMValueRef Global) {
+ return Val_bool(LLVMIsDeclaration(Global));
+}
+
+/* llvalue -> Linkage.t */
+CAMLprim value llvm_linkage(LLVMValueRef Global) {
+ return Val_int(LLVMGetLinkage(Global));
+}
+
+/* Linkage.t -> llvalue -> unit */
+CAMLprim value llvm_set_linkage(value Linkage, LLVMValueRef Global) {
+ LLVMSetLinkage(Global, Int_val(Linkage));
+ return Val_unit;
+}
+
+/* llvalue -> string */
+CAMLprim value llvm_section(LLVMValueRef Global) {
+ return copy_string(LLVMGetSection(Global));
+}
+
+/* string -> llvalue -> unit */
+CAMLprim value llvm_set_section(value Section, LLVMValueRef Global) {
+ LLVMSetSection(Global, String_val(Section));
+ return Val_unit;
+}
+
+/* llvalue -> Visibility.t */
+CAMLprim value llvm_visibility(LLVMValueRef Global) {
+ return Val_int(LLVMGetVisibility(Global));
+}
+
+/* Visibility.t -> llvalue -> unit */
+CAMLprim value llvm_set_visibility(value Viz, LLVMValueRef Global) {
+ LLVMSetVisibility(Global, Int_val(Viz));
+ return Val_unit;
+}
+
+/* llvalue -> int */
+CAMLprim value llvm_alignment(LLVMValueRef Global) {
+ return Val_int(LLVMGetAlignment(Global));
+}
+
+/* int -> llvalue -> unit */
+CAMLprim value llvm_set_alignment(value Bytes, LLVMValueRef Global) {
+ LLVMSetAlignment(Global, Int_val(Bytes));
+ return Val_unit;
+}
+
+/*--... Operations on uses .................................................--*/
+
+/* llvalue -> lluse option */
+CAMLprim value llvm_use_begin(LLVMValueRef Val) {
+ CAMLparam0();
+ LLVMUseRef First;
+ if ((First = LLVMGetFirstUse(Val))) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = (value) First;
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* lluse -> lluse option */
+CAMLprim value llvm_use_succ(LLVMUseRef U) {
+ CAMLparam0();
+ LLVMUseRef Next;
+ if ((Next = LLVMGetNextUse(U))) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = (value) Next;
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* lluse -> llvalue */
+CAMLprim LLVMValueRef llvm_user(LLVMUseRef UR) {
+ return LLVMGetUser(UR);
+}
+
+/* lluse -> llvalue */
+CAMLprim LLVMValueRef llvm_used_value(LLVMUseRef UR) {
+ return LLVMGetUsedValue(UR);
+}
+
+/*--... Operations on global variables .....................................--*/
+
+DEFINE_ITERATORS(global, Global, LLVMModuleRef, LLVMValueRef,
+ LLVMGetGlobalParent)
+
+/* lltype -> string -> llmodule -> llvalue */
+CAMLprim LLVMValueRef llvm_declare_global(LLVMTypeRef Ty, value Name,
+ LLVMModuleRef M) {
+ LLVMValueRef GlobalVar;
+ if ((GlobalVar = LLVMGetNamedGlobal(M, String_val(Name)))) {
+ if (LLVMGetElementType(LLVMTypeOf(GlobalVar)) != Ty)
+ return LLVMConstBitCast(GlobalVar, LLVMPointerType(Ty, 0));
+ return GlobalVar;
+ }
+ return LLVMAddGlobal(M, Ty, String_val(Name));
+}
+
+/* lltype -> string -> int -> llmodule -> llvalue */
+CAMLprim LLVMValueRef llvm_declare_qualified_global(LLVMTypeRef Ty, value Name,
+ value AddressSpace,
+ LLVMModuleRef M) {
+ LLVMValueRef GlobalVar;
+ if ((GlobalVar = LLVMGetNamedGlobal(M, String_val(Name)))) {
+ if (LLVMGetElementType(LLVMTypeOf(GlobalVar)) != Ty)
+ return LLVMConstBitCast(GlobalVar,
+ LLVMPointerType(Ty, Int_val(AddressSpace)));
+ return GlobalVar;
+ }
+ return LLVMAddGlobal(M, Ty, String_val(Name));
+}
+
+/* string -> llmodule -> llvalue option */
+CAMLprim value llvm_lookup_global(value Name, LLVMModuleRef M) {
+ CAMLparam1(Name);
+ LLVMValueRef GlobalVar;
+ if ((GlobalVar = LLVMGetNamedGlobal(M, String_val(Name)))) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = (value) GlobalVar;
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* string -> llvalue -> llmodule -> llvalue */
+CAMLprim LLVMValueRef llvm_define_global(value Name, LLVMValueRef Initializer,
+ LLVMModuleRef M) {
+ LLVMValueRef GlobalVar = LLVMAddGlobal(M, LLVMTypeOf(Initializer),
+ String_val(Name));
+ LLVMSetInitializer(GlobalVar, Initializer);
+ return GlobalVar;
+}
+
+/* string -> llvalue -> int -> llmodule -> llvalue */
+CAMLprim LLVMValueRef llvm_define_qualified_global(value Name,
+ LLVMValueRef Initializer,
+ value AddressSpace,
+ LLVMModuleRef M) {
+ LLVMValueRef GlobalVar = LLVMAddGlobalInAddressSpace(M,
+ LLVMTypeOf(Initializer),
+ String_val(Name),
+ Int_val(AddressSpace));
+ LLVMSetInitializer(GlobalVar, Initializer);
+ return GlobalVar;
+}
+
+/* llvalue -> unit */
+CAMLprim value llvm_delete_global(LLVMValueRef GlobalVar) {
+ LLVMDeleteGlobal(GlobalVar);
+ return Val_unit;
+}
+
+/* llvalue -> llvalue -> unit */
+CAMLprim value llvm_set_initializer(LLVMValueRef ConstantVal,
+ LLVMValueRef GlobalVar) {
+ LLVMSetInitializer(GlobalVar, ConstantVal);
+ return Val_unit;
+}
+
+/* llvalue -> unit */
+CAMLprim value llvm_remove_initializer(LLVMValueRef GlobalVar) {
+ LLVMSetInitializer(GlobalVar, NULL);
+ return Val_unit;
+}
+
+/* llvalue -> bool */
+CAMLprim value llvm_is_thread_local(LLVMValueRef GlobalVar) {
+ return Val_bool(LLVMIsThreadLocal(GlobalVar));
+}
+
+/* bool -> llvalue -> unit */
+CAMLprim value llvm_set_thread_local(value IsThreadLocal,
+ LLVMValueRef GlobalVar) {
+ LLVMSetThreadLocal(GlobalVar, Bool_val(IsThreadLocal));
+ return Val_unit;
+}
+
+/* llvalue -> bool */
+CAMLprim value llvm_is_global_constant(LLVMValueRef GlobalVar) {
+ return Val_bool(LLVMIsGlobalConstant(GlobalVar));
+}
+
+/* bool -> llvalue -> unit */
+CAMLprim value llvm_set_global_constant(value Flag, LLVMValueRef GlobalVar) {
+ LLVMSetGlobalConstant(GlobalVar, Bool_val(Flag));
+ return Val_unit;
+}
+
+/*--... Operations on aliases ..............................................--*/
+
+CAMLprim LLVMValueRef llvm_add_alias(LLVMModuleRef M, LLVMTypeRef Ty,
+ LLVMValueRef Aliasee, value Name) {
+ return LLVMAddAlias(M, Ty, Aliasee, String_val(Name));
+}
+
+/*--... Operations on functions ............................................--*/
+
+DEFINE_ITERATORS(function, Function, LLVMModuleRef, LLVMValueRef,
+ LLVMGetGlobalParent)
+
+/* string -> lltype -> llmodule -> llvalue */
+CAMLprim LLVMValueRef llvm_declare_function(value Name, LLVMTypeRef Ty,
+ LLVMModuleRef M) {
+ LLVMValueRef Fn;
+ if ((Fn = LLVMGetNamedFunction(M, String_val(Name)))) {
+ if (LLVMGetElementType(LLVMTypeOf(Fn)) != Ty)
+ return LLVMConstBitCast(Fn, LLVMPointerType(Ty, 0));
+ return Fn;
+ }
+ return LLVMAddFunction(M, String_val(Name), Ty);
+}
+
+/* string -> llmodule -> llvalue option */
+CAMLprim value llvm_lookup_function(value Name, LLVMModuleRef M) {
+ CAMLparam1(Name);
+ LLVMValueRef Fn;
+ if ((Fn = LLVMGetNamedFunction(M, String_val(Name)))) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = (value) Fn;
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* string -> lltype -> llmodule -> llvalue */
+CAMLprim LLVMValueRef llvm_define_function(value Name, LLVMTypeRef Ty,
+ LLVMModuleRef M) {
+ LLVMValueRef Fn = LLVMAddFunction(M, String_val(Name), Ty);
+ LLVMAppendBasicBlockInContext(LLVMGetTypeContext(Ty), Fn, "entry");
+ return Fn;
+}
+
+/* llvalue -> unit */
+CAMLprim value llvm_delete_function(LLVMValueRef Fn) {
+ LLVMDeleteFunction(Fn);
+ return Val_unit;
+}
+
+/* llvalue -> bool */
+CAMLprim value llvm_is_intrinsic(LLVMValueRef Fn) {
+ return Val_bool(LLVMGetIntrinsicID(Fn));
+}
+
+/* llvalue -> int */
+CAMLprim value llvm_function_call_conv(LLVMValueRef Fn) {
+ return Val_int(LLVMGetFunctionCallConv(Fn));
+}
+
+/* int -> llvalue -> unit */
+CAMLprim value llvm_set_function_call_conv(value Id, LLVMValueRef Fn) {
+ LLVMSetFunctionCallConv(Fn, Int_val(Id));
+ return Val_unit;
+}
+
+/* llvalue -> string option */
+CAMLprim value llvm_gc(LLVMValueRef Fn) {
+ const char *GC;
+ CAMLparam0();
+ CAMLlocal2(Name, Option);
+
+ if ((GC = LLVMGetGC(Fn))) {
+ Name = copy_string(GC);
+
+ Option = alloc(1, 0);
+ Field(Option, 0) = Name;
+ CAMLreturn(Option);
+ } else {
+ CAMLreturn(Val_int(0));
+ }
+}
+
+/* string option -> llvalue -> unit */
+CAMLprim value llvm_set_gc(value GC, LLVMValueRef Fn) {
+ LLVMSetGC(Fn, GC == Val_int(0)? 0 : String_val(Field(GC, 0)));
+ return Val_unit;
+}
+
+/* llvalue -> int32 -> unit */
+CAMLprim value llvm_add_function_attr(LLVMValueRef Arg, value PA) {
+ LLVMAddFunctionAttr(Arg, Int32_val(PA));
+ return Val_unit;
+}
+
+/* llvalue -> int32 */
+CAMLprim value llvm_function_attr(LLVMValueRef Fn)
+{
+ CAMLparam0();
+ CAMLreturn(caml_copy_int32(LLVMGetFunctionAttr(Fn)));
+}
+
+/* llvalue -> int32 -> unit */
+CAMLprim value llvm_remove_function_attr(LLVMValueRef Arg, value PA) {
+ LLVMRemoveFunctionAttr(Arg, Int32_val(PA));
+ return Val_unit;
+}
+/*--... Operations on parameters ...........................................--*/
+
+DEFINE_ITERATORS(param, Param, LLVMValueRef, LLVMValueRef, LLVMGetParamParent)
+
+/* llvalue -> int -> llvalue */
+CAMLprim LLVMValueRef llvm_param(LLVMValueRef Fn, value Index) {
+ return LLVMGetParam(Fn, Int_val(Index));
+}
+
+/* llvalue -> int */
+CAMLprim value llvm_param_attr(LLVMValueRef Param)
+{
+ CAMLparam0();
+ CAMLreturn(caml_copy_int32(LLVMGetAttribute(Param)));
+}
+
+/* llvalue -> llvalue */
+CAMLprim value llvm_params(LLVMValueRef Fn) {
+ value Params = alloc(LLVMCountParams(Fn), 0);
+ LLVMGetParams(Fn, (LLVMValueRef *) Op_val(Params));
+ return Params;
+}
+
+/* llvalue -> int32 -> unit */
+CAMLprim value llvm_add_param_attr(LLVMValueRef Arg, value PA) {
+ LLVMAddAttribute(Arg, Int32_val(PA));
+ return Val_unit;
+}
+
+/* llvalue -> int32 -> unit */
+CAMLprim value llvm_remove_param_attr(LLVMValueRef Arg, value PA) {
+ LLVMRemoveAttribute(Arg, Int32_val(PA));
+ return Val_unit;
+}
+
+/* llvalue -> int -> unit */
+CAMLprim value llvm_set_param_alignment(LLVMValueRef Arg, value align) {
+ LLVMSetParamAlignment(Arg, Int_val(align));
+ return Val_unit;
+}
+
+/*--... Operations on basic blocks .........................................--*/
+
+DEFINE_ITERATORS(
+ block, BasicBlock, LLVMValueRef, LLVMBasicBlockRef, LLVMGetBasicBlockParent)
+
+/* llbasicblock -> llvalue option */
+CAMLprim value llvm_block_terminator(LLVMBasicBlockRef Block)
+{
+ CAMLparam0();
+ LLVMValueRef Term = LLVMGetBasicBlockTerminator(Block);
+ if (Term) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = (value) Term;
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* llvalue -> llbasicblock array */
+CAMLprim value llvm_basic_blocks(LLVMValueRef Fn) {
+ value MLArray = alloc(LLVMCountBasicBlocks(Fn), 0);
+ LLVMGetBasicBlocks(Fn, (LLVMBasicBlockRef *) Op_val(MLArray));
+ return MLArray;
+}
+
+/* llbasicblock -> unit */
+CAMLprim value llvm_delete_block(LLVMBasicBlockRef BB) {
+ LLVMDeleteBasicBlock(BB);
+ return Val_unit;
+}
+
+/* string -> llvalue -> llbasicblock */
+CAMLprim LLVMBasicBlockRef llvm_append_block(LLVMContextRef Context, value Name,
+ LLVMValueRef Fn) {
+ return LLVMAppendBasicBlockInContext(Context, Fn, String_val(Name));
+}
+
+/* string -> llbasicblock -> llbasicblock */
+CAMLprim LLVMBasicBlockRef llvm_insert_block(LLVMContextRef Context, value Name,
+ LLVMBasicBlockRef BB) {
+ return LLVMInsertBasicBlockInContext(Context, BB, String_val(Name));
+}
+
+/* llvalue -> bool */
+CAMLprim value llvm_value_is_block(LLVMValueRef Val) {
+ return Val_bool(LLVMValueIsBasicBlock(Val));
+}
+
+/*--... Operations on instructions .........................................--*/
+
+DEFINE_ITERATORS(instr, Instruction, LLVMBasicBlockRef, LLVMValueRef,
+ LLVMGetInstructionParent)
+
+/* llvalue -> Opcode.t */
+CAMLprim value llvm_instr_get_opcode(LLVMValueRef Inst) {
+ LLVMOpcode o;
+ if (!LLVMIsAInstruction(Inst))
+ failwith("Not an instruction");
+ o = LLVMGetInstructionOpcode(Inst);
+ assert (o <= LLVMLandingPad);
+ return Val_int(o);
+}
+
+/* llvalue -> ICmp.t */
+CAMLprim value llvm_instr_icmp_predicate(LLVMValueRef Val) {
+ CAMLparam0();
+ int x = LLVMGetICmpPredicate(Val);
+ if (x) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = Val_int(x - LLVMIntEQ);
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+
+/*--... Operations on call sites ...........................................--*/
+
+/* llvalue -> int */
+CAMLprim value llvm_instruction_call_conv(LLVMValueRef Inst) {
+ return Val_int(LLVMGetInstructionCallConv(Inst));
+}
+
+/* int -> llvalue -> unit */
+CAMLprim value llvm_set_instruction_call_conv(value CC, LLVMValueRef Inst) {
+ LLVMSetInstructionCallConv(Inst, Int_val(CC));
+ return Val_unit;
+}
+
+/* llvalue -> int -> int32 -> unit */
+CAMLprim value llvm_add_instruction_param_attr(LLVMValueRef Instr,
+ value index,
+ value PA) {
+ LLVMAddInstrAttribute(Instr, Int_val(index), Int32_val(PA));
+ return Val_unit;
+}
+
+/* llvalue -> int -> int32 -> unit */
+CAMLprim value llvm_remove_instruction_param_attr(LLVMValueRef Instr,
+ value index,
+ value PA) {
+ LLVMRemoveInstrAttribute(Instr, Int_val(index), Int32_val(PA));
+ return Val_unit;
+}
+
+/*--... Operations on call instructions (only) .............................--*/
+
+/* llvalue -> bool */
+CAMLprim value llvm_is_tail_call(LLVMValueRef CallInst) {
+ return Val_bool(LLVMIsTailCall(CallInst));
+}
+
+/* bool -> llvalue -> unit */
+CAMLprim value llvm_set_tail_call(value IsTailCall,
+ LLVMValueRef CallInst) {
+ LLVMSetTailCall(CallInst, Bool_val(IsTailCall));
+ return Val_unit;
+}
+
+/*--... Operations on phi nodes ............................................--*/
+
+/* (llvalue * llbasicblock) -> llvalue -> unit */
+CAMLprim value llvm_add_incoming(value Incoming, LLVMValueRef PhiNode) {
+ LLVMAddIncoming(PhiNode,
+ (LLVMValueRef*) &Field(Incoming, 0),
+ (LLVMBasicBlockRef*) &Field(Incoming, 1),
+ 1);
+ return Val_unit;
+}
+
+/* llvalue -> (llvalue * llbasicblock) list */
+CAMLprim value llvm_incoming(LLVMValueRef PhiNode) {
+ unsigned I;
+ CAMLparam0();
+ CAMLlocal3(Hd, Tl, Tmp);
+
+ /* Build a tuple list of them. */
+ Tl = Val_int(0);
+ for (I = LLVMCountIncoming(PhiNode); I != 0; ) {
+ Hd = alloc(2, 0);
+ Store_field(Hd, 0, (value) LLVMGetIncomingValue(PhiNode, --I));
+ Store_field(Hd, 1, (value) LLVMGetIncomingBlock(PhiNode, I));
+
+ Tmp = alloc(2, 0);
+ Store_field(Tmp, 0, Hd);
+ Store_field(Tmp, 1, Tl);
+ Tl = Tmp;
+ }
+
+ CAMLreturn(Tl);
+}
+
+/* llvalue -> unit */
+CAMLprim value llvm_delete_instruction(LLVMValueRef Instruction) {
+ LLVMInstructionEraseFromParent(Instruction);
+ return Val_unit;
+}
+
+/*===-- Instruction builders ----------------------------------------------===*/
+
+#define Builder_val(v) (*(LLVMBuilderRef *)(Data_custom_val(v)))
+
+static void llvm_finalize_builder(value B) {
+ LLVMDisposeBuilder(Builder_val(B));
+}
+
+static struct custom_operations builder_ops = {
+ (char *) "IRBuilder",
+ llvm_finalize_builder,
+ custom_compare_default,
+ custom_hash_default,
+ custom_serialize_default,
+ custom_deserialize_default
+#ifdef custom_compare_ext_default
+ , custom_compare_ext_default
+#endif
+};
+
+static value alloc_builder(LLVMBuilderRef B) {
+ value V = alloc_custom(&builder_ops, sizeof(LLVMBuilderRef), 0, 1);
+ Builder_val(V) = B;
+ return V;
+}
+
+/* llcontext -> llbuilder */
+CAMLprim value llvm_builder(LLVMContextRef C) {
+ return alloc_builder(LLVMCreateBuilderInContext(C));
+}
+
+/* (llbasicblock, llvalue) llpos -> llbuilder -> unit */
+CAMLprim value llvm_position_builder(value Pos, value B) {
+ if (Tag_val(Pos) == 0) {
+ LLVMBasicBlockRef BB = (LLVMBasicBlockRef) Op_val(Field(Pos, 0));
+ LLVMPositionBuilderAtEnd(Builder_val(B), BB);
+ } else {
+ LLVMValueRef I = (LLVMValueRef) Op_val(Field(Pos, 0));
+ LLVMPositionBuilderBefore(Builder_val(B), I);
+ }
+ return Val_unit;
+}
+
+/* llbuilder -> llbasicblock */
+CAMLprim LLVMBasicBlockRef llvm_insertion_block(value B) {
+ LLVMBasicBlockRef InsertBlock = LLVMGetInsertBlock(Builder_val(B));
+ if (!InsertBlock)
+ raise_not_found();
+ return InsertBlock;
+}
+
+/* llvalue -> string -> llbuilder -> unit */
+CAMLprim value llvm_insert_into_builder(LLVMValueRef I, value Name, value B) {
+ LLVMInsertIntoBuilderWithName(Builder_val(B), I, String_val(Name));
+ return Val_unit;
+}
+
+/*--... Metadata ...........................................................--*/
+
+/* llbuilder -> llvalue -> unit */
+CAMLprim value llvm_set_current_debug_location(value B, LLVMValueRef V) {
+ LLVMSetCurrentDebugLocation(Builder_val(B), V);
+ return Val_unit;
+}
+
+/* llbuilder -> unit */
+CAMLprim value llvm_clear_current_debug_location(value B) {
+ LLVMSetCurrentDebugLocation(Builder_val(B), NULL);
+ return Val_unit;
+}
+
+/* llbuilder -> llvalue option */
+CAMLprim value llvm_current_debug_location(value B) {
+ CAMLparam0();
+ LLVMValueRef L;
+ if ((L = LLVMGetCurrentDebugLocation(Builder_val(B)))) {
+ value Option = alloc(1, 0);
+ Field(Option, 0) = (value) L;
+ CAMLreturn(Option);
+ }
+ CAMLreturn(Val_int(0));
+}
+
+/* llbuilder -> llvalue -> unit */
+CAMLprim value llvm_set_inst_debug_location(value B, LLVMValueRef V) {
+ LLVMSetInstDebugLocation(Builder_val(B), V);
+ return Val_unit;
+}
+
+
+/*--... Terminators ........................................................--*/
+
+/* llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_ret_void(value B) {
+ return LLVMBuildRetVoid(Builder_val(B));
+}
+
+/* llvalue -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_ret(LLVMValueRef Val, value B) {
+ return LLVMBuildRet(Builder_val(B), Val);
+}
+
+/* llvalue array -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_aggregate_ret(value RetVals, value B) {
+ return LLVMBuildAggregateRet(Builder_val(B), (LLVMValueRef *) Op_val(RetVals),
+ Wosize_val(RetVals));
+}
+
+/* llbasicblock -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_br(LLVMBasicBlockRef BB, value B) {
+ return LLVMBuildBr(Builder_val(B), BB);
+}
+
+/* llvalue -> llbasicblock -> llbasicblock -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_cond_br(LLVMValueRef If,
+ LLVMBasicBlockRef Then,
+ LLVMBasicBlockRef Else,
+ value B) {
+ return LLVMBuildCondBr(Builder_val(B), If, Then, Else);
+}
+
+/* llvalue -> llbasicblock -> int -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_switch(LLVMValueRef Of,
+ LLVMBasicBlockRef Else,
+ value EstimatedCount,
+ value B) {
+ return LLVMBuildSwitch(Builder_val(B), Of, Else, Int_val(EstimatedCount));
+}
+
+/* lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_malloc(LLVMTypeRef Ty, value Name,
+ value B)
+{
+ return LLVMBuildMalloc(Builder_val(B), Ty, String_val(Name));
+}
+
+/* lltype -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_array_malloc(LLVMTypeRef Ty,
+ LLVMValueRef Val,
+ value Name, value B)
+{
+ return LLVMBuildArrayMalloc(Builder_val(B), Ty, Val, String_val(Name));
+}
+
+/* llvalue -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_free(LLVMValueRef P, value B)
+{
+ return LLVMBuildFree(Builder_val(B), P);
+}
+
+/* llvalue -> llvalue -> llbasicblock -> unit */
+CAMLprim value llvm_add_case(LLVMValueRef Switch, LLVMValueRef OnVal,
+ LLVMBasicBlockRef Dest) {
+ LLVMAddCase(Switch, OnVal, Dest);
+ return Val_unit;
+}
+
+/* llvalue -> llbasicblock -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_indirect_br(LLVMValueRef Addr,
+ value EstimatedDests,
+ value B) {
+ return LLVMBuildIndirectBr(Builder_val(B), Addr, EstimatedDests);
+}
+
+/* llvalue -> llvalue -> llbasicblock -> unit */
+CAMLprim value llvm_add_destination(LLVMValueRef IndirectBr,
+ LLVMBasicBlockRef Dest) {
+ LLVMAddDestination(IndirectBr, Dest);
+ return Val_unit;
+}
+
+/* llvalue -> llvalue array -> llbasicblock -> llbasicblock -> string ->
+ llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_invoke_nat(LLVMValueRef Fn, value Args,
+ LLVMBasicBlockRef Then,
+ LLVMBasicBlockRef Catch,
+ value Name, value B) {
+ return LLVMBuildInvoke(Builder_val(B), Fn, (LLVMValueRef *) Op_val(Args),
+ Wosize_val(Args), Then, Catch, String_val(Name));
+}
+
+/* llvalue -> llvalue array -> llbasicblock -> llbasicblock -> string ->
+ llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_invoke_bc(value Args[], int NumArgs) {
+ return llvm_build_invoke_nat((LLVMValueRef) Args[0], Args[1],
+ (LLVMBasicBlockRef) Args[2],
+ (LLVMBasicBlockRef) Args[3],
+ Args[4], Args[5]);
+}
+
+/* lltype -> llvalue -> int -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_landingpad(LLVMTypeRef Ty, LLVMValueRef PersFn,
+ value NumClauses, value Name,
+ value B) {
+ return LLVMBuildLandingPad(Builder_val(B), Ty, PersFn, Int_val(NumClauses),
+ String_val(Name));
+}
+
+/* llvalue -> llvalue -> unit */
+CAMLprim value llvm_add_clause(LLVMValueRef LandingPadInst, LLVMValueRef ClauseVal)
+{
+ LLVMAddClause(LandingPadInst, ClauseVal);
+ return Val_unit;
+}
+
+
+/* llvalue -> bool -> unit */
+CAMLprim value llvm_set_cleanup(LLVMValueRef LandingPadInst, value flag)
+{
+ LLVMSetCleanup(LandingPadInst, Bool_val(flag));
+ return Val_unit;
+}
+
+/* llvalue -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_resume(LLVMValueRef Exn, value B)
+{
+ return LLVMBuildResume(Builder_val(B), Exn);
+}
+
+/* llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_unreachable(value B) {
+ return LLVMBuildUnreachable(Builder_val(B));
+}
+
+/*--... Arithmetic .........................................................--*/
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_add(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildAdd(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_nsw_add(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildNSWAdd(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_nuw_add(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildNUWAdd(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fadd(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildFAdd(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_sub(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildSub(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_nsw_sub(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildNSWSub(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_nuw_sub(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildNUWSub(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fsub(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildFSub(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_mul(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildMul(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_nsw_mul(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildNSWMul(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_nuw_mul(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildNUWMul(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fmul(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildFMul(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_udiv(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildUDiv(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_sdiv(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildSDiv(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_exact_sdiv(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildExactSDiv(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fdiv(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildFDiv(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_urem(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildURem(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_srem(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildSRem(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_frem(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildFRem(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_shl(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildShl(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_lshr(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildLShr(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_ashr(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildAShr(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_and(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildAnd(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_or(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildOr(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_xor(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildXor(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+/* llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_neg(LLVMValueRef X,
+ value Name, value B) {
+ return LLVMBuildNeg(Builder_val(B), X, String_val(Name));
+}
+
+/* llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_nsw_neg(LLVMValueRef X,
+ value Name, value B) {
+ return LLVMBuildNSWNeg(Builder_val(B), X, String_val(Name));
+}
+
+/* llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_nuw_neg(LLVMValueRef X,
+ value Name, value B) {
+ return LLVMBuildNUWNeg(Builder_val(B), X, String_val(Name));
+}
+
+/* llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fneg(LLVMValueRef X,
+ value Name, value B) {
+ return LLVMBuildFNeg(Builder_val(B), X, String_val(Name));
+}
+
+/* llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_not(LLVMValueRef X,
+ value Name, value B) {
+ return LLVMBuildNot(Builder_val(B), X, String_val(Name));
+}
+
+/*--... Memory .............................................................--*/
+
+/* lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_alloca(LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildAlloca(Builder_val(B), Ty, String_val(Name));
+}
+
+/* lltype -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_array_alloca(LLVMTypeRef Ty, LLVMValueRef Size,
+ value Name, value B) {
+ return LLVMBuildArrayAlloca(Builder_val(B), Ty, Size, String_val(Name));
+}
+
+/* llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_load(LLVMValueRef Pointer,
+ value Name, value B) {
+ return LLVMBuildLoad(Builder_val(B), Pointer, String_val(Name));
+}
+
+/* llvalue -> llvalue -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_store(LLVMValueRef Value, LLVMValueRef Pointer,
+ value B) {
+ return LLVMBuildStore(Builder_val(B), Value, Pointer);
+}
+
+/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_gep(LLVMValueRef Pointer, value Indices,
+ value Name, value B) {
+ return LLVMBuildGEP(Builder_val(B), Pointer,
+ (LLVMValueRef *) Op_val(Indices), Wosize_val(Indices),
+ String_val(Name));
+}
+
+/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_in_bounds_gep(LLVMValueRef Pointer,
+ value Indices, value Name,
+ value B) {
+ return LLVMBuildInBoundsGEP(Builder_val(B), Pointer,
+ (LLVMValueRef *) Op_val(Indices),
+ Wosize_val(Indices), String_val(Name));
+}
+
+/* llvalue -> int -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_struct_gep(LLVMValueRef Pointer,
+ value Index, value Name,
+ value B) {
+ return LLVMBuildStructGEP(Builder_val(B), Pointer,
+ Int_val(Index), String_val(Name));
+}
+
+/* string -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_global_string(value Str, value Name, value B) {
+ return LLVMBuildGlobalString(Builder_val(B), String_val(Str),
+ String_val(Name));
+}
+
+/* string -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_global_stringptr(value Str, value Name,
+ value B) {
+ return LLVMBuildGlobalStringPtr(Builder_val(B), String_val(Str),
+ String_val(Name));
+}
+
+/*--... Casts ..............................................................--*/
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_trunc(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildTrunc(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_zext(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildZExt(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_sext(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildSExt(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fptoui(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildFPToUI(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fptosi(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildFPToSI(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_uitofp(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildUIToFP(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_sitofp(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildSIToFP(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fptrunc(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildFPTrunc(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fpext(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildFPExt(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_prttoint(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildPtrToInt(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_inttoptr(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildIntToPtr(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_bitcast(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildBitCast(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_zext_or_bitcast(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildZExtOrBitCast(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_sext_or_bitcast(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildSExtOrBitCast(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_trunc_or_bitcast(LLVMValueRef X,
+ LLVMTypeRef Ty, value Name,
+ value B) {
+ return LLVMBuildTruncOrBitCast(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_pointercast(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildPointerCast(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_intcast(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildIntCast(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fpcast(LLVMValueRef X, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildFPCast(Builder_val(B), X, Ty, String_val(Name));
+}
+
+/*--... Comparisons ........................................................--*/
+
+/* Icmp.t -> llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_icmp(value Pred,
+ LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildICmp(Builder_val(B), Int_val(Pred) + LLVMIntEQ, LHS, RHS,
+ String_val(Name));
+}
+
+/* Fcmp.t -> llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_fcmp(value Pred,
+ LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildFCmp(Builder_val(B), Int_val(Pred), LHS, RHS,
+ String_val(Name));
+}
+
+/*--... Miscellaneous instructions .........................................--*/
+
+/* (llvalue * llbasicblock) list -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_phi(value Incoming, value Name, value B) {
+ value Hd, Tl;
+ LLVMValueRef FirstValue, PhiNode;
+
+ assert(Incoming != Val_int(0) && "Empty list passed to Llvm.build_phi!");
+
+ Hd = Field(Incoming, 0);
+ FirstValue = (LLVMValueRef) Field(Hd, 0);
+ PhiNode = LLVMBuildPhi(Builder_val(B), LLVMTypeOf(FirstValue),
+ String_val(Name));
+
+ for (Tl = Incoming; Tl != Val_int(0); Tl = Field(Tl, 1)) {
+ value Hd = Field(Tl, 0);
+ LLVMAddIncoming(PhiNode, (LLVMValueRef*) &Field(Hd, 0),
+ (LLVMBasicBlockRef*) &Field(Hd, 1), 1);
+ }
+
+ return PhiNode;
+}
+
+/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_call(LLVMValueRef Fn, value Params,
+ value Name, value B) {
+ return LLVMBuildCall(Builder_val(B), Fn, (LLVMValueRef *) Op_val(Params),
+ Wosize_val(Params), String_val(Name));
+}
+
+/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_select(LLVMValueRef If,
+ LLVMValueRef Then, LLVMValueRef Else,
+ value Name, value B) {
+ return LLVMBuildSelect(Builder_val(B), If, Then, Else, String_val(Name));
+}
+
+/* llvalue -> lltype -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_va_arg(LLVMValueRef List, LLVMTypeRef Ty,
+ value Name, value B) {
+ return LLVMBuildVAArg(Builder_val(B), List, Ty, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_extractelement(LLVMValueRef Vec,
+ LLVMValueRef Idx,
+ value Name, value B) {
+ return LLVMBuildExtractElement(Builder_val(B), Vec, Idx, String_val(Name));
+}
+
+/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_insertelement(LLVMValueRef Vec,
+ LLVMValueRef Element,
+ LLVMValueRef Idx,
+ value Name, value B) {
+ return LLVMBuildInsertElement(Builder_val(B), Vec, Element, Idx,
+ String_val(Name));
+}
+
+/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_shufflevector(LLVMValueRef V1, LLVMValueRef V2,
+ LLVMValueRef Mask,
+ value Name, value B) {
+ return LLVMBuildShuffleVector(Builder_val(B), V1, V2, Mask, String_val(Name));
+}
+
+/* llvalue -> int -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_extractvalue(LLVMValueRef Aggregate,
+ value Idx, value Name, value B) {
+ return LLVMBuildExtractValue(Builder_val(B), Aggregate, Int_val(Idx),
+ String_val(Name));
+}
+
+/* llvalue -> llvalue -> int -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_insertvalue(LLVMValueRef Aggregate,
+ LLVMValueRef Val, value Idx,
+ value Name, value B) {
+ return LLVMBuildInsertValue(Builder_val(B), Aggregate, Val, Int_val(Idx),
+ String_val(Name));
+}
+
+/* llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_is_null(LLVMValueRef Val, value Name,
+ value B) {
+ return LLVMBuildIsNull(Builder_val(B), Val, String_val(Name));
+}
+
+/* llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_is_not_null(LLVMValueRef Val, value Name,
+ value B) {
+ return LLVMBuildIsNotNull(Builder_val(B), Val, String_val(Name));
+}
+
+/* llvalue -> llvalue -> string -> llbuilder -> llvalue */
+CAMLprim LLVMValueRef llvm_build_ptrdiff(LLVMValueRef LHS, LLVMValueRef RHS,
+ value Name, value B) {
+ return LLVMBuildPtrDiff(Builder_val(B), LHS, RHS, String_val(Name));
+}
+
+
+/*===-- Memory buffers ----------------------------------------------------===*/
+
+/* string -> llmemorybuffer
+ raises IoError msg on error */
+CAMLprim value llvm_memorybuffer_of_file(value Path) {
+ CAMLparam1(Path);
+ char *Message;
+ LLVMMemoryBufferRef MemBuf;
+
+ if (LLVMCreateMemoryBufferWithContentsOfFile(String_val(Path),
+ &MemBuf, &Message))
+ llvm_raise(llvm_ioerror_exn, Message);
+
+ CAMLreturn((value) MemBuf);
+}
+
+/* unit -> llmemorybuffer
+ raises IoError msg on error */
+CAMLprim LLVMMemoryBufferRef llvm_memorybuffer_of_stdin(value Unit) {
+ char *Message;
+ LLVMMemoryBufferRef MemBuf;
+
+ if (LLVMCreateMemoryBufferWithSTDIN(&MemBuf, &Message))
+ llvm_raise(llvm_ioerror_exn, Message);
+
+ return MemBuf;
+}
+
+/* llmemorybuffer -> unit */
+CAMLprim value llvm_memorybuffer_dispose(LLVMMemoryBufferRef MemBuf) {
+ LLVMDisposeMemoryBuffer(MemBuf);
+ return Val_unit;
+}
+
+/*===-- Pass Managers -----------------------------------------------------===*/
+
+/* unit -> [ `Module ] PassManager.t */
+CAMLprim LLVMPassManagerRef llvm_passmanager_create(value Unit) {
+ return LLVMCreatePassManager();
+}
+
+/* llmodule -> [ `Function ] PassManager.t -> bool */
+CAMLprim value llvm_passmanager_run_module(LLVMModuleRef M,
+ LLVMPassManagerRef PM) {
+ return Val_bool(LLVMRunPassManager(PM, M));
+}
+
+/* [ `Function ] PassManager.t -> bool */
+CAMLprim value llvm_passmanager_initialize(LLVMPassManagerRef FPM) {
+ return Val_bool(LLVMInitializeFunctionPassManager(FPM));
+}
+
+/* llvalue -> [ `Function ] PassManager.t -> bool */
+CAMLprim value llvm_passmanager_run_function(LLVMValueRef F,
+ LLVMPassManagerRef FPM) {
+ return Val_bool(LLVMRunFunctionPassManager(FPM, F));
+}
+
+/* [ `Function ] PassManager.t -> bool */
+CAMLprim value llvm_passmanager_finalize(LLVMPassManagerRef FPM) {
+ return Val_bool(LLVMFinalizeFunctionPassManager(FPM));
+}
+
+/* PassManager.any PassManager.t -> unit */
+CAMLprim value llvm_passmanager_dispose(LLVMPassManagerRef PM) {
+ LLVMDisposePassManager(PM);
+ return Val_unit;
+}
diff --git a/bindings/ocaml/target/Makefile b/bindings/ocaml/target/Makefile
new file mode 100644
index 00000000000..3c48cd8fc20
--- /dev/null
+++ b/bindings/ocaml/target/Makefile
@@ -0,0 +1,19 @@
+##===- bindings/ocaml/target/Makefile ----------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml Llvm_target interface.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+LIBRARYNAME := llvm_target
+UsedComponents := target
+UsedOcamlInterfaces := llvm
+
+include ../Makefile.ocaml
diff --git a/bindings/ocaml/target/llvm_target.ml b/bindings/ocaml/target/llvm_target.ml
new file mode 100644
index 00000000000..49940eec480
--- /dev/null
+++ b/bindings/ocaml/target/llvm_target.ml
@@ -0,0 +1,42 @@
+(*===-- llvm_target.ml - LLVM Ocaml Interface ------------------*- OCaml -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+module Endian = struct
+ type t =
+ | Big
+ | Little
+end
+
+module TargetData = struct
+ type t
+
+ external create : string -> t = "llvm_targetdata_create"
+ external add : t -> [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_targetdata_add"
+ external as_string : t -> string = "llvm_targetdata_as_string"
+ external dispose : t -> unit = "llvm_targetdata_dispose"
+end
+
+external byte_order : TargetData.t -> Endian.t = "llvm_byte_order"
+external pointer_size : TargetData.t -> int = "llvm_pointer_size"
+external intptr_type : TargetData.t -> Llvm.lltype = "LLVMIntPtrType"
+external size_in_bits : TargetData.t -> Llvm.lltype -> Int64.t
+ = "llvm_size_in_bits"
+external store_size : TargetData.t -> Llvm.lltype -> Int64.t = "llvm_store_size"
+external abi_size : TargetData.t -> Llvm.lltype -> Int64.t = "llvm_abi_size"
+external abi_align : TargetData.t -> Llvm.lltype -> int = "llvm_abi_align"
+external stack_align : TargetData.t -> Llvm.lltype -> int = "llvm_stack_align"
+external preferred_align : TargetData.t -> Llvm.lltype -> int
+ = "llvm_preferred_align"
+external preferred_align_of_global : TargetData.t -> Llvm.llvalue -> int
+ = "llvm_preferred_align_of_global"
+external element_at_offset : TargetData.t -> Llvm.lltype -> Int64.t -> int
+ = "llvm_element_at_offset"
+external offset_of_element : TargetData.t -> Llvm.lltype -> int -> Int64.t
+ = "llvm_offset_of_element"
diff --git a/bindings/ocaml/target/llvm_target.mli b/bindings/ocaml/target/llvm_target.mli
new file mode 100644
index 00000000000..c288b9ac2d9
--- /dev/null
+++ b/bindings/ocaml/target/llvm_target.mli
@@ -0,0 +1,95 @@
+(*===-- llvm_target.mli - LLVM Ocaml Interface -----------------*- OCaml -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** Target Information.
+
+ This interface provides an ocaml API for LLVM target information,
+ the classes in the Target library. *)
+
+module Endian : sig
+ type t =
+ | Big
+ | Little
+end
+
+module TargetData : sig
+ type t
+
+ (** [TargetData.create rep] parses the target data string representation [rep].
+ See the constructor llvm::TargetData::TargetData. *)
+ external create : string -> t = "llvm_targetdata_create"
+
+ (** [add_target_data td pm] adds the target data [td] to the pass manager [pm].
+ Does not take ownership of the target data.
+ See the method llvm::PassManagerBase::add. *)
+ external add : t -> [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_targetdata_add"
+
+ (** [as_string td] is the string representation of the target data [td].
+ See the constructor llvm::TargetData::TargetData. *)
+ external as_string : t -> string = "llvm_targetdata_as_string"
+
+ (** Deallocates a TargetData.
+ See the destructor llvm::TargetData::~TargetData. *)
+ external dispose : t -> unit = "llvm_targetdata_dispose"
+end
+
+(** Returns the byte order of a target, either LLVMBigEndian or
+ LLVMLittleEndian.
+ See the method llvm::TargetData::isLittleEndian. *)
+external byte_order : TargetData.t -> Endian.t = "llvm_byte_order"
+
+(** Returns the pointer size in bytes for a target.
+ See the method llvm::TargetData::getPointerSize. *)
+external pointer_size : TargetData.t -> int = "llvm_pointer_size"
+
+(** Returns the integer type that is the same size as a pointer on a target.
+ See the method llvm::TargetData::getIntPtrType. *)
+external intptr_type : TargetData.t -> Llvm.lltype = "LLVMIntPtrType"
+
+(** Computes the size of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeSizeInBits. *)
+external size_in_bits : TargetData.t -> Llvm.lltype -> Int64.t
+ = "llvm_size_in_bits"
+
+(** Computes the storage size of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeStoreSize. *)
+external store_size : TargetData.t -> Llvm.lltype -> Int64.t = "llvm_store_size"
+
+(** Computes the ABI size of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeAllocSize. *)
+external abi_size : TargetData.t -> Llvm.lltype -> Int64.t = "llvm_abi_size"
+
+(** Computes the ABI alignment of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeABISize. *)
+external abi_align : TargetData.t -> Llvm.lltype -> int = "llvm_abi_align"
+
+(** Computes the call frame alignment of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeABISize. *)
+external stack_align : TargetData.t -> Llvm.lltype -> int = "llvm_stack_align"
+
+(** Computes the preferred alignment of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeABISize. *)
+external preferred_align : TargetData.t -> Llvm.lltype -> int
+ = "llvm_preferred_align"
+
+(** Computes the preferred alignment of a global variable in bytes for a target.
+ See the method llvm::TargetData::getPreferredAlignment. *)
+external preferred_align_of_global : TargetData.t -> Llvm.llvalue -> int
+ = "llvm_preferred_align_of_global"
+
+(** Computes the structure element that contains the byte offset for a target.
+ See the method llvm::StructLayout::getElementContainingOffset. *)
+external element_at_offset : TargetData.t -> Llvm.lltype -> Int64.t -> int
+ = "llvm_element_at_offset"
+
+(** Computes the byte offset of the indexed struct element for a target.
+ See the method llvm::StructLayout::getElementContainingOffset. *)
+external offset_of_element : TargetData.t -> Llvm.lltype -> int -> Int64.t
+ = "llvm_offset_of_element"
diff --git a/bindings/ocaml/target/target_ocaml.c b/bindings/ocaml/target/target_ocaml.c
new file mode 100644
index 00000000000..ca01e7786b6
--- /dev/null
+++ b/bindings/ocaml/target/target_ocaml.c
@@ -0,0 +1,102 @@
+/*===-- target_ocaml.c - LLVM Ocaml Glue ------------------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file glues LLVM's ocaml interface to its C interface. These functions *|
+|* are by and large transparent wrappers to the corresponding C functions. *|
+|* *|
+|* Note that these functions intentionally take liberties with the CAMLparamX *|
+|* macros, since most of the parameters are not GC heap objects. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#include "llvm-c/Target.h"
+#include "caml/alloc.h"
+
+/* string -> TargetData.t */
+CAMLprim LLVMTargetDataRef llvm_targetdata_create(value StringRep) {
+ return LLVMCreateTargetData(String_val(StringRep));
+}
+
+/* TargetData.t -> [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_targetdata_add(LLVMTargetDataRef TD, LLVMPassManagerRef PM){
+ LLVMAddTargetData(TD, PM);
+ return Val_unit;
+}
+
+/* TargetData.t -> string */
+CAMLprim value llvm_targetdata_as_string(LLVMTargetDataRef TD) {
+ char *StringRep = LLVMCopyStringRepOfTargetData(TD);
+ value Copy = copy_string(StringRep);
+ LLVMDisposeMessage(StringRep);
+ return Copy;
+}
+
+/* TargetData.t -> unit */
+CAMLprim value llvm_targetdata_dispose(LLVMTargetDataRef TD) {
+ LLVMDisposeTargetData(TD);
+ return Val_unit;
+}
+
+/* TargetData.t -> Endian.t */
+CAMLprim value llvm_byte_order(LLVMTargetDataRef TD) {
+ return Val_int(LLVMByteOrder(TD));
+}
+
+/* TargetData.t -> int */
+CAMLprim value llvm_pointer_size(LLVMTargetDataRef TD) {
+ return Val_int(LLVMPointerSize(TD));
+}
+
+/* TargetData.t -> Llvm.lltype -> Int64.t */
+CAMLprim value llvm_size_in_bits(LLVMTargetDataRef TD, LLVMTypeRef Ty) {
+ return caml_copy_int64(LLVMSizeOfTypeInBits(TD, Ty));
+}
+
+/* TargetData.t -> Llvm.lltype -> Int64.t */
+CAMLprim value llvm_store_size(LLVMTargetDataRef TD, LLVMTypeRef Ty) {
+ return caml_copy_int64(LLVMStoreSizeOfType(TD, Ty));
+}
+
+/* TargetData.t -> Llvm.lltype -> Int64.t */
+CAMLprim value llvm_abi_size(LLVMTargetDataRef TD, LLVMTypeRef Ty) {
+ return caml_copy_int64(LLVMABISizeOfType(TD, Ty));
+}
+
+/* TargetData.t -> Llvm.lltype -> int */
+CAMLprim value llvm_abi_align(LLVMTargetDataRef TD, LLVMTypeRef Ty) {
+ return Val_int(LLVMABIAlignmentOfType(TD, Ty));
+}
+
+/* TargetData.t -> Llvm.lltype -> int */
+CAMLprim value llvm_stack_align(LLVMTargetDataRef TD, LLVMTypeRef Ty) {
+ return Val_int(LLVMCallFrameAlignmentOfType(TD, Ty));
+}
+
+/* TargetData.t -> Llvm.lltype -> int */
+CAMLprim value llvm_preferred_align(LLVMTargetDataRef TD, LLVMTypeRef Ty) {
+ return Val_int(LLVMPreferredAlignmentOfType(TD, Ty));
+}
+
+/* TargetData.t -> Llvm.llvalue -> int */
+CAMLprim value llvm_preferred_align_of_global(LLVMTargetDataRef TD,
+ LLVMValueRef GlobalVar) {
+ return Val_int(LLVMPreferredAlignmentOfGlobal(TD, GlobalVar));
+}
+
+/* TargetData.t -> Llvm.lltype -> Int64.t -> int */
+CAMLprim value llvm_element_at_offset(LLVMTargetDataRef TD, LLVMTypeRef Ty,
+ value Offset) {
+ return Val_int(LLVMElementAtOffset(TD, Ty, Int_val(Offset)));
+}
+
+/* TargetData.t -> Llvm.lltype -> int -> Int64.t */
+CAMLprim value llvm_offset_of_element(LLVMTargetDataRef TD, LLVMTypeRef Ty,
+ value Index) {
+ return caml_copy_int64(LLVMOffsetOfElement(TD, Ty, Int_val(Index)));
+}
diff --git a/bindings/ocaml/transforms/Makefile b/bindings/ocaml/transforms/Makefile
new file mode 100644
index 00000000000..05fcd90097f
--- /dev/null
+++ b/bindings/ocaml/transforms/Makefile
@@ -0,0 +1,18 @@
+##===- bindings/ocaml/transforms/Makefile ------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+DIRS = scalar ipo
+
+ocamldoc:
+ $(Verb) for i in $(DIRS) ; do \
+ $(MAKE) -C $$i ocamldoc; \
+ done
+
+include $(LEVEL)/Makefile.common
diff --git a/bindings/ocaml/transforms/ipo/Makefile b/bindings/ocaml/transforms/ipo/Makefile
new file mode 100644
index 00000000000..130d74c9060
--- /dev/null
+++ b/bindings/ocaml/transforms/ipo/Makefile
@@ -0,0 +1,20 @@
+##===- bindings/ocaml/transforms/scalar/Makefile -----------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml Llvm_scalar_opts interface.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../../..
+LIBRARYNAME := llvm_ipo
+DONT_BUILD_RELINKED := 1
+UsedComponents := ipo
+UsedOcamlInterfaces := llvm
+
+include ../../Makefile.ocaml
diff --git a/bindings/ocaml/transforms/ipo/ipo_ocaml.c b/bindings/ocaml/transforms/ipo/ipo_ocaml.c
new file mode 100644
index 00000000000..612015c099a
--- /dev/null
+++ b/bindings/ocaml/transforms/ipo/ipo_ocaml.c
@@ -0,0 +1,104 @@
+/*===-- ipo_ocaml.c - LLVM Ocaml Glue -------------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file glues LLVM's ocaml interface to its C interface. These functions *|
+|* are by and large transparent wrappers to the corresponding C functions. *|
+|* *|
+|* Note that these functions intentionally take liberties with the CAMLparamX *|
+|* macros, since most of the parameters are not GC heap objects. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#include "llvm-c/Transforms/IPO.h"
+#include "caml/mlvalues.h"
+#include "caml/misc.h"
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_argument_promotion(LLVMPassManagerRef PM) {
+ LLVMAddArgumentPromotionPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_constant_merge(LLVMPassManagerRef PM) {
+ LLVMAddConstantMergePass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_dead_arg_elimination(LLVMPassManagerRef PM) {
+ LLVMAddDeadArgEliminationPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_function_attrs(LLVMPassManagerRef PM) {
+ LLVMAddFunctionAttrsPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_function_inlining(LLVMPassManagerRef PM) {
+ LLVMAddFunctionInliningPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_always_inliner_pass(LLVMPassManagerRef PM) {
+ LLVMAddAlwaysInlinerPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_global_dce(LLVMPassManagerRef PM) {
+ LLVMAddGlobalDCEPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_global_optimizer(LLVMPassManagerRef PM) {
+ LLVMAddGlobalOptimizerPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_ipc_propagation(LLVMPassManagerRef PM) {
+ LLVMAddIPConstantPropagationPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_prune_eh(LLVMPassManagerRef PM) {
+ LLVMAddPruneEHPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_ipsccp(LLVMPassManagerRef PM) {
+ LLVMAddIPSCCPPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> bool -> unit */
+CAMLprim value llvm_add_internalize(LLVMPassManagerRef PM, value AllButMain) {
+ LLVMAddInternalizePass(PM, Bool_val(AllButMain));
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_strip_dead_prototypes(LLVMPassManagerRef PM) {
+ LLVMAddStripDeadPrototypesPass(PM);
+ return Val_unit;
+}
+
+/* [`Module] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_strip_symbols(LLVMPassManagerRef PM) {
+ LLVMAddStripSymbolsPass(PM);
+ return Val_unit;
+}
diff --git a/bindings/ocaml/transforms/ipo/llvm_ipo.ml b/bindings/ocaml/transforms/ipo/llvm_ipo.ml
new file mode 100644
index 00000000000..1562d10ae16
--- /dev/null
+++ b/bindings/ocaml/transforms/ipo/llvm_ipo.ml
@@ -0,0 +1,65 @@
+(*===-- llvm_ipo.mli - LLVM Ocaml Interface ------------*- OCaml -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** IPO Transforms.
+
+ This interface provides an ocaml API for LLVM interprocedural optimizations, the
+ classes in the [LLVMIPO] library. *)
+
+(** See llvm::createAddArgumentPromotionPass *)
+external add_argument_promotion : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_argument_promotion"
+
+(** See llvm::createConstantMergePass function. *)
+external add_constant_merge : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_constant_merge"
+
+(** See llvm::createDeadArgEliminationPass function. *)
+external add_dead_arg_elimination :
+ [ | `Module ] Llvm.PassManager.t -> unit = "llvm_add_dead_arg_elimination"
+
+(** See llvm::createFunctionAttrsPass function. *)
+external add_function_attrs : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_function_attrs"
+
+(** See llvm::createFunctionInliningPass function. *)
+external add_function_inlining : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_function_inlining"
+
+(** See llvm::createGlobalDCEPass function. *)
+external add_global_dce : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_global_dce"
+
+(** See llvm::createGlobalOptimizerPass function. *)
+external add_global_optimizer : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_global_optimizer"
+
+(** See llvm::createIPConstantPropagationPass function. *)
+external add_ipc_propagation : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_ipc_propagation"
+
+(** See llvm::createPruneEHPass function. *)
+external add_prune_eh : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_prune_eh"
+
+(** See llvm::createIPSCCPPass function. *)
+external add_ipsccp : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_ipsccp"
+
+(** See llvm::createInternalizePass function. *)
+external add_internalize : [ | `Module ] Llvm.PassManager.t -> bool -> unit =
+ "llvm_add_internalize"
+
+(** See llvm::createStripDeadPrototypesPass function. *)
+external add_strip_dead_prototypes :
+ [ | `Module ] Llvm.PassManager.t -> unit = "llvm_add_strip_dead_prototypes"
+
+(** See llvm::createStripSymbolsPass function. *)
+external add_strip_symbols : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_strip_symbols"
diff --git a/bindings/ocaml/transforms/ipo/llvm_ipo.mli b/bindings/ocaml/transforms/ipo/llvm_ipo.mli
new file mode 100644
index 00000000000..636103d4f8c
--- /dev/null
+++ b/bindings/ocaml/transforms/ipo/llvm_ipo.mli
@@ -0,0 +1,65 @@
+(*===-- llvm_ipo.mli - LLVM Ocaml Interface ------------*- OCaml -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** IPO Transforms.
+
+ This interface provides an ocaml API for LLVM interprocedural optimizations, the
+ classes in the [LLVMIPO] library. *)
+
+(** See llvm::createAddArgumentPromotionPass *)
+external add_argument_promotion : [ | `Module ] Llvm.PassManager.t -> unit =
+
+ "llvm_add_argument_promotion"
+(** See llvm::createConstantMergePass function. *)
+external add_constant_merge : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_constant_merge"
+
+(** See llvm::createDeadArgEliminationPass function. *)
+external add_dead_arg_elimination :
+ [ | `Module ] Llvm.PassManager.t -> unit = "llvm_add_dead_arg_elimination"
+
+(** See llvm::createFunctionAttrsPass function. *)
+external add_function_attrs : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_function_attrs"
+
+(** See llvm::createFunctionInliningPass function. *)
+external add_function_inlining : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_function_inlining"
+
+(** See llvm::createGlobalDCEPass function. *)
+external add_global_dce : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_global_dce"
+
+(** See llvm::createGlobalOptimizerPass function. *)
+external add_global_optimizer : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_global_optimizer"
+
+(** See llvm::createIPConstantPropagationPass function. *)
+external add_ipc_propagation : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_ipc_propagation"
+
+(** See llvm::createPruneEHPass function. *)
+external add_prune_eh : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_prune_eh"
+
+(** See llvm::createIPSCCPPass function. *)
+external add_ipsccp : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_ipsccp"
+
+(** See llvm::createInternalizePass function. *)
+external add_internalize : [ | `Module ] Llvm.PassManager.t -> bool -> unit =
+ "llvm_add_internalize"
+
+(** See llvm::createStripDeadPrototypesPass function. *)
+external add_strip_dead_prototypes :
+ [ | `Module ] Llvm.PassManager.t -> unit = "llvm_add_strip_dead_prototypes"
+
+(** See llvm::createStripSymbolsPass function. *)
+external add_strip_symbols : [ | `Module ] Llvm.PassManager.t -> unit =
+ "llvm_add_strip_symbols"
diff --git a/bindings/ocaml/transforms/scalar/Makefile b/bindings/ocaml/transforms/scalar/Makefile
new file mode 100644
index 00000000000..cbaffa4ea7a
--- /dev/null
+++ b/bindings/ocaml/transforms/scalar/Makefile
@@ -0,0 +1,20 @@
+##===- bindings/ocaml/transforms/scalar/Makefile -----------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml Llvm_scalar_opts interface.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../../..
+LIBRARYNAME := llvm_scalar_opts
+DONT_BUILD_RELINKED := 1
+UsedComponents := scalaropts
+UsedOcamlInterfaces := llvm
+
+include ../../Makefile.ocaml
diff --git a/bindings/ocaml/transforms/scalar/llvm_scalar_opts.ml b/bindings/ocaml/transforms/scalar/llvm_scalar_opts.ml
new file mode 100644
index 00000000000..93ab1de2582
--- /dev/null
+++ b/bindings/ocaml/transforms/scalar/llvm_scalar_opts.ml
@@ -0,0 +1,111 @@
+(*===-- llvm_scalar_opts.ml - LLVM Ocaml Interface -------------*- OCaml -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+external add_constant_propagation : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_constant_propagation"
+external add_sccp : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_sccp"
+external add_dead_store_elimination : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_dead_store_elimination"
+external add_aggressive_dce : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_aggressive_dce"
+external
+add_scalar_repl_aggregation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_scalar_repl_aggregation"
+
+external
+add_scalar_repl_aggregation_ssa : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_scalar_repl_aggregation_ssa"
+
+external
+add_scalar_repl_aggregation_with_threshold : int -> [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_scalar_repl_aggregation_with_threshold"
+external add_ind_var_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_ind_var_simplification"
+external
+add_instruction_combination : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_instruction_combination"
+external add_licm : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_licm"
+external add_loop_unswitch : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_unswitch"
+external add_loop_unroll : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_unroll"
+external add_loop_rotation : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_rotation"
+external
+add_memory_to_register_promotion : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_memory_to_register_promotion"
+external
+add_memory_to_register_demotion : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_memory_to_register_demotion"
+external add_reassociation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_reassociation"
+external add_jump_threading : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_jump_threading"
+external add_cfg_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_cfg_simplification"
+external
+add_tail_call_elimination : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_tail_call_elimination"
+external add_gvn : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_gvn"
+external add_memcpy_opt : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_memcpy_opt"
+external add_loop_deletion : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_deletion"
+
+external add_loop_idiom : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_idiom"
+
+external
+add_lib_call_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_lib_call_simplification"
+
+external
+add_verifier : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_verifier"
+
+external
+add_correlated_value_propagation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_correlated_value_propagation"
+
+external
+add_early_cse : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_early_cse"
+
+external
+add_lower_expect_intrinsic : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_lower_expect_intrinsic"
+
+external
+add_type_based_alias_analysis : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_type_based_alias_analysis"
+
+external
+add_basic_alias_analysis : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_basic_alias_analysis"
+
diff --git a/bindings/ocaml/transforms/scalar/llvm_scalar_opts.mli b/bindings/ocaml/transforms/scalar/llvm_scalar_opts.mli
new file mode 100644
index 00000000000..121b3761282
--- /dev/null
+++ b/bindings/ocaml/transforms/scalar/llvm_scalar_opts.mli
@@ -0,0 +1,164 @@
+(*===-- llvm_scalar_opts.mli - LLVM Ocaml Interface ------------*- OCaml -*-===*
+ *
+ * The LLVM Compiler Infrastructure
+ *
+ * This file is distributed under the University of Illinois Open Source
+ * License. See LICENSE.TXT for details.
+ *
+ *===----------------------------------------------------------------------===*)
+
+(** Scalar Transforms.
+
+ This interface provides an ocaml API for LLVM scalar transforms, the
+ classes in the [LLVMScalarOpts] library. *)
+
+(** See the [llvm::createConstantPropogationPass] function. *)
+external add_constant_propagation : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_constant_propagation"
+
+(** See the [llvm::createSCCPPass] function. *)
+external add_sccp : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_sccp"
+
+(** See [llvm::createDeadStoreEliminationPass] function. *)
+external add_dead_store_elimination : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_dead_store_elimination"
+
+(** See The [llvm::createAggressiveDCEPass] function. *)
+external add_aggressive_dce : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_aggressive_dce"
+
+(** See the [llvm::createScalarReplAggregatesPass] function. *)
+external
+add_scalar_repl_aggregation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_scalar_repl_aggregation"
+
+(** See the [llvm::createScalarReplAggregatesPassSSA] function. *)
+external
+add_scalar_repl_aggregation_ssa : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_scalar_repl_aggregation_ssa"
+
+(** See the [llvm::createScalarReplAggregatesWithThreshold] function. *)
+external
+add_scalar_repl_aggregation_with_threshold : int -> [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_scalar_repl_aggregation_with_threshold"
+
+(** See the [llvm::createIndVarSimplifyPass] function. *)
+external add_ind_var_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_ind_var_simplification"
+
+(** See the [llvm::createInstructionCombiningPass] function. *)
+external
+add_instruction_combination : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_instruction_combination"
+
+(** See the [llvm::createLICMPass] function. *)
+external add_licm : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_licm"
+
+(** See the [llvm::createLoopUnswitchPass] function. *)
+external add_loop_unswitch : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_unswitch"
+
+(** See the [llvm::createLoopUnrollPass] function. *)
+external add_loop_unroll : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_unroll"
+
+(** See the [llvm::createLoopRotatePass] function. *)
+external add_loop_rotation : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_rotation"
+
+(** See the [llvm::createPromoteMemoryToRegisterPass] function. *)
+external
+add_memory_to_register_promotion : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_memory_to_register_promotion"
+
+(** See the [llvm::createDemoteMemoryToRegisterPass] function. *)
+external
+add_memory_to_register_demotion : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_memory_to_register_demotion"
+
+(** See the [llvm::createReassociatePass] function. *)
+external add_reassociation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_reassociation"
+
+(** See the [llvm::createJumpThreadingPass] function. *)
+external add_jump_threading : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_jump_threading"
+
+(** See the [llvm::createCFGSimplificationPass] function. *)
+external add_cfg_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_cfg_simplification"
+
+(** See the [llvm::createTailCallEliminationPass] function. *)
+external
+add_tail_call_elimination : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_tail_call_elimination"
+
+(** See the [llvm::createGVNPass] function. *)
+external add_gvn : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_gvn"
+
+(** See the [llvm::createMemCpyOptPass] function. *)
+external add_memcpy_opt : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_memcpy_opt"
+
+(** See the [llvm::createLoopDeletionPass] function. *)
+external add_loop_deletion : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_deletion"
+
+external add_loop_idiom : [<Llvm.PassManager.any] Llvm.PassManager.t
+ -> unit
+ = "llvm_add_loop_idiom"
+
+(** See the [llvm::createSimplifyLibCallsPass] function. *)
+external
+add_lib_call_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_lib_call_simplification"
+
+(** See the [llvm::createVerifierPass] function. *)
+external
+add_verifier : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_verifier"
+
+(** See the [llvm::createCorrelatedValuePropagationPass] function. *)
+external
+add_correlated_value_propagation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_correlated_value_propagation"
+
+(** See the [llvm::createEarlyCSE] function. *)
+external
+add_early_cse : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_early_cse"
+
+(** See the [llvm::createLowerExpectIntrinsicPass] function. *)
+external
+add_lower_expect_intrinsic : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_lower_expect_intrinsic"
+
+(** See the [llvm::createTypeBasedAliasAnalysisPass] function. *)
+external
+add_type_based_alias_analysis : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_type_based_alias_analysis"
+
+(** See the [llvm::createBasicAliasAnalysisPass] function. *)
+external
+add_basic_alias_analysis : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit
+ = "llvm_add_basic_alias_analysis"
+
diff --git a/bindings/ocaml/transforms/scalar/scalar_opts_ocaml.c b/bindings/ocaml/transforms/scalar/scalar_opts_ocaml.c
new file mode 100644
index 00000000000..7047ec04c74
--- /dev/null
+++ b/bindings/ocaml/transforms/scalar/scalar_opts_ocaml.c
@@ -0,0 +1,201 @@
+/*===-- scalar_opts_ocaml.c - LLVM Ocaml Glue -------------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file glues LLVM's ocaml interface to its C interface. These functions *|
+|* are by and large transparent wrappers to the corresponding C functions. *|
+|* *|
+|* Note that these functions intentionally take liberties with the CAMLparamX *|
+|* macros, since most of the parameters are not GC heap objects. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#include "llvm-c/Transforms/Scalar.h"
+#include "caml/mlvalues.h"
+#include "caml/misc.h"
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_constant_propagation(LLVMPassManagerRef PM) {
+ LLVMAddConstantPropagationPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_sccp(LLVMPassManagerRef PM) {
+ LLVMAddSCCPPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_dead_store_elimination(LLVMPassManagerRef PM) {
+ LLVMAddDeadStoreEliminationPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_aggressive_dce(LLVMPassManagerRef PM) {
+ LLVMAddAggressiveDCEPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_scalar_repl_aggregation(LLVMPassManagerRef PM) {
+ LLVMAddScalarReplAggregatesPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_scalar_repl_aggregation_ssa(LLVMPassManagerRef PM) {
+ LLVMAddScalarReplAggregatesPassSSA(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> int -> unit */
+CAMLprim value llvm_add_scalar_repl_aggregation_with_threshold(value threshold,
+ LLVMPassManagerRef PM) {
+ LLVMAddScalarReplAggregatesPassWithThreshold(PM, Int_val(threshold));
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_ind_var_simplification(LLVMPassManagerRef PM) {
+ LLVMAddIndVarSimplifyPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_instruction_combination(LLVMPassManagerRef PM) {
+ LLVMAddInstructionCombiningPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_licm(LLVMPassManagerRef PM) {
+ LLVMAddLICMPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_loop_unswitch(LLVMPassManagerRef PM) {
+ LLVMAddLoopUnswitchPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_loop_unroll(LLVMPassManagerRef PM) {
+ LLVMAddLoopUnrollPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_loop_rotation(LLVMPassManagerRef PM) {
+ LLVMAddLoopRotatePass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_memory_to_register_promotion(LLVMPassManagerRef PM) {
+ LLVMAddPromoteMemoryToRegisterPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_memory_to_register_demotion(LLVMPassManagerRef PM) {
+ LLVMAddDemoteMemoryToRegisterPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_reassociation(LLVMPassManagerRef PM) {
+ LLVMAddReassociatePass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_jump_threading(LLVMPassManagerRef PM) {
+ LLVMAddJumpThreadingPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_cfg_simplification(LLVMPassManagerRef PM) {
+ LLVMAddCFGSimplificationPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_tail_call_elimination(LLVMPassManagerRef PM) {
+ LLVMAddTailCallEliminationPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_gvn(LLVMPassManagerRef PM) {
+ LLVMAddGVNPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_memcpy_opt(LLVMPassManagerRef PM) {
+ LLVMAddMemCpyOptPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_loop_deletion(LLVMPassManagerRef PM) {
+ LLVMAddLoopDeletionPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_loop_idiom(LLVMPassManagerRef PM) {
+ LLVMAddLoopIdiomPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_lib_call_simplification(LLVMPassManagerRef PM) {
+ LLVMAddSimplifyLibCallsPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_verifier(LLVMPassManagerRef PM) {
+ LLVMAddVerifierPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_correlated_value_propagation(LLVMPassManagerRef PM) {
+ LLVMAddCorrelatedValuePropagationPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_early_cse(LLVMPassManagerRef PM) {
+ LLVMAddEarlyCSEPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_lower_expect_intrinsic(LLVMPassManagerRef PM) {
+ LLVMAddLowerExpectIntrinsicPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_type_based_alias_analysis(LLVMPassManagerRef PM) {
+ LLVMAddTypeBasedAliasAnalysisPass(PM);
+ return Val_unit;
+}
+
+/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
+CAMLprim value llvm_add_basic_alias_analysis(LLVMPassManagerRef PM) {
+ LLVMAddBasicAliasAnalysisPass(PM);
+ return Val_unit;
+}
diff --git a/bindings/python/README.txt b/bindings/python/README.txt
new file mode 100644
index 00000000000..96e334319bd
--- /dev/null
+++ b/bindings/python/README.txt
@@ -0,0 +1,67 @@
+This directory contains Python bindings for LLVM's C library.
+
+The bindings are currently a work in progress and are far from complete.
+Use at your own risk.
+
+Developer Info
+==============
+
+The single Python package is "llvm." Modules inside this package roughly
+follow the names of the modules/headers defined by LLVM's C API.
+
+Testing
+-------
+
+All test code is location in llvm/tests. Tests are written as classes
+which inherit from llvm.tests.base.TestBase, which is a convenience base
+class that provides common functionality.
+
+Tests can be executed by installing nose:
+
+ pip install nosetests
+
+Then by running nosetests:
+
+ nosetests
+
+To see more output:
+
+ nosetests -v
+
+To step into the Python debugger while running a test, add the following
+to your test at the point you wish to enter the debugger:
+
+ import pdb; pdb.set_trace()
+
+Then run nosetests:
+
+ nosetests -s -v
+
+You should strive for high code coverage. To see current coverage:
+
+ pip install coverage
+ nosetests --with-coverage --cover-html
+
+Then open cover/index.html in your browser of choice to see the code coverage.
+
+Style Convention
+----------------
+
+All code should pass PyFlakes. First, install PyFlakes:
+
+ pip install pyflakes
+
+Then at any time run it to see a report:
+
+ pyflakes .
+
+Eventually we'll provide a Pylint config file. In the meantime, install
+Pylint:
+
+ pip install pylint
+
+And run:
+
+ pylint llvm
+
+And try to keep the number of violations to a minimum.
diff --git a/bindings/python/llvm/__init__.py b/bindings/python/llvm/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
--- /dev/null
+++ b/bindings/python/llvm/__init__.py
diff --git a/bindings/python/llvm/common.py b/bindings/python/llvm/common.py
new file mode 100644
index 00000000000..0c5fcd03d84
--- /dev/null
+++ b/bindings/python/llvm/common.py
@@ -0,0 +1,106 @@
+#===- common.py - Python LLVM Bindings -----------------------*- python -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+
+from ctypes import POINTER
+from ctypes import c_void_p
+from ctypes import cdll
+
+import ctypes.util
+
+__all__ = [
+ 'c_object_p',
+ 'find_library',
+ 'get_library',
+]
+
+c_object_p = POINTER(c_void_p)
+
+class LLVMObject(object):
+ """Base class for objects that are backed by an LLVM data structure.
+
+ This class should never be instantiated outside of this package.
+ """
+ def __init__(self, ptr, ownable=True, disposer=None):
+ assert isinstance(ptr, c_object_p)
+
+ self._ptr = self._as_parameter_ = ptr
+
+ self._self_owned = True
+ self._ownable = ownable
+ self._disposer = disposer
+
+ self._owned_objects = []
+
+ def take_ownership(self, obj):
+ """Take ownership of another object.
+
+ When you take ownership of another object, you are responsible for
+ destroying that object. In addition, a reference to that object is
+ placed inside this object so the Python garbage collector will not
+ collect the object while it is still alive in libLLVM.
+
+ This method should likely only be called from within modules inside
+ this package.
+ """
+ assert isinstance(obj, LLVMObject)
+
+ self._owned_objects.append(obj)
+ obj._self_owned = False
+
+ def from_param(self):
+ """ctypes function that converts this object to a function parameter."""
+ return self._as_parameter_
+
+ def __del__(self):
+ if not hasattr(self, '_self_owned') or not hasattr(self, '_disposer'):
+ return
+
+ if self._self_owned and self._disposer:
+ self._disposer(self)
+
+class CachedProperty(object):
+ """Decorator that caches the result of a property lookup.
+
+ This is a useful replacement for @property. It is recommended to use this
+ decorator on properties that invoke C API calls for which the result of the
+ call will be idempotent.
+ """
+ def __init__(self, wrapped):
+ self.wrapped = wrapped
+ try:
+ self.__doc__ = wrapped.__doc__
+ except: # pragma: no cover
+ pass
+
+ def __get__(self, instance, instance_type=None):
+ if instance is None:
+ return self
+
+ value = self.wrapped(instance)
+ setattr(instance, self.wrapped.__name__, value)
+
+ return value
+
+def find_library():
+ # FIXME should probably have build system define absolute path of shared
+ # library at install time.
+ for lib in ['LLVM-3.1svn', 'libLLVM-3.1svn', 'LLVM', 'libLLVM']:
+ result = ctypes.util.find_library(lib)
+ if result:
+ return result
+
+ return None
+
+def get_library():
+ """Obtain a reference to the llvm library."""
+ lib = find_library()
+ if not lib:
+ raise Exception('LLVM shared library not found!')
+
+ return cdll.LoadLibrary(lib)
diff --git a/bindings/python/llvm/core.py b/bindings/python/llvm/core.py
new file mode 100644
index 00000000000..67566374256
--- /dev/null
+++ b/bindings/python/llvm/core.py
@@ -0,0 +1,98 @@
+#===- core.py - Python LLVM Bindings -------------------------*- python -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+
+from .common import LLVMObject
+from .common import c_object_p
+from .common import get_library
+
+from . import enumerations
+
+from ctypes import POINTER
+from ctypes import byref
+from ctypes import c_char_p
+
+__all__ = [
+ "lib",
+ "MemoryBuffer",
+]
+
+lib = get_library()
+
+class OpCode(object):
+ """Represents an individual OpCode enumeration."""
+
+ _value_map = {}
+
+ def __init__(self, name, value):
+ self.name = name
+ self.value = value
+
+ def __repr__(self):
+ return 'OpCode.%s' % self.name
+
+ @staticmethod
+ def from_value(value):
+ """Obtain an OpCode instance from a numeric value."""
+ result = OpCode._value_map.get(value, None)
+
+ if result is None:
+ raise ValueError('Unknown OpCode: %d' % value)
+
+ return result
+
+ @staticmethod
+ def register(name, value):
+ """Registers a new OpCode enumeration.
+
+ This is called by this module for each enumeration defined in
+ enumerations. You should not need to call this outside this module.
+ """
+ if value in OpCode._value_map:
+ raise ValueError('OpCode value already registered: %d' % value)
+
+ opcode = OpCode(name, value)
+ OpCode._value_map[value] = opcode
+ setattr(OpCode, name, opcode)
+
+class MemoryBuffer(LLVMObject):
+ """Represents an opaque memory buffer."""
+
+ def __init__(self, filename=None):
+ """Create a new memory buffer.
+
+ Currently, we support creating from the contents of a file at the
+ specified filename.
+ """
+ if filename is None:
+ raise Exception("filename argument must be defined")
+
+ memory = c_object_p()
+ out = c_char_p(None)
+
+ result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
+ byref(memory), byref(out))
+
+ if result:
+ raise Exception("Could not create memory buffer: %s" % out.value)
+
+ LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
+
+def register_library(library):
+ library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
+ POINTER(c_object_p), POINTER(c_char_p)]
+ library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
+
+ library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
+
+def register_enumerations():
+ for name, value in enumerations.OpCodes:
+ OpCode.register(name, value)
+
+register_library(lib)
+register_enumerations()
diff --git a/bindings/python/llvm/disassembler.py b/bindings/python/llvm/disassembler.py
new file mode 100644
index 00000000000..5030b989a94
--- /dev/null
+++ b/bindings/python/llvm/disassembler.py
@@ -0,0 +1,134 @@
+#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+
+from ctypes import CFUNCTYPE
+from ctypes import POINTER
+from ctypes import addressof
+from ctypes import byref
+from ctypes import c_byte
+from ctypes import c_char_p
+from ctypes import c_int
+from ctypes import c_size_t
+from ctypes import c_ubyte
+from ctypes import c_uint64
+from ctypes import c_void_p
+from ctypes import cast
+
+from .common import LLVMObject
+from .common import c_object_p
+from .common import get_library
+
+__all__ = [
+ 'Disassembler',
+]
+
+lib = get_library()
+callbacks = {}
+
+class Disassembler(LLVMObject):
+ """Represents a disassembler instance.
+
+ Disassembler instances are tied to specific "triple," which must be defined
+ at creation time.
+
+ Disassembler instances can disassemble instructions from multiple sources.
+ """
+ def __init__(self, triple):
+ """Create a new disassembler instance.
+
+ The triple argument is the triple to create the disassembler for. This
+ is something like 'i386-apple-darwin9'.
+ """
+ ptr = lib.LLVMCreateDisasm(c_char_p(triple), c_void_p(None), c_int(0),
+ callbacks['op_info'](0), callbacks['symbol_lookup'](0))
+ if not ptr.contents:
+ raise Exception('Could not obtain disassembler for triple: %s' %
+ triple)
+
+ LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisasmDispose)
+
+ def get_instruction(self, source, pc=0):
+ """Obtain the next instruction from an input source.
+
+ The input source should be a str or bytearray or something that
+ represents a sequence of bytes.
+
+ This function will start reading bytes from the beginning of the
+ source.
+
+ The pc argument specifies the address that the first byte is at.
+
+ This returns a 2-tuple of:
+
+ long number of bytes read. 0 if no instruction was read.
+ str representation of instruction. This will be the assembly that
+ represents the instruction.
+ """
+ buf = cast(c_char_p(source), POINTER(c_ubyte))
+ out_str = cast((c_byte * 255)(), c_char_p)
+
+ result = lib.LLVMDisasmInstruction(self, buf, c_uint64(len(source)),
+ c_uint64(pc), out_str, 255)
+
+ return (result, out_str.value)
+
+ def get_instructions(self, source, pc=0):
+ """Obtain multiple instructions from an input source.
+
+ This is like get_instruction() except it is a generator for all
+ instructions within the source. It starts at the beginning of the
+ source and reads instructions until no more can be read.
+
+ This generator returns 3-tuple of:
+
+ long address of instruction.
+ long size of instruction, in bytes.
+ str representation of instruction.
+ """
+ source_bytes = c_char_p(source)
+ out_str = cast((c_byte * 255)(), c_char_p)
+
+ # This could probably be written cleaner. But, it does work.
+ buf = cast(source_bytes, POINTER(c_ubyte * len(source))).contents
+ offset = 0
+ address = pc
+ end_address = pc + len(source)
+ while address < end_address:
+ b = cast(addressof(buf) + offset, POINTER(c_ubyte))
+ result = lib.LLVMDisasmInstruction(self, b,
+ c_uint64(len(source) - offset), c_uint64(address),
+ out_str, 255)
+
+ if result == 0:
+ break
+
+ yield (address, result, out_str.value)
+
+ address += result
+ offset += result
+
+
+def register_library(library):
+ library.LLVMCreateDisasm.argtypes = [c_char_p, c_void_p, c_int,
+ callbacks['op_info'], callbacks['symbol_lookup']]
+ library.LLVMCreateDisasm.restype = c_object_p
+
+ library.LLVMDisasmDispose.argtypes = [Disassembler]
+
+ library.LLVMDisasmInstruction.argtypes = [Disassembler, POINTER(c_ubyte),
+ c_uint64, c_uint64, c_char_p, c_size_t]
+ library.LLVMDisasmInstruction.restype = c_size_t
+
+callbacks['op_info'] = CFUNCTYPE(c_int, c_void_p, c_uint64, c_uint64, c_uint64,
+ c_int, c_void_p)
+callbacks['symbol_lookup'] = CFUNCTYPE(c_char_p, c_void_p, c_uint64,
+ POINTER(c_uint64), c_uint64,
+ POINTER(c_char_p))
+
+register_library(lib)
diff --git a/bindings/python/llvm/enumerations.py b/bindings/python/llvm/enumerations.py
new file mode 100644
index 00000000000..f49d2faad35
--- /dev/null
+++ b/bindings/python/llvm/enumerations.py
@@ -0,0 +1,211 @@
+#===- enumerations.py - Python LLVM Enumerations -------------*- python -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+
+r"""
+LLVM Enumerations
+=================
+
+This file defines enumerations from LLVM.
+
+Each enumeration is exposed as a list of 2-tuples. These lists are consumed by
+dedicated types elsewhere in the package. The enumerations are centrally
+defined in this file so they are easier to locate and maintain.
+"""
+
+__all__ = [
+ 'Attributes',
+ 'OpCodes',
+ 'TypeKinds',
+ 'Linkages',
+ 'Visibility',
+ 'CallConv',
+ 'IntPredicate',
+ 'RealPredicate',
+ 'LandingPadClauseTy',
+]
+
+Attributes = [
+ ('ZExt', 1 << 0),
+ ('MSExt', 1 << 1),
+ ('NoReturn', 1 << 2),
+ ('InReg', 1 << 3),
+ ('StructRet', 1 << 4),
+ ('NoUnwind', 1 << 5),
+ ('NoAlias', 1 << 6),
+ ('ByVal', 1 << 7),
+ ('Nest', 1 << 8),
+ ('ReadNone', 1 << 9),
+ ('ReadOnly', 1 << 10),
+ ('NoInline', 1 << 11),
+ ('AlwaysInline', 1 << 12),
+ ('OptimizeForSize', 1 << 13),
+ ('StackProtect', 1 << 14),
+ ('StackProtectReq', 1 << 15),
+ ('Alignment', 31 << 16),
+ ('NoCapture', 1 << 21),
+ ('NoRedZone', 1 << 22),
+ ('ImplicitFloat', 1 << 23),
+ ('Naked', 1 << 24),
+ ('InlineHint', 1 << 25),
+ ('StackAlignment', 7 << 26),
+ ('ReturnsTwice', 1 << 29),
+ ('UWTable', 1 << 30),
+ ('NonLazyBind', 1 << 31),
+]
+
+OpCodes = [
+ ('Ret', 1),
+ ('Br', 2),
+ ('Switch', 3),
+ ('IndirectBr', 4),
+ ('Invoke', 5),
+ ('Unreachable', 7),
+ ('Add', 8),
+ ('FAdd', 9),
+ ('Sub', 10),
+ ('FSub', 11),
+ ('Mul', 12),
+ ('FMul', 13),
+ ('UDiv', 14),
+ ('SDiv', 15),
+ ('FDiv', 16),
+ ('URem', 17),
+ ('SRem', 18),
+ ('FRem', 19),
+ ('Shl', 20),
+ ('LShr', 21),
+ ('AShr', 22),
+ ('And', 23),
+ ('Or', 24),
+ ('Xor', 25),
+ ('Alloca', 26),
+ ('Load', 27),
+ ('Store', 28),
+ ('GetElementPtr', 29),
+ ('Trunc', 30),
+ ('ZExt', 31),
+ ('SExt', 32),
+ ('FPToUI', 33),
+ ('FPToSI', 34),
+ ('UIToFP', 35),
+ ('SIToFP', 36),
+ ('FPTrunc', 37),
+ ('FPExt', 38),
+ ('PtrToInt', 39),
+ ('IntToPtr', 40),
+ ('BitCast', 41),
+ ('ICmp', 42),
+ ('FCmpl', 43),
+ ('PHI', 44),
+ ('Call', 45),
+ ('Select', 46),
+ ('UserOp1', 47),
+ ('UserOp2', 48),
+ ('AArg', 49),
+ ('ExtractElement', 50),
+ ('InsertElement', 51),
+ ('ShuffleVector', 52),
+ ('ExtractValue', 53),
+ ('InsertValue', 54),
+ ('Fence', 55),
+ ('AtomicCmpXchg', 56),
+ ('AtomicRMW', 57),
+ ('Resume', 58),
+ ('LandingPad', 59),
+]
+
+TypeKinds = [
+ ('Void', 0),
+ ('Half', 1),
+ ('Float', 2),
+ ('Double', 3),
+ ('X86_FP80', 4),
+ ('FP128', 5),
+ ('PPC_FP128', 6),
+ ('Label', 7),
+ ('Integer', 8),
+ ('Function', 9),
+ ('Struct', 10),
+ ('Array', 11),
+ ('Pointer', 12),
+ ('Vector', 13),
+ ('Metadata', 14),
+ ('X86_MMX', 15),
+]
+
+Linkages = [
+ ('External', 0),
+ ('AvailableExternally', 1),
+ ('LinkOnceAny', 2),
+ ('LinkOnceODR', 3),
+ ('WeakAny', 4),
+ ('WeakODR', 5),
+ ('Appending', 6),
+ ('Internal', 7),
+ ('Private', 8),
+ ('DLLImport', 9),
+ ('DLLExport', 10),
+ ('ExternalWeak', 11),
+ ('Ghost', 12),
+ ('Common', 13),
+ ('LinkerPrivate', 14),
+ ('LinkerPrivateWeak', 15),
+ ('LinkerPrivateWeakDefAuto', 16),
+]
+
+Visibility = [
+ ('Default', 0),
+ ('Hidden', 1),
+ ('Protected', 2),
+]
+
+CallConv = [
+ ('CCall', 0),
+ ('FastCall', 8),
+ ('ColdCall', 9),
+ ('X86StdcallCall', 64),
+ ('X86FastcallCall', 65),
+]
+
+IntPredicate = [
+ ('EQ', 32),
+ ('NE', 33),
+ ('UGT', 34),
+ ('UGE', 35),
+ ('ULT', 36),
+ ('ULE', 37),
+ ('SGT', 38),
+ ('SGE', 39),
+ ('SLT', 40),
+ ('SLE', 41),
+]
+
+RealPredicate = [
+ ('PredicateFalse', 0),
+ ('OEQ', 1),
+ ('OGT', 2),
+ ('OGE', 3),
+ ('OLT', 4),
+ ('OLE', 5),
+ ('ONE', 6),
+ ('ORD', 7),
+ ('UNO', 8),
+ ('UEQ', 9),
+ ('UGT', 10),
+ ('UGE', 11),
+ ('ULT', 12),
+ ('ULE', 13),
+ ('UNE', 14),
+ ('PredicateTrue', 15),
+]
+
+LandingPadClauseTy = [
+ ('Catch', 0),
+ ('Filter', 1),
+]
diff --git a/bindings/python/llvm/object.py b/bindings/python/llvm/object.py
new file mode 100644
index 00000000000..473aa3a1089
--- /dev/null
+++ b/bindings/python/llvm/object.py
@@ -0,0 +1,523 @@
+#===- object.py - Python Object Bindings --------------------*- python -*--===#
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+#===------------------------------------------------------------------------===#
+
+r"""
+Object File Interface
+=====================
+
+This module provides an interface for reading information from object files
+(e.g. binary executables and libraries).
+
+Using this module, you can obtain information about an object file's sections,
+symbols, and relocations. These are represented by the classes ObjectFile,
+Section, Symbol, and Relocation, respectively.
+
+Usage
+-----
+
+The only way to use this module is to start by creating an ObjectFile. You can
+create an ObjectFile by loading a file (specified by its path) or by creating a
+llvm.core.MemoryBuffer and loading that.
+
+Once you have an object file, you can inspect its sections and symbols directly
+by calling get_sections() and get_symbols() respectively. To inspect
+relocations, call get_relocations() on a Section instance.
+
+Iterator Interface
+------------------
+
+The LLVM bindings expose iteration over sections, symbols, and relocations in a
+way that only allows one instance to be operated on at a single time. This is
+slightly annoying from a Python perspective, as it isn't very Pythonic to have
+objects that "expire" but are still active from a dynamic language.
+
+To aid working around this limitation, each Section, Symbol, and Relocation
+instance caches its properties after first access. So, if the underlying
+iterator is advanced, the properties can still be obtained provided they have
+already been retrieved.
+
+In addition, we also provide a "cache" method on each class to cache all
+available data. You can call this on each obtained instance. Or, you can pass
+cache=True to the appropriate get_XXX() method to have this done for you.
+
+Here are some examples on how to perform iteration:
+
+ obj = ObjectFile(filename='/bin/ls')
+
+ # This is OK. Each Section is only accessed inside its own iteration slot.
+ section_names = []
+ for section in obj.get_sections():
+ section_names.append(section.name)
+
+ # This is NOT OK. You perform a lookup after the object has expired.
+ symbols = list(obj.get_symbols())
+ for symbol in symbols:
+ print symbol.name # This raises because the object has expired.
+
+ # In this example, we mix a working and failing scenario.
+ symbols = []
+ for symbol in obj.get_symbols():
+ symbols.append(symbol)
+ print symbol.name
+
+ for symbol in symbols:
+ print symbol.name # OK
+ print symbol.address # NOT OK. We didn't look up this property before.
+
+ # Cache everything up front.
+ symbols = list(obj.get_symbols(cache=True))
+ for symbol in symbols:
+ print symbol.name # OK
+
+"""
+
+from ctypes import c_char_p
+from ctypes import c_uint64
+
+from .common import CachedProperty
+from .common import LLVMObject
+from .common import c_object_p
+from .common import get_library
+from .core import MemoryBuffer
+
+__all__ = [
+ "lib",
+ "ObjectFile",
+ "Relocation",
+ "Section",
+ "Symbol",
+]
+
+class ObjectFile(LLVMObject):
+ """Represents an object/binary file."""
+
+ def __init__(self, filename=None, contents=None):
+ """Construct an instance from a filename or binary data.
+
+ filename must be a path to a file that can be opened with open().
+ contents can be either a native Python buffer type (like str) or a
+ llvm.core.MemoryBuffer instance.
+ """
+ if contents:
+ assert isinstance(contents, MemoryBuffer)
+
+ if filename is not None:
+ contents = MemoryBuffer(filename=filename)
+
+ if contents is None:
+ raise Exception('No input found.')
+
+ ptr = lib.LLVMCreateObjectFile(contents)
+ LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisposeObjectFile)
+ self.take_ownership(contents)
+
+ def get_sections(self, cache=False):
+ """Obtain the sections in this object file.
+
+ This is a generator for llvm.object.Section instances.
+
+ Sections are exposed as limited-use objects. See the module's
+ documentation on iterators for more.
+ """
+ sections = lib.LLVMGetSections(self)
+ last = None
+ while True:
+ if lib.LLVMIsSectionIteratorAtEnd(self, sections):
+ break
+
+ last = Section(sections)
+ if cache:
+ last.cache()
+
+ yield last
+
+ lib.LLVMMoveToNextSection(sections)
+ last.expire()
+
+ if last is not None:
+ last.expire()
+
+ lib.LLVMDisposeSectionIterator(sections)
+
+ def get_symbols(self, cache=False):
+ """Obtain the symbols in this object file.
+
+ This is a generator for llvm.object.Symbol instances.
+
+ Each Symbol instance is a limited-use object. See this module's
+ documentation on iterators for more.
+ """
+ symbols = lib.LLVMGetSymbols(self)
+ last = None
+ while True:
+ if lib.LLVMIsSymbolIteratorAtEnd(self, symbols):
+ break
+
+ last = Symbol(symbols, self)
+ if cache:
+ last.cache()
+
+ yield last
+
+ lib.LLVMMoveToNextSymbol(symbols)
+ last.expire()
+
+ if last is not None:
+ last.expire()
+
+ lib.LLVMDisposeSymbolIterator(symbols)
+
+class Section(LLVMObject):
+ """Represents a section in an object file."""
+
+ def __init__(self, ptr):
+ """Construct a new section instance.
+
+ Section instances can currently only be created from an ObjectFile
+ instance. Therefore, this constructor should not be used outside of
+ this module.
+ """
+ LLVMObject.__init__(self, ptr)
+
+ self.expired = False
+
+ @CachedProperty
+ def name(self):
+ """Obtain the string name of the section.
+
+ This is typically something like '.dynsym' or '.rodata'.
+ """
+ if self.expired:
+ raise Exception('Section instance has expired.')
+
+ return lib.LLVMGetSectionName(self)
+
+ @CachedProperty
+ def size(self):
+ """The size of the section, in long bytes."""
+ if self.expired:
+ raise Exception('Section instance has expired.')
+
+ return lib.LLVMGetSectionSize(self)
+
+ @CachedProperty
+ def contents(self):
+ if self.expired:
+ raise Exception('Section instance has expired.')
+
+ return lib.LLVMGetSectionContents(self)
+
+ @CachedProperty
+ def address(self):
+ """The address of this section, in long bytes."""
+ if self.expired:
+ raise Exception('Section instance has expired.')
+
+ return lib.LLVMGetSectionAddress(self)
+
+ def has_symbol(self, symbol):
+ """Returns whether a Symbol instance is present in this Section."""
+ if self.expired:
+ raise Exception('Section instance has expired.')
+
+ assert isinstance(symbol, Symbol)
+ return lib.LLVMGetSectionContainsSymbol(self, symbol)
+
+ def get_relocations(self, cache=False):
+ """Obtain the relocations in this Section.
+
+ This is a generator for llvm.object.Relocation instances.
+
+ Each instance is a limited used object. See this module's documentation
+ on iterators for more.
+ """
+ if self.expired:
+ raise Exception('Section instance has expired.')
+
+ relocations = lib.LLVMGetRelocations(self)
+ last = None
+ while True:
+ if lib.LLVMIsRelocationIteratorAtEnd(self, relocations):
+ break
+
+ last = Relocation(relocations)
+ if cache:
+ last.cache()
+
+ yield last
+
+ lib.LLVMMoveToNextRelocation(relocations)
+ last.expire()
+
+ if last is not None:
+ last.expire()
+
+ lib.LLVMDisposeRelocationIterator(relocations)
+
+ def cache(self):
+ """Cache properties of this Section.
+
+ This can be called as a workaround to the single active Section
+ limitation. When called, the properties of the Section are fetched so
+ they are still available after the Section has been marked inactive.
+ """
+ getattr(self, 'name')
+ getattr(self, 'size')
+ getattr(self, 'contents')
+ getattr(self, 'address')
+
+ def expire(self):
+ """Expire the section.
+
+ This is called internally by the section iterator.
+ """
+ self.expired = True
+
+class Symbol(LLVMObject):
+ """Represents a symbol in an object file."""
+ def __init__(self, ptr, object_file):
+ assert isinstance(ptr, c_object_p)
+ assert isinstance(object_file, ObjectFile)
+
+ LLVMObject.__init__(self, ptr)
+
+ self.expired = False
+ self._object_file = object_file
+
+ @CachedProperty
+ def name(self):
+ """The str name of the symbol.
+
+ This is often a function or variable name. Keep in mind that name
+ mangling could be in effect.
+ """
+ if self.expired:
+ raise Exception('Symbol instance has expired.')
+
+ return lib.LLVMGetSymbolName(self)
+
+ @CachedProperty
+ def address(self):
+ """The address of this symbol, in long bytes."""
+ if self.expired:
+ raise Exception('Symbol instance has expired.')
+
+ return lib.LLVMGetSymbolAddress(self)
+
+ @CachedProperty
+ def file_offset(self):
+ """The offset of this symbol in the file, in long bytes."""
+ if self.expired:
+ raise Exception('Symbol instance has expired.')
+
+ return lib.LLVMGetSymbolFileOffset(self)
+
+ @CachedProperty
+ def size(self):
+ """The size of the symbol, in long bytes."""
+ if self.expired:
+ raise Exception('Symbol instance has expired.')
+
+ return lib.LLVMGetSymbolSize(self)
+
+ @CachedProperty
+ def section(self):
+ """The Section to which this Symbol belongs.
+
+ The returned Section instance does not expire, unlike Sections that are
+ commonly obtained through iteration.
+
+ Because this obtains a new section iterator each time it is accessed,
+ calling this on a number of Symbol instances could be expensive.
+ """
+ sections = lib.LLVMGetSections(self._object_file)
+ lib.LLVMMoveToContainingSection(sections, self)
+
+ return Section(sections)
+
+ def cache(self):
+ """Cache all cacheable properties."""
+ getattr(self, 'name')
+ getattr(self, 'address')
+ getattr(self, 'file_offset')
+ getattr(self, 'size')
+
+ def expire(self):
+ """Mark the object as expired to prevent future API accesses.
+
+ This is called internally by this module and it is unlikely that
+ external callers have a legitimate reason for using it.
+ """
+ self.expired = True
+
+class Relocation(LLVMObject):
+ """Represents a relocation definition."""
+ def __init__(self, ptr):
+ """Create a new relocation instance.
+
+ Relocations are created from objects derived from Section instances.
+ Therefore, this constructor should not be called outside of this
+ module. See Section.get_relocations() for the proper method to obtain
+ a Relocation instance.
+ """
+ assert isinstance(ptr, c_object_p)
+
+ LLVMObject.__init__(self, ptr)
+
+ self.expired = False
+
+ @CachedProperty
+ def address(self):
+ """The address of this relocation, in long bytes."""
+ if self.expired:
+ raise Exception('Relocation instance has expired.')
+
+ return lib.LLVMGetRelocationAddress(self)
+
+ @CachedProperty
+ def offset(self):
+ """The offset of this relocation, in long bytes."""
+ if self.expired:
+ raise Exception('Relocation instance has expired.')
+
+ return lib.LLVMGetRelocationOffset(self)
+
+ @CachedProperty
+ def symbol(self):
+ """The Symbol corresponding to this Relocation."""
+ if self.expired:
+ raise Exception('Relocation instance has expired.')
+
+ ptr = lib.LLVMGetRelocationSymbol(self)
+ return Symbol(ptr)
+
+ @CachedProperty
+ def type_number(self):
+ """The relocation type, as a long."""
+ if self.expired:
+ raise Exception('Relocation instance has expired.')
+
+ return lib.LLVMGetRelocationType(self)
+
+ @CachedProperty
+ def type_name(self):
+ """The relocation type's name, as a str."""
+ if self.expired:
+ raise Exception('Relocation instance has expired.')
+
+ return lib.LLVMGetRelocationTypeName(self)
+
+ @CachedProperty
+ def value_string(self):
+ if self.expired:
+ raise Exception('Relocation instance has expired.')
+
+ return lib.LLVMGetRelocationValueString(self)
+
+ def expire(self):
+ """Expire this instance, making future API accesses fail."""
+ self.expired = True
+
+ def cache(self):
+ """Cache all cacheable properties on this instance."""
+ getattr(self, 'address')
+ getattr(self, 'offset')
+ getattr(self, 'symbol')
+ getattr(self, 'type')
+ getattr(self, 'type_name')
+ getattr(self, 'value_string')
+
+def register_library(library):
+ """Register function prototypes with LLVM library instance."""
+
+ # Object.h functions
+ library.LLVMCreateObjectFile.argtypes = [MemoryBuffer]
+ library.LLVMCreateObjectFile.restype = c_object_p
+
+ library.LLVMDisposeObjectFile.argtypes = [ObjectFile]
+
+ library.LLVMGetSections.argtypes = [ObjectFile]
+ library.LLVMGetSections.restype = c_object_p
+
+ library.LLVMDisposeSectionIterator.argtypes = [c_object_p]
+
+ library.LLVMIsSectionIteratorAtEnd.argtypes = [ObjectFile, c_object_p]
+ library.LLVMIsSectionIteratorAtEnd.restype = bool
+
+ library.LLVMMoveToNextSection.argtypes = [c_object_p]
+
+ library.LLVMMoveToContainingSection.argtypes = [c_object_p, c_object_p]
+
+ library.LLVMGetSymbols.argtypes = [ObjectFile]
+ library.LLVMGetSymbols.restype = c_object_p
+
+ library.LLVMDisposeSymbolIterator.argtypes = [c_object_p]
+
+ library.LLVMIsSymbolIteratorAtEnd.argtypes = [ObjectFile, c_object_p]
+ library.LLVMIsSymbolIteratorAtEnd.restype = bool
+
+ library.LLVMMoveToNextSymbol.argtypes = [c_object_p]
+
+ library.LLVMGetSectionName.argtypes = [c_object_p]
+ library.LLVMGetSectionName.restype = c_char_p
+
+ library.LLVMGetSectionSize.argtypes = [c_object_p]
+ library.LLVMGetSectionSize.restype = c_uint64
+
+ library.LLVMGetSectionContents.argtypes = [c_object_p]
+ library.LLVMGetSectionContents.restype = c_char_p
+
+ library.LLVMGetSectionAddress.argtypes = [c_object_p]
+ library.LLVMGetSectionAddress.restype = c_uint64
+
+ library.LLVMGetSectionContainsSymbol.argtypes = [c_object_p, c_object_p]
+ library.LLVMGetSectionContainsSymbol.restype = bool
+
+ library.LLVMGetRelocations.argtypes = [c_object_p]
+ library.LLVMGetRelocations.restype = c_object_p
+
+ library.LLVMDisposeRelocationIterator.argtypes = [c_object_p]
+
+ library.LLVMIsRelocationIteratorAtEnd.argtypes = [c_object_p, c_object_p]
+ library.LLVMIsRelocationIteratorAtEnd.restype = bool
+
+ library.LLVMMoveToNextRelocation.argtypes = [c_object_p]
+
+ library.LLVMGetSymbolName.argtypes = [Symbol]
+ library.LLVMGetSymbolName.restype = c_char_p
+
+ library.LLVMGetSymbolAddress.argtypes = [Symbol]
+ library.LLVMGetSymbolAddress.restype = c_uint64
+
+ library.LLVMGetSymbolFileOffset.argtypes = [Symbol]
+ library.LLVMGetSymbolFileOffset.restype = c_uint64
+
+ library.LLVMGetSymbolSize.argtypes = [Symbol]
+ library.LLVMGetSymbolSize.restype = c_uint64
+
+ library.LLVMGetRelocationAddress.argtypes = [c_object_p]
+ library.LLVMGetRelocationAddress.restype = c_uint64
+
+ library.LLVMGetRelocationOffset.argtypes = [c_object_p]
+ library.LLVMGetRelocationOffset.restype = c_uint64
+
+ library.LLVMGetRelocationSymbol.argtypes = [c_object_p]
+ library.LLVMGetRelocationSymbol.restype = c_object_p
+
+ library.LLVMGetRelocationType.argtypes = [c_object_p]
+ library.LLVMGetRelocationType.restype = c_uint64
+
+ library.LLVMGetRelocationTypeName.argtypes = [c_object_p]
+ library.LLVMGetRelocationTypeName.restype = c_char_p
+
+ library.LLVMGetRelocationValueString.argtypes = [c_object_p]
+ library.LLVMGetRelocationValueString.restype = c_char_p
+
+lib = get_library()
+register_library(lib)
diff --git a/bindings/python/llvm/tests/__init__.py b/bindings/python/llvm/tests/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
--- /dev/null
+++ b/bindings/python/llvm/tests/__init__.py
diff --git a/bindings/python/llvm/tests/base.py b/bindings/python/llvm/tests/base.py
new file mode 100644
index 00000000000..ff9eb2fc143
--- /dev/null
+++ b/bindings/python/llvm/tests/base.py
@@ -0,0 +1,32 @@
+import os.path
+import unittest
+
+POSSIBLE_TEST_BINARIES = [
+ 'libreadline.so.5',
+ 'libreadline.so.6',
+]
+
+POSSIBLE_TEST_BINARY_PATHS = [
+ '/usr/lib/debug',
+ '/lib',
+ '/usr/lib',
+ '/usr/local/lib',
+ '/lib/i386-linux-gnu',
+]
+
+class TestBase(unittest.TestCase):
+ def get_test_binary(self):
+ """Helper to obtain a test binary for object file testing.
+
+ FIXME Support additional, highly-likely targets or create one
+ ourselves.
+ """
+ for d in POSSIBLE_TEST_BINARY_PATHS:
+ for lib in POSSIBLE_TEST_BINARIES:
+ path = os.path.join(d, lib)
+
+ if os.path.exists(path):
+ return path
+
+ raise Exception('No suitable test binaries available!')
+ get_test_binary.__test__ = False
diff --git a/bindings/python/llvm/tests/test_core.py b/bindings/python/llvm/tests/test_core.py
new file mode 100644
index 00000000000..545abc826ea
--- /dev/null
+++ b/bindings/python/llvm/tests/test_core.py
@@ -0,0 +1,23 @@
+from .base import TestBase
+from ..core import OpCode
+from ..core import MemoryBuffer
+
+class TestCore(TestBase):
+ def test_opcode(self):
+ self.assertTrue(hasattr(OpCode, 'Ret'))
+ self.assertTrue(isinstance(OpCode.Ret, OpCode))
+ self.assertEqual(OpCode.Ret.value, 1)
+
+ op = OpCode.from_value(1)
+ self.assertTrue(isinstance(op, OpCode))
+ self.assertEqual(op, OpCode.Ret)
+
+ def test_memory_buffer_create_from_file(self):
+ source = self.get_test_binary()
+
+ MemoryBuffer(filename=source)
+
+ def test_memory_buffer_failing(self):
+ with self.assertRaises(Exception):
+ MemoryBuffer(filename="/hopefully/this/path/doesnt/exist")
+
diff --git a/bindings/python/llvm/tests/test_disassembler.py b/bindings/python/llvm/tests/test_disassembler.py
new file mode 100644
index 00000000000..545e8668b6c
--- /dev/null
+++ b/bindings/python/llvm/tests/test_disassembler.py
@@ -0,0 +1,28 @@
+from .base import TestBase
+
+from ..disassembler import Disassembler
+
+class TestDisassembler(TestBase):
+ def test_instantiate(self):
+ Disassembler('i686-apple-darwin9')
+
+ def test_basic(self):
+ sequence = '\x67\xe3\x81' # jcxz -127
+ triple = 'i686-apple-darwin9'
+
+ disassembler = Disassembler(triple)
+
+ count, s = disassembler.get_instruction(sequence)
+ self.assertEqual(count, 3)
+ self.assertEqual(s, '\tjcxz\t-127')
+
+ def test_get_instructions(self):
+ sequence = '\x67\xe3\x81\x01\xc7' # jcxz -127; addl %eax, %edi
+
+ disassembler = Disassembler('i686-apple-darwin9')
+
+ instructions = list(disassembler.get_instructions(sequence))
+ self.assertEqual(len(instructions), 2)
+
+ self.assertEqual(instructions[0], (0, 3, '\tjcxz\t-127'))
+ self.assertEqual(instructions[1], (3, 2, '\taddl\t%eax, %edi'))
diff --git a/bindings/python/llvm/tests/test_object.py b/bindings/python/llvm/tests/test_object.py
new file mode 100644
index 00000000000..7ff981b6a2f
--- /dev/null
+++ b/bindings/python/llvm/tests/test_object.py
@@ -0,0 +1,67 @@
+from .base import TestBase
+from ..object import ObjectFile
+from ..object import Relocation
+from ..object import Section
+from ..object import Symbol
+
+class TestObjectFile(TestBase):
+ def get_object_file(self):
+ source = self.get_test_binary()
+ return ObjectFile(filename=source)
+
+ def test_create_from_file(self):
+ self.get_object_file()
+
+ def test_get_sections(self):
+ o = self.get_object_file()
+
+ count = 0
+ for section in o.get_sections():
+ count += 1
+ assert isinstance(section, Section)
+ assert isinstance(section.name, str)
+ assert isinstance(section.size, long)
+ assert isinstance(section.contents, str)
+ assert isinstance(section.address, long)
+
+ self.assertGreater(count, 0)
+
+ for section in o.get_sections():
+ section.cache()
+
+ def test_get_symbols(self):
+ o = self.get_object_file()
+
+ count = 0
+ for symbol in o.get_symbols():
+ count += 1
+ assert isinstance(symbol, Symbol)
+ assert isinstance(symbol.name, str)
+ assert isinstance(symbol.address, long)
+ assert isinstance(symbol.size, long)
+ assert isinstance(symbol.file_offset, long)
+
+ self.assertGreater(count, 0)
+
+ for symbol in o.get_symbols():
+ symbol.cache()
+
+ def test_symbol_section_accessor(self):
+ o = self.get_object_file()
+
+ for symbol in o.get_symbols():
+ section = symbol.section
+ assert isinstance(section, Section)
+
+ break
+
+ def test_get_relocations(self):
+ o = self.get_object_file()
+ for section in o.get_sections():
+ for relocation in section.get_relocations():
+ assert isinstance(relocation, Relocation)
+ assert isinstance(relocation.address, long)
+ assert isinstance(relocation.offset, long)
+ assert isinstance(relocation.type_number, long)
+ assert isinstance(relocation.type_name, str)
+ assert isinstance(relocation.value_string, str)
diff --git a/cmake/README b/cmake/README
new file mode 100644
index 00000000000..4aafdbf32a3
--- /dev/null
+++ b/cmake/README
@@ -0,0 +1 @@
+See docs/CMake.html for instructions on how to build LLVM with CMake.
diff --git a/cmake/config-ix.cmake b/cmake/config-ix.cmake
new file mode 100755
index 00000000000..fcd5dd55667
--- /dev/null
+++ b/cmake/config-ix.cmake
@@ -0,0 +1,419 @@
+if( WIN32 AND NOT CYGWIN )
+ # We consider Cygwin as another Unix
+ set(PURE_WINDOWS 1)
+endif()
+
+include(CheckIncludeFile)
+include(CheckLibraryExists)
+include(CheckSymbolExists)
+include(CheckFunctionExists)
+include(CheckCXXSourceCompiles)
+include(TestBigEndian)
+
+if( UNIX AND NOT BEOS )
+ # Used by check_symbol_exists:
+ set(CMAKE_REQUIRED_LIBRARIES m)
+endif()
+
+# Helper macros and functions
+macro(add_cxx_include result files)
+ set(${result} "")
+ foreach (file_name ${files})
+ set(${result} "${${result}}#include<${file_name}>\n")
+ endforeach()
+endmacro(add_cxx_include files result)
+
+function(check_type_exists type files variable)
+ add_cxx_include(includes "${files}")
+ CHECK_CXX_SOURCE_COMPILES("
+ ${includes} ${type} typeVar;
+ int main() {
+ return 0;
+ }
+ " ${variable})
+endfunction()
+
+# include checks
+check_include_file(argz.h HAVE_ARGZ_H)
+check_include_file(assert.h HAVE_ASSERT_H)
+check_include_file(ctype.h HAVE_CTYPE_H)
+check_include_file(dirent.h HAVE_DIRENT_H)
+check_include_file(dl.h HAVE_DL_H)
+check_include_file(dld.h HAVE_DLD_H)
+check_include_file(dlfcn.h HAVE_DLFCN_H)
+check_include_file(errno.h HAVE_ERRNO_H)
+check_include_file(execinfo.h HAVE_EXECINFO_H)
+check_include_file(fcntl.h HAVE_FCNTL_H)
+check_include_file(inttypes.h HAVE_INTTYPES_H)
+check_include_file(limits.h HAVE_LIMITS_H)
+check_include_file(link.h HAVE_LINK_H)
+check_include_file(malloc.h HAVE_MALLOC_H)
+check_include_file(malloc/malloc.h HAVE_MALLOC_MALLOC_H)
+check_include_file(memory.h HAVE_MEMORY_H)
+check_include_file(ndir.h HAVE_NDIR_H)
+if( NOT PURE_WINDOWS )
+ check_include_file(pthread.h HAVE_PTHREAD_H)
+endif()
+check_include_file(setjmp.h HAVE_SETJMP_H)
+check_include_file(signal.h HAVE_SIGNAL_H)
+check_include_file(stdint.h HAVE_STDINT_H)
+check_include_file(stdio.h HAVE_STDIO_H)
+check_include_file(stdlib.h HAVE_STDLIB_H)
+check_include_file(string.h HAVE_STRING_H)
+check_include_file(strings.h HAVE_STRINGS_H)
+check_include_file(sys/dir.h HAVE_SYS_DIR_H)
+check_include_file(sys/dl.h HAVE_SYS_DL_H)
+check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H)
+check_include_file(sys/mman.h HAVE_SYS_MMAN_H)
+check_include_file(sys/ndir.h HAVE_SYS_NDIR_H)
+check_include_file(sys/param.h HAVE_SYS_PARAM_H)
+check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H)
+check_include_file(sys/stat.h HAVE_SYS_STAT_H)
+check_include_file(sys/time.h HAVE_SYS_TIME_H)
+check_include_file(sys/types.h HAVE_SYS_TYPES_H)
+check_include_file(sys/uio.h HAVE_SYS_UIO_H)
+check_include_file(sys/wait.h HAVE_SYS_WAIT_H)
+check_include_file(termios.h HAVE_TERMIOS_H)
+check_include_file(unistd.h HAVE_UNISTD_H)
+check_include_file(utime.h HAVE_UTIME_H)
+check_include_file(valgrind/valgrind.h HAVE_VALGRIND_VALGRIND_H)
+check_include_file(windows.h HAVE_WINDOWS_H)
+check_include_file(fenv.h HAVE_FENV_H)
+check_include_file(mach/mach.h HAVE_MACH_MACH_H)
+check_include_file(mach-o/dyld.h HAVE_MACH_O_DYLD_H)
+
+# library checks
+if( NOT PURE_WINDOWS )
+ check_library_exists(pthread pthread_create "" HAVE_LIBPTHREAD)
+ if (HAVE_LIBPTHREAD)
+ check_library_exists(pthread pthread_getspecific "" HAVE_PTHREAD_GETSPECIFIC)
+ check_library_exists(pthread pthread_rwlock_init "" HAVE_PTHREAD_RWLOCK_INIT)
+ check_library_exists(pthread pthread_mutex_lock "" HAVE_PTHREAD_MUTEX_LOCK)
+ else()
+ # this could be Android
+ check_library_exists(c pthread_create "" PTHREAD_IN_LIBC)
+ if (PTHREAD_IN_LIBC)
+ check_library_exists(c pthread_getspecific "" HAVE_PTHREAD_GETSPECIFIC)
+ check_library_exists(c pthread_rwlock_init "" HAVE_PTHREAD_RWLOCK_INIT)
+ check_library_exists(c pthread_mutex_lock "" HAVE_PTHREAD_MUTEX_LOCK)
+ endif()
+ endif()
+ check_library_exists(dl dlopen "" HAVE_LIBDL)
+endif()
+
+# function checks
+check_symbol_exists(arc4random "stdlib.h" HAVE_ARC4RANDOM)
+check_symbol_exists(backtrace "execinfo.h" HAVE_BACKTRACE)
+check_symbol_exists(getpagesize unistd.h HAVE_GETPAGESIZE)
+check_symbol_exists(getrusage sys/resource.h HAVE_GETRUSAGE)
+check_symbol_exists(setrlimit sys/resource.h HAVE_SETRLIMIT)
+check_symbol_exists(isatty unistd.h HAVE_ISATTY)
+check_symbol_exists(index strings.h HAVE_INDEX)
+check_symbol_exists(isinf cmath HAVE_ISINF_IN_CMATH)
+check_symbol_exists(isinf math.h HAVE_ISINF_IN_MATH_H)
+check_symbol_exists(finite ieeefp.h HAVE_FINITE_IN_IEEEFP_H)
+check_symbol_exists(isnan cmath HAVE_ISNAN_IN_CMATH)
+check_symbol_exists(isnan math.h HAVE_ISNAN_IN_MATH_H)
+check_symbol_exists(ceilf math.h HAVE_CEILF)
+check_symbol_exists(floorf math.h HAVE_FLOORF)
+check_symbol_exists(fmodf math.h HAVE_FMODF)
+if( HAVE_SETJMP_H )
+ check_symbol_exists(longjmp setjmp.h HAVE_LONGJMP)
+ check_symbol_exists(setjmp setjmp.h HAVE_SETJMP)
+ check_symbol_exists(siglongjmp setjmp.h HAVE_SIGLONGJMP)
+ check_symbol_exists(sigsetjmp setjmp.h HAVE_SIGSETJMP)
+endif()
+if( HAVE_SYS_UIO_H )
+ check_symbol_exists(writev sys/uio.h HAVE_WRITEV)
+endif()
+check_symbol_exists(nearbyintf math.h HAVE_NEARBYINTF)
+check_symbol_exists(mallinfo malloc.h HAVE_MALLINFO)
+check_symbol_exists(malloc_zone_statistics malloc/malloc.h
+ HAVE_MALLOC_ZONE_STATISTICS)
+check_symbol_exists(mkdtemp "stdlib.h;unistd.h" HAVE_MKDTEMP)
+check_symbol_exists(mkstemp "stdlib.h;unistd.h" HAVE_MKSTEMP)
+check_symbol_exists(mktemp "stdlib.h;unistd.h" HAVE_MKTEMP)
+check_symbol_exists(closedir "sys/types.h;dirent.h" HAVE_CLOSEDIR)
+check_symbol_exists(opendir "sys/types.h;dirent.h" HAVE_OPENDIR)
+check_symbol_exists(readdir "sys/types.h;dirent.h" HAVE_READDIR)
+check_symbol_exists(getcwd unistd.h HAVE_GETCWD)
+check_symbol_exists(gettimeofday sys/time.h HAVE_GETTIMEOFDAY)
+check_symbol_exists(getrlimit "sys/types.h;sys/time.h;sys/resource.h" HAVE_GETRLIMIT)
+check_symbol_exists(posix_spawn spawn.h HAVE_POSIX_SPAWN)
+check_symbol_exists(pread unistd.h HAVE_PREAD)
+check_symbol_exists(rindex strings.h HAVE_RINDEX)
+check_symbol_exists(strchr string.h HAVE_STRCHR)
+check_symbol_exists(strcmp string.h HAVE_STRCMP)
+check_symbol_exists(strdup string.h HAVE_STRDUP)
+check_symbol_exists(strrchr string.h HAVE_STRRCHR)
+check_symbol_exists(sbrk unistd.h HAVE_SBRK)
+check_symbol_exists(srand48 stdlib.h HAVE_RAND48_SRAND48)
+if( HAVE_RAND48_SRAND48 )
+ check_symbol_exists(lrand48 stdlib.h HAVE_RAND48_LRAND48)
+ if( HAVE_RAND48_LRAND48 )
+ check_symbol_exists(drand48 stdlib.h HAVE_RAND48_DRAND48)
+ if( HAVE_RAND48_DRAND48 )
+ set(HAVE_RAND48 1 CACHE INTERNAL "are srand48/lrand48/drand48 available?")
+ endif()
+ endif()
+endif()
+check_symbol_exists(strtoll stdlib.h HAVE_STRTOLL)
+check_symbol_exists(strtoq stdlib.h HAVE_STRTOQ)
+check_symbol_exists(strerror string.h HAVE_STRERROR)
+check_symbol_exists(strerror_r string.h HAVE_STRERROR_R)
+check_symbol_exists(strerror_s string.h HAVE_DECL_STRERROR_S)
+check_symbol_exists(memcpy string.h HAVE_MEMCPY)
+check_symbol_exists(memmove string.h HAVE_MEMMOVE)
+check_symbol_exists(setenv stdlib.h HAVE_SETENV)
+if( PURE_WINDOWS )
+ check_symbol_exists(_chsize_s io.h HAVE__CHSIZE_S)
+
+ check_function_exists(_alloca HAVE__ALLOCA)
+ check_function_exists(__alloca HAVE___ALLOCA)
+ check_function_exists(__chkstk HAVE___CHKSTK)
+ check_function_exists(___chkstk HAVE____CHKSTK)
+
+ check_function_exists(__ashldi3 HAVE___ASHLDI3)
+ check_function_exists(__ashrdi3 HAVE___ASHRDI3)
+ check_function_exists(__divdi3 HAVE___DIVDI3)
+ check_function_exists(__fixdfdi HAVE___FIXDFDI)
+ check_function_exists(__fixsfdi HAVE___FIXSFDI)
+ check_function_exists(__floatdidf HAVE___FLOATDIDF)
+ check_function_exists(__lshrdi3 HAVE___LSHRDI3)
+ check_function_exists(__moddi3 HAVE___MODDI3)
+ check_function_exists(__udivdi3 HAVE___UDIVDI3)
+ check_function_exists(__umoddi3 HAVE___UMODDI3)
+
+ check_function_exists(__main HAVE___MAIN)
+ check_function_exists(__cmpdi2 HAVE___CMPDI2)
+endif()
+if( HAVE_ARGZ_H )
+ check_symbol_exists(argz_append argz.h HAVE_ARGZ_APPEND)
+ check_symbol_exists(argz_create_sep argz.h HAVE_ARGZ_CREATE_SEP)
+ check_symbol_exists(argz_insert argz.h HAVE_ARGZ_INSERT)
+ check_symbol_exists(argz_next argz.h HAVE_ARGZ_NEXT)
+ check_symbol_exists(argz_stringify argz.h HAVE_ARGZ_STRINGIFY)
+endif()
+if( HAVE_DLFCN_H )
+ if( HAVE_LIBDL )
+ list(APPEND CMAKE_REQUIRED_LIBRARIES dl)
+ endif()
+ check_symbol_exists(dlerror dlfcn.h HAVE_DLERROR)
+ check_symbol_exists(dlopen dlfcn.h HAVE_DLOPEN)
+ if( HAVE_LIBDL )
+ list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES dl)
+ endif()
+endif()
+
+check_symbol_exists(__GLIBC__ stdio.h LLVM_USING_GLIBC)
+if( LLVM_USING_GLIBC )
+ add_llvm_definitions( -D_GNU_SOURCE )
+endif()
+
+set(headers "")
+if (HAVE_SYS_TYPES_H)
+ set(headers ${headers} "sys/types.h")
+endif()
+
+if (HAVE_INTTYPES_H)
+ set(headers ${headers} "inttypes.h")
+endif()
+
+if (HAVE_STDINT_H)
+ set(headers ${headers} "stdint.h")
+endif()
+
+check_type_exists(int64_t "${headers}" HAVE_INT64_T)
+check_type_exists(uint64_t "${headers}" HAVE_UINT64_T)
+check_type_exists(u_int64_t "${headers}" HAVE_U_INT64_T)
+check_type_exists(error_t errno.h HAVE_ERROR_T)
+
+# available programs checks
+function(llvm_find_program name)
+ string(TOUPPER ${name} NAME)
+ string(REGEX REPLACE "\\." "_" NAME ${NAME})
+ find_program(LLVM_PATH_${NAME} ${name})
+ mark_as_advanced(LLVM_PATH_${NAME})
+ if(LLVM_PATH_${NAME})
+ set(HAVE_${NAME} 1 CACHE INTERNAL "Is ${name} available ?")
+ mark_as_advanced(HAVE_${NAME})
+ else(LLVM_PATH_${NAME})
+ set(HAVE_${NAME} "" CACHE INTERNAL "Is ${name} available ?")
+ endif(LLVM_PATH_${NAME})
+endfunction()
+
+llvm_find_program(gv)
+llvm_find_program(circo)
+llvm_find_program(twopi)
+llvm_find_program(neato)
+llvm_find_program(fdp)
+llvm_find_program(dot)
+llvm_find_program(dotty)
+llvm_find_program(xdot.py)
+llvm_find_program(Graphviz)
+
+if( LLVM_ENABLE_FFI )
+ find_path(FFI_INCLUDE_PATH ffi.h PATHS ${FFI_INCLUDE_DIR})
+ if( FFI_INCLUDE_PATH )
+ set(FFI_HEADER ffi.h CACHE INTERNAL "")
+ set(HAVE_FFI_H 1 CACHE INTERNAL "")
+ else()
+ find_path(FFI_INCLUDE_PATH ffi/ffi.h PATHS ${FFI_INCLUDE_DIR})
+ if( FFI_INCLUDE_PATH )
+ set(FFI_HEADER ffi/ffi.h CACHE INTERNAL "")
+ set(HAVE_FFI_FFI_H 1 CACHE INTERNAL "")
+ endif()
+ endif()
+
+ if( NOT FFI_HEADER )
+ message(FATAL_ERROR "libffi includes are not found.")
+ endif()
+
+ find_library(FFI_LIBRARY_PATH ffi PATHS ${FFI_LIBRARY_DIR})
+ if( NOT FFI_LIBRARY_PATH )
+ message(FATAL_ERROR "libffi is not found.")
+ endif()
+
+ list(APPEND CMAKE_REQUIRED_LIBRARIES ${FFI_LIBRARY_PATH})
+ list(APPEND CMAKE_REQUIRED_INCLUDES ${FFI_INCLUDE_PATH})
+ check_symbol_exists(ffi_call ${FFI_HEADER} HAVE_FFI_CALL)
+ list(REMOVE_ITEM CMAKE_REQUIRED_INCLUDES ${FFI_INCLUDE_PATH})
+ list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES ${FFI_LIBRARY_PATH})
+else()
+ unset(HAVE_FFI_FFI_H CACHE)
+ unset(HAVE_FFI_H CACHE)
+ unset(HAVE_FFI_CALL CACHE)
+endif( LLVM_ENABLE_FFI )
+
+# Define LLVM_HAS_ATOMICS if gcc or MSVC atomic builtins are supported.
+include(CheckAtomic)
+
+if( LLVM_ENABLE_PIC )
+ set(ENABLE_PIC 1)
+else()
+ set(ENABLE_PIC 0)
+endif()
+
+include(CheckCXXCompilerFlag)
+
+check_cxx_compiler_flag("-Wno-variadic-macros" SUPPORTS_NO_VARIADIC_MACROS_FLAG)
+
+include(GetHostTriple)
+get_host_triple(LLVM_HOST_TRIPLE)
+
+# By default, we target the host, but this can be overridden at CMake
+# invocation time.
+set(LLVM_HOSTTRIPLE "${LLVM_HOST_TRIPLE}")
+
+# Determine the native architecture.
+string(TOLOWER "${LLVM_TARGET_ARCH}" LLVM_NATIVE_ARCH)
+if( LLVM_NATIVE_ARCH STREQUAL "host" )
+ string(REGEX MATCH "^[^-]*" LLVM_NATIVE_ARCH ${LLVM_HOST_TRIPLE})
+endif ()
+
+if (LLVM_NATIVE_ARCH MATCHES "i[2-6]86")
+ set(LLVM_NATIVE_ARCH X86)
+elseif (LLVM_NATIVE_ARCH STREQUAL "x86")
+ set(LLVM_NATIVE_ARCH X86)
+elseif (LLVM_NATIVE_ARCH STREQUAL "amd64")
+ set(LLVM_NATIVE_ARCH X86)
+elseif (LLVM_NATIVE_ARCH STREQUAL "x86_64")
+ set(LLVM_NATIVE_ARCH X86)
+elseif (LLVM_NATIVE_ARCH MATCHES "sparc")
+ set(LLVM_NATIVE_ARCH Sparc)
+elseif (LLVM_NATIVE_ARCH MATCHES "powerpc")
+ set(LLVM_NATIVE_ARCH PowerPC)
+elseif (LLVM_NATIVE_ARCH MATCHES "arm")
+ set(LLVM_NATIVE_ARCH ARM)
+elseif (LLVM_NATIVE_ARCH MATCHES "mips")
+ set(LLVM_NATIVE_ARCH Mips)
+elseif (LLVM_NATIVE_ARCH MATCHES "xcore")
+ set(LLVM_NATIVE_ARCH XCore)
+elseif (LLVM_NATIVE_ARCH MATCHES "msp430")
+ set(LLVM_NATIVE_ARCH MSP430)
+elseif (LLVM_NATIVE_ARCH MATCHES "hexagon")
+ set(LLVM_NATIVE_ARCH Hexagon)
+else ()
+ message(FATAL_ERROR "Unknown architecture ${LLVM_NATIVE_ARCH}")
+endif ()
+
+list(FIND LLVM_TARGETS_TO_BUILD ${LLVM_NATIVE_ARCH} NATIVE_ARCH_IDX)
+if (NATIVE_ARCH_IDX EQUAL -1)
+ message(STATUS
+ "Native target ${LLVM_NATIVE_ARCH} is not selected; lli will not JIT code")
+else ()
+ message(STATUS "Native target architecture is ${LLVM_NATIVE_ARCH}")
+ set(LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target)
+ set(LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo)
+ set(LLVM_NATIVE_TARGETMC LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC)
+ set(LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter)
+
+ # We don't have an ASM parser for all architectures yet.
+ if (EXISTS ${CMAKE_SOURCE_DIR}/lib/Target/${LLVM_NATIVE_ARCH}/AsmParser/CMakeLists.txt)
+ set(LLVM_NATIVE_ASMPARSER LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser)
+ endif ()
+
+ # We don't have an disassembler for all architectures yet.
+ if (EXISTS ${CMAKE_SOURCE_DIR}/lib/Target/${LLVM_NATIVE_ARCH}/Disassembler/CMakeLists.txt)
+ set(LLVM_NATIVE_DISASSEMBLER LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler)
+ endif ()
+endif ()
+
+if( MINGW )
+ set(HAVE_LIBIMAGEHLP 1)
+ set(HAVE_LIBPSAPI 1)
+ # TODO: Check existence of libraries.
+ # include(CheckLibraryExists)
+ # CHECK_LIBRARY_EXISTS(imagehlp ??? . HAVE_LIBIMAGEHLP)
+endif( MINGW )
+
+if( MSVC )
+ set(error_t int)
+ set(LTDL_SHLIBPATH_VAR "PATH")
+ set(LTDL_SYSSEARCHPATH "")
+ set(LTDL_DLOPEN_DEPLIBS 1)
+ set(SHLIBEXT ".lib")
+ set(LTDL_OBJDIR "_libs")
+ set(HAVE_STRTOLL 1)
+ set(strtoll "_strtoi64")
+ set(strtoull "_strtoui64")
+ set(stricmp "_stricmp")
+ set(strdup "_strdup")
+else( MSVC )
+ set(LTDL_SHLIBPATH_VAR "LD_LIBRARY_PATH")
+ set(LTDL_SYSSEARCHPATH "") # TODO
+ set(LTDL_DLOPEN_DEPLIBS 0) # TODO
+endif( MSVC )
+
+if( PURE_WINDOWS )
+ CHECK_CXX_SOURCE_COMPILES("
+ #include <windows.h>
+ #include <imagehlp.h>
+ extern \"C\" void foo(PENUMLOADED_MODULES_CALLBACK);
+ extern \"C\" void foo(BOOL(CALLBACK*)(PCSTR,ULONG_PTR,ULONG,PVOID));
+ int main(){return 0;}"
+ HAVE_ELMCB_PCSTR)
+ if( HAVE_ELMCB_PCSTR )
+ set(WIN32_ELMCB_PCSTR "PCSTR")
+ else()
+ set(WIN32_ELMCB_PCSTR "PSTR")
+ endif()
+endif( PURE_WINDOWS )
+
+# FIXME: Signal handler return type, currently hardcoded to 'void'
+set(RETSIGTYPE void)
+
+if( LLVM_ENABLE_THREADS )
+ # Check if threading primitives aren't supported on this platform
+ if( NOT HAVE_PTHREAD_H AND NOT WIN32 )
+ set(LLVM_ENABLE_THREADS 0)
+ endif()
+endif()
+
+if( LLVM_ENABLE_THREADS )
+ message(STATUS "Threads enabled.")
+else( LLVM_ENABLE_THREADS )
+ message(STATUS "Threads disabled.")
+endif()
+
+set(LLVM_PREFIX ${CMAKE_INSTALL_PREFIX})
diff --git a/cmake/modules/AddLLVM.cmake b/cmake/modules/AddLLVM.cmake
new file mode 100755
index 00000000000..f44a27cce83
--- /dev/null
+++ b/cmake/modules/AddLLVM.cmake
@@ -0,0 +1,294 @@
+include(LLVMParseArguments)
+include(LLVMProcessSources)
+include(LLVM-Config)
+
+macro(add_llvm_library name)
+ llvm_process_sources( ALL_FILES ${ARGN} )
+ add_library( ${name} ${ALL_FILES} )
+ set_property( GLOBAL APPEND PROPERTY LLVM_LIBS ${name} )
+ if( LLVM_COMMON_DEPENDS )
+ add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} )
+ endif( LLVM_COMMON_DEPENDS )
+
+ if( BUILD_SHARED_LIBS )
+ llvm_config( ${name} ${LLVM_LINK_COMPONENTS} )
+ endif()
+
+ # Ensure that the system libraries always comes last on the
+ # list. Without this, linking the unit tests on MinGW fails.
+ link_system_libs( ${name} )
+
+ if( EXCLUDE_FROM_ALL )
+ set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
+ else()
+ install(TARGETS ${name}
+ LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX}
+ ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX})
+ endif()
+ set_target_properties(${name} PROPERTIES FOLDER "Libraries")
+
+ # Add the explicit dependency information for this library.
+ #
+ # It would be nice to verify that we have the dependencies for this library
+ # name, but using get_property(... SET) doesn't suffice to determine if a
+ # property has been set to an empty value.
+ get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name})
+ target_link_libraries(${name} ${lib_deps})
+endmacro(add_llvm_library name)
+
+macro(add_llvm_loadable_module name)
+ if( NOT LLVM_ON_UNIX OR CYGWIN )
+ message(STATUS "Loadable modules not supported on this platform.
+${name} ignored.")
+ # Add empty "phony" target
+ add_custom_target(${name})
+ else()
+ llvm_process_sources( ALL_FILES ${ARGN} )
+ if (MODULE)
+ set(libkind MODULE)
+ else()
+ set(libkind SHARED)
+ endif()
+
+ add_library( ${name} ${libkind} ${ALL_FILES} )
+ set_target_properties( ${name} PROPERTIES PREFIX "" )
+
+ llvm_config( ${name} ${LLVM_LINK_COMPONENTS} )
+ link_system_libs( ${name} )
+
+ if (APPLE)
+ # Darwin-specific linker flags for loadable modules.
+ set_target_properties(${name} PROPERTIES
+ LINK_FLAGS "-Wl,-flat_namespace -Wl,-undefined -Wl,suppress")
+ endif()
+
+ if( EXCLUDE_FROM_ALL )
+ set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
+ else()
+ install(TARGETS ${name}
+ LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX}
+ ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX})
+ endif()
+ endif()
+
+ set_target_properties(${name} PROPERTIES FOLDER "Loadable modules")
+endmacro(add_llvm_loadable_module name)
+
+
+macro(add_llvm_executable name)
+ llvm_process_sources( ALL_FILES ${ARGN} )
+ if( EXCLUDE_FROM_ALL )
+ add_executable(${name} EXCLUDE_FROM_ALL ${ALL_FILES})
+ else()
+ add_executable(${name} ${ALL_FILES})
+ endif()
+ set(EXCLUDE_FROM_ALL OFF)
+ llvm_config( ${name} ${LLVM_LINK_COMPONENTS} )
+ if( LLVM_COMMON_DEPENDS )
+ add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} )
+ endif( LLVM_COMMON_DEPENDS )
+ link_system_libs( ${name} )
+endmacro(add_llvm_executable name)
+
+
+macro(add_llvm_tool name)
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LLVM_TOOLS_BINARY_DIR})
+ if( NOT LLVM_BUILD_TOOLS )
+ set(EXCLUDE_FROM_ALL ON)
+ endif()
+ add_llvm_executable(${name} ${ARGN})
+ if( LLVM_BUILD_TOOLS )
+ install(TARGETS ${name} RUNTIME DESTINATION bin)
+ endif()
+ set_target_properties(${name} PROPERTIES FOLDER "Tools")
+endmacro(add_llvm_tool name)
+
+
+macro(add_llvm_example name)
+# set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LLVM_EXAMPLES_BINARY_DIR})
+ if( NOT LLVM_BUILD_EXAMPLES )
+ set(EXCLUDE_FROM_ALL ON)
+ endif()
+ add_llvm_executable(${name} ${ARGN})
+ if( LLVM_BUILD_EXAMPLES )
+ install(TARGETS ${name} RUNTIME DESTINATION examples)
+ endif()
+ set_target_properties(${name} PROPERTIES FOLDER "Examples")
+endmacro(add_llvm_example name)
+
+
+macro(add_llvm_utility name)
+ add_llvm_executable(${name} ${ARGN})
+ set_target_properties(${name} PROPERTIES FOLDER "Utils")
+endmacro(add_llvm_utility name)
+
+
+macro(add_llvm_target target_name)
+ include_directories(BEFORE
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR})
+ add_llvm_library(LLVM${target_name} ${ARGN} ${TABLEGEN_OUTPUT})
+ set( CURRENT_LLVM_TARGET LLVM${target_name} )
+endmacro(add_llvm_target)
+
+# Add external project that may want to be built as part of llvm such as Clang,
+# lld, and Polly. This adds two options. One for the source directory of the
+# project, which defaults to ${CMAKE_CURRENT_SOURCE_DIR}/${name}. Another to
+# enable or disable building it with everthing else.
+macro(add_llvm_external_project name)
+ string(TOUPPER ${name} nameUPPER)
+ set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${name}"
+ CACHE PATH "Path to ${name} source directory")
+ if (NOT ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} STREQUAL ""
+ AND EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}/CMakeLists.txt)
+ option(LLVM_EXTERNAL_${nameUPPER}_BUILD
+ "Whether to build ${name} as part of LLVM" ON)
+ if (LLVM_EXTERNAL_${nameUPPER}_BUILD)
+ add_subdirectory(${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} ${name})
+ endif()
+ endif()
+endmacro(add_llvm_external_project)
+
+# Generic support for adding a unittest.
+function(add_unittest test_suite test_name)
+ if (CMAKE_BUILD_TYPE)
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY
+ ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE})
+ else()
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
+ endif()
+ if( NOT LLVM_BUILD_TESTS )
+ set(EXCLUDE_FROM_ALL ON)
+ endif()
+
+ add_llvm_executable(${test_name} ${ARGN})
+ target_link_libraries(${test_name}
+ gtest
+ gtest_main
+ LLVMSupport # gtest needs it for raw_ostream.
+ )
+
+ add_dependencies(${test_suite} ${test_name})
+ get_target_property(test_suite_folder ${test_suite} FOLDER)
+ if (NOT ${test_suite_folder} STREQUAL "NOTFOUND")
+ set_property(TARGET ${test_name} PROPERTY FOLDER "${test_suite_folder}")
+ endif ()
+
+ # Visual Studio 2012 only supports up to 8 template parameters in
+ # std::tr1::tuple by default, but gtest requires 10
+ if (MSVC AND MSVC_VERSION EQUAL 1700)
+ set_property(TARGET ${test_name} APPEND PROPERTY COMPILE_DEFINITIONS _VARIADIC_MAX=10)
+ endif ()
+
+ include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googletest/include)
+ set_property(TARGET ${test_name} APPEND PROPERTY COMPILE_DEFINITIONS GTEST_HAS_RTTI=0)
+ if (NOT LLVM_ENABLE_THREADS)
+ set_property(TARGET ${test_name} APPEND PROPERTY COMPILE_DEFINITIONS GTEST_HAS_PTHREAD=0)
+ endif ()
+
+ get_property(target_compile_flags TARGET ${test_name} PROPERTY COMPILE_FLAGS)
+ if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
+ set(target_compile_flags "${target_compile_flags} -fno-rtti")
+ elseif (MSVC)
+ set(target_compile_flags "${target_compile_flags} /GR-")
+ endif ()
+
+ if (SUPPORTS_NO_VARIADIC_MACROS_FLAG)
+ set(target_compile_flags "${target_compile_flags} -Wno-variadic-macros")
+ endif ()
+ set_property(TARGET ${test_name} PROPERTY COMPILE_FLAGS "${target_compile_flags}")
+endfunction()
+
+# This function provides an automatic way to 'configure'-like generate a file
+# based on a set of common and custom variables, specifically targetting the
+# variables needed for the 'lit.site.cfg' files. This function bundles the
+# common variables that any Lit instance is likely to need, and custom
+# variables can be passed in.
+function(configure_lit_site_cfg input output)
+ foreach(c ${LLVM_TARGETS_TO_BUILD})
+ set(TARGETS_BUILT "${TARGETS_BUILT} ${c}")
+ endforeach(c)
+ set(TARGETS_TO_BUILD ${TARGETS_BUILT})
+
+ set(SHLIBEXT "${LTDL_SHLIB_EXT}")
+ set(SHLIBDIR "${LLVM_BINARY_DIR}/lib/${CMAKE_CFG_INTDIR}")
+
+ if(BUILD_SHARED_LIBS)
+ set(LLVM_SHARED_LIBS_ENABLED "1")
+ else()
+ set(LLVM_SHARED_LIBS_ENABLED "0")
+ endif(BUILD_SHARED_LIBS)
+
+ if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
+ set(SHLIBPATH_VAR "DYLD_LIBRARY_PATH")
+ else() # Default for all other unix like systems.
+ # CMake hardcodes the library locaction using rpath.
+ # Therefore LD_LIBRARY_PATH is not required to run binaries in the
+ # build dir. We pass it anyways.
+ set(SHLIBPATH_VAR "LD_LIBRARY_PATH")
+ endif()
+
+ # Configuration-time: See Unit/lit.site.cfg.in
+ set(LLVM_BUILD_MODE "%(build_mode)s")
+
+ set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
+ set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
+ set(LLVM_TOOLS_DIR "${LLVM_TOOLS_BINARY_DIR}/%(build_config)s")
+ set(LLVM_LIBS_DIR "${LLVM_BINARY_DIR}/lib/%(build_config)s")
+ set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE})
+ set(ENABLE_SHARED ${LLVM_SHARED_LIBS_ENABLED})
+ set(SHLIBPATH_VAR ${SHLIBPATH_VAR})
+
+ if(LLVM_ENABLE_ASSERTIONS AND NOT MSVC_IDE)
+ set(ENABLE_ASSERTIONS "1")
+ else()
+ set(ENABLE_ASSERTIONS "0")
+ endif()
+
+ set(HOST_OS ${CMAKE_HOST_SYSTEM_NAME})
+ set(HOST_ARCH ${CMAKE_HOST_SYSTEM_PROCESSOR})
+
+ configure_file(${input} ${output} @ONLY)
+endfunction()
+
+# A raw function to create a lit target. This is used to implement the testuite
+# management functions.
+function(add_lit_target target comment)
+ parse_arguments(ARG "PARAMS;DEPENDS;ARGS" "" ${ARGN})
+ set(LIT_ARGS "${ARG_ARGS} ${LLVM_LIT_ARGS}")
+ separate_arguments(LIT_ARGS)
+ set(LIT_COMMAND
+ ${PYTHON_EXECUTABLE}
+ ${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py
+ --param build_config=${CMAKE_CFG_INTDIR}
+ --param build_mode=${RUNTIME_BUILD_MODE}
+ ${LIT_ARGS}
+ )
+ foreach(param ${ARG_PARAMS})
+ list(APPEND LIT_COMMAND --param ${param})
+ endforeach()
+ add_custom_target(${target}
+ COMMAND ${LIT_COMMAND} ${ARG_DEFAULT_ARGS}
+ COMMENT "${comment}"
+ )
+ add_dependencies(${target} ${ARG_DEPENDS})
+endfunction()
+
+# A function to add a set of lit test suites to be driven through 'check-*' targets.
+function(add_lit_testsuite target comment)
+ parse_arguments(ARG "PARAMS;DEPENDS;ARGS" "" ${ARGN})
+
+ # Register the testsuites, params and depends for the global check rule.
+ set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${ARG_DEFAULT_ARGS})
+ set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${ARG_PARAMS})
+ set_property(GLOBAL APPEND PROPERTY LLVM_LIT_DEPENDS ${ARG_DEPENDS})
+ set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${ARG_ARGS})
+
+ # Produce a specific suffixed check rule.
+ add_lit_target(${target} ${comment}
+ ${ARG_DEFAULT_ARGS}
+ PARAMS ${ARG_PARAMS}
+ DEPENDS ${ARG_DEPENDS}
+ ARGS ${ARG_ARGS}
+ )
+endfunction()
diff --git a/cmake/modules/AddLLVMDefinitions.cmake b/cmake/modules/AddLLVMDefinitions.cmake
new file mode 100644
index 00000000000..33ac9731db5
--- /dev/null
+++ b/cmake/modules/AddLLVMDefinitions.cmake
@@ -0,0 +1,13 @@
+# There is no clear way of keeping track of compiler command-line
+# options chosen via `add_definitions', so we need our own method for
+# using it on tools/llvm-config/CMakeLists.txt.
+
+# Beware that there is no implementation of remove_llvm_definitions.
+
+macro(add_llvm_definitions)
+ # We don't want no semicolons on LLVM_DEFINITIONS:
+ foreach(arg ${ARGN})
+ set(LLVM_DEFINITIONS "${LLVM_DEFINITIONS} ${arg}")
+ endforeach(arg)
+ add_definitions( ${ARGN} )
+endmacro(add_llvm_definitions)
diff --git a/cmake/modules/CMakeLists.txt b/cmake/modules/CMakeLists.txt
new file mode 100644
index 00000000000..f51e9af8db0
--- /dev/null
+++ b/cmake/modules/CMakeLists.txt
@@ -0,0 +1,37 @@
+set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/share/llvm/cmake")
+set(LLVM_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX})
+
+get_property(llvm_libs GLOBAL PROPERTY LLVM_LIBS)
+
+foreach(lib ${llvm_libs})
+ get_property(llvm_lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${lib})
+ set(all_llvm_lib_deps
+ "${all_llvm_lib_deps}\nset_property(GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${lib} ${llvm_lib_deps})")
+endforeach(lib)
+
+configure_file(
+ LLVMConfig.cmake.in
+ ${llvm_cmake_builddir}/LLVMConfig.cmake
+ @ONLY)
+
+configure_file(
+ LLVMConfigVersion.cmake.in
+ ${llvm_cmake_builddir}/LLVMConfigVersion.cmake
+ @ONLY)
+
+install(FILES
+ ${llvm_cmake_builddir}/LLVMConfig.cmake
+ ${llvm_cmake_builddir}/LLVMConfigVersion.cmake
+ LLVM-Config.cmake
+ DESTINATION share/llvm/cmake)
+
+install(DIRECTORY .
+ DESTINATION share/llvm/cmake
+ FILES_MATCHING PATTERN *.cmake
+ PATTERN .svn EXCLUDE
+ PATTERN LLVMConfig.cmake EXCLUDE
+ PATTERN LLVMConfigVersion.cmake EXCLUDE
+ PATTERN LLVM-Config.cmake EXCLUDE
+ PATTERN GetHostTriple.cmake EXCLUDE
+ PATTERN VersionFromVCS.cmake EXCLUDE
+ PATTERN CheckAtomic.cmake EXCLUDE)
diff --git a/cmake/modules/CheckAtomic.cmake b/cmake/modules/CheckAtomic.cmake
new file mode 100644
index 00000000000..0d63a82b97a
--- /dev/null
+++ b/cmake/modules/CheckAtomic.cmake
@@ -0,0 +1,29 @@
+# atomic builtins are required for threading support.
+
+INCLUDE(CheckCXXSourceCompiles)
+
+CHECK_CXX_SOURCE_COMPILES("
+#ifdef _MSC_VER
+#include <windows.h>
+#endif
+int main() {
+#ifdef _MSC_VER
+ volatile LONG val = 1;
+ MemoryBarrier();
+ InterlockedCompareExchange(&val, 0, 1);
+ InterlockedIncrement(&val);
+ InterlockedDecrement(&val);
+#else
+ volatile unsigned long val = 1;
+ __sync_synchronize();
+ __sync_val_compare_and_swap(&val, 1, 0);
+ __sync_add_and_fetch(&val, 1);
+ __sync_sub_and_fetch(&val, 1);
+#endif
+ return 0;
+ }
+" LLVM_HAS_ATOMICS)
+
+if( NOT LLVM_HAS_ATOMICS )
+ message(STATUS "Warning: LLVM will be built thread-unsafe because atomic builtins are missing")
+endif()
diff --git a/cmake/modules/ChooseMSVCCRT.cmake b/cmake/modules/ChooseMSVCCRT.cmake
new file mode 100644
index 00000000000..6a2f426b269
--- /dev/null
+++ b/cmake/modules/ChooseMSVCCRT.cmake
@@ -0,0 +1,106 @@
+# The macro choose_msvc_crt() takes a list of possible
+# C runtimes to choose from, in the form of compiler flags,
+# to present to the user. (MTd for /MTd, etc)
+#
+# The macro is invoked at the end of the file.
+#
+# CMake already sets CRT flags in the CMAKE_CXX_FLAGS_* and
+# CMAKE_C_FLAGS_* variables by default. To let the user
+# override that for each build type:
+# 1. Detect which CRT is already selected, and reflect this in
+# LLVM_USE_CRT_* so the user can have a better idea of what
+# changes they're making.
+# 2. Replace the flags in both variables with the new flag via a regex.
+# 3. set() the variables back into the cache so the changes
+# are user-visible.
+
+### Helper macros: ###
+macro(make_crt_regex regex crts)
+ set(${regex} "")
+ foreach(crt ${${crts}})
+ # Trying to match the beginning or end of the string with stuff
+ # like [ ^]+ didn't work, so use a bunch of parentheses instead.
+ set(${regex} "${${regex}}|(^| +)/${crt}($| +)")
+ endforeach(crt)
+ string(REGEX REPLACE "^\\|" "" ${regex} "${${regex}}")
+endmacro(make_crt_regex)
+
+macro(get_current_crt crt_current regex flagsvar)
+ # Find the selected-by-CMake CRT for each build type, if any.
+ # Strip off the leading slash and any whitespace.
+ string(REGEX MATCH "${${regex}}" ${crt_current} "${${flagsvar}}")
+ string(REPLACE "/" " " ${crt_current} "${${crt_current}}")
+ string(STRIP "${${crt_current}}" ${crt_current})
+endmacro(get_current_crt)
+
+# Replaces or adds a flag to a variable.
+# Expects 'flag' to be padded with spaces.
+macro(set_flag_in_var flagsvar regex flag)
+ string(REGEX MATCH "${${regex}}" current_flag "${${flagsvar}}")
+ if("${current_flag}" STREQUAL "")
+ set(${flagsvar} "${${flagsvar}}${${flag}}")
+ else()
+ string(REGEX REPLACE "${${regex}}" "${${flag}}" ${flagsvar} "${${flagsvar}}")
+ endif()
+ string(STRIP "${${flagsvar}}" ${flagsvar})
+ # Make sure this change gets reflected in the cache/gui.
+ # CMake requires the docstring parameter whenever set() touches the cache,
+ # so get the existing docstring and re-use that.
+ get_property(flagsvar_docs CACHE ${flagsvar} PROPERTY HELPSTRING)
+ set(${flagsvar} "${${flagsvar}}" CACHE STRING "${flagsvar_docs}" FORCE)
+endmacro(set_flag_in_var)
+
+
+macro(choose_msvc_crt MSVC_CRT)
+ if(LLVM_USE_CRT)
+ message(FATAL_ERROR
+ "LLVM_USE_CRT is deprecated. Use the CMAKE_BUILD_TYPE-specific
+variables (LLVM_USE_CRT_DEBUG, etc) instead.")
+ endif()
+
+ make_crt_regex(MSVC_CRT_REGEX ${MSVC_CRT})
+
+ foreach(build_type ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE})
+ string(TOUPPER "${build_type}" build)
+ if (NOT LLVM_USE_CRT_${build})
+ get_current_crt(LLVM_USE_CRT_${build}
+ MSVC_CRT_REGEX
+ CMAKE_CXX_FLAGS_${build})
+ set(LLVM_USE_CRT_${build}
+ "${LLVM_USE_CRT_${build}}"
+ CACHE STRING "Specify VC++ CRT to use for ${build_type} configurations."
+ FORCE)
+ set_property(CACHE LLVM_USE_CRT_${build}
+ PROPERTY STRINGS "";${${MSVC_CRT}})
+ endif(NOT LLVM_USE_CRT_${build})
+ endforeach(build_type)
+
+ foreach(build_type ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE})
+ string(TOUPPER "${build_type}" build)
+ if ("${LLVM_USE_CRT_${build}}" STREQUAL "")
+ set(flag_string " ")
+ else()
+ set(flag_string " /${LLVM_USE_CRT_${build}} ")
+ list(FIND ${MSVC_CRT} ${LLVM_USE_CRT_${build}} idx)
+ if (idx LESS 0)
+ message(FATAL_ERROR
+ "Invalid value for LLVM_USE_CRT_${build}: ${LLVM_USE_CRT_${build}}. Valid options are one of: ${${MSVC_CRT}}")
+ endif (idx LESS 0)
+ message(STATUS "Using ${build_type} VC++ CRT: ${LLVM_USE_CRT_${build}}")
+ endif()
+ foreach(lang C CXX)
+ set_flag_in_var(CMAKE_${lang}_FLAGS_${build} MSVC_CRT_REGEX flag_string)
+ endforeach(lang)
+ endforeach(build_type)
+endmacro(choose_msvc_crt MSVC_CRT)
+
+
+# List of valid CRTs for MSVC
+set(MSVC_CRT
+ MD
+ MDd
+ MT
+ MTd)
+
+choose_msvc_crt(MSVC_CRT)
+
diff --git a/cmake/modules/GetHostTriple.cmake b/cmake/modules/GetHostTriple.cmake
new file mode 100644
index 00000000000..671a8ce7d7c
--- /dev/null
+++ b/cmake/modules/GetHostTriple.cmake
@@ -0,0 +1,30 @@
+# Returns the host triple.
+# Invokes config.guess
+
+function( get_host_triple var )
+ if( MSVC )
+ if( CMAKE_CL_64 )
+ set( value "x86_64-pc-win32" )
+ else()
+ set( value "i686-pc-win32" )
+ endif()
+ elseif( MINGW AND NOT MSYS )
+ if( CMAKE_SIZEOF_VOID_P EQUAL 8 )
+ set( value "x86_64-w64-mingw32" )
+ else()
+ set( value "i686-pc-mingw32" )
+ endif()
+ else( MSVC )
+ set(config_guess ${LLVM_MAIN_SRC_DIR}/autoconf/config.guess)
+ execute_process(COMMAND sh ${config_guess}
+ RESULT_VARIABLE TT_RV
+ OUTPUT_VARIABLE TT_OUT
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if( NOT TT_RV EQUAL 0 )
+ message(FATAL_ERROR "Failed to execute ${config_guess}")
+ endif( NOT TT_RV EQUAL 0 )
+ set( value ${TT_OUT} )
+ endif( MSVC )
+ set( ${var} ${value} PARENT_SCOPE )
+ message(STATUS "Target triple: ${value}")
+endfunction( get_host_triple var )
diff --git a/cmake/modules/HandleLLVMOptions.cmake b/cmake/modules/HandleLLVMOptions.cmake
new file mode 100644
index 00000000000..b5f96e8f711
--- /dev/null
+++ b/cmake/modules/HandleLLVMOptions.cmake
@@ -0,0 +1,209 @@
+# This CMake module is responsible for interpreting the user defined LLVM_
+# options and executing the appropriate CMake commands to realize the users'
+# selections.
+
+include(AddLLVMDefinitions)
+
+if( CMAKE_COMPILER_IS_GNUCXX )
+ set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON)
+elseif( "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" )
+ set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON)
+endif()
+
+# Run-time build mode; It is used for unittests.
+if(MSVC_IDE)
+ # Expect "$(Configuration)", "$(OutDir)", etc.
+ # It is expanded by msbuild or similar.
+ set(RUNTIME_BUILD_MODE "${CMAKE_CFG_INTDIR}")
+elseif(NOT CMAKE_BUILD_TYPE STREQUAL "")
+ # Expect "Release" "Debug", etc.
+ # Or unittests could not run.
+ set(RUNTIME_BUILD_MODE ${CMAKE_BUILD_TYPE})
+else()
+ # It might be "."
+ set(RUNTIME_BUILD_MODE "${CMAKE_CFG_INTDIR}")
+endif()
+
+if( LLVM_ENABLE_ASSERTIONS )
+ # MSVC doesn't like _DEBUG on release builds. See PR 4379.
+ if( NOT MSVC )
+ add_definitions( -D_DEBUG )
+ endif()
+ # On Release builds cmake automatically defines NDEBUG, so we
+ # explicitly undefine it:
+ if( uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE" )
+ add_definitions( -UNDEBUG )
+ endif()
+else()
+ if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE" )
+ if( NOT MSVC_IDE AND NOT XCODE )
+ add_definitions( -DNDEBUG )
+ endif()
+ endif()
+endif()
+
+if(WIN32)
+ if(CYGWIN)
+ set(LLVM_ON_WIN32 0)
+ set(LLVM_ON_UNIX 1)
+ else(CYGWIN)
+ set(LLVM_ON_WIN32 1)
+ set(LLVM_ON_UNIX 0)
+ endif(CYGWIN)
+ set(LTDL_SHLIB_EXT ".dll")
+ set(EXEEXT ".exe")
+ # Maximum path length is 160 for non-unicode paths
+ set(MAXPATHLEN 160)
+else(WIN32)
+ if(UNIX)
+ set(LLVM_ON_WIN32 0)
+ set(LLVM_ON_UNIX 1)
+ if(APPLE)
+ set(LTDL_SHLIB_EXT ".dylib")
+ else(APPLE)
+ set(LTDL_SHLIB_EXT ".so")
+ endif(APPLE)
+ set(EXEEXT "")
+ # FIXME: Maximum path length is currently set to 'safe' fixed value
+ set(MAXPATHLEN 2024)
+ else(UNIX)
+ MESSAGE(SEND_ERROR "Unable to determine platform")
+ endif(UNIX)
+endif(WIN32)
+
+if( LLVM_ENABLE_PIC )
+ if( XCODE )
+ # Xcode has -mdynamic-no-pic on by default, which overrides -fPIC. I don't
+ # know how to disable this, so just force ENABLE_PIC off for now.
+ message(WARNING "-fPIC not supported with Xcode.")
+ elseif( WIN32 OR CYGWIN)
+ # On Windows all code is PIC. MinGW warns if -fPIC is used.
+ else()
+ include(CheckCXXCompilerFlag)
+ check_cxx_compiler_flag("-fPIC" SUPPORTS_FPIC_FLAG)
+ if( SUPPORTS_FPIC_FLAG )
+ message(STATUS "Building with -fPIC")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
+ else( SUPPORTS_FPIC_FLAG )
+ message(WARNING "-fPIC not supported.")
+ endif()
+
+ if( WIN32 OR CYGWIN)
+ # MinGW warns if -fvisibility-inlines-hidden is used.
+ else()
+ check_cxx_compiler_flag("-fvisibility-inlines-hidden" SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG)
+ if( SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG )
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility-inlines-hidden")
+ endif()
+ endif()
+ endif()
+endif()
+
+if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
+ # TODO: support other platforms and toolchains.
+ if( LLVM_BUILD_32_BITS )
+ message(STATUS "Building 32 bits executables and libraries.")
+ add_llvm_definitions( -m32 )
+ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32")
+ set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32")
+ set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -m32")
+ endif( LLVM_BUILD_32_BITS )
+endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
+
+# On Win32 using MS tools, provide an option to set the number of parallel jobs
+# to use.
+if( MSVC_IDE )
+ set(LLVM_COMPILER_JOBS "0" CACHE STRING
+ "Number of parallel compiler jobs. 0 means use all processors. Default is 0.")
+ if( NOT LLVM_COMPILER_JOBS STREQUAL "1" )
+ if( LLVM_COMPILER_JOBS STREQUAL "0" )
+ add_llvm_definitions( /MP )
+ else()
+ if (MSVC10)
+ message(FATAL_ERROR
+ "Due to a bug in CMake only 0 and 1 is supported for "
+ "LLVM_COMPILER_JOBS when generating for Visual Studio 2010")
+ else()
+ message(STATUS "Number of parallel compiler jobs set to " ${LLVM_COMPILER_JOBS})
+ add_llvm_definitions( /MP${LLVM_COMPILER_JOBS} )
+ endif()
+ endif()
+ else()
+ message(STATUS "Parallel compilation disabled")
+ endif()
+endif()
+
+if( MSVC )
+ include(ChooseMSVCCRT)
+
+ if( MSVC11 )
+ add_llvm_definitions(-D_VARIADIC_MAX=10)
+ endif()
+
+ # Add definitions that make MSVC much less annoying.
+ add_llvm_definitions(
+ # For some reason MS wants to deprecate a bunch of standard functions...
+ -D_CRT_SECURE_NO_DEPRECATE
+ -D_CRT_SECURE_NO_WARNINGS
+ -D_CRT_NONSTDC_NO_DEPRECATE
+ -D_CRT_NONSTDC_NO_WARNINGS
+ -D_SCL_SECURE_NO_DEPRECATE
+ -D_SCL_SECURE_NO_WARNINGS
+
+ # Disabled warnings.
+ -wd4065 # Suppress 'switch statement contains 'default' but no 'case' labels'
+ -wd4146 # Suppress 'unary minus operator applied to unsigned type, result still unsigned'
+ -wd4180 # Suppress 'qualifier applied to function type has no meaning; ignored'
+ -wd4181 # Suppress 'qualifier applied to reference type; ignored'
+ -wd4224 # Suppress 'nonstandard extension used : formal parameter 'identifier' was previously defined as a type'
+ -wd4244 # Suppress ''argument' : conversion from 'type1' to 'type2', possible loss of data'
+ -wd4267 # Suppress ''var' : conversion from 'size_t' to 'type', possible loss of data'
+ -wd4275 # Suppress 'An exported class was derived from a class that was not exported.'
+ -wd4291 # Suppress ''declaration' : no matching operator delete found; memory will not be freed if initialization throws an exception'
+ -wd4345 # Suppress 'behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized'
+ -wd4351 # Suppress 'new behavior: elements of array 'array' will be default initialized'
+ -wd4355 # Suppress ''this' : used in base member initializer list'
+ -wd4503 # Suppress ''identifier' : decorated name length exceeded, name was truncated'
+ -wd4551 # Suppress 'function call missing argument list'
+ -wd4624 # Suppress ''derived class' : destructor could not be generated because a base class destructor is inaccessible'
+ -wd4715 # Suppress ''function' : not all control paths return a value'
+ -wd4800 # Suppress ''type' : forcing value to bool 'true' or 'false' (performance warning)'
+
+ # Promoted warnings.
+ -w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning.
+
+ # Promoted warnings to errors.
+ -we4238 # Promote 'nonstandard extension used : class rvalue used as lvalue' to error.
+ -we4239 # Promote 'nonstandard extension used : 'token' : conversion from 'type' to 'type'' to error.
+ )
+
+ # Enable warnings
+ if (LLVM_ENABLE_WARNINGS)
+ add_llvm_definitions( /W4 )
+ if (LLVM_ENABLE_PEDANTIC)
+ # No MSVC equivalent available
+ endif (LLVM_ENABLE_PEDANTIC)
+ endif (LLVM_ENABLE_WARNINGS)
+ if (LLVM_ENABLE_WERROR)
+ add_llvm_definitions( /WX )
+ endif (LLVM_ENABLE_WERROR)
+elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
+ if (LLVM_ENABLE_WARNINGS)
+ add_llvm_definitions( -Wall -W -Wno-unused-parameter -Wwrite-strings )
+ if (LLVM_ENABLE_PEDANTIC)
+ add_llvm_definitions( -pedantic -Wno-long-long )
+ endif (LLVM_ENABLE_PEDANTIC)
+ check_cxx_compiler_flag("-Werror -Wcovered-switch-default" SUPPORTS_COVERED_SWITCH_DEFAULT_FLAG)
+ if( SUPPORTS_COVERED_SWITCH_DEFAULT_FLAG )
+ add_llvm_definitions( -Wcovered-switch-default )
+ endif()
+ endif (LLVM_ENABLE_WARNINGS)
+ if (LLVM_ENABLE_WERROR)
+ add_llvm_definitions( -Werror )
+ endif (LLVM_ENABLE_WERROR)
+endif( MSVC )
+
+add_llvm_definitions( -D__STDC_CONSTANT_MACROS )
+add_llvm_definitions( -D__STDC_FORMAT_MACROS )
+add_llvm_definitions( -D__STDC_LIMIT_MACROS )
diff --git a/cmake/modules/LLVM-Config.cmake b/cmake/modules/LLVM-Config.cmake
new file mode 100755
index 00000000000..574335c49d0
--- /dev/null
+++ b/cmake/modules/LLVM-Config.cmake
@@ -0,0 +1,178 @@
+function(get_system_libs return_var)
+ # Returns in `return_var' a list of system libraries used by LLVM.
+ if( NOT MSVC )
+ if( MINGW )
+ set(system_libs ${system_libs} imagehlp psapi)
+ elseif( CMAKE_HOST_UNIX )
+ if( HAVE_LIBDL )
+ set(system_libs ${system_libs} ${CMAKE_DL_LIBS})
+ endif()
+ if( LLVM_ENABLE_THREADS AND HAVE_LIBPTHREAD )
+ set(system_libs ${system_libs} pthread)
+ endif()
+ endif( MINGW )
+ endif( NOT MSVC )
+ set(${return_var} ${system_libs} PARENT_SCOPE)
+endfunction(get_system_libs)
+
+
+function(link_system_libs target)
+ get_system_libs(llvm_system_libs)
+ target_link_libraries(${target} ${llvm_system_libs})
+endfunction(link_system_libs)
+
+
+function(is_llvm_target_library library return_var)
+ # Sets variable `return_var' to ON if `library' corresponds to a
+ # LLVM supported target. To OFF if it doesn't.
+ set(${return_var} OFF PARENT_SCOPE)
+ string(TOUPPER "${library}" capitalized_lib)
+ string(TOUPPER "${LLVM_ALL_TARGETS}" targets)
+ foreach(t ${targets})
+ if( capitalized_lib STREQUAL t OR
+ capitalized_lib STREQUAL "LLVM${t}" OR
+ capitalized_lib STREQUAL "LLVM${t}CODEGEN" OR
+ capitalized_lib STREQUAL "LLVM${t}ASMPARSER" OR
+ capitalized_lib STREQUAL "LLVM${t}ASMPRINTER" OR
+ capitalized_lib STREQUAL "LLVM${t}DISASSEMBLER" OR
+ capitalized_lib STREQUAL "LLVM${t}INFO" )
+ set(${return_var} ON PARENT_SCOPE)
+ break()
+ endif()
+ endforeach()
+endfunction(is_llvm_target_library)
+
+
+macro(llvm_config executable)
+ explicit_llvm_config(${executable} ${ARGN})
+endmacro(llvm_config)
+
+
+function(explicit_llvm_config executable)
+ set( link_components ${ARGN} )
+
+ explicit_map_components_to_libraries(LIBRARIES ${link_components})
+ target_link_libraries(${executable} ${LIBRARIES})
+endfunction(explicit_llvm_config)
+
+
+# This is a variant intended for the final user:
+function(llvm_map_components_to_libraries OUT_VAR)
+ explicit_map_components_to_libraries(result ${ARGN})
+ get_system_libs(sys_result)
+ set( ${OUT_VAR} ${result} ${sys_result} PARENT_SCOPE )
+endfunction(llvm_map_components_to_libraries)
+
+
+function(explicit_map_components_to_libraries out_libs)
+ set( link_components ${ARGN} )
+ get_property(llvm_libs GLOBAL PROPERTY LLVM_LIBS)
+ string(TOUPPER "${llvm_libs}" capitalized_libs)
+
+ # Expand some keywords:
+ list(FIND LLVM_TARGETS_TO_BUILD "${LLVM_NATIVE_ARCH}" have_native_backend)
+ list(FIND link_components "engine" engine_required)
+ if( NOT engine_required EQUAL -1 )
+ list(FIND LLVM_TARGETS_WITH_JIT "${LLVM_NATIVE_ARCH}" have_jit)
+ if( NOT have_native_backend EQUAL -1 AND NOT have_jit EQUAL -1 )
+ list(APPEND link_components "jit")
+ list(APPEND link_components "native")
+ else()
+ list(APPEND link_components "interpreter")
+ endif()
+ endif()
+ list(FIND link_components "native" native_required)
+ if( NOT native_required EQUAL -1 )
+ if( NOT have_native_backend EQUAL -1 )
+ list(APPEND link_components ${LLVM_NATIVE_ARCH})
+ endif()
+ endif()
+
+ # Translate symbolic component names to real libraries:
+ foreach(c ${link_components})
+ # add codegen, asmprinter, asmparser, disassembler
+ list(FIND LLVM_TARGETS_TO_BUILD ${c} idx)
+ if( NOT idx LESS 0 )
+ list(FIND llvm_libs "LLVM${c}CodeGen" idx)
+ if( NOT idx LESS 0 )
+ list(APPEND expanded_components "LLVM${c}CodeGen")
+ else()
+ list(FIND llvm_libs "LLVM${c}" idx)
+ if( NOT idx LESS 0 )
+ list(APPEND expanded_components "LLVM${c}")
+ else()
+ message(FATAL_ERROR "Target ${c} is not in the set of libraries.")
+ endif()
+ endif()
+ list(FIND llvm_libs "LLVM${c}AsmPrinter" asmidx)
+ if( NOT asmidx LESS 0 )
+ list(APPEND expanded_components "LLVM${c}AsmPrinter")
+ endif()
+ list(FIND llvm_libs "LLVM${c}AsmParser" asmidx)
+ if( NOT asmidx LESS 0 )
+ list(APPEND expanded_components "LLVM${c}AsmParser")
+ endif()
+ list(FIND llvm_libs "LLVM${c}Info" asmidx)
+ if( NOT asmidx LESS 0 )
+ list(APPEND expanded_components "LLVM${c}Info")
+ endif()
+ list(FIND llvm_libs "LLVM${c}Disassembler" asmidx)
+ if( NOT asmidx LESS 0 )
+ list(APPEND expanded_components "LLVM${c}Disassembler")
+ endif()
+ elseif( c STREQUAL "native" )
+ # already processed
+ elseif( c STREQUAL "nativecodegen" )
+ list(APPEND expanded_components "LLVM${LLVM_NATIVE_ARCH}CodeGen")
+ elseif( c STREQUAL "backend" )
+ # same case as in `native'.
+ elseif( c STREQUAL "engine" )
+ # already processed
+ elseif( c STREQUAL "all" )
+ list(APPEND expanded_components ${llvm_libs})
+ else( NOT idx LESS 0 )
+ # Canonize the component name:
+ string(TOUPPER "${c}" capitalized)
+ list(FIND capitalized_libs LLVM${capitalized} lib_idx)
+ if( lib_idx LESS 0 )
+ # The component is unknown. Maybe is an omitted target?
+ is_llvm_target_library(${c} iltl_result)
+ if( NOT iltl_result )
+ message(FATAL_ERROR "Library `${c}' not found in list of llvm libraries.")
+ endif()
+ else( lib_idx LESS 0 )
+ list(GET llvm_libs ${lib_idx} canonical_lib)
+ list(APPEND expanded_components ${canonical_lib})
+ endif( lib_idx LESS 0 )
+ endif( NOT idx LESS 0 )
+ endforeach(c)
+ # Expand dependencies while topologically sorting the list of libraries:
+ list(LENGTH expanded_components lst_size)
+ set(cursor 0)
+ set(processed)
+ while( cursor LESS lst_size )
+ list(GET expanded_components ${cursor} lib)
+ get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${lib})
+ list(APPEND expanded_components ${lib_deps})
+ # Remove duplicates at the front:
+ list(REVERSE expanded_components)
+ list(REMOVE_DUPLICATES expanded_components)
+ list(REVERSE expanded_components)
+ list(APPEND processed ${lib})
+ # Find the maximum index that doesn't have to be re-processed:
+ while(NOT "${expanded_components}" MATCHES "^${processed}.*" )
+ list(REMOVE_AT processed -1)
+ endwhile()
+ list(LENGTH processed cursor)
+ list(LENGTH expanded_components lst_size)
+ endwhile( cursor LESS lst_size )
+ # Return just the libraries included in this build:
+ set(result)
+ foreach(c ${expanded_components})
+ list(FIND llvm_libs ${c} lib_idx)
+ if( NOT lib_idx LESS 0 )
+ set(result ${result} ${c})
+ endif()
+ endforeach(c)
+ set(${out_libs} ${result} PARENT_SCOPE)
+endfunction(explicit_map_components_to_libraries)
diff --git a/cmake/modules/LLVMConfig.cmake.in b/cmake/modules/LLVMConfig.cmake.in
new file mode 100644
index 00000000000..c43119ed3d3
--- /dev/null
+++ b/cmake/modules/LLVMConfig.cmake.in
@@ -0,0 +1,51 @@
+# This file provides information and services to the final user.
+
+set(LLVM_VERSION_MAJOR @LLVM_VERSION_MAJOR@)
+set(LLVM_VERSION_MINOR @LLVM_VERSION_MINOR@)
+set(LLVM_PACKAGE_VERSION @PACKAGE_VERSION@)
+
+set(LLVM_COMMON_DEPENDS @LLVM_COMMON_DEPENDS@)
+
+set_property( GLOBAL PROPERTY LLVM_LIBS "@llvm_libs@")
+
+set(LLVM_ALL_TARGETS @LLVM_ALL_TARGETS@)
+
+set(LLVM_TARGETS_TO_BUILD @LLVM_TARGETS_TO_BUILD@)
+
+set(LLVM_TARGETS_WITH_JIT @LLVM_TARGETS_WITH_JIT@)
+
+@all_llvm_lib_deps@
+
+set(TARGET_TRIPLE "@TARGET_TRIPLE@")
+
+set(LLVM_TOOLS_BINARY_DIR @LLVM_TOOLS_BINARY_DIR@)
+
+set(LLVM_ENABLE_THREADS @LLVM_ENABLE_THREADS@)
+
+set(LLVM_NATIVE_ARCH @LLVM_NATIVE_ARCH@)
+
+set(LLVM_ENABLE_PIC @LLVM_ENABLE_PIC@)
+
+set(HAVE_LIBDL @HAVE_LIBDL@)
+set(HAVE_LIBPTHREAD @HAVE_LIBPTHREAD@)
+set(LLVM_ON_UNIX @LLVM_ON_UNIX@)
+set(LLVM_ON_WIN32 @LLVM_ON_WIN32@)
+
+set(LLVM_INSTALL_PREFIX "@LLVM_INSTALL_PREFIX@")
+set(LLVM_INCLUDE_DIRS ${LLVM_INSTALL_PREFIX}/include)
+set(LLVM_LIBRARY_DIRS ${LLVM_INSTALL_PREFIX}/lib)
+set(LLVM_DEFINITIONS "-D__STDC_LIMIT_MACROS" "-D__STDC_CONSTANT_MACROS")
+
+# We try to include using the current setting of CMAKE_MODULE_PATH,
+# which suppossedly was filled by the user with the directory where
+# this file was installed:
+include( LLVM-Config OPTIONAL RESULT_VARIABLE LLVMCONFIG_INCLUDED )
+
+# If failed, we assume that this is an un-installed build:
+if( NOT LLVMCONFIG_INCLUDED )
+ set(CMAKE_MODULE_PATH
+ ${CMAKE_MODULE_PATH}
+ "@LLVM_SOURCE_DIR@/cmake/modules")
+ include( LLVM-Config )
+endif()
+
diff --git a/cmake/modules/LLVMConfigVersion.cmake.in b/cmake/modules/LLVMConfigVersion.cmake.in
new file mode 100644
index 00000000000..add5aa9a1cb
--- /dev/null
+++ b/cmake/modules/LLVMConfigVersion.cmake.in
@@ -0,0 +1 @@
+set(PACKAGE_VERSION "@PACKAGE_VERSION@") \ No newline at end of file
diff --git a/cmake/modules/LLVMParseArguments.cmake b/cmake/modules/LLVMParseArguments.cmake
new file mode 100644
index 00000000000..ce19be114b3
--- /dev/null
+++ b/cmake/modules/LLVMParseArguments.cmake
@@ -0,0 +1,80 @@
+# Copied from http://www.itk.org/Wiki/CMakeMacroParseArguments under
+# http://creativecommons.org/licenses/by/2.5/.
+#
+# The PARSE_ARGUMENTS macro will take the arguments of another macro and define
+# several variables. The first argument to PARSE_ARGUMENTS is a prefix to put on
+# all variables it creates. The second argument is a list of names, and the
+# third argument is a list of options. Both of these lists should be quoted. The
+# rest of PARSE_ARGUMENTS are arguments from another macro to be parsed.
+#
+# PARSE_ARGUMENTS(prefix arg_names options arg1 arg2...)
+#
+# For each item in options, PARSE_ARGUMENTS will create a variable with that
+# name, prefixed with prefix_. So, for example, if prefix is MY_MACRO and
+# options is OPTION1;OPTION2, then PARSE_ARGUMENTS will create the variables
+# MY_MACRO_OPTION1 and MY_MACRO_OPTION2. These variables will be set to true if
+# the option exists in the command line or false otherwise.
+#
+#For each item in arg_names, PARSE_ARGUMENTS will create a variable with that
+#name, prefixed with prefix_. Each variable will be filled with the arguments
+#that occur after the given arg_name is encountered up to the next arg_name or
+#the end of the arguments. All options are removed from these
+#lists. PARSE_ARGUMENTS also creates a prefix_DEFAULT_ARGS variable containing
+#the list of all arguments up to the first arg_name encountered.
+#
+#Here is a simple, albeit impractical, example of using PARSE_ARGUMENTS that
+#demonstrates its behavior.
+#
+# SET(arguments
+# hello OPTION3 world
+# LIST3 foo bar
+# OPTION2
+# LIST1 fuz baz
+# )
+#
+# PARSE_ARGUMENTS(ARG "LIST1;LIST2;LIST3" "OPTION1;OPTION2;OPTION3" ${arguments})
+#
+# PARSE_ARGUMENTS creates 7 variables and sets them as follows:
+# ARG_DEFAULT_ARGS: hello;world
+# ARG_LIST1: fuz;baz
+# ARG_LIST2:
+# ARG_LIST3: foo;bar
+# ARG_OPTION1: FALSE
+# ARG_OPTION2: TRUE
+# ARG_OPTION3: TRUE
+#
+# If you don't have any options, use an empty string in its place.
+# PARSE_ARGUMENTS(ARG "LIST1;LIST2;LIST3" "" ${arguments})
+# Likewise if you have no lists.
+# PARSE_ARGUMENTS(ARG "" "OPTION1;OPTION2;OPTION3" ${arguments})
+
+MACRO(PARSE_ARGUMENTS prefix arg_names option_names)
+ SET(DEFAULT_ARGS)
+ FOREACH(arg_name ${arg_names})
+ SET(${prefix}_${arg_name})
+ ENDFOREACH(arg_name)
+ FOREACH(option ${option_names})
+ SET(${prefix}_${option} FALSE)
+ ENDFOREACH(option)
+
+ SET(current_arg_name DEFAULT_ARGS)
+ SET(current_arg_list)
+ FOREACH(arg ${ARGN})
+ SET(larg_names ${arg_names})
+ LIST(FIND larg_names "${arg}" is_arg_name)
+ IF (is_arg_name GREATER -1)
+ SET(${prefix}_${current_arg_name} ${current_arg_list})
+ SET(current_arg_name ${arg})
+ SET(current_arg_list)
+ ELSE (is_arg_name GREATER -1)
+ SET(loption_names ${option_names})
+ LIST(FIND loption_names "${arg}" is_option)
+ IF (is_option GREATER -1)
+ SET(${prefix}_${arg} TRUE)
+ ELSE (is_option GREATER -1)
+ SET(current_arg_list ${current_arg_list} ${arg})
+ ENDIF (is_option GREATER -1)
+ ENDIF (is_arg_name GREATER -1)
+ ENDFOREACH(arg)
+ SET(${prefix}_${current_arg_name} ${current_arg_list})
+ENDMACRO(PARSE_ARGUMENTS)
diff --git a/cmake/modules/LLVMProcessSources.cmake b/cmake/modules/LLVMProcessSources.cmake
new file mode 100644
index 00000000000..0e410edc15f
--- /dev/null
+++ b/cmake/modules/LLVMProcessSources.cmake
@@ -0,0 +1,94 @@
+include(AddFileDependencies)
+
+function(llvm_replace_compiler_option var old new)
+ # Replaces a compiler option or switch `old' in `var' by `new'.
+ # If `old' is not in `var', appends `new' to `var'.
+ # Example: llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELEASE "-O3" "-O2")
+ # If the option already is on the variable, don't add it:
+ if( "${${var}}" MATCHES "(^| )${new}($| )" )
+ set(n "")
+ else()
+ set(n "${new}")
+ endif()
+ if( "${${var}}" MATCHES "(^| )${old}($| )" )
+ string( REGEX REPLACE "(^| )${old}($| )" " ${n} " ${var} "${${var}}" )
+ else()
+ set( ${var} "${${var}} ${n}" )
+ endif()
+ set( ${var} "${${var}}" PARENT_SCOPE )
+endfunction(llvm_replace_compiler_option)
+
+macro(add_td_sources srcs)
+ file(GLOB tds *.td)
+ if( tds )
+ source_group("TableGen descriptions" FILES ${tds})
+ set_source_files_properties(${tds} PROPERTIES HEADER_FILE_ONLY ON)
+ list(APPEND ${srcs} ${tds})
+ endif()
+endmacro(add_td_sources)
+
+
+macro(add_header_files srcs)
+ file(GLOB hds *.h)
+ if( hds )
+ set_source_files_properties(${hds} PROPERTIES HEADER_FILE_ONLY ON)
+ list(APPEND ${srcs} ${hds})
+ endif()
+endmacro(add_header_files)
+
+
+function(llvm_process_sources OUT_VAR)
+ set( sources ${ARGN} )
+ llvm_check_source_file_list( ${sources} )
+ # Create file dependencies on the tablegenned files, if any. Seems
+ # that this is not strictly needed, as dependencies of the .cpp
+ # sources on the tablegenned .inc files are detected and handled,
+ # but just in case...
+ foreach( s ${sources} )
+ set( f ${CMAKE_CURRENT_SOURCE_DIR}/${s} )
+ add_file_dependencies( ${f} ${TABLEGEN_OUTPUT} )
+ endforeach(s)
+ if( MSVC_IDE )
+ # This adds .td and .h files to the Visual Studio solution:
+ # FIXME: Shall we handle *.def here?
+ add_td_sources(sources)
+ add_header_files(sources)
+ endif()
+
+ # Set common compiler options:
+ if( NOT LLVM_REQUIRES_EH )
+ if( LLVM_COMPILER_IS_GCC_COMPATIBLE )
+ add_definitions( -fno-exceptions )
+ elseif( MSVC )
+ llvm_replace_compiler_option(CMAKE_CXX_FLAGS "/EHsc" "/EHs-c-")
+ add_definitions( /D_HAS_EXCEPTIONS=0 )
+ endif()
+ endif()
+ if( NOT LLVM_REQUIRES_RTTI )
+ if( LLVM_COMPILER_IS_GCC_COMPATIBLE )
+ llvm_replace_compiler_option(CMAKE_CXX_FLAGS "-frtti" "-fno-rtti")
+ elseif( MSVC )
+ llvm_replace_compiler_option(CMAKE_CXX_FLAGS "/GR" "/GR-")
+ endif()
+ endif()
+
+ set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" PARENT_SCOPE )
+ set( ${OUT_VAR} ${sources} PARENT_SCOPE )
+endfunction(llvm_process_sources)
+
+
+function(llvm_check_source_file_list)
+ set(listed ${ARGN})
+ file(GLOB globbed *.cpp)
+ foreach(g ${globbed})
+ get_filename_component(fn ${g} NAME)
+ list(FIND LLVM_OPTIONAL_SOURCES ${fn} idx)
+ if( idx LESS 0 )
+ list(FIND listed ${fn} idx)
+ if( idx LESS 0 )
+ message(SEND_ERROR "Found unknown source file ${g}
+Please update ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt\n")
+ endif()
+ endif()
+ endforeach()
+endfunction(llvm_check_source_file_list)
diff --git a/cmake/modules/TableGen.cmake b/cmake/modules/TableGen.cmake
new file mode 100644
index 00000000000..e3bdd9c7048
--- /dev/null
+++ b/cmake/modules/TableGen.cmake
@@ -0,0 +1,130 @@
+# LLVM_TARGET_DEFINITIONS must contain the name of the .td file to process.
+# Extra parameters for `tblgen' may come after `ofn' parameter.
+# Adds the name of the generated file to TABLEGEN_OUTPUT.
+
+macro(tablegen project ofn)
+ file(GLOB local_tds "*.td")
+ file(GLOB_RECURSE global_tds "${LLVM_MAIN_SRC_DIR}/include/llvm/*.td")
+
+ if (IS_ABSOLUTE ${LLVM_TARGET_DEFINITIONS})
+ set(LLVM_TARGET_DEFINITIONS_ABSOLUTE ${LLVM_TARGET_DEFINITIONS})
+ else()
+ set(LLVM_TARGET_DEFINITIONS_ABSOLUTE
+ ${CMAKE_CURRENT_SOURCE_DIR}/${LLVM_TARGET_DEFINITIONS})
+ endif()
+ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${ofn}.tmp
+ # Generate tablegen output in a temporary file.
+ COMMAND ${${project}_TABLEGEN_EXE} ${ARGN} -I ${CMAKE_CURRENT_SOURCE_DIR}
+ -I ${LLVM_MAIN_SRC_DIR}/lib/Target -I ${LLVM_MAIN_INCLUDE_DIR}
+ ${LLVM_TARGET_DEFINITIONS_ABSOLUTE}
+ -o ${CMAKE_CURRENT_BINARY_DIR}/${ofn}.tmp
+ # The file in LLVM_TARGET_DEFINITIONS may be not in the current
+ # directory and local_tds may not contain it, so we must
+ # explicitly list it here:
+ DEPENDS ${${project}_TABLEGEN_EXE} ${local_tds} ${global_tds}
+ ${LLVM_TARGET_DEFINITIONS_ABSOLUTE}
+ COMMENT "Building ${ofn}..."
+ )
+ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${ofn}
+ # Only update the real output file if there are any differences.
+ # This prevents recompilation of all the files depending on it if there
+ # aren't any.
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ ${CMAKE_CURRENT_BINARY_DIR}/${ofn}.tmp
+ ${CMAKE_CURRENT_BINARY_DIR}/${ofn}
+ DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${ofn}.tmp
+ COMMENT ""
+ )
+
+ # `make clean' must remove all those generated files:
+ set_property(DIRECTORY APPEND
+ PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${ofn}.tmp ${ofn})
+
+ set(TABLEGEN_OUTPUT ${TABLEGEN_OUTPUT} ${CMAKE_CURRENT_BINARY_DIR}/${ofn})
+ set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/${ofn}
+ PROPERTIES GENERATED 1)
+endmacro(tablegen)
+
+function(add_public_tablegen_target target)
+ # Creates a target for publicly exporting tablegen dependencies.
+ if( TABLEGEN_OUTPUT )
+ add_custom_target(${target}
+ DEPENDS ${TABLEGEN_OUTPUT})
+ if (LLVM_COMMON_DEPENDS)
+ add_dependencies(${target} ${LLVM_COMMON_DEPENDS})
+ endif ()
+ set_target_properties(${target} PROPERTIES FOLDER "Tablegenning")
+ endif( TABLEGEN_OUTPUT )
+endfunction()
+
+if(CMAKE_CROSSCOMPILING)
+ set(CX_NATIVE_TG_DIR "${CMAKE_BINARY_DIR}/native")
+
+ add_custom_command(OUTPUT ${CX_NATIVE_TG_DIR}
+ COMMAND ${CMAKE_COMMAND} -E make_directory ${CX_NATIVE_TG_DIR}
+ COMMENT "Creating ${CX_NATIVE_TG_DIR}...")
+
+ add_custom_command(OUTPUT ${CX_NATIVE_TG_DIR}/CMakeCache.txt
+ COMMAND ${CMAKE_COMMAND} -UMAKE_TOOLCHAIN_FILE -DCMAKE_BUILD_TYPE=Release
+ -DLLVM_BUILD_POLLY=OFF ${CMAKE_SOURCE_DIR}
+ WORKING_DIRECTORY ${CX_NATIVE_TG_DIR}
+ DEPENDS ${CX_NATIVE_TG_DIR}
+ COMMENT "Configuring native TableGen...")
+
+ add_custom_target(ConfigureNativeTableGen DEPENDS ${CX_NATIVE_TG_DIR}/CMakeCache.txt)
+
+ set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES ${CX_NATIVE_TG_DIR})
+endif()
+
+macro(add_tablegen target project)
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LLVM_TOOLS_BINARY_DIR})
+
+ set(${target}_OLD_LLVM_LINK_COMPONENTS ${LLVM_LINK_COMPONENTS})
+ set(LLVM_LINK_COMPONENTS ${LLVM_LINK_COMPONENTS} TableGen)
+ add_llvm_utility(${target} ${ARGN})
+ set(LLVM_LINK_COMPONENTS ${${target}_OLD_LLVM_LINK_COMPONENTS})
+
+ set(${project}_TABLEGEN "${target}" CACHE
+ STRING "Native TableGen executable. Saves building one when cross-compiling.")
+
+ # Upgrade existing LLVM_TABLEGEN setting.
+ if(${project} STREQUAL LLVM)
+ if(${LLVM_TABLEGEN} STREQUAL tblgen)
+ set(LLVM_TABLEGEN "${target}" CACHE
+ STRING "Native TableGen executable. Saves building one when cross-compiling."
+ FORCE)
+ endif()
+ endif()
+
+ # Effective tblgen executable to be used:
+ set(${project}_TABLEGEN_EXE ${${project}_TABLEGEN} PARENT_SCOPE)
+
+ if(CMAKE_CROSSCOMPILING)
+ if( ${${project}_TABLEGEN} STREQUAL "${target}" )
+ set(${project}_TABLEGEN_EXE "${CX_NATIVE_TG_DIR}/bin/${target}")
+ set(${project}_TABLEGEN_EXE ${${project}_TABLEGEN_EXE} PARENT_SCOPE)
+
+ add_custom_command(OUTPUT ${${project}_TABLEGEN_EXE}
+ COMMAND ${CMAKE_BUILD_TOOL} ${target}
+ DEPENDS ${CX_NATIVE_TG_DIR}/CMakeCache.txt
+ WORKING_DIRECTORY ${CX_NATIVE_TG_DIR}
+ COMMENT "Building native TableGen...")
+ add_custom_target(${project}NativeTableGen DEPENDS ${${project}_TABLEGEN_EXE})
+ add_dependencies(${project}NativeTableGen ConfigureNativeTableGen)
+
+ add_dependencies(${target} ${project}NativeTableGen)
+ endif()
+ endif()
+
+ if( MINGW )
+ target_link_libraries(${target} imagehlp psapi)
+ if(CMAKE_SIZEOF_VOID_P MATCHES "8")
+ set_target_properties(${target} PROPERTIES LINK_FLAGS -Wl,--stack,16777216)
+ endif(CMAKE_SIZEOF_VOID_P MATCHES "8")
+ endif( MINGW )
+ if( LLVM_ENABLE_THREADS AND HAVE_LIBPTHREAD AND NOT BEOS )
+ target_link_libraries(${target} pthread)
+ endif()
+
+ install(TARGETS ${target} RUNTIME DESTINATION bin)
+endmacro()
diff --git a/cmake/modules/VersionFromVCS.cmake b/cmake/modules/VersionFromVCS.cmake
new file mode 100644
index 00000000000..d6a2ae5f45f
--- /dev/null
+++ b/cmake/modules/VersionFromVCS.cmake
@@ -0,0 +1,70 @@
+# Adds version control information to the variable VERS. For
+# determining the Version Control System used (if any) it inspects the
+# existence of certain subdirectories under CMAKE_CURRENT_SOURCE_DIR.
+
+function(add_version_info_from_vcs VERS)
+ string(REPLACE "svn" "" result "${${VERS}}")
+ if( EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.svn" )
+ set(result "${result}svn")
+ # FindSubversion does not work with symlinks. See PR 8437
+ if( NOT IS_SYMLINK "${CMAKE_CURRENT_SOURCE_DIR}" )
+ find_package(Subversion)
+ endif()
+ if( Subversion_FOUND )
+ subversion_wc_info( ${CMAKE_CURRENT_SOURCE_DIR} Project )
+ if( Project_WC_REVISION )
+ set(SVN_REVISION ${Project_WC_REVISION} PARENT_SCOPE)
+ set(result "${result}-r${Project_WC_REVISION}")
+ endif()
+ endif()
+ elseif( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git )
+ set(result "${result}git")
+ # Try to get a ref-id
+ find_program(git_executable NAMES git git.exe git.cmd)
+ if( git_executable )
+ set(is_git_svn_rev_exact false)
+ execute_process(COMMAND ${git_executable} svn log --limit=1 --oneline
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ TIMEOUT 5
+ RESULT_VARIABLE git_result
+ OUTPUT_VARIABLE git_output)
+ if( git_result EQUAL 0 )
+ string(REGEX MATCH r[0-9]+ git_svn_rev ${git_output})
+ string(LENGTH "${git_svn_rev}" rev_length)
+ math(EXPR rev_length "${rev_length}-1")
+ string(SUBSTRING "${git_svn_rev}" 1 ${rev_length} git_svn_rev_number)
+ set(SVN_REVISION ${git_svn_rev_number} PARENT_SCOPE)
+ set(git_svn_rev "-svn-${git_svn_rev}")
+
+ # Determine if the HEAD points directly at a subversion revision.
+ execute_process(COMMAND ${git_executable} svn find-rev HEAD
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ TIMEOUT 5
+ RESULT_VARIABLE git_result
+ OUTPUT_VARIABLE git_output)
+ if( git_result EQUAL 0 )
+ string(STRIP "${git_output}" git_head_svn_rev_number)
+ if( git_head_svn_rev_number EQUAL git_svn_rev_number )
+ set(is_git_svn_rev_exact true)
+ endif()
+ endif()
+ else()
+ set(git_svn_rev "")
+ endif()
+ execute_process(COMMAND
+ ${git_executable} rev-parse --short HEAD
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ TIMEOUT 5
+ RESULT_VARIABLE git_result
+ OUTPUT_VARIABLE git_output)
+ if( git_result EQUAL 0 AND NOT is_git_svn_rev_exact )
+ string(STRIP "${git_output}" git_ref_id)
+ set(GIT_COMMIT ${git_ref_id} PARENT_SCOPE)
+ set(result "${result}${git_svn_rev}-${git_ref_id}")
+ else()
+ set(result "${result}${git_svn_rev}")
+ endif()
+ endif()
+ endif()
+ set(${VERS} ${result} PARENT_SCOPE)
+endfunction(add_version_info_from_vcs)
diff --git a/cmake/platforms/Android.cmake b/cmake/platforms/Android.cmake
new file mode 100644
index 00000000000..72849b16c76
--- /dev/null
+++ b/cmake/platforms/Android.cmake
@@ -0,0 +1,21 @@
+# Toolchain config for Android NDK.
+# This is expected to be used with a standalone Android toolchain (see
+# docs/STANDALONE-TOOLCHAIN.html in the NDK on how to get one).
+#
+# Usage:
+# mkdir build; cd build
+# cmake ..; make
+# mkdir android; cd android
+# cmake -DLLVM_ANDROID_TOOLCHAIN_DIR=/path/to/android/ndk \
+# -DCMAKE_TOOLCHAIN_FILE=../../cmake/platforms/Android.cmake ../..
+# make <target>
+
+SET(CMAKE_SYSTEM_NAME Linux)
+SET(CMAKE_C_COMPILER ${CMAKE_BINARY_DIR}/../bin/clang)
+SET(CMAKE_CXX_COMPILER ${CMAKE_BINARY_DIR}/../bin/clang++)
+SET(ANDROID "1" CACHE STRING "ANDROID" FORCE)
+
+SET(ANDROID_COMMON_FLAGS "-target arm-linux-androideabi --sysroot=${LLVM_ANDROID_TOOLCHAIN_DIR}/sysroot -B${LLVM_ANDROID_TOOLCHAIN_DIR} -mllvm -arm-enable-ehabi")
+SET(CMAKE_C_FLAGS "${ANDROID_COMMON_FLAGS}" CACHE STRING "toolchain_cflags" FORCE)
+SET(CMAKE_CXX_FLAGS "${ANDROID_COMMON_FLAGS}" CACHE STRING "toolchain_cxxflags" FORCE)
+SET(CMAKE_LINK_FLAGS "${ANDROID_COMMON_FLAGS}" CACHE STRING "toolchain_linkflags" FORCE)
diff --git a/configure b/configure
new file mode 100755
index 00000000000..6fbc47c72a7
--- /dev/null
+++ b/configure
@@ -0,0 +1,22949 @@
+#! /bin/sh
+# Guess values for system-dependent variables and create Makefiles.
+# Generated by GNU Autoconf 2.60 for LLVM 3.2svn.
+#
+# Report bugs to <http://llvm.org/bugs/>.
+#
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+# This configure script is free software; the Free Software Foundation
+# gives unlimited permission to copy, distribute and modify it.
+#
+# Copyright (c) 2003-2012 University of Illinois at Urbana-Champaign.
+## --------------------- ##
+## M4sh Initialization. ##
+## --------------------- ##
+
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+ setopt NO_GLOB_SUBST
+else
+ case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+ echo "#! /bin/sh" >conf$$.sh
+ echo "exit 0" >>conf$$.sh
+ chmod +x conf$$.sh
+ if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+ PATH_SEPARATOR=';'
+ else
+ PATH_SEPARATOR=:
+ fi
+ rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+ as_unset=unset
+else
+ as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order. Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" "" $as_nl"
+
+# Find who we are. Look in the path if we contain no directory separator.
+case $0 in
+ *[\\/]* ) as_myself=$0 ;;
+ *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+ as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+ echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+ { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+ LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+ LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+ LC_TELEPHONE LC_TIME
+do
+ if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+ eval $as_var=C; export $as_var
+ else
+ ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+ fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+ test "X`expr 00001 : '.*\(...\)'`" = X001; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+ as_basename=basename
+else
+ as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+ X"$0" : 'X\(//\)$' \| \
+ X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+ sed '/^.*\/\([^/][^/]*\)\/*$/{
+ s//\1/
+ q
+ }
+ /^X\/\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\/\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+if test "x$CONFIG_SHELL" = x; then
+ if (eval ":") 2>/dev/null; then
+ as_have_required=yes
+else
+ as_have_required=no
+fi
+
+ if test $as_have_required = yes && (eval ":
+(as_func_return () {
+ (exit \$1)
+}
+as_func_success () {
+ as_func_return 0
+}
+as_func_failure () {
+ as_func_return 1
+}
+as_func_ret_success () {
+ return 0
+}
+as_func_ret_failure () {
+ return 1
+}
+
+exitcode=0
+if as_func_success; then
+ :
+else
+ exitcode=1
+ echo as_func_success failed.
+fi
+
+if as_func_failure; then
+ exitcode=1
+ echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+ :
+else
+ exitcode=1
+ echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+ exitcode=1
+ echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+ :
+else
+ exitcode=1
+ echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0) || { (exit 1); exit 1; }
+
+(
+ as_lineno_1=\$LINENO
+ as_lineno_2=\$LINENO
+ test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" &&
+ test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; }
+") 2> /dev/null; then
+ :
+else
+ as_candidate_shells=
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in /usr/bin/posix$PATH_SEPARATOR/bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ case $as_dir in
+ /*)
+ for as_base in sh bash ksh sh5; do
+ as_candidate_shells="$as_candidate_shells $as_dir/$as_base"
+ done;;
+ esac
+done
+IFS=$as_save_IFS
+
+
+ for as_shell in $as_candidate_shells $SHELL; do
+ # Try only shells that exist, to save several forks.
+ if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+ { ("$as_shell") 2> /dev/null <<\_ASEOF
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+ setopt NO_GLOB_SUBST
+else
+ case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+:
+_ASEOF
+}; then
+ CONFIG_SHELL=$as_shell
+ as_have_required=yes
+ if { "$as_shell" 2> /dev/null <<\_ASEOF
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+ setopt NO_GLOB_SUBST
+else
+ case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+:
+(as_func_return () {
+ (exit $1)
+}
+as_func_success () {
+ as_func_return 0
+}
+as_func_failure () {
+ as_func_return 1
+}
+as_func_ret_success () {
+ return 0
+}
+as_func_ret_failure () {
+ return 1
+}
+
+exitcode=0
+if as_func_success; then
+ :
+else
+ exitcode=1
+ echo as_func_success failed.
+fi
+
+if as_func_failure; then
+ exitcode=1
+ echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+ :
+else
+ exitcode=1
+ echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+ exitcode=1
+ echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = "$1" ); then
+ :
+else
+ exitcode=1
+ echo positional parameters were not saved.
+fi
+
+test $exitcode = 0) || { (exit 1); exit 1; }
+
+(
+ as_lineno_1=$LINENO
+ as_lineno_2=$LINENO
+ test "x$as_lineno_1" != "x$as_lineno_2" &&
+ test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; }
+
+_ASEOF
+}; then
+ break
+fi
+
+fi
+
+ done
+
+ if test "x$CONFIG_SHELL" != x; then
+ for as_var in BASH_ENV ENV
+ do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+ done
+ export CONFIG_SHELL
+ exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+fi
+
+
+ if test $as_have_required = no; then
+ echo This script requires a shell more modern than all the
+ echo shells that I found on your system. Please install a
+ echo modern shell, or manually run the script under such a
+ echo shell if you do have one.
+ { (exit 1); exit 1; }
+fi
+
+
+fi
+
+fi
+
+
+
+(eval "as_func_return () {
+ (exit \$1)
+}
+as_func_success () {
+ as_func_return 0
+}
+as_func_failure () {
+ as_func_return 1
+}
+as_func_ret_success () {
+ return 0
+}
+as_func_ret_failure () {
+ return 1
+}
+
+exitcode=0
+if as_func_success; then
+ :
+else
+ exitcode=1
+ echo as_func_success failed.
+fi
+
+if as_func_failure; then
+ exitcode=1
+ echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+ :
+else
+ exitcode=1
+ echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+ exitcode=1
+ echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+ :
+else
+ exitcode=1
+ echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0") || {
+ echo No shell found that supports shell functions.
+ echo Please tell autoconf@gnu.org about your system,
+ echo including any error possibly output before this
+ echo message
+}
+
+
+
+ as_lineno_1=$LINENO
+ as_lineno_2=$LINENO
+ test "x$as_lineno_1" != "x$as_lineno_2" &&
+ test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+ # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+ # uniformly replaced by the line number. The first 'sed' inserts a
+ # line-number line after each line using $LINENO; the second 'sed'
+ # does the real work. The second script uses 'N' to pair each
+ # line-number line with the line containing $LINENO, and appends
+ # trailing '-' during substitution so that $LINENO is not a special
+ # case at line end.
+ # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+ # scripts with optimization help from Paolo Bonzini. Blame Lee
+ # E. McMahon (1931-1989) for sed's syntax. :-)
+ sed -n '
+ p
+ /[$]LINENO/=
+ ' <$as_myself |
+ sed '
+ s/[$]LINENO.*/&-/
+ t lineno
+ b
+ :lineno
+ N
+ :loop
+ s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+ t loop
+ s/-\n.*//
+ ' >$as_me.lineno &&
+ chmod +x "$as_me.lineno" ||
+ { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+ { (exit 1); exit 1; }; }
+
+ # Don't try to exec as it changes $[0], causing all sort of problems
+ # (the dirname of $[0] is not the place where we might find the
+ # original and so on. Autoconf is especially sensitive to this).
+ . "./$as_me.lineno"
+ # Exit status is that of the last command.
+ exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+ as_dirname=dirname
+else
+ as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+ case `echo 'x\c'` in
+ *c*) ECHO_T=' ';; # ECHO_T is single tab character.
+ *) ECHO_C='\c';;
+ esac;;
+*)
+ ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+ test "X`expr 00001 : '.*\(...\)'`" = X001; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+ rm -f conf$$.dir/conf$$.file
+else
+ rm -f conf$$.dir
+ mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+ as_ln_s='ln -s'
+ # ... but there are two gotchas:
+ # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+ # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+ # In both cases, we have to default to `cp -p'.
+ ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+ as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+ as_ln_s=ln
+else
+ as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+ as_mkdir_p=:
+else
+ test -d ./-p && rmdir ./-p
+ as_mkdir_p=false
+fi
+
+# Find out whether ``test -x'' works. Don't use a zero-byte file, as
+# systems may use methods other than mode bits to determine executability.
+cat >conf$$.file <<_ASEOF
+#! /bin/sh
+exit 0
+_ASEOF
+chmod +x conf$$.file
+if test -x conf$$.file >/dev/null 2>&1; then
+ as_executable_p="test -x"
+else
+ as_executable_p=:
+fi
+rm -f conf$$.file
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+
+exec 7<&0 </dev/null 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
+ac_default_prefix=/usr/local
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+# Identity of this package.
+PACKAGE_NAME='LLVM'
+PACKAGE_TARNAME='llvm'
+PACKAGE_VERSION='3.2svn'
+PACKAGE_STRING='LLVM 3.2svn'
+PACKAGE_BUGREPORT='http://llvm.org/bugs/'
+
+ac_unique_file="lib/VMCore/Module.cpp"
+# Factoring default headers for most tests.
+ac_includes_default="\
+#include <stdio.h>
+#if HAVE_SYS_TYPES_H
+# include <sys/types.h>
+#endif
+#if HAVE_SYS_STAT_H
+# include <sys/stat.h>
+#endif
+#if STDC_HEADERS
+# include <stdlib.h>
+# include <stddef.h>
+#else
+# if HAVE_STDLIB_H
+# include <stdlib.h>
+# endif
+#endif
+#if HAVE_STRING_H
+# if !STDC_HEADERS && HAVE_MEMORY_H
+# include <memory.h>
+# endif
+# include <string.h>
+#endif
+#if HAVE_STRINGS_H
+# include <strings.h>
+#endif
+#if HAVE_INTTYPES_H
+# include <inttypes.h>
+#endif
+#if HAVE_STDINT_H
+# include <stdint.h>
+#endif
+#if HAVE_UNISTD_H
+# include <unistd.h>
+#endif"
+
+ac_subst_vars='SHELL
+PATH_SEPARATOR
+PACKAGE_NAME
+PACKAGE_TARNAME
+PACKAGE_VERSION
+PACKAGE_STRING
+PACKAGE_BUGREPORT
+exec_prefix
+prefix
+program_transform_name
+bindir
+sbindir
+libexecdir
+datarootdir
+datadir
+sysconfdir
+sharedstatedir
+localstatedir
+includedir
+oldincludedir
+docdir
+infodir
+htmldir
+dvidir
+pdfdir
+psdir
+libdir
+localedir
+mandir
+DEFS
+ECHO_C
+ECHO_N
+ECHO_T
+LIBS
+build_alias
+host_alias
+target_alias
+LLVM_COPYRIGHT
+CC
+CFLAGS
+LDFLAGS
+CPPFLAGS
+ac_ct_CC
+EXEEXT
+OBJEXT
+CXX
+CXXFLAGS
+ac_ct_CXX
+CPP
+subdirs
+ENABLE_POLLY
+LLVM_HAS_POLLY
+build
+build_cpu
+build_vendor
+build_os
+host
+host_cpu
+host_vendor
+host_os
+target
+target_cpu
+target_vendor
+target_os
+OS
+HOST_OS
+TARGET_OS
+LINKALL
+NOLINKALL
+LLVM_ON_UNIX
+LLVM_ON_WIN32
+ARCH
+HOST_ARCH
+ENDIAN
+GREP
+EGREP
+LLVM_CROSS_COMPILING
+BUILD_CC
+BUILD_EXEEXT
+BUILD_CXX
+CVSBUILD
+ENABLE_LIBCPP
+ENABLE_CXX11
+ENABLE_OPTIMIZED
+ENABLE_PROFILING
+DISABLE_ASSERTIONS
+ENABLE_WERROR
+ENABLE_EXPENSIVE_CHECKS
+EXPENSIVE_CHECKS
+DEBUG_RUNTIME
+DEBUG_SYMBOLS
+KEEP_SYMBOLS
+JIT
+TARGET_HAS_JIT
+ENABLE_DOCS
+ENABLE_DOXYGEN
+LLVM_ENABLE_THREADS
+ENABLE_PTHREADS
+ENABLE_PIC
+ENABLE_SHARED
+ENABLE_EMBED_STDCXX
+ENABLE_TIMESTAMPS
+TARGETS_TO_BUILD
+LLVM_ENUM_TARGETS
+LLVM_ENUM_ASM_PRINTERS
+LLVM_ENUM_ASM_PARSERS
+LLVM_ENUM_DISASSEMBLERS
+OPTIMIZE_OPTION
+EXTRA_OPTIONS
+EXTRA_LD_OPTIONS
+CLANG_SRC_ROOT
+BINUTILS_INCDIR
+INTERNAL_PREFIX
+NM
+ifGNUmake
+LN_S
+CMP
+CP
+DATE
+FIND
+MKDIR
+MV
+RANLIB
+AR
+RM
+SED
+TAR
+BINPWD
+GRAPHVIZ
+DOT
+FDP
+NEATO
+TWOPI
+CIRCO
+GV
+DOTTY
+XDOT_PY
+INSTALL_PROGRAM
+INSTALL_SCRIPT
+INSTALL_DATA
+BZIP2
+CAT
+DOXYGEN
+GROFF
+GZIPBIN
+PDFROFF
+ZIP
+OCAMLC
+OCAMLOPT
+OCAMLDEP
+OCAMLDOC
+GAS
+HAVE_LINK_VERSION_SCRIPT
+INSTALL_LTDL_TRUE
+INSTALL_LTDL_FALSE
+CONVENIENCE_LTDL_TRUE
+CONVENIENCE_LTDL_FALSE
+LIBADD_DL
+NO_VARIADIC_MACROS
+NO_MISSING_FIELD_INITIALIZERS
+COVERED_SWITCH_DEFAULT
+USE_UDIS86
+USE_OPROFILE
+USE_INTEL_JITEVENTS
+INTEL_JITEVENTS_INCDIR
+INTEL_JITEVENTS_LIBDIR
+XML2CONFIG
+LIBXML2_LIBS
+LIBXML2_INC
+HAVE_PTHREAD
+HUGE_VAL_SANITY
+MMAP_FILE
+SHLIBEXT
+SHLIBPATH_VAR
+LLVM_PREFIX
+LLVM_BINDIR
+LLVM_LIBDIR
+LLVM_DATADIR
+LLVM_DOCSDIR
+LLVM_ETCDIR
+LLVM_INCLUDEDIR
+LLVM_INFODIR
+LLVM_MANDIR
+LLVM_CONFIGTIME
+BINDINGS_TO_BUILD
+ALL_BINDINGS
+OCAML_LIBDIR
+ENABLE_VISIBILITY_INLINES_HIDDEN
+RPATH
+RDYNAMIC
+LIBOBJS
+LTLIBOBJS'
+ac_subst_files=''
+ ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+CPPFLAGS
+CXX
+CXXFLAGS
+CCC
+CPP'
+ac_subdirs_all='projects/llvm-gcc
+projects/test-suite
+projects/llvm-test
+projects/poolalloc
+projects/llvm-poolalloc
+projects/sample
+projects/privbracket
+projects/llvm-stacker
+projects/llvm-reopt
+projects/llvm-java
+projects/llvm-tv
+projects/safecode
+projects/llvm-kernel
+tools/polly'
+
+# Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
+# The variables have the same names as the options, with
+# dashes changed to underlines.
+cache_file=/dev/null
+exec_prefix=NONE
+no_create=
+no_recursion=
+prefix=NONE
+program_prefix=NONE
+program_suffix=NONE
+program_transform_name=s,x,x,
+silent=
+site=
+srcdir=
+verbose=
+x_includes=NONE
+x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
+bindir='${exec_prefix}/bin'
+sbindir='${exec_prefix}/sbin'
+libexecdir='${exec_prefix}/libexec'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
+sysconfdir='${prefix}/etc'
+sharedstatedir='${prefix}/com'
+localstatedir='${prefix}/var'
+includedir='${prefix}/include'
+oldincludedir='/usr/include'
+docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
+
+ac_prev=
+ac_dashdash=
+for ac_option
+do
+ # If the previous option needs an argument, assign it.
+ if test -n "$ac_prev"; then
+ eval $ac_prev=\$ac_option
+ ac_prev=
+ continue
+ fi
+
+ case $ac_option in
+ *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+ *) ac_optarg=yes ;;
+ esac
+
+ # Accept the important Cygnus configure options, so we can diagnose typos.
+
+ case $ac_dashdash$ac_option in
+ --)
+ ac_dashdash=yes ;;
+
+ -bindir | --bindir | --bindi | --bind | --bin | --bi)
+ ac_prev=bindir ;;
+ -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
+ bindir=$ac_optarg ;;
+
+ -build | --build | --buil | --bui | --bu)
+ ac_prev=build_alias ;;
+ -build=* | --build=* | --buil=* | --bui=* | --bu=*)
+ build_alias=$ac_optarg ;;
+
+ -cache-file | --cache-file | --cache-fil | --cache-fi \
+ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+ ac_prev=cache_file ;;
+ -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
+ cache_file=$ac_optarg ;;
+
+ --config-cache | -C)
+ cache_file=config.cache ;;
+
+ -datadir | --datadir | --datadi | --datad)
+ ac_prev=datadir ;;
+ -datadir=* | --datadir=* | --datadi=* | --datad=*)
+ datadir=$ac_optarg ;;
+
+ -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+ | --dataroo | --dataro | --datar)
+ ac_prev=datarootdir ;;
+ -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+ datarootdir=$ac_optarg ;;
+
+ -disable-* | --disable-*)
+ ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+ { (exit 1); exit 1; }; }
+ ac_feature=`echo $ac_feature | sed 's/-/_/g'`
+ eval enable_$ac_feature=no ;;
+
+ -docdir | --docdir | --docdi | --doc | --do)
+ ac_prev=docdir ;;
+ -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+ docdir=$ac_optarg ;;
+
+ -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+ ac_prev=dvidir ;;
+ -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+ dvidir=$ac_optarg ;;
+
+ -enable-* | --enable-*)
+ ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+ { (exit 1); exit 1; }; }
+ ac_feature=`echo $ac_feature | sed 's/-/_/g'`
+ eval enable_$ac_feature=\$ac_optarg ;;
+
+ -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
+ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
+ | --exec | --exe | --ex)
+ ac_prev=exec_prefix ;;
+ -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
+ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
+ | --exec=* | --exe=* | --ex=*)
+ exec_prefix=$ac_optarg ;;
+
+ -gas | --gas | --ga | --g)
+ # Obsolete; use --with-gas.
+ with_gas=yes ;;
+
+ -help | --help | --hel | --he | -h)
+ ac_init_help=long ;;
+ -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+ ac_init_help=recursive ;;
+ -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+ ac_init_help=short ;;
+
+ -host | --host | --hos | --ho)
+ ac_prev=host_alias ;;
+ -host=* | --host=* | --hos=* | --ho=*)
+ host_alias=$ac_optarg ;;
+
+ -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+ ac_prev=htmldir ;;
+ -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+ | --ht=*)
+ htmldir=$ac_optarg ;;
+
+ -includedir | --includedir | --includedi | --included | --include \
+ | --includ | --inclu | --incl | --inc)
+ ac_prev=includedir ;;
+ -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
+ | --includ=* | --inclu=* | --incl=* | --inc=*)
+ includedir=$ac_optarg ;;
+
+ -infodir | --infodir | --infodi | --infod | --info | --inf)
+ ac_prev=infodir ;;
+ -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
+ infodir=$ac_optarg ;;
+
+ -libdir | --libdir | --libdi | --libd)
+ ac_prev=libdir ;;
+ -libdir=* | --libdir=* | --libdi=* | --libd=*)
+ libdir=$ac_optarg ;;
+
+ -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
+ | --libexe | --libex | --libe)
+ ac_prev=libexecdir ;;
+ -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
+ | --libexe=* | --libex=* | --libe=*)
+ libexecdir=$ac_optarg ;;
+
+ -localedir | --localedir | --localedi | --localed | --locale)
+ ac_prev=localedir ;;
+ -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+ localedir=$ac_optarg ;;
+
+ -localstatedir | --localstatedir | --localstatedi | --localstated \
+ | --localstate | --localstat | --localsta | --localst | --locals)
+ ac_prev=localstatedir ;;
+ -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
+ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+ localstatedir=$ac_optarg ;;
+
+ -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
+ ac_prev=mandir ;;
+ -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
+ mandir=$ac_optarg ;;
+
+ -nfp | --nfp | --nf)
+ # Obsolete; use --without-fp.
+ with_fp=no ;;
+
+ -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+ | --no-cr | --no-c | -n)
+ no_create=yes ;;
+
+ -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
+ no_recursion=yes ;;
+
+ -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
+ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
+ | --oldin | --oldi | --old | --ol | --o)
+ ac_prev=oldincludedir ;;
+ -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
+ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
+ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
+ oldincludedir=$ac_optarg ;;
+
+ -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+ ac_prev=prefix ;;
+ -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+ prefix=$ac_optarg ;;
+
+ -program-prefix | --program-prefix | --program-prefi | --program-pref \
+ | --program-pre | --program-pr | --program-p)
+ ac_prev=program_prefix ;;
+ -program-prefix=* | --program-prefix=* | --program-prefi=* \
+ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
+ program_prefix=$ac_optarg ;;
+
+ -program-suffix | --program-suffix | --program-suffi | --program-suff \
+ | --program-suf | --program-su | --program-s)
+ ac_prev=program_suffix ;;
+ -program-suffix=* | --program-suffix=* | --program-suffi=* \
+ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
+ program_suffix=$ac_optarg ;;
+
+ -program-transform-name | --program-transform-name \
+ | --program-transform-nam | --program-transform-na \
+ | --program-transform-n | --program-transform- \
+ | --program-transform | --program-transfor \
+ | --program-transfo | --program-transf \
+ | --program-trans | --program-tran \
+ | --progr-tra | --program-tr | --program-t)
+ ac_prev=program_transform_name ;;
+ -program-transform-name=* | --program-transform-name=* \
+ | --program-transform-nam=* | --program-transform-na=* \
+ | --program-transform-n=* | --program-transform-=* \
+ | --program-transform=* | --program-transfor=* \
+ | --program-transfo=* | --program-transf=* \
+ | --program-trans=* | --program-tran=* \
+ | --progr-tra=* | --program-tr=* | --program-t=*)
+ program_transform_name=$ac_optarg ;;
+
+ -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+ ac_prev=pdfdir ;;
+ -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+ pdfdir=$ac_optarg ;;
+
+ -psdir | --psdir | --psdi | --psd | --ps)
+ ac_prev=psdir ;;
+ -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+ psdir=$ac_optarg ;;
+
+ -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+ | -silent | --silent | --silen | --sile | --sil)
+ silent=yes ;;
+
+ -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
+ ac_prev=sbindir ;;
+ -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
+ | --sbi=* | --sb=*)
+ sbindir=$ac_optarg ;;
+
+ -sharedstatedir | --sharedstatedir | --sharedstatedi \
+ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
+ | --sharedst | --shareds | --shared | --share | --shar \
+ | --sha | --sh)
+ ac_prev=sharedstatedir ;;
+ -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
+ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
+ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
+ | --sha=* | --sh=*)
+ sharedstatedir=$ac_optarg ;;
+
+ -site | --site | --sit)
+ ac_prev=site ;;
+ -site=* | --site=* | --sit=*)
+ site=$ac_optarg ;;
+
+ -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+ ac_prev=srcdir ;;
+ -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+ srcdir=$ac_optarg ;;
+
+ -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
+ | --syscon | --sysco | --sysc | --sys | --sy)
+ ac_prev=sysconfdir ;;
+ -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
+ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
+ sysconfdir=$ac_optarg ;;
+
+ -target | --target | --targe | --targ | --tar | --ta | --t)
+ ac_prev=target_alias ;;
+ -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
+ target_alias=$ac_optarg ;;
+
+ -v | -verbose | --verbose | --verbos | --verbo | --verb)
+ verbose=yes ;;
+
+ -version | --version | --versio | --versi | --vers | -V)
+ ac_init_version=: ;;
+
+ -with-* | --with-*)
+ ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid package name: $ac_package" >&2
+ { (exit 1); exit 1; }; }
+ ac_package=`echo $ac_package| sed 's/-/_/g'`
+ eval with_$ac_package=\$ac_optarg ;;
+
+ -without-* | --without-*)
+ ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid package name: $ac_package" >&2
+ { (exit 1); exit 1; }; }
+ ac_package=`echo $ac_package | sed 's/-/_/g'`
+ eval with_$ac_package=no ;;
+
+ --x)
+ # Obsolete; use --with-x.
+ with_x=yes ;;
+
+ -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
+ | --x-incl | --x-inc | --x-in | --x-i)
+ ac_prev=x_includes ;;
+ -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
+ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
+ x_includes=$ac_optarg ;;
+
+ -x-libraries | --x-libraries | --x-librarie | --x-librari \
+ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
+ ac_prev=x_libraries ;;
+ -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
+ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
+ x_libraries=$ac_optarg ;;
+
+ -*) { echo "$as_me: error: unrecognized option: $ac_option
+Try \`$0 --help' for more information." >&2
+ { (exit 1); exit 1; }; }
+ ;;
+
+ *=*)
+ ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
+ { (exit 1); exit 1; }; }
+ eval $ac_envvar=\$ac_optarg
+ export $ac_envvar ;;
+
+ *)
+ # FIXME: should be removed in autoconf 3.0.
+ echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+ expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+ echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+ : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
+ ;;
+
+ esac
+done
+
+if test -n "$ac_prev"; then
+ ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+ { echo "$as_me: error: missing argument to $ac_option" >&2
+ { (exit 1); exit 1; }; }
+fi
+
+# Be sure to have absolute directory names.
+for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \
+ datadir sysconfdir sharedstatedir localstatedir includedir \
+ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+ libdir localedir mandir
+do
+ eval ac_val=\$$ac_var
+ case $ac_val in
+ [\\/$]* | ?:[\\/]* ) continue;;
+ NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+ esac
+ { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+ { (exit 1); exit 1; }; }
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+ if test "x$build_alias" = x; then
+ cross_compiling=maybe
+ echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
+ If a cross compiler is detected then cross compile mode will be used." >&2
+ elif test "x$build_alias" != "x$host_alias"; then
+ cross_compiling=yes
+ fi
+fi
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+ { echo "$as_me: error: Working directory cannot be determined" >&2
+ { (exit 1); exit 1; }; }
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+ { echo "$as_me: error: pwd does not report name of working directory" >&2
+ { (exit 1); exit 1; }; }
+
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+ ac_srcdir_defaulted=yes
+ # Try the directory containing this script, then the parent directory.
+ ac_confdir=`$as_dirname -- "$0" ||
+$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$0" : 'X\(//\)[^/]' \| \
+ X"$0" : 'X\(//\)$' \| \
+ X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$0" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ srcdir=$ac_confdir
+ if test ! -r "$srcdir/$ac_unique_file"; then
+ srcdir=..
+ fi
+else
+ ac_srcdir_defaulted=no
+fi
+if test ! -r "$srcdir/$ac_unique_file"; then
+ test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+ { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+ { (exit 1); exit 1; }; }
+fi
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+ cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2
+ { (exit 1); exit 1; }; }
+ pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+ srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+ eval ac_env_${ac_var}_set=\${${ac_var}+set}
+ eval ac_env_${ac_var}_value=\$${ac_var}
+ eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+ eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+if test "$ac_init_help" = "long"; then
+ # Omit some internal or obsolete options to make the list less imposing.
+ # This message is too long to be a string in the A/UX 3.1 sh.
+ cat <<_ACEOF
+\`configure' configures LLVM 3.2svn to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE. See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+ -h, --help display this help and exit
+ --help=short display options specific to this package
+ --help=recursive display the short help of all the included packages
+ -V, --version display version information and exit
+ -q, --quiet, --silent do not print \`checking...' messages
+ --cache-file=FILE cache test results in FILE [disabled]
+ -C, --config-cache alias for \`--cache-file=config.cache'
+ -n, --no-create do not create output files
+ --srcdir=DIR find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+ --prefix=PREFIX install architecture-independent files in PREFIX
+ [$ac_default_prefix]
+ --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
+ [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+ --bindir=DIR user executables [EPREFIX/bin]
+ --sbindir=DIR system admin executables [EPREFIX/sbin]
+ --libexecdir=DIR program executables [EPREFIX/libexec]
+ --sysconfdir=DIR read-only single-machine data [PREFIX/etc]
+ --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com]
+ --localstatedir=DIR modifiable single-machine data [PREFIX/var]
+ --libdir=DIR object code libraries [EPREFIX/lib]
+ --includedir=DIR C header files [PREFIX/include]
+ --oldincludedir=DIR C header files for non-gcc [/usr/include]
+ --datarootdir=DIR read-only arch.-independent data root [PREFIX/share]
+ --datadir=DIR read-only architecture-independent data [DATAROOTDIR]
+ --infodir=DIR info documentation [DATAROOTDIR/info]
+ --localedir=DIR locale-dependent data [DATAROOTDIR/locale]
+ --mandir=DIR man documentation [DATAROOTDIR/man]
+ --docdir=DIR documentation root [DATAROOTDIR/doc/llvm]
+ --htmldir=DIR html documentation [DOCDIR]
+ --dvidir=DIR dvi documentation [DOCDIR]
+ --pdfdir=DIR pdf documentation [DOCDIR]
+ --psdir=DIR ps documentation [DOCDIR]
+_ACEOF
+
+ cat <<\_ACEOF
+
+System types:
+ --build=BUILD configure for building on BUILD [guessed]
+ --host=HOST cross-compile to build programs to run on HOST [BUILD]
+ --target=TARGET configure for building compilers for TARGET [HOST]
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+ case $ac_init_help in
+ short | recursive ) echo "Configuration of LLVM 3.2svn:";;
+ esac
+ cat <<\_ACEOF
+
+Optional Features:
+ --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
+ --enable-FEATURE[=ARG] include FEATURE [ARG=yes]
+ --enable-polly Use polly if available (default is YES)
+ --enable-libcpp Use libc++ if available (default is NO)
+ --enable-cxx11 Use c++11 if available (default is NO)
+ --enable-optimized Compile with optimizations enabled (default is NO)
+ --enable-profiling Compile with profiling enabled (default is NO)
+ --enable-assertions Compile with assertion checks enabled (default is
+ YES)
+ --enable-werror Compile with -Werror enabled (default is NO)
+ --enable-expensive-checks
+ Compile with expensive debug checks enabled (default
+ is NO)
+ --enable-debug-runtime Build runtime libs with debug symbols (default is
+ NO)
+ --enable-debug-symbols Build compiler with debug symbols (default is NO if
+ optimization is on and YES if it's off)
+ --enable-keep-symbols Do not strip installed executables)
+ --enable-jit Enable Just In Time Compiling (default is YES)
+ --enable-docs Build documents (default is YES)
+ --enable-doxygen Build doxygen documentation (default is NO)
+ --enable-threads Use threads if available (default is YES)
+ --enable-pthreads Use pthreads if available (default is YES)
+ --enable-pic Build LLVM with Position Independent Code (default
+ is YES)
+ --enable-shared Build a shared library and link tools against it
+ (default is NO)
+ --enable-embed-stdcxx Build a shared library with embedded libstdc++ for
+ Win32 DLL (default is NO)
+ --enable-timestamps Enable embedding timestamp information in build
+ (default is YES)
+ --enable-targets Build specific host targets: all or
+ target1,target2,... Valid targets are: host, x86,
+ x86_64, sparc, powerpc, arm, mips, spu, hexagon,
+ xcore, msp430, nvptx, and cpp (default=all)
+ --enable-experimental-targets
+ Build experimental host targets: disable or
+ target1,target2,... (default=disable)
+ --enable-bindings Build specific language bindings:
+ all,auto,none,{binding-name} (default=auto)
+ --enable-libffi Check for the presence of libffi (default is NO)
+ --enable-ltdl-install install libltdl
+
+Optional Packages:
+ --with-PACKAGE[=ARG] use PACKAGE [ARG=yes]
+ --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no)
+ --with-optimize-option Select the compiler options to use for optimized
+ builds
+ --with-extra-options Specify additional options to compile LLVM with
+ --with-extra-ld-options Specify additional options to link LLVM with
+ --with-ocaml-libdir Specify install location for ocaml bindings (default
+ is stdlib)
+ --with-clang-srcdir Directory to the out-of-tree Clang source
+ --with-clang-resource-dir
+ Relative directory from the Clang binary for
+ resource files
+ --with-c-include-dirs Colon separated list of directories clang will
+ search for headers
+ --with-gcc-toolchain Directory where gcc is installed.
+ --with-default-sysroot Add --sysroot=<path> to all compiler invocations.
+ --with-binutils-include Specify path to binutils/include/ containing
+ plugin-api.h file for gold plugin.
+ --with-bug-report-url Specify the URL where bug reports should be
+ submitted (default=http://llvm.org/bugs/)
+ --with-internal-prefix Installation directory for internal files
+ --with-udis86=<path> Use udis86 external x86 disassembler library
+ --with-oprofile=<prefix>
+ Tell OProfile >= 0.9.4 how to symbolize JIT output
+ --with-intel-jitevents=<vtune-amplifier-dir>
+ Specify location of run-time support library for
+ Intel JIT API
+ (default=/opt/intel/vtune_amplifier_xe_2011)
+
+Some influential environment variables:
+ CC C compiler command
+ CFLAGS C compiler flags
+ LDFLAGS linker flags, e.g. -L<lib dir> if you have libraries in a
+ nonstandard directory <lib dir>
+ CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I<include dir> if
+ you have headers in a nonstandard directory <include dir>
+ CXX C++ compiler command
+ CXXFLAGS C++ compiler flags
+ CPP C preprocessor
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+Report bugs to <http://llvm.org/bugs/>.
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+ # If there are subdirs, report their specific --help.
+ for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+ test -d "$ac_dir" || continue
+ ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+ ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+ # A ".." for each directory in $ac_dir_suffix.
+ ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+ case $ac_top_builddir_sub in
+ "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+ *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+ esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+ .) # We are building in place.
+ ac_srcdir=.
+ ac_top_srcdir=$ac_top_builddir_sub
+ ac_abs_top_srcdir=$ac_pwd ;;
+ [\\/]* | ?:[\\/]* ) # Absolute name.
+ ac_srcdir=$srcdir$ac_dir_suffix;
+ ac_top_srcdir=$srcdir
+ ac_abs_top_srcdir=$srcdir ;;
+ *) # Relative name.
+ ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+ ac_top_srcdir=$ac_top_build_prefix$srcdir
+ ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+ cd "$ac_dir" || { ac_status=$?; continue; }
+ # Check for guested configure.
+ if test -f "$ac_srcdir/configure.gnu"; then
+ echo &&
+ $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+ elif test -f "$ac_srcdir/configure"; then
+ echo &&
+ $SHELL "$ac_srcdir/configure" --help=recursive
+ else
+ echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+ fi || ac_status=$?
+ cd "$ac_pwd" || { ac_status=$?; break; }
+ done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+ cat <<\_ACEOF
+LLVM configure 3.2svn
+generated by GNU Autoconf 2.60
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+
+Copyright (c) 2003-2012 University of Illinois at Urbana-Champaign.
+_ACEOF
+ exit
+fi
+cat >config.log <<_ACEOF
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+
+It was created by LLVM $as_me 3.2svn, which was
+generated by GNU Autoconf 2.60. Invocation command line was
+
+ $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown`
+
+/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown`
+/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown`
+/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown`
+/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown`
+/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ echo "PATH: $as_dir"
+done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+ for ac_arg
+ do
+ case $ac_arg in
+ -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+ -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+ | -silent | --silent | --silen | --sile | --sil)
+ continue ;;
+ *\'*)
+ ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+ esac
+ case $ac_pass in
+ 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
+ 2)
+ ac_configure_args1="$ac_configure_args1 '$ac_arg'"
+ if test $ac_must_keep_next = true; then
+ ac_must_keep_next=false # Got value, back to normal.
+ else
+ case $ac_arg in
+ *=* | --config-cache | -C | -disable-* | --disable-* \
+ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+ | -with-* | --with-* | -without-* | --without-* | --x)
+ case "$ac_configure_args0 " in
+ "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+ esac
+ ;;
+ -* ) ac_must_keep_next=true ;;
+ esac
+ fi
+ ac_configure_args="$ac_configure_args '$ac_arg'"
+ ;;
+ esac
+ done
+done
+$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
+$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log. We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+ # Save into config.log some information that might help in debugging.
+ {
+ echo
+
+ cat <<\_ASBOX
+## ---------------- ##
+## Cache variables. ##
+## ---------------- ##
+_ASBOX
+ echo
+ # The following way of writing the cache mishandles newlines in values,
+(
+ for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+ eval ac_val=\$$ac_var
+ case $ac_val in #(
+ *${as_nl}*)
+ case $ac_var in #(
+ *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+ esac
+ case $ac_var in #(
+ _ | IFS | as_nl) ;; #(
+ *) $as_unset $ac_var ;;
+ esac ;;
+ esac
+ done
+ (set) 2>&1 |
+ case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+ *${as_nl}ac_space=\ *)
+ sed -n \
+ "s/'\''/'\''\\\\'\'''\''/g;
+ s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+ ;; #(
+ *)
+ sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+ ;;
+ esac |
+ sort
+)
+ echo
+
+ cat <<\_ASBOX
+## ----------------- ##
+## Output variables. ##
+## ----------------- ##
+_ASBOX
+ echo
+ for ac_var in $ac_subst_vars
+ do
+ eval ac_val=\$$ac_var
+ case $ac_val in
+ *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+ esac
+ echo "$ac_var='\''$ac_val'\''"
+ done | sort
+ echo
+
+ if test -n "$ac_subst_files"; then
+ cat <<\_ASBOX
+## ------------------- ##
+## File substitutions. ##
+## ------------------- ##
+_ASBOX
+ echo
+ for ac_var in $ac_subst_files
+ do
+ eval ac_val=\$$ac_var
+ case $ac_val in
+ *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+ esac
+ echo "$ac_var='\''$ac_val'\''"
+ done | sort
+ echo
+ fi
+
+ if test -s confdefs.h; then
+ cat <<\_ASBOX
+## ----------- ##
+## confdefs.h. ##
+## ----------- ##
+_ASBOX
+ echo
+ cat confdefs.h
+ echo
+ fi
+ test "$ac_signal" != 0 &&
+ echo "$as_me: caught signal $ac_signal"
+ echo "$as_me: exit $exit_status"
+ } >&5
+ rm -f core *.core core.conftest.* &&
+ rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+ exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+ trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
+# Prefer explicitly selected file to automatically selected ones.
+if test -n "$CONFIG_SITE"; then
+ set x "$CONFIG_SITE"
+elif test "x$prefix" != xNONE; then
+ set x "$prefix/share/config.site" "$prefix/etc/config.site"
+else
+ set x "$ac_default_prefix/share/config.site" \
+ "$ac_default_prefix/etc/config.site"
+fi
+shift
+for ac_site_file
+do
+ if test -r "$ac_site_file"; then
+ { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
+echo "$as_me: loading site script $ac_site_file" >&6;}
+ sed 's/^/| /' "$ac_site_file" >&5
+ . "$ac_site_file"
+ fi
+done
+
+if test -r "$cache_file"; then
+ # Some versions of bash will fail to source /dev/null (special
+ # files actually), so we avoid doing that.
+ if test -f "$cache_file"; then
+ { echo "$as_me:$LINENO: loading cache $cache_file" >&5
+echo "$as_me: loading cache $cache_file" >&6;}
+ case $cache_file in
+ [\\/]* | ?:[\\/]* ) . "$cache_file";;
+ *) . "./$cache_file";;
+ esac
+ fi
+else
+ { echo "$as_me:$LINENO: creating cache $cache_file" >&5
+echo "$as_me: creating cache $cache_file" >&6;}
+ >$cache_file
+fi
+
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+ eval ac_old_set=\$ac_cv_env_${ac_var}_set
+ eval ac_new_set=\$ac_env_${ac_var}_set
+ eval ac_old_val=\$ac_cv_env_${ac_var}_value
+ eval ac_new_val=\$ac_env_${ac_var}_value
+ case $ac_old_set,$ac_new_set in
+ set,)
+ { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+ ac_cache_corrupted=: ;;
+ ,set)
+ { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+ ac_cache_corrupted=: ;;
+ ,);;
+ *)
+ if test "x$ac_old_val" != "x$ac_new_val"; then
+ { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
+echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+ { echo "$as_me:$LINENO: former value: $ac_old_val" >&5
+echo "$as_me: former value: $ac_old_val" >&2;}
+ { echo "$as_me:$LINENO: current value: $ac_new_val" >&5
+echo "$as_me: current value: $ac_new_val" >&2;}
+ ac_cache_corrupted=:
+ fi;;
+ esac
+ # Pass precious variables to config.status.
+ if test "$ac_new_set" = set; then
+ case $ac_new_val in
+ *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+ *) ac_arg=$ac_var=$ac_new_val ;;
+ esac
+ case " $ac_configure_args " in
+ *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy.
+ *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
+ esac
+ fi
+done
+if $ac_cache_corrupted; then
+ { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
+echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+ { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
+echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+cat >>confdefs.h <<\_ACEOF
+#define LLVM_VERSION_MAJOR 3
+_ACEOF
+
+
+cat >>confdefs.h <<\_ACEOF
+#define LLVM_VERSION_MINOR 2
+_ACEOF
+
+
+LLVM_COPYRIGHT="Copyright (c) 2003-2012 University of Illinois at Urbana-Champaign."
+
+
+
+
+
+
+
+ac_aux_dir=
+for ac_dir in autoconf "$srcdir"/autoconf; do
+ if test -f "$ac_dir/install-sh"; then
+ ac_aux_dir=$ac_dir
+ ac_install_sh="$ac_aux_dir/install-sh -c"
+ break
+ elif test -f "$ac_dir/install.sh"; then
+ ac_aux_dir=$ac_dir
+ ac_install_sh="$ac_aux_dir/install.sh -c"
+ break
+ elif test -f "$ac_dir/shtool"; then
+ ac_aux_dir=$ac_dir
+ ac_install_sh="$ac_aux_dir/shtool install -c"
+ break
+ fi
+done
+if test -z "$ac_aux_dir"; then
+ { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in autoconf \"$srcdir\"/autoconf" >&5
+echo "$as_me: error: cannot find install-sh or install.sh in autoconf \"$srcdir\"/autoconf" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+# These three variables are undocumented and unsupported,
+# and are intended to be withdrawn in a future Autoconf release.
+# They can cause serious problems if a builder's source tree is in a directory
+# whose full name contains unusual characters.
+ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var.
+ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var.
+ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var.
+
+
+
+if test ${srcdir} != "." ; then
+ if test -f ${srcdir}/include/llvm/Config/config.h ; then
+ { { echo "$as_me:$LINENO: error: Already configured in ${srcdir}" >&5
+echo "$as_me: error: Already configured in ${srcdir}" >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+ for ac_prog in clang llvm-gcc gcc
+ do
+ # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$CC"; then
+ ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+ { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$CC" && break
+ done
+fi
+if test -z "$CC"; then
+ ac_ct_CC=$CC
+ for ac_prog in clang llvm-gcc gcc
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_CC"; then
+ ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_ac_ct_CC="$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+ { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$ac_ct_CC" && break
+done
+
+ if test "x$ac_ct_CC" = x; then
+ CC=""
+ else
+ case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet. If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet. If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+ CC=$ac_ct_CC
+ fi
+fi
+
+
+test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH
+See \`config.log' for more details." >&5
+echo "$as_me: error: no acceptable C compiler found in \$PATH
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+
+# Provide some information about the compiler.
+echo "$as_me:$LINENO: checking for C compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (ac_try="$ac_compiler --version >&5"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compiler --version >&5") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (ac_try="$ac_compiler -v >&5"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compiler -v >&5") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (ac_try="$ac_compiler -V >&5"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compiler -V >&5") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
+echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; }
+ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+#
+# List of possible output files, starting from the most likely.
+# The algorithm is not robust to junk in `.', hence go to wildcards (a.*)
+# only as a last resort. b.out is created by i960 compilers.
+ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out'
+#
+# The IRIX 6 linker writes into existing files which may not be
+# executable, retaining their permissions. Remove them first so a
+# subsequent execution test works.
+ac_rmfiles=
+for ac_file in $ac_files
+do
+ case $ac_file in
+ *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;;
+ * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+ esac
+done
+rm -f $ac_rmfiles
+
+if { (ac_try="$ac_link_default"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link_default") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile. We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files
+do
+ test -f "$ac_file" || continue
+ case $ac_file in
+ *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj )
+ ;;
+ [ab].out )
+ # We found the default executable, but exeext='' is most
+ # certainly right.
+ break;;
+ *.* )
+ if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+ then :; else
+ ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+ fi
+ # We set ac_cv_exeext here because the later test for it is not
+ # safe: cross compilers may not add the suffix if given an `-o'
+ # argument, so we may need to know it at that point already.
+ # Even if this section looks crufty: it has the advantage of
+ # actually working.
+ break;;
+ * )
+ break;;
+ esac
+done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
+See \`config.log' for more details." >&5
+echo "$as_me: error: C compiler cannot create executables
+See \`config.log' for more details." >&2;}
+ { (exit 77); exit 77; }; }
+fi
+
+ac_exeext=$ac_cv_exeext
+{ echo "$as_me:$LINENO: result: $ac_file" >&5
+echo "${ECHO_T}$ac_file" >&6; }
+
+# Check that the compiler produces executables we can run. If not, either
+# the compiler is broken, or we cross compile.
+{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5
+echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; }
+# FIXME: These cross compiler hacks should be removed for Autoconf 3.0
+# If not cross compiling, check that we can run a simple program.
+if test "$cross_compiling" != yes; then
+ if { ac_try='./$ac_file'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ cross_compiling=no
+ else
+ if test "$cross_compiling" = maybe; then
+ cross_compiling=yes
+ else
+ { { echo "$as_me:$LINENO: error: cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+ fi
+fi
+{ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
+
+rm -f a.out a.exe conftest$ac_cv_exeext b.out
+ac_clean_files=$ac_clean_files_save
+# Check that the compiler produces executables we can run. If not, either
+# the compiler is broken, or we cross compile.
+{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
+echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; }
+{ echo "$as_me:$LINENO: result: $cross_compiling" >&5
+echo "${ECHO_T}$cross_compiling" >&6; }
+
+{ echo "$as_me:$LINENO: checking for suffix of executables" >&5
+echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; }
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+ test -f "$ac_file" || continue
+ case $ac_file in
+ *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;;
+ *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+ break;;
+ * ) break;;
+ esac
+done
+else
+ { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+rm -f conftest$ac_cv_exeext
+{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
+echo "${ECHO_T}$ac_cv_exeext" >&6; }
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+{ echo "$as_me:$LINENO: checking for suffix of object files" >&5
+echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; }
+if test "${ac_cv_objext+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ for ac_file in conftest.o conftest.obj conftest.*; do
+ test -f "$ac_file" || continue;
+ case $ac_file in
+ *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;;
+ *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+ break;;
+ esac
+done
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
+echo "${ECHO_T}$ac_cv_objext" >&6; }
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; }
+if test "${ac_cv_c_compiler_gnu+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+#ifndef __GNUC__
+ choke me
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_compiler_gnu=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_compiler_gnu=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; }
+GCC=`test $ac_compiler_gnu = yes && echo yes`
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
+echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cc_g+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_save_c_werror_flag=$ac_c_werror_flag
+ ac_c_werror_flag=yes
+ ac_cv_prog_cc_g=no
+ CFLAGS="-g"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_cc_g=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ CFLAGS=""
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_c_werror_flag=$ac_save_c_werror_flag
+ CFLAGS="-g"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_cc_g=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; }
+if test "$ac_test_CFLAGS" = set; then
+ CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+ if test "$GCC" = yes; then
+ CFLAGS="-g -O2"
+ else
+ CFLAGS="-g"
+ fi
+else
+ if test "$GCC" = yes; then
+ CFLAGS="-O2"
+ else
+ CFLAGS=
+ fi
+fi
+{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5
+echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cc_c89+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdarg.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+ char **p;
+ int i;
+{
+ return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+ char *s;
+ va_list v;
+ va_start (v,p);
+ s = g (p, va_arg (v,int));
+ va_end (v);
+ return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has
+ function prototypes and stuff, but not '\xHH' hex character constants.
+ These don't provoke an error unfortunately, instead are silently treated
+ as 'x'. The following induces an error, until -std is added to get
+ proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an
+ array size at least. It's necessary to write '\x00'==0 to get something
+ that's true only with -std. */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+ inside strings and character constants. */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1];
+ ;
+ return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+ CC="$ac_save_CC $ac_arg"
+ rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_cc_c89=$ac_arg
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext
+ test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+ x)
+ { echo "$as_me:$LINENO: result: none needed" >&5
+echo "${ECHO_T}none needed" >&6; } ;;
+ xno)
+ { echo "$as_me:$LINENO: result: unsupported" >&5
+echo "${ECHO_T}unsupported" >&6; } ;;
+ *)
+ CC="$CC $ac_cv_prog_cc_c89"
+ { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+if test -z "$CXX"; then
+ if test -n "$CCC"; then
+ CXX=$CCC
+ else
+ if test -n "$ac_tool_prefix"; then
+ for ac_prog in clang++ llvm-g++ g++
+ do
+ # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$CXX"; then
+ ac_cv_prog_CXX="$CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+CXX=$ac_cv_prog_CXX
+if test -n "$CXX"; then
+ { echo "$as_me:$LINENO: result: $CXX" >&5
+echo "${ECHO_T}$CXX" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$CXX" && break
+ done
+fi
+if test -z "$CXX"; then
+ ac_ct_CXX=$CXX
+ for ac_prog in clang++ llvm-g++ g++
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_CXX"; then
+ ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_ac_ct_CXX="$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
+if test -n "$ac_ct_CXX"; then
+ { echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
+echo "${ECHO_T}$ac_ct_CXX" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$ac_ct_CXX" && break
+done
+
+ if test "x$ac_ct_CXX" = x; then
+ CXX="g++"
+ else
+ case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet. If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet. If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+ CXX=$ac_ct_CXX
+ fi
+fi
+
+ fi
+fi
+# Provide some information about the compiler.
+echo "$as_me:$LINENO: checking for C++ compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (ac_try="$ac_compiler --version >&5"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compiler --version >&5") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (ac_try="$ac_compiler -v >&5"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compiler -v >&5") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (ac_try="$ac_compiler -V >&5"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compiler -V >&5") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+
+{ echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6; }
+if test "${ac_cv_cxx_compiler_gnu+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+#ifndef __GNUC__
+ choke me
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_compiler_gnu=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_compiler_gnu=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6; }
+GXX=`test $ac_compiler_gnu = yes && echo yes`
+ac_test_CXXFLAGS=${CXXFLAGS+set}
+ac_save_CXXFLAGS=$CXXFLAGS
+{ echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
+echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cxx_g+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_save_cxx_werror_flag=$ac_cxx_werror_flag
+ ac_cxx_werror_flag=yes
+ ac_cv_prog_cxx_g=no
+ CXXFLAGS="-g"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_cxx_g=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ CXXFLAGS=""
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+ CXXFLAGS="-g"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_cxx_g=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6; }
+if test "$ac_test_CXXFLAGS" = set; then
+ CXXFLAGS=$ac_save_CXXFLAGS
+elif test $ac_cv_prog_cxx_g = yes; then
+ if test "$GXX" = yes; then
+ CXXFLAGS="-g -O2"
+ else
+ CXXFLAGS="-g"
+ fi
+else
+ if test "$GXX" = yes; then
+ CXXFLAGS="-O2"
+ else
+ CXXFLAGS=
+ fi
+fi
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
+echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; }
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+ CPP=
+fi
+if test -z "$CPP"; then
+ if test "${ac_cv_prog_CPP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # Double quotes because CPP needs to be expanded
+ for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+ do
+ ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+ # Use a header file that comes with gcc, so configuring glibc
+ # with a fresh cross-compiler works.
+ # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ # <limits.h> exists even on freestanding compilers.
+ # On the NeXT, cc -E runs the code through the compiler's parser,
+ # not just through cpp. "Syntax error" is here to catch this case.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+ Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Broken: fails on valid input.
+continue
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+ # OK, works on sane cases. Now check whether nonexistent headers
+ # can be detected and how.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ # Broken: success on invalid input.
+continue
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+ break
+fi
+
+ done
+ ac_cv_prog_CPP=$CPP
+
+fi
+ CPP=$ac_cv_prog_CPP
+else
+ ac_cv_prog_CPP=$CPP
+fi
+{ echo "$as_me:$LINENO: result: $CPP" >&5
+echo "${ECHO_T}$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+ # Use a header file that comes with gcc, so configuring glibc
+ # with a fresh cross-compiler works.
+ # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ # <limits.h> exists even on freestanding compilers.
+ # On the NeXT, cc -E runs the code through the compiler's parser,
+ # not just through cpp. "Syntax error" is here to catch this case.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+ Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Broken: fails on valid input.
+continue
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+ # OK, works on sane cases. Now check whether nonexistent headers
+ # can be detected and how.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ # Broken: success on invalid input.
+continue
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+ :
+else
+ { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." >&5
+echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+
+if test -d ${srcdir}/projects/llvm-gcc ; then
+ subdirs="$subdirs projects/llvm-gcc"
+
+fi
+
+if test -d ${srcdir}/projects/test-suite ; then
+ subdirs="$subdirs projects/test-suite"
+
+fi
+
+if test -d ${srcdir}/projects/llvm-test ; then
+ subdirs="$subdirs projects/llvm-test"
+
+fi
+
+if test -d ${srcdir}/projects/poolalloc ; then
+ subdirs="$subdirs projects/poolalloc"
+
+fi
+
+if test -d ${srcdir}/projects/llvm-poolalloc ; then
+ subdirs="$subdirs projects/llvm-poolalloc"
+
+fi
+
+for i in `ls ${srcdir}/projects`
+do
+ if test -d ${srcdir}/projects/${i} ; then
+ case ${i} in
+ sample) subdirs="$subdirs projects/sample"
+ ;;
+ privbracket) subdirs="$subdirs projects/privbracket"
+ ;;
+ llvm-stacker) subdirs="$subdirs projects/llvm-stacker"
+ ;;
+ llvm-reopt) subdirs="$subdirs projects/llvm-reopt"
+;;
+ llvm-java) subdirs="$subdirs projects/llvm-java"
+ ;;
+ llvm-tv) subdirs="$subdirs projects/llvm-tv"
+ ;;
+ safecode) subdirs="$subdirs projects/safecode"
+ ;;
+ llvm-kernel) subdirs="$subdirs projects/llvm-kernel"
+ ;;
+ compiler-rt) ;;
+ llvm-gcc) ;;
+ test-suite) ;;
+ llvm-test) ;;
+ poolalloc) ;;
+ llvm-poolalloc) ;;
+ *)
+ { echo "$as_me:$LINENO: WARNING: Unknown project (${i}) won't be configured automatically" >&5
+echo "$as_me: WARNING: Unknown project (${i}) won't be configured automatically" >&2;}
+ ;;
+ esac
+ fi
+done
+
+# Check whether --enable-polly was given.
+if test "${enable_polly+set}" = set; then
+ enableval=$enable_polly;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_POLLY=1
+ ;;
+ no) ENABLE_POLLY=0
+ ;;
+ default) ENABLE_POLLY=1
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-polly. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-polly. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+
+if (test -d ${srcdir}/tools/polly) && (test $ENABLE_POLLY -eq 1) ; then
+ LLVM_HAS_POLLY=1
+
+ subdirs="$subdirs tools/polly"
+
+fi
+
+
+# Make sure we can run config.sub.
+$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
+ { { echo "$as_me:$LINENO: error: cannot run $SHELL $ac_aux_dir/config.sub" >&5
+echo "$as_me: error: cannot run $SHELL $ac_aux_dir/config.sub" >&2;}
+ { (exit 1); exit 1; }; }
+
+{ echo "$as_me:$LINENO: checking build system type" >&5
+echo $ECHO_N "checking build system type... $ECHO_C" >&6; }
+if test "${ac_cv_build+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_build_alias=$build_alias
+test "x$ac_build_alias" = x &&
+ ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
+test "x$ac_build_alias" = x &&
+ { { echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5
+echo "$as_me: error: cannot guess build type; you must specify one" >&2;}
+ { (exit 1); exit 1; }; }
+ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
+ { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&5
+echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&2;}
+ { (exit 1); exit 1; }; }
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_build" >&5
+echo "${ECHO_T}$ac_cv_build" >&6; }
+case $ac_cv_build in
+*-*-*) ;;
+*) { { echo "$as_me:$LINENO: error: invalid value of canonical build" >&5
+echo "$as_me: error: invalid value of canonical build" >&2;}
+ { (exit 1); exit 1; }; };;
+esac
+build=$ac_cv_build
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_build
+shift
+build_cpu=$1
+build_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+build_os=$*
+IFS=$ac_save_IFS
+case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
+
+
+{ echo "$as_me:$LINENO: checking host system type" >&5
+echo $ECHO_N "checking host system type... $ECHO_C" >&6; }
+if test "${ac_cv_host+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test "x$host_alias" = x; then
+ ac_cv_host=$ac_cv_build
+else
+ ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
+ { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&5
+echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_host" >&5
+echo "${ECHO_T}$ac_cv_host" >&6; }
+case $ac_cv_host in
+*-*-*) ;;
+*) { { echo "$as_me:$LINENO: error: invalid value of canonical host" >&5
+echo "$as_me: error: invalid value of canonical host" >&2;}
+ { (exit 1); exit 1; }; };;
+esac
+host=$ac_cv_host
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_host
+shift
+host_cpu=$1
+host_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+host_os=$*
+IFS=$ac_save_IFS
+case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
+
+
+{ echo "$as_me:$LINENO: checking target system type" >&5
+echo $ECHO_N "checking target system type... $ECHO_C" >&6; }
+if test "${ac_cv_target+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test "x$target_alias" = x; then
+ ac_cv_target=$ac_cv_host
+else
+ ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` ||
+ { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $target_alias failed" >&5
+echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $target_alias failed" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_target" >&5
+echo "${ECHO_T}$ac_cv_target" >&6; }
+case $ac_cv_target in
+*-*-*) ;;
+*) { { echo "$as_me:$LINENO: error: invalid value of canonical target" >&5
+echo "$as_me: error: invalid value of canonical target" >&2;}
+ { (exit 1); exit 1; }; };;
+esac
+target=$ac_cv_target
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_target
+shift
+target_cpu=$1
+target_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+target_os=$*
+IFS=$ac_save_IFS
+case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac
+
+
+# The aliases save the names the user supplied, while $host etc.
+# will get canonicalized.
+test -n "$target_alias" &&
+ test "$program_prefix$program_suffix$program_transform_name" = \
+ NONENONEs,x,x, &&
+ program_prefix=${target_alias}-
+
+{ echo "$as_me:$LINENO: checking type of operating system we're going to host on" >&5
+echo $ECHO_N "checking type of operating system we're going to host on... $ECHO_C" >&6; }
+if test "${llvm_cv_os_type+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $host in
+ *-*-aix*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="AIX"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-irix*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="IRIX"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-cygwin*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Cygwin"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-darwin*)
+ llvm_cv_link_all_option="-Wl,-all_load"
+ llvm_cv_no_link_all_option="-Wl,-noall_load"
+ llvm_cv_os_type="Darwin"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-minix*)
+ llvm_cv_link_all_option="-Wl,-all_load"
+ llvm_cv_no_link_all_option="-Wl,-noall_load"
+ llvm_cv_os_type="Minix"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-freebsd* | *-*-kfreebsd-gnu)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="FreeBSD"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-openbsd*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="OpenBSD"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-netbsd*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="NetBSD"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-dragonfly*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="DragonFly"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-hpux*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="HP-UX"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-interix*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Interix"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-linux*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Linux"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-gnu*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="GNU"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-solaris*)
+ llvm_cv_link_all_option="-Wl,-z,allextract"
+ llvm_cv_no_link_all_option="-Wl,-z,defaultextract"
+ llvm_cv_os_type="SunOS"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-auroraux*)
+ llvm_cv_link_all_option="-Wl,-z,allextract"
+ llvm_cv_link_all_option="-Wl,-z,defaultextract"
+ llvm_cv_os_type="AuroraUX"
+ llvm_cv_platform_type="Unix" ;;
+ *-*-win32*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Win32"
+ llvm_cv_platform_type="Win32" ;;
+ *-*-mingw*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="MingW"
+ llvm_cv_platform_type="Win32" ;;
+ *-*-haiku*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Haiku"
+ llvm_cv_platform_type="Unix" ;;
+ *-unknown-eabi*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Freestanding"
+ llvm_cv_platform_type="Unix" ;;
+ *-unknown-elf*)
+ llvm_cv_link_all_option="-Wl,--whole-archive"
+ llvm_cv_no_link_all_option="-Wl,--no-whole-archive"
+ llvm_cv_os_type="Freestanding"
+ llvm_cv_platform_type="Unix" ;;
+ *)
+ llvm_cv_link_all_option=""
+ llvm_cv_no_link_all_option=""
+ llvm_cv_os_type="Unknown"
+ llvm_cv_platform_type="Unknown" ;;
+esac
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_os_type" >&5
+echo "${ECHO_T}$llvm_cv_os_type" >&6; }
+
+{ echo "$as_me:$LINENO: checking type of operating system we're going to target" >&5
+echo $ECHO_N "checking type of operating system we're going to target... $ECHO_C" >&6; }
+if test "${llvm_cv_target_os_type+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $target in
+ *-*-aix*)
+ llvm_cv_target_os_type="AIX" ;;
+ *-*-irix*)
+ llvm_cv_target_os_type="IRIX" ;;
+ *-*-cygwin*)
+ llvm_cv_target_os_type="Cygwin" ;;
+ *-*-darwin*)
+ llvm_cv_target_os_type="Darwin" ;;
+ *-*-minix*)
+ llvm_cv_target_os_type="Minix" ;;
+ *-*-freebsd* | *-*-kfreebsd-gnu)
+ llvm_cv_target_os_type="FreeBSD" ;;
+ *-*-openbsd*)
+ llvm_cv_target_os_type="OpenBSD" ;;
+ *-*-netbsd*)
+ llvm_cv_target_os_type="NetBSD" ;;
+ *-*-dragonfly*)
+ llvm_cv_target_os_type="DragonFly" ;;
+ *-*-hpux*)
+ llvm_cv_target_os_type="HP-UX" ;;
+ *-*-interix*)
+ llvm_cv_target_os_type="Interix" ;;
+ *-*-linux*)
+ llvm_cv_target_os_type="Linux" ;;
+ *-*-gnu*)
+ llvm_cv_target_os_type="GNU" ;;
+ *-*-solaris*)
+ llvm_cv_target_os_type="SunOS" ;;
+ *-*-auroraux*)
+ llvm_cv_target_os_type="AuroraUX" ;;
+ *-*-win32*)
+ llvm_cv_target_os_type="Win32" ;;
+ *-*-mingw*)
+ llvm_cv_target_os_type="MingW" ;;
+ *-*-haiku*)
+ llvm_cv_target_os_type="Haiku" ;;
+ *-*-rtems*)
+ llvm_cv_target_os_type="RTEMS" ;;
+ *-*-nacl*)
+ llvm_cv_target_os_type="NativeClient" ;;
+ *-unknown-eabi*)
+ llvm_cv_target_os_type="Freestanding" ;;
+ *)
+ llvm_cv_target_os_type="Unknown" ;;
+esac
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_target_os_type" >&5
+echo "${ECHO_T}$llvm_cv_target_os_type" >&6; }
+
+if test "$llvm_cv_os_type" = "Unknown" ; then
+ { { echo "$as_me:$LINENO: error: Operating system is unknown, configure can't continue" >&5
+echo "$as_me: error: Operating system is unknown, configure can't continue" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+OS=$llvm_cv_os_type
+
+HOST_OS=$llvm_cv_os_type
+
+TARGET_OS=$llvm_cv_target_os_type
+
+
+LINKALL=$llvm_cv_link_all_option
+
+NOLINKALL=$llvm_cv_no_link_all_option
+
+
+case $llvm_cv_platform_type in
+ Unix)
+
+cat >>confdefs.h <<\_ACEOF
+#define LLVM_ON_UNIX 1
+_ACEOF
+
+ LLVM_ON_UNIX=1
+
+ LLVM_ON_WIN32=0
+
+ ;;
+ Win32)
+
+cat >>confdefs.h <<\_ACEOF
+#define LLVM_ON_WIN32 1
+_ACEOF
+
+ LLVM_ON_UNIX=0
+
+ LLVM_ON_WIN32=1
+
+ ;;
+esac
+
+{ echo "$as_me:$LINENO: checking target architecture" >&5
+echo $ECHO_N "checking target architecture... $ECHO_C" >&6; }
+if test "${llvm_cv_target_arch+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $target in
+ i?86-*) llvm_cv_target_arch="x86" ;;
+ amd64-* | x86_64-*) llvm_cv_target_arch="x86_64" ;;
+ sparc*-*) llvm_cv_target_arch="Sparc" ;;
+ powerpc*-*) llvm_cv_target_arch="PowerPC" ;;
+ arm*-*) llvm_cv_target_arch="ARM" ;;
+ mips-*) llvm_cv_target_arch="Mips" ;;
+ mipsel-*) llvm_cv_target_arch="Mips" ;;
+ xcore-*) llvm_cv_target_arch="XCore" ;;
+ msp430-*) llvm_cv_target_arch="MSP430" ;;
+ hexagon-*) llvm_cv_target_arch="Hexagon" ;;
+ mblaze-*) llvm_cv_target_arch="MBlaze" ;;
+ nvptx-*) llvm_cv_target_arch="NVPTX" ;;
+ *) llvm_cv_target_arch="Unknown" ;;
+esac
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_target_arch" >&5
+echo "${ECHO_T}$llvm_cv_target_arch" >&6; }
+
+if test "$llvm_cv_target_arch" = "Unknown" ; then
+ { echo "$as_me:$LINENO: WARNING: Configuring LLVM for an unknown target archicture" >&5
+echo "$as_me: WARNING: Configuring LLVM for an unknown target archicture" >&2;}
+fi
+
+case "$llvm_cv_target_arch" in
+ x86) LLVM_NATIVE_ARCH="X86" ;;
+ x86_64) LLVM_NATIVE_ARCH="X86" ;;
+ *) LLVM_NATIVE_ARCH="$llvm_cv_target_arch" ;;
+esac
+
+ARCH=$llvm_cv_target_arch
+
+
+case $host in
+ i?86-*) host_arch="x86" ;;
+ amd64-* | x86_64-*) host_arch="x86_64" ;;
+ sparc*-*) host_arch="Sparc" ;;
+ powerpc*-*) host_arch="PowerPC" ;;
+ arm*-*) host_arch="ARM" ;;
+ mips-*) host_arch="Mips" ;;
+ mipsel-*) host_arch="Mips" ;;
+ xcore-*) host_arch="XCore" ;;
+ msp430-*) host_arch="MSP430" ;;
+ hexagon-*) host_arch="Hexagon" ;;
+ mblaze-*) host_arch="MBlaze" ;;
+ *) host_arch="Unknown" ;;
+esac
+
+if test "$host_arch" = "Unknown" ; then
+ { echo "$as_me:$LINENO: WARNING: Configuring LLVM for an unknown host archicture" >&5
+echo "$as_me: WARNING: Configuring LLVM for an unknown host archicture" >&2;}
+fi
+
+HOST_ARCH=$host_arch
+
+
+
+
+{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5
+echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; }
+if test "${ac_cv_path_GREP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # Extract the first word of "grep ggrep" to use in msg output
+if test -z "$GREP"; then
+set dummy grep ggrep; ac_prog_name=$2
+if test "${ac_cv_path_GREP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_path_GREP_found=false
+# Loop through the user's path and test for each of PROGNAME-LIST
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_prog in grep ggrep; do
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
+ { test -f "$ac_path_GREP" && $as_executable_p "$ac_path_GREP"; } || continue
+ # Check for GNU ac_path_GREP and select it if it is found.
+ # Check for GNU $ac_path_GREP
+case `"$ac_path_GREP" --version 2>&1` in
+*GNU*)
+ ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
+*)
+ ac_count=0
+ echo $ECHO_N "0123456789$ECHO_C" >"conftest.in"
+ while :
+ do
+ cat "conftest.in" "conftest.in" >"conftest.tmp"
+ mv "conftest.tmp" "conftest.in"
+ cp "conftest.in" "conftest.nl"
+ echo 'GREP' >> "conftest.nl"
+ "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+ diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+ ac_count=`expr $ac_count + 1`
+ if test $ac_count -gt ${ac_path_GREP_max-0}; then
+ # Best one so far, save it but keep looking for a better one
+ ac_cv_path_GREP="$ac_path_GREP"
+ ac_path_GREP_max=$ac_count
+ fi
+ # 10*(2^10) chars as input seems more than enough
+ test $ac_count -gt 10 && break
+ done
+ rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+
+ $ac_path_GREP_found && break 3
+ done
+done
+
+done
+IFS=$as_save_IFS
+
+
+fi
+
+GREP="$ac_cv_path_GREP"
+if test -z "$GREP"; then
+ { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5
+echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+else
+ ac_cv_path_GREP=$GREP
+fi
+
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5
+echo "${ECHO_T}$ac_cv_path_GREP" >&6; }
+ GREP="$ac_cv_path_GREP"
+
+
+{ echo "$as_me:$LINENO: checking for egrep" >&5
+echo $ECHO_N "checking for egrep... $ECHO_C" >&6; }
+if test "${ac_cv_path_EGREP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
+ then ac_cv_path_EGREP="$GREP -E"
+ else
+ # Extract the first word of "egrep" to use in msg output
+if test -z "$EGREP"; then
+set dummy egrep; ac_prog_name=$2
+if test "${ac_cv_path_EGREP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_path_EGREP_found=false
+# Loop through the user's path and test for each of PROGNAME-LIST
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_prog in egrep; do
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
+ { test -f "$ac_path_EGREP" && $as_executable_p "$ac_path_EGREP"; } || continue
+ # Check for GNU ac_path_EGREP and select it if it is found.
+ # Check for GNU $ac_path_EGREP
+case `"$ac_path_EGREP" --version 2>&1` in
+*GNU*)
+ ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
+*)
+ ac_count=0
+ echo $ECHO_N "0123456789$ECHO_C" >"conftest.in"
+ while :
+ do
+ cat "conftest.in" "conftest.in" >"conftest.tmp"
+ mv "conftest.tmp" "conftest.in"
+ cp "conftest.in" "conftest.nl"
+ echo 'EGREP' >> "conftest.nl"
+ "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+ diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+ ac_count=`expr $ac_count + 1`
+ if test $ac_count -gt ${ac_path_EGREP_max-0}; then
+ # Best one so far, save it but keep looking for a better one
+ ac_cv_path_EGREP="$ac_path_EGREP"
+ ac_path_EGREP_max=$ac_count
+ fi
+ # 10*(2^10) chars as input seems more than enough
+ test $ac_count -gt 10 && break
+ done
+ rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+
+ $ac_path_EGREP_found && break 3
+ done
+done
+
+done
+IFS=$as_save_IFS
+
+
+fi
+
+EGREP="$ac_cv_path_EGREP"
+if test -z "$EGREP"; then
+ { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5
+echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+else
+ ac_cv_path_EGREP=$EGREP
+fi
+
+
+ fi
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5
+echo "${ECHO_T}$ac_cv_path_EGREP" >&6; }
+ EGREP="$ac_cv_path_EGREP"
+
+
+{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5
+echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; }
+if test "${ac_cv_header_stdc+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_header_stdc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_header_stdc=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+ # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+ $EGREP "memchr" >/dev/null 2>&1; then
+ :
+else
+ ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+ # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+ $EGREP "free" >/dev/null 2>&1; then
+ :
+else
+ ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+ # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+ if test "$cross_compiling" = yes; then
+ :
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+ (('a' <= (c) && (c) <= 'i') \
+ || ('j' <= (c) && (c) <= 'r') \
+ || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+ int i;
+ for (i = 0; i < 256; i++)
+ if (XOR (islower (i), ISLOWER (i))
+ || toupper (i) != TOUPPER (i))
+ return 2;
+ return 0;
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+
+
+fi
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
+echo "${ECHO_T}$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define STDC_HEADERS 1
+_ACEOF
+
+fi
+
+# On IRIX 5.3, sys/types and inttypes.h are conflicting.
+
+
+
+
+
+
+
+
+
+for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
+ inttypes.h stdint.h unistd.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_Header=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_Header=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+{ echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5
+echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6; }
+if test "${ac_cv_c_bigendian+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # See if sys/param.h defines the BYTE_ORDER macro.
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/types.h>
+#include <sys/param.h>
+
+int
+main ()
+{
+#if !BYTE_ORDER || !BIG_ENDIAN || !LITTLE_ENDIAN
+ bogus endian macros
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ # It does; now see whether it defined to BIG_ENDIAN or not.
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/types.h>
+#include <sys/param.h>
+
+int
+main ()
+{
+#if BYTE_ORDER != BIG_ENDIAN
+ not big endian
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_c_bigendian=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_c_bigendian=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # It does not; compile a test program.
+if test "$cross_compiling" = yes; then
+ # try to guess the endianness by grepping values into an object file
+ ac_cv_c_bigendian=unknown
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
+short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
+void _ascii () { char *s = (char *) ascii_mm; s = (char *) ascii_ii; }
+short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
+short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
+void _ebcdic () { char *s = (char *) ebcdic_mm; s = (char *) ebcdic_ii; }
+int
+main ()
+{
+ _ascii (); _ebcdic ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ if grep BIGenDianSyS conftest.$ac_objext >/dev/null ; then
+ ac_cv_c_bigendian=yes
+fi
+if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then
+ if test "$ac_cv_c_bigendian" = unknown; then
+ ac_cv_c_bigendian=no
+ else
+ # finding both strings is unlikely to happen, but who knows?
+ ac_cv_c_bigendian=unknown
+ fi
+fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+
+ /* Are we little or big endian? From Harbison&Steele. */
+ union
+ {
+ long int l;
+ char c[sizeof (long int)];
+ } u;
+ u.l = 1;
+ return u.c[sizeof (long int) - 1] == 1;
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_c_bigendian=no
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+ac_cv_c_bigendian=yes
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5
+echo "${ECHO_T}$ac_cv_c_bigendian" >&6; }
+case $ac_cv_c_bigendian in
+ yes)
+ ENDIAN=big
+ ;;
+ no)
+ ENDIAN=little
+ ;;
+ *)
+ { { echo "$as_me:$LINENO: error: unknown endianness
+presetting ac_cv_c_bigendian=no (or yes) will help" >&5
+echo "$as_me: error: unknown endianness
+presetting ac_cv_c_bigendian=no (or yes) will help" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+
+if test "$cross_compiling" = yes; then
+ LLVM_CROSS_COMPILING=1
+
+
+{ echo "$as_me:$LINENO: checking for executable suffix on build platform" >&5
+echo $ECHO_N "checking for executable suffix on build platform... $ECHO_C" >&6; }
+if test "${ac_cv_build_exeext+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test "$CYGWIN" = yes || test "$MINGW32" = yes; then
+ ac_cv_build_exeext=.exe
+else
+ ac_build_prefix=${build_alias}-
+
+ # Extract the first word of "${ac_build_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_build_prefix}gcc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_BUILD_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$BUILD_CC"; then
+ ac_cv_prog_BUILD_CC="$BUILD_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_BUILD_CC="${ac_build_prefix}gcc"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+BUILD_CC=$ac_cv_prog_BUILD_CC
+if test -n "$BUILD_CC"; then
+ { echo "$as_me:$LINENO: result: $BUILD_CC" >&5
+echo "${ECHO_T}$BUILD_CC" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ if test -z "$BUILD_CC"; then
+ # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_BUILD_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$BUILD_CC"; then
+ ac_cv_prog_BUILD_CC="$BUILD_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_BUILD_CC="gcc"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+BUILD_CC=$ac_cv_prog_BUILD_CC
+if test -n "$BUILD_CC"; then
+ { echo "$as_me:$LINENO: result: $BUILD_CC" >&5
+echo "${ECHO_T}$BUILD_CC" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ if test -z "$BUILD_CC"; then
+ # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_BUILD_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$BUILD_CC"; then
+ ac_cv_prog_BUILD_CC="$BUILD_CC" # Let the user override the test.
+else
+ ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+ ac_prog_rejected=yes
+ continue
+ fi
+ ac_cv_prog_BUILD_CC="cc"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+if test $ac_prog_rejected = yes; then
+ # We found a bogon in the path, so make sure we never use it.
+ set dummy $ac_cv_prog_BUILD_CC
+ shift
+ if test $# != 0; then
+ # We chose a different compiler from the bogus one.
+ # However, it has the same basename, so the bogon will be chosen
+ # first if we set BUILD_CC to just the basename; use the full file name.
+ shift
+ ac_cv_prog_BUILD_CC="$as_dir/$ac_word${1+' '}$@"
+ fi
+fi
+fi
+fi
+BUILD_CC=$ac_cv_prog_BUILD_CC
+if test -n "$BUILD_CC"; then
+ { echo "$as_me:$LINENO: result: $BUILD_CC" >&5
+echo "${ECHO_T}$BUILD_CC" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ fi
+ fi
+ test -z "$BUILD_CC" && { { echo "$as_me:$LINENO: error: no acceptable cc found in \$PATH" >&5
+echo "$as_me: error: no acceptable cc found in \$PATH" >&2;}
+ { (exit 1); exit 1; }; }
+ ac_build_link='${BUILD_CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
+ rm -f conftest*
+ echo 'int main () { return 0; }' > conftest.$ac_ext
+ ac_cv_build_exeext=
+ if { (eval echo "$as_me:$LINENO: \"$ac_build_link\"") >&5
+ (eval $ac_build_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ for file in conftest.*; do
+ case $file in
+ *.c | *.o | *.obj | *.dSYM) ;;
+ *) ac_cv_build_exeext=`echo $file | sed -e s/conftest//` ;;
+ esac
+ done
+ else
+ { { echo "$as_me:$LINENO: error: installation or configuration problem: compiler cannot create executables." >&5
+echo "$as_me: error: installation or configuration problem: compiler cannot create executables." >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+ rm -f conftest*
+ test x"${ac_cv_build_exeext}" = x && ac_cv_build_exeext=blank
+fi
+fi
+
+BUILD_EXEEXT=""
+test x"${ac_cv_build_exeext}" != xblank && BUILD_EXEEXT=${ac_cv_build_exeext}
+{ echo "$as_me:$LINENO: result: ${ac_cv_build_exeext}" >&5
+echo "${ECHO_T}${ac_cv_build_exeext}" >&6; }
+ac_build_exeext=$BUILD_EXEEXT
+
+ ac_build_prefix=${build_alias}-
+ # Extract the first word of "${ac_build_prefix}g++", so it can be a program name with args.
+set dummy ${ac_build_prefix}g++; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_BUILD_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$BUILD_CXX"; then
+ ac_cv_prog_BUILD_CXX="$BUILD_CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_BUILD_CXX="${ac_build_prefix}g++"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+BUILD_CXX=$ac_cv_prog_BUILD_CXX
+if test -n "$BUILD_CXX"; then
+ { echo "$as_me:$LINENO: result: $BUILD_CXX" >&5
+echo "${ECHO_T}$BUILD_CXX" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ if test -z "$BUILD_CXX"; then
+ # Extract the first word of "g++", so it can be a program name with args.
+set dummy g++; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_BUILD_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$BUILD_CXX"; then
+ ac_cv_prog_BUILD_CXX="$BUILD_CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_BUILD_CXX="g++"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+BUILD_CXX=$ac_cv_prog_BUILD_CXX
+if test -n "$BUILD_CXX"; then
+ { echo "$as_me:$LINENO: result: $BUILD_CXX" >&5
+echo "${ECHO_T}$BUILD_CXX" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ if test -z "$BUILD_CXX"; then
+ # Extract the first word of "c++", so it can be a program name with args.
+set dummy c++; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_BUILD_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$BUILD_CXX"; then
+ ac_cv_prog_BUILD_CXX="$BUILD_CXX" # Let the user override the test.
+else
+ ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/c++"; then
+ ac_prog_rejected=yes
+ continue
+ fi
+ ac_cv_prog_BUILD_CXX="c++"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+if test $ac_prog_rejected = yes; then
+ # We found a bogon in the path, so make sure we never use it.
+ set dummy $ac_cv_prog_BUILD_CXX
+ shift
+ if test $# != 0; then
+ # We chose a different compiler from the bogus one.
+ # However, it has the same basename, so the bogon will be chosen
+ # first if we set BUILD_CXX to just the basename; use the full file name.
+ shift
+ ac_cv_prog_BUILD_CXX="$as_dir/$ac_word${1+' '}$@"
+ fi
+fi
+fi
+fi
+BUILD_CXX=$ac_cv_prog_BUILD_CXX
+if test -n "$BUILD_CXX"; then
+ { echo "$as_me:$LINENO: result: $BUILD_CXX" >&5
+echo "${ECHO_T}$BUILD_CXX" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ fi
+ fi
+else
+ LLVM_CROSS_COMPILING=0
+
+fi
+
+if test -d ".svn" -o -d "${srcdir}/.svn" -o -d ".git" -o -d "${srcdir}/.git"; then
+ cvsbuild="yes"
+ optimize="no"
+ CVSBUILD=CVSBUILD=1
+
+else
+ cvsbuild="no"
+ optimize="yes"
+fi
+
+
+# Check whether --enable-libcpp was given.
+if test "${enable_libcpp+set}" = set; then
+ enableval=$enable_libcpp;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_LIBCPP=1
+ ;;
+ no) ENABLE_LIBCPP=0
+ ;;
+ default) ENABLE_LIBCPP=0
+;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-libcpp. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-libcpp. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+# Check whether --enable-cxx11 was given.
+if test "${enable_cxx11+set}" = set; then
+ enableval=$enable_cxx11;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_CXX11=1
+ ;;
+ no) ENABLE_CXX11=0
+ ;;
+ default) ENABLE_CXX11=0
+;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-cxx11. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-cxx11. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+# Check whether --enable-optimized was given.
+if test "${enable_optimized+set}" = set; then
+ enableval=$enable_optimized;
+else
+ enableval=$optimize
+fi
+
+if test ${enableval} = "no" ; then
+ ENABLE_OPTIMIZED=
+
+else
+ ENABLE_OPTIMIZED=ENABLE_OPTIMIZED=1
+
+fi
+
+# Check whether --enable-profiling was given.
+if test "${enable_profiling+set}" = set; then
+ enableval=$enable_profiling;
+else
+ enableval="no"
+fi
+
+if test ${enableval} = "no" ; then
+ ENABLE_PROFILING=
+
+else
+ ENABLE_PROFILING=ENABLE_PROFILING=1
+
+fi
+
+# Check whether --enable-assertions was given.
+if test "${enable_assertions+set}" = set; then
+ enableval=$enable_assertions;
+else
+ enableval="yes"
+fi
+
+if test ${enableval} = "yes" ; then
+ DISABLE_ASSERTIONS=
+
+else
+ DISABLE_ASSERTIONS=DISABLE_ASSERTIONS=1
+
+fi
+
+# Check whether --enable-werror was given.
+if test "${enable_werror+set}" = set; then
+ enableval=$enable_werror;
+else
+ enableval="no"
+fi
+
+case "$enableval" in
+ yes) ENABLE_WERROR=1
+ ;;
+ no) ENABLE_WERROR=0
+ ;;
+ default) ENABLE_WERROR=0
+;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-werror. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-werror. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+# Check whether --enable-expensive-checks was given.
+if test "${enable_expensive_checks+set}" = set; then
+ enableval=$enable_expensive_checks;
+else
+ enableval="no"
+fi
+
+if test ${enableval} = "yes" ; then
+ ENABLE_EXPENSIVE_CHECKS=ENABLE_EXPENSIVE_CHECKS=1
+
+ EXPENSIVE_CHECKS=yes
+
+else
+ ENABLE_EXPENSIVE_CHECKS=
+
+ EXPENSIVE_CHECKS=no
+
+fi
+
+# Check whether --enable-debug-runtime was given.
+if test "${enable_debug_runtime+set}" = set; then
+ enableval=$enable_debug_runtime;
+else
+ enableval=no
+fi
+
+if test ${enableval} = "no" ; then
+ DEBUG_RUNTIME=
+
+else
+ DEBUG_RUNTIME=DEBUG_RUNTIME=1
+
+fi
+
+# Check whether --enable-debug-symbols was given.
+if test "${enable_debug_symbols+set}" = set; then
+ enableval=$enable_debug_symbols;
+else
+ enableval=no
+fi
+
+if test ${enableval} = "no" ; then
+ DEBUG_SYMBOLS=
+
+else
+ DEBUG_SYMBOLS=DEBUG_SYMBOLS=1
+
+fi
+
+# Check whether --enable-keep-symbols was given.
+if test "${enable_keep_symbols+set}" = set; then
+ enableval=$enable_keep_symbols;
+else
+ enableval=no
+fi
+
+if test ${enableval} = "no" ; then
+ KEEP_SYMBOLS=
+
+else
+ KEEP_SYMBOLS=KEEP_SYMBOLS=1
+
+fi
+
+# Check whether --enable-jit was given.
+if test "${enable_jit+set}" = set; then
+ enableval=$enable_jit;
+else
+ enableval=default
+fi
+
+if test ${enableval} = "no"
+then
+ JIT=
+
+else
+ case "$llvm_cv_target_arch" in
+ x86) TARGET_HAS_JIT=1
+ ;;
+ Sparc) TARGET_HAS_JIT=0
+ ;;
+ PowerPC) TARGET_HAS_JIT=1
+ ;;
+ x86_64) TARGET_HAS_JIT=1
+ ;;
+ ARM) TARGET_HAS_JIT=1
+ ;;
+ Mips) TARGET_HAS_JIT=1
+ ;;
+ XCore) TARGET_HAS_JIT=0
+ ;;
+ MSP430) TARGET_HAS_JIT=0
+ ;;
+ Hexagon) TARGET_HAS_JIT=0
+ ;;
+ MBlaze) TARGET_HAS_JIT=0
+ ;;
+ NVPTX) TARGET_HAS_JIT=0
+ ;;
+ *) TARGET_HAS_JIT=0
+ ;;
+ esac
+fi
+
+# Check whether --enable-docs was given.
+if test "${enable_docs+set}" = set; then
+ enableval=$enable_docs;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_DOCS=1
+ ;;
+ no) ENABLE_DOCS=0
+ ;;
+ default) ENABLE_DOCS=1
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-docs. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-docs. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+# Check whether --enable-doxygen was given.
+if test "${enable_doxygen+set}" = set; then
+ enableval=$enable_doxygen;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_DOXYGEN=1
+ ;;
+ no) ENABLE_DOXYGEN=0
+ ;;
+ default) ENABLE_DOXYGEN=0
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-doxygen. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-doxygen. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+# Check whether --enable-threads was given.
+if test "${enable_threads+set}" = set; then
+ enableval=$enable_threads;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) LLVM_ENABLE_THREADS=1
+ ;;
+ no) LLVM_ENABLE_THREADS=0
+ ;;
+ default) LLVM_ENABLE_THREADS=1
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-threads. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-threads. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_ENABLE_THREADS $LLVM_ENABLE_THREADS
+_ACEOF
+
+
+# Check whether --enable-pthreads was given.
+if test "${enable_pthreads+set}" = set; then
+ enableval=$enable_pthreads;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_PTHREADS=1
+ ;;
+ no) ENABLE_PTHREADS=0
+ ;;
+ default) ENABLE_PTHREADS=1
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-pthreads. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-pthreads. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+# Check whether --enable-pic was given.
+if test "${enable_pic+set}" = set; then
+ enableval=$enable_pic;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_PIC=1
+ ;;
+ no) ENABLE_PIC=0
+ ;;
+ default) ENABLE_PIC=1
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-pic. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-pic. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+cat >>confdefs.h <<_ACEOF
+#define ENABLE_PIC $ENABLE_PIC
+_ACEOF
+
+
+# Check whether --enable-shared was given.
+if test "${enable_shared+set}" = set; then
+ enableval=$enable_shared;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_SHARED=1
+ ;;
+ no) ENABLE_SHARED=0
+ ;;
+ default) ENABLE_SHARED=0
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-shared. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-shared. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+# Check whether --enable-embed-stdcxx was given.
+if test "${enable_embed_stdcxx+set}" = set; then
+ enableval=$enable_embed_stdcxx;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_EMBED_STDCXX=1
+ ;;
+ no) ENABLE_EMBED_STDCXX=0
+ ;;
+ default) ENABLE_EMBED_STDCXX=0
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-embed-stdcxx. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-embed-stdcxx. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+# Check whether --enable-timestamps was given.
+if test "${enable_timestamps+set}" = set; then
+ enableval=$enable_timestamps;
+else
+ enableval=default
+fi
+
+case "$enableval" in
+ yes) ENABLE_TIMESTAMPS=1
+ ;;
+ no) ENABLE_TIMESTAMPS=0
+ ;;
+ default) ENABLE_TIMESTAMPS=1
+ ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-timestamps. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-timestamps. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+cat >>confdefs.h <<_ACEOF
+#define ENABLE_TIMESTAMPS $ENABLE_TIMESTAMPS
+_ACEOF
+
+
+TARGETS_TO_BUILD=""
+# Check whether --enable-targets was given.
+if test "${enable_targets+set}" = set; then
+ enableval=$enable_targets;
+else
+ enableval=all
+fi
+
+if test "$enableval" = host-only ; then
+ enableval=host
+fi
+case "$enableval" in
+ all) TARGETS_TO_BUILD="X86 Sparc PowerPC ARM Mips CellSPU XCore MSP430 CppBackend MBlaze NVPTX Hexagon" ;;
+ *)for a_target in `echo $enableval|sed -e 's/,/ /g' ` ; do
+ case "$a_target" in
+ x86) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
+ x86_64) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
+ sparc) TARGETS_TO_BUILD="Sparc $TARGETS_TO_BUILD" ;;
+ powerpc) TARGETS_TO_BUILD="PowerPC $TARGETS_TO_BUILD" ;;
+ arm) TARGETS_TO_BUILD="ARM $TARGETS_TO_BUILD" ;;
+ mips) TARGETS_TO_BUILD="Mips $TARGETS_TO_BUILD" ;;
+ mipsel) TARGETS_TO_BUILD="Mips $TARGETS_TO_BUILD" ;;
+ spu) TARGETS_TO_BUILD="CellSPU $TARGETS_TO_BUILD" ;;
+ xcore) TARGETS_TO_BUILD="XCore $TARGETS_TO_BUILD" ;;
+ msp430) TARGETS_TO_BUILD="MSP430 $TARGETS_TO_BUILD" ;;
+ cpp) TARGETS_TO_BUILD="CppBackend $TARGETS_TO_BUILD" ;;
+ hexagon) TARGETS_TO_BUILD="Hexagon $TARGETS_TO_BUILD" ;;
+ mblaze) TARGETS_TO_BUILD="MBlaze $TARGETS_TO_BUILD" ;;
+ nvptx) TARGETS_TO_BUILD="NVPTX $TARGETS_TO_BUILD" ;;
+ host) case "$llvm_cv_target_arch" in
+ x86) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
+ x86_64) TARGETS_TO_BUILD="X86 $TARGETS_TO_BUILD" ;;
+ Sparc) TARGETS_TO_BUILD="Sparc $TARGETS_TO_BUILD" ;;
+ PowerPC) TARGETS_TO_BUILD="PowerPC $TARGETS_TO_BUILD" ;;
+ ARM) TARGETS_TO_BUILD="ARM $TARGETS_TO_BUILD" ;;
+ Mips) TARGETS_TO_BUILD="Mips $TARGETS_TO_BUILD" ;;
+ MBlaze) TARGETS_TO_BUILD="MBlaze $TARGETS_TO_BUILD" ;;
+ CellSPU|SPU) TARGETS_TO_BUILD="CellSPU $TARGETS_TO_BUILD" ;;
+ XCore) TARGETS_TO_BUILD="XCore $TARGETS_TO_BUILD" ;;
+ MSP430) TARGETS_TO_BUILD="MSP430 $TARGETS_TO_BUILD" ;;
+ Hexagon) TARGETS_TO_BUILD="Hexagon $TARGETS_TO_BUILD" ;;
+ NVPTX) TARGETS_TO_BUILD="NVPTX $TARGETS_TO_BUILD" ;;
+ *) { { echo "$as_me:$LINENO: error: Can not set target to build" >&5
+echo "$as_me: error: Can not set target to build" >&2;}
+ { (exit 1); exit 1; }; } ;;
+ esac ;;
+ *) { { echo "$as_me:$LINENO: error: Unrecognized target $a_target" >&5
+echo "$as_me: error: Unrecognized target $a_target" >&2;}
+ { (exit 1); exit 1; }; } ;;
+ esac
+ done
+ ;;
+esac
+
+# Check whether --enable-experimental-targets was given.
+if test "${enable_experimental_targets+set}" = set; then
+ enableval=$enable_experimental_targets;
+else
+ enableval=disable
+fi
+
+
+if test ${enableval} != "disable"
+then
+ TARGETS_TO_BUILD="$enableval $TARGETS_TO_BUILD"
+fi
+
+TARGETS_TO_BUILD=$TARGETS_TO_BUILD
+
+
+for a_target in $TARGETS_TO_BUILD; do
+ if test "$a_target" = "$LLVM_NATIVE_ARCH"; then
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_NATIVE_ARCH $LLVM_NATIVE_ARCH
+_ACEOF
+
+ LLVM_NATIVE_TARGET="LLVMInitialize${LLVM_NATIVE_ARCH}Target"
+ LLVM_NATIVE_TARGETINFO="LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo"
+ LLVM_NATIVE_TARGETMC="LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC"
+ LLVM_NATIVE_ASMPRINTER="LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter"
+ if test -f ${srcdir}/lib/Target/${LLVM_NATIVE_ARCH}/AsmParser/Makefile ; then
+ LLVM_NATIVE_ASMPARSER="LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser"
+ fi
+ if test -f ${srcdir}/lib/Target/${LLVM_NATIVE_ARCH}/Disassembler/Makefile ; then
+ LLVM_NATIVE_DISASSEMBLER="LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler"
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_NATIVE_TARGET $LLVM_NATIVE_TARGET
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_NATIVE_TARGETINFO $LLVM_NATIVE_TARGETINFO
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_NATIVE_TARGETMC $LLVM_NATIVE_TARGETMC
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_NATIVE_ASMPRINTER $LLVM_NATIVE_ASMPRINTER
+_ACEOF
+
+ if test -f ${srcdir}/lib/Target/${LLVM_NATIVE_ARCH}/AsmParser/Makefile ; then
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_NATIVE_ASMPARSER $LLVM_NATIVE_ASMPARSER
+_ACEOF
+
+ fi
+ if test -f ${srcdir}/lib/Target/${LLVM_NATIVE_ARCH}/Disassembler/Makefile ; then
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_NATIVE_DISASSEMBLER $LLVM_NATIVE_DISASSEMBLER
+_ACEOF
+
+ fi
+ fi
+done
+
+LLVM_ENUM_TARGETS=""
+LLVM_ENUM_ASM_PRINTERS=""
+LLVM_ENUM_ASM_PARSERS=""
+LLVM_ENUM_DISASSEMBLERS=""
+for target_to_build in $TARGETS_TO_BUILD; do
+ LLVM_ENUM_TARGETS="LLVM_TARGET($target_to_build) $LLVM_ENUM_TARGETS"
+ if test -f ${srcdir}/lib/Target/${target_to_build}/*AsmPrinter.cpp ; then
+ LLVM_ENUM_ASM_PRINTERS="LLVM_ASM_PRINTER($target_to_build) $LLVM_ENUM_ASM_PRINTERS";
+ fi
+ if test -f ${srcdir}/lib/Target/${target_to_build}/AsmParser/Makefile ; then
+ LLVM_ENUM_ASM_PARSERS="LLVM_ASM_PARSER($target_to_build) $LLVM_ENUM_ASM_PARSERS";
+ fi
+ if test -f ${srcdir}/lib/Target/${target_to_build}/Disassembler/Makefile ; then
+ LLVM_ENUM_DISASSEMBLERS="LLVM_DISASSEMBLER($target_to_build) $LLVM_ENUM_DISASSEMBLERS";
+ fi
+done
+
+
+
+
+
+
+# Check whether --with-optimize-option was given.
+if test "${with_optimize_option+set}" = set; then
+ withval=$with_optimize_option;
+else
+ withval=default
+fi
+
+{ echo "$as_me:$LINENO: checking optimization flags" >&5
+echo $ECHO_N "checking optimization flags... $ECHO_C" >&6; }
+case "$withval" in
+ default)
+ case "$llvm_cv_os_type" in
+ FreeBSD) optimize_option=-O2 ;;
+ MingW) optimize_option=-O2 ;;
+ *) optimize_option=-O3 ;;
+ esac ;;
+ *) optimize_option="$withval" ;;
+esac
+OPTIMIZE_OPTION=$optimize_option
+
+{ echo "$as_me:$LINENO: result: $optimize_option" >&5
+echo "${ECHO_T}$optimize_option" >&6; }
+
+
+# Check whether --with-extra-options was given.
+if test "${with_extra_options+set}" = set; then
+ withval=$with_extra_options;
+else
+ withval=default
+fi
+
+case "$withval" in
+ default) EXTRA_OPTIONS= ;;
+ *) EXTRA_OPTIONS=$withval ;;
+esac
+EXTRA_OPTIONS=$EXTRA_OPTIONS
+
+
+
+# Check whether --with-extra-ld-options was given.
+if test "${with_extra_ld_options+set}" = set; then
+ withval=$with_extra_ld_options;
+else
+ withval=default
+fi
+
+case "$withval" in
+ default) EXTRA_LD_OPTIONS= ;;
+ *) EXTRA_LD_OPTIONS=$withval ;;
+esac
+EXTRA_LD_OPTIONS=$EXTRA_LD_OPTIONS
+
+
+# Check whether --enable-bindings was given.
+if test "${enable_bindings+set}" = set; then
+ enableval=$enable_bindings;
+else
+ enableval=default
+fi
+
+BINDINGS_TO_BUILD=""
+case "$enableval" in
+ yes | default | auto) BINDINGS_TO_BUILD="auto" ;;
+ all ) BINDINGS_TO_BUILD="ocaml" ;;
+ none | no) BINDINGS_TO_BUILD="" ;;
+ *)for a_binding in `echo $enableval|sed -e 's/,/ /g' ` ; do
+ case "$a_binding" in
+ ocaml) BINDINGS_TO_BUILD="ocaml $BINDINGS_TO_BUILD" ;;
+ *) { { echo "$as_me:$LINENO: error: Unrecognized binding $a_binding" >&5
+echo "$as_me: error: Unrecognized binding $a_binding" >&2;}
+ { (exit 1); exit 1; }; } ;;
+ esac
+ done
+ ;;
+esac
+
+
+# Check whether --with-ocaml-libdir was given.
+if test "${with_ocaml_libdir+set}" = set; then
+ withval=$with_ocaml_libdir;
+else
+ withval=auto
+fi
+
+case "$withval" in
+ auto) with_ocaml_libdir="$withval" ;;
+ /* | [A-Za-z]:[\\/]*) with_ocaml_libdir="$withval" ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid path for --with-ocaml-libdir. Provide full path" >&5
+echo "$as_me: error: Invalid path for --with-ocaml-libdir. Provide full path" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+
+
+# Check whether --with-clang-srcdir was given.
+if test "${with_clang_srcdir+set}" = set; then
+ withval=$with_clang_srcdir;
+else
+ withval="-"
+fi
+
+case "$withval" in
+ -) clang_src_root="" ;;
+ /* | [A-Za-z]:[\\/]*) clang_src_root="$withval" ;;
+ *) clang_src_root="$ac_pwd/$withval" ;;
+esac
+CLANG_SRC_ROOT=$clang_src_root
+
+
+
+# Check whether --with-clang-resource-dir was given.
+if test "${with_clang_resource_dir+set}" = set; then
+ withval=$with_clang_resource_dir;
+else
+ withval=""
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define CLANG_RESOURCE_DIR "$withval"
+_ACEOF
+
+
+
+# Check whether --with-c-include-dirs was given.
+if test "${with_c_include_dirs+set}" = set; then
+ withval=$with_c_include_dirs;
+else
+ withval=""
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define C_INCLUDE_DIRS "$withval"
+_ACEOF
+
+
+# Clang normally uses the system c++ headers and libraries. With this option,
+# clang will use the ones provided by a gcc installation instead. This option should
+# be passed the same value that was used with --prefix when configuring gcc.
+
+# Check whether --with-gcc-toolchain was given.
+if test "${with_gcc_toolchain+set}" = set; then
+ withval=$with_gcc_toolchain;
+else
+ withval=""
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define GCC_INSTALL_PREFIX "$withval"
+_ACEOF
+
+
+
+# Check whether --with-default-sysroot was given.
+if test "${with_default_sysroot+set}" = set; then
+ withval=$with_default_sysroot;
+else
+ withval=""
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define DEFAULT_SYSROOT "$withval"
+_ACEOF
+
+
+
+# Check whether --with-binutils-include was given.
+if test "${with_binutils_include+set}" = set; then
+ withval=$with_binutils_include;
+else
+ withval=default
+fi
+
+case "$withval" in
+ default) WITH_BINUTILS_INCDIR=default ;;
+ /* | [A-Za-z]:[\\/]*) WITH_BINUTILS_INCDIR=$withval ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid path for --with-binutils-include. Provide full path" >&5
+echo "$as_me: error: Invalid path for --with-binutils-include. Provide full path" >&2;}
+ { (exit 1); exit 1; }; } ;;
+esac
+if test "x$WITH_BINUTILS_INCDIR" != xdefault ; then
+ BINUTILS_INCDIR=$WITH_BINUTILS_INCDIR
+
+ if test ! -f "$WITH_BINUTILS_INCDIR/plugin-api.h"; then
+ echo "$WITH_BINUTILS_INCDIR/plugin-api.h"
+ { { echo "$as_me:$LINENO: error: Invalid path to directory containing plugin-api.h." >&5
+echo "$as_me: error: Invalid path to directory containing plugin-api.h." >&2;}
+ { (exit 1); exit 1; }; };
+ fi
+fi
+
+
+# Check whether --with-bug-report-url was given.
+if test "${with_bug_report_url+set}" = set; then
+ withval=$with_bug_report_url;
+else
+ withval="http://llvm.org/bugs/"
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define BUG_REPORT_URL "$withval"
+_ACEOF
+
+
+# Check whether --enable-libffi was given.
+if test "${enable_libffi+set}" = set; then
+ enableval=$enable_libffi; case "$enableval" in
+ yes) llvm_cv_enable_libffi="yes" ;;
+ no) llvm_cv_enable_libffi="no" ;;
+ *) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-libffi. Use \"yes\" or \"no\"" >&5
+echo "$as_me: error: Invalid setting for --enable-libffi. Use \"yes\" or \"no\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+ esac
+else
+ llvm_cv_enable_libffi=no
+fi
+
+
+
+# Check whether --with-internal-prefix was given.
+if test "${with_internal_prefix+set}" = set; then
+ withval=$with_internal_prefix;
+else
+ withval=""
+fi
+
+INTERNAL_PREFIX=$withval
+
+
+
+{ echo "$as_me:$LINENO: checking for BSD-compatible nm" >&5
+echo $ECHO_N "checking for BSD-compatible nm... $ECHO_C" >&6; }
+if test "${lt_cv_path_NM+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$NM"; then
+ # Let the user override the test.
+ lt_cv_path_NM="$NM"
+else
+ lt_nm_to_check="${ac_tool_prefix}nm"
+ if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+ lt_nm_to_check="$lt_nm_to_check nm"
+ fi
+ for lt_tmp_nm in $lt_nm_to_check; do
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ tmp_nm="$ac_dir/$lt_tmp_nm"
+ if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+ # Check to see if the nm accepts a BSD-compat flag.
+ # Adding the `sed 1q' prevents false positives on HP-UX, which says:
+ # nm: unknown option "B" ignored
+ # Tru64's nm complains that /dev/null is an invalid object file
+ case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+ */dev/null* | *'Invalid file or object type'*)
+ lt_cv_path_NM="$tmp_nm -B"
+ break
+ ;;
+ *)
+ case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+ */dev/null*)
+ lt_cv_path_NM="$tmp_nm -p"
+ break
+ ;;
+ *)
+ lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+ continue # so that we can try to find one that supports BSD flags
+ ;;
+ esac
+ ;;
+ esac
+ fi
+ done
+ IFS="$lt_save_ifs"
+ done
+ test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm
+fi
+fi
+{ echo "$as_me:$LINENO: result: $lt_cv_path_NM" >&5
+echo "${ECHO_T}$lt_cv_path_NM" >&6; }
+NM="$lt_cv_path_NM"
+
+
+
+{ echo "$as_me:$LINENO: checking for GNU make" >&5
+echo $ECHO_N "checking for GNU make... $ECHO_C" >&6; }
+if test "${llvm_cv_gnu_make_command+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ llvm_cv_gnu_make_command=''
+ for a in "$MAKE" make gmake gnumake ; do
+ if test -z "$a" ; then continue ; fi ;
+ if ( sh -c "$a --version" 2> /dev/null | grep GNU 2>&1 > /dev/null )
+ then
+ llvm_cv_gnu_make_command=$a ;
+ break;
+ fi
+ done
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_gnu_make_command" >&5
+echo "${ECHO_T}$llvm_cv_gnu_make_command" >&6; }
+ if test "x$llvm_cv_gnu_make_command" != "x" ; then
+ ifGNUmake='' ;
+ else
+ ifGNUmake='#' ;
+ { echo "$as_me:$LINENO: result: \"Not found\"" >&5
+echo "${ECHO_T}\"Not found\"" >&6; };
+ fi
+
+
+{ echo "$as_me:$LINENO: checking whether ln -s works" >&5
+echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6; }
+LN_S=$as_ln_s
+if test "$LN_S" = "ln -s"; then
+ { echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no, using $LN_S" >&5
+echo "${ECHO_T}no, using $LN_S" >&6; }
+fi
+
+# Extract the first word of "cmp", so it can be a program name with args.
+set dummy cmp; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_CMP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $CMP in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_CMP="$CMP" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_CMP="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_CMP" && ac_cv_path_CMP="cmp"
+ ;;
+esac
+fi
+CMP=$ac_cv_path_CMP
+if test -n "$CMP"; then
+ { echo "$as_me:$LINENO: result: $CMP" >&5
+echo "${ECHO_T}$CMP" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "cp", so it can be a program name with args.
+set dummy cp; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_CP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $CP in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_CP="$CP" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_CP="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_CP" && ac_cv_path_CP="cp"
+ ;;
+esac
+fi
+CP=$ac_cv_path_CP
+if test -n "$CP"; then
+ { echo "$as_me:$LINENO: result: $CP" >&5
+echo "${ECHO_T}$CP" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "date", so it can be a program name with args.
+set dummy date; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_DATE+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $DATE in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_DATE="$DATE" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_DATE="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_DATE" && ac_cv_path_DATE="date"
+ ;;
+esac
+fi
+DATE=$ac_cv_path_DATE
+if test -n "$DATE"; then
+ { echo "$as_me:$LINENO: result: $DATE" >&5
+echo "${ECHO_T}$DATE" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "find", so it can be a program name with args.
+set dummy find; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_FIND+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $FIND in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_FIND="$FIND" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_FIND="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_FIND" && ac_cv_path_FIND="find"
+ ;;
+esac
+fi
+FIND=$ac_cv_path_FIND
+if test -n "$FIND"; then
+ { echo "$as_me:$LINENO: result: $FIND" >&5
+echo "${ECHO_T}$FIND" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "grep", so it can be a program name with args.
+set dummy grep; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_GREP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $GREP in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_GREP="$GREP" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_GREP="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_GREP" && ac_cv_path_GREP="grep"
+ ;;
+esac
+fi
+GREP=$ac_cv_path_GREP
+if test -n "$GREP"; then
+ { echo "$as_me:$LINENO: result: $GREP" >&5
+echo "${ECHO_T}$GREP" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "mkdir", so it can be a program name with args.
+set dummy mkdir; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_MKDIR+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $MKDIR in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_MKDIR="$MKDIR" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_MKDIR="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_MKDIR" && ac_cv_path_MKDIR="mkdir"
+ ;;
+esac
+fi
+MKDIR=$ac_cv_path_MKDIR
+if test -n "$MKDIR"; then
+ { echo "$as_me:$LINENO: result: $MKDIR" >&5
+echo "${ECHO_T}$MKDIR" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "mv", so it can be a program name with args.
+set dummy mv; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_MV+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $MV in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_MV="$MV" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_MV="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_MV" && ac_cv_path_MV="mv"
+ ;;
+esac
+fi
+MV=$ac_cv_path_MV
+if test -n "$MV"; then
+ { echo "$as_me:$LINENO: result: $MV" >&5
+echo "${ECHO_T}$MV" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
+set dummy ${ac_tool_prefix}ranlib; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_RANLIB+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$RANLIB"; then
+ ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+RANLIB=$ac_cv_prog_RANLIB
+if test -n "$RANLIB"; then
+ { echo "$as_me:$LINENO: result: $RANLIB" >&5
+echo "${ECHO_T}$RANLIB" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_RANLIB"; then
+ ac_ct_RANLIB=$RANLIB
+ # Extract the first word of "ranlib", so it can be a program name with args.
+set dummy ranlib; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_RANLIB"; then
+ ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_ac_ct_RANLIB="ranlib"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
+if test -n "$ac_ct_RANLIB"; then
+ { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
+echo "${ECHO_T}$ac_ct_RANLIB" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+ if test "x$ac_ct_RANLIB" = x; then
+ RANLIB=":"
+ else
+ case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet. If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet. If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+ RANLIB=$ac_ct_RANLIB
+ fi
+else
+ RANLIB="$ac_cv_prog_RANLIB"
+fi
+
+if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args.
+set dummy ${ac_tool_prefix}ar; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_AR+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$AR"; then
+ ac_cv_prog_AR="$AR" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_AR="${ac_tool_prefix}ar"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+AR=$ac_cv_prog_AR
+if test -n "$AR"; then
+ { echo "$as_me:$LINENO: result: $AR" >&5
+echo "${ECHO_T}$AR" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_AR"; then
+ ac_ct_AR=$AR
+ # Extract the first word of "ar", so it can be a program name with args.
+set dummy ar; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_AR+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_AR"; then
+ ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_ac_ct_AR="ar"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_AR=$ac_cv_prog_ac_ct_AR
+if test -n "$ac_ct_AR"; then
+ { echo "$as_me:$LINENO: result: $ac_ct_AR" >&5
+echo "${ECHO_T}$ac_ct_AR" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+ if test "x$ac_ct_AR" = x; then
+ AR="false"
+ else
+ case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet. If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet. If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+ AR=$ac_ct_AR
+ fi
+else
+ AR="$ac_cv_prog_AR"
+fi
+
+# Extract the first word of "rm", so it can be a program name with args.
+set dummy rm; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_RM+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $RM in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_RM="$RM" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_RM="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_RM" && ac_cv_path_RM="rm"
+ ;;
+esac
+fi
+RM=$ac_cv_path_RM
+if test -n "$RM"; then
+ { echo "$as_me:$LINENO: result: $RM" >&5
+echo "${ECHO_T}$RM" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "sed", so it can be a program name with args.
+set dummy sed; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_SED+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $SED in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_SED="$SED" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_SED="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_SED" && ac_cv_path_SED="sed"
+ ;;
+esac
+fi
+SED=$ac_cv_path_SED
+if test -n "$SED"; then
+ { echo "$as_me:$LINENO: result: $SED" >&5
+echo "${ECHO_T}$SED" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "tar", so it can be a program name with args.
+set dummy tar; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_TAR+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $TAR in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_TAR="$TAR" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_TAR="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_TAR" && ac_cv_path_TAR="gtar"
+ ;;
+esac
+fi
+TAR=$ac_cv_path_TAR
+if test -n "$TAR"; then
+ { echo "$as_me:$LINENO: result: $TAR" >&5
+echo "${ECHO_T}$TAR" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "pwd", so it can be a program name with args.
+set dummy pwd; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_BINPWD+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $BINPWD in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_BINPWD="$BINPWD" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_BINPWD="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_BINPWD" && ac_cv_path_BINPWD="pwd"
+ ;;
+esac
+fi
+BINPWD=$ac_cv_path_BINPWD
+if test -n "$BINPWD"; then
+ { echo "$as_me:$LINENO: result: $BINPWD" >&5
+echo "${ECHO_T}$BINPWD" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+
+# Extract the first word of "Graphviz", so it can be a program name with args.
+set dummy Graphviz; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_GRAPHVIZ+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $GRAPHVIZ in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_GRAPHVIZ="$GRAPHVIZ" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_GRAPHVIZ="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_GRAPHVIZ" && ac_cv_path_GRAPHVIZ="echo Graphviz"
+ ;;
+esac
+fi
+GRAPHVIZ=$ac_cv_path_GRAPHVIZ
+if test -n "$GRAPHVIZ"; then
+ { echo "$as_me:$LINENO: result: $GRAPHVIZ" >&5
+echo "${ECHO_T}$GRAPHVIZ" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test "$GRAPHVIZ" != "echo Graphviz" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_GRAPHVIZ 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ GRAPHVIZ=`echo $GRAPHVIZ | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_GRAPHVIZ "$GRAPHVIZ${EXEEXT}"
+_ACEOF
+
+fi
+# Extract the first word of "dot", so it can be a program name with args.
+set dummy dot; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_DOT+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $DOT in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_DOT="$DOT" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_DOT="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_DOT" && ac_cv_path_DOT="echo dot"
+ ;;
+esac
+fi
+DOT=$ac_cv_path_DOT
+if test -n "$DOT"; then
+ { echo "$as_me:$LINENO: result: $DOT" >&5
+echo "${ECHO_T}$DOT" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test "$DOT" != "echo dot" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_DOT 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ DOT=`echo $DOT | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_DOT "$DOT${EXEEXT}"
+_ACEOF
+
+fi
+# Extract the first word of "fdp", so it can be a program name with args.
+set dummy fdp; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_FDP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $FDP in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_FDP="$FDP" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_FDP="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_FDP" && ac_cv_path_FDP="echo fdp"
+ ;;
+esac
+fi
+FDP=$ac_cv_path_FDP
+if test -n "$FDP"; then
+ { echo "$as_me:$LINENO: result: $FDP" >&5
+echo "${ECHO_T}$FDP" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test "$FDP" != "echo fdp" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_FDP 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ FDP=`echo $FDP | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_FDP "$FDP${EXEEXT}"
+_ACEOF
+
+fi
+# Extract the first word of "neato", so it can be a program name with args.
+set dummy neato; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_NEATO+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $NEATO in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_NEATO="$NEATO" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_NEATO="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_NEATO" && ac_cv_path_NEATO="echo neato"
+ ;;
+esac
+fi
+NEATO=$ac_cv_path_NEATO
+if test -n "$NEATO"; then
+ { echo "$as_me:$LINENO: result: $NEATO" >&5
+echo "${ECHO_T}$NEATO" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test "$NEATO" != "echo neato" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_NEATO 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ NEATO=`echo $NEATO | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_NEATO "$NEATO${EXEEXT}"
+_ACEOF
+
+fi
+# Extract the first word of "twopi", so it can be a program name with args.
+set dummy twopi; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_TWOPI+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $TWOPI in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_TWOPI="$TWOPI" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_TWOPI="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_TWOPI" && ac_cv_path_TWOPI="echo twopi"
+ ;;
+esac
+fi
+TWOPI=$ac_cv_path_TWOPI
+if test -n "$TWOPI"; then
+ { echo "$as_me:$LINENO: result: $TWOPI" >&5
+echo "${ECHO_T}$TWOPI" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test "$TWOPI" != "echo twopi" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_TWOPI 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ TWOPI=`echo $TWOPI | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_TWOPI "$TWOPI${EXEEXT}"
+_ACEOF
+
+fi
+# Extract the first word of "circo", so it can be a program name with args.
+set dummy circo; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_CIRCO+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $CIRCO in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_CIRCO="$CIRCO" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_CIRCO="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_CIRCO" && ac_cv_path_CIRCO="echo circo"
+ ;;
+esac
+fi
+CIRCO=$ac_cv_path_CIRCO
+if test -n "$CIRCO"; then
+ { echo "$as_me:$LINENO: result: $CIRCO" >&5
+echo "${ECHO_T}$CIRCO" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test "$CIRCO" != "echo circo" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_CIRCO 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ CIRCO=`echo $CIRCO | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_CIRCO "$CIRCO${EXEEXT}"
+_ACEOF
+
+fi
+for ac_prog in gv gsview32
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_GV+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $GV in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_GV="$GV" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_GV="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+GV=$ac_cv_path_GV
+if test -n "$GV"; then
+ { echo "$as_me:$LINENO: result: $GV" >&5
+echo "${ECHO_T}$GV" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$GV" && break
+done
+test -n "$GV" || GV="echo gv"
+
+if test "$GV" != "echo gv" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_GV 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ GV=`echo $GV | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_GV "$GV${EXEEXT}"
+_ACEOF
+
+fi
+# Extract the first word of "dotty", so it can be a program name with args.
+set dummy dotty; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_DOTTY+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $DOTTY in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_DOTTY="$DOTTY" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_DOTTY="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_DOTTY" && ac_cv_path_DOTTY="echo dotty"
+ ;;
+esac
+fi
+DOTTY=$ac_cv_path_DOTTY
+if test -n "$DOTTY"; then
+ { echo "$as_me:$LINENO: result: $DOTTY" >&5
+echo "${ECHO_T}$DOTTY" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test "$DOTTY" != "echo dotty" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_DOTTY 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ DOTTY=`echo $DOTTY | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_DOTTY "$DOTTY${EXEEXT}"
+_ACEOF
+
+fi
+# Extract the first word of "xdot.py", so it can be a program name with args.
+set dummy xdot.py; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_XDOT_PY+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $XDOT_PY in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_XDOT_PY="$XDOT_PY" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_XDOT_PY="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ test -z "$ac_cv_path_XDOT_PY" && ac_cv_path_XDOT_PY="echo xdot.py"
+ ;;
+esac
+fi
+XDOT_PY=$ac_cv_path_XDOT_PY
+if test -n "$XDOT_PY"; then
+ { echo "$as_me:$LINENO: result: $XDOT_PY" >&5
+echo "${ECHO_T}$XDOT_PY" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+if test "$XDOT_PY" != "echo xdot.py" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_XDOT_PY 1
+_ACEOF
+
+ if test "$llvm_cv_os_type" = "MingW" ; then
+ XDOT_PY=`echo $XDOT_PY | sed 's/^\/\([A-Za-z]\)\//\1:\//' `
+ fi
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PATH_XDOT_PY "$XDOT_PY${EXEEXT}"
+_ACEOF
+
+fi
+
+# Find a good install program. We prefer a C program (faster),
+# so one script is as good as another. But avoid the broken or
+# incompatible versions:
+# SysV /etc/install, /usr/sbin/install
+# SunOS /usr/etc/install
+# IRIX /sbin/install
+# AIX /bin/install
+# AmigaOS /C/install, which installs bootblocks on floppy discs
+# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
+# AFS /usr/afsws/bin/install, which mishandles nonexistent args
+# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
+# OS/2's system install, which has a completely different semantic
+# ./install, which can be erroneously created by make from ./install.sh.
+{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5
+echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; }
+if test -z "$INSTALL"; then
+if test "${ac_cv_path_install+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ # Account for people who put trailing slashes in PATH elements.
+case $as_dir/ in
+ ./ | .// | /cC/* | \
+ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \
+ ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \
+ /usr/ucb/* ) ;;
+ *)
+ # OSF1 and SCO ODT 3.0 have their own names for install.
+ # Don't use installbsd from OSF since it installs stuff as root
+ # by default.
+ for ac_prog in ginstall scoinst install; do
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_executable_p "$as_dir/$ac_prog$ac_exec_ext"; }; then
+ if test $ac_prog = install &&
+ grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+ # AIX install. It has an incompatible calling convention.
+ :
+ elif test $ac_prog = install &&
+ grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+ # program-specific install script used by HP pwplus--don't use.
+ :
+ else
+ ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c"
+ break 3
+ fi
+ fi
+ done
+ done
+ ;;
+esac
+done
+IFS=$as_save_IFS
+
+
+fi
+ if test "${ac_cv_path_install+set}" = set; then
+ INSTALL=$ac_cv_path_install
+ else
+ # As a last resort, use the slow shell script. Don't cache a
+ # value for INSTALL within a source directory, because that will
+ # break other packages using the cache if that directory is
+ # removed, or if the value is a relative name.
+ INSTALL=$ac_install_sh
+ fi
+fi
+{ echo "$as_me:$LINENO: result: $INSTALL" >&5
+echo "${ECHO_T}$INSTALL" >&6; }
+
+# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
+# It thinks the first close brace ends the variable substitution.
+test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
+
+test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}'
+
+test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
+
+case "$INSTALL" in
+ [\\/$]* | ?:[\\/]* ) ;;
+ *) INSTALL="\\\$(TOPSRCDIR)/$INSTALL" ;;
+esac
+
+# Extract the first word of "bzip2", so it can be a program name with args.
+set dummy bzip2; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_BZIP2+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $BZIP2 in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_BZIP2="$BZIP2" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_BZIP2="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+BZIP2=$ac_cv_path_BZIP2
+if test -n "$BZIP2"; then
+ { echo "$as_me:$LINENO: result: $BZIP2" >&5
+echo "${ECHO_T}$BZIP2" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "cat", so it can be a program name with args.
+set dummy cat; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_CAT+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $CAT in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_CAT="$CAT" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_CAT="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+CAT=$ac_cv_path_CAT
+if test -n "$CAT"; then
+ { echo "$as_me:$LINENO: result: $CAT" >&5
+echo "${ECHO_T}$CAT" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "doxygen", so it can be a program name with args.
+set dummy doxygen; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_DOXYGEN+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $DOXYGEN in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_DOXYGEN="$DOXYGEN" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_DOXYGEN="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+DOXYGEN=$ac_cv_path_DOXYGEN
+if test -n "$DOXYGEN"; then
+ { echo "$as_me:$LINENO: result: $DOXYGEN" >&5
+echo "${ECHO_T}$DOXYGEN" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "groff", so it can be a program name with args.
+set dummy groff; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_GROFF+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $GROFF in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_GROFF="$GROFF" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_GROFF="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+GROFF=$ac_cv_path_GROFF
+if test -n "$GROFF"; then
+ { echo "$as_me:$LINENO: result: $GROFF" >&5
+echo "${ECHO_T}$GROFF" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "gzip", so it can be a program name with args.
+set dummy gzip; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_GZIPBIN+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $GZIPBIN in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_GZIPBIN="$GZIPBIN" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_GZIPBIN="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+GZIPBIN=$ac_cv_path_GZIPBIN
+if test -n "$GZIPBIN"; then
+ { echo "$as_me:$LINENO: result: $GZIPBIN" >&5
+echo "${ECHO_T}$GZIPBIN" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "pdfroff", so it can be a program name with args.
+set dummy pdfroff; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_PDFROFF+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $PDFROFF in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_PDFROFF="$PDFROFF" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_PDFROFF="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+PDFROFF=$ac_cv_path_PDFROFF
+if test -n "$PDFROFF"; then
+ { echo "$as_me:$LINENO: result: $PDFROFF" >&5
+echo "${ECHO_T}$PDFROFF" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+# Extract the first word of "zip", so it can be a program name with args.
+set dummy zip; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_ZIP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $ZIP in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_ZIP="$ZIP" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_ZIP="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+ZIP=$ac_cv_path_ZIP
+if test -n "$ZIP"; then
+ { echo "$as_me:$LINENO: result: $ZIP" >&5
+echo "${ECHO_T}$ZIP" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+for ac_prog in ocamlc
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_OCAMLC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $OCAMLC in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_OCAMLC="$OCAMLC" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_OCAMLC="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+OCAMLC=$ac_cv_path_OCAMLC
+if test -n "$OCAMLC"; then
+ { echo "$as_me:$LINENO: result: $OCAMLC" >&5
+echo "${ECHO_T}$OCAMLC" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$OCAMLC" && break
+done
+
+for ac_prog in ocamlopt
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_OCAMLOPT+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $OCAMLOPT in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_OCAMLOPT="$OCAMLOPT" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_OCAMLOPT="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+OCAMLOPT=$ac_cv_path_OCAMLOPT
+if test -n "$OCAMLOPT"; then
+ { echo "$as_me:$LINENO: result: $OCAMLOPT" >&5
+echo "${ECHO_T}$OCAMLOPT" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$OCAMLOPT" && break
+done
+
+for ac_prog in ocamldep
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_OCAMLDEP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $OCAMLDEP in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_OCAMLDEP="$OCAMLDEP" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_OCAMLDEP="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+OCAMLDEP=$ac_cv_path_OCAMLDEP
+if test -n "$OCAMLDEP"; then
+ { echo "$as_me:$LINENO: result: $OCAMLDEP" >&5
+echo "${ECHO_T}$OCAMLDEP" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$OCAMLDEP" && break
+done
+
+for ac_prog in ocamldoc
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_OCAMLDOC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $OCAMLDOC in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_OCAMLDOC="$OCAMLDOC" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_OCAMLDOC="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+OCAMLDOC=$ac_cv_path_OCAMLDOC
+if test -n "$OCAMLDOC"; then
+ { echo "$as_me:$LINENO: result: $OCAMLDOC" >&5
+echo "${ECHO_T}$OCAMLDOC" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$OCAMLDOC" && break
+done
+
+for ac_prog in gas as
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_path_GAS+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $GAS in
+ [\\/]* | ?:[\\/]*)
+ ac_cv_path_GAS="$GAS" # Let the user override the test with a path.
+ ;;
+ *)
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_path_GAS="$as_dir/$ac_word$ac_exec_ext"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+fi
+GAS=$ac_cv_path_GAS
+if test -n "$GAS"; then
+ { echo "$as_me:$LINENO: result: $GAS" >&5
+echo "${ECHO_T}$GAS" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$GAS" && break
+done
+
+
+{ echo "$as_me:$LINENO: checking for linker version" >&5
+echo $ECHO_N "checking for linker version... $ECHO_C" >&6; }
+if test "${llvm_cv_link_version+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+
+ version_string="$(ld -v 2>&1 | head -1)"
+
+ # Check for ld64.
+ if (echo "$version_string" | grep -q "ld64"); then
+ llvm_cv_link_version=$(echo "$version_string" | sed -e "s#.*ld64-\([^ ]*\)\( (.*)\)\{0,1\}#\1#")
+ else
+ llvm_cv_link_version=$(echo "$version_string" | sed -e "s#[^0-9]*\([0-9.]*\).*#\1#")
+ fi
+
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_link_version" >&5
+echo "${ECHO_T}$llvm_cv_link_version" >&6; }
+
+cat >>confdefs.h <<_ACEOF
+#define HOST_LINK_VERSION "$llvm_cv_link_version"
+_ACEOF
+
+
+
+{ echo "$as_me:$LINENO: checking for compiler -Wl,-R<path> option" >&5
+echo $ECHO_N "checking for compiler -Wl,-R<path> option... $ECHO_C" >&6; }
+if test "${llvm_cv_link_use_r+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ oldcflags="$CFLAGS"
+ CFLAGS="$CFLAGS -Wl,-R."
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ llvm_cv_link_use_r=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ llvm_cv_link_use_r=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+ CFLAGS="$oldcflags"
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_link_use_r" >&5
+echo "${ECHO_T}$llvm_cv_link_use_r" >&6; }
+if test "$llvm_cv_link_use_r" = yes ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_LINK_R 1
+_ACEOF
+
+ fi
+
+
+{ echo "$as_me:$LINENO: checking for compiler -Wl,-export-dynamic option" >&5
+echo $ECHO_N "checking for compiler -Wl,-export-dynamic option... $ECHO_C" >&6; }
+if test "${llvm_cv_link_use_export_dynamic+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ oldcflags="$CFLAGS"
+ CFLAGS="$CFLAGS -Wl,-export-dynamic"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ llvm_cv_link_use_export_dynamic=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ llvm_cv_link_use_export_dynamic=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+ CFLAGS="$oldcflags"
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_link_use_export_dynamic" >&5
+echo "${ECHO_T}$llvm_cv_link_use_export_dynamic" >&6; }
+if test "$llvm_cv_link_use_export_dynamic" = yes ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_LINK_EXPORT_DYNAMIC 1
+_ACEOF
+
+ fi
+
+
+{ echo "$as_me:$LINENO: checking for compiler -Wl,--version-script option" >&5
+echo $ECHO_N "checking for compiler -Wl,--version-script option... $ECHO_C" >&6; }
+if test "${llvm_cv_link_use_version_script+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ oldcflags="$CFLAGS"
+
+ # The following code is from the autoconf manual,
+ # "11.13: Limitations of Usual Tools".
+ # Create a temporary directory $tmp in $TMPDIR (default /tmp).
+ # Use mktemp if possible; otherwise fall back on mkdir,
+ # with $RANDOM to make collisions less likely.
+ : ${TMPDIR=/tmp}
+ {
+ tmp=`
+ (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
+ ` &&
+ test -n "$tmp" && test -d "$tmp"
+ } || {
+ tmp=$TMPDIR/foo$$-$RANDOM
+ (umask 077 && mkdir "$tmp")
+ } || exit $?
+
+ echo "{" > "$tmp/export.map"
+ echo " global: main;" >> "$tmp/export.map"
+ echo " local: *;" >> "$tmp/export.map"
+ echo "};" >> "$tmp/export.map"
+
+ CFLAGS="$CFLAGS -Wl,--version-script=$tmp/export.map"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ llvm_cv_link_use_version_script=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ llvm_cv_link_use_version_script=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+ rm "$tmp/export.map"
+ rmdir "$tmp"
+ CFLAGS="$oldcflags"
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_link_use_version_script" >&5
+echo "${ECHO_T}$llvm_cv_link_use_version_script" >&6; }
+if test "$llvm_cv_link_use_version_script" = yes ; then
+ HAVE_LINK_VERSION_SCRIPT=1
+
+ fi
+
+
+
+
+{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5
+echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; }
+if test "${ac_cv_c_const+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+/* FIXME: Include the comments suggested by Paul. */
+#ifndef __cplusplus
+ /* Ultrix mips cc rejects this. */
+ typedef int charset[2];
+ const charset x;
+ /* SunOS 4.1.1 cc rejects this. */
+ char const *const *ccp;
+ char **p;
+ /* NEC SVR4.0.2 mips cc rejects this. */
+ struct point {int x, y;};
+ static struct point const zero = {0,0};
+ /* AIX XL C 1.02.0.0 rejects this.
+ It does not let you subtract one const X* pointer from another in
+ an arm of an if-expression whose if-part is not a constant
+ expression */
+ const char *g = "string";
+ ccp = &g + (g ? g-g : 0);
+ /* HPUX 7.0 cc rejects these. */
+ ++ccp;
+ p = (char**) ccp;
+ ccp = (char const *const *) p;
+ { /* SCO 3.2v4 cc rejects this. */
+ char *t;
+ char const *s = 0 ? (char *) 0 : (char const *) 0;
+
+ *t++ = 0;
+ if (s) return 0;
+ }
+ { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */
+ int x[] = {25, 17};
+ const int *foo = &x[0];
+ ++foo;
+ }
+ { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
+ typedef const int *iptr;
+ iptr p = 0;
+ ++p;
+ }
+ { /* AIX XL C 1.02.0.0 rejects this saying
+ "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
+ struct s { int j; const int *ap[3]; };
+ struct s *b; b->j = 5;
+ }
+ { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
+ const int foo = 10;
+ if (!foo) return 0;
+ }
+ return !x[0] && !zero.x;
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_c_const=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_c_const=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5
+echo "${ECHO_T}$ac_cv_c_const" >&6; }
+if test $ac_cv_c_const = no; then
+
+cat >>confdefs.h <<\_ACEOF
+#define const
+_ACEOF
+
+fi
+
+
+
+
+
+
+ac_header_dirent=no
+for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do
+ as_ac_Header=`echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5
+echo $ECHO_N "checking for $ac_hdr that defines DIR... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/types.h>
+#include <$ac_hdr>
+
+int
+main ()
+{
+if ((DIR *) 0)
+return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_Header=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_Header=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_hdr" | $as_tr_cpp` 1
+_ACEOF
+
+ac_header_dirent=$ac_hdr; break
+fi
+
+done
+# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix.
+if test $ac_header_dirent = dirent.h; then
+ { echo "$as_me:$LINENO: checking for library containing opendir" >&5
+echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; }
+if test "${ac_cv_search_opendir+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char opendir ();
+int
+main ()
+{
+return opendir ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' dir; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_opendir=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_opendir+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_opendir+set}" = set; then
+ :
+else
+ ac_cv_search_opendir=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5
+echo "${ECHO_T}$ac_cv_search_opendir" >&6; }
+ac_res=$ac_cv_search_opendir
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+fi
+
+else
+ { echo "$as_me:$LINENO: checking for library containing opendir" >&5
+echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; }
+if test "${ac_cv_search_opendir+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char opendir ();
+int
+main ()
+{
+return opendir ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' x; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_opendir=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_opendir+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_opendir+set}" = set; then
+ :
+else
+ ac_cv_search_opendir=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5
+echo "${ECHO_T}$ac_cv_search_opendir" >&6; }
+ac_res=$ac_cv_search_opendir
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+fi
+
+fi
+
+
+for ac_header in dlfcn.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+# Check whether --enable-ltdl-install was given.
+if test "${enable_ltdl_install+set}" = set; then
+ enableval=$enable_ltdl_install;
+fi
+
+
+
+
+if test x"${enable_ltdl_install-no}" != xno; then
+ INSTALL_LTDL_TRUE=
+ INSTALL_LTDL_FALSE='#'
+else
+ INSTALL_LTDL_TRUE='#'
+ INSTALL_LTDL_FALSE=
+fi
+
+
+
+if test x"${enable_ltdl_convenience-no}" != xno; then
+ CONVENIENCE_LTDL_TRUE=
+ CONVENIENCE_LTDL_FALSE='#'
+else
+ CONVENIENCE_LTDL_TRUE='#'
+ CONVENIENCE_LTDL_FALSE=
+fi
+
+
+{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
+ # if the path contains ";" then we assume it to be the separator
+ # otherwise default to the standard path separator (i.e. ":") - it is
+ # assumed that no part of a normal pathname contains ";" but that should
+ # okay in the real world where ";" in dirpaths is itself problematic.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+else
+ sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+ shlibpath_var=LIBPATH
+
+ # AIX 3 has no versioning support, so we append a major version to the name.
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+
+aix4* | aix5*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ hardcode_into_libs=yes
+ if test "$host_cpu" = ia64; then
+ # AIX 5 supports IA64
+ library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ else
+ # With GCC up to 2.95.x, collect2 would create an import file
+ # for dependence libraries. The import file would start with
+ # the line `#! .'. This would cause the generated library to
+ # depend on `.', always an invalid library. This was fixed in
+ # development snapshots of GCC prior to 3.0.
+ case $host_os in
+ aix4 | aix4.[01] | aix4.[01].*)
+ if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+ echo ' yes '
+ echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+ :
+ else
+ can_build_shared=no
+ fi
+ ;;
+ esac
+ # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+ # soname into executable. Probably we can add versioning support to
+ # collect2, so additional links can be useful in future.
+ if test "$aix_use_runtimelinking" = yes; then
+ # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+ # instead of lib<name>.a to let people know that these are not
+ # typical AIX shared libraries.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ else
+ # We preserve .a as extension for shared libraries through AIX4.2
+ # and later when we are not doing run time linking.
+ library_names_spec='${libname}${release}.a $libname.a'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ fi
+ shlibpath_var=LIBPATH
+ fi
+ ;;
+
+amigaos*)
+ library_names_spec='$libname.ixlibrary $libname.a'
+ # Create ${libname}_ixlibrary.a entries in /sys/libs.
+ finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+ ;;
+
+beos*)
+ library_names_spec='${libname}${shared_ext}'
+ dynamic_linker="$host_os ld.so"
+ shlibpath_var=LIBRARY_PATH
+ ;;
+
+bsdi[45]*)
+ version_type=linux
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+ sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+ # the default ld.so.conf also contains /usr/contrib/lib and
+ # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+ # libtool to hard-code these into programs
+ ;;
+
+cygwin* | mingw* | pw32*)
+ version_type=windows
+ shrext_cmds=".dll"
+ need_version=no
+ need_lib_prefix=no
+
+ case $GCC,$host_os in
+ yes,cygwin* | yes,mingw* | yes,pw32*)
+ library_names_spec='$libname.dll.a'
+ # DLL is installed to $(libdir)/../bin by postinstall_cmds
+ postinstall_cmds='base_file=`basename \${file}`~
+ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
+ dldir=$destdir/`dirname \$dlpath`~
+ test -d \$dldir || mkdir -p \$dldir~
+ $install_prog $dir/$dlname \$dldir/$dlname~
+ chmod a+x \$dldir/$dlname'
+ postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+ dlpath=$dir/\$dldll~
+ $rm \$dlpath'
+ shlibpath_overrides_runpath=yes
+
+ case $host_os in
+ cygwin*)
+ # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+ soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+ ;;
+ mingw*)
+ # MinGW DLLs use traditional 'lib' prefix
+ soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then
+ # It is most probably a Windows format PATH printed by
+ # mingw gcc, but we are running on Cygwin. Gcc prints its search
+ # path with ; separators, and with drive letters. We can handle the
+ # drive letters (cygwin fileutils understands them), so leave them,
+ # especially as we might pass files found there to a mingw objdump,
+ # which wouldn't understand a cygwinified path. Ahh.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+ ;;
+ pw32*)
+ # pw32 DLLs use 'pw' prefix rather than 'lib'
+ library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ ;;
+ esac
+ ;;
+
+ *)
+ library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+ ;;
+ esac
+ dynamic_linker='Win32 ld.exe'
+ # FIXME: first we should search . and the directory the executable is in
+ shlibpath_var=PATH
+ ;;
+
+darwin* | rhapsody*)
+ dynamic_linker="$host_os dyld"
+ version_type=darwin
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+ soname_spec='${libname}${release}${major}$shared_ext'
+ shlibpath_overrides_runpath=yes
+ shlibpath_var=DYLD_LIBRARY_PATH
+ shrext_cmds='.dylib'
+ # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
+ if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
+ else
+ sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
+ fi
+ sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+ ;;
+
+dgux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+freebsd1.*)
+ dynamic_linker=no
+ ;;
+
+kfreebsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+freebsd* | dragonfly*)
+ # DragonFly does not have aout. When/if they implement a new
+ # versioning mechanism, adjust this.
+ if test -x /usr/bin/objformat; then
+ objformat=`/usr/bin/objformat`
+ else
+ case $host_os in
+ freebsd[123].*) objformat=aout ;;
+ *) objformat=elf ;;
+ esac
+ fi
+ version_type=freebsd-$objformat
+ case $version_type in
+ freebsd-elf*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ need_version=no
+ need_lib_prefix=no
+ ;;
+ freebsd-*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+ need_version=yes
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_os in
+ freebsd2.*)
+ shlibpath_overrides_runpath=yes
+ ;;
+ freebsd3.[01]* | freebsdelf3.[01]*)
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
+ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+ freebsd*) # from 4.6 on
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ esac
+ ;;
+
+gnu*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ ;;
+
+hpux9* | hpux10* | hpux11*)
+ # Give a soname corresponding to the major version so that dld.sl refuses to
+ # link against other versions.
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ case $host_cpu in
+ ia64*)
+ shrext_cmds='.so'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.so"
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ if test "X$HPUX_IA64_MODE" = X32; then
+ sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+ else
+ sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+ fi
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ hppa*64*)
+ shrext_cmds='.sl'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ *)
+ shrext_cmds='.sl'
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=SHLIB_PATH
+ shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+ esac
+ # HP-UX runs *really* slowly unless shared libraries are mode 555.
+ postinstall_cmds='chmod 555 $lib'
+ ;;
+
+interix3*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $host_os in
+ nonstopux*) version_type=nonstopux ;;
+ *)
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ version_type=linux
+ else
+ version_type=irix
+ fi ;;
+ esac
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+ case $host_os in
+ irix5* | nonstopux*)
+ libsuff= shlibsuff=
+ ;;
+ *)
+ case $LD in # libtool.m4 will add one of these switches to LD
+ *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+ libsuff= shlibsuff= libmagic=32-bit;;
+ *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+ libsuff=32 shlibsuff=N32 libmagic=N32;;
+ *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+ libsuff=64 shlibsuff=64 libmagic=64-bit;;
+ *) libsuff= shlibsuff= libmagic=never-match;;
+ esac
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+ sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+ hardcode_into_libs=yes
+ ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+ dynamic_linker=no
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ # This implies no fast_install, which is unacceptable.
+ # Some rework will be needed to allow for fast_install
+ # before this can be enabled.
+ hardcode_into_libs=yes
+
+ # Append ld.so.conf contents to the search path
+ if test -f /etc/ld.so.conf; then
+ lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+ sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+ fi
+
+ # We used to test for /lib/ld.so.1 and disable shared libraries on
+ # powerpc, because MkLinux only supported shared libraries with the
+ # GNU dynamic linker. Since this was broken with cross compilers,
+ # most powerpc-linux boxes support dynamic linking these days and
+ # people can always --disable-shared, the test was removed, and we
+ # assume the GNU/Linux dynamic linker is in use.
+ dynamic_linker='GNU/Linux ld.so'
+ ;;
+
+knetbsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+netbsd*)
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ dynamic_linker='NetBSD (a.out) ld.so'
+ else
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='NetBSD ld.elf_so'
+ fi
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+
+newsos6)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+nto-qnx*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+openbsd* | bitrig*)
+ version_type=sunos
+ sys_lib_dlsearch_path_spec="/usr/lib"
+ need_lib_prefix=no
+ # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+ case $host_os in
+ openbsd3.3 | openbsd3.3.*) need_version=yes ;;
+ *) need_version=no ;;
+ esac
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ case $host_os in
+ openbsd2.[89] | openbsd2.[89].*)
+ shlibpath_overrides_runpath=no
+ ;;
+ *)
+ shlibpath_overrides_runpath=yes
+ ;;
+ esac
+ else
+ shlibpath_overrides_runpath=yes
+ fi
+ ;;
+
+os2*)
+ libname_spec='$name'
+ shrext_cmds=".dll"
+ need_lib_prefix=no
+ library_names_spec='$libname${shared_ext} $libname.a'
+ dynamic_linker='OS/2 ld.exe'
+ shlibpath_var=LIBPATH
+ ;;
+
+osf3* | osf4* | osf5*)
+ version_type=osf
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+ sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+ ;;
+
+solaris*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ # ldd complains unless libraries are executable
+ postinstall_cmds='chmod +x $lib'
+ ;;
+
+sunos4*)
+ version_type=sunos
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ if test "$with_gnu_ld" = yes; then
+ need_lib_prefix=no
+ fi
+ need_version=yes
+ ;;
+
+sysv4 | sysv4.3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_vendor in
+ sni)
+ shlibpath_overrides_runpath=no
+ need_lib_prefix=no
+ export_dynamic_flag_spec='${wl}-Blargedynsym'
+ runpath_var=LD_RUN_PATH
+ ;;
+ siemens)
+ need_lib_prefix=no
+ ;;
+ motorola)
+ need_lib_prefix=no
+ need_version=no
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+ ;;
+ esac
+ ;;
+
+sysv4*MP*)
+ if test -d /usr/nec ;then
+ version_type=linux
+ library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+ soname_spec='$libname${shared_ext}.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ fi
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ version_type=freebsd-elf
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ if test "$with_gnu_ld" = yes; then
+ sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+ shlibpath_overrides_runpath=no
+ else
+ sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+ shlibpath_overrides_runpath=yes
+ case $host_os in
+ sco3.2v5*)
+ sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+ ;;
+ esac
+ fi
+ sys_lib_dlsearch_path_spec='/usr/lib'
+ ;;
+
+uts4*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+*)
+ dynamic_linker=no
+ ;;
+esac
+{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6; }
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+ variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+
+{ echo "$as_me:$LINENO: checking which extension is used for loadable modules" >&5
+echo $ECHO_N "checking which extension is used for loadable modules... $ECHO_C" >&6; }
+if test "${libltdl_cv_shlibext+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+
+module=yes
+eval libltdl_cv_shlibext=$shrext_cmds
+
+fi
+{ echo "$as_me:$LINENO: result: $libltdl_cv_shlibext" >&5
+echo "${ECHO_T}$libltdl_cv_shlibext" >&6; }
+if test -n "$libltdl_cv_shlibext"; then
+
+cat >>confdefs.h <<_ACEOF
+#define LTDL_SHLIB_EXT "$libltdl_cv_shlibext"
+_ACEOF
+
+fi
+
+
+{ echo "$as_me:$LINENO: checking which variable specifies run-time library path" >&5
+echo $ECHO_N "checking which variable specifies run-time library path... $ECHO_C" >&6; }
+if test "${libltdl_cv_shlibpath_var+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ libltdl_cv_shlibpath_var="$shlibpath_var"
+fi
+{ echo "$as_me:$LINENO: result: $libltdl_cv_shlibpath_var" >&5
+echo "${ECHO_T}$libltdl_cv_shlibpath_var" >&6; }
+if test -n "$libltdl_cv_shlibpath_var"; then
+
+cat >>confdefs.h <<_ACEOF
+#define LTDL_SHLIBPATH_VAR "$libltdl_cv_shlibpath_var"
+_ACEOF
+
+fi
+
+
+{ echo "$as_me:$LINENO: checking for the default library search path" >&5
+echo $ECHO_N "checking for the default library search path... $ECHO_C" >&6; }
+if test "${libltdl_cv_sys_search_path+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ libltdl_cv_sys_search_path="$sys_lib_dlsearch_path_spec"
+fi
+{ echo "$as_me:$LINENO: result: $libltdl_cv_sys_search_path" >&5
+echo "${ECHO_T}$libltdl_cv_sys_search_path" >&6; }
+if test -n "$libltdl_cv_sys_search_path"; then
+ sys_search_path=
+ for dir in $libltdl_cv_sys_search_path; do
+ if test -z "$sys_search_path"; then
+ sys_search_path="$dir"
+ else
+ sys_search_path="$sys_search_path$PATH_SEPARATOR$dir"
+ fi
+ done
+
+cat >>confdefs.h <<_ACEOF
+#define LTDL_SYSSEARCHPATH "$sys_search_path"
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for objdir" >&5
+echo $ECHO_N "checking for objdir... $ECHO_C" >&6; }
+if test "${libltdl_cv_objdir+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ libltdl_cv_objdir="$objdir"
+ if test -n "$objdir"; then
+ :
+ else
+ rm -f .libs 2>/dev/null
+ mkdir .libs 2>/dev/null
+ if test -d .libs; then
+ libltdl_cv_objdir=.libs
+ else
+ # MS-DOS does not allow filenames that begin with a dot.
+ libltdl_cv_objdir=_libs
+ fi
+ rmdir .libs 2>/dev/null
+ fi
+
+fi
+{ echo "$as_me:$LINENO: result: $libltdl_cv_objdir" >&5
+echo "${ECHO_T}$libltdl_cv_objdir" >&6; }
+
+cat >>confdefs.h <<_ACEOF
+#define LTDL_OBJDIR "$libltdl_cv_objdir/"
+_ACEOF
+
+
+
+
+
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+{ echo "$as_me:$LINENO: checking command to parse $NM output from $compiler object" >&5
+echo $ECHO_N "checking command to parse $NM output from $compiler object... $ECHO_C" >&6; }
+if test "${lt_cv_sys_global_symbol_pipe+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix. What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[BCDEGRST]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([_A-Za-z][_A-Za-z0-9]*\)'
+
+# Transform an extracted symbol line into a proper C declaration
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^. .* \(.*\)$/extern int \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+ symcode='[BCDT]'
+ ;;
+cygwin* | mingw* | pw32*)
+ symcode='[ABCDGISTW]'
+ ;;
+hpux*) # Its linker distinguishes data from code symbols
+ if test "$host_cpu" = ia64; then
+ symcode='[ABCDEGRST]'
+ fi
+ lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+ lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+ ;;
+linux*)
+ if test "$host_cpu" = ia64; then
+ symcode='[ABCDGIRSTW]'
+ lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+ lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+ fi
+ ;;
+irix* | nonstopux*)
+ symcode='[BCDEGRST]'
+ ;;
+osf*)
+ symcode='[BCDEGQRST]'
+ ;;
+solaris*)
+ symcode='[BDRT]'
+ ;;
+sco3.2v5*)
+ symcode='[DT]'
+ ;;
+sysv4.2uw2*)
+ symcode='[DT]'
+ ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+ symcode='[ABDT]'
+ ;;
+sysv4)
+ symcode='[DFNSTU]'
+ ;;
+esac
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+ opt_cr=`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+ ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+ symcode='[ABCDGIRSTW]' ;;
+esac
+
+# Try without a prefix undercore, then with it.
+for ac_symprfx in "" "_"; do
+
+ # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+ symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+ # Write the raw and C identifiers.
+ lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+
+ # Check to see that the pipe works correctly.
+ pipe_works=no
+
+ rm -f conftest*
+ cat > conftest.$ac_ext <<EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+EOF
+
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ # Now try to grab the symbols.
+ nlist=conftest.nm
+ if { (eval echo "$as_me:$LINENO: \"$NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist\"") >&5
+ (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && test -s "$nlist"; then
+ # Try sorting and uniquifying the output.
+ if sort "$nlist" | uniq > "$nlist"T; then
+ mv -f "$nlist"T "$nlist"
+ else
+ rm -f "$nlist"T
+ fi
+
+ # Make sure that we snagged all the symbols we need.
+ if grep ' nm_test_var$' "$nlist" >/dev/null; then
+ if grep ' nm_test_func$' "$nlist" >/dev/null; then
+ cat <<EOF > conftest.$ac_ext
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+EOF
+ # Now generate the symbol file.
+ eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> conftest.$ac_ext'
+
+ cat <<EOF >> conftest.$ac_ext
+#if defined (__STDC__) && __STDC__
+# define lt_ptr_t void *
+#else
+# define lt_ptr_t char *
+# define const
+#endif
+
+/* The mapping between symbol names and symbols. */
+const struct {
+ const char *name;
+ lt_ptr_t address;
+}
+lt_preloaded_symbols[] =
+{
+EOF
+ $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (lt_ptr_t) \&\2},/" < "$nlist" | grep -v main >> conftest.$ac_ext
+ cat <<\EOF >> conftest.$ac_ext
+ {0, (lt_ptr_t) 0}
+};
+
+#ifdef __cplusplus
+}
+#endif
+EOF
+ # Now try linking the two files.
+ mv conftest.$ac_objext conftstm.$ac_objext
+ lt_save_LIBS="$LIBS"
+ lt_save_CFLAGS="$CFLAGS"
+ LIBS="conftstm.$ac_objext"
+ CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag"
+ if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && test -s conftest${ac_exeext}; then
+ pipe_works=yes
+ fi
+ LIBS="$lt_save_LIBS"
+ CFLAGS="$lt_save_CFLAGS"
+ else
+ echo "cannot find nm_test_func in $nlist" >&5
+ fi
+ else
+ echo "cannot find nm_test_var in $nlist" >&5
+ fi
+ else
+ echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5
+ fi
+ else
+ echo "$progname: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ fi
+ rm -f conftest* conftst*
+
+ # Do not use the global_symbol_pipe unless it works.
+ if test "$pipe_works" = yes; then
+ break
+ else
+ lt_cv_sys_global_symbol_pipe=
+ fi
+done
+
+fi
+
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+ lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+ { echo "$as_me:$LINENO: result: failed" >&5
+echo "${ECHO_T}failed" >&6; }
+else
+ { echo "$as_me:$LINENO: result: ok" >&5
+echo "${ECHO_T}ok" >&6; }
+fi
+
+
+{ echo "$as_me:$LINENO: checking whether libtool supports -dlopen/-dlpreopen" >&5
+echo $ECHO_N "checking whether libtool supports -dlopen/-dlpreopen... $ECHO_C" >&6; }
+if test "${libltdl_cv_preloaded_symbols+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$lt_cv_sys_global_symbol_pipe"; then
+ libltdl_cv_preloaded_symbols=yes
+ else
+ libltdl_cv_preloaded_symbols=no
+ fi
+
+fi
+{ echo "$as_me:$LINENO: result: $libltdl_cv_preloaded_symbols" >&5
+echo "${ECHO_T}$libltdl_cv_preloaded_symbols" >&6; }
+if test x"$libltdl_cv_preloaded_symbols" = xyes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_PRELOADED_SYMBOLS 1
+_ACEOF
+
+fi
+
+LIBADD_DL=
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+{ echo "$as_me:$LINENO: checking for shl_load" >&5
+echo $ECHO_N "checking for shl_load... $ECHO_C" >&6; }
+if test "${ac_cv_func_shl_load+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define shl_load to an innocuous variant, in case <limits.h> declares shl_load.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define shl_load innocuous_shl_load
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char shl_load (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef shl_load
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char shl_load ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_shl_load || defined __stub___shl_load
+choke me
+#endif
+
+int
+main ()
+{
+return shl_load ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_shl_load=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_shl_load=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5
+echo "${ECHO_T}$ac_cv_func_shl_load" >&6; }
+if test $ac_cv_func_shl_load = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_SHL_LOAD 1
+_ACEOF
+
+else
+ { echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5
+echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6; }
+if test "${ac_cv_lib_dld_shl_load+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char shl_load ();
+int
+main ()
+{
+return shl_load ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dld_shl_load=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_dld_shl_load=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6; }
+if test $ac_cv_lib_dld_shl_load = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_SHL_LOAD 1
+_ACEOF
+
+ LIBADD_DL="$LIBADD_DL -ldld"
+else
+ { echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; }
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dl_dlopen=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_dl_dlopen=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; }
+if test $ac_cv_lib_dl_dlopen = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_LIBDL 1
+_ACEOF
+
+ LIBADD_DL="-ldl" libltdl_cv_lib_dl_dlopen="yes"
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#if HAVE_DLFCN_H
+# include <dlfcn.h>
+#endif
+
+int
+main ()
+{
+dlopen(0, 0);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_LIBDL 1
+_ACEOF
+ libltdl_cv_func_dlopen="yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ { echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5
+echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6; }
+if test "${ac_cv_lib_svld_dlopen+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsvld $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_svld_dlopen=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_svld_dlopen=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6; }
+if test $ac_cv_lib_svld_dlopen = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_LIBDL 1
+_ACEOF
+
+ LIBADD_DL="-lsvld" libltdl_cv_func_dlopen="yes"
+else
+ { echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5
+echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6; }
+if test "${ac_cv_lib_dld_dld_link+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dld_link ();
+int
+main ()
+{
+return dld_link ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dld_dld_link=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_dld_dld_link=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6; }
+if test $ac_cv_lib_dld_dld_link = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_DLD 1
+_ACEOF
+
+ LIBADD_DL="$LIBADD_DL -ldld"
+else
+ { echo "$as_me:$LINENO: checking for _dyld_func_lookup" >&5
+echo $ECHO_N "checking for _dyld_func_lookup... $ECHO_C" >&6; }
+if test "${ac_cv_func__dyld_func_lookup+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define _dyld_func_lookup to an innocuous variant, in case <limits.h> declares _dyld_func_lookup.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define _dyld_func_lookup innocuous__dyld_func_lookup
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char _dyld_func_lookup (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef _dyld_func_lookup
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char _dyld_func_lookup ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub__dyld_func_lookup || defined __stub____dyld_func_lookup
+choke me
+#endif
+
+int
+main ()
+{
+return _dyld_func_lookup ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func__dyld_func_lookup=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func__dyld_func_lookup=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func__dyld_func_lookup" >&5
+echo "${ECHO_T}$ac_cv_func__dyld_func_lookup" >&6; }
+if test $ac_cv_func__dyld_func_lookup = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_DYLD 1
+_ACEOF
+
+fi
+
+
+fi
+
+
+fi
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+
+fi
+
+
+fi
+
+
+fi
+
+
+if test x"$libltdl_cv_func_dlopen" = xyes || test x"$libltdl_cv_lib_dl_dlopen" = xyes
+then
+ lt_save_LIBS="$LIBS"
+ LIBS="$LIBS $LIBADD_DL"
+
+for ac_func in dlerror
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+ LIBS="$lt_save_LIBS"
+fi
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+{ echo "$as_me:$LINENO: checking for _ prefix in compiled symbols" >&5
+echo $ECHO_N "checking for _ prefix in compiled symbols... $ECHO_C" >&6; }
+if test "${ac_cv_sys_symbol_underscore+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_sys_symbol_underscore=no
+ cat > conftest.$ac_ext <<EOF
+void nm_test_func(){}
+int main(){nm_test_func;return 0;}
+EOF
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ # Now try to grab the symbols.
+ ac_nlist=conftest.nm
+ if { (eval echo "$as_me:$LINENO: \"$NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $ac_nlist\"") >&5
+ (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $ac_nlist) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && test -s "$ac_nlist"; then
+ # See whether the symbols have a leading underscore.
+ if grep '^. _nm_test_func' "$ac_nlist" >/dev/null; then
+ ac_cv_sys_symbol_underscore=yes
+ else
+ if grep '^. nm_test_func ' "$ac_nlist" >/dev/null; then
+ :
+ else
+ echo "configure: cannot find nm_test_func in $ac_nlist" >&5
+ fi
+ fi
+ else
+ echo "configure: cannot run $lt_cv_sys_global_symbol_pipe" >&5
+ fi
+ else
+ echo "configure: failed program was:" >&5
+ cat conftest.c >&5
+ fi
+ rm -rf conftest*
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_sys_symbol_underscore" >&5
+echo "${ECHO_T}$ac_cv_sys_symbol_underscore" >&6; }
+
+
+if test x"$ac_cv_sys_symbol_underscore" = xyes; then
+ if test x"$libltdl_cv_func_dlopen" = xyes ||
+ test x"$libltdl_cv_lib_dl_dlopen" = xyes ; then
+ { echo "$as_me:$LINENO: checking whether we have to add an underscore for dlsym" >&5
+echo $ECHO_N "checking whether we have to add an underscore for dlsym... $ECHO_C" >&6; }
+if test "${libltdl_cv_need_uscore+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ libltdl_cv_need_uscore=unknown
+ save_LIBS="$LIBS"
+ LIBS="$LIBS $LIBADD_DL"
+ if test "$cross_compiling" = yes; then :
+ libltdl_cv_need_uscore=cross
+else
+ lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+ lt_status=$lt_dlunknown
+ cat > conftest.$ac_ext <<EOF
+#line 10292 "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+# define LT_DLGLOBAL RTLD_GLOBAL
+#else
+# ifdef DL_GLOBAL
+# define LT_DLGLOBAL DL_GLOBAL
+# else
+# define LT_DLGLOBAL 0
+# endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+ find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+# ifdef RTLD_LAZY
+# define LT_DLLAZY_OR_NOW RTLD_LAZY
+# else
+# ifdef DL_LAZY
+# define LT_DLLAZY_OR_NOW DL_LAZY
+# else
+# ifdef RTLD_NOW
+# define LT_DLLAZY_OR_NOW RTLD_NOW
+# else
+# ifdef DL_NOW
+# define LT_DLLAZY_OR_NOW DL_NOW
+# else
+# define LT_DLLAZY_OR_NOW 0
+# endif
+# endif
+# endif
+# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
+
+void fnord() { int i=42;}
+int main ()
+{
+ void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+ int status = $lt_dlunknown;
+
+ if (self)
+ {
+ if (dlsym (self,"fnord")) status = $lt_dlno_uscore;
+ else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+ /* dlclose (self); */
+ }
+ else
+ puts (dlerror ());
+
+ exit (status);
+}
+EOF
+ if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+ (./conftest; exit; ) >&5 2>/dev/null
+ lt_status=$?
+ case x$lt_status in
+ x$lt_dlno_uscore) libltdl_cv_need_uscore=no ;;
+ x$lt_dlneed_uscore) libltdl_cv_need_uscore=yes ;;
+ x$lt_dlunknown|x*) ;;
+ esac
+ else :
+ # compilation failed
+
+ fi
+fi
+rm -fr conftest*
+
+ LIBS="$save_LIBS"
+
+fi
+{ echo "$as_me:$LINENO: result: $libltdl_cv_need_uscore" >&5
+echo "${ECHO_T}$libltdl_cv_need_uscore" >&6; }
+ fi
+fi
+
+if test x"$libltdl_cv_need_uscore" = xyes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define NEED_USCORE 1
+_ACEOF
+
+fi
+
+
+{ echo "$as_me:$LINENO: checking whether deplibs are loaded by dlopen" >&5
+echo $ECHO_N "checking whether deplibs are loaded by dlopen... $ECHO_C" >&6; }
+if test "${libltdl_cv_sys_dlopen_deplibs+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # PORTME does your system automatically load deplibs for dlopen?
+ # or its logical equivalent (e.g. shl_load for HP-UX < 11)
+ # For now, we just catch OSes we know something about -- in the
+ # future, we'll try test this programmatically.
+ libltdl_cv_sys_dlopen_deplibs=unknown
+ case "$host_os" in
+ aix3*|aix4.1.*|aix4.2.*)
+ # Unknown whether this is true for these versions of AIX, but
+ # we want this `case' here to explicitly catch those versions.
+ libltdl_cv_sys_dlopen_deplibs=unknown
+ ;;
+ aix[45]*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ darwin*)
+ # Assuming the user has installed a libdl from somewhere, this is true
+ # If you are looking for one http://www.opendarwin.org/projects/dlcompat
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ gnu* | linux* | kfreebsd*-gnu | knetbsd*-gnu)
+ # GNU and its variants, using gnu ld.so (Glibc)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ hpux10*|hpux11*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ interix*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ irix[12345]*|irix6.[01]*)
+ # Catch all versions of IRIX before 6.2, and indicate that we don't
+ # know how it worked for any of those versions.
+ libltdl_cv_sys_dlopen_deplibs=unknown
+ ;;
+ irix*)
+ # The case above catches anything before 6.2, and it's known that
+ # at 6.2 and later dlopen does load deplibs.
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ netbsd*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ openbsd*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ osf[1234]*)
+ # dlopen did load deplibs (at least at 4.x), but until the 5.x series,
+ # it did *not* use an RPATH in a shared library to find objects the
+ # library depends on, so we explicitly say `no'.
+ libltdl_cv_sys_dlopen_deplibs=no
+ ;;
+ osf5.0|osf5.0a|osf5.1)
+ # dlopen *does* load deplibs and with the right loader patch applied
+ # it even uses RPATH in a shared library to search for shared objects
+ # that the library depends on, but there's no easy way to know if that
+ # patch is installed. Since this is the case, all we can really
+ # say is unknown -- it depends on the patch being installed. If
+ # it is, this changes to `yes'. Without it, it would be `no'.
+ libltdl_cv_sys_dlopen_deplibs=unknown
+ ;;
+ osf*)
+ # the two cases above should catch all versions of osf <= 5.1. Read
+ # the comments above for what we know about them.
+ # At > 5.1, deplibs are loaded *and* any RPATH in a shared library
+ # is used to find them so we can finally say `yes'.
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ solaris*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ libltdl_cv_sys_dlopen_deplibs=yes
+ ;;
+ esac
+
+fi
+{ echo "$as_me:$LINENO: result: $libltdl_cv_sys_dlopen_deplibs" >&5
+echo "${ECHO_T}$libltdl_cv_sys_dlopen_deplibs" >&6; }
+if test "$libltdl_cv_sys_dlopen_deplibs" != yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define LTDL_DLOPEN_DEPLIBS 1
+_ACEOF
+
+fi
+
+
+for ac_header in argz.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+{ echo "$as_me:$LINENO: checking for error_t" >&5
+echo $ECHO_N "checking for error_t... $ECHO_C" >&6; }
+if test "${ac_cv_type_error_t+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#if HAVE_ARGZ_H
+# include <argz.h>
+#endif
+
+typedef error_t ac__type_new_;
+int
+main ()
+{
+if ((ac__type_new_ *) 0)
+ return 0;
+if (sizeof (ac__type_new_))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_error_t=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_type_error_t=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_type_error_t" >&5
+echo "${ECHO_T}$ac_cv_type_error_t" >&6; }
+if test $ac_cv_type_error_t = yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_ERROR_T 1
+_ACEOF
+
+
+else
+
+cat >>confdefs.h <<\_ACEOF
+#define error_t int
+_ACEOF
+
+fi
+
+
+
+
+
+
+
+for ac_func in argz_append argz_create_sep argz_insert argz_next argz_stringify
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+for ac_header in assert.h ctype.h errno.h malloc.h memory.h stdlib.h \
+ stdio.h unistd.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+for ac_header in dl.h sys/dl.h dld.h mach-o/dyld.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+for ac_header in string.h strings.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+ break
+fi
+
+done
+
+
+
+
+for ac_func in strchr index
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+ break
+fi
+done
+
+
+
+for ac_func in strrchr rindex
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+ break
+fi
+done
+
+
+
+for ac_func in memcpy bcopy
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+ break
+fi
+done
+
+
+
+for ac_func in memmove strcmp
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+for ac_func in closedir opendir readdir
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+{ echo "$as_me:$LINENO: checking tool compatibility" >&5
+echo $ECHO_N "checking tool compatibility... $ECHO_C" >&6; }
+
+ICC=no
+IXX=no
+case $CC in
+ icc*|icpc*)
+ ICC=yes
+ IXX=yes
+ ;;
+ *)
+ ;;
+esac
+
+if test "$GCC" != "yes" && test "$ICC" != "yes"
+then
+ { { echo "$as_me:$LINENO: error: gcc|icc required but not found" >&5
+echo "$as_me: error: gcc|icc required but not found" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+if test "$GXX" != "yes" && test "$IXX" != "yes"
+then
+ { { echo "$as_me:$LINENO: error: g++|clang++|icc required but not found" >&5
+echo "$as_me: error: g++|clang++|icc required but not found" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+if test "$GCC" = "yes"
+then
+ cat >conftest.$ac_ext <<_ACEOF
+#if !defined(__GNUC__) || __GNUC__ < 3
+#error Unsupported GCC version
+#endif
+
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ { { echo "$as_me:$LINENO: error: gcc 3.x required, but you have a lower version" >&5
+echo "$as_me: error: gcc 3.x required, but you have a lower version" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+if test -z "$llvm_cv_gnu_make_command"
+then
+ { { echo "$as_me:$LINENO: error: GNU Make required but not found" >&5
+echo "$as_me: error: GNU Make required but not found" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+{ echo "$as_me:$LINENO: result: ok" >&5
+echo "${ECHO_T}ok" >&6; }
+
+{ echo "$as_me:$LINENO: checking optional compiler flags" >&5
+echo $ECHO_N "checking optional compiler flags... $ECHO_C" >&6; }
+NO_VARIADIC_MACROS=`$CXX -Werror -Wno-variadic-macros -fsyntax-only -xc /dev/null 2>/dev/null && echo -Wno-variadic-macros`
+
+NO_MISSING_FIELD_INITIALIZERS=`$CXX -Werror -Wno-missing-field-initializers -fsyntax-only -xc /dev/null 2>/dev/null && echo -Wno-missing-field-initializers`
+
+COVERED_SWITCH_DEFAULT=`$CXX -Werror -Wcovered-switch-default -fsyntax-only -xc /dev/null 2>/dev/null && echo -Wcovered-switch-default`
+
+{ echo "$as_me:$LINENO: result: $NO_VARIADIC_MACROS $NO_MISSING_FIELD_INITIALIZERS $COVERED_SWITCH_DEFAULT" >&5
+echo "${ECHO_T}$NO_VARIADIC_MACROS $NO_MISSING_FIELD_INITIALIZERS $COVERED_SWITCH_DEFAULT" >&6; }
+
+
+
+{ echo "$as_me:$LINENO: checking for sin in -lm" >&5
+echo $ECHO_N "checking for sin in -lm... $ECHO_C" >&6; }
+if test "${ac_cv_lib_m_sin+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char sin ();
+int
+main ()
+{
+return sin ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_m_sin=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_m_sin=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_m_sin" >&5
+echo "${ECHO_T}$ac_cv_lib_m_sin" >&6; }
+if test $ac_cv_lib_m_sin = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBM 1
+_ACEOF
+
+ LIBS="-lm $LIBS"
+
+fi
+
+if test "$llvm_cv_os_type" = "MingW" ; then
+
+{ echo "$as_me:$LINENO: checking for main in -limagehlp" >&5
+echo $ECHO_N "checking for main in -limagehlp... $ECHO_C" >&6; }
+if test "${ac_cv_lib_imagehlp_main+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-limagehlp $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+
+int
+main ()
+{
+return main ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_imagehlp_main=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_imagehlp_main=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_imagehlp_main" >&5
+echo "${ECHO_T}$ac_cv_lib_imagehlp_main" >&6; }
+if test $ac_cv_lib_imagehlp_main = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBIMAGEHLP 1
+_ACEOF
+
+ LIBS="-limagehlp $LIBS"
+
+fi
+
+
+{ echo "$as_me:$LINENO: checking for main in -lpsapi" >&5
+echo $ECHO_N "checking for main in -lpsapi... $ECHO_C" >&6; }
+if test "${ac_cv_lib_psapi_main+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpsapi $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+
+int
+main ()
+{
+return main ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_psapi_main=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_psapi_main=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_psapi_main" >&5
+echo "${ECHO_T}$ac_cv_lib_psapi_main" >&6; }
+if test $ac_cv_lib_psapi_main = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBPSAPI 1
+_ACEOF
+
+ LIBS="-lpsapi $LIBS"
+
+fi
+
+fi
+
+{ echo "$as_me:$LINENO: checking for library containing dlopen" >&5
+echo $ECHO_N "checking for library containing dlopen... $ECHO_C" >&6; }
+if test "${ac_cv_search_dlopen+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' dl; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_dlopen=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_dlopen+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_dlopen+set}" = set; then
+ :
+else
+ ac_cv_search_dlopen=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_dlopen" >&5
+echo "${ECHO_T}$ac_cv_search_dlopen" >&6; }
+ac_res=$ac_cv_search_dlopen
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_DLOPEN 1
+_ACEOF
+
+else
+ { echo "$as_me:$LINENO: WARNING: dlopen() not found - disabling plugin support" >&5
+echo "$as_me: WARNING: dlopen() not found - disabling plugin support" >&2;}
+fi
+
+
+if test "$llvm_cv_enable_libffi" = "yes" ; then
+ { echo "$as_me:$LINENO: checking for library containing ffi_call" >&5
+echo $ECHO_N "checking for library containing ffi_call... $ECHO_C" >&6; }
+if test "${ac_cv_search_ffi_call+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ffi_call ();
+int
+main ()
+{
+return ffi_call ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' ffi; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_ffi_call=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_ffi_call+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_ffi_call+set}" = set; then
+ :
+else
+ ac_cv_search_ffi_call=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_ffi_call" >&5
+echo "${ECHO_T}$ac_cv_search_ffi_call" >&6; }
+ac_res=$ac_cv_search_ffi_call
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_FFI_CALL 1
+_ACEOF
+
+else
+ { { echo "$as_me:$LINENO: error: libffi not found - configure without --enable-libffi to compile without it" >&5
+echo "$as_me: error: libffi not found - configure without --enable-libffi to compile without it" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+fi
+
+{ echo "$as_me:$LINENO: checking for library containing mallinfo" >&5
+echo $ECHO_N "checking for library containing mallinfo... $ECHO_C" >&6; }
+if test "${ac_cv_search_mallinfo+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char mallinfo ();
+int
+main ()
+{
+return mallinfo ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' malloc; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_mallinfo=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_mallinfo+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_mallinfo+set}" = set; then
+ :
+else
+ ac_cv_search_mallinfo=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_mallinfo" >&5
+echo "${ECHO_T}$ac_cv_search_mallinfo" >&6; }
+ac_res=$ac_cv_search_mallinfo
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_MALLINFO 1
+_ACEOF
+
+fi
+
+
+if test "$LLVM_ENABLE_THREADS" -eq 1 && test "$ENABLE_PTHREADS" -eq 1 ; then
+
+{ echo "$as_me:$LINENO: checking for pthread_mutex_init in -lpthread" >&5
+echo $ECHO_N "checking for pthread_mutex_init in -lpthread... $ECHO_C" >&6; }
+if test "${ac_cv_lib_pthread_pthread_mutex_init+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpthread $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char pthread_mutex_init ();
+int
+main ()
+{
+return pthread_mutex_init ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_pthread_pthread_mutex_init=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_pthread_pthread_mutex_init=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthread_pthread_mutex_init" >&5
+echo "${ECHO_T}$ac_cv_lib_pthread_pthread_mutex_init" >&6; }
+if test $ac_cv_lib_pthread_pthread_mutex_init = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBPTHREAD 1
+_ACEOF
+
+ LIBS="-lpthread $LIBS"
+
+fi
+
+ { echo "$as_me:$LINENO: checking for library containing pthread_mutex_lock" >&5
+echo $ECHO_N "checking for library containing pthread_mutex_lock... $ECHO_C" >&6; }
+if test "${ac_cv_search_pthread_mutex_lock+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char pthread_mutex_lock ();
+int
+main ()
+{
+return pthread_mutex_lock ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' pthread; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_pthread_mutex_lock=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_pthread_mutex_lock+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_pthread_mutex_lock+set}" = set; then
+ :
+else
+ ac_cv_search_pthread_mutex_lock=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_pthread_mutex_lock" >&5
+echo "${ECHO_T}$ac_cv_search_pthread_mutex_lock" >&6; }
+ac_res=$ac_cv_search_pthread_mutex_lock
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_PTHREAD_MUTEX_LOCK 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for library containing pthread_rwlock_init" >&5
+echo $ECHO_N "checking for library containing pthread_rwlock_init... $ECHO_C" >&6; }
+if test "${ac_cv_search_pthread_rwlock_init+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char pthread_rwlock_init ();
+int
+main ()
+{
+return pthread_rwlock_init ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' pthread; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_pthread_rwlock_init=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_pthread_rwlock_init+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_pthread_rwlock_init+set}" = set; then
+ :
+else
+ ac_cv_search_pthread_rwlock_init=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_pthread_rwlock_init" >&5
+echo "${ECHO_T}$ac_cv_search_pthread_rwlock_init" >&6; }
+ac_res=$ac_cv_search_pthread_rwlock_init
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_PTHREAD_RWLOCK_INIT 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for library containing pthread_getspecific" >&5
+echo $ECHO_N "checking for library containing pthread_getspecific... $ECHO_C" >&6; }
+if test "${ac_cv_search_pthread_getspecific+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char pthread_getspecific ();
+int
+main ()
+{
+return pthread_getspecific ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' pthread; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_pthread_getspecific=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_pthread_getspecific+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_pthread_getspecific+set}" = set; then
+ :
+else
+ ac_cv_search_pthread_getspecific=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_pthread_getspecific" >&5
+echo "${ECHO_T}$ac_cv_search_pthread_getspecific" >&6; }
+ac_res=$ac_cv_search_pthread_getspecific
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_PTHREAD_GETSPECIFIC 1
+_ACEOF
+
+fi
+
+fi
+
+
+# Check whether --with-udis86 was given.
+if test "${with_udis86+set}" = set; then
+ withval=$with_udis86;
+ USE_UDIS86=1
+
+ case "$withval" in
+ /usr/lib|yes) ;;
+ *) LDFLAGS="$LDFLAGS -L${withval}" ;;
+ esac
+
+{ echo "$as_me:$LINENO: checking for ud_init in -ludis86" >&5
+echo $ECHO_N "checking for ud_init in -ludis86... $ECHO_C" >&6; }
+if test "${ac_cv_lib_udis86_ud_init+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ludis86 $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ud_init ();
+int
+main ()
+{
+return ud_init ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_udis86_ud_init=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_udis86_ud_init=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_udis86_ud_init" >&5
+echo "${ECHO_T}$ac_cv_lib_udis86_ud_init" >&6; }
+if test $ac_cv_lib_udis86_ud_init = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBUDIS86 1
+_ACEOF
+
+ LIBS="-ludis86 $LIBS"
+
+else
+
+ echo "Error! You need to have libudis86 around."
+ exit -1
+
+fi
+
+
+else
+ USE_UDIS86=0
+
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define USE_UDIS86 $USE_UDIS86
+_ACEOF
+
+
+
+# Check whether --with-oprofile was given.
+if test "${with_oprofile+set}" = set; then
+ withval=$with_oprofile;
+ USE_OPROFILE=1
+
+ case "$withval" in
+ /usr|yes) llvm_cv_oppath=/usr/lib/oprofile ;;
+ no) llvm_cv_oppath=
+ USE_OPROFILE=0
+ ;;
+ *) llvm_cv_oppath="${withval}/lib/oprofile"
+ CPPFLAGS="-I${withval}/include";;
+ esac
+ case $llvm_cv_os_type in
+ Linux)
+ if test -n "$llvm_cv_oppath" ; then
+ LIBS="$LIBS -lopagent -L${llvm_cv_oppath} -Wl,-rpath,${llvm_cv_oppath}"
+ { echo "$as_me:$LINENO: checking for library containing bfd_init" >&5
+echo $ECHO_N "checking for library containing bfd_init... $ECHO_C" >&6; }
+if test "${ac_cv_search_bfd_init+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char bfd_init ();
+int
+main ()
+{
+return bfd_init ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' bfd; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_bfd_init=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_bfd_init+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_bfd_init+set}" = set; then
+ :
+else
+ ac_cv_search_bfd_init=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_bfd_init" >&5
+echo "${ECHO_T}$ac_cv_search_bfd_init" >&6; }
+ac_res=$ac_cv_search_bfd_init
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+fi
+
+ { echo "$as_me:$LINENO: checking for library containing op_open_agent" >&5
+echo $ECHO_N "checking for library containing op_open_agent... $ECHO_C" >&6; }
+if test "${ac_cv_search_op_open_agent+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char op_open_agent ();
+int
+main ()
+{
+return op_open_agent ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' opagent; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_op_open_agent=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_op_open_agent+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_op_open_agent+set}" = set; then
+ :
+else
+ ac_cv_search_op_open_agent=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_op_open_agent" >&5
+echo "${ECHO_T}$ac_cv_search_op_open_agent" >&6; }
+ac_res=$ac_cv_search_op_open_agent
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+else
+
+ echo "Error! You need to have libopagent around."
+ exit -1
+
+fi
+
+ if test "${ac_cv_header_opagent_h+set}" = set; then
+ { echo "$as_me:$LINENO: checking for opagent.h" >&5
+echo $ECHO_N "checking for opagent.h... $ECHO_C" >&6; }
+if test "${ac_cv_header_opagent_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_opagent_h" >&5
+echo "${ECHO_T}$ac_cv_header_opagent_h" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking opagent.h usability" >&5
+echo $ECHO_N "checking opagent.h usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <opagent.h>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking opagent.h presence" >&5
+echo $ECHO_N "checking opagent.h presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <opagent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: opagent.h: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: opagent.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: opagent.h: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: opagent.h: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: opagent.h: present but cannot be compiled" >&5
+echo "$as_me: WARNING: opagent.h: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: opagent.h: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: opagent.h: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: opagent.h: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: opagent.h: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: opagent.h: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: opagent.h: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: opagent.h: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: opagent.h: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: opagent.h: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: opagent.h: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for opagent.h" >&5
+echo $ECHO_N "checking for opagent.h... $ECHO_C" >&6; }
+if test "${ac_cv_header_opagent_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_header_opagent_h=$ac_header_preproc
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_opagent_h" >&5
+echo "${ECHO_T}$ac_cv_header_opagent_h" >&6; }
+
+fi
+if test $ac_cv_header_opagent_h = yes; then
+ :
+else
+
+ echo "Error! You need to have opagent.h around."
+ exit -1
+
+fi
+
+
+ fi ;;
+ *)
+ { { echo "$as_me:$LINENO: error: OProfile support is available on Linux only." >&5
+echo "$as_me: error: OProfile support is available on Linux only." >&2;}
+ { (exit 1); exit 1; }; } ;;
+ esac
+
+else
+
+ USE_OPROFILE=0
+
+
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_USE_OPROFILE $USE_OPROFILE
+_ACEOF
+
+
+
+# Check whether --with-intel-jitevents was given.
+if test "${with_intel_jitevents+set}" = set; then
+ withval=$with_intel_jitevents;
+ case $llvm_cv_os_type in
+ Linux|Win32|Cygwin|MingW) ;;
+ *)
+ { { echo "$as_me:$LINENO: error:
+ Intel JIT API support is available on Linux and Windows only.\"" >&5
+echo "$as_me: error:
+ Intel JIT API support is available on Linux and Windows only.\"" >&2;}
+ { (exit 1); exit 1; }; } ;;
+ esac
+
+ USE_INTEL_JITEVENTS=1
+
+ case "$llvm_cv_target_arch" in
+ x86) llvm_intel_jitevents_archdir="lib32";;
+ x86_64) llvm_intel_jitevents_archdir="lib64";;
+ *) echo "Target architecture $llvm_cv_target_arch does not support Intel JIT Events API"
+ exit -1;;
+ esac
+ INTEL_JITEVENTS_INCDIR="/opt/intel/vtune_amplifier_xe_2011/include"
+ INTEL_JITEVENTS_LIBDIR="/opt/intel/vtune_amplifier_xe_2011/$llvm_intel_jitevents_archdir"
+ case "$withval" in
+ /* | [A-Za-z]:[\\/]*) INTEL_JITEVENTS_INCDIR=$withval/include
+ INTEL_JITEVENTS_LIBDIR=$withval/$llvm_intel_jitevents_archdir ;;
+ *) ;;
+ esac
+
+
+
+
+ LIBS="$LIBS -L${INTEL_JITEVENTS_LIBDIR}"
+ CPPFLAGS="$CPPFLAGS -I$INTEL_JITEVENTS_INCDIR"
+
+ { echo "$as_me:$LINENO: checking for library containing iJIT_IsProfilingActive" >&5
+echo $ECHO_N "checking for library containing iJIT_IsProfilingActive... $ECHO_C" >&6; }
+if test "${ac_cv_search_iJIT_IsProfilingActive+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char iJIT_IsProfilingActive ();
+int
+main ()
+{
+return iJIT_IsProfilingActive ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' jitprofiling; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_iJIT_IsProfilingActive=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_iJIT_IsProfilingActive+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_iJIT_IsProfilingActive+set}" = set; then
+ :
+else
+ ac_cv_search_iJIT_IsProfilingActive=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_iJIT_IsProfilingActive" >&5
+echo "${ECHO_T}$ac_cv_search_iJIT_IsProfilingActive" >&6; }
+ac_res=$ac_cv_search_iJIT_IsProfilingActive
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+else
+
+ echo "Error! Cannot find libjitprofiling.a. Please check path specified in flag --with-intel-jitevents"
+ exit -1
+
+fi
+
+ if test "${ac_cv_header_jitprofiling_h+set}" = set; then
+ { echo "$as_me:$LINENO: checking for jitprofiling.h" >&5
+echo $ECHO_N "checking for jitprofiling.h... $ECHO_C" >&6; }
+if test "${ac_cv_header_jitprofiling_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_jitprofiling_h" >&5
+echo "${ECHO_T}$ac_cv_header_jitprofiling_h" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking jitprofiling.h usability" >&5
+echo $ECHO_N "checking jitprofiling.h usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <jitprofiling.h>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking jitprofiling.h presence" >&5
+echo $ECHO_N "checking jitprofiling.h presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <jitprofiling.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: jitprofiling.h: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: jitprofiling.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: jitprofiling.h: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: jitprofiling.h: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: jitprofiling.h: present but cannot be compiled" >&5
+echo "$as_me: WARNING: jitprofiling.h: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: jitprofiling.h: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: jitprofiling.h: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: jitprofiling.h: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: jitprofiling.h: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: jitprofiling.h: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: jitprofiling.h: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: jitprofiling.h: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: jitprofiling.h: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: jitprofiling.h: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: jitprofiling.h: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for jitprofiling.h" >&5
+echo $ECHO_N "checking for jitprofiling.h... $ECHO_C" >&6; }
+if test "${ac_cv_header_jitprofiling_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_header_jitprofiling_h=$ac_header_preproc
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_jitprofiling_h" >&5
+echo "${ECHO_T}$ac_cv_header_jitprofiling_h" >&6; }
+
+fi
+if test $ac_cv_header_jitprofiling_h = yes; then
+ :
+else
+
+ echo "Error! Cannot find jitprofiling.h. Please check path specified in flag --with-intel-jitevents"
+ exit -1
+
+fi
+
+
+
+
+else
+
+ USE_INTEL_JITEVENTS=0
+
+
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_USE_INTEL_JITEVENTS $USE_INTEL_JITEVENTS
+_ACEOF
+
+
+for ac_prog in xml2-config
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_XML2CONFIG+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$XML2CONFIG"; then
+ ac_cv_prog_XML2CONFIG="$XML2CONFIG" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; }; then
+ ac_cv_prog_XML2CONFIG="$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+XML2CONFIG=$ac_cv_prog_XML2CONFIG
+if test -n "$XML2CONFIG"; then
+ { echo "$as_me:$LINENO: result: $XML2CONFIG" >&5
+echo "${ECHO_T}$XML2CONFIG" >&6; }
+else
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+ test -n "$XML2CONFIG" && break
+done
+
+
+{ echo "$as_me:$LINENO: checking for libxml2 includes" >&5
+echo $ECHO_N "checking for libxml2 includes... $ECHO_C" >&6; }
+if test "x$XML2CONFIG" = "x"; then
+ { echo "$as_me:$LINENO: result: xml2-config not found" >&5
+echo "${ECHO_T}xml2-config not found" >&6; }
+else
+ LIBXML2_INC=`$XML2CONFIG --cflags`
+ { echo "$as_me:$LINENO: result: $LIBXML2_INC" >&5
+echo "${ECHO_T}$LIBXML2_INC" >&6; }
+ { echo "$as_me:$LINENO: checking for xmlReadFile in -lxml2" >&5
+echo $ECHO_N "checking for xmlReadFile in -lxml2... $ECHO_C" >&6; }
+if test "${ac_cv_lib_xml2_xmlReadFile+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lxml2 $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char xmlReadFile ();
+int
+main ()
+{
+return xmlReadFile ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_xml2_xmlReadFile=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_xml2_xmlReadFile=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_xml2_xmlReadFile" >&5
+echo "${ECHO_T}$ac_cv_lib_xml2_xmlReadFile" >&6; }
+if test $ac_cv_lib_xml2_xmlReadFile = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define CLANG_HAVE_LIBXML 1
+_ACEOF
+
+ LIBXML2_LIBS="-lxml2"
+fi
+
+fi
+
+
+
+
+
+
+
+
+
+ac_header_dirent=no
+for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do
+ as_ac_Header=`echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5
+echo $ECHO_N "checking for $ac_hdr that defines DIR... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/types.h>
+#include <$ac_hdr>
+
+int
+main ()
+{
+if ((DIR *) 0)
+return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_Header=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_Header=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_hdr" | $as_tr_cpp` 1
+_ACEOF
+
+ac_header_dirent=$ac_hdr; break
+fi
+
+done
+# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix.
+if test $ac_header_dirent = dirent.h; then
+ { echo "$as_me:$LINENO: checking for library containing opendir" >&5
+echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; }
+if test "${ac_cv_search_opendir+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char opendir ();
+int
+main ()
+{
+return opendir ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' dir; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_opendir=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_opendir+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_opendir+set}" = set; then
+ :
+else
+ ac_cv_search_opendir=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5
+echo "${ECHO_T}$ac_cv_search_opendir" >&6; }
+ac_res=$ac_cv_search_opendir
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+fi
+
+else
+ { echo "$as_me:$LINENO: checking for library containing opendir" >&5
+echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; }
+if test "${ac_cv_search_opendir+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_func_search_save_LIBS=$LIBS
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char opendir ();
+int
+main ()
+{
+return opendir ();
+ ;
+ return 0;
+}
+_ACEOF
+for ac_lib in '' x; do
+ if test -z "$ac_lib"; then
+ ac_res="none required"
+ else
+ ac_res=-l$ac_lib
+ LIBS="-l$ac_lib $ac_func_search_save_LIBS"
+ fi
+ rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_search_opendir=$ac_res
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext
+ if test "${ac_cv_search_opendir+set}" = set; then
+ break
+fi
+done
+if test "${ac_cv_search_opendir+set}" = set; then
+ :
+else
+ ac_cv_search_opendir=no
+fi
+rm conftest.$ac_ext
+LIBS=$ac_func_search_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5
+echo "${ECHO_T}$ac_cv_search_opendir" >&6; }
+ac_res=$ac_cv_search_opendir
+if test "$ac_res" != no; then
+ test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
+
+fi
+
+fi
+
+{ echo "$as_me:$LINENO: checking for MAP_ANONYMOUS vs. MAP_ANON" >&5
+echo $ECHO_N "checking for MAP_ANONYMOUS vs. MAP_ANON... $ECHO_C" >&6; }
+if test "${ac_cv_header_mmap_anon+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/mman.h>
+#include <unistd.h>
+#include <fcntl.h>
+int
+main ()
+{
+mmap (0, 1, PROT_READ, MAP_ANONYMOUS, -1, 0); return (0);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_header_mmap_anon=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_header_mmap_anon=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_mmap_anon" >&5
+echo "${ECHO_T}$ac_cv_header_mmap_anon" >&6; }
+if test "$ac_cv_header_mmap_anon" = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_MMAP_ANONYMOUS 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking whether stat file-mode macros are broken" >&5
+echo $ECHO_N "checking whether stat file-mode macros are broken... $ECHO_C" >&6; }
+if test "${ac_cv_header_stat_broken+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#if defined S_ISBLK && defined S_IFDIR
+# if S_ISBLK (S_IFDIR)
+You lose.
+# endif
+#endif
+
+#if defined S_ISBLK && defined S_IFCHR
+# if S_ISBLK (S_IFCHR)
+You lose.
+# endif
+#endif
+
+#if defined S_ISLNK && defined S_IFREG
+# if S_ISLNK (S_IFREG)
+You lose.
+# endif
+#endif
+
+#if defined S_ISSOCK && defined S_IFREG
+# if S_ISSOCK (S_IFREG)
+You lose.
+# endif
+#endif
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+ $EGREP "You lose" >/dev/null 2>&1; then
+ ac_cv_header_stat_broken=yes
+else
+ ac_cv_header_stat_broken=no
+fi
+rm -f conftest*
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_stat_broken" >&5
+echo "${ECHO_T}$ac_cv_header_stat_broken" >&6; }
+if test $ac_cv_header_stat_broken = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define STAT_MACROS_BROKEN 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for sys/wait.h that is POSIX.1 compatible" >&5
+echo $ECHO_N "checking for sys/wait.h that is POSIX.1 compatible... $ECHO_C" >&6; }
+if test "${ac_cv_header_sys_wait_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/types.h>
+#include <sys/wait.h>
+#ifndef WEXITSTATUS
+# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
+#endif
+#ifndef WIFEXITED
+# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
+#endif
+
+int
+main ()
+{
+ int s;
+ wait (&s);
+ s = WIFEXITED (s) ? WEXITSTATUS (s) : 1;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_header_sys_wait_h=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_header_sys_wait_h=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_wait_h" >&5
+echo "${ECHO_T}$ac_cv_header_sys_wait_h" >&6; }
+if test $ac_cv_header_sys_wait_h = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_SYS_WAIT_H 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5
+echo $ECHO_N "checking whether time.h and sys/time.h may both be included... $ECHO_C" >&6; }
+if test "${ac_cv_header_time+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/types.h>
+#include <sys/time.h>
+#include <time.h>
+
+int
+main ()
+{
+if ((struct tm *) 0)
+return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_header_time=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_header_time=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5
+echo "${ECHO_T}$ac_cv_header_time" >&6; }
+if test $ac_cv_header_time = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define TIME_WITH_SYS_TIME 1
+_ACEOF
+
+fi
+
+
+
+
+
+
+
+
+for ac_header in dlfcn.h execinfo.h fcntl.h inttypes.h limits.h link.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+
+
+for ac_header in malloc.h setjmp.h signal.h stdint.h termios.h unistd.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+for ac_header in utime.h windows.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+
+for ac_header in sys/mman.h sys/param.h sys/resource.h sys/time.h sys/uio.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+for ac_header in sys/types.h sys/ioctl.h malloc/malloc.h mach/mach.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+for ac_header in valgrind/valgrind.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+for ac_header in fenv.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+if test "$LLVM_ENABLE_THREADS" -eq 1 && test "$ENABLE_PTHREADS" -eq 1 ; then
+
+for ac_header in pthread.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+ HAVE_PTHREAD=1
+
+else
+ HAVE_PTHREAD=0
+
+fi
+
+done
+
+else
+ HAVE_PTHREAD=0
+
+fi
+
+if test "$llvm_cv_enable_libffi" = "yes" ; then
+
+
+for ac_header in ffi.h ffi/ffi.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+fi
+
+
+for ac_header in CrashReporterClient.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+{ echo "$as_me:$LINENO: checking __crashreporter_info__" >&5
+echo $ECHO_N "checking __crashreporter_info__... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+extern const char *__crashreporter_info__;
+ int main() {
+ __crashreporter_info__ = "test";
+ return 0;
+ }
+
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ { echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_CRASHREPORTER_INFO 1
+_ACEOF
+
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_CRASHREPORTER_INFO 0
+_ACEOF
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+
+
+
+
+ { echo "$as_me:$LINENO: checking for HUGE_VAL sanity" >&5
+echo $ECHO_N "checking for HUGE_VAL sanity... $ECHO_C" >&6; }
+if test "${ac_cv_huge_val_sanity+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ ac_save_CXXFLAGS=$CXXFLAGS
+ CXXFLAGS="$CXXFLAGS -pedantic"
+ if test "$cross_compiling" = yes; then
+ ac_cv_huge_val_sanity=yes
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <math.h>
+int
+main ()
+{
+double x = HUGE_VAL; return x != x;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_huge_val_sanity=yes
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+ac_cv_huge_val_sanity=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+
+
+ CXXFLAGS=$ac_save_CXXFLAGS
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_huge_val_sanity" >&5
+echo "${ECHO_T}$ac_cv_huge_val_sanity" >&6; }
+ HUGE_VAL_SANITY=$ac_cv_huge_val_sanity
+
+
+{ echo "$as_me:$LINENO: checking for pid_t" >&5
+echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; }
+if test "${ac_cv_type_pid_t+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+typedef pid_t ac__type_new_;
+int
+main ()
+{
+if ((ac__type_new_ *) 0)
+ return 0;
+if (sizeof (ac__type_new_))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_pid_t=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_type_pid_t=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5
+echo "${ECHO_T}$ac_cv_type_pid_t" >&6; }
+if test $ac_cv_type_pid_t = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define pid_t int
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for size_t" >&5
+echo $ECHO_N "checking for size_t... $ECHO_C" >&6; }
+if test "${ac_cv_type_size_t+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+typedef size_t ac__type_new_;
+int
+main ()
+{
+if ((ac__type_new_ *) 0)
+ return 0;
+if (sizeof (ac__type_new_))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_size_t=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_type_size_t=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5
+echo "${ECHO_T}$ac_cv_type_size_t" >&6; }
+if test $ac_cv_type_size_t = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define size_t unsigned int
+_ACEOF
+
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define RETSIGTYPE void
+_ACEOF
+
+{ echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5
+echo $ECHO_N "checking whether struct tm is in sys/time.h or time.h... $ECHO_C" >&6; }
+if test "${ac_cv_struct_tm+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <sys/types.h>
+#include <time.h>
+
+int
+main ()
+{
+struct tm *tp; tp->tm_sec;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_struct_tm=time.h
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_struct_tm=sys/time.h
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5
+echo "${ECHO_T}$ac_cv_struct_tm" >&6; }
+if test $ac_cv_struct_tm = sys/time.h; then
+
+cat >>confdefs.h <<\_ACEOF
+#define TM_IN_SYS_TIME 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for int64_t" >&5
+echo $ECHO_N "checking for int64_t... $ECHO_C" >&6; }
+if test "${ac_cv_type_int64_t+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+typedef int64_t ac__type_new_;
+int
+main ()
+{
+if ((ac__type_new_ *) 0)
+ return 0;
+if (sizeof (ac__type_new_))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_int64_t=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_type_int64_t=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_type_int64_t" >&5
+echo "${ECHO_T}$ac_cv_type_int64_t" >&6; }
+if test $ac_cv_type_int64_t = yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_INT64_T 1
+_ACEOF
+
+
+else
+ { { echo "$as_me:$LINENO: error: Type int64_t required but not found" >&5
+echo "$as_me: error: Type int64_t required but not found" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+{ echo "$as_me:$LINENO: checking for uint64_t" >&5
+echo $ECHO_N "checking for uint64_t... $ECHO_C" >&6; }
+if test "${ac_cv_type_uint64_t+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+typedef uint64_t ac__type_new_;
+int
+main ()
+{
+if ((ac__type_new_ *) 0)
+ return 0;
+if (sizeof (ac__type_new_))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_uint64_t=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_type_uint64_t=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_type_uint64_t" >&5
+echo "${ECHO_T}$ac_cv_type_uint64_t" >&6; }
+if test $ac_cv_type_uint64_t = yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_UINT64_T 1
+_ACEOF
+
+
+else
+ { echo "$as_me:$LINENO: checking for u_int64_t" >&5
+echo $ECHO_N "checking for u_int64_t... $ECHO_C" >&6; }
+if test "${ac_cv_type_u_int64_t+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+typedef u_int64_t ac__type_new_;
+int
+main ()
+{
+if ((ac__type_new_ *) 0)
+ return 0;
+if (sizeof (ac__type_new_))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_u_int64_t=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_type_u_int64_t=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_type_u_int64_t" >&5
+echo "${ECHO_T}$ac_cv_type_u_int64_t" >&6; }
+if test $ac_cv_type_u_int64_t = yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_U_INT64_T 1
+_ACEOF
+
+
+else
+ { { echo "$as_me:$LINENO: error: Type uint64_t or u_int64_t required but not found" >&5
+echo "$as_me: error: Type uint64_t or u_int64_t required but not found" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+fi
+
+
+
+
+
+
+
+
+
+
+for ac_func in backtrace ceilf floorf roundf rintf nearbyintf getcwd
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+for ac_func in powf fmodf strtof round
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+
+for ac_func in getpagesize getrusage getrlimit setrlimit gettimeofday
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+for ac_func in isatty mkdtemp mkstemp
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+
+
+
+for ac_func in mktemp posix_spawn pread realpath sbrk setrlimit strdup
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+for ac_func in strerror strerror_r setenv arc4random
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+for ac_func in strtoll strtoq sysconf malloc_zone_statistics
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+
+for ac_func in setjmp longjmp sigsetjmp siglongjmp writev
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+{ echo "$as_me:$LINENO: checking if printf has the %a format character" >&5
+echo $ECHO_N "checking if printf has the %a format character... $ECHO_C" >&6; }
+if test "${llvm_cv_c_printf_a+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ if test "$cross_compiling" = yes; then
+ llvmac_cv_c_printf_a=no
+else
+ cat >conftest.$ac_ext <<_ACEOF
+
+ /* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+int
+main ()
+{
+
+volatile double A, B;
+char Buffer[100];
+A = 1;
+A /= 10.0;
+sprintf(Buffer, "%a", A);
+B = atof(Buffer);
+if (A != B)
+ return (1);
+if (A != 0x1.999999999999ap-4)
+ return (1);
+return (0);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ llvm_cv_c_printf_a=yes
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+llvmac_cv_c_printf_a=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+
+
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_c_printf_a" >&5
+echo "${ECHO_T}$llvm_cv_c_printf_a" >&6; }
+ if test "$llvm_cv_c_printf_a" = "yes"; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_PRINTF_A 1
+_ACEOF
+
+ fi
+
+
+{ echo "$as_me:$LINENO: checking for srand48/lrand48/drand48 in <stdlib.h>" >&5
+echo $ECHO_N "checking for srand48/lrand48/drand48 in <stdlib.h>... $ECHO_C" >&6; }
+if test "${ac_cv_func_rand48+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdlib.h>
+int
+main ()
+{
+srand48(0);lrand48();drand48();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_rand48=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_rand48=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_rand48" >&5
+echo "${ECHO_T}$ac_cv_func_rand48" >&6; }
+
+if test "$ac_cv_func_rand48" = "yes" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_RAND48 1
+_ACEOF
+
+fi
+
+
+{ echo "$as_me:$LINENO: checking whether strerror_s is declared" >&5
+echo $ECHO_N "checking whether strerror_s is declared... $ECHO_C" >&6; }
+if test "${ac_cv_have_decl_strerror_s+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+#ifndef strerror_s
+ char *p = (char *) strerror_s;
+ return !p;
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_have_decl_strerror_s=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_have_decl_strerror_s=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_strerror_s" >&5
+echo "${ECHO_T}$ac_cv_have_decl_strerror_s" >&6; }
+if test $ac_cv_have_decl_strerror_s = yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_STRERROR_S 1
+_ACEOF
+
+
+else
+ cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_STRERROR_S 0
+_ACEOF
+
+
+fi
+
+
+
+if test "$llvm_cv_os_type" = "MingW" ; then
+ { echo "$as_me:$LINENO: checking for _alloca in -lgcc" >&5
+echo $ECHO_N "checking for _alloca in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc__alloca+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char _alloca ();
+int
+main ()
+{
+return _alloca ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc__alloca=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc__alloca=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc__alloca" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc__alloca" >&6; }
+if test $ac_cv_lib_gcc__alloca = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE__ALLOCA 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __alloca in -lgcc" >&5
+echo $ECHO_N "checking for __alloca in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___alloca+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __alloca ();
+int
+main ()
+{
+return __alloca ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___alloca=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___alloca=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___alloca" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___alloca" >&6; }
+if test $ac_cv_lib_gcc___alloca = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___ALLOCA 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __chkstk in -lgcc" >&5
+echo $ECHO_N "checking for __chkstk in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___chkstk+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __chkstk ();
+int
+main ()
+{
+return __chkstk ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___chkstk=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___chkstk=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___chkstk" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___chkstk" >&6; }
+if test $ac_cv_lib_gcc___chkstk = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___CHKSTK 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for ___chkstk in -lgcc" >&5
+echo $ECHO_N "checking for ___chkstk in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc____chkstk+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ___chkstk ();
+int
+main ()
+{
+return ___chkstk ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc____chkstk=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc____chkstk=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc____chkstk" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc____chkstk" >&6; }
+if test $ac_cv_lib_gcc____chkstk = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE____CHKSTK 1
+_ACEOF
+
+fi
+
+
+ { echo "$as_me:$LINENO: checking for __ashldi3 in -lgcc" >&5
+echo $ECHO_N "checking for __ashldi3 in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___ashldi3+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __ashldi3 ();
+int
+main ()
+{
+return __ashldi3 ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___ashldi3=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___ashldi3=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___ashldi3" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___ashldi3" >&6; }
+if test $ac_cv_lib_gcc___ashldi3 = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___ASHLDI3 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __ashrdi3 in -lgcc" >&5
+echo $ECHO_N "checking for __ashrdi3 in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___ashrdi3+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __ashrdi3 ();
+int
+main ()
+{
+return __ashrdi3 ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___ashrdi3=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___ashrdi3=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___ashrdi3" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___ashrdi3" >&6; }
+if test $ac_cv_lib_gcc___ashrdi3 = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___ASHRDI3 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __divdi3 in -lgcc" >&5
+echo $ECHO_N "checking for __divdi3 in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___divdi3+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __divdi3 ();
+int
+main ()
+{
+return __divdi3 ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___divdi3=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___divdi3=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___divdi3" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___divdi3" >&6; }
+if test $ac_cv_lib_gcc___divdi3 = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___DIVDI3 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __fixdfdi in -lgcc" >&5
+echo $ECHO_N "checking for __fixdfdi in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___fixdfdi+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __fixdfdi ();
+int
+main ()
+{
+return __fixdfdi ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___fixdfdi=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___fixdfdi=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___fixdfdi" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___fixdfdi" >&6; }
+if test $ac_cv_lib_gcc___fixdfdi = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___FIXDFDI 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __fixsfdi in -lgcc" >&5
+echo $ECHO_N "checking for __fixsfdi in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___fixsfdi+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __fixsfdi ();
+int
+main ()
+{
+return __fixsfdi ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___fixsfdi=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___fixsfdi=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___fixsfdi" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___fixsfdi" >&6; }
+if test $ac_cv_lib_gcc___fixsfdi = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___FIXSFDI 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __floatdidf in -lgcc" >&5
+echo $ECHO_N "checking for __floatdidf in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___floatdidf+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __floatdidf ();
+int
+main ()
+{
+return __floatdidf ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___floatdidf=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___floatdidf=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___floatdidf" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___floatdidf" >&6; }
+if test $ac_cv_lib_gcc___floatdidf = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___FLOATDIDF 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __lshrdi3 in -lgcc" >&5
+echo $ECHO_N "checking for __lshrdi3 in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___lshrdi3+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __lshrdi3 ();
+int
+main ()
+{
+return __lshrdi3 ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___lshrdi3=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___lshrdi3=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___lshrdi3" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___lshrdi3" >&6; }
+if test $ac_cv_lib_gcc___lshrdi3 = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___LSHRDI3 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __moddi3 in -lgcc" >&5
+echo $ECHO_N "checking for __moddi3 in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___moddi3+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __moddi3 ();
+int
+main ()
+{
+return __moddi3 ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___moddi3=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___moddi3=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___moddi3" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___moddi3" >&6; }
+if test $ac_cv_lib_gcc___moddi3 = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___MODDI3 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __udivdi3 in -lgcc" >&5
+echo $ECHO_N "checking for __udivdi3 in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___udivdi3+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __udivdi3 ();
+int
+main ()
+{
+return __udivdi3 ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___udivdi3=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___udivdi3=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___udivdi3" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___udivdi3" >&6; }
+if test $ac_cv_lib_gcc___udivdi3 = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___UDIVDI3 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __umoddi3 in -lgcc" >&5
+echo $ECHO_N "checking for __umoddi3 in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___umoddi3+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __umoddi3 ();
+int
+main ()
+{
+return __umoddi3 ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___umoddi3=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___umoddi3=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___umoddi3" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___umoddi3" >&6; }
+if test $ac_cv_lib_gcc___umoddi3 = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___UMODDI3 1
+_ACEOF
+
+fi
+
+
+ { echo "$as_me:$LINENO: checking for __main in -lgcc" >&5
+echo $ECHO_N "checking for __main in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___main+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __main ();
+int
+main ()
+{
+return __main ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___main=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___main=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___main" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___main" >&6; }
+if test $ac_cv_lib_gcc___main = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___MAIN 1
+_ACEOF
+
+fi
+
+ { echo "$as_me:$LINENO: checking for __cmpdi2 in -lgcc" >&5
+echo $ECHO_N "checking for __cmpdi2 in -lgcc... $ECHO_C" >&6; }
+if test "${ac_cv_lib_gcc___cmpdi2+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lgcc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char __cmpdi2 ();
+int
+main ()
+{
+return __cmpdi2 ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_gcc___cmpdi2=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_lib_gcc___cmpdi2=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_gcc___cmpdi2" >&5
+echo "${ECHO_T}$ac_cv_lib_gcc___cmpdi2" >&6; }
+if test $ac_cv_lib_gcc___cmpdi2 = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE___CMPDI2 1
+_ACEOF
+
+fi
+
+fi
+
+if test "$llvm_cv_os_type" = "MingW" ; then
+ { echo "$as_me:$LINENO: checking whether EnumerateLoadedModules() accepts new decl" >&5
+echo $ECHO_N "checking whether EnumerateLoadedModules() accepts new decl... $ECHO_C" >&6; }
+ cat >conftest.$ac_ext <<_ACEOF
+#include <windows.h>
+#include <imagehlp.h>
+extern void foo(PENUMLOADED_MODULES_CALLBACK);
+extern void foo(BOOL(CALLBACK*)(PCSTR,ULONG_PTR,ULONG,PVOID));
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+ { echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
+ llvm_cv_win32_elmcb_pcstr="PCSTR"
+
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+ llvm_cv_win32_elmcb_pcstr="PSTR"
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+cat >>confdefs.h <<_ACEOF
+#define WIN32_ELMCB_PCSTR $llvm_cv_win32_elmcb_pcstr
+_ACEOF
+
+fi
+
+
+{ echo "$as_me:$LINENO: checking for isnan in <math.h>" >&5
+echo $ECHO_N "checking for isnan in <math.h>... $ECHO_C" >&6; }
+if test "${ac_cv_func_isnan_in_math_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <math.h>
+int
+main ()
+{
+float f; isnan(f);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_isnan_in_math_h=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_isnan_in_math_h=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_isnan_in_math_h" >&5
+echo "${ECHO_T}$ac_cv_func_isnan_in_math_h" >&6; }
+
+
+if test "$ac_cv_func_isnan_in_math_h" = "yes" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_ISNAN_IN_MATH_H 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for isnan in <cmath>" >&5
+echo $ECHO_N "checking for isnan in <cmath>... $ECHO_C" >&6; }
+if test "${ac_cv_func_isnan_in_cmath+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <cmath>
+int
+main ()
+{
+float f; isnan(f);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_isnan_in_cmath=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_isnan_in_cmath=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_isnan_in_cmath" >&5
+echo "${ECHO_T}$ac_cv_func_isnan_in_cmath" >&6; }
+
+if test "$ac_cv_func_isnan_in_cmath" = "yes" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_ISNAN_IN_CMATH 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for std::isnan in <cmath>" >&5
+echo $ECHO_N "checking for std::isnan in <cmath>... $ECHO_C" >&6; }
+if test "${ac_cv_func_std_isnan_in_cmath+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <cmath>
+int
+main ()
+{
+float f; std::isnan(f);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_std_isnan_in_cmath=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_std_isnan_in_cmath=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_std_isnan_in_cmath" >&5
+echo "${ECHO_T}$ac_cv_func_std_isnan_in_cmath" >&6; }
+
+if test "$ac_cv_func_std_isnan_in_cmath" = "yes" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_STD_ISNAN_IN_CMATH 1
+_ACEOF
+
+fi
+
+
+{ echo "$as_me:$LINENO: checking for isinf in <math.h>" >&5
+echo $ECHO_N "checking for isinf in <math.h>... $ECHO_C" >&6; }
+if test "${ac_cv_func_isinf_in_math_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <math.h>
+int
+main ()
+{
+float f; isinf(f);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_isinf_in_math_h=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_isinf_in_math_h=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_isinf_in_math_h" >&5
+echo "${ECHO_T}$ac_cv_func_isinf_in_math_h" >&6; }
+
+if test "$ac_cv_func_isinf_in_math_h" = "yes" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_ISINF_IN_MATH_H 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for isinf in <cmath>" >&5
+echo $ECHO_N "checking for isinf in <cmath>... $ECHO_C" >&6; }
+if test "${ac_cv_func_isinf_in_cmath+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <cmath>
+int
+main ()
+{
+float f; isinf(f);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_isinf_in_cmath=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_isinf_in_cmath=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_isinf_in_cmath" >&5
+echo "${ECHO_T}$ac_cv_func_isinf_in_cmath" >&6; }
+
+if test "$ac_cv_func_isinf_in_cmath" = "yes" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_ISINF_IN_CMATH 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for std::isinf in <cmath>" >&5
+echo $ECHO_N "checking for std::isinf in <cmath>... $ECHO_C" >&6; }
+if test "${ac_cv_func_std_isinf_in_cmath+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <cmath>
+int
+main ()
+{
+float f; std::isinf(f);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_std_isinf_in_cmath=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_std_isinf_in_cmath=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_std_isinf_in_cmath" >&5
+echo "${ECHO_T}$ac_cv_func_std_isinf_in_cmath" >&6; }
+
+if test "$ac_cv_func_std_isinf_in_cmath" = "yes" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_STD_ISINF_IN_CMATH 1
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for finite in <ieeefp.h>" >&5
+echo $ECHO_N "checking for finite in <ieeefp.h>... $ECHO_C" >&6; }
+if test "${ac_cv_func_finite_in_ieeefp_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ieeefp.h>
+int
+main ()
+{
+float f; finite(f);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_finite_in_ieeefp_h=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_func_finite_in_ieeefp_h=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_finite_in_ieeefp_h" >&5
+echo "${ECHO_T}$ac_cv_func_finite_in_ieeefp_h" >&6; }
+
+if test "$ac_cv_func_finite_in_ieeefp_h" = "yes" ; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_FINITE_IN_IEEEFP_H 1
+_ACEOF
+
+fi
+
+
+
+if test "$llvm_cv_platform_type" = "Unix" ; then
+
+
+for ac_header in stdlib.h unistd.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+else
+ # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ ( cat <<\_ASBOX
+## ------------------------------------ ##
+## Report this to http://llvm.org/bugs/ ##
+## ------------------------------------ ##
+_ASBOX
+ ) | sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+for ac_func in getpagesize
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+{ echo "$as_me:$LINENO: checking for working mmap" >&5
+echo $ECHO_N "checking for working mmap... $ECHO_C" >&6; }
+if test "${ac_cv_func_mmap_fixed_mapped+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test "$cross_compiling" = yes; then
+ ac_cv_func_mmap_fixed_mapped=no
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+/* malloc might have been renamed as rpl_malloc. */
+#undef malloc
+
+/* Thanks to Mike Haertel and Jim Avera for this test.
+ Here is a matrix of mmap possibilities:
+ mmap private not fixed
+ mmap private fixed at somewhere currently unmapped
+ mmap private fixed at somewhere already mapped
+ mmap shared not fixed
+ mmap shared fixed at somewhere currently unmapped
+ mmap shared fixed at somewhere already mapped
+ For private mappings, we should verify that changes cannot be read()
+ back from the file, nor mmap's back from the file at a different
+ address. (There have been systems where private was not correctly
+ implemented like the infamous i386 svr4.0, and systems where the
+ VM page cache was not coherent with the file system buffer cache
+ like early versions of FreeBSD and possibly contemporary NetBSD.)
+ For shared mappings, we should conversely verify that changes get
+ propagated back to all the places they're supposed to be.
+
+ Grep wants private fixed already mapped.
+ The main things grep needs to know about mmap are:
+ * does it exist and is it safe to write into the mmap'd area
+ * how to use it (BSD variants) */
+
+#include <fcntl.h>
+#include <sys/mman.h>
+
+#if !STDC_HEADERS && !HAVE_STDLIB_H
+char *malloc ();
+#endif
+
+/* This mess was copied from the GNU getpagesize.h. */
+#if !HAVE_GETPAGESIZE
+/* Assume that all systems that can run configure have sys/param.h. */
+# if !HAVE_SYS_PARAM_H
+# define HAVE_SYS_PARAM_H 1
+# endif
+
+# ifdef _SC_PAGESIZE
+# define getpagesize() sysconf(_SC_PAGESIZE)
+# else /* no _SC_PAGESIZE */
+# if HAVE_SYS_PARAM_H
+# include <sys/param.h>
+# ifdef EXEC_PAGESIZE
+# define getpagesize() EXEC_PAGESIZE
+# else /* no EXEC_PAGESIZE */
+# ifdef NBPG
+# define getpagesize() NBPG * CLSIZE
+# ifndef CLSIZE
+# define CLSIZE 1
+# endif /* no CLSIZE */
+# else /* no NBPG */
+# ifdef NBPC
+# define getpagesize() NBPC
+# else /* no NBPC */
+# ifdef PAGESIZE
+# define getpagesize() PAGESIZE
+# endif /* PAGESIZE */
+# endif /* no NBPC */
+# endif /* no NBPG */
+# endif /* no EXEC_PAGESIZE */
+# else /* no HAVE_SYS_PARAM_H */
+# define getpagesize() 8192 /* punt totally */
+# endif /* no HAVE_SYS_PARAM_H */
+# endif /* no _SC_PAGESIZE */
+
+#endif /* no HAVE_GETPAGESIZE */
+
+int
+main ()
+{
+ char *data, *data2, *data3;
+ int i, pagesize;
+ int fd;
+
+ pagesize = getpagesize ();
+
+ /* First, make a file with some known garbage in it. */
+ data = (char *) malloc (pagesize);
+ if (!data)
+ return 1;
+ for (i = 0; i < pagesize; ++i)
+ *(data + i) = rand ();
+ umask (0);
+ fd = creat ("conftest.mmap", 0600);
+ if (fd < 0)
+ return 1;
+ if (write (fd, data, pagesize) != pagesize)
+ return 1;
+ close (fd);
+
+ /* Next, try to mmap the file at a fixed address which already has
+ something else allocated at it. If we can, also make sure that
+ we see the same garbage. */
+ fd = open ("conftest.mmap", O_RDWR);
+ if (fd < 0)
+ return 1;
+ data2 = (char *) malloc (2 * pagesize);
+ if (!data2)
+ return 1;
+ data2 += (pagesize - ((long int) data2 & (pagesize - 1))) & (pagesize - 1);
+ if (data2 != mmap (data2, pagesize, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_FIXED, fd, 0L))
+ return 1;
+ for (i = 0; i < pagesize; ++i)
+ if (*(data + i) != *(data2 + i))
+ return 1;
+
+ /* Finally, make sure that changes to the mapped area do not
+ percolate back to the file as seen by read(). (This is a bug on
+ some variants of i386 svr4.0.) */
+ for (i = 0; i < pagesize; ++i)
+ *(data2 + i) = *(data2 + i) + 1;
+ data3 = (char *) malloc (pagesize);
+ if (!data3)
+ return 1;
+ if (read (fd, data3, pagesize) != pagesize)
+ return 1;
+ for (i = 0; i < pagesize; ++i)
+ if (*(data + i) != *(data3 + i))
+ return 1;
+ close (fd);
+ return 0;
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_mmap_fixed_mapped=yes
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+ac_cv_func_mmap_fixed_mapped=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_mmap_fixed_mapped" >&5
+echo "${ECHO_T}$ac_cv_func_mmap_fixed_mapped" >&6; }
+if test $ac_cv_func_mmap_fixed_mapped = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_MMAP 1
+_ACEOF
+
+fi
+rm -f conftest.mmap
+
+ { echo "$as_me:$LINENO: checking for mmap of files" >&5
+echo $ECHO_N "checking for mmap of files... $ECHO_C" >&6; }
+if test "${ac_cv_func_mmap_file+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ if test "$cross_compiling" = yes; then
+ ac_cv_func_mmap_file=no
+else
+ cat >conftest.$ac_ext <<_ACEOF
+
+ /* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <fcntl.h>
+
+int
+main ()
+{
+
+ int fd;
+ fd = creat ("foo",0777);
+ fd = (int) mmap (0, 1, PROT_READ, MAP_SHARED, fd, 0);
+ unlink ("foo");
+ return (fd != (int) MAP_FAILED);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_mmap_file=yes
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+ac_cv_func_mmap_file=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+
+
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_mmap_file" >&5
+echo "${ECHO_T}$ac_cv_func_mmap_file" >&6; }
+if test "$ac_cv_func_mmap_file" = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_MMAP_FILE
+_ACEOF
+
+ MMAP_FILE=yes
+
+fi
+
+ { echo "$as_me:$LINENO: checking if /dev/zero is needed for mmap" >&5
+echo $ECHO_N "checking if /dev/zero is needed for mmap... $ECHO_C" >&6; }
+if test "${ac_cv_need_dev_zero_for_mmap+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test "$llvm_cv_os_type" = "Interix" ; then
+ ac_cv_need_dev_zero_for_mmap=yes
+ else
+ ac_cv_need_dev_zero_for_mmap=no
+ fi
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_need_dev_zero_for_mmap" >&5
+echo "${ECHO_T}$ac_cv_need_dev_zero_for_mmap" >&6; }
+if test "$ac_cv_need_dev_zero_for_mmap" = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define NEED_DEV_ZERO_FOR_MMAP 1
+_ACEOF
+
+fi
+
+ if test "$ac_cv_func_mmap_fixed_mapped" = "no"
+ then
+ { echo "$as_me:$LINENO: WARNING: mmap() of a fixed address required but not supported" >&5
+echo "$as_me: WARNING: mmap() of a fixed address required but not supported" >&2;}
+ fi
+ if test "$ac_cv_func_mmap_file" = "no"
+ then
+ { echo "$as_me:$LINENO: WARNING: mmap() of files required but not found" >&5
+echo "$as_me: WARNING: mmap() of files required but not found" >&2;}
+ fi
+fi
+
+{ echo "$as_me:$LINENO: checking for GCC atomic builtins" >&5
+echo $ECHO_N "checking for GCC atomic builtins... $ECHO_C" >&6; }
+ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+int main() {
+ volatile unsigned long val = 1;
+ __sync_synchronize();
+ __sync_val_compare_and_swap(&val, 1, 0);
+ __sync_add_and_fetch(&val, 1);
+ __sync_sub_and_fetch(&val, 1);
+ return 0;
+ }
+
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ { echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
+
+cat >>confdefs.h <<\_ACEOF
+#define LLVM_HAS_ATOMICS 1
+_ACEOF
+
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+
+cat >>confdefs.h <<\_ACEOF
+#define LLVM_HAS_ATOMICS 0
+_ACEOF
+
+ { echo "$as_me:$LINENO: WARNING: LLVM will be built thread-unsafe because atomic builtins are missing" >&5
+echo "$as_me: WARNING: LLVM will be built thread-unsafe because atomic builtins are missing" >&2;}
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+
+
+if test "$llvm_cv_os_type" = "Linux" -a "$llvm_cv_target_arch" = "x86_64" ; then
+ { echo "$as_me:$LINENO: checking for 32-bit userspace on 64-bit system" >&5
+echo $ECHO_N "checking for 32-bit userspace on 64-bit system... $ECHO_C" >&6; }
+if test "${llvm_cv_linux_mixed+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#ifndef __x86_64__
+ error: Not x86-64 even if uname says so!
+ #endif
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ llvm_cv_linux_mixed=no
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ llvm_cv_linux_mixed=yes
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_linux_mixed" >&5
+echo "${ECHO_T}$llvm_cv_linux_mixed" >&6; }
+
+ if test "$llvm_cv_linux_mixed" = "yes"; then
+ llvm_cv_target_arch="x86"
+ ARCH="x86"
+ fi
+fi
+
+
+for ac_func in __dso_handle
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any GCC internal prototype to avoid an error.
+ Use char because int might match the return type of a GCC
+ builtin and then its argument prototype would still apply. */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
+int
+main ()
+{
+return $ac_func ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_link") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ eval "$as_ac_var=no"
+fi
+
+rm -f core conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+ac_res=`eval echo '${'$as_ac_var'}'`
+ { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+SHLIBEXT=$libltdl_cv_shlibext
+
+
+SHLIBPATH_VAR=$libltdl_cv_shlibpath_var
+
+
+if test "${prefix}" = "NONE" ; then
+ prefix="/usr/local"
+fi
+eval LLVM_PREFIX="${prefix}";
+eval LLVM_BINDIR="${prefix}/bin";
+eval LLVM_LIBDIR="${prefix}/lib";
+eval LLVM_DATADIR="${prefix}/share/llvm";
+eval LLVM_DOCSDIR="${prefix}/share/doc/llvm";
+eval LLVM_ETCDIR="${prefix}/etc/llvm";
+eval LLVM_INCLUDEDIR="${prefix}/include";
+eval LLVM_INFODIR="${prefix}/info";
+eval LLVM_MANDIR="${prefix}/man";
+LLVM_CONFIGTIME=`date`
+
+
+
+
+
+
+
+
+
+
+
+if test "${ENABLE_TIMESTAMPS}" = "0"; then
+ LLVM_CONFIGTIME="(timestamp not enabled)"
+fi
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_PREFIX "$LLVM_PREFIX"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_BINDIR "$LLVM_BINDIR"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_LIBDIR "$LLVM_LIBDIR"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_DATADIR "$LLVM_DATADIR"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_DOCSDIR "$LLVM_DOCSDIR"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_ETCDIR "$LLVM_ETCDIR"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_INCLUDEDIR "$LLVM_INCLUDEDIR"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_INFODIR "$LLVM_INFODIR"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_MANDIR "$LLVM_MANDIR"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_CONFIGTIME "$LLVM_CONFIGTIME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_HOSTTRIPLE "$host"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define LLVM_DEFAULT_TARGET_TRIPLE "$target"
+_ACEOF
+
+
+if test "$BINDINGS_TO_BUILD" = auto ; then
+ BINDINGS_TO_BUILD=""
+ if test "x$OCAMLC" != x -a "x$OCAMLDEP" != x ; then
+ BINDINGS_TO_BUILD="ocaml $BINDINGS_TO_BUILD"
+ fi
+fi
+BINDINGS_TO_BUILD=$BINDINGS_TO_BUILD
+
+
+ALL_BINDINGS=ocaml
+
+
+binding_prereqs_failed=0
+for a_binding in $BINDINGS_TO_BUILD ; do
+ case "$a_binding" in
+ ocaml)
+ if test "x$OCAMLC" = x ; then
+ { echo "$as_me:$LINENO: WARNING: --enable-bindings=ocaml specified, but ocamlc not found. Try configure OCAMLC=/path/to/ocamlc" >&5
+echo "$as_me: WARNING: --enable-bindings=ocaml specified, but ocamlc not found. Try configure OCAMLC=/path/to/ocamlc" >&2;}
+ binding_prereqs_failed=1
+ fi
+ if test "x$OCAMLDEP" = x ; then
+ { echo "$as_me:$LINENO: WARNING: --enable-bindings=ocaml specified, but ocamldep not found. Try configure OCAMLDEP=/path/to/ocamldep" >&5
+echo "$as_me: WARNING: --enable-bindings=ocaml specified, but ocamldep not found. Try configure OCAMLDEP=/path/to/ocamldep" >&2;}
+ binding_prereqs_failed=1
+ fi
+ if test "x$OCAMLOPT" = x ; then
+ { echo "$as_me:$LINENO: WARNING: --enable-bindings=ocaml specified, but ocamlopt not found. Try configure OCAMLOPT=/path/to/ocamlopt" >&5
+echo "$as_me: WARNING: --enable-bindings=ocaml specified, but ocamlopt not found. Try configure OCAMLOPT=/path/to/ocamlopt" >&2;}
+ fi
+ if test "x$with_ocaml_libdir" != xauto ; then
+ OCAML_LIBDIR=$with_ocaml_libdir
+
+ else
+ ocaml_stdlib="`"$OCAMLC" -where`"
+ if test "$LLVM_PREFIX" '<' "$ocaml_stdlib" -a "$ocaml_stdlib" '<' "$LLVM_PREFIX~"
+ then
+ # ocaml stdlib is beneath our prefix; use stdlib
+ OCAML_LIBDIR=$ocaml_stdlib
+
+ else
+ # ocaml stdlib is outside our prefix; use libdir/ocaml
+ OCAML_LIBDIR=$LLVM_LIBDIR/ocaml
+
+ fi
+ fi
+ ;;
+ esac
+done
+if test "$binding_prereqs_failed" = 1 ; then
+ { { echo "$as_me:$LINENO: error: Prequisites for bindings not satisfied. Fix them or use configure --disable-bindings." >&5
+echo "$as_me: error: Prequisites for bindings not satisfied. Fix them or use configure --disable-bindings." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+{ echo "$as_me:$LINENO: checking for compiler -fvisibility-inlines-hidden option" >&5
+echo $ECHO_N "checking for compiler -fvisibility-inlines-hidden option... $ECHO_C" >&6; }
+if test "${llvm_cv_cxx_visibility_inlines_hidden+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=cpp
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+ oldcxxflags="$CXXFLAGS"
+ CXXFLAGS="$CXXFLAGS -O0 -fvisibility-inlines-hidden -Werror"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+template <typename T> struct X { void __attribute__((noinline)) f() {} };
+int
+main ()
+{
+X<int>().f();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_compile") 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag" || test ! -s conftest.err'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (case "(($ac_try" in
+ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+ *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+ (eval "$ac_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ llvm_cv_cxx_visibility_inlines_hidden=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ llvm_cv_cxx_visibility_inlines_hidden=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ CXXFLAGS="$oldcxxflags"
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+fi
+{ echo "$as_me:$LINENO: result: $llvm_cv_cxx_visibility_inlines_hidden" >&5
+echo "${ECHO_T}$llvm_cv_cxx_visibility_inlines_hidden" >&6; }
+if test "$llvm_cv_cxx_visibility_inlines_hidden" = yes ; then
+ ENABLE_VISIBILITY_INLINES_HIDDEN=1
+
+else
+ ENABLE_VISIBILITY_INLINES_HIDDEN=0
+
+fi
+
+
+if test "$llvm_cv_link_use_r" = "yes" ; then
+ RPATH="-Wl,-R"
+else
+ RPATH="-Wl,-rpath"
+fi
+
+
+if test "$llvm_cv_link_use_export_dynamic" = "yes" ; then
+ RDYNAMIC="-Wl,-export-dynamic"
+else
+ RDYNAMIC=""
+fi
+
+
+
+ac_config_headers="$ac_config_headers include/llvm/Config/config.h include/llvm/Config/llvm-config.h"
+
+
+
+
+
+
+ac_config_files="$ac_config_files include/llvm/Config/Targets.def"
+
+ac_config_files="$ac_config_files include/llvm/Config/AsmPrinters.def"
+
+ac_config_files="$ac_config_files include/llvm/Config/AsmParsers.def"
+
+ac_config_files="$ac_config_files include/llvm/Config/Disassemblers.def"
+
+ac_config_headers="$ac_config_headers include/llvm/Support/DataTypes.h"
+
+
+ac_config_files="$ac_config_files Makefile.config"
+
+
+ac_config_files="$ac_config_files llvm.spec"
+
+
+ac_config_files="$ac_config_files docs/doxygen.cfg"
+
+
+if test "${clang_src_root}" = ""; then
+ clang_src_root="$srcdir/tools/clang"
+fi
+if test -f ${clang_src_root}/README.txt; then
+ configh="include/clang/Config/config.h"
+ doxy="docs/doxygen.cfg"
+ ac_config_headers="$ac_config_headers tools/clang/${configh}:${clang_src_root}/${configh}.in"
+
+ ac_config_files="$ac_config_files tools/clang/${doxy}:${clang_src_root}/${doxy}.in"
+
+fi
+
+ac_config_files="$ac_config_files bindings/ocaml/llvm/META.llvm"
+
+
+ac_config_commands="$ac_config_commands setup"
+
+ac_config_commands="$ac_config_commands Makefile"
+
+
+ac_config_commands="$ac_config_commands Makefile.common"
+
+
+ac_config_commands="$ac_config_commands examples/Makefile"
+
+
+ac_config_commands="$ac_config_commands lib/Makefile"
+
+
+ac_config_commands="$ac_config_commands runtime/Makefile"
+
+
+ac_config_commands="$ac_config_commands test/Makefile"
+
+
+ac_config_commands="$ac_config_commands test/Makefile.tests"
+
+
+ac_config_commands="$ac_config_commands unittests/Makefile"
+
+
+ac_config_commands="$ac_config_commands tools/Makefile"
+
+
+ac_config_commands="$ac_config_commands utils/Makefile"
+
+
+ac_config_commands="$ac_config_commands projects/Makefile"
+
+
+ac_config_commands="$ac_config_commands bindings/Makefile"
+
+
+ac_config_commands="$ac_config_commands bindings/ocaml/Makefile.ocaml"
+
+
+
+cat >confcache <<\_ACEOF
+# This file is a shell script that caches the results of configure
+# tests run on this system so they can be shared between configure
+# scripts and configure runs, see configure's option --config-cache.
+# It is not useful on other systems. If it contains results you don't
+# want to keep, you may remove or edit it.
+#
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
+#
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
+# The following way of writing the cache mishandles newlines in values,
+# but we know of no workaround that is simple, portable, and efficient.
+# So, we kill variables containing newlines.
+# Ultrix sh set writes to stderr and can't be redirected directly,
+# and sets the high bit in the cache file unless we assign to the vars.
+(
+ for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+ eval ac_val=\$$ac_var
+ case $ac_val in #(
+ *${as_nl}*)
+ case $ac_var in #(
+ *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+ esac
+ case $ac_var in #(
+ _ | IFS | as_nl) ;; #(
+ *) $as_unset $ac_var ;;
+ esac ;;
+ esac
+ done
+
+ (set) 2>&1 |
+ case $as_nl`(ac_space=' '; set) 2>&1` in #(
+ *${as_nl}ac_space=\ *)
+ # `set' does not quote correctly, so add quotes (double-quote
+ # substitution turns \\\\ into \\, and sed turns \\ into \).
+ sed -n \
+ "s/'/'\\\\''/g;
+ s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+ ;; #(
+ *)
+ # `set' quotes correctly as required by POSIX, so do not add quotes.
+ sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+ ;;
+ esac |
+ sort
+) |
+ sed '
+ /^ac_cv_env_/b end
+ t clear
+ :clear
+ s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+ t end
+ s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+ :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+ if test -w "$cache_file"; then
+ test "x$cache_file" != "x/dev/null" &&
+ { echo "$as_me:$LINENO: updating cache $cache_file" >&5
+echo "$as_me: updating cache $cache_file" >&6;}
+ cat confcache >$cache_file
+ else
+ { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
+echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+ fi
+fi
+rm -f confcache
+
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+
+DEFS=-DHAVE_CONFIG_H
+
+ac_libobjs=
+ac_ltlibobjs=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+ # 1. Remove the extension, and $U if already installed.
+ ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+ ac_i=`echo "$ac_i" | sed "$ac_script"`
+ # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR
+ # will be set to the directory where LIBOBJS objects are built.
+ ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+ ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+if test -z "${INSTALL_LTDL_TRUE}" && test -z "${INSTALL_LTDL_FALSE}"; then
+ { { echo "$as_me:$LINENO: error: conditional \"INSTALL_LTDL\" was never defined.
+Usually this means the macro was only invoked conditionally." >&5
+echo "$as_me: error: conditional \"INSTALL_LTDL\" was never defined.
+Usually this means the macro was only invoked conditionally." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+if test -z "${CONVENIENCE_LTDL_TRUE}" && test -z "${CONVENIENCE_LTDL_FALSE}"; then
+ { { echo "$as_me:$LINENO: error: conditional \"CONVENIENCE_LTDL\" was never defined.
+Usually this means the macro was only invoked conditionally." >&5
+echo "$as_me: error: conditional \"CONVENIENCE_LTDL\" was never defined.
+Usually this means the macro was only invoked conditionally." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+: ${CONFIG_STATUS=./config.status}
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
+echo "$as_me: creating $CONFIG_STATUS" >&6;}
+cat >$CONFIG_STATUS <<_ACEOF
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+SHELL=\${CONFIG_SHELL-$SHELL}
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+## --------------------- ##
+## M4sh Initialization. ##
+## --------------------- ##
+
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+ setopt NO_GLOB_SUBST
+else
+ case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+ echo "#! /bin/sh" >conf$$.sh
+ echo "exit 0" >>conf$$.sh
+ chmod +x conf$$.sh
+ if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+ PATH_SEPARATOR=';'
+ else
+ PATH_SEPARATOR=:
+ fi
+ rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+ as_unset=unset
+else
+ as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order. Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" "" $as_nl"
+
+# Find who we are. Look in the path if we contain no directory separator.
+case $0 in
+ *[\\/]* ) as_myself=$0 ;;
+ *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+ as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+ echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+ { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+ LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+ LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+ LC_TELEPHONE LC_TIME
+do
+ if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+ eval $as_var=C; export $as_var
+ else
+ ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+ fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+ test "X`expr 00001 : '.*\(...\)'`" = X001; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+ as_basename=basename
+else
+ as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+ X"$0" : 'X\(//\)$' \| \
+ X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+ sed '/^.*\/\([^/][^/]*\)\/*$/{
+ s//\1/
+ q
+ }
+ /^X\/\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\/\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+
+ as_lineno_1=$LINENO
+ as_lineno_2=$LINENO
+ test "x$as_lineno_1" != "x$as_lineno_2" &&
+ test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+ # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+ # uniformly replaced by the line number. The first 'sed' inserts a
+ # line-number line after each line using $LINENO; the second 'sed'
+ # does the real work. The second script uses 'N' to pair each
+ # line-number line with the line containing $LINENO, and appends
+ # trailing '-' during substitution so that $LINENO is not a special
+ # case at line end.
+ # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+ # scripts with optimization help from Paolo Bonzini. Blame Lee
+ # E. McMahon (1931-1989) for sed's syntax. :-)
+ sed -n '
+ p
+ /[$]LINENO/=
+ ' <$as_myself |
+ sed '
+ s/[$]LINENO.*/&-/
+ t lineno
+ b
+ :lineno
+ N
+ :loop
+ s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+ t loop
+ s/-\n.*//
+ ' >$as_me.lineno &&
+ chmod +x "$as_me.lineno" ||
+ { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+ { (exit 1); exit 1; }; }
+
+ # Don't try to exec as it changes $[0], causing all sort of problems
+ # (the dirname of $[0] is not the place where we might find the
+ # original and so on. Autoconf is especially sensitive to this).
+ . "./$as_me.lineno"
+ # Exit status is that of the last command.
+ exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+ as_dirname=dirname
+else
+ as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+ case `echo 'x\c'` in
+ *c*) ECHO_T=' ';; # ECHO_T is single tab character.
+ *) ECHO_C='\c';;
+ esac;;
+*)
+ ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+ test "X`expr 00001 : '.*\(...\)'`" = X001; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+ rm -f conf$$.dir/conf$$.file
+else
+ rm -f conf$$.dir
+ mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+ as_ln_s='ln -s'
+ # ... but there are two gotchas:
+ # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+ # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+ # In both cases, we have to default to `cp -p'.
+ ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+ as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+ as_ln_s=ln
+else
+ as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+ as_mkdir_p=:
+else
+ test -d ./-p && rmdir ./-p
+ as_mkdir_p=false
+fi
+
+# Find out whether ``test -x'' works. Don't use a zero-byte file, as
+# systems may use methods other than mode bits to determine executability.
+cat >conf$$.file <<_ASEOF
+#! /bin/sh
+exit 0
+_ASEOF
+chmod +x conf$$.file
+if test -x conf$$.file >/dev/null 2>&1; then
+ as_executable_p="test -x"
+else
+ as_executable_p=:
+fi
+rm -f conf$$.file
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+
+# Save the log message, to keep $[0] and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by LLVM $as_me 3.2svn, which was
+generated by GNU Autoconf 2.60. Invocation command line was
+
+ CONFIG_FILES = $CONFIG_FILES
+ CONFIG_HEADERS = $CONFIG_HEADERS
+ CONFIG_LINKS = $CONFIG_LINKS
+ CONFIG_COMMANDS = $CONFIG_COMMANDS
+ $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+# Files that config.status was made for.
+config_files="$ac_config_files"
+config_headers="$ac_config_headers"
+config_commands="$ac_config_commands"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+ac_cs_usage="\
+\`$as_me' instantiates files from templates according to the
+current configuration.
+
+Usage: $0 [OPTIONS] [FILE]...
+
+ -h, --help print this help, then exit
+ -V, --version print version number, then exit
+ -q, --quiet do not print progress messages
+ -d, --debug don't remove temporary files
+ --recheck update $as_me by reconfiguring in the same conditions
+ --file=FILE[:TEMPLATE]
+ instantiate the configuration file FILE
+ --header=FILE[:TEMPLATE]
+ instantiate the configuration header FILE
+
+Configuration files:
+$config_files
+
+Configuration headers:
+$config_headers
+
+Configuration commands:
+$config_commands
+
+Report bugs to <bug-autoconf@gnu.org>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+ac_cs_version="\\
+LLVM config.status 3.2svn
+configured by $0, generated by GNU Autoconf 2.60,
+ with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
+
+Copyright (C) 2006 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+INSTALL='$INSTALL'
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If no file are specified by the user, then we need to provide default
+# value. By we need to know if files were specified by the user.
+ac_need_defaults=:
+while test $# != 0
+do
+ case $1 in
+ --*=*)
+ ac_option=`expr "X$1" : 'X\([^=]*\)='`
+ ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+ ac_shift=:
+ ;;
+ *)
+ ac_option=$1
+ ac_optarg=$2
+ ac_shift=shift
+ ;;
+ esac
+
+ case $ac_option in
+ # Handling of the options.
+ -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+ ac_cs_recheck=: ;;
+ --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+ echo "$ac_cs_version"; exit ;;
+ --debug | --debu | --deb | --de | --d | -d )
+ debug=: ;;
+ --file | --fil | --fi | --f )
+ $ac_shift
+ CONFIG_FILES="$CONFIG_FILES $ac_optarg"
+ ac_need_defaults=false;;
+ --header | --heade | --head | --hea )
+ $ac_shift
+ CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
+ ac_need_defaults=false;;
+ --he | --h)
+ # Conflict between --help and --header
+ { echo "$as_me: error: ambiguous option: $1
+Try \`$0 --help' for more information." >&2
+ { (exit 1); exit 1; }; };;
+ --help | --hel | -h )
+ echo "$ac_cs_usage"; exit ;;
+ -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+ | -silent | --silent | --silen | --sile | --sil | --si | --s)
+ ac_cs_silent=: ;;
+
+ # This is an error.
+ -*) { echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2
+ { (exit 1); exit 1; }; } ;;
+
+ *) ac_config_targets="$ac_config_targets $1"
+ ac_need_defaults=false ;;
+
+ esac
+ shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+ exec 6>/dev/null
+ ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+if \$ac_cs_recheck; then
+ echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
+ CONFIG_SHELL=$SHELL
+ export CONFIG_SHELL
+ exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+exec 5>>config.log
+{
+ echo
+ sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+ echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+#
+# INIT-COMMANDS
+#
+llvm_src="${srcdir}"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+ case $ac_config_target in
+ "include/llvm/Config/config.h") CONFIG_HEADERS="$CONFIG_HEADERS include/llvm/Config/config.h" ;;
+ "include/llvm/Config/llvm-config.h") CONFIG_HEADERS="$CONFIG_HEADERS include/llvm/Config/llvm-config.h" ;;
+ "include/llvm/Config/Targets.def") CONFIG_FILES="$CONFIG_FILES include/llvm/Config/Targets.def" ;;
+ "include/llvm/Config/AsmPrinters.def") CONFIG_FILES="$CONFIG_FILES include/llvm/Config/AsmPrinters.def" ;;
+ "include/llvm/Config/AsmParsers.def") CONFIG_FILES="$CONFIG_FILES include/llvm/Config/AsmParsers.def" ;;
+ "include/llvm/Config/Disassemblers.def") CONFIG_FILES="$CONFIG_FILES include/llvm/Config/Disassemblers.def" ;;
+ "include/llvm/Support/DataTypes.h") CONFIG_HEADERS="$CONFIG_HEADERS include/llvm/Support/DataTypes.h" ;;
+ "Makefile.config") CONFIG_FILES="$CONFIG_FILES Makefile.config" ;;
+ "llvm.spec") CONFIG_FILES="$CONFIG_FILES llvm.spec" ;;
+ "docs/doxygen.cfg") CONFIG_FILES="$CONFIG_FILES docs/doxygen.cfg" ;;
+ "tools/clang/${configh}") CONFIG_HEADERS="$CONFIG_HEADERS tools/clang/${configh}:${clang_src_root}/${configh}.in" ;;
+ "tools/clang/${doxy}") CONFIG_FILES="$CONFIG_FILES tools/clang/${doxy}:${clang_src_root}/${doxy}.in" ;;
+ "bindings/ocaml/llvm/META.llvm") CONFIG_FILES="$CONFIG_FILES bindings/ocaml/llvm/META.llvm" ;;
+ "setup") CONFIG_COMMANDS="$CONFIG_COMMANDS setup" ;;
+ "Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS Makefile" ;;
+ "Makefile.common") CONFIG_COMMANDS="$CONFIG_COMMANDS Makefile.common" ;;
+ "examples/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS examples/Makefile" ;;
+ "lib/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS lib/Makefile" ;;
+ "runtime/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS runtime/Makefile" ;;
+ "test/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS test/Makefile" ;;
+ "test/Makefile.tests") CONFIG_COMMANDS="$CONFIG_COMMANDS test/Makefile.tests" ;;
+ "unittests/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS unittests/Makefile" ;;
+ "tools/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS tools/Makefile" ;;
+ "utils/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS utils/Makefile" ;;
+ "projects/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS projects/Makefile" ;;
+ "bindings/Makefile") CONFIG_COMMANDS="$CONFIG_COMMANDS bindings/Makefile" ;;
+ "bindings/ocaml/Makefile.ocaml") CONFIG_COMMANDS="$CONFIG_COMMANDS bindings/ocaml/Makefile.ocaml" ;;
+
+ *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
+echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
+ { (exit 1); exit 1; }; };;
+ esac
+done
+
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used. Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+ test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+ test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
+ test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands
+fi
+
+# Have a temporary directory for convenience. Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+ tmp=
+ trap 'exit_status=$?
+ { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+' 0
+ trap '{ (exit 1); exit 1; }' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+ tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+ test -n "$tmp" && test -d "$tmp"
+} ||
+{
+ tmp=./conf$$-$RANDOM
+ (umask 077 && mkdir "$tmp")
+} ||
+{
+ echo "$me: cannot create a temporary directory in ." >&2
+ { (exit 1); exit 1; }
+}
+
+#
+# Set up the sed scripts for CONFIG_FILES section.
+#
+
+# No need to generate the scripts if there are no CONFIG_FILES.
+# This happens for instance when ./config.status config.h
+if test -n "$CONFIG_FILES"; then
+
+_ACEOF
+
+
+
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+ cat >conf$$subs.sed <<_ACEOF
+SHELL!$SHELL$ac_delim
+PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
+PACKAGE_NAME!$PACKAGE_NAME$ac_delim
+PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
+PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
+PACKAGE_STRING!$PACKAGE_STRING$ac_delim
+PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
+exec_prefix!$exec_prefix$ac_delim
+prefix!$prefix$ac_delim
+program_transform_name!$program_transform_name$ac_delim
+bindir!$bindir$ac_delim
+sbindir!$sbindir$ac_delim
+libexecdir!$libexecdir$ac_delim
+datarootdir!$datarootdir$ac_delim
+datadir!$datadir$ac_delim
+sysconfdir!$sysconfdir$ac_delim
+sharedstatedir!$sharedstatedir$ac_delim
+localstatedir!$localstatedir$ac_delim
+includedir!$includedir$ac_delim
+oldincludedir!$oldincludedir$ac_delim
+docdir!$docdir$ac_delim
+infodir!$infodir$ac_delim
+htmldir!$htmldir$ac_delim
+dvidir!$dvidir$ac_delim
+pdfdir!$pdfdir$ac_delim
+psdir!$psdir$ac_delim
+libdir!$libdir$ac_delim
+localedir!$localedir$ac_delim
+mandir!$mandir$ac_delim
+DEFS!$DEFS$ac_delim
+ECHO_C!$ECHO_C$ac_delim
+ECHO_N!$ECHO_N$ac_delim
+ECHO_T!$ECHO_T$ac_delim
+LIBS!$LIBS$ac_delim
+build_alias!$build_alias$ac_delim
+host_alias!$host_alias$ac_delim
+target_alias!$target_alias$ac_delim
+LLVM_COPYRIGHT!$LLVM_COPYRIGHT$ac_delim
+CC!$CC$ac_delim
+CFLAGS!$CFLAGS$ac_delim
+LDFLAGS!$LDFLAGS$ac_delim
+CPPFLAGS!$CPPFLAGS$ac_delim
+ac_ct_CC!$ac_ct_CC$ac_delim
+EXEEXT!$EXEEXT$ac_delim
+OBJEXT!$OBJEXT$ac_delim
+CXX!$CXX$ac_delim
+CXXFLAGS!$CXXFLAGS$ac_delim
+ac_ct_CXX!$ac_ct_CXX$ac_delim
+CPP!$CPP$ac_delim
+subdirs!$subdirs$ac_delim
+ENABLE_POLLY!$ENABLE_POLLY$ac_delim
+LLVM_HAS_POLLY!$LLVM_HAS_POLLY$ac_delim
+build!$build$ac_delim
+build_cpu!$build_cpu$ac_delim
+build_vendor!$build_vendor$ac_delim
+build_os!$build_os$ac_delim
+host!$host$ac_delim
+host_cpu!$host_cpu$ac_delim
+host_vendor!$host_vendor$ac_delim
+host_os!$host_os$ac_delim
+target!$target$ac_delim
+target_cpu!$target_cpu$ac_delim
+target_vendor!$target_vendor$ac_delim
+target_os!$target_os$ac_delim
+OS!$OS$ac_delim
+HOST_OS!$HOST_OS$ac_delim
+TARGET_OS!$TARGET_OS$ac_delim
+LINKALL!$LINKALL$ac_delim
+NOLINKALL!$NOLINKALL$ac_delim
+LLVM_ON_UNIX!$LLVM_ON_UNIX$ac_delim
+LLVM_ON_WIN32!$LLVM_ON_WIN32$ac_delim
+ARCH!$ARCH$ac_delim
+HOST_ARCH!$HOST_ARCH$ac_delim
+ENDIAN!$ENDIAN$ac_delim
+GREP!$GREP$ac_delim
+EGREP!$EGREP$ac_delim
+LLVM_CROSS_COMPILING!$LLVM_CROSS_COMPILING$ac_delim
+BUILD_CC!$BUILD_CC$ac_delim
+BUILD_EXEEXT!$BUILD_EXEEXT$ac_delim
+BUILD_CXX!$BUILD_CXX$ac_delim
+CVSBUILD!$CVSBUILD$ac_delim
+ENABLE_LIBCPP!$ENABLE_LIBCPP$ac_delim
+ENABLE_CXX11!$ENABLE_CXX11$ac_delim
+ENABLE_OPTIMIZED!$ENABLE_OPTIMIZED$ac_delim
+ENABLE_PROFILING!$ENABLE_PROFILING$ac_delim
+DISABLE_ASSERTIONS!$DISABLE_ASSERTIONS$ac_delim
+ENABLE_WERROR!$ENABLE_WERROR$ac_delim
+ENABLE_EXPENSIVE_CHECKS!$ENABLE_EXPENSIVE_CHECKS$ac_delim
+EXPENSIVE_CHECKS!$EXPENSIVE_CHECKS$ac_delim
+DEBUG_RUNTIME!$DEBUG_RUNTIME$ac_delim
+DEBUG_SYMBOLS!$DEBUG_SYMBOLS$ac_delim
+KEEP_SYMBOLS!$KEEP_SYMBOLS$ac_delim
+JIT!$JIT$ac_delim
+TARGET_HAS_JIT!$TARGET_HAS_JIT$ac_delim
+ENABLE_DOCS!$ENABLE_DOCS$ac_delim
+ENABLE_DOXYGEN!$ENABLE_DOXYGEN$ac_delim
+LLVM_ENABLE_THREADS!$LLVM_ENABLE_THREADS$ac_delim
+_ACEOF
+
+ if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 97; then
+ break
+ elif $ac_last_try; then
+ { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
+echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
+ { (exit 1); exit 1; }; }
+ else
+ ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+ fi
+done
+
+ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
+if test -n "$ac_eof"; then
+ ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
+ ac_eof=`expr $ac_eof + 1`
+fi
+
+cat >>$CONFIG_STATUS <<_ACEOF
+cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+_ACEOF
+sed '
+s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
+s/^/s,@/; s/!/@,|#_!!_#|/
+:n
+t n
+s/'"$ac_delim"'$/,g/; t
+s/$/\\/; p
+N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
+' >>$CONFIG_STATUS <conf$$subs.sed
+rm -f conf$$subs.sed
+cat >>$CONFIG_STATUS <<_ACEOF
+CEOF$ac_eof
+_ACEOF
+
+
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+ cat >conf$$subs.sed <<_ACEOF
+ENABLE_PTHREADS!$ENABLE_PTHREADS$ac_delim
+ENABLE_PIC!$ENABLE_PIC$ac_delim
+ENABLE_SHARED!$ENABLE_SHARED$ac_delim
+ENABLE_EMBED_STDCXX!$ENABLE_EMBED_STDCXX$ac_delim
+ENABLE_TIMESTAMPS!$ENABLE_TIMESTAMPS$ac_delim
+TARGETS_TO_BUILD!$TARGETS_TO_BUILD$ac_delim
+LLVM_ENUM_TARGETS!$LLVM_ENUM_TARGETS$ac_delim
+LLVM_ENUM_ASM_PRINTERS!$LLVM_ENUM_ASM_PRINTERS$ac_delim
+LLVM_ENUM_ASM_PARSERS!$LLVM_ENUM_ASM_PARSERS$ac_delim
+LLVM_ENUM_DISASSEMBLERS!$LLVM_ENUM_DISASSEMBLERS$ac_delim
+OPTIMIZE_OPTION!$OPTIMIZE_OPTION$ac_delim
+EXTRA_OPTIONS!$EXTRA_OPTIONS$ac_delim
+EXTRA_LD_OPTIONS!$EXTRA_LD_OPTIONS$ac_delim
+CLANG_SRC_ROOT!$CLANG_SRC_ROOT$ac_delim
+BINUTILS_INCDIR!$BINUTILS_INCDIR$ac_delim
+INTERNAL_PREFIX!$INTERNAL_PREFIX$ac_delim
+NM!$NM$ac_delim
+ifGNUmake!$ifGNUmake$ac_delim
+LN_S!$LN_S$ac_delim
+CMP!$CMP$ac_delim
+CP!$CP$ac_delim
+DATE!$DATE$ac_delim
+FIND!$FIND$ac_delim
+MKDIR!$MKDIR$ac_delim
+MV!$MV$ac_delim
+RANLIB!$RANLIB$ac_delim
+AR!$AR$ac_delim
+RM!$RM$ac_delim
+SED!$SED$ac_delim
+TAR!$TAR$ac_delim
+BINPWD!$BINPWD$ac_delim
+GRAPHVIZ!$GRAPHVIZ$ac_delim
+DOT!$DOT$ac_delim
+FDP!$FDP$ac_delim
+NEATO!$NEATO$ac_delim
+TWOPI!$TWOPI$ac_delim
+CIRCO!$CIRCO$ac_delim
+GV!$GV$ac_delim
+DOTTY!$DOTTY$ac_delim
+XDOT_PY!$XDOT_PY$ac_delim
+INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim
+INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim
+INSTALL_DATA!$INSTALL_DATA$ac_delim
+BZIP2!$BZIP2$ac_delim
+CAT!$CAT$ac_delim
+DOXYGEN!$DOXYGEN$ac_delim
+GROFF!$GROFF$ac_delim
+GZIPBIN!$GZIPBIN$ac_delim
+PDFROFF!$PDFROFF$ac_delim
+ZIP!$ZIP$ac_delim
+OCAMLC!$OCAMLC$ac_delim
+OCAMLOPT!$OCAMLOPT$ac_delim
+OCAMLDEP!$OCAMLDEP$ac_delim
+OCAMLDOC!$OCAMLDOC$ac_delim
+GAS!$GAS$ac_delim
+HAVE_LINK_VERSION_SCRIPT!$HAVE_LINK_VERSION_SCRIPT$ac_delim
+INSTALL_LTDL_TRUE!$INSTALL_LTDL_TRUE$ac_delim
+INSTALL_LTDL_FALSE!$INSTALL_LTDL_FALSE$ac_delim
+CONVENIENCE_LTDL_TRUE!$CONVENIENCE_LTDL_TRUE$ac_delim
+CONVENIENCE_LTDL_FALSE!$CONVENIENCE_LTDL_FALSE$ac_delim
+LIBADD_DL!$LIBADD_DL$ac_delim
+NO_VARIADIC_MACROS!$NO_VARIADIC_MACROS$ac_delim
+NO_MISSING_FIELD_INITIALIZERS!$NO_MISSING_FIELD_INITIALIZERS$ac_delim
+COVERED_SWITCH_DEFAULT!$COVERED_SWITCH_DEFAULT$ac_delim
+USE_UDIS86!$USE_UDIS86$ac_delim
+USE_OPROFILE!$USE_OPROFILE$ac_delim
+USE_INTEL_JITEVENTS!$USE_INTEL_JITEVENTS$ac_delim
+INTEL_JITEVENTS_INCDIR!$INTEL_JITEVENTS_INCDIR$ac_delim
+INTEL_JITEVENTS_LIBDIR!$INTEL_JITEVENTS_LIBDIR$ac_delim
+XML2CONFIG!$XML2CONFIG$ac_delim
+LIBXML2_LIBS!$LIBXML2_LIBS$ac_delim
+LIBXML2_INC!$LIBXML2_INC$ac_delim
+HAVE_PTHREAD!$HAVE_PTHREAD$ac_delim
+HUGE_VAL_SANITY!$HUGE_VAL_SANITY$ac_delim
+MMAP_FILE!$MMAP_FILE$ac_delim
+SHLIBEXT!$SHLIBEXT$ac_delim
+SHLIBPATH_VAR!$SHLIBPATH_VAR$ac_delim
+LLVM_PREFIX!$LLVM_PREFIX$ac_delim
+LLVM_BINDIR!$LLVM_BINDIR$ac_delim
+LLVM_LIBDIR!$LLVM_LIBDIR$ac_delim
+LLVM_DATADIR!$LLVM_DATADIR$ac_delim
+LLVM_DOCSDIR!$LLVM_DOCSDIR$ac_delim
+LLVM_ETCDIR!$LLVM_ETCDIR$ac_delim
+LLVM_INCLUDEDIR!$LLVM_INCLUDEDIR$ac_delim
+LLVM_INFODIR!$LLVM_INFODIR$ac_delim
+LLVM_MANDIR!$LLVM_MANDIR$ac_delim
+LLVM_CONFIGTIME!$LLVM_CONFIGTIME$ac_delim
+BINDINGS_TO_BUILD!$BINDINGS_TO_BUILD$ac_delim
+ALL_BINDINGS!$ALL_BINDINGS$ac_delim
+OCAML_LIBDIR!$OCAML_LIBDIR$ac_delim
+ENABLE_VISIBILITY_INLINES_HIDDEN!$ENABLE_VISIBILITY_INLINES_HIDDEN$ac_delim
+RPATH!$RPATH$ac_delim
+RDYNAMIC!$RDYNAMIC$ac_delim
+LIBOBJS!$LIBOBJS$ac_delim
+LTLIBOBJS!$LTLIBOBJS$ac_delim
+_ACEOF
+
+ if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 95; then
+ break
+ elif $ac_last_try; then
+ { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
+echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
+ { (exit 1); exit 1; }; }
+ else
+ ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+ fi
+done
+
+ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
+if test -n "$ac_eof"; then
+ ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
+ ac_eof=`expr $ac_eof + 1`
+fi
+
+cat >>$CONFIG_STATUS <<_ACEOF
+cat >"\$tmp/subs-2.sed" <<\CEOF$ac_eof
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
+_ACEOF
+sed '
+s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
+s/^/s,@/; s/!/@,|#_!!_#|/
+:n
+t n
+s/'"$ac_delim"'$/,g/; t
+s/$/\\/; p
+N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
+' >>$CONFIG_STATUS <conf$$subs.sed
+rm -f conf$$subs.sed
+cat >>$CONFIG_STATUS <<_ACEOF
+:end
+s/|#_!!_#|//g
+CEOF$ac_eof
+_ACEOF
+
+
+# VPATH may cause trouble with some makes, so we remove $(srcdir),
+# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+ ac_vpsub='/^[ ]*VPATH[ ]*=/{
+s/:*\$(srcdir):*/:/
+s/:*\${srcdir}:*/:/
+s/:*@srcdir@:*/:/
+s/^\([^=]*=[ ]*\):*/\1/
+s/:*$//
+s/^[^=]*=[ ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+fi # test -n "$CONFIG_FILES"
+
+
+for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS
+do
+ case $ac_tag in
+ :[FHLC]) ac_mode=$ac_tag; continue;;
+ esac
+ case $ac_mode$ac_tag in
+ :[FHL]*:*);;
+ :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
+echo "$as_me: error: Invalid tag $ac_tag." >&2;}
+ { (exit 1); exit 1; }; };;
+ :[FH]-) ac_tag=-:-;;
+ :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+ esac
+ ac_save_IFS=$IFS
+ IFS=:
+ set x $ac_tag
+ IFS=$ac_save_IFS
+ shift
+ ac_file=$1
+ shift
+
+ case $ac_mode in
+ :L) ac_source=$1;;
+ :[FH])
+ ac_file_inputs=
+ for ac_f
+ do
+ case $ac_f in
+ -) ac_f="$tmp/stdin";;
+ *) # Look for the file first in the build tree, then in the source tree
+ # (if the path is not absolute). The absolute path cannot be DOS-style,
+ # because $ac_f cannot contain `:'.
+ test -f "$ac_f" ||
+ case $ac_f in
+ [\\/$]*) false;;
+ *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+ esac ||
+ { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
+echo "$as_me: error: cannot find input file: $ac_f" >&2;}
+ { (exit 1); exit 1; }; };;
+ esac
+ ac_file_inputs="$ac_file_inputs $ac_f"
+ done
+
+ # Let's still pretend it is `configure' which instantiates (i.e., don't
+ # use $as_me), people would be surprised to read:
+ # /* config.h. Generated by config.status. */
+ configure_input="Generated from "`IFS=:
+ echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
+ if test x"$ac_file" != x-; then
+ configure_input="$ac_file. $configure_input"
+ { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+ fi
+
+ case $ac_tag in
+ *:-:* | *:-) cat >"$tmp/stdin";;
+ esac
+ ;;
+ esac
+
+ ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$ac_file" : 'X\(//\)[^/]' \| \
+ X"$ac_file" : 'X\(//\)$' \| \
+ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$ac_file" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ { as_dir="$ac_dir"
+ case $as_dir in #(
+ -*) as_dir=./$as_dir;;
+ esac
+ test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+ as_dirs=
+ while :; do
+ case $as_dir in #(
+ *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+ *) as_qdir=$as_dir;;
+ esac
+ as_dirs="'$as_qdir' $as_dirs"
+ as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$as_dir" : 'X\(//\)[^/]' \| \
+ X"$as_dir" : 'X\(//\)$' \| \
+ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ test -d "$as_dir" && break
+ done
+ test -z "$as_dirs" || eval "mkdir $as_dirs"
+ } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+ { (exit 1); exit 1; }; }; }
+ ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+ ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+ # A ".." for each directory in $ac_dir_suffix.
+ ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+ case $ac_top_builddir_sub in
+ "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+ *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+ esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+ .) # We are building in place.
+ ac_srcdir=.
+ ac_top_srcdir=$ac_top_builddir_sub
+ ac_abs_top_srcdir=$ac_pwd ;;
+ [\\/]* | ?:[\\/]* ) # Absolute name.
+ ac_srcdir=$srcdir$ac_dir_suffix;
+ ac_top_srcdir=$srcdir
+ ac_abs_top_srcdir=$srcdir ;;
+ *) # Relative name.
+ ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+ ac_top_srcdir=$ac_top_build_prefix$srcdir
+ ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+ case $ac_mode in
+ :F)
+ #
+ # CONFIG_FILE
+ #
+
+ case $INSTALL in
+ [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
+ *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
+ esac
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+
+case `sed -n '/datarootdir/ {
+ p
+ q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p
+' $ac_file_inputs` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+ { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+ ac_datarootdir_hack='
+ s&@datadir@&$datadir&g
+ s&@docdir@&$docdir&g
+ s&@infodir@&$infodir&g
+ s&@localedir@&$localedir&g
+ s&@mandir@&$mandir&g
+ s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF
+ sed "$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s&@configure_input@&$configure_input&;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+s&@INSTALL@&$ac_INSTALL&;t t
+$ac_datarootdir_hack
+" $ac_file_inputs | sed -f "$tmp/subs-1.sed" | sed -f "$tmp/subs-2.sed" >$tmp/out
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+ { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+ { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+ { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined. Please make sure it is defined." >&5
+echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined. Please make sure it is defined." >&2;}
+
+ rm -f "$tmp/stdin"
+ case $ac_file in
+ -) cat "$tmp/out"; rm -f "$tmp/out";;
+ *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
+ esac
+ ;;
+ :H)
+ #
+ # CONFIG_HEADER
+ #
+_ACEOF
+
+# Transform confdefs.h into a sed script `conftest.defines', that
+# substitutes the proper values into config.h.in to produce config.h.
+rm -f conftest.defines conftest.tail
+# First, append a space to every undef/define line, to ease matching.
+echo 's/$/ /' >conftest.defines
+# Then, protect against being on the right side of a sed subst, or in
+# an unquoted here document, in config.status. If some macros were
+# called several times there might be several #defines for the same
+# symbol, which is useless. But do not sort them, since the last
+# AC_DEFINE must be honored.
+ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
+# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where
+# NAME is the cpp macro being defined, VALUE is the value it is being given.
+# PARAMS is the parameter list in the macro definition--in most cases, it's
+# just an empty string.
+ac_dA='s,^\\([ #]*\\)[^ ]*\\([ ]*'
+ac_dB='\\)[ (].*,\\1define\\2'
+ac_dC=' '
+ac_dD=' ,'
+
+uniq confdefs.h |
+ sed -n '
+ t rset
+ :rset
+ s/^[ ]*#[ ]*define[ ][ ]*//
+ t ok
+ d
+ :ok
+ s/[\\&,]/\\&/g
+ s/^\('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p
+ s/^\('"$ac_word_re"'\)[ ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p
+ ' >>conftest.defines
+
+# Remove the space that was appended to ease matching.
+# Then replace #undef with comments. This is necessary, for
+# example, in the case of _POSIX_SOURCE, which is predefined and required
+# on some systems where configure will not decide to define it.
+# (The regexp can be short, since the line contains either #define or #undef.)
+echo 's/ $//
+s,^[ #]*u.*,/* & */,' >>conftest.defines
+
+# Break up conftest.defines:
+ac_max_sed_lines=50
+
+# First sed command is: sed -f defines.sed $ac_file_inputs >"$tmp/out1"
+# Second one is: sed -f defines.sed "$tmp/out1" >"$tmp/out2"
+# Third one will be: sed -f defines.sed "$tmp/out2" >"$tmp/out1"
+# et cetera.
+ac_in='$ac_file_inputs'
+ac_out='"$tmp/out1"'
+ac_nxt='"$tmp/out2"'
+
+while :
+do
+ # Write a here document:
+ cat >>$CONFIG_STATUS <<_ACEOF
+ # First, check the format of the line:
+ cat >"\$tmp/defines.sed" <<\\CEOF
+/^[ ]*#[ ]*undef[ ][ ]*$ac_word_re[ ]*\$/b def
+/^[ ]*#[ ]*define[ ][ ]*$ac_word_re[( ]/b def
+b
+:def
+_ACEOF
+ sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS
+ echo 'CEOF
+ sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS
+ ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in
+ sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail
+ grep . conftest.tail >/dev/null || break
+ rm -f conftest.defines
+ mv conftest.tail conftest.defines
+done
+rm -f conftest.defines conftest.tail
+
+echo "ac_result=$ac_in" >>$CONFIG_STATUS
+cat >>$CONFIG_STATUS <<\_ACEOF
+ if test x"$ac_file" != x-; then
+ echo "/* $configure_input */" >"$tmp/config.h"
+ cat "$ac_result" >>"$tmp/config.h"
+ if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then
+ { echo "$as_me:$LINENO: $ac_file is unchanged" >&5
+echo "$as_me: $ac_file is unchanged" >&6;}
+ else
+ rm -f $ac_file
+ mv "$tmp/config.h" $ac_file
+ fi
+ else
+ echo "/* $configure_input */"
+ cat "$ac_result"
+ fi
+ rm -f "$tmp/out12"
+ ;;
+
+ :C) { echo "$as_me:$LINENO: executing $ac_file commands" >&5
+echo "$as_me: executing $ac_file commands" >&6;}
+ ;;
+ esac
+
+
+ case $ac_file$ac_mode in
+ "Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/Makefile Makefile ;;
+ "Makefile.common":C) ${llvm_src}/autoconf/mkinstalldirs `dirname Makefile.common`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/Makefile.common Makefile.common ;;
+ "examples/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname examples/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/examples/Makefile examples/Makefile ;;
+ "lib/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname lib/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/lib/Makefile lib/Makefile ;;
+ "runtime/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname runtime/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/runtime/Makefile runtime/Makefile ;;
+ "test/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname test/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/test/Makefile test/Makefile ;;
+ "test/Makefile.tests":C) ${llvm_src}/autoconf/mkinstalldirs `dirname test/Makefile.tests`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/test/Makefile.tests test/Makefile.tests ;;
+ "unittests/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname unittests/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/unittests/Makefile unittests/Makefile ;;
+ "tools/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname tools/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/tools/Makefile tools/Makefile ;;
+ "utils/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname utils/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/utils/Makefile utils/Makefile ;;
+ "projects/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname projects/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/projects/Makefile projects/Makefile ;;
+ "bindings/Makefile":C) ${llvm_src}/autoconf/mkinstalldirs `dirname bindings/Makefile`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/bindings/Makefile bindings/Makefile ;;
+ "bindings/ocaml/Makefile.ocaml":C) ${llvm_src}/autoconf/mkinstalldirs `dirname bindings/ocaml/Makefile.ocaml`
+ ${SHELL} ${llvm_src}/autoconf/install-sh -m 0644 -c ${srcdir}/bindings/ocaml/Makefile.ocaml bindings/ocaml/Makefile.ocaml ;;
+
+ esac
+done # for ac_tag
+
+
+{ (exit 0); exit 0; }
+_ACEOF
+chmod +x $CONFIG_STATUS
+ac_clean_files=$ac_clean_files_save
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded. So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status. When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+ ac_cs_success=:
+ ac_config_status_args=
+ test "$silent" = yes &&
+ ac_config_status_args="$ac_config_status_args --quiet"
+ exec 5>/dev/null
+ $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+ exec 5>>config.log
+ # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+ # would make configure fail if this is the last instruction.
+ $ac_cs_success || { (exit 1); exit 1; }
+fi
+
+#
+# CONFIG_SUBDIRS section.
+#
+if test "$no_recursion" != yes; then
+
+ # Remove --cache-file and --srcdir arguments so they do not pile up.
+ ac_sub_configure_args=
+ ac_prev=
+ eval "set x $ac_configure_args"
+ shift
+ for ac_arg
+ do
+ if test -n "$ac_prev"; then
+ ac_prev=
+ continue
+ fi
+ case $ac_arg in
+ -cache-file | --cache-file | --cache-fil | --cache-fi \
+ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+ ac_prev=cache_file ;;
+ -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* \
+ | --c=*)
+ ;;
+ --config-cache | -C)
+ ;;
+ -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+ ac_prev=srcdir ;;
+ -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+ ;;
+ -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+ ac_prev=prefix ;;
+ -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+ ;;
+ *)
+ case $ac_arg in
+ *\'*) ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+ esac
+ ac_sub_configure_args="$ac_sub_configure_args '$ac_arg'" ;;
+ esac
+ done
+
+ # Always prepend --prefix to ensure using the same prefix
+ # in subdir configurations.
+ ac_arg="--prefix=$prefix"
+ case $ac_arg in
+ *\'*) ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+ esac
+ ac_sub_configure_args="$ac_arg $ac_sub_configure_args"
+
+ ac_popdir=`pwd`
+ for ac_dir in : $subdirs; do test "x$ac_dir" = x: && continue
+
+ # Do not complain, so a configure script can configure whichever
+ # parts of a large source tree are present.
+ test -d "$srcdir/$ac_dir" || continue
+
+ ac_msg="=== configuring in $ac_dir (`pwd`/$ac_dir)"
+ echo "$as_me:$LINENO: $ac_msg" >&5
+ echo "$ac_msg" >&6
+ { as_dir="$ac_dir"
+ case $as_dir in #(
+ -*) as_dir=./$as_dir;;
+ esac
+ test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+ as_dirs=
+ while :; do
+ case $as_dir in #(
+ *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+ *) as_qdir=$as_dir;;
+ esac
+ as_dirs="'$as_qdir' $as_dirs"
+ as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$as_dir" : 'X\(//\)[^/]' \| \
+ X"$as_dir" : 'X\(//\)$' \| \
+ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ test -d "$as_dir" && break
+ done
+ test -z "$as_dirs" || eval "mkdir $as_dirs"
+ } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+ { (exit 1); exit 1; }; }; }
+ ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+ ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+ # A ".." for each directory in $ac_dir_suffix.
+ ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+ case $ac_top_builddir_sub in
+ "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+ *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+ esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+ .) # We are building in place.
+ ac_srcdir=.
+ ac_top_srcdir=$ac_top_builddir_sub
+ ac_abs_top_srcdir=$ac_pwd ;;
+ [\\/]* | ?:[\\/]* ) # Absolute name.
+ ac_srcdir=$srcdir$ac_dir_suffix;
+ ac_top_srcdir=$srcdir
+ ac_abs_top_srcdir=$srcdir ;;
+ *) # Relative name.
+ ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+ ac_top_srcdir=$ac_top_build_prefix$srcdir
+ ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+ cd "$ac_dir"
+
+ # Check for guested configure; otherwise get Cygnus style configure.
+ if test -f "$ac_srcdir/configure.gnu"; then
+ ac_sub_configure=$ac_srcdir/configure.gnu
+ elif test -f "$ac_srcdir/configure"; then
+ ac_sub_configure=$ac_srcdir/configure
+ elif test -f "$ac_srcdir/configure.in"; then
+ # This should be Cygnus configure.
+ ac_sub_configure=$ac_aux_dir/configure
+ else
+ { echo "$as_me:$LINENO: WARNING: no configuration information is in $ac_dir" >&5
+echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2;}
+ ac_sub_configure=
+ fi
+
+ # The recursion is here.
+ if test -n "$ac_sub_configure"; then
+ # Make the cache file name correct relative to the subdirectory.
+ case $cache_file in
+ [\\/]* | ?:[\\/]* ) ac_sub_cache_file=$cache_file ;;
+ *) # Relative name.
+ ac_sub_cache_file=$ac_top_build_prefix$cache_file ;;
+ esac
+
+ { echo "$as_me:$LINENO: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&5
+echo "$as_me: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&6;}
+ # The eval makes quoting arguments work.
+ eval "\$SHELL \"\$ac_sub_configure\" $ac_sub_configure_args \
+ --cache-file=\"\$ac_sub_cache_file\" --srcdir=\"\$ac_srcdir\"" ||
+ { { echo "$as_me:$LINENO: error: $ac_sub_configure failed for $ac_dir" >&5
+echo "$as_me: error: $ac_sub_configure failed for $ac_dir" >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+
+ cd "$ac_popdir"
+ done
+fi
+
diff --git a/docs/AliasAnalysis.rst b/docs/AliasAnalysis.rst
new file mode 100644
index 00000000000..2d4f2914ee0
--- /dev/null
+++ b/docs/AliasAnalysis.rst
@@ -0,0 +1,702 @@
+.. _alias_analysis:
+
+==================================
+LLVM Alias Analysis Infrastructure
+==================================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+Alias Analysis (aka Pointer Analysis) is a class of techniques which attempt to
+determine whether or not two pointers ever can point to the same object in
+memory. There are many different algorithms for alias analysis and many
+different ways of classifying them: flow-sensitive vs. flow-insensitive,
+context-sensitive vs. context-insensitive, field-sensitive
+vs. field-insensitive, unification-based vs. subset-based, etc. Traditionally,
+alias analyses respond to a query with a `Must, May, or No`_ alias response,
+indicating that two pointers always point to the same object, might point to the
+same object, or are known to never point to the same object.
+
+The LLVM `AliasAnalysis
+<http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__ class is the
+primary interface used by clients and implementations of alias analyses in the
+LLVM system. This class is the common interface between clients of alias
+analysis information and the implementations providing it, and is designed to
+support a wide range of implementations and clients (but currently all clients
+are assumed to be flow-insensitive). In addition to simple alias analysis
+information, this class exposes Mod/Ref information from those implementations
+which can provide it, allowing for powerful analyses and transformations to work
+well together.
+
+This document contains information necessary to successfully implement this
+interface, use it, and to test both sides. It also explains some of the finer
+points about what exactly results mean. If you feel that something is unclear
+or should be added, please `let me know <mailto:sabre@nondot.org>`_.
+
+``AliasAnalysis`` Class Overview
+================================
+
+The `AliasAnalysis <http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__
+class defines the interface that the various alias analysis implementations
+should support. This class exports two important enums: ``AliasResult`` and
+``ModRefResult`` which represent the result of an alias query or a mod/ref
+query, respectively.
+
+The ``AliasAnalysis`` interface exposes information about memory, represented in
+several different ways. In particular, memory objects are represented as a
+starting address and size, and function calls are represented as the actual
+``call`` or ``invoke`` instructions that performs the call. The
+``AliasAnalysis`` interface also exposes some helper methods which allow you to
+get mod/ref information for arbitrary instructions.
+
+All ``AliasAnalysis`` interfaces require that in queries involving multiple
+values, values which are not `constants <LangRef.html#constants>`_ are all
+defined within the same function.
+
+Representation of Pointers
+--------------------------
+
+Most importantly, the ``AliasAnalysis`` class provides several methods which are
+used to query whether or not two memory objects alias, whether function calls
+can modify or read a memory object, etc. For all of these queries, memory
+objects are represented as a pair of their starting address (a symbolic LLVM
+``Value*``) and a static size.
+
+Representing memory objects as a starting address and a size is critically
+important for correct Alias Analyses. For example, consider this (silly, but
+possible) C code:
+
+.. code-block:: c++
+
+ int i;
+ char C[2];
+ char A[10];
+ /* ... */
+ for (i = 0; i != 10; ++i) {
+ C[0] = A[i]; /* One byte store */
+ C[1] = A[9-i]; /* One byte store */
+ }
+
+In this case, the ``basicaa`` pass will disambiguate the stores to ``C[0]`` and
+``C[1]`` because they are accesses to two distinct locations one byte apart, and
+the accesses are each one byte. In this case, the Loop Invariant Code Motion
+(LICM) pass can use store motion to remove the stores from the loop. In
+constrast, the following code:
+
+.. code-block:: c++
+
+ int i;
+ char C[2];
+ char A[10];
+ /* ... */
+ for (i = 0; i != 10; ++i) {
+ ((short*)C)[0] = A[i]; /* Two byte store! */
+ C[1] = A[9-i]; /* One byte store */
+ }
+
+In this case, the two stores to C do alias each other, because the access to the
+``&C[0]`` element is a two byte access. If size information wasn't available in
+the query, even the first case would have to conservatively assume that the
+accesses alias.
+
+.. _alias:
+
+The ``alias`` method
+--------------------
+
+The ``alias`` method is the primary interface used to determine whether or not
+two memory objects alias each other. It takes two memory objects as input and
+returns MustAlias, PartialAlias, MayAlias, or NoAlias as appropriate.
+
+Like all ``AliasAnalysis`` interfaces, the ``alias`` method requires that either
+the two pointer values be defined within the same function, or at least one of
+the values is a `constant <LangRef.html#constants>`_.
+
+.. _Must, May, or No:
+
+Must, May, and No Alias Responses
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``NoAlias`` response may be used when there is never an immediate dependence
+between any memory reference *based* on one pointer and any memory reference
+*based* the other. The most obvious example is when the two pointers point to
+non-overlapping memory ranges. Another is when the two pointers are only ever
+used for reading memory. Another is when the memory is freed and reallocated
+between accesses through one pointer and accesses through the other --- in this
+case, there is a dependence, but it's mediated by the free and reallocation.
+
+As an exception to this is with the `noalias <LangRef.html#noalias>`_ keyword;
+the "irrelevant" dependencies are ignored.
+
+The ``MayAlias`` response is used whenever the two pointers might refer to the
+same object.
+
+The ``PartialAlias`` response is used when the two memory objects are known to
+be overlapping in some way, but do not start at the same address.
+
+The ``MustAlias`` response may only be returned if the two memory objects are
+guaranteed to always start at exactly the same location. A ``MustAlias``
+response implies that the pointers compare equal.
+
+The ``getModRefInfo`` methods
+-----------------------------
+
+The ``getModRefInfo`` methods return information about whether the execution of
+an instruction can read or modify a memory location. Mod/Ref information is
+always conservative: if an instruction **might** read or write a location,
+``ModRef`` is returned.
+
+The ``AliasAnalysis`` class also provides a ``getModRefInfo`` method for testing
+dependencies between function calls. This method takes two call sites (``CS1``
+& ``CS2``), returns ``NoModRef`` if neither call writes to memory read or
+written by the other, ``Ref`` if ``CS1`` reads memory written by ``CS2``,
+``Mod`` if ``CS1`` writes to memory read or written by ``CS2``, or ``ModRef`` if
+``CS1`` might read or write memory written to by ``CS2``. Note that this
+relation is not commutative.
+
+Other useful ``AliasAnalysis`` methods
+--------------------------------------
+
+Several other tidbits of information are often collected by various alias
+analysis implementations and can be put to good use by various clients.
+
+The ``pointsToConstantMemory`` method
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``pointsToConstantMemory`` method returns true if and only if the analysis
+can prove that the pointer only points to unchanging memory locations
+(functions, constant global variables, and the null pointer). This information
+can be used to refine mod/ref information: it is impossible for an unchanging
+memory location to be modified.
+
+.. _never access memory or only read memory:
+
+The ``doesNotAccessMemory`` and ``onlyReadsMemory`` methods
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+These methods are used to provide very simple mod/ref information for function
+calls. The ``doesNotAccessMemory`` method returns true for a function if the
+analysis can prove that the function never reads or writes to memory, or if the
+function only reads from constant memory. Functions with this property are
+side-effect free and only depend on their input arguments, allowing them to be
+eliminated if they form common subexpressions or be hoisted out of loops. Many
+common functions behave this way (e.g., ``sin`` and ``cos``) but many others do
+not (e.g., ``acos``, which modifies the ``errno`` variable).
+
+The ``onlyReadsMemory`` method returns true for a function if analysis can prove
+that (at most) the function only reads from non-volatile memory. Functions with
+this property are side-effect free, only depending on their input arguments and
+the state of memory when they are called. This property allows calls to these
+functions to be eliminated and moved around, as long as there is no store
+instruction that changes the contents of memory. Note that all functions that
+satisfy the ``doesNotAccessMemory`` method also satisfies ``onlyReadsMemory``.
+
+Writing a new ``AliasAnalysis`` Implementation
+==============================================
+
+Writing a new alias analysis implementation for LLVM is quite straight-forward.
+There are already several implementations that you can use for examples, and the
+following information should help fill in any details. For a examples, take a
+look at the `various alias analysis implementations`_ included with LLVM.
+
+Different Pass styles
+---------------------
+
+The first step to determining what type of `LLVM pass <WritingAnLLVMPass.html>`_
+you need to use for your Alias Analysis. As is the case with most other
+analyses and transformations, the answer should be fairly obvious from what type
+of problem you are trying to solve:
+
+#. If you require interprocedural analysis, it should be a ``Pass``.
+#. If you are a function-local analysis, subclass ``FunctionPass``.
+#. If you don't need to look at the program at all, subclass ``ImmutablePass``.
+
+In addition to the pass that you subclass, you should also inherit from the
+``AliasAnalysis`` interface, of course, and use the ``RegisterAnalysisGroup``
+template to register as an implementation of ``AliasAnalysis``.
+
+Required initialization calls
+-----------------------------
+
+Your subclass of ``AliasAnalysis`` is required to invoke two methods on the
+``AliasAnalysis`` base class: ``getAnalysisUsage`` and
+``InitializeAliasAnalysis``. In particular, your implementation of
+``getAnalysisUsage`` should explicitly call into the
+``AliasAnalysis::getAnalysisUsage`` method in addition to doing any declaring
+any pass dependencies your pass has. Thus you should have something like this:
+
+.. code-block:: c++
+
+ void getAnalysisUsage(AnalysisUsage &amp;AU) const {
+ AliasAnalysis::getAnalysisUsage(AU);
+ // declare your dependencies here.
+ }
+
+Additionally, your must invoke the ``InitializeAliasAnalysis`` method from your
+analysis run method (``run`` for a ``Pass``, ``runOnFunction`` for a
+``FunctionPass``, or ``InitializePass`` for an ``ImmutablePass``). For example
+(as part of a ``Pass``):
+
+.. code-block:: c++
+
+ bool run(Module &M) {
+ InitializeAliasAnalysis(this);
+ // Perform analysis here...
+ return false;
+ }
+
+Interfaces which may be specified
+---------------------------------
+
+All of the `AliasAnalysis
+<http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__ virtual methods
+default to providing `chaining`_ to another alias analysis implementation, which
+ends up returning conservatively correct information (returning "May" Alias and
+"Mod/Ref" for alias and mod/ref queries respectively). Depending on the
+capabilities of the analysis you are implementing, you just override the
+interfaces you can improve.
+
+.. _chaining:
+.. _chain:
+
+``AliasAnalysis`` chaining behavior
+-----------------------------------
+
+With only one special exception (the `no-aa`_ pass) every alias analysis pass
+chains to another alias analysis implementation (for example, the user can
+specify "``-basicaa -ds-aa -licm``" to get the maximum benefit from both alias
+analyses). The alias analysis class automatically takes care of most of this
+for methods that you don't override. For methods that you do override, in code
+paths that return a conservative MayAlias or Mod/Ref result, simply return
+whatever the superclass computes. For example:
+
+.. code-block:: c++
+
+ AliasAnalysis::AliasResult alias(const Value *V1, unsigned V1Size,
+ const Value *V2, unsigned V2Size) {
+ if (...)
+ return NoAlias;
+ ...
+
+ // Couldn't determine a must or no-alias result.
+ return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
+ }
+
+In addition to analysis queries, you must make sure to unconditionally pass LLVM
+`update notification`_ methods to the superclass as well if you override them,
+which allows all alias analyses in a change to be updated.
+
+.. _update notification:
+
+Updating analysis results for transformations
+---------------------------------------------
+
+Alias analysis information is initially computed for a static snapshot of the
+program, but clients will use this information to make transformations to the
+code. All but the most trivial forms of alias analysis will need to have their
+analysis results updated to reflect the changes made by these transformations.
+
+The ``AliasAnalysis`` interface exposes four methods which are used to
+communicate program changes from the clients to the analysis implementations.
+Various alias analysis implementations should use these methods to ensure that
+their internal data structures are kept up-to-date as the program changes (for
+example, when an instruction is deleted), and clients of alias analysis must be
+sure to call these interfaces appropriately.
+
+The ``deleteValue`` method
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``deleteValue`` method is called by transformations when they remove an
+instruction or any other value from the program (including values that do not
+use pointers). Typically alias analyses keep data structures that have entries
+for each value in the program. When this method is called, they should remove
+any entries for the specified value, if they exist.
+
+The ``copyValue`` method
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``copyValue`` method is used when a new value is introduced into the
+program. There is no way to introduce a value into the program that did not
+exist before (this doesn't make sense for a safe compiler transformation), so
+this is the only way to introduce a new value. This method indicates that the
+new value has exactly the same properties as the value being copied.
+
+The ``replaceWithNewValue`` method
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+This method is a simple helper method that is provided to make clients easier to
+use. It is implemented by copying the old analysis information to the new
+value, then deleting the old value. This method cannot be overridden by alias
+analysis implementations.
+
+The ``addEscapingUse`` method
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``addEscapingUse`` method is used when the uses of a pointer value have
+changed in ways that may invalidate precomputed analysis information.
+Implementations may either use this callback to provide conservative responses
+for points whose uses have change since analysis time, or may recompute some or
+all of their internal state to continue providing accurate responses.
+
+In general, any new use of a pointer value is considered an escaping use, and
+must be reported through this callback, *except* for the uses below:
+
+* A ``bitcast`` or ``getelementptr`` of the pointer
+* A ``store`` through the pointer (but not a ``store`` *of* the pointer)
+* A ``load`` through the pointer
+
+Efficiency Issues
+-----------------
+
+From the LLVM perspective, the only thing you need to do to provide an efficient
+alias analysis is to make sure that alias analysis **queries** are serviced
+quickly. The actual calculation of the alias analysis results (the "run"
+method) is only performed once, but many (perhaps duplicate) queries may be
+performed. Because of this, try to move as much computation to the run method
+as possible (within reason).
+
+Limitations
+-----------
+
+The AliasAnalysis infrastructure has several limitations which make writing a
+new ``AliasAnalysis`` implementation difficult.
+
+There is no way to override the default alias analysis. It would be very useful
+to be able to do something like "``opt -my-aa -O2``" and have it use ``-my-aa``
+for all passes which need AliasAnalysis, but there is currently no support for
+that, short of changing the source code and recompiling. Similarly, there is
+also no way of setting a chain of analyses as the default.
+
+There is no way for transform passes to declare that they preserve
+``AliasAnalysis`` implementations. The ``AliasAnalysis`` interface includes
+``deleteValue`` and ``copyValue`` methods which are intended to allow a pass to
+keep an AliasAnalysis consistent, however there's no way for a pass to declare
+in its ``getAnalysisUsage`` that it does so. Some passes attempt to use
+``AU.addPreserved<AliasAnalysis>``, however this doesn't actually have any
+effect.
+
+``AliasAnalysisCounter`` (``-count-aa``) and ``AliasDebugger`` (``-debug-aa``)
+are implemented as ``ModulePass`` classes, so if your alias analysis uses
+``FunctionPass``, it won't be able to use these utilities. If you try to use
+them, the pass manager will silently route alias analysis queries directly to
+``BasicAliasAnalysis`` instead.
+
+Similarly, the ``opt -p`` option introduces ``ModulePass`` passes between each
+pass, which prevents the use of ``FunctionPass`` alias analysis passes.
+
+The ``AliasAnalysis`` API does have functions for notifying implementations when
+values are deleted or copied, however these aren't sufficient. There are many
+other ways that LLVM IR can be modified which could be relevant to
+``AliasAnalysis`` implementations which can not be expressed.
+
+The ``AliasAnalysisDebugger`` utility seems to suggest that ``AliasAnalysis``
+implementations can expect that they will be informed of any relevant ``Value``
+before it appears in an alias query. However, popular clients such as ``GVN``
+don't support this, and are known to trigger errors when run with the
+``AliasAnalysisDebugger``.
+
+Due to several of the above limitations, the most obvious use for the
+``AliasAnalysisCounter`` utility, collecting stats on all alias queries in a
+compilation, doesn't work, even if the ``AliasAnalysis`` implementations don't
+use ``FunctionPass``. There's no way to set a default, much less a default
+sequence, and there's no way to preserve it.
+
+The ``AliasSetTracker`` class (which is used by ``LICM``) makes a
+non-deterministic number of alias queries. This can cause stats collected by
+``AliasAnalysisCounter`` to have fluctuations among identical runs, for
+example. Another consequence is that debugging techniques involving pausing
+execution after a predetermined number of queries can be unreliable.
+
+Many alias queries can be reformulated in terms of other alias queries. When
+multiple ``AliasAnalysis`` queries are chained together, it would make sense to
+start those queries from the beginning of the chain, with care taken to avoid
+infinite looping, however currently an implementation which wants to do this can
+only start such queries from itself.
+
+Using alias analysis results
+============================
+
+There are several different ways to use alias analysis results. In order of
+preference, these are:
+
+Using the ``MemoryDependenceAnalysis`` Pass
+-------------------------------------------
+
+The ``memdep`` pass uses alias analysis to provide high-level dependence
+information about memory-using instructions. This will tell you which store
+feeds into a load, for example. It uses caching and other techniques to be
+efficient, and is used by Dead Store Elimination, GVN, and memcpy optimizations.
+
+.. _AliasSetTracker:
+
+Using the ``AliasSetTracker`` class
+-----------------------------------
+
+Many transformations need information about alias **sets** that are active in
+some scope, rather than information about pairwise aliasing. The
+`AliasSetTracker <http://llvm.org/doxygen/classllvm_1_1AliasSetTracker.html>`__
+class is used to efficiently build these Alias Sets from the pairwise alias
+analysis information provided by the ``AliasAnalysis`` interface.
+
+First you initialize the AliasSetTracker by using the "``add``" methods to add
+information about various potentially aliasing instructions in the scope you are
+interested in. Once all of the alias sets are completed, your pass should
+simply iterate through the constructed alias sets, using the ``AliasSetTracker``
+``begin()``/``end()`` methods.
+
+The ``AliasSet``\s formed by the ``AliasSetTracker`` are guaranteed to be
+disjoint, calculate mod/ref information and volatility for the set, and keep
+track of whether or not all of the pointers in the set are Must aliases. The
+AliasSetTracker also makes sure that sets are properly folded due to call
+instructions, and can provide a list of pointers in each set.
+
+As an example user of this, the `Loop Invariant Code Motion
+<doxygen/structLICM.html>`_ pass uses ``AliasSetTracker``\s to calculate alias
+sets for each loop nest. If an ``AliasSet`` in a loop is not modified, then all
+load instructions from that set may be hoisted out of the loop. If any alias
+sets are stored to **and** are must alias sets, then the stores may be sunk
+to outside of the loop, promoting the memory location to a register for the
+duration of the loop nest. Both of these transformations only apply if the
+pointer argument is loop-invariant.
+
+The AliasSetTracker implementation
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The AliasSetTracker class is implemented to be as efficient as possible. It
+uses the union-find algorithm to efficiently merge AliasSets when a pointer is
+inserted into the AliasSetTracker that aliases multiple sets. The primary data
+structure is a hash table mapping pointers to the AliasSet they are in.
+
+The AliasSetTracker class must maintain a list of all of the LLVM ``Value*``\s
+that are in each AliasSet. Since the hash table already has entries for each
+LLVM ``Value*`` of interest, the AliasesSets thread the linked list through
+these hash-table nodes to avoid having to allocate memory unnecessarily, and to
+make merging alias sets extremely efficient (the linked list merge is constant
+time).
+
+You shouldn't need to understand these details if you are just a client of the
+AliasSetTracker, but if you look at the code, hopefully this brief description
+will help make sense of why things are designed the way they are.
+
+Using the ``AliasAnalysis`` interface directly
+----------------------------------------------
+
+If neither of these utility class are what your pass needs, you should use the
+interfaces exposed by the ``AliasAnalysis`` class directly. Try to use the
+higher-level methods when possible (e.g., use mod/ref information instead of the
+`alias`_ method directly if possible) to get the best precision and efficiency.
+
+Existing alias analysis implementations and clients
+===================================================
+
+If you're going to be working with the LLVM alias analysis infrastructure, you
+should know what clients and implementations of alias analysis are available.
+In particular, if you are implementing an alias analysis, you should be aware of
+the `the clients`_ that are useful for monitoring and evaluating different
+implementations.
+
+.. _various alias analysis implementations:
+
+Available ``AliasAnalysis`` implementations
+-------------------------------------------
+
+This section lists the various implementations of the ``AliasAnalysis``
+interface. With the exception of the `-no-aa`_ implementation, all of these
+`chain`_ to other alias analysis implementations.
+
+.. _no-aa:
+.. _-no-aa:
+
+The ``-no-aa`` pass
+^^^^^^^^^^^^^^^^^^^
+
+The ``-no-aa`` pass is just like what it sounds: an alias analysis that never
+returns any useful information. This pass can be useful if you think that alias
+analysis is doing something wrong and are trying to narrow down a problem.
+
+The ``-basicaa`` pass
+^^^^^^^^^^^^^^^^^^^^^
+
+The ``-basicaa`` pass is an aggressive local analysis that *knows* many
+important facts:
+
+* Distinct globals, stack allocations, and heap allocations can never alias.
+* Globals, stack allocations, and heap allocations never alias the null pointer.
+* Different fields of a structure do not alias.
+* Indexes into arrays with statically differing subscripts cannot alias.
+* Many common standard C library functions `never access memory or only read
+ memory`_.
+* Pointers that obviously point to constant globals "``pointToConstantMemory``".
+* Function calls can not modify or references stack allocations if they never
+ escape from the function that allocates them (a common case for automatic
+ arrays).
+
+The ``-globalsmodref-aa`` pass
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+This pass implements a simple context-sensitive mod/ref and alias analysis for
+internal global variables that don't "have their address taken". If a global
+does not have its address taken, the pass knows that no pointers alias the
+global. This pass also keeps track of functions that it knows never access
+memory or never read memory. This allows certain optimizations (e.g. GVN) to
+eliminate call instructions entirely.
+
+The real power of this pass is that it provides context-sensitive mod/ref
+information for call instructions. This allows the optimizer to know that calls
+to a function do not clobber or read the value of the global, allowing loads and
+stores to be eliminated.
+
+.. note::
+
+ This pass is somewhat limited in its scope (only support non-address taken
+ globals), but is very quick analysis.
+
+The ``-steens-aa`` pass
+^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``-steens-aa`` pass implements a variation on the well-known "Steensgaard's
+algorithm" for interprocedural alias analysis. Steensgaard's algorithm is a
+unification-based, flow-insensitive, context-insensitive, and field-insensitive
+alias analysis that is also very scalable (effectively linear time).
+
+The LLVM ``-steens-aa`` pass implements a "speculatively field-**sensitive**"
+version of Steensgaard's algorithm using the Data Structure Analysis framework.
+This gives it substantially more precision than the standard algorithm while
+maintaining excellent analysis scalability.
+
+.. note::
+
+ ``-steens-aa`` is available in the optional "poolalloc" module. It is not part
+ of the LLVM core.
+
+The ``-ds-aa`` pass
+^^^^^^^^^^^^^^^^^^^
+
+The ``-ds-aa`` pass implements the full Data Structure Analysis algorithm. Data
+Structure Analysis is a modular unification-based, flow-insensitive,
+context-**sensitive**, and speculatively field-**sensitive** alias
+analysis that is also quite scalable, usually at ``O(n * log(n))``.
+
+This algorithm is capable of responding to a full variety of alias analysis
+queries, and can provide context-sensitive mod/ref information as well. The
+only major facility not implemented so far is support for must-alias
+information.
+
+.. note::
+
+ ``-ds-aa`` is available in the optional "poolalloc" module. It is not part of
+ the LLVM core.
+
+The ``-scev-aa`` pass
+^^^^^^^^^^^^^^^^^^^^^
+
+The ``-scev-aa`` pass implements AliasAnalysis queries by translating them into
+ScalarEvolution queries. This gives it a more complete understanding of
+``getelementptr`` instructions and loop induction variables than other alias
+analyses have.
+
+Alias analysis driven transformations
+-------------------------------------
+
+LLVM includes several alias-analysis driven transformations which can be used
+with any of the implementations above.
+
+The ``-adce`` pass
+^^^^^^^^^^^^^^^^^^
+
+The ``-adce`` pass, which implements Aggressive Dead Code Elimination uses the
+``AliasAnalysis`` interface to delete calls to functions that do not have
+side-effects and are not used.
+
+The ``-licm`` pass
+^^^^^^^^^^^^^^^^^^
+
+The ``-licm`` pass implements various Loop Invariant Code Motion related
+transformations. It uses the ``AliasAnalysis`` interface for several different
+transformations:
+
+* It uses mod/ref information to hoist or sink load instructions out of loops if
+ there are no instructions in the loop that modifies the memory loaded.
+
+* It uses mod/ref information to hoist function calls out of loops that do not
+ write to memory and are loop-invariant.
+
+* If uses alias information to promote memory objects that are loaded and stored
+ to in loops to live in a register instead. It can do this if there are no may
+ aliases to the loaded/stored memory location.
+
+The ``-argpromotion`` pass
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``-argpromotion`` pass promotes by-reference arguments to be passed in
+by-value instead. In particular, if pointer arguments are only loaded from it
+passes in the value loaded instead of the address to the function. This pass
+uses alias information to make sure that the value loaded from the argument
+pointer is not modified between the entry of the function and any load of the
+pointer.
+
+The ``-gvn``, ``-memcpyopt``, and ``-dse`` passes
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+These passes use AliasAnalysis information to reason about loads and stores.
+
+.. _the clients:
+
+Clients for debugging and evaluation of implementations
+-------------------------------------------------------
+
+These passes are useful for evaluating the various alias analysis
+implementations. You can use them with commands like:
+
+.. code-block:: bash
+
+ % opt -ds-aa -aa-eval foo.bc -disable-output -stats
+
+The ``-print-alias-sets`` pass
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``-print-alias-sets`` pass is exposed as part of the ``opt`` tool to print
+out the Alias Sets formed by the `AliasSetTracker`_ class. This is useful if
+you're using the ``AliasSetTracker`` class. To use it, use something like:
+
+.. code-block:: bash
+
+ % opt -ds-aa -print-alias-sets -disable-output
+
+The ``-count-aa`` pass
+^^^^^^^^^^^^^^^^^^^^^^
+
+The ``-count-aa`` pass is useful to see how many queries a particular pass is
+making and what responses are returned by the alias analysis. As an example:
+
+.. code-block:: bash
+
+ % opt -basicaa -count-aa -ds-aa -count-aa -licm
+
+will print out how many queries (and what responses are returned) by the
+``-licm`` pass (of the ``-ds-aa`` pass) and how many queries are made of the
+``-basicaa`` pass by the ``-ds-aa`` pass. This can be useful when debugging a
+transformation or an alias analysis implementation.
+
+The ``-aa-eval`` pass
+^^^^^^^^^^^^^^^^^^^^^
+
+The ``-aa-eval`` pass simply iterates through all pairs of pointers in a
+function and asks an alias analysis whether or not the pointers alias. This
+gives an indication of the precision of the alias analysis. Statistics are
+printed indicating the percent of no/may/must aliases found (a more precise
+algorithm will have a lower number of may aliases).
+
+Memory Dependence Analysis
+==========================
+
+If you're just looking to be a client of alias analysis information, consider
+using the Memory Dependence Analysis interface instead. MemDep is a lazy,
+caching layer on top of alias analysis that is able to answer the question of
+what preceding memory operations a given instruction depends on, either at an
+intra- or inter-block level. Because of its laziness and caching policy, using
+MemDep can be a significant performance win over accessing alias analysis
+directly.
diff --git a/docs/Atomics.rst b/docs/Atomics.rst
new file mode 100644
index 00000000000..1bca53e2b17
--- /dev/null
+++ b/docs/Atomics.rst
@@ -0,0 +1,441 @@
+.. _atomics:
+
+==============================================
+LLVM Atomic Instructions and Concurrency Guide
+==============================================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+Historically, LLVM has not had very strong support for concurrency; some minimal
+intrinsics were provided, and ``volatile`` was used in some cases to achieve
+rough semantics in the presence of concurrency. However, this is changing;
+there are now new instructions which are well-defined in the presence of threads
+and asynchronous signals, and the model for existing instructions has been
+clarified in the IR.
+
+The atomic instructions are designed specifically to provide readable IR and
+optimized code generation for the following:
+
+* The new C++0x ``<atomic>`` header. (`C++0x draft available here
+ <http://www.open-std.org/jtc1/sc22/wg21/>`_.) (`C1x draft available here
+ <http://www.open-std.org/jtc1/sc22/wg14/>`_.)
+
+* Proper semantics for Java-style memory, for both ``volatile`` and regular
+ shared variables. (`Java Specification
+ <http://java.sun.com/docs/books/jls/third_edition/html/memory.html>`_)
+
+* gcc-compatible ``__sync_*`` builtins. (`Description
+ <http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html>`_)
+
+* Other scenarios with atomic semantics, including ``static`` variables with
+ non-trivial constructors in C++.
+
+Atomic and volatile in the IR are orthogonal; "volatile" is the C/C++ volatile,
+which ensures that every volatile load and store happens and is performed in the
+stated order. A couple examples: if a SequentiallyConsistent store is
+immediately followed by another SequentiallyConsistent store to the same
+address, the first store can be erased. This transformation is not allowed for a
+pair of volatile stores. On the other hand, a non-volatile non-atomic load can
+be moved across a volatile load freely, but not an Acquire load.
+
+This document is intended to provide a guide to anyone either writing a frontend
+for LLVM or working on optimization passes for LLVM with a guide for how to deal
+with instructions with special semantics in the presence of concurrency. This
+is not intended to be a precise guide to the semantics; the details can get
+extremely complicated and unreadable, and are not usually necessary.
+
+.. _Optimization outside atomic:
+
+Optimization outside atomic
+===========================
+
+The basic ``'load'`` and ``'store'`` allow a variety of optimizations, but can
+lead to undefined results in a concurrent environment; see `NotAtomic`_. This
+section specifically goes into the one optimizer restriction which applies in
+concurrent environments, which gets a bit more of an extended description
+because any optimization dealing with stores needs to be aware of it.
+
+From the optimizer's point of view, the rule is that if there are not any
+instructions with atomic ordering involved, concurrency does not matter, with
+one exception: if a variable might be visible to another thread or signal
+handler, a store cannot be inserted along a path where it might not execute
+otherwise. Take the following example:
+
+.. code-block:: c
+
+ /* C code, for readability; run through clang -O2 -S -emit-llvm to get
+ equivalent IR */
+ int x;
+ void f(int* a) {
+ for (int i = 0; i < 100; i++) {
+ if (a[i])
+ x += 1;
+ }
+ }
+
+The following is equivalent in non-concurrent situations:
+
+.. code-block:: c
+
+ int x;
+ void f(int* a) {
+ int xtemp = x;
+ for (int i = 0; i < 100; i++) {
+ if (a[i])
+ xtemp += 1;
+ }
+ x = xtemp;
+ }
+
+However, LLVM is not allowed to transform the former to the latter: it could
+indirectly introduce undefined behavior if another thread can access ``x`` at
+the same time. (This example is particularly of interest because before the
+concurrency model was implemented, LLVM would perform this transformation.)
+
+Note that speculative loads are allowed; a load which is part of a race returns
+``undef``, but does not have undefined behavior.
+
+Atomic instructions
+===================
+
+For cases where simple loads and stores are not sufficient, LLVM provides
+various atomic instructions. The exact guarantees provided depend on the
+ordering; see `Atomic orderings`_.
+
+``load atomic`` and ``store atomic`` provide the same basic functionality as
+non-atomic loads and stores, but provide additional guarantees in situations
+where threads and signals are involved.
+
+``cmpxchg`` and ``atomicrmw`` are essentially like an atomic load followed by an
+atomic store (where the store is conditional for ``cmpxchg``), but no other
+memory operation can happen on any thread between the load and store. Note that
+LLVM's cmpxchg does not provide quite as many options as the C++0x version.
+
+A ``fence`` provides Acquire and/or Release ordering which is not part of
+another operation; it is normally used along with Monotonic memory operations.
+A Monotonic load followed by an Acquire fence is roughly equivalent to an
+Acquire load.
+
+Frontends generating atomic instructions generally need to be aware of the
+target to some degree; atomic instructions are guaranteed to be lock-free, and
+therefore an instruction which is wider than the target natively supports can be
+impossible to generate.
+
+.. _Atomic orderings:
+
+Atomic orderings
+================
+
+In order to achieve a balance between performance and necessary guarantees,
+there are six levels of atomicity. They are listed in order of strength; each
+level includes all the guarantees of the previous level except for
+Acquire/Release. (See also `LangRef Ordering <LangRef.html#ordering>`_.)
+
+.. _NotAtomic:
+
+NotAtomic
+---------
+
+NotAtomic is the obvious, a load or store which is not atomic. (This isn't
+really a level of atomicity, but is listed here for comparison.) This is
+essentially a regular load or store. If there is a race on a given memory
+location, loads from that location return undef.
+
+Relevant standard
+ This is intended to match shared variables in C/C++, and to be used in any
+ other context where memory access is necessary, and a race is impossible. (The
+ precise definition is in `LangRef Memory Model <LangRef.html#memmodel>`_.)
+
+Notes for frontends
+ The rule is essentially that all memory accessed with basic loads and stores
+ by multiple threads should be protected by a lock or other synchronization;
+ otherwise, you are likely to run into undefined behavior. If your frontend is
+ for a "safe" language like Java, use Unordered to load and store any shared
+ variable. Note that NotAtomic volatile loads and stores are not properly
+ atomic; do not try to use them as a substitute. (Per the C/C++ standards,
+ volatile does provide some limited guarantees around asynchronous signals, but
+ atomics are generally a better solution.)
+
+Notes for optimizers
+ Introducing loads to shared variables along a codepath where they would not
+ otherwise exist is allowed; introducing stores to shared variables is not. See
+ `Optimization outside atomic`_.
+
+Notes for code generation
+ The one interesting restriction here is that it is not allowed to write to
+ bytes outside of the bytes relevant to a store. This is mostly relevant to
+ unaligned stores: it is not allowed in general to convert an unaligned store
+ into two aligned stores of the same width as the unaligned store. Backends are
+ also expected to generate an i8 store as an i8 store, and not an instruction
+ which writes to surrounding bytes. (If you are writing a backend for an
+ architecture which cannot satisfy these restrictions and cares about
+ concurrency, please send an email to llvmdev.)
+
+Unordered
+---------
+
+Unordered is the lowest level of atomicity. It essentially guarantees that races
+produce somewhat sane results instead of having undefined behavior. It also
+guarantees the operation to be lock-free, so it do not depend on the data being
+part of a special atomic structure or depend on a separate per-process global
+lock. Note that code generation will fail for unsupported atomic operations; if
+you need such an operation, use explicit locking.
+
+Relevant standard
+ This is intended to match the Java memory model for shared variables.
+
+Notes for frontends
+ This cannot be used for synchronization, but is useful for Java and other
+ "safe" languages which need to guarantee that the generated code never
+ exhibits undefined behavior. Note that this guarantee is cheap on common
+ platforms for loads of a native width, but can be expensive or unavailable for
+ wider loads, like a 64-bit store on ARM. (A frontend for Java or other "safe"
+ languages would normally split a 64-bit store on ARM into two 32-bit unordered
+ stores.)
+
+Notes for optimizers
+ In terms of the optimizer, this prohibits any transformation that transforms a
+ single load into multiple loads, transforms a store into multiple stores,
+ narrows a store, or stores a value which would not be stored otherwise. Some
+ examples of unsafe optimizations are narrowing an assignment into a bitfield,
+ rematerializing a load, and turning loads and stores into a memcpy
+ call. Reordering unordered operations is safe, though, and optimizers should
+ take advantage of that because unordered operations are common in languages
+ that need them.
+
+Notes for code generation
+ These operations are required to be atomic in the sense that if you use
+ unordered loads and unordered stores, a load cannot see a value which was
+ never stored. A normal load or store instruction is usually sufficient, but
+ note that an unordered load or store cannot be split into multiple
+ instructions (or an instruction which does multiple memory operations, like
+ ``LDRD`` on ARM).
+
+Monotonic
+---------
+
+Monotonic is the weakest level of atomicity that can be used in synchronization
+primitives, although it does not provide any general synchronization. It
+essentially guarantees that if you take all the operations affecting a specific
+address, a consistent ordering exists.
+
+Relevant standard
+ This corresponds to the C++0x/C1x ``memory_order_relaxed``; see those
+ standards for the exact definition.
+
+Notes for frontends
+ If you are writing a frontend which uses this directly, use with caution. The
+ guarantees in terms of synchronization are very weak, so make sure these are
+ only used in a pattern which you know is correct. Generally, these would
+ either be used for atomic operations which do not protect other memory (like
+ an atomic counter), or along with a ``fence``.
+
+Notes for optimizers
+ In terms of the optimizer, this can be treated as a read+write on the relevant
+ memory location (and alias analysis will take advantage of that). In addition,
+ it is legal to reorder non-atomic and Unordered loads around Monotonic
+ loads. CSE/DSE and a few other optimizations are allowed, but Monotonic
+ operations are unlikely to be used in ways which would make those
+ optimizations useful.
+
+Notes for code generation
+ Code generation is essentially the same as that for unordered for loads and
+ stores. No fences are required. ``cmpxchg`` and ``atomicrmw`` are required
+ to appear as a single operation.
+
+Acquire
+-------
+
+Acquire provides a barrier of the sort necessary to acquire a lock to access
+other memory with normal loads and stores.
+
+Relevant standard
+ This corresponds to the C++0x/C1x ``memory_order_acquire``. It should also be
+ used for C++0x/C1x ``memory_order_consume``.
+
+Notes for frontends
+ If you are writing a frontend which uses this directly, use with caution.
+ Acquire only provides a semantic guarantee when paired with a Release
+ operation.
+
+Notes for optimizers
+ Optimizers not aware of atomics can treat this like a nothrow call. It is
+ also possible to move stores from before an Acquire load or read-modify-write
+ operation to after it, and move non-Acquire loads from before an Acquire
+ operation to after it.
+
+Notes for code generation
+ Architectures with weak memory ordering (essentially everything relevant today
+ except x86 and SPARC) require some sort of fence to maintain the Acquire
+ semantics. The precise fences required varies widely by architecture, but for
+ a simple implementation, most architectures provide a barrier which is strong
+ enough for everything (``dmb`` on ARM, ``sync`` on PowerPC, etc.). Putting
+ such a fence after the equivalent Monotonic operation is sufficient to
+ maintain Acquire semantics for a memory operation.
+
+Release
+-------
+
+Release is similar to Acquire, but with a barrier of the sort necessary to
+release a lock.
+
+Relevant standard
+ This corresponds to the C++0x/C1x ``memory_order_release``.
+
+Notes for frontends
+ If you are writing a frontend which uses this directly, use with caution.
+ Release only provides a semantic guarantee when paired with a Acquire
+ operation.
+
+Notes for optimizers
+ Optimizers not aware of atomics can treat this like a nothrow call. It is
+ also possible to move loads from after a Release store or read-modify-write
+ operation to before it, and move non-Release stores from after an Release
+ operation to before it.
+
+Notes for code generation
+ See the section on Acquire; a fence before the relevant operation is usually
+ sufficient for Release. Note that a store-store fence is not sufficient to
+ implement Release semantics; store-store fences are generally not exposed to
+ IR because they are extremely difficult to use correctly.
+
+AcquireRelease
+--------------
+
+AcquireRelease (``acq_rel`` in IR) provides both an Acquire and a Release
+barrier (for fences and operations which both read and write memory).
+
+Relevant standard
+ This corresponds to the C++0x/C1x ``memory_order_acq_rel``.
+
+Notes for frontends
+ If you are writing a frontend which uses this directly, use with caution.
+ Acquire only provides a semantic guarantee when paired with a Release
+ operation, and vice versa.
+
+Notes for optimizers
+ In general, optimizers should treat this like a nothrow call; the possible
+ optimizations are usually not interesting.
+
+Notes for code generation
+ This operation has Acquire and Release semantics; see the sections on Acquire
+ and Release.
+
+SequentiallyConsistent
+----------------------
+
+SequentiallyConsistent (``seq_cst`` in IR) provides Acquire semantics for loads
+and Release semantics for stores. Additionally, it guarantees that a total
+ordering exists between all SequentiallyConsistent operations.
+
+Relevant standard
+ This corresponds to the C++0x/C1x ``memory_order_seq_cst``, Java volatile, and
+ the gcc-compatible ``__sync_*`` builtins which do not specify otherwise.
+
+Notes for frontends
+ If a frontend is exposing atomic operations, these are much easier to reason
+ about for the programmer than other kinds of operations, and using them is
+ generally a practical performance tradeoff.
+
+Notes for optimizers
+ Optimizers not aware of atomics can treat this like a nothrow call. For
+ SequentiallyConsistent loads and stores, the same reorderings are allowed as
+ for Acquire loads and Release stores, except that SequentiallyConsistent
+ operations may not be reordered.
+
+Notes for code generation
+ SequentiallyConsistent loads minimally require the same barriers as Acquire
+ operations and SequentiallyConsistent stores require Release
+ barriers. Additionally, the code generator must enforce ordering between
+ SequentiallyConsistent stores followed by SequentiallyConsistent loads. This
+ is usually done by emitting either a full fence before the loads or a full
+ fence after the stores; which is preferred varies by architecture.
+
+Atomics and IR optimization
+===========================
+
+Predicates for optimizer writers to query:
+
+* ``isSimple()``: A load or store which is not volatile or atomic. This is
+ what, for example, memcpyopt would check for operations it might transform.
+
+* ``isUnordered()``: A load or store which is not volatile and at most
+ Unordered. This would be checked, for example, by LICM before hoisting an
+ operation.
+
+* ``mayReadFromMemory()``/``mayWriteToMemory()``: Existing predicate, but note
+ that they return true for any operation which is volatile or at least
+ Monotonic.
+
+* Alias analysis: Note that AA will return ModRef for anything Acquire or
+ Release, and for the address accessed by any Monotonic operation.
+
+To support optimizing around atomic operations, make sure you are using the
+right predicates; everything should work if that is done. If your pass should
+optimize some atomic operations (Unordered operations in particular), make sure
+it doesn't replace an atomic load or store with a non-atomic operation.
+
+Some examples of how optimizations interact with various kinds of atomic
+operations:
+
+* ``memcpyopt``: An atomic operation cannot be optimized into part of a
+ memcpy/memset, including unordered loads/stores. It can pull operations
+ across some atomic operations.
+
+* LICM: Unordered loads/stores can be moved out of a loop. It just treats
+ monotonic operations like a read+write to a memory location, and anything
+ stricter than that like a nothrow call.
+
+* DSE: Unordered stores can be DSE'ed like normal stores. Monotonic stores can
+ be DSE'ed in some cases, but it's tricky to reason about, and not especially
+ important.
+
+* Folding a load: Any atomic load from a constant global can be constant-folded,
+ because it cannot be observed. Similar reasoning allows scalarrepl with
+ atomic loads and stores.
+
+Atomics and Codegen
+===================
+
+Atomic operations are represented in the SelectionDAG with ``ATOMIC_*`` opcodes.
+On architectures which use barrier instructions for all atomic ordering (like
+ARM), appropriate fences are split out as the DAG is built.
+
+The MachineMemOperand for all atomic operations is currently marked as volatile;
+this is not correct in the IR sense of volatile, but CodeGen handles anything
+marked volatile very conservatively. This should get fixed at some point.
+
+Common architectures have some way of representing at least a pointer-sized
+lock-free ``cmpxchg``; such an operation can be used to implement all the other
+atomic operations which can be represented in IR up to that size. Backends are
+expected to implement all those operations, but not operations which cannot be
+implemented in a lock-free manner. It is expected that backends will give an
+error when given an operation which cannot be implemented. (The LLVM code
+generator is not very helpful here at the moment, but hopefully that will
+change.)
+
+The implementation of atomics on LL/SC architectures (like ARM) is currently a
+bit of a mess; there is a lot of copy-pasted code across targets, and the
+representation is relatively unsuited to optimization (it would be nice to be
+able to optimize loops involving cmpxchg etc.).
+
+On x86, all atomic loads generate a ``MOV``. SequentiallyConsistent stores
+generate an ``XCHG``, other stores generate a ``MOV``. SequentiallyConsistent
+fences generate an ``MFENCE``, other fences do not cause any code to be
+generated. cmpxchg uses the ``LOCK CMPXCHG`` instruction. ``atomicrmw xchg``
+uses ``XCHG``, ``atomicrmw add`` and ``atomicrmw sub`` use ``XADD``, and all
+other ``atomicrmw`` operations generate a loop with ``LOCK CMPXCHG``. Depending
+on the users of the result, some ``atomicrmw`` operations can be translated into
+operations like ``LOCK AND``, but that does not work in general.
+
+On ARM, MIPS, and many other RISC architectures, Acquire, Release, and
+SequentiallyConsistent semantics require barrier instructions for every such
+operation. Loads and stores generate normal instructions. ``cmpxchg`` and
+``atomicrmw`` can be represented using a loop with LL/SC-style instructions
+which take some sort of exclusive lock on a cache line (``LDREX`` and ``STREX``
+on ARM, etc.). At the moment, the IR does not provide any way to represent a
+weak ``cmpxchg`` which would not require a loop.
diff --git a/docs/BitCodeFormat.rst b/docs/BitCodeFormat.rst
new file mode 100644
index 00000000000..d3995e7036b
--- /dev/null
+++ b/docs/BitCodeFormat.rst
@@ -0,0 +1,1045 @@
+.. _bitcode_format:
+
+.. role:: raw-html(raw)
+ :format: html
+
+========================
+LLVM Bitcode File Format
+========================
+
+.. contents::
+ :local:
+
+Abstract
+========
+
+This document describes the LLVM bitstream file format and the encoding of the
+LLVM IR into it.
+
+Overview
+========
+
+What is commonly known as the LLVM bitcode file format (also, sometimes
+anachronistically known as bytecode) is actually two things: a `bitstream
+container format`_ and an `encoding of LLVM IR`_ into the container format.
+
+The bitstream format is an abstract encoding of structured data, very similar to
+XML in some ways. Like XML, bitstream files contain tags, and nested
+structures, and you can parse the file without having to understand the tags.
+Unlike XML, the bitstream format is a binary encoding, and unlike XML it
+provides a mechanism for the file to self-describe "abbreviations", which are
+effectively size optimizations for the content.
+
+LLVM IR files may be optionally embedded into a `wrapper`_ structure that makes
+it easy to embed extra data along with LLVM IR files.
+
+This document first describes the LLVM bitstream format, describes the wrapper
+format, then describes the record structure used by LLVM IR files.
+
+.. _bitstream container format:
+
+Bitstream Format
+================
+
+The bitstream format is literally a stream of bits, with a very simple
+structure. This structure consists of the following concepts:
+
+* A "`magic number`_" that identifies the contents of the stream.
+
+* Encoding `primitives`_ like variable bit-rate integers.
+
+* `Blocks`_, which define nested content.
+
+* `Data Records`_, which describe entities within the file.
+
+* Abbreviations, which specify compression optimizations for the file.
+
+Note that the `llvm-bcanalyzer <CommandGuide/html/llvm-bcanalyzer.html>`_ tool
+can be used to dump and inspect arbitrary bitstreams, which is very useful for
+understanding the encoding.
+
+.. _magic number:
+
+Magic Numbers
+-------------
+
+The first two bytes of a bitcode file are 'BC' (``0x42``, ``0x43``). The second
+two bytes are an application-specific magic number. Generic bitcode tools can
+look at only the first two bytes to verify the file is bitcode, while
+application-specific programs will want to look at all four.
+
+.. _primitives:
+
+Primitives
+----------
+
+A bitstream literally consists of a stream of bits, which are read in order
+starting with the least significant bit of each byte. The stream is made up of
+a number of primitive values that encode a stream of unsigned integer values.
+These integers are encoded in two ways: either as `Fixed Width Integers`_ or as
+`Variable Width Integers`_.
+
+.. _Fixed Width Integers:
+.. _fixed-width value:
+
+Fixed Width Integers
+^^^^^^^^^^^^^^^^^^^^
+
+Fixed-width integer values have their low bits emitted directly to the file.
+For example, a 3-bit integer value encodes 1 as 001. Fixed width integers are
+used when there are a well-known number of options for a field. For example,
+boolean values are usually encoded with a 1-bit wide integer.
+
+.. _Variable Width Integers:
+.. _Variable Width Integer:
+.. _variable-width value:
+
+Variable Width Integers
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Variable-width integer (VBR) values encode values of arbitrary size, optimizing
+for the case where the values are small. Given a 4-bit VBR field, any 3-bit
+value (0 through 7) is encoded directly, with the high bit set to zero. Values
+larger than N-1 bits emit their bits in a series of N-1 bit chunks, where all
+but the last set the high bit.
+
+For example, the value 27 (0x1B) is encoded as 1011 0011 when emitted as a vbr4
+value. The first set of four bits indicates the value 3 (011) with a
+continuation piece (indicated by a high bit of 1). The next word indicates a
+value of 24 (011 << 3) with no continuation. The sum (3+24) yields the value
+27.
+
+.. _char6-encoded value:
+
+6-bit characters
+^^^^^^^^^^^^^^^^
+
+6-bit characters encode common characters into a fixed 6-bit field. They
+represent the following characters with the following 6-bit values:
+
+::
+
+ 'a' .. 'z' --- 0 .. 25
+ 'A' .. 'Z' --- 26 .. 51
+ '0' .. '9' --- 52 .. 61
+ '.' --- 62
+ '_' --- 63
+
+This encoding is only suitable for encoding characters and strings that consist
+only of the above characters. It is completely incapable of encoding characters
+not in the set.
+
+Word Alignment
+^^^^^^^^^^^^^^
+
+Occasionally, it is useful to emit zero bits until the bitstream is a multiple
+of 32 bits. This ensures that the bit position in the stream can be represented
+as a multiple of 32-bit words.
+
+Abbreviation IDs
+----------------
+
+A bitstream is a sequential series of `Blocks`_ and `Data Records`_. Both of
+these start with an abbreviation ID encoded as a fixed-bitwidth field. The
+width is specified by the current block, as described below. The value of the
+abbreviation ID specifies either a builtin ID (which have special meanings,
+defined below) or one of the abbreviation IDs defined for the current block by
+the stream itself.
+
+The set of builtin abbrev IDs is:
+
+* 0 - `END_BLOCK`_ --- This abbrev ID marks the end of the current block.
+
+* 1 - `ENTER_SUBBLOCK`_ --- This abbrev ID marks the beginning of a new
+ block.
+
+* 2 - `DEFINE_ABBREV`_ --- This defines a new abbreviation.
+
+* 3 - `UNABBREV_RECORD`_ --- This ID specifies the definition of an
+ unabbreviated record.
+
+Abbreviation IDs 4 and above are defined by the stream itself, and specify an
+`abbreviated record encoding`_.
+
+.. _Blocks:
+
+Blocks
+------
+
+Blocks in a bitstream denote nested regions of the stream, and are identified by
+a content-specific id number (for example, LLVM IR uses an ID of 12 to represent
+function bodies). Block IDs 0-7 are reserved for `standard blocks`_ whose
+meaning is defined by Bitcode; block IDs 8 and greater are application
+specific. Nested blocks capture the hierarchical structure of the data encoded
+in it, and various properties are associated with blocks as the file is parsed.
+Block definitions allow the reader to efficiently skip blocks in constant time
+if the reader wants a summary of blocks, or if it wants to efficiently skip data
+it does not understand. The LLVM IR reader uses this mechanism to skip function
+bodies, lazily reading them on demand.
+
+When reading and encoding the stream, several properties are maintained for the
+block. In particular, each block maintains:
+
+#. A current abbrev id width. This value starts at 2 at the beginning of the
+ stream, and is set every time a block record is entered. The block entry
+ specifies the abbrev id width for the body of the block.
+
+#. A set of abbreviations. Abbreviations may be defined within a block, in
+ which case they are only defined in that block (neither subblocks nor
+ enclosing blocks see the abbreviation). Abbreviations can also be defined
+ inside a `BLOCKINFO`_ block, in which case they are defined in all blocks
+ that match the ID that the ``BLOCKINFO`` block is describing.
+
+As sub blocks are entered, these properties are saved and the new sub-block has
+its own set of abbreviations, and its own abbrev id width. When a sub-block is
+popped, the saved values are restored.
+
+.. _ENTER_SUBBLOCK:
+
+ENTER_SUBBLOCK Encoding
+^^^^^^^^^^^^^^^^^^^^^^^
+
+:raw-html:`<tt>`
+[ENTER_SUBBLOCK, blockid\ :sub:`vbr8`, newabbrevlen\ :sub:`vbr4`, <align32bits>, blocklen_32]
+:raw-html:`</tt>`
+
+The ``ENTER_SUBBLOCK`` abbreviation ID specifies the start of a new block
+record. The ``blockid`` value is encoded as an 8-bit VBR identifier, and
+indicates the type of block being entered, which can be a `standard block`_ or
+an application-specific block. The ``newabbrevlen`` value is a 4-bit VBR, which
+specifies the abbrev id width for the sub-block. The ``blocklen`` value is a
+32-bit aligned value that specifies the size of the subblock in 32-bit
+words. This value allows the reader to skip over the entire block in one jump.
+
+.. _END_BLOCK:
+
+END_BLOCK Encoding
+^^^^^^^^^^^^^^^^^^
+
+``[END_BLOCK, <align32bits>]``
+
+The ``END_BLOCK`` abbreviation ID specifies the end of the current block record.
+Its end is aligned to 32-bits to ensure that the size of the block is an even
+multiple of 32-bits.
+
+.. _Data Records:
+
+Data Records
+------------
+
+Data records consist of a record code and a number of (up to) 64-bit integer
+values. The interpretation of the code and values is application specific and
+may vary between different block types. Records can be encoded either using an
+unabbrev record, or with an abbreviation. In the LLVM IR format, for example,
+there is a record which encodes the target triple of a module. The code is
+``MODULE_CODE_TRIPLE``, and the values of the record are the ASCII codes for the
+characters in the string.
+
+.. _UNABBREV_RECORD:
+
+UNABBREV_RECORD Encoding
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+:raw-html:`<tt>`
+[UNABBREV_RECORD, code\ :sub:`vbr6`, numops\ :sub:`vbr6`, op0\ :sub:`vbr6`, op1\ :sub:`vbr6`, ...]
+:raw-html:`</tt>`
+
+An ``UNABBREV_RECORD`` provides a default fallback encoding, which is both
+completely general and extremely inefficient. It can describe an arbitrary
+record by emitting the code and operands as VBRs.
+
+For example, emitting an LLVM IR target triple as an unabbreviated record
+requires emitting the ``UNABBREV_RECORD`` abbrevid, a vbr6 for the
+``MODULE_CODE_TRIPLE`` code, a vbr6 for the length of the string, which is equal
+to the number of operands, and a vbr6 for each character. Because there are no
+letters with values less than 32, each letter would need to be emitted as at
+least a two-part VBR, which means that each letter would require at least 12
+bits. This is not an efficient encoding, but it is fully general.
+
+.. _abbreviated record encoding:
+
+Abbreviated Record Encoding
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[<abbrevid>, fields...]``
+
+An abbreviated record is a abbreviation id followed by a set of fields that are
+encoded according to the `abbreviation definition`_. This allows records to be
+encoded significantly more densely than records encoded with the
+`UNABBREV_RECORD`_ type, and allows the abbreviation types to be specified in
+the stream itself, which allows the files to be completely self describing. The
+actual encoding of abbreviations is defined below.
+
+The record code, which is the first field of an abbreviated record, may be
+encoded in the abbreviation definition (as a literal operand) or supplied in the
+abbreviated record (as a Fixed or VBR operand value).
+
+.. _abbreviation definition:
+
+Abbreviations
+-------------
+
+Abbreviations are an important form of compression for bitstreams. The idea is
+to specify a dense encoding for a class of records once, then use that encoding
+to emit many records. It takes space to emit the encoding into the file, but
+the space is recouped (hopefully plus some) when the records that use it are
+emitted.
+
+Abbreviations can be determined dynamically per client, per file. Because the
+abbreviations are stored in the bitstream itself, different streams of the same
+format can contain different sets of abbreviations according to the needs of the
+specific stream. As a concrete example, LLVM IR files usually emit an
+abbreviation for binary operators. If a specific LLVM module contained no or
+few binary operators, the abbreviation does not need to be emitted.
+
+.. _DEFINE_ABBREV:
+
+DEFINE_ABBREV Encoding
+^^^^^^^^^^^^^^^^^^^^^^
+
+:raw-html:`<tt>`
+[DEFINE_ABBREV, numabbrevops\ :sub:`vbr5`, abbrevop0, abbrevop1, ...]
+:raw-html:`</tt>`
+
+A ``DEFINE_ABBREV`` record adds an abbreviation to the list of currently defined
+abbreviations in the scope of this block. This definition only exists inside
+this immediate block --- it is not visible in subblocks or enclosing blocks.
+Abbreviations are implicitly assigned IDs sequentially starting from 4 (the
+first application-defined abbreviation ID). Any abbreviations defined in a
+``BLOCKINFO`` record for the particular block type receive IDs first, in order,
+followed by any abbreviations defined within the block itself. Abbreviated data
+records reference this ID to indicate what abbreviation they are invoking.
+
+An abbreviation definition consists of the ``DEFINE_ABBREV`` abbrevid followed
+by a VBR that specifies the number of abbrev operands, then the abbrev operands
+themselves. Abbreviation operands come in three forms. They all start with a
+single bit that indicates whether the abbrev operand is a literal operand (when
+the bit is 1) or an encoding operand (when the bit is 0).
+
+#. Literal operands --- :raw-html:`<tt>` [1\ :sub:`1`, litvalue\
+ :sub:`vbr8`] :raw-html:`</tt>` --- Literal operands specify that the value in
+ the result is always a single specific value. This specific value is emitted
+ as a vbr8 after the bit indicating that it is a literal operand.
+
+#. Encoding info without data --- :raw-html:`<tt>` [0\ :sub:`1`, encoding\
+ :sub:`3`] :raw-html:`</tt>` --- Operand encodings that do not have extra data
+ are just emitted as their code.
+
+#. Encoding info with data --- :raw-html:`<tt>` [0\ :sub:`1`, encoding\
+ :sub:`3`, value\ :sub:`vbr5`] :raw-html:`</tt>` --- Operand encodings that do
+ have extra data are emitted as their code, followed by the extra data.
+
+The possible operand encodings are:
+
+* Fixed (code 1): The field should be emitted as a `fixed-width value`_, whose
+ width is specified by the operand's extra data.
+
+* VBR (code 2): The field should be emitted as a `variable-width value`_, whose
+ width is specified by the operand's extra data.
+
+* Array (code 3): This field is an array of values. The array operand has no
+ extra data, but expects another operand to follow it, indicating the element
+ type of the array. When reading an array in an abbreviated record, the first
+ integer is a vbr6 that indicates the array length, followed by the encoded
+ elements of the array. An array may only occur as the last operand of an
+ abbreviation (except for the one final operand that gives the array's
+ type).
+
+* Char6 (code 4): This field should be emitted as a `char6-encoded value`_.
+ This operand type takes no extra data. Char6 encoding is normally used as an
+ array element type.
+
+* Blob (code 5): This field is emitted as a vbr6, followed by padding to a
+ 32-bit boundary (for alignment) and an array of 8-bit objects. The array of
+ bytes is further followed by tail padding to ensure that its total length is a
+ multiple of 4 bytes. This makes it very efficient for the reader to decode
+ the data without having to make a copy of it: it can use a pointer to the data
+ in the mapped in file and poke directly at it. A blob may only occur as the
+ last operand of an abbreviation.
+
+For example, target triples in LLVM modules are encoded as a record of the form
+``[TRIPLE, 'a', 'b', 'c', 'd']``. Consider if the bitstream emitted the
+following abbrev entry:
+
+::
+
+ [0, Fixed, 4]
+ [0, Array]
+ [0, Char6]
+
+When emitting a record with this abbreviation, the above entry would be emitted
+as:
+
+:raw-html:`<tt><blockquote>`
+[4\ :sub:`abbrevwidth`, 2\ :sub:`4`, 4\ :sub:`vbr6`, 0\ :sub:`6`, 1\ :sub:`6`, 2\ :sub:`6`, 3\ :sub:`6`]
+:raw-html:`</blockquote></tt>`
+
+These values are:
+
+#. The first value, 4, is the abbreviation ID for this abbreviation.
+
+#. The second value, 2, is the record code for ``TRIPLE`` records within LLVM IR
+ file ``MODULE_BLOCK`` blocks.
+
+#. The third value, 4, is the length of the array.
+
+#. The rest of the values are the char6 encoded values for ``"abcd"``.
+
+With this abbreviation, the triple is emitted with only 37 bits (assuming a
+abbrev id width of 3). Without the abbreviation, significantly more space would
+be required to emit the target triple. Also, because the ``TRIPLE`` value is
+not emitted as a literal in the abbreviation, the abbreviation can also be used
+for any other string value.
+
+.. _standard blocks:
+.. _standard block:
+
+Standard Blocks
+---------------
+
+In addition to the basic block structure and record encodings, the bitstream
+also defines specific built-in block types. These block types specify how the
+stream is to be decoded or other metadata. In the future, new standard blocks
+may be added. Block IDs 0-7 are reserved for standard blocks.
+
+.. _BLOCKINFO:
+
+#0 - BLOCKINFO Block
+^^^^^^^^^^^^^^^^^^^^
+
+The ``BLOCKINFO`` block allows the description of metadata for other blocks.
+The currently specified records are:
+
+::
+
+ [SETBID (#1), blockid]
+ [DEFINE_ABBREV, ...]
+ [BLOCKNAME, ...name...]
+ [SETRECORDNAME, RecordID, ...name...]
+
+The ``SETBID`` record (code 1) indicates which block ID is being described.
+``SETBID`` records can occur multiple times throughout the block to change which
+block ID is being described. There must be a ``SETBID`` record prior to any
+other records.
+
+Standard ``DEFINE_ABBREV`` records can occur inside ``BLOCKINFO`` blocks, but
+unlike their occurrence in normal blocks, the abbreviation is defined for blocks
+matching the block ID we are describing, *not* the ``BLOCKINFO`` block
+itself. The abbreviations defined in ``BLOCKINFO`` blocks receive abbreviation
+IDs as described in `DEFINE_ABBREV`_.
+
+The ``BLOCKNAME`` record (code 2) can optionally occur in this block. The
+elements of the record are the bytes of the string name of the block.
+llvm-bcanalyzer can use this to dump out bitcode files symbolically.
+
+The ``SETRECORDNAME`` record (code 3) can also optionally occur in this block.
+The first operand value is a record ID number, and the rest of the elements of
+the record are the bytes for the string name of the record. llvm-bcanalyzer can
+use this to dump out bitcode files symbolically.
+
+Note that although the data in ``BLOCKINFO`` blocks is described as "metadata,"
+the abbreviations they contain are essential for parsing records from the
+corresponding blocks. It is not safe to skip them.
+
+.. _wrapper:
+
+Bitcode Wrapper Format
+======================
+
+Bitcode files for LLVM IR may optionally be wrapped in a simple wrapper
+structure. This structure contains a simple header that indicates the offset
+and size of the embedded BC file. This allows additional information to be
+stored alongside the BC file. The structure of this file header is:
+
+:raw-html:`<tt><blockquote>`
+[Magic\ :sub:`32`, Version\ :sub:`32`, Offset\ :sub:`32`, Size\ :sub:`32`, CPUType\ :sub:`32`]
+:raw-html:`</blockquote></tt>`
+
+Each of the fields are 32-bit fields stored in little endian form (as with the
+rest of the bitcode file fields). The Magic number is always ``0x0B17C0DE`` and
+the version is currently always ``0``. The Offset field is the offset in bytes
+to the start of the bitcode stream in the file, and the Size field is the size
+in bytes of the stream. CPUType is a target-specific value that can be used to
+encode the CPU of the target.
+
+.. _encoding of LLVM IR:
+
+LLVM IR Encoding
+================
+
+LLVM IR is encoded into a bitstream by defining blocks and records. It uses
+blocks for things like constant pools, functions, symbol tables, etc. It uses
+records for things like instructions, global variable descriptors, type
+descriptions, etc. This document does not describe the set of abbreviations
+that the writer uses, as these are fully self-described in the file, and the
+reader is not allowed to build in any knowledge of this.
+
+Basics
+------
+
+LLVM IR Magic Number
+^^^^^^^^^^^^^^^^^^^^
+
+The magic number for LLVM IR files is:
+
+:raw-html:`<tt><blockquote>`
+[0x0\ :sub:`4`, 0xC\ :sub:`4`, 0xE\ :sub:`4`, 0xD\ :sub:`4`]
+:raw-html:`</blockquote></tt>`
+
+When combined with the bitcode magic number and viewed as bytes, this is
+``"BC 0xC0DE"``.
+
+Signed VBRs
+^^^^^^^^^^^
+
+`Variable Width Integer`_ encoding is an efficient way to encode arbitrary sized
+unsigned values, but is an extremely inefficient for encoding signed values, as
+signed values are otherwise treated as maximally large unsigned values.
+
+As such, signed VBR values of a specific width are emitted as follows:
+
+* Positive values are emitted as VBRs of the specified width, but with their
+ value shifted left by one.
+
+* Negative values are emitted as VBRs of the specified width, but the negated
+ value is shifted left by one, and the low bit is set.
+
+With this encoding, small positive and small negative values can both be emitted
+efficiently. Signed VBR encoding is used in ``CST_CODE_INTEGER`` and
+``CST_CODE_WIDE_INTEGER`` records within ``CONSTANTS_BLOCK`` blocks.
+
+LLVM IR Blocks
+^^^^^^^^^^^^^^
+
+LLVM IR is defined with the following blocks:
+
+* 8 --- `MODULE_BLOCK`_ --- This is the top-level block that contains the entire
+ module, and describes a variety of per-module information.
+
+* 9 --- `PARAMATTR_BLOCK`_ --- This enumerates the parameter attributes.
+
+* 10 --- `TYPE_BLOCK`_ --- This describes all of the types in the module.
+
+* 11 --- `CONSTANTS_BLOCK`_ --- This describes constants for a module or
+ function.
+
+* 12 --- `FUNCTION_BLOCK`_ --- This describes a function body.
+
+* 13 --- `TYPE_SYMTAB_BLOCK`_ --- This describes the type symbol table.
+
+* 14 --- `VALUE_SYMTAB_BLOCK`_ --- This describes a value symbol table.
+
+* 15 --- `METADATA_BLOCK`_ --- This describes metadata items.
+
+* 16 --- `METADATA_ATTACHMENT`_ --- This contains records associating metadata
+ with function instruction values.
+
+.. _MODULE_BLOCK:
+
+MODULE_BLOCK Contents
+---------------------
+
+The ``MODULE_BLOCK`` block (id 8) is the top-level block for LLVM bitcode files,
+and each bitcode file must contain exactly one. In addition to records
+(described below) containing information about the module, a ``MODULE_BLOCK``
+block may contain the following sub-blocks:
+
+* `BLOCKINFO`_
+* `PARAMATTR_BLOCK`_
+* `TYPE_BLOCK`_
+* `TYPE_SYMTAB_BLOCK`_
+* `VALUE_SYMTAB_BLOCK`_
+* `CONSTANTS_BLOCK`_
+* `FUNCTION_BLOCK`_
+* `METADATA_BLOCK`_
+
+MODULE_CODE_VERSION Record
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[VERSION, version#]``
+
+The ``VERSION`` record (code 1) contains a single value indicating the format
+version. Only version 0 is supported at this time.
+
+MODULE_CODE_TRIPLE Record
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[TRIPLE, ...string...]``
+
+The ``TRIPLE`` record (code 2) contains a variable number of values representing
+the bytes of the ``target triple`` specification string.
+
+MODULE_CODE_DATALAYOUT Record
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[DATALAYOUT, ...string...]``
+
+The ``DATALAYOUT`` record (code 3) contains a variable number of values
+representing the bytes of the ``target datalayout`` specification string.
+
+MODULE_CODE_ASM Record
+^^^^^^^^^^^^^^^^^^^^^^
+
+``[ASM, ...string...]``
+
+The ``ASM`` record (code 4) contains a variable number of values representing
+the bytes of ``module asm`` strings, with individual assembly blocks separated
+by newline (ASCII 10) characters.
+
+.. _MODULE_CODE_SECTIONNAME:
+
+MODULE_CODE_SECTIONNAME Record
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[SECTIONNAME, ...string...]``
+
+The ``SECTIONNAME`` record (code 5) contains a variable number of values
+representing the bytes of a single section name string. There should be one
+``SECTIONNAME`` record for each section name referenced (e.g., in global
+variable or function ``section`` attributes) within the module. These records
+can be referenced by the 1-based index in the *section* fields of ``GLOBALVAR``
+or ``FUNCTION`` records.
+
+MODULE_CODE_DEPLIB Record
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[DEPLIB, ...string...]``
+
+The ``DEPLIB`` record (code 6) contains a variable number of values representing
+the bytes of a single dependent library name string, one of the libraries
+mentioned in a ``deplibs`` declaration. There should be one ``DEPLIB`` record
+for each library name referenced.
+
+MODULE_CODE_GLOBALVAR Record
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[GLOBALVAR, pointer type, isconst, initid, linkage, alignment, section, visibility, threadlocal, unnamed_addr]``
+
+The ``GLOBALVAR`` record (code 7) marks the declaration or definition of a
+global variable. The operand fields are:
+
+* *pointer type*: The type index of the pointer type used to point to this
+ global variable
+
+* *isconst*: Non-zero if the variable is treated as constant within the module,
+ or zero if it is not
+
+* *initid*: If non-zero, the value index of the initializer for this variable,
+ plus 1.
+
+.. _linkage type:
+
+* *linkage*: An encoding of the linkage type for this variable:
+ * ``external``: code 0
+ * ``weak``: code 1
+ * ``appending``: code 2
+ * ``internal``: code 3
+ * ``linkonce``: code 4
+ * ``dllimport``: code 5
+ * ``dllexport``: code 6
+ * ``extern_weak``: code 7
+ * ``common``: code 8
+ * ``private``: code 9
+ * ``weak_odr``: code 10
+ * ``linkonce_odr``: code 11
+ * ``available_externally``: code 12
+ * ``linker_private``: code 13
+
+* alignment*: The logarithm base 2 of the variable's requested alignment, plus 1
+
+* *section*: If non-zero, the 1-based section index in the table of
+ `MODULE_CODE_SECTIONNAME`_ entries.
+
+.. _visibility:
+
+* *visibility*: If present, an encoding of the visibility of this variable:
+ * ``default``: code 0
+ * ``hidden``: code 1
+ * ``protected``: code 2
+
+* *threadlocal*: If present, an encoding of the thread local storage mode of the
+ variable:
+ * ``not thread local``: code 0
+ * ``thread local; default TLS model``: code 1
+ * ``localdynamic``: code 2
+ * ``initialexec``: code 3
+ * ``localexec``: code 4
+
+* *unnamed_addr*: If present and non-zero, indicates that the variable has
+ ``unnamed_addr``
+
+.. _FUNCTION:
+
+MODULE_CODE_FUNCTION Record
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[FUNCTION, type, callingconv, isproto, linkage, paramattr, alignment, section, visibility, gc]``
+
+The ``FUNCTION`` record (code 8) marks the declaration or definition of a
+function. The operand fields are:
+
+* *type*: The type index of the function type describing this function
+
+* *callingconv*: The calling convention number:
+ * ``ccc``: code 0
+ * ``fastcc``: code 8
+ * ``coldcc``: code 9
+ * ``x86_stdcallcc``: code 64
+ * ``x86_fastcallcc``: code 65
+ * ``arm_apcscc``: code 66
+ * ``arm_aapcscc``: code 67
+ * ``arm_aapcs_vfpcc``: code 68
+
+* isproto*: Non-zero if this entry represents a declaration rather than a
+ definition
+
+* *linkage*: An encoding of the `linkage type`_ for this function
+
+* *paramattr*: If nonzero, the 1-based parameter attribute index into the table
+ of `PARAMATTR_CODE_ENTRY`_ entries.
+
+* *alignment*: The logarithm base 2 of the function's requested alignment, plus
+ 1
+
+* *section*: If non-zero, the 1-based section index in the table of
+ `MODULE_CODE_SECTIONNAME`_ entries.
+
+* *visibility*: An encoding of the `visibility`_ of this function
+
+* *gc*: If present and nonzero, the 1-based garbage collector index in the table
+ of `MODULE_CODE_GCNAME`_ entries.
+
+* *unnamed_addr*: If present and non-zero, indicates that the function has
+ ``unnamed_addr``
+
+MODULE_CODE_ALIAS Record
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[ALIAS, alias type, aliasee val#, linkage, visibility]``
+
+The ``ALIAS`` record (code 9) marks the definition of an alias. The operand
+fields are
+
+* *alias type*: The type index of the alias
+
+* *aliasee val#*: The value index of the aliased value
+
+* *linkage*: An encoding of the `linkage type`_ for this alias
+
+* *visibility*: If present, an encoding of the `visibility`_ of the alias
+
+MODULE_CODE_PURGEVALS Record
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[PURGEVALS, numvals]``
+
+The ``PURGEVALS`` record (code 10) resets the module-level value list to the
+size given by the single operand value. Module-level value list items are added
+by ``GLOBALVAR``, ``FUNCTION``, and ``ALIAS`` records. After a ``PURGEVALS``
+record is seen, new value indices will start from the given *numvals* value.
+
+.. _MODULE_CODE_GCNAME:
+
+MODULE_CODE_GCNAME Record
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[GCNAME, ...string...]``
+
+The ``GCNAME`` record (code 11) contains a variable number of values
+representing the bytes of a single garbage collector name string. There should
+be one ``GCNAME`` record for each garbage collector name referenced in function
+``gc`` attributes within the module. These records can be referenced by 1-based
+index in the *gc* fields of ``FUNCTION`` records.
+
+.. _PARAMATTR_BLOCK:
+
+PARAMATTR_BLOCK Contents
+------------------------
+
+The ``PARAMATTR_BLOCK`` block (id 9) contains a table of entries describing the
+attributes of function parameters. These entries are referenced by 1-based index
+in the *paramattr* field of module block `FUNCTION`_ records, or within the
+*attr* field of function block ``INST_INVOKE`` and ``INST_CALL`` records.
+
+Entries within ``PARAMATTR_BLOCK`` are constructed to ensure that each is unique
+(i.e., no two indicies represent equivalent attribute lists).
+
+.. _PARAMATTR_CODE_ENTRY:
+
+PARAMATTR_CODE_ENTRY Record
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[ENTRY, paramidx0, attr0, paramidx1, attr1...]``
+
+The ``ENTRY`` record (code 1) contains an even number of values describing a
+unique set of function parameter attributes. Each *paramidx* value indicates
+which set of attributes is represented, with 0 representing the return value
+attributes, 0xFFFFFFFF representing function attributes, and other values
+representing 1-based function parameters. Each *attr* value is a bitmap with the
+following interpretation:
+
+* bit 0: ``zeroext``
+* bit 1: ``signext``
+* bit 2: ``noreturn``
+* bit 3: ``inreg``
+* bit 4: ``sret``
+* bit 5: ``nounwind``
+* bit 6: ``noalias``
+* bit 7: ``byval``
+* bit 8: ``nest``
+* bit 9: ``readnone``
+* bit 10: ``readonly``
+* bit 11: ``noinline``
+* bit 12: ``alwaysinline``
+* bit 13: ``optsize``
+* bit 14: ``ssp``
+* bit 15: ``sspreq``
+* bits 16-31: ``align n``
+* bit 32: ``nocapture``
+* bit 33: ``noredzone``
+* bit 34: ``noimplicitfloat``
+* bit 35: ``naked``
+* bit 36: ``inlinehint``
+* bits 37-39: ``alignstack n``, represented as the logarithm
+ base 2 of the requested alignment, plus 1
+
+.. _TYPE_BLOCK:
+
+TYPE_BLOCK Contents
+-------------------
+
+The ``TYPE_BLOCK`` block (id 10) contains records which constitute a table of
+type operator entries used to represent types referenced within an LLVM
+module. Each record (with the exception of `NUMENTRY`_) generates a single type
+table entry, which may be referenced by 0-based index from instructions,
+constants, metadata, type symbol table entries, or other type operator records.
+
+Entries within ``TYPE_BLOCK`` are constructed to ensure that each entry is
+unique (i.e., no two indicies represent structurally equivalent types).
+
+.. _TYPE_CODE_NUMENTRY:
+.. _NUMENTRY:
+
+TYPE_CODE_NUMENTRY Record
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[NUMENTRY, numentries]``
+
+The ``NUMENTRY`` record (code 1) contains a single value which indicates the
+total number of type code entries in the type table of the module. If present,
+``NUMENTRY`` should be the first record in the block.
+
+TYPE_CODE_VOID Record
+^^^^^^^^^^^^^^^^^^^^^
+
+``[VOID]``
+
+The ``VOID`` record (code 2) adds a ``void`` type to the type table.
+
+TYPE_CODE_HALF Record
+^^^^^^^^^^^^^^^^^^^^^
+
+``[HALF]``
+
+The ``HALF`` record (code 10) adds a ``half`` (16-bit floating point) type to
+the type table.
+
+TYPE_CODE_FLOAT Record
+^^^^^^^^^^^^^^^^^^^^^^
+
+``[FLOAT]``
+
+The ``FLOAT`` record (code 3) adds a ``float`` (32-bit floating point) type to
+the type table.
+
+TYPE_CODE_DOUBLE Record
+^^^^^^^^^^^^^^^^^^^^^^^
+
+``[DOUBLE]``
+
+The ``DOUBLE`` record (code 4) adds a ``double`` (64-bit floating point) type to
+the type table.
+
+TYPE_CODE_LABEL Record
+^^^^^^^^^^^^^^^^^^^^^^
+
+``[LABEL]``
+
+The ``LABEL`` record (code 5) adds a ``label`` type to the type table.
+
+TYPE_CODE_OPAQUE Record
+^^^^^^^^^^^^^^^^^^^^^^^
+
+``[OPAQUE]``
+
+The ``OPAQUE`` record (code 6) adds an ``opaque`` type to the type table. Note
+that distinct ``opaque`` types are not unified.
+
+TYPE_CODE_INTEGER Record
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[INTEGER, width]``
+
+The ``INTEGER`` record (code 7) adds an integer type to the type table. The
+single *width* field indicates the width of the integer type.
+
+TYPE_CODE_POINTER Record
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[POINTER, pointee type, address space]``
+
+The ``POINTER`` record (code 8) adds a pointer type to the type table. The
+operand fields are
+
+* *pointee type*: The type index of the pointed-to type
+
+* *address space*: If supplied, the target-specific numbered address space where
+ the pointed-to object resides. Otherwise, the default address space is zero.
+
+TYPE_CODE_FUNCTION Record
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[FUNCTION, vararg, ignored, retty, ...paramty... ]``
+
+The ``FUNCTION`` record (code 9) adds a function type to the type table. The
+operand fields are
+
+* *vararg*: Non-zero if the type represents a varargs function
+
+* *ignored*: This value field is present for backward compatibility only, and is
+ ignored
+
+* *retty*: The type index of the function's return type
+
+* *paramty*: Zero or more type indices representing the parameter types of the
+ function
+
+TYPE_CODE_STRUCT Record
+^^^^^^^^^^^^^^^^^^^^^^^
+
+``[STRUCT, ispacked, ...eltty...]``
+
+The ``STRUCT`` record (code 10) adds a struct type to the type table. The
+operand fields are
+
+* *ispacked*: Non-zero if the type represents a packed structure
+
+* *eltty*: Zero or more type indices representing the element types of the
+ structure
+
+TYPE_CODE_ARRAY Record
+^^^^^^^^^^^^^^^^^^^^^^
+
+``[ARRAY, numelts, eltty]``
+
+The ``ARRAY`` record (code 11) adds an array type to the type table. The
+operand fields are
+
+* *numelts*: The number of elements in arrays of this type
+
+* *eltty*: The type index of the array element type
+
+TYPE_CODE_VECTOR Record
+^^^^^^^^^^^^^^^^^^^^^^^
+
+``[VECTOR, numelts, eltty]``
+
+The ``VECTOR`` record (code 12) adds a vector type to the type table. The
+operand fields are
+
+* *numelts*: The number of elements in vectors of this type
+
+* *eltty*: The type index of the vector element type
+
+TYPE_CODE_X86_FP80 Record
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[X86_FP80]``
+
+The ``X86_FP80`` record (code 13) adds an ``x86_fp80`` (80-bit floating point)
+type to the type table.
+
+TYPE_CODE_FP128 Record
+^^^^^^^^^^^^^^^^^^^^^^
+
+``[FP128]``
+
+The ``FP128`` record (code 14) adds an ``fp128`` (128-bit floating point) type
+to the type table.
+
+TYPE_CODE_PPC_FP128 Record
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[PPC_FP128]``
+
+The ``PPC_FP128`` record (code 15) adds a ``ppc_fp128`` (128-bit floating point)
+type to the type table.
+
+TYPE_CODE_METADATA Record
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``[METADATA]``
+
+The ``METADATA`` record (code 16) adds a ``metadata`` type to the type table.
+
+.. _CONSTANTS_BLOCK:
+
+CONSTANTS_BLOCK Contents
+------------------------
+
+The ``CONSTANTS_BLOCK`` block (id 11) ...
+
+.. _FUNCTION_BLOCK:
+
+FUNCTION_BLOCK Contents
+-----------------------
+
+The ``FUNCTION_BLOCK`` block (id 12) ...
+
+In addition to the record types described below, a ``FUNCTION_BLOCK`` block may
+contain the following sub-blocks:
+
+* `CONSTANTS_BLOCK`_
+* `VALUE_SYMTAB_BLOCK`_
+* `METADATA_ATTACHMENT`_
+
+.. _TYPE_SYMTAB_BLOCK:
+
+TYPE_SYMTAB_BLOCK Contents
+--------------------------
+
+The ``TYPE_SYMTAB_BLOCK`` block (id 13) contains entries which map between
+module-level named types and their corresponding type indices.
+
+.. _TST_CODE_ENTRY:
+
+TST_CODE_ENTRY Record
+^^^^^^^^^^^^^^^^^^^^^
+
+``[ENTRY, typeid, ...string...]``
+
+The ``ENTRY`` record (code 1) contains a variable number of values, with the
+first giving the type index of the designated type, and the remaining values
+giving the character codes of the type name. Each entry corresponds to a single
+named type.
+
+.. _VALUE_SYMTAB_BLOCK:
+
+VALUE_SYMTAB_BLOCK Contents
+---------------------------
+
+The ``VALUE_SYMTAB_BLOCK`` block (id 14) ...
+
+.. _METADATA_BLOCK:
+
+METADATA_BLOCK Contents
+-----------------------
+
+The ``METADATA_BLOCK`` block (id 15) ...
+
+.. _METADATA_ATTACHMENT:
+
+METADATA_ATTACHMENT Contents
+----------------------------
+
+The ``METADATA_ATTACHMENT`` block (id 16) ...
diff --git a/docs/BranchWeightMetadata.rst b/docs/BranchWeightMetadata.rst
new file mode 100644
index 00000000000..f0df971f874
--- /dev/null
+++ b/docs/BranchWeightMetadata.rst
@@ -0,0 +1,118 @@
+.. _branch_weight:
+
+===========================
+LLVM Branch Weight Metadata
+===========================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+Branch Weight Metadata represents branch weights as its likeliness to be
+taken. Metadata is assigned to the ``TerminatorInst`` as a ``MDNode`` of the
+``MD_prof`` kind. The first operator is always a ``MDString`` node with the
+string "branch_weights". Number of operators depends on the terminator type.
+
+Branch weights might be fetch from the profiling file, or generated based on
+`__builtin_expect`_ instruction.
+
+All weights are represented as an unsigned 32-bit values, where higher value
+indicates greater chance to be taken.
+
+Supported Instructions
+======================
+
+``BranchInst``
+^^^^^^^^^^^^^^
+
+Metadata is only assign to the conditional branches. There are two extra
+operarands, for the true and the false branch.
+
+.. code-block:: llvm
+
+ !0 = metadata !{
+ metadata !"branch_weights",
+ i32 <TRUE_BRANCH_WEIGHT>,
+ i32 <FALSE_BRANCH_WEIGHT>
+ }
+
+``SwitchInst``
+^^^^^^^^^^^^^^
+
+Branch weights are assign to every case (including ``default`` case which is
+always case #0).
+
+.. code-block:: llvm
+
+ !0 = metadata !{
+ metadata !"branch_weights",
+ i32 <DEFAULT_BRANCH_WEIGHT>
+ [ , i32 <CASE_BRANCH_WEIGHT> ... ]
+ }
+
+``IndirectBrInst``
+^^^^^^^^^^^^^^^^^^
+
+Branch weights are assign to every destination.
+
+.. code-block:: llvm
+
+ !0 = metadata !{
+ metadata !"branch_weights",
+ i32 <LABEL_BRANCH_WEIGHT>
+ [ , i32 <LABEL_BRANCH_WEIGHT> ... ]
+ }
+
+Other
+^^^^^
+
+Other terminator instructions are not allowed to contain Branch Weight Metadata.
+
+.. _\__builtin_expect:
+
+Built-in ``expect`` Instructions
+================================
+
+``__builtin_expect(long exp, long c)`` instruction provides branch prediction
+information. The return value is the value of ``exp``.
+
+It is especially useful in conditional statements. Currently Clang supports two
+conditional statements:
+
+``if`` statement
+^^^^^^^^^^^^^^^^
+
+The ``exp`` parameter is the condition. The ``c`` parameter is the expected
+comparison value. If it is equal to 1 (true), the condition is likely to be
+true, in other case condition is likely to be false. For example:
+
+.. code-block:: c++
+
+ if (__builtin_expect(x > 0, 1)) {
+ // This block is likely to be taken.
+ }
+
+``switch`` statement
+^^^^^^^^^^^^^^^^^^^^
+
+The ``exp`` parameter is the value. The ``c`` parameter is the expected
+value. If the expected value doesn't show on the cases list, the ``default``
+case is assumed to be likely taken.
+
+.. code-block:: c++
+
+ switch (__builtin_expect(x, 5)) {
+ default: break;
+ case 0: // ...
+ case 3: // ...
+ case 5: // This case is likely to be taken.
+ }
+
+CFG Modifications
+=================
+
+Branch Weight Metatada is not proof against CFG changes. If terminator operands'
+are changed some action should be taken. In other case some misoptimizations may
+occur due to incorrent branch prediction information.
diff --git a/docs/Bugpoint.rst b/docs/Bugpoint.rst
new file mode 100644
index 00000000000..9ccf0cc2d9d
--- /dev/null
+++ b/docs/Bugpoint.rst
@@ -0,0 +1,218 @@
+.. _bugpoint:
+
+====================================
+LLVM bugpoint tool: design and usage
+====================================
+
+.. contents::
+ :local:
+
+Description
+===========
+
+``bugpoint`` narrows down the source of problems in LLVM tools and passes. It
+can be used to debug three types of failures: optimizer crashes, miscompilations
+by optimizers, or bad native code generation (including problems in the static
+and JIT compilers). It aims to reduce large test cases to small, useful ones.
+For example, if ``opt`` crashes while optimizing a file, it will identify the
+optimization (or combination of optimizations) that causes the crash, and reduce
+the file down to a small example which triggers the crash.
+
+For detailed case scenarios, such as debugging ``opt``, or one of the LLVM code
+generators, see `How To Submit a Bug Report document <HowToSubmitABug.html>`_.
+
+Design Philosophy
+=================
+
+``bugpoint`` is designed to be a useful tool without requiring any hooks into
+the LLVM infrastructure at all. It works with any and all LLVM passes and code
+generators, and does not need to "know" how they work. Because of this, it may
+appear to do stupid things or miss obvious simplifications. ``bugpoint`` is
+also designed to trade off programmer time for computer time in the
+compiler-debugging process; consequently, it may take a long period of
+(unattended) time to reduce a test case, but we feel it is still worth it. Note
+that ``bugpoint`` is generally very quick unless debugging a miscompilation
+where each test of the program (which requires executing it) takes a long time.
+
+Automatic Debugger Selection
+----------------------------
+
+``bugpoint`` reads each ``.bc`` or ``.ll`` file specified on the command line
+and links them together into a single module, called the test program. If any
+LLVM passes are specified on the command line, it runs these passes on the test
+program. If any of the passes crash, or if they produce malformed output (which
+causes the verifier to abort), ``bugpoint`` starts the `crash debugger`_.
+
+Otherwise, if the ``-output`` option was not specified, ``bugpoint`` runs the
+test program with the "safe" backend (which is assumed to generate good code) to
+generate a reference output. Once ``bugpoint`` has a reference output for the
+test program, it tries executing it with the selected code generator. If the
+selected code generator crashes, ``bugpoint`` starts the `crash debugger`_ on
+the code generator. Otherwise, if the resulting output differs from the
+reference output, it assumes the difference resulted from a code generator
+failure, and starts the `code generator debugger`_.
+
+Finally, if the output of the selected code generator matches the reference
+output, ``bugpoint`` runs the test program after all of the LLVM passes have
+been applied to it. If its output differs from the reference output, it assumes
+the difference resulted from a failure in one of the LLVM passes, and enters the
+`miscompilation debugger`_. Otherwise, there is no problem ``bugpoint`` can
+debug.
+
+.. _crash debugger:
+
+Crash debugger
+--------------
+
+If an optimizer or code generator crashes, ``bugpoint`` will try as hard as it
+can to reduce the list of passes (for optimizer crashes) and the size of the
+test program. First, ``bugpoint`` figures out which combination of optimizer
+passes triggers the bug. This is useful when debugging a problem exposed by
+``opt``, for example, because it runs over 38 passes.
+
+Next, ``bugpoint`` tries removing functions from the test program, to reduce its
+size. Usually it is able to reduce a test program to a single function, when
+debugging intraprocedural optimizations. Once the number of functions has been
+reduced, it attempts to delete various edges in the control flow graph, to
+reduce the size of the function as much as possible. Finally, ``bugpoint``
+deletes any individual LLVM instructions whose absence does not eliminate the
+failure. At the end, ``bugpoint`` should tell you what passes crash, give you a
+bitcode file, and give you instructions on how to reproduce the failure with
+``opt`` or ``llc``.
+
+.. _code generator debugger:
+
+Code generator debugger
+-----------------------
+
+The code generator debugger attempts to narrow down the amount of code that is
+being miscompiled by the selected code generator. To do this, it takes the test
+program and partitions it into two pieces: one piece which it compiles with the
+"safe" backend (into a shared object), and one piece which it runs with either
+the JIT or the static LLC compiler. It uses several techniques to reduce the
+amount of code pushed through the LLVM code generator, to reduce the potential
+scope of the problem. After it is finished, it emits two bitcode files (called
+"test" [to be compiled with the code generator] and "safe" [to be compiled with
+the "safe" backend], respectively), and instructions for reproducing the
+problem. The code generator debugger assumes that the "safe" backend produces
+good code.
+
+.. _miscompilation debugger:
+
+Miscompilation debugger
+-----------------------
+
+The miscompilation debugger works similarly to the code generator debugger. It
+works by splitting the test program into two pieces, running the optimizations
+specified on one piece, linking the two pieces back together, and then executing
+the result. It attempts to narrow down the list of passes to the one (or few)
+which are causing the miscompilation, then reduce the portion of the test
+program which is being miscompiled. The miscompilation debugger assumes that
+the selected code generator is working properly.
+
+Advice for using bugpoint
+=========================
+
+``bugpoint`` can be a remarkably useful tool, but it sometimes works in
+non-obvious ways. Here are some hints and tips:
+
+* In the code generator and miscompilation debuggers, ``bugpoint`` only works
+ with programs that have deterministic output. Thus, if the program outputs
+ ``argv[0]``, the date, time, or any other "random" data, ``bugpoint`` may
+ misinterpret differences in these data, when output, as the result of a
+ miscompilation. Programs should be temporarily modified to disable outputs
+ that are likely to vary from run to run.
+
+* In the code generator and miscompilation debuggers, debugging will go faster
+ if you manually modify the program or its inputs to reduce the runtime, but
+ still exhibit the problem.
+
+* ``bugpoint`` is extremely useful when working on a new optimization: it helps
+ track down regressions quickly. To avoid having to relink ``bugpoint`` every
+ time you change your optimization however, have ``bugpoint`` dynamically load
+ your optimization with the ``-load`` option.
+
+* ``bugpoint`` can generate a lot of output and run for a long period of time.
+ It is often useful to capture the output of the program to file. For example,
+ in the C shell, you can run:
+
+ .. code-block:: bash
+
+ bugpoint ... |& tee bugpoint.log
+
+ to get a copy of ``bugpoint``'s output in the file ``bugpoint.log``, as well
+ as on your terminal.
+
+* ``bugpoint`` cannot debug problems with the LLVM linker. If ``bugpoint``
+ crashes before you see its "All input ok" message, you might try ``llvm-link
+ -v`` on the same set of input files. If that also crashes, you may be
+ experiencing a linker bug.
+
+* ``bugpoint`` is useful for proactively finding bugs in LLVM. Invoking
+ ``bugpoint`` with the ``-find-bugs`` option will cause the list of specified
+ optimizations to be randomized and applied to the program. This process will
+ repeat until a bug is found or the user kills ``bugpoint``.
+
+What to do when bugpoint isn't enough
+=====================================
+
+Sometimes, ``bugpoint`` is not enough. In particular, InstCombine and
+TargetLowering both have visitor structured code with lots of potential
+transformations. If the process of using bugpoint has left you with still too
+much code to figure out and the problem seems to be in instcombine, the
+following steps may help. These same techniques are useful with TargetLowering
+as well.
+
+Turn on ``-debug-only=instcombine`` and see which transformations within
+instcombine are firing by selecting out lines with "``IC``" in them.
+
+At this point, you have a decision to make. Is the number of transformations
+small enough to step through them using a debugger? If so, then try that.
+
+If there are too many transformations, then a source modification approach may
+be helpful. In this approach, you can modify the source code of instcombine to
+disable just those transformations that are being performed on your test input
+and perform a binary search over the set of transformations. One set of places
+to modify are the "``visit*``" methods of ``InstCombiner`` (*e.g.*
+``visitICmpInst``) by adding a "``return false``" as the first line of the
+method.
+
+If that still doesn't remove enough, then change the caller of
+``InstCombiner::DoOneIteration``, ``InstCombiner::runOnFunction`` to limit the
+number of iterations.
+
+You may also find it useful to use "``-stats``" now to see what parts of
+instcombine are firing. This can guide where to put additional reporting code.
+
+At this point, if the amount of transformations is still too large, then
+inserting code to limit whether or not to execute the body of the code in the
+visit function can be helpful. Add a static counter which is incremented on
+every invocation of the function. Then add code which simply returns false on
+desired ranges. For example:
+
+.. code-block:: c++
+
+
+ static int calledCount = 0;
+ calledCount++;
+ DEBUG(if (calledCount < 212) return false);
+ DEBUG(if (calledCount > 217) return false);
+ DEBUG(if (calledCount == 213) return false);
+ DEBUG(if (calledCount == 214) return false);
+ DEBUG(if (calledCount == 215) return false);
+ DEBUG(if (calledCount == 216) return false);
+ DEBUG(dbgs() << "visitXOR calledCount: " << calledCount << "\n");
+ DEBUG(dbgs() << "I: "; I->dump());
+
+could be added to ``visitXOR`` to limit ``visitXor`` to being applied only to
+calls 212 and 217. This is from an actual test case and raises an important
+point---a simple binary search may not be sufficient, as transformations that
+interact may require isolating more than one call. In TargetLowering, use
+``return SDNode();`` instead of ``return false;``.
+
+Now that that the number of transformations is down to a manageable number, try
+examining the output to see if you can figure out which transformations are
+being done. If that can be figured out, then do the usual debugging. If which
+code corresponds to the transformation being performed isn't obvious, set a
+breakpoint after the call count based disabling and step through the code.
+Alternatively, you can use "``printf``" style debugging to report waypoints.
diff --git a/docs/CMake.rst b/docs/CMake.rst
new file mode 100644
index 00000000000..e1761c5b1d4
--- /dev/null
+++ b/docs/CMake.rst
@@ -0,0 +1,423 @@
+.. _building-with-cmake:
+
+========================
+Building LLVM with CMake
+========================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+`CMake <http://www.cmake.org/>`_ is a cross-platform build-generator tool. CMake
+does not build the project, it generates the files needed by your build tool
+(GNU make, Visual Studio, etc) for building LLVM.
+
+If you are really anxious about getting a functional LLVM build, go to the
+`Quick start`_ section. If you are a CMake novice, start on `Basic CMake usage`_
+and then go back to the `Quick start`_ once you know what you are doing. The
+`Options and variables`_ section is a reference for customizing your build. If
+you already have experience with CMake, this is the recommended starting point.
+
+.. _Quick start:
+
+Quick start
+===========
+
+We use here the command-line, non-interactive CMake interface.
+
+#. `Download <http://www.cmake.org/cmake/resources/software.html>`_ and install
+ CMake. Version 2.8 is the minimum required.
+
+#. Open a shell. Your development tools must be reachable from this shell
+ through the PATH environment variable.
+
+#. Create a directory for containing the build. It is not supported to build
+ LLVM on the source directory. cd to this directory:
+
+ .. code-block:: bash
+
+ $ mkdir mybuilddir
+ $ cd mybuilddir
+
+#. Execute this command on the shell replacing `path/to/llvm/source/root` with
+ the path to the root of your LLVM source tree:
+
+ .. code-block:: bash
+
+ $ cmake path/to/llvm/source/root
+
+ CMake will detect your development environment, perform a series of test and
+ generate the files required for building LLVM. CMake will use default values
+ for all build parameters. See the `Options and variables`_ section for
+ fine-tuning your build
+
+ This can fail if CMake can't detect your toolset, or if it thinks that the
+ environment is not sane enough. On this case make sure that the toolset that
+ you intend to use is the only one reachable from the shell and that the shell
+ itself is the correct one for you development environment. CMake will refuse
+ to build MinGW makefiles if you have a POSIX shell reachable through the PATH
+ environment variable, for instance. You can force CMake to use a given build
+ tool, see the `Usage`_ section.
+
+.. _Basic CMake usage:
+.. _Usage:
+
+Basic CMake usage
+=================
+
+This section explains basic aspects of CMake, mostly for explaining those
+options which you may need on your day-to-day usage.
+
+CMake comes with extensive documentation in the form of html files and on the
+cmake executable itself. Execute ``cmake --help`` for further help options.
+
+CMake requires to know for which build tool it shall generate files (GNU make,
+Visual Studio, Xcode, etc). If not specified on the command line, it tries to
+guess it based on you environment. Once identified the build tool, CMake uses
+the corresponding *Generator* for creating files for your build tool. You can
+explicitly specify the generator with the command line option ``-G "Name of the
+generator"``. For knowing the available generators on your platform, execute
+
+.. code-block:: bash
+
+ $ cmake --help
+
+This will list the generator's names at the end of the help text. Generator's
+names are case-sensitive. Example:
+
+.. code-block:: bash
+
+ $ cmake -G "Visual Studio 9 2008" path/to/llvm/source/root
+
+For a given development platform there can be more than one adequate
+generator. If you use Visual Studio "NMake Makefiles" is a generator you can use
+for building with NMake. By default, CMake chooses the more specific generator
+supported by your development environment. If you want an alternative generator,
+you must tell this to CMake with the ``-G`` option.
+
+.. todo::
+
+ Explain variables and cache. Move explanation here from #options section.
+
+.. _Options and variables:
+
+Options and variables
+=====================
+
+Variables customize how the build will be generated. Options are boolean
+variables, with possible values ON/OFF. Options and variables are defined on the
+CMake command line like this:
+
+.. code-block:: bash
+
+ $ cmake -DVARIABLE=value path/to/llvm/source
+
+You can set a variable after the initial CMake invocation for changing its
+value. You can also undefine a variable:
+
+.. code-block:: bash
+
+ $ cmake -UVARIABLE path/to/llvm/source
+
+Variables are stored on the CMake cache. This is a file named ``CMakeCache.txt``
+on the root of the build directory. Do not hand-edit it.
+
+Variables are listed here appending its type after a colon. It is correct to
+write the variable and the type on the CMake command line:
+
+.. code-block:: bash
+
+ $ cmake -DVARIABLE:TYPE=value path/to/llvm/source
+
+Frequently-used CMake variables
+-------------------------------
+
+Here are listed some of the CMake variables that are used often, along with a
+brief explanation and LLVM-specific notes. For full documentation, check the
+CMake docs or execute ``cmake --help-variable VARIABLE_NAME``.
+
+**CMAKE_BUILD_TYPE**:STRING
+ Sets the build type for ``make`` based generators. Possible values are
+ Release, Debug, RelWithDebInfo and MinSizeRel. On systems like Visual Studio
+ the user sets the build type with the IDE settings.
+
+**CMAKE_INSTALL_PREFIX**:PATH
+ Path where LLVM will be installed if "make install" is invoked or the
+ "INSTALL" target is built.
+
+**LLVM_LIBDIR_SUFFIX**:STRING
+ Extra suffix to append to the directory where libraries are to be
+ installed. On a 64-bit architecture, one could use ``-DLLVM_LIBDIR_SUFFIX=64``
+ to install libraries to ``/usr/lib64``.
+
+**CMAKE_C_FLAGS**:STRING
+ Extra flags to use when compiling C source files.
+
+**CMAKE_CXX_FLAGS**:STRING
+ Extra flags to use when compiling C++ source files.
+
+**BUILD_SHARED_LIBS**:BOOL
+ Flag indicating is shared libraries will be built. Its default value is
+ OFF. Shared libraries are not supported on Windows and not recommended in the
+ other OSes.
+
+.. _LLVM-specific variables:
+
+LLVM-specific variables
+-----------------------
+
+**LLVM_TARGETS_TO_BUILD**:STRING
+ Semicolon-separated list of targets to build, or *all* for building all
+ targets. Case-sensitive. For Visual C++ defaults to *X86*. On the other cases
+ defaults to *all*. Example: ``-DLLVM_TARGETS_TO_BUILD="X86;PowerPC"``.
+
+**LLVM_BUILD_TOOLS**:BOOL
+ Build LLVM tools. Defaults to ON. Targets for building each tool are generated
+ in any case. You can build an tool separately by invoking its target. For
+ example, you can build *llvm-as* with a makefile-based system executing *make
+ llvm-as* on the root of your build directory.
+
+**LLVM_INCLUDE_TOOLS**:BOOL
+ Generate build targets for the LLVM tools. Defaults to ON. You can use that
+ option for disabling the generation of build targets for the LLVM tools.
+
+**LLVM_BUILD_EXAMPLES**:BOOL
+ Build LLVM examples. Defaults to OFF. Targets for building each example are
+ generated in any case. See documentation for *LLVM_BUILD_TOOLS* above for more
+ details.
+
+**LLVM_INCLUDE_EXAMPLES**:BOOL
+ Generate build targets for the LLVM examples. Defaults to ON. You can use that
+ option for disabling the generation of build targets for the LLVM examples.
+
+**LLVM_BUILD_TESTS**:BOOL
+ Build LLVM unit tests. Defaults to OFF. Targets for building each unit test
+ are generated in any case. You can build a specific unit test with the target
+ *UnitTestNameTests* (where at this time *UnitTestName* can be ADT, Analysis,
+ ExecutionEngine, JIT, Support, Transform, VMCore; see the subdirectories of
+ *unittests* for an updated list.) It is possible to build all unit tests with
+ the target *UnitTests*.
+
+**LLVM_INCLUDE_TESTS**:BOOL
+ Generate build targets for the LLVM unit tests. Defaults to ON. You can use
+ that option for disabling the generation of build targets for the LLVM unit
+ tests.
+
+**LLVM_APPEND_VC_REV**:BOOL
+ Append version control revision info (svn revision number or git revision id)
+ to LLVM version string (stored in the PACKAGE_VERSION macro). For this to work
+ cmake must be invoked before the build. Defaults to OFF.
+
+**LLVM_ENABLE_THREADS**:BOOL
+ Build with threads support, if available. Defaults to ON.
+
+**LLVM_ENABLE_ASSERTIONS**:BOOL
+ Enables code assertions. Defaults to OFF if and only if ``CMAKE_BUILD_TYPE``
+ is *Release*.
+
+**LLVM_ENABLE_PIC**:BOOL
+ Add the ``-fPIC`` flag for the compiler command-line, if the compiler supports
+ this flag. Some systems, like Windows, do not need this flag. Defaults to ON.
+
+**LLVM_ENABLE_WARNINGS**:BOOL
+ Enable all compiler warnings. Defaults to ON.
+
+**LLVM_ENABLE_PEDANTIC**:BOOL
+ Enable pedantic mode. This disable compiler specific extensions, is
+ possible. Defaults to ON.
+
+**LLVM_ENABLE_WERROR**:BOOL
+ Stop and fail build, if a compiler warning is triggered. Defaults to OFF.
+
+**LLVM_BUILD_32_BITS**:BOOL
+ Build 32-bits executables and libraries on 64-bits systems. This option is
+ available only on some 64-bits unix systems. Defaults to OFF.
+
+**LLVM_TARGET_ARCH**:STRING
+ LLVM target to use for native code generation. This is required for JIT
+ generation. It defaults to "host", meaning that it shall pick the architecture
+ of the machine where LLVM is being built. If you are cross-compiling, set it
+ to the target architecture name.
+
+**LLVM_TABLEGEN**:STRING
+ Full path to a native TableGen executable (usually named ``tblgen``). This is
+ intended for cross-compiling: if the user sets this variable, no native
+ TableGen will be created.
+
+**LLVM_LIT_ARGS**:STRING
+ Arguments given to lit. ``make check`` and ``make clang-test`` are affected.
+ By default, ``'-sv --no-progress-bar'`` on Visual C++ and Xcode, ``'-sv'`` on
+ others.
+
+**LLVM_LIT_TOOLS_DIR**:PATH
+ The path to GnuWin32 tools for tests. Valid on Windows host. Defaults to "",
+ then Lit seeks tools according to %PATH%. Lit can find tools(eg. grep, sort,
+ &c) on LLVM_LIT_TOOLS_DIR at first, without specifying GnuWin32 to %PATH%.
+
+**LLVM_ENABLE_FFI**:BOOL
+ Indicates whether LLVM Interpreter will be linked with Foreign Function
+ Interface library. If the library or its headers are installed on a custom
+ location, you can set the variables FFI_INCLUDE_DIR and
+ FFI_LIBRARY_DIR. Defaults to OFF.
+
+**LLVM_EXTERNAL_{CLANG,LLD,POLLY}_SOURCE_DIR**:PATH
+ Path to ``{Clang,lld,Polly}``\'s source directory. Defaults to
+ ``tools/{clang,lld,polly}``. ``{Clang,lld,Polly}`` will not be built when it
+ is empty or it does not point valid path.
+
+**LLVM_USE_OPROFILE**:BOOL
+ Enable building OProfile JIT support. Defaults to OFF
+
+**LLVM_USE_INTEL_JITEVENTS**:BOOL
+ Enable building support for Intel JIT Events API. Defaults to OFF
+
+**LLVM_INTEL_JITEVENTS_DIR**:PATH
+ Path to installation of Intel(R) VTune(TM) Amplifier XE 2011, used to locate
+ the ``jitprofiling`` library. Default = ``%VTUNE_AMPLIFIER_XE_2011_DIR%``
+ (Windows) | ``/opt/intel/vtune_amplifier_xe_2011`` (Linux)
+
+Executing the test suite
+========================
+
+Testing is performed when the *check* target is built. For instance, if you are
+using makefiles, execute this command while on the top level of your build
+directory:
+
+.. code-block:: bash
+
+ $ make check
+
+On Visual Studio, you may run tests to build the project "check".
+
+Cross compiling
+===============
+
+See `this wiki page <http://www.vtk.org/Wiki/CMake_Cross_Compiling>`_ for
+generic instructions on how to cross-compile with CMake. It goes into detailed
+explanations and may seem daunting, but it is not. On the wiki page there are
+several examples including toolchain files. Go directly to `this section
+<http://www.vtk.org/Wiki/CMake_Cross_Compiling#Information_how_to_set_up_various_cross_compiling_toolchains>`_
+for a quick solution.
+
+Also see the `LLVM-specific variables`_ section for variables used when
+cross-compiling.
+
+Embedding LLVM in your project
+==============================
+
+The most difficult part of adding LLVM to the build of a project is to determine
+the set of LLVM libraries corresponding to the set of required LLVM
+features. What follows is an example of how to obtain this information:
+
+.. code-block:: cmake
+
+ # A convenience variable:
+ set(LLVM_ROOT "" CACHE PATH "Root of LLVM install.")
+
+ # A bit of a sanity check:
+ if( NOT EXISTS ${LLVM_ROOT}/include/llvm )
+ message(FATAL_ERROR "LLVM_ROOT (${LLVM_ROOT}) is not a valid LLVM install")
+ endif()
+
+ # We incorporate the CMake features provided by LLVM:
+ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${LLVM_ROOT}/share/llvm/cmake")
+ include(LLVMConfig)
+
+ # Now set the header and library paths:
+ include_directories( ${LLVM_INCLUDE_DIRS} )
+ link_directories( ${LLVM_LIBRARY_DIRS} )
+ add_definitions( ${LLVM_DEFINITIONS} )
+
+ # Let's suppose we want to build a JIT compiler with support for
+ # binary code (no interpreter):
+ llvm_map_components_to_libraries(REQ_LLVM_LIBRARIES jit native)
+
+ # Finally, we link the LLVM libraries to our executable:
+ target_link_libraries(mycompiler ${REQ_LLVM_LIBRARIES})
+
+This assumes that LLVM_ROOT points to an install of LLVM. The procedure works
+too for uninstalled builds although we need to take care to add an
+`include_directories` for the location of the headers on the LLVM source
+directory (if we are building out-of-source.)
+
+Alternativaly, you can utilize CMake's ``find_package`` functionality. Here is
+an equivalent variant of snippet shown above:
+
+.. code-block:: cmake
+
+ find_package(LLVM)
+
+ if( NOT LLVM_FOUND )
+ message(FATAL_ERROR "LLVM package can't be found. Set CMAKE_PREFIX_PATH variable to LLVM's installation prefix.")
+ endif()
+
+ include_directories( ${LLVM_INCLUDE_DIRS} )
+ link_directories( ${LLVM_LIBRARY_DIRS} )
+
+ llvm_map_components_to_libraries(REQ_LLVM_LIBRARIES jit native)
+
+ target_link_libraries(mycompiler ${REQ_LLVM_LIBRARIES})
+
+Developing LLVM pass out of source
+----------------------------------
+
+It is possible to develop LLVM passes against installed LLVM. An example of
+project layout provided below:
+
+.. code-block:: bash
+
+ <project dir>/
+ |
+ CMakeLists.txt
+ <pass name>/
+ |
+ CMakeLists.txt
+ Pass.cpp
+ ...
+
+Contents of ``<project dir>/CMakeLists.txt``:
+
+.. code-block:: cmake
+
+ find_package(LLVM)
+
+ # Define add_llvm_* macro's.
+ include(AddLLVM)
+
+ add_definitions(${LLVM_DEFINITIONS})
+ include_directories(${LLVM_INCLUDE_DIRS})
+ link_directories(${LLVM_LIBRARY_DIRS})
+
+ add_subdirectory(<pass name>)
+
+Contents of ``<project dir>/<pass name>/CMakeLists.txt``:
+
+.. code-block:: cmake
+
+ add_llvm_loadable_module(LLVMPassname
+ Pass.cpp
+ )
+
+When you are done developing your pass, you may wish to integrate it
+into LLVM source tree. You can achieve it in two easy steps:
+
+#. Copying ``<pass name>`` folder into ``<LLVM root>/lib/Transform`` directory.
+
+#. Adding ``add_subdirectory(<pass name>)`` line into
+ ``<LLVM root>/lib/Transform/CMakeLists.txt``.
+
+Compiler/Platform specific topics
+=================================
+
+Notes for specific compilers and/or platforms.
+
+Microsoft Visual C++
+--------------------
+
+**LLVM_COMPILER_JOBS**:STRING
+ Specifies the maximum number of parallell compiler jobs to use per project
+ when building with msbuild or Visual Studio. Only supported for Visual Studio
+ 2008 and Visual Studio 2010 CMake generators. 0 means use all
+ processors. Default is 0.
diff --git a/docs/CodeGenerator.rst b/docs/CodeGenerator.rst
new file mode 100644
index 00000000000..d1d0231105b
--- /dev/null
+++ b/docs/CodeGenerator.rst
@@ -0,0 +1,2428 @@
+.. _code_generator:
+
+==========================================
+The LLVM Target-Independent Code Generator
+==========================================
+
+.. role:: raw-html(raw)
+ :format: html
+
+.. raw:: html
+
+ <style>
+ .unknown { background-color: #C0C0C0; text-align: center; }
+ .unknown:before { content: "?" }
+ .no { background-color: #C11B17 }
+ .no:before { content: "N" }
+ .partial { background-color: #F88017 }
+ .yes { background-color: #0F0; }
+ .yes:before { content: "Y" }
+ </style>
+
+.. contents::
+ :local:
+
+.. warning::
+ This is a work in progress.
+
+Introduction
+============
+
+The LLVM target-independent code generator is a framework that provides a suite
+of reusable components for translating the LLVM internal representation to the
+machine code for a specified target---either in assembly form (suitable for a
+static compiler) or in binary machine code format (usable for a JIT
+compiler). The LLVM target-independent code generator consists of six main
+components:
+
+1. `Abstract target description`_ interfaces which capture important properties
+ about various aspects of the machine, independently of how they will be used.
+ These interfaces are defined in ``include/llvm/Target/``.
+
+2. Classes used to represent the `code being generated`_ for a target. These
+ classes are intended to be abstract enough to represent the machine code for
+ *any* target machine. These classes are defined in
+ ``include/llvm/CodeGen/``. At this level, concepts like "constant pool
+ entries" and "jump tables" are explicitly exposed.
+
+3. Classes and algorithms used to represent code as the object file level, the
+ `MC Layer`_. These classes represent assembly level constructs like labels,
+ sections, and instructions. At this level, concepts like "constant pool
+ entries" and "jump tables" don't exist.
+
+4. `Target-independent algorithms`_ used to implement various phases of native
+ code generation (register allocation, scheduling, stack frame representation,
+ etc). This code lives in ``lib/CodeGen/``.
+
+5. `Implementations of the abstract target description interfaces`_ for
+ particular targets. These machine descriptions make use of the components
+ provided by LLVM, and can optionally provide custom target-specific passes,
+ to build complete code generators for a specific target. Target descriptions
+ live in ``lib/Target/``.
+
+6. The target-independent JIT components. The LLVM JIT is completely target
+ independent (it uses the ``TargetJITInfo`` structure to interface for
+ target-specific issues. The code for the target-independent JIT lives in
+ ``lib/ExecutionEngine/JIT``.
+
+Depending on which part of the code generator you are interested in working on,
+different pieces of this will be useful to you. In any case, you should be
+familiar with the `target description`_ and `machine code representation`_
+classes. If you want to add a backend for a new target, you will need to
+`implement the target description`_ classes for your new target and understand
+the `LLVM code representation <LangRef.html>`_. If you are interested in
+implementing a new `code generation algorithm`_, it should only depend on the
+target-description and machine code representation classes, ensuring that it is
+portable.
+
+Required components in the code generator
+-----------------------------------------
+
+The two pieces of the LLVM code generator are the high-level interface to the
+code generator and the set of reusable components that can be used to build
+target-specific backends. The two most important interfaces (:raw-html:`<tt>`
+`TargetMachine`_ :raw-html:`</tt>` and :raw-html:`<tt>` `TargetData`_
+:raw-html:`</tt>`) are the only ones that are required to be defined for a
+backend to fit into the LLVM system, but the others must be defined if the
+reusable code generator components are going to be used.
+
+This design has two important implications. The first is that LLVM can support
+completely non-traditional code generation targets. For example, the C backend
+does not require register allocation, instruction selection, or any of the other
+standard components provided by the system. As such, it only implements these
+two interfaces, and does its own thing. Note that C backend was removed from the
+trunk since LLVM 3.1 release. Another example of a code generator like this is a
+(purely hypothetical) backend that converts LLVM to the GCC RTL form and uses
+GCC to emit machine code for a target.
+
+This design also implies that it is possible to design and implement radically
+different code generators in the LLVM system that do not make use of any of the
+built-in components. Doing so is not recommended at all, but could be required
+for radically different targets that do not fit into the LLVM machine
+description model: FPGAs for example.
+
+.. _high-level design of the code generator:
+
+The high-level design of the code generator
+-------------------------------------------
+
+The LLVM target-independent code generator is designed to support efficient and
+quality code generation for standard register-based microprocessors. Code
+generation in this model is divided into the following stages:
+
+1. `Instruction Selection`_ --- This phase determines an efficient way to
+ express the input LLVM code in the target instruction set. This stage
+ produces the initial code for the program in the target instruction set, then
+ makes use of virtual registers in SSA form and physical registers that
+ represent any required register assignments due to target constraints or
+ calling conventions. This step turns the LLVM code into a DAG of target
+ instructions.
+
+2. `Scheduling and Formation`_ --- This phase takes the DAG of target
+ instructions produced by the instruction selection phase, determines an
+ ordering of the instructions, then emits the instructions as :raw-html:`<tt>`
+ `MachineInstr`_\s :raw-html:`</tt>` with that ordering. Note that we
+ describe this in the `instruction selection section`_ because it operates on
+ a `SelectionDAG`_.
+
+3. `SSA-based Machine Code Optimizations`_ --- This optional stage consists of a
+ series of machine-code optimizations that operate on the SSA-form produced by
+ the instruction selector. Optimizations like modulo-scheduling or peephole
+ optimization work here.
+
+4. `Register Allocation`_ --- The target code is transformed from an infinite
+ virtual register file in SSA form to the concrete register file used by the
+ target. This phase introduces spill code and eliminates all virtual register
+ references from the program.
+
+5. `Prolog/Epilog Code Insertion`_ --- Once the machine code has been generated
+ for the function and the amount of stack space required is known (used for
+ LLVM alloca's and spill slots), the prolog and epilog code for the function
+ can be inserted and "abstract stack location references" can be eliminated.
+ This stage is responsible for implementing optimizations like frame-pointer
+ elimination and stack packing.
+
+6. `Late Machine Code Optimizations`_ --- Optimizations that operate on "final"
+ machine code can go here, such as spill code scheduling and peephole
+ optimizations.
+
+7. `Code Emission`_ --- The final stage actually puts out the code for the
+ current function, either in the target assembler format or in machine
+ code.
+
+The code generator is based on the assumption that the instruction selector will
+use an optimal pattern matching selector to create high-quality sequences of
+native instructions. Alternative code generator designs based on pattern
+expansion and aggressive iterative peephole optimization are much slower. This
+design permits efficient compilation (important for JIT environments) and
+aggressive optimization (used when generating code offline) by allowing
+components of varying levels of sophistication to be used for any step of
+compilation.
+
+In addition to these stages, target implementations can insert arbitrary
+target-specific passes into the flow. For example, the X86 target uses a
+special pass to handle the 80x87 floating point stack architecture. Other
+targets with unusual requirements can be supported with custom passes as needed.
+
+Using TableGen for target description
+-------------------------------------
+
+The target description classes require a detailed description of the target
+architecture. These target descriptions often have a large amount of common
+information (e.g., an ``add`` instruction is almost identical to a ``sub``
+instruction). In order to allow the maximum amount of commonality to be
+factored out, the LLVM code generator uses the
+`TableGen <TableGenFundamentals.html>`_ tool to describe big chunks of the
+target machine, which allows the use of domain-specific and target-specific
+abstractions to reduce the amount of repetition.
+
+As LLVM continues to be developed and refined, we plan to move more and more of
+the target description to the ``.td`` form. Doing so gives us a number of
+advantages. The most important is that it makes it easier to port LLVM because
+it reduces the amount of C++ code that has to be written, and the surface area
+of the code generator that needs to be understood before someone can get
+something working. Second, it makes it easier to change things. In particular,
+if tables and other things are all emitted by ``tblgen``, we only need a change
+in one place (``tblgen``) to update all of the targets to a new interface.
+
+.. _Abstract target description:
+.. _target description:
+
+Target description classes
+==========================
+
+The LLVM target description classes (located in the ``include/llvm/Target``
+directory) provide an abstract description of the target machine independent of
+any particular client. These classes are designed to capture the *abstract*
+properties of the target (such as the instructions and registers it has), and do
+not incorporate any particular pieces of code generation algorithms.
+
+All of the target description classes (except the :raw-html:`<tt>` `TargetData`_
+:raw-html:`</tt>` class) are designed to be subclassed by the concrete target
+implementation, and have virtual methods implemented. To get to these
+implementations, the :raw-html:`<tt>` `TargetMachine`_ :raw-html:`</tt>` class
+provides accessors that should be implemented by the target.
+
+.. _TargetMachine:
+
+The ``TargetMachine`` class
+---------------------------
+
+The ``TargetMachine`` class provides virtual methods that are used to access the
+target-specific implementations of the various target description classes via
+the ``get*Info`` methods (``getInstrInfo``, ``getRegisterInfo``,
+``getFrameInfo``, etc.). This class is designed to be specialized by a concrete
+target implementation (e.g., ``X86TargetMachine``) which implements the various
+virtual methods. The only required target description class is the
+:raw-html:`<tt>` `TargetData`_ :raw-html:`</tt>` class, but if the code
+generator components are to be used, the other interfaces should be implemented
+as well.
+
+.. _TargetData:
+
+The ``TargetData`` class
+------------------------
+
+The ``TargetData`` class is the only required target description class, and it
+is the only class that is not extensible (you cannot derived a new class from
+it). ``TargetData`` specifies information about how the target lays out memory
+for structures, the alignment requirements for various data types, the size of
+pointers in the target, and whether the target is little-endian or
+big-endian.
+
+.. _targetlowering:
+
+The ``TargetLowering`` class
+----------------------------
+
+The ``TargetLowering`` class is used by SelectionDAG based instruction selectors
+primarily to describe how LLVM code should be lowered to SelectionDAG
+operations. Among other things, this class indicates:
+
+* an initial register class to use for various ``ValueType``\s,
+
+* which operations are natively supported by the target machine,
+
+* the return type of ``setcc`` operations,
+
+* the type to use for shift amounts, and
+
+* various high-level characteristics, like whether it is profitable to turn
+ division by a constant into a multiplication sequence
+
+The ``TargetRegisterInfo`` class
+--------------------------------
+
+The ``TargetRegisterInfo`` class is used to describe the register file of the
+target and any interactions between the registers.
+
+Registers in the code generator are represented in the code generator by
+unsigned integers. Physical registers (those that actually exist in the target
+description) are unique small numbers, and virtual registers are generally
+large. Note that register ``#0`` is reserved as a flag value.
+
+Each register in the processor description has an associated
+``TargetRegisterDesc`` entry, which provides a textual name for the register
+(used for assembly output and debugging dumps) and a set of aliases (used to
+indicate whether one register overlaps with another).
+
+In addition to the per-register description, the ``TargetRegisterInfo`` class
+exposes a set of processor specific register classes (instances of the
+``TargetRegisterClass`` class). Each register class contains sets of registers
+that have the same properties (for example, they are all 32-bit integer
+registers). Each SSA virtual register created by the instruction selector has
+an associated register class. When the register allocator runs, it replaces
+virtual registers with a physical register in the set.
+
+The target-specific implementations of these classes is auto-generated from a
+`TableGen <TableGenFundamentals.html>`_ description of the register file.
+
+.. _TargetInstrInfo:
+
+The ``TargetInstrInfo`` class
+-----------------------------
+
+The ``TargetInstrInfo`` class is used to describe the machine instructions
+supported by the target. It is essentially an array of ``TargetInstrDescriptor``
+objects, each of which describes one instruction the target
+supports. Descriptors define things like the mnemonic for the opcode, the number
+of operands, the list of implicit register uses and defs, whether the
+instruction has certain target-independent properties (accesses memory, is
+commutable, etc), and holds any target-specific flags.
+
+The ``TargetFrameInfo`` class
+-----------------------------
+
+The ``TargetFrameInfo`` class is used to provide information about the stack
+frame layout of the target. It holds the direction of stack growth, the known
+stack alignment on entry to each function, and the offset to the local area.
+The offset to the local area is the offset from the stack pointer on function
+entry to the first location where function data (local variables, spill
+locations) can be stored.
+
+The ``TargetSubtarget`` class
+-----------------------------
+
+The ``TargetSubtarget`` class is used to provide information about the specific
+chip set being targeted. A sub-target informs code generation of which
+instructions are supported, instruction latencies and instruction execution
+itinerary; i.e., which processing units are used, in what order, and for how
+long.
+
+The ``TargetJITInfo`` class
+---------------------------
+
+The ``TargetJITInfo`` class exposes an abstract interface used by the
+Just-In-Time code generator to perform target-specific activities, such as
+emitting stubs. If a ``TargetMachine`` supports JIT code generation, it should
+provide one of these objects through the ``getJITInfo`` method.
+
+.. _code being generated:
+.. _machine code representation:
+
+Machine code description classes
+================================
+
+At the high-level, LLVM code is translated to a machine specific representation
+formed out of :raw-html:`<tt>` `MachineFunction`_ :raw-html:`</tt>`,
+:raw-html:`<tt>` `MachineBasicBlock`_ :raw-html:`</tt>`, and :raw-html:`<tt>`
+`MachineInstr`_ :raw-html:`</tt>` instances (defined in
+``include/llvm/CodeGen``). This representation is completely target agnostic,
+representing instructions in their most abstract form: an opcode and a series of
+operands. This representation is designed to support both an SSA representation
+for machine code, as well as a register allocated, non-SSA form.
+
+.. _MachineInstr:
+
+The ``MachineInstr`` class
+--------------------------
+
+Target machine instructions are represented as instances of the ``MachineInstr``
+class. This class is an extremely abstract way of representing machine
+instructions. In particular, it only keeps track of an opcode number and a set
+of operands.
+
+The opcode number is a simple unsigned integer that only has meaning to a
+specific backend. All of the instructions for a target should be defined in the
+``*InstrInfo.td`` file for the target. The opcode enum values are auto-generated
+from this description. The ``MachineInstr`` class does not have any information
+about how to interpret the instruction (i.e., what the semantics of the
+instruction are); for that you must refer to the :raw-html:`<tt>`
+`TargetInstrInfo`_ :raw-html:`</tt>` class.
+
+The operands of a machine instruction can be of several different types: a
+register reference, a constant integer, a basic block reference, etc. In
+addition, a machine operand should be marked as a def or a use of the value
+(though only registers are allowed to be defs).
+
+By convention, the LLVM code generator orders instruction operands so that all
+register definitions come before the register uses, even on architectures that
+are normally printed in other orders. For example, the SPARC add instruction:
+"``add %i1, %i2, %i3``" adds the "%i1", and "%i2" registers and stores the
+result into the "%i3" register. In the LLVM code generator, the operands should
+be stored as "``%i3, %i1, %i2``": with the destination first.
+
+Keeping destination (definition) operands at the beginning of the operand list
+has several advantages. In particular, the debugging printer will print the
+instruction like this:
+
+.. code-block:: llvm
+
+ %r3 = add %i1, %i2
+
+Also if the first operand is a def, it is easier to `create instructions`_ whose
+only def is the first operand.
+
+.. _create instructions:
+
+Using the ``MachineInstrBuilder.h`` functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Machine instructions are created by using the ``BuildMI`` functions, located in
+the ``include/llvm/CodeGen/MachineInstrBuilder.h`` file. The ``BuildMI``
+functions make it easy to build arbitrary machine instructions. Usage of the
+``BuildMI`` functions look like this:
+
+.. code-block:: c++
+
+ // Create a 'DestReg = mov 42' (rendered in X86 assembly as 'mov DestReg, 42')
+ // instruction. The '1' specifies how many operands will be added.
+ MachineInstr *MI = BuildMI(X86::MOV32ri, 1, DestReg).addImm(42);
+
+ // Create the same instr, but insert it at the end of a basic block.
+ MachineBasicBlock &amp;MBB = ...
+ BuildMI(MBB, X86::MOV32ri, 1, DestReg).addImm(42);
+
+ // Create the same instr, but insert it before a specified iterator point.
+ MachineBasicBlock::iterator MBBI = ...
+ BuildMI(MBB, MBBI, X86::MOV32ri, 1, DestReg).addImm(42);
+
+ // Create a 'cmp Reg, 0' instruction, no destination reg.
+ MI = BuildMI(X86::CMP32ri, 2).addReg(Reg).addImm(0);
+
+ // Create an 'sahf' instruction which takes no operands and stores nothing.
+ MI = BuildMI(X86::SAHF, 0);
+
+ // Create a self looping branch instruction.
+ BuildMI(MBB, X86::JNE, 1).addMBB(&amp;MBB);
+
+The key thing to remember with the ``BuildMI`` functions is that you have to
+specify the number of operands that the machine instruction will take. This
+allows for efficient memory allocation. You also need to specify if operands
+default to be uses of values, not definitions. If you need to add a definition
+operand (other than the optional destination register), you must explicitly mark
+it as such:
+
+.. code-block:: c++
+
+ MI.addReg(Reg, RegState::Define);
+
+Fixed (preassigned) registers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+One important issue that the code generator needs to be aware of is the presence
+of fixed registers. In particular, there are often places in the instruction
+stream where the register allocator *must* arrange for a particular value to be
+in a particular register. This can occur due to limitations of the instruction
+set (e.g., the X86 can only do a 32-bit divide with the ``EAX``/``EDX``
+registers), or external factors like calling conventions. In any case, the
+instruction selector should emit code that copies a virtual register into or out
+of a physical register when needed.
+
+For example, consider this simple LLVM example:
+
+.. code-block:: llvm
+
+ define i32 @test(i32 %X, i32 %Y) {
+ %Z = udiv i32 %X, %Y
+ ret i32 %Z
+ }
+
+The X86 instruction selector produces this machine code for the ``div`` and
+``ret`` (use "``llc X.bc -march=x86 -print-machineinstrs``" to get this):
+
+.. code-block:: llvm
+
+ ;; Start of div
+ %EAX = mov %reg1024 ;; Copy X (in reg1024) into EAX
+ %reg1027 = sar %reg1024, 31
+ %EDX = mov %reg1027 ;; Sign extend X into EDX
+ idiv %reg1025 ;; Divide by Y (in reg1025)
+ %reg1026 = mov %EAX ;; Read the result (Z) out of EAX
+
+ ;; Start of ret
+ %EAX = mov %reg1026 ;; 32-bit return value goes in EAX
+ ret
+
+By the end of code generation, the register allocator has coalesced the
+registers and deleted the resultant identity moves producing the following
+code:
+
+.. code-block:: llvm
+
+ ;; X is in EAX, Y is in ECX
+ mov %EAX, %EDX
+ sar %EDX, 31
+ idiv %ECX
+ ret
+
+This approach is extremely general (if it can handle the X86 architecture, it
+can handle anything!) and allows all of the target specific knowledge about the
+instruction stream to be isolated in the instruction selector. Note that
+physical registers should have a short lifetime for good code generation, and
+all physical registers are assumed dead on entry to and exit from basic blocks
+(before register allocation). Thus, if you need a value to be live across basic
+block boundaries, it *must* live in a virtual register.
+
+Call-clobbered registers
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Some machine instructions, like calls, clobber a large number of physical
+registers. Rather than adding ``<def,dead>`` operands for all of them, it is
+possible to use an ``MO_RegisterMask`` operand instead. The register mask
+operand holds a bit mask of preserved registers, and everything else is
+considered to be clobbered by the instruction.
+
+Machine code in SSA form
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+``MachineInstr``'s are initially selected in SSA-form, and are maintained in
+SSA-form until register allocation happens. For the most part, this is
+trivially simple since LLVM is already in SSA form; LLVM PHI nodes become
+machine code PHI nodes, and virtual registers are only allowed to have a single
+definition.
+
+After register allocation, machine code is no longer in SSA-form because there
+are no virtual registers left in the code.
+
+.. _MachineBasicBlock:
+
+The ``MachineBasicBlock`` class
+-------------------------------
+
+The ``MachineBasicBlock`` class contains a list of machine instructions
+(:raw-html:`<tt>` `MachineInstr`_ :raw-html:`</tt>` instances). It roughly
+corresponds to the LLVM code input to the instruction selector, but there can be
+a one-to-many mapping (i.e. one LLVM basic block can map to multiple machine
+basic blocks). The ``MachineBasicBlock`` class has a "``getBasicBlock``" method,
+which returns the LLVM basic block that it comes from.
+
+.. _MachineFunction:
+
+The ``MachineFunction`` class
+-----------------------------
+
+The ``MachineFunction`` class contains a list of machine basic blocks
+(:raw-html:`<tt>` `MachineBasicBlock`_ :raw-html:`</tt>` instances). It
+corresponds one-to-one with the LLVM function input to the instruction selector.
+In addition to a list of basic blocks, the ``MachineFunction`` contains a a
+``MachineConstantPool``, a ``MachineFrameInfo``, a ``MachineFunctionInfo``, and
+a ``MachineRegisterInfo``. See ``include/llvm/CodeGen/MachineFunction.h`` for
+more information.
+
+``MachineInstr Bundles``
+------------------------
+
+LLVM code generator can model sequences of instructions as MachineInstr
+bundles. A MI bundle can model a VLIW group / pack which contains an arbitrary
+number of parallel instructions. It can also be used to model a sequential list
+of instructions (potentially with data dependencies) that cannot be legally
+separated (e.g. ARM Thumb2 IT blocks).
+
+Conceptually a MI bundle is a MI with a number of other MIs nested within:
+
+::
+
+ --------------
+ | Bundle | ---------
+ -------------- \
+ | ----------------
+ | | MI |
+ | ----------------
+ | |
+ | ----------------
+ | | MI |
+ | ----------------
+ | |
+ | ----------------
+ | | MI |
+ | ----------------
+ |
+ --------------
+ | Bundle | --------
+ -------------- \
+ | ----------------
+ | | MI |
+ | ----------------
+ | |
+ | ----------------
+ | | MI |
+ | ----------------
+ | |
+ | ...
+ |
+ --------------
+ | Bundle | --------
+ -------------- \
+ |
+ ...
+
+MI bundle support does not change the physical representations of
+MachineBasicBlock and MachineInstr. All the MIs (including top level and nested
+ones) are stored as sequential list of MIs. The "bundled" MIs are marked with
+the 'InsideBundle' flag. A top level MI with the special BUNDLE opcode is used
+to represent the start of a bundle. It's legal to mix BUNDLE MIs with indiviual
+MIs that are not inside bundles nor represent bundles.
+
+MachineInstr passes should operate on a MI bundle as a single unit. Member
+methods have been taught to correctly handle bundles and MIs inside bundles.
+The MachineBasicBlock iterator has been modified to skip over bundled MIs to
+enforce the bundle-as-a-single-unit concept. An alternative iterator
+instr_iterator has been added to MachineBasicBlock to allow passes to iterate
+over all of the MIs in a MachineBasicBlock, including those which are nested
+inside bundles. The top level BUNDLE instruction must have the correct set of
+register MachineOperand's that represent the cumulative inputs and outputs of
+the bundled MIs.
+
+Packing / bundling of MachineInstr's should be done as part of the register
+allocation super-pass. More specifically, the pass which determines what MIs
+should be bundled together must be done after code generator exits SSA form
+(i.e. after two-address pass, PHI elimination, and copy coalescing). Bundles
+should only be finalized (i.e. adding BUNDLE MIs and input and output register
+MachineOperands) after virtual registers have been rewritten into physical
+registers. This requirement eliminates the need to add virtual register operands
+to BUNDLE instructions which would effectively double the virtual register def
+and use lists.
+
+.. _MC Layer:
+
+The "MC" Layer
+==============
+
+The MC Layer is used to represent and process code at the raw machine code
+level, devoid of "high level" information like "constant pools", "jump tables",
+"global variables" or anything like that. At this level, LLVM handles things
+like label names, machine instructions, and sections in the object file. The
+code in this layer is used for a number of important purposes: the tail end of
+the code generator uses it to write a .s or .o file, and it is also used by the
+llvm-mc tool to implement standalone machine code assemblers and disassemblers.
+
+This section describes some of the important classes. There are also a number
+of important subsystems that interact at this layer, they are described later in
+this manual.
+
+.. _MCStreamer:
+
+The ``MCStreamer`` API
+----------------------
+
+MCStreamer is best thought of as an assembler API. It is an abstract API which
+is *implemented* in different ways (e.g. to output a .s file, output an ELF .o
+file, etc) but whose API correspond directly to what you see in a .s file.
+MCStreamer has one method per directive, such as EmitLabel, EmitSymbolAttribute,
+SwitchSection, EmitValue (for .byte, .word), etc, which directly correspond to
+assembly level directives. It also has an EmitInstruction method, which is used
+to output an MCInst to the streamer.
+
+This API is most important for two clients: the llvm-mc stand-alone assembler is
+effectively a parser that parses a line, then invokes a method on MCStreamer. In
+the code generator, the `Code Emission`_ phase of the code generator lowers
+higher level LLVM IR and Machine* constructs down to the MC layer, emitting
+directives through MCStreamer.
+
+On the implementation side of MCStreamer, there are two major implementations:
+one for writing out a .s file (MCAsmStreamer), and one for writing out a .o
+file (MCObjectStreamer). MCAsmStreamer is a straight-forward implementation
+that prints out a directive for each method (e.g. ``EmitValue -> .byte``), but
+MCObjectStreamer implements a full assembler.
+
+The ``MCContext`` class
+-----------------------
+
+The MCContext class is the owner of a variety of uniqued data structures at the
+MC layer, including symbols, sections, etc. As such, this is the class that you
+interact with to create symbols and sections. This class can not be subclassed.
+
+The ``MCSymbol`` class
+----------------------
+
+The MCSymbol class represents a symbol (aka label) in the assembly file. There
+are two interesting kinds of symbols: assembler temporary symbols, and normal
+symbols. Assembler temporary symbols are used and processed by the assembler
+but are discarded when the object file is produced. The distinction is usually
+represented by adding a prefix to the label, for example "L" labels are
+assembler temporary labels in MachO.
+
+MCSymbols are created by MCContext and uniqued there. This means that MCSymbols
+can be compared for pointer equivalence to find out if they are the same symbol.
+Note that pointer inequality does not guarantee the labels will end up at
+different addresses though. It's perfectly legal to output something like this
+to the .s file:
+
+::
+
+ foo:
+ bar:
+ .byte 4
+
+In this case, both the foo and bar symbols will have the same address.
+
+The ``MCSection`` class
+-----------------------
+
+The ``MCSection`` class represents an object-file specific section. It is
+subclassed by object file specific implementations (e.g. ``MCSectionMachO``,
+``MCSectionCOFF``, ``MCSectionELF``) and these are created and uniqued by
+MCContext. The MCStreamer has a notion of the current section, which can be
+changed with the SwitchToSection method (which corresponds to a ".section"
+directive in a .s file).
+
+.. _MCInst:
+
+The ``MCInst`` class
+--------------------
+
+The ``MCInst`` class is a target-independent representation of an instruction.
+It is a simple class (much more so than `MachineInstr`_) that holds a
+target-specific opcode and a vector of MCOperands. MCOperand, in turn, is a
+simple discriminated union of three cases: 1) a simple immediate, 2) a target
+register ID, 3) a symbolic expression (e.g. "``Lfoo-Lbar+42``") as an MCExpr.
+
+MCInst is the common currency used to represent machine instructions at the MC
+layer. It is the type used by the instruction encoder, the instruction printer,
+and the type generated by the assembly parser and disassembler.
+
+.. _Target-independent algorithms:
+.. _code generation algorithm:
+
+Target-independent code generation algorithms
+=============================================
+
+This section documents the phases described in the `high-level design of the
+code generator`_. It explains how they work and some of the rationale behind
+their design.
+
+.. _Instruction Selection:
+.. _instruction selection section:
+
+Instruction Selection
+---------------------
+
+Instruction Selection is the process of translating LLVM code presented to the
+code generator into target-specific machine instructions. There are several
+well-known ways to do this in the literature. LLVM uses a SelectionDAG based
+instruction selector.
+
+Portions of the DAG instruction selector are generated from the target
+description (``*.td``) files. Our goal is for the entire instruction selector
+to be generated from these ``.td`` files, though currently there are still
+things that require custom C++ code.
+
+.. _SelectionDAG:
+
+Introduction to SelectionDAGs
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The SelectionDAG provides an abstraction for code representation in a way that
+is amenable to instruction selection using automatic techniques
+(e.g. dynamic-programming based optimal pattern matching selectors). It is also
+well-suited to other phases of code generation; in particular, instruction
+scheduling (SelectionDAG's are very close to scheduling DAGs post-selection).
+Additionally, the SelectionDAG provides a host representation where a large
+variety of very-low-level (but target-independent) `optimizations`_ may be
+performed; ones which require extensive information about the instructions
+efficiently supported by the target.
+
+The SelectionDAG is a Directed-Acyclic-Graph whose nodes are instances of the
+``SDNode`` class. The primary payload of the ``SDNode`` is its operation code
+(Opcode) that indicates what operation the node performs and the operands to the
+operation. The various operation node types are described at the top of the
+``include/llvm/CodeGen/SelectionDAGNodes.h`` file.
+
+Although most operations define a single value, each node in the graph may
+define multiple values. For example, a combined div/rem operation will define
+both the dividend and the remainder. Many other situations require multiple
+values as well. Each node also has some number of operands, which are edges to
+the node defining the used value. Because nodes may define multiple values,
+edges are represented by instances of the ``SDValue`` class, which is a
+``<SDNode, unsigned>`` pair, indicating the node and result value being used,
+respectively. Each value produced by an ``SDNode`` has an associated ``MVT``
+(Machine Value Type) indicating what the type of the value is.
+
+SelectionDAGs contain two different kinds of values: those that represent data
+flow and those that represent control flow dependencies. Data values are simple
+edges with an integer or floating point value type. Control edges are
+represented as "chain" edges which are of type ``MVT::Other``. These edges
+provide an ordering between nodes that have side effects (such as loads, stores,
+calls, returns, etc). All nodes that have side effects should take a token
+chain as input and produce a new one as output. By convention, token chain
+inputs are always operand #0, and chain results are always the last value
+produced by an operation.
+
+A SelectionDAG has designated "Entry" and "Root" nodes. The Entry node is
+always a marker node with an Opcode of ``ISD::EntryToken``. The Root node is
+the final side-effecting node in the token chain. For example, in a single basic
+block function it would be the return node.
+
+One important concept for SelectionDAGs is the notion of a "legal" vs.
+"illegal" DAG. A legal DAG for a target is one that only uses supported
+operations and supported types. On a 32-bit PowerPC, for example, a DAG with a
+value of type i1, i8, i16, or i64 would be illegal, as would a DAG that uses a
+SREM or UREM operation. The `legalize types`_ and `legalize operations`_ phases
+are responsible for turning an illegal DAG into a legal DAG.
+
+SelectionDAG Instruction Selection Process
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+SelectionDAG-based instruction selection consists of the following steps:
+
+#. `Build initial DAG`_ --- This stage performs a simple translation from the
+ input LLVM code to an illegal SelectionDAG.
+
+#. `Optimize SelectionDAG`_ --- This stage performs simple optimizations on the
+ SelectionDAG to simplify it, and recognize meta instructions (like rotates
+ and ``div``/``rem`` pairs) for targets that support these meta operations.
+ This makes the resultant code more efficient and the `select instructions
+ from DAG`_ phase (below) simpler.
+
+#. `Legalize SelectionDAG Types`_ --- This stage transforms SelectionDAG nodes
+ to eliminate any types that are unsupported on the target.
+
+#. `Optimize SelectionDAG`_ --- The SelectionDAG optimizer is run to clean up
+ redundancies exposed by type legalization.
+
+#. `Legalize SelectionDAG Ops`_ --- This stage transforms SelectionDAG nodes to
+ eliminate any operations that are unsupported on the target.
+
+#. `Optimize SelectionDAG`_ --- The SelectionDAG optimizer is run to eliminate
+ inefficiencies introduced by operation legalization.
+
+#. `Select instructions from DAG`_ --- Finally, the target instruction selector
+ matches the DAG operations to target instructions. This process translates
+ the target-independent input DAG into another DAG of target instructions.
+
+#. `SelectionDAG Scheduling and Formation`_ --- The last phase assigns a linear
+ order to the instructions in the target-instruction DAG and emits them into
+ the MachineFunction being compiled. This step uses traditional prepass
+ scheduling techniques.
+
+After all of these steps are complete, the SelectionDAG is destroyed and the
+rest of the code generation passes are run.
+
+One great way to visualize what is going on here is to take advantage of a few
+LLC command line options. The following options pop up a window displaying the
+SelectionDAG at specific times (if you only get errors printed to the console
+while using this, you probably `need to configure your
+system <ProgrammersManual.html#ViewGraph>`_ to add support for it).
+
+* ``-view-dag-combine1-dags`` displays the DAG after being built, before the
+ first optimization pass.
+
+* ``-view-legalize-dags`` displays the DAG before Legalization.
+
+* ``-view-dag-combine2-dags`` displays the DAG before the second optimization
+ pass.
+
+* ``-view-isel-dags`` displays the DAG before the Select phase.
+
+* ``-view-sched-dags`` displays the DAG before Scheduling.
+
+The ``-view-sunit-dags`` displays the Scheduler's dependency graph. This graph
+is based on the final SelectionDAG, with nodes that must be scheduled together
+bundled into a single scheduling-unit node, and with immediate operands and
+other nodes that aren't relevant for scheduling omitted.
+
+.. _Build initial DAG:
+
+Initial SelectionDAG Construction
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The initial SelectionDAG is na\ :raw-html:`&iuml;`\ vely peephole expanded from
+the LLVM input by the ``SelectionDAGLowering`` class in the
+``lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp`` file. The intent of this pass
+is to expose as much low-level, target-specific details to the SelectionDAG as
+possible. This pass is mostly hard-coded (e.g. an LLVM ``add`` turns into an
+``SDNode add`` while a ``getelementptr`` is expanded into the obvious
+arithmetic). This pass requires target-specific hooks to lower calls, returns,
+varargs, etc. For these features, the :raw-html:`<tt>` `TargetLowering`_
+:raw-html:`</tt>` interface is used.
+
+.. _legalize types:
+.. _Legalize SelectionDAG Types:
+.. _Legalize SelectionDAG Ops:
+
+SelectionDAG LegalizeTypes Phase
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The Legalize phase is in charge of converting a DAG to only use the types that
+are natively supported by the target.
+
+There are two main ways of converting values of unsupported scalar types to
+values of supported types: converting small types to larger types ("promoting"),
+and breaking up large integer types into smaller ones ("expanding"). For
+example, a target might require that all f32 values are promoted to f64 and that
+all i1/i8/i16 values are promoted to i32. The same target might require that
+all i64 values be expanded into pairs of i32 values. These changes can insert
+sign and zero extensions as needed to make sure that the final code has the same
+behavior as the input.
+
+There are two main ways of converting values of unsupported vector types to
+value of supported types: splitting vector types, multiple times if necessary,
+until a legal type is found, and extending vector types by adding elements to
+the end to round them out to legal types ("widening"). If a vector gets split
+all the way down to single-element parts with no supported vector type being
+found, the elements are converted to scalars ("scalarizing").
+
+A target implementation tells the legalizer which types are supported (and which
+register class to use for them) by calling the ``addRegisterClass`` method in
+its TargetLowering constructor.
+
+.. _legalize operations:
+.. _Legalizer:
+
+SelectionDAG Legalize Phase
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The Legalize phase is in charge of converting a DAG to only use the operations
+that are natively supported by the target.
+
+Targets often have weird constraints, such as not supporting every operation on
+every supported datatype (e.g. X86 does not support byte conditional moves and
+PowerPC does not support sign-extending loads from a 16-bit memory location).
+Legalize takes care of this by open-coding another sequence of operations to
+emulate the operation ("expansion"), by promoting one type to a larger type that
+supports the operation ("promotion"), or by using a target-specific hook to
+implement the legalization ("custom").
+
+A target implementation tells the legalizer which operations are not supported
+(and which of the above three actions to take) by calling the
+``setOperationAction`` method in its ``TargetLowering`` constructor.
+
+Prior to the existence of the Legalize passes, we required that every target
+`selector`_ supported and handled every operator and type even if they are not
+natively supported. The introduction of the Legalize phases allows all of the
+canonicalization patterns to be shared across targets, and makes it very easy to
+optimize the canonicalized code because it is still in the form of a DAG.
+
+.. _optimizations:
+.. _Optimize SelectionDAG:
+.. _selector:
+
+SelectionDAG Optimization Phase: the DAG Combiner
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The SelectionDAG optimization phase is run multiple times for code generation,
+immediately after the DAG is built and once after each legalization. The first
+run of the pass allows the initial code to be cleaned up (e.g. performing
+optimizations that depend on knowing that the operators have restricted type
+inputs). Subsequent runs of the pass clean up the messy code generated by the
+Legalize passes, which allows Legalize to be very simple (it can focus on making
+code legal instead of focusing on generating *good* and legal code).
+
+One important class of optimizations performed is optimizing inserted sign and
+zero extension instructions. We currently use ad-hoc techniques, but could move
+to more rigorous techniques in the future. Here are some good papers on the
+subject:
+
+"`Widening integer arithmetic <http://www.eecs.harvard.edu/~nr/pubs/widen-abstract.html>`_" :raw-html:`<br>`
+Kevin Redwine and Norman Ramsey :raw-html:`<br>`
+International Conference on Compiler Construction (CC) 2004
+
+"`Effective sign extension elimination <http://portal.acm.org/citation.cfm?doid=512529.512552>`_" :raw-html:`<br>`
+Motohiro Kawahito, Hideaki Komatsu, and Toshio Nakatani :raw-html:`<br>`
+Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language Design
+and Implementation.
+
+.. _Select instructions from DAG:
+
+SelectionDAG Select Phase
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The Select phase is the bulk of the target-specific code for instruction
+selection. This phase takes a legal SelectionDAG as input, pattern matches the
+instructions supported by the target to this DAG, and produces a new DAG of
+target code. For example, consider the following LLVM fragment:
+
+.. code-block:: llvm
+
+ %t1 = fadd float %W, %X
+ %t2 = fmul float %t1, %Y
+ %t3 = fadd float %t2, %Z
+
+This LLVM code corresponds to a SelectionDAG that looks basically like this:
+
+.. code-block:: llvm
+
+ (fadd:f32 (fmul:f32 (fadd:f32 W, X), Y), Z)
+
+If a target supports floating point multiply-and-add (FMA) operations, one of
+the adds can be merged with the multiply. On the PowerPC, for example, the
+output of the instruction selector might look like this DAG:
+
+::
+
+ (FMADDS (FADDS W, X), Y, Z)
+
+The ``FMADDS`` instruction is a ternary instruction that multiplies its first
+two operands and adds the third (as single-precision floating-point numbers).
+The ``FADDS`` instruction is a simple binary single-precision add instruction.
+To perform this pattern match, the PowerPC backend includes the following
+instruction definitions:
+
+::
+
+ def FMADDS : AForm_1<59, 29,
+ (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRC, F4RC:$FRB),
+ "fmadds $FRT, $FRA, $FRC, $FRB",
+ [(set F4RC:$FRT, (fadd (fmul F4RC:$FRA, F4RC:$FRC),
+ F4RC:$FRB))]>;
+ def FADDS : AForm_2<59, 21,
+ (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRB),
+ "fadds $FRT, $FRA, $FRB",
+ [(set F4RC:$FRT, (fadd F4RC:$FRA, F4RC:$FRB))]>;
+
+The portion of the instruction definition in bold indicates the pattern used to
+match the instruction. The DAG operators (like ``fmul``/``fadd``) are defined
+in the ``include/llvm/Target/TargetSelectionDAG.td`` file. " ``F4RC``" is the
+register class of the input and result values.
+
+The TableGen DAG instruction selector generator reads the instruction patterns
+in the ``.td`` file and automatically builds parts of the pattern matching code
+for your target. It has the following strengths:
+
+* At compiler-compiler time, it analyzes your instruction patterns and tells you
+ if your patterns make sense or not.
+
+* It can handle arbitrary constraints on operands for the pattern match. In
+ particular, it is straight-forward to say things like "match any immediate
+ that is a 13-bit sign-extended value". For examples, see the ``immSExt16``
+ and related ``tblgen`` classes in the PowerPC backend.
+
+* It knows several important identities for the patterns defined. For example,
+ it knows that addition is commutative, so it allows the ``FMADDS`` pattern
+ above to match "``(fadd X, (fmul Y, Z))``" as well as "``(fadd (fmul X, Y),
+ Z)``", without the target author having to specially handle this case.
+
+* It has a full-featured type-inferencing system. In particular, you should
+ rarely have to explicitly tell the system what type parts of your patterns
+ are. In the ``FMADDS`` case above, we didn't have to tell ``tblgen`` that all
+ of the nodes in the pattern are of type 'f32'. It was able to infer and
+ propagate this knowledge from the fact that ``F4RC`` has type 'f32'.
+
+* Targets can define their own (and rely on built-in) "pattern fragments".
+ Pattern fragments are chunks of reusable patterns that get inlined into your
+ patterns during compiler-compiler time. For example, the integer "``(not
+ x)``" operation is actually defined as a pattern fragment that expands as
+ "``(xor x, -1)``", since the SelectionDAG does not have a native '``not``'
+ operation. Targets can define their own short-hand fragments as they see fit.
+ See the definition of '``not``' and '``ineg``' for examples.
+
+* In addition to instructions, targets can specify arbitrary patterns that map
+ to one or more instructions using the 'Pat' class. For example, the PowerPC
+ has no way to load an arbitrary integer immediate into a register in one
+ instruction. To tell tblgen how to do this, it defines:
+
+ ::
+
+ // Arbitrary immediate support. Implement in terms of LIS/ORI.
+ def : Pat<(i32 imm:$imm),
+ (ORI (LIS (HI16 imm:$imm)), (LO16 imm:$imm))>;
+
+ If none of the single-instruction patterns for loading an immediate into a
+ register match, this will be used. This rule says "match an arbitrary i32
+ immediate, turning it into an ``ORI`` ('or a 16-bit immediate') and an ``LIS``
+ ('load 16-bit immediate, where the immediate is shifted to the left 16 bits')
+ instruction". To make this work, the ``LO16``/``HI16`` node transformations
+ are used to manipulate the input immediate (in this case, take the high or low
+ 16-bits of the immediate).
+
+* While the system does automate a lot, it still allows you to write custom C++
+ code to match special cases if there is something that is hard to
+ express.
+
+While it has many strengths, the system currently has some limitations,
+primarily because it is a work in progress and is not yet finished:
+
+* Overall, there is no way to define or match SelectionDAG nodes that define
+ multiple values (e.g. ``SMUL_LOHI``, ``LOAD``, ``CALL``, etc). This is the
+ biggest reason that you currently still *have to* write custom C++ code
+ for your instruction selector.
+
+* There is no great way to support matching complex addressing modes yet. In
+ the future, we will extend pattern fragments to allow them to define multiple
+ values (e.g. the four operands of the `X86 addressing mode`_, which are
+ currently matched with custom C++ code). In addition, we'll extend fragments
+ so that a fragment can match multiple different patterns.
+
+* We don't automatically infer flags like ``isStore``/``isLoad`` yet.
+
+* We don't automatically generate the set of supported registers and operations
+ for the `Legalizer`_ yet.
+
+* We don't have a way of tying in custom legalized nodes yet.
+
+Despite these limitations, the instruction selector generator is still quite
+useful for most of the binary and logical operations in typical instruction
+sets. If you run into any problems or can't figure out how to do something,
+please let Chris know!
+
+.. _Scheduling and Formation:
+.. _SelectionDAG Scheduling and Formation:
+
+SelectionDAG Scheduling and Formation Phase
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The scheduling phase takes the DAG of target instructions from the selection
+phase and assigns an order. The scheduler can pick an order depending on
+various constraints of the machines (i.e. order for minimal register pressure or
+try to cover instruction latencies). Once an order is established, the DAG is
+converted to a list of :raw-html:`<tt>` `MachineInstr`_\s :raw-html:`</tt>` and
+the SelectionDAG is destroyed.
+
+Note that this phase is logically separate from the instruction selection phase,
+but is tied to it closely in the code because it operates on SelectionDAGs.
+
+Future directions for the SelectionDAG
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+#. Optional function-at-a-time selection.
+
+#. Auto-generate entire selector from ``.td`` file.
+
+.. _SSA-based Machine Code Optimizations:
+
+SSA-based Machine Code Optimizations
+------------------------------------
+
+To Be Written
+
+Live Intervals
+--------------
+
+Live Intervals are the ranges (intervals) where a variable is *live*. They are
+used by some `register allocator`_ passes to determine if two or more virtual
+registers which require the same physical register are live at the same point in
+the program (i.e., they conflict). When this situation occurs, one virtual
+register must be *spilled*.
+
+Live Variable Analysis
+^^^^^^^^^^^^^^^^^^^^^^
+
+The first step in determining the live intervals of variables is to calculate
+the set of registers that are immediately dead after the instruction (i.e., the
+instruction calculates the value, but it is never used) and the set of registers
+that are used by the instruction, but are never used after the instruction
+(i.e., they are killed). Live variable information is computed for
+each *virtual* register and *register allocatable* physical register
+in the function. This is done in a very efficient manner because it uses SSA to
+sparsely compute lifetime information for virtual registers (which are in SSA
+form) and only has to track physical registers within a block. Before register
+allocation, LLVM can assume that physical registers are only live within a
+single basic block. This allows it to do a single, local analysis to resolve
+physical register lifetimes within each basic block. If a physical register is
+not register allocatable (e.g., a stack pointer or condition codes), it is not
+tracked.
+
+Physical registers may be live in to or out of a function. Live in values are
+typically arguments in registers. Live out values are typically return values in
+registers. Live in values are marked as such, and are given a dummy "defining"
+instruction during live intervals analysis. If the last basic block of a
+function is a ``return``, then it's marked as using all live out values in the
+function.
+
+``PHI`` nodes need to be handled specially, because the calculation of the live
+variable information from a depth first traversal of the CFG of the function
+won't guarantee that a virtual register used by the ``PHI`` node is defined
+before it's used. When a ``PHI`` node is encountered, only the definition is
+handled, because the uses will be handled in other basic blocks.
+
+For each ``PHI`` node of the current basic block, we simulate an assignment at
+the end of the current basic block and traverse the successor basic blocks. If a
+successor basic block has a ``PHI`` node and one of the ``PHI`` node's operands
+is coming from the current basic block, then the variable is marked as *alive*
+within the current basic block and all of its predecessor basic blocks, until
+the basic block with the defining instruction is encountered.
+
+Live Intervals Analysis
+^^^^^^^^^^^^^^^^^^^^^^^
+
+We now have the information available to perform the live intervals analysis and
+build the live intervals themselves. We start off by numbering the basic blocks
+and machine instructions. We then handle the "live-in" values. These are in
+physical registers, so the physical register is assumed to be killed by the end
+of the basic block. Live intervals for virtual registers are computed for some
+ordering of the machine instructions ``[1, N]``. A live interval is an interval
+``[i, j)``, where ``1 >= i >= j > N``, for which a variable is live.
+
+.. note::
+ More to come...
+
+.. _Register Allocation:
+.. _register allocator:
+
+Register Allocation
+-------------------
+
+The *Register Allocation problem* consists in mapping a program
+:raw-html:`<b><tt>` P\ :sub:`v`\ :raw-html:`</tt></b>`, that can use an unbounded
+number of virtual registers, to a program :raw-html:`<b><tt>` P\ :sub:`p`\
+:raw-html:`</tt></b>` that contains a finite (possibly small) number of physical
+registers. Each target architecture has a different number of physical
+registers. If the number of physical registers is not enough to accommodate all
+the virtual registers, some of them will have to be mapped into memory. These
+virtuals are called *spilled virtuals*.
+
+How registers are represented in LLVM
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In LLVM, physical registers are denoted by integer numbers that normally range
+from 1 to 1023. To see how this numbering is defined for a particular
+architecture, you can read the ``GenRegisterNames.inc`` file for that
+architecture. For instance, by inspecting
+``lib/Target/X86/X86GenRegisterInfo.inc`` we see that the 32-bit register
+``EAX`` is denoted by 43, and the MMX register ``MM0`` is mapped to 65.
+
+Some architectures contain registers that share the same physical location. A
+notable example is the X86 platform. For instance, in the X86 architecture, the
+registers ``EAX``, ``AX`` and ``AL`` share the first eight bits. These physical
+registers are marked as *aliased* in LLVM. Given a particular architecture, you
+can check which registers are aliased by inspecting its ``RegisterInfo.td``
+file. Moreover, the class ``MCRegAliasIterator`` enumerates all the physical
+registers aliased to a register.
+
+Physical registers, in LLVM, are grouped in *Register Classes*. Elements in the
+same register class are functionally equivalent, and can be interchangeably
+used. Each virtual register can only be mapped to physical registers of a
+particular class. For instance, in the X86 architecture, some virtuals can only
+be allocated to 8 bit registers. A register class is described by
+``TargetRegisterClass`` objects. To discover if a virtual register is
+compatible with a given physical, this code can be used:</p>
+
+.. code-block:: c++
+
+ bool RegMapping_Fer::compatible_class(MachineFunction &mf,
+ unsigned v_reg,
+ unsigned p_reg) {
+ assert(TargetRegisterInfo::isPhysicalRegister(p_reg) &&
+ "Target register must be physical");
+ const TargetRegisterClass *trc = mf.getRegInfo().getRegClass(v_reg);
+ return trc->contains(p_reg);
+ }
+
+Sometimes, mostly for debugging purposes, it is useful to change the number of
+physical registers available in the target architecture. This must be done
+statically, inside the ``TargetRegsterInfo.td`` file. Just ``grep`` for
+``RegisterClass``, the last parameter of which is a list of registers. Just
+commenting some out is one simple way to avoid them being used. A more polite
+way is to explicitly exclude some registers from the *allocation order*. See the
+definition of the ``GR8`` register class in
+``lib/Target/X86/X86RegisterInfo.td`` for an example of this.
+
+Virtual registers are also denoted by integer numbers. Contrary to physical
+registers, different virtual registers never share the same number. Whereas
+physical registers are statically defined in a ``TargetRegisterInfo.td`` file
+and cannot be created by the application developer, that is not the case with
+virtual registers. In order to create new virtual registers, use the method
+``MachineRegisterInfo::createVirtualRegister()``. This method will return a new
+virtual register. Use an ``IndexedMap<Foo, VirtReg2IndexFunctor>`` to hold
+information per virtual register. If you need to enumerate all virtual
+registers, use the function ``TargetRegisterInfo::index2VirtReg()`` to find the
+virtual register numbers:
+
+.. code-block:: c++
+
+ for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
+ unsigned VirtReg = TargetRegisterInfo::index2VirtReg(i);
+ stuff(VirtReg);
+ }
+
+Before register allocation, the operands of an instruction are mostly virtual
+registers, although physical registers may also be used. In order to check if a
+given machine operand is a register, use the boolean function
+``MachineOperand::isRegister()``. To obtain the integer code of a register, use
+``MachineOperand::getReg()``. An instruction may define or use a register. For
+instance, ``ADD reg:1026 := reg:1025 reg:1024`` defines the registers 1024, and
+uses registers 1025 and 1026. Given a register operand, the method
+``MachineOperand::isUse()`` informs if that register is being used by the
+instruction. The method ``MachineOperand::isDef()`` informs if that registers is
+being defined.
+
+We will call physical registers present in the LLVM bitcode before register
+allocation *pre-colored registers*. Pre-colored registers are used in many
+different situations, for instance, to pass parameters of functions calls, and
+to store results of particular instructions. There are two types of pre-colored
+registers: the ones *implicitly* defined, and those *explicitly*
+defined. Explicitly defined registers are normal operands, and can be accessed
+with ``MachineInstr::getOperand(int)::getReg()``. In order to check which
+registers are implicitly defined by an instruction, use the
+``TargetInstrInfo::get(opcode)::ImplicitDefs``, where ``opcode`` is the opcode
+of the target instruction. One important difference between explicit and
+implicit physical registers is that the latter are defined statically for each
+instruction, whereas the former may vary depending on the program being
+compiled. For example, an instruction that represents a function call will
+always implicitly define or use the same set of physical registers. To read the
+registers implicitly used by an instruction, use
+``TargetInstrInfo::get(opcode)::ImplicitUses``. Pre-colored registers impose
+constraints on any register allocation algorithm. The register allocator must
+make sure that none of them are overwritten by the values of virtual registers
+while still alive.
+
+Mapping virtual registers to physical registers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+There are two ways to map virtual registers to physical registers (or to memory
+slots). The first way, that we will call *direct mapping*, is based on the use
+of methods of the classes ``TargetRegisterInfo``, and ``MachineOperand``. The
+second way, that we will call *indirect mapping*, relies on the ``VirtRegMap``
+class in order to insert loads and stores sending and getting values to and from
+memory.
+
+The direct mapping provides more flexibility to the developer of the register
+allocator; however, it is more error prone, and demands more implementation
+work. Basically, the programmer will have to specify where load and store
+instructions should be inserted in the target function being compiled in order
+to get and store values in memory. To assign a physical register to a virtual
+register present in a given operand, use ``MachineOperand::setReg(p_reg)``. To
+insert a store instruction, use ``TargetInstrInfo::storeRegToStackSlot(...)``,
+and to insert a load instruction, use ``TargetInstrInfo::loadRegFromStackSlot``.
+
+The indirect mapping shields the application developer from the complexities of
+inserting load and store instructions. In order to map a virtual register to a
+physical one, use ``VirtRegMap::assignVirt2Phys(vreg, preg)``. In order to map
+a certain virtual register to memory, use
+``VirtRegMap::assignVirt2StackSlot(vreg)``. This method will return the stack
+slot where ``vreg``'s value will be located. If it is necessary to map another
+virtual register to the same stack slot, use
+``VirtRegMap::assignVirt2StackSlot(vreg, stack_location)``. One important point
+to consider when using the indirect mapping, is that even if a virtual register
+is mapped to memory, it still needs to be mapped to a physical register. This
+physical register is the location where the virtual register is supposed to be
+found before being stored or after being reloaded.
+
+If the indirect strategy is used, after all the virtual registers have been
+mapped to physical registers or stack slots, it is necessary to use a spiller
+object to place load and store instructions in the code. Every virtual that has
+been mapped to a stack slot will be stored to memory after been defined and will
+be loaded before being used. The implementation of the spiller tries to recycle
+load/store instructions, avoiding unnecessary instructions. For an example of
+how to invoke the spiller, see ``RegAllocLinearScan::runOnMachineFunction`` in
+``lib/CodeGen/RegAllocLinearScan.cpp``.
+
+Handling two address instructions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+With very rare exceptions (e.g., function calls), the LLVM machine code
+instructions are three address instructions. That is, each instruction is
+expected to define at most one register, and to use at most two registers.
+However, some architectures use two address instructions. In this case, the
+defined register is also one of the used register. For instance, an instruction
+such as ``ADD %EAX, %EBX``, in X86 is actually equivalent to ``%EAX = %EAX +
+%EBX``.
+
+In order to produce correct code, LLVM must convert three address instructions
+that represent two address instructions into true two address instructions. LLVM
+provides the pass ``TwoAddressInstructionPass`` for this specific purpose. It
+must be run before register allocation takes place. After its execution, the
+resulting code may no longer be in SSA form. This happens, for instance, in
+situations where an instruction such as ``%a = ADD %b %c`` is converted to two
+instructions such as:
+
+::
+
+ %a = MOVE %b
+ %a = ADD %a %c
+
+Notice that, internally, the second instruction is represented as ``ADD
+%a[def/use] %c``. I.e., the register operand ``%a`` is both used and defined by
+the instruction.
+
+The SSA deconstruction phase
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+An important transformation that happens during register allocation is called
+the *SSA Deconstruction Phase*. The SSA form simplifies many analyses that are
+performed on the control flow graph of programs. However, traditional
+instruction sets do not implement PHI instructions. Thus, in order to generate
+executable code, compilers must replace PHI instructions with other instructions
+that preserve their semantics.
+
+There are many ways in which PHI instructions can safely be removed from the
+target code. The most traditional PHI deconstruction algorithm replaces PHI
+instructions with copy instructions. That is the strategy adopted by LLVM. The
+SSA deconstruction algorithm is implemented in
+``lib/CodeGen/PHIElimination.cpp``. In order to invoke this pass, the identifier
+``PHIEliminationID`` must be marked as required in the code of the register
+allocator.
+
+Instruction folding
+^^^^^^^^^^^^^^^^^^^
+
+*Instruction folding* is an optimization performed during register allocation
+that removes unnecessary copy instructions. For instance, a sequence of
+instructions such as:
+
+::
+
+ %EBX = LOAD %mem_address
+ %EAX = COPY %EBX
+
+can be safely substituted by the single instruction:
+
+::
+
+ %EAX = LOAD %mem_address
+
+Instructions can be folded with the
+``TargetRegisterInfo::foldMemoryOperand(...)`` method. Care must be taken when
+folding instructions; a folded instruction can be quite different from the
+original instruction. See ``LiveIntervals::addIntervalsForSpills`` in
+``lib/CodeGen/LiveIntervalAnalysis.cpp`` for an example of its use.
+
+Built in register allocators
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The LLVM infrastructure provides the application developer with three different
+register allocators:
+
+* *Fast* --- This register allocator is the default for debug builds. It
+ allocates registers on a basic block level, attempting to keep values in
+ registers and reusing registers as appropriate.
+
+* *Basic* --- This is an incremental approach to register allocation. Live
+ ranges are assigned to registers one at a time in an order that is driven by
+ heuristics. Since code can be rewritten on-the-fly during allocation, this
+ framework allows interesting allocators to be developed as extensions. It is
+ not itself a production register allocator but is a potentially useful
+ stand-alone mode for triaging bugs and as a performance baseline.
+
+* *Greedy* --- *The default allocator*. This is a highly tuned implementation of
+ the *Basic* allocator that incorporates global live range splitting. This
+ allocator works hard to minimize the cost of spill code.
+
+* *PBQP* --- A Partitioned Boolean Quadratic Programming (PBQP) based register
+ allocator. This allocator works by constructing a PBQP problem representing
+ the register allocation problem under consideration, solving this using a PBQP
+ solver, and mapping the solution back to a register assignment.
+
+The type of register allocator used in ``llc`` can be chosen with the command
+line option ``-regalloc=...``:
+
+.. code-block:: bash
+
+ $ llc -regalloc=linearscan file.bc -o ln.s
+ $ llc -regalloc=fast file.bc -o fa.s
+ $ llc -regalloc=pbqp file.bc -o pbqp.s
+
+.. _Prolog/Epilog Code Insertion:
+
+Prolog/Epilog Code Insertion
+----------------------------
+
+Compact Unwind
+
+Throwing an exception requires *unwinding* out of a function. The information on
+how to unwind a given function is traditionally expressed in DWARF unwind
+(a.k.a. frame) info. But that format was originally developed for debuggers to
+backtrace, and each Frame Description Entry (FDE) requires ~20-30 bytes per
+function. There is also the cost of mapping from an address in a function to the
+corresponding FDE at runtime. An alternative unwind encoding is called *compact
+unwind* and requires just 4-bytes per function.
+
+The compact unwind encoding is a 32-bit value, which is encoded in an
+architecture-specific way. It specifies which registers to restore and from
+where, and how to unwind out of the function. When the linker creates a final
+linked image, it will create a ``__TEXT,__unwind_info`` section. This section is
+a small and fast way for the runtime to access unwind info for any given
+function. If we emit compact unwind info for the function, that compact unwind
+info will be encoded in the ``__TEXT,__unwind_info`` section. If we emit DWARF
+unwind info, the ``__TEXT,__unwind_info`` section will contain the offset of the
+FDE in the ``__TEXT,__eh_frame`` section in the final linked image.
+
+For X86, there are three modes for the compact unwind encoding:
+
+*Function with a Frame Pointer (``EBP`` or ``RBP``)*
+ ``EBP/RBP``-based frame, where ``EBP/RBP`` is pushed onto the stack
+ immediately after the return address, then ``ESP/RSP`` is moved to
+ ``EBP/RBP``. Thus to unwind, ``ESP/RSP`` is restored with the current
+ ``EBP/RBP`` value, then ``EBP/RBP`` is restored by popping the stack, and the
+ return is done by popping the stack once more into the PC. All non-volatile
+ registers that need to be restored must have been saved in a small range on
+ the stack that starts ``EBP-4`` to ``EBP-1020`` (``RBP-8`` to
+ ``RBP-1020``). The offset (divided by 4 in 32-bit mode and 8 in 64-bit mode)
+ is encoded in bits 16-23 (mask: ``0x00FF0000``). The registers saved are
+ encoded in bits 0-14 (mask: ``0x00007FFF``) as five 3-bit entries from the
+ following table:
+
+ ============== ============= ===============
+ Compact Number i386 Register x86-64 Register
+ ============== ============= ===============
+ 1 ``EBX`` ``RBX``
+ 2 ``ECX`` ``R12``
+ 3 ``EDX`` ``R13``
+ 4 ``EDI`` ``R14``
+ 5 ``ESI`` ``R15``
+ 6 ``EBP`` ``RBP``
+ ============== ============= ===============
+
+*Frameless with a Small Constant Stack Size (``EBP`` or ``RBP`` is not used as a frame pointer)*
+ To return, a constant (encoded in the compact unwind encoding) is added to the
+ ``ESP/RSP``. Then the return is done by popping the stack into the PC. All
+ non-volatile registers that need to be restored must have been saved on the
+ stack immediately after the return address. The stack size (divided by 4 in
+ 32-bit mode and 8 in 64-bit mode) is encoded in bits 16-23 (mask:
+ ``0x00FF0000``). There is a maximum stack size of 1024 bytes in 32-bit mode
+ and 2048 in 64-bit mode. The number of registers saved is encoded in bits 9-12
+ (mask: ``0x00001C00``). Bits 0-9 (mask: ``0x000003FF``) contain which
+ registers were saved and their order. (See the
+ ``encodeCompactUnwindRegistersWithoutFrame()`` function in
+ ``lib/Target/X86FrameLowering.cpp`` for the encoding algorithm.)
+
+*Frameless with a Large Constant Stack Size (``EBP`` or ``RBP`` is not used as a frame pointer)*
+ This case is like the "Frameless with a Small Constant Stack Size" case, but
+ the stack size is too large to encode in the compact unwind encoding. Instead
+ it requires that the function contains "``subl $nnnnnn, %esp``" in its
+ prolog. The compact encoding contains the offset to the ``$nnnnnn`` value in
+ the function in bits 9-12 (mask: ``0x00001C00``).
+
+.. _Late Machine Code Optimizations:
+
+Late Machine Code Optimizations
+-------------------------------
+
+.. note::
+
+ To Be Written
+
+.. _Code Emission:
+
+Code Emission
+-------------
+
+The code emission step of code generation is responsible for lowering from the
+code generator abstractions (like `MachineFunction`_, `MachineInstr`_, etc) down
+to the abstractions used by the MC layer (`MCInst`_, `MCStreamer`_, etc). This
+is done with a combination of several different classes: the (misnamed)
+target-independent AsmPrinter class, target-specific subclasses of AsmPrinter
+(such as SparcAsmPrinter), and the TargetLoweringObjectFile class.
+
+Since the MC layer works at the level of abstraction of object files, it doesn't
+have a notion of functions, global variables etc. Instead, it thinks about
+labels, directives, and instructions. A key class used at this time is the
+MCStreamer class. This is an abstract API that is implemented in different ways
+(e.g. to output a .s file, output an ELF .o file, etc) that is effectively an
+"assembler API". MCStreamer has one method per directive, such as EmitLabel,
+EmitSymbolAttribute, SwitchSection, etc, which directly correspond to assembly
+level directives.
+
+If you are interested in implementing a code generator for a target, there are
+three important things that you have to implement for your target:
+
+#. First, you need a subclass of AsmPrinter for your target. This class
+ implements the general lowering process converting MachineFunction's into MC
+ label constructs. The AsmPrinter base class provides a number of useful
+ methods and routines, and also allows you to override the lowering process in
+ some important ways. You should get much of the lowering for free if you are
+ implementing an ELF, COFF, or MachO target, because the
+ TargetLoweringObjectFile class implements much of the common logic.
+
+#. Second, you need to implement an instruction printer for your target. The
+ instruction printer takes an `MCInst`_ and renders it to a raw_ostream as
+ text. Most of this is automatically generated from the .td file (when you
+ specify something like "``add $dst, $src1, $src2``" in the instructions), but
+ you need to implement routines to print operands.
+
+#. Third, you need to implement code that lowers a `MachineInstr`_ to an MCInst,
+ usually implemented in "<target>MCInstLower.cpp". This lowering process is
+ often target specific, and is responsible for turning jump table entries,
+ constant pool indices, global variable addresses, etc into MCLabels as
+ appropriate. This translation layer is also responsible for expanding pseudo
+ ops used by the code generator into the actual machine instructions they
+ correspond to. The MCInsts that are generated by this are fed into the
+ instruction printer or the encoder.
+
+Finally, at your choosing, you can also implement an subclass of MCCodeEmitter
+which lowers MCInst's into machine code bytes and relocations. This is
+important if you want to support direct .o file emission, or would like to
+implement an assembler for your target.
+
+VLIW Packetizer
+---------------
+
+In a Very Long Instruction Word (VLIW) architecture, the compiler is responsible
+for mapping instructions to functional-units available on the architecture. To
+that end, the compiler creates groups of instructions called *packets* or
+*bundles*. The VLIW packetizer in LLVM is a target-independent mechanism to
+enable the packetization of machine instructions.
+
+Mapping from instructions to functional units
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Instructions in a VLIW target can typically be mapped to multiple functional
+units. During the process of packetizing, the compiler must be able to reason
+about whether an instruction can be added to a packet. This decision can be
+complex since the compiler has to examine all possible mappings of instructions
+to functional units. Therefore to alleviate compilation-time complexity, the
+VLIW packetizer parses the instruction classes of a target and generates tables
+at compiler build time. These tables can then be queried by the provided
+machine-independent API to determine if an instruction can be accommodated in a
+packet.
+
+How the packetization tables are generated and used
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The packetizer reads instruction classes from a target's itineraries and creates
+a deterministic finite automaton (DFA) to represent the state of a packet. A DFA
+consists of three major elements: inputs, states, and transitions. The set of
+inputs for the generated DFA represents the instruction being added to a
+packet. The states represent the possible consumption of functional units by
+instructions in a packet. In the DFA, transitions from one state to another
+occur on the addition of an instruction to an existing packet. If there is a
+legal mapping of functional units to instructions, then the DFA contains a
+corresponding transition. The absence of a transition indicates that a legal
+mapping does not exist and that the instruction cannot be added to the packet.
+
+To generate tables for a VLIW target, add *Target*\ GenDFAPacketizer.inc as a
+target to the Makefile in the target directory. The exported API provides three
+functions: ``DFAPacketizer::clearResources()``,
+``DFAPacketizer::reserveResources(MachineInstr *MI)``, and
+``DFAPacketizer::canReserveResources(MachineInstr *MI)``. These functions allow
+a target packetizer to add an instruction to an existing packet and to check
+whether an instruction can be added to a packet. See
+``llvm/CodeGen/DFAPacketizer.h`` for more information.
+
+Implementing a Native Assembler
+===============================
+
+Though you're probably reading this because you want to write or maintain a
+compiler backend, LLVM also fully supports building a native assemblers too.
+We've tried hard to automate the generation of the assembler from the .td files
+(in particular the instruction syntax and encodings), which means that a large
+part of the manual and repetitive data entry can be factored and shared with the
+compiler.
+
+Instruction Parsing
+-------------------
+
+.. note::
+
+ To Be Written
+
+
+Instruction Alias Processing
+----------------------------
+
+Once the instruction is parsed, it enters the MatchInstructionImpl function.
+The MatchInstructionImpl function performs alias processing and then does actual
+matching.
+
+Alias processing is the phase that canonicalizes different lexical forms of the
+same instructions down to one representation. There are several different kinds
+of alias that are possible to implement and they are listed below in the order
+that they are processed (which is in order from simplest/weakest to most
+complex/powerful). Generally you want to use the first alias mechanism that
+meets the needs of your instruction, because it will allow a more concise
+description.
+
+Mnemonic Aliases
+^^^^^^^^^^^^^^^^
+
+The first phase of alias processing is simple instruction mnemonic remapping for
+classes of instructions which are allowed with two different mnemonics. This
+phase is a simple and unconditionally remapping from one input mnemonic to one
+output mnemonic. It isn't possible for this form of alias to look at the
+operands at all, so the remapping must apply for all forms of a given mnemonic.
+Mnemonic aliases are defined simply, for example X86 has:
+
+::
+
+ def : MnemonicAlias<"cbw", "cbtw">;
+ def : MnemonicAlias<"smovq", "movsq">;
+ def : MnemonicAlias<"fldcww", "fldcw">;
+ def : MnemonicAlias<"fucompi", "fucomip">;
+ def : MnemonicAlias<"ud2a", "ud2">;
+
+... and many others. With a MnemonicAlias definition, the mnemonic is remapped
+simply and directly. Though MnemonicAlias's can't look at any aspect of the
+instruction (such as the operands) they can depend on global modes (the same
+ones supported by the matcher), through a Requires clause:
+
+::
+
+ def : MnemonicAlias<"pushf", "pushfq">, Requires<[In64BitMode]>;
+ def : MnemonicAlias<"pushf", "pushfl">, Requires<[In32BitMode]>;
+
+In this example, the mnemonic gets mapped into different a new one depending on
+the current instruction set.
+
+Instruction Aliases
+^^^^^^^^^^^^^^^^^^^
+
+The most general phase of alias processing occurs while matching is happening:
+it provides new forms for the matcher to match along with a specific instruction
+to generate. An instruction alias has two parts: the string to match and the
+instruction to generate. For example:
+
+::
+
+ def : InstAlias<"movsx $src, $dst", (MOVSX16rr8W GR16:$dst, GR8 :$src)>;
+ def : InstAlias<"movsx $src, $dst", (MOVSX16rm8W GR16:$dst, i8mem:$src)>;
+ def : InstAlias<"movsx $src, $dst", (MOVSX32rr8 GR32:$dst, GR8 :$src)>;
+ def : InstAlias<"movsx $src, $dst", (MOVSX32rr16 GR32:$dst, GR16 :$src)>;
+ def : InstAlias<"movsx $src, $dst", (MOVSX64rr8 GR64:$dst, GR8 :$src)>;
+ def : InstAlias<"movsx $src, $dst", (MOVSX64rr16 GR64:$dst, GR16 :$src)>;
+ def : InstAlias<"movsx $src, $dst", (MOVSX64rr32 GR64:$dst, GR32 :$src)>;
+
+This shows a powerful example of the instruction aliases, matching the same
+mnemonic in multiple different ways depending on what operands are present in
+the assembly. The result of instruction aliases can include operands in a
+different order than the destination instruction, and can use an input multiple
+times, for example:
+
+::
+
+ def : InstAlias<"clrb $reg", (XOR8rr GR8 :$reg, GR8 :$reg)>;
+ def : InstAlias<"clrw $reg", (XOR16rr GR16:$reg, GR16:$reg)>;
+ def : InstAlias<"clrl $reg", (XOR32rr GR32:$reg, GR32:$reg)>;
+ def : InstAlias<"clrq $reg", (XOR64rr GR64:$reg, GR64:$reg)>;
+
+This example also shows that tied operands are only listed once. In the X86
+backend, XOR8rr has two input GR8's and one output GR8 (where an input is tied
+to the output). InstAliases take a flattened operand list without duplicates
+for tied operands. The result of an instruction alias can also use immediates
+and fixed physical registers which are added as simple immediate operands in the
+result, for example:
+
+::
+
+ // Fixed Immediate operand.
+ def : InstAlias<"aad", (AAD8i8 10)>;
+
+ // Fixed register operand.
+ def : InstAlias<"fcomi", (COM_FIr ST1)>;
+
+ // Simple alias.
+ def : InstAlias<"fcomi $reg", (COM_FIr RST:$reg)>;
+
+Instruction aliases can also have a Requires clause to make them subtarget
+specific.
+
+If the back-end supports it, the instruction printer can automatically emit the
+alias rather than what's being aliased. It typically leads to better, more
+readable code. If it's better to print out what's being aliased, then pass a '0'
+as the third parameter to the InstAlias definition.
+
+Instruction Matching
+--------------------
+
+.. note::
+
+ To Be Written
+
+.. _Implementations of the abstract target description interfaces:
+.. _implement the target description:
+
+Target-specific Implementation Notes
+====================================
+
+This section of the document explains features or design decisions that are
+specific to the code generator for a particular target. First we start with a
+table that summarizes what features are supported by each target.
+
+Target Feature Matrix
+---------------------
+
+Note that this table does not include the C backend or Cpp backends, since they
+do not use the target independent code generator infrastructure. It also
+doesn't list features that are not supported fully by any target yet. It
+considers a feature to be supported if at least one subtarget supports it. A
+feature being supported means that it is useful and works for most cases, it
+does not indicate that there are zero known bugs in the implementation. Here is
+the key:
+
+:raw-html:`<table border="1" cellspacing="0">`
+:raw-html:`<tr>`
+:raw-html:`<th>Unknown</th>`
+:raw-html:`<th>No support</th>`
+:raw-html:`<th>Partial Support</th>`
+:raw-html:`<th>Complete Support</th>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td class="unknown"></td>`
+:raw-html:`<td class="no"></td>`
+:raw-html:`<td class="partial"></td>`
+:raw-html:`<td class="yes"></td>`
+:raw-html:`</tr>`
+:raw-html:`</table>`
+
+Here is the table:
+
+:raw-html:`<table width="689" border="1" cellspacing="0">`
+:raw-html:`<tr><td></td>`
+:raw-html:`<td colspan="13" align="center" style="background-color:#ffc">Target</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<th>Feature</th>`
+:raw-html:`<th>ARM</th>`
+:raw-html:`<th>CellSPU</th>`
+:raw-html:`<th>Hexagon</th>`
+:raw-html:`<th>MBlaze</th>`
+:raw-html:`<th>MSP430</th>`
+:raw-html:`<th>Mips</th>`
+:raw-html:`<th>PTX</th>`
+:raw-html:`<th>PowerPC</th>`
+:raw-html:`<th>Sparc</th>`
+:raw-html:`<th>X86</th>`
+:raw-html:`<th>XCore</th>`
+:raw-html:`</tr>`
+
+:raw-html:`<tr>`
+:raw-html:`<td><a href="#feat_reliable">is generally reliable</a></td>`
+:raw-html:`<td class="yes"></td> <!-- ARM -->`
+:raw-html:`<td class="no"></td> <!-- CellSPU -->`
+:raw-html:`<td class="yes"></td> <!-- Hexagon -->`
+:raw-html:`<td class="no"></td> <!-- MBlaze -->`
+:raw-html:`<td class="unknown"></td> <!-- MSP430 -->`
+:raw-html:`<td class="yes"></td> <!-- Mips -->`
+:raw-html:`<td class="no"></td> <!-- PTX -->`
+:raw-html:`<td class="yes"></td> <!-- PowerPC -->`
+:raw-html:`<td class="yes"></td> <!-- Sparc -->`
+:raw-html:`<td class="yes"></td> <!-- X86 -->`
+:raw-html:`<td class="unknown"></td> <!-- XCore -->`
+:raw-html:`</tr>`
+
+:raw-html:`<tr>`
+:raw-html:`<td><a href="#feat_asmparser">assembly parser</a></td>`
+:raw-html:`<td class="no"></td> <!-- ARM -->`
+:raw-html:`<td class="no"></td> <!-- CellSPU -->`
+:raw-html:`<td class="no"></td> <!-- Hexagon -->`
+:raw-html:`<td class="yes"></td> <!-- MBlaze -->`
+:raw-html:`<td class="no"></td> <!-- MSP430 -->`
+:raw-html:`<td class="no"></td> <!-- Mips -->`
+:raw-html:`<td class="no"></td> <!-- PTX -->`
+:raw-html:`<td class="no"></td> <!-- PowerPC -->`
+:raw-html:`<td class="no"></td> <!-- Sparc -->`
+:raw-html:`<td class="yes"></td> <!-- X86 -->`
+:raw-html:`<td class="no"></td> <!-- XCore -->`
+:raw-html:`</tr>`
+
+:raw-html:`<tr>`
+:raw-html:`<td><a href="#feat_disassembler">disassembler</a></td>`
+:raw-html:`<td class="yes"></td> <!-- ARM -->`
+:raw-html:`<td class="no"></td> <!-- CellSPU -->`
+:raw-html:`<td class="no"></td> <!-- Hexagon -->`
+:raw-html:`<td class="yes"></td> <!-- MBlaze -->`
+:raw-html:`<td class="no"></td> <!-- MSP430 -->`
+:raw-html:`<td class="no"></td> <!-- Mips -->`
+:raw-html:`<td class="no"></td> <!-- PTX -->`
+:raw-html:`<td class="no"></td> <!-- PowerPC -->`
+:raw-html:`<td class="no"></td> <!-- Sparc -->`
+:raw-html:`<td class="yes"></td> <!-- X86 -->`
+:raw-html:`<td class="no"></td> <!-- XCore -->`
+:raw-html:`</tr>`
+
+:raw-html:`<tr>`
+:raw-html:`<td><a href="#feat_inlineasm">inline asm</a></td>`
+:raw-html:`<td class="yes"></td> <!-- ARM -->`
+:raw-html:`<td class="no"></td> <!-- CellSPU -->`
+:raw-html:`<td class="yes"></td> <!-- Hexagon -->`
+:raw-html:`<td class="yes"></td> <!-- MBlaze -->`
+:raw-html:`<td class="unknown"></td> <!-- MSP430 -->`
+:raw-html:`<td class="no"></td> <!-- Mips -->`
+:raw-html:`<td class="unknown"></td> <!-- PTX -->`
+:raw-html:`<td class="yes"></td> <!-- PowerPC -->`
+:raw-html:`<td class="unknown"></td> <!-- Sparc -->`
+:raw-html:`<td class="yes"></td> <!-- X86 -->`
+:raw-html:`<td class="unknown"></td> <!-- XCore -->`
+:raw-html:`</tr>`
+
+:raw-html:`<tr>`
+:raw-html:`<td><a href="#feat_jit">jit</a></td>`
+:raw-html:`<td class="partial"><a href="#feat_jit_arm">*</a></td> <!-- ARM -->`
+:raw-html:`<td class="no"></td> <!-- CellSPU -->`
+:raw-html:`<td class="no"></td> <!-- Hexagon -->`
+:raw-html:`<td class="no"></td> <!-- MBlaze -->`
+:raw-html:`<td class="unknown"></td> <!-- MSP430 -->`
+:raw-html:`<td class="yes"></td> <!-- Mips -->`
+:raw-html:`<td class="unknown"></td> <!-- PTX -->`
+:raw-html:`<td class="yes"></td> <!-- PowerPC -->`
+:raw-html:`<td class="unknown"></td> <!-- Sparc -->`
+:raw-html:`<td class="yes"></td> <!-- X86 -->`
+:raw-html:`<td class="unknown"></td> <!-- XCore -->`
+:raw-html:`</tr>`
+
+:raw-html:`<tr>`
+:raw-html:`<td><a href="#feat_objectwrite">.o&nbsp;file writing</a></td>`
+:raw-html:`<td class="no"></td> <!-- ARM -->`
+:raw-html:`<td class="no"></td> <!-- CellSPU -->`
+:raw-html:`<td class="no"></td> <!-- Hexagon -->`
+:raw-html:`<td class="yes"></td> <!-- MBlaze -->`
+:raw-html:`<td class="no"></td> <!-- MSP430 -->`
+:raw-html:`<td class="no"></td> <!-- Mips -->`
+:raw-html:`<td class="no"></td> <!-- PTX -->`
+:raw-html:`<td class="no"></td> <!-- PowerPC -->`
+:raw-html:`<td class="no"></td> <!-- Sparc -->`
+:raw-html:`<td class="yes"></td> <!-- X86 -->`
+:raw-html:`<td class="no"></td> <!-- XCore -->`
+:raw-html:`</tr>`
+
+:raw-html:`<tr>`
+:raw-html:`<td><a hr:raw-html:`ef="#feat_tailcall">tail calls</a></td>`
+:raw-html:`<td class="yes"></td> <!-- ARM -->`
+:raw-html:`<td class="no"></td> <!-- CellSPU -->`
+:raw-html:`<td class="yes"></td> <!-- Hexagon -->`
+:raw-html:`<td class="no"></td> <!-- MBlaze -->`
+:raw-html:`<td class="unknown"></td> <!-- MSP430 -->`
+:raw-html:`<td class="no"></td> <!-- Mips -->`
+:raw-html:`<td class="unknown"></td> <!-- PTX -->`
+:raw-html:`<td class="yes"></td> <!-- PowerPC -->`
+:raw-html:`<td class="unknown"></td> <!-- Sparc -->`
+:raw-html:`<td class="yes"></td> <!-- X86 -->`
+:raw-html:`<td class="unknown"></td> <!-- XCore -->`
+:raw-html:`</tr>`
+
+:raw-html:`<tr>`
+:raw-html:`<td><a href="#feat_segstacks">segmented stacks</a></td>`
+:raw-html:`<td class="no"></td> <!-- ARM -->`
+:raw-html:`<td class="no"></td> <!-- CellSPU -->`
+:raw-html:`<td class="no"></td> <!-- Hexagon -->`
+:raw-html:`<td class="no"></td> <!-- MBlaze -->`
+:raw-html:`<td class="no"></td> <!-- MSP430 -->`
+:raw-html:`<td class="no"></td> <!-- Mips -->`
+:raw-html:`<td class="no"></td> <!-- PTX -->`
+:raw-html:`<td class="no"></td> <!-- PowerPC -->`
+:raw-html:`<td class="no"></td> <!-- Sparc -->`
+:raw-html:`<td class="partial"><a href="#feat_segstacks_x86">*</a></td> <!-- X86 -->`
+:raw-html:`<td class="no"></td> <!-- XCore -->`
+:raw-html:`</tr>`
+
+:raw-html:`</table>`
+
+.. _feat_reliable:
+
+Is Generally Reliable
+^^^^^^^^^^^^^^^^^^^^^
+
+This box indicates whether the target is considered to be production quality.
+This indicates that the target has been used as a static compiler to compile
+large amounts of code by a variety of different people and is in continuous use.
+
+.. _feat_asmparser:
+
+Assembly Parser
+^^^^^^^^^^^^^^^
+
+This box indicates whether the target supports parsing target specific .s files
+by implementing the MCAsmParser interface. This is required for llvm-mc to be
+able to act as a native assembler and is required for inline assembly support in
+the native .o file writer.
+
+.. _feat_disassembler:
+
+Disassembler
+^^^^^^^^^^^^
+
+This box indicates whether the target supports the MCDisassembler API for
+disassembling machine opcode bytes into MCInst's.
+
+.. _feat_inlineasm:
+
+Inline Asm
+^^^^^^^^^^
+
+This box indicates whether the target supports most popular inline assembly
+constraints and modifiers.
+
+.. _feat_jit:
+
+JIT Support
+^^^^^^^^^^^
+
+This box indicates whether the target supports the JIT compiler through the
+ExecutionEngine interface.
+
+.. _feat_jit_arm:
+
+The ARM backend has basic support for integer code in ARM codegen mode, but
+lacks NEON and full Thumb support.
+
+.. _feat_objectwrite:
+
+.o File Writing
+^^^^^^^^^^^^^^^
+
+This box indicates whether the target supports writing .o files (e.g. MachO,
+ELF, and/or COFF) files directly from the target. Note that the target also
+must include an assembly parser and general inline assembly support for full
+inline assembly support in the .o writer.
+
+Targets that don't support this feature can obviously still write out .o files,
+they just rely on having an external assembler to translate from a .s file to a
+.o file (as is the case for many C compilers).
+
+.. _feat_tailcall:
+
+Tail Calls
+^^^^^^^^^^
+
+This box indicates whether the target supports guaranteed tail calls. These are
+calls marked "`tail <LangRef.html#i_call>`_" and use the fastcc calling
+convention. Please see the `tail call section more more details`_.
+
+.. _feat_segstacks:
+
+Segmented Stacks
+^^^^^^^^^^^^^^^^
+
+This box indicates whether the target supports segmented stacks. This replaces
+the traditional large C stack with many linked segments. It is compatible with
+the `gcc implementation <http://gcc.gnu.org/wiki/SplitStacks>`_ used by the Go
+front end.
+
+.. _feat_segstacks_x86:
+
+Basic support exists on the X86 backend. Currently vararg doesn't work and the
+object files are not marked the way the gold linker expects, but simple Go
+programs can be built by dragonegg.
+
+.. _tail call section more more details:
+
+Tail call optimization
+----------------------
+
+Tail call optimization, callee reusing the stack of the caller, is currently
+supported on x86/x86-64 and PowerPC. It is performed if:
+
+* Caller and callee have the calling convention ``fastcc`` or ``cc 10`` (GHC
+ call convention).
+
+* The call is a tail call - in tail position (ret immediately follows call and
+ ret uses value of call or is void).
+
+* Option ``-tailcallopt`` is enabled.
+
+* Platform specific constraints are met.
+
+x86/x86-64 constraints:
+
+* No variable argument lists are used.
+
+* On x86-64 when generating GOT/PIC code only module-local calls (visibility =
+ hidden or protected) are supported.
+
+PowerPC constraints:
+
+* No variable argument lists are used.
+
+* No byval parameters are used.
+
+* On ppc32/64 GOT/PIC only module-local calls (visibility = hidden or protected)
+ are supported.
+
+Example:
+
+Call as ``llc -tailcallopt test.ll``.
+
+.. code-block:: llvm
+
+ declare fastcc i32 @tailcallee(i32 inreg %a1, i32 inreg %a2, i32 %a3, i32 %a4)
+
+ define fastcc i32 @tailcaller(i32 %in1, i32 %in2) {
+ %l1 = add i32 %in1, %in2
+ %tmp = tail call fastcc i32 @tailcallee(i32 %in1 inreg, i32 %in2 inreg, i32 %in1, i32 %l1)
+ ret i32 %tmp
+ }
+
+Implications of ``-tailcallopt``:
+
+To support tail call optimization in situations where the callee has more
+arguments than the caller a 'callee pops arguments' convention is used. This
+currently causes each ``fastcc`` call that is not tail call optimized (because
+one or more of above constraints are not met) to be followed by a readjustment
+of the stack. So performance might be worse in such cases.
+
+Sibling call optimization
+-------------------------
+
+Sibling call optimization is a restricted form of tail call optimization.
+Unlike tail call optimization described in the previous section, it can be
+performed automatically on any tail calls when ``-tailcallopt`` option is not
+specified.
+
+Sibling call optimization is currently performed on x86/x86-64 when the
+following constraints are met:
+
+* Caller and callee have the same calling convention. It can be either ``c`` or
+ ``fastcc``.
+
+* The call is a tail call - in tail position (ret immediately follows call and
+ ret uses value of call or is void).
+
+* Caller and callee have matching return type or the callee result is not used.
+
+* If any of the callee arguments are being passed in stack, they must be
+ available in caller's own incoming argument stack and the frame offsets must
+ be the same.
+
+Example:
+
+.. code-block:: llvm
+
+ declare i32 @bar(i32, i32)
+
+ define i32 @foo(i32 %a, i32 %b, i32 %c) {
+ entry:
+ %0 = tail call i32 @bar(i32 %a, i32 %b)
+ ret i32 %0
+ }
+
+The X86 backend
+---------------
+
+The X86 code generator lives in the ``lib/Target/X86`` directory. This code
+generator is capable of targeting a variety of x86-32 and x86-64 processors, and
+includes support for ISA extensions such as MMX and SSE.
+
+X86 Target Triples supported
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following are the known target triples that are supported by the X86
+backend. This is not an exhaustive list, and it would be useful to add those
+that people test.
+
+* **i686-pc-linux-gnu** --- Linux
+
+* **i386-unknown-freebsd5.3** --- FreeBSD 5.3
+
+* **i686-pc-cygwin** --- Cygwin on Win32
+
+* **i686-pc-mingw32** --- MingW on Win32
+
+* **i386-pc-mingw32msvc** --- MingW crosscompiler on Linux
+
+* **i686-apple-darwin*** --- Apple Darwin on X86
+
+* **x86_64-unknown-linux-gnu** --- Linux
+
+X86 Calling Conventions supported
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following target-specific calling conventions are known to backend:
+
+* **x86_StdCall** --- stdcall calling convention seen on Microsoft Windows
+ platform (CC ID = 64).
+
+* **x86_FastCall** --- fastcall calling convention seen on Microsoft Windows
+ platform (CC ID = 65).
+
+* **x86_ThisCall** --- Similar to X86_StdCall. Passes first argument in ECX,
+ others via stack. Callee is responsible for stack cleaning. This convention is
+ used by MSVC by default for methods in its ABI (CC ID = 70).
+
+.. _X86 addressing mode:
+
+Representing X86 addressing modes in MachineInstrs
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The x86 has a very flexible way of accessing memory. It is capable of forming
+memory addresses of the following expression directly in integer instructions
+(which use ModR/M addressing):
+
+::
+
+ SegmentReg: Base + [1,2,4,8] * IndexReg + Disp32
+
+In order to represent this, LLVM tracks no less than 5 operands for each memory
+operand of this form. This means that the "load" form of '``mov``' has the
+following ``MachineOperand``\s in this order:
+
+::
+
+ Index: 0 | 1 2 3 4 5
+ Meaning: DestReg, | BaseReg, Scale, IndexReg, Displacement Segment
+ OperandTy: VirtReg, | VirtReg, UnsImm, VirtReg, SignExtImm PhysReg
+
+Stores, and all other instructions, treat the four memory operands in the same
+way and in the same order. If the segment register is unspecified (regno = 0),
+then no segment override is generated. "Lea" operations do not have a segment
+register specified, so they only have 4 operands for their memory reference.
+
+X86 address spaces supported
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+x86 has a feature which provides the ability to perform loads and stores to
+different address spaces via the x86 segment registers. A segment override
+prefix byte on an instruction causes the instruction's memory access to go to
+the specified segment. LLVM address space 0 is the default address space, which
+includes the stack, and any unqualified memory accesses in a program. Address
+spaces 1-255 are currently reserved for user-defined code. The GS-segment is
+represented by address space 256, while the FS-segment is represented by address
+space 257. Other x86 segments have yet to be allocated address space
+numbers.
+
+While these address spaces may seem similar to TLS via the ``thread_local``
+keyword, and often use the same underlying hardware, there are some fundamental
+differences.
+
+The ``thread_local`` keyword applies to global variables and specifies that they
+are to be allocated in thread-local memory. There are no type qualifiers
+involved, and these variables can be pointed to with normal pointers and
+accessed with normal loads and stores. The ``thread_local`` keyword is
+target-independent at the LLVM IR level (though LLVM doesn't yet have
+implementations of it for some configurations)
+
+Special address spaces, in contrast, apply to static types. Every load and store
+has a particular address space in its address operand type, and this is what
+determines which address space is accessed. LLVM ignores these special address
+space qualifiers on global variables, and does not provide a way to directly
+allocate storage in them. At the LLVM IR level, the behavior of these special
+address spaces depends in part on the underlying OS or runtime environment, and
+they are specific to x86 (and LLVM doesn't yet handle them correctly in some
+cases).
+
+Some operating systems and runtime environments use (or may in the future use)
+the FS/GS-segment registers for various low-level purposes, so care should be
+taken when considering them.
+
+Instruction naming
+^^^^^^^^^^^^^^^^^^
+
+An instruction name consists of the base name, a default operand size, and a a
+character per operand with an optional special size. For example:
+
+::
+
+ ADD8rr -> add, 8-bit register, 8-bit register
+ IMUL16rmi -> imul, 16-bit register, 16-bit memory, 16-bit immediate
+ IMUL16rmi8 -> imul, 16-bit register, 16-bit memory, 8-bit immediate
+ MOVSX32rm16 -> movsx, 32-bit register, 16-bit memory
+
+The PowerPC backend
+-------------------
+
+The PowerPC code generator lives in the lib/Target/PowerPC directory. The code
+generation is retargetable to several variations or *subtargets* of the PowerPC
+ISA; including ppc32, ppc64 and altivec.
+
+LLVM PowerPC ABI
+^^^^^^^^^^^^^^^^
+
+LLVM follows the AIX PowerPC ABI, with two deviations. LLVM uses a PC relative
+(PIC) or static addressing for accessing global values, so no TOC (r2) is
+used. Second, r31 is used as a frame pointer to allow dynamic growth of a stack
+frame. LLVM takes advantage of having no TOC to provide space to save the frame
+pointer in the PowerPC linkage area of the caller frame. Other details of
+PowerPC ABI can be found at `PowerPC ABI
+<http://developer.apple.com/documentation/DeveloperTools/Conceptual/LowLevelABI/Articles/32bitPowerPC.html>`_\
+. Note: This link describes the 32 bit ABI. The 64 bit ABI is similar except
+space for GPRs are 8 bytes wide (not 4) and r13 is reserved for system use.
+
+Frame Layout
+^^^^^^^^^^^^
+
+The size of a PowerPC frame is usually fixed for the duration of a function's
+invocation. Since the frame is fixed size, all references into the frame can be
+accessed via fixed offsets from the stack pointer. The exception to this is
+when dynamic alloca or variable sized arrays are present, then a base pointer
+(r31) is used as a proxy for the stack pointer and stack pointer is free to grow
+or shrink. A base pointer is also used if llvm-gcc is not passed the
+-fomit-frame-pointer flag. The stack pointer is always aligned to 16 bytes, so
+that space allocated for altivec vectors will be properly aligned.
+
+An invocation frame is laid out as follows (low memory at top):
+
+:raw-html:`<table border="1" cellspacing="0">`
+:raw-html:`<tr>`
+:raw-html:`<td>Linkage<br><br></td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>Parameter area<br><br></td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>Dynamic area<br><br></td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>Locals area<br><br></td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>Saved registers area<br><br></td>`
+:raw-html:`</tr>`
+:raw-html:`<tr style="border-style: none hidden none hidden;">`
+:raw-html:`<td><br></td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>Previous Frame<br><br></td>`
+:raw-html:`</tr>`
+:raw-html:`</table>`
+
+The *linkage* area is used by a callee to save special registers prior to
+allocating its own frame. Only three entries are relevant to LLVM. The first
+entry is the previous stack pointer (sp), aka link. This allows probing tools
+like gdb or exception handlers to quickly scan the frames in the stack. A
+function epilog can also use the link to pop the frame from the stack. The
+third entry in the linkage area is used to save the return address from the lr
+register. Finally, as mentioned above, the last entry is used to save the
+previous frame pointer (r31.) The entries in the linkage area are the size of a
+GPR, thus the linkage area is 24 bytes long in 32 bit mode and 48 bytes in 64
+bit mode.
+
+32 bit linkage area:
+
+:raw-html:`<table border="1" cellspacing="0">`
+:raw-html:`<tr>`
+:raw-html:`<td>0</td>`
+:raw-html:`<td>Saved SP (r1)</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>4</td>`
+:raw-html:`<td>Saved CR</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>8</td>`
+:raw-html:`<td>Saved LR</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>12</td>`
+:raw-html:`<td>Reserved</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>16</td>`
+:raw-html:`<td>Reserved</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>20</td>`
+:raw-html:`<td>Saved FP (r31)</td>`
+:raw-html:`</tr>`
+:raw-html:`</table>`
+
+64 bit linkage area:
+
+:raw-html:`<table border="1" cellspacing="0">`
+:raw-html:`<tr>`
+:raw-html:`<td>0</td>`
+:raw-html:`<td>Saved SP (r1)</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>8</td>`
+:raw-html:`<td>Saved CR</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>16</td>`
+:raw-html:`<td>Saved LR</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>24</td>`
+:raw-html:`<td>Reserved</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>32</td>`
+:raw-html:`<td>Reserved</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>40</td>`
+:raw-html:`<td>Saved FP (r31)</td>`
+:raw-html:`</tr>`
+:raw-html:`</table>`
+
+The *parameter area* is used to store arguments being passed to a callee
+function. Following the PowerPC ABI, the first few arguments are actually
+passed in registers, with the space in the parameter area unused. However, if
+there are not enough registers or the callee is a thunk or vararg function,
+these register arguments can be spilled into the parameter area. Thus, the
+parameter area must be large enough to store all the parameters for the largest
+call sequence made by the caller. The size must also be minimally large enough
+to spill registers r3-r10. This allows callees blind to the call signature,
+such as thunks and vararg functions, enough space to cache the argument
+registers. Therefore, the parameter area is minimally 32 bytes (64 bytes in 64
+bit mode.) Also note that since the parameter area is a fixed offset from the
+top of the frame, that a callee can access its spilt arguments using fixed
+offsets from the stack pointer (or base pointer.)
+
+Combining the information about the linkage, parameter areas and alignment. A
+stack frame is minimally 64 bytes in 32 bit mode and 128 bytes in 64 bit mode.
+
+The *dynamic area* starts out as size zero. If a function uses dynamic alloca
+then space is added to the stack, the linkage and parameter areas are shifted to
+top of stack, and the new space is available immediately below the linkage and
+parameter areas. The cost of shifting the linkage and parameter areas is minor
+since only the link value needs to be copied. The link value can be easily
+fetched by adding the original frame size to the base pointer. Note that
+allocations in the dynamic space need to observe 16 byte alignment.
+
+The *locals area* is where the llvm compiler reserves space for local variables.
+
+The *saved registers area* is where the llvm compiler spills callee saved
+registers on entry to the callee.
+
+Prolog/Epilog
+^^^^^^^^^^^^^
+
+The llvm prolog and epilog are the same as described in the PowerPC ABI, with
+the following exceptions. Callee saved registers are spilled after the frame is
+created. This allows the llvm epilog/prolog support to be common with other
+targets. The base pointer callee saved register r31 is saved in the TOC slot of
+linkage area. This simplifies allocation of space for the base pointer and
+makes it convenient to locate programatically and during debugging.
+
+Dynamic Allocation
+^^^^^^^^^^^^^^^^^^
+
+.. note::
+
+ TODO - More to come.
+
+The PTX backend
+---------------
+
+The PTX code generator lives in the lib/Target/PTX directory. It is currently a
+work-in-progress, but already supports most of the code generation functionality
+needed to generate correct PTX kernels for CUDA devices.
+
+The code generator can target PTX 2.0+, and shader model 1.0+. The PTX ISA
+Reference Manual is used as the primary source of ISA information, though an
+effort is made to make the output of the code generator match the output of the
+NVidia nvcc compiler, whenever possible.
+
+Code Generator Options:
+
+:raw-html:`<table border="1" cellspacing="0">`
+:raw-html:`<tr>`
+:raw-html:`<th>Option</th>`
+:raw-html:`<th>Description</th>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>``double``</td>`
+:raw-html:`<td align="left">If enabled, the map_f64_to_f32 directive is disabled in the PTX output, allowing native double-precision arithmetic</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>``no-fma``</td>`
+:raw-html:`<td align="left">Disable generation of Fused-Multiply Add instructions, which may be beneficial for some devices</td>`
+:raw-html:`</tr>`
+:raw-html:`<tr>`
+:raw-html:`<td>``smxy / computexy``</td>`
+:raw-html:`<td align="left">Set shader model/compute capability to x.y, e.g. sm20 or compute13</td>`
+:raw-html:`</tr>`
+:raw-html:`</table>`
+
+Working:
+
+* Arithmetic instruction selection (including combo FMA)
+
+* Bitwise instruction selection
+
+* Control-flow instruction selection
+
+* Function calls (only on SM 2.0+ and no return arguments)
+
+* Addresses spaces (0 = global, 1 = constant, 2 = local, 4 = shared)
+
+* Thread synchronization (bar.sync)
+
+* Special register reads ([N]TID, [N]CTAID, PMx, CLOCK, etc.)
+
+In Progress:
+
+* Robust call instruction selection
+
+* Stack frame allocation
+
+* Device-specific instruction scheduling optimizations
diff --git a/docs/CodingStandards.rst b/docs/CodingStandards.rst
new file mode 100644
index 00000000000..4d16e2a9bd6
--- /dev/null
+++ b/docs/CodingStandards.rst
@@ -0,0 +1,1175 @@
+.. _coding_standards:
+
+=====================
+LLVM Coding Standards
+=====================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+This document attempts to describe a few coding standards that are being used in
+the LLVM source tree. Although no coding standards should be regarded as
+absolute requirements to be followed in all instances, coding standards are
+particularly important for large-scale code bases that follow a library-based
+design (like LLVM).
+
+This document intentionally does not prescribe fixed standards for religious
+issues such as brace placement and space usage. For issues like this, follow
+the golden rule:
+
+.. _Golden Rule:
+
+ **If you are extending, enhancing, or bug fixing already implemented code,
+ use the style that is already being used so that the source is uniform and
+ easy to follow.**
+
+Note that some code bases (e.g. ``libc++``) have really good reasons to deviate
+from the coding standards. In the case of ``libc++``, this is because the
+naming and other conventions are dictated by the C++ standard. If you think
+there is a specific good reason to deviate from the standards here, please bring
+it up on the LLVMdev mailing list.
+
+There are some conventions that are not uniformly followed in the code base
+(e.g. the naming convention). This is because they are relatively new, and a
+lot of code was written before they were put in place. Our long term goal is
+for the entire codebase to follow the convention, but we explicitly *do not*
+want patches that do large-scale reformating of existing code. On the other
+hand, it is reasonable to rename the methods of a class if you're about to
+change it in some other way. Just do the reformating as a separate commit from
+the functionality change.
+
+The ultimate goal of these guidelines is the increase readability and
+maintainability of our common source base. If you have suggestions for topics to
+be included, please mail them to `Chris <mailto:sabre@nondot.org>`_.
+
+Mechanical Source Issues
+========================
+
+Source Code Formatting
+----------------------
+
+Commenting
+^^^^^^^^^^
+
+Comments are one critical part of readability and maintainability. Everyone
+knows they should comment their code, and so should you. When writing comments,
+write them as English prose, which means they should use proper capitalization,
+punctuation, etc. Aim to describe what the code is trying to do and why, not
+*how* it does it at a micro level. Here are a few critical things to document:
+
+.. _header file comment:
+
+File Headers
+""""""""""""
+
+Every source file should have a header on it that describes the basic purpose of
+the file. If a file does not have a header, it should not be checked into the
+tree. The standard header looks like this:
+
+.. code-block:: c++
+
+ //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
+ //
+ // The LLVM Compiler Infrastructure
+ //
+ // This file is distributed under the University of Illinois Open Source
+ // License. See LICENSE.TXT for details.
+ //
+ //===----------------------------------------------------------------------===//
+ //
+ // This file contains the declaration of the Instruction class, which is the
+ // base class for all of the VM instructions.
+ //
+ //===----------------------------------------------------------------------===//
+
+A few things to note about this particular format: The "``-*- C++ -*-``" string
+on the first line is there to tell Emacs that the source file is a C++ file, not
+a C file (Emacs assumes ``.h`` files are C files by default).
+
+.. note::
+
+ This tag is not necessary in ``.cpp`` files. The name of the file is also
+ on the first line, along with a very short description of the purpose of the
+ file. This is important when printing out code and flipping though lots of
+ pages.
+
+The next section in the file is a concise note that defines the license that the
+file is released under. This makes it perfectly clear what terms the source
+code can be distributed under and should not be modified in any way.
+
+The main body of the description does not have to be very long in most cases.
+Here it's only two lines. If an algorithm is being implemented or something
+tricky is going on, a reference to the paper where it is published should be
+included, as well as any notes or *gotchas* in the code to watch out for.
+
+Class overviews
+"""""""""""""""
+
+Classes are one fundamental part of a good object oriented design. As such, a
+class definition should have a comment block that explains what the class is
+used for and how it works. Every non-trivial class is expected to have a
+``doxygen`` comment block.
+
+Method information
+""""""""""""""""""
+
+Methods defined in a class (as well as any global functions) should also be
+documented properly. A quick note about what it does and a description of the
+borderline behaviour is all that is necessary here (unless something
+particularly tricky or insidious is going on). The hope is that people can
+figure out how to use your interfaces without reading the code itself.
+
+Good things to talk about here are what happens when something unexpected
+happens: does the method return null? Abort? Format your hard disk?
+
+Comment Formatting
+^^^^^^^^^^^^^^^^^^
+
+In general, prefer C++ style (``//``) comments. They take less space, require
+less typing, don't have nesting problems, etc. There are a few cases when it is
+useful to use C style (``/* */``) comments however:
+
+#. When writing C code: Obviously if you are writing C code, use C style
+ comments.
+
+#. When writing a header file that may be ``#include``\d by a C source file.
+
+#. When writing a source file that is used by a tool that only accepts C style
+ comments.
+
+To comment out a large block of code, use ``#if 0`` and ``#endif``. These nest
+properly and are better behaved in general than C style comments.
+
+``#include`` Style
+^^^^^^^^^^^^^^^^^^
+
+Immediately after the `header file comment`_ (and include guards if working on a
+header file), the `minimal list of #includes`_ required by the file should be
+listed. We prefer these ``#include``\s to be listed in this order:
+
+.. _Main Module Header:
+.. _Local/Private Headers:
+
+#. Main Module Header
+#. Local/Private Headers
+#. ``llvm/*``
+#. ``llvm/Analysis/*``
+#. ``llvm/Assembly/*``
+#. ``llvm/Bitcode/*``
+#. ``llvm/CodeGen/*``
+#. ...
+#. ``llvm/Support/*``
+#. ``llvm/Config/*``
+#. System ``#include``\s
+
+and each category should be sorted by name.
+
+The `Main Module Header`_ file applies to ``.cpp`` files which implement an
+interface defined by a ``.h`` file. This ``#include`` should always be included
+**first** regardless of where it lives on the file system. By including a
+header file first in the ``.cpp`` files that implement the interfaces, we ensure
+that the header does not have any hidden dependencies which are not explicitly
+``#include``\d in the header, but should be. It is also a form of documentation
+in the ``.cpp`` file to indicate where the interfaces it implements are defined.
+
+.. _fit into 80 columns:
+
+Source Code Width
+^^^^^^^^^^^^^^^^^
+
+Write your code to fit within 80 columns of text. This helps those of us who
+like to print out code and look at your code in an ``xterm`` without resizing
+it.
+
+The longer answer is that there must be some limit to the width of the code in
+order to reasonably allow developers to have multiple files side-by-side in
+windows on a modest display. If you are going to pick a width limit, it is
+somewhat arbitrary but you might as well pick something standard. Going with 90
+columns (for example) instead of 80 columns wouldn't add any significant value
+and would be detrimental to printing out code. Also many other projects have
+standardized on 80 columns, so some people have already configured their editors
+for it (vs something else, like 90 columns).
+
+This is one of many contentious issues in coding standards, but it is not up for
+debate.
+
+Use Spaces Instead of Tabs
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In all cases, prefer spaces to tabs in source files. People have different
+preferred indentation levels, and different styles of indentation that they
+like; this is fine. What isn't fine is that different editors/viewers expand
+tabs out to different tab stops. This can cause your code to look completely
+unreadable, and it is not worth dealing with.
+
+As always, follow the `Golden Rule`_ above: follow the style of
+existing code if you are modifying and extending it. If you like four spaces of
+indentation, **DO NOT** do that in the middle of a chunk of code with two spaces
+of indentation. Also, do not reindent a whole source file: it makes for
+incredible diffs that are absolutely worthless.
+
+Indent Code Consistently
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Okay, in your first year of programming you were told that indentation is
+important. If you didn't believe and internalize this then, now is the time.
+Just do it.
+
+Compiler Issues
+---------------
+
+Treat Compiler Warnings Like Errors
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+If your code has compiler warnings in it, something is wrong --- you aren't
+casting values correctly, you have "questionable" constructs in your code, or
+you are doing something legitimately wrong. Compiler warnings can cover up
+legitimate errors in output and make dealing with a translation unit difficult.
+
+It is not possible to prevent all warnings from all compilers, nor is it
+desirable. Instead, pick a standard compiler (like ``gcc``) that provides a
+good thorough set of warnings, and stick to it. At least in the case of
+``gcc``, it is possible to work around any spurious errors by changing the
+syntax of the code slightly. For example, a warning that annoys me occurs when
+I write code like this:
+
+.. code-block:: c++
+
+ if (V = getValue()) {
+ ...
+ }
+
+``gcc`` will warn me that I probably want to use the ``==`` operator, and that I
+probably mistyped it. In most cases, I haven't, and I really don't want the
+spurious errors. To fix this particular problem, I rewrite the code like
+this:
+
+.. code-block:: c++
+
+ if ((V = getValue())) {
+ ...
+ }
+
+which shuts ``gcc`` up. Any ``gcc`` warning that annoys you can be fixed by
+massaging the code appropriately.
+
+Write Portable Code
+^^^^^^^^^^^^^^^^^^^
+
+In almost all cases, it is possible and within reason to write completely
+portable code. If there are cases where it isn't possible to write portable
+code, isolate it behind a well defined (and well documented) interface.
+
+In practice, this means that you shouldn't assume much about the host compiler
+(and Visual Studio tends to be the lowest common denominator). If advanced
+features are used, they should only be an implementation detail of a library
+which has a simple exposed API, and preferably be buried in ``libSystem``.
+
+Do not use RTTI or Exceptions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In an effort to reduce code and executable size, LLVM does not use RTTI
+(e.g. ``dynamic_cast<>;``) or exceptions. These two language features violate
+the general C++ principle of *"you only pay for what you use"*, causing
+executable bloat even if exceptions are never used in the code base, or if RTTI
+is never used for a class. Because of this, we turn them off globally in the
+code.
+
+That said, LLVM does make extensive use of a hand-rolled form of RTTI that use
+templates like `isa<>, cast<>, and dyn_cast<> <ProgrammersManual.html#isa>`_.
+This form of RTTI is opt-in and can be added to any class. It is also
+substantially more efficient than ``dynamic_cast<>``.
+
+.. _static constructor:
+
+Do not use Static Constructors
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Static constructors and destructors (e.g. global variables whose types have a
+constructor or destructor) should not be added to the code base, and should be
+removed wherever possible. Besides `well known problems
+<http://yosefk.com/c++fqa/ctors.html#fqa-10.12>`_ where the order of
+initialization is undefined between globals in different source files, the
+entire concept of static constructors is at odds with the common use case of
+LLVM as a library linked into a larger application.
+
+Consider the use of LLVM as a JIT linked into another application (perhaps for
+`OpenGL, custom languages <http://llvm.org/Users.html>`_, `shaders in movies
+<http://llvm.org/devmtg/2010-11/Gritz-OpenShadingLang.pdf>`_, etc). Due to the
+design of static constructors, they must be executed at startup time of the
+entire application, regardless of whether or how LLVM is used in that larger
+application. There are two problems with this:
+
+* The time to run the static constructors impacts startup time of applications
+ --- a critical time for GUI apps, among others.
+
+* The static constructors cause the app to pull many extra pages of memory off
+ the disk: both the code for the constructor in each ``.o`` file and the small
+ amount of data that gets touched. In addition, touched/dirty pages put more
+ pressure on the VM system on low-memory machines.
+
+We would really like for there to be zero cost for linking in an additional LLVM
+target or other library into an application, but static constructors violate
+this goal.
+
+That said, LLVM unfortunately does contain static constructors. It would be a
+`great project <http://llvm.org/PR11944>`_ for someone to purge all static
+constructors from LLVM, and then enable the ``-Wglobal-constructors`` warning
+flag (when building with Clang) to ensure we do not regress in the future.
+
+Use of ``class`` and ``struct`` Keywords
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In C++, the ``class`` and ``struct`` keywords can be used almost
+interchangeably. The only difference is when they are used to declare a class:
+``class`` makes all members private by default while ``struct`` makes all
+members public by default.
+
+Unfortunately, not all compilers follow the rules and some will generate
+different symbols based on whether ``class`` or ``struct`` was used to declare
+the symbol. This can lead to problems at link time.
+
+So, the rule for LLVM is to always use the ``class`` keyword, unless **all**
+members are public and the type is a C++ `POD
+<http://en.wikipedia.org/wiki/Plain_old_data_structure>`_ type, in which case
+``struct`` is allowed.
+
+Style Issues
+============
+
+The High-Level Issues
+---------------------
+
+A Public Header File **is** a Module
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+C++ doesn't do too well in the modularity department. There is no real
+encapsulation or data hiding (unless you use expensive protocol classes), but it
+is what we have to work with. When you write a public header file (in the LLVM
+source tree, they live in the top level "``include``" directory), you are
+defining a module of functionality.
+
+Ideally, modules should be completely independent of each other, and their
+header files should only ``#include`` the absolute minimum number of headers
+possible. A module is not just a class, a function, or a namespace: it's a
+collection of these that defines an interface. This interface may be several
+functions, classes, or data structures, but the important issue is how they work
+together.
+
+In general, a module should be implemented by one or more ``.cpp`` files. Each
+of these ``.cpp`` files should include the header that defines their interface
+first. This ensures that all of the dependences of the module header have been
+properly added to the module header itself, and are not implicit. System
+headers should be included after user headers for a translation unit.
+
+.. _minimal list of #includes:
+
+``#include`` as Little as Possible
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+``#include`` hurts compile time performance. Don't do it unless you have to,
+especially in header files.
+
+But wait! Sometimes you need to have the definition of a class to use it, or to
+inherit from it. In these cases go ahead and ``#include`` that header file. Be
+aware however that there are many cases where you don't need to have the full
+definition of a class. If you are using a pointer or reference to a class, you
+don't need the header file. If you are simply returning a class instance from a
+prototyped function or method, you don't need it. In fact, for most cases, you
+simply don't need the definition of a class. And not ``#include``\ing speeds up
+compilation.
+
+It is easy to try to go too overboard on this recommendation, however. You
+**must** include all of the header files that you are using --- you can include
+them either directly or indirectly through another header file. To make sure
+that you don't accidentally forget to include a header file in your module
+header, make sure to include your module header **first** in the implementation
+file (as mentioned above). This way there won't be any hidden dependencies that
+you'll find out about later.
+
+Keep "Internal" Headers Private
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Many modules have a complex implementation that causes them to use more than one
+implementation (``.cpp``) file. It is often tempting to put the internal
+communication interface (helper classes, extra functions, etc) in the public
+module header file. Don't do this!
+
+If you really need to do something like this, put a private header file in the
+same directory as the source files, and include it locally. This ensures that
+your private interface remains private and undisturbed by outsiders.
+
+.. note::
+
+ It's okay to put extra implementation methods in a public class itself. Just
+ make them private (or protected) and all is well.
+
+.. _early exits:
+
+Use Early Exits and ``continue`` to Simplify Code
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+When reading code, keep in mind how much state and how many previous decisions
+have to be remembered by the reader to understand a block of code. Aim to
+reduce indentation where possible when it doesn't make it more difficult to
+understand the code. One great way to do this is by making use of early exits
+and the ``continue`` keyword in long loops. As an example of using an early
+exit from a function, consider this "bad" code:
+
+.. code-block:: c++
+
+ Value *DoSomething(Instruction *I) {
+ if (!isa<TerminatorInst>(I) &&
+ I->hasOneUse() && SomeOtherThing(I)) {
+ ... some long code ....
+ }
+
+ return 0;
+ }
+
+This code has several problems if the body of the ``'if'`` is large. When
+you're looking at the top of the function, it isn't immediately clear that this
+*only* does interesting things with non-terminator instructions, and only
+applies to things with the other predicates. Second, it is relatively difficult
+to describe (in comments) why these predicates are important because the ``if``
+statement makes it difficult to lay out the comments. Third, when you're deep
+within the body of the code, it is indented an extra level. Finally, when
+reading the top of the function, it isn't clear what the result is if the
+predicate isn't true; you have to read to the end of the function to know that
+it returns null.
+
+It is much preferred to format the code like this:
+
+.. code-block:: c++
+
+ Value *DoSomething(Instruction *I) {
+ // Terminators never need 'something' done to them because ...
+ if (isa<TerminatorInst>(I))
+ return 0;
+
+ // We conservatively avoid transforming instructions with multiple uses
+ // because goats like cheese.
+ if (!I->hasOneUse())
+ return 0;
+
+ // This is really just here for example.
+ if (!SomeOtherThing(I))
+ return 0;
+
+ ... some long code ....
+ }
+
+This fixes these problems. A similar problem frequently happens in ``for``
+loops. A silly example is something like this:
+
+.. code-block:: c++
+
+ for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
+ if (BinaryOperator *BO = dyn_cast<BinaryOperator>(II)) {
+ Value *LHS = BO->getOperand(0);
+ Value *RHS = BO->getOperand(1);
+ if (LHS != RHS) {
+ ...
+ }
+ }
+ }
+
+When you have very, very small loops, this sort of structure is fine. But if it
+exceeds more than 10-15 lines, it becomes difficult for people to read and
+understand at a glance. The problem with this sort of code is that it gets very
+nested very quickly. Meaning that the reader of the code has to keep a lot of
+context in their brain to remember what is going immediately on in the loop,
+because they don't know if/when the ``if`` conditions will have ``else``\s etc.
+It is strongly preferred to structure the loop like this:
+
+.. code-block:: c++
+
+ for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
+ BinaryOperator *BO = dyn_cast<BinaryOperator>(II);
+ if (!BO) continue;
+
+ Value *LHS = BO->getOperand(0);
+ Value *RHS = BO->getOperand(1);
+ if (LHS == RHS) continue;
+
+ ...
+ }
+
+This has all the benefits of using early exits for functions: it reduces nesting
+of the loop, it makes it easier to describe why the conditions are true, and it
+makes it obvious to the reader that there is no ``else`` coming up that they
+have to push context into their brain for. If a loop is large, this can be a
+big understandability win.
+
+Don't use ``else`` after a ``return``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+For similar reasons above (reduction of indentation and easier reading), please
+do not use ``'else'`` or ``'else if'`` after something that interrupts control
+flow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For
+example, this is *bad*:
+
+.. code-block:: c++
+
+ case 'J': {
+ if (Signed) {
+ Type = Context.getsigjmp_bufType();
+ if (Type.isNull()) {
+ Error = ASTContext::GE_Missing_sigjmp_buf;
+ return QualType();
+ } else {
+ break;
+ }
+ } else {
+ Type = Context.getjmp_bufType();
+ if (Type.isNull()) {
+ Error = ASTContext::GE_Missing_jmp_buf;
+ return QualType();
+ } else {
+ break;
+ }
+ }
+ }
+
+It is better to write it like this:
+
+.. code-block:: c++
+
+ case 'J':
+ if (Signed) {
+ Type = Context.getsigjmp_bufType();
+ if (Type.isNull()) {
+ Error = ASTContext::GE_Missing_sigjmp_buf;
+ return QualType();
+ }
+ } else {
+ Type = Context.getjmp_bufType();
+ if (Type.isNull()) {
+ Error = ASTContext::GE_Missing_jmp_buf;
+ return QualType();
+ }
+ }
+ break;
+
+Or better yet (in this case) as:
+
+.. code-block:: c++
+
+ case 'J':
+ if (Signed)
+ Type = Context.getsigjmp_bufType();
+ else
+ Type = Context.getjmp_bufType();
+
+ if (Type.isNull()) {
+ Error = Signed ? ASTContext::GE_Missing_sigjmp_buf :
+ ASTContext::GE_Missing_jmp_buf;
+ return QualType();
+ }
+ break;
+
+The idea is to reduce indentation and the amount of code you have to keep track
+of when reading the code.
+
+Turn Predicate Loops into Predicate Functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+It is very common to write small loops that just compute a boolean value. There
+are a number of ways that people commonly write these, but an example of this
+sort of thing is:
+
+.. code-block:: c++
+
+ bool FoundFoo = false;
+ for (unsigned i = 0, e = BarList.size(); i != e; ++i)
+ if (BarList[i]->isFoo()) {
+ FoundFoo = true;
+ break;
+ }
+
+ if (FoundFoo) {
+ ...
+ }
+
+This sort of code is awkward to write, and is almost always a bad sign. Instead
+of this sort of loop, we strongly prefer to use a predicate function (which may
+be `static`_) that uses `early exits`_ to compute the predicate. We prefer the
+code to be structured like this:
+
+.. code-block:: c++
+
+ /// ListContainsFoo - Return true if the specified list has an element that is
+ /// a foo.
+ static bool ListContainsFoo(const std::vector<Bar*> &List) {
+ for (unsigned i = 0, e = List.size(); i != e; ++i)
+ if (List[i]->isFoo())
+ return true;
+ return false;
+ }
+ ...
+
+ if (ListContainsFoo(BarList)) {
+ ...
+ }
+
+There are many reasons for doing this: it reduces indentation and factors out
+code which can often be shared by other code that checks for the same predicate.
+More importantly, it *forces you to pick a name* for the function, and forces
+you to write a comment for it. In this silly example, this doesn't add much
+value. However, if the condition is complex, this can make it a lot easier for
+the reader to understand the code that queries for this predicate. Instead of
+being faced with the in-line details of how we check to see if the BarList
+contains a foo, we can trust the function name and continue reading with better
+locality.
+
+The Low-Level Issues
+--------------------
+
+Name Types, Functions, Variables, and Enumerators Properly
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Poorly-chosen names can mislead the reader and cause bugs. We cannot stress
+enough how important it is to use *descriptive* names. Pick names that match
+the semantics and role of the underlying entities, within reason. Avoid
+abbreviations unless they are well known. After picking a good name, make sure
+to use consistent capitalization for the name, as inconsistency requires clients
+to either memorize the APIs or to look it up to find the exact spelling.
+
+In general, names should be in camel case (e.g. ``TextFileReader`` and
+``isLValue()``). Different kinds of declarations have different rules:
+
+* **Type names** (including classes, structs, enums, typedefs, etc) should be
+ nouns and start with an upper-case letter (e.g. ``TextFileReader``).
+
+* **Variable names** should be nouns (as they represent state). The name should
+ be camel case, and start with an upper case letter (e.g. ``Leader`` or
+ ``Boats``).
+
+* **Function names** should be verb phrases (as they represent actions), and
+ command-like function should be imperative. The name should be camel case,
+ and start with a lower case letter (e.g. ``openFile()`` or ``isFoo()``).
+
+* **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should
+ follow the naming conventions for types. A common use for enums is as a
+ discriminator for a union, or an indicator of a subclass. When an enum is
+ used for something like this, it should have a ``Kind`` suffix
+ (e.g. ``ValueKind``).
+
+* **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables**
+ should start with an upper-case letter, just like types. Unless the
+ enumerators are defined in their own small namespace or inside a class,
+ enumerators should have a prefix corresponding to the enum declaration name.
+ For example, ``enum ValueKind { ... };`` may contain enumerators like
+ ``VK_Argument``, ``VK_BasicBlock``, etc. Enumerators that are just
+ convenience constants are exempt from the requirement for a prefix. For
+ instance:
+
+ .. code-block:: c++
+
+ enum {
+ MaxSize = 42,
+ Density = 12
+ };
+
+As an exception, classes that mimic STL classes can have member names in STL's
+style of lower-case words separated by underscores (e.g. ``begin()``,
+``push_back()``, and ``empty()``).
+
+Here are some examples of good and bad names:
+
+.. code-block:: c++
+
+ class VehicleMaker {
+ ...
+ Factory<Tire> F; // Bad -- abbreviation and non-descriptive.
+ Factory<Tire> Factory; // Better.
+ Factory<Tire> TireFactory; // Even better -- if VehicleMaker has more than one
+ // kind of factories.
+ };
+
+ Vehicle MakeVehicle(VehicleType Type) {
+ VehicleMaker M; // Might be OK if having a short life-span.
+ Tire tmp1 = M.makeTire(); // Bad -- 'tmp1' provides no information.
+ Light headlight = M.makeLight("head"); // Good -- descriptive.
+ ...
+ }
+
+Assert Liberally
+^^^^^^^^^^^^^^^^
+
+Use the "``assert``" macro to its fullest. Check all of your preconditions and
+assumptions, you never know when a bug (not necessarily even yours) might be
+caught early by an assertion, which reduces debugging time dramatically. The
+"``<cassert>``" header file is probably already included by the header files you
+are using, so it doesn't cost anything to use it.
+
+To further assist with debugging, make sure to put some kind of error message in
+the assertion statement, which is printed if the assertion is tripped. This
+helps the poor debugger make sense of why an assertion is being made and
+enforced, and hopefully what to do about it. Here is one complete example:
+
+.. code-block:: c++
+
+ inline Value *getOperand(unsigned i) {
+ assert(i < Operands.size() &amp;&amp; "getOperand() out of range!");
+ return Operands[i];
+ }
+
+Here are more examples:
+
+.. code-block:: c++
+
+ assert(Ty->isPointerType() && "Can't allocate a non pointer type!");
+
+ assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
+
+ assert(idx < getNumSuccessors() && "Successor # out of range!");
+
+ assert(V1.getType() == V2.getType() && "Constant types must be identical!");
+
+ assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
+
+You get the idea.
+
+Please be aware that, when adding assert statements, not all compilers are aware
+of the semantics of the assert. In some places, asserts are used to indicate a
+piece of code that should not be reached. These are typically of the form:
+
+.. code-block:: c++
+
+ assert(0 && "Some helpful error message");
+
+When used in a function that returns a value, they should be followed with a
+return statement and a comment indicating that this line is never reached. This
+will prevent a compiler which is unable to deduce that the assert statement
+never returns from generating a warning.
+
+.. code-block:: c++
+
+ assert(0 && "Some helpful error message");
+ return 0;
+
+Another issue is that values used only by assertions will produce an "unused
+value" warning when assertions are disabled. For example, this code will warn:
+
+.. code-block:: c++
+
+ unsigned Size = V.size();
+ assert(Size > 42 && "Vector smaller than it should be");
+
+ bool NewToSet = Myset.insert(Value);
+ assert(NewToSet && "The value shouldn't be in the set yet");
+
+These are two interesting different cases. In the first case, the call to
+``V.size()`` is only useful for the assert, and we don't want it executed when
+assertions are disabled. Code like this should move the call into the assert
+itself. In the second case, the side effects of the call must happen whether
+the assert is enabled or not. In this case, the value should be cast to void to
+disable the warning. To be specific, it is preferred to write the code like
+this:
+
+.. code-block:: c++
+
+ assert(V.size() > 42 && "Vector smaller than it should be");
+
+ bool NewToSet = Myset.insert(Value); (void)NewToSet;
+ assert(NewToSet && "The value shouldn't be in the set yet");
+
+Do Not Use ``using namespace std``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In LLVM, we prefer to explicitly prefix all identifiers from the standard
+namespace with an "``std::``" prefix, rather than rely on "``using namespace
+std;``".
+
+In header files, adding a ``'using namespace XXX'`` directive pollutes the
+namespace of any source file that ``#include``\s the header. This is clearly a
+bad thing.
+
+In implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic
+rule, but is still important. Basically, using explicit namespace prefixes
+makes the code **clearer**, because it is immediately obvious what facilities
+are being used and where they are coming from. And **more portable**, because
+namespace clashes cannot occur between LLVM code and other namespaces. The
+portability rule is important because different standard library implementations
+expose different symbols (potentially ones they shouldn't), and future revisions
+to the C++ standard will add more symbols to the ``std`` namespace. As such, we
+never use ``'using namespace std;'`` in LLVM.
+
+The exception to the general rule (i.e. it's not an exception for the ``std``
+namespace) is for implementation files. For example, all of the code in the
+LLVM project implements code that lives in the 'llvm' namespace. As such, it is
+ok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace
+llvm;'`` directive at the top, after the ``#include``\s. This reduces
+indentation in the body of the file for source editors that indent based on
+braces, and keeps the conceptual context cleaner. The general form of this rule
+is that any ``.cpp`` file that implements code in any namespace may use that
+namespace (and its parents'), but should not use any others.
+
+Provide a Virtual Method Anchor for Classes in Headers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+If a class is defined in a header file and has a vtable (either it has virtual
+methods or it derives from classes with virtual methods), it must always have at
+least one out-of-line virtual method in the class. Without this, the compiler
+will copy the vtable and RTTI into every ``.o`` file that ``#include``\s the
+header, bloating ``.o`` file sizes and increasing link times.
+
+Use ``LLVM_DELETED_FUNCTION`` to mark uncallable methods
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Prior to C++11, a common pattern to make a class uncopyable was to declare an
+unimplemented copy constructor and copy assignment operator and make them
+private. This would give a compiler error for accessing a private method or a
+linker error because it wasn't implemented.
+
+With C++11, we can mark methods that won't be implemented with ``= delete``.
+This will trigger a much better error message and tell the compiler that the
+method will never be implemented. This enables other checks like
+``-Wunused-private-field`` to run correctly on classes that contain these
+methods.
+
+To maintain compatibility with C++03, ``LLVM_DELETED_FUNCTION`` should be used
+which will expand to ``= delete`` if the compiler supports it. These methods
+should still be declared private. Example of the uncopyable pattern:
+
+.. code-block:: c++
+
+ class DontCopy {
+ private:
+ DontCopy(const DontCopy&) LLVM_DELETED_FUNCTION;
+ DontCopy &operator =(const DontCopy&) LLVM_DELETED_FUNCTION;
+ public:
+ ...
+ };
+
+Don't evaluate ``end()`` every time through a loop
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Because C++ doesn't have a standard "``foreach``" loop (though it can be
+emulated with macros and may be coming in C++'0x) we end up writing a lot of
+loops that manually iterate from begin to end on a variety of containers or
+through other data structures. One common mistake is to write a loop in this
+style:
+
+.. code-block:: c++
+
+ BasicBlock *BB = ...
+ for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
+ ... use I ...
+
+The problem with this construct is that it evaluates "``BB->end()``" every time
+through the loop. Instead of writing the loop like this, we strongly prefer
+loops to be written so that they evaluate it once before the loop starts. A
+convenient way to do this is like so:
+
+.. code-block:: c++
+
+ BasicBlock *BB = ...
+ for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
+ ... use I ...
+
+The observant may quickly point out that these two loops may have different
+semantics: if the container (a basic block in this case) is being mutated, then
+"``BB->end()``" may change its value every time through the loop and the second
+loop may not in fact be correct. If you actually do depend on this behavior,
+please write the loop in the first form and add a comment indicating that you
+did it intentionally.
+
+Why do we prefer the second form (when correct)? Writing the loop in the first
+form has two problems. First it may be less efficient than evaluating it at the
+start of the loop. In this case, the cost is probably minor --- a few extra
+loads every time through the loop. However, if the base expression is more
+complex, then the cost can rise quickly. I've seen loops where the end
+expression was actually something like: "``SomeMap[x]->end()``" and map lookups
+really aren't cheap. By writing it in the second form consistently, you
+eliminate the issue entirely and don't even have to think about it.
+
+The second (even bigger) issue is that writing the loop in the first form hints
+to the reader that the loop is mutating the container (a fact that a comment
+would handily confirm!). If you write the loop in the second form, it is
+immediately obvious without even looking at the body of the loop that the
+container isn't being modified, which makes it easier to read the code and
+understand what it does.
+
+While the second form of the loop is a few extra keystrokes, we do strongly
+prefer it.
+
+``#include <iostream>`` is Forbidden
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The use of ``#include <iostream>`` in library files is hereby **forbidden**,
+because many common implementations transparently inject a `static constructor`_
+into every translation unit that includes it.
+
+Note that using the other stream headers (``<sstream>`` for example) is not
+problematic in this regard --- just ``<iostream>``. However, ``raw_ostream``
+provides various APIs that are better performing for almost every use than
+``std::ostream`` style APIs.
+
+.. note::
+
+ New code should always use `raw_ostream`_ for writing, or the
+ ``llvm::MemoryBuffer`` API for reading files.
+
+.. _raw_ostream:
+
+Use ``raw_ostream``
+^^^^^^^^^^^^^^^^^^^
+
+LLVM includes a lightweight, simple, and efficient stream implementation in
+``llvm/Support/raw_ostream.h``, which provides all of the common features of
+``std::ostream``. All new code should use ``raw_ostream`` instead of
+``ostream``.
+
+Unlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward
+declared as ``class raw_ostream``. Public headers should generally not include
+the ``raw_ostream`` header, but use forward declarations and constant references
+to ``raw_ostream`` instances.
+
+Avoid ``std::endl``
+^^^^^^^^^^^^^^^^^^^
+
+The ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to
+the output stream specified. In addition to doing this, however, it also
+flushes the output stream. In other words, these are equivalent:
+
+.. code-block:: c++
+
+ std::cout << std::endl;
+ std::cout << '\n' << std::flush;
+
+Most of the time, you probably have no reason to flush the output stream, so
+it's better to use a literal ``'\n'``.
+
+Microscopic Details
+-------------------
+
+This section describes preferred low-level formatting guidelines along with
+reasoning on why we prefer them.
+
+Spaces Before Parentheses
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+We prefer to put a space before an open parenthesis only in control flow
+statements, but not in normal function call expressions and function-like
+macros. For example, this is good:
+
+.. code-block:: c++
+
+ if (x) ...
+ for (i = 0; i != 100; ++i) ...
+ while (llvm_rocks) ...
+
+ somefunc(42);
+ assert(3 != 4 && "laws of math are failing me");
+
+ a = foo(42, 92) + bar(x);
+
+and this is bad:
+
+.. code-block:: c++
+
+ if(x) ...
+ for(i = 0; i != 100; ++i) ...
+ while(llvm_rocks) ...
+
+ somefunc (42);
+ assert (3 != 4 && "laws of math are failing me");
+
+ a = foo (42, 92) + bar (x);
+
+The reason for doing this is not completely arbitrary. This style makes control
+flow operators stand out more, and makes expressions flow better. The function
+call operator binds very tightly as a postfix operator. Putting a space after a
+function name (as in the last example) makes it appear that the code might bind
+the arguments of the left-hand-side of a binary operator with the argument list
+of a function and the name of the right side. More specifically, it is easy to
+misread the "``a``" example as:
+
+.. code-block:: c++
+
+ a = foo ((42, 92) + bar) (x);
+
+when skimming through the code. By avoiding a space in a function, we avoid
+this misinterpretation.
+
+Prefer Preincrement
+^^^^^^^^^^^^^^^^^^^
+
+Hard fast rule: Preincrement (``++X``) may be no slower than postincrement
+(``X++``) and could very well be a lot faster than it. Use preincrementation
+whenever possible.
+
+The semantics of postincrement include making a copy of the value being
+incremented, returning it, and then preincrementing the "work value". For
+primitive types, this isn't a big deal. But for iterators, it can be a huge
+issue (for example, some iterators contains stack and set objects in them...
+copying an iterator could invoke the copy ctor's of these as well). In general,
+get in the habit of always using preincrement, and you won't have a problem.
+
+
+Namespace Indentation
+^^^^^^^^^^^^^^^^^^^^^
+
+In general, we strive to reduce indentation wherever possible. This is useful
+because we want code to `fit into 80 columns`_ without wrapping horribly, but
+also because it makes it easier to understand the code. Namespaces are a funny
+thing: they are often large, and we often desire to put lots of stuff into them
+(so they can be large). Other times they are tiny, because they just hold an
+enum or something similar. In order to balance this, we use different
+approaches for small versus large namespaces.
+
+If a namespace definition is small and *easily* fits on a screen (say, less than
+35 lines of code), then you should indent its body. Here's an example:
+
+.. code-block:: c++
+
+ namespace llvm {
+ namespace X86 {
+ /// RelocationType - An enum for the x86 relocation codes. Note that
+ /// the terminology here doesn't follow x86 convention - word means
+ /// 32-bit and dword means 64-bit.
+ enum RelocationType {
+ /// reloc_pcrel_word - PC relative relocation, add the relocated value to
+ /// the value already in memory, after we adjust it for where the PC is.
+ reloc_pcrel_word = 0,
+
+ /// reloc_picrel_word - PIC base relative relocation, add the relocated
+ /// value to the value already in memory, after we adjust it for where the
+ /// PIC base is.
+ reloc_picrel_word = 1,
+
+ /// reloc_absolute_word, reloc_absolute_dword - Absolute relocation, just
+ /// add the relocated value to the value already in memory.
+ reloc_absolute_word = 2,
+ reloc_absolute_dword = 3
+ };
+ }
+ }
+
+Since the body is small, indenting adds value because it makes it very clear
+where the namespace starts and ends, and it is easy to take the whole thing in
+in one "gulp" when reading the code. If the blob of code in the namespace is
+larger (as it typically is in a header in the ``llvm`` or ``clang`` namespaces),
+do not indent the code, and add a comment indicating what namespace is being
+closed. For example:
+
+.. code-block:: c++
+
+ namespace llvm {
+ namespace knowledge {
+
+ /// Grokable - This class represents things that Smith can have an intimate
+ /// understanding of and contains the data associated with it.
+ class Grokable {
+ ...
+ public:
+ explicit Grokable() { ... }
+ virtual ~Grokable() = 0;
+
+ ...
+
+ };
+
+ } // end namespace knowledge
+ } // end namespace llvm
+
+Because the class is large, we don't expect that the reader can easily
+understand the entire concept in a glance, and the end of the file (where the
+namespaces end) may be a long ways away from the place they open. As such,
+indenting the contents of the namespace doesn't add any value, and detracts from
+the readability of the class. In these cases it is best to *not* indent the
+contents of the namespace.
+
+.. _static:
+
+Anonymous Namespaces
+^^^^^^^^^^^^^^^^^^^^
+
+After talking about namespaces in general, you may be wondering about anonymous
+namespaces in particular. Anonymous namespaces are a great language feature
+that tells the C++ compiler that the contents of the namespace are only visible
+within the current translation unit, allowing more aggressive optimization and
+eliminating the possibility of symbol name collisions. Anonymous namespaces are
+to C++ as "static" is to C functions and global variables. While "``static``"
+is available in C++, anonymous namespaces are more general: they can make entire
+classes private to a file.
+
+The problem with anonymous namespaces is that they naturally want to encourage
+indentation of their body, and they reduce locality of reference: if you see a
+random function definition in a C++ file, it is easy to see if it is marked
+static, but seeing if it is in an anonymous namespace requires scanning a big
+chunk of the file.
+
+Because of this, we have a simple guideline: make anonymous namespaces as small
+as possible, and only use them for class declarations. For example, this is
+good:
+
+.. code-block:: c++
+
+ namespace {
+ class StringSort {
+ ...
+ public:
+ StringSort(...)
+ bool operator<(const char *RHS) const;
+ };
+ } // end anonymous namespace
+
+ static void Helper() {
+ ...
+ }
+
+ bool StringSort::operator<(const char *RHS) const {
+ ...
+ }
+
+This is bad:
+
+.. code-block:: c++
+
+ namespace {
+ class StringSort {
+ ...
+ public:
+ StringSort(...)
+ bool operator<(const char *RHS) const;
+ };
+
+ void Helper() {
+ ...
+ }
+
+ bool StringSort::operator<(const char *RHS) const {
+ ...
+ }
+
+ } // end anonymous namespace
+
+This is bad specifically because if you're looking at "``Helper``" in the middle
+of a large C++ file, that you have no immediate way to tell if it is local to
+the file. When it is marked static explicitly, this is immediately obvious.
+Also, there is no reason to enclose the definition of "``operator<``" in the
+namespace just because it was declared there.
+
+See Also
+========
+
+A lot of these comments and recommendations have been culled for other sources.
+Two particularly important books for our work are:
+
+#. `Effective C++
+ <http://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_
+ by Scott Meyers. Also interesting and useful are "More Effective C++" and
+ "Effective STL" by the same author.
+
+#. `Large-Scale C++ Software Design
+ <http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620/ref=sr_1_1>`_
+ by John Lakos
+
+If you get some free time, and you haven't read them: do so, you might learn
+something.
diff --git a/docs/CommandGuide/FileCheck.rst b/docs/CommandGuide/FileCheck.rst
new file mode 100644
index 00000000000..51a9bf6293b
--- /dev/null
+++ b/docs/CommandGuide/FileCheck.rst
@@ -0,0 +1,284 @@
+FileCheck - Flexible pattern matching file verifier
+===================================================
+
+
+SYNOPSIS
+--------
+
+
+**FileCheck** *match-filename* [*--check-prefix=XXX*] [*--strict-whitespace*]
+
+
+DESCRIPTION
+-----------
+
+
+**FileCheck** reads two files (one from standard input, and one specified on the
+command line) and uses one to verify the other. This behavior is particularly
+useful for the testsuite, which wants to verify that the output of some tool
+(e.g. llc) contains the expected information (for example, a movsd from esp or
+whatever is interesting). This is similar to using grep, but it is optimized
+for matching multiple different inputs in one file in a specific order.
+
+The *match-filename* file specifies the file that contains the patterns to
+match. The file to verify is always read from standard input.
+
+
+OPTIONS
+-------
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**--check-prefix** *prefix*
+
+ FileCheck searches the contents of *match-filename* for patterns to match. By
+ default, these patterns are prefixed with "CHECK:". If you'd like to use a
+ different prefix (e.g. because the same input file is checking multiple
+ different tool or options), the **--check-prefix** argument allows you to specify
+ a specific prefix to match.
+
+
+
+**--strict-whitespace**
+
+ By default, FileCheck canonicalizes input horizontal whitespace (spaces and
+ tabs) which causes it to ignore these differences (a space will match a tab).
+ The --strict-whitespace argument disables this behavior.
+
+
+
+**-version**
+
+ Show the version number of this program.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **FileCheck** verifies that the file matches the expected contents, it exits
+with 0. Otherwise, if not, or if an error occurs, it will exit with a non-zero
+value.
+
+
+TUTORIAL
+--------
+
+
+FileCheck is typically used from LLVM regression tests, being invoked on the RUN
+line of the test. A simple example of using FileCheck from a RUN line looks
+like this:
+
+
+.. code-block:: llvm
+
+ ; RUN: llvm-as < %s | llc -march=x86-64 | FileCheck %s
+
+
+This syntax says to pipe the current file ("%s") into llvm-as, pipe that into
+llc, then pipe the output of llc into FileCheck. This means that FileCheck will
+be verifying its standard input (the llc output) against the filename argument
+specified (the original .ll file specified by "%s"). To see how this works,
+let's look at the rest of the .ll file (after the RUN line):
+
+
+.. code-block:: llvm
+
+ define void @sub1(i32* %p, i32 %v) {
+ entry:
+ ; CHECK: sub1:
+ ; CHECK: subl
+ %0 = tail call i32 @llvm.atomic.load.sub.i32.p0i32(i32* %p, i32 %v)
+ ret void
+ }
+
+ define void @inc4(i64* %p) {
+ entry:
+ ; CHECK: inc4:
+ ; CHECK: incq
+ %0 = tail call i64 @llvm.atomic.load.add.i64.p0i64(i64* %p, i64 1)
+ ret void
+ }
+
+
+Here you can see some "CHECK:" lines specified in comments. Now you can see
+how the file is piped into llvm-as, then llc, and the machine code output is
+what we are verifying. FileCheck checks the machine code output to verify that
+it matches what the "CHECK:" lines specify.
+
+The syntax of the CHECK: lines is very simple: they are fixed strings that
+must occur in order. FileCheck defaults to ignoring horizontal whitespace
+differences (e.g. a space is allowed to match a tab) but otherwise, the contents
+of the CHECK: line is required to match some thing in the test file exactly.
+
+One nice thing about FileCheck (compared to grep) is that it allows merging
+test cases together into logical groups. For example, because the test above
+is checking for the "sub1:" and "inc4:" labels, it will not match unless there
+is a "subl" in between those labels. If it existed somewhere else in the file,
+that would not count: "grep subl" matches if subl exists anywhere in the
+file.
+
+The FileCheck -check-prefix option
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+The FileCheck -check-prefix option allows multiple test configurations to be
+driven from one .ll file. This is useful in many circumstances, for example,
+testing different architectural variants with llc. Here's a simple example:
+
+
+.. code-block:: llvm
+
+ ; RUN: llvm-as < %s | llc -mtriple=i686-apple-darwin9 -mattr=sse41 \
+ ; RUN: | FileCheck %s -check-prefix=X32
+ ; RUN: llvm-as < %s | llc -mtriple=x86_64-apple-darwin9 -mattr=sse41 \
+ ; RUN: | FileCheck %s -check-prefix=X64
+
+ define <4 x i32> @pinsrd_1(i32 %s, <4 x i32> %tmp) nounwind {
+ %tmp1 = insertelement <4 x i32>; %tmp, i32 %s, i32 1
+ ret <4 x i32> %tmp1
+ ; X32: pinsrd_1:
+ ; X32: pinsrd $1, 4(%esp), %xmm0
+
+ ; X64: pinsrd_1:
+ ; X64: pinsrd $1, %edi, %xmm0
+ }
+
+
+In this case, we're testing that we get the expected code generation with
+both 32-bit and 64-bit code generation.
+
+
+The "CHECK-NEXT:" directive
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+Sometimes you want to match lines and would like to verify that matches
+happen on exactly consecutive lines with no other lines in between them. In
+this case, you can use CHECK: and CHECK-NEXT: directives to specify this. If
+you specified a custom check prefix, just use "<PREFIX>-NEXT:". For
+example, something like this works as you'd expect:
+
+
+.. code-block:: llvm
+
+ define void @t2(<2 x double>* %r, <2 x double>* %A, double %B) {
+ %tmp3 = load <2 x double>* %A, align 16
+ %tmp7 = insertelement <2 x double> undef, double %B, i32 0
+ %tmp9 = shufflevector <2 x double> %tmp3,
+ <2 x double> %tmp7,
+ <2 x i32> < i32 0, i32 2 >
+ store <2 x double> %tmp9, <2 x double>* %r, align 16
+ ret void
+
+ ; CHECK: t2:
+ ; CHECK: movl 8(%esp), %eax
+ ; CHECK-NEXT: movapd (%eax), %xmm0
+ ; CHECK-NEXT: movhpd 12(%esp), %xmm0
+ ; CHECK-NEXT: movl 4(%esp), %eax
+ ; CHECK-NEXT: movapd %xmm0, (%eax)
+ ; CHECK-NEXT: ret
+ }
+
+
+CHECK-NEXT: directives reject the input unless there is exactly one newline
+between it an the previous directive. A CHECK-NEXT cannot be the first
+directive in a file.
+
+
+The "CHECK-NOT:" directive
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+The CHECK-NOT: directive is used to verify that a string doesn't occur
+between two matches (or before the first match, or after the last match). For
+example, to verify that a load is removed by a transformation, a test like this
+can be used:
+
+
+.. code-block:: llvm
+
+ define i8 @coerce_offset0(i32 %V, i32* %P) {
+ store i32 %V, i32* %P
+
+ %P2 = bitcast i32* %P to i8*
+ %P3 = getelementptr i8* %P2, i32 2
+
+ %A = load i8* %P3
+ ret i8 %A
+ ; CHECK: @coerce_offset0
+ ; CHECK-NOT: load
+ ; CHECK: ret i8
+ }
+
+
+
+FileCheck Pattern Matching Syntax
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+The CHECK: and CHECK-NOT: directives both take a pattern to match. For most
+uses of FileCheck, fixed string matching is perfectly sufficient. For some
+things, a more flexible form of matching is desired. To support this, FileCheck
+allows you to specify regular expressions in matching strings, surrounded by
+double braces: **{{yourregex}}**. Because we want to use fixed string
+matching for a majority of what we do, FileCheck has been designed to support
+mixing and matching fixed string matching with regular expressions. This allows
+you to write things like this:
+
+
+.. code-block:: llvm
+
+ ; CHECK: movhpd {{[0-9]+}}(%esp), {{%xmm[0-7]}}
+
+
+In this case, any offset from the ESP register will be allowed, and any xmm
+register will be allowed.
+
+Because regular expressions are enclosed with double braces, they are
+visually distinct, and you don't need to use escape characters within the double
+braces like you would in C. In the rare case that you want to match double
+braces explicitly from the input, you can use something ugly like
+**{{[{][{]}}** as your pattern.
+
+
+FileCheck Variables
+~~~~~~~~~~~~~~~~~~~
+
+
+It is often useful to match a pattern and then verify that it occurs again
+later in the file. For codegen tests, this can be useful to allow any register,
+but verify that that register is used consistently later. To do this, FileCheck
+allows named variables to be defined and substituted into patterns. Here is a
+simple example:
+
+
+.. code-block:: llvm
+
+ ; CHECK: test5:
+ ; CHECK: notw [[REGISTER:%[a-z]+]]
+ ; CHECK: andw {{.*}}[[REGISTER]]
+
+
+The first check line matches a regex (**%[a-z]+**) and captures it into
+the variable "REGISTER". The second line verifies that whatever is in REGISTER
+occurs later in the file after an "andw". FileCheck variable references are
+always contained in **[[ ]]** pairs, are named, and their names can be
+name, then it is a definition of the variable, if not, it is a use.
+
+FileCheck variables can be defined multiple times, and uses always get the
+latest value. Note that variables are all read at the start of a "CHECK" line
+and are all defined at the end. This means that if you have something like
+"**CHECK: [[XYZ:.\\*]]x[[XYZ]]**", the check line will read the previous
+value of the XYZ variable and define a new one after the match is performed. If
+you need to do something like this you can probably take advantage of the fact
+that FileCheck is not actually line-oriented when it matches, this allows you to
+define two separate CHECK lines that match on the same line.
diff --git a/docs/CommandGuide/bugpoint.rst b/docs/CommandGuide/bugpoint.rst
new file mode 100644
index 00000000000..c1b3b6eca62
--- /dev/null
+++ b/docs/CommandGuide/bugpoint.rst
@@ -0,0 +1,247 @@
+bugpoint - automatic test case reduction tool
+=============================================
+
+
+SYNOPSIS
+--------
+
+
+**bugpoint** [*options*] [*input LLVM ll/bc files*] [*LLVM passes*] **--args**
+*program arguments*
+
+
+DESCRIPTION
+-----------
+
+
+**bugpoint** narrows down the source of problems in LLVM tools and passes. It
+can be used to debug three types of failures: optimizer crashes, miscompilations
+by optimizers, or bad native code generation (including problems in the static
+and JIT compilers). It aims to reduce large test cases to small, useful ones.
+For more information on the design and inner workings of **bugpoint**, as well as
+advice for using bugpoint, see *llvm/docs/Bugpoint.html* in the LLVM
+distribution.
+
+
+OPTIONS
+-------
+
+
+
+**--additional-so** *library*
+
+ Load the dynamic shared object *library* into the test program whenever it is
+ run. This is useful if you are debugging programs which depend on non-LLVM
+ libraries (such as the X or curses libraries) to run.
+
+
+
+**--append-exit-code**\ =\ *{true,false}*
+
+ Append the test programs exit code to the output file so that a change in exit
+ code is considered a test failure. Defaults to false.
+
+
+
+**--args** *program args*
+
+ Pass all arguments specified after -args to the test program whenever it runs.
+ Note that if any of the *program args* start with a '-', you should use:
+
+
+ .. code-block:: perl
+
+ bugpoint [bugpoint args] --args -- [program args]
+
+
+ The "--" right after the **--args** option tells **bugpoint** to consider any
+ options starting with ``-`` to be part of the **--args** option, not as options to
+ **bugpoint** itself.
+
+
+
+**--tool-args** *tool args*
+
+ Pass all arguments specified after --tool-args to the LLVM tool under test
+ (**llc**, **lli**, etc.) whenever it runs. You should use this option in the
+ following way:
+
+
+ .. code-block:: perl
+
+ bugpoint [bugpoint args] --tool-args -- [tool args]
+
+
+ The "--" right after the **--tool-args** option tells **bugpoint** to consider any
+ options starting with ``-`` to be part of the **--tool-args** option, not as
+ options to **bugpoint** itself. (See **--args**, above.)
+
+
+
+**--safe-tool-args** *tool args*
+
+ Pass all arguments specified after **--safe-tool-args** to the "safe" execution
+ tool.
+
+
+
+**--gcc-tool-args** *gcc tool args*
+
+ Pass all arguments specified after **--gcc-tool-args** to the invocation of
+ **gcc**.
+
+
+
+**--opt-args** *opt args*
+
+ Pass all arguments specified after **--opt-args** to the invocation of **opt**.
+
+
+
+**--disable-{dce,simplifycfg}**
+
+ Do not run the specified passes to clean up and reduce the size of the test
+ program. By default, **bugpoint** uses these passes internally when attempting to
+ reduce test programs. If you're trying to find a bug in one of these passes,
+ **bugpoint** may crash.
+
+
+
+**--enable-valgrind**
+
+ Use valgrind to find faults in the optimization phase. This will allow
+ bugpoint to find otherwise asymptomatic problems caused by memory
+ mis-management.
+
+
+
+**-find-bugs**
+
+ Continually randomize the specified passes and run them on the test program
+ until a bug is found or the user kills **bugpoint**.
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**--input** *filename*
+
+ Open *filename* and redirect the standard input of the test program, whenever
+ it runs, to come from that file.
+
+
+
+**--load** *plugin*
+
+ Load the dynamic object *plugin* into **bugpoint** itself. This object should
+ register new optimization passes. Once loaded, the object will add new command
+ line options to enable various optimizations. To see the new complete list of
+ optimizations, use the **-help** and **--load** options together; for example:
+
+
+ .. code-block:: perl
+
+ bugpoint --load myNewPass.so -help
+
+
+
+
+**--mlimit** *megabytes*
+
+ Specifies an upper limit on memory usage of the optimization and codegen. Set
+ to zero to disable the limit.
+
+
+
+**--output** *filename*
+
+ Whenever the test program produces output on its standard output stream, it
+ should match the contents of *filename* (the "reference output"). If you
+ do not use this option, **bugpoint** will attempt to generate a reference output
+ by compiling the program with the "safe" backend and running it.
+
+
+
+**--profile-info-file** *filename*
+
+ Profile file loaded by **--profile-loader**.
+
+
+
+**--run-{int,jit,llc,custom}**
+
+ Whenever the test program is compiled, **bugpoint** should generate code for it
+ using the specified code generator. These options allow you to choose the
+ interpreter, the JIT compiler, the static native code compiler, or a
+ custom command (see **--exec-command**) respectively.
+
+
+
+**--safe-{llc,custom}**
+
+ When debugging a code generator, **bugpoint** should use the specified code
+ generator as the "safe" code generator. This is a known-good code generator
+ used to generate the "reference output" if it has not been provided, and to
+ compile portions of the program that as they are excluded from the testcase.
+ These options allow you to choose the
+ static native code compiler, or a custom command, (see **--exec-command**)
+ respectively. The interpreter and the JIT backends cannot currently
+ be used as the "safe" backends.
+
+
+
+**--exec-command** *command*
+
+ This option defines the command to use with the **--run-custom** and
+ **--safe-custom** options to execute the bitcode testcase. This can
+ be useful for cross-compilation.
+
+
+
+**--compile-command** *command*
+
+ This option defines the command to use with the **--compile-custom**
+ option to compile the bitcode testcase. This can be useful for
+ testing compiler output without running any link or execute stages. To
+ generate a reduced unit test, you may add CHECK directives to the
+ testcase and pass the name of an executable compile-command script in this form:
+
+
+ .. code-block:: sh
+
+ #!/bin/sh
+ llc "$@"
+ not FileCheck [bugpoint input file].ll < bugpoint-test-program.s
+
+
+ This script will "fail" as long as FileCheck passes. So the result
+ will be the minimum bitcode that passes FileCheck.
+
+
+
+**--safe-path** *path*
+
+ This option defines the path to the command to execute with the
+ **--safe-{int,jit,llc,custom}**
+ option.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **bugpoint** succeeds in finding a problem, it will exit with 0. Otherwise,
+if an error occurs, it will exit with a non-zero value.
+
+
+SEE ALSO
+--------
+
+
+opt|opt
diff --git a/docs/CommandGuide/index.rst b/docs/CommandGuide/index.rst
new file mode 100644
index 00000000000..73a4835dd7a
--- /dev/null
+++ b/docs/CommandGuide/index.rst
@@ -0,0 +1,53 @@
+.. _commands:
+
+LLVM Command Guide
+------------------
+
+The following documents are command descriptions for all of the LLVM tools.
+These pages describe how to use the LLVM commands and what their options are.
+Note that these pages do not describe all of the options available for all
+tools. To get a complete listing, pass the ``--help`` (general options) or
+``--help-hidden`` (general and debugging options) arguments to the tool you are
+interested in.
+
+Basic Commands
+~~~~~~~~~~~~~~
+
+.. toctree::
+ :maxdepth: 1
+
+ llvm-as
+ llvm-dis
+ opt
+ llc
+ lli
+ llvm-link
+ llvm-ar
+ llvm-ranlib
+ llvm-nm
+ llvm-prof
+ llvm-config
+ llvm-diff
+ llvm-cov
+ llvm-stress
+
+Debugging Tools
+~~~~~~~~~~~~~~~
+
+.. toctree::
+ :maxdepth: 1
+
+ bugpoint
+ llvm-extract
+ llvm-bcanalyzer
+
+Developer Tools
+~~~~~~~~~~~~~~~
+
+.. toctree::
+ :maxdepth: 1
+
+ FileCheck
+ tblgen
+ lit
+ llvm-build
diff --git a/docs/CommandGuide/lit.rst b/docs/CommandGuide/lit.rst
new file mode 100644
index 00000000000..3eb0be91f13
--- /dev/null
+++ b/docs/CommandGuide/lit.rst
@@ -0,0 +1,474 @@
+lit - LLVM Integrated Tester
+============================
+
+
+SYNOPSIS
+--------
+
+
+**lit** [*options*] [*tests*]
+
+
+DESCRIPTION
+-----------
+
+
+**lit** is a portable tool for executing LLVM and Clang style test suites,
+summarizing their results, and providing indication of failures. **lit** is
+designed to be a lightweight testing tool with as simple a user interface as
+possible.
+
+**lit** should be run with one or more *tests* to run specified on the command
+line. Tests can be either individual test files or directories to search for
+tests (see "TEST DISCOVERY").
+
+Each specified test will be executed (potentially in parallel) and once all
+tests have been run **lit** will print summary information on the number of tests
+which passed or failed (see "TEST STATUS RESULTS"). The **lit** program will
+execute with a non-zero exit code if any tests fail.
+
+By default **lit** will use a succinct progress display and will only print
+summary information for test failures. See "OUTPUT OPTIONS" for options
+controlling the **lit** progress display and output.
+
+**lit** also includes a number of options for controlling how tests are executed
+(specific features may depend on the particular test format). See "EXECUTION
+OPTIONS" for more information.
+
+Finally, **lit** also supports additional options for only running a subset of
+the options specified on the command line, see "SELECTION OPTIONS" for
+more information.
+
+Users interested in the **lit** architecture or designing a **lit** testing
+implementation should see "LIT INFRASTRUCTURE"
+
+
+GENERAL OPTIONS
+---------------
+
+
+
+**-h**, **--help**
+
+ Show the **lit** help message.
+
+
+
+**-j** *N*, **--threads**\ =\ *N*
+
+ Run *N* tests in parallel. By default, this is automatically chosen to match
+ the number of detected available CPUs.
+
+
+
+**--config-prefix**\ =\ *NAME*
+
+ Search for *NAME.cfg* and *NAME.site.cfg* when searching for test suites,
+ instead of *lit.cfg* and *lit.site.cfg*.
+
+
+
+**--param** *NAME*, **--param** *NAME*\ =\ *VALUE*
+
+ Add a user defined parameter *NAME* with the given *VALUE* (or the empty
+ string if not given). The meaning and use of these parameters is test suite
+ dependent.
+
+
+
+
+OUTPUT OPTIONS
+--------------
+
+
+
+**-q**, **--quiet**
+
+ Suppress any output except for test failures.
+
+
+
+**-s**, **--succinct**
+
+ Show less output, for example don't show information on tests that pass.
+
+
+
+**-v**, **--verbose**
+
+ Show more information on test failures, for example the entire test output
+ instead of just the test result.
+
+
+
+**--no-progress-bar**
+
+ Do not use curses based progress bar.
+
+
+
+
+EXECUTION OPTIONS
+-----------------
+
+
+
+**--path**\ =\ *PATH*
+
+ Specify an addition *PATH* to use when searching for executables in tests.
+
+
+
+**--vg**
+
+ Run individual tests under valgrind (using the memcheck tool). The
+ *--error-exitcode* argument for valgrind is used so that valgrind failures will
+ cause the program to exit with a non-zero status.
+
+
+
+**--vg-arg**\ =\ *ARG*
+
+ When *--vg* is used, specify an additional argument to pass to valgrind itself.
+
+
+
+**--time-tests**
+
+ Track the wall time individual tests take to execute and includes the results in
+ the summary output. This is useful for determining which tests in a test suite
+ take the most time to execute. Note that this option is most useful with *-j
+ 1*.
+
+
+
+
+SELECTION OPTIONS
+-----------------
+
+
+
+**--max-tests**\ =\ *N*
+
+ Run at most *N* tests and then terminate.
+
+
+
+**--max-time**\ =\ *N*
+
+ Spend at most *N* seconds (approximately) running tests and then terminate.
+
+
+
+**--shuffle**
+
+ Run the tests in a random order.
+
+
+
+
+ADDITIONAL OPTIONS
+------------------
+
+
+
+**--debug**
+
+ Run **lit** in debug mode, for debugging configuration issues and **lit** itself.
+
+
+
+**--show-suites**
+
+ List the discovered test suites as part of the standard output.
+
+
+
+**--no-tcl-as-sh**
+
+ Run Tcl scripts internally (instead of converting to shell scripts).
+
+
+
+**--repeat**\ =\ *N*
+
+ Run each test *N* times. Currently this is primarily useful for timing tests,
+ other results are not collated in any reasonable fashion.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+**lit** will exit with an exit code of 1 if there are any FAIL or XPASS
+results. Otherwise, it will exit with the status 0. Other exit codes are used
+for non-test related failures (for example a user error or an internal program
+error).
+
+
+TEST DISCOVERY
+--------------
+
+
+The inputs passed to **lit** can be either individual tests, or entire
+directories or hierarchies of tests to run. When **lit** starts up, the first
+thing it does is convert the inputs into a complete list of tests to run as part
+of *test discovery*.
+
+In the **lit** model, every test must exist inside some *test suite*. **lit**
+resolves the inputs specified on the command line to test suites by searching
+upwards from the input path until it finds a *lit.cfg* or *lit.site.cfg*
+file. These files serve as both a marker of test suites and as configuration
+files which **lit** loads in order to understand how to find and run the tests
+inside the test suite.
+
+Once **lit** has mapped the inputs into test suites it traverses the list of
+inputs adding tests for individual files and recursively searching for tests in
+directories.
+
+This behavior makes it easy to specify a subset of tests to run, while still
+allowing the test suite configuration to control exactly how tests are
+interpreted. In addition, **lit** always identifies tests by the test suite they
+are in, and their relative path inside the test suite. For appropriately
+configured projects, this allows **lit** to provide convenient and flexible
+support for out-of-tree builds.
+
+
+TEST STATUS RESULTS
+-------------------
+
+
+Each test ultimately produces one of the following six results:
+
+
+**PASS**
+
+ The test succeeded.
+
+
+
+**XFAIL**
+
+ The test failed, but that is expected. This is used for test formats which allow
+ specifying that a test does not currently work, but wish to leave it in the test
+ suite.
+
+
+
+**XPASS**
+
+ The test succeeded, but it was expected to fail. This is used for tests which
+ were specified as expected to fail, but are now succeeding (generally because
+ the feature they test was broken and has been fixed).
+
+
+
+**FAIL**
+
+ The test failed.
+
+
+
+**UNRESOLVED**
+
+ The test result could not be determined. For example, this occurs when the test
+ could not be run, the test itself is invalid, or the test was interrupted.
+
+
+
+**UNSUPPORTED**
+
+ The test is not supported in this environment. This is used by test formats
+ which can report unsupported tests.
+
+
+
+Depending on the test format tests may produce additional information about
+their status (generally only for failures). See the Output|"OUTPUT OPTIONS"
+section for more information.
+
+
+LIT INFRASTRUCTURE
+------------------
+
+
+This section describes the **lit** testing architecture for users interested in
+creating a new **lit** testing implementation, or extending an existing one.
+
+**lit** proper is primarily an infrastructure for discovering and running
+arbitrary tests, and to expose a single convenient interface to these
+tests. **lit** itself doesn't know how to run tests, rather this logic is
+defined by *test suites*.
+
+TEST SUITES
+~~~~~~~~~~~
+
+
+As described in "TEST DISCOVERY", tests are always located inside a *test
+suite*. Test suites serve to define the format of the tests they contain, the
+logic for finding those tests, and any additional information to run the tests.
+
+**lit** identifies test suites as directories containing *lit.cfg* or
+*lit.site.cfg* files (see also **--config-prefix**). Test suites are initially
+discovered by recursively searching up the directory hierarchy for all the input
+files passed on the command line. You can use **--show-suites** to display the
+discovered test suites at startup.
+
+Once a test suite is discovered, its config file is loaded. Config files
+themselves are Python modules which will be executed. When the config file is
+executed, two important global variables are predefined:
+
+
+**lit**
+
+ The global **lit** configuration object (a *LitConfig* instance), which defines
+ the builtin test formats, global configuration parameters, and other helper
+ routines for implementing test configurations.
+
+
+
+**config**
+
+ This is the config object (a *TestingConfig* instance) for the test suite,
+ which the config file is expected to populate. The following variables are also
+ available on the *config* object, some of which must be set by the config and
+ others are optional or predefined:
+
+ **name** *[required]* The name of the test suite, for use in reports and
+ diagnostics.
+
+ **test_format** *[required]* The test format object which will be used to
+ discover and run tests in the test suite. Generally this will be a builtin test
+ format available from the *lit.formats* module.
+
+ **test_src_root** The filesystem path to the test suite root. For out-of-dir
+ builds this is the directory that will be scanned for tests.
+
+ **test_exec_root** For out-of-dir builds, the path to the test suite root inside
+ the object directory. This is where tests will be run and temporary output files
+ placed.
+
+ **environment** A dictionary representing the environment to use when executing
+ tests in the suite.
+
+ **suffixes** For **lit** test formats which scan directories for tests, this
+ variable is a list of suffixes to identify test files. Used by: *ShTest*,
+ *TclTest*.
+
+ **substitutions** For **lit** test formats which substitute variables into a test
+ script, the list of substitutions to perform. Used by: *ShTest*, *TclTest*.
+
+ **unsupported** Mark an unsupported directory, all tests within it will be
+ reported as unsupported. Used by: *ShTest*, *TclTest*.
+
+ **parent** The parent configuration, this is the config object for the directory
+ containing the test suite, or None.
+
+ **root** The root configuration. This is the top-most **lit** configuration in
+ the project.
+
+ **on_clone** The config is actually cloned for every subdirectory inside a test
+ suite, to allow local configuration on a per-directory basis. The *on_clone*
+ variable can be set to a Python function which will be called whenever a
+ configuration is cloned (for a subdirectory). The function should takes three
+ arguments: (1) the parent configuration, (2) the new configuration (which the
+ *on_clone* function will generally modify), and (3) the test path to the new
+ directory being scanned.
+
+
+
+
+TEST DISCOVERY
+~~~~~~~~~~~~~~
+
+
+Once test suites are located, **lit** recursively traverses the source directory
+(following *test_src_root*) looking for tests. When **lit** enters a
+sub-directory, it first checks to see if a nested test suite is defined in that
+directory. If so, it loads that test suite recursively, otherwise it
+instantiates a local test config for the directory (see "LOCAL CONFIGURATION
+FILES").
+
+Tests are identified by the test suite they are contained within, and the
+relative path inside that suite. Note that the relative path may not refer to an
+actual file on disk; some test formats (such as *GoogleTest*) define "virtual
+tests" which have a path that contains both the path to the actual test file and
+a subpath to identify the virtual test.
+
+
+LOCAL CONFIGURATION FILES
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+When **lit** loads a subdirectory in a test suite, it instantiates a local test
+configuration by cloning the configuration for the parent direction -- the root
+of this configuration chain will always be a test suite. Once the test
+configuration is cloned **lit** checks for a *lit.local.cfg* file in the
+subdirectory. If present, this file will be loaded and can be used to specialize
+the configuration for each individual directory. This facility can be used to
+define subdirectories of optional tests, or to change other configuration
+parameters -- for example, to change the test format, or the suffixes which
+identify test files.
+
+
+TEST RUN OUTPUT FORMAT
+~~~~~~~~~~~~~~~~~~~~~~
+
+
+The b<lit> output for a test run conforms to the following schema, in both short
+and verbose modes (although in short mode no PASS lines will be shown). This
+schema has been chosen to be relatively easy to reliably parse by a machine (for
+example in buildbot log scraping), and for other tools to generate.
+
+Each test result is expected to appear on a line that matches:
+
+<result code>: <test name> (<progress info>)
+
+where <result-code> is a standard test result such as PASS, FAIL, XFAIL, XPASS,
+UNRESOLVED, or UNSUPPORTED. The performance result codes of IMPROVED and
+REGRESSED are also allowed.
+
+The <test name> field can consist of an arbitrary string containing no newline.
+
+The <progress info> field can be used to report progress information such as
+(1/300) or can be empty, but even when empty the parentheses are required.
+
+Each test result may include additional (multiline) log information in the
+following format.
+
+<log delineator> TEST '(<test name>)' <trailing delineator>
+... log message ...
+<log delineator>
+
+where <test name> should be the name of a preceding reported test, <log
+delineator> is a string of '\*' characters *at least* four characters long (the
+recommended length is 20), and <trailing delineator> is an arbitrary (unparsed)
+string.
+
+The following is an example of a test run output which consists of four tests A,
+B, C, and D, and a log message for the failing test C::
+
+ PASS: A (1 of 4)
+ PASS: B (2 of 4)
+ FAIL: C (3 of 4)
+ \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* TEST 'C' FAILED \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+ Test 'C' failed as a result of exit code 1.
+ \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
+ PASS: D (4 of 4)
+
+
+LIT EXAMPLE TESTS
+~~~~~~~~~~~~~~~~~
+
+
+The **lit** distribution contains several example implementations of test suites
+in the *ExampleTests* directory.
+
+
+SEE ALSO
+--------
+
+
+valgrind(1)
diff --git a/docs/CommandGuide/llc.rst b/docs/CommandGuide/llc.rst
new file mode 100644
index 00000000000..6f1c486c3f4
--- /dev/null
+++ b/docs/CommandGuide/llc.rst
@@ -0,0 +1,251 @@
+llc - LLVM static compiler
+==========================
+
+
+SYNOPSIS
+--------
+
+
+**llc** [*options*] [*filename*]
+
+
+DESCRIPTION
+-----------
+
+
+The **llc** command compiles LLVM source inputs into assembly language for a
+specified architecture. The assembly language output can then be passed through
+a native assembler and linker to generate a native executable.
+
+The choice of architecture for the output assembly code is automatically
+determined from the input file, unless the **-march** option is used to override
+the default.
+
+
+OPTIONS
+-------
+
+
+If *filename* is - or omitted, **llc** reads from standard input. Otherwise, it
+will from *filename*. Inputs can be in either the LLVM assembly language
+format (.ll) or the LLVM bitcode format (.bc).
+
+If the **-o** option is omitted, then **llc** will send its output to standard
+output if the input is from standard input. If the **-o** option specifies -,
+then the output will also be sent to standard output.
+
+If no **-o** option is specified and an input file other than - is specified,
+then **llc** creates the output filename by taking the input filename,
+removing any existing *.bc* extension, and adding a *.s* suffix.
+
+Other **llc** options are as follows:
+
+End-user Options
+~~~~~~~~~~~~~~~~
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**-O**\ =\ *uint*
+
+ Generate code at different optimization levels. These correspond to the *-O0*,
+ *-O1*, *-O2*, and *-O3* optimization levels used by **llvm-gcc** and
+ **clang**.
+
+
+
+**-mtriple**\ =\ *target triple*
+
+ Override the target triple specified in the input file with the specified
+ string.
+
+
+
+**-march**\ =\ *arch*
+
+ Specify the architecture for which to generate assembly, overriding the target
+ encoded in the input file. See the output of **llc -help** for a list of
+ valid architectures. By default this is inferred from the target triple or
+ autodetected to the current architecture.
+
+
+
+**-mcpu**\ =\ *cpuname*
+
+ Specify a specific chip in the current architecture to generate code for.
+ By default this is inferred from the target triple and autodetected to
+ the current architecture. For a list of available CPUs, use:
+ **llvm-as < /dev/null | llc -march=xyz -mcpu=help**
+
+
+
+**-mattr**\ =\ *a1,+a2,-a3,...*
+
+ Override or control specific attributes of the target, such as whether SIMD
+ operations are enabled or not. The default set of attributes is set by the
+ current CPU. For a list of available attributes, use:
+ **llvm-as < /dev/null | llc -march=xyz -mattr=help**
+
+
+
+**--disable-fp-elim**
+
+ Disable frame pointer elimination optimization.
+
+
+
+**--disable-excess-fp-precision**
+
+ Disable optimizations that may produce excess precision for floating point.
+ Note that this option can dramatically slow down code on some systems
+ (e.g. X86).
+
+
+
+**--enable-no-infs-fp-math**
+
+ Enable optimizations that assume no Inf values.
+
+
+
+**--enable-no-nans-fp-math**
+
+ Enable optimizations that assume no NAN values.
+
+
+
+**--enable-unsafe-fp-math**
+
+ Enable optimizations that make unsafe assumptions about IEEE math (e.g. that
+ addition is associative) or may not work for all input ranges. These
+ optimizations allow the code generator to make use of some instructions which
+ would otherwise not be usable (such as fsin on X86).
+
+
+
+**--enable-correct-eh-support**
+
+ Instruct the **lowerinvoke** pass to insert code for correct exception handling
+ support. This is expensive and is by default omitted for efficiency.
+
+
+
+**--stats**
+
+ Print statistics recorded by code-generation passes.
+
+
+
+**--time-passes**
+
+ Record the amount of time needed for each pass and print a report to standard
+ error.
+
+
+
+**--load**\ =\ *dso_path*
+
+ Dynamically load *dso_path* (a path to a dynamically shared object) that
+ implements an LLVM target. This will permit the target name to be used with the
+ **-march** option so that code can be generated for that target.
+
+
+
+
+Tuning/Configuration Options
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+
+**--print-machineinstrs**
+
+ Print generated machine code between compilation phases (useful for debugging).
+
+
+
+**--regalloc**\ =\ *allocator*
+
+ Specify the register allocator to use. The default *allocator* is *local*.
+ Valid register allocators are:
+
+
+ *simple*
+
+ Very simple "always spill" register allocator
+
+
+
+ *local*
+
+ Local register allocator
+
+
+
+ *linearscan*
+
+ Linear scan global register allocator
+
+
+
+ *iterativescan*
+
+ Iterative scan global register allocator
+
+
+
+
+
+**--spiller**\ =\ *spiller*
+
+ Specify the spiller to use for register allocators that support it. Currently
+ this option is used only by the linear scan register allocator. The default
+ *spiller* is *local*. Valid spillers are:
+
+
+ *simple*
+
+ Simple spiller
+
+
+
+ *local*
+
+ Local spiller
+
+
+
+
+
+
+Intel IA-32-specific Options
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+
+**--x86-asm-syntax=att|intel**
+
+ Specify whether to emit assembly code in AT&T syntax (the default) or intel
+ syntax.
+
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **llc** succeeds, it will exit with 0. Otherwise, if an error occurs,
+it will exit with a non-zero value.
+
+
+SEE ALSO
+--------
+
+
+lli|lli
diff --git a/docs/CommandGuide/lli.rst b/docs/CommandGuide/lli.rst
new file mode 100644
index 00000000000..7cc128444da
--- /dev/null
+++ b/docs/CommandGuide/lli.rst
@@ -0,0 +1,300 @@
+lli - directly execute programs from LLVM bitcode
+=================================================
+
+
+SYNOPSIS
+--------
+
+
+**lli** [*options*] [*filename*] [*program args*]
+
+
+DESCRIPTION
+-----------
+
+
+**lli** directly executes programs in LLVM bitcode format. It takes a program
+in LLVM bitcode format and executes it using a just-in-time compiler, if one is
+available for the current architecture, or an interpreter. **lli** takes all of
+the same code generator options as llc|llc, but they are only effective when
+**lli** is using the just-in-time compiler.
+
+If *filename* is not specified, then **lli** reads the LLVM bitcode for the
+program from standard input.
+
+The optional *args* specified on the command line are passed to the program as
+arguments.
+
+
+GENERAL OPTIONS
+---------------
+
+
+
+**-fake-argv0**\ =\ *executable*
+
+ Override the ``argv[0]`` value passed into the executing program.
+
+
+
+**-force-interpreter**\ =\ *{false,true}*
+
+ If set to true, use the interpreter even if a just-in-time compiler is available
+ for this architecture. Defaults to false.
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**-load**\ =\ *puginfilename*
+
+ Causes **lli** to load the plugin (shared object) named *pluginfilename* and use
+ it for optimization.
+
+
+
+**-stats**
+
+ Print statistics from the code-generation passes. This is only meaningful for
+ the just-in-time compiler, at present.
+
+
+
+**-time-passes**
+
+ Record the amount of time needed for each code-generation pass and print it to
+ standard error.
+
+
+
+**-version**
+
+ Print out the version of **lli** and exit without doing anything else.
+
+
+
+
+TARGET OPTIONS
+--------------
+
+
+
+**-mtriple**\ =\ *target triple*
+
+ Override the target triple specified in the input bitcode file with the
+ specified string. This may result in a crash if you pick an
+ architecture which is not compatible with the current system.
+
+
+
+**-march**\ =\ *arch*
+
+ Specify the architecture for which to generate assembly, overriding the target
+ encoded in the bitcode file. See the output of **llc -help** for a list of
+ valid architectures. By default this is inferred from the target triple or
+ autodetected to the current architecture.
+
+
+
+**-mcpu**\ =\ *cpuname*
+
+ Specify a specific chip in the current architecture to generate code for.
+ By default this is inferred from the target triple and autodetected to
+ the current architecture. For a list of available CPUs, use:
+ **llvm-as < /dev/null | llc -march=xyz -mcpu=help**
+
+
+
+**-mattr**\ =\ *a1,+a2,-a3,...*
+
+ Override or control specific attributes of the target, such as whether SIMD
+ operations are enabled or not. The default set of attributes is set by the
+ current CPU. For a list of available attributes, use:
+ **llvm-as < /dev/null | llc -march=xyz -mattr=help**
+
+
+
+
+FLOATING POINT OPTIONS
+----------------------
+
+
+
+**-disable-excess-fp-precision**
+
+ Disable optimizations that may increase floating point precision.
+
+
+
+**-enable-no-infs-fp-math**
+
+ Enable optimizations that assume no Inf values.
+
+
+
+**-enable-no-nans-fp-math**
+
+ Enable optimizations that assume no NAN values.
+
+
+
+**-enable-unsafe-fp-math**
+
+ Causes **lli** to enable optimizations that may decrease floating point
+ precision.
+
+
+
+**-soft-float**
+
+ Causes **lli** to generate software floating point library calls instead of
+ equivalent hardware instructions.
+
+
+
+
+CODE GENERATION OPTIONS
+-----------------------
+
+
+
+**-code-model**\ =\ *model*
+
+ Choose the code model from:
+
+
+ .. code-block:: perl
+
+ default: Target default code model
+ small: Small code model
+ kernel: Kernel code model
+ medium: Medium code model
+ large: Large code model
+
+
+
+
+**-disable-post-RA-scheduler**
+
+ Disable scheduling after register allocation.
+
+
+
+**-disable-spill-fusing**
+
+ Disable fusing of spill code into instructions.
+
+
+
+**-enable-correct-eh-support**
+
+ Make the -lowerinvoke pass insert expensive, but correct, EH code.
+
+
+
+**-jit-enable-eh**
+
+ Exception handling should be enabled in the just-in-time compiler.
+
+
+
+**-join-liveintervals**
+
+ Coalesce copies (default=true).
+
+
+
+**-nozero-initialized-in-bss** Don't place zero-initialized symbols into the BSS section.
+
+
+
+**-pre-RA-sched**\ =\ *scheduler*
+
+ Instruction schedulers available (before register allocation):
+
+
+ .. code-block:: perl
+
+ =default: Best scheduler for the target
+ =none: No scheduling: breadth first sequencing
+ =simple: Simple two pass scheduling: minimize critical path and maximize processor utilization
+ =simple-noitin: Simple two pass scheduling: Same as simple except using generic latency
+ =list-burr: Bottom-up register reduction list scheduling
+ =list-tdrr: Top-down register reduction list scheduling
+ =list-td: Top-down list scheduler -print-machineinstrs - Print generated machine code
+
+
+
+
+**-regalloc**\ =\ *allocator*
+
+ Register allocator to use (default=linearscan)
+
+
+ .. code-block:: perl
+
+ =bigblock: Big-block register allocator
+ =linearscan: linear scan register allocator =local - local register allocator
+ =simple: simple register allocator
+
+
+
+
+**-relocation-model**\ =\ *model*
+
+ Choose relocation model from:
+
+
+ .. code-block:: perl
+
+ =default: Target default relocation model
+ =static: Non-relocatable code =pic - Fully relocatable, position independent code
+ =dynamic-no-pic: Relocatable external references, non-relocatable code
+
+
+
+
+**-spiller**
+
+ Spiller to use (default=local)
+
+
+ .. code-block:: perl
+
+ =simple: simple spiller
+ =local: local spiller
+
+
+
+
+**-x86-asm-syntax**\ =\ *syntax*
+
+ Choose style of code to emit from X86 backend:
+
+
+ .. code-block:: perl
+
+ =att: Emit AT&T-style assembly
+ =intel: Emit Intel-style assembly
+
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **lli** fails to load the program, it will exit with an exit code of 1.
+Otherwise, it will return the exit code of the program it executes.
+
+
+SEE ALSO
+--------
+
+
+llc|llc
diff --git a/docs/CommandGuide/llvm-ar.rst b/docs/CommandGuide/llvm-ar.rst
new file mode 100644
index 00000000000..8ff4192a500
--- /dev/null
+++ b/docs/CommandGuide/llvm-ar.rst
@@ -0,0 +1,458 @@
+llvm-ar - LLVM archiver
+=======================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-ar** [-]{dmpqrtx}[Rabfikou] [relpos] [count] <archive> [files...]
+
+
+DESCRIPTION
+-----------
+
+
+The **llvm-ar** command is similar to the common Unix utility, ``ar``. It
+archives several files together into a single file. The intent for this is
+to produce archive libraries by LLVM bitcode that can be linked into an
+LLVM program. However, the archive can contain any kind of file. By default,
+**llvm-ar** generates a symbol table that makes linking faster because
+only the symbol table needs to be consulted, not each individual file member
+of the archive.
+
+The **llvm-ar** command can be used to *read* both SVR4 and BSD style archive
+files. However, it cannot be used to write them. While the **llvm-ar** command
+produces files that are *almost* identical to the format used by other ``ar``
+implementations, it has two significant departures in order to make the
+archive appropriate for LLVM. The first departure is that **llvm-ar** only
+uses BSD4.4 style long path names (stored immediately after the header) and
+never contains a string table for long names. The second departure is that the
+symbol table is formated for efficient construction of an in-memory data
+structure that permits rapid (red-black tree) lookups. Consequently, archives
+produced with **llvm-ar** usually won't be readable or editable with any
+``ar`` implementation or useful for linking. Using the ``f`` modifier to flatten
+file names will make the archive readable by other ``ar`` implementations
+but not for linking because the symbol table format for LLVM is unique. If an
+SVR4 or BSD style archive is used with the ``r`` (replace) or ``q`` (quick
+update) operations, the archive will be reconstructed in LLVM format. This
+means that the string table will be dropped (in deference to BSD 4.4 long names)
+and an LLVM symbol table will be added (by default). The system symbol table
+will be retained.
+
+Here's where **llvm-ar** departs from previous ``ar`` implementations:
+
+
+*Symbol Table*
+
+ Since **llvm-ar** is intended to archive bitcode files, the symbol table
+ won't make much sense to anything but LLVM. Consequently, the symbol table's
+ format has been simplified. It consists simply of a sequence of pairs
+ of a file member index number as an LSB 4byte integer and a null-terminated
+ string.
+
+
+
+*Long Paths*
+
+ Some ``ar`` implementations (SVR4) use a separate file member to record long
+ path names (> 15 characters). **llvm-ar** takes the BSD 4.4 and Mac OS X
+ approach which is to simply store the full path name immediately preceding
+ the data for the file. The path name is null terminated and may contain the
+ slash (/) character.
+
+
+
+*Directory Recursion*
+
+ Most ``ar`` implementations do not recurse through directories but simply
+ ignore directories if they are presented to the program in the *files*
+ option. **llvm-ar**, however, can recurse through directory structures and
+ add all the files under a directory, if requested.
+
+
+
+*TOC Verbose Output*
+
+ When **llvm-ar** prints out the verbose table of contents (``tv`` option), it
+ precedes the usual output with a character indicating the basic kind of
+ content in the file. A blank means the file is a regular file. A 'B' means
+ the file is an LLVM bitcode file. An 'S' means the file is the symbol table.
+
+
+
+
+OPTIONS
+-------
+
+
+The options to **llvm-ar** are compatible with other ``ar`` implementations.
+However, there are a few modifiers (*R*) that are not found in other ``ar``
+implementations. The options to **llvm-ar** specify a single basic operation to
+perform on the archive, a variety of modifiers for that operation, the name of
+the archive file, and an optional list of file names. These options are used to
+determine how **llvm-ar** should process the archive file.
+
+The Operations and Modifiers are explained in the sections below. The minimal
+set of options is at least one operator and the name of the archive. Typically
+archive files end with a ``.a`` suffix, but this is not required. Following
+the *archive-name* comes a list of *files* that indicate the specific members
+of the archive to operate on. If the *files* option is not specified, it
+generally means either "none" or "all" members, depending on the operation.
+
+Operations
+~~~~~~~~~~
+
+
+
+d
+
+ Delete files from the archive. No modifiers are applicable to this operation.
+ The *files* options specify which members should be removed from the
+ archive. It is not an error if a specified file does not appear in the archive.
+ If no *files* are specified, the archive is not modified.
+
+
+
+m[abi]
+
+ Move files from one location in the archive to another. The *a*, *b*, and
+ *i* modifiers apply to this operation. The *files* will all be moved
+ to the location given by the modifiers. If no modifiers are used, the files
+ will be moved to the end of the archive. If no *files* are specified, the
+ archive is not modified.
+
+
+
+p[k]
+
+ Print files to the standard output. The *k* modifier applies to this
+ operation. This operation simply prints the *files* indicated to the
+ standard output. If no *files* are specified, the entire archive is printed.
+ Printing bitcode files is ill-advised as they might confuse your terminal
+ settings. The *p* operation never modifies the archive.
+
+
+
+q[Rf]
+
+ Quickly append files to the end of the archive. The *R*, and *f*
+ modifiers apply to this operation. This operation quickly adds the
+ *files* to the archive without checking for duplicates that should be
+ removed first. If no *files* are specified, the archive is not modified.
+ Because of the way that **llvm-ar** constructs the archive file, its dubious
+ whether the *q* operation is any faster than the *r* operation.
+
+
+
+r[Rabfu]
+
+ Replace or insert file members. The *R*, *a*, *b*, *f*, and *u*
+ modifiers apply to this operation. This operation will replace existing
+ *files* or insert them at the end of the archive if they do not exist. If no
+ *files* are specified, the archive is not modified.
+
+
+
+t[v]
+
+ Print the table of contents. Without any modifiers, this operation just prints
+ the names of the members to the standard output. With the *v* modifier,
+ **llvm-ar** also prints out the file type (B=bitcode, S=symbol
+ table, blank=regular file), the permission mode, the owner and group, the
+ size, and the date. If any *files* are specified, the listing is only for
+ those files. If no *files* are specified, the table of contents for the
+ whole archive is printed.
+
+
+
+x[oP]
+
+ Extract archive members back to files. The *o* modifier applies to this
+ operation. This operation retrieves the indicated *files* from the archive
+ and writes them back to the operating system's file system. If no
+ *files* are specified, the entire archive is extract.
+
+
+
+
+Modifiers (operation specific)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+The modifiers below are specific to certain operations. See the Operations
+section (above) to determine which modifiers are applicable to which operations.
+
+
+[a]
+
+ When inserting or moving member files, this option specifies the destination of
+ the new files as being after the *relpos* member. If *relpos* is not found,
+ the files are placed at the end of the archive.
+
+
+
+[b]
+
+ When inserting or moving member files, this option specifies the destination of
+ the new files as being before the *relpos* member. If *relpos* is not
+ found, the files are placed at the end of the archive. This modifier is
+ identical to the *i* modifier.
+
+
+
+[f]
+
+ Normally, **llvm-ar** stores the full path name to a file as presented to it on
+ the command line. With this option, truncated (15 characters max) names are
+ used. This ensures name compatibility with older versions of ``ar`` but may also
+ thwart correct extraction of the files (duplicates may overwrite). If used with
+ the *R* option, the directory recursion will be performed but the file names
+ will all be flattened to simple file names.
+
+
+
+[i]
+
+ A synonym for the *b* option.
+
+
+
+[k]
+
+ Normally, **llvm-ar** will not print the contents of bitcode files when the
+ *p* operation is used. This modifier defeats the default and allows the
+ bitcode members to be printed.
+
+
+
+[N]
+
+ This option is ignored by **llvm-ar** but provided for compatibility.
+
+
+
+[o]
+
+ When extracting files, this option will cause **llvm-ar** to preserve the
+ original modification times of the files it writes.
+
+
+
+[P]
+
+ use full path names when matching
+
+
+
+[R]
+
+ This modifier instructions the *r* option to recursively process directories.
+ Without *R*, directories are ignored and only those *files* that refer to
+ files will be added to the archive. When *R* is used, any directories specified
+ with *files* will be scanned (recursively) to find files to be added to the
+ archive. Any file whose name begins with a dot will not be added.
+
+
+
+[u]
+
+ When replacing existing files in the archive, only replace those files that have
+ a time stamp than the time stamp of the member in the archive.
+
+
+
+
+Modifiers (generic)
+~~~~~~~~~~~~~~~~~~~
+
+
+The modifiers below may be applied to any operation.
+
+
+[c]
+
+ For all operations, **llvm-ar** will always create the archive if it doesn't
+ exist. Normally, **llvm-ar** will print a warning message indicating that the
+ archive is being created. Using this modifier turns off that warning.
+
+
+
+[s]
+
+ This modifier requests that an archive index (or symbol table) be added to the
+ archive. This is the default mode of operation. The symbol table will contain
+ all the externally visible functions and global variables defined by all the
+ bitcode files in the archive. Using this modifier is more efficient that using
+ llvm-ranlib|llvm-ranlib which also creates the symbol table.
+
+
+
+[S]
+
+ This modifier is the opposite of the *s* modifier. It instructs **llvm-ar** to
+ not build the symbol table. If both *s* and *S* are used, the last modifier to
+ occur in the options will prevail.
+
+
+
+[v]
+
+ This modifier instructs **llvm-ar** to be verbose about what it is doing. Each
+ editing operation taken against the archive will produce a line of output saying
+ what is being done.
+
+
+
+
+
+STANDARDS
+---------
+
+
+The **llvm-ar** utility is intended to provide a superset of the IEEE Std 1003.2
+(POSIX.2) functionality for ``ar``. **llvm-ar** can read both SVR4 and BSD4.4 (or
+Mac OS X) archives. If the ``f`` modifier is given to the ``x`` or ``r`` operations
+then **llvm-ar** will write SVR4 compatible archives. Without this modifier,
+**llvm-ar** will write BSD4.4 compatible archives that have long names
+immediately after the header and indicated using the "#1/ddd" notation for the
+name in the header.
+
+
+FILE FORMAT
+-----------
+
+
+The file format for LLVM Archive files is similar to that of BSD 4.4 or Mac OSX
+archive files. In fact, except for the symbol table, the ``ar`` commands on those
+operating systems should be able to read LLVM archive files. The details of the
+file format follow.
+
+Each archive begins with the archive magic number which is the eight printable
+characters "!<arch>\n" where \n represents the newline character (0x0A).
+Following the magic number, the file is composed of even length members that
+begin with an archive header and end with a \n padding character if necessary
+(to make the length even). Each file member is composed of a header (defined
+below), an optional newline-terminated "long file name" and the contents of
+the file.
+
+The fields of the header are described in the items below. All fields of the
+header contain only ASCII characters, are left justified and are right padded
+with space characters.
+
+
+name - char[16]
+
+ This field of the header provides the name of the archive member. If the name is
+ longer than 15 characters or contains a slash (/) character, then this field
+ contains ``#1/nnn`` where ``nnn`` provides the length of the name and the ``#1/``
+ is literal. In this case, the actual name of the file is provided in the ``nnn``
+ bytes immediately following the header. If the name is 15 characters or less, it
+ is contained directly in this field and terminated with a slash (/) character.
+
+
+
+date - char[12]
+
+ This field provides the date of modification of the file in the form of a
+ decimal encoded number that provides the number of seconds since the epoch
+ (since 00:00:00 Jan 1, 1970) per Posix specifications.
+
+
+
+uid - char[6]
+
+ This field provides the user id of the file encoded as a decimal ASCII string.
+ This field might not make much sense on non-Unix systems. On Unix, it is the
+ same value as the st_uid field of the stat structure returned by the stat(2)
+ operating system call.
+
+
+
+gid - char[6]
+
+ This field provides the group id of the file encoded as a decimal ASCII string.
+ This field might not make much sense on non-Unix systems. On Unix, it is the
+ same value as the st_gid field of the stat structure returned by the stat(2)
+ operating system call.
+
+
+
+mode - char[8]
+
+ This field provides the access mode of the file encoded as an octal ASCII
+ string. This field might not make much sense on non-Unix systems. On Unix, it
+ is the same value as the st_mode field of the stat structure returned by the
+ stat(2) operating system call.
+
+
+
+size - char[10]
+
+ This field provides the size of the file, in bytes, encoded as a decimal ASCII
+ string.
+
+
+
+fmag - char[2]
+
+ This field is the archive file member magic number. Its content is always the
+ two characters back tick (0x60) and newline (0x0A). This provides some measure
+ utility in identifying archive files that have been corrupted.
+
+
+
+The LLVM symbol table has the special name "#_LLVM_SYM_TAB_#". It is presumed
+that no regular archive member file will want this name. The LLVM symbol table
+is simply composed of a sequence of triplets: byte offset, length of symbol,
+and the symbol itself. Symbols are not null or newline terminated. Here are
+the details on each of these items:
+
+
+offset - vbr encoded 32-bit integer
+
+ The offset item provides the offset into the archive file where the bitcode
+ member is stored that is associated with the symbol. The offset value is 0
+ based at the start of the first "normal" file member. To derive the actual
+ file offset of the member, you must add the number of bytes occupied by the file
+ signature (8 bytes) and the symbol tables. The value of this item is encoded
+ using variable bit rate encoding to reduce the size of the symbol table.
+ Variable bit rate encoding uses the high bit (0x80) of each byte to indicate
+ if there are more bytes to follow. The remaining 7 bits in each byte carry bits
+ from the value. The final byte does not have the high bit set.
+
+
+
+length - vbr encoded 32-bit integer
+
+ The length item provides the length of the symbol that follows. Like this
+ *offset* item, the length is variable bit rate encoded.
+
+
+
+symbol - character array
+
+ The symbol item provides the text of the symbol that is associated with the
+ *offset*. The symbol is not terminated by any character. Its length is provided
+ by the *length* field. Note that is allowed (but unwise) to use non-printing
+ characters (even 0x00) in the symbol. This allows for multiple encodings of
+ symbol names.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **llvm-ar** succeeds, it will exit with 0. A usage error, results
+in an exit code of 1. A hard (file system typically) error results in an
+exit code of 2. Miscellaneous or unknown errors result in an
+exit code of 3.
+
+
+SEE ALSO
+--------
+
+
+llvm-ranlib|llvm-ranlib, ar(1)
diff --git a/docs/CommandGuide/llvm-as.rst b/docs/CommandGuide/llvm-as.rst
new file mode 100644
index 00000000000..1b499bbe970
--- /dev/null
+++ b/docs/CommandGuide/llvm-as.rst
@@ -0,0 +1,56 @@
+llvm-as - LLVM assembler
+========================
+
+SYNOPSIS
+--------
+
+**llvm-as** [*options*] [*filename*]
+
+DESCRIPTION
+-----------
+
+**llvm-as** is the LLVM assembler. It reads a file containing human-readable
+LLVM assembly language, translates it to LLVM bitcode, and writes the result
+into a file or to standard output.
+
+If *filename* is omitted or is ``-``, then **llvm-as** reads its input from
+standard input.
+
+If an output file is not specified with the **-o** option, then
+**llvm-as** sends its output to a file or standard output by following
+these rules:
+
+* If the input is standard input, then the output is standard output.
+
+* If the input is a file that ends with ``.ll``, then the output file is of the
+ same name, except that the suffix is changed to ``.bc``.
+
+* If the input is a file that does not end with the ``.ll`` suffix, then the
+ output file has the same name as the input file, except that the ``.bc``
+ suffix is appended.
+
+OPTIONS
+-------
+
+**-f**
+ Enable binary output on terminals. Normally, **llvm-as** will refuse to
+ write raw bitcode output if the output stream is a terminal. With this option,
+ **llvm-as** will write raw bitcode regardless of the output device.
+
+**-help**
+ Print a summary of command line options.
+
+**-o** *filename*
+ Specify the output file name. If *filename* is ``-``, then **llvm-as**
+ sends its output to standard output.
+
+EXIT STATUS
+-----------
+
+If **llvm-as** succeeds, it will exit with 0. Otherwise, if an error occurs, it
+will exit with a non-zero value.
+
+SEE ALSO
+--------
+
+llvm-dis|llvm-dis, gccas|gccas
diff --git a/docs/CommandGuide/llvm-bcanalyzer.rst b/docs/CommandGuide/llvm-bcanalyzer.rst
new file mode 100644
index 00000000000..f1e4eac1be5
--- /dev/null
+++ b/docs/CommandGuide/llvm-bcanalyzer.rst
@@ -0,0 +1,424 @@
+llvm-bcanalyzer - LLVM bitcode analyzer
+=======================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-bcanalyzer** [*options*] [*filename*]
+
+
+DESCRIPTION
+-----------
+
+
+The **llvm-bcanalyzer** command is a small utility for analyzing bitcode files.
+The tool reads a bitcode file (such as generated with the **llvm-as** tool) and
+produces a statistical report on the contents of the bitcode file. The tool
+can also dump a low level but human readable version of the bitcode file.
+This tool is probably not of much interest or utility except for those working
+directly with the bitcode file format. Most LLVM users can just ignore
+this tool.
+
+If *filename* is omitted or is ``-``, then **llvm-bcanalyzer** reads its input
+from standard input. This is useful for combining the tool into a pipeline.
+Output is written to the standard output.
+
+
+OPTIONS
+-------
+
+
+
+**-nodetails**
+
+ Causes **llvm-bcanalyzer** to abbreviate its output by writing out only a module
+ level summary. The details for individual functions are not displayed.
+
+
+
+**-dump**
+
+ Causes **llvm-bcanalyzer** to dump the bitcode in a human readable format. This
+ format is significantly different from LLVM assembly and provides details about
+ the encoding of the bitcode file.
+
+
+
+**-verify**
+
+ Causes **llvm-bcanalyzer** to verify the module produced by reading the
+ bitcode. This ensures that the statistics generated are based on a consistent
+ module.
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **llvm-bcanalyzer** succeeds, it will exit with 0. Otherwise, if an error
+occurs, it will exit with a non-zero value, usually 1.
+
+
+SUMMARY OUTPUT DEFINITIONS
+--------------------------
+
+
+The following items are always printed by llvm-bcanalyzer. They comprize the
+summary output.
+
+
+**Bitcode Analysis Of Module**
+
+ This just provides the name of the module for which bitcode analysis is being
+ generated.
+
+
+
+**Bitcode Version Number**
+
+ The bitcode version (not LLVM version) of the file read by the analyzer.
+
+
+
+**File Size**
+
+ The size, in bytes, of the entire bitcode file.
+
+
+
+**Module Bytes**
+
+ The size, in bytes, of the module block. Percentage is relative to File Size.
+
+
+
+**Function Bytes**
+
+ The size, in bytes, of all the function blocks. Percentage is relative to File
+ Size.
+
+
+
+**Global Types Bytes**
+
+ The size, in bytes, of the Global Types Pool. Percentage is relative to File
+ Size. This is the size of the definitions of all types in the bitcode file.
+
+
+
+**Constant Pool Bytes**
+
+ The size, in bytes, of the Constant Pool Blocks Percentage is relative to File
+ Size.
+
+
+
+**Module Globals Bytes**
+
+ Ths size, in bytes, of the Global Variable Definitions and their initializers.
+ Percentage is relative to File Size.
+
+
+
+**Instruction List Bytes**
+
+ The size, in bytes, of all the instruction lists in all the functions.
+ Percentage is relative to File Size. Note that this value is also included in
+ the Function Bytes.
+
+
+
+**Compaction Table Bytes**
+
+ The size, in bytes, of all the compaction tables in all the functions.
+ Percentage is relative to File Size. Note that this value is also included in
+ the Function Bytes.
+
+
+
+**Symbol Table Bytes**
+
+ The size, in bytes, of all the symbol tables in all the functions. Percentage is
+ relative to File Size. Note that this value is also included in the Function
+ Bytes.
+
+
+
+**Dependent Libraries Bytes**
+
+ The size, in bytes, of the list of dependent libraries in the module. Percentage
+ is relative to File Size. Note that this value is also included in the Module
+ Global Bytes.
+
+
+
+**Number Of Bitcode Blocks**
+
+ The total number of blocks of any kind in the bitcode file.
+
+
+
+**Number Of Functions**
+
+ The total number of function definitions in the bitcode file.
+
+
+
+**Number Of Types**
+
+ The total number of types defined in the Global Types Pool.
+
+
+
+**Number Of Constants**
+
+ The total number of constants (of any type) defined in the Constant Pool.
+
+
+
+**Number Of Basic Blocks**
+
+ The total number of basic blocks defined in all functions in the bitcode file.
+
+
+
+**Number Of Instructions**
+
+ The total number of instructions defined in all functions in the bitcode file.
+
+
+
+**Number Of Long Instructions**
+
+ The total number of long instructions defined in all functions in the bitcode
+ file. Long instructions are those taking greater than 4 bytes. Typically long
+ instructions are GetElementPtr with several indices, PHI nodes, and calls to
+ functions with large numbers of arguments.
+
+
+
+**Number Of Operands**
+
+ The total number of operands used in all instructions in the bitcode file.
+
+
+
+**Number Of Compaction Tables**
+
+ The total number of compaction tables in all functions in the bitcode file.
+
+
+
+**Number Of Symbol Tables**
+
+ The total number of symbol tables in all functions in the bitcode file.
+
+
+
+**Number Of Dependent Libs**
+
+ The total number of dependent libraries found in the bitcode file.
+
+
+
+**Total Instruction Size**
+
+ The total size of the instructions in all functions in the bitcode file.
+
+
+
+**Average Instruction Size**
+
+ The average number of bytes per instruction across all functions in the bitcode
+ file. This value is computed by dividing Total Instruction Size by Number Of
+ Instructions.
+
+
+
+**Maximum Type Slot Number**
+
+ The maximum value used for a type's slot number. Larger slot number values take
+ more bytes to encode.
+
+
+
+**Maximum Value Slot Number**
+
+ The maximum value used for a value's slot number. Larger slot number values take
+ more bytes to encode.
+
+
+
+**Bytes Per Value**
+
+ The average size of a Value definition (of any type). This is computed by
+ dividing File Size by the total number of values of any type.
+
+
+
+**Bytes Per Global**
+
+ The average size of a global definition (constants and global variables).
+
+
+
+**Bytes Per Function**
+
+ The average number of bytes per function definition. This is computed by
+ dividing Function Bytes by Number Of Functions.
+
+
+
+**# of VBR 32-bit Integers**
+
+ The total number of 32-bit integers encoded using the Variable Bit Rate
+ encoding scheme.
+
+
+
+**# of VBR 64-bit Integers**
+
+ The total number of 64-bit integers encoded using the Variable Bit Rate encoding
+ scheme.
+
+
+
+**# of VBR Compressed Bytes**
+
+ The total number of bytes consumed by the 32-bit and 64-bit integers that use
+ the Variable Bit Rate encoding scheme.
+
+
+
+**# of VBR Expanded Bytes**
+
+ The total number of bytes that would have been consumed by the 32-bit and 64-bit
+ integers had they not been compressed with the Variable Bit Rage encoding
+ scheme.
+
+
+
+**Bytes Saved With VBR**
+
+ The total number of bytes saved by using the Variable Bit Rate encoding scheme.
+ The percentage is relative to # of VBR Expanded Bytes.
+
+
+
+
+DETAILED OUTPUT DEFINITIONS
+---------------------------
+
+
+The following definitions occur only if the -nodetails option was not given.
+The detailed output provides additional information on a per-function basis.
+
+
+**Type**
+
+ The type signature of the function.
+
+
+
+**Byte Size**
+
+ The total number of bytes in the function's block.
+
+
+
+**Basic Blocks**
+
+ The number of basic blocks defined by the function.
+
+
+
+**Instructions**
+
+ The number of instructions defined by the function.
+
+
+
+**Long Instructions**
+
+ The number of instructions using the long instruction format in the function.
+
+
+
+**Operands**
+
+ The number of operands used by all instructions in the function.
+
+
+
+**Instruction Size**
+
+ The number of bytes consumed by instructions in the function.
+
+
+
+**Average Instruction Size**
+
+ The average number of bytes consumed by the instructions in the function. This
+ value is computed by dividing Instruction Size by Instructions.
+
+
+
+**Bytes Per Instruction**
+
+ The average number of bytes used by the function per instruction. This value is
+ computed by dividing Byte Size by Instructions. Note that this is not the same
+ as Average Instruction Size. It computes a number relative to the total function
+ size not just the size of the instruction list.
+
+
+
+**Number of VBR 32-bit Integers**
+
+ The total number of 32-bit integers found in this function (for any use).
+
+
+
+**Number of VBR 64-bit Integers**
+
+ The total number of 64-bit integers found in this function (for any use).
+
+
+
+**Number of VBR Compressed Bytes**
+
+ The total number of bytes in this function consumed by the 32-bit and 64-bit
+ integers that use the Variable Bit Rate encoding scheme.
+
+
+
+**Number of VBR Expanded Bytes**
+
+ The total number of bytes in this function that would have been consumed by
+ the 32-bit and 64-bit integers had they not been compressed with the Variable
+ Bit Rate encoding scheme.
+
+
+
+**Bytes Saved With VBR**
+
+ The total number of bytes saved in this function by using the Variable Bit
+ Rate encoding scheme. The percentage is relative to # of VBR Expanded Bytes.
+
+
+
+
+SEE ALSO
+--------
+
+
+llvm-dis|llvm-dis, `http://llvm.org/docs/BitCodeFormat.html <http://llvm.org/docs/BitCodeFormat.html>`_
diff --git a/docs/CommandGuide/llvm-build.rst b/docs/CommandGuide/llvm-build.rst
new file mode 100644
index 00000000000..f788f7c5a83
--- /dev/null
+++ b/docs/CommandGuide/llvm-build.rst
@@ -0,0 +1,102 @@
+llvm-build - LLVM Project Build Utility
+=======================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-build** [*options*]
+
+
+DESCRIPTION
+-----------
+
+
+**llvm-build** is a tool for working with LLVM projects that use the LLVMBuild
+system for describing their components.
+
+At heart, **llvm-build** is responsible for loading, verifying, and manipulating
+the project's component data. The tool is primarily designed for use in
+implementing build systems and tools which need access to the project structure
+information.
+
+
+OPTIONS
+-------
+
+
+
+**-h**, **--help**
+
+ Print the builtin program help.
+
+
+
+**--source-root**\ =\ *PATH*
+
+ If given, load the project at the given source root path. If this option is not
+ given, the location of the project sources will be inferred from the location of
+ the **llvm-build** script itself.
+
+
+
+**--print-tree**
+
+ Print the component tree for the project.
+
+
+
+**--write-library-table**
+
+ Write out the C++ fragment which defines the components, library names, and
+ required libraries. This C++ fragment is built into llvm-config|llvm-config
+ in order to provide clients with the list of required libraries for arbitrary
+ component combinations.
+
+
+
+**--write-llvmbuild**
+
+ Write out new *LLVMBuild.txt* files based on the loaded components. This is
+ useful for auto-upgrading the schema of the files. **llvm-build** will try to a
+ limited extent to preserve the comments which were written in the original
+ source file, although at this time it only preserves block comments that precede
+ the section names in the *LLVMBuild* files.
+
+
+
+**--write-cmake-fragment**
+
+ Write out the LLVMBuild in the form of a CMake fragment, so it can easily be
+ consumed by the CMake based build system. The exact contents and format of this
+ file are closely tied to how LLVMBuild is integrated with CMake, see LLVM's
+ top-level CMakeLists.txt.
+
+
+
+**--write-make-fragment**
+
+ Write out the LLVMBuild in the form of a Makefile fragment, so it can easily be
+ consumed by a Make based build system. The exact contents and format of this
+ file are closely tied to how LLVMBuild is integrated with the Makefiles, see
+ LLVM's Makefile.rules.
+
+
+
+**--llvmbuild-source-root**\ =\ *PATH*
+
+ If given, expect the *LLVMBuild* files for the project to be rooted at the
+ given path, instead of inside the source tree itself. This option is primarily
+ designed for use in conjunction with **--write-llvmbuild** to test changes to
+ *LLVMBuild* schema.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+**llvm-build** exits with 0 if operation was successful. Otherwise, it will exist
+with a non-zero value.
diff --git a/docs/CommandGuide/llvm-config.rst b/docs/CommandGuide/llvm-config.rst
new file mode 100644
index 00000000000..0ebb344c06a
--- /dev/null
+++ b/docs/CommandGuide/llvm-config.rst
@@ -0,0 +1,176 @@
+llvm-config - Print LLVM compilation options
+============================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-config** *option* [*components*...]
+
+
+DESCRIPTION
+-----------
+
+
+**llvm-config** makes it easier to build applications that use LLVM. It can
+print the compiler flags, linker flags and object libraries needed to link
+against LLVM.
+
+
+EXAMPLES
+--------
+
+
+To link against the JIT:
+
+
+.. code-block:: sh
+
+ g++ `llvm-config --cxxflags` -o HowToUseJIT.o -c HowToUseJIT.cpp
+ g++ `llvm-config --ldflags` -o HowToUseJIT HowToUseJIT.o \
+ `llvm-config --libs engine bcreader scalaropts`
+
+
+
+OPTIONS
+-------
+
+
+
+**--version**
+
+ Print the version number of LLVM.
+
+
+
+**-help**
+
+ Print a summary of **llvm-config** arguments.
+
+
+
+**--prefix**
+
+ Print the installation prefix for LLVM.
+
+
+
+**--src-root**
+
+ Print the source root from which LLVM was built.
+
+
+
+**--obj-root**
+
+ Print the object root used to build LLVM.
+
+
+
+**--bindir**
+
+ Print the installation directory for LLVM binaries.
+
+
+
+**--includedir**
+
+ Print the installation directory for LLVM headers.
+
+
+
+**--libdir**
+
+ Print the installation directory for LLVM libraries.
+
+
+
+**--cxxflags**
+
+ Print the C++ compiler flags needed to use LLVM headers.
+
+
+
+**--ldflags**
+
+ Print the flags needed to link against LLVM libraries.
+
+
+
+**--libs**
+
+ Print all the libraries needed to link against the specified LLVM
+ *components*, including any dependencies.
+
+
+
+**--libnames**
+
+ Similar to **--libs**, but prints the bare filenames of the libraries
+ without **-l** or pathnames. Useful for linking against a not-yet-installed
+ copy of LLVM.
+
+
+
+**--libfiles**
+
+ Similar to **--libs**, but print the full path to each library file. This is
+ useful when creating makefile dependencies, to ensure that a tool is relinked if
+ any library it uses changes.
+
+
+
+**--components**
+
+ Print all valid component names.
+
+
+
+**--targets-built**
+
+ Print the component names for all targets supported by this copy of LLVM.
+
+
+
+**--build-mode**
+
+ Print the build mode used when LLVM was built (e.g. Debug or Release)
+
+
+
+
+COMPONENTS
+----------
+
+
+To print a list of all available components, run **llvm-config
+--components**. In most cases, components correspond directly to LLVM
+libraries. Useful "virtual" components include:
+
+
+**all**
+
+ Includes all LLVM libaries. The default if no components are specified.
+
+
+
+**backend**
+
+ Includes either a native backend or the C backend.
+
+
+
+**engine**
+
+ Includes either a native JIT or the bitcode interpreter.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **llvm-config** succeeds, it will exit with 0. Otherwise, if an error
+occurs, it will exit with a non-zero value.
diff --git a/docs/CommandGuide/llvm-cov.rst b/docs/CommandGuide/llvm-cov.rst
new file mode 100644
index 00000000000..09275f6af71
--- /dev/null
+++ b/docs/CommandGuide/llvm-cov.rst
@@ -0,0 +1,51 @@
+llvm-cov - emit coverage information
+====================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-cov** [-gcno=filename] [-gcda=filename] [dump]
+
+
+DESCRIPTION
+-----------
+
+
+The experimental **llvm-cov** tool reads in description file generated by compiler
+and coverage data file generated by instrumented program. This program assumes
+that the description and data file uses same format as gcov files.
+
+
+OPTIONS
+-------
+
+
+
+**-gcno=filename]**
+
+ This option selects input description file generated by compiler while instrumenting
+ program.
+
+
+
+**-gcda=filename]**
+
+ This option selects coverage data file generated by instrumented compiler.
+
+
+
+**-dump**
+
+ This options enables output dump that is suitable for a developer to help debug
+ **llvm-cov** itself.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+**llvm-cov** returns 1 if it cannot read input files. Otherwise, it exits with zero.
diff --git a/docs/CommandGuide/llvm-diff.rst b/docs/CommandGuide/llvm-diff.rst
new file mode 100644
index 00000000000..991d4fece04
--- /dev/null
+++ b/docs/CommandGuide/llvm-diff.rst
@@ -0,0 +1,56 @@
+llvm-diff - LLVM structural 'diff'
+==================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-diff** [*options*] *module 1* *module 2* [*global name ...*]
+
+
+DESCRIPTION
+-----------
+
+
+**llvm-diff** compares the structure of two LLVM modules, primarily
+focusing on differences in function definitions. Insignificant
+differences, such as changes in the ordering of globals or in the
+names of local values, are ignored.
+
+An input module will be interpreted as an assembly file if its name
+ends in '.ll'; otherwise it will be read in as a bitcode file.
+
+If a list of global names is given, just the values with those names
+are compared; otherwise, all global values are compared, and
+diagnostics are produced for globals which only appear in one module
+or the other.
+
+**llvm-diff** compares two functions by comparing their basic blocks,
+beginning with the entry blocks. If the terminators seem to match,
+then the corresponding successors are compared; otherwise they are
+ignored. This algorithm is very sensitive to changes in control flow,
+which tend to stop any downstream changes from being detected.
+
+**llvm-diff** is intended as a debugging tool for writers of LLVM
+passes and frontends. It does not have a stable output format.
+
+
+EXIT STATUS
+-----------
+
+
+If **llvm-diff** finds no differences between the modules, it will exit
+with 0 and produce no output. Otherwise it will exit with a non-zero
+value.
+
+
+BUGS
+----
+
+
+Many important differences, like changes in linkage or function
+attributes, are not diagnosed.
+
+Changes in memory behavior (for example, coalescing loads) can cause
+massive detected differences in blocks.
diff --git a/docs/CommandGuide/llvm-dis.rst b/docs/CommandGuide/llvm-dis.rst
new file mode 100644
index 00000000000..85cdca85ecd
--- /dev/null
+++ b/docs/CommandGuide/llvm-dis.rst
@@ -0,0 +1,69 @@
+llvm-dis - LLVM disassembler
+============================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-dis** [*options*] [*filename*]
+
+
+DESCRIPTION
+-----------
+
+
+The **llvm-dis** command is the LLVM disassembler. It takes an LLVM
+bitcode file and converts it into human-readable LLVM assembly language.
+
+If filename is omitted or specified as ``-``, **llvm-dis** reads its
+input from standard input.
+
+If the input is being read from standard input, then **llvm-dis**
+will send its output to standard output by default. Otherwise, the
+output will be written to a file named after the input file, with
+a ``.ll`` suffix added (any existing ``.bc`` suffix will first be
+removed). You can override the choice of output file using the
+**-o** option.
+
+
+OPTIONS
+-------
+
+
+
+**-f**
+
+ Enable binary output on terminals. Normally, **llvm-dis** will refuse to
+ write raw bitcode output if the output stream is a terminal. With this option,
+ **llvm-dis** will write raw bitcode regardless of the output device.
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**-o** *filename*
+
+ Specify the output file name. If *filename* is -, then the output is sent
+ to standard output.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **llvm-dis** succeeds, it will exit with 0. Otherwise, if an error
+occurs, it will exit with a non-zero value.
+
+
+SEE ALSO
+--------
+
+
+llvm-as|llvm-as
diff --git a/docs/CommandGuide/llvm-extract.rst b/docs/CommandGuide/llvm-extract.rst
new file mode 100644
index 00000000000..d569e35729e
--- /dev/null
+++ b/docs/CommandGuide/llvm-extract.rst
@@ -0,0 +1,104 @@
+llvm-extract - extract a function from an LLVM module
+=====================================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-extract** [*options*] **--func** *function-name* [*filename*]
+
+
+DESCRIPTION
+-----------
+
+
+The **llvm-extract** command takes the name of a function and extracts it from
+the specified LLVM bitcode file. It is primarily used as a debugging tool to
+reduce test cases from larger programs that are triggering a bug.
+
+In addition to extracting the bitcode of the specified function,
+**llvm-extract** will also remove unreachable global variables, prototypes, and
+unused types.
+
+The **llvm-extract** command reads its input from standard input if filename is
+omitted or if filename is -. The output is always written to standard output,
+unless the **-o** option is specified (see below).
+
+
+OPTIONS
+-------
+
+
+
+**-f**
+
+ Enable binary output on terminals. Normally, **llvm-extract** will refuse to
+ write raw bitcode output if the output stream is a terminal. With this option,
+ **llvm-extract** will write raw bitcode regardless of the output device.
+
+
+
+**--func** *function-name*
+
+ Extract the function named *function-name* from the LLVM bitcode. May be
+ specified multiple times to extract multiple functions at once.
+
+
+
+**--rfunc** *function-regular-expr*
+
+ Extract the function(s) matching *function-regular-expr* from the LLVM bitcode.
+ All functions matching the regular expression will be extracted. May be
+ specified multiple times.
+
+
+
+**--glob** *global-name*
+
+ Extract the global variable named *global-name* from the LLVM bitcode. May be
+ specified multiple times to extract multiple global variables at once.
+
+
+
+**--rglob** *glob-regular-expr*
+
+ Extract the global variable(s) matching *global-regular-expr* from the LLVM
+ bitcode. All global variables matching the regular expression will be extracted.
+ May be specified multiple times.
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**-o** *filename*
+
+ Specify the output filename. If filename is "-" (the default), then
+ **llvm-extract** sends its output to standard output.
+
+
+
+**-S**
+
+ Write output in LLVM intermediate language (instead of bitcode).
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **llvm-extract** succeeds, it will exit with 0. Otherwise, if an error
+occurs, it will exit with a non-zero value.
+
+
+SEE ALSO
+--------
+
+
+bugpoint|bugpoint
diff --git a/docs/CommandGuide/llvm-link.rst b/docs/CommandGuide/llvm-link.rst
new file mode 100644
index 00000000000..63019d7cca7
--- /dev/null
+++ b/docs/CommandGuide/llvm-link.rst
@@ -0,0 +1,96 @@
+llvm-link - LLVM linker
+=======================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-link** [*options*] *filename ...*
+
+
+DESCRIPTION
+-----------
+
+
+**llvm-link** takes several LLVM bitcode files and links them together into a
+single LLVM bitcode file. It writes the output file to standard output, unless
+the **-o** option is used to specify a filename.
+
+**llvm-link** attempts to load the input files from the current directory. If
+that fails, it looks for each file in each of the directories specified by the
+**-L** options on the command line. The library search paths are global; each
+one is searched for every input file if necessary. The directories are searched
+in the order they were specified on the command line.
+
+
+OPTIONS
+-------
+
+
+
+**-L** *directory*
+
+ Add the specified *directory* to the library search path. When looking for
+ libraries, **llvm-link** will look in path name for libraries. This option can be
+ specified multiple times; **llvm-link** will search inside these directories in
+ the order in which they were specified on the command line.
+
+
+
+**-f**
+
+ Enable binary output on terminals. Normally, **llvm-link** will refuse to
+ write raw bitcode output if the output stream is a terminal. With this option,
+ **llvm-link** will write raw bitcode regardless of the output device.
+
+
+
+**-o** *filename*
+
+ Specify the output file name. If *filename* is ``-``, then **llvm-link** will
+ write its output to standard output.
+
+
+
+**-S**
+
+ Write output in LLVM intermediate language (instead of bitcode).
+
+
+
+**-d**
+
+ If specified, **llvm-link** prints a human-readable version of the output
+ bitcode file to standard error.
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**-v**
+
+ Verbose mode. Print information about what **llvm-link** is doing. This
+ typically includes a message for each bitcode file linked in and for each
+ library found.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **llvm-link** succeeds, it will exit with 0. Otherwise, if an error
+occurs, it will exit with a non-zero value.
+
+
+SEE ALSO
+--------
+
+
+gccld|gccld
diff --git a/docs/CommandGuide/llvm-nm.rst b/docs/CommandGuide/llvm-nm.rst
new file mode 100644
index 00000000000..cbc7af20759
--- /dev/null
+++ b/docs/CommandGuide/llvm-nm.rst
@@ -0,0 +1,189 @@
+llvm-nm - list LLVM bitcode and object file's symbol table
+==========================================================
+
+
+SYNOPSIS
+--------
+
+
+:program:`llvm-nm` [*options*] [*filenames...*]
+
+
+DESCRIPTION
+-----------
+
+
+The :program:`llvm-nm` utility lists the names of symbols from the LLVM bitcode
+files, object files, or :program:`ar` archives containing them, named on the
+command line. Each symbol is listed along with some simple information about its
+provenance. If no file name is specified, or *-* is used as a file name,
+:program:`llvm-nm` will process a file on its standard input stream.
+
+:program:`llvm-nm`'s default output format is the traditional BSD :program:`nm`
+output format. Each such output record consists of an (optional) 8-digit
+hexadecimal address, followed by a type code character, followed by a name, for
+each symbol. One record is printed per line; fields are separated by spaces.
+When the address is omitted, it is replaced by 8 spaces.
+
+Type code characters currently supported, and their meanings, are as follows:
+
+
+U
+
+ Named object is referenced but undefined in this bitcode file
+
+
+
+C
+
+ Common (multiple definitions link together into one def)
+
+
+
+W
+
+ Weak reference (multiple definitions link together into zero or one definitions)
+
+
+
+t
+
+ Local function (text) object
+
+
+
+T
+
+ Global function (text) object
+
+
+
+d
+
+ Local data object
+
+
+
+D
+
+ Global data object
+
+
+
+?
+
+ Something unrecognizable
+
+
+
+Because LLVM bitcode files typically contain objects that are not considered to
+have addresses until they are linked into an executable image or dynamically
+compiled "just-in-time", :program:`llvm-nm` does not print an address for any
+symbol in a LLVM bitcode file, even symbols which are defined in the bitcode
+file.
+
+
+OPTIONS
+-------
+
+
+.. program:: llvm-nm
+
+
+.. option:: -B (default)
+
+ Use BSD output format. Alias for :option:`--format=bsd`.
+
+
+.. option:: -P
+
+ Use POSIX.2 output format. Alias for :option:`--format=posix`.
+
+
+.. option:: --debug-syms, -a
+
+ Show all symbols, even debugger only.
+
+
+.. option:: --defined-only
+
+ Print only symbols defined in this file (as opposed to
+ symbols which may be referenced by objects in this file, but not
+ defined in this file.)
+
+
+.. option:: --dynamic, -D
+
+ Display dynamic symbols instead of normal symbols.
+
+
+.. option:: --extern-only, -g
+
+ Print only symbols whose definitions are external; that is, accessible
+ from other files.
+
+
+.. option:: --format=format, -f format
+
+ Select an output format; *format* may be *sysv*, *posix*, or *bsd*. The default
+ is *bsd*.
+
+
+.. option:: -help
+
+ Print a summary of command-line options and their meanings.
+
+
+.. option:: --no-sort, -p
+
+ Shows symbols in order encountered.
+
+
+.. option:: --numeric-sort, -n, -v
+
+ Sort symbols by address.
+
+
+.. option:: --print-file-name, -A, -o
+
+ Precede each symbol with the file it came from.
+
+
+.. option:: --print-size, -S
+
+ Show symbol size instead of address.
+
+
+.. option:: --size-sort
+
+ Sort symbols by size.
+
+
+.. option:: --undefined-only, -u
+
+ Print only symbols referenced but not defined in this file.
+
+
+BUGS
+----
+
+
+ * :program:`llvm-nm` cannot demangle C++ mangled names, like GNU :program:`nm`
+ can.
+
+ * :program:`llvm-nm` does not support the full set of arguments that GNU
+ :program:`nm` does.
+
+
+EXIT STATUS
+-----------
+
+
+:program:`llvm-nm` exits with an exit code of zero.
+
+
+SEE ALSO
+--------
+
+
+llvm-dis|llvm-dis, ar(1), nm(1)
diff --git a/docs/CommandGuide/llvm-prof.rst b/docs/CommandGuide/llvm-prof.rst
new file mode 100644
index 00000000000..e8d0b19ca94
--- /dev/null
+++ b/docs/CommandGuide/llvm-prof.rst
@@ -0,0 +1,63 @@
+llvm-prof - print execution profile of LLVM program
+===================================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-prof** [*options*] [*bitcode file*] [*llvmprof.out*]
+
+
+DESCRIPTION
+-----------
+
+
+The **llvm-prof** tool reads in an *llvmprof.out* file (which can
+optionally use a specific file with the third program argument), a bitcode file
+for the program, and produces a human readable report, suitable for determining
+where the program hotspots are.
+
+This program is often used in conjunction with the *utils/profile.pl*
+script. This script automatically instruments a program, runs it with the JIT,
+then runs **llvm-prof** to format a report. To get more information about
+*utils/profile.pl*, execute it with the **-help** option.
+
+
+OPTIONS
+-------
+
+
+
+**--annotated-llvm** or **-A**
+
+ In addition to the normal report printed, print out the code for the
+ program, annotated with execution frequency information. This can be
+ particularly useful when trying to visualize how frequently basic blocks
+ are executed. This is most useful with basic block profiling
+ information or better.
+
+
+
+**--print-all-code**
+
+ Using this option enables the **--annotated-llvm** option, but it
+ prints the entire module, instead of just the most commonly executed
+ functions.
+
+
+
+**--time-passes**
+
+ Record the amount of time needed for each pass and print it to standard
+ error.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+**llvm-prof** returns 1 if it cannot load the bitcode file or the profile
+information. Otherwise, it exits with zero.
diff --git a/docs/CommandGuide/llvm-ranlib.rst b/docs/CommandGuide/llvm-ranlib.rst
new file mode 100644
index 00000000000..6658818f41e
--- /dev/null
+++ b/docs/CommandGuide/llvm-ranlib.rst
@@ -0,0 +1,61 @@
+llvm-ranlib - Generate index for LLVM archive
+=============================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-ranlib** [--version] [-help] <archive-file>
+
+
+DESCRIPTION
+-----------
+
+
+The **llvm-ranlib** command is similar to the common Unix utility, ``ranlib``. It
+adds or updates the symbol table in an LLVM archive file. Note that using the
+**llvm-ar** modifier *s* is usually more efficient than running **llvm-ranlib**
+which is only provided only for completness and compatibility. Unlike other
+implementations of ``ranlib``, **llvm-ranlib** indexes LLVM bitcode files, not
+native object modules. You can list the contents of the symbol table with the
+``llvm-nm -s`` command.
+
+
+OPTIONS
+-------
+
+
+
+*archive-file*
+
+ Specifies the archive-file to which the symbol table is added or updated.
+
+
+
+*--version*
+
+ Print the version of **llvm-ranlib** and exit without building a symbol table.
+
+
+
+*-help*
+
+ Print usage help for **llvm-ranlib** and exit without building a symbol table.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **llvm-ranlib** succeeds, it will exit with 0. If an error occurs, a non-zero
+exit code will be returned.
+
+
+SEE ALSO
+--------
+
+
+llvm-ar|llvm-ar, ranlib(1)
diff --git a/docs/CommandGuide/llvm-stress.rst b/docs/CommandGuide/llvm-stress.rst
new file mode 100644
index 00000000000..44aa32c7557
--- /dev/null
+++ b/docs/CommandGuide/llvm-stress.rst
@@ -0,0 +1,48 @@
+llvm-stress - generate random .ll files
+=======================================
+
+
+SYNOPSIS
+--------
+
+
+**llvm-stress** [-size=filesize] [-seed=initialseed] [-o=outfile]
+
+
+DESCRIPTION
+-----------
+
+
+The **llvm-stress** tool is used to generate random .ll files that can be used to
+test different components of LLVM.
+
+
+OPTIONS
+-------
+
+
+
+**-o** *filename*
+
+ Specify the output filename.
+
+
+
+**-size** *size*
+
+ Specify the size of the generated .ll file.
+
+
+
+**-seed** *seed*
+
+ Specify the seed to be used for the randomly generated instructions.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+**llvm-stress** returns 0.
diff --git a/docs/CommandGuide/opt.rst b/docs/CommandGuide/opt.rst
new file mode 100644
index 00000000000..72f19034c9e
--- /dev/null
+++ b/docs/CommandGuide/opt.rst
@@ -0,0 +1,183 @@
+opt - LLVM optimizer
+====================
+
+
+SYNOPSIS
+--------
+
+
+**opt** [*options*] [*filename*]
+
+
+DESCRIPTION
+-----------
+
+
+The **opt** command is the modular LLVM optimizer and analyzer. It takes LLVM
+source files as input, runs the specified optimizations or analyses on it, and then
+outputs the optimized file or the analysis results. The function of
+**opt** depends on whether the **-analyze** option is given.
+
+When **-analyze** is specified, **opt** performs various analyses of the input
+source. It will usually print the results on standard output, but in a few
+cases, it will print output to standard error or generate a file with the
+analysis output, which is usually done when the output is meant for another
+program.
+
+While **-analyze** is *not* given, **opt** attempts to produce an optimized
+output file. The optimizations available via **opt** depend upon what
+libraries were linked into it as well as any additional libraries that have
+been loaded with the **-load** option. Use the **-help** option to determine
+what optimizations you can use.
+
+If *filename* is omitted from the command line or is *-*, **opt** reads its
+input from standard input. Inputs can be in either the LLVM assembly language
+format (.ll) or the LLVM bitcode format (.bc).
+
+If an output filename is not specified with the **-o** option, **opt**
+writes its output to the standard output.
+
+
+OPTIONS
+-------
+
+
+
+**-f**
+
+ Enable binary output on terminals. Normally, **opt** will refuse to
+ write raw bitcode output if the output stream is a terminal. With this option,
+ **opt** will write raw bitcode regardless of the output device.
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**-o** *filename*
+
+ Specify the output filename.
+
+
+
+**-S**
+
+ Write output in LLVM intermediate language (instead of bitcode).
+
+
+
+**-{passname}**
+
+ **opt** provides the ability to run any of LLVM's optimization or analysis passes
+ in any order. The **-help** option lists all the passes available. The order in
+ which the options occur on the command line are the order in which they are
+ executed (within pass constraints).
+
+
+
+**-std-compile-opts**
+
+ This is short hand for a standard list of *compile time optimization* passes.
+ This is typically used to optimize the output from the llvm-gcc front end. It
+ might be useful for other front end compilers as well. To discover the full set
+ of options available, use the following command:
+
+
+ .. code-block:: sh
+
+ llvm-as < /dev/null | opt -std-compile-opts -disable-output -debug-pass=Arguments
+
+
+
+
+**-disable-inlining**
+
+ This option is only meaningful when **-std-compile-opts** is given. It simply
+ removes the inlining pass from the standard list.
+
+
+
+**-disable-opt**
+
+ This option is only meaningful when **-std-compile-opts** is given. It disables
+ most, but not all, of the **-std-compile-opts**. The ones that remain are
+ **-verify**, **-lower-setjmp**, and **-funcresolve**.
+
+
+
+**-strip-debug**
+
+ This option causes opt to strip debug information from the module before
+ applying other optimizations. It is essentially the same as **-strip** but it
+ ensures that stripping of debug information is done first.
+
+
+
+**-verify-each**
+
+ This option causes opt to add a verify pass after every pass otherwise specified
+ on the command line (including **-verify**). This is useful for cases where it
+ is suspected that a pass is creating an invalid module but it is not clear which
+ pass is doing it. The combination of **-std-compile-opts** and **-verify-each**
+ can quickly track down this kind of problem.
+
+
+
+**-profile-info-file** *filename*
+
+ Specify the name of the file loaded by the -profile-loader option.
+
+
+
+**-stats**
+
+ Print statistics.
+
+
+
+**-time-passes**
+
+ Record the amount of time needed for each pass and print it to standard
+ error.
+
+
+
+**-debug**
+
+ If this is a debug build, this option will enable debug printouts
+ from passes which use the *DEBUG()* macro. See the **LLVM Programmer's
+ Manual**, section *#DEBUG* for more information.
+
+
+
+**-load**\ =\ *plugin*
+
+ Load the dynamic object *plugin*. This object should register new optimization
+ or analysis passes. Once loaded, the object will add new command line options to
+ enable various optimizations or analyses. To see the new complete list of
+ optimizations, use the **-help** and **-load** options together. For example:
+
+
+ .. code-block:: sh
+
+ opt -load=plugin.so -help
+
+
+
+
+**-p**
+
+ Print module after each transformation.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **opt** succeeds, it will exit with 0. Otherwise, if an error
+occurs, it will exit with a non-zero value.
diff --git a/docs/CommandGuide/tblgen.rst b/docs/CommandGuide/tblgen.rst
new file mode 100644
index 00000000000..2d191676d9f
--- /dev/null
+++ b/docs/CommandGuide/tblgen.rst
@@ -0,0 +1,186 @@
+tblgen - Target Description To C++ Code Generator
+=================================================
+
+
+SYNOPSIS
+--------
+
+
+**tblgen** [*options*] [*filename*]
+
+
+DESCRIPTION
+-----------
+
+
+**tblgen** translates from target description (.td) files into C++ code that can
+be included in the definition of an LLVM target library. Most users of LLVM will
+not need to use this program. It is only for assisting with writing an LLVM
+target backend.
+
+The input and output of **tblgen** is beyond the scope of this short
+introduction. Please see the *CodeGeneration* page in the LLVM documentation.
+
+The *filename* argument specifies the name of a Target Description (.td) file
+to read as input.
+
+
+OPTIONS
+-------
+
+
+
+**-help**
+
+ Print a summary of command line options.
+
+
+
+**-o** *filename*
+
+ Specify the output file name. If *filename* is ``-``, then **tblgen**
+ sends its output to standard output.
+
+
+
+**-I** *directory*
+
+ Specify where to find other target description files for inclusion. The
+ *directory* value should be a full or partial path to a directory that contains
+ target description files.
+
+
+
+**-asmparsernum** *N*
+
+ Make -gen-asm-parser emit assembly writer number *N*.
+
+
+
+**-asmwriternum** *N*
+
+ Make -gen-asm-writer emit assembly writer number *N*.
+
+
+
+**-class** *class Name*
+
+ Print the enumeration list for this class.
+
+
+
+**-print-records**
+
+ Print all records to standard output (default).
+
+
+
+**-print-enums**
+
+ Print enumeration values for a class
+
+
+
+**-print-sets**
+
+ Print expanded sets for testing DAG exprs.
+
+
+
+**-gen-emitter**
+
+ Generate machine code emitter.
+
+
+
+**-gen-register-info**
+
+ Generate registers and register classes info.
+
+
+
+**-gen-instr-info**
+
+ Generate instruction descriptions.
+
+
+
+**-gen-asm-writer**
+
+ Generate the assembly writer.
+
+
+
+**-gen-disassembler**
+
+ Generate disassembler.
+
+
+
+**-gen-pseudo-lowering**
+
+ Generate pseudo instruction lowering.
+
+
+
+**-gen-dag-isel**
+
+ Generate a DAG (Directed Acycle Graph) instruction selector.
+
+
+
+**-gen-asm-matcher**
+
+ Generate assembly instruction matcher.
+
+
+
+**-gen-dfa-packetizer**
+
+ Generate DFA Packetizer for VLIW targets.
+
+
+
+**-gen-fast-isel**
+
+ Generate a "fast" instruction selector.
+
+
+
+**-gen-subtarget**
+
+ Generate subtarget enumerations.
+
+
+
+**-gen-intrinsic**
+
+ Generate intrinsic information.
+
+
+
+**-gen-tgt-intrinsic**
+
+ Generate target intrinsic information.
+
+
+
+**-gen-enhanced-disassembly-info**
+
+ Generate enhanced disassembly info.
+
+
+
+**-version**
+
+ Show the version number of this program.
+
+
+
+
+EXIT STATUS
+-----------
+
+
+If **tblgen** succeeds, it will exit with 0. Otherwise, if an error
+occurs, it will exit with a non-zero value.
diff --git a/docs/CommandLine.rst b/docs/CommandLine.rst
new file mode 100644
index 00000000000..302f5a4cf59
--- /dev/null
+++ b/docs/CommandLine.rst
@@ -0,0 +1,1615 @@
+.. _commandline:
+
+==============================
+CommandLine 2.0 Library Manual
+==============================
+
+Introduction
+============
+
+This document describes the CommandLine argument processing library. It will
+show you how to use it, and what it can do. The CommandLine library uses a
+declarative approach to specifying the command line options that your program
+takes. By default, these options declarations implicitly hold the value parsed
+for the option declared (of course this `can be changed`_).
+
+Although there are a **lot** of command line argument parsing libraries out
+there in many different languages, none of them fit well with what I needed. By
+looking at the features and problems of other libraries, I designed the
+CommandLine library to have the following features:
+
+#. Speed: The CommandLine library is very quick and uses little resources. The
+ parsing time of the library is directly proportional to the number of
+ arguments parsed, not the number of options recognized. Additionally,
+ command line argument values are captured transparently into user defined
+ global variables, which can be accessed like any other variable (and with the
+ same performance).
+
+#. Type Safe: As a user of CommandLine, you don't have to worry about
+ remembering the type of arguments that you want (is it an int? a string? a
+ bool? an enum?) and keep casting it around. Not only does this help prevent
+ error prone constructs, it also leads to dramatically cleaner source code.
+
+#. No subclasses required: To use CommandLine, you instantiate variables that
+ correspond to the arguments that you would like to capture, you don't
+ subclass a parser. This means that you don't have to write **any**
+ boilerplate code.
+
+#. Globally accessible: Libraries can specify command line arguments that are
+ automatically enabled in any tool that links to the library. This is
+ possible because the application doesn't have to keep a list of arguments to
+ pass to the parser. This also makes supporting `dynamically loaded options`_
+ trivial.
+
+#. Cleaner: CommandLine supports enum and other types directly, meaning that
+ there is less error and more security built into the library. You don't have
+ to worry about whether your integral command line argument accidentally got
+ assigned a value that is not valid for your enum type.
+
+#. Powerful: The CommandLine library supports many different types of arguments,
+ from simple `boolean flags`_ to `scalars arguments`_ (`strings`_,
+ `integers`_, `enums`_, `doubles`_), to `lists of arguments`_. This is
+ possible because CommandLine is...
+
+#. Extensible: It is very simple to add a new argument type to CommandLine.
+ Simply specify the parser that you want to use with the command line option
+ when you declare it. `Custom parsers`_ are no problem.
+
+#. Labor Saving: The CommandLine library cuts down on the amount of grunt work
+ that you, the user, have to do. For example, it automatically provides a
+ ``-help`` option that shows the available command line options for your tool.
+ Additionally, it does most of the basic correctness checking for you.
+
+#. Capable: The CommandLine library can handle lots of different forms of
+ options often found in real programs. For example, `positional`_ arguments,
+ ``ls`` style `grouping`_ options (to allow processing '``ls -lad``'
+ naturally), ``ld`` style `prefix`_ options (to parse '``-lmalloc
+ -L/usr/lib``'), and interpreter style options.
+
+This document will hopefully let you jump in and start using CommandLine in your
+utility quickly and painlessly. Additionally it should be a simple reference
+manual to figure out how stuff works. If it is failing in some area (or you
+want an extension to the library), nag the author, `Chris
+Lattner <mailto:sabre@nondot.org>`_.
+
+Quick Start Guide
+=================
+
+This section of the manual runs through a simple CommandLine'ification of a
+basic compiler tool. This is intended to show you how to jump into using the
+CommandLine library in your own program, and show you some of the cool things it
+can do.
+
+To start out, you need to include the CommandLine header file into your program:
+
+.. code-block:: c++
+
+ #include "llvm/Support/CommandLine.h"
+
+Additionally, you need to add this as the first line of your main program:
+
+.. code-block:: c++
+
+ int main(int argc, char **argv) {
+ cl::ParseCommandLineOptions(argc, argv);
+ ...
+ }
+
+... which actually parses the arguments and fills in the variable declarations.
+
+Now that you are ready to support command line arguments, we need to tell the
+system which ones we want, and what type of arguments they are. The CommandLine
+library uses a declarative syntax to model command line arguments with the
+global variable declarations that capture the parsed values. This means that
+for every command line option that you would like to support, there should be a
+global variable declaration to capture the result. For example, in a compiler,
+we would like to support the Unix-standard '``-o <filename>``' option to specify
+where to put the output. With the CommandLine library, this is represented like
+this:
+
+.. _scalars arguments:
+.. _here:
+
+.. code-block:: c++
+
+ cl::opt<string> OutputFilename("o", cl::desc("Specify output filename"), cl::value_desc("filename"));
+
+This declares a global variable "``OutputFilename``" that is used to capture the
+result of the "``o``" argument (first parameter). We specify that this is a
+simple scalar option by using the "``cl::opt``" template (as opposed to the
+"``cl::list``" template), and tell the CommandLine library that the data
+type that we are parsing is a string.
+
+The second and third parameters (which are optional) are used to specify what to
+output for the "``-help``" option. In this case, we get a line that looks like
+this:
+
+::
+
+ USAGE: compiler [options]
+
+ OPTIONS:
+ -help - display available options (-help-hidden for more)
+ -o <filename> - Specify output filename
+
+Because we specified that the command line option should parse using the
+``string`` data type, the variable declared is automatically usable as a real
+string in all contexts that a normal C++ string object may be used. For
+example:
+
+.. code-block:: c++
+
+ ...
+ std::ofstream Output(OutputFilename.c_str());
+ if (Output.good()) ...
+ ...
+
+There are many different options that you can use to customize the command line
+option handling library, but the above example shows the general interface to
+these options. The options can be specified in any order, and are specified
+with helper functions like `cl::desc(...)`_, so there are no positional
+dependencies to remember. The available options are discussed in detail in the
+`Reference Guide`_.
+
+Continuing the example, we would like to have our compiler take an input
+filename as well as an output filename, but we do not want the input filename to
+be specified with a hyphen (ie, not ``-filename.c``). To support this style of
+argument, the CommandLine library allows for `positional`_ arguments to be
+specified for the program. These positional arguments are filled with command
+line parameters that are not in option form. We use this feature like this:
+
+.. code-block:: c++
+
+
+ cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
+
+This declaration indicates that the first positional argument should be treated
+as the input filename. Here we use the `cl::init`_ option to specify an initial
+value for the command line option, which is used if the option is not specified
+(if you do not specify a `cl::init`_ modifier for an option, then the default
+constructor for the data type is used to initialize the value). Command line
+options default to being optional, so if we would like to require that the user
+always specify an input filename, we would add the `cl::Required`_ flag, and we
+could eliminate the `cl::init`_ modifier, like this:
+
+.. code-block:: c++
+
+ cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::Required);
+
+Again, the CommandLine library does not require the options to be specified in
+any particular order, so the above declaration is equivalent to:
+
+.. code-block:: c++
+
+ cl::opt<string> InputFilename(cl::Positional, cl::Required, cl::desc("<input file>"));
+
+By simply adding the `cl::Required`_ flag, the CommandLine library will
+automatically issue an error if the argument is not specified, which shifts all
+of the command line option verification code out of your application into the
+library. This is just one example of how using flags can alter the default
+behaviour of the library, on a per-option basis. By adding one of the
+declarations above, the ``-help`` option synopsis is now extended to:
+
+::
+
+ USAGE: compiler [options] <input file>
+
+ OPTIONS:
+ -help - display available options (-help-hidden for more)
+ -o <filename> - Specify output filename
+
+... indicating that an input filename is expected.
+
+Boolean Arguments
+-----------------
+
+In addition to input and output filenames, we would like the compiler example to
+support three boolean flags: "``-f``" to force writing binary output to a
+terminal, "``--quiet``" to enable quiet mode, and "``-q``" for backwards
+compatibility with some of our users. We can support these by declaring options
+of boolean type like this:
+
+.. code-block:: c++
+
+ cl::opt<bool> Force ("f", cl::desc("Enable binary output on terminals"));
+ cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
+ cl::opt<bool> Quiet2("q", cl::desc("Don't print informational messages"), cl::Hidden);
+
+This does what you would expect: it declares three boolean variables
+("``Force``", "``Quiet``", and "``Quiet2``") to recognize these options. Note
+that the "``-q``" option is specified with the "`cl::Hidden`_" flag. This
+modifier prevents it from being shown by the standard "``-help``" output (note
+that it is still shown in the "``-help-hidden``" output).
+
+The CommandLine library uses a `different parser`_ for different data types.
+For example, in the string case, the argument passed to the option is copied
+literally into the content of the string variable... we obviously cannot do that
+in the boolean case, however, so we must use a smarter parser. In the case of
+the boolean parser, it allows no options (in which case it assigns the value of
+true to the variable), or it allows the values "``true``" or "``false``" to be
+specified, allowing any of the following inputs:
+
+::
+
+ compiler -f # No value, 'Force' == true
+ compiler -f=true # Value specified, 'Force' == true
+ compiler -f=TRUE # Value specified, 'Force' == true
+ compiler -f=FALSE # Value specified, 'Force' == false
+
+... you get the idea. The `bool parser`_ just turns the string values into
+boolean values, and rejects things like '``compiler -f=foo``'. Similarly, the
+`float`_, `double`_, and `int`_ parsers work like you would expect, using the
+'``strtol``' and '``strtod``' C library calls to parse the string value into the
+specified data type.
+
+With the declarations above, "``compiler -help``" emits this:
+
+::
+
+ USAGE: compiler [options] <input file>
+
+ OPTIONS:
+ -f - Enable binary output on terminals
+ -o - Override output filename
+ -quiet - Don't print informational messages
+ -help - display available options (-help-hidden for more)
+
+and "``compiler -help-hidden``" prints this:
+
+::
+
+ USAGE: compiler [options] <input file>
+
+ OPTIONS:
+ -f - Enable binary output on terminals
+ -o - Override output filename
+ -q - Don't print informational messages
+ -quiet - Don't print informational messages
+ -help - display available options (-help-hidden for more)
+
+This brief example has shown you how to use the '`cl::opt`_' class to parse
+simple scalar command line arguments. In addition to simple scalar arguments,
+the CommandLine library also provides primitives to support CommandLine option
+`aliases`_, and `lists`_ of options.
+
+.. _aliases:
+
+Argument Aliases
+----------------
+
+So far, the example works well, except for the fact that we need to check the
+quiet condition like this now:
+
+.. code-block:: c++
+
+ ...
+ if (!Quiet && !Quiet2) printInformationalMessage(...);
+ ...
+
+... which is a real pain! Instead of defining two values for the same
+condition, we can use the "`cl::alias`_" class to make the "``-q``" option an
+**alias** for the "``-quiet``" option, instead of providing a value itself:
+
+.. code-block:: c++
+
+ cl::opt<bool> Force ("f", cl::desc("Overwrite output files"));
+ cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
+ cl::alias QuietA("q", cl::desc("Alias for -quiet"), cl::aliasopt(Quiet));
+
+The third line (which is the only one we modified from above) defines a "``-q``"
+alias that updates the "``Quiet``" variable (as specified by the `cl::aliasopt`_
+modifier) whenever it is specified. Because aliases do not hold state, the only
+thing the program has to query is the ``Quiet`` variable now. Another nice
+feature of aliases is that they automatically hide themselves from the ``-help``
+output (although, again, they are still visible in the ``-help-hidden output``).
+
+Now the application code can simply use:
+
+.. code-block:: c++
+
+ ...
+ if (!Quiet) printInformationalMessage(...);
+ ...
+
+... which is much nicer! The "`cl::alias`_" can be used to specify an
+alternative name for any variable type, and has many uses.
+
+.. _unnamed alternatives using the generic parser:
+
+Selecting an alternative from a set of possibilities
+----------------------------------------------------
+
+So far we have seen how the CommandLine library handles builtin types like
+``std::string``, ``bool`` and ``int``, but how does it handle things it doesn't
+know about, like enums or '``int*``'s?
+
+The answer is that it uses a table-driven generic parser (unless you specify
+your own parser, as described in the `Extension Guide`_). This parser maps
+literal strings to whatever type is required, and requires you to tell it what
+this mapping should be.
+
+Let's say that we would like to add four optimization levels to our optimizer,
+using the standard flags "``-g``", "``-O0``", "``-O1``", and "``-O2``". We
+could easily implement this with boolean options like above, but there are
+several problems with this strategy:
+
+#. A user could specify more than one of the options at a time, for example,
+ "``compiler -O3 -O2``". The CommandLine library would not be able to catch
+ this erroneous input for us.
+
+#. We would have to test 4 different variables to see which ones are set.
+
+#. This doesn't map to the numeric levels that we want... so we cannot easily
+ see if some level >= "``-O1``" is enabled.
+
+To cope with these problems, we can use an enum value, and have the CommandLine
+library fill it in with the appropriate level directly, which is used like this:
+
+.. code-block:: c++
+
+ enum OptLevel {
+ g, O1, O2, O3
+ };
+
+ cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
+ cl::values(
+ clEnumVal(g , "No optimizations, enable debugging"),
+ clEnumVal(O1, "Enable trivial optimizations"),
+ clEnumVal(O2, "Enable default optimizations"),
+ clEnumVal(O3, "Enable expensive optimizations"),
+ clEnumValEnd));
+
+ ...
+ if (OptimizationLevel >= O2) doPartialRedundancyElimination(...);
+ ...
+
+This declaration defines a variable "``OptimizationLevel``" of the
+"``OptLevel``" enum type. This variable can be assigned any of the values that
+are listed in the declaration (Note that the declaration list must be terminated
+with the "``clEnumValEnd``" argument!). The CommandLine library enforces that
+the user can only specify one of the options, and it ensure that only valid enum
+values can be specified. The "``clEnumVal``" macros ensure that the command
+line arguments matched the enum values. With this option added, our help output
+now is:
+
+::
+
+ USAGE: compiler [options] <input file>
+
+ OPTIONS:
+ Choose optimization level:
+ -g - No optimizations, enable debugging
+ -O1 - Enable trivial optimizations
+ -O2 - Enable default optimizations
+ -O3 - Enable expensive optimizations
+ -f - Enable binary output on terminals
+ -help - display available options (-help-hidden for more)
+ -o <filename> - Specify output filename
+ -quiet - Don't print informational messages
+
+In this case, it is sort of awkward that flag names correspond directly to enum
+names, because we probably don't want a enum definition named "``g``" in our
+program. Because of this, we can alternatively write this example like this:
+
+.. code-block:: c++
+
+ enum OptLevel {
+ Debug, O1, O2, O3
+ };
+
+ cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
+ cl::values(
+ clEnumValN(Debug, "g", "No optimizations, enable debugging"),
+ clEnumVal(O1 , "Enable trivial optimizations"),
+ clEnumVal(O2 , "Enable default optimizations"),
+ clEnumVal(O3 , "Enable expensive optimizations"),
+ clEnumValEnd));
+
+ ...
+ if (OptimizationLevel == Debug) outputDebugInfo(...);
+ ...
+
+By using the "``clEnumValN``" macro instead of "``clEnumVal``", we can directly
+specify the name that the flag should get. In general a direct mapping is nice,
+but sometimes you can't or don't want to preserve the mapping, which is when you
+would use it.
+
+Named Alternatives
+------------------
+
+Another useful argument form is a named alternative style. We shall use this
+style in our compiler to specify different debug levels that can be used.
+Instead of each debug level being its own switch, we want to support the
+following options, of which only one can be specified at a time:
+"``--debug-level=none``", "``--debug-level=quick``",
+"``--debug-level=detailed``". To do this, we use the exact same format as our
+optimization level flags, but we also specify an option name. For this case,
+the code looks like this:
+
+.. code-block:: c++
+
+ enum DebugLev {
+ nodebuginfo, quick, detailed
+ };
+
+ // Enable Debug Options to be specified on the command line
+ cl::opt<DebugLev> DebugLevel("debug_level", cl::desc("Set the debugging level:"),
+ cl::values(
+ clEnumValN(nodebuginfo, "none", "disable debug information"),
+ clEnumVal(quick, "enable quick debug information"),
+ clEnumVal(detailed, "enable detailed debug information"),
+ clEnumValEnd));
+
+This definition defines an enumerated command line variable of type "``enum
+DebugLev``", which works exactly the same way as before. The difference here is
+just the interface exposed to the user of your program and the help output by
+the "``-help``" option:
+
+::
+
+ USAGE: compiler [options] <input file>
+
+ OPTIONS:
+ Choose optimization level:
+ -g - No optimizations, enable debugging
+ -O1 - Enable trivial optimizations
+ -O2 - Enable default optimizations
+ -O3 - Enable expensive optimizations
+ -debug_level - Set the debugging level:
+ =none - disable debug information
+ =quick - enable quick debug information
+ =detailed - enable detailed debug information
+ -f - Enable binary output on terminals
+ -help - display available options (-help-hidden for more)
+ -o <filename> - Specify output filename
+ -quiet - Don't print informational messages
+
+Again, the only structural difference between the debug level declaration and
+the optimization level declaration is that the debug level declaration includes
+an option name (``"debug_level"``), which automatically changes how the library
+processes the argument. The CommandLine library supports both forms so that you
+can choose the form most appropriate for your application.
+
+.. _lists:
+
+Parsing a list of options
+-------------------------
+
+Now that we have the standard run-of-the-mill argument types out of the way,
+lets get a little wild and crazy. Lets say that we want our optimizer to accept
+a **list** of optimizations to perform, allowing duplicates. For example, we
+might want to run: "``compiler -dce -constprop -inline -dce -strip``". In this
+case, the order of the arguments and the number of appearances is very
+important. This is what the "``cl::list``" template is for. First, start by
+defining an enum of the optimizations that you would like to perform:
+
+.. code-block:: c++
+
+ enum Opts {
+ // 'inline' is a C++ keyword, so name it 'inlining'
+ dce, constprop, inlining, strip
+ };
+
+Then define your "``cl::list``" variable:
+
+.. code-block:: c++
+
+ cl::list<Opts> OptimizationList(cl::desc("Available Optimizations:"),
+ cl::values(
+ clEnumVal(dce , "Dead Code Elimination"),
+ clEnumVal(constprop , "Constant Propagation"),
+ clEnumValN(inlining, "inline", "Procedure Integration"),
+ clEnumVal(strip , "Strip Symbols"),
+ clEnumValEnd));
+
+This defines a variable that is conceptually of the type
+"``std::vector<enum Opts>``". Thus, you can access it with standard vector
+methods:
+
+.. code-block:: c++
+
+ for (unsigned i = 0; i != OptimizationList.size(); ++i)
+ switch (OptimizationList[i])
+ ...
+
+... to iterate through the list of options specified.
+
+Note that the "``cl::list``" template is completely general and may be used with
+any data types or other arguments that you can use with the "``cl::opt``"
+template. One especially useful way to use a list is to capture all of the
+positional arguments together if there may be more than one specified. In the
+case of a linker, for example, the linker takes several '``.o``' files, and
+needs to capture them into a list. This is naturally specified as:
+
+.. code-block:: c++
+
+ ...
+ cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<Input files>"), cl::OneOrMore);
+ ...
+
+This variable works just like a "``vector<string>``" object. As such, accessing
+the list is simple, just like above. In this example, we used the
+`cl::OneOrMore`_ modifier to inform the CommandLine library that it is an error
+if the user does not specify any ``.o`` files on our command line. Again, this
+just reduces the amount of checking we have to do.
+
+Collecting options as a set of flags
+------------------------------------
+
+Instead of collecting sets of options in a list, it is also possible to gather
+information for enum values in a **bit vector**. The representation used by the
+`cl::bits`_ class is an ``unsigned`` integer. An enum value is represented by a
+0/1 in the enum's ordinal value bit position. 1 indicating that the enum was
+specified, 0 otherwise. As each specified value is parsed, the resulting enum's
+bit is set in the option's bit vector:
+
+.. code-block:: c++
+
+ bits |= 1 << (unsigned)enum;
+
+Options that are specified multiple times are redundant. Any instances after
+the first are discarded.
+
+Reworking the above list example, we could replace `cl::list`_ with `cl::bits`_:
+
+.. code-block:: c++
+
+ cl::bits<Opts> OptimizationBits(cl::desc("Available Optimizations:"),
+ cl::values(
+ clEnumVal(dce , "Dead Code Elimination"),
+ clEnumVal(constprop , "Constant Propagation"),
+ clEnumValN(inlining, "inline", "Procedure Integration"),
+ clEnumVal(strip , "Strip Symbols"),
+ clEnumValEnd));
+
+To test to see if ``constprop`` was specified, we can use the ``cl:bits::isSet``
+function:
+
+.. code-block:: c++
+
+ if (OptimizationBits.isSet(constprop)) {
+ ...
+ }
+
+It's also possible to get the raw bit vector using the ``cl::bits::getBits``
+function:
+
+.. code-block:: c++
+
+ unsigned bits = OptimizationBits.getBits();
+
+Finally, if external storage is used, then the location specified must be of
+**type** ``unsigned``. In all other ways a `cl::bits`_ option is equivalent to a
+`cl::list`_ option.
+
+.. _additional extra text:
+
+Adding freeform text to help output
+-----------------------------------
+
+As our program grows and becomes more mature, we may decide to put summary
+information about what it does into the help output. The help output is styled
+to look similar to a Unix ``man`` page, providing concise information about a
+program. Unix ``man`` pages, however often have a description about what the
+program does. To add this to your CommandLine program, simply pass a third
+argument to the `cl::ParseCommandLineOptions`_ call in main. This additional
+argument is then printed as the overview information for your program, allowing
+you to include any additional information that you want. For example:
+
+.. code-block:: c++
+
+ int main(int argc, char **argv) {
+ cl::ParseCommandLineOptions(argc, argv, " CommandLine compiler example\n\n"
+ " This program blah blah blah...\n");
+ ...
+ }
+
+would yield the help output:
+
+::
+
+ **OVERVIEW: CommandLine compiler example
+
+ This program blah blah blah...**
+
+ USAGE: compiler [options] <input file>
+
+ OPTIONS:
+ ...
+ -help - display available options (-help-hidden for more)
+ -o <filename> - Specify output filename
+
+.. _Reference Guide:
+
+Reference Guide
+===============
+
+Now that you know the basics of how to use the CommandLine library, this section
+will give you the detailed information you need to tune how command line options
+work, as well as information on more "advanced" command line option processing
+capabilities.
+
+.. _positional:
+.. _positional argument:
+.. _Positional Arguments:
+.. _Positional arguments section:
+.. _positional options:
+
+Positional Arguments
+--------------------
+
+Positional arguments are those arguments that are not named, and are not
+specified with a hyphen. Positional arguments should be used when an option is
+specified by its position alone. For example, the standard Unix ``grep`` tool
+takes a regular expression argument, and an optional filename to search through
+(which defaults to standard input if a filename is not specified). Using the
+CommandLine library, this would be specified as:
+
+.. code-block:: c++
+
+ cl::opt<string> Regex (cl::Positional, cl::desc("<regular expression>"), cl::Required);
+ cl::opt<string> Filename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
+
+Given these two option declarations, the ``-help`` output for our grep
+replacement would look like this:
+
+::
+
+ USAGE: spiffygrep [options] <regular expression> <input file>
+
+ OPTIONS:
+ -help - display available options (-help-hidden for more)
+
+... and the resultant program could be used just like the standard ``grep``
+tool.
+
+Positional arguments are sorted by their order of construction. This means that
+command line options will be ordered according to how they are listed in a .cpp
+file, but will not have an ordering defined if the positional arguments are
+defined in multiple .cpp files. The fix for this problem is simply to define
+all of your positional arguments in one .cpp file.
+
+Specifying positional options with hyphens
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sometimes you may want to specify a value to your positional argument that
+starts with a hyphen (for example, searching for '``-foo``' in a file). At
+first, you will have trouble doing this, because it will try to find an argument
+named '``-foo``', and will fail (and single quotes will not save you). Note
+that the system ``grep`` has the same problem:
+
+::
+
+ $ spiffygrep '-foo' test.txt
+ Unknown command line argument '-foo'. Try: spiffygrep -help'
+
+ $ grep '-foo' test.txt
+ grep: illegal option -- f
+ grep: illegal option -- o
+ grep: illegal option -- o
+ Usage: grep -hblcnsviw pattern file . . .
+
+The solution for this problem is the same for both your tool and the system
+version: use the '``--``' marker. When the user specifies '``--``' on the
+command line, it is telling the program that all options after the '``--``'
+should be treated as positional arguments, not options. Thus, we can use it
+like this:
+
+::
+
+ $ spiffygrep -- -foo test.txt
+ ...output...
+
+Determining absolute position with getPosition()
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sometimes an option can affect or modify the meaning of another option. For
+example, consider ``gcc``'s ``-x LANG`` option. This tells ``gcc`` to ignore the
+suffix of subsequent positional arguments and force the file to be interpreted
+as if it contained source code in language ``LANG``. In order to handle this
+properly, you need to know the absolute position of each argument, especially
+those in lists, so their interaction(s) can be applied correctly. This is also
+useful for options like ``-llibname`` which is actually a positional argument
+that starts with a dash.
+
+So, generally, the problem is that you have two ``cl::list`` variables that
+interact in some way. To ensure the correct interaction, you can use the
+``cl::list::getPosition(optnum)`` method. This method returns the absolute
+position (as found on the command line) of the ``optnum`` item in the
+``cl::list``.
+
+The idiom for usage is like this:
+
+.. code-block:: c++
+
+ static cl::list<std::string> Files(cl::Positional, cl::OneOrMore);
+ static cl::list<std::string> Libraries("l", cl::ZeroOrMore);
+
+ int main(int argc, char**argv) {
+ // ...
+ std::vector<std::string>::iterator fileIt = Files.begin();
+ std::vector<std::string>::iterator libIt = Libraries.begin();
+ unsigned libPos = 0, filePos = 0;
+ while ( 1 ) {
+ if ( libIt != Libraries.end() )
+ libPos = Libraries.getPosition( libIt - Libraries.begin() );
+ else
+ libPos = 0;
+ if ( fileIt != Files.end() )
+ filePos = Files.getPosition( fileIt - Files.begin() );
+ else
+ filePos = 0;
+
+ if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
+ // Source File Is next
+ ++fileIt;
+ }
+ else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
+ // Library is next
+ ++libIt;
+ }
+ else
+ break; // we're done with the list
+ }
+ }
+
+Note that, for compatibility reasons, the ``cl::opt`` also supports an
+``unsigned getPosition()`` option that will provide the absolute position of
+that option. You can apply the same approach as above with a ``cl::opt`` and a
+``cl::list`` option as you can with two lists.
+
+.. _interpreter style options:
+.. _cl::ConsumeAfter:
+.. _this section for more information:
+
+The ``cl::ConsumeAfter`` modifier
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::ConsumeAfter`` `formatting option`_ is used to construct programs that
+use "interpreter style" option processing. With this style of option
+processing, all arguments specified after the last positional argument are
+treated as special interpreter arguments that are not interpreted by the command
+line argument.
+
+As a concrete example, lets say we are developing a replacement for the standard
+Unix Bourne shell (``/bin/sh``). To run ``/bin/sh``, first you specify options
+to the shell itself (like ``-x`` which turns on trace output), then you specify
+the name of the script to run, then you specify arguments to the script. These
+arguments to the script are parsed by the Bourne shell command line option
+processor, but are not interpreted as options to the shell itself. Using the
+CommandLine library, we would specify this as:
+
+.. code-block:: c++
+
+ cl::opt<string> Script(cl::Positional, cl::desc("<input script>"), cl::init("-"));
+ cl::list<string> Argv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
+ cl::opt<bool> Trace("x", cl::desc("Enable trace output"));
+
+which automatically provides the help output:
+
+::
+
+ USAGE: spiffysh [options] <input script> <program arguments>...
+
+ OPTIONS:
+ -help - display available options (-help-hidden for more)
+ -x - Enable trace output
+
+At runtime, if we run our new shell replacement as ```spiffysh -x test.sh -a -x
+-y bar``', the ``Trace`` variable will be set to true, the ``Script`` variable
+will be set to "``test.sh``", and the ``Argv`` list will contain ``["-a", "-x",
+"-y", "bar"]``, because they were specified after the last positional argument
+(which is the script name).
+
+There are several limitations to when ``cl::ConsumeAfter`` options can be
+specified. For example, only one ``cl::ConsumeAfter`` can be specified per
+program, there must be at least one `positional argument`_ specified, there must
+not be any `cl::list`_ positional arguments, and the ``cl::ConsumeAfter`` option
+should be a `cl::list`_ option.
+
+.. _can be changed:
+.. _Internal vs External Storage:
+
+Internal vs External Storage
+----------------------------
+
+By default, all command line options automatically hold the value that they
+parse from the command line. This is very convenient in the common case,
+especially when combined with the ability to define command line options in the
+files that use them. This is called the internal storage model.
+
+Sometimes, however, it is nice to separate the command line option processing
+code from the storage of the value parsed. For example, lets say that we have a
+'``-debug``' option that we would like to use to enable debug information across
+the entire body of our program. In this case, the boolean value controlling the
+debug code should be globally accessible (in a header file, for example) yet the
+command line option processing code should not be exposed to all of these
+clients (requiring lots of .cpp files to ``#include CommandLine.h``).
+
+To do this, set up your .h file with your option, like this for example:
+
+.. code-block:: c++
+
+ // DebugFlag.h - Get access to the '-debug' command line option
+ //
+
+ // DebugFlag - This boolean is set to true if the '-debug' command line option
+ // is specified. This should probably not be referenced directly, instead, use
+ // the DEBUG macro below.
+ //
+ extern bool DebugFlag;
+
+ // DEBUG macro - This macro should be used by code to emit debug information.
+ // In the '-debug' option is specified on the command line, and if this is a
+ // debug build, then the code specified as the option to the macro will be
+ // executed. Otherwise it will not be.
+ #ifdef NDEBUG
+ #define DEBUG(X)
+ #else
+ #define DEBUG(X) do { if (DebugFlag) { X; } } while (0)
+ #endif
+
+This allows clients to blissfully use the ``DEBUG()`` macro, or the
+``DebugFlag`` explicitly if they want to. Now we just need to be able to set
+the ``DebugFlag`` boolean when the option is set. To do this, we pass an
+additional argument to our command line argument processor, and we specify where
+to fill in with the `cl::location`_ attribute:
+
+.. code-block:: c++
+
+ bool DebugFlag; // the actual value
+ static cl::opt<bool, true> // The parser
+ Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag));
+
+In the above example, we specify "``true``" as the second argument to the
+`cl::opt`_ template, indicating that the template should not maintain a copy of
+the value itself. In addition to this, we specify the `cl::location`_
+attribute, so that ``DebugFlag`` is automatically set.
+
+Option Attributes
+-----------------
+
+This section describes the basic attributes that you can specify on options.
+
+* The option name attribute (which is required for all options, except
+ `positional options`_) specifies what the option name is. This option is
+ specified in simple double quotes:
+
+ .. code-block:: c++
+
+ cl::opt<**bool**> Quiet("quiet");
+
+.. _cl::desc(...):
+
+* The **cl::desc** attribute specifies a description for the option to be
+ shown in the ``-help`` output for the program.
+
+.. _cl::value_desc:
+
+* The **cl::value_desc** attribute specifies a string that can be used to
+ fine tune the ``-help`` output for a command line option. Look `here`_ for an
+ example.
+
+.. _cl::init:
+
+* The **cl::init** attribute specifies an initial value for a `scalar`_
+ option. If this attribute is not specified then the command line option value
+ defaults to the value created by the default constructor for the
+ type.
+
+ .. warning::
+
+ If you specify both **cl::init** and **cl::location** for an option, you
+ must specify **cl::location** first, so that when the command-line parser
+ sees **cl::init**, it knows where to put the initial value. (You will get an
+ error at runtime if you don't put them in the right order.)
+
+.. _cl::location:
+
+* The **cl::location** attribute where to store the value for a parsed command
+ line option if using external storage. See the section on `Internal vs
+ External Storage`_ for more information.
+
+.. _cl::aliasopt:
+
+* The **cl::aliasopt** attribute specifies which option a `cl::alias`_ option is
+ an alias for.
+
+.. _cl::values:
+
+* The **cl::values** attribute specifies the string-to-value mapping to be used
+ by the generic parser. It takes a **clEnumValEnd terminated** list of
+ (option, value, description) triplets that specify the option name, the value
+ mapped to, and the description shown in the ``-help`` for the tool. Because
+ the generic parser is used most frequently with enum values, two macros are
+ often useful:
+
+ #. The **clEnumVal** macro is used as a nice simple way to specify a triplet
+ for an enum. This macro automatically makes the option name be the same as
+ the enum name. The first option to the macro is the enum, the second is
+ the description for the command line option.
+
+ #. The **clEnumValN** macro is used to specify macro options where the option
+ name doesn't equal the enum name. For this macro, the first argument is
+ the enum value, the second is the flag name, and the second is the
+ description.
+
+ You will get a compile time error if you try to use cl::values with a parser
+ that does not support it.
+
+.. _cl::multi_val:
+
+* The **cl::multi_val** attribute specifies that this option takes has multiple
+ values (example: ``-sectalign segname sectname sectvalue``). This attribute
+ takes one unsigned argument - the number of values for the option. This
+ attribute is valid only on ``cl::list`` options (and will fail with compile
+ error if you try to use it with other option types). It is allowed to use all
+ of the usual modifiers on multi-valued options (besides
+ ``cl::ValueDisallowed``, obviously).
+
+Option Modifiers
+----------------
+
+Option modifiers are the flags and expressions that you pass into the
+constructors for `cl::opt`_ and `cl::list`_. These modifiers give you the
+ability to tweak how options are parsed and how ``-help`` output is generated to
+fit your application well.
+
+These options fall into five main categories:
+
+#. Hiding an option from ``-help`` output
+
+#. Controlling the number of occurrences required and allowed
+
+#. Controlling whether or not a value must be specified
+
+#. Controlling other formatting options
+
+#. Miscellaneous option modifiers
+
+It is not possible to specify two options from the same category (you'll get a
+runtime error) to a single option, except for options in the miscellaneous
+category. The CommandLine library specifies defaults for all of these settings
+that are the most useful in practice and the most common, which mean that you
+usually shouldn't have to worry about these.
+
+Hiding an option from ``-help`` output
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::NotHidden``, ``cl::Hidden``, and ``cl::ReallyHidden`` modifiers are
+used to control whether or not an option appears in the ``-help`` and
+``-help-hidden`` output for the compiled program:
+
+.. _cl::NotHidden:
+
+* The **cl::NotHidden** modifier (which is the default for `cl::opt`_ and
+ `cl::list`_ options) indicates the option is to appear in both help
+ listings.
+
+.. _cl::Hidden:
+
+* The **cl::Hidden** modifier (which is the default for `cl::alias`_ options)
+ indicates that the option should not appear in the ``-help`` output, but
+ should appear in the ``-help-hidden`` output.
+
+.. _cl::ReallyHidden:
+
+* The **cl::ReallyHidden** modifier indicates that the option should not appear
+ in any help output.
+
+Controlling the number of occurrences required and allowed
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+This group of options is used to control how many time an option is allowed (or
+required) to be specified on the command line of your program. Specifying a
+value for this setting allows the CommandLine library to do error checking for
+you.
+
+The allowed values for this option group are:
+
+.. _cl::Optional:
+
+* The **cl::Optional** modifier (which is the default for the `cl::opt`_ and
+ `cl::alias`_ classes) indicates that your program will allow either zero or
+ one occurrence of the option to be specified.
+
+.. _cl::ZeroOrMore:
+
+* The **cl::ZeroOrMore** modifier (which is the default for the `cl::list`_
+ class) indicates that your program will allow the option to be specified zero
+ or more times.
+
+.. _cl::Required:
+
+* The **cl::Required** modifier indicates that the specified option must be
+ specified exactly one time.
+
+.. _cl::OneOrMore:
+
+* The **cl::OneOrMore** modifier indicates that the option must be specified at
+ least one time.
+
+* The **cl::ConsumeAfter** modifier is described in the `Positional arguments
+ section`_.
+
+If an option is not specified, then the value of the option is equal to the
+value specified by the `cl::init`_ attribute. If the ``cl::init`` attribute is
+not specified, the option value is initialized with the default constructor for
+the data type.
+
+If an option is specified multiple times for an option of the `cl::opt`_ class,
+only the last value will be retained.
+
+Controlling whether or not a value must be specified
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+This group of options is used to control whether or not the option allows a
+value to be present. In the case of the CommandLine library, a value is either
+specified with an equal sign (e.g. '``-index-depth=17``') or as a trailing
+string (e.g. '``-o a.out``').
+
+The allowed values for this option group are:
+
+.. _cl::ValueOptional:
+
+* The **cl::ValueOptional** modifier (which is the default for ``bool`` typed
+ options) specifies that it is acceptable to have a value, or not. A boolean
+ argument can be enabled just by appearing on the command line, or it can have
+ an explicit '``-foo=true``'. If an option is specified with this mode, it is
+ illegal for the value to be provided without the equal sign. Therefore
+ '``-foo true``' is illegal. To get this behavior, you must use
+ the `cl::ValueRequired`_ modifier.
+
+.. _cl::ValueRequired:
+
+* The **cl::ValueRequired** modifier (which is the default for all other types
+ except for `unnamed alternatives using the generic parser`_) specifies that a
+ value must be provided. This mode informs the command line library that if an
+ option is not provides with an equal sign, that the next argument provided
+ must be the value. This allows things like '``-o a.out``' to work.
+
+.. _cl::ValueDisallowed:
+
+* The **cl::ValueDisallowed** modifier (which is the default for `unnamed
+ alternatives using the generic parser`_) indicates that it is a runtime error
+ for the user to specify a value. This can be provided to disallow users from
+ providing options to boolean options (like '``-foo=true``').
+
+In general, the default values for this option group work just like you would
+want them to. As mentioned above, you can specify the `cl::ValueDisallowed`_
+modifier to a boolean argument to restrict your command line parser. These
+options are mostly useful when `extending the library`_.
+
+.. _formatting option:
+
+Controlling other formatting options
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The formatting option group is used to specify that the command line option has
+special abilities and is otherwise different from other command line arguments.
+As usual, you can only specify one of these arguments at most.
+
+.. _cl::NormalFormatting:
+
+* The **cl::NormalFormatting** modifier (which is the default all options)
+ specifies that this option is "normal".
+
+.. _cl::Positional:
+
+* The **cl::Positional** modifier specifies that this is a positional argument
+ that does not have a command line option associated with it. See the
+ `Positional Arguments`_ section for more information.
+
+* The **cl::ConsumeAfter** modifier specifies that this option is used to
+ capture "interpreter style" arguments. See `this section for more
+ information`_.
+
+.. _prefix:
+.. _cl::Prefix:
+
+* The **cl::Prefix** modifier specifies that this option prefixes its value.
+ With 'Prefix' options, the equal sign does not separate the value from the
+ option name specified. Instead, the value is everything after the prefix,
+ including any equal sign if present. This is useful for processing odd
+ arguments like ``-lmalloc`` and ``-L/usr/lib`` in a linker tool or
+ ``-DNAME=value`` in a compiler tool. Here, the '``l``', '``D``' and '``L``'
+ options are normal string (or list) options, that have the **cl::Prefix**
+ modifier added to allow the CommandLine library to recognize them. Note that
+ **cl::Prefix** options must not have the **cl::ValueDisallowed** modifier
+ specified.
+
+.. _grouping:
+.. _cl::Grouping:
+
+* The **cl::Grouping** modifier is used to implement Unix-style tools (like
+ ``ls``) that have lots of single letter arguments, but only require a single
+ dash. For example, the '``ls -labF``' command actually enables four different
+ options, all of which are single letters. Note that **cl::Grouping** options
+ cannot have values.
+
+The CommandLine library does not restrict how you use the **cl::Prefix** or
+**cl::Grouping** modifiers, but it is possible to specify ambiguous argument
+settings. Thus, it is possible to have multiple letter options that are prefix
+or grouping options, and they will still work as designed.
+
+To do this, the CommandLine library uses a greedy algorithm to parse the input
+option into (potentially multiple) prefix and grouping options. The strategy
+basically looks like this:
+
+::
+
+ parse(string OrigInput) {
+
+ 1. string input = OrigInput;
+ 2. if (isOption(input)) return getOption(input).parse(); // Normal option
+ 3. while (!isOption(input) && !input.empty()) input.pop_back(); // Remove the last letter
+ 4. if (input.empty()) return error(); // No matching option
+ 5. if (getOption(input).isPrefix())
+ return getOption(input).parse(input);
+ 6. while (!input.empty()) { // Must be grouping options
+ getOption(input).parse();
+ OrigInput.erase(OrigInput.begin(), OrigInput.begin()+input.length());
+ input = OrigInput;
+ while (!isOption(input) && !input.empty()) input.pop_back();
+ }
+ 7. if (!OrigInput.empty()) error();
+
+ }
+
+Miscellaneous option modifiers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The miscellaneous option modifiers are the only flags where you can specify more
+than one flag from the set: they are not mutually exclusive. These flags
+specify boolean properties that modify the option.
+
+.. _cl::CommaSeparated:
+
+* The **cl::CommaSeparated** modifier indicates that any commas specified for an
+ option's value should be used to split the value up into multiple values for
+ the option. For example, these two options are equivalent when
+ ``cl::CommaSeparated`` is specified: "``-foo=a -foo=b -foo=c``" and
+ "``-foo=a,b,c``". This option only makes sense to be used in a case where the
+ option is allowed to accept one or more values (i.e. it is a `cl::list`_
+ option).
+
+.. _cl::PositionalEatsArgs:
+
+* The **cl::PositionalEatsArgs** modifier (which only applies to positional
+ arguments, and only makes sense for lists) indicates that positional argument
+ should consume any strings after it (including strings that start with a "-")
+ up until another recognized positional argument. For example, if you have two
+ "eating" positional arguments, "``pos1``" and "``pos2``", the string "``-pos1
+ -foo -bar baz -pos2 -bork``" would cause the "``-foo -bar -baz``" strings to
+ be applied to the "``-pos1``" option and the "``-bork``" string to be applied
+ to the "``-pos2``" option.
+
+.. _cl::Sink:
+
+* The **cl::Sink** modifier is used to handle unknown options. If there is at
+ least one option with ``cl::Sink`` modifier specified, the parser passes
+ unrecognized option strings to it as values instead of signaling an error. As
+ with ``cl::CommaSeparated``, this modifier only makes sense with a `cl::list`_
+ option.
+
+So far, these are the only three miscellaneous option modifiers.
+
+.. _response files:
+
+Response files
+^^^^^^^^^^^^^^
+
+Some systems, such as certain variants of Microsoft Windows and some older
+Unices have a relatively low limit on command-line length. It is therefore
+customary to use the so-called 'response files' to circumvent this
+restriction. These files are mentioned on the command-line (using the "@file")
+syntax. The program reads these files and inserts the contents into argv,
+thereby working around the command-line length limits. Response files are
+enabled by an optional fourth argument to `cl::ParseEnvironmentOptions`_ and
+`cl::ParseCommandLineOptions`_.
+
+Top-Level Classes and Functions
+-------------------------------
+
+Despite all of the built-in flexibility, the CommandLine option library really
+only consists of one function `cl::ParseCommandLineOptions`_) and three main
+classes: `cl::opt`_, `cl::list`_, and `cl::alias`_. This section describes
+these three classes in detail.
+
+.. _cl::ParseCommandLineOptions:
+
+The ``cl::ParseCommandLineOptions`` function
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::ParseCommandLineOptions`` function is designed to be called directly
+from ``main``, and is used to fill in the values of all of the command line
+option variables once ``argc`` and ``argv`` are available.
+
+The ``cl::ParseCommandLineOptions`` function requires two parameters (``argc``
+and ``argv``), but may also take an optional third parameter which holds
+`additional extra text`_ to emit when the ``-help`` option is invoked, and a
+fourth boolean parameter that enables `response files`_.
+
+.. _cl::ParseEnvironmentOptions:
+
+The ``cl::ParseEnvironmentOptions`` function
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::ParseEnvironmentOptions`` function has mostly the same effects as
+`cl::ParseCommandLineOptions`_, except that it is designed to take values for
+options from an environment variable, for those cases in which reading the
+command line is not convenient or desired. It fills in the values of all the
+command line option variables just like `cl::ParseCommandLineOptions`_ does.
+
+It takes four parameters: the name of the program (since ``argv`` may not be
+available, it can't just look in ``argv[0]``), the name of the environment
+variable to examine, the optional `additional extra text`_ to emit when the
+``-help`` option is invoked, and the boolean switch that controls whether
+`response files`_ should be read.
+
+``cl::ParseEnvironmentOptions`` will break the environment variable's value up
+into words and then process them using `cl::ParseCommandLineOptions`_.
+**Note:** Currently ``cl::ParseEnvironmentOptions`` does not support quoting, so
+an environment variable containing ``-option "foo bar"`` will be parsed as three
+words, ``-option``, ``"foo``, and ``bar"``, which is different from what you
+would get from the shell with the same input.
+
+The ``cl::SetVersionPrinter`` function
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::SetVersionPrinter`` function is designed to be called directly from
+``main`` and *before* ``cl::ParseCommandLineOptions``. Its use is optional. It
+simply arranges for a function to be called in response to the ``--version``
+option instead of having the ``CommandLine`` library print out the usual version
+string for LLVM. This is useful for programs that are not part of LLVM but wish
+to use the ``CommandLine`` facilities. Such programs should just define a small
+function that takes no arguments and returns ``void`` and that prints out
+whatever version information is appropriate for the program. Pass the address of
+that function to ``cl::SetVersionPrinter`` to arrange for it to be called when
+the ``--version`` option is given by the user.
+
+.. _cl::opt:
+.. _scalar:
+
+The ``cl::opt`` class
+^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::opt`` class is the class used to represent scalar command line
+options, and is the one used most of the time. It is a templated class which
+can take up to three arguments (all except for the first have default values
+though):
+
+.. code-block:: c++
+
+ namespace cl {
+ template <class DataType, bool ExternalStorage = false,
+ class ParserClass = parser<DataType> >
+ class opt;
+ }
+
+The first template argument specifies what underlying data type the command line
+argument is, and is used to select a default parser implementation. The second
+template argument is used to specify whether the option should contain the
+storage for the option (the default) or whether external storage should be used
+to contain the value parsed for the option (see `Internal vs External Storage`_
+for more information).
+
+The third template argument specifies which parser to use. The default value
+selects an instantiation of the ``parser`` class based on the underlying data
+type of the option. In general, this default works well for most applications,
+so this option is only used when using a `custom parser`_.
+
+.. _lists of arguments:
+.. _cl::list:
+
+The ``cl::list`` class
+^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::list`` class is the class used to represent a list of command line
+options. It too is a templated class which can take up to three arguments:
+
+.. code-block:: c++
+
+ namespace cl {
+ template <class DataType, class Storage = bool,
+ class ParserClass = parser<DataType> >
+ class list;
+ }
+
+This class works the exact same as the `cl::opt`_ class, except that the second
+argument is the **type** of the external storage, not a boolean value. For this
+class, the marker type '``bool``' is used to indicate that internal storage
+should be used.
+
+.. _cl::bits:
+
+The ``cl::bits`` class
+^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::bits`` class is the class used to represent a list of command line
+options in the form of a bit vector. It is also a templated class which can
+take up to three arguments:
+
+.. code-block:: c++
+
+ namespace cl {
+ template <class DataType, class Storage = bool,
+ class ParserClass = parser<DataType> >
+ class bits;
+ }
+
+This class works the exact same as the `cl::list`_ class, except that the second
+argument must be of **type** ``unsigned`` if external storage is used.
+
+.. _cl::alias:
+
+The ``cl::alias`` class
+^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::alias`` class is a nontemplated class that is used to form aliases for
+other arguments.
+
+.. code-block:: c++
+
+ namespace cl {
+ class alias;
+ }
+
+The `cl::aliasopt`_ attribute should be used to specify which option this is an
+alias for. Alias arguments default to being `cl::Hidden`_, and use the aliased
+options parser to do the conversion from string to data.
+
+.. _cl::extrahelp:
+
+The ``cl::extrahelp`` class
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``cl::extrahelp`` class is a nontemplated class that allows extra help text
+to be printed out for the ``-help`` option.
+
+.. code-block:: c++
+
+ namespace cl {
+ struct extrahelp;
+ }
+
+To use the extrahelp, simply construct one with a ``const char*`` parameter to
+the constructor. The text passed to the constructor will be printed at the
+bottom of the help message, verbatim. Note that multiple ``cl::extrahelp``
+**can** be used, but this practice is discouraged. If your tool needs to print
+additional help information, put all that help into a single ``cl::extrahelp``
+instance.
+
+For example:
+
+.. code-block:: c++
+
+ cl::extrahelp("\nADDITIONAL HELP:\n\n This is the extra help\n");
+
+.. _different parser:
+.. _discussed previously:
+
+Builtin parsers
+---------------
+
+Parsers control how the string value taken from the command line is translated
+into a typed value, suitable for use in a C++ program. By default, the
+CommandLine library uses an instance of ``parser<type>`` if the command line
+option specifies that it uses values of type '``type``'. Because of this,
+custom option processing is specified with specializations of the '``parser``'
+class.
+
+The CommandLine library provides the following builtin parser specializations,
+which are sufficient for most applications. It can, however, also be extended to
+work with new data types and new ways of interpreting the same data. See the
+`Writing a Custom Parser`_ for more details on this type of library extension.
+
+.. _enums:
+.. _cl::parser:
+
+* The generic ``parser<t>`` parser can be used to map strings values to any data
+ type, through the use of the `cl::values`_ property, which specifies the
+ mapping information. The most common use of this parser is for parsing enum
+ values, which allows you to use the CommandLine library for all of the error
+ checking to make sure that only valid enum values are specified (as opposed to
+ accepting arbitrary strings). Despite this, however, the generic parser class
+ can be used for any data type.
+
+.. _boolean flags:
+.. _bool parser:
+
+* The **parser<bool> specialization** is used to convert boolean strings to a
+ boolean value. Currently accepted strings are "``true``", "``TRUE``",
+ "``True``", "``1``", "``false``", "``FALSE``", "``False``", and "``0``".
+
+* The **parser<boolOrDefault> specialization** is used for cases where the value
+ is boolean, but we also need to know whether the option was specified at all.
+ boolOrDefault is an enum with 3 values, BOU_UNSET, BOU_TRUE and BOU_FALSE.
+ This parser accepts the same strings as **``parser<bool>``**.
+
+.. _strings:
+
+* The **parser<string> specialization** simply stores the parsed string into the
+ string value specified. No conversion or modification of the data is
+ performed.
+
+.. _integers:
+.. _int:
+
+* The **parser<int> specialization** uses the C ``strtol`` function to parse the
+ string input. As such, it will accept a decimal number (with an optional '+'
+ or '-' prefix) which must start with a non-zero digit. It accepts octal
+ numbers, which are identified with a '``0``' prefix digit, and hexadecimal
+ numbers with a prefix of '``0x``' or '``0X``'.
+
+.. _doubles:
+.. _float:
+.. _double:
+
+* The **parser<double>** and **parser<float> specializations** use the standard
+ C ``strtod`` function to convert floating point strings into floating point
+ values. As such, a broad range of string formats is supported, including
+ exponential notation (ex: ``1.7e15``) and properly supports locales.
+
+.. _Extension Guide:
+.. _extending the library:
+
+Extension Guide
+===============
+
+Although the CommandLine library has a lot of functionality built into it
+already (as discussed previously), one of its true strengths lie in its
+extensibility. This section discusses how the CommandLine library works under
+the covers and illustrates how to do some simple, common, extensions.
+
+.. _Custom parsers:
+.. _custom parser:
+.. _Writing a Custom Parser:
+
+Writing a custom parser
+-----------------------
+
+One of the simplest and most common extensions is the use of a custom parser.
+As `discussed previously`_, parsers are the portion of the CommandLine library
+that turns string input from the user into a particular parsed data type,
+validating the input in the process.
+
+There are two ways to use a new parser:
+
+#. Specialize the `cl::parser`_ template for your custom data type.
+
+ This approach has the advantage that users of your custom data type will
+ automatically use your custom parser whenever they define an option with a
+ value type of your data type. The disadvantage of this approach is that it
+ doesn't work if your fundamental data type is something that is already
+ supported.
+
+#. Write an independent class, using it explicitly from options that need it.
+
+ This approach works well in situations where you would line to parse an
+ option using special syntax for a not-very-special data-type. The drawback
+ of this approach is that users of your parser have to be aware that they are
+ using your parser instead of the builtin ones.
+
+To guide the discussion, we will discuss a custom parser that accepts file
+sizes, specified with an optional unit after the numeric size. For example, we
+would like to parse "102kb", "41M", "1G" into the appropriate integer value. In
+this case, the underlying data type we want to parse into is '``unsigned``'. We
+choose approach #2 above because we don't want to make this the default for all
+``unsigned`` options.
+
+To start out, we declare our new ``FileSizeParser`` class:
+
+.. code-block:: c++
+
+ struct FileSizeParser : public cl::basic_parser<unsigned> {
+ // parse - Return true on error.
+ bool parse(cl::Option &O, const char *ArgName, const std::string &ArgValue,
+ unsigned &Val);
+ };
+
+Our new class inherits from the ``cl::basic_parser`` template class to fill in
+the default, boiler plate code for us. We give it the data type that we parse
+into, the last argument to the ``parse`` method, so that clients of our custom
+parser know what object type to pass in to the parse method. (Here we declare
+that we parse into '``unsigned``' variables.)
+
+For most purposes, the only method that must be implemented in a custom parser
+is the ``parse`` method. The ``parse`` method is called whenever the option is
+invoked, passing in the option itself, the option name, the string to parse, and
+a reference to a return value. If the string to parse is not well-formed, the
+parser should output an error message and return true. Otherwise it should
+return false and set '``Val``' to the parsed value. In our example, we
+implement ``parse`` as:
+
+.. code-block:: c++
+
+ bool FileSizeParser::parse(cl::Option &O, const char *ArgName,
+ const std::string &Arg, unsigned &Val) {
+ const char *ArgStart = Arg.c_str();
+ char *End;
+
+ // Parse integer part, leaving 'End' pointing to the first non-integer char
+ Val = (unsigned)strtol(ArgStart, &End, 0);
+
+ while (1) {
+ switch (*End++) {
+ case 0: return false; // No error
+ case 'i': // Ignore the 'i' in KiB if people use that
+ case 'b': case 'B': // Ignore B suffix
+ break;
+
+ case 'g': case 'G': Val *= 1024*1024*1024; break;
+ case 'm': case 'M': Val *= 1024*1024; break;
+ case 'k': case 'K': Val *= 1024; break;
+
+ default:
+ // Print an error message if unrecognized character!
+ return O.error("'" + Arg + "' value invalid for file size argument!");
+ }
+ }
+ }
+
+This function implements a very simple parser for the kinds of strings we are
+interested in. Although it has some holes (it allows "``123KKK``" for example),
+it is good enough for this example. Note that we use the option itself to print
+out the error message (the ``error`` method always returns true) in order to get
+a nice error message (shown below). Now that we have our parser class, we can
+use it like this:
+
+.. code-block:: c++
+
+ static cl::opt<unsigned, false, FileSizeParser>
+ MFS("max-file-size", cl::desc("Maximum file size to accept"),
+ cl::value_desc("size"));
+
+Which adds this to the output of our program:
+
+::
+
+ OPTIONS:
+ -help - display available options (-help-hidden for more)
+ ...
+ -max-file-size=<size> - Maximum file size to accept
+
+And we can test that our parse works correctly now (the test program just prints
+out the max-file-size argument value):
+
+::
+
+ $ ./test
+ MFS: 0
+ $ ./test -max-file-size=123MB
+ MFS: 128974848
+ $ ./test -max-file-size=3G
+ MFS: 3221225472
+ $ ./test -max-file-size=dog
+ -max-file-size option: 'dog' value invalid for file size argument!
+
+It looks like it works. The error message that we get is nice and helpful, and
+we seem to accept reasonable file sizes. This wraps up the "custom parser"
+tutorial.
+
+Exploiting external storage
+---------------------------
+
+Several of the LLVM libraries define static ``cl::opt`` instances that will
+automatically be included in any program that links with that library. This is
+a feature. However, sometimes it is necessary to know the value of the command
+line option outside of the library. In these cases the library does or should
+provide an external storage location that is accessible to users of the
+library. Examples of this include the ``llvm::DebugFlag`` exported by the
+``lib/Support/Debug.cpp`` file and the ``llvm::TimePassesIsEnabled`` flag
+exported by the ``lib/VMCore/PassManager.cpp`` file.
+
+.. todo::
+
+ TODO: complete this section
+
+.. _dynamically loaded options:
+
+Dynamically adding command line options
+
+.. todo::
+
+ TODO: fill in this section
diff --git a/docs/CompilerWriterInfo.html b/docs/CompilerWriterInfo.html
new file mode 100644
index 00000000000..66190655fa5
--- /dev/null
+++ b/docs/CompilerWriterInfo.html
@@ -0,0 +1,267 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Architecture/platform information for compiler writers</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>
+ Architecture/platform information for compiler writers
+</h1>
+
+<div class="doc_warning">
+ <p>Note: This document is a work-in-progress. Additions and clarifications
+ are welcome.</p>
+</div>
+
+<ol>
+ <li><a href="#hw">Hardware</a>
+ <ol>
+ <li><a href="#arm">ARM</a></li>
+ <li><a href="#ia64">Itanium</a></li>
+ <li><a href="#mips">MIPS</a></li>
+ <li><a href="#ppc">PowerPC</a></li>
+ <li><a href="#sparc">SPARC</a></li>
+ <li><a href="#x86">X86</a></li>
+ <li><a href="#other">Other lists</a></li>
+ </ol></li>
+ <li><a href="#abi">Application Binary Interface (ABI)</a>
+ <ol>
+ <li><a href="#linux">Linux</a></li>
+ <li><a href="#osx">OS X</a></li>
+ </ol></li>
+ <li><a href="#misc">Miscellaneous resources</a></li>
+</ol>
+
+<div class="doc_author">
+ <p>Compiled by <a href="http://misha.brukman.net">Misha Brukman</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="hw">Hardware</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<!-- ======================================================================= -->
+<h3><a name="arm">ARM</a></h3>
+
+<div>
+<ul>
+<li><a href="http://www.arm.com/documentation/">ARM documentation</a>
+(<a href="http://www.arm.com/documentation/ARMProcessor_Cores/">Processor
+Cores</a>)</li>
+<li><a href="http://www.arm.com/products/DevTools/ABI.html">ABI</a></li>
+</ul>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="ia64">Itanium (ia64)</a></h3>
+
+<div>
+<ul>
+<li><a
+href="http://developer.intel.com/design/itanium2/documentation.htm">Itanium documentation</a>
+</li>
+</ul>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="mips">MIPS</a></h3>
+
+<div>
+<ul>
+<li><a
+href="http://mips.com/content/Documentation/MIPSDocumentation/ProcessorArchitecture/doclibrary">MIPS
+Processor Architecture</a></li>
+</ul>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="ppc">PowerPC</a></h3>
+
+<div>
+
+<!-- _______________________________________________________________________ -->
+<h4>IBM - Official manuals and docs</h4>
+
+<div>
+
+<ul>
+<li><a
+href="http://www-106.ibm.com/developerworks/eserver/articles/archguide.html">PowerPC
+Architecture Book</a>
+<ul>
+ <li>Book I: <a
+ href="http://www-106.ibm.com/developerworks/eserver/pdfs/archpub1.pdf">PowerPC
+ User Instruction Set Architecture</a></li>
+ <li>Book II: <a
+ href="http://www-106.ibm.com/developerworks/eserver/pdfs/archpub2.pdf">PowerPC
+ Virtual Environment Architecture</a></li>
+ <li>Book III: <a
+ href="http://www-106.ibm.com/developerworks/eserver/pdfs/archpub3.pdf">PowerPC
+ Operating Environment Architecture</a></li>
+</ul></li>
+<li><a
+href="http://www-3.ibm.com/chips/techlib/techlib.nsf/techdocs/852569B20050FF7785256996007558C6">PowerPC
+Compiler Writer's Guide</a></li>
+<li><A
+href="http://www-3.ibm.com/chips/techlib/techlib.nsf/products/PowerPC">PowerPC
+Processor Manuals</a></li>
+<li><a
+href="http://www-106.ibm.com/developerworks/linux/library/l-powarch/">Intro to
+PowerPC architecture</a></li>
+<li><a href="http://publibn.boulder.ibm.com/doc_link/en_US/a_doc_lib/aixassem/alangref/alangreftfrm.htm">IBM AIX/5L for POWER Assembly reference</a></li>
+</ul>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>Other documents, collections, notes</h4>
+
+<div>
+
+<ul>
+<li><a href="http://penguinppc.org/dev/#library">PowerPC ABI documents</a></li>
+<li><a href="http://gcc.gnu.org/ml/gcc-patches/2003-09/msg00997.html">PowerPC64
+alignment of long doubles (from GCC)</a></li>
+<li><a href="http://sources.redhat.com/ml/binutils/2002-04/msg00573.html">Long
+branch stubs for powerpc64-linux (from binutils)</a></li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="sparc">SPARC</a></h3>
+
+<div>
+
+<ul>
+<li><a href="http://www.sparc.org/resource.htm">SPARC resources</a></li>
+<li><a href="http://www.sparc.org/standards.html">SPARC standards</a></li>
+</ul>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="x86">X86</a></h3>
+
+<div>
+
+<!-- _______________________________________________________________________ -->
+<h4>AMD - Official manuals and docs</h4>
+
+<div>
+<ul>
+<li><a
+href="http://www.amd.com/us-en/Processors/TechnicalResources/0,,30_182_739,00.html">AMD processor manuals</a></li>
+<li><a href="http://www.x86-64.org/documentation">X86-64 ABI</a></li>
+</ul>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>Intel - Official manuals and docs</h4>
+
+<div>
+<ul>
+<li><a
+href="http://developer.intel.com/design/pentium4/manuals/index_new.htm">IA-32
+manuals</a></li>
+<li><a
+href="http://www.intel.com/design/itanium/documentation.htm?iid=ipp_srvr_proc_itanium2+techdocs">Intel
+Itanium documentation</a></li>
+</ul>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>Other x86-specific information</h4>
+
+<div>
+<ul>
+<li><a href="http://www.agner.org/assem/calling_conventions.pdf">Calling
+conventions for different C++ compilers and operating systems</a></li>
+</ul>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="other">Other relevant lists</a></h3>
+
+<div>
+
+<ul>
+<li><a href="http://gcc.gnu.org/readings.html">GCC reading list</a></li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="abi">ABI</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<!-- ======================================================================= -->
+<h3><a name="linux">Linux</a></h3>
+
+<div>
+<ol>
+<li><a href="http://www.linuxbase.org/spec/ELF/ppc64/">PowerPC 64-bit ELF ABI
+Supplement</a></li>
+</ol>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="osx">OS X</a></h3>
+
+<div>
+<ol>
+<li><a
+href="http://developer.apple.com/documentation/Darwin/RuntimeArchitecture-date.html">Mach-O
+Runtime Architecture</a></li>
+<li><a href="http://www.unsanity.org/archives/000044.php">Notes on Mach-O
+ABI</a></li>
+</ol>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="misc">Miscellaneous resources</a></h2>
+<!-- *********************************************************************** -->
+
+<ul>
+<li><a
+href="http://www.nondot.org/sabre/os/articles/ExecutableFileFormats/">Executable
+File Format library</a></li>
+<li><a href="http://gcc.gnu.org/projects/prefetch.html">GCC prefetch project</a>
+page has a good survey of the prefetching capabilities of a variety of modern
+processors.</li>
+</ul>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="http://misha.brukman.net">Misha Brukman</a><br>
+ <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/DebuggingJITedCode.html b/docs/DebuggingJITedCode.html
new file mode 100644
index 00000000000..7d52fa76354
--- /dev/null
+++ b/docs/DebuggingJITedCode.html
@@ -0,0 +1,184 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Debugging JITed Code With GDB</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>Debugging JIT-ed Code With GDB</h1>
+<ol>
+ <li><a href="#background">Background</a></li>
+ <li><a href="#gdbversion">GDB Version</a></li>
+ <li><a href="#mcjitdebug">Debugging MCJIT-ed code</a></li>
+ <ul>
+ <li><a href="#mcjitdebug_example">Example</a></li>
+ </ul>
+</ol>
+<div class="doc_author">Written by Reid Kleckner and Eli Bendersky</div>
+
+<!--=========================================================================-->
+<h2><a name="background">Background</a></h2>
+<!--=========================================================================-->
+<div>
+
+<p>Without special runtime support, debugging dynamically generated code with
+GDB (as well as most debuggers) can be quite painful. Debuggers generally read
+debug information from the object file of the code, but for JITed code, there is
+no such file to look for.
+</p>
+
+<p>In order to communicate the necessary debug info to GDB, an interface for
+registering JITed code with debuggers has been designed and implemented for
+GDB and LLVM MCJIT. At a high level, whenever MCJIT generates new machine code,
+it does so in an in-memory object file that contains the debug information in
+DWARF format. MCJIT then adds this in-memory object file to a global list of
+dynamically generated object files and calls a special function
+(<tt>__jit_debug_register_code</tt>) marked noinline that GDB knows about. When
+GDB attaches to a process, it puts a breakpoint in this function and loads all
+of the object files in the global list. When MCJIT calls the registration
+function, GDB catches the breakpoint signal, loads the new object file from
+the inferior's memory, and resumes the execution. In this way, GDB can get the
+necessary debug information.
+</p>
+</div>
+
+<!--=========================================================================-->
+<h2><a name="gdbversion">GDB Version</a></h2>
+<!--=========================================================================-->
+
+<p>In order to debug code JIT-ed by LLVM, you need GDB 7.0 or newer, which is
+available on most modern distributions of Linux. The version of GDB that Apple
+ships with Xcode has been frozen at 6.3 for a while. LLDB may be a better
+option for debugging JIT-ed code on Mac OS X.
+</p>
+
+
+<!--=========================================================================-->
+<h2><a name="mcjitdebug">Debugging MCJIT-ed code</a></h2>
+<!--=========================================================================-->
+<div>
+
+<p>The emerging MCJIT component of LLVM allows full debugging of JIT-ed code with
+GDB. This is due to MCJIT's ability to use the MC emitter to provide full
+DWARF debugging information to GDB.</p>
+
+<p>Note that lli has to be passed the <tt>-use-mcjit</tt> flag to JIT the code
+with MCJIT instead of the old JIT.</p>
+
+<h3><a name="mcjitdebug_example">Example</a></h3>
+
+<div>
+
+<p>Consider the following C code (with line numbers added to make the example
+easier to follow):</p>
+
+<pre class="doc_code">
+1 int compute_factorial(int n)
+2 {
+3 if (n <= 1)
+4 return 1;
+5
+6 int f = n;
+7 while (--n > 1)
+8 f *= n;
+9 return f;
+10 }
+11
+12
+13 int main(int argc, char** argv)
+14 {
+15 if (argc < 2)
+16 return -1;
+17 char firstletter = argv[1][0];
+18 int result = compute_factorial(firstletter - '0');
+19
+20 // Returned result is clipped at 255...
+21 return result;
+22 }
+</pre>
+
+<p>Here is a sample command line session that shows how to build and run this
+code via lli inside GDB:
+</p>
+
+<pre class="doc_code">
+$ $BINPATH/clang -cc1 -O0 -g -emit-llvm showdebug.c
+$ gdb --quiet --args $BINPATH/lli -use-mcjit showdebug.ll 5
+Reading symbols from $BINPATH/lli...done.
+(gdb) b showdebug.c:6
+No source file named showdebug.c.
+Make breakpoint pending on future shared library load? (y or [n]) y
+Breakpoint 1 (showdebug.c:6) pending.
+(gdb) r
+Starting program: $BINPATH/lli -use-mcjit showdebug.ll 5
+[Thread debugging using libthread_db enabled]
+
+Breakpoint 1, compute_factorial (n=5) at showdebug.c:6
+6 int f = n;
+(gdb) p n
+$1 = 5
+(gdb) p f
+$2 = 0
+(gdb) n
+7 while (--n > 1)
+(gdb) p f
+$3 = 5
+(gdb) b showdebug.c:9
+Breakpoint 2 at 0x7ffff7ed404c: file showdebug.c, line 9.
+(gdb) c
+Continuing.
+
+Breakpoint 2, compute_factorial (n=1) at showdebug.c:9
+9 return f;
+(gdb) p f
+$4 = 120
+(gdb) bt
+#0 compute_factorial (n=1) at showdebug.c:9
+#1 0x00007ffff7ed40a9 in main (argc=2, argv=0x16677e0) at showdebug.c:18
+#2 0x3500000001652748 in ?? ()
+#3 0x00000000016677e0 in ?? ()
+#4 0x0000000000000002 in ?? ()
+#5 0x0000000000d953b3 in llvm::MCJIT::runFunction (this=0x16151f0, F=0x1603020, ArgValues=...) at /home/ebenders_test/llvm_svn_rw/lib/ExecutionEngine/MCJIT/MCJIT.cpp:161
+#6 0x0000000000dc8872 in llvm::ExecutionEngine::runFunctionAsMain (this=0x16151f0, Fn=0x1603020, argv=..., envp=0x7fffffffe040)
+ at /home/ebenders_test/llvm_svn_rw/lib/ExecutionEngine/ExecutionEngine.cpp:397
+#7 0x000000000059c583 in main (argc=4, argv=0x7fffffffe018, envp=0x7fffffffe040) at /home/ebenders_test/llvm_svn_rw/tools/lli/lli.cpp:324
+(gdb) finish
+Run till exit from #0 compute_factorial (n=1) at showdebug.c:9
+0x00007ffff7ed40a9 in main (argc=2, argv=0x16677e0) at showdebug.c:18
+18 int result = compute_factorial(firstletter - '0');
+Value returned is $5 = 120
+(gdb) p result
+$6 = 23406408
+(gdb) n
+21 return result;
+(gdb) p result
+$7 = 120
+(gdb) c
+Continuing.
+
+Program exited with code 0170.
+(gdb)
+
+</pre>
+
+</div>
+</div>
+
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+ <a href="mailto:reid.kleckner@gmail.com">Reid Kleckner</a>,
+ <a href="mailto:eliben@gmail.com">Eli Bendersky</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/DeveloperPolicy.rst b/docs/DeveloperPolicy.rst
new file mode 100644
index 00000000000..cda281a25c1
--- /dev/null
+++ b/docs/DeveloperPolicy.rst
@@ -0,0 +1,508 @@
+.. _developer_policy:
+
+=====================
+LLVM Developer Policy
+=====================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+This document contains the LLVM Developer Policy which defines the project's
+policy towards developers and their contributions. The intent of this policy is
+to eliminate miscommunication, rework, and confusion that might arise from the
+distributed nature of LLVM's development. By stating the policy in clear terms,
+we hope each developer can know ahead of time what to expect when making LLVM
+contributions. This policy covers all llvm.org subprojects, including Clang,
+LLDB, libc++, etc.
+
+This policy is also designed to accomplish the following objectives:
+
+#. Attract both users and developers to the LLVM project.
+
+#. Make life as simple and easy for contributors as possible.
+
+#. Keep the top of Subversion trees as stable as possible.
+
+#. Establish awareness of the project's `copyright, license, and patent
+ policies`_ with contributors to the project.
+
+This policy is aimed at frequent contributors to LLVM. People interested in
+contributing one-off patches can do so in an informal way by sending them to the
+`llvm-commits mailing list
+<http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits>`_ and engaging another
+developer to see it through the process.
+
+Developer Policies
+==================
+
+This section contains policies that pertain to frequent LLVM developers. We
+always welcome `one-off patches`_ from people who do not routinely contribute to
+LLVM, but we expect more from frequent contributors to keep the system as
+efficient as possible for everyone. Frequent LLVM contributors are expected to
+meet the following requirements in order for LLVM to maintain a high standard of
+quality.
+
+Stay Informed
+-------------
+
+Developers should stay informed by reading at least the "dev" mailing list for
+the projects you are interested in, such as `llvmdev
+<http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev>`_ for LLVM, `cfe-dev
+<http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev>`_ for Clang, or `lldb-dev
+<http://lists.cs.uiuc.edu/mailman/listinfo/lldb-dev>`_ for LLDB. If you are
+doing anything more than just casual work on LLVM, it is suggested that you also
+subscribe to the "commits" mailing list for the subproject you're interested in,
+such as `llvm-commits
+<http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits>`_, `cfe-commits
+<http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits>`_, or `lldb-commits
+<http://lists.cs.uiuc.edu/mailman/listinfo/lldb-commits>`_. Reading the
+"commits" list and paying attention to changes being made by others is a good
+way to see what other people are interested in and watching the flow of the
+project as a whole.
+
+We recommend that active developers register an email account with `LLVM
+Bugzilla <http://llvm.org/bugs/>`_ and preferably subscribe to the `llvm-bugs
+<http://lists.cs.uiuc.edu/mailman/listinfo/llvmbugs>`_ email list to keep track
+of bugs and enhancements occurring in LLVM. We really appreciate people who are
+proactive at catching incoming bugs in their components and dealing with them
+promptly.
+
+.. _patch:
+.. _one-off patches:
+
+Making a Patch
+--------------
+
+When making a patch for review, the goal is to make it as easy for the reviewer
+to read it as possible. As such, we recommend that you:
+
+#. Make your patch against the Subversion trunk, not a branch, and not an old
+ version of LLVM. This makes it easy to apply the patch. For information on
+ how to check out SVN trunk, please see the `Getting Started
+ Guide <GettingStarted.html#checkout>`_.
+
+#. Similarly, patches should be submitted soon after they are generated. Old
+ patches may not apply correctly if the underlying code changes between the
+ time the patch was created and the time it is applied.
+
+#. Patches should be made with ``svn diff``, or similar. If you use a
+ different tool, make sure it uses the ``diff -u`` format and that it
+ doesn't contain clutter which makes it hard to read.
+
+#. If you are modifying generated files, such as the top-level ``configure``
+ script, please separate out those changes into a separate patch from the rest
+ of your changes.
+
+When sending a patch to a mailing list, it is a good idea to send it as an
+*attachment* to the message, not embedded into the text of the message. This
+ensures that your mailer will not mangle the patch when it sends it (e.g. by
+making whitespace changes or by wrapping lines).
+
+*For Thunderbird users:* Before submitting a patch, please open *Preferences >
+Advanced > General > Config Editor*, find the key
+``mail.content_disposition_type``, and set its value to ``1``. Without this
+setting, Thunderbird sends your attachment using ``Content-Disposition: inline``
+rather than ``Content-Disposition: attachment``. Apple Mail gamely displays such
+a file inline, making it difficult to work with for reviewers using that
+program.
+
+.. _code review:
+
+Code Reviews
+------------
+
+LLVM has a code review policy. Code review is one way to increase the quality of
+software. We generally follow these policies:
+
+#. All developers are required to have significant changes reviewed before they
+ are committed to the repository.
+
+#. Code reviews are conducted by email, usually on the llvm-commits list.
+
+#. Code can be reviewed either before it is committed or after. We expect major
+ changes to be reviewed before being committed, but smaller changes (or
+ changes where the developer owns the component) can be reviewed after commit.
+
+#. The developer responsible for a code change is also responsible for making
+ all necessary review-related changes.
+
+#. Code review can be an iterative process, which continues until the patch is
+ ready to be committed.
+
+Developers should participate in code reviews as both reviewers and
+reviewees. If someone is kind enough to review your code, you should return the
+favor for someone else. Note that anyone is welcome to review and give feedback
+on a patch, but only people with Subversion write access can approve it.
+
+Code Owners
+-----------
+
+The LLVM Project relies on two features of its process to maintain rapid
+development in addition to the high quality of its source base: the combination
+of code review plus post-commit review for trusted maintainers. Having both is
+a great way for the project to take advantage of the fact that most people do
+the right thing most of the time, and only commit patches without pre-commit
+review when they are confident they are right.
+
+The trick to this is that the project has to guarantee that all patches that are
+committed are reviewed after they go in: you don't want everyone to assume
+someone else will review it, allowing the patch to go unreviewed. To solve this
+problem, we have a notion of an 'owner' for a piece of the code. The sole
+responsibility of a code owner is to ensure that a commit to their area of the
+code is appropriately reviewed, either by themself or by someone else. The list
+of current code owners can be found in the file
+`CODE_OWNERS.TXT <http://llvm.org/viewvc/llvm-project/llvm/trunk/CODE_OWNERS.TXT?view=markup>`_
+in the root of the LLVM source tree.
+
+Note that code ownership is completely different than reviewers: anyone can
+review a piece of code, and we welcome code review from anyone who is
+interested. Code owners are the "last line of defense" to guarantee that all
+patches that are committed are actually reviewed.
+
+Being a code owner is a somewhat unglamorous position, but it is incredibly
+important for the ongoing success of the project. Because people get busy,
+interests change, and unexpected things happen, code ownership is purely opt-in,
+and anyone can choose to resign their "title" at any time. For now, we do not
+have an official policy on how one gets elected to be a code owner.
+
+.. _include a testcase:
+
+Test Cases
+----------
+
+Developers are required to create test cases for any bugs fixed and any new
+features added. Some tips for getting your testcase approved:
+
+* All feature and regression test cases are added to the ``llvm/test``
+ directory. The appropriate sub-directory should be selected (see the `Testing
+ Guide <TestingGuide.html>`_ for details).
+
+* Test cases should be written in `LLVM assembly language <LangRef.html>`_
+ unless the feature or regression being tested requires another language
+ (e.g. the bug being fixed or feature being implemented is in the llvm-gcc C++
+ front-end, in which case it must be written in C++).
+
+* Test cases, especially for regressions, should be reduced as much as possible,
+ by `bugpoint <Bugpoint.html>`_ or manually. It is unacceptable to place an
+ entire failing program into ``llvm/test`` as this creates a *time-to-test*
+ burden on all developers. Please keep them short.
+
+Note that llvm/test and clang/test are designed for regression and small feature
+tests only. More extensive test cases (e.g., entire applications, benchmarks,
+etc) should be added to the ``llvm-test`` test suite. The llvm-test suite is
+for coverage (correctness, performance, etc) testing, not feature or regression
+testing.
+
+Quality
+-------
+
+The minimum quality standards that any change must satisfy before being
+committed to the main development branch are:
+
+#. Code must adhere to the `LLVM Coding Standards <CodingStandards.html>`_.
+
+#. Code must compile cleanly (no errors, no warnings) on at least one platform.
+
+#. Bug fixes and new features should `include a testcase`_ so we know if the
+ fix/feature ever regresses in the future.
+
+#. Code must pass the ``llvm/test`` test suite.
+
+#. The code must not cause regressions on a reasonable subset of llvm-test,
+ where "reasonable" depends on the contributor's judgement and the scope of
+ the change (more invasive changes require more testing). A reasonable subset
+ might be something like "``llvm-test/MultiSource/Benchmarks``".
+
+Additionally, the committer is responsible for addressing any problems found in
+the future that the change is responsible for. For example:
+
+* The code should compile cleanly on all supported platforms.
+
+* The changes should not cause any correctness regressions in the ``llvm-test``
+ suite and must not cause any major performance regressions.
+
+* The change set should not cause performance or correctness regressions for the
+ LLVM tools.
+
+* The changes should not cause performance or correctness regressions in code
+ compiled by LLVM on all applicable targets.
+
+* You are expected to address any `Bugzilla bugs <http://llvm.org/bugs/>`_ that
+ result from your change.
+
+We prefer for this to be handled before submission but understand that it isn't
+possible to test all of this for every submission. Our build bots and nightly
+testing infrastructure normally finds these problems. A good rule of thumb is
+to check the nightly testers for regressions the day after your change. Build
+bots will directly email you if a group of commits that included yours caused a
+failure. You are expected to check the build bot messages to see if they are
+your fault and, if so, fix the breakage.
+
+Commits that violate these quality standards (e.g. are very broken) may be
+reverted. This is necessary when the change blocks other developers from making
+progress. The developer is welcome to re-commit the change after the problem has
+been fixed.
+
+Obtaining Commit Access
+-----------------------
+
+We grant commit access to contributors with a track record of submitting high
+quality patches. If you would like commit access, please send an email to
+`Chris <mailto:sabre@nondot.org>`_ with the following information:
+
+#. The user name you want to commit with, e.g. "hacker".
+
+#. The full name and email address you want message to llvm-commits to come
+ from, e.g. "J. Random Hacker <hacker@yoyodyne.com>".
+
+#. A "password hash" of the password you want to use, e.g. "``2ACR96qjUqsyM``".
+ Note that you don't ever tell us what your password is, you just give it to
+ us in an encrypted form. To get this, run "``htpasswd``" (a utility that
+ comes with apache) in crypt mode (often enabled with "``-d``"), or find a web
+ page that will do it for you.
+
+Once you've been granted commit access, you should be able to check out an LLVM
+tree with an SVN URL of "https://username@llvm.org/..." instead of the normal
+anonymous URL of "http://llvm.org/...". The first time you commit you'll have
+to type in your password. Note that you may get a warning from SVN about an
+untrusted key, you can ignore this. To verify that your commit access works,
+please do a test commit (e.g. change a comment or add a blank line). Your first
+commit to a repository may require the autogenerated email to be approved by a
+mailing list. This is normal, and will be done when the mailing list owner has
+time.
+
+If you have recently been granted commit access, these policies apply:
+
+#. You are granted *commit-after-approval* to all parts of LLVM. To get
+ approval, submit a `patch`_ to `llvm-commits
+ <http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits>`_. When approved
+ you may commit it yourself.</li>
+
+#. You are allowed to commit patches without approval which you think are
+ obvious. This is clearly a subjective decision --- we simply expect you to
+ use good judgement. Examples include: fixing build breakage, reverting
+ obviously broken patches, documentation/comment changes, any other minor
+ changes.
+
+#. You are allowed to commit patches without approval to those portions of LLVM
+ that you have contributed or maintain (i.e., have been assigned
+ responsibility for), with the proviso that such commits must not break the
+ build. This is a "trust but verify" policy and commits of this nature are
+ reviewed after they are committed.
+
+#. Multiple violations of these policies or a single egregious violation may
+ cause commit access to be revoked.
+
+In any case, your changes are still subject to `code review`_ (either before or
+after they are committed, depending on the nature of the change). You are
+encouraged to review other peoples' patches as well, but you aren't required
+to.
+
+.. _discuss the change/gather consensus:
+
+Making a Major Change
+---------------------
+
+When a developer begins a major new project with the aim of contributing it back
+to LLVM, s/he should inform the community with an email to the `llvmdev
+<http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev>`_ email list, to the extent
+possible. The reason for this is to:
+
+#. keep the community informed about future changes to LLVM,
+
+#. avoid duplication of effort by preventing multiple parties working on the
+ same thing and not knowing about it, and
+
+#. ensure that any technical issues around the proposed work are discussed and
+ resolved before any significant work is done.
+
+The design of LLVM is carefully controlled to ensure that all the pieces fit
+together well and are as consistent as possible. If you plan to make a major
+change to the way LLVM works or want to add a major new extension, it is a good
+idea to get consensus with the development community before you start working on
+it.
+
+Once the design of the new feature is finalized, the work itself should be done
+as a series of `incremental changes`_, not as a long-term development branch.
+
+.. _incremental changes:
+
+Incremental Development
+-----------------------
+
+In the LLVM project, we do all significant changes as a series of incremental
+patches. We have a strong dislike for huge changes or long-term development
+branches. Long-term development branches have a number of drawbacks:
+
+#. Branches must have mainline merged into them periodically. If the branch
+ development and mainline development occur in the same pieces of code,
+ resolving merge conflicts can take a lot of time.
+
+#. Other people in the community tend to ignore work on branches.
+
+#. Huge changes (produced when a branch is merged back onto mainline) are
+ extremely difficult to `code review`_.
+
+#. Branches are not routinely tested by our nightly tester infrastructure.
+
+#. Changes developed as monolithic large changes often don't work until the
+ entire set of changes is done. Breaking it down into a set of smaller
+ changes increases the odds that any of the work will be committed to the main
+ repository.
+
+To address these problems, LLVM uses an incremental development style and we
+require contributors to follow this practice when making a large/invasive
+change. Some tips:
+
+* Large/invasive changes usually have a number of secondary changes that are
+ required before the big change can be made (e.g. API cleanup, etc). These
+ sorts of changes can often be done before the major change is done,
+ independently of that work.
+
+* The remaining inter-related work should be decomposed into unrelated sets of
+ changes if possible. Once this is done, define the first increment and get
+ consensus on what the end goal of the change is.
+
+* Each change in the set can be stand alone (e.g. to fix a bug), or part of a
+ planned series of changes that works towards the development goal.
+
+* Each change should be kept as small as possible. This simplifies your work
+ (into a logical progression), simplifies code review and reduces the chance
+ that you will get negative feedback on the change. Small increments also
+ facilitate the maintenance of a high quality code base.
+
+* Often, an independent precursor to a big change is to add a new API and slowly
+ migrate clients to use the new API. Each change to use the new API is often
+ "obvious" and can be committed without review. Once the new API is in place
+ and used, it is much easier to replace the underlying implementation of the
+ API. This implementation change is logically separate from the API
+ change.
+
+If you are interested in making a large change, and this scares you, please make
+sure to first `discuss the change/gather consensus`_ then ask about the best way
+to go about making the change.
+
+Attribution of Changes
+----------------------
+
+We believe in correct attribution of contributions to their contributors.
+However, we do not want the source code to be littered with random attributions
+"this code written by J. Random Hacker" (this is noisy and distracting). In
+practice, the revision control system keeps a perfect history of who changed
+what, and the CREDITS.txt file describes higher-level contributions. If you
+commit a patch for someone else, please say "patch contributed by J. Random
+Hacker!" in the commit message.
+
+Overall, please do not add contributor names to the source code.
+
+.. _copyright, license, and patent policies:
+
+Copyright, License, and Patents
+===============================
+
+.. note::
+
+ This section deals with legal matters but does not provide legal advice. We
+ are not lawyers --- please seek legal counsel from an attorney.
+
+This section addresses the issues of copyright, license and patents for the LLVM
+project. The copyright for the code is held by the individual contributors of
+the code and the terms of its license to LLVM users and developers is the
+`University of Illinois/NCSA Open Source License
+<http://www.opensource.org/licenses/UoI-NCSA.php>`_ (with portions dual licensed
+under the `MIT License <http://www.opensource.org/licenses/mit-license.php>`_,
+see below). As contributor to the LLVM project, you agree to allow any
+contributions to the project to licensed under these terms.
+
+Copyright
+---------
+
+The LLVM project does not require copyright assignments, which means that the
+copyright for the code in the project is held by its respective contributors who
+have each agreed to release their contributed code under the terms of the `LLVM
+License`_.
+
+An implication of this is that the LLVM license is unlikely to ever change:
+changing it would require tracking down all the contributors to LLVM and getting
+them to agree that a license change is acceptable for their contribution. Since
+there are no plans to change the license, this is not a cause for concern.
+
+As a contributor to the project, this means that you (or your company) retain
+ownership of the code you contribute, that it cannot be used in a way that
+contradicts the license (which is a liberal BSD-style license), and that the
+license for your contributions won't change without your approval in the
+future.
+
+.. _LLVM License:
+
+License
+-------
+
+We intend to keep LLVM perpetually open source and to use a liberal open source
+license. **As a contributor to the project, you agree that any contributions be
+licensed under the terms of the corresponding subproject.** All of the code in
+LLVM is available under the `University of Illinois/NCSA Open Source License
+<http://www.opensource.org/licenses/UoI-NCSA.php>`_, which boils down to
+this:
+
+* You can freely distribute LLVM.
+* You must retain the copyright notice if you redistribute LLVM.
+* Binaries derived from LLVM must reproduce the copyright notice (e.g. in an
+ included readme file).
+* You can't use our names to promote your LLVM derived products.
+* There's no warranty on LLVM at all.
+
+We believe this fosters the widest adoption of LLVM because it **allows
+commercial products to be derived from LLVM** with few restrictions and without
+a requirement for making any derived works also open source (i.e. LLVM's
+license is not a "copyleft" license like the GPL). We suggest that you read the
+`License <http://www.opensource.org/licenses/UoI-NCSA.php>`_ if further
+clarification is needed.
+
+In addition to the UIUC license, the runtime library components of LLVM
+(**compiler_rt, libc++, and libclc**) are also licensed under the `MIT License
+<http://www.opensource.org/licenses/mit-license.php>`_, which does not contain
+the binary redistribution clause. As a user of these runtime libraries, it
+means that you can choose to use the code under either license (and thus don't
+need the binary redistribution clause), and as a contributor to the code that
+you agree that any contributions to these libraries be licensed under both
+licenses. We feel that this is important for runtime libraries, because they
+are implicitly linked into applications and therefore should not subject those
+applications to the binary redistribution clause. This also means that it is ok
+to move code from (e.g.) libc++ to the LLVM core without concern, but that code
+cannot be moved from the LLVM core to libc++ without the copyright owner's
+permission.
+
+Note that the LLVM Project does distribute llvm-gcc and dragonegg, **which are
+GPL.** This means that anything "linked" into llvm-gcc must itself be compatible
+with the GPL, and must be releasable under the terms of the GPL. This implies
+that **any code linked into llvm-gcc and distributed to others may be subject to
+the viral aspects of the GPL** (for example, a proprietary code generator linked
+into llvm-gcc must be made available under the GPL). This is not a problem for
+code already distributed under a more liberal license (like the UIUC license),
+and GPL-containing subprojects are kept in separate SVN repositories whose
+LICENSE.txt files specifically indicate that they contain GPL code.
+
+We have no plans to change the license of LLVM. If you have questions or
+comments about the license, please contact the `LLVM Developer's Mailing
+List <mailto:llvmdev@cs.uiuc.edu>`_.
+
+Patents
+-------
+
+To the best of our knowledge, LLVM does not infringe on any patents (we have
+actually removed code from LLVM in the past that was found to infringe). Having
+code in LLVM that infringes on patents would violate an important goal of the
+project by making it hard or impossible to reuse the code for arbitrary purposes
+(including commercial use).
+
+When contributing code, we expect contributors to notify us of any potential for
+patent-related trouble with their changes (including from third parties). If
+you or your employer own the rights to a patent and would like to contribute
+code to LLVM that relies on it, we require that the copyright owner sign an
+agreement that allows any other user of LLVM to freely use your patent. Please
+contact the `oversight group <mailto:llvm-oversight@cs.uiuc.edu>`_ for more
+details.
diff --git a/docs/ExceptionHandling.rst b/docs/ExceptionHandling.rst
new file mode 100644
index 00000000000..190f18261da
--- /dev/null
+++ b/docs/ExceptionHandling.rst
@@ -0,0 +1,367 @@
+.. _exception_handling:
+
+==========================
+Exception Handling in LLVM
+==========================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+This document is the central repository for all information pertaining to
+exception handling in LLVM. It describes the format that LLVM exception
+handling information takes, which is useful for those interested in creating
+front-ends or dealing directly with the information. Further, this document
+provides specific examples of what exception handling information is used for in
+C and C++.
+
+Itanium ABI Zero-cost Exception Handling
+----------------------------------------
+
+Exception handling for most programming languages is designed to recover from
+conditions that rarely occur during general use of an application. To that end,
+exception handling should not interfere with the main flow of an application's
+algorithm by performing checkpointing tasks, such as saving the current pc or
+register state.
+
+The Itanium ABI Exception Handling Specification defines a methodology for
+providing outlying data in the form of exception tables without inlining
+speculative exception handling code in the flow of an application's main
+algorithm. Thus, the specification is said to add "zero-cost" to the normal
+execution of an application.
+
+A more complete description of the Itanium ABI exception handling runtime
+support of can be found at `Itanium C++ ABI: Exception Handling
+<http://www.codesourcery.com/cxx-abi/abi-eh.html>`_. A description of the
+exception frame format can be found at `Exception Frames
+<http://refspecs.freestandards.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html>`_,
+with details of the DWARF 4 specification at `DWARF 4 Standard
+<http://dwarfstd.org/Dwarf4Std.php>`_. A description for the C++ exception
+table formats can be found at `Exception Handling Tables
+<http://www.codesourcery.com/cxx-abi/exceptions.pdf>`_.
+
+Setjmp/Longjmp Exception Handling
+---------------------------------
+
+Setjmp/Longjmp (SJLJ) based exception handling uses LLVM intrinsics
+`llvm.eh.sjlj.setjmp`_ and `llvm.eh.sjlj.longjmp`_ to handle control flow for
+exception handling.
+
+For each function which does exception processing --- be it ``try``/``catch``
+blocks or cleanups --- that function registers itself on a global frame
+list. When exceptions are unwinding, the runtime uses this list to identify
+which functions need processing.
+
+Landing pad selection is encoded in the call site entry of the function
+context. The runtime returns to the function via `llvm.eh.sjlj.longjmp`_, where
+a switch table transfers control to the appropriate landing pad based on the
+index stored in the function context.
+
+In contrast to DWARF exception handling, which encodes exception regions and
+frame information in out-of-line tables, SJLJ exception handling builds and
+removes the unwind frame context at runtime. This results in faster exception
+handling at the expense of slower execution when no exceptions are thrown. As
+exceptions are, by their nature, intended for uncommon code paths, DWARF
+exception handling is generally preferred to SJLJ.
+
+Overview
+--------
+
+When an exception is thrown in LLVM code, the runtime does its best to find a
+handler suited to processing the circumstance.
+
+The runtime first attempts to find an *exception frame* corresponding to the
+function where the exception was thrown. If the programming language supports
+exception handling (e.g. C++), the exception frame contains a reference to an
+exception table describing how to process the exception. If the language does
+not support exception handling (e.g. C), or if the exception needs to be
+forwarded to a prior activation, the exception frame contains information about
+how to unwind the current activation and restore the state of the prior
+activation. This process is repeated until the exception is handled. If the
+exception is not handled and no activations remain, then the application is
+terminated with an appropriate error message.
+
+Because different programming languages have different behaviors when handling
+exceptions, the exception handling ABI provides a mechanism for
+supplying *personalities*. An exception handling personality is defined by
+way of a *personality function* (e.g. ``__gxx_personality_v0`` in C++),
+which receives the context of the exception, an *exception structure*
+containing the exception object type and value, and a reference to the exception
+table for the current function. The personality function for the current
+compile unit is specified in a *common exception frame*.
+
+The organization of an exception table is language dependent. For C++, an
+exception table is organized as a series of code ranges defining what to do if
+an exception occurs in that range. Typically, the information associated with a
+range defines which types of exception objects (using C++ *type info*) that are
+handled in that range, and an associated action that should take place. Actions
+typically pass control to a *landing pad*.
+
+A landing pad corresponds roughly to the code found in the ``catch`` portion of
+a ``try``/``catch`` sequence. When execution resumes at a landing pad, it
+receives an *exception structure* and a *selector value* corresponding to the
+*type* of exception thrown. The selector is then used to determine which *catch*
+should actually process the exception.
+
+LLVM Code Generation
+====================
+
+From a C++ developer's perspective, exceptions are defined in terms of the
+``throw`` and ``try``/``catch`` statements. In this section we will describe the
+implementation of LLVM exception handling in terms of C++ examples.
+
+Throw
+-----
+
+Languages that support exception handling typically provide a ``throw``
+operation to initiate the exception process. Internally, a ``throw`` operation
+breaks down into two steps.
+
+#. A request is made to allocate exception space for an exception structure.
+ This structure needs to survive beyond the current activation. This structure
+ will contain the type and value of the object being thrown.
+
+#. A call is made to the runtime to raise the exception, passing the exception
+ structure as an argument.
+
+In C++, the allocation of the exception structure is done by the
+``__cxa_allocate_exception`` runtime function. The exception raising is handled
+by ``__cxa_throw``. The type of the exception is represented using a C++ RTTI
+structure.
+
+Try/Catch
+---------
+
+A call within the scope of a *try* statement can potentially raise an
+exception. In those circumstances, the LLVM C++ front-end replaces the call with
+an ``invoke`` instruction. Unlike a call, the ``invoke`` has two potential
+continuation points:
+
+#. where to continue when the call succeeds as per normal, and
+
+#. where to continue if the call raises an exception, either by a throw or the
+ unwinding of a throw
+
+The term used to define a the place where an ``invoke`` continues after an
+exception is called a *landing pad*. LLVM landing pads are conceptually
+alternative function entry points where an exception structure reference and a
+type info index are passed in as arguments. The landing pad saves the exception
+structure reference and then proceeds to select the catch block that corresponds
+to the type info of the exception object.
+
+The LLVM `landingpad instruction <LangRef.html#i_landingpad>`_ is used to convey
+information about the landing pad to the back end. For C++, the ``landingpad``
+instruction returns a pointer and integer pair corresponding to the pointer to
+the *exception structure* and the *selector value* respectively.
+
+The ``landingpad`` instruction takes a reference to the personality function to
+be used for this ``try``/``catch`` sequence. The remainder of the instruction is
+a list of *cleanup*, *catch*, and *filter* clauses. The exception is tested
+against the clauses sequentially from first to last. The selector value is a
+positive number if the exception matched a type info, a negative number if it
+matched a filter, and zero if it matched a cleanup. If nothing is matched, the
+behavior of the program is `undefined`_. If a type info matched, then the
+selector value is the index of the type info in the exception table, which can
+be obtained using the `llvm.eh.typeid.for`_ intrinsic.
+
+Once the landing pad has the type info selector, the code branches to the code
+for the first catch. The catch then checks the value of the type info selector
+against the index of type info for that catch. Since the type info index is not
+known until all the type infos have been gathered in the backend, the catch code
+must call the `llvm.eh.typeid.for`_ intrinsic to determine the index for a given
+type info. If the catch fails to match the selector then control is passed on to
+the next catch.
+
+Finally, the entry and exit of catch code is bracketed with calls to
+``__cxa_begin_catch`` and ``__cxa_end_catch``.
+
+* ``__cxa_begin_catch`` takes an exception structure reference as an argument
+ and returns the value of the exception object.
+
+* ``__cxa_end_catch`` takes no arguments. This function:
+
+ #. Locates the most recently caught exception and decrements its handler
+ count,
+
+ #. Removes the exception from the *caught* stack if the handler count goes to
+ zero, and
+
+ #. Destroys the exception if the handler count goes to zero and the exception
+ was not re-thrown by throw.
+
+ .. note::
+
+ a rethrow from within the catch may replace this call with a
+ ``__cxa_rethrow``.
+
+Cleanups
+--------
+
+A cleanup is extra code which needs to be run as part of unwinding a scope. C++
+destructors are a typical example, but other languages and language extensions
+provide a variety of different kinds of cleanups. In general, a landing pad may
+need to run arbitrary amounts of cleanup code before actually entering a catch
+block. To indicate the presence of cleanups, a `landingpad
+instruction <LangRef.html#i_landingpad>`_ should have a *cleanup*
+clause. Otherwise, the unwinder will not stop at the landing pad if there are no
+catches or filters that require it to.
+
+.. note::
+
+ Do not allow a new exception to propagate out of the execution of a
+ cleanup. This can corrupt the internal state of the unwinder. Different
+ languages describe different high-level semantics for these situations: for
+ example, C++ requires that the process be terminated, whereas Ada cancels both
+ exceptions and throws a third.
+
+When all cleanups are finished, if the exception is not handled by the current
+function, resume unwinding by calling the `resume
+instruction <LangRef.html#i_resume>`_, passing in the result of the
+``landingpad`` instruction for the original landing pad.
+
+Throw Filters
+-------------
+
+C++ allows the specification of which exception types may be thrown from a
+function. To represent this, a top level landing pad may exist to filter out
+invalid types. To express this in LLVM code the `landingpad
+instruction <LangRef.html#i_landingpad>`_ will have a filter clause. The clause
+consists of an array of type infos. ``landingpad`` will return a negative value
+if the exception does not match any of the type infos. If no match is found then
+a call to ``__cxa_call_unexpected`` should be made, otherwise
+``_Unwind_Resume``. Each of these functions requires a reference to the
+exception structure. Note that the most general form of a ``landingpad``
+instruction can have any number of catch, cleanup, and filter clauses (though
+having more than one cleanup is pointless). The LLVM C++ front-end can generate
+such ``landingpad`` instructions due to inlining creating nested exception
+handling scopes.
+
+.. _undefined:
+
+Restrictions
+------------
+
+The unwinder delegates the decision of whether to stop in a call frame to that
+call frame's language-specific personality function. Not all unwinders guarantee
+that they will stop to perform cleanups. For example, the GNU C++ unwinder
+doesn't do so unless the exception is actually caught somewhere further up the
+stack.
+
+In order for inlining to behave correctly, landing pads must be prepared to
+handle selector results that they did not originally advertise. Suppose that a
+function catches exceptions of type ``A``, and it's inlined into a function that
+catches exceptions of type ``B``. The inliner will update the ``landingpad``
+instruction for the inlined landing pad to include the fact that ``B`` is also
+caught. If that landing pad assumes that it will only be entered to catch an
+``A``, it's in for a rude awakening. Consequently, landing pads must test for
+the selector results they understand and then resume exception propagation with
+the `resume instruction <LangRef.html#i_resume>`_ if none of the conditions
+match.
+
+Exception Handling Intrinsics
+=============================
+
+In addition to the ``landingpad`` and ``resume`` instructions, LLVM uses several
+intrinsic functions (name prefixed with ``llvm.eh``) to provide exception
+handling information at various points in generated code.
+
+.. _llvm.eh.typeid.for:
+
+llvm.eh.typeid.for
+------------------
+
+.. code-block:: llvm
+
+ i32 @llvm.eh.typeid.for(i8* %type_info)
+
+
+This intrinsic returns the type info index in the exception table of the current
+function. This value can be used to compare against the result of
+``landingpad`` instruction. The single argument is a reference to a type info.
+
+.. _llvm.eh.sjlj.setjmp:
+
+llvm.eh.sjlj.setjmp
+-------------------
+
+.. code-block:: llvm
+
+ i32 @llvm.eh.sjlj.setjmp(i8* %setjmp_buf)
+
+For SJLJ based exception handling, this intrinsic forces register saving for the
+current function and stores the address of the following instruction for use as
+a destination address by `llvm.eh.sjlj.longjmp`_. The buffer format and the
+overall functioning of this intrinsic is compatible with the GCC
+``__builtin_setjmp`` implementation allowing code built with the clang and GCC
+to interoperate.
+
+The single parameter is a pointer to a five word buffer in which the calling
+context is saved. The front end places the frame pointer in the first word, and
+the target implementation of this intrinsic should place the destination address
+for a `llvm.eh.sjlj.longjmp`_ in the second word. The following three words are
+available for use in a target-specific manner.
+
+.. _llvm.eh.sjlj.longjmp:
+
+llvm.eh.sjlj.longjmp
+--------------------
+
+.. code-block:: llvm
+
+ void @llvm.eh.sjlj.longjmp(i8* %setjmp_buf)
+
+For SJLJ based exception handling, the ``llvm.eh.sjlj.longjmp`` intrinsic is
+used to implement ``__builtin_longjmp()``. The single parameter is a pointer to
+a buffer populated by `llvm.eh.sjlj.setjmp`_. The frame pointer and stack
+pointer are restored from the buffer, then control is transferred to the
+destination address.
+
+llvm.eh.sjlj.lsda
+-----------------
+
+.. code-block:: llvm
+
+ i8* @llvm.eh.sjlj.lsda()
+
+For SJLJ based exception handling, the ``llvm.eh.sjlj.lsda`` intrinsic returns
+the address of the Language Specific Data Area (LSDA) for the current
+function. The SJLJ front-end code stores this address in the exception handling
+function context for use by the runtime.
+
+llvm.eh.sjlj.callsite
+---------------------
+
+.. code-block:: llvm
+
+ void @llvm.eh.sjlj.callsite(i32 %call_site_num)
+
+For SJLJ based exception handling, the ``llvm.eh.sjlj.callsite`` intrinsic
+identifies the callsite value associated with the following ``invoke``
+instruction. This is used to ensure that landing pad entries in the LSDA are
+generated in matching order.
+
+Asm Table Formats
+=================
+
+There are two tables that are used by the exception handling runtime to
+determine which actions should be taken when an exception is thrown.
+
+Exception Handling Frame
+------------------------
+
+An exception handling frame ``eh_frame`` is very similar to the unwind frame
+used by DWARF debug info. The frame contains all the information necessary to
+tear down the current frame and restore the state of the prior frame. There is
+an exception handling frame for each function in a compile unit, plus a common
+exception handling frame that defines information common to all functions in the
+unit.
+
+Exception Tables
+----------------
+
+An exception table contains information about what actions to take when an
+exception is thrown in a particular part of a function's code. There is one
+exception table per function, except leaf functions and functions that have
+calls only to non-throwing functions. They do not need an exception table.
diff --git a/docs/ExtendedIntegerResults.txt b/docs/ExtendedIntegerResults.txt
new file mode 100644
index 00000000000..44e9fbf0e76
--- /dev/null
+++ b/docs/ExtendedIntegerResults.txt
@@ -0,0 +1,133 @@
+//===----------------------------------------------------------------------===//
+// Representing sign/zero extension of function results
+//===----------------------------------------------------------------------===//
+
+Mar 25, 2009 - Initial Revision
+
+Most ABIs specify that functions which return small integers do so in a
+specific integer GPR. This is an efficient way to go, but raises the question:
+if the returned value is smaller than the register, what do the high bits hold?
+
+There are three (interesting) possible answers: undefined, zero extended, or
+sign extended. The number of bits in question depends on the data-type that
+the front-end is referencing (typically i1/i8/i16/i32).
+
+Knowing the answer to this is important for two reasons: 1) we want to be able
+to implement the ABI correctly. If we need to sign extend the result according
+to the ABI, we really really do need to do this to preserve correctness. 2)
+this information is often useful for optimization purposes, and we want the
+mid-level optimizers to be able to process this (e.g. eliminate redundant
+extensions).
+
+For example, lets pretend that X86 requires the caller to properly extend the
+result of a return (I'm not sure this is the case, but the argument doesn't
+depend on this). Given this, we should compile this:
+
+int a();
+short b() { return a(); }
+
+into:
+
+_b:
+ subl $12, %esp
+ call L_a$stub
+ addl $12, %esp
+ cwtl
+ ret
+
+An optimization example is that we should be able to eliminate the explicit
+sign extension in this example:
+
+short y();
+int z() {
+ return ((int)y() << 16) >> 16;
+}
+
+_z:
+ subl $12, %esp
+ call _y
+ ;; movswl %ax, %eax -> not needed because eax is already sext'd
+ addl $12, %esp
+ ret
+
+//===----------------------------------------------------------------------===//
+// What we have right now.
+//===----------------------------------------------------------------------===//
+
+Currently, these sorts of things are modelled by compiling a function to return
+the small type and a signext/zeroext marker is used. For example, we compile
+Z into:
+
+define i32 @z() nounwind {
+entry:
+ %0 = tail call signext i16 (...)* @y() nounwind
+ %1 = sext i16 %0 to i32
+ ret i32 %1
+}
+
+and b into:
+
+define signext i16 @b() nounwind {
+entry:
+ %0 = tail call i32 (...)* @a() nounwind ; <i32> [#uses=1]
+ %retval12 = trunc i32 %0 to i16 ; <i16> [#uses=1]
+ ret i16 %retval12
+}
+
+This has some problems: 1) the actual precise semantics are really poorly
+defined (see PR3779). 2) some targets might want the caller to extend, some
+might want the callee to extend 3) the mid-level optimizer doesn't know the
+size of the GPR, so it doesn't know that %0 is sign extended up to 32-bits
+here, and even if it did, it could not eliminate the sext. 4) the code
+generator has historically assumed that the result is extended to i32, which is
+a problem on PIC16 (and is also probably wrong on alpha and other 64-bit
+targets).
+
+//===----------------------------------------------------------------------===//
+// The proposal
+//===----------------------------------------------------------------------===//
+
+I suggest that we have the front-end fully lower out the ABI issues here to
+LLVM IR. This makes it 100% explicit what is going on and means that there is
+no cause for confusion. For example, the cases above should compile into:
+
+define i32 @z() nounwind {
+entry:
+ %0 = tail call i32 (...)* @y() nounwind
+ %1 = trunc i32 %0 to i16
+ %2 = sext i16 %1 to i32
+ ret i32 %2
+}
+define i32 @b() nounwind {
+entry:
+ %0 = tail call i32 (...)* @a() nounwind
+ %retval12 = trunc i32 %0 to i16
+ %tmp = sext i16 %retval12 to i32
+ ret i32 %tmp
+}
+
+In this model, no functions will return an i1/i8/i16 (and on a x86-64 target
+that extends results to i64, no i32). This solves the ambiguity issue, allows us
+to fully describe all possible ABIs, and now allows the optimizers to reason
+about and eliminate these extensions.
+
+The one thing that is missing is the ability for the front-end and optimizer to
+specify/infer the guarantees provided by the ABI to allow other optimizations.
+For example, in the y/z case, since y is known to return a sign extended value,
+the trunc/sext in z should be eliminable.
+
+This can be done by introducing new sext/zext attributes which mean "I know
+that the result of the function is sign extended at least N bits. Given this,
+and given that it is stuck on the y function, the mid-level optimizer could
+easily eliminate the extensions etc with existing functionality.
+
+The major disadvantage of doing this sort of thing is that it makes the ABI
+lowering stuff even more explicit in the front-end, and that we would like to
+eventually move to having the code generator do more of this work. However,
+the sad truth of the matter is that this is a) unlikely to happen anytime in
+the near future, and b) this is no worse than we have now with the existing
+attributes.
+
+C compilers fundamentally have to reason about the target in many ways.
+This is ugly and horrible, but a fact of life.
+
diff --git a/docs/ExtendingLLVM.html b/docs/ExtendingLLVM.html
new file mode 100644
index 00000000000..99e209b8940
--- /dev/null
+++ b/docs/ExtendingLLVM.html
@@ -0,0 +1,379 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Extending LLVM: Adding instructions, intrinsics, types, etc.</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>
+ Extending LLVM: Adding instructions, intrinsics, types, etc.
+</h1>
+
+<ol>
+ <li><a href="#introduction">Introduction and Warning</a></li>
+ <li><a href="#intrinsic">Adding a new intrinsic function</a></li>
+ <li><a href="#instruction">Adding a new instruction</a></li>
+ <li><a href="#sdnode">Adding a new SelectionDAG node</a></li>
+ <li><a href="#type">Adding a new type</a>
+ <ol>
+ <li><a href="#fund_type">Adding a new fundamental type</a></li>
+ <li><a href="#derived_type">Adding a new derived type</a></li>
+ </ol></li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by <a href="http://misha.brukman.net">Misha Brukman</a>,
+ Brad Jones, Nate Begeman,
+ and <a href="http://nondot.org/sabre">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="introduction">Introduction and Warning</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>During the course of using LLVM, you may wish to customize it for your
+research project or for experimentation. At this point, you may realize that
+you need to add something to LLVM, whether it be a new fundamental type, a new
+intrinsic function, or a whole new instruction.</p>
+
+<p>When you come to this realization, stop and think. Do you really need to
+extend LLVM? Is it a new fundamental capability that LLVM does not support at
+its current incarnation or can it be synthesized from already pre-existing LLVM
+elements? If you are not sure, ask on the <a
+href="http://mail.cs.uiuc.edu/mailman/listinfo/llvmdev">LLVM-dev</a> list. The
+reason is that extending LLVM will get involved as you need to update all the
+different passes that you intend to use with your extension, and there are
+<em>many</em> LLVM analyses and transformations, so it may be quite a bit of
+work.</p>
+
+<p>Adding an <a href="#intrinsic">intrinsic function</a> is far easier than
+adding an instruction, and is transparent to optimization passes. If your added
+functionality can be expressed as a
+function call, an intrinsic function is the method of choice for LLVM
+extension.</p>
+
+<p>Before you invest a significant amount of effort into a non-trivial
+extension, <span class="doc_warning">ask on the list</span> if what you are
+looking to do can be done with already-existing infrastructure, or if maybe
+someone else is already working on it. You will save yourself a lot of time and
+effort by doing so.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="intrinsic">Adding a new intrinsic function</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Adding a new intrinsic function to LLVM is much easier than adding a new
+instruction. Almost all extensions to LLVM should start as an intrinsic
+function and then be turned into an instruction if warranted.</p>
+
+<ol>
+<li><tt>llvm/docs/LangRef.html</tt>:
+ Document the intrinsic. Decide whether it is code generator specific and
+ what the restrictions are. Talk to other people about it so that you are
+ sure it's a good idea.</li>
+
+<li><tt>llvm/include/llvm/Intrinsics*.td</tt>:
+ Add an entry for your intrinsic. Describe its memory access characteristics
+ for optimization (this controls whether it will be DCE'd, CSE'd, etc). Note
+ that any intrinsic using the <tt>llvm_int_ty</tt> type for an argument will
+ be deemed by <tt>tblgen</tt> as overloaded and the corresponding suffix
+ will be required on the intrinsic's name.</li>
+
+<li><tt>llvm/lib/Analysis/ConstantFolding.cpp</tt>: If it is possible to
+ constant fold your intrinsic, add support to it in the
+ <tt>canConstantFoldCallTo</tt> and <tt>ConstantFoldCall</tt> functions.</li>
+
+<li><tt>llvm/test/Regression/*</tt>: Add test cases for your test cases to the
+ test suite</li>
+</ol>
+
+<p>Once the intrinsic has been added to the system, you must add code generator
+support for it. Generally you must do the following steps:</p>
+
+<dl>
+
+<dt>Add support to the .td file for the target(s) of your choice in
+ <tt>lib/Target/*/*.td</tt>.</dt>
+
+<dd>This is usually a matter of adding a pattern to the .td file that matches
+ the intrinsic, though it may obviously require adding the instructions you
+ want to generate as well. There are lots of examples in the PowerPC and X86
+ backend to follow.</dd>
+</dl>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="sdnode">Adding a new SelectionDAG node</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>As with intrinsics, adding a new SelectionDAG node to LLVM is much easier
+than adding a new instruction. New nodes are often added to help represent
+instructions common to many targets. These nodes often map to an LLVM
+instruction (add, sub) or intrinsic (byteswap, population count). In other
+cases, new nodes have been added to allow many targets to perform a common task
+(converting between floating point and integer representation) or capture more
+complicated behavior in a single node (rotate).</p>
+
+<ol>
+<li><tt>include/llvm/CodeGen/ISDOpcodes.h</tt>:
+ Add an enum value for the new SelectionDAG node.</li>
+<li><tt>lib/CodeGen/SelectionDAG/SelectionDAG.cpp</tt>:
+ Add code to print the node to <tt>getOperationName</tt>. If your new node
+ can be evaluated at compile time when given constant arguments (such as an
+ add of a constant with another constant), find the <tt>getNode</tt> method
+ that takes the appropriate number of arguments, and add a case for your node
+ to the switch statement that performs constant folding for nodes that take
+ the same number of arguments as your new node.</li>
+<li><tt>lib/CodeGen/SelectionDAG/LegalizeDAG.cpp</tt>:
+ Add code to <a href="CodeGenerator.html#selectiondag_legalize">legalize,
+ promote, and expand</a> the node as necessary. At a minimum, you will need
+ to add a case statement for your node in <tt>LegalizeOp</tt> which calls
+ LegalizeOp on the node's operands, and returns a new node if any of the
+ operands changed as a result of being legalized. It is likely that not all
+ targets supported by the SelectionDAG framework will natively support the
+ new node. In this case, you must also add code in your node's case
+ statement in <tt>LegalizeOp</tt> to Expand your node into simpler, legal
+ operations. The case for <tt>ISD::UREM</tt> for expanding a remainder into
+ a divide, multiply, and a subtract is a good example.</li>
+<li><tt>lib/CodeGen/SelectionDAG/LegalizeDAG.cpp</tt>:
+ If targets may support the new node being added only at certain sizes, you
+ will also need to add code to your node's case statement in
+ <tt>LegalizeOp</tt> to Promote your node's operands to a larger size, and
+ perform the correct operation. You will also need to add code to
+ <tt>PromoteOp</tt> to do this as well. For a good example, see
+ <tt>ISD::BSWAP</tt>,
+ which promotes its operand to a wider size, performs the byteswap, and then
+ shifts the correct bytes right to emulate the narrower byteswap in the
+ wider type.</li>
+<li><tt>lib/CodeGen/SelectionDAG/LegalizeDAG.cpp</tt>:
+ Add a case for your node in <tt>ExpandOp</tt> to teach the legalizer how to
+ perform the action represented by the new node on a value that has been
+ split into high and low halves. This case will be used to support your
+ node with a 64 bit operand on a 32 bit target.</li>
+<li><tt>lib/CodeGen/SelectionDAG/DAGCombiner.cpp</tt>:
+ If your node can be combined with itself, or other existing nodes in a
+ peephole-like fashion, add a visit function for it, and call that function
+ from <tt></tt>. There are several good examples for simple combines you
+ can do; <tt>visitFABS</tt> and <tt>visitSRL</tt> are good starting places.
+ </li>
+<li><tt>lib/Target/PowerPC/PPCISelLowering.cpp</tt>:
+ Each target has an implementation of the <tt>TargetLowering</tt> class,
+ usually in its own file (although some targets include it in the same
+ file as the DAGToDAGISel). The default behavior for a target is to
+ assume that your new node is legal for all types that are legal for
+ that target. If this target does not natively support your node, then
+ tell the target to either Promote it (if it is supported at a larger
+ type) or Expand it. This will cause the code you wrote in
+ <tt>LegalizeOp</tt> above to decompose your new node into other legal
+ nodes for this target.</li>
+<li><tt>lib/Target/TargetSelectionDAG.td</tt>:
+ Most current targets supported by LLVM generate code using the DAGToDAG
+ method, where SelectionDAG nodes are pattern matched to target-specific
+ nodes, which represent individual instructions. In order for the targets
+ to match an instruction to your new node, you must add a def for that node
+ to the list in this file, with the appropriate type constraints. Look at
+ <tt>add</tt>, <tt>bswap</tt>, and <tt>fadd</tt> for examples.</li>
+<li><tt>lib/Target/PowerPC/PPCInstrInfo.td</tt>:
+ Each target has a tablegen file that describes the target's instruction
+ set. For targets that use the DAGToDAG instruction selection framework,
+ add a pattern for your new node that uses one or more target nodes.
+ Documentation for this is a bit sparse right now, but there are several
+ decent examples. See the patterns for <tt>rotl</tt> in
+ <tt>PPCInstrInfo.td</tt>.</li>
+<li>TODO: document complex patterns.</li>
+<li><tt>llvm/test/Regression/CodeGen/*</tt>: Add test cases for your new node
+ to the test suite. <tt>llvm/test/Regression/CodeGen/X86/bswap.ll</tt> is
+ a good example.</li>
+</ol>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="instruction">Adding a new instruction</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p><span class="doc_warning">WARNING: adding instructions changes the bitcode
+format, and it will take some effort to maintain compatibility with
+the previous version.</span> Only add an instruction if it is absolutely
+necessary.</p>
+
+<ol>
+
+<li><tt>llvm/include/llvm/Instruction.def</tt>:
+ add a number for your instruction and an enum name</li>
+
+<li><tt>llvm/include/llvm/Instructions.h</tt>:
+ add a definition for the class that will represent your instruction</li>
+
+<li><tt>llvm/include/llvm/Support/InstVisitor.h</tt>:
+ add a prototype for a visitor to your new instruction type</li>
+
+<li><tt>llvm/lib/AsmParser/Lexer.l</tt>:
+ add a new token to parse your instruction from assembly text file</li>
+
+<li><tt>llvm/lib/AsmParser/llvmAsmParser.y</tt>:
+ add the grammar on how your instruction can be read and what it will
+ construct as a result</li>
+
+<li><tt>llvm/lib/Bitcode/Reader/Reader.cpp</tt>:
+ add a case for your instruction and how it will be parsed from bitcode</li>
+
+<li><tt>llvm/lib/VMCore/Instruction.cpp</tt>:
+ add a case for how your instruction will be printed out to assembly</li>
+
+<li><tt>llvm/lib/VMCore/Instructions.cpp</tt>:
+ implement the class you defined in
+ <tt>llvm/include/llvm/Instructions.h</tt></li>
+
+<li>Test your instruction</li>
+
+<li><tt>llvm/lib/Target/*</tt>:
+ Add support for your instruction to code generators, or add a lowering
+ pass.</li>
+
+<li><tt>llvm/test/Regression/*</tt>: add your test cases to the test suite.</li>
+
+</ol>
+
+<p>Also, you need to implement (or modify) any analyses or passes that you want
+to understand this new instruction.</p>
+
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="type">Adding a new type</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p><span class="doc_warning">WARNING: adding new types changes the bitcode
+format, and will break compatibility with currently-existing LLVM
+installations.</span> Only add new types if it is absolutely necessary.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="fund_type">Adding a fundamental type</a>
+</h3>
+
+<div>
+
+<ol>
+
+<li><tt>llvm/include/llvm/Type.h</tt>:
+ add enum for the new type; add static <tt>Type*</tt> for this type</li>
+
+<li><tt>llvm/lib/VMCore/Type.cpp</tt>:
+ add mapping from <tt>TypeID</tt> =&gt; <tt>Type*</tt>;
+ initialize the static <tt>Type*</tt></li>
+
+<li><tt>llvm/lib/AsmReader/Lexer.l</tt>:
+ add ability to parse in the type from text assembly</li>
+
+<li><tt>llvm/lib/AsmReader/llvmAsmParser.y</tt>:
+ add a token for that type</li>
+
+</ol>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="derived_type">Adding a derived type</a>
+</h3>
+
+<div>
+
+<ol>
+<li><tt>llvm/include/llvm/Type.h</tt>:
+ add enum for the new type; add a forward declaration of the type
+ also</li>
+
+<li><tt>llvm/include/llvm/DerivedTypes.h</tt>:
+ add new class to represent new class in the hierarchy; add forward
+ declaration to the TypeMap value type</li>
+
+<li><tt>llvm/lib/VMCore/Type.cpp</tt>:
+ add support for derived type to:
+<div class="doc_code">
+<pre>
+std::string getTypeDescription(const Type &amp;Ty,
+ std::vector&lt;const Type*&gt; &amp;TypeStack)
+bool TypesEqual(const Type *Ty, const Type *Ty2,
+ std::map&lt;const Type*, const Type*&gt; &amp; EqTypes)
+</pre>
+</div>
+ add necessary member functions for type, and factory methods</li>
+
+<li><tt>llvm/lib/AsmReader/Lexer.l</tt>:
+ add ability to parse in the type from text assembly</li>
+
+<li><tt>llvm/lib/BitCode/Writer/Writer.cpp</tt>:
+ modify <tt>void BitcodeWriter::outputType(const Type *T)</tt> to serialize
+ your type</li>
+
+<li><tt>llvm/lib/BitCode/Reader/Reader.cpp</tt>:
+ modify <tt>const Type *BitcodeReader::ParseType()</tt> to read your data
+ type</li>
+
+<li><tt>llvm/lib/VMCore/AsmWriter.cpp</tt>:
+ modify
+<div class="doc_code">
+<pre>
+void calcTypeName(const Type *Ty,
+ std::vector&lt;const Type*&gt; &amp;TypeStack,
+ std::map&lt;const Type*,std::string&gt; &amp;TypeNames,
+ std::string &amp; Result)
+</pre>
+</div>
+ to output the new derived type
+</li>
+
+
+</ol>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a>
+ <br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/FAQ.rst b/docs/FAQ.rst
new file mode 100644
index 00000000000..b0e3ca04569
--- /dev/null
+++ b/docs/FAQ.rst
@@ -0,0 +1,464 @@
+.. _faq:
+
+================================
+Frequently Asked Questions (FAQ)
+================================
+
+.. contents::
+ :local:
+
+
+License
+=======
+
+Does the University of Illinois Open Source License really qualify as an "open source" license?
+-----------------------------------------------------------------------------------------------
+Yes, the license is `certified
+<http://www.opensource.org/licenses/UoI-NCSA.php>`_ by the Open Source
+Initiative (OSI).
+
+
+Can I modify LLVM source code and redistribute the modified source?
+-------------------------------------------------------------------
+Yes. The modified source distribution must retain the copyright notice and
+follow the three bulletted conditions listed in the `LLVM license
+<http://llvm.org/svn/llvm-project/llvm/trunk/LICENSE.TXT>`_.
+
+
+Can I modify the LLVM source code and redistribute binaries or other tools based on it, without redistributing the source?
+--------------------------------------------------------------------------------------------------------------------------
+Yes. This is why we distribute LLVM under a less restrictive license than GPL,
+as explained in the first question above.
+
+
+Source Code
+===========
+
+In what language is LLVM written?
+---------------------------------
+All of the LLVM tools and libraries are written in C++ with extensive use of
+the STL.
+
+
+How portable is the LLVM source code?
+-------------------------------------
+The LLVM source code should be portable to most modern Unix-like operating
+systems. Most of the code is written in standard C++ with operating system
+services abstracted to a support library. The tools required to build and
+test LLVM have been ported to a plethora of platforms.
+
+Some porting problems may exist in the following areas:
+
+* The autoconf/makefile build system relies heavily on UNIX shell tools,
+ like the Bourne Shell and sed. Porting to systems without these tools
+ (MacOS 9, Plan 9) will require more effort.
+
+
+Build Problems
+==============
+
+When I run configure, it finds the wrong C compiler.
+----------------------------------------------------
+The ``configure`` script attempts to locate first ``gcc`` and then ``cc``,
+unless it finds compiler paths set in ``CC`` and ``CXX`` for the C and C++
+compiler, respectively.
+
+If ``configure`` finds the wrong compiler, either adjust your ``PATH``
+environment variable or set ``CC`` and ``CXX`` explicitly.
+
+
+The ``configure`` script finds the right C compiler, but it uses the LLVM tools from a previous build. What do I do?
+---------------------------------------------------------------------------------------------------------------------
+The ``configure`` script uses the ``PATH`` to find executables, so if it's
+grabbing the wrong linker/assembler/etc, there are two ways to fix it:
+
+#. Adjust your ``PATH`` environment variable so that the correct program
+ appears first in the ``PATH``. This may work, but may not be convenient
+ when you want them *first* in your path for other work.
+
+#. Run ``configure`` with an alternative ``PATH`` that is correct. In a
+ Bourne compatible shell, the syntax would be:
+
+.. code-block:: bash
+
+ % PATH=[the path without the bad program] ./configure ...
+
+This is still somewhat inconvenient, but it allows ``configure`` to do its
+work without having to adjust your ``PATH`` permanently.
+
+
+When creating a dynamic library, I get a strange GLIBC error.
+-------------------------------------------------------------
+Under some operating systems (i.e. Linux), libtool does not work correctly if
+GCC was compiled with the ``--disable-shared option``. To work around this,
+install your own version of GCC that has shared libraries enabled by default.
+
+
+I've updated my source tree from Subversion, and now my build is trying to use a file/directory that doesn't exist.
+-------------------------------------------------------------------------------------------------------------------
+You need to re-run configure in your object directory. When new Makefiles
+are added to the source tree, they have to be copied over to the object tree
+in order to be used by the build.
+
+
+I've modified a Makefile in my source tree, but my build tree keeps using the old version. What do I do?
+---------------------------------------------------------------------------------------------------------
+If the Makefile already exists in your object tree, you can just run the
+following command in the top level directory of your object tree:
+
+.. code-block:: bash
+
+ % ./config.status <relative path to Makefile>;
+
+If the Makefile is new, you will have to modify the configure script to copy
+it over.
+
+
+I've upgraded to a new version of LLVM, and I get strange build errors.
+-----------------------------------------------------------------------
+Sometimes, changes to the LLVM source code alters how the build system works.
+Changes in ``libtool``, ``autoconf``, or header file dependencies are
+especially prone to this sort of problem.
+
+The best thing to try is to remove the old files and re-build. In most cases,
+this takes care of the problem. To do this, just type ``make clean`` and then
+``make`` in the directory that fails to build.
+
+
+I've built LLVM and am testing it, but the tests freeze.
+--------------------------------------------------------
+This is most likely occurring because you built a profile or release
+(optimized) build of LLVM and have not specified the same information on the
+``gmake`` command line.
+
+For example, if you built LLVM with the command:
+
+.. code-block:: bash
+
+ % gmake ENABLE_PROFILING=1
+
+...then you must run the tests with the following commands:
+
+.. code-block:: bash
+
+ % cd llvm/test
+ % gmake ENABLE_PROFILING=1
+
+Why do test results differ when I perform different types of builds?
+--------------------------------------------------------------------
+The LLVM test suite is dependent upon several features of the LLVM tools and
+libraries.
+
+First, the debugging assertions in code are not enabled in optimized or
+profiling builds. Hence, tests that used to fail may pass.
+
+Second, some tests may rely upon debugging options or behavior that is only
+available in the debug build. These tests will fail in an optimized or
+profile build.
+
+
+Compiling LLVM with GCC 3.3.2 fails, what should I do?
+------------------------------------------------------
+This is `a bug in GCC <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=13392>`_,
+and affects projects other than LLVM. Try upgrading or downgrading your GCC.
+
+
+Compiling LLVM with GCC succeeds, but the resulting tools do not work, what can be wrong?
+-----------------------------------------------------------------------------------------
+Several versions of GCC have shown a weakness in miscompiling the LLVM
+codebase. Please consult your compiler version (``gcc --version``) to find
+out whether it is `broken <GettingStarted.html#brokengcc>`_. If so, your only
+option is to upgrade GCC to a known good version.
+
+
+After Subversion update, rebuilding gives the error "No rule to make target".
+-----------------------------------------------------------------------------
+If the error is of the form:
+
+.. code-block:: bash
+
+ gmake[2]: *** No rule to make target `/path/to/somefile',
+ needed by `/path/to/another/file.d'.
+ Stop.
+
+This may occur anytime files are moved within the Subversion repository or
+removed entirely. In this case, the best solution is to erase all ``.d``
+files, which list dependencies for source files, and rebuild:
+
+.. code-block:: bash
+
+ % cd $LLVM_OBJ_DIR
+ % rm -f `find . -name \*\.d`
+ % gmake
+
+In other cases, it may be necessary to run ``make clean`` before rebuilding.
+
+
+Source Languages
+================
+
+What source languages are supported?
+------------------------------------
+LLVM currently has full support for C and C++ source languages. These are
+available through both `Clang <http://clang.llvm.org/>`_ and `DragonEgg
+<http://dragonegg.llvm.org/>`_.
+
+The PyPy developers are working on integrating LLVM into the PyPy backend so
+that PyPy language can translate to LLVM.
+
+
+I'd like to write a self-hosting LLVM compiler. How should I interface with the LLVM middle-end optimizers and back-end code generators?
+----------------------------------------------------------------------------------------------------------------------------------------
+Your compiler front-end will communicate with LLVM by creating a module in the
+LLVM intermediate representation (IR) format. Assuming you want to write your
+language's compiler in the language itself (rather than C++), there are 3
+major ways to tackle generating LLVM IR from a front-end:
+
+1. **Call into the LLVM libraries code using your language's FFI (foreign
+ function interface).**
+
+ * *for:* best tracks changes to the LLVM IR, .ll syntax, and .bc format
+
+ * *for:* enables running LLVM optimization passes without a emit/parse
+ overhead
+
+ * *for:* adapts well to a JIT context
+
+ * *against:* lots of ugly glue code to write
+
+2. **Emit LLVM assembly from your compiler's native language.**
+
+ * *for:* very straightforward to get started
+
+ * *against:* the .ll parser is slower than the bitcode reader when
+ interfacing to the middle end
+
+ * *against:* it may be harder to track changes to the IR
+
+3. **Emit LLVM bitcode from your compiler's native language.**
+
+ * *for:* can use the more-efficient bitcode reader when interfacing to the
+ middle end
+
+ * *against:* you'll have to re-engineer the LLVM IR object model and bitcode
+ writer in your language
+
+ * *against:* it may be harder to track changes to the IR
+
+If you go with the first option, the C bindings in include/llvm-c should help
+a lot, since most languages have strong support for interfacing with C. The
+most common hurdle with calling C from managed code is interfacing with the
+garbage collector. The C interface was designed to require very little memory
+management, and so is straightforward in this regard.
+
+What support is there for a higher level source language constructs for building a compiler?
+--------------------------------------------------------------------------------------------
+Currently, there isn't much. LLVM supports an intermediate representation
+which is useful for code representation but will not support the high level
+(abstract syntax tree) representation needed by most compilers. There are no
+facilities for lexical nor semantic analysis.
+
+
+I don't understand the ``GetElementPtr`` instruction. Help!
+-----------------------------------------------------------
+See `The Often Misunderstood GEP Instruction <GetElementPtr.html>`_.
+
+
+Using the C and C++ Front Ends
+==============================
+
+Can I compile C or C++ code to platform-independent LLVM bitcode?
+-----------------------------------------------------------------
+No. C and C++ are inherently platform-dependent languages. The most obvious
+example of this is the preprocessor. A very common way that C code is made
+portable is by using the preprocessor to include platform-specific code. In
+practice, information about other platforms is lost after preprocessing, so
+the result is inherently dependent on the platform that the preprocessing was
+targeting.
+
+Another example is ``sizeof``. It's common for ``sizeof(long)`` to vary
+between platforms. In most C front-ends, ``sizeof`` is expanded to a
+constant immediately, thus hard-wiring a platform-specific detail.
+
+Also, since many platforms define their ABIs in terms of C, and since LLVM is
+lower-level than C, front-ends currently must emit platform-specific IR in
+order to have the result conform to the platform ABI.
+
+
+Questions about code generated by the demo page
+===============================================
+
+What is this ``llvm.global_ctors`` and ``_GLOBAL__I_a...`` stuff that happens when I ``#include <iostream>``?
+-------------------------------------------------------------------------------------------------------------
+If you ``#include`` the ``<iostream>`` header into a C++ translation unit,
+the file will probably use the ``std::cin``/``std::cout``/... global objects.
+However, C++ does not guarantee an order of initialization between static
+objects in different translation units, so if a static ctor/dtor in your .cpp
+file used ``std::cout``, for example, the object would not necessarily be
+automatically initialized before your use.
+
+To make ``std::cout`` and friends work correctly in these scenarios, the STL
+that we use declares a static object that gets created in every translation
+unit that includes ``<iostream>``. This object has a static constructor
+and destructor that initializes and destroys the global iostream objects
+before they could possibly be used in the file. The code that you see in the
+``.ll`` file corresponds to the constructor and destructor registration code.
+
+If you would like to make it easier to *understand* the LLVM code generated
+by the compiler in the demo page, consider using ``printf()`` instead of
+``iostream``\s to print values.
+
+
+Where did all of my code go??
+-----------------------------
+If you are using the LLVM demo page, you may often wonder what happened to
+all of the code that you typed in. Remember that the demo script is running
+the code through the LLVM optimizers, so if your code doesn't actually do
+anything useful, it might all be deleted.
+
+To prevent this, make sure that the code is actually needed. For example, if
+you are computing some expression, return the value from the function instead
+of leaving it in a local variable. If you really want to constrain the
+optimizer, you can read from and assign to ``volatile`` global variables.
+
+
+What is this "``undef``" thing that shows up in my code?
+--------------------------------------------------------
+``undef`` is the LLVM way of representing a value that is not defined. You
+can get these if you do not initialize a variable before you use it. For
+example, the C function:
+
+.. code-block:: c
+
+ int X() { int i; return i; }
+
+Is compiled to "``ret i32 undef``" because "``i``" never has a value specified
+for it.
+
+
+Why does instcombine + simplifycfg turn a call to a function with a mismatched calling convention into "unreachable"? Why not make the verifier reject it?
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+This is a common problem run into by authors of front-ends that are using
+custom calling conventions: you need to make sure to set the right calling
+convention on both the function and on each call to the function. For
+example, this code:
+
+.. code-block:: llvm
+
+ define fastcc void @foo() {
+ ret void
+ }
+ define void @bar() {
+ call void @foo()
+ ret void
+ }
+
+Is optimized to:
+
+.. code-block:: llvm
+
+ define fastcc void @foo() {
+ ret void
+ }
+ define void @bar() {
+ unreachable
+ }
+
+... with "``opt -instcombine -simplifycfg``". This often bites people because
+"all their code disappears". Setting the calling convention on the caller and
+callee is required for indirect calls to work, so people often ask why not
+make the verifier reject this sort of thing.
+
+The answer is that this code has undefined behavior, but it is not illegal.
+If we made it illegal, then every transformation that could potentially create
+this would have to ensure that it doesn't, and there is valid code that can
+create this sort of construct (in dead code). The sorts of things that can
+cause this to happen are fairly contrived, but we still need to accept them.
+Here's an example:
+
+.. code-block:: llvm
+
+ define fastcc void @foo() {
+ ret void
+ }
+ define internal void @bar(void()* %FP, i1 %cond) {
+ br i1 %cond, label %T, label %F
+ T:
+ call void %FP()
+ ret void
+ F:
+ call fastcc void %FP()
+ ret void
+ }
+ define void @test() {
+ %X = or i1 false, false
+ call void @bar(void()* @foo, i1 %X)
+ ret void
+ }
+
+In this example, "test" always passes ``@foo``/``false`` into ``bar``, which
+ensures that it is dynamically called with the right calling conv (thus, the
+code is perfectly well defined). If you run this through the inliner, you
+get this (the explicit "or" is there so that the inliner doesn't dead code
+eliminate a bunch of stuff):
+
+.. code-block:: llvm
+
+ define fastcc void @foo() {
+ ret void
+ }
+ define void @test() {
+ %X = or i1 false, false
+ br i1 %X, label %T.i, label %F.i
+ T.i:
+ call void @foo()
+ br label %bar.exit
+ F.i:
+ call fastcc void @foo()
+ br label %bar.exit
+ bar.exit:
+ ret void
+ }
+
+Here you can see that the inlining pass made an undefined call to ``@foo``
+with the wrong calling convention. We really don't want to make the inliner
+have to know about this sort of thing, so it needs to be valid code. In this
+case, dead code elimination can trivially remove the undefined code. However,
+if ``%X`` was an input argument to ``@test``, the inliner would produce this:
+
+.. code-block:: llvm
+
+ define fastcc void @foo() {
+ ret void
+ }
+
+ define void @test(i1 %X) {
+ br i1 %X, label %T.i, label %F.i
+ T.i:
+ call void @foo()
+ br label %bar.exit
+ F.i:
+ call fastcc void @foo()
+ br label %bar.exit
+ bar.exit:
+ ret void
+ }
+
+The interesting thing about this is that ``%X`` *must* be false for the
+code to be well-defined, but no amount of dead code elimination will be able
+to delete the broken call as unreachable. However, since
+``instcombine``/``simplifycfg`` turns the undefined call into unreachable, we
+end up with a branch on a condition that goes to unreachable: a branch to
+unreachable can never happen, so "``-inline -instcombine -simplifycfg``" is
+able to produce:
+
+.. code-block:: llvm
+
+ define fastcc void @foo() {
+ ret void
+ }
+ define void @test(i1 %X) {
+ F.i:
+ call fastcc void @foo()
+ ret void
+ }
diff --git a/docs/GCCFEBuildInstrs.html b/docs/GCCFEBuildInstrs.html
new file mode 100644
index 00000000000..0caf9d86186
--- /dev/null
+++ b/docs/GCCFEBuildInstrs.html
@@ -0,0 +1,279 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css" media="screen">
+ <title>Building the LLVM GCC Front-End</title>
+</head>
+<body>
+
+<h1>
+ Building the LLVM GCC Front-End
+</h1>
+
+<ol>
+ <li><a href="#instructions">Building llvm-gcc from Source</a></li>
+ <li><a href="#ada">Building the Ada front-end</a></li>
+ <li><a href="#fortran">Building the Fortran front-end</a></li>
+ <li><a href="#license">License Information</a></li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by the LLVM Team</p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="instructions">Building llvm-gcc from Source</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This section describes how to acquire and build llvm-gcc 4.2, which is based
+on the GCC 4.2.1 front-end. Supported languages are Ada, C, C++, Fortran,
+Objective-C and Objective-C++. Note that the instructions for building these
+front-ends are completely different (and much easier!) than those for building
+llvm-gcc3 in the past.</p>
+
+<ol>
+ <li><p>Retrieve the appropriate llvm-gcc-4.2-<i>version</i>.source.tar.gz
+ archive from the <a href="http://llvm.org/releases/">LLVM web
+ site</a>.</p>
+
+ <p>It is also possible to download the sources of the llvm-gcc front end
+ from a read-only mirror using subversion. To check out the 4.2 code
+ for first time use:</p>
+
+<div class="doc_code">
+<pre>
+svn co http://llvm.org/svn/llvm-project/llvm-gcc-4.2/trunk <i>dst-directory</i>
+</pre>
+</div>
+
+ <p>After that, the code can be be updated in the destination directory
+ using:</p>
+
+<div class="doc_code">
+<pre>svn update</pre>
+</div>
+
+ <p>The mirror is brought up to date every evening.</p></li>
+
+ <li>Follow the directions in the top-level <tt>README.LLVM</tt> file for
+ up-to-date instructions on how to build llvm-gcc. See below for building
+ with support for Ada or Fortran.
+</ol>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="ada">Building the Ada front-end</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+<p>Building with support for Ada amounts to following the directions in the
+top-level <tt>README.LLVM</tt> file, adding ",ada" to EXTRALANGS, for example:
+<tt>EXTRALANGS=,ada</tt></p>
+
+<p>There are some complications however:</p>
+
+<ol>
+ <li><p>The only platform for which the Ada front-end is known to build is
+ 32 bit intel x86 running linux. It is unlikely to build for other
+ systems without some work.</p></li>
+ <li><p>The build requires having a compiler that supports Ada, C and C++.
+ The Ada front-end is written in Ada so an Ada compiler is needed to
+ build it. Compilers known to work with the
+ <a href="http://llvm.org/releases/download.html">LLVM 2.7 release</a>
+ are <a href="http://gcc.gnu.org/releases.html">gcc-4.2</a> and the
+ 2005, 2006 and 2007 versions of the
+ <a href="http://libre.adacore.com/">GNAT GPL Edition</a>.
+ <b>GNAT GPL 2008, gcc-4.3 and later will not work</b>.
+ The LLVM parts of llvm-gcc are written in C++ so a C++ compiler is
+ needed to build them. The rest of gcc is written in C.
+ Some linux distributions provide a version of gcc that supports all
+ three languages (the Ada part often comes as an add-on package to
+ the rest of gcc). Otherwise it is possible to combine two versions
+ of gcc, one that supports Ada and C (such as the
+ <a href="http://libre.adacore.com/">2007 GNAT GPL Edition</a>)
+ and another which supports C++, see below.</p></li>
+ <li><p>Because the Ada front-end is experimental, it is wise to build the
+ compiler with checking enabled. This causes it to run much slower, but
+ helps catch mistakes in the compiler (please report any problems using
+ <a href="http://llvm.org/bugs/">LLVM bugzilla</a>).</p></li>
+ <li><p>The Ada front-end <a href="http://llvm.org/PR2007">fails to
+ bootstrap</a>, due to lack of LLVM support for
+ <tt>setjmp</tt>/<tt>longjmp</tt> style exception handling (used
+ internally by the compiler), so you must specify
+ <tt>--disable-bootstrap</tt>.</p></li>
+</ol>
+
+<p>Supposing appropriate compilers are available, llvm-gcc with Ada support can
+ be built on an x86-32 linux box using the following recipe:</p>
+
+<ol>
+ <li><p>Download the <a href="http://llvm.org/releases/download.html">LLVM source</a>
+ and unpack it:</p>
+
+<pre class="doc_code">
+wget http://llvm.org/releases/2.7/llvm-2.7.tgz
+tar xzf llvm-2.7.tgz
+mv llvm-2.7 llvm
+</pre>
+
+ <p>or <a href="GettingStarted.html#checkout">check out the
+ latest version from subversion</a>:</p>
+
+<pre class="doc_code">svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm</pre>
+
+ </li>
+
+ <li><p>Download the
+ <a href="http://llvm.org/releases/download.html">llvm-gcc-4.2 source</a>
+ and unpack it:</p>
+
+<pre class="doc_code">
+wget http://llvm.org/releases/2.7/llvm-gcc-4.2-2.7.source.tgz
+tar xzf llvm-gcc-4.2-2.7.source.tgz
+mv llvm-gcc-4.2-2.7.source llvm-gcc-4.2
+</pre>
+
+ <p>or <a href="GettingStarted.html#checkout">check out the
+ latest version from subversion</a>:</p>
+
+<pre class="doc_code">
+svn co http://llvm.org/svn/llvm-project/llvm-gcc-4.2/trunk llvm-gcc-4.2
+</pre>
+ </li>
+
+ <li><p>Make a build directory <tt>llvm-objects</tt> for llvm and make it the
+ current directory:</p>
+
+<pre class="doc_code">
+mkdir llvm-objects
+cd llvm-objects
+</pre>
+ </li>
+
+ <li><p>Configure LLVM (here it is configured to install into <tt>/usr/local</tt>):</p>
+
+<pre class="doc_code">
+../llvm/configure --prefix=<b>/usr/local</b> --enable-optimized --enable-assertions
+</pre>
+
+ <p>If you have a multi-compiler setup and the C++ compiler is not the
+ default, then you can configure like this:</p>
+
+<pre class="doc_code">
+CXX=<b>PATH_TO_C++_COMPILER</b> ../llvm/configure --prefix=<b>/usr/local</b> --enable-optimized --enable-assertions
+</pre>
+
+ <p>To compile without checking (not recommended), replace
+ <tt>--enable-assertions</tt> with <tt>--disable-assertions</tt>.</p>
+
+ </li>
+
+ <li><p>Build LLVM:</p>
+
+<pre class="doc_code">
+make
+</pre>
+ </li>
+
+ <li><p>Install LLVM (optional):</p>
+
+<pre class="doc_code">
+make install
+</pre>
+ </li>
+
+ <li><p>Make a build directory <tt>llvm-gcc-4.2-objects</tt> for llvm-gcc and make it the
+ current directory:</p>
+
+<pre class="doc_code">
+cd ..
+mkdir llvm-gcc-4.2-objects
+cd llvm-gcc-4.2-objects
+</pre>
+ </li>
+
+ <li><p>Configure llvm-gcc (here it is configured to install into <tt>/usr/local</tt>).
+ The <tt>--enable-checking</tt> flag turns on sanity checks inside the compiler.
+ To turn off these checks (not recommended), replace <tt>--enable-checking</tt>
+ with <tt>--disable-checking</tt>.
+ Additional languages can be appended to the <tt>--enable-languages</tt> switch,
+ for example <tt>--enable-languages=ada,c,c++</tt>.</p>
+
+<pre class="doc_code">
+../llvm-gcc-4.2/configure --prefix=<b>/usr/local</b> --enable-languages=ada,c \
+ --enable-checking --enable-llvm=$PWD/../llvm-objects \
+ --disable-bootstrap --disable-multilib
+</pre>
+
+ <p>If you have a multi-compiler setup, then you can configure like this:</p>
+
+<pre class="doc_code">
+export CC=<b>PATH_TO_C_AND_ADA_COMPILER</b>
+export CXX=<b>PATH_TO_C++_COMPILER</b>
+../llvm-gcc-4.2/configure --prefix=<b>/usr/local</b> --enable-languages=ada,c \
+ --enable-checking --enable-llvm=$PWD/../llvm-objects \
+ --disable-bootstrap --disable-multilib
+</pre>
+ </li>
+
+ <li><p>Build and install the compiler:</p>
+
+<pre class="doc_code">
+make
+make install
+</pre>
+ </li>
+</ol>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="fortran">Building the Fortran front-end</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+<p>To build with support for Fortran, follow the directions in the top-level
+<tt>README.LLVM</tt> file, adding ",fortran" to EXTRALANGS, for example:</p>
+
+<pre class="doc_code">
+EXTRALANGS=,fortran
+</pre>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="license">License Information</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+<p>
+The LLVM GCC frontend is licensed to you under the GNU General Public License
+and the GNU Lesser General Public License. Please see the files COPYING and
+COPYING.LIB for more details.
+</p>
+
+<p>
+More information is <a href="FAQ.html#license">available in the FAQ</a>.
+</p>
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/GarbageCollection.html b/docs/GarbageCollection.html
new file mode 100644
index 00000000000..20f2c96a2b5
--- /dev/null
+++ b/docs/GarbageCollection.html
@@ -0,0 +1,1389 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" Content="text/html; charset=UTF-8" >
+ <title>Accurate Garbage Collection with LLVM</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+ <style type="text/css">
+ .rowhead { text-align: left; background: inherit; }
+ .indent { padding-left: 1em; }
+ .optl { color: #BFBFBF; }
+ </style>
+</head>
+<body>
+
+<h1>
+ Accurate Garbage Collection with LLVM
+</h1>
+
+<ol>
+ <li><a href="#introduction">Introduction</a>
+ <ul>
+ <li><a href="#feature">Goals and non-goals</a></li>
+ </ul>
+ </li>
+
+ <li><a href="#quickstart">Getting started</a>
+ <ul>
+ <li><a href="#quickstart-compiler">In your compiler</a></li>
+ <li><a href="#quickstart-runtime">In your runtime library</a></li>
+ <li><a href="#shadow-stack">About the shadow stack</a></li>
+ </ul>
+ </li>
+
+ <li><a href="#core">Core support</a>
+ <ul>
+ <li><a href="#gcattr">Specifying GC code generation:
+ <tt>gc "..."</tt></a></li>
+ <li><a href="#gcroot">Identifying GC roots on the stack:
+ <tt>llvm.gcroot</tt></a></li>
+ <li><a href="#barriers">Reading and writing references in the heap</a>
+ <ul>
+ <li><a href="#gcwrite">Write barrier: <tt>llvm.gcwrite</tt></a></li>
+ <li><a href="#gcread">Read barrier: <tt>llvm.gcread</tt></a></li>
+ </ul>
+ </li>
+ </ul>
+ </li>
+
+ <li><a href="#plugin">Compiler plugin interface</a>
+ <ul>
+ <li><a href="#collector-algos">Overview of available features</a></li>
+ <li><a href="#stack-map">Computing stack maps</a></li>
+ <li><a href="#init-roots">Initializing roots to null:
+ <tt>InitRoots</tt></a></li>
+ <li><a href="#custom">Custom lowering of intrinsics: <tt>CustomRoots</tt>,
+ <tt>CustomReadBarriers</tt>, and <tt>CustomWriteBarriers</tt></a></li>
+ <li><a href="#safe-points">Generating safe points:
+ <tt>NeededSafePoints</tt></a></li>
+ <li><a href="#assembly">Emitting assembly code:
+ <tt>GCMetadataPrinter</tt></a></li>
+ </ul>
+ </li>
+
+ <li><a href="#runtime-impl">Implementing a collector runtime</a>
+ <ul>
+ <li><a href="#gcdescriptors">Tracing GC pointers from heap
+ objects</a></li>
+ </ul>
+ </li>
+
+ <li><a href="#references">References</a></li>
+
+</ol>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a> and
+ Gordon Henriksen</p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="introduction">Introduction</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Garbage collection is a widely used technique that frees the programmer from
+having to know the lifetimes of heap objects, making software easier to produce
+and maintain. Many programming languages rely on garbage collection for
+automatic memory management. There are two primary forms of garbage collection:
+conservative and accurate.</p>
+
+<p>Conservative garbage collection often does not require any special support
+from either the language or the compiler: it can handle non-type-safe
+programming languages (such as C/C++) and does not require any special
+information from the compiler. The
+<a href="http://www.hpl.hp.com/personal/Hans_Boehm/gc/">Boehm collector</a> is
+an example of a state-of-the-art conservative collector.</p>
+
+<p>Accurate garbage collection requires the ability to identify all pointers in
+the program at run-time (which requires that the source-language be type-safe in
+most cases). Identifying pointers at run-time requires compiler support to
+locate all places that hold live pointer variables at run-time, including the
+<a href="#gcroot">processor stack and registers</a>.</p>
+
+<p>Conservative garbage collection is attractive because it does not require any
+special compiler support, but it does have problems. In particular, because the
+conservative garbage collector cannot <i>know</i> that a particular word in the
+machine is a pointer, it cannot move live objects in the heap (preventing the
+use of compacting and generational GC algorithms) and it can occasionally suffer
+from memory leaks due to integer values that happen to point to objects in the
+program. In addition, some aggressive compiler transformations can break
+conservative garbage collectors (though these seem rare in practice).</p>
+
+<p>Accurate garbage collectors do not suffer from any of these problems, but
+they can suffer from degraded scalar optimization of the program. In particular,
+because the runtime must be able to identify and update all pointers active in
+the program, some optimizations are less effective. In practice, however, the
+locality and performance benefits of using aggressive garbage collection
+techniques dominates any low-level losses.</p>
+
+<p>This document describes the mechanisms and interfaces provided by LLVM to
+support accurate garbage collection.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="feature">Goals and non-goals</a>
+</h3>
+
+<div>
+
+<p>LLVM's intermediate representation provides <a href="#intrinsics">garbage
+collection intrinsics</a> that offer support for a broad class of
+collector models. For instance, the intrinsics permit:</p>
+
+<ul>
+ <li>semi-space collectors</li>
+ <li>mark-sweep collectors</li>
+ <li>generational collectors</li>
+ <li>reference counting</li>
+ <li>incremental collectors</li>
+ <li>concurrent collectors</li>
+ <li>cooperative collectors</li>
+</ul>
+
+<p>We hope that the primitive support built into the LLVM IR is sufficient to
+support a broad class of garbage collected languages including Scheme, ML, Java,
+C#, Perl, Python, Lua, Ruby, other scripting languages, and more.</p>
+
+<p>However, LLVM does not itself provide a garbage collector&mdash;this should
+be part of your language's runtime library. LLVM provides a framework for
+compile time <a href="#plugin">code generation plugins</a>. The role of these
+plugins is to generate code and data structures which conforms to the <em>binary
+interface</em> specified by the <em>runtime library</em>. This is similar to the
+relationship between LLVM and DWARF debugging info, for example. The
+difference primarily lies in the lack of an established standard in the domain
+of garbage collection&mdash;thus the plugins.</p>
+
+<p>The aspects of the binary interface with which LLVM's GC support is
+concerned are:</p>
+
+<ul>
+ <li>Creation of GC-safe points within code where collection is allowed to
+ execute safely.</li>
+ <li>Computation of the stack map. For each safe point in the code, object
+ references within the stack frame must be identified so that the
+ collector may traverse and perhaps update them.</li>
+ <li>Write barriers when storing object references to the heap. These are
+ commonly used to optimize incremental scans in generational
+ collectors.</li>
+ <li>Emission of read barriers when loading object references. These are
+ useful for interoperating with concurrent collectors.</li>
+</ul>
+
+<p>There are additional areas that LLVM does not directly address:</p>
+
+<ul>
+ <li>Registration of global roots with the runtime.</li>
+ <li>Registration of stack map entries with the runtime.</li>
+ <li>The functions used by the program to allocate memory, trigger a
+ collection, etc.</li>
+ <li>Computation or compilation of type maps, or registration of them with
+ the runtime. These are used to crawl the heap for object
+ references.</li>
+</ul>
+
+<p>In general, LLVM's support for GC does not include features which can be
+adequately addressed with other features of the IR and does not specify a
+particular binary interface. On the plus side, this means that you should be
+able to integrate LLVM with an existing runtime. On the other hand, it leaves
+a lot of work for the developer of a novel language. However, it's easy to get
+started quickly and scale up to a more sophisticated implementation as your
+compiler matures.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="quickstart">Getting started</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Using a GC with LLVM implies many things, for example:</p>
+
+<ul>
+ <li>Write a runtime library or find an existing one which implements a GC
+ heap.<ol>
+ <li>Implement a memory allocator.</li>
+ <li>Design a binary interface for the stack map, used to identify
+ references within a stack frame on the machine stack.*</li>
+ <li>Implement a stack crawler to discover functions on the call stack.*</li>
+ <li>Implement a registry for global roots.</li>
+ <li>Design a binary interface for type maps, used to identify references
+ within heap objects.</li>
+ <li>Implement a collection routine bringing together all of the above.</li>
+ </ol></li>
+ <li>Emit compatible code from your compiler.<ul>
+ <li>Initialization in the main function.</li>
+ <li>Use the <tt>gc "..."</tt> attribute to enable GC code generation
+ (or <tt>F.setGC("...")</tt>).</li>
+ <li>Use <tt>@llvm.gcroot</tt> to mark stack roots.</li>
+ <li>Use <tt>@llvm.gcread</tt> and/or <tt>@llvm.gcwrite</tt> to
+ manipulate GC references, if necessary.</li>
+ <li>Allocate memory using the GC allocation routine provided by the
+ runtime library.</li>
+ <li>Generate type maps according to your runtime's binary interface.</li>
+ </ul></li>
+ <li>Write a compiler plugin to interface LLVM with the runtime library.*<ul>
+ <li>Lower <tt>@llvm.gcread</tt> and <tt>@llvm.gcwrite</tt> to appropriate
+ code sequences.*</li>
+ <li>Compile LLVM's stack map to the binary form expected by the
+ runtime.</li>
+ </ul></li>
+ <li>Load the plugin into the compiler. Use <tt>llc -load</tt> or link the
+ plugin statically with your language's compiler.*</li>
+ <li>Link program executables with the runtime.</li>
+</ul>
+
+<p>To help with several of these tasks (those indicated with a *), LLVM
+includes a highly portable, built-in ShadowStack code generator. It is compiled
+into <tt>llc</tt> and works even with the interpreter and C backends.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="quickstart-compiler">In your compiler</a>
+</h3>
+
+<div>
+
+<p>To turn the shadow stack on for your functions, first call:</p>
+
+<div class="doc_code"><pre
+>F.setGC("shadow-stack");</pre></div>
+
+<p>for each function your compiler emits. Since the shadow stack is built into
+LLVM, you do not need to load a plugin.</p>
+
+<p>Your compiler must also use <tt>@llvm.gcroot</tt> as documented.
+Don't forget to create a root for each intermediate value that is generated
+when evaluating an expression. In <tt>h(f(), g())</tt>, the result of
+<tt>f()</tt> could easily be collected if evaluating <tt>g()</tt> triggers a
+collection.</p>
+
+<p>There's no need to use <tt>@llvm.gcread</tt> and <tt>@llvm.gcwrite</tt> over
+plain <tt>load</tt> and <tt>store</tt> for now. You will need them when
+switching to a more advanced GC.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="quickstart-runtime">In your runtime</a>
+</h3>
+
+<div>
+
+<p>The shadow stack doesn't imply a memory allocation algorithm. A semispace
+collector or building atop <tt>malloc</tt> are great places to start, and can
+be implemented with very little code.</p>
+
+<p>When it comes time to collect, however, your runtime needs to traverse the
+stack roots, and for this it needs to integrate with the shadow stack. Luckily,
+doing so is very simple. (This code is heavily commented to help you
+understand the data structure, but there are only 20 lines of meaningful
+code.)</p>
+
+<pre class="doc_code">
+/// @brief The map for a single function's stack frame. One of these is
+/// compiled as constant data into the executable for each function.
+///
+/// Storage of metadata values is elided if the %metadata parameter to
+/// @llvm.gcroot is null.
+struct FrameMap {
+ int32_t NumRoots; //&lt; Number of roots in stack frame.
+ int32_t NumMeta; //&lt; Number of metadata entries. May be &lt; NumRoots.
+ const void *Meta[0]; //&lt; Metadata for each root.
+};
+
+/// @brief A link in the dynamic shadow stack. One of these is embedded in the
+/// stack frame of each function on the call stack.
+struct StackEntry {
+ StackEntry *Next; //&lt; Link to next stack entry (the caller's).
+ const FrameMap *Map; //&lt; Pointer to constant FrameMap.
+ void *Roots[0]; //&lt; Stack roots (in-place array).
+};
+
+/// @brief The head of the singly-linked list of StackEntries. Functions push
+/// and pop onto this in their prologue and epilogue.
+///
+/// Since there is only a global list, this technique is not threadsafe.
+StackEntry *llvm_gc_root_chain;
+
+/// @brief Calls Visitor(root, meta) for each GC root on the stack.
+/// root and meta are exactly the values passed to
+/// <tt>@llvm.gcroot</tt>.
+///
+/// Visitor could be a function to recursively mark live objects. Or it
+/// might copy them to another heap or generation.
+///
+/// @param Visitor A function to invoke for every GC root on the stack.
+void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
+ for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
+ unsigned i = 0;
+
+ // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
+ for (unsigned e = R->Map->NumMeta; i != e; ++i)
+ Visitor(&amp;R->Roots[i], R->Map->Meta[i]);
+
+ // For roots [NumMeta, NumRoots), the metadata pointer is null.
+ for (unsigned e = R->Map->NumRoots; i != e; ++i)
+ Visitor(&amp;R->Roots[i], NULL);
+ }
+}</pre>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="shadow-stack">About the shadow stack</a>
+</h3>
+
+<div>
+
+<p>Unlike many GC algorithms which rely on a cooperative code generator to
+compile stack maps, this algorithm carefully maintains a linked list of stack
+roots [<a href="#henderson02">Henderson2002</a>]. This so-called "shadow stack"
+mirrors the machine stack. Maintaining this data structure is slower than using
+a stack map compiled into the executable as constant data, but has a significant
+portability advantage because it requires no special support from the target
+code generator, and does not require tricky platform-specific code to crawl
+the machine stack.</p>
+
+<p>The tradeoff for this simplicity and portability is:</p>
+
+<ul>
+ <li>High overhead per function call.</li>
+ <li>Not thread-safe.</li>
+</ul>
+
+<p>Still, it's an easy way to get started. After your compiler and runtime are
+up and running, writing a <a href="#plugin">plugin</a> will allow you to take
+advantage of <a href="#collector-algos">more advanced GC features</a> of LLVM
+in order to improve performance.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="core">IR features</a><a name="intrinsics"></a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This section describes the garbage collection facilities provided by the
+<a href="LangRef.html">LLVM intermediate representation</a>. The exact behavior
+of these IR features is specified by the binary interface implemented by a
+<a href="#plugin">code generation plugin</a>, not by this document.</p>
+
+<p>These facilities are limited to those strictly necessary; they are not
+intended to be a complete interface to any garbage collector. A program will
+need to interface with the GC library using the facilities provided by that
+program.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="gcattr">Specifying GC code generation: <tt>gc "..."</tt></a>
+</h3>
+
+<div>
+
+<div class="doc_code"><tt>
+ define <i>ty</i> @<i>name</i>(...) <span style="text-decoration: underline">gc "<i>name</i>"</span> { ...
+</tt></div>
+
+<p>The <tt>gc</tt> function attribute is used to specify the desired GC style
+to the compiler. Its programmatic equivalent is the <tt>setGC</tt> method of
+<tt>Function</tt>.</p>
+
+<p>Setting <tt>gc "<i>name</i>"</tt> on a function triggers a search for a
+matching code generation plugin "<i>name</i>"; it is that plugin which defines
+the exact nature of the code generated to support GC. If none is found, the
+compiler will raise an error.</p>
+
+<p>Specifying the GC style on a per-function basis allows LLVM to link together
+programs that use different garbage collection algorithms (or none at all).</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="gcroot">Identifying GC roots on the stack: <tt>llvm.gcroot</tt></a>
+</h3>
+
+<div>
+
+<div class="doc_code"><tt>
+ void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
+</tt></div>
+
+<p>The <tt>llvm.gcroot</tt> intrinsic is used to inform LLVM that a stack
+variable references an object on the heap and is to be tracked for garbage
+collection. The exact impact on generated code is specified by a <a
+href="#plugin">compiler plugin</a>. All calls to <tt>llvm.gcroot</tt> <b>must</b> reside
+ inside the first basic block.</p>
+
+<p>A compiler which uses mem2reg to raise imperative code using <tt>alloca</tt>
+into SSA form need only add a call to <tt>@llvm.gcroot</tt> for those variables
+which a pointers into the GC heap.</p>
+
+<p>It is also important to mark intermediate values with <tt>llvm.gcroot</tt>.
+For example, consider <tt>h(f(), g())</tt>. Beware leaking the result of
+<tt>f()</tt> in the case that <tt>g()</tt> triggers a collection. Note, that
+stack variables must be initialized and marked with <tt>llvm.gcroot</tt> in
+function's prologue.</p>
+
+<p>The first argument <b>must</b> be a value referring to an alloca instruction
+or a bitcast of an alloca. The second contains a pointer to metadata that
+should be associated with the pointer, and <b>must</b> be a constant or global
+value address. If your target collector uses tags, use a null pointer for
+metadata.</p>
+
+<p>The <tt>%metadata</tt> argument can be used to avoid requiring heap objects
+to have 'isa' pointers or tag bits. [<a href="#appel89">Appel89</a>, <a
+href="#goldberg91">Goldberg91</a>, <a href="#tolmach94">Tolmach94</a>] If
+specified, its value will be tracked along with the location of the pointer in
+the stack frame.</p>
+
+<p>Consider the following fragment of Java code:</p>
+
+<pre class="doc_code">
+ {
+ Object X; // A null-initialized reference to an object
+ ...
+ }
+</pre>
+
+<p>This block (which may be located in the middle of a function or in a loop
+nest), could be compiled to this LLVM code:</p>
+
+<pre class="doc_code">
+Entry:
+ ;; In the entry block for the function, allocate the
+ ;; stack space for X, which is an LLVM pointer.
+ %X = alloca %Object*
+
+ ;; Tell LLVM that the stack space is a stack root.
+ ;; Java has type-tags on objects, so we pass null as metadata.
+ %tmp = bitcast %Object** %X to i8**
+ call void @llvm.gcroot(i8** %tmp, i8* null)
+ ...
+
+ ;; "CodeBlock" is the block corresponding to the start
+ ;; of the scope above.
+CodeBlock:
+ ;; Java null-initializes pointers.
+ store %Object* null, %Object** %X
+
+ ...
+
+ ;; As the pointer goes out of scope, store a null value into
+ ;; it, to indicate that the value is no longer live.
+ store %Object* null, %Object** %X
+ ...
+</pre>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="barriers">Reading and writing references in the heap</a>
+</h3>
+
+<div>
+
+<p>Some collectors need to be informed when the mutator (the program that needs
+garbage collection) either reads a pointer from or writes a pointer to a field
+of a heap object. The code fragments inserted at these points are called
+<em>read barriers</em> and <em>write barriers</em>, respectively. The amount of
+code that needs to be executed is usually quite small and not on the critical
+path of any computation, so the overall performance impact of the barrier is
+tolerable.</p>
+
+<p>Barriers often require access to the <em>object pointer</em> rather than the
+<em>derived pointer</em> (which is a pointer to the field within the
+object). Accordingly, these intrinsics take both pointers as separate arguments
+for completeness. In this snippet, <tt>%object</tt> is the object pointer, and
+<tt>%derived</tt> is the derived pointer:</p>
+
+<blockquote><pre>
+ ;; An array type.
+ %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
+ ...
+
+ ;; Load the object pointer from a gcroot.
+ %object = load %class.Array** %object_addr
+
+ ;; Compute the derived pointer.
+ %derived = getelementptr %object, i32 0, i32 2, i32 %n</pre></blockquote>
+
+<p>LLVM does not enforce this relationship between the object and derived
+pointer (although a <a href="#plugin">plugin</a> might). However, it would be
+an unusual collector that violated it.</p>
+
+<p>The use of these intrinsics is naturally optional if the target GC does
+require the corresponding barrier. Such a GC plugin will replace the intrinsic
+calls with the corresponding <tt>load</tt> or <tt>store</tt> instruction if they
+are used.</p>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="gcwrite">Write barrier: <tt>llvm.gcwrite</tt></a>
+</h4>
+
+<div>
+
+<div class="doc_code"><tt>
+void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
+</tt></div>
+
+<p>For write barriers, LLVM provides the <tt>llvm.gcwrite</tt> intrinsic
+function. It has exactly the same semantics as a non-volatile <tt>store</tt> to
+the derived pointer (the third argument). The exact code generated is specified
+by a <a href="#plugin">compiler plugin</a>.</p>
+
+<p>Many important algorithms require write barriers, including generational
+and concurrent collectors. Additionally, write barriers could be used to
+implement reference counting.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="gcread">Read barrier: <tt>llvm.gcread</tt></a>
+</h4>
+
+<div>
+
+<div class="doc_code"><tt>
+i8* @llvm.gcread(i8* %object, i8** %derived)<br>
+</tt></div>
+
+<p>For read barriers, LLVM provides the <tt>llvm.gcread</tt> intrinsic function.
+It has exactly the same semantics as a non-volatile <tt>load</tt> from the
+derived pointer (the second argument). The exact code generated is specified by
+a <a href="#plugin">compiler plugin</a>.</p>
+
+<p>Read barriers are needed by fewer algorithms than write barriers, and may
+have a greater performance impact since pointer reads are more frequent than
+writes.</p>
+
+</div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="plugin">Implementing a collector plugin</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>User code specifies which GC code generation to use with the <tt>gc</tt>
+function attribute or, equivalently, with the <tt>setGC</tt> method of
+<tt>Function</tt>.</p>
+
+<p>To implement a GC plugin, it is necessary to subclass
+<tt>llvm::GCStrategy</tt>, which can be accomplished in a few lines of
+boilerplate code. LLVM's infrastructure provides access to several important
+algorithms. For an uncontroversial collector, all that remains may be to
+compile LLVM's computed stack map to assembly code (using the binary
+representation expected by the runtime library). This can be accomplished in
+about 100 lines of code.</p>
+
+<p>This is not the appropriate place to implement a garbage collected heap or a
+garbage collector itself. That code should exist in the language's runtime
+library. The compiler plugin is responsible for generating code which
+conforms to the binary interface defined by library, most essentially the
+<a href="#stack-map">stack map</a>.</p>
+
+<p>To subclass <tt>llvm::GCStrategy</tt> and register it with the compiler:</p>
+
+<blockquote><pre>// lib/MyGC/MyGC.cpp - Example LLVM GC plugin
+
+#include "llvm/CodeGen/GCStrategy.h"
+#include "llvm/CodeGen/GCMetadata.h"
+#include "llvm/Support/Compiler.h"
+
+using namespace llvm;
+
+namespace {
+ class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
+ public:
+ MyGC() {}
+ };
+
+ GCRegistry::Add&lt;MyGC&gt;
+ X("mygc", "My bespoke garbage collector.");
+}</pre></blockquote>
+
+<p>This boilerplate collector does nothing. More specifically:</p>
+
+<ul>
+ <li><tt>llvm.gcread</tt> calls are replaced with the corresponding
+ <tt>load</tt> instruction.</li>
+ <li><tt>llvm.gcwrite</tt> calls are replaced with the corresponding
+ <tt>store</tt> instruction.</li>
+ <li>No safe points are added to the code.</li>
+ <li>The stack map is not compiled into the executable.</li>
+</ul>
+
+<p>Using the LLVM makefiles (like the <a
+href="http://llvm.org/viewvc/llvm-project/llvm/trunk/projects/sample/">sample
+project</a>), this code can be compiled as a plugin using a simple
+makefile:</p>
+
+<blockquote><pre
+># lib/MyGC/Makefile
+
+LEVEL := ../..
+LIBRARYNAME = <var>MyGC</var>
+LOADABLE_MODULE = 1
+
+include $(LEVEL)/Makefile.common</pre></blockquote>
+
+<p>Once the plugin is compiled, code using it may be compiled using <tt>llc
+-load=<var>MyGC.so</var></tt> (though <var>MyGC.so</var> may have some other
+platform-specific extension):</p>
+
+<blockquote><pre
+>$ cat sample.ll
+define void @f() gc "mygc" {
+entry:
+ ret void
+}
+$ llvm-as &lt; sample.ll | llc -load=MyGC.so</pre></blockquote>
+
+<p>It is also possible to statically link the collector plugin into tools, such
+as a language-specific compiler front-end.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="collector-algos">Overview of available features</a>
+</h3>
+
+<div>
+
+<p><tt>GCStrategy</tt> provides a range of features through which a plugin
+may do useful work. Some of these are callbacks, some are algorithms that can
+be enabled, disabled, or customized. This matrix summarizes the supported (and
+planned) features and correlates them with the collection techniques which
+typically require them.</p>
+
+<table>
+ <tr>
+ <th>Algorithm</th>
+ <th>Done</th>
+ <th>shadow stack</th>
+ <th>refcount</th>
+ <th>mark-sweep</th>
+ <th>copying</th>
+ <th>incremental</th>
+ <th>threaded</th>
+ <th>concurrent</th>
+ </tr>
+ <tr>
+ <th class="rowhead"><a href="#stack-map">stack map</a></th>
+ <td>&#10004;</td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ </tr>
+ <tr>
+ <th class="rowhead"><a href="#init-roots">initialize roots</a></th>
+ <td>&#10004;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ </tr>
+ <tr class="doc_warning">
+ <th class="rowhead">derived pointers</th>
+ <td>NO</td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td>&#10008;*</td>
+ <td>&#10008;*</td>
+ </tr>
+ <tr>
+ <th class="rowhead"><em><a href="#custom">custom lowering</a></em></th>
+ <td>&#10004;</td>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+ <tr>
+ <th class="rowhead indent">gcroot</th>
+ <td>&#10004;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+ <tr>
+ <th class="rowhead indent">gcwrite</th>
+ <td>&#10004;</td>
+ <td></td>
+ <td>&#10008;</td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ <td></td>
+ <td>&#10008;</td>
+ </tr>
+ <tr>
+ <th class="rowhead indent">gcread</th>
+ <td>&#10004;</td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ </tr>
+ <tr>
+ <th class="rowhead"><em><a href="#safe-points">safe points</a></em></th>
+ <td></td>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+ <tr>
+ <th class="rowhead indent">in calls</th>
+ <td>&#10004;</td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ </tr>
+ <tr>
+ <th class="rowhead indent">before calls</th>
+ <td>&#10004;</td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ </tr>
+ <tr class="doc_warning">
+ <th class="rowhead indent">for loops</th>
+ <td>NO</td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ </tr>
+ <tr>
+ <th class="rowhead indent">before escape</th>
+ <td>&#10004;</td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ </tr>
+ <tr class="doc_warning">
+ <th class="rowhead">emit code at safe points</th>
+ <td>NO</td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ </tr>
+ <tr>
+ <th class="rowhead"><em>output</em></th>
+ <td></td>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+ <tr>
+ <th class="rowhead indent"><a href="#assembly">assembly</a></th>
+ <td>&#10004;</td>
+ <td></td>
+ <td></td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ <td>&#10008;</td>
+ </tr>
+ <tr class="doc_warning">
+ <th class="rowhead indent">JIT</th>
+ <td>NO</td>
+ <td></td>
+ <td></td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ </tr>
+ <tr class="doc_warning">
+ <th class="rowhead indent">obj</th>
+ <td>NO</td>
+ <td></td>
+ <td></td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ </tr>
+ <tr class="doc_warning">
+ <th class="rowhead">live analysis</th>
+ <td>NO</td>
+ <td></td>
+ <td></td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ </tr>
+ <tr class="doc_warning">
+ <th class="rowhead">register map</th>
+ <td>NO</td>
+ <td></td>
+ <td></td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ <td class="optl">&#10008;</td>
+ </tr>
+ <tr>
+ <td colspan="10">
+ <div><span class="doc_warning">*</span> Derived pointers only pose a
+ hazard to copying collectors.</div>
+ <div><span class="optl">&#10008;</span> in gray denotes a feature which
+ could be utilized if available.</div>
+ </td>
+ </tr>
+</table>
+
+<p>To be clear, the collection techniques above are defined as:</p>
+
+<dl>
+ <dt>Shadow Stack</dt>
+ <dd>The mutator carefully maintains a linked list of stack roots.</dd>
+ <dt>Reference Counting</dt>
+ <dd>The mutator maintains a reference count for each object and frees an
+ object when its count falls to zero.</dd>
+ <dt>Mark-Sweep</dt>
+ <dd>When the heap is exhausted, the collector marks reachable objects starting
+ from the roots, then deallocates unreachable objects in a sweep
+ phase.</dd>
+ <dt>Copying</dt>
+ <dd>As reachability analysis proceeds, the collector copies objects from one
+ heap area to another, compacting them in the process. Copying collectors
+ enable highly efficient "bump pointer" allocation and can improve locality
+ of reference.</dd>
+ <dt>Incremental</dt>
+ <dd>(Including generational collectors.) Incremental collectors generally have
+ all the properties of a copying collector (regardless of whether the
+ mature heap is compacting), but bring the added complexity of requiring
+ write barriers.</dd>
+ <dt>Threaded</dt>
+ <dd>Denotes a multithreaded mutator; the collector must still stop the mutator
+ ("stop the world") before beginning reachability analysis. Stopping a
+ multithreaded mutator is a complicated problem. It generally requires
+ highly platform specific code in the runtime, and the production of
+ carefully designed machine code at safe points.</dd>
+ <dt>Concurrent</dt>
+ <dd>In this technique, the mutator and the collector run concurrently, with
+ the goal of eliminating pause times. In a <em>cooperative</em> collector,
+ the mutator further aids with collection should a pause occur, allowing
+ collection to take advantage of multiprocessor hosts. The "stop the world"
+ problem of threaded collectors is generally still present to a limited
+ extent. Sophisticated marking algorithms are necessary. Read barriers may
+ be necessary.</dd>
+</dl>
+
+<p>As the matrix indicates, LLVM's garbage collection infrastructure is already
+suitable for a wide variety of collectors, but does not currently extend to
+multithreaded programs. This will be added in the future as there is
+interest.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="stack-map">Computing stack maps</a>
+</h3>
+
+<div>
+
+<p>LLVM automatically computes a stack map. One of the most important features
+of a <tt>GCStrategy</tt> is to compile this information into the executable in
+the binary representation expected by the runtime library.</p>
+
+<p>The stack map consists of the location and identity of each GC root in the
+each function in the module. For each root:</p>
+
+<ul>
+ <li><tt>RootNum</tt>: The index of the root.</li>
+ <li><tt>StackOffset</tt>: The offset of the object relative to the frame
+ pointer.</li>
+ <li><tt>RootMetadata</tt>: The value passed as the <tt>%metadata</tt>
+ parameter to the <a href="#gcroot"><tt>@llvm.gcroot</tt></a> intrinsic.</li>
+</ul>
+
+<p>Also, for the function as a whole:</p>
+
+<ul>
+ <li><tt>getFrameSize()</tt>: The overall size of the function's initial
+ stack frame, not accounting for any dynamic allocation.</li>
+ <li><tt>roots_size()</tt>: The count of roots in the function.</li>
+</ul>
+
+<p>To access the stack map, use <tt>GCFunctionMetadata::roots_begin()</tt> and
+-<tt>end()</tt> from the <tt><a
+href="#assembly">GCMetadataPrinter</a></tt>:</p>
+
+<blockquote><pre
+>for (iterator I = begin(), E = end(); I != E; ++I) {
+ GCFunctionInfo *FI = *I;
+ unsigned FrameSize = FI-&gt;getFrameSize();
+ size_t RootCount = FI-&gt;roots_size();
+
+ for (GCFunctionInfo::roots_iterator RI = FI-&gt;roots_begin(),
+ RE = FI-&gt;roots_end();
+ RI != RE; ++RI) {
+ int RootNum = RI->Num;
+ int RootStackOffset = RI->StackOffset;
+ Constant *RootMetadata = RI->Metadata;
+ }
+}</pre></blockquote>
+
+<p>If the <tt>llvm.gcroot</tt> intrinsic is eliminated before code generation by
+a custom lowering pass, LLVM will compute an empty stack map. This may be useful
+for collector plugins which implement reference counting or a shadow stack.</p>
+
+</div>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="init-roots">Initializing roots to null: <tt>InitRoots</tt></a>
+</h3>
+
+<div>
+
+<blockquote><pre
+>MyGC::MyGC() {
+ InitRoots = true;
+}</pre></blockquote>
+
+<p>When set, LLVM will automatically initialize each root to <tt>null</tt> upon
+entry to the function. This prevents the GC's sweep phase from visiting
+uninitialized pointers, which will almost certainly cause it to crash. This
+initialization occurs before custom lowering, so the two may be used
+together.</p>
+
+<p>Since LLVM does not yet compute liveness information, there is no means of
+distinguishing an uninitialized stack root from an initialized one. Therefore,
+this feature should be used by all GC plugins. It is enabled by default.</p>
+
+</div>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="custom">Custom lowering of intrinsics: <tt>CustomRoots</tt>,
+ <tt>CustomReadBarriers</tt>, and <tt>CustomWriteBarriers</tt></a>
+</h3>
+
+<div>
+
+<p>For GCs which use barriers or unusual treatment of stack roots, these
+flags allow the collector to perform arbitrary transformations of the LLVM
+IR:</p>
+
+<blockquote><pre
+>class MyGC : public GCStrategy {
+public:
+ MyGC() {
+ CustomRoots = true;
+ CustomReadBarriers = true;
+ CustomWriteBarriers = true;
+ }
+
+ virtual bool initializeCustomLowering(Module &amp;M);
+ virtual bool performCustomLowering(Function &amp;F);
+};</pre></blockquote>
+
+<p>If any of these flags are set, then LLVM suppresses its default lowering for
+the corresponding intrinsics and instead calls
+<tt>performCustomLowering</tt>.</p>
+
+<p>LLVM's default action for each intrinsic is as follows:</p>
+
+<ul>
+ <li><tt>llvm.gcroot</tt>: Leave it alone. The code generator must see it
+ or the stack map will not be computed.</li>
+ <li><tt>llvm.gcread</tt>: Substitute a <tt>load</tt> instruction.</li>
+ <li><tt>llvm.gcwrite</tt>: Substitute a <tt>store</tt> instruction.</li>
+</ul>
+
+<p>If <tt>CustomReadBarriers</tt> or <tt>CustomWriteBarriers</tt> are specified,
+then <tt>performCustomLowering</tt> <strong>must</strong> eliminate the
+corresponding barriers.</p>
+
+<p><tt>performCustomLowering</tt> must comply with the same restrictions as <a
+href="WritingAnLLVMPass.html#runOnFunction"><tt
+>FunctionPass::runOnFunction</tt></a>.
+Likewise, <tt>initializeCustomLowering</tt> has the same semantics as <a
+href="WritingAnLLVMPass.html#doInitialization_mod"><tt
+>Pass::doInitialization(Module&amp;)</tt></a>.</p>
+
+<p>The following can be used as a template:</p>
+
+<blockquote><pre
+>#include "llvm/Module.h"
+#include "llvm/IntrinsicInst.h"
+
+bool MyGC::initializeCustomLowering(Module &amp;M) {
+ return false;
+}
+
+bool MyGC::performCustomLowering(Function &amp;F) {
+ bool MadeChange = false;
+
+ for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
+ for (BasicBlock::iterator II = BB-&gt;begin(), E = BB-&gt;end(); II != E; )
+ if (IntrinsicInst *CI = dyn_cast&lt;IntrinsicInst&gt;(II++))
+ if (Function *F = CI-&gt;getCalledFunction())
+ switch (F-&gt;getIntrinsicID()) {
+ case Intrinsic::gcwrite:
+ // Handle llvm.gcwrite.
+ CI-&gt;eraseFromParent();
+ MadeChange = true;
+ break;
+ case Intrinsic::gcread:
+ // Handle llvm.gcread.
+ CI-&gt;eraseFromParent();
+ MadeChange = true;
+ break;
+ case Intrinsic::gcroot:
+ // Handle llvm.gcroot.
+ CI-&gt;eraseFromParent();
+ MadeChange = true;
+ break;
+ }
+
+ return MadeChange;
+}</pre></blockquote>
+
+</div>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="safe-points">Generating safe points: <tt>NeededSafePoints</tt></a>
+</h3>
+
+<div>
+
+<p>LLVM can compute four kinds of safe points:</p>
+
+<blockquote><pre
+>namespace GC {
+ /// PointKind - The type of a collector-safe point.
+ ///
+ enum PointKind {
+ Loop, //&lt; Instr is a loop (backwards branch).
+ Return, //&lt; Instr is a return instruction.
+ PreCall, //&lt; Instr is a call instruction.
+ PostCall //&lt; Instr is the return address of a call.
+ };
+}</pre></blockquote>
+
+<p>A collector can request any combination of the four by setting the
+<tt>NeededSafePoints</tt> mask:</p>
+
+<blockquote><pre
+>MyGC::MyGC() {
+ NeededSafePoints = 1 &lt;&lt; GC::Loop
+ | 1 &lt;&lt; GC::Return
+ | 1 &lt;&lt; GC::PreCall
+ | 1 &lt;&lt; GC::PostCall;
+}</pre></blockquote>
+
+<p>It can then use the following routines to access safe points.</p>
+
+<blockquote><pre
+>for (iterator I = begin(), E = end(); I != E; ++I) {
+ GCFunctionInfo *MD = *I;
+ size_t PointCount = MD-&gt;size();
+
+ for (GCFunctionInfo::iterator PI = MD-&gt;begin(),
+ PE = MD-&gt;end(); PI != PE; ++PI) {
+ GC::PointKind PointKind = PI-&gt;Kind;
+ unsigned PointNum = PI-&gt;Num;
+ }
+}
+</pre></blockquote>
+
+<p>Almost every collector requires <tt>PostCall</tt> safe points, since these
+correspond to the moments when the function is suspended during a call to a
+subroutine.</p>
+
+<p>Threaded programs generally require <tt>Loop</tt> safe points to guarantee
+that the application will reach a safe point within a bounded amount of time,
+even if it is executing a long-running loop which contains no function
+calls.</p>
+
+<p>Threaded collectors may also require <tt>Return</tt> and <tt>PreCall</tt>
+safe points to implement "stop the world" techniques using self-modifying code,
+where it is important that the program not exit the function without reaching a
+safe point (because only the topmost function has been patched).</p>
+
+</div>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="assembly">Emitting assembly code: <tt>GCMetadataPrinter</tt></a>
+</h3>
+
+<div>
+
+<p>LLVM allows a plugin to print arbitrary assembly code before and after the
+rest of a module's assembly code. At the end of the module, the GC can compile
+the LLVM stack map into assembly code. (At the beginning, this information is not
+yet computed.)</p>
+
+<p>Since AsmWriter and CodeGen are separate components of LLVM, a separate
+abstract base class and registry is provided for printing assembly code, the
+<tt>GCMetadaPrinter</tt> and <tt>GCMetadataPrinterRegistry</tt>. The AsmWriter
+will look for such a subclass if the <tt>GCStrategy</tt> sets
+<tt>UsesMetadata</tt>:</p>
+
+<blockquote><pre
+>MyGC::MyGC() {
+ UsesMetadata = true;
+}</pre></blockquote>
+
+<p>This separation allows JIT-only clients to be smaller.</p>
+
+<p>Note that LLVM does not currently have analogous APIs to support code
+generation in the JIT, nor using the object writers.</p>
+
+<blockquote><pre
+>// lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
+
+#include "llvm/CodeGen/GCMetadataPrinter.h"
+#include "llvm/Support/Compiler.h"
+
+using namespace llvm;
+
+namespace {
+ class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
+ public:
+ virtual void beginAssembly(std::ostream &amp;OS, AsmPrinter &amp;AP,
+ const TargetAsmInfo &amp;TAI);
+
+ virtual void finishAssembly(std::ostream &amp;OS, AsmPrinter &amp;AP,
+ const TargetAsmInfo &amp;TAI);
+ };
+
+ GCMetadataPrinterRegistry::Add&lt;MyGCPrinter&gt;
+ X("mygc", "My bespoke garbage collector.");
+}</pre></blockquote>
+
+<p>The collector should use <tt>AsmPrinter</tt> and <tt>TargetAsmInfo</tt> to
+print portable assembly code to the <tt>std::ostream</tt>. The collector itself
+contains the stack map for the entire module, and may access the
+<tt>GCFunctionInfo</tt> using its own <tt>begin()</tt> and <tt>end()</tt>
+methods. Here's a realistic example:</p>
+
+<blockquote><pre
+>#include "llvm/CodeGen/AsmPrinter.h"
+#include "llvm/Function.h"
+#include "llvm/Target/TargetMachine.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetAsmInfo.h"
+
+void MyGCPrinter::beginAssembly(std::ostream &amp;OS, AsmPrinter &amp;AP,
+ const TargetAsmInfo &amp;TAI) {
+ // Nothing to do.
+}
+
+void MyGCPrinter::finishAssembly(std::ostream &amp;OS, AsmPrinter &amp;AP,
+ const TargetAsmInfo &amp;TAI) {
+ // Set up for emitting addresses.
+ const char *AddressDirective;
+ int AddressAlignLog;
+ if (AP.TM.getTargetData()->getPointerSize() == sizeof(int32_t)) {
+ AddressDirective = TAI.getData32bitsDirective();
+ AddressAlignLog = 2;
+ } else {
+ AddressDirective = TAI.getData64bitsDirective();
+ AddressAlignLog = 3;
+ }
+
+ // Put this in the data section.
+ AP.SwitchToDataSection(TAI.getDataSection());
+
+ // For each function...
+ for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
+ GCFunctionInfo &amp;MD = **FI;
+
+ // Emit this data structure:
+ //
+ // struct {
+ // int32_t PointCount;
+ // struct {
+ // void *SafePointAddress;
+ // int32_t LiveCount;
+ // int32_t LiveOffsets[LiveCount];
+ // } Points[PointCount];
+ // } __gcmap_&lt;FUNCTIONNAME&gt;;
+
+ // Align to address width.
+ AP.EmitAlignment(AddressAlignLog);
+
+ // Emit the symbol by which the stack map entry can be found.
+ std::string Symbol;
+ Symbol += TAI.getGlobalPrefix();
+ Symbol += "__gcmap_";
+ Symbol += MD.getFunction().getName();
+ if (const char *GlobalDirective = TAI.getGlobalDirective())
+ OS &lt;&lt; GlobalDirective &lt;&lt; Symbol &lt;&lt; "\n";
+ OS &lt;&lt; TAI.getGlobalPrefix() &lt;&lt; Symbol &lt;&lt; ":\n";
+
+ // Emit PointCount.
+ AP.EmitInt32(MD.size());
+ AP.EOL("safe point count");
+
+ // And each safe point...
+ for (GCFunctionInfo::iterator PI = MD.begin(),
+ PE = MD.end(); PI != PE; ++PI) {
+ // Align to address width.
+ AP.EmitAlignment(AddressAlignLog);
+
+ // Emit the address of the safe point.
+ OS &lt;&lt; AddressDirective
+ &lt;&lt; TAI.getPrivateGlobalPrefix() &lt;&lt; "label" &lt;&lt; PI-&gt;Num;
+ AP.EOL("safe point address");
+
+ // Emit the stack frame size.
+ AP.EmitInt32(MD.getFrameSize());
+ AP.EOL("stack frame size");
+
+ // Emit the number of live roots in the function.
+ AP.EmitInt32(MD.live_size(PI));
+ AP.EOL("live root count");
+
+ // And for each live root...
+ for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
+ LE = MD.live_end(PI);
+ LI != LE; ++LI) {
+ // Print its offset within the stack frame.
+ AP.EmitInt32(LI-&gt;StackOffset);
+ AP.EOL("stack offset");
+ }
+ }
+ }
+}
+</pre></blockquote>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="references">References</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p><a name="appel89">[Appel89]</a> Runtime Tags Aren't Necessary. Andrew
+W. Appel. Lisp and Symbolic Computation 19(7):703-705, July 1989.</p>
+
+<p><a name="goldberg91">[Goldberg91]</a> Tag-free garbage collection for
+strongly typed programming languages. Benjamin Goldberg. ACM SIGPLAN
+PLDI'91.</p>
+
+<p><a name="tolmach94">[Tolmach94]</a> Tag-free garbage collection using
+explicit type parameters. Andrew Tolmach. Proceedings of the 1994 ACM
+conference on LISP and functional programming.</p>
+
+<p><a name="henderson02">[Henderson2002]</a> <a
+href="http://citeseer.ist.psu.edu/henderson02accurate.html">
+Accurate Garbage Collection in an Uncooperative Environment</a>.
+Fergus Henderson. International Symposium on Memory Management 2002.</p>
+
+</div>
+
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/GetElementPtr.rst b/docs/GetElementPtr.rst
new file mode 100644
index 00000000000..f6f904b2e35
--- /dev/null
+++ b/docs/GetElementPtr.rst
@@ -0,0 +1,538 @@
+.. _gep:
+
+=======================================
+The Often Misunderstood GEP Instruction
+=======================================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+This document seeks to dispel the mystery and confusion surrounding LLVM's
+`GetElementPtr <LangRef.html#i_getelementptr>`_ (GEP) instruction. Questions
+about the wily GEP instruction are probably the most frequently occurring
+questions once a developer gets down to coding with LLVM. Here we lay out the
+sources of confusion and show that the GEP instruction is really quite simple.
+
+Address Computation
+===================
+
+When people are first confronted with the GEP instruction, they tend to relate
+it to known concepts from other programming paradigms, most notably C array
+indexing and field selection. GEP closely resembles C array indexing and field
+selection, however it's is a little different and this leads to the following
+questions.
+
+What is the first index of the GEP instruction?
+-----------------------------------------------
+
+Quick answer: The index stepping through the first operand.
+
+The confusion with the first index usually arises from thinking about the
+GetElementPtr instruction as if it was a C index operator. They aren't the
+same. For example, when we write, in "C":
+
+.. code-block:: c++
+
+ AType *Foo;
+ ...
+ X = &Foo->F;
+
+it is natural to think that there is only one index, the selection of the field
+``F``. However, in this example, ``Foo`` is a pointer. That pointer
+must be indexed explicitly in LLVM. C, on the other hand, indices through it
+transparently. To arrive at the same address location as the C code, you would
+provide the GEP instruction with two index operands. The first operand indexes
+through the pointer; the second operand indexes the field ``F`` of the
+structure, just as if you wrote:
+
+.. code-block:: c++
+
+ X = &Foo[0].F;
+
+Sometimes this question gets rephrased as:
+
+.. _GEP index through first pointer:
+
+ *Why is it okay to index through the first pointer, but subsequent pointers
+ won't be dereferenced?*
+
+The answer is simply because memory does not have to be accessed to perform the
+computation. The first operand to the GEP instruction must be a value of a
+pointer type. The value of the pointer is provided directly to the GEP
+instruction as an operand without any need for accessing memory. It must,
+therefore be indexed and requires an index operand. Consider this example:
+
+.. code-block:: c++
+
+ struct munger_struct {
+ int f1;
+ int f2;
+ };
+ void munge(struct munger_struct *P) {
+ P[0].f1 = P[1].f1 + P[2].f2;
+ }
+ ...
+ munger_struct Array[3];
+ ...
+ munge(Array);
+
+In this "C" example, the front end compiler (llvm-gcc) will generate three GEP
+instructions for the three indices through "P" in the assignment statement. The
+function argument ``P`` will be the first operand of each of these GEP
+instructions. The second operand indexes through that pointer. The third
+operand will be the field offset into the ``struct munger_struct`` type, for
+either the ``f1`` or ``f2`` field. So, in LLVM assembly the ``munge`` function
+looks like:
+
+.. code-block:: llvm
+
+ void %munge(%struct.munger_struct* %P) {
+ entry:
+ %tmp = getelementptr %struct.munger_struct* %P, i32 1, i32 0
+ %tmp = load i32* %tmp
+ %tmp6 = getelementptr %struct.munger_struct* %P, i32 2, i32 1
+ %tmp7 = load i32* %tmp6
+ %tmp8 = add i32 %tmp7, %tmp
+ %tmp9 = getelementptr %struct.munger_struct* %P, i32 0, i32 0
+ store i32 %tmp8, i32* %tmp9
+ ret void
+ }
+
+In each case the first operand is the pointer through which the GEP instruction
+starts. The same is true whether the first operand is an argument, allocated
+memory, or a global variable.
+
+To make this clear, let's consider a more obtuse example:
+
+.. code-block:: llvm
+
+ %MyVar = uninitialized global i32
+ ...
+ %idx1 = getelementptr i32* %MyVar, i64 0
+ %idx2 = getelementptr i32* %MyVar, i64 1
+ %idx3 = getelementptr i32* %MyVar, i64 2
+
+These GEP instructions are simply making address computations from the base
+address of ``MyVar``. They compute, as follows (using C syntax):
+
+.. code-block:: c++
+
+ idx1 = (char*) &MyVar + 0
+ idx2 = (char*) &MyVar + 4
+ idx3 = (char*) &MyVar + 8
+
+Since the type ``i32`` is known to be four bytes long, the indices 0, 1 and 2
+translate into memory offsets of 0, 4, and 8, respectively. No memory is
+accessed to make these computations because the address of ``%MyVar`` is passed
+directly to the GEP instructions.
+
+The obtuse part of this example is in the cases of ``%idx2`` and ``%idx3``. They
+result in the computation of addresses that point to memory past the end of the
+``%MyVar`` global, which is only one ``i32`` long, not three ``i32``\s long.
+While this is legal in LLVM, it is inadvisable because any load or store with
+the pointer that results from these GEP instructions would produce undefined
+results.
+
+Why is the extra 0 index required?
+----------------------------------
+
+Quick answer: there are no superfluous indices.
+
+This question arises most often when the GEP instruction is applied to a global
+variable which is always a pointer type. For example, consider this:
+
+.. code-block:: llvm
+
+ %MyStruct = uninitialized global { float*, i32 }
+ ...
+ %idx = getelementptr { float*, i32 }* %MyStruct, i64 0, i32 1
+
+The GEP above yields an ``i32*`` by indexing the ``i32`` typed field of the
+structure ``%MyStruct``. When people first look at it, they wonder why the ``i64
+0`` index is needed. However, a closer inspection of how globals and GEPs work
+reveals the need. Becoming aware of the following facts will dispel the
+confusion:
+
+#. The type of ``%MyStruct`` is *not* ``{ float*, i32 }`` but rather ``{ float*,
+ i32 }*``. That is, ``%MyStruct`` is a pointer to a structure containing a
+ pointer to a ``float`` and an ``i32``.
+
+#. Point #1 is evidenced by noticing the type of the first operand of the GEP
+ instruction (``%MyStruct``) which is ``{ float*, i32 }*``.
+
+#. The first index, ``i64 0`` is required to step over the global variable
+ ``%MyStruct``. Since the first argument to the GEP instruction must always
+ be a value of pointer type, the first index steps through that pointer. A
+ value of 0 means 0 elements offset from that pointer.
+
+#. The second index, ``i32 1`` selects the second field of the structure (the
+ ``i32``).
+
+What is dereferenced by GEP?
+----------------------------
+
+Quick answer: nothing.
+
+The GetElementPtr instruction dereferences nothing. That is, it doesn't access
+memory in any way. That's what the Load and Store instructions are for. GEP is
+only involved in the computation of addresses. For example, consider this:
+
+.. code-block:: llvm
+
+ %MyVar = uninitialized global { [40 x i32 ]* }
+ ...
+ %idx = getelementptr { [40 x i32]* }* %MyVar, i64 0, i32 0, i64 0, i64 17
+
+In this example, we have a global variable, ``%MyVar`` that is a pointer to a
+structure containing a pointer to an array of 40 ints. The GEP instruction seems
+to be accessing the 18th integer of the structure's array of ints. However, this
+is actually an illegal GEP instruction. It won't compile. The reason is that the
+pointer in the structure <i>must</i> be dereferenced in order to index into the
+array of 40 ints. Since the GEP instruction never accesses memory, it is
+illegal.
+
+In order to access the 18th integer in the array, you would need to do the
+following:
+
+.. code-block:: llvm
+
+ %idx = getelementptr { [40 x i32]* }* %, i64 0, i32 0
+ %arr = load [40 x i32]** %idx
+ %idx = getelementptr [40 x i32]* %arr, i64 0, i64 17
+
+In this case, we have to load the pointer in the structure with a load
+instruction before we can index into the array. If the example was changed to:
+
+.. code-block:: llvm
+
+ %MyVar = uninitialized global { [40 x i32 ] }
+ ...
+ %idx = getelementptr { [40 x i32] }*, i64 0, i32 0, i64 17
+
+then everything works fine. In this case, the structure does not contain a
+pointer and the GEP instruction can index through the global variable, into the
+first field of the structure and access the 18th ``i32`` in the array there.
+
+Why don't GEP x,0,0,1 and GEP x,1 alias?
+----------------------------------------
+
+Quick Answer: They compute different address locations.
+
+If you look at the first indices in these GEP instructions you find that they
+are different (0 and 1), therefore the address computation diverges with that
+index. Consider this example:
+
+.. code-block:: llvm
+
+ %MyVar = global { [10 x i32 ] }
+ %idx1 = getelementptr { [10 x i32 ] }* %MyVar, i64 0, i32 0, i64 1
+ %idx2 = getelementptr { [10 x i32 ] }* %MyVar, i64 1
+
+In this example, ``idx1`` computes the address of the second integer in the
+array that is in the structure in ``%MyVar``, that is ``MyVar+4``. The type of
+``idx1`` is ``i32*``. However, ``idx2`` computes the address of *the next*
+structure after ``%MyVar``. The type of ``idx2`` is ``{ [10 x i32] }*`` and its
+value is equivalent to ``MyVar + 40`` because it indexes past the ten 4-byte
+integers in ``MyVar``. Obviously, in such a situation, the pointers don't
+alias.
+
+Why do GEP x,1,0,0 and GEP x,1 alias?
+-------------------------------------
+
+Quick Answer: They compute the same address location.
+
+These two GEP instructions will compute the same address because indexing
+through the 0th element does not change the address. However, it does change the
+type. Consider this example:
+
+.. code-block:: llvm
+
+ %MyVar = global { [10 x i32 ] }
+ %idx1 = getelementptr { [10 x i32 ] }* %MyVar, i64 1, i32 0, i64 0
+ %idx2 = getelementptr { [10 x i32 ] }* %MyVar, i64 1
+
+In this example, the value of ``%idx1`` is ``%MyVar+40`` and its type is
+``i32*``. The value of ``%idx2`` is also ``MyVar+40`` but its type is ``{ [10 x
+i32] }*``.
+
+Can GEP index into vector elements?
+-----------------------------------
+
+This hasn't always been forcefully disallowed, though it's not recommended. It
+leads to awkward special cases in the optimizers, and fundamental inconsistency
+in the IR. In the future, it will probably be outright disallowed.
+
+What effect do address spaces have on GEPs?
+-------------------------------------------
+
+None, except that the address space qualifier on the first operand pointer type
+always matches the address space qualifier on the result type.
+
+How is GEP different from ``ptrtoint``, arithmetic, and ``inttoptr``?
+---------------------------------------------------------------------
+
+It's very similar; there are only subtle differences.
+
+With ptrtoint, you have to pick an integer type. One approach is to pick i64;
+this is safe on everything LLVM supports (LLVM internally assumes pointers are
+never wider than 64 bits in many places), and the optimizer will actually narrow
+the i64 arithmetic down to the actual pointer size on targets which don't
+support 64-bit arithmetic in most cases. However, there are some cases where it
+doesn't do this. With GEP you can avoid this problem.
+
+Also, GEP carries additional pointer aliasing rules. It's invalid to take a GEP
+from one object, address into a different separately allocated object, and
+dereference it. IR producers (front-ends) must follow this rule, and consumers
+(optimizers, specifically alias analysis) benefit from being able to rely on
+it. See the `Rules`_ section for more information.
+
+And, GEP is more concise in common cases.
+
+However, for the underlying integer computation implied, there is no
+difference.
+
+
+I'm writing a backend for a target which needs custom lowering for GEP. How do I do this?
+-----------------------------------------------------------------------------------------
+
+You don't. The integer computation implied by a GEP is target-independent.
+Typically what you'll need to do is make your backend pattern-match expressions
+trees involving ADD, MUL, etc., which are what GEP is lowered into. This has the
+advantage of letting your code work correctly in more cases.
+
+GEP does use target-dependent parameters for the size and layout of data types,
+which targets can customize.
+
+If you require support for addressing units which are not 8 bits, you'll need to
+fix a lot of code in the backend, with GEP lowering being only a small piece of
+the overall picture.
+
+How does VLA addressing work with GEPs?
+---------------------------------------
+
+GEPs don't natively support VLAs. LLVM's type system is entirely static, and GEP
+address computations are guided by an LLVM type.
+
+VLA indices can be implemented as linearized indices. For example, an expression
+like ``X[a][b][c]``, must be effectively lowered into a form like
+``X[a*m+b*n+c]``, so that it appears to the GEP as a single-dimensional array
+reference.
+
+This means if you want to write an analysis which understands array indices and
+you want to support VLAs, your code will have to be prepared to reverse-engineer
+the linearization. One way to solve this problem is to use the ScalarEvolution
+library, which always presents VLA and non-VLA indexing in the same manner.
+
+.. _Rules:
+
+Rules
+=====
+
+What happens if an array index is out of bounds?
+------------------------------------------------
+
+There are two senses in which an array index can be out of bounds.
+
+First, there's the array type which comes from the (static) type of the first
+operand to the GEP. Indices greater than the number of elements in the
+corresponding static array type are valid. There is no problem with out of
+bounds indices in this sense. Indexing into an array only depends on the size of
+the array element, not the number of elements.
+
+A common example of how this is used is arrays where the size is not known.
+It's common to use array types with zero length to represent these. The fact
+that the static type says there are zero elements is irrelevant; it's perfectly
+valid to compute arbitrary element indices, as the computation only depends on
+the size of the array element, not the number of elements. Note that zero-sized
+arrays are not a special case here.
+
+This sense is unconnected with ``inbounds`` keyword. The ``inbounds`` keyword is
+designed to describe low-level pointer arithmetic overflow conditions, rather
+than high-level array indexing rules.
+
+Analysis passes which wish to understand array indexing should not assume that
+the static array type bounds are respected.
+
+The second sense of being out of bounds is computing an address that's beyond
+the actual underlying allocated object.
+
+With the ``inbounds`` keyword, the result value of the GEP is undefined if the
+address is outside the actual underlying allocated object and not the address
+one-past-the-end.
+
+Without the ``inbounds`` keyword, there are no restrictions on computing
+out-of-bounds addresses. Obviously, performing a load or a store requires an
+address of allocated and sufficiently aligned memory. But the GEP itself is only
+concerned with computing addresses.
+
+Can array indices be negative?
+------------------------------
+
+Yes. This is basically a special case of array indices being out of bounds.
+
+Can I compare two values computed with GEPs?
+--------------------------------------------
+
+Yes. If both addresses are within the same allocated object, or
+one-past-the-end, you'll get the comparison result you expect. If either is
+outside of it, integer arithmetic wrapping may occur, so the comparison may not
+be meaningful.
+
+Can I do GEP with a different pointer type than the type of the underlying object?
+----------------------------------------------------------------------------------
+
+Yes. There are no restrictions on bitcasting a pointer value to an arbitrary
+pointer type. The types in a GEP serve only to define the parameters for the
+underlying integer computation. They need not correspond with the actual type of
+the underlying object.
+
+Furthermore, loads and stores don't have to use the same types as the type of
+the underlying object. Types in this context serve only to specify memory size
+and alignment. Beyond that there are merely a hint to the optimizer indicating
+how the value will likely be used.
+
+Can I cast an object's address to integer and add it to null?
+-------------------------------------------------------------
+
+You can compute an address that way, but if you use GEP to do the add, you can't
+use that pointer to actually access the object, unless the object is managed
+outside of LLVM.
+
+The underlying integer computation is sufficiently defined; null has a defined
+value --- zero --- and you can add whatever value you want to it.
+
+However, it's invalid to access (load from or store to) an LLVM-aware object
+with such a pointer. This includes ``GlobalVariables``, ``Allocas``, and objects
+pointed to by noalias pointers.
+
+If you really need this functionality, you can do the arithmetic with explicit
+integer instructions, and use inttoptr to convert the result to an address. Most
+of GEP's special aliasing rules do not apply to pointers computed from ptrtoint,
+arithmetic, and inttoptr sequences.
+
+Can I compute the distance between two objects, and add that value to one address to compute the other address?
+---------------------------------------------------------------------------------------------------------------
+
+As with arithmetic on null, You can use GEP to compute an address that way, but
+you can't use that pointer to actually access the object if you do, unless the
+object is managed outside of LLVM.
+
+Also as above, ptrtoint and inttoptr provide an alternative way to do this which
+do not have this restriction.
+
+Can I do type-based alias analysis on LLVM IR?
+----------------------------------------------
+
+You can't do type-based alias analysis using LLVM's built-in type system,
+because LLVM has no restrictions on mixing types in addressing, loads or stores.
+
+LLVM's type-based alias analysis pass uses metadata to describe a different type
+system (such as the C type system), and performs type-based aliasing on top of
+that. Further details are in the `language reference <LangRef.html#tbaa>`_.
+
+What happens if a GEP computation overflows?
+--------------------------------------------
+
+If the GEP lacks the ``inbounds`` keyword, the value is the result from
+evaluating the implied two's complement integer computation. However, since
+there's no guarantee of where an object will be allocated in the address space,
+such values have limited meaning.
+
+If the GEP has the ``inbounds`` keyword, the result value is undefined (a "trap
+value") if the GEP overflows (i.e. wraps around the end of the address space).
+
+As such, there are some ramifications of this for inbounds GEPs: scales implied
+by array/vector/pointer indices are always known to be "nsw" since they are
+signed values that are scaled by the element size. These values are also
+allowed to be negative (e.g. "``gep i32 *%P, i32 -1``") but the pointer itself
+is logically treated as an unsigned value. This means that GEPs have an
+asymmetric relation between the pointer base (which is treated as unsigned) and
+the offset applied to it (which is treated as signed). The result of the
+additions within the offset calculation cannot have signed overflow, but when
+applied to the base pointer, there can be signed overflow.
+
+How can I tell if my front-end is following the rules?
+------------------------------------------------------
+
+There is currently no checker for the getelementptr rules. Currently, the only
+way to do this is to manually check each place in your front-end where
+GetElementPtr operators are created.
+
+It's not possible to write a checker which could find all rule violations
+statically. It would be possible to write a checker which works by instrumenting
+the code with dynamic checks though. Alternatively, it would be possible to
+write a static checker which catches a subset of possible problems. However, no
+such checker exists today.
+
+Rationale
+=========
+
+Why is GEP designed this way?
+-----------------------------
+
+The design of GEP has the following goals, in rough unofficial order of
+priority:
+
+* Support C, C-like languages, and languages which can be conceptually lowered
+ into C (this covers a lot).
+
+* Support optimizations such as those that are common in C compilers. In
+ particular, GEP is a cornerstone of LLVM's `pointer aliasing
+ model <LangRef.html#pointeraliasing>`_.
+
+* Provide a consistent method for computing addresses so that address
+ computations don't need to be a part of load and store instructions in the IR.
+
+* Support non-C-like languages, to the extent that it doesn't interfere with
+ other goals.
+
+* Minimize target-specific information in the IR.
+
+Why do struct member indices always use ``i32``?
+------------------------------------------------
+
+The specific type i32 is probably just a historical artifact, however it's wide
+enough for all practical purposes, so there's been no need to change it. It
+doesn't necessarily imply i32 address arithmetic; it's just an identifier which
+identifies a field in a struct. Requiring that all struct indices be the same
+reduces the range of possibilities for cases where two GEPs are effectively the
+same but have distinct operand types.
+
+What's an uglygep?
+------------------
+
+Some LLVM optimizers operate on GEPs by internally lowering them into more
+primitive integer expressions, which allows them to be combined with other
+integer expressions and/or split into multiple separate integer expressions. If
+they've made non-trivial changes, translating back into LLVM IR can involve
+reverse-engineering the structure of the addressing in order to fit it into the
+static type of the original first operand. It isn't always possibly to fully
+reconstruct this structure; sometimes the underlying addressing doesn't
+correspond with the static type at all. In such cases the optimizer instead will
+emit a GEP with the base pointer casted to a simple address-unit pointer, using
+the name "uglygep". This isn't pretty, but it's just as valid, and it's
+sufficient to preserve the pointer aliasing guarantees that GEP provides.
+
+Summary
+=======
+
+In summary, here's some things to always remember about the GetElementPtr
+instruction:
+
+
+#. The GEP instruction never accesses memory, it only provides pointer
+ computations.
+
+#. The first operand to the GEP instruction is always a pointer and it must be
+ indexed.
+
+#. There are no superfluous indices for the GEP instruction.
+
+#. Trailing zero indices are superfluous for pointer aliasing, but not for the
+ types of the pointers.
+
+#. Leading zero indices are not superfluous for pointer aliasing nor the types
+ of the pointers.
diff --git a/docs/GettingStarted.html b/docs/GettingStarted.html
new file mode 100644
index 00000000000..c91cb03d18c
--- /dev/null
+++ b/docs/GettingStarted.html
@@ -0,0 +1,1760 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Getting Started with LLVM System</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>
+ Getting Started with the LLVM System
+</h1>
+
+<ul>
+ <li><a href="#overview">Overview</a>
+ <li><a href="#quickstart">Getting Started Quickly (A Summary)</a>
+ <li><a href="#requirements">Requirements</a>
+ <ol>
+ <li><a href="#hardware">Hardware</a></li>
+ <li><a href="#software">Software</a></li>
+ <li><a href="#brokengcc">Broken versions of GCC and other tools</a></li>
+ </ol></li>
+
+ <li><a href="#starting">Getting Started with LLVM</a>
+ <ol>
+ <li><a href="#terminology">Terminology and Notation</a></li>
+ <li><a href="#environment">Setting Up Your Environment</a></li>
+ <li><a href="#unpack">Unpacking the LLVM Archives</a></li>
+ <li><a href="#checkout">Checkout LLVM from Subversion</a></li>
+ <li><a href="#git_mirror">LLVM GIT mirror</a></li>
+ <li><a href="#config">Local LLVM Configuration</a></li>
+ <li><a href="#compile">Compiling the LLVM Suite Source Code</a></li>
+ <li><a href="#cross-compile">Cross-Compiling LLVM</a></li>
+ <li><a href="#objfiles">The Location of LLVM Object Files</a></li>
+ <li><a href="#optionalconfig">Optional Configuration Items</a></li>
+ </ol></li>
+
+ <li><a href="#layout">Program layout</a>
+ <ol>
+ <li><a href="#examples"><tt>llvm/examples</tt></a></li>
+ <li><a href="#include"><tt>llvm/include</tt></a></li>
+ <li><a href="#lib"><tt>llvm/lib</tt></a></li>
+ <li><a href="#projects"><tt>llvm/projects</tt></a></li>
+ <li><a href="#runtime"><tt>llvm/runtime</tt></a></li>
+ <li><a href="#test"><tt>llvm/test</tt></a></li>
+ <li><a href="#test-suite"><tt>test-suite</tt></a></li>
+ <li><a href="#tools"><tt>llvm/tools</tt></a></li>
+ <li><a href="#utils"><tt>llvm/utils</tt></a></li>
+ </ol></li>
+
+ <li><a href="#tutorial">An Example Using the LLVM Tool Chain</a>
+ <ol>
+ <li><a href="#tutorial4">Example with Clang</a></li>
+ </ol>
+ <li><a href="#problems">Common Problems</a>
+ <li><a href="#links">Links</a>
+</ul>
+
+<div class="doc_author">
+ <p>Written by:
+ <a href="mailto:criswell@uiuc.edu">John Criswell</a>,
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a>,
+ <a href="http://misha.brukman.net/">Misha Brukman</a>,
+ <a href="http://www.cs.uiuc.edu/~vadve">Vikram Adve</a>, and
+ <a href="mailto:gshi1@uiuc.edu">Guochun Shi</a>.
+ </p>
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="overview">Overview</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to LLVM! In order to get started, you first need to know some
+basic information.</p>
+
+<p>First, LLVM comes in three pieces. The first piece is the LLVM
+suite. This contains all of the tools, libraries, and header files
+needed to use LLVM. It contains an assembler, disassembler, bitcode
+analyzer and bitcode optimizer. It also contains basic regression tests that
+can be used to test the LLVM tools and the Clang front end.</p>
+
+<p>The second piece is the <a href="http://clang.llvm.org/">Clang</a> front end.
+This component compiles C, C++, Objective C, and Objective C++ code into LLVM
+bitcode. Once compiled into LLVM bitcode, a program can be manipulated with the
+LLVM tools from the LLVM suite.
+</p>
+
+<p>
+There is a third, optional piece called Test Suite. It is a suite of programs
+with a testing harness that can be used to further test LLVM's functionality
+and performance.
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="quickstart">Getting Started Quickly (A Summary)</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The LLVM Getting Started documentation may be out of date. So, the Clang
+<a href="http://clang.llvm.org/get_started.html">Getting Started</a> page might
+also be a good place to start.</p>
+
+<p>Here's the short story for getting up and running quickly with LLVM:</p>
+
+<ol>
+ <li>Read the documentation.</li>
+ <li>Read the documentation.</li>
+ <li>Remember that you were warned twice about reading the documentation.</li>
+
+ <li>Checkout LLVM:
+ <ul>
+ <li><tt>cd <i>where-you-want-llvm-to-live</i></tt>
+ <li><tt>svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm</tt></li>
+ </ul>
+ </li>
+
+ <li>Checkout Clang:
+ <ul>
+ <li><tt>cd <i>where-you-want-llvm-to-live</i></tt>
+ <li><tt>cd llvm/tools</tt>
+ <li><tt>svn co http://llvm.org/svn/llvm-project/cfe/trunk clang</tt></li>
+ </ul>
+ </li>
+
+ <li>Checkout Compiler-RT:
+ <ul>
+ <li><tt>cd <i>where-you-want-llvm-to-live</i></tt>
+ <li><tt>cd llvm/projects</tt>
+ <li><tt>svn co http://llvm.org/svn/llvm-project/compiler-rt/trunk
+ compiler-rt</tt></li>
+ </ul>
+ </li>
+
+ <li>Get the Test Suite Source Code <b>[Optional]</b>
+ <ul>
+ <li><tt>cd <i>where-you-want-llvm-to-live</i></tt>
+ <li><tt>cd llvm/projects</tt>
+ <li><tt>svn co http://llvm.org/svn/llvm-project/test-suite/trunk test-suite</tt></li>
+ </ul>
+ </li>
+
+ <li>Configure and build LLVM and Clang:
+ <ul>
+ <li><tt>cd <i>where-you-want-to-build-llvm</i></tt></li>
+ <li><tt>mkdir build</tt> (for building without polluting the source dir)</li>
+ <li><tt>cd build</tt></li>
+ <li><tt>../llvm/configure [options]</tt>
+ <br>Some common options:
+
+ <ul>
+ <li><tt>--prefix=<i>directory</i></tt> -
+ Specify for <i>directory</i> the full pathname of where you
+ want the LLVM tools and libraries to be installed (default
+ <tt>/usr/local</tt>).</li>
+ </ul>
+
+ <ul>
+ <li><tt>--enable-optimized</tt> -
+ Compile with optimizations enabled (default is NO).</li>
+ </ul>
+
+ <ul>
+ <li><tt>--enable-assertions</tt> -
+ Compile with assertion checks enabled (default is YES).</li>
+ </ul>
+ </li>
+ <li><tt>make [-j]</tt> - The -j specifies the number of jobs (commands) to
+ run simultaneously. This builds both LLVM and Clang for Debug+Asserts mode.
+ The --enabled-optimized configure option is used to specify a Release build.</li>
+ <li><tt>make check-all</tt> -
+ This run the regression tests to ensure everything is in working order.</li>
+ <li><tt>make update</tt> -
+ This command is used to update all the svn repositories at once, rather then
+ having to <tt>cd</tt> into the individual repositories and running
+ <tt>svn update</tt>.</li>
+ <li>It is also possible to use CMake instead of the makefiles. With CMake
+ it is also possible to generate project files for several IDEs: Eclipse
+ CDT4, CodeBlocks, Qt-Creator (use the CodeBlocks generator), KDevelop3.</li>
+ <li>If you get an "internal compiler error (ICE)" or test failures, see
+ <a href="#brokengcc">below</a>.</li>
+
+ </ul>
+ </li>
+
+</ol>
+
+<p>Consult the <a href="#starting">Getting Started with LLVM</a> section for
+detailed information on configuring and compiling LLVM. See <a
+href="#environment">Setting Up Your Environment</a> for tips that simplify
+working with the Clang front end and LLVM tools. Go to <a href="#layout">Program
+Layout</a> to learn about the layout of the source code tree.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="requirements">Requirements</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Before you begin to use the LLVM system, review the requirements given below.
+This may save you some trouble by knowing ahead of time what hardware and
+software you will need.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="hardware">Hardware</a>
+</h3>
+
+<div>
+
+<p>LLVM is known to work on the following platforms:</p>
+
+<table cellpadding="3" summary="Known LLVM platforms">
+<tr>
+ <th>OS</th>
+ <th>Arch</th>
+ <th>Compilers</th>
+</tr>
+<tr>
+ <td>AuroraUX</td>
+ <td>x86<sup><a href="#pf_1">1</a></sup></td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>Linux</td>
+ <td>x86<sup><a href="#pf_1">1</a></sup></td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>Linux</td>
+ <td>amd64</td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>Solaris</td>
+ <td>V9 (Ultrasparc)</td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>FreeBSD</td>
+ <td>x86<sup><a href="#pf_1">1</a></sup></td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>FreeBSD</td>
+ <td>amd64</td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>MacOS X<sup><a href="#pf_2">2</a></sup></td>
+ <td>PowerPC</td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>MacOS X<sup><a href="#pf_2">2</a>,<a href="#pf_9">9</a></sup></td>
+ <td>x86</td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>Cygwin/Win32</td>
+ <td>x86<sup><a href="#pf_1">1</a>,<a href="#pf_8">8</a>,
+ <a href="#pf_11">11</a></sup></td>
+ <td>GCC 3.4.X, binutils 2.20</td>
+</tr>
+<tr>
+ <td>MinGW/Win32</td>
+ <td>x86<sup><a href="#pf_1">1</a>,<a href="#pf_6">6</a>,
+ <a href="#pf_8">8</a>, <a href="#pf_10">10</a>,
+ <a href="#pf_11">11</a></sup></td>
+ <td>GCC 3.4.X, binutils 2.20</td>
+</tr>
+</table>
+
+<p>LLVM has partial support for the following platforms:</p>
+
+<table summary="LLVM partial platform support">
+<tr>
+ <th>OS</th>
+ <th>Arch</th>
+ <th>Compilers</th>
+</tr>
+<tr>
+ <td>Windows</td>
+ <td>x86<sup><a href="#pf_1">1</a></sup></td>
+ <td>Visual Studio 2008 or higher<sup><a href="#pf_4">4</a>,<a href="#pf_5">5</a></sup></td>
+<tr>
+ <td>AIX<sup><a href="#pf_3">3</a>,<a href="#pf_4">4</a></sup></td>
+ <td>PowerPC</td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>Linux<sup><a href="#pf_3">3</a>,<a href="#pf_5">5</a></sup></td>
+ <td>PowerPC</td>
+ <td>GCC</td>
+</tr>
+
+<tr>
+ <td>Linux<sup><a href="#pf_7">7</a></sup></td>
+ <td>Alpha</td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>Linux<sup><a href="#pf_7">7</a></sup></td>
+ <td>Itanium (IA-64)</td>
+ <td>GCC</td>
+</tr>
+<tr>
+ <td>HP-UX<sup><a href="#pf_7">7</a></sup></td>
+ <td>Itanium (IA-64)</td>
+ <td>HP aCC</td>
+</tr>
+<tr>
+ <td>Windows x64</td>
+ <td>x86-64</td>
+ <td>mingw-w64's GCC-4.5.x<sup><a href="#pf_12">12</a></sup></td>
+</tr>
+</table>
+
+<p><b>Notes:</b></p>
+
+<div class="doc_notes">
+<ol>
+<li><a name="pf_1">Code generation supported for Pentium processors and
+up</a></li>
+<li><a name="pf_2">Code generation supported for 32-bit ABI only</a></li>
+<li><a name="pf_3">No native code generation</a></li>
+<li><a name="pf_4">Build is not complete: one or more tools do not link or function</a></li>
+<li><a name="pf_5">The GCC-based C/C++ frontend does not build</a></li>
+<li><a name="pf_6">The port is done using the MSYS shell.</a></li>
+<li><a name="pf_7">Native code generation exists but is not complete.</a></li>
+<li><a name="pf_8">Binutils 2.20 or later is required to build the assembler
+ generated by LLVM properly.</a></li>
+<li><a name="pf_9">Xcode 2.5 and gcc 4.0.1</a> (Apple Build 5370) will trip
+ internal LLVM assert messages when compiled for Release at optimization
+ levels greater than 0 (i.e., <i>"-O1"</i> and higher).
+ Add <i>OPTIMIZE_OPTION="-O0"</i> to the build command line
+ if compiling for LLVM Release or bootstrapping the LLVM toolchain.</li>
+<li><a name="pf_10">For MSYS/MinGW on Windows, be sure to install the MSYS
+ version of the perl package, and be sure it appears in your path
+ before any Windows-based versions such as Strawberry Perl and
+ ActivePerl, as these have Windows-specifics that will cause the
+ build to fail.</a></li>
+<li><a name="pf_11">To use LLVM modules on Win32-based system,
+ you may configure LLVM with <i>&quot;--enable-shared&quot;</i>.</a></li>
+<li><a name="pf_12">To compile SPU backend, you need to add
+ <tt>&quot;LDFLAGS=-Wl,--stack,16777216&quot;</tt> to configure.</a></li>
+</ol>
+</div>
+
+<p>Note that you will need about 1-3 GB of space for a full LLVM build in Debug
+mode, depending on the system (it is so large because of all the debugging
+information and the fact that the libraries are statically linked into multiple
+tools). If you do not need many of the tools and you are space-conscious, you
+can pass <tt>ONLY_TOOLS="tools you need"</tt> to make. The Release build
+requires considerably less space.</p>
+
+<p>The LLVM suite <i>may</i> compile on other platforms, but it is not
+guaranteed to do so. If compilation is successful, the LLVM utilities should be
+able to assemble, disassemble, analyze, and optimize LLVM bitcode. Code
+generation should work as well, although the generated native code may not work
+on your platform.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="software">Software</a>
+</h3>
+<div>
+ <p>Compiling LLVM requires that you have several software packages
+ installed. The table below lists those required packages. The Package column
+ is the usual name for the software package that LLVM depends on. The Version
+ column provides "known to work" versions of the package. The Notes column
+ describes how LLVM uses the package and provides other details.</p>
+ <table summary="Packages required to compile LLVM">
+ <tr><th>Package</th><th>Version</th><th>Notes</th></tr>
+
+ <tr>
+ <td><a href="http://savannah.gnu.org/projects/make">GNU Make</a></td>
+ <td>3.79, 3.79.1</td>
+ <td>Makefile/build processor</td>
+ </tr>
+
+ <tr>
+ <td><a href="http://gcc.gnu.org/">GCC</a></td>
+ <td>3.4.2</td>
+ <td>C/C++ compiler<sup><a href="#sf1">1</a></sup></td>
+ </tr>
+
+ <tr>
+ <td><a href="http://www.gnu.org/software/texinfo/">TeXinfo</a></td>
+ <td>4.5</td>
+ <td>For building the CFE</td>
+ </tr>
+
+ <tr>
+ <td><a href="http://subversion.tigris.org/project_packages.html">SVN</a></td>
+ <td>&ge;1.3</td>
+ <td>Subversion access to LLVM<sup><a href="#sf2">2</a></sup></td>
+ </tr>
+
+ <!-- FIXME:
+ Do we support dg?
+ Are DejaGnu and expect obsolete?
+ Shall we mention Python? -->
+
+ <tr>
+ <td><a href="http://savannah.gnu.org/projects/dejagnu">DejaGnu</a></td>
+ <td>1.4.2</td>
+ <td>Automated test suite<sup><a href="#sf3">3</a></sup></td>
+ </tr>
+
+ <tr>
+ <td><a href="http://www.tcl.tk/software/tcltk/">tcl</a></td>
+ <td>8.3, 8.4</td>
+ <td>Automated test suite<sup><a href="#sf3">3</a></sup></td>
+ </tr>
+
+ <tr>
+ <td><a href="http://expect.nist.gov/">expect</a></td>
+ <td>5.38.0</td>
+ <td>Automated test suite<sup><a href="#sf3">3</a></sup></td>
+ </tr>
+
+ <tr>
+ <td><a href="http://www.perl.com/download.csp">perl</a></td>
+ <td>&ge;5.6.0</td>
+ <td>Utilities</td>
+ </tr>
+
+ <tr>
+ <td><a href="http://savannah.gnu.org/projects/m4">GNU M4</a>
+ <td>1.4</td>
+ <td>Macro processor for configuration<sup><a href="#sf4">4</a></sup></td>
+ </tr>
+
+ <tr>
+ <td><a href="http://www.gnu.org/software/autoconf/">GNU Autoconf</a></td>
+ <td>2.60</td>
+ <td>Configuration script builder<sup><a href="#sf4">4</a></sup></td>
+ </tr>
+
+ <tr>
+ <td><a href="http://www.gnu.org/software/automake/">GNU Automake</a></td>
+ <td>1.9.6</td>
+ <td>aclocal macro generator<sup><a href="#sf4">4</a></sup></td>
+ </tr>
+
+ <tr>
+ <td><a href="http://savannah.gnu.org/projects/libtool">libtool</a></td>
+ <td>1.5.22</td>
+ <td>Shared library manager<sup><a href="#sf4">4</a></sup></td>
+ </tr>
+
+ </table>
+
+ <p><b>Notes:</b></p>
+ <div class="doc_notes">
+ <ol>
+ <li><a name="sf1">Only the C and C++ languages are needed so there's no
+ need to build the other languages for LLVM's purposes.</a> See
+ <a href="#brokengcc">below</a> for specific version info.</li>
+ <li><a name="sf2">You only need Subversion if you intend to build from the
+ latest LLVM sources. If you're working from a release distribution, you
+ don't need Subversion.</a></li>
+ <li><a name="sf3">Only needed if you want to run the automated test
+ suite in the <tt>llvm/test</tt> directory.</a></li>
+ <li><a name="sf4">If you want to make changes to the configure scripts,
+ you will need GNU autoconf (2.60), and consequently, GNU M4 (version 1.4
+ or higher). You will also need automake (1.9.6). We only use aclocal
+ from that package.</a></li>
+ </ol>
+ </div>
+
+ <p>Additionally, your compilation host is expected to have the usual
+ plethora of Unix utilities. Specifically:</p>
+ <ul>
+ <li><b>ar</b> - archive library builder</li>
+ <li><b>bzip2*</b> - bzip2 command for distribution generation</li>
+ <li><b>bunzip2*</b> - bunzip2 command for distribution checking</li>
+ <li><b>chmod</b> - change permissions on a file</li>
+ <li><b>cat</b> - output concatenation utility</li>
+ <li><b>cp</b> - copy files</li>
+ <li><b>date</b> - print the current date/time </li>
+ <li><b>echo</b> - print to standard output</li>
+ <li><b>egrep</b> - extended regular expression search utility</li>
+ <li><b>find</b> - find files/dirs in a file system</li>
+ <li><b>grep</b> - regular expression search utility</li>
+ <li><b>gzip*</b> - gzip command for distribution generation</li>
+ <li><b>gunzip*</b> - gunzip command for distribution checking</li>
+ <li><b>install</b> - install directories/files </li>
+ <li><b>mkdir</b> - create a directory</li>
+ <li><b>mv</b> - move (rename) files</li>
+ <li><b>ranlib</b> - symbol table builder for archive libraries</li>
+ <li><b>rm</b> - remove (delete) files and directories</li>
+ <li><b>sed</b> - stream editor for transforming output</li>
+ <li><b>sh</b> - Bourne shell for make build scripts</li>
+ <li><b>tar</b> - tape archive for distribution generation</li>
+ <li><b>test</b> - test things in file system</li>
+ <li><b>unzip*</b> - unzip command for distribution checking</li>
+ <li><b>zip*</b> - zip command for distribution generation</li>
+ </ul>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="brokengcc">Broken versions of GCC and other tools</a>
+</h3>
+
+<div>
+
+<p>LLVM is very demanding of the host C++ compiler, and as such tends to expose
+bugs in the compiler. In particular, several versions of GCC crash when trying
+to compile LLVM. We routinely use GCC 4.2 (and higher) or Clang.
+Other versions of GCC will probably work as well. GCC versions listed
+here are known to not work. If you are using one of these versions, please try
+to upgrade your GCC to something more recent. If you run into a problem with a
+version of GCC not listed here, please <a href="mailto:llvmdev@cs.uiuc.edu">let
+us know</a>. Please use the "<tt>gcc -v</tt>" command to find out which version
+of GCC you are using.
+</p>
+
+<p><b>GCC versions prior to 3.0</b>: GCC 2.96.x and before had several
+problems in the STL that effectively prevent it from compiling LLVM.
+</p>
+
+<p><b>GCC 3.2.2 and 3.2.3</b>: These versions of GCC fails to compile LLVM with
+a bogus template error. This was fixed in later GCCs.</p>
+
+<p><b>GCC 3.3.2</b>: This version of GCC suffered from a <a
+href="http://gcc.gnu.org/PR13392">serious bug</a> which causes it to crash in
+the "<tt>convert_from_eh_region_ranges_1</tt>" GCC function.</p>
+
+<p><b>Cygwin GCC 3.3.3</b>: The version of GCC 3.3.3 commonly shipped with
+ Cygwin does not work.</p>
+<p><b>SuSE GCC 3.3.3</b>: The version of GCC 3.3.3 shipped with SuSE 9.1 (and
+ possibly others) does not compile LLVM correctly (it appears that exception
+ handling is broken in some cases). Please download the FSF 3.3.3 or upgrade
+ to a newer version of GCC.</p>
+<p><b>GCC 3.4.0 on linux/x86 (32-bit)</b>: GCC miscompiles portions of the
+ code generator, causing an infinite loop in the llvm-gcc build when built
+ with optimizations enabled (i.e. a release build).</p>
+<p><b>GCC 3.4.2 on linux/x86 (32-bit)</b>: GCC miscompiles portions of the
+ code generator at -O3, as with 3.4.0. However gcc 3.4.2 (unlike 3.4.0)
+ correctly compiles LLVM at -O2. A work around is to build release LLVM
+ builds with "make ENABLE_OPTIMIZED=1 OPTIMIZE_OPTION=-O2 ..."</p>
+<p><b>GCC 3.4.x on X86-64/amd64</b>: GCC <a href="http://llvm.org/PR1056">
+ miscompiles portions of LLVM</a>.</p>
+<p><b>GCC 3.4.4 (CodeSourcery ARM 2005q3-2)</b>: this compiler miscompiles LLVM
+ when building with optimizations enabled. It appears to work with
+ "<tt>make ENABLE_OPTIMIZED=1 OPTIMIZE_OPTION=-O1</tt>" or build a debug
+ build.</p>
+<p><b>IA-64 GCC 4.0.0</b>: The IA-64 version of GCC 4.0.0 is known to
+ miscompile LLVM.</p>
+<p><b>Apple Xcode 2.3</b>: GCC crashes when compiling LLVM at -O3 (which is the
+ default with ENABLE_OPTIMIZED=1. To work around this, build with
+ "ENABLE_OPTIMIZED=1 OPTIMIZE_OPTION=-O2".</p>
+<p><b>GCC 4.1.1</b>: GCC fails to build LLVM with template concept check errors
+ compiling some files. At the time of this writing, GCC mainline (4.2)
+ did not share the problem.</p>
+<p><b>GCC 4.1.1 on X86-64/amd64</b>: GCC <a href="http://llvm.org/PR1063">
+ miscompiles portions of LLVM</a> when compiling llvm itself into 64-bit
+ code. LLVM will appear to mostly work but will be buggy, e.g. failing
+ portions of its testsuite.</p>
+<p><b>GCC 4.1.2 on OpenSUSE</b>: Seg faults during libstdc++ build and on x86_64
+platforms compiling md5.c gets a mangled constant.</p>
+<p><b>GCC 4.1.2 (20061115 (prerelease) (Debian 4.1.1-21)) on Debian</b>: Appears
+to miscompile parts of LLVM 2.4. One symptom is ValueSymbolTable complaining
+about symbols remaining in the table on destruction.</p>
+<p><b>GCC 4.1.2 20071124 (Red Hat 4.1.2-42)</b>: Suffers from the same symptoms
+as the previous one. It appears to work with ENABLE_OPTIMIZED=0 (the default).</p>
+<p><b>Cygwin GCC 4.3.2 20080827 (beta) 2</b>:
+ Users <a href="http://llvm.org/PR4145">reported</a> various problems related
+ with link errors when using this GCC version.</p>
+<p><b>Debian GCC 4.3.2 on X86</b>: Crashes building some files in LLVM 2.6.</p>
+<p><b>GCC 4.3.3 (Debian 4.3.3-10) on ARM</b>: Miscompiles parts of LLVM 2.6
+when optimizations are turned on. The symptom is an infinite loop in
+FoldingSetImpl::RemoveNode while running the code generator.</p>
+<p><b>SUSE 11 GCC 4.3.4</b>: Miscompiles LLVM, causing crashes in ValueHandle logic.</p>
+<p><b>GCC 4.3.5 and GCC 4.4.5 on ARM</b>: These can miscompile <tt>value >>
+1</tt> even at -O0. A test failure in <tt>test/Assembler/alignstack.ll</tt> is
+one symptom of the problem.
+<p><b>GNU ld 2.16.X</b>. Some 2.16.X versions of the ld linker will produce very
+long warning messages complaining that some ".gnu.linkonce.t.*" symbol was
+defined in a discarded section. You can safely ignore these messages as they are
+erroneous and the linkage is correct. These messages disappear using ld
+2.17.</p>
+
+<p><b>GNU binutils 2.17</b>: Binutils 2.17 contains <a
+href="http://sourceware.org/bugzilla/show_bug.cgi?id=3111">a bug</a> which
+causes huge link times (minutes instead of seconds) when building LLVM. We
+recommend upgrading to a newer version (2.17.50.0.4 or later).</p>
+
+<p><b>GNU Binutils 2.19.1 Gold</b>: This version of Gold contained
+<a href="http://sourceware.org/bugzilla/show_bug.cgi?id=9836">a bug</a>
+which causes intermittent failures when building LLVM with position independent
+code. The symptom is an error about cyclic dependencies. We recommend
+upgrading to a newer version of Gold.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="starting">Getting Started with LLVM</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The remainder of this guide is meant to get you up and running with
+LLVM and to give you some basic information about the LLVM environment.</p>
+
+<p>The later sections of this guide describe the <a
+href="#layout">general layout</a> of the LLVM source tree, a <a
+href="#tutorial">simple example</a> using the LLVM tool chain, and <a
+href="#links">links</a> to find more information about LLVM or to get
+help via e-mail.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="terminology">Terminology and Notation</a>
+</h3>
+
+<div>
+
+<p>Throughout this manual, the following names are used to denote paths
+specific to the local system and working environment. <i>These are not
+environment variables you need to set but just strings used in the rest
+of this document below</i>. In any of the examples below, simply replace
+each of these names with the appropriate pathname on your local system.
+All these paths are absolute:</p>
+
+<dl>
+ <dt>SRC_ROOT
+ <dd>
+ This is the top level directory of the LLVM source tree.
+ <br><br>
+
+ <dt>OBJ_ROOT
+ <dd>
+ This is the top level directory of the LLVM object tree (i.e. the
+ tree where object files and compiled programs will be placed. It
+ can be the same as SRC_ROOT).
+ <br><br>
+
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="environment">Setting Up Your Environment</a>
+</h3>
+
+<div>
+
+<p>
+In order to compile and use LLVM, you may need to set some environment
+variables.
+
+<dl>
+ <dt><tt>LLVM_LIB_SEARCH_PATH</tt>=<tt>/path/to/your/bitcode/libs</tt></dt>
+ <dd>[Optional] This environment variable helps LLVM linking tools find the
+ locations of your bitcode libraries. It is provided only as a
+ convenience since you can specify the paths using the -L options of the
+ tools and the C/C++ front-end will automatically use the bitcode files
+ installed in its
+ <tt>lib</tt> directory.</dd>
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="unpack">Unpacking the LLVM Archives</a>
+</h3>
+
+<div>
+
+<p>
+If you have the LLVM distribution, you will need to unpack it before you
+can begin to compile it. LLVM is distributed as a set of two files: the LLVM
+suite and the LLVM GCC front end compiled for your platform. There is an
+additional test suite that is optional. Each file is a TAR archive that is
+compressed with the gzip program.
+</p>
+
+<p>The files are as follows, with <em>x.y</em> marking the version number:
+<dl>
+ <dt><tt>llvm-x.y.tar.gz</tt></dt>
+ <dd>Source release for the LLVM libraries and tools.<br></dd>
+
+ <dt><tt>llvm-test-x.y.tar.gz</tt></dt>
+ <dd>Source release for the LLVM test-suite.</dd>
+
+ <dt><tt>llvm-gcc-4.2-x.y.source.tar.gz</tt></dt>
+ <dd>Source release of the llvm-gcc-4.2 front end. See README.LLVM in the root
+ directory for build instructions.<br></dd>
+
+ <dt><tt>llvm-gcc-4.2-x.y-platform.tar.gz</tt></dt>
+ <dd>Binary release of the llvm-gcc-4.2 front end for a specific platform.<br></dd>
+
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="checkout">Checkout LLVM from Subversion</a>
+</h3>
+
+<div>
+
+<p>If you have access to our Subversion repository, you can get a fresh copy of
+the entire source code. All you need to do is check it out from Subversion as
+follows:</p>
+
+<ul>
+ <li><tt>cd <i>where-you-want-llvm-to-live</i></tt></li>
+ <li>Read-Only: <tt>svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm</tt></li>
+ <li>Read-Write:<tt>svn co https://user@llvm.org/svn/llvm-project/llvm/trunk
+ llvm</tt></li>
+</ul>
+
+
+<p>This will create an '<tt>llvm</tt>' directory in the current
+directory and fully populate it with the LLVM source code, Makefiles,
+test directories, and local copies of documentation files.</p>
+
+<p>If you want to get a specific release (as opposed to the most recent
+revision), you can checkout it from the '<tt>tags</tt>' directory (instead of
+'<tt>trunk</tt>'). The following releases are located in the following
+subdirectories of the '<tt>tags</tt>' directory:</p>
+
+<ul>
+<li>Release 3.1: <b>RELEASE_31/final</b></li>
+<li>Release 3.0: <b>RELEASE_30/final</b></li>
+<li>Release 2.9: <b>RELEASE_29/final</b></li>
+<li>Release 2.8: <b>RELEASE_28</b></li>
+<li>Release 2.7: <b>RELEASE_27</b></li>
+<li>Release 2.6: <b>RELEASE_26</b></li>
+<li>Release 2.5: <b>RELEASE_25</b></li>
+<li>Release 2.4: <b>RELEASE_24</b></li>
+<li>Release 2.3: <b>RELEASE_23</b></li>
+<li>Release 2.2: <b>RELEASE_22</b></li>
+<li>Release 2.1: <b>RELEASE_21</b></li>
+<li>Release 2.0: <b>RELEASE_20</b></li>
+<li>Release 1.9: <b>RELEASE_19</b></li>
+<li>Release 1.8: <b>RELEASE_18</b></li>
+<li>Release 1.7: <b>RELEASE_17</b></li>
+<li>Release 1.6: <b>RELEASE_16</b></li>
+<li>Release 1.5: <b>RELEASE_15</b></li>
+<li>Release 1.4: <b>RELEASE_14</b></li>
+<li>Release 1.3: <b>RELEASE_13</b></li>
+<li>Release 1.2: <b>RELEASE_12</b></li>
+<li>Release 1.1: <b>RELEASE_11</b></li>
+<li>Release 1.0: <b>RELEASE_1</b></li>
+</ul>
+
+<p>If you would like to get the LLVM test suite (a separate package as of 1.4),
+you get it from the Subversion repository:</p>
+
+<div class="doc_code">
+<pre>
+% cd llvm/projects
+% svn co http://llvm.org/svn/llvm-project/test-suite/trunk test-suite
+</pre>
+</div>
+
+<p>By placing it in the <tt>llvm/projects</tt>, it will be automatically
+configured by the LLVM configure script as well as automatically updated when
+you run <tt>svn update</tt>.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="git_mirror">GIT mirror</a>
+</h3>
+
+<div>
+
+<p>GIT mirrors are available for a number of LLVM subprojects. These mirrors
+ sync automatically with each Subversion commit and contain all necessary
+ git-svn marks (so, you can recreate git-svn metadata locally). Note that right
+ now mirrors reflect only <tt>trunk</tt> for each project. You can do the
+ read-only GIT clone of LLVM via:</p>
+
+<pre class="doc_code">
+git clone http://llvm.org/git/llvm.git
+</pre>
+
+<p>If you want to check out clang too, run:</p>
+
+<pre class="doc_code">
+git clone http://llvm.org/git/llvm.git
+cd llvm/tools
+git clone http://llvm.org/git/clang.git
+</pre>
+
+<p>
+Since the upstream repository is in Subversion, you should use
+<tt>&quot;git pull --rebase&quot;</tt>
+instead of <tt>&quot;git pull&quot;</tt> to avoid generating a non-linear
+history in your clone.
+To configure <tt>&quot;git pull&quot;</tt> to pass <tt>--rebase</tt> by default
+on the master branch, run the following command:
+</p>
+
+<pre class="doc_code">
+git config branch.master.rebase true
+</pre>
+
+<h4>Sending patches with Git</h4>
+<div>
+<p>
+Please read <a href="DeveloperPolicy.html#patches">Developer Policy</a>, too.
+</p>
+
+<p>
+Assume <tt>master</tt> points the upstream and <tt>mybranch</tt> points your
+working branch, and <tt>mybranch</tt> is rebased onto <tt>master</tt>.
+At first you may check sanity of whitespaces:
+</p>
+
+<pre class="doc_code">
+git diff --check master..mybranch
+</pre>
+
+<p>
+The easiest way to generate a patch is as below:
+</p>
+
+<pre class="doc_code">
+git diff master..mybranch &gt; /path/to/mybranch.diff
+</pre>
+
+<p>
+It is a little different from svn-generated diff. git-diff-generated diff has
+prefixes like <tt>a/</tt> and <tt>b/</tt>. Don't worry, most developers might
+know it could be accepted with <tt>patch -p1 -N</tt>.
+</p>
+
+<p>
+But you may generate patchset with git-format-patch. It generates
+by-each-commit patchset. To generate patch files to attach to your article:
+</p>
+
+<pre class="doc_code">
+git format-patch --no-attach master..mybranch -o /path/to/your/patchset
+</pre>
+
+<p>
+If you would like to send patches directly, you may use git-send-email or
+git-imap-send. Here is an example to generate the patchset in Gmail's [Drafts].
+</p>
+
+<pre class="doc_code">
+git format-patch --attach master..mybranch --stdout | git imap-send
+</pre>
+
+<p>
+Then, your .git/config should have [imap] sections.
+</p>
+
+<pre class="doc_code">
+[imap]
+ host = imaps://imap.gmail.com
+ user = <em>your.gmail.account</em>@gmail.com
+ pass = <em>himitsu!</em>
+ port = 993
+ sslverify = false
+; in English
+ folder = "[Gmail]/Drafts"
+; example for Japanese, "Modified UTF-7" encoded.
+ folder = "[Gmail]/&amp;Tgtm+DBN-"
+; example for Traditional Chinese
+ folder = "[Gmail]/&amp;g0l6Pw-"
+</pre>
+
+</div>
+
+<h4>For developers to work with git-svn</h4>
+<div>
+
+<p>To set up clone from which you can submit code using
+ <tt>git-svn</tt>, run:</p>
+
+<pre class="doc_code">
+git clone http://llvm.org/git/llvm.git
+cd llvm
+git svn init https://llvm.org/svn/llvm-project/llvm/trunk --username=&lt;username>
+git config svn-remote.svn.fetch :refs/remotes/origin/master
+git svn rebase -l # -l avoids fetching ahead of the git mirror.
+
+# If you have clang too:
+cd tools
+git clone http://llvm.org/git/clang.git
+cd clang
+git svn init https://llvm.org/svn/llvm-project/cfe/trunk --username=&lt;username>
+git config svn-remote.svn.fetch :refs/remotes/origin/master
+git svn rebase -l
+</pre>
+
+<p>To update this clone without generating git-svn tags that conflict
+with the upstream git repo, run:</p>
+
+<pre class="doc_code">
+git fetch && (cd tools/clang && git fetch) # Get matching revisions of both trees.
+git checkout master
+git svn rebase -l
+(cd tools/clang &&
+ git checkout master &&
+ git svn rebase -l)
+</pre>
+
+<p>This leaves your working directories on their master branches, so
+you'll need to <tt>checkout</tt> each working branch individually and
+<tt>rebase</tt> it on top of its parent branch. (Note: This script is
+intended for relative newbies to git. If you have more experience,
+you can likely improve on it.)</p>
+
+<p>The git-svn metadata can get out of sync after you mess around with
+branches and <code>dcommit</code>. When that happens, <code>git svn
+dcommit</code> stops working, complaining about files with uncommitted
+changes. The fix is to rebuild the metadata:</p>
+
+<pre class="doc_code">
+rm -rf .git/svn
+git svn rebase -l
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="config">Local LLVM Configuration</a>
+</h3>
+
+<div>
+
+ <p>Once checked out from the Subversion repository, the LLVM suite source
+ code must be
+configured via the <tt>configure</tt> script. This script sets variables in the
+various <tt>*.in</tt> files, most notably <tt>llvm/Makefile.config</tt> and
+<tt>llvm/include/Config/config.h</tt>. It also populates <i>OBJ_ROOT</i> with
+the Makefiles needed to begin building LLVM.</p>
+
+<p>The following environment variables are used by the <tt>configure</tt>
+script to configure the build system:</p>
+
+<table summary="LLVM configure script environment variables">
+ <tr><th>Variable</th><th>Purpose</th></tr>
+ <tr>
+ <td>CC</td>
+ <td>Tells <tt>configure</tt> which C compiler to use. By default,
+ <tt>configure</tt> will look for the first GCC C compiler in
+ <tt>PATH</tt>. Use this variable to override
+ <tt>configure</tt>'s default behavior.</td>
+ </tr>
+ <tr>
+ <td>CXX</td>
+ <td>Tells <tt>configure</tt> which C++ compiler to use. By default,
+ <tt>configure</tt> will look for the first GCC C++ compiler in
+ <tt>PATH</tt>. Use this variable to override
+ <tt>configure</tt>'s default behavior.</td>
+ </tr>
+</table>
+
+<p>The following options can be used to set or enable LLVM specific options:</p>
+
+<dl>
+ <dt><i>--enable-optimized</i></dt>
+ <dd>
+ Enables optimized compilation (debugging symbols are removed
+ and GCC optimization flags are enabled). Note that this is the default
+ setting if you are using the LLVM distribution. The default behavior
+ of an Subversion checkout is to use an unoptimized build (also known as a
+ debug build).
+ <br><br>
+ </dd>
+ <dt><i>--enable-debug-runtime</i></dt>
+ <dd>
+ Enables debug symbols in the runtime libraries. The default is to strip
+ debug symbols from the runtime libraries.
+ </dd>
+ <dt><i>--enable-jit</i></dt>
+ <dd>
+ Compile the Just In Time (JIT) compiler functionality. This is not
+ available
+ on all platforms. The default is dependent on platform, so it is best
+ to explicitly enable it if you want it.
+ <br><br>
+ </dd>
+ <dt><i>--enable-targets=</i><tt>target-option</tt></dt>
+ <dd>Controls which targets will be built and linked into llc. The default
+ value for <tt>target_options</tt> is "all" which builds and links all
+ available targets. The value "host-only" can be specified to build only a
+ native compiler (no cross-compiler targets available). The "native" target is
+ selected as the target of the build host. You can also specify a comma
+ separated list of target names that you want available in llc. The target
+ names use all lower case. The current set of targets is: <br>
+ <tt>arm, cpp, hexagon, mblaze, mips, mipsel, msp430, powerpc, ptx, sparc, spu, x86, x86_64, xcore</tt>.
+ <br><br></dd>
+ <dt><i>--enable-doxygen</i></dt>
+ <dd>Look for the doxygen program and enable construction of doxygen based
+ documentation from the source code. This is disabled by default because
+ generating the documentation can take a long time and producess 100s of
+ megabytes of output.</dd>
+ <dt><i>--with-udis86</i></dt>
+ <dd>LLVM can use external disassembler library for various purposes (now it's
+ used only for examining code produced by JIT). This option will enable usage
+ of <a href="http://udis86.sourceforge.net/">udis86</a> x86 (both 32 and 64
+ bits) disassembler library.</dd>
+</dl>
+
+<p>To configure LLVM, follow these steps:</p>
+
+<ol>
+ <li><p>Change directory into the object root directory:</p>
+
+ <div class="doc_code"><pre>% cd <i>OBJ_ROOT</i></pre></div></li>
+
+ <li><p>Run the <tt>configure</tt> script located in the LLVM source
+ tree:</p>
+
+ <div class="doc_code">
+ <pre>% <i>SRC_ROOT</i>/configure --prefix=/install/path [other options]</pre>
+ </div></li>
+</ol>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="compile">Compiling the LLVM Suite Source Code</a>
+</h3>
+
+<div>
+
+<p>Once you have configured LLVM, you can build it. There are three types of
+builds:</p>
+
+<dl>
+ <dt>Debug Builds
+ <dd>
+ These builds are the default when one is using an Subversion checkout and
+ types <tt>gmake</tt> (unless the <tt>--enable-optimized</tt> option was
+ used during configuration). The build system will compile the tools and
+ libraries with debugging information. To get a Debug Build using the
+ LLVM distribution the <tt>--disable-optimized</tt> option must be passed
+ to <tt>configure</tt>.
+ <br><br>
+
+ <dt>Release (Optimized) Builds
+ <dd>
+ These builds are enabled with the <tt>--enable-optimized</tt> option to
+ <tt>configure</tt> or by specifying <tt>ENABLE_OPTIMIZED=1</tt> on the
+ <tt>gmake</tt> command line. For these builds, the build system will
+ compile the tools and libraries with GCC optimizations enabled and strip
+ debugging information from the libraries and executables it generates.
+ Note that Release Builds are default when using an LLVM distribution.
+ <br><br>
+
+ <dt>Profile Builds
+ <dd>
+ These builds are for use with profiling. They compile profiling
+ information into the code for use with programs like <tt>gprof</tt>.
+ Profile builds must be started by specifying <tt>ENABLE_PROFILING=1</tt>
+ on the <tt>gmake</tt> command line.
+</dl>
+
+<p>Once you have LLVM configured, you can build it by entering the
+<i>OBJ_ROOT</i> directory and issuing the following command:</p>
+
+<div class="doc_code"><pre>% gmake</pre></div>
+
+<p>If the build fails, please <a href="#brokengcc">check here</a> to see if you
+are using a version of GCC that is known not to compile LLVM.</p>
+
+<p>
+If you have multiple processors in your machine, you may wish to use some of
+the parallel build options provided by GNU Make. For example, you could use the
+command:</p>
+
+<div class="doc_code"><pre>% gmake -j2</pre></div>
+
+<p>There are several special targets which are useful when working with the LLVM
+source code:</p>
+
+<dl>
+ <dt><tt>gmake clean</tt>
+ <dd>
+ Removes all files generated by the build. This includes object files,
+ generated C/C++ files, libraries, and executables.
+ <br><br>
+
+ <dt><tt>gmake dist-clean</tt>
+ <dd>
+ Removes everything that <tt>gmake clean</tt> does, but also removes files
+ generated by <tt>configure</tt>. It attempts to return the source tree to the
+ original state in which it was shipped.
+ <br><br>
+
+ <dt><tt>gmake install</tt>
+ <dd>
+ Installs LLVM header files, libraries, tools, and documentation in a
+ hierarchy
+ under $PREFIX, specified with <tt>./configure --prefix=[dir]</tt>, which
+ defaults to <tt>/usr/local</tt>.
+ <br><br>
+
+ <dt><tt>gmake -C runtime install-bytecode</tt>
+ <dd>
+ Assuming you built LLVM into $OBJDIR, when this command is run, it will
+ install bitcode libraries into the GCC front end's bitcode library
+ directory. If you need to update your bitcode libraries,
+ this is the target to use once you've built them.
+ <br><br>
+</dl>
+
+<p>Please see the <a href="MakefileGuide.html">Makefile Guide</a> for further
+details on these <tt>make</tt> targets and descriptions of other targets
+available.</p>
+
+<p>It is also possible to override default values from <tt>configure</tt> by
+declaring variables on the command line. The following are some examples:</p>
+
+<dl>
+ <dt><tt>gmake ENABLE_OPTIMIZED=1</tt>
+ <dd>
+ Perform a Release (Optimized) build.
+ <br><br>
+
+ <dt><tt>gmake ENABLE_OPTIMIZED=1 DISABLE_ASSERTIONS=1</tt>
+ <dd>
+ Perform a Release (Optimized) build without assertions enabled.
+ <br><br>
+
+ <dt><tt>gmake ENABLE_OPTIMIZED=0</tt>
+ <dd>
+ Perform a Debug build.
+ <br><br>
+
+ <dt><tt>gmake ENABLE_PROFILING=1</tt>
+ <dd>
+ Perform a Profiling build.
+ <br><br>
+
+ <dt><tt>gmake VERBOSE=1</tt>
+ <dd>
+ Print what <tt>gmake</tt> is doing on standard output.
+ <br><br>
+
+ <dt><tt>gmake TOOL_VERBOSE=1</tt></dt>
+ <dd>Ask each tool invoked by the makefiles to print out what it is doing on
+ the standard output. This also implies <tt>VERBOSE=1</tt>.
+ <br><br></dd>
+</dl>
+
+<p>Every directory in the LLVM object tree includes a <tt>Makefile</tt> to build
+it and any subdirectories that it contains. Entering any directory inside the
+LLVM object tree and typing <tt>gmake</tt> should rebuild anything in or below
+that directory that is out of date.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="cross-compile">Cross-Compiling LLVM</a>
+</h3>
+
+<div>
+ <p>It is possible to cross-compile LLVM itself. That is, you can create LLVM
+ executables and libraries to be hosted on a platform different from the
+ platform where they are build (a Canadian Cross build). To configure a
+ cross-compile, supply the configure script with <tt>--build</tt> and
+ <tt>--host</tt> options that are different. The values of these options must
+ be legal target triples that your GCC compiler supports.</p>
+
+ <p>The result of such a build is executables that are not runnable on
+ on the build host (--build option) but can be executed on the compile host
+ (--host option).</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="objfiles">The Location of LLVM Object Files</a>
+</h3>
+
+<div>
+
+<p>The LLVM build system is capable of sharing a single LLVM source tree among
+several LLVM builds. Hence, it is possible to build LLVM for several different
+platforms or configurations using the same source tree.</p>
+
+<p>This is accomplished in the typical autoconf manner:</p>
+
+<ul>
+ <li><p>Change directory to where the LLVM object files should live:</p>
+
+ <div class="doc_code"><pre>% cd <i>OBJ_ROOT</i></pre></div></li>
+
+ <li><p>Run the <tt>configure</tt> script found in the LLVM source
+ directory:</p>
+
+ <div class="doc_code"><pre>% <i>SRC_ROOT</i>/configure</pre></div></li>
+</ul>
+
+<p>The LLVM build will place files underneath <i>OBJ_ROOT</i> in directories
+named after the build type:</p>
+
+<dl>
+ <dt>Debug Builds with assertions enabled (the default)
+ <dd>
+ <dl>
+ <dt>Tools
+ <dd><tt><i>OBJ_ROOT</i>/Debug+Asserts/bin</tt>
+ <dt>Libraries
+ <dd><tt><i>OBJ_ROOT</i>/Debug+Asserts/lib</tt>
+ </dl>
+ <br><br>
+
+ <dt>Release Builds
+ <dd>
+ <dl>
+ <dt>Tools
+ <dd><tt><i>OBJ_ROOT</i>/Release/bin</tt>
+ <dt>Libraries
+ <dd><tt><i>OBJ_ROOT</i>/Release/lib</tt>
+ </dl>
+ <br><br>
+
+ <dt>Profile Builds
+ <dd>
+ <dl>
+ <dt>Tools
+ <dd><tt><i>OBJ_ROOT</i>/Profile/bin</tt>
+ <dt>Libraries
+ <dd><tt><i>OBJ_ROOT</i>/Profile/lib</tt>
+ </dl>
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="optionalconfig">Optional Configuration Items</a>
+</h3>
+
+<div>
+
+<p>
+If you're running on a Linux system that supports the "<a
+href="http://www.tat.physik.uni-tuebingen.de/~rguenth/linux/binfmt_misc.html">binfmt_misc</a>"
+module, and you have root access on the system, you can set your system up to
+execute LLVM bitcode files directly. To do this, use commands like this (the
+first command may not be required if you are already using the module):</p>
+
+<div class="doc_code">
+<pre>
+$ mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
+$ echo ':llvm:M::BC::/path/to/lli:' &gt; /proc/sys/fs/binfmt_misc/register
+$ chmod u+x hello.bc (if needed)
+$ ./hello.bc
+</pre>
+</div>
+
+<p>
+This allows you to execute LLVM bitcode files directly. On Debian, you
+can also use this command instead of the 'echo' command above:
+</p>
+
+<div class="doc_code">
+<pre>
+$ sudo update-binfmts --install llvm /path/to/lli --magic 'BC'
+</pre>
+</div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="layout">Program Layout</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>One useful source of information about the LLVM source base is the LLVM <a
+href="http://www.doxygen.org/">doxygen</a> documentation available at <tt><a
+href="http://llvm.org/doxygen/">http://llvm.org/doxygen/</a></tt>.
+The following is a brief introduction to code layout:</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="examples"><tt>llvm/examples</tt></a>
+</h3>
+
+<div>
+ <p>This directory contains some simple examples of how to use the LLVM IR and
+ JIT.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="include"><tt>llvm/include</tt></a>
+</h3>
+
+<div>
+
+<p>This directory contains public header files exported from the LLVM
+library. The three main subdirectories of this directory are:</p>
+
+<dl>
+ <dt><tt><b>llvm/include/llvm</b></tt></dt>
+ <dd>This directory contains all of the LLVM specific header files. This
+ directory also has subdirectories for different portions of LLVM:
+ <tt>Analysis</tt>, <tt>CodeGen</tt>, <tt>Target</tt>, <tt>Transforms</tt>,
+ etc...</dd>
+
+ <dt><tt><b>llvm/include/llvm/Support</b></tt></dt>
+ <dd>This directory contains generic support libraries that are provided with
+ LLVM but not necessarily specific to LLVM. For example, some C++ STL utilities
+ and a Command Line option processing library store their header files here.
+ </dd>
+
+ <dt><tt><b>llvm/include/llvm/Config</b></tt></dt>
+ <dd>This directory contains header files configured by the <tt>configure</tt>
+ script. They wrap "standard" UNIX and C header files. Source code can
+ include these header files which automatically take care of the conditional
+ #includes that the <tt>configure</tt> script generates.</dd>
+</dl>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="lib"><tt>llvm/lib</tt></a>
+</h3>
+
+<div>
+
+<p>This directory contains most of the source files of the LLVM system. In LLVM,
+almost all code exists in libraries, making it very easy to share code among the
+different <a href="#tools">tools</a>.</p>
+
+<dl>
+ <dt><tt><b>llvm/lib/VMCore/</b></tt></dt>
+ <dd> This directory holds the core LLVM source files that implement core
+ classes like Instruction and BasicBlock.</dd>
+
+ <dt><tt><b>llvm/lib/AsmParser/</b></tt></dt>
+ <dd>This directory holds the source code for the LLVM assembly language parser
+ library.</dd>
+
+ <dt><tt><b>llvm/lib/BitCode/</b></tt></dt>
+ <dd>This directory holds code for reading and write LLVM bitcode.</dd>
+
+ <dt><tt><b>llvm/lib/Analysis/</b></tt><dd>This directory contains a variety of
+ different program analyses, such as Dominator Information, Call Graphs,
+ Induction Variables, Interval Identification, Natural Loop Identification,
+ etc.</dd>
+
+ <dt><tt><b>llvm/lib/Transforms/</b></tt></dt>
+ <dd> This directory contains the source code for the LLVM to LLVM program
+ transformations, such as Aggressive Dead Code Elimination, Sparse Conditional
+ Constant Propagation, Inlining, Loop Invariant Code Motion, Dead Global
+ Elimination, and many others.</dd>
+
+ <dt><tt><b>llvm/lib/Target/</b></tt></dt>
+ <dd> This directory contains files that describe various target architectures
+ for code generation. For example, the <tt>llvm/lib/Target/X86</tt>
+ directory holds the X86 machine description while
+ <tt>llvm/lib/Target/ARM</tt> implements the ARM backend.</dd>
+
+ <dt><tt><b>llvm/lib/CodeGen/</b></tt></dt>
+ <dd> This directory contains the major parts of the code generator: Instruction
+ Selector, Instruction Scheduling, and Register Allocation.</dd>
+
+ <dt><tt><b>llvm/lib/MC/</b></tt></dt>
+ <dd>(FIXME: T.B.D.)</dd>
+
+ <!--FIXME: obsoleted -->
+ <dt><tt><b>llvm/lib/Debugger/</b></tt></dt>
+ <dd> This directory contains the source level debugger library that makes
+ it possible to instrument LLVM programs so that a debugger could identify
+ source code locations at which the program is executing.</dd>
+
+ <dt><tt><b>llvm/lib/ExecutionEngine/</b></tt></dt>
+ <dd> This directory contains libraries for executing LLVM bitcode directly
+ at runtime in both interpreted and JIT compiled fashions.</dd>
+
+ <dt><tt><b>llvm/lib/Support/</b></tt></dt>
+ <dd> This directory contains the source code that corresponds to the header
+ files located in <tt>llvm/include/ADT/</tt>
+ and <tt>llvm/include/Support/</tt>.</dd>
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="projects"><tt>llvm/projects</tt></a>
+</h3>
+
+<div>
+ <p>This directory contains projects that are not strictly part of LLVM but are
+ shipped with LLVM. This is also the directory where you should create your own
+ LLVM-based projects. See <tt>llvm/projects/sample</tt> for an example of how
+ to set up your own project.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="runtime"><tt>llvm/runtime</tt></a>
+</h3>
+
+<div>
+
+<p>This directory contains libraries which are compiled into LLVM bitcode and
+used when linking programs with the Clang front end. Most of these libraries are
+skeleton versions of real libraries; for example, libc is a stripped down
+version of glibc.</p>
+
+<p>Unlike the rest of the LLVM suite, this directory needs the LLVM GCC front
+end to compile.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="test"><tt>llvm/test</tt></a>
+</h3>
+
+<div>
+ <p>This directory contains feature and regression tests and other basic sanity
+ checks on the LLVM infrastructure. These are intended to run quickly and cover
+ a lot of territory without being exhaustive.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="test-suite"><tt>test-suite</tt></a>
+</h3>
+
+<div>
+ <p>This is not a directory in the normal llvm module; it is a separate
+ Subversion
+ module that must be checked out (usually to <tt>projects/test-suite</tt>).
+ This
+ module contains a comprehensive correctness, performance, and benchmarking
+ test
+ suite for LLVM. It is a separate Subversion module because not every LLVM
+ user is
+ interested in downloading or building such a comprehensive test suite. For
+ further details on this test suite, please see the
+ <a href="TestingGuide.html">Testing Guide</a> document.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="tools"><tt>llvm/tools</tt></a>
+</h3>
+
+<div>
+
+<p>The <b>tools</b> directory contains the executables built out of the
+libraries above, which form the main part of the user interface. You can
+always get help for a tool by typing <tt>tool_name -help</tt>. The
+following is a brief introduction to the most important tools. More detailed
+information is in the <a href="CommandGuide/index.html">Command Guide</a>.</p>
+
+<dl>
+
+ <dt><tt><b>bugpoint</b></tt></dt>
+ <dd><tt>bugpoint</tt> is used to debug
+ optimization passes or code generation backends by narrowing down the
+ given test case to the minimum number of passes and/or instructions that
+ still cause a problem, whether it is a crash or miscompilation. See <a
+ href="HowToSubmitABug.html">HowToSubmitABug.html</a> for more information
+ on using <tt>bugpoint</tt>.</dd>
+
+ <dt><tt><b>llvm-ar</b></tt></dt>
+ <dd>The archiver produces an archive containing
+ the given LLVM bitcode files, optionally with an index for faster
+ lookup.</dd>
+
+ <dt><tt><b>llvm-as</b></tt></dt>
+ <dd>The assembler transforms the human readable LLVM assembly to LLVM
+ bitcode.</dd>
+
+ <dt><tt><b>llvm-dis</b></tt></dt>
+ <dd>The disassembler transforms the LLVM bitcode to human readable
+ LLVM assembly.</dd>
+
+ <dt><tt><b>llvm-link</b></tt></dt>
+ <dd><tt>llvm-link</tt>, not surprisingly, links multiple LLVM modules into
+ a single program.</dd>
+
+ <dt><tt><b>lli</b></tt></dt>
+ <dd><tt>lli</tt> is the LLVM interpreter, which
+ can directly execute LLVM bitcode (although very slowly...). For architectures
+ that support it (currently x86, Sparc, and PowerPC), by default, <tt>lli</tt>
+ will function as a Just-In-Time compiler (if the functionality was compiled
+ in), and will execute the code <i>much</i> faster than the interpreter.</dd>
+
+ <dt><tt><b>llc</b></tt></dt>
+ <dd> <tt>llc</tt> is the LLVM backend compiler, which
+ translates LLVM bitcode to a native code assembly file or to C code (with
+ the -march=c option).</dd>
+
+ <dt><tt><b>llvm-gcc</b></tt></dt>
+ <dd><tt>llvm-gcc</tt> is a GCC-based C frontend that has been retargeted to
+ use LLVM as its backend instead of GCC's RTL backend. It can also emit LLVM
+ bitcode or assembly (with the <tt>-emit-llvm</tt> option) instead of the
+ usual machine code output. It works just like any other GCC compiler,
+ taking the typical <tt>-c, -S, -E, -o</tt> options that are typically used.
+ Additionally, the source code for <tt>llvm-gcc</tt> is available as a
+ separate Subversion module.</dd>
+
+ <dt><tt><b>opt</b></tt></dt>
+ <dd><tt>opt</tt> reads LLVM bitcode, applies a series of LLVM to LLVM
+ transformations (which are specified on the command line), and then outputs
+ the resultant bitcode. The '<tt>opt -help</tt>' command is a good way to
+ get a list of the program transformations available in LLVM.<br>
+ <dd><tt>opt</tt> can also be used to run a specific analysis on an input
+ LLVM bitcode file and print out the results. It is primarily useful for
+ debugging analyses, or familiarizing yourself with what an analysis does.</dd>
+</dl>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="utils"><tt>llvm/utils</tt></a>
+</h3>
+
+<div>
+
+<p>This directory contains utilities for working with LLVM source code, and some
+of the utilities are actually required as part of the build process because they
+are code generators for parts of LLVM infrastructure.</p>
+
+<dl>
+ <dt><tt><b>codegen-diff</b></tt> <dd><tt>codegen-diff</tt> is a script
+ that finds differences between code that LLC generates and code that LLI
+ generates. This is a useful tool if you are debugging one of them,
+ assuming that the other generates correct output. For the full user
+ manual, run <tt>`perldoc codegen-diff'</tt>.<br><br>
+
+ <dt><tt><b>emacs/</b></tt> <dd>The <tt>emacs</tt> directory contains
+ syntax-highlighting files which will work with Emacs and XEmacs editors,
+ providing syntax highlighting support for LLVM assembly files and TableGen
+ description files. For information on how to use the syntax files, consult
+ the <tt>README</tt> file in that directory.<br><br>
+
+ <dt><tt><b>getsrcs.sh</b></tt> <dd>The <tt>getsrcs.sh</tt> script finds
+ and outputs all non-generated source files, which is useful if one wishes
+ to do a lot of development across directories and does not want to
+ individually find each file. One way to use it is to run, for example:
+ <tt>xemacs `utils/getsources.sh`</tt> from the top of your LLVM source
+ tree.<br><br>
+
+ <dt><tt><b>llvmgrep</b></tt></dt>
+ <dd>This little tool performs an "egrep -H -n" on each source file in LLVM and
+ passes to it a regular expression provided on <tt>llvmgrep</tt>'s command
+ line. This is a very efficient way of searching the source base for a
+ particular regular expression.</dd>
+
+ <dt><tt><b>makellvm</b></tt> <dd>The <tt>makellvm</tt> script compiles all
+ files in the current directory and then compiles and links the tool that
+ is the first argument. For example, assuming you are in the directory
+ <tt>llvm/lib/Target/Sparc</tt>, if <tt>makellvm</tt> is in your path,
+ simply running <tt>makellvm llc</tt> will make a build of the current
+ directory, switch to directory <tt>llvm/tools/llc</tt> and build it,
+ causing a re-linking of LLC.<br><br>
+
+ <dt><tt><b>TableGen/</b></tt> <dd>The <tt>TableGen</tt> directory contains
+ the tool used to generate register descriptions, instruction set
+ descriptions, and even assemblers from common TableGen description
+ files.<br><br>
+
+ <dt><tt><b>vim/</b></tt> <dd>The <tt>vim</tt> directory contains
+ syntax-highlighting files which will work with the VIM editor, providing
+ syntax highlighting support for LLVM assembly files and TableGen
+ description files. For information on how to use the syntax files, consult
+ the <tt>README</tt> file in that directory.<br><br>
+
+</dl>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="tutorial">An Example Using the LLVM Tool Chain</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+<p>This section gives an example of using LLVM with the Clang front end.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="tutorial4">Example with clang</a>
+</h3>
+
+<div>
+
+<ol>
+ <li><p>First, create a simple C file, name it 'hello.c':</p>
+
+<div class="doc_code">
+<pre>
+#include &lt;stdio.h&gt;
+
+int main() {
+ printf("hello world\n");
+ return 0;
+}
+</pre></div></li>
+
+ <li><p>Next, compile the C file into a native executable:</p>
+
+ <div class="doc_code"><pre>% clang hello.c -o hello</pre></div>
+
+ <p>Note that clang works just like GCC by default. The standard -S and
+ -c arguments work as usual (producing a native .s or .o file,
+ respectively).</p></li>
+
+ <li><p>Next, compile the C file into a LLVM bitcode file:</p>
+
+ <div class="doc_code">
+ <pre>% clang -O3 -emit-llvm hello.c -c -o hello.bc</pre></div>
+
+ <p>The -emit-llvm option can be used with the -S or -c options to emit an
+ LLVM ".ll" or ".bc" file (respectively) for the code. This allows you
+ to use the <a href="CommandGuide/index.html">standard LLVM tools</a> on
+ the bitcode file.</p></li>
+
+ <li><p>Run the program in both forms. To run the program, use:</p>
+
+ <div class="doc_code"><pre>% ./hello</pre></div>
+
+ <p>and</p>
+
+ <div class="doc_code"><pre>% lli hello.bc</pre></div>
+
+ <p>The second examples shows how to invoke the LLVM JIT, <a
+ href="CommandGuide/html/lli.html">lli</a>.</p></li>
+
+ <li><p>Use the <tt>llvm-dis</tt> utility to take a look at the LLVM assembly
+ code:</p>
+
+<div class="doc_code">
+<pre>llvm-dis &lt; hello.bc | less</pre>
+</div></li>
+
+ <li><p>Compile the program to native assembly using the LLC code
+ generator:</p>
+
+ <div class="doc_code"><pre>% llc hello.bc -o hello.s</pre></div></li>
+
+ <li><p>Assemble the native assembly language file into a program:</p>
+
+<div class="doc_code">
+<pre>
+<b>Solaris:</b> % /opt/SUNWspro/bin/cc -xarch=v9 hello.s -o hello.native
+
+<b>Others:</b> % gcc hello.s -o hello.native
+</pre>
+</div></li>
+
+ <li><p>Execute the native code program:</p>
+
+ <div class="doc_code"><pre>% ./hello.native</pre></div>
+
+ <p>Note that using clang to compile directly to native code (i.e. when
+ the -emit-llvm option is not present) does steps 6/7/8 for you.</p>
+ </li>
+
+</ol>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="problems">Common Problems</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>If you are having problems building or using LLVM, or if you have any other
+general questions about LLVM, please consult the <a href="FAQ.html">Frequently
+Asked Questions</a> page.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="links">Links</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This document is just an <b>introduction</b> on how to use LLVM to do
+some simple things... there are many more interesting and complicated things
+that you can do that aren't documented here (but we'll gladly accept a patch
+if you want to write something up!). For more information about LLVM, check
+out:</p>
+
+<ul>
+ <li><a href="http://llvm.org/">LLVM homepage</a></li>
+ <li><a href="http://llvm.org/doxygen/">LLVM doxygen tree</a></li>
+ <li><a href="http://llvm.org/docs/Projects.html">Starting a Project
+ that Uses LLVM</a></li>
+</ul>
+
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.x10sys.com/rspencer/">Reid Spencer</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/GettingStartedVS.rst b/docs/GettingStartedVS.rst
new file mode 100644
index 00000000000..35f97f04b9d
--- /dev/null
+++ b/docs/GettingStartedVS.rst
@@ -0,0 +1,234 @@
+.. _winvs:
+
+==================================================================
+Getting Started with the LLVM System using Microsoft Visual Studio
+==================================================================
+
+.. contents::
+ :local:
+
+
+Overview
+========
+Welcome to LLVM on Windows! This document only covers LLVM on Windows using
+Visual Studio, not mingw or cygwin. In order to get started, you first need to
+know some basic information.
+
+There are many different projects that compose LLVM. The first is the LLVM
+suite. This contains all of the tools, libraries, and header files needed to
+use LLVM. It contains an assembler, disassembler,
+bitcode analyzer and bitcode optimizer. It also contains a test suite that can
+be used to test the LLVM tools.
+
+Another useful project on Windows is `Clang <http://clang.llvm.org/>`_.
+Clang is a C family ([Objective]C/C++) compiler. Clang mostly works on
+Windows, but does not currently understand all of the Microsoft extensions
+to C and C++. Because of this, clang cannot parse the C++ standard library
+included with Visual Studio, nor parts of the Windows Platform SDK. However,
+most standard C programs do compile. Clang can be used to emit bitcode,
+directly emit object files or even linked executables using Visual Studio's
+``link.exe``.
+
+The large LLVM test suite cannot be run on the Visual Studio port at this
+time.
+
+Most of the tools build and work. ``bugpoint`` does build, but does
+not work.
+
+Additional information about the LLVM directory structure and tool chain
+can be found on the main `Getting Started <GettingStarted.html>`_ page.
+
+
+Requirements
+============
+Before you begin to use the LLVM system, review the requirements given
+below. This may save you some trouble by knowing ahead of time what hardware
+and software you will need.
+
+Hardware
+--------
+Any system that can adequately run Visual Studio 2008 is fine. The LLVM
+source tree and object files, libraries and executables will consume
+approximately 3GB.
+
+Software
+--------
+You will need Visual Studio 2008 or higher. Earlier versions of Visual
+Studio have bugs, are not completely compatible, or do not support the C++
+standard well enough.
+
+You will also need the `CMake <http://www.cmake.org/>`_ build system since it
+generates the project files you will use to build with.
+
+If you would like to run the LLVM tests you will need `Python
+<http://www.python.org/>`_. Versions 2.4-2.7 are known to work. You will need
+`GnuWin32 <http://gnuwin32.sourceforge.net/>`_ tools, too.
+
+Do not install the LLVM directory tree into a path containing spaces (e.g.
+``C:\Documents and Settings\...``) as the configure step will fail.
+
+
+Getting Started
+===============
+Here's the short story for getting up and running quickly with LLVM:
+
+1. Read the documentation.
+2. Seriously, read the documentation.
+3. Remember that you were warned twice about reading the documentation.
+4. Get the Source Code
+
+ * With the distributed files:
+
+ 1. ``cd <where-you-want-llvm-to-live>``
+ 2. ``gunzip --stdout llvm-VERSION.tar.gz | tar -xvf -``
+ (*or use WinZip*)
+ 3. ``cd llvm``
+
+ * With anonymous Subversion access:
+
+ 1. ``cd <where-you-want-llvm-to-live>``
+ 2. ``svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm``
+ 3. ``cd llvm``
+
+5. Use `CMake <http://www.cmake.org/>`_ to generate up-to-date project files:
+
+ * Once CMake is installed then the simplest way is to just start the
+ CMake GUI, select the directory where you have LLVM extracted to, and
+ the default options should all be fine. One option you may really
+ want to change, regardless of anything else, might be the
+ ``CMAKE_INSTALL_PREFIX`` setting to select a directory to INSTALL to
+ once compiling is complete, although installation is not mandatory for
+ using LLVM. Another important option is ``LLVM_TARGETS_TO_BUILD``,
+ which controls the LLVM target architectures that are included on the
+ build.
+ * See the `LLVM CMake guide <CMake.html>`_ for detailed information about
+ how to configure the LLVM build.
+
+6. Start Visual Studio
+
+ * In the directory you created the project files will have an ``llvm.sln``
+ file, just double-click on that to open Visual Studio.
+
+7. Build the LLVM Suite:
+
+ * The projects may still be built individually, but to build them all do
+ not just select all of them in batch build (as some are meant as
+ configuration projects), but rather select and build just the
+ ``ALL_BUILD`` project to build everything, or the ``INSTALL`` project,
+ which first builds the ``ALL_BUILD`` project, then installs the LLVM
+ headers, libs, and other useful things to the directory set by the
+ ``CMAKE_INSTALL_PREFIX`` setting when you first configured CMake.
+ * The Fibonacci project is a sample program that uses the JIT. Modify the
+ project's debugging properties to provide a numeric command line argument
+ or run it from the command line. The program will print the
+ corresponding fibonacci value.
+
+8. Test LLVM on Visual Studio:
+
+ * If ``%PATH%`` does not contain GnuWin32, you may specify
+ ``LLVM_LIT_TOOLS_DIR`` on CMake for the path to GnuWin32.
+ * You can run LLVM tests by merely building the project "check". The test
+ results will be shown in the VS output window.
+
+.. FIXME: Is it up-to-date?
+
+9. Test LLVM:
+
+ * The LLVM tests can be run by changing directory to the llvm source
+ directory and running:
+
+ .. code-block:: bat
+
+ C:\..\llvm> llvm-lit test
+
+ Note that quite a few of these test will fail.
+
+ A specific test or test directory can be run with:
+
+ .. code-block:: bat
+
+ C:\..\llvm> llvm-lit test/path/to/test
+
+
+An Example Using the LLVM Tool Chain
+====================================
+
+1. First, create a simple C file, name it '``hello.c``':
+
+ .. code-block:: c
+
+ #include <stdio.h>
+ int main() {
+ printf("hello world\n");
+ return 0;
+ }
+
+2. Next, compile the C file into a LLVM bitcode file:
+
+ .. code-block:: bat
+
+ C:\..> clang -c hello.c -emit-llvm -o hello.bc
+
+ This will create the result file ``hello.bc`` which is the LLVM bitcode
+ that corresponds the compiled program and the library facilities that
+ it required. You can execute this file directly using ``lli`` tool,
+ compile it to native assembly with the ``llc``, optimize or analyze it
+ further with the ``opt`` tool, etc.
+
+ Alternatively you can directly output an executable with clang with:
+
+ .. code-block:: bat
+
+ C:\..> clang hello.c -o hello.exe
+
+ The ``-o hello.exe`` is required because clang currently outputs ``a.out``
+ when neither ``-o`` nor ``-c`` are given.
+
+3. Run the program using the just-in-time compiler:
+
+ .. code-block:: bat
+
+ C:\..> lli hello.bc
+
+4. Use the ``llvm-dis`` utility to take a look at the LLVM assembly code:
+
+ .. code-block:: bat
+
+ C:\..> llvm-dis < hello.bc | more
+
+5. Compile the program to object code using the LLC code generator:
+
+ .. code-block:: bat
+
+ C:\..> llc -filetype=obj hello.bc
+
+6. Link to binary using Microsoft link:
+
+ .. code-block:: bat
+
+ C:\..> link hello.obj -defaultlib:libcmt
+
+7. Execute the native code program:
+
+ .. code-block:: bat
+
+ C:\..> hello.exe
+
+
+Common Problems
+===============
+If you are having problems building or using LLVM, or if you have any other
+general questions about LLVM, please consult the `Frequently Asked Questions
+<FAQ.html>`_ page.
+
+
+Links
+=====
+This document is just an **introduction** to how to use LLVM to do some simple
+things... there are many more interesting and complicated things that you can
+do that aren't documented here (but we'll gladly accept a patch if you want to
+write something up!). For more information about LLVM, check out:
+
+* `LLVM homepage <http://llvm.org/>`_
+* `LLVM doxygen tree <http://llvm.org/doxygen/>`_
+
diff --git a/docs/GoldPlugin.html b/docs/GoldPlugin.html
new file mode 100644
index 00000000000..1e99a5a3d6a
--- /dev/null
+++ b/docs/GoldPlugin.html
@@ -0,0 +1,227 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>LLVM gold plugin</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>LLVM gold plugin</h1>
+<ol>
+ <li><a href="#introduction">Introduction</a></li>
+ <li><a href="#build">How to build it</a></li>
+ <li><a href="#usage">Usage</a>
+ <ul>
+ <li><a href="#example1">Example of link time optimization</a></li>
+ <li><a href="#lto_autotools">Quickstart for using LTO with autotooled projects</a></li>
+ </ul></li>
+ <li><a href="#licensing">Licensing</a></li>
+</ol>
+<div class="doc_author">Written by Nick Lewycky</div>
+
+<!--=========================================================================-->
+<h2><a name="introduction">Introduction</a></h2>
+<!--=========================================================================-->
+<div>
+ <p>Building with link time optimization requires cooperation from the
+system linker. LTO support on Linux systems requires that you use
+the <a href="http://sourceware.org/binutils">gold linker</a> which supports
+LTO via plugins. This is the same mechanism used by the
+<a href="http://gcc.gnu.org/wiki/LinkTimeOptimization">GCC LTO</a>
+project.</p>
+ <p>The LLVM gold plugin implements the
+<a href="http://gcc.gnu.org/wiki/whopr/driver">gold plugin interface</a>
+on top of
+<a href="LinkTimeOptimization.html#lto">libLTO</a>.
+The same plugin can also be used by other tools such as <tt>ar</tt> and
+<tt>nm</tt>.
+</div>
+<!--=========================================================================-->
+<h2><a name="build">How to build it</a></h2>
+<!--=========================================================================-->
+<div>
+ <p>You need to have gold with plugin support and build the LLVMgold
+plugin. Check whether you have gold running <tt>/usr/bin/ld -v</tt>. It will
+report &#8220;GNU gold&#8221; or else &#8220GNU ld&#8221; if not. If you have
+gold, check for plugin support by running <tt>/usr/bin/ld -plugin</tt>. If it
+complains &#8220missing argument&#8221 then you have plugin support. If not,
+such as an &#8220;unknown option&#8221; error then you will either need to
+build gold or install a version with plugin support.</p>
+<ul>
+ <li>To build gold with plugin support:
+ <pre class="doc_code">
+mkdir binutils
+cd binutils
+cvs -z 9 -d :pserver:anoncvs@sourceware.org:/cvs/src login
+<em>{enter "anoncvs" as the password}</em>
+cvs -z 9 -d :pserver:anoncvs@sourceware.org:/cvs/src co binutils
+mkdir build
+cd build
+../src/configure --enable-gold --enable-plugins
+make all-gold
+</pre>
+ That should leave you with <tt>binutils/build/gold/ld-new</tt> which supports the <tt>-plugin</tt> option. It also built would have
+<tt>binutils/build/binutils/ar</tt> and <tt>nm-new</tt> which support plugins
+but don't have a visible -plugin option, instead relying on the gold plugin
+being present in <tt>../lib/bfd-plugins</tt> relative to where the binaries are
+placed.
+ <li>Build the LLVMgold plugin: Configure LLVM with
+ <tt>--with-binutils-include=/path/to/binutils/src/include</tt> and run
+ <tt>make</tt>.
+</ul>
+</div>
+<!--=========================================================================-->
+<h2><a name="usage">Usage</a></h2>
+<!--=========================================================================-->
+<div>
+
+ <p>The linker takes a <tt>-plugin</tt> option that points to the path of
+ the plugin <tt>.so</tt> file. To find out what link command <tt>gcc</tt>
+ would run in a given situation, run <tt>gcc -v <em>[...]</em></tt> and look
+ for the line where it runs <tt>collect2</tt>. Replace that with
+ <tt>ld-new -plugin /path/to/LLVMgold.so</tt> to test it out. Once you're
+ ready to switch to using gold, backup your existing <tt>/usr/bin/ld</tt>
+ then replace it with <tt>ld-new</tt>.</p>
+
+ <p>You can produce bitcode files from <tt>clang</tt> using
+ <tt>-emit-llvm</tt> or <tt>-flto</tt>, or the <tt>-O4</tt> flag which is
+ synonymous with <tt>-O3 -flto</tt>.</p>
+
+ <p>Any of these flags will also cause <tt>clang</tt> to look for the
+ gold plugin in the <tt>lib</tt> directory under its prefix and pass the
+ <tt>-plugin</tt> option to <tt>ld</tt>. It will not look for an alternate
+ linker, which is why you need gold to be the installed system linker in
+ your path.</p>
+
+ <p>If you want <tt>ar</tt> and <tt>nm</tt> to work seamlessly as well, install
+ <tt>LLVMgold.so</tt> to <tt>/usr/lib/bfd-plugins</tt>. If you built your
+ own gold, be sure to install the <tt>ar</tt> and <tt>nm-new</tt> you built to
+ <tt>/usr/bin</tt>.<p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="example1">Example of link time optimization</a>
+</h3>
+
+<div>
+ <p>The following example shows a worked example of the gold plugin mixing
+ LLVM bitcode and native code.
+<pre class="doc_code">
+--- a.c ---
+#include &lt;stdio.h&gt;
+
+extern void foo1(void);
+extern void foo4(void);
+
+void foo2(void) {
+ printf("Foo2\n");
+}
+
+void foo3(void) {
+ foo4();
+}
+
+int main(void) {
+ foo1();
+}
+
+--- b.c ---
+#include &lt;stdio.h&gt;
+
+extern void foo2(void);
+
+void foo1(void) {
+ foo2();
+}
+
+void foo4(void) {
+ printf("Foo4");
+}
+
+--- command lines ---
+$ clang -flto a.c -c -o a.o # &lt;-- a.o is LLVM bitcode file
+$ ar q a.a a.o # &lt;-- a.a is an archive with LLVM bitcode
+$ clang b.c -c -o b.o # &lt;-- b.o is native object file
+$ clang -flto a.a b.o -o main # &lt;-- link with LLVMgold plugin
+</pre>
+
+ <p>Gold informs the plugin that foo3 is never referenced outside the IR,
+ leading LLVM to delete that function. However, unlike in the
+ <a href="LinkTimeOptimization.html#example1">libLTO
+ example</a> gold does not currently eliminate foo4.</p>
+</div>
+
+</div>
+
+<!--=========================================================================-->
+<h2>
+ <a name="lto_autotools">
+ Quickstart for using LTO with autotooled projects
+ </a>
+</h2>
+<!--=========================================================================-->
+<div>
+ <p>Once your system <tt>ld</tt>, <tt>ar</tt>, and <tt>nm</tt> all support LLVM
+ bitcode, everything is in place for an easy to use LTO build of autotooled
+ projects:</p>
+
+ <ul>
+ <li>Follow the instructions <a href="#build">on how to build LLVMgold.so</a>.</li>
+ <li>Install the newly built binutils to <tt>$PREFIX</tt></li>
+ <li>Copy <tt>Release/lib/LLVMgold.so</tt> to
+ <tt>$PREFIX/lib/bfd-plugins/</tt></li>
+ <li>Set environment variables (<tt>$PREFIX</tt> is where you installed clang and
+ binutils):
+<pre class="doc_code">
+export CC="$PREFIX/bin/clang -flto"
+export CXX="$PREFIX/bin/clang++ -flto"
+export AR="$PREFIX/bin/ar"
+export NM="$PREFIX/bin/nm"
+export RANLIB=/bin/true #ranlib is not needed, and doesn't support .bc files in .a
+export CFLAGS="-O4"
+</pre>
+ </li>
+ <li>Or you can just set your path:
+<pre class="doc_code">
+export PATH="$PREFIX/bin:$PATH"
+export CC="clang -flto"
+export CXX="clang++ -flto"
+export RANLIB=/bin/true
+export CFLAGS="-O4"
+</pre></li>
+ <li>Configure &amp; build the project as usual:
+<pre class="doc_code">
+% ./configure &amp;&amp; make &amp;&amp; make check
+</pre></li>
+ </ul>
+
+ <p>The environment variable settings may work for non-autotooled projects
+ too, but you may need to set the <tt>LD</tt> environment variable as
+ well.</p>
+</div>
+
+<!--=========================================================================-->
+<h2><a name="licensing">Licensing</a></h2>
+<!--=========================================================================-->
+<div>
+ <p>Gold is licensed under the GPLv3. LLVMgold uses the interface file
+<tt>plugin-api.h</tt> from gold which means that the resulting LLVMgold.so
+binary is also GPLv3. This can still be used to link non-GPLv3 programs just
+as much as gold could without the plugin.</p>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+ <a href="mailto:nicholas@metrix.on.ca">Nick Lewycky</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date: 2010-04-16 23:58:21 -0800 (Fri, 16 Apr 2010) $
+</address>
+</body>
+</html>
diff --git a/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeas.txt b/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeas.txt
new file mode 100644
index 00000000000..f0861811920
--- /dev/null
+++ b/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeas.txt
@@ -0,0 +1,74 @@
+Date: Sat, 18 Nov 2000 09:19:35 -0600 (CST)
+From: Vikram Adve <vadve@cs.uiuc.edu>
+To: Chris Lattner <lattner@cs.uiuc.edu>
+Subject: a few thoughts
+
+I've been mulling over the virtual machine problem and I had some
+thoughts about some things for us to think about discuss:
+
+1. We need to be clear on our goals for the VM. Do we want to emphasize
+ portability and safety like the Java VM? Or shall we focus on the
+ architecture interface first (i.e., consider the code generation and
+ processor issues), since the architecture interface question is also
+ important for portable Java-type VMs?
+
+ This is important because the audiences for these two goals are very
+ different. Architects and many compiler people care much more about
+ the second question. The Java compiler and OS community care much more
+ about the first one.
+
+ Also, while the architecture interface question is important for
+ Java-type VMs, the design constraints are very different.
+
+
+2. Design issues to consider (an initial list that we should continue
+ to modify). Note that I'm not trying to suggest actual solutions here,
+ but just various directions we can pursue:
+
+ a. A single-assignment VM, which we've both already been thinking about.
+
+ b. A strongly-typed VM. One question is do we need the types to be
+ explicitly declared or should they be inferred by the dynamic compiler?
+
+ c. How do we get more high-level information into the VM while keeping
+ to a low-level VM design?
+
+ o Explicit array references as operands? An alternative is
+ to have just an array type, and let the index computations be
+ separate 3-operand instructions.
+
+ o Explicit instructions to handle aliasing, e.g.s:
+ -- an instruction to say "I speculate that these two values are not
+ aliased, but check at runtime", like speculative execution in
+ EPIC?
+ -- or an instruction to check whether two values are aliased and
+ execute different code depending on the answer, somewhat like
+ predicated code in EPIC
+
+ o (This one is a difficult but powerful idea.)
+ A "thread-id" field on every instruction that allows the static
+ compiler to generate a set of parallel threads, and then have
+ the runtime compiler and hardware do what they please with it.
+ This has very powerful uses, but thread-id on every instruction
+ is expensive in terms of instruction size and code size.
+ We would need to compactly encode it somehow.
+
+ Also, this will require some reading on at least two other
+ projects:
+ -- Multiscalar architecture from Wisconsin
+ -- Simultaneous multithreading architecture from Washington
+
+ o Or forget all this and stick to a traditional instruction set?
+
+
+BTW, on an unrelated note, after the meeting yesterday, I did remember
+that you had suggested doing instruction scheduling on SSA form instead
+of a dependence DAG earlier in the semester. When we talked about
+it yesterday, I didn't remember where the idea had come from but I
+remembered later. Just giving credit where its due...
+
+Perhaps you can save the above as a file under RCS so you and I can
+continue to expand on this.
+
+--Vikram
+
diff --git a/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeasResp.txt b/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeasResp.txt
new file mode 100644
index 00000000000..81ca53919d4
--- /dev/null
+++ b/docs/HistoricalNotes/2000-11-18-EarlyDesignIdeasResp.txt
@@ -0,0 +1,199 @@
+Date: Sun, 19 Nov 2000 16:23:57 -0600 (CST)
+From: Chris Lattner <sabre@nondot.org>
+To: Vikram Adve <vadve@cs.uiuc.edu>
+Subject: Re: a few thoughts
+
+Okay... here are a few of my thoughts on this (it's good to know that we
+think so alike!):
+
+> 1. We need to be clear on our goals for the VM. Do we want to emphasize
+> portability and safety like the Java VM? Or shall we focus on the
+> architecture interface first (i.e., consider the code generation and
+> processor issues), since the architecture interface question is also
+> important for portable Java-type VMs?
+
+I forsee the architecture looking kinda like this: (which is completely
+subject to change)
+
+1. The VM code is NOT guaranteed safe in a java sense. Doing so makes it
+ basically impossible to support C like languages. Besides that,
+ certifying a register based language as safe at run time would be a
+ pretty expensive operation to have to do. Additionally, we would like
+ to be able to statically eliminate many bounds checks in Java
+ programs... for example.
+
+ 2. Instead, we can do the following (eventually):
+ * Java bytecode is used as our "safe" representation (to avoid
+ reinventing something that we don't add much value to). When the
+ user chooses to execute Java bytecodes directly (ie, not
+ precompiled) the runtime compiler can do some very simple
+ transformations (JIT style) to convert it into valid input for our
+ VM. Performance is not wonderful, but it works right.
+ * The file is scheduled to be compiled (rigorously) at a later
+ time. This could be done by some background process or by a second
+ processor in the system during idle time or something...
+ * To keep things "safe" ie to enforce a sandbox on Java/foreign code,
+ we could sign the generated VM code with a host specific private
+ key. Then before the code is executed/loaded, we can check to see if
+ the trusted compiler generated the code. This would be much quicker
+ than having to validate consistency (especially if bounds checks have
+ been removed, for example)
+
+> This is important because the audiences for these two goals are very
+> different. Architects and many compiler people care much more about
+> the second question. The Java compiler and OS community care much more
+> about the first one.
+
+3. By focusing on a more low level virtual machine, we have much more room
+ for value add. The nice safe "sandbox" VM can be provided as a layer
+ on top of it. It also lets us focus on the more interesting compilers
+ related projects.
+
+> 2. Design issues to consider (an initial list that we should continue
+> to modify). Note that I'm not trying to suggest actual solutions here,
+> but just various directions we can pursue:
+
+Understood. :)
+
+> a. A single-assignment VM, which we've both already been thinking
+> about.
+
+Yup, I think that this makes a lot of sense. I am still intrigued,
+however, by the prospect of a minimally allocated VM representation... I
+think that it could have definite advantages for certain applications
+(think very small machines, like PDAs). I don't, however, think that our
+initial implementations should focus on this. :)
+
+Here are some other auxiliary goals that I think we should consider:
+
+1. Primary goal: Support a high performance dynamic compilation
+ system. This means that we have an "ideal" division of labor between
+ the runtime and static compilers. Of course, the other goals of the
+ system somewhat reduce the importance of this point (f.e. portability
+ reduces performance, but hopefully not much)
+2. Portability to different processors. Since we are most familiar with
+ x86 and solaris, I think that these two are excellent candidates when
+ we get that far...
+3. Support for all languages & styles of programming (general purpose
+ VM). This is the point that disallows java style bytecodes, where all
+ array refs are checked for bounds, etc...
+4. Support linking between different language families. For example, call
+ C functions directly from Java without using the nasty/slow/gross JNI
+ layer. This involves several subpoints:
+ A. Support for languages that require garbage collectors and integration
+ with languages that don't. As a base point, we could insist on
+ always using a conservative GC, but implement free as a noop, f.e.
+
+> b. A strongly-typed VM. One question is do we need the types to be
+> explicitly declared or should they be inferred by the dynamic
+> compiler?
+
+ B. This is kind of similar to another idea that I have: make OOP
+ constructs (virtual function tables, class heirarchies, etc) explicit
+ in the VM representation. I believe that the number of additional
+ constructs would be fairly low, but would give us lots of important
+ information... something else that would/could be important is to
+ have exceptions as first class types so that they would be handled in
+ a uniform way for the entire VM... so that C functions can call Java
+ functions for example...
+
+> c. How do we get more high-level information into the VM while keeping
+> to a low-level VM design?
+> o Explicit array references as operands? An alternative is
+> to have just an array type, and let the index computations be
+> separate 3-operand instructions.
+
+ C. In the model I was thinking of (subject to change of course), we
+ would just have an array type (distinct from the pointer
+ types). This would allow us to have arbitrarily complex index
+ expressions, while still distinguishing "load" from "Array load",
+ for example. Perhaps also, switch jump tables would be first class
+ types as well? This would allow better reasoning about the program.
+
+5. Support dynamic loading of code from various sources. Already
+ mentioned above was the example of loading java bytecodes, but we want
+ to support dynamic loading of VM code as well. This makes the job of
+ the runtime compiler much more interesting: it can do interprocedural
+ optimizations that the static compiler can't do, because it doesn't
+ have all of the required information (for example, inlining from
+ shared libraries, etc...)
+
+6. Define a set of generally useful annotations to add to the VM
+ representation. For example, a function can be analysed to see if it
+ has any sideeffects when run... also, the MOD/REF sets could be
+ calculated, etc... we would have to determine what is reasonable. This
+ would generally be used to make IP optimizations cheaper for the
+ runtime compiler...
+
+> o Explicit instructions to handle aliasing, e.g.s:
+> -- an instruction to say "I speculate that these two values are not
+> aliased, but check at runtime", like speculative execution in
+> EPIC?
+> -- or an instruction to check whether two values are aliased and
+> execute different code depending on the answer, somewhat like
+> predicated code in EPIC
+
+These are also very good points... if this can be determined at compile
+time. I think that an epic style of representation (not the instruction
+packing, just the information presented) could be a very interesting model
+to use... more later...
+
+> o (This one is a difficult but powerful idea.)
+> A "thread-id" field on every instruction that allows the static
+> compiler to generate a set of parallel threads, and then have
+> the runtime compiler and hardware do what they please with it.
+> This has very powerful uses, but thread-id on every instruction
+> is expensive in terms of instruction size and code size.
+> We would need to compactly encode it somehow.
+
+Yes yes yes! :) I think it would be *VERY* useful to include this kind
+of information (which EPIC architectures *implicitly* encode. The trend
+that we are seeing supports this greatly:
+
+1. Commodity processors are getting massive SIMD support:
+ * Intel/Amd MMX/MMX2
+ * AMD's 3Dnow!
+ * Intel's SSE/SSE2
+ * Sun's VIS
+2. SMP is becoming much more common, especially in the server space.
+3. Multiple processors on a die are right around the corner.
+
+If nothing else, not designing this in would severely limit our future
+expansion of the project...
+
+> Also, this will require some reading on at least two other
+> projects:
+> -- Multiscalar architecture from Wisconsin
+> -- Simultaneous multithreading architecture from Washington
+>
+> o Or forget all this and stick to a traditional instruction set?
+
+Heh... :) Well, from a pure research point of view, it is almost more
+attactive to go with the most extreme/different ISA possible. On one axis
+you get safety and conservatism, and on the other you get degree of
+influence that the results have. Of course the problem with pure research
+is that often times there is no concrete product of the research... :)
+
+> BTW, on an unrelated note, after the meeting yesterday, I did remember
+> that you had suggested doing instruction scheduling on SSA form instead
+> of a dependence DAG earlier in the semester. When we talked about
+> it yesterday, I didn't remember where the idea had come from but I
+> remembered later. Just giving credit where its due...
+
+:) Thanks.
+
+> Perhaps you can save the above as a file under RCS so you and I can
+> continue to expand on this.
+
+I think it makes sense to do so when we get our ideas more formalized and
+bounce it back and forth a couple of times... then I'll do a more formal
+writeup of our goals and ideas. Obviously our first implementation will
+not want to do all of the stuff that I pointed out above... be we will
+want to design the project so that we do not artificially limit ourselves
+at sometime in the future...
+
+Anyways, let me know what you think about these ideas... and if they sound
+reasonable...
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2000-12-06-EncodingIdea.txt b/docs/HistoricalNotes/2000-12-06-EncodingIdea.txt
new file mode 100644
index 00000000000..8c452924dd1
--- /dev/null
+++ b/docs/HistoricalNotes/2000-12-06-EncodingIdea.txt
@@ -0,0 +1,30 @@
+From: Chris Lattner [mailto:sabre@nondot.org]
+Sent: Wednesday, December 06, 2000 6:41 PM
+To: Vikram S. Adve
+Subject: Additional idea with respect to encoding
+
+Here's another idea with respect to keeping the common case instruction
+size down (less than 32 bits ideally):
+
+Instead of encoding an instruction to operate on two register numbers,
+have it operate on two negative offsets based on the current register
+number. Therefore, instead of using:
+
+r57 = add r55, r56 (r57 is the implicit dest register, of course)
+
+We could use:
+
+r57 = add -2, -1
+
+My guess is that most SSA references are to recent values (especially if
+they correspond to expressions like (x+y*z+p*q/ ...), so the negative
+numbers would tend to stay small, even at the end of the procedure (where
+the implicit register destination number could be quite large). Of course
+the negative sign is reduntant, so you would be storing small integers
+almost all of the time, and 5-6 bits worth of register number would be
+plenty for most cases...
+
+What do you think?
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2000-12-06-MeetingSummary.txt b/docs/HistoricalNotes/2000-12-06-MeetingSummary.txt
new file mode 100644
index 00000000000..01b644b3517
--- /dev/null
+++ b/docs/HistoricalNotes/2000-12-06-MeetingSummary.txt
@@ -0,0 +1,83 @@
+SUMMARY
+-------
+
+We met to discuss the LLVM instruction format and bytecode representation:
+
+ISSUES RESOLVED
+---------------
+
+1. We decided that we shall use a flat namespace to represent our
+ variables in SSA form, as opposed to having a two dimensional namespace
+ of the original variable and the SSA instance subscript.
+
+ARGUMENT AGAINST:
+ * A two dimensional namespace would be valuable when doing alias
+ analysis because the extra information can help limit the scope of
+ analysis.
+
+ARGUMENT FOR:
+ * Including this information would require that all users of the LLVM
+ bytecode would have to parse and handle it. This would slow down the
+ common case and inflate the instruction representation with another
+ infinite variable space.
+
+REASONING:
+ * It was decided that because original variable sources could be
+ reconstructed from SSA form in linear time, that it would be an
+ unjustified expense for the common case to include the extra
+ information for one optimization. Alias analysis itself is typically
+ greater than linear in asymptotic complexity, so this extra analaysis
+ would not affect the runtime of the optimization in a significant
+ way. Additionally, this would be an unlikely optimization to do at
+ runtime.
+
+
+IDEAS TO CONSIDER
+-----------------
+
+1. Including dominator information in the LLVM bytecode
+ representation. This is one example of an analysis result that may be
+ packaged with the bytecodes themselves. As a conceptual implementation
+ idea, we could include an immediate dominator number for each basic block
+ in the LLVM bytecode program. Basic blocks could be numbered according
+ to the order of occurrence in the bytecode representation.
+
+2. Including loop header and body information. This would facilitate
+ detection of intervals and natural loops.
+
+UNRESOLVED ISSUES
+-----------------
+
+1. Will oSUIF provide enough of an infrastructure to support the research
+ that we will be doing? We know that it has less than stellar
+ performance, but hope that this will be of little importance for our
+ static compiler. This could affect us if we decided to do some IP
+ research. Also we do not yet understand the level of exception support
+ currently implemented.
+
+2. Should we consider the requirements of a direct hardware implementation
+ of the LLVM when we design it? If so, several design issues should
+ have their priorities shifted. The other option is to focus on a
+ software layer interpreting the LLVM in all cases.
+
+3. Should we use some form of packetized format to improve forward
+ compatibility? For example, we could design the system to encode a
+ packet type and length field before analysis information, to allow a
+ runtime to skip information that it didn't understand in a bytecode
+ stream. The obvious benefit would be for compatibility, the drawback
+ is that it would tend to splinter that 'standard' LLVM definition.
+
+4. Should we use fixed length instructions or variable length
+ instructions? Fetching variable length instructions is expensive (for
+ either hardware or software based LLVM runtimes), but we have several
+ 'infinite' spaces that instructions operate in (SSA register numbers,
+ type spaces, or packet length [if packets were implemented]). Several
+ options were mentioned including:
+ A. Using 16 or 32 bit numbers, which would be 'big enough'
+ B. A scheme similar to how UTF-8 works, to encode infinite numbers
+ while keeping small number small.
+ C. Use something similar to Huffman encoding, so that the most common
+ numbers are the smallest.
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2001-01-31-UniversalIRIdea.txt b/docs/HistoricalNotes/2001-01-31-UniversalIRIdea.txt
new file mode 100644
index 00000000000..111706a3447
--- /dev/null
+++ b/docs/HistoricalNotes/2001-01-31-UniversalIRIdea.txt
@@ -0,0 +1,39 @@
+Date: Wed, 31 Jan 2001 12:04:33 -0600
+From: Vikram S. Adve <vadve@cs.uiuc.edu>
+To: Chris Lattner <lattner@cs.uiuc.edu>
+Subject: another thought
+
+I have a budding idea about making LLVM a little more ambitious: a
+customizable runtime system that can be used to implement language-specific
+virtual machines for many different languages. E.g., a C vm, a C++ vm, a
+Java vm, a Lisp vm, ..
+
+The idea would be that LLVM would provide a standard set of runtime features
+(some low-level like standard assembly instructions with code generation and
+static and runtime optimization; some higher-level like type-safety and
+perhaps a garbage collection library). Each language vm would select the
+runtime features needed for that language, extending or customizing them as
+needed. Most of the machine-dependent code-generation and optimization
+features as well as low-level machine-independent optimizations (like PRE)
+could be provided by LLVM and should be sufficient for any language,
+simplifying the language compiler. (This would also help interoperability
+between languages.) Also, some or most of the higher-level
+machine-independent features like type-safety and access safety should be
+reusable by different languages, with minor extensions. The language
+compiler could then focus on language-specific analyses and optimizations.
+
+The risk is that this sounds like a universal IR -- something that the
+compiler community has tried and failed to develop for decades, and is
+universally skeptical about. No matter what we say, we won't be able to
+convince anyone that we have a universal IR that will work. We need to
+think about whether LLVM is different or if has something novel that might
+convince people. E.g., the idea of providing a package of separable
+features that different languages select from. Also, using SSA with or
+without type-safety as the intermediate representation.
+
+One interesting starting point would be to discuss how a JVM would be
+implemented on top of LLVM a bit more. That might give us clues on how to
+structure LLVM to support one or more language VMs.
+
+--Vikram
+
diff --git a/docs/HistoricalNotes/2001-02-06-TypeNotationDebate.txt b/docs/HistoricalNotes/2001-02-06-TypeNotationDebate.txt
new file mode 100644
index 00000000000..c09cf1f03cc
--- /dev/null
+++ b/docs/HistoricalNotes/2001-02-06-TypeNotationDebate.txt
@@ -0,0 +1,67 @@
+Date: Tue, 6 Feb 2001 20:27:37 -0600 (CST)
+From: Chris Lattner <sabre@nondot.org>
+To: Vikram S. Adve <vadve@cs.uiuc.edu>
+Subject: Type notation debate...
+
+This is the way that I am currently planning on implementing types:
+
+Primitive Types:
+type ::= void|bool|sbyte|ubyte|short|ushort|int|uint|long|ulong
+
+Method:
+typelist ::= typelisth | /*empty*/
+typelisth ::= type | typelisth ',' type
+type ::= type (typelist)
+
+Arrays (without and with size):
+type ::= '[' type ']' | '[' INT ',' type ']'
+
+Pointer:
+type ::= type '*'
+
+Structure:
+type ::= '{' typelist '}'
+
+Packed:
+type ::= '<' INT ',' type '>'
+
+Simple examples:
+
+[[ %4, int ]] - array of (array of 4 (int))
+[ { int, int } ] - Array of structure
+[ < %4, int > ] - Array of 128 bit SIMD packets
+int (int, [[int, %4]]) - Method taking a 2d array and int, returning int
+
+
+Okay before you comment, please look at:
+
+http://www.research.att.com/~bs/devXinterview.html
+
+Search for "In another interview, you defined the C declarator syntax as
+an experiment that failed. However, this syntactic construct has been
+around for 27 years and perhaps more; why do you consider it problematic
+(except for its cumbersome syntax)?" and read that response for me. :)
+
+Now with this syntax, his example would be represented as:
+
+[ %10, bool (int, int) * ] *
+
+vs
+
+bool (*(*)[10])(int, int)
+
+in C.
+
+Basically, my argument for this type construction system is that it is
+VERY simple to use and understand (although it IS different than C, it is
+very simple and straightforward, which C is NOT). In fact, I would assert
+that most programmers TODAY do not understand pointers to member
+functions, and have to look up an example when they have to write them.
+
+In my opinion, it is critically important to have clear and concise type
+specifications, because types are going to be all over the programs.
+
+Let me know your thoughts on this. :)
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp1.txt b/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp1.txt
new file mode 100644
index 00000000000..8bfefbf69f6
--- /dev/null
+++ b/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp1.txt
@@ -0,0 +1,75 @@
+Date: Thu, 8 Feb 2001 08:42:04 -0600
+From: Vikram S. Adve <vadve@cs.uiuc.edu>
+To: Chris Lattner <sabre@nondot.org>
+Subject: RE: Type notation debate...
+
+Chris,
+
+> Okay before you comment, please look at:
+>
+> http://www.research.att.com/~bs/devXinterview.html
+
+I read this argument. Even before that, I was already in agreement with you
+and him that the C declarator syntax is difficult and confusing.
+
+But in fact, if you read the entire answer carefully, he came to the same
+conclusion I do: that you have to go with familiar syntax over logical
+syntax because familiarity is such a strong force:
+
+ "However, familiarity is a strong force. To compare, in English, we
+live
+more or less happily with the absurd rules for "to be" (am, are, is, been,
+was, were, ...) and all attempts to simplify are treated with contempt or
+(preferably) humor. It be a curious world and it always beed."
+
+> Basically, my argument for this type construction system is that it is
+> VERY simple to use and understand (although it IS different than C, it is
+> very simple and straightforward, which C is NOT). In fact, I would assert
+> that most programmers TODAY do not understand pointers to member
+> functions, and have to look up an example when they have to write them.
+
+Again, I don't disagree with this at all. But to some extent this
+particular problem is inherently difficult. Your syntax for the above
+example may be easier for you to read because this is the way you have been
+thinking about it. Honestly, I don't find it much easier than the C syntax.
+In either case, I would have to look up an example to write pointers to
+member functions.
+
+But pointers to member functions are nowhere near as common as arrays. And
+the old array syntax:
+ type [ int, int, ...]
+is just much more familiar and clear to people than anything new you
+introduce, no matter how logical it is. Introducing a new syntax that may
+make function pointers easier but makes arrays much more difficult seems
+very risky to me.
+
+> In my opinion, it is critically important to have clear and concise type
+> specifications, because types are going to be all over the programs.
+
+I absolutely agree. But the question is, what is more clear and concise?
+The syntax programmers are used to out of years of experience or a new
+syntax that they have never seen that has a more logical structure. I think
+the answer is the former. Sometimes, you have to give up a better idea
+because you can't overcome sociological barriers to it. Qwerty keyboards
+and Windows are two classic examples of bad technology that are difficult to
+root out.
+
+P.S. Also, while I agree that most your syntax is more logical, there is
+one part that isn't:
+
+Arrays (without and with size):
+type ::= '[' type ']' | '[' INT ',' type ']'.
+
+The arrays with size lists the dimensions and the type in a single list.
+That is just too confusing:
+ [10, 40, int]
+This seems to be a 3-D array where the third dimension is something strange.
+It is too confusing to have a list of 3 things, some of which are dimensions
+and one is a type. Either of the following would be better:
+
+ array [10, 40] of int
+or
+ int [10, 40]
+
+--Vikram
+
diff --git a/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp2.txt b/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp2.txt
new file mode 100644
index 00000000000..6e9784158a3
--- /dev/null
+++ b/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp2.txt
@@ -0,0 +1,53 @@
+Date: Thu, 8 Feb 2001 14:31:05 -0600 (CST)
+From: Chris Lattner <sabre@nondot.org>
+To: Vikram S. Adve <vadve@cs.uiuc.edu>
+Subject: RE: Type notation debate...
+
+> Arrays (without and with size):
+> type ::= '[' type ']' | '[' INT ',' type ']'.
+>
+> The arrays with size lists the dimensions and the type in a single list.
+> That is just too confusing:
+
+> [10, 40, int]
+> This seems to be a 3-D array where the third dimension is something strange.
+> It is too confusing to have a list of 3 things, some of which are dimensions
+> and one is a type.
+
+The above grammar indicates that there is only one integer parameter, ie
+the upper bound. The lower bound is always implied to be zero, for
+several reasons:
+
+* As a low level VM, we want to expose addressing computations
+ explicitly. Since the lower bound must always be known in a high level
+ language statically, the language front end can do the translation
+ automatically.
+* This fits more closely with what Java needs, ie what we need in the
+ short term. Java arrays are always zero based.
+
+If a two element list is too confusing, I would recommend an alternate
+syntax of:
+
+type ::= '[' type ']' | '[' INT 'x' type ']'.
+
+For example:
+ [12 x int]
+ [12x int]
+ [ 12 x [ 4x int ]]
+
+Which is syntactically nicer, and more explicit.
+
+> Either of the following would be better:
+> array [10, 40] of int
+
+I considered this approach for arrays in general (ie array of int/ array
+of 12 int), but found that it made declarations WAY too long. Remember
+that because of the nature of llvm, you get a lot of types strewn all over
+the program, and using the 'typedef' like facility is not a wonderful
+option, because then types aren't explicit anymore.
+
+I find this email interesting, because you contradict the previous email
+you sent, where you recommend that we stick to C syntax....
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp4.txt b/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp4.txt
new file mode 100644
index 00000000000..839732444f9
--- /dev/null
+++ b/docs/HistoricalNotes/2001-02-06-TypeNotationDebateResp4.txt
@@ -0,0 +1,89 @@
+> But in fact, if you read the entire answer carefully, he came to the same
+> conclusion I do: that you have to go with familiar syntax over logical
+> syntax because familiarity is such a strong force:
+> "However, familiarity is a strong force. To compare, in English, we
+live
+> more or less happily with the absurd rules for "to be" (am, are, is, been,
+> was, were, ...) and all attempts to simplify are treated with contempt or
+> (preferably) humor. It be a curious world and it always beed."
+
+Although you have to remember that his situation was considerably
+different than ours. He was in a position where he was designing a high
+level language that had to be COMPATIBLE with C. Our language is such
+that a new person would have to learn the new, different, syntax
+anyways. Making them learn about the type system does not seem like much
+of a stretch from learning the opcodes and how SSA form works, and how
+everything ties together...
+
+> > Basically, my argument for this type construction system is that it is
+> > VERY simple to use and understand (although it IS different than C, it is
+> > very simple and straightforward, which C is NOT). In fact, I would assert
+> > that most programmers TODAY do not understand pointers to member
+> > functions, and have to look up an example when they have to write them.
+
+> Again, I don't disagree with this at all. But to some extent this
+> particular problem is inherently difficult. Your syntax for the above
+> example may be easier for you to read because this is the way you have been
+> thinking about it. Honestly, I don't find it much easier than the C syntax.
+> In either case, I would have to look up an example to write pointers to
+> member functions.
+
+I would argue that because the lexical structure of the language is self
+consistent, any person who spent a significant amount of time programming
+in LLVM directly would understand how to do it without looking it up in a
+manual. The reason this does not work for C is because you rarely have to
+declare these pointers, and the syntax is inconsistent with the method
+declaration and calling syntax.
+
+> But pointers to member functions are nowhere near as common as arrays.
+
+Very true. If you're implementing an object oriented language, however,
+remember that you have to do all the pointer to member function stuff
+yourself.... so every time you invoke a virtual method one is involved
+(instead of having C++ hide it for you behind "syntactic sugar").
+
+> And the old array syntax:
+> type [ int, int, ...]
+> is just much more familiar and clear to people than anything new you
+> introduce, no matter how logical it is.
+
+Erm... excuse me but how is this the "old array syntax"? If you are
+arguing for consistency with C, you should be asking for 'type int []',
+which is significantly different than the above (beside the above
+introduces a new operator and duplicates information
+needlessly). Basically what I am suggesting is exactly the above without
+the fluff. So instead of:
+
+ type [ int, int, ...]
+
+you use:
+
+ type [ int ]
+
+> Introducing a new syntax that may
+> make function pointers easier but makes arrays much more difficult seems
+> very risky to me.
+
+This is not about function pointers. This is about consistency in the
+type system, and consistency with the rest of the language. The point
+above does not make arrays any more difficult to use, and makes the
+structure of types much more obvious than the "c way".
+
+> > In my opinion, it is critically important to have clear and concise type
+> > specifications, because types are going to be all over the programs.
+>
+> I absolutely agree. But the question is, what is more clear and concise?
+> The syntax programmers are used to out of years of experience or a new
+> syntax that they have never seen that has a more logical structure. I think
+> the answer is the former. Sometimes, you have to give up a better idea
+> because you can't overcome sociological barriers to it. Qwerty keyboards
+> and Windows are two classic examples of bad technology that are difficult to
+> root out.
+
+Very true, but you seem to be advocating a completely different Type
+system than C has, in addition to it not offering the advantages of clear
+structure that the system I recommended does... so you seem to not have a
+problem with changing this, just with what I change it to. :)
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2001-02-09-AdveComments.txt b/docs/HistoricalNotes/2001-02-09-AdveComments.txt
new file mode 100644
index 00000000000..5503233c1ed
--- /dev/null
+++ b/docs/HistoricalNotes/2001-02-09-AdveComments.txt
@@ -0,0 +1,120 @@
+Ok, here are my comments and suggestions about the LLVM instruction set.
+We should discuss some now, but can discuss many of them later, when we
+revisit synchronization, type inference, and other issues.
+(We have discussed some of the comments already.)
+
+
+o We should consider eliminating the type annotation in cases where it is
+ essentially obvious from the instruction type, e.g., in br, it is obvious
+ that the first arg. should be a bool and the other args should be labels:
+
+ br bool <cond>, label <iftrue>, label <iffalse>
+
+ I think your point was that making all types explicit improves clarity
+ and readability. I agree to some extent, but it also comes at the cost
+ of verbosity. And when the types are obvious from people's experience
+ (e.g., in the br instruction), it doesn't seem to help as much.
+
+
+o On reflection, I really like your idea of having the two different switch
+ types (even though they encode implementation techniques rather than
+ semantics). It should simplify building the CFG and my guess is it could
+ enable some significant optimizations, though we should think about which.
+
+
+o In the lookup-indirect form of the switch, is there a reason not to make
+ the val-type uint? Most HLL switch statements (including Java and C++)
+ require that anyway. And it would also make the val-type uniform
+ in the two forms of the switch.
+
+ I did see the switch-on-bool examples and, while cute, we can just use
+ the branch instructions in that particular case.
+
+
+o I agree with your comment that we don't need 'neg'.
+
+
+o There's a trade-off with the cast instruction:
+ + it avoids having to define all the upcasts and downcasts that are
+ valid for the operands of each instruction (you probably have thought
+ of other benefits also)
+ - it could make the bytecode significantly larger because there could
+ be a lot of cast operations
+
+
+o Making the second arg. to 'shl' a ubyte seems good enough to me.
+ 255 positions seems adequate for several generations of machines
+ and is more compact than uint.
+
+
+o I still have some major concerns about including malloc and free in the
+ language (either as builtin functions or instructions). LLVM must be
+ able to represent code from many different languages. Languages such as
+ C, C++ Java and Fortran 90 would not be able to use our malloc anyway
+ because each of them will want to provide a library implementation of it.
+
+ This gets even worse when code from different languages is linked
+ into a single executable (which is fairly common in large apps).
+ Having a single malloc would just not suffice, and instead would simply
+ complicate the picture further because it adds an extra variant in
+ addition to the one each language provides.
+
+ Instead, providing a default library version of malloc and free
+ (and perhaps a malloc_gc with garbage collection instead of free)
+ would make a good implementation available to anyone who wants it.
+
+ I don't recall all your arguments in favor so let's discuss this again,
+ and soon.
+
+
+o 'alloca' on the other hand sounds like a good idea, and the
+ implementation seems fairly language-independent so it doesn't have the
+ problems with malloc listed above.
+
+
+o About indirect call:
+ Your option #2 sounded good to me. I'm not sure I understand your
+ concern about an explicit 'icall' instruction?
+
+
+o A pair of important synchronization instr'ns to think about:
+ load-linked
+ store-conditional
+
+
+o Other classes of instructions that are valuable for pipeline performance:
+ conditional-move
+ predicated instructions
+
+
+o I believe tail calls are relatively easy to identify; do you know why
+ .NET has a tailcall instruction?
+
+
+o I agree that we need a static data space. Otherwise, emulating global
+ data gets unnecessarily complex.
+
+
+o About explicit parallelism:
+
+ We once talked about adding a symbolic thread-id field to each
+ instruction. (It could be optional so single-threaded codes are
+ not penalized.) This could map well to multi-threaded architectures
+ while providing easy ILP for single-threaded onces. But it is probably
+ too radical an idea to include in a base version of LLVM. Instead, it
+ could a great topic for a separate study.
+
+ What is the semantics of the IA64 stop bit?
+
+
+
+
+o And finally, another thought about the syntax for arrays :-)
+
+ Although this syntax:
+ array <dimension-list> of <type>
+ is verbose, it will be used only in the human-readable assembly code so
+ size should not matter. I think we should consider it because I find it
+ to be the clearest syntax. It could even make arrays of function
+ pointers somewhat readable.
+
diff --git a/docs/HistoricalNotes/2001-02-09-AdveCommentsResponse.txt b/docs/HistoricalNotes/2001-02-09-AdveCommentsResponse.txt
new file mode 100644
index 00000000000..da502636653
--- /dev/null
+++ b/docs/HistoricalNotes/2001-02-09-AdveCommentsResponse.txt
@@ -0,0 +1,245 @@
+From: Chris Lattner <sabre@nondot.org>
+To: "Vikram S. Adve" <vadve@cs.uiuc.edu>
+Subject: Re: LLVM Feedback
+
+I've included your feedback in the /home/vadve/lattner/llvm/docs directory
+so that it will live in CVS eventually with the rest of LLVM. I've
+significantly updated the documentation to reflect the changes you
+suggested, as specified below:
+
+> We should consider eliminating the type annotation in cases where it is
+> essentially obvious from the instruction type:
+> br bool <cond>, label <iftrue>, label <iffalse>
+> I think your point was that making all types explicit improves clarity
+> and readability. I agree to some extent, but it also comes at the
+> cost of verbosity. And when the types are obvious from people's
+> experience (e.g., in the br instruction), it doesn't seem to help as
+> much.
+
+Very true. We should discuss this more, but my reasoning is more of a
+consistency argument. There are VERY few instructions that can have all
+of the types eliminated, and doing so when available unnecessarily makes
+the language more difficult to handle. Especially when you see 'int
+%this' and 'bool %that' all over the place, I think it would be
+disorienting to see:
+
+ br %predicate, %iftrue, %iffalse
+
+for branches. Even just typing that once gives me the creeps. ;) Like I
+said, we should probably discuss this further in person...
+
+> On reflection, I really like your idea of having the two different
+> switch types (even though they encode implementation techniques rather
+> than semantics). It should simplify building the CFG and my guess is it
+> could enable some significant optimizations, though we should think
+> about which.
+
+Great. I added a note to the switch section commenting on how the VM
+should just use the instruction type as a hint, and that the
+implementation may choose altermate representations (such as predicated
+branches).
+
+> In the lookup-indirect form of the switch, is there a reason not to
+> make the val-type uint?
+
+No. This was something I was debating for a while, and didn't really feel
+strongly about either way. It is common to switch on other types in HLL's
+(for example signed int's are particularly common), but in this case, all
+that will be added is an additional 'cast' instruction. I removed that
+from the spec.
+
+> I agree with your comment that we don't need 'neg'
+
+Removed.
+
+> There's a trade-off with the cast instruction:
+> + it avoids having to define all the upcasts and downcasts that are
+> valid for the operands of each instruction (you probably have
+> thought of other benefits also)
+> - it could make the bytecode significantly larger because there could
+> be a lot of cast operations
+
+ + You NEED casts to represent things like:
+ void foo(float);
+ ...
+ int x;
+ ...
+ foo(x);
+ in a language like C. Even in a Java like language, you need upcasts
+ and some way to implement dynamic downcasts.
+ + Not all forms of instructions take every type (for example you can't
+ shift by a floating point number of bits), thus SOME programs will need
+ implicit casts.
+
+To be efficient and to avoid your '-' point above, we just have to be
+careful to specify that the instructions shall operate on all common
+types, therefore casting should be relatively uncommon. For example all
+of the arithmetic operations work on almost all data types.
+
+> Making the second arg. to 'shl' a ubyte seems good enough to me.
+> 255 positions seems adequate for several generations of machines
+
+Okay, that comment is removed.
+
+> and is more compact than uint.
+
+No, it isn't. Remember that the bytecode encoding saves value slots into
+the bytecode instructions themselves, not constant values. This is
+another case where we may introduce more cast instructions (but we will
+also reduce the number of opcode variants that must be supported by a
+virtual machine). Because most shifts are by constant values, I don't
+think that we'll have to cast many shifts. :)
+
+> I still have some major concerns about including malloc and free in the
+> language (either as builtin functions or instructions).
+
+Agreed. How about this proposal:
+
+malloc/free are either built in functions or actual opcodes. They provide
+all of the type safety that the document would indicate, blah blah
+blah. :)
+
+Now, because of all of the excellent points that you raised, an
+implementation may want to override the default malloc/free behavior of
+the program. To do this, they simply implement a "malloc" and
+"free" function. The virtual machine will then be defined to use the user
+defined malloc/free function (which return/take void*'s, not type'd
+pointers like the builtin function would) if one is available, otherwise
+fall back on a system malloc/free.
+
+Does this sound like a good compromise? It would give us all of the
+typesafety/elegance in the language while still allowing the user to do
+all the cool stuff they want to...
+
+> 'alloca' on the other hand sounds like a good idea, and the
+> implementation seems fairly language-independent so it doesn't have the
+> problems with malloc listed above.
+
+Okay, once we get the above stuff figured out, I'll put it all in the
+spec.
+
+> About indirect call:
+> Your option #2 sounded good to me. I'm not sure I understand your
+> concern about an explicit 'icall' instruction?
+
+I worry too much. :) The other alternative has been removed. 'icall' is
+now up in the instruction list next to 'call'.
+
+> I believe tail calls are relatively easy to identify; do you know why
+> .NET has a tailcall instruction?
+
+Although I am just guessing, I believe it probably has to do with the fact
+that they want languages like Haskell and lisp to be efficiently runnable
+on their VM. Of course this means that the VM MUST implement tail calls
+'correctly', or else life will suck. :) I would put this into a future
+feature bin, because it could be pretty handy...
+
+> A pair of important synchronization instr'ns to think about:
+> load-linked
+> store-conditional
+
+What is 'load-linked'? I think that (at least for now) I should add these
+to the 'possible extensions' section, because they are not immediately
+needed...
+
+> Other classes of instructions that are valuable for pipeline
+> performance:
+> conditional-move
+> predicated instructions
+
+Conditional move is effectly a special case of a predicated
+instruction... and I think that all predicated instructions can possibly
+be implemented later in LLVM. It would significantly change things, and
+it doesn't seem to be very necessary right now. It would seem to
+complicate flow control analysis a LOT in the virtual machine. I would
+tend to prefer that a predicated architecture like IA64 convert from a
+"basic block" representation to a predicated rep as part of it's dynamic
+complication phase. Also, if a basic block contains ONLY a move, then
+that can be trivally translated into a conditional move...
+
+> I agree that we need a static data space. Otherwise, emulating global
+> data gets unnecessarily complex.
+
+Definitely. Also a later item though. :)
+
+> We once talked about adding a symbolic thread-id field to each
+> ..
+> Instead, it could a great topic for a separate study.
+
+Agreed. :)
+
+> What is the semantics of the IA64 stop bit?
+
+Basically, the IA64 writes instructions like this:
+mov ...
+add ...
+sub ...
+op xxx
+op xxx
+;;
+mov ...
+add ...
+sub ...
+op xxx
+op xxx
+;;
+
+Where the ;; delimits a group of instruction with no dependencies between
+them, which can all be executed concurrently (to the limits of the
+available functional units). The ;; gets translated into a bit set in one
+of the opcodes.
+
+The advantages of this representation is that you don't have to do some
+kind of 'thread id scheduling' pass by having to specify ahead of time how
+many threads to use, and the representation doesn't have a per instruction
+overhead...
+
+> And finally, another thought about the syntax for arrays :-)
+> Although this syntax:
+> array <dimension-list> of <type>
+> is verbose, it will be used only in the human-readable assembly code so
+> size should not matter. I think we should consider it because I find it
+> to be the clearest syntax. It could even make arrays of function
+> pointers somewhat readable.
+
+My only comment will be to give you an example of why this is a bad
+idea. :)
+
+Here is an example of using the switch statement (with my recommended
+syntax):
+
+switch uint %val, label %otherwise,
+ [%3 x {uint, label}] [ { uint %57, label %l1 },
+ { uint %20, label %l2 },
+ { uint %14, label %l3 } ]
+
+Here it is with the syntax you are proposing:
+
+switch uint %val, label %otherwise,
+ array %3 of {uint, label}
+ array of {uint, label}
+ { uint %57, label %l1 },
+ { uint %20, label %l2 },
+ { uint %14, label %l3 }
+
+Which is ambiguous and very verbose. It would be possible to specify
+constants with [] brackets as in my syntax, which would look like this:
+
+switch uint %val, label %otherwise,
+ array %3 of {uint, label} [ { uint %57, label %l1 },
+ { uint %20, label %l2 },
+ { uint %14, label %l3 } ]
+
+But then the syntax is inconsistent between type definition and constant
+definition (why do []'s enclose the constants but not the types??).
+
+Anyways, I'm sure that there is much debate still to be had over
+this... :)
+
+-Chris
+
+http://www.nondot.org/~sabre/os/
+http://www.nondot.org/MagicStats/
+http://korbit.sourceforge.net/
+
+
diff --git a/docs/HistoricalNotes/2001-02-13-Reference-Memory.txt b/docs/HistoricalNotes/2001-02-13-Reference-Memory.txt
new file mode 100644
index 00000000000..2c7534d9da1
--- /dev/null
+++ b/docs/HistoricalNotes/2001-02-13-Reference-Memory.txt
@@ -0,0 +1,39 @@
+Date: Tue, 13 Feb 2001 13:29:52 -0600 (CST)
+From: Chris Lattner <sabre@nondot.org>
+To: Vikram S. Adve <vadve@cs.uiuc.edu>
+Subject: LLVM Concerns...
+
+
+I've updated the documentation to include load store and allocation
+instructions (please take a look and let me know if I'm on the right
+track):
+
+file:/home/vadve/lattner/llvm/docs/LangRef.html#memoryops
+
+I have a couple of concerns I would like to bring up:
+
+1. Reference types
+ Right now, I've spec'd out the language to have a pointer type, which
+ works fine for lots of stuff... except that Java really has
+ references: constrained pointers that cannot be manipulated: added and
+ subtracted, moved, etc... Do we want to have a type like this? It
+ could be very nice for analysis (pointer always points to the start of
+ an object, etc...) and more closely matches Java semantics. The
+ pointer type would be kept for C++ like semantics. Through analysis,
+ C++ pointers could be promoted to references in the LLVM
+ representation.
+
+2. Our "implicit" memory references in assembly language:
+ After thinking about it, this model has two problems:
+ A. If you do pointer analysis and realize that two stores are
+ independent and can share the same memory source object, there is
+ no way to represent this in either the bytecode or assembly.
+ B. When parsing assembly/bytecode, we effectively have to do a full
+ SSA generation/PHI node insertion pass to build the dependencies
+ when we don't want the "pinned" representation. This is not
+ cool.
+ I'm tempted to make memory references explicit in both the assembly and
+ bytecode to get around this... what do you think?
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2001-02-13-Reference-MemoryResponse.txt b/docs/HistoricalNotes/2001-02-13-Reference-MemoryResponse.txt
new file mode 100644
index 00000000000..505343378df
--- /dev/null
+++ b/docs/HistoricalNotes/2001-02-13-Reference-MemoryResponse.txt
@@ -0,0 +1,47 @@
+Date: Tue, 13 Feb 2001 18:25:42 -0600
+From: Vikram S. Adve <vadve@cs.uiuc.edu>
+To: Chris Lattner <sabre@nondot.org>
+Subject: RE: LLVM Concerns...
+
+> 1. Reference types
+> Right now, I've spec'd out the language to have a pointer type, which
+> works fine for lots of stuff... except that Java really has
+> references: constrained pointers that cannot be manipulated: added and
+> subtracted, moved, etc... Do we want to have a type like this? It
+> could be very nice for analysis (pointer always points to the start of
+> an object, etc...) and more closely matches Java semantics. The
+> pointer type would be kept for C++ like semantics. Through analysis,
+> C++ pointers could be promoted to references in the LLVM
+> representation.
+
+
+You're right, having references would be useful. Even for C++ the *static*
+compiler could generate references instead of pointers with fairly
+straightforward analysis. Let's include a reference type for now. But I'm
+also really concerned that LLVM is becoming big and complex and (perhaps)
+too high-level. After we get some initial performance results, we may have
+a clearer idea of what our goals should be and we should revisit this
+question then.
+
+> 2. Our "implicit" memory references in assembly language:
+> After thinking about it, this model has two problems:
+> A. If you do pointer analysis and realize that two stores are
+> independent and can share the same memory source object,
+
+not sure what you meant by "share the same memory source object"
+
+> there is
+> no way to represent this in either the bytecode or assembly.
+> B. When parsing assembly/bytecode, we effectively have to do a full
+> SSA generation/PHI node insertion pass to build the dependencies
+> when we don't want the "pinned" representation. This is not
+> cool.
+
+I understand the concern. But again, let's focus on the performance first
+and then look at the language design issues. E.g., it would be good to know
+how big the bytecode files are before expanding them further. I am pretty
+keen to explore the implications of LLVM for mobile devices. Both bytecode
+size and power consumption are important to consider there.
+
+--Vikram
+
diff --git a/docs/HistoricalNotes/2001-04-16-DynamicCompilation.txt b/docs/HistoricalNotes/2001-04-16-DynamicCompilation.txt
new file mode 100644
index 00000000000..5f7843ab563
--- /dev/null
+++ b/docs/HistoricalNotes/2001-04-16-DynamicCompilation.txt
@@ -0,0 +1,49 @@
+By Chris:
+
+LLVM has been designed with two primary goals in mind. First we strive to
+enable the best possible division of labor between static and dynamic
+compilers, and second, we need a flexible and powerful interface
+between these two complementary stages of compilation. We feel that
+providing a solution to these two goals will yield an excellent solution
+to the performance problem faced by modern architectures and programming
+languages.
+
+A key insight into current compiler and runtime systems is that a
+compiler may fall in anywhere in a "continuum of compilation" to do its
+job. On one side, scripting languages statically compile nothing and
+dynamically compile (or equivalently, interpret) everything. On the far
+other side, traditional static compilers process everything statically and
+nothing dynamically. These approaches have typically been seen as a
+tradeoff between performance and portability. On a deeper level, however,
+there are two reasons that optimal system performance may be obtained by a
+system somewhere in between these two extremes: Dynamic application
+behavior and social constraints.
+
+From a technical perspective, pure static compilation cannot ever give
+optimal performance in all cases, because applications have varying dynamic
+behavior that the static compiler cannot take into consideration. Even
+compilers that support profile guided optimization generate poor code in
+the real world, because using such optimization tunes that application
+to one particular usage pattern, whereas real programs (as opposed to
+benchmarks) often have several different usage patterns.
+
+On a social level, static compilation is a very shortsighted solution to
+the performance problem. Instruction set architectures (ISAs) continuously
+evolve, and each implementation of an ISA (a processor) must choose a set
+of tradeoffs that make sense in the market context that it is designed for.
+With every new processor introduced, the vendor faces two fundamental
+problems: First, there is a lag time between when a processor is introduced
+to when compilers generate quality code for the architecture. Secondly,
+even when compilers catch up to the new architecture there is often a large
+body of legacy code that was compiled for previous generations and will
+not or can not be upgraded. Thus a large percentage of code running on a
+processor may be compiled quite sub-optimally for the current
+characteristics of the dynamic execution environment.
+
+For these reasons, LLVM has been designed from the beginning as a long-term
+solution to these problems. Its design allows the large body of platform
+independent, static, program optimizations currently in compilers to be
+reused unchanged in their current form. It also provides important static
+type information to enable powerful dynamic and link time optimizations
+to be performed quickly and efficiently. This combination enables an
+increase in effective system performance for real world environments.
diff --git a/docs/HistoricalNotes/2001-05-18-ExceptionHandling.txt b/docs/HistoricalNotes/2001-05-18-ExceptionHandling.txt
new file mode 100644
index 00000000000..b546301d35a
--- /dev/null
+++ b/docs/HistoricalNotes/2001-05-18-ExceptionHandling.txt
@@ -0,0 +1,202 @@
+Meeting notes: Implementation idea: Exception Handling in C++/Java
+
+The 5/18/01 meeting discussed ideas for implementing exceptions in LLVM.
+We decided that the best solution requires a set of library calls provided by
+the VM, as well as an extension to the LLVM function invocation syntax.
+
+The LLVM function invocation instruction previously looks like this (ignoring
+types):
+
+ call func(arg1, arg2, arg3)
+
+The extension discussed today adds an optional "with" clause that
+associates a label with the call site. The new syntax looks like this:
+
+ call func(arg1, arg2, arg3) with funcCleanup
+
+This funcHandler always stays tightly associated with the call site (being
+encoded directly into the call opcode itself), and should be used whenever
+there is cleanup work that needs to be done for the current function if
+an exception is thrown by func (or if we are in a try block).
+
+To support this, the VM/Runtime provide the following simple library
+functions (all syntax in this document is very abstract):
+
+typedef struct { something } %frame;
+ The VM must export a "frame type", that is an opaque structure used to
+ implement different types of stack walking that may be used by various
+ language runtime libraries. We imagine that it would be typical to
+ represent a frame with a PC and frame pointer pair, although that is not
+ required.
+
+%frame getStackCurrentFrame();
+ Get a frame object for the current function. Note that if the current
+ function was inlined into its caller, the "current" frame will belong to
+ the "caller".
+
+bool isFirstFrame(%frame f);
+ Returns true if the specified frame is the top level (first activated) frame
+ for this thread. For the main thread, this corresponds to the main()
+ function, for a spawned thread, it corresponds to the thread function.
+
+%frame getNextFrame(%frame f);
+ Return the previous frame on the stack. This function is undefined if f
+ satisfies the predicate isFirstFrame(f).
+
+Label *getFrameLabel(%frame f);
+ If a label was associated with f (as discussed below), this function returns
+ it. Otherwise, it returns a null pointer.
+
+doNonLocalBranch(Label *L);
+ At this point, it is not clear whether this should be a function or
+ intrinsic. It should probably be an intrinsic in LLVM, but we'll deal with
+ this issue later.
+
+
+Here is a motivating example that illustrates how these facilities could be
+used to implement the C++ exception model:
+
+void TestFunction(...) {
+ A a; B b;
+ foo(); // Any function call may throw
+ bar();
+ C c;
+
+ try {
+ D d;
+ baz();
+ } catch (int) {
+ ...int Stuff...
+ // execution continues after the try block: the exception is consumed
+ } catch (double) {
+ ...double stuff...
+ throw; // Exception is propogated
+ }
+}
+
+This function would compile to approximately the following code (heavy
+pseudo code follows):
+
+Func:
+ %a = alloca A
+ A::A(%a) // These ctors & dtors could throw, but we ignore this
+ %b = alloca B // minor detail for this example
+ B::B(%b)
+
+ call foo() with fooCleanup // An exception in foo is propogated to fooCleanup
+ call bar() with barCleanup // An exception in bar is propogated to barCleanup
+
+ %c = alloca C
+ C::C(c)
+ %d = alloca D
+ D::D(d)
+ call baz() with bazCleanup // An exception in baz is propogated to bazCleanup
+ d->~D();
+EndTry: // This label corresponds to the end of the try block
+ c->~C() // These could also throw, these are also ignored
+ b->~B()
+ a->~A()
+ return
+
+Note that this is a very straight forward and literal translation: exactly
+what we want for zero cost (when unused) exception handling. Especially on
+platforms with many registers (ie, the IA64) setjmp/longjmp style exception
+handling is *very* impractical. Also, the "with" clauses describe the
+control flow paths explicitly so that analysis is not adversly effected.
+
+The foo/barCleanup labels are implemented as:
+
+TryCleanup: // Executed if an exception escapes the try block
+ c->~C()
+barCleanup: // Executed if an exception escapes from bar()
+ // fall through
+fooCleanup: // Executed if an exception escapes from foo()
+ b->~B()
+ a->~A()
+ Exception *E = getThreadLocalException()
+ call throw(E) // Implemented by the C++ runtime, described below
+
+Which does the work one would expect. getThreadLocalException is a function
+implemented by the C++ support library. It returns the current exception
+object for the current thread. Note that we do not attempt to recycle the
+shutdown code from before, because performance of the mainline code is
+critically important. Also, obviously fooCleanup and barCleanup may be
+merged and one of them eliminated. This just shows how the code generator
+would most likely emit code.
+
+The bazCleanup label is more interesting. Because the exception may be caught
+by the try block, we must dispatch to its handler... but it does not exist
+on the call stack (it does not have a VM Call->Label mapping installed), so
+we must dispatch statically with a goto. The bazHandler thus appears as:
+
+bazHandler:
+ d->~D(); // destruct D as it goes out of scope when entering catch clauses
+ goto TryHandler
+
+In general, TryHandler is not the same as bazHandler, because multiple
+function calls could be made from the try block. In this case, trivial
+optimization could merge the two basic blocks. TryHandler is the code
+that actually determines the type of exception, based on the Exception object
+itself. For this discussion, assume that the exception object contains *at
+least*:
+
+1. A pointer to the RTTI info for the contained object
+2. A pointer to the dtor for the contained object
+3. The contained object itself
+
+Note that it is necessary to maintain #1 & #2 in the exception object itself
+because objects without virtual function tables may be thrown (as in this
+example). Assuming this, TryHandler would look something like this:
+
+TryHandler:
+ Exception *E = getThreadLocalException();
+ switch (E->RTTIType) {
+ case IntRTTIInfo:
+ ...int Stuff... // The action to perform from the catch block
+ break;
+ case DoubleRTTIInfo:
+ ...double Stuff... // The action to perform from the catch block
+ goto TryCleanup // This catch block rethrows the exception
+ break; // Redundant, eliminated by the optimizer
+ default:
+ goto TryCleanup // Exception not caught, rethrow
+ }
+
+ // Exception was consumed
+ if (E->dtor)
+ E->dtor(E->object) // Invoke the dtor on the object if it exists
+ goto EndTry // Continue mainline code...
+
+And that is all there is to it.
+
+The throw(E) function would then be implemented like this (which may be
+inlined into the caller through standard optimization):
+
+function throw(Exception *E) {
+ // Get the start of the stack trace...
+ %frame %f = call getStackCurrentFrame()
+
+ // Get the label information that corresponds to it
+ label * %L = call getFrameLabel(%f)
+ while (%L == 0 && !isFirstFrame(%f)) {
+ // Loop until a cleanup handler is found
+ %f = call getNextFrame(%f)
+ %L = call getFrameLabel(%f)
+ }
+
+ if (%L != 0) {
+ call setThreadLocalException(E) // Allow handlers access to this...
+ call doNonLocalBranch(%L)
+ }
+ // No handler found!
+ call BlowUp() // Ends up calling the terminate() method in use
+}
+
+That's a brief rundown of how C++ exception handling could be implemented in
+llvm. Java would be very similar, except it only uses destructors to unlock
+synchronized blocks, not to destroy data. Also, it uses two stack walks: a
+nondestructive walk that builds a stack trace, then a destructive walk that
+unwinds the stack as shown here.
+
+It would be trivial to get exception interoperability between C++ and Java.
+
diff --git a/docs/HistoricalNotes/2001-05-19-ExceptionResponse.txt b/docs/HistoricalNotes/2001-05-19-ExceptionResponse.txt
new file mode 100644
index 00000000000..3375365f54c
--- /dev/null
+++ b/docs/HistoricalNotes/2001-05-19-ExceptionResponse.txt
@@ -0,0 +1,45 @@
+Date: Sat, 19 May 2001 19:09:13 -0500 (CDT)
+From: Chris Lattner <sabre@nondot.org>
+To: Vikram S. Adve <vadve@cs.uiuc.edu>
+Subject: RE: Meeting writeup
+
+> I read it through and it looks great!
+
+Thanks!
+
+> The finally clause in Java may need more thought. The code for this clause
+> is like a subroutine because it needs to be entered from many points (end of
+> try block and beginning of each catch block), and then needs to *return to
+> the place from where the code was entered*. That's why JVM has the
+> jsr/jsr_w instruction.
+
+Hrm... I guess that is an implementation decision. It can either be
+modelled as a subroutine (as java bytecodes do), which is really
+gross... or it can be modelled as code duplication (emitted once inline,
+then once in the exception path). Because this could, at worst,
+slightly less than double the amount of code in a function (it is
+bounded) I don't think this is a big deal. One of the really nice things
+about the LLVM representation is that it still allows for runtime code
+generation for exception paths (exceptions paths are not compiled until
+needed). Obviously a static compiler couldn't do this though. :)
+
+In this case, only one copy of the code would be compiled... until the
+other one is needed on demand. Also this strategy fits with the "zero
+cost" exception model... the standard case is not burdened with extra
+branches or "call"s.
+
+> I suppose you could save the return address in a particular register
+> (specific to this finally block), jump to the finally block, and then at the
+> end of the finally block, jump back indirectly through this register. It
+> will complicate building the CFG but I suppose that can be handled. It is
+> also unsafe in terms of checking where control returns (which is I suppose
+> why the JVM doesn't use this).
+
+I think that a code duplication method would be cleaner, and would avoid
+the caveats that you mention. Also, it does not slow down the normal case
+with an indirect branch...
+
+Like everything, we can probably defer a final decision until later. :)
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2001-06-01-GCCOptimizations.txt b/docs/HistoricalNotes/2001-06-01-GCCOptimizations.txt
new file mode 100644
index 00000000000..97af16a2dad
--- /dev/null
+++ b/docs/HistoricalNotes/2001-06-01-GCCOptimizations.txt
@@ -0,0 +1,63 @@
+Date: Fri, 1 Jun 2001 16:38:17 -0500 (CDT)
+From: Chris Lattner <sabre@nondot.org>
+To: Vikram S. Adve <vadve@cs.uiuc.edu>
+Subject: Interesting: GCC passes
+
+
+Take a look at this document (which describes the order of optimizations
+that GCC performs):
+
+http://gcc.gnu.org/onlinedocs/gcc_17.html
+
+The rundown is that after RTL generation, the following happens:
+
+1 . [t] jump optimization (jumps to jumps, etc)
+2 . [t] Delete unreachable code
+3 . Compute live ranges for CSE
+4 . [t] Jump threading (jumps to jumps with identical or inverse conditions)
+5 . [t] CSE
+6 . *** Conversion to SSA
+7 . [t] SSA Based DCE
+8 . *** Conversion to LLVM
+9 . UnSSA
+10. GCSE
+11. LICM
+12. Strength Reduction
+13. Loop unrolling
+14. [t] CSE
+15. [t] DCE
+16. Instruction combination, register movement, scheduling... etc.
+
+I've marked optimizations with a [t] to indicate things that I believe to
+be relatively trivial to implement in LLVM itself. The time consuming
+things to reimplement would be SSA based PRE, Strength reduction & loop
+unrolling... these would be the major things we would miss out on if we
+did LLVM creation from tree code [inlining and other high level
+optimizations are done on the tree representation].
+
+Given the lack of "strong" optimizations that would take a long time to
+reimplement, I am leaning a bit more towards creating LLVM from the tree
+code. Especially given that SGI has GPL'd their compiler, including many
+SSA based optimizations that could be adapted (besides the fact that their
+code looks MUCH nicer than GCC :)
+
+Even if we choose to do LLVM code emission from RTL, we will almost
+certainly want to move LLVM emission from step 8 down until at least CSE
+has been rerun... which causes me to wonder if the SSA generation code
+will still work (due to global variable dependencies and stuff). I assume
+that it can be made to work, but might be a little more involved than we
+would like.
+
+I'm continuing to look at the Tree -> RTL code. It is pretty gross
+because they do some of the translation a statement at a time, and some
+of it a function at a time... I'm not quite clear why and how the
+distinction is drawn, but it does not appear that there is a wonderful
+place to attach extra info.
+
+Anyways, I'm proceeding with the RTL -> LLVM conversion phase for now. We
+can talk about this more on Monday.
+
+Wouldn't it be nice if there were a obvious decision to be made? :)
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2001-06-01-GCCOptimizations2.txt b/docs/HistoricalNotes/2001-06-01-GCCOptimizations2.txt
new file mode 100644
index 00000000000..e61042fd657
--- /dev/null
+++ b/docs/HistoricalNotes/2001-06-01-GCCOptimizations2.txt
@@ -0,0 +1,71 @@
+Date: Fri, 1 Jun 2001 17:08:44 -0500 (CDT)
+From: Chris Lattner <sabre@nondot.org>
+To: Vikram S. Adve <vadve@cs.uiuc.edu>
+Subject: RE: Interesting: GCC passes
+
+> That is very interesting. I agree that some of these could be done on LLVM
+> at link-time, but it is the extra time required that concerns me. Link-time
+> optimization is severely time-constrained.
+
+If we were to reimplement any of these optimizations, I assume that we
+could do them a translation unit at a time, just as GCC does now. This
+would lead to a pipeline like this:
+
+Static optimizations, xlation unit at a time:
+.c --GCC--> .llvm --llvmopt--> .llvm
+
+Link time optimizations:
+.llvm --llvm-ld--> .llvm --llvm-link-opt--> .llvm
+
+Of course, many optimizations could be shared between llvmopt and
+llvm-link-opt, but the wouldn't need to be shared... Thus compile time
+could be faster, because we are using a "smarter" IR (SSA based).
+
+> BTW, about SGI, "borrowing" SSA-based optimizations from one compiler and
+> putting it into another is not necessarily easier than re-doing it.
+> Optimization code is usually heavily tied in to the specific IR they use.
+
+Understood. The only reason that I brought this up is because SGI's IR is
+more similar to LLVM than it is different in many respects (SSA based,
+relatively low level, etc), and could be easily adapted. Also their
+optimizations are written in C++ and are actually somewhat
+structured... of course it would be no walk in the park, but it would be
+much less time consuming to adapt, say, SSA-PRE than to rewrite it.
+
+> But your larger point is valid that adding SSA based optimizations is
+> feasible and should be fun. (Again, link time cost is the issue.)
+
+Assuming linktime cost wasn't an issue, the question is:
+Does using GCC's backend buy us anything?
+
+> It also occurs to me that GCC is probably doing quite a bit of back-end
+> optimization (step 16 in your list). Do you have a breakdown of that?
+
+Not really. The irritating part of GCC is that it mixes it all up and
+doesn't have a clean separation of concerns. A lot of the "back end
+optimization" happens right along with other data optimizations (ie, CSE
+of machine specific things).
+
+As far as REAL back end optimizations go, it looks something like this:
+
+1. Instruction combination: try to make CISCy instructions, if available
+2. Register movement: try to get registers in the right places for the
+architecture to avoid register to register moves. For example, try to get
+the first argument of a function to naturally land in %o0 for sparc.
+3. Instruction scheduling: 'nuff said :)
+4. Register class preferencing: ??
+5. Local register allocation
+6. global register allocation
+7. Spilling
+8. Local regalloc
+9. Jump optimization
+10. Delay slot scheduling
+11. Branch shorting for CISC machines
+12. Instruction selection & peephole optimization
+13. Debug info output
+
+But none of this would be usable for LLVM anyways, unless we were using
+GCC as a static compiler.
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2001-06-20-.NET-Differences.txt b/docs/HistoricalNotes/2001-06-20-.NET-Differences.txt
new file mode 100644
index 00000000000..1bc2eae746c
--- /dev/null
+++ b/docs/HistoricalNotes/2001-06-20-.NET-Differences.txt
@@ -0,0 +1,30 @@
+Date: Wed, 20 Jun 2001 12:32:22 -0500
+From: Vikram Adve <vadve@cs.uiuc.edu>
+To: Chris Lattner <lattner@cs.uiuc.edu>
+Subject: .NET vs. our VM
+
+One significant difference between .NET CLR and our VM is that the CLR
+includes full information about classes and inheritance. In fact, I just
+sat through the paper on adding templates to .NET CLR, and the speaker
+indicated that the goal seems to be to do simple static compilation (very
+little lowering or optimization). Also, the templates implementation in CLR
+"relies on dynamic class loading and JIT compilation".
+
+This is an important difference because I think there are some significant
+advantages to have a much lower level VM layer, and do significant static
+analysis and optimization.
+
+I also talked to the lead guy for KAI's C++ compiler (Arch Robison) and he
+said that SGI and other commercial compilers have included options to export
+their *IR* next to the object code (i.e., .il files) and use them for
+link-time code generation. In fact, he said that the .o file was nearly
+empty and was entirely generated from the .il at link-time. But he agreed
+that this limited the link-time interprocedural optimization to modules
+compiled by the same compiler, whereas our approach allows us to link and
+optimize modules from multiple different compilers. (Also, of course, they
+don't do anything for runtime optimization).
+
+All issues to bring up in Related Work.
+
+--Vikram
+
diff --git a/docs/HistoricalNotes/2001-07-06-LoweringIRForCodeGen.txt b/docs/HistoricalNotes/2001-07-06-LoweringIRForCodeGen.txt
new file mode 100644
index 00000000000..3e10416fe67
--- /dev/null
+++ b/docs/HistoricalNotes/2001-07-06-LoweringIRForCodeGen.txt
@@ -0,0 +1,31 @@
+Date: Fri, 6 Jul 2001 16:56:56 -0500
+From: Vikram S. Adve <vadve@cs.uiuc.edu>
+To: Chris Lattner <lattner@cs.uiuc.edu>
+Subject: lowering the IR
+
+BTW, I do think that we should consider lowering the IR as you said. I
+didn't get time to raise it today, but it comes up with the SPARC
+move-conditional instruction. I don't think we want to put that in the core
+VM -- it is a little too specialized. But without a corresponding
+conditional move instruction in the VM, it is pretty difficult to maintain a
+close mapping between VM and machine code. Other architectures may have
+other such instructions.
+
+What I was going to suggest was that for a particular processor, we define
+additional VM instructions that match some of the unusual opcodes on the
+processor but have VM semantics otherwise, i.e., all operands are in SSA
+form and typed. This means that we can re-generate core VM code from the
+more specialized code any time we want (so that portability is not lost).
+
+Typically, a static compiler like gcc would generate just the core VM, which
+is relatively portable. Anyone (an offline tool, the linker, etc., or even
+the static compiler itself if it chooses) can transform that into more
+specialized target-specific VM code for a particular architecture. If the
+linker does it, it can do it after all machine-independent optimizations.
+This would be the most convenient, but not necessary.
+
+The main benefit of lowering will be that we will be able to retain a close
+mapping between VM and machine code.
+
+--Vikram
+
diff --git a/docs/HistoricalNotes/2001-09-18-OptimizeExceptions.txt b/docs/HistoricalNotes/2001-09-18-OptimizeExceptions.txt
new file mode 100644
index 00000000000..9379081018d
--- /dev/null
+++ b/docs/HistoricalNotes/2001-09-18-OptimizeExceptions.txt
@@ -0,0 +1,56 @@
+Date: Tue, 18 Sep 2001 00:38:37 -0500 (CDT)
+From: Chris Lattner <sabre@nondot.org>
+To: Vikram S. Adve <vadve@cs.uiuc.edu>
+Subject: Idea for a simple, useful link time optimization
+
+
+In C++ programs, exceptions suck, and here's why:
+
+1. In virtually all function calls, you must assume that the function
+ throws an exception, unless it is defined as 'nothrow'. This means
+ that every function call has to have code to invoke dtors on objects
+ locally if one is thrown by the function. Most functions don't throw
+ exceptions, so this code is dead [with all the bad effects of dead
+ code, including icache pollution].
+2. Declaring a function nothrow causes catch blocks to be added to every
+ call that isnot provably nothrow. This makes them very slow.
+3. Extra extraneous exception edges reduce the opportunity for code
+ motion.
+4. EH is typically implemented with large lookup tables. Ours is going to
+ be much smaller (than the "standard" way of doing it) to start with,
+ but eliminating it entirely would be nice. :)
+5. It is physically impossible to correctly put (accurate, correct)
+ exception specifications on generic, templated code. But it is trivial
+ to analyze instantiations of said code.
+6. Most large C++ programs throw few exceptions. Most well designed
+ programs only throw exceptions in specific planned portions of the
+ code.
+
+Given our _planned_ model of handling exceptions, all of this would be
+pretty trivial to eliminate through some pretty simplistic interprocedural
+analysis. The DCE factor alone could probably be pretty significant. The
+extra code motion opportunities could also be exploited though...
+
+Additionally, this optimization can be implemented in a straight forward
+conservative manner, allowing libraries to be optimized or individual
+files even (if there are leaf functions visible in the translation unit
+that are called).
+
+I think it's a reasonable optimization that hasn't really been addressed
+(because assembly is way too low level for this), and could have decent
+payoffs... without being a overly complex optimization.
+
+After I wrote all of that, I found this page that is talking about
+basically the same thing I just wrote, except that it is translation unit
+at a time, tree based approach:
+http://www.ocston.org/~jls/ehopt.html
+
+but is very useful from "expected gain" and references perspective. Note
+that their compiler is apparently unable to inline functions that use
+exceptions, so there numbers are pretty worthless... also our results
+would (hopefully) be better because it's interprocedural...
+
+What do you think?
+
+-Chris
+
diff --git a/docs/HistoricalNotes/2002-05-12-InstListChange.txt b/docs/HistoricalNotes/2002-05-12-InstListChange.txt
new file mode 100644
index 00000000000..638682b49fd
--- /dev/null
+++ b/docs/HistoricalNotes/2002-05-12-InstListChange.txt
@@ -0,0 +1,55 @@
+Date: Sun, 12 May 2002 17:12:53 -0500 (CDT)
+From: Chris Lattner <sabre@nondot.org>
+To: "Vikram S. Adve" <vadve@cs.uiuc.edu>
+Subject: LLVM change
+
+There is a fairly fundemental change that I would like to make to the LLVM
+infrastructure, but I'd like to know if you see any drawbacks that I
+don't...
+
+Basically right now at the basic block level, each basic block contains an
+instruction list (returned by getInstList()) that is a ValueHolder of
+instructions. To iterate over instructions, we must actually iterate over
+the instlist, and access the instructions through the instlist.
+
+To add or remove an instruction from a basic block, we need to get an
+iterator to an instruction, which, given just an Instruction*, requires a
+linear search of the basic block the instruction is contained in... just
+to insert an instruction before another instruction, or to delete an
+instruction! This complicates algorithms that should be very simple (like
+simple constant propagation), because they aren't actually sparse anymore,
+they have to traverse basic blocks to remove constant propogated
+instructions.
+
+Additionally, adding or removing instructions to a basic block
+_invalidates all iterators_ pointing into that block, which is really
+irritating.
+
+To fix these problems (and others), I would like to make the ordering of
+the instructions be represented with a doubly linked list in the
+instructions themselves, instead of an external data structure. This is
+how many other representations do it, and frankly I can't remember why I
+originally implemented it the way I did.
+
+Long term, all of the code that depends on the nasty features in the
+instruction list (which can be found by grep'ing for getInstList()) will
+be changed to do nice local transformations. In the short term, I'll
+change the representation, but preserve the interface (including
+getInstList()) so that all of the code doesn't have to change.
+
+Iteration over the instructions in a basic block remains the simple:
+for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) ...
+
+But we will also support:
+for (Instruction *I = BB->front(); I; I = I->getNext()) ...
+
+After converting instructions over, I'll convert basic blocks and
+functions to have a similar interface.
+
+The only negative aspect of this change that I see is that it increases
+the amount of memory consumed by one pointer per instruction. Given the
+benefits, I think this is a very reasonable tradeoff.
+
+What do you think?
+
+-Chris
diff --git a/docs/HistoricalNotes/2002-06-25-MegaPatchInfo.txt b/docs/HistoricalNotes/2002-06-25-MegaPatchInfo.txt
new file mode 100644
index 00000000000..2ca46117ca8
--- /dev/null
+++ b/docs/HistoricalNotes/2002-06-25-MegaPatchInfo.txt
@@ -0,0 +1,72 @@
+Changes:
+* Change the casting code to be const correct. Now, doing this is invalid:
+ const Value *V = ...;
+ Instruction *I = dyn_cast<Instruction>(V);
+ instead, the second line should be:
+ const Instruction *I = dyn_cast<Instruction>(V);
+
+* Change the casting code to allow casting a reference value thus:
+ const Value &V = ...;
+ Instruction &I = cast<Instruction>(V);
+
+ dyn_cast does not work with references, because it must return a null pointer
+ on failure.
+
+* Fundamentally change how instructions and other values are represented.
+ Before, every llvm container was an instance of the ValueHolder template,
+ instantiated for each container type. This ValueHolder was effectively a
+ wrapper around a vector of pointers to the sub-objects.
+
+ Now, instead of having a vector to pointers of objects, the objects are
+ maintained in a doubly linked list of values (ie each Instruction now has
+ Next & Previous fields). The containers are now instances of ilist (intrusive
+ linked list class), which use the next and previous fields to chain them
+ together. The advantage of this implementation is that iterators can be
+ formed directly from pointers to the LLVM value, and invalidation is much
+ easier to handle.
+
+* As part of the above change, dereferencing an iterator (for example:
+ BasicBlock::iterator) now produces a reference to the underlying type (same
+ example: Instruction&) instead of a pointer to the underlying object. This
+ makes it much easier to write nested loops that iterator over things, changing
+ this:
+
+ for (Function::iterator BI = Func->begin(); BI != Func->end(); ++BI)
+ for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
+ (*II)->dump();
+
+ into:
+
+ for (Function::iterator BI = Func->begin(); BI != Func->end(); ++BI)
+ for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II)
+ II->dump();
+
+ which is much more natural and what users expect.
+
+* Simplification of #include's: Before, it was necessary for a .cpp file to
+ include every .h file that it used. Now things are batched a little bit more
+ to make it easier to use. Specifically, the include graph now includes these
+ edges:
+ Module.h -> Function.h, GlobalVariable.h
+ Function.h -> BasicBlock.h, Argument.h
+ BasicBlock.h -> Instruction.h
+
+ Which means that #including Function.h is usually sufficient for getting the
+ lower level #includes.
+
+* Printing out a Value* has now changed: Printing a Value* will soon print out
+ the address of the value instead of the contents of the Value. To print out
+ the contents, you must convert it to a reference with (for example)
+ 'cout << *I' instead of 'cout << I;'. This conversion is not yet complete,
+ but will be eventually. In the mean time, both forms print out the contents.
+
+* References are used much more throughout the code base. In general, if a
+ pointer is known to never be null, it is passed in as a reference instead of a
+ pointer. For example, the instruction visitor class uses references instead
+ of pointers, and that Pass subclasses now all receive references to Values
+ instead of pointers, because they may never be null.
+
+* The Function class now has helper functions for accessing the Arguments list.
+ Instead of having to go through getArgumentList for simple things like
+ iterator over the arguments, now the a*() methods can be used to access them.
+
diff --git a/docs/HistoricalNotes/2003-01-23-CygwinNotes.txt b/docs/HistoricalNotes/2003-01-23-CygwinNotes.txt
new file mode 100644
index 00000000000..fbe811d627f
--- /dev/null
+++ b/docs/HistoricalNotes/2003-01-23-CygwinNotes.txt
@@ -0,0 +1,28 @@
+Date: Mon, 20 Jan 2003 00:00:28 -0600
+From: Brian R. Gaeke <gaeke@uiuc.edu>
+Subject: windows vs. llvm
+
+If you're interested, here are some of the major problems compiling LLVM
+under Cygwin and/or Mingw.
+
+1. Cygwin doesn't have <inttypes.h> or <stdint.h>, so all the INT*_MAX
+ symbols and standard int*_t types are off in limbo somewhere. Mingw has
+ <stdint.h>, but Cygwin doesn't like it.
+
+2. Mingw doesn't have <dlfcn.h> (because Windows doesn't have it.)
+
+3. SA_SIGINFO and friends are not around; only signal() seems to work.
+
+4. Relink, aka ld -r, doesn't work (probably an ld bug); you need
+ DONT_BUILD_RELINKED. This breaks all the tools makefiles; you just need to
+ change them to have .a's.
+
+5. There isn't a <values.h>.
+
+6. There isn't a mallinfo() (or, at least, it's documented, but it doesn't seem
+ to link).
+
+7. The version of Bison that cygwin (and newer Linux versions) comes with
+ does not like = signs in rules. Burg's gram.yc source file uses them. I think
+ you can just take them out.
+
diff --git a/docs/HistoricalNotes/2003-06-25-Reoptimizer1.txt b/docs/HistoricalNotes/2003-06-25-Reoptimizer1.txt
new file mode 100644
index 00000000000..a7457846395
--- /dev/null
+++ b/docs/HistoricalNotes/2003-06-25-Reoptimizer1.txt
@@ -0,0 +1,137 @@
+Wed Jun 25 15:13:51 CDT 2003
+
+First-level instrumentation
+---------------------------
+
+We use opt to do Bytecode-to-bytecode instrumentation. Look at
+back-edges and insert llvm_first_trigger() function call which takes
+no arguments and no return value. This instrumentation is designed to
+be easy to remove, for instance by writing a NOP over the function
+call instruction.
+
+Keep count of every call to llvm_first_trigger(), and maintain
+counters in a map indexed by return address. If the trigger count
+exceeds a threshold, we identify a hot loop and perform second-level
+instrumentation on the hot loop region (the instructions between the
+target of the back-edge and the branch that causes the back-edge). We
+do not move code across basic-block boundaries.
+
+
+Second-level instrumentation
+---------------------------
+
+We remove the first-level instrumentation by overwriting the CALL to
+llvm_first_trigger() with a NOP.
+
+The reoptimizer maintains a map between machine-code basic blocks and
+LLVM BasicBlock*s. We only keep track of paths that start at the
+first machine-code basic block of the hot loop region.
+
+How do we keep track of which edges to instrument, and which edges are
+exits from the hot region? 3 step process.
+
+1) Do a DFS from the first machine-code basic block of the hot loop
+region and mark reachable edges.
+
+2) Do a DFS from the last machine-code basic block of the hot loop
+region IGNORING back edges, and mark the edges which are reachable in
+1) and also in 2) (i.e., must be reachable from both the start BB and
+the end BB of the hot region).
+
+3) Mark BBs which end in edges that exit the hot region; we need to
+instrument these differently.
+
+Assume that there is 1 free register. On SPARC we use %g1, which LLC
+has agreed not to use. Shift a 1 into it at the beginning. At every
+edge which corresponds to a conditional branch, we shift 0 for not
+taken and 1 for taken into a register. This uniquely numbers the paths
+through the hot region. Silently fail if we need more than 64 bits.
+
+At the end BB we call countPath and increment the counter based on %g1
+and the return address of the countPath call. We keep track of the
+number of iterations and the number of paths. We only run this
+version 30 or 40 times.
+
+Find the BBs that total 90% or more of execution, and aggregate them
+together to form our trace. But we do not allow more than 5 paths; if
+we have more than 5 we take the ones that are executed the most. We
+verify our assumption that we picked a hot back-edge in first-level
+instrumentation, by making sure that the number of times we took an
+exit edge from the hot trace is less than 10% of the number of
+iterations.
+
+LLC has been taught to recognize llvm_first_trigger() calls and NOT
+generate saves and restores of caller-saved registers around these
+calls.
+
+
+Phase behavior
+--------------
+
+We turn off llvm_first_trigger() calls with NOPs, but this would hide
+phase behavior from us (when some funcs/traces stop being hot and
+others become hot.)
+
+We have a SIGALRM timer that counts time for us. Every time we get a
+SIGALRM we look at our priority queue of locations where we have
+removed llvm_first_trigger() calls. Each location is inserted along
+with a time when we will next turn instrumentation back on for that
+call site. If the time has arrived for a particular call site, we pop
+that off the prio. queue and turn instrumentation back on for that
+call site.
+
+
+Generating traces
+-----------------
+
+When we finally generate an optimized trace we first copy the code
+into the trace cache. This leaves us with 3 copies of the code: the
+original code, the instrumented code, and the optimized trace. The
+optimized trace does not have instrumentation. The original code and
+the instrumented code are modified to have a branch to the trace
+cache, where the optimized traces are kept.
+
+We copy the code from the original to the instrumentation version
+by tracing the LLVM-to-Machine code basic block map and then copying
+each machine code basic block we think is in the hot region into the
+trace cache. Then we instrument that code. The process is similar for
+generating the final optimized trace; we copy the same basic blocks
+because we might need to put in fixup code for exit BBs.
+
+LLVM basic blocks are not typically used in the Reoptimizer except
+for the mapping information.
+
+We are restricted to using single instructions to branch between the
+original code, trace, and instrumented code. So we have to keep the
+code copies in memory near the original code (they can't be far enough
+away that a single pc-relative branch would not work.) Malloc() or
+data region space is too far away. this impacts the design of the
+trace cache.
+
+We use a dummy function that is full of a bunch of for loops which we
+overwrite with trace-cache code. The trace manager keeps track of
+whether or not we have enough space in the trace cache, etc.
+
+The trace insertion routine takes an original start address, a vector
+of machine instructions representing the trace, index of branches and
+their corresponding absolute targets, and index of calls and their
+corresponding absolute targets.
+
+The trace insertion routine is responsible for inserting branches from
+the beginning of the original code to the beginning of the optimized
+trace. This is because at some point the trace cache may run out of
+space and it may have to evict a trace, at which point the branch to
+the trace would also have to be removed. It uses a round-robin
+replacement policy; we have found that this is almost as good as LRU
+and better than random (especially because of problems fitting the new
+trace in.)
+
+We cannot deal with discontiguous trace cache areas. The trace cache
+is supposed to be cache-line-aligned, but it is not page-aligned.
+
+We generate instrumentation traces and optimized traces into separate
+trace caches. We keep the instrumented code around because you don't
+want to delete a trace when you still might have to return to it
+(i.e., return from a llvm_first_trigger() or countPath() call.)
+
+
diff --git a/docs/HistoricalNotes/2003-06-26-Reoptimizer2.txt b/docs/HistoricalNotes/2003-06-26-Reoptimizer2.txt
new file mode 100644
index 00000000000..ec4b93fea0a
--- /dev/null
+++ b/docs/HistoricalNotes/2003-06-26-Reoptimizer2.txt
@@ -0,0 +1,110 @@
+Thu Jun 26 14:43:04 CDT 2003
+
+Information about BinInterface
+------------------------------
+
+Take in a set of instructions with some particular register
+allocation. It allows you to add, modify, or delete some instructions,
+in SSA form (kind of like LLVM's MachineInstrs.) Then re-allocate
+registers. It assumes that the transformations you are doing are safe.
+It does not update the mapping information or the LLVM representation
+for the modified trace (so it would not, for instance, support
+multiple optimization passes; passes have to be aware of and update
+manually the mapping information.)
+
+The way you use it is you take the original code and provide it to
+BinInterface; then you do optimizations to it, then you put it in the
+trace cache.
+
+The BinInterface tries to find live-outs for traces so that it can do
+register allocation on just the trace, and stitch the trace back into
+the original code. It has to preserve the live-ins and live-outs when
+it does its register allocation. (On exits from the trace we have
+epilogues that copy live-outs back into the right registers, but
+live-ins have to be in the right registers.)
+
+
+Limitations of BinInterface
+---------------------------
+
+It does copy insertions for PHIs, which it infers from the machine
+code. The mapping info inserted by LLC is not sufficient to determine
+the PHIs.
+
+It does not handle integer or floating-point condition codes and it
+does not handle floating-point register allocation.
+
+It is not aggressively able to use lots of registers.
+
+There is a problem with alloca: we cannot find our spill space for
+spilling registers, normally allocated on the stack, if the trace
+follows an alloca(). What might be an acceptable solution would be to
+disable trace generation on functions that have variable-sized
+alloca()s. Variable-sized allocas in the trace would also probably
+screw things up.
+
+Because of the FP and alloca limitations, the BinInterface is
+completely disabled right now.
+
+
+Demo
+----
+
+This is a demo of the Ball & Larus version that does NOT use 2-level
+profiling.
+
+1. Compile program with llvm-gcc.
+2. Run opt -lowerswitch -paths -emitfuncs on the bytecode.
+ -lowerswitch change switch statements to branches
+ -paths Ball & Larus path-profiling algorithm
+ -emitfuncs emit the table of functions
+3. Run llc to generate SPARC assembly code for the result of step 2.
+4. Use g++ to link the (instrumented) assembly code.
+
+We use a script to do all this:
+------------------------------------------------------------------------------
+#!/bin/sh
+llvm-gcc $1.c -o $1
+opt -lowerswitch -paths -emitfuncs $1.bc > $1.run.bc
+llc -f $1.run.bc
+LIBS=$HOME/llvm_sparc/lib/Debug
+GXX=/usr/dcs/software/evaluation/bin/g++
+$GXX -g -L $LIBS $1.run.s -o $1.run.llc \
+$LIBS/tracecache.o \
+$LIBS/mapinfo.o \
+$LIBS/trigger.o \
+$LIBS/profpaths.o \
+$LIBS/bininterface.o \
+$LIBS/support.o \
+$LIBS/vmcore.o \
+$LIBS/transformutils.o \
+$LIBS/bcreader.o \
+-lscalaropts -lscalaropts -lanalysis \
+-lmalloc -lcpc -lm -ldl
+------------------------------------------------------------------------------
+
+5. Run the resulting binary. You will see output from BinInterface
+(described below) intermixed with the output from the program.
+
+
+Output from BinInterface
+------------------------
+
+BinInterface's debugging code prints out the following stuff in order:
+
+1. Initial code provided to BinInterface with original register
+allocation.
+
+2. Section 0 is the trace prolog, consisting mainly of live-ins and
+register saves which will be restored in epilogs.
+
+3. Section 1 is the trace itself, in SSA form used by BinInterface,
+along with the PHIs that are inserted.
+PHIs are followed by the copies that implement them.
+Each branch (i.e., out of the trace) is annotated with the
+section number that represents the epilog it branches to.
+
+4. All the other sections starting with Section 2 are trace epilogs.
+Every branch from the trace has to go to some epilog.
+
+5. After the last section is the register allocation output.
diff --git a/docs/HistoricalNotes/2007-OriginalClangReadme.txt b/docs/HistoricalNotes/2007-OriginalClangReadme.txt
new file mode 100644
index 00000000000..611dc9d2c01
--- /dev/null
+++ b/docs/HistoricalNotes/2007-OriginalClangReadme.txt
@@ -0,0 +1,178 @@
+//===----------------------------------------------------------------------===//
+// C Language Family Front-end
+//===----------------------------------------------------------------------===//
+ Chris Lattner
+
+I. Introduction:
+
+ clang: noun
+ 1. A loud, resonant, metallic sound.
+ 2. The strident call of a crane or goose.
+ 3. C-language family front-end toolkit.
+
+ The world needs better compiler tools, tools which are built as libraries. This
+ design point allows reuse of the tools in new and novel ways. However, building
+ the tools as libraries isn't enough: they must have clean APIs, be as
+ decoupled from each other as possible, and be easy to modify/extend. This
+ requires clean layering, decent design, and avoiding tying the libraries to a
+ specific use. Oh yeah, did I mention that we want the resultant libraries to
+ be as fast as possible? :)
+
+ This front-end is built as a component of the LLVM toolkit that can be used
+ with the LLVM backend or independently of it. In this spirit, the API has been
+ carefully designed as the following components:
+
+ libsupport - Basic support library, reused from LLVM.
+
+ libsystem - System abstraction library, reused from LLVM.
+
+ libbasic - Diagnostics, SourceLocations, SourceBuffer abstraction,
+ file system caching for input source files. This depends on
+ libsupport and libsystem.
+
+ libast - Provides classes to represent the C AST, the C type system,
+ builtin functions, and various helpers for analyzing and
+ manipulating the AST (visitors, pretty printers, etc). This
+ library depends on libbasic.
+
+
+ liblex - C/C++/ObjC lexing and preprocessing, identifier hash table,
+ pragma handling, tokens, and macros. This depends on libbasic.
+
+ libparse - C (for now) parsing and local semantic analysis. This library
+ invokes coarse-grained 'Actions' provided by the client to do
+ stuff (e.g. libsema builds ASTs). This depends on liblex.
+
+ libsema - Provides a set of parser actions to build a standardized AST
+ for programs. AST's are 'streamed' out a top-level declaration
+ at a time, allowing clients to use decl-at-a-time processing,
+ build up entire translation units, or even build 'whole
+ program' ASTs depending on how they use the APIs. This depends
+ on libast and libparse.
+
+ librewrite - Fast, scalable rewriting of source code. This operates on
+ the raw syntactic text of source code, allowing a client
+ to insert and delete text in very large source files using
+ the same source location information embedded in ASTs. This
+ is intended to be a low-level API that is useful for
+ higher-level clients and libraries such as code refactoring.
+
+ libanalysis - Source-level dataflow analysis useful for performing analyses
+ such as computing live variables. It also includes a
+ path-sensitive "graph-reachability" engine for writing
+ analyses that reason about different possible paths of
+ execution through source code. This is currently being
+ employed to write a set of checks for finding bugs in software.
+
+ libcodegen - Lower the AST to LLVM IR for optimization & codegen. Depends
+ on libast.
+
+ clang - An example driver, client of the libraries at various levels.
+ This depends on all these libraries, and on LLVM VMCore.
+
+ This front-end has been intentionally built as a DAG of libraries, making it
+ easy to reuse individual parts or replace pieces if desired. For example, to
+ build a preprocessor, you take the Basic and Lexer libraries. If you want an
+ indexer, you take those plus the Parser library and provide some actions for
+ indexing. If you want a refactoring, static analysis, or source-to-source
+ compiler tool, it makes sense to take those plus the AST building and semantic
+ analyzer library. Finally, if you want to use this with the LLVM backend,
+ you'd take these components plus the AST to LLVM lowering code.
+
+ In the future I hope this toolkit will grow to include new and interesting
+ components, including a C++ front-end, ObjC support, and a whole lot of other
+ things.
+
+ Finally, it should be pointed out that the goal here is to build something that
+ is high-quality and industrial-strength: all the obnoxious features of the C
+ family must be correctly supported (trigraphs, preprocessor arcana, K&R-style
+ prototypes, GCC/MS extensions, etc). It cannot be used if it is not 'real'.
+
+
+II. Usage of clang driver:
+
+ * Basic Command-Line Options:
+ - Help: clang --help
+ - Standard GCC options accepted: -E, -I*, -i*, -pedantic, -std=c90, etc.
+ - To make diagnostics more gcc-like: -fno-caret-diagnostics -fno-show-column
+ - Enable metric printing: -stats
+
+ * -fsyntax-only is currently the default mode.
+
+ * -E mode works the same way as GCC.
+
+ * -Eonly mode does all preprocessing, but does not print the output,
+ useful for timing the preprocessor.
+
+ * -fsyntax-only is currently partially implemented, lacking some
+ semantic analysis (some errors and warnings are not produced).
+
+ * -parse-noop parses code without building an AST. This is useful
+ for timing the cost of the parser without including AST building
+ time.
+
+ * -parse-ast builds ASTs, but doesn't print them. This is most
+ useful for timing AST building vs -parse-noop.
+
+ * -parse-ast-print pretty prints most expression and statements nodes.
+
+ * -parse-ast-check checks that diagnostic messages that are expected
+ are reported and that those which are reported are expected.
+
+ * -dump-cfg builds ASTs and then CFGs. CFGs are then pretty-printed.
+
+ * -view-cfg builds ASTs and then CFGs. CFGs are then visualized by
+ invoking Graphviz.
+
+ For more information on getting Graphviz to work with clang/LLVM,
+ see: http://llvm.org/docs/ProgrammersManual.html#ViewGraph
+
+
+III. Current advantages over GCC:
+
+ * Column numbers are fully tracked (no 256 col limit, no GCC-style pruning).
+ * All diagnostics have column numbers, includes 'caret diagnostics', and they
+ highlight regions of interesting code (e.g. the LHS and RHS of a binop).
+ * Full diagnostic customization by client (can format diagnostics however they
+ like, e.g. in an IDE or refactoring tool) through DiagnosticClient interface.
+ * Built as a framework, can be reused by multiple tools.
+ * All languages supported linked into same library (no cc1,cc1obj, ...).
+ * mmap's code in read-only, does not dirty the pages like GCC (mem footprint).
+ * LLVM License, can be linked into non-GPL projects.
+ * Full diagnostic control, per diagnostic. Diagnostics are identified by ID.
+ * Significantly faster than GCC at semantic analysis, parsing, preprocessing
+ and lexing.
+ * Defers exposing platform-specific stuff to as late as possible, tracks use of
+ platform-specific features (e.g. #ifdef PPC) to allow 'portable bytecodes'.
+ * The lexer doesn't rely on the "lexer hack": it has no notion of scope and
+ does not categorize identifiers as types or variables -- this is up to the
+ parser to decide.
+
+Potential Future Features:
+
+ * Fine grained diag control within the source (#pragma enable/disable warning).
+ * Better token tracking within macros? (Token came from this line, which is
+ a macro argument instantiated here, recursively instantiated here).
+ * Fast #import with a module system.
+ * Dependency tracking: change to header file doesn't recompile every function
+ that texually depends on it: recompile only those functions that need it.
+ This is aka 'incremental parsing'.
+
+
+IV. Missing Functionality / Improvements
+
+Lexer:
+ * Source character mapping. GCC supports ASCII and UTF-8.
+ See GCC options: -ftarget-charset and -ftarget-wide-charset.
+ * Universal character support. Experimental in GCC, enabled with
+ -fextended-identifiers.
+ * -fpreprocessed mode.
+
+Preprocessor:
+ * #assert/#unassert
+ * MSExtension: "L#param" stringizes to a wide string literal.
+ * Add support for -M*
+
+Traditional Preprocessor:
+ * Currently, we have none. :)
+
diff --git a/docs/HowToAddABuilder.rst b/docs/HowToAddABuilder.rst
new file mode 100644
index 00000000000..b0cd2907f97
--- /dev/null
+++ b/docs/HowToAddABuilder.rst
@@ -0,0 +1,90 @@
+.. _how_to_add_a_builder:
+
+===================================================================
+How To Add Your Build Configuration To LLVM Buildbot Infrastructure
+===================================================================
+
+.. sectionauthor:: Galina Kistanova <gkistanova@gmail.com>
+
+Introduction
+============
+
+This document contains information about adding a build configuration and
+buildslave to private slave builder to LLVM Buildbot Infrastructure
+`<http://lab.llvm.org:8011>`_.
+
+
+Steps To Add Builder To LLVM Buildbot
+=====================================
+Volunteers can provide their build machines to work as build slaves to
+public LLVM Buildbot.
+
+Here are the steps you can follow to do so:
+
+#. Check the existing build configurations to make sure the one you are
+ interested in is not covered yet or gets built on your computer much
+ faster than on the existing one. We prefer faster builds so developers
+ will get feedback sooner after changes get committed.
+
+#. The computer you will be registering with the LLVM buildbot
+ infrastructure should have all dependencies installed and you can
+ actually build your configuration successfully. Please check what degree
+ of parallelism (-j param) would give the fastest build. You can build
+ multiple configurations on one computer.
+
+#. Install buildslave (currently we are using buildbot version 0.8.5).
+ Depending on the platform, buildslave could be available to download and
+ install with your packet manager, or you can download it directly from
+ `<http://trac.buildbot.net>`_ and install it manually.
+
+#. Create a designated user account, your buildslave will be running under,
+ and set appropriate permissions.
+
+#. Choose the buildslave root directory (all builds will be placed under
+ it), buildslave access name and password the build master will be using
+ to authenticate your buildslave.
+
+#. Create a buildslave in context of that buildslave account. Point it to
+ the **lab.llvm.org** port **9990** (see `Buildbot documentation,
+ Creating a slave
+ <http://buildbot.net/buildbot/docs/current/full.html#creating-a-slave>`_
+ for more details) by running the following command:
+
+ .. code-block:: bash
+
+ $ buildslave create-slave <buildslave-root-directory> \
+ lab.llvm.org:9990 \
+ <buildslave-access-name> <buildslave-access-password>
+
+#. Fill the buildslave description and admin name/e-mail. Here is an
+ example of the buildslave description::
+
+ Windows 7 x64
+ Core i7 (2.66GHz), 16GB of RAM
+
+ g++.exe (TDM-1 mingw32) 4.4.0
+ GNU Binutils 2.19.1
+ cmake version 2.8.4
+ Microsoft(R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
+
+#. Make sure you can actually start the buildslave successfully. Then set
+ up your buildslave to start automatically at the start up time. See the
+ buildbot documentation for help. You may want to restart your computer
+ to see if it works.
+
+#. Send a patch which adds your build slave and your builder to zorg.
+
+ * slaves are added to ``buildbot/osuosl/master/config/slaves.py``
+ * builders are added to ``buildbot/osuosl/master/config/builders.py``
+
+#. Send the buildslave access name and the access password directly to
+ `Galina Kistanova <mailto:gkistanova@gmail.com>`_, and wait till she
+ will let you know that your changes are applied and buildmaster is
+ reconfigured.
+
+#. Check the status of your buildslave on the `Waterfall Display
+ <http://lab.llvm.org:8011/waterfall>`_ to make sure it is connected, and
+ ``http://lab.llvm.org:8011/buildslaves/<your-buildslave-name>`` to see
+ if administrator contact and slave information are correct.
+
+#. Wait for the first build to succeed and enjoy.
diff --git a/docs/HowToReleaseLLVM.html b/docs/HowToReleaseLLVM.html
new file mode 100644
index 00000000000..30c3d5da5e9
--- /dev/null
+++ b/docs/HowToReleaseLLVM.html
@@ -0,0 +1,581 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>How To Release LLVM To The Public</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>How To Release LLVM To The Public</h1>
+<ol>
+ <li><a href="#introduction">Introduction</a></li>
+ <li><a href="#criteria">Qualification Criteria</a></li>
+ <li><a href="#introduction">Release Timeline</a></li>
+ <li><a href="#process">Release Process</a></li>
+</ol>
+<div class="doc_author">
+ <p>Written by <a href="mailto:tonic@nondot.org">Tanya Lattner</a>,
+ <a href="mailto:rspencer@x10sys.com">Reid Spencer</a>,
+ <a href="mailto:criswell@cs.uiuc.edu">John Criswell</a>, &amp;
+ <a href="mailto:wendling@apple.com">Bill Wendling</a>
+ </p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="introduction">Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This document contains information about successfully releasing LLVM &mdash;
+ including subprojects: e.g., <tt>clang</tt> and <tt>dragonegg</tt> &mdash; to
+ the public. It is the Release Manager's responsibility to ensure that a high
+ quality build of LLVM is released.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="process">Release Timeline</a></h2>
+<!-- *********************************************************************** -->
+<div>
+
+<p>LLVM is released on a time based schedule &mdash; roughly every 6 months. We
+ do not normally have dot releases because of the nature of LLVM's incremental
+ development philosophy. That said, the only thing preventing dot releases for
+ critical bug fixes from happening is a lack of resources &mdash; testers,
+ machines, time, etc. And, because of the high quality we desire for LLVM
+ releases, we cannot allow for a truncated form of release qualification.</p>
+
+<p>The release process is roughly as follows:</p>
+
+<ul>
+ <li><p>Set code freeze and branch creation date for 6 months after last code
+ freeze date. Announce release schedule to the LLVM community and update
+ the website.</p></li>
+
+ <li><p>Create release branch and begin release process.</p></li>
+
+ <li><p>Send out release candidate sources for first round of testing. Testing
+ lasts 7-10 days. During the first round of testing, any regressions found
+ should be fixed. Patches are merged from mainline into the release
+ branch. Also, all features need to be completed during this time. Any
+ features not completed at the end of the first round of testing will be
+ removed or disabled for the release.</p></li>
+
+ <li><p>Generate and send out the second release candidate sources. Only
+ <em>critial</em> bugs found during this testing phase will be fixed. Any
+ bugs introduced by merged patches will be fixed. If so a third round of
+ testing is needed.</p></li>
+
+ <li><p>The release notes are updated.</p></li>
+
+ <li><p>Finally, release!</p></li>
+</ul>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="process">Release Process</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<ol>
+ <li><a href="#release-admin">Release Administrative Tasks</a>
+ <ol>
+ <li><a href="#branch">Create Release Branch</a></li>
+ <li><a href="#verchanges">Update Version Numbers</a></li>
+ </ol>
+ </li>
+ <li><a href="#release-build">Building the Release</a>
+ <ol>
+ <li><a href="#dist">Build the LLVM Source Distributions</a></li>
+ <li><a href="#build">Build LLVM</a></li>
+ <li><a href="#clangbin">Build the Clang Binary Distribution</a></li>
+ <li><a href="#target-build">Target Specific Build Details</a></li>
+ </ol>
+ </li>
+ <li><a href="#release-qualify">Release Qualification Criteria</a>
+ <ol>
+ <li><a href="#llvm-qualify">Qualify LLVM</a></li>
+ <li><a href="#clang-qualify">Qualify Clang</a></li>
+ <li><a href="#targets">Specific Target Qualification Details</a></li>
+ </ol>
+ </li>
+
+ <li><a href="#commTest">Community Testing</a></li>
+ <li><a href="#release-patch">Release Patch Rules</a></li>
+ <li><a href="#release-final">Release final tasks</a>
+ <ol>
+ <li><a href="#updocs">Update Documentation</a></li>
+ <li><a href="#tag">Tag the LLVM Final Release</a></li>
+ <li><a href="#updemo">Update the LLVM Demo Page</a></li>
+ <li><a href="#webupdates">Update the LLVM Website</a></li>
+ <li><a href="#announce">Announce the Release</a></li>
+ </ol>
+ </li>
+</ol>
+
+<!-- ======================================================================= -->
+<h3><a name="release-admin">Release Administrative Tasks</a></h3>
+
+<div>
+
+<p>This section describes a few administrative tasks that need to be done for
+ the release process to begin. Specifically, it involves:</p>
+
+<ul>
+ <li>Creating the release branch,</li>
+ <li>Setting version numbers, and</li>
+ <li>Tagging release candidates for the release team to begin testing</li>
+</ul>
+
+<!-- ======================================================================= -->
+<h4><a name="branch">Create Release Branch</a></h4>
+
+<div>
+
+<p>Branch the Subversion trunk using the following procedure:</p>
+
+<ol>
+ <li><p>Remind developers that the release branching is imminent and to refrain
+ from committing patches that might break the build. E.g., new features,
+ large patches for works in progress, an overhaul of the type system, an
+ exciting new TableGen feature, etc.</p></li>
+
+ <li><p>Verify that the current Subversion trunk is in decent shape by
+ examining nightly tester and buildbot results.</p></li>
+
+ <li><p>Create the release branch for <tt>llvm</tt>, <tt>clang</tt>,
+ the <tt>test-suite</tt>, and <tt>dragonegg</tt> from the last known good
+ revision. The branch's name is <tt>release_<i>XY</i></tt>,
+ where <tt>X</tt> is the major and <tt>Y</tt> the minor release
+ numbers. The branches should be created using the following commands:</p>
+
+<div class="doc_code">
+<pre>
+$ svn copy https://llvm.org/svn/llvm-project/llvm/trunk \
+ https://llvm.org/svn/llvm-project/llvm/branches/release_<i>XY</i>
+
+$ svn copy https://llvm.org/svn/llvm-project/cfe/trunk \
+ https://llvm.org/svn/llvm-project/cfe/branches/release_<i>XY</i>
+
+$ svn copy https://llvm.org/svn/llvm-project/dragonegg/trunk \
+ https://llvm.org/svn/llvm-project/dragonegg/branches/release_<i>XY</i>
+
+$ svn copy https://llvm.org/svn/llvm-project/test-suite/trunk \
+ https://llvm.org/svn/llvm-project/test-suite/branches/release_<i>XY</i>
+</pre>
+</div></li>
+
+ <li><p>Advise developers that they may now check their patches into the
+ Subversion tree again.</p></li>
+
+ <li><p>The Release Manager should switch to the release branch, because all
+ changes to the release will now be done in the branch. The easiest way to
+ do this is to grab a working copy using the following commands:</p>
+
+<div class="doc_code">
+<pre>
+$ svn co https://llvm.org/svn/llvm-project/llvm/branches/release_<i>XY</i> llvm-<i>X.Y</i>
+
+$ svn co https://llvm.org/svn/llvm-project/cfe/branches/release_<i>XY</i> clang-<i>X.Y</i>
+
+$ svn co https://llvm.org/svn/llvm-project/dragonegg/branches/release_<i>XY</i> dragonegg-<i>X.Y</i>
+
+$ svn co https://llvm.org/svn/llvm-project/test-suite/branches/release_<i>XY</i> test-suite-<i>X.Y</i>
+</pre>
+</div></li>
+</ol>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="verchanges">Update LLVM Version</a></h4>
+
+<div>
+
+<p>After creating the LLVM release branch, update the release branches'
+ <tt>autoconf</tt> and <tt>configure.ac</tt> versions from '<tt>X.Ysvn</tt>'
+ to '<tt>X.Y</tt>'. Update it on mainline as well to be the next version
+ ('<tt>X.Y+1svn</tt>'). Regenerate the configure scripts for both
+ <tt>llvm</tt> and the <tt>test-suite</tt>.</p>
+
+<p>In addition, the version numbers of all the Bugzilla components must be
+ updated for the next release.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="dist">Build the LLVM Release Candidates</a></h4>
+
+<div>
+
+<p>Create release candidates for <tt>llvm</tt>, <tt>clang</tt>,
+ <tt>dragonegg</tt>, and the LLVM <tt>test-suite</tt> by tagging the branch
+ with the respective release candidate number. For instance, to
+ create <b>Release Candidate 1</b> you would issue the following commands:</p>
+
+<div class="doc_code">
+<pre>
+$ svn mkdir https://llvm.org/svn/llvm-project/llvm/tags/RELEASE_<i>XY</i>
+$ svn copy https://llvm.org/svn/llvm-project/llvm/branches/release_<i>XY</i> \
+ https://llvm.org/svn/llvm-project/llvm/tags/RELEASE_<i>XY</i>/rc1
+
+$ svn mkdir https://llvm.org/svn/llvm-project/cfe/tags/RELEASE_<i>XY</i>
+$ svn copy https://llvm.org/svn/llvm-project/cfe/branches/release_<i>XY</i> \
+ https://llvm.org/svn/llvm-project/cfe/tags/RELEASE_<i>XY</i>/rc1
+
+$ svn mkdir https://llvm.org/svn/llvm-project/dragonegg/tags/RELEASE_<i>XY</i>
+$ svn copy https://llvm.org/svn/llvm-project/dragonegg/branches/release_<i>XY</i> \
+ https://llvm.org/svn/llvm-project/dragonegg/tags/RELEASE_<i>XY</i>/rc1
+
+$ svn mkdir https://llvm.org/svn/llvm-project/test-suite/tags/RELEASE_<i>XY</i>
+$ svn copy https://llvm.org/svn/llvm-project/test-suite/branches/release_<i>XY</i> \
+ https://llvm.org/svn/llvm-project/test-suite/tags/RELEASE_<i>XY</i>/rc1
+</pre>
+</div>
+
+<p>Similarly, <b>Release Candidate 2</b> would be named <tt>RC2</tt> and so
+ on. This keeps a permanent copy of the release candidate around for people to
+ export and build as they wish. The final released sources will be tagged in
+ the <tt>RELEASE_<i>XY</i></tt> directory as <tt>Final</tt>
+ (c.f. <a href="#tag">Tag the LLVM Final Release</a>).</p>
+
+<p>The Release Manager may supply pre-packaged source tarballs for users. This
+ can be done with the following commands:</p>
+
+<div class="doc_code">
+<pre>
+$ svn export https://llvm.org/svn/llvm-project/llvm/tags/RELEASE_<i>XY</i>/rc1 llvm-<i>X.Y</i>rc1
+$ svn export https://llvm.org/svn/llvm-project/cfe/tags/RELEASE_<i>XY</i>/rc1 clang-<i>X.Y</i>rc1
+$ svn export https://llvm.org/svn/llvm-project/dragonegg/tags/RELEASE_<i>XY</i>/rc1 dragonegg-<i>X.Y</i>rc1
+$ svn export https://llvm.org/svn/llvm-project/test-suite/tags/RELEASE_<i>XY</i>/rc1 llvm-test-<i>X.Y</i>rc1
+
+$ tar -cvf - llvm-<i>X.Y</i>rc1 | gzip &gt; llvm-<i>X.Y</i>rc1.src.tar.gz
+$ tar -cvf - clang-<i>X.Y</i>rc1 | gzip &gt; clang-<i>X.Y</i>rc1.src.tar.gz
+$ tar -cvf - dragonegg-<i>X.Y</i>rc1 | gzip &gt; dragonegg-<i>X.Y</i>rc1.src.tar.gz
+$ tar -cvf - llvm-test-<i>X.Y</i>rc1 | gzip &gt; llvm-test-<i>X.Y</i>rc1.src.tar.gz
+</pre>
+</div>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="release-build">Building the Release</a></h3>
+
+<div>
+
+<p>The builds of <tt>llvm</tt>, <tt>clang</tt>, and <tt>dragonegg</tt>
+ <em>must</em> be free of errors and warnings in Debug, Release+Asserts, and
+ Release builds. If all builds are clean, then the release passes Build
+ Qualification.</p>
+
+<p>The <tt>make</tt> options for building the different modes:</p>
+
+<table>
+ <tr><th>Mode</th><th>Options</th></tr>
+ <tr align="left"><td>Debug</td><td><tt>ENABLE_OPTIMIZED=0</tt></td></tr>
+ <tr align="left"><td>Release+Asserts</td><td><tt>ENABLE_OPTIMIZED=1</tt></td></tr>
+ <tr align="left"><td>Release</td><td><tt>ENABLE_OPTIMIZED=1 DISABLE_ASSERTIONS=1</tt></td></tr>
+</table>
+
+<!-- ======================================================================= -->
+<h4><a name="build">Build LLVM</a></h4>
+
+<div>
+
+<p>Build <tt>Debug</tt>, <tt>Release+Asserts</tt>, and <tt>Release</tt> versions
+ of <tt>llvm</tt> on all supported platforms. Directions to build
+ <tt>llvm</tt> are <a href="GettingStarted.html#quickstart">here</a>.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="clangbin">Build Clang Binary Distribution</a></h4>
+
+<div>
+
+<p>Creating the <tt>clang</tt> binary distribution
+ (Debug/Release+Asserts/Release) requires performing the following steps for
+ each supported platform:</p>
+
+<ol>
+ <li>Build clang according to the directions
+ <a href="http://clang.llvm.org/get_started.html">here</a>.</li>
+
+ <li>Build both a Debug and Release version of clang. The binary will be the
+ Release build.</lI>
+
+ <li>Package <tt>clang</tt> (details to follow).</li>
+</ol>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="target-build">Target Specific Build Details</a></h4>
+
+<div>
+
+<p>The table below specifies which compilers are used for each Arch/OS
+ combination when qualifying the build of <tt>llvm</tt>, <tt>clang</tt>,
+ and <tt>dragonegg</tt>.</p>
+
+<table>
+ <tr><th>Architecture</th> <th>OS</th> <th>compiler</th></tr>
+ <tr><td>x86-32</td> <td>Mac OS 10.5</td> <td>gcc 4.0.1</td></tr>
+ <tr><td>x86-32</td> <td>Linux</td> <td>gcc 4.2.X, gcc 4.3.X</td></tr>
+ <tr><td>x86-32</td> <td>FreeBSD</td> <td>gcc 4.2.X</td></tr>
+ <tr><td>x86-32</td> <td>mingw</td> <td>gcc 3.4.5</td></tr>
+ <tr><td>x86-64</td> <td>Mac OS 10.5</td> <td>gcc 4.0.1</td></tr>
+ <tr><td>x86-64</td> <td>Linux</td> <td>gcc 4.2.X, gcc 4.3.X</td></tr>
+ <tr><td>x86-64</td> <td>FreeBSD</td> <td>gcc 4.2.X</td></tr>
+</table>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="release-qualify">Building the Release</a></h3>
+
+<div>
+
+<p>A release is qualified when it has no regressions from the previous release
+ (or baseline). Regressions are related to correctness first and performance
+ second. (We may tolerate some minor performance regressions if they are
+ deemed necessary for the general quality of the compiler.)</p>
+
+<p><b>Regressions are new failures in the set of tests that are used to qualify
+ each product and only include things on the list. Every release will have
+ some bugs in it. It is the reality of developing a complex piece of
+ software. We need a very concrete and definitive release criteria that
+ ensures we have monotonically improving quality on some metric. The metric we
+ use is described below. This doesn't mean that we don't care about other
+ criteria, but these are the criteria which we found to be most important and
+ which must be satisfied before a release can go out</b></p>
+
+<!-- ======================================================================= -->
+<h4><a name="llvm-qualify">Qualify LLVM</a></h4>
+
+<div>
+
+<p>LLVM is qualified when it has a clean test run without a front-end. And it
+ has no regressions when using either <tt>clang</tt> or <tt>dragonegg</tt>
+ with the <tt>test-suite</tt> from the previous release.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="clang-qualify">Qualify Clang</a></h4>
+
+<div>
+
+<p><tt>Clang</tt> is qualified when front-end specific tests in the
+ <tt>llvm</tt> dejagnu test suite all pass, clang's own test suite passes
+ cleanly, and there are no regressions in the <tt>test-suite</tt>.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="targets">Specific Target Qualification Details</a></h4>
+
+<div>
+
+<table>
+ <tr><th>Architecture</th> <th>OS</th> <th>clang baseline</th> <th>tests</th></tr>
+ <tr><td>x86-32</td> <td>Linux</td> <td>last release</td> <td>llvm dejagnu, clang tests, test-suite (including spec)</td></tr>
+ <tr><td>x86-32</td> <td>FreeBSD</td> <td>last release</td> <td>llvm dejagnu, clang tests, test-suite</td></tr>
+ <tr><td>x86-32</td> <td>mingw</td> <td>none</td> <td>QT</td></tr>
+ <tr><td>x86-64</td> <td>Mac OS 10.X</td> <td>last release</td> <td>llvm dejagnu, clang tests, test-suite (including spec)</td></tr>
+ <tr><td>x86-64</td> <td>Linux</td> <td>last release</td> <td>llvm dejagnu, clang tests, test-suite (including spec)</td></tr>
+ <tr><td>x86-64</td> <td>FreeBSD</td> <td>last release</td> <td>llvm dejagnu, clang tests, test-suite</td></tr>
+</table>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="commTest">Community Testing</a></h3>
+<div>
+
+<p>Once all testing has been completed and appropriate bugs filed, the release
+ candidate tarballs are put on the website and the LLVM community is
+ notified. Ask that all LLVM developers test the release in 2 ways:</p>
+
+<ol>
+ <li>Download <tt>llvm-<i>X.Y</i></tt>, <tt>llvm-test-<i>X.Y</i></tt>, and the
+ appropriate <tt>clang</tt> binary. Build LLVM. Run <tt>make check</tt> and
+ the full LLVM test suite (<tt>make TEST=nightly report</tt>).</li>
+
+ <li>Download <tt>llvm-<i>X.Y</i></tt>, <tt>llvm-test-<i>X.Y</i></tt>, and the
+ <tt>clang</tt> sources. Compile everything. Run <tt>make check</tt> and
+ the full LLVM test suite (<tt>make TEST=nightly report</tt>).</li>
+</ol>
+
+<p>Ask LLVM developers to submit the test suite report and <tt>make check</tt>
+ results to the list. Verify that there are no regressions from the previous
+ release. The results are not used to qualify a release, but to spot other
+ potential problems. For unsupported targets, verify that <tt>make check</tt>
+ is at least clean.</p>
+
+<p>During the first round of testing, all regressions must be fixed before the
+ second release candidate is tagged.</p>
+
+<p>If this is the second round of testing, the testing is only to ensure that
+ bug fixes previously merged in have not created new major problems. <i>This
+ is not the time to solve additional and unrelated bugs!</i> If no patches are
+ merged in, the release is determined to be ready and the release manager may
+ move onto the next stage.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="release-patch">Release Patch Rules</a></h3>
+
+<div>
+
+<p>Below are the rules regarding patching the release branch:</p>
+
+<ol>
+ <li><p>Patches applied to the release branch may only be applied by the
+ release manager.</p></li>
+
+ <li><p>During the first round of testing, patches that fix regressions or that
+ are small and relatively risk free (verified by the appropriate code
+ owner) are applied to the branch. Code owners are asked to be very
+ conservative in approving patches for the branch. We reserve the right to
+ reject any patch that does not fix a regression as previously
+ defined.</p></li>
+
+ <li><p>During the remaining rounds of testing, only patches that fix critical
+ regressions may be applied.</p></li>
+</ol>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="release-final">Release Final Tasks</a></h3>
+
+<div>
+
+<p>The final stages of the release process involves tagging the "final" release
+ branch, updating documentation that refers to the release, and updating the
+ demo page.</p>
+
+<!-- ======================================================================= -->
+<h4><a name="updocs">Update Documentation</a></h4>
+
+<div>
+
+<p>Review the documentation and ensure that it is up to date. The "Release
+ Notes" must be updated to reflect new features, bug fixes, new known issues,
+ and changes in the list of supported platforms. The "Getting Started Guide"
+ should be updated to reflect the new release version number tag available from
+ Subversion and changes in basic system requirements. Merge both changes from
+ mainline into the release branch.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="tag">Tag the LLVM Final Release</a></h4>
+
+<div>
+
+<p>Tag the final release sources using the following procedure:</p>
+
+<div class="doc_code">
+<pre>
+$ svn copy https://llvm.org/svn/llvm-project/llvm/branches/release_XY \
+ https://llvm.org/svn/llvm-project/llvm/tags/RELEASE_<i>XY</i>/Final
+
+$ svn copy https://llvm.org/svn/llvm-project/cfe/branches/release_XY \
+ https://llvm.org/svn/llvm-project/cfe/tags/RELEASE_<i>XY</i>/Final
+
+$ svn copy https://llvm.org/svn/llvm-project/dragonegg/branches/release_XY \
+ https://llvm.org/svn/llvm-project/dragonegg/tags/RELEASE_<i>XY</i>/Final
+
+$ svn copy https://llvm.org/svn/llvm-project/test-suite/branches/release_XY \
+ https://llvm.org/svn/llvm-project/test-suite/tags/RELEASE_<i>XY</i>/Final
+</pre>
+</div>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="updemo">Update the LLVM Demo Page</a></h3>
+
+<div>
+
+<p>The LLVM demo page must be updated to use the new release. This consists of
+ using the new <tt>clang</tt> binary and building LLVM.</p>
+
+<!-- ======================================================================= -->
+<h4><a name="webupdates">Update the LLVM Website</a></h4>
+
+<div>
+
+<p>The website must be updated before the release announcement is sent out. Here
+ is what to do:</p>
+
+<ol>
+ <li>Check out the <tt>www</tt> module from Subversion.</li>
+
+ <li>Create a new subdirectory <tt>X.Y</tt> in the releases directory.</li>
+
+ <li>Commit the <tt>llvm</tt>, <tt>test-suite</tt>, <tt>clang</tt> source,
+ <tt>clang binaries</tt>, <tt>dragonegg</tt> source, and <tt>dragonegg</tt>
+ binaries in this new directory.</li>
+
+ <li>Copy and commit the <tt>llvm/docs</tt> and <tt>LICENSE.txt</tt> files
+ into this new directory. The docs should be built with
+ <tt>BUILD_FOR_WEBSITE=1</tt>.</li>
+
+ <li>Commit the <tt>index.html</tt> to the <tt>release/X.Y</tt> directory to
+ redirect (use from previous release.</li>
+
+ <li>Update the <tt>releases/download.html</tt> file with the new release.</li>
+
+ <li>Update the <tt>releases/index.html</tt> with the new release and link to
+ release documentation.</li>
+
+ <li>Finally, update the main page (<tt>index.html</tt> and sidebar) to point
+ to the new release and release announcement. Make sure this all gets
+ committed back into Subversion.</li>
+</ol>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="announce">Announce the Release</a></h4>
+
+<div>
+
+<p>Have Chris send out the release announcement when everything is finished.</p>
+
+</div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a>
+ <br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/HowToSubmitABug.html b/docs/HowToSubmitABug.html
new file mode 100644
index 00000000000..39f83851293
--- /dev/null
+++ b/docs/HowToSubmitABug.html
@@ -0,0 +1,345 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>How to submit an LLVM bug report</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>
+ How to submit an LLVM bug report
+</h1>
+
+<table class="layout" style="width: 90%" >
+<tr class="layout">
+ <td class="left">
+<ol>
+ <li><a href="#introduction">Introduction - Got bugs?</a></li>
+ <li><a href="#crashers">Crashing Bugs</a>
+ <ul>
+ <li><a href="#front-end">Front-end bugs</a>
+ <li><a href="#ct_optimizer">Compile-time optimization bugs</a>
+ <li><a href="#ct_codegen">Code generator bugs</a>
+ </ul></li>
+ <li><a href="#miscompilations">Miscompilations</a></li>
+ <li><a href="#codegen">Incorrect code generation (JIT and LLC)</a></li>
+</ol>
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a> and
+ <a href="http://misha.brukman.net">Misha Brukman</a></p>
+</div>
+</td>
+</tr>
+</table>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="introduction">Introduction - Got bugs?</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>If you're working with LLVM and run into a bug, we definitely want to know
+about it. This document describes what you can do to increase the odds of
+getting it fixed quickly.</p>
+
+<p>Basically you have to do two things at a minimum. First, decide whether the
+bug <a href="#crashers">crashes the compiler</a> (or an LLVM pass), or if the
+compiler is <a href="#miscompilations">miscompiling</a> the program (i.e., the
+compiler successfully produces an executable, but it doesn't run right). Based
+on
+what type of bug it is, follow the instructions in the linked section to narrow
+down the bug so that the person who fixes it will be able to find the problem
+more easily.</p>
+
+<p>Once you have a reduced test-case, go to <a
+href="http://llvm.org/bugs/enter_bug.cgi">the LLVM Bug Tracking
+System</a> and fill out the form with the necessary details (note that you don't
+need to pick a category, just use the "new-bugs" category if you're not sure).
+The bug description should contain the following
+information:</p>
+
+<ul>
+ <li>All information necessary to reproduce the problem.</li>
+ <li>The reduced test-case that triggers the bug.</li>
+ <li>The location where you obtained LLVM (if not from our Subversion
+ repository).</li>
+</ul>
+
+<p>Thanks for helping us make LLVM better!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="crashers">Crashing Bugs</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>More often than not, bugs in the compiler cause it to crash&mdash;often due
+to an assertion failure of some sort. The most important
+piece of the puzzle is to figure out if it is crashing in the GCC front-end
+or if it is one of the LLVM libraries (e.g. the optimizer or code generator)
+that has problems.</p>
+
+<p>To figure out which component is crashing (the front-end,
+optimizer or code generator), run the
+<tt><b>llvm-gcc</b></tt> command line as you were when the crash occurred, but
+with the following extra command line options:</p>
+
+<ul>
+ <li><tt><b>-O0 -emit-llvm</b></tt>: If <tt>llvm-gcc</tt> still crashes when
+ passed these options (which disable the optimizer and code generator), then
+ the crash is in the front-end. Jump ahead to the section on <a
+ href="#front-end">front-end bugs</a>.</li>
+
+ <li><tt><b>-emit-llvm</b></tt>: If <tt>llvm-gcc</tt> crashes with this option
+ (which disables the code generator), you found an optimizer bug. Jump ahead
+ to <a href="#ct_optimizer"> compile-time optimization bugs</a>.</li>
+
+ <li>Otherwise, you have a code generator crash. Jump ahead to <a
+ href="#ct_codegen">code generator bugs</a>.</li>
+
+</ul>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="front-end">Front-end bugs</a>
+</h3>
+
+<div>
+
+<p>If the problem is in the front-end, you should re-run the same
+<tt>llvm-gcc</tt> command that resulted in the crash, but add the
+<tt>-save-temps</tt> option. The compiler will crash again, but it will leave
+behind a <tt><i>foo</i>.i</tt> file (containing preprocessed C source code) and
+possibly <tt><i>foo</i>.s</tt> for each
+compiled <tt><i>foo</i>.c</tt> file. Send us the <tt><i>foo</i>.i</tt> file,
+along with the options you passed to llvm-gcc, and a brief description of the
+error it caused.</p>
+
+<p>The <a href="http://delta.tigris.org/">delta</a> tool helps to reduce the
+preprocessed file down to the smallest amount of code that still replicates the
+problem. You're encouraged to use delta to reduce the code to make the
+developers' lives easier. <a
+href="http://gcc.gnu.org/wiki/A_guide_to_testcase_reduction">This website</a>
+has instructions on the best way to use delta.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ct_optimizer">Compile-time optimization bugs</a>
+</h3>
+
+<div>
+
+<p>If you find that a bug crashes in the optimizer, compile your test-case to a
+<tt>.bc</tt> file by passing "<tt><b>-emit-llvm -O0 -c -o foo.bc</b></tt>".
+Then run:</p>
+
+<div class="doc_code">
+<p><tt><b>opt</b> -std-compile-opts -debug-pass=Arguments foo.bc
+ -disable-output</tt></p>
+</div>
+
+<p>This command should do two things: it should print out a list of passes, and
+then it should crash in the same way as llvm-gcc. If it doesn't crash, please
+follow the instructions for a <a href="#front-end">front-end bug</a>.</p>
+
+<p>If this does crash, then you should be able to debug this with the following
+bugpoint command:</p>
+
+<div class="doc_code">
+<p><tt><b>bugpoint</b> foo.bc &lt;list of passes printed by
+<b>opt</b>&gt;</tt></p>
+</div>
+
+<p>Please run this, then file a bug with the instructions and reduced .bc files
+that bugpoint emits. If something goes wrong with bugpoint, please submit the
+"foo.bc" file and the list of passes printed by <b>opt</b>.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ct_codegen">Code generator bugs</a>
+</h3>
+
+<div>
+
+<p>If you find a bug that crashes llvm-gcc in the code generator, compile your
+source file to a .bc file by passing "<tt><b>-emit-llvm -c -o foo.bc</b></tt>"
+to llvm-gcc (in addition to the options you already pass). Once your have
+foo.bc, one of the following commands should fail:</p>
+
+<ol>
+<li><tt><b>llc</b> foo.bc</tt></li>
+<li><tt><b>llc</b> foo.bc -relocation-model=pic</tt></li>
+<li><tt><b>llc</b> foo.bc -relocation-model=static</tt></li>
+</ol>
+
+<p>If none of these crash, please follow the instructions for a
+<a href="#front-end">front-end bug</a>. If one of these do crash, you should
+be able to reduce this with one of the following bugpoint command lines (use
+the one corresponding to the command above that failed):</p>
+
+<ol>
+<li><tt><b>bugpoint</b> -run-llc foo.bc</tt></li>
+<li><tt><b>bugpoint</b> -run-llc foo.bc --tool-args
+ -relocation-model=pic</tt></li>
+<li><tt><b>bugpoint</b> -run-llc foo.bc --tool-args
+ -relocation-model=static</tt></li>
+</ol>
+
+<p>Please run this, then file a bug with the instructions and reduced .bc file
+that bugpoint emits. If something goes wrong with bugpoint, please submit the
+"foo.bc" file and the option that llc crashes with.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="miscompilations">Miscompilations</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>If llvm-gcc successfully produces an executable, but that executable doesn't
+run right, this is either a bug in the code or a bug in the
+compiler. The first thing to check is to make sure it is not using undefined
+behavior (e.g. reading a variable before it is defined). In particular, check
+to see if the program <a href="http://valgrind.org/">valgrind</a>s clean,
+passes purify, or some other memory checker tool. Many of the "LLVM bugs" that
+we have chased down ended up being bugs in the program being compiled, not
+ LLVM.</p>
+
+<p>Once you determine that the program itself is not buggy, you should choose
+which code generator you wish to compile the program with (e.g. LLC or the JIT)
+and optionally a series of LLVM passes to run. For example:</p>
+
+<div class="doc_code">
+<p><tt>
+<b>bugpoint</b> -run-llc [... optzn passes ...] file-to-test.bc --args -- [program arguments]</tt></p>
+</div>
+
+<p><tt>bugpoint</tt> will try to narrow down your list of passes to the one pass
+that causes an error, and simplify the bitcode file as much as it can to assist
+you. It will print a message letting you know how to reproduce the resulting
+error.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="codegen">Incorrect code generation</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Similarly to debugging incorrect compilation by mis-behaving passes, you can
+debug incorrect code generation by either LLC or the JIT, using
+<tt>bugpoint</tt>. The process <tt>bugpoint</tt> follows in this case is to try
+to narrow the code down to a function that is miscompiled by one or the other
+method, but since for correctness, the entire program must be run,
+<tt>bugpoint</tt> will compile the code it deems to not be affected with the C
+Backend, and then link in the shared object it generates.</p>
+
+<p>To debug the JIT:</p>
+
+<div class="doc_code">
+<pre>
+bugpoint -run-jit -output=[correct output file] [bitcode file] \
+ --tool-args -- [arguments to pass to lli] \
+ --args -- [program arguments]
+</pre>
+</div>
+
+<p>Similarly, to debug the LLC, one would run:</p>
+
+<div class="doc_code">
+<pre>
+bugpoint -run-llc -output=[correct output file] [bitcode file] \
+ --tool-args -- [arguments to pass to llc] \
+ --args -- [program arguments]
+</pre>
+</div>
+
+<p><b>Special note:</b> if you are debugging MultiSource or SPEC tests that
+already exist in the <tt>llvm/test</tt> hierarchy, there is an easier way to
+debug the JIT, LLC, and CBE, using the pre-written Makefile targets, which
+will pass the program options specified in the Makefiles:</p>
+
+<div class="doc_code">
+<p><tt>
+cd llvm/test/../../program<br>
+make bugpoint-jit
+</tt></p>
+</div>
+
+<p>At the end of a successful <tt>bugpoint</tt> run, you will be presented
+with two bitcode files: a <em>safe</em> file which can be compiled with the C
+backend and the <em>test</em> file which either LLC or the JIT
+mis-codegenerates, and thus causes the error.</p>
+
+<p>To reproduce the error that <tt>bugpoint</tt> found, it is sufficient to do
+the following:</p>
+
+<ol>
+
+<li><p>Regenerate the shared object from the safe bitcode file:</p>
+
+<div class="doc_code">
+<p><tt>
+<b>llc</b> -march=c safe.bc -o safe.c<br>
+<b>gcc</b> -shared safe.c -o safe.so
+</tt></p>
+</div></li>
+
+<li><p>If debugging LLC, compile test bitcode native and link with the shared
+ object:</p>
+
+<div class="doc_code">
+<p><tt>
+<b>llc</b> test.bc -o test.s<br>
+<b>gcc</b> test.s safe.so -o test.llc<br>
+./test.llc [program options]
+</tt></p>
+</div></li>
+
+<li><p>If debugging the JIT, load the shared object and supply the test
+ bitcode:</p>
+
+<div class="doc_code">
+<p><tt><b>lli</b> -load=safe.so test.bc [program options]</tt></p>
+</div></li>
+
+</ol>
+
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a>
+ <br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/LLVMBuild.html b/docs/LLVMBuild.html
new file mode 100644
index 00000000000..9e7f8c76577
--- /dev/null
+++ b/docs/LLVMBuild.html
@@ -0,0 +1,368 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>LLVMBuild Documentation</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>LLVMBuild Guide</h1>
+
+<ol>
+ <li><a href="#introduction">Introduction</a></li>
+ <li><a href="#projectorg">Project Organization</a></li>
+ <li><a href="#buildintegration">Build Integration</a></li>
+ <li><a href="#componentoverview">Component Overview</a></li>
+ <li><a href="#formatreference">Format Reference</a></li>
+</ol>
+
+<!-- *********************************************************************** -->
+<h2><a name="introduction">Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+ <p>This document describes the <tt>LLVMBuild</tt> organization and files which
+ we use to describe parts of the LLVM ecosystem. For description of specific
+ LLVMBuild related tools, please see the command guide.</p>
+
+ <p>LLVM is designed to be a modular set of libraries which can be flexibly
+ mixed together in order to build a variety of tools, like compilers, JITs,
+ custom code generators, optimization passes, interpreters, and so on. Related
+ projects in the LLVM system like Clang and LLDB also tend to follow this
+ philosophy.</p>
+
+ <p>In order to support this usage style, LLVM has a fairly strict structure as
+ to how the source code and various components are organized. The
+ <tt>LLVMBuild.txt</tt> files are the explicit specification of that structure,
+ and are used by the build systems and other tools in order to develop the LLVM
+ project.</p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="projectorg">Project Organization</a></h2>
+<!-- *********************************************************************** -->
+
+<!-- FIXME: We should probably have an explicit top level project object. Good
+place to hang project level data, name, etc. Also useful for serving as the
+$ROOT of project trees for things which can be checked out separately. -->
+
+<div>
+ <p>The source code for LLVM projects using the LLVMBuild system (LLVM, Clang,
+ and LLDB) is organized into <em>components</em>, which define the separate
+ pieces of functionality that make up the project. These projects may consist
+ of many libraries, associated tools, build tools, or other utility tools (for
+ example, testing tools).</p>
+
+ <p>For the most part, the project contents are organized around defining one
+ main component per each subdirectory. Each such directory contains
+ an <tt>LLVMBuild.txt</tt> which contains the component definitions.</p>
+
+ <p>The component descriptions for the project as a whole are automatically
+ gathered by the LLVMBuild tools. The tools automatically traverse the source
+ directory structure to find all of the component description files. NOTE: For
+ performance/sanity reasons, we only traverse into subdirectories when the
+ parent itself contains an <tt>LLVMBuild.txt</tt> description file.</p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="buildintegration">Build Integration</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+ <p>The LLVMBuild files themselves are just a declarative way to describe the
+ project structure. The actual building of the LLVM project is handled by
+ another build system (currently we support
+ both <a href="MakefileGuide.html">Makefiles</a>
+ and <a href="CMake.html">CMake</a>.</p>
+
+ <p>The build system implementation will load the relevant contents of the
+ LLVMBuild files and use that to drive the actual project build. Typically, the
+ build system will only need to load this information at "configure" time, and
+ use it to generative native information. Build systems will also handle
+ automatically reconfiguring their information when the contents of
+ the <i>LLVMBuild.txt</i> files change.</p>
+
+ <p>Developers generally are not expected to need to be aware of the details of
+ how the LLVMBuild system is integrated into their build. Ideally, LLVM
+ developers who are not working on the build system would only ever need to
+ modify the contents of the <i>LLVMBuild.txt</i> description files (although we
+ have not reached this goal yet).</p>
+
+ <p>For more information on the utility tool we provide to help interfacing
+ with the build system, please see
+ the <a href="CommandGuide/html/llvm-build.html">llvm-build</a>
+ documentation.</p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="componentoverview">Component Overview</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+ <p>As mentioned earlier, LLVM projects are organized into
+ logical <em>components</em>. Every component is typically grouped into its
+ own subdirectory. Generally, a component is organized around a coherent group
+ of sources which have some kind of clear API separation from other parts of
+ the code.</p>
+
+ <p>LLVM primarily uses the following types of components:</p>
+ <ul>
+ <li><em>Libraries</em> - Library components define a distinct API which can
+ be independently linked into LLVM client applications. Libraries typically
+ have private and public header files, and may specify a link of required
+ libraries that they build on top of.</li>
+
+ <li><em>Build Tools</em> - Build tools are applications which are designed
+ to be run as part of the build process (typically to generate other source
+ files). Currently, LLVM uses one main build tool
+ called <a href="TableGenFundamentals.html">TableGen</a> to generate a
+ variety of source files.</li>
+
+ <li><em>Tools</em> - Command line applications which are built using the
+ LLVM component libraries. Most LLVM tools are small and are primarily
+ frontends to the library interfaces.</li>
+
+<!-- FIXME: We also need shared libraries as a first class component, but this
+ is not yet implemented. -->
+ </ul>
+
+ <p>Components are described using <em>LLVMBuild.txt</em> files in the
+ directories that define the component. See
+ the <a href="#formatreference">Format Reference</a> section for information on
+ the exact format of these files.</p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="formatreference">LLVMBuild Format Reference</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+ <p>LLVMBuild files are written in a simple variant of the INI or configuration
+ file format (<a href="http://en.wikipedia.org/wiki/INI_file">Wikipedia
+ entry</a>). The format defines a list of sections each of which may contain
+ some number of properties. A simple example of the file format is below:</p>
+ <div class="doc_code">
+ <pre>
+<i>; Comments start with a semi-colon.</i>
+
+<i>; Sections are declared using square brackets.</i>
+[component_0]
+
+<i>; Properties are declared using '=' and are contained in the previous section.
+;
+; We support simple string and boolean scalar values and list values, where
+; items are separated by spaces. There is no support for quoting, and so
+; property values may not contain spaces.</i>
+property_name = property_value
+list_property_name = value_1 value_2 <em>...</em> value_n
+boolean_property_name = 1 <em>(or 0)</em>
+</pre>
+ </div>
+
+ <p>LLVMBuild files are expected to define a strict set of sections and
+ properties. An typical component description file for a library
+ component would look typically look like the following example:</p>
+ <div class="doc_code">
+ <pre>
+[component_0]
+type = Library
+name = Linker
+parent = Libraries
+required_libraries = Archive BitReader Core Support TransformUtils
+</pre>
+ </div>
+
+ <p>A full description of the exact sections and properties which are allowed
+ follows.</p>
+
+ <p>Each file may define exactly one common component, named "common". The
+ common component may define the following properties:</p>
+ <ul>
+ <li><i>subdirectories</i> <b>[optional]</b>
+ <p>If given, a list of the names of the subdirectories from the current
+ subpath to search for additional LLVMBuild files.</p></li>
+ </ul>
+
+ <p>Each file may define multiple components. Each component is described by a
+ section who name starts with "component". The remainder of the section name is
+ ignored, but each section name must be unique. Typically components are just
+ number in order for files with multiple components ("component_0",
+ "component_1", and so on).<p>
+
+ <p><b>Section names not matching this format (or the "common" section) are
+ currently unused and are disallowed.</b></p>
+
+ <p>Every component is defined by the properties in the section. The exact list
+ of properties that are allowed depends on the component
+ type. Components <b>may not</b> define any properties other than those
+ expected by the component type.</p>
+
+ <p>Every component must define the following properties:</p>
+ <ul>
+ <li><i>type</i> <b>[required]</b>
+ <p>The type of the component. Supported component types are
+ detailed below. Most components will define additional properties which
+ may be required or optional.</p></li>
+
+ <li><i>name</i> <b>[required]</b>
+ <p>The name of the component. Names are required to be unique
+ across the entire project.</p></li>
+
+ <li><i>parent</i> <b>[required]</b>
+ <p>The name of the logical parent of the component. Components are
+ organized into a logical tree to make it easier to navigate and organize
+ groups of components. The parents have no semantics as far as the project
+ build is concerned, however. Typically, the parent will be the main
+ component of the parent directory.</p>
+
+ <!-- FIXME: Should we make the parent optional, and default to parent
+ directories component? -->
+
+ <p>Components may reference the root pseudo component using '$ROOT' to
+ indicate they should logically be grouped at the top-level.</p>
+ </li>
+ </ul>
+
+ <p>Components may define the following properties:</p>
+ <ul>
+ <li><i>dependencies</i> <b>[optional]</b>
+ <p>If specified, a list of names of components which <i>must</i> be built
+ prior to this one. This should only be exactly those components which
+ produce some tool or source code required for building the
+ component.</p>
+
+ <p><em>NOTE:</em> Group and LibraryGroup components have no semantics for
+ the actual build, and are not allowed to specify dependencies.</p></li>
+ </ul>
+
+ <p>The following section lists the available component types, as well as the
+ properties which are associated with that component.</p>
+
+ <ul>
+ <li><i>type = Group</i>
+ <p>Group components exist purely to allow additional arbitrary structuring
+ of the logical components tree. For example, one might define a
+ "Libraries" group to hold all of the root library components.</p>
+
+ <p>Group components have no additionally properties.</p>
+ </li>
+
+ <li><i>type = Library</i>
+ <p>Library components define an individual library which should be built
+ from the source code in the component directory.</p>
+
+ <p>Components with this type use the following properties:</p>
+ <ul>
+ <li><i>library_name</i> <b>[optional]</b>
+ <p>If given, the name to use for the actual library file on disk. If
+ not given, the name is derived from the component name
+ itself.</p></li>
+
+ <li><i>required_libraries</i> <b>[optional]</b>
+ <p>If given, a list of the names of Library or LibraryGroup components
+ which must also be linked in whenever this library is used. That is,
+ the link time dependencies for this component. When tools are built,
+ the build system will include the transitive closure of
+ all <i>required_libraries</i> for the components the tool needs.</p></li>
+
+ <li><i>add_to_library_groups</i> <b>[optional]</b>
+ <p>If given, a list of the names of LibraryGroup components which this
+ component is also part of. This allows nesting groups of
+ components. For example, the <i>X86</i> target might define a library
+ group for all of the <i>X86</i> components. That library group might
+ then be included in the <i>all-targets</i> library group.</p></li>
+
+ <li><i>installed</i> <b>[optional]</b> <b>[boolean]</b>
+ <p>Whether this library is installed. Libraries that are not installed
+ are only reported by <tt>llvm-config</tt> when it is run as part of a
+ development directory.</p></li>
+ </ul>
+ </li>
+
+ <li><i>type = LibraryGroup</i>
+ <p>LibraryGroup components are a mechanism to allow easy definition of
+ useful sets of related components. In particular, we use them to easily
+ specify things like "all targets", or "all assembly printers".</p>
+
+ <p>Components with this type use the following properties:</p>
+ <ul>
+ <li><i>required_libraries</i> <b>[optional]</b>
+ <p>See the Library type for a description of this property.</p></li>
+
+ <li><i>add_to_library_groups</i> <b>[optional]</b>
+ <p>See the Library type for a description of this property.</p></li>
+ </ul>
+ </li>
+
+ <li><i>type = TargetGroup</i>
+ <p>TargetGroup components are an extension of LibraryGroups, specifically
+ for defining LLVM targets (which are handled specially in a few
+ places).</p>
+
+ <p>The name of the component should always be the name of the target.</p>
+
+ <p>Components with this type use the LibraryGroup properties in addition
+ to:</p>
+ <ul>
+ <li><i>has_asmparser</i> <b>[optional]</b> <b>[boolean]</b>
+ <p>Whether this target defines an assembly parser.</p></li>
+ <li><i>has_asmprinter</i> <b>[optional]</b> <b>[boolean]</b>
+ <p>Whether this target defines an assembly printer.</p></li>
+ <li><i>has_disassembler</i> <b>[optional]</b> <b>[boolean]</b>
+ <p>Whether this target defines a disassembler.</p></li>
+ <li><i>has_jit</i> <b>[optional]</b> <b>[boolean]</b>
+ <p>Whether this target supports JIT compilation.</p></li>
+ </ul>
+ </li>
+
+ <li><i>type = Tool</i>
+ <p>Tool components define standalone command line tools which should be
+ built from the source code in the component directory and linked.</p>
+
+ <p>Components with this type use the following properties:</p>
+ <ul>
+ <li><i>required_libraries</i> <b>[optional]</b>
+
+ <p>If given, a list of the names of Library or LibraryGroup components
+ which this tool is required to be linked with. <b>NOTE:</b> The values
+ should be the component names, which may not always match up with the
+ actual library names on disk.</p>
+
+ <p>Build systems are expected to properly include all of the libraries
+ required by the linked components (i.e., the transitive closer
+ of <em>required_libraries</em>).</p>
+
+ <p>Build systems are also expected to understand that those library
+ components must be built prior to linking -- they do not also need to
+ be listed under <i>dependencies</i>.</p></li>
+ </ul>
+ </li>
+
+ <li><i>type = BuildTool</i>
+ <p>BuildTool components are like Tool components, except that the tool is
+ supposed to be built for the platform where the build is running (instead
+ of that platform being targetted). Build systems are expected to handle
+ the fact that required libraries may need to be built for multiple
+ platforms in order to be able to link this tool.</p>
+
+ <p>BuildTool components currently use the exact same properties as Tool
+ components, the type distinction is only used to differentiate what the
+ tool is built for.</p>
+ </li>
+ </ul>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/LLVMBuild.txt b/docs/LLVMBuild.txt
new file mode 100644
index 00000000000..d5aea864ecd
--- /dev/null
+++ b/docs/LLVMBuild.txt
@@ -0,0 +1,21 @@
+;===- ./docs/LLVMBuild.txt -------------------------------------*- Conf -*--===;
+;
+; The LLVM Compiler Infrastructure
+;
+; This file is distributed under the University of Illinois Open Source
+; License. See LICENSE.TXT for details.
+;
+;===------------------------------------------------------------------------===;
+;
+; This is an LLVMBuild description file for the components in this subdirectory.
+;
+; For more information on the LLVMBuild system, please see:
+;
+; http://llvm.org/docs/LLVMBuild.html
+;
+;===------------------------------------------------------------------------===;
+
+[component_0]
+type = Group
+name = Docs
+parent = $ROOT
diff --git a/docs/LangRef.html b/docs/LangRef.html
new file mode 100644
index 00000000000..4daab592e9d
--- /dev/null
+++ b/docs/LangRef.html
@@ -0,0 +1,8731 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <title>LLVM Assembly Language Reference Manual</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <meta name="description"
+ content="LLVM Assembly Language Reference Manual.">
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>LLVM Language Reference Manual</h1>
+<ol>
+ <li><a href="#abstract">Abstract</a></li>
+ <li><a href="#introduction">Introduction</a></li>
+ <li><a href="#identifiers">Identifiers</a></li>
+ <li><a href="#highlevel">High Level Structure</a>
+ <ol>
+ <li><a href="#modulestructure">Module Structure</a></li>
+ <li><a href="#linkage">Linkage Types</a>
+ <ol>
+ <li><a href="#linkage_private">'<tt>private</tt>' Linkage</a></li>
+ <li><a href="#linkage_linker_private">'<tt>linker_private</tt>' Linkage</a></li>
+ <li><a href="#linkage_linker_private_weak">'<tt>linker_private_weak</tt>' Linkage</a></li>
+ <li><a href="#linkage_internal">'<tt>internal</tt>' Linkage</a></li>
+ <li><a href="#linkage_available_externally">'<tt>available_externally</tt>' Linkage</a></li>
+ <li><a href="#linkage_linkonce">'<tt>linkonce</tt>' Linkage</a></li>
+ <li><a href="#linkage_common">'<tt>common</tt>' Linkage</a></li>
+ <li><a href="#linkage_weak">'<tt>weak</tt>' Linkage</a></li>
+ <li><a href="#linkage_appending">'<tt>appending</tt>' Linkage</a></li>
+ <li><a href="#linkage_externweak">'<tt>extern_weak</tt>' Linkage</a></li>
+ <li><a href="#linkage_linkonce_odr">'<tt>linkonce_odr</tt>' Linkage</a></li>
+ <li><a href="#linkage_linkonce_odr_auto_hide">'<tt>linkonce_odr_auto_hide</tt>' Linkage</a></li>
+ <li><a href="#linkage_weak">'<tt>weak_odr</tt>' Linkage</a></li>
+ <li><a href="#linkage_external">'<tt>external</tt>' Linkage</a></li>
+ <li><a href="#linkage_dllimport">'<tt>dllimport</tt>' Linkage</a></li>
+ <li><a href="#linkage_dllexport">'<tt>dllexport</tt>' Linkage</a></li>
+ </ol>
+ </li>
+ <li><a href="#callingconv">Calling Conventions</a></li>
+ <li><a href="#namedtypes">Named Types</a></li>
+ <li><a href="#globalvars">Global Variables</a></li>
+ <li><a href="#functionstructure">Functions</a></li>
+ <li><a href="#aliasstructure">Aliases</a></li>
+ <li><a href="#namedmetadatastructure">Named Metadata</a></li>
+ <li><a href="#paramattrs">Parameter Attributes</a></li>
+ <li><a href="#fnattrs">Function Attributes</a></li>
+ <li><a href="#gc">Garbage Collector Names</a></li>
+ <li><a href="#moduleasm">Module-Level Inline Assembly</a></li>
+ <li><a href="#datalayout">Data Layout</a></li>
+ <li><a href="#pointeraliasing">Pointer Aliasing Rules</a></li>
+ <li><a href="#volatile">Volatile Memory Accesses</a></li>
+ <li><a href="#memmodel">Memory Model for Concurrent Operations</a></li>
+ <li><a href="#ordering">Atomic Memory Ordering Constraints</a></li>
+ </ol>
+ </li>
+ <li><a href="#typesystem">Type System</a>
+ <ol>
+ <li><a href="#t_classifications">Type Classifications</a></li>
+ <li><a href="#t_primitive">Primitive Types</a>
+ <ol>
+ <li><a href="#t_integer">Integer Type</a></li>
+ <li><a href="#t_floating">Floating Point Types</a></li>
+ <li><a href="#t_x86mmx">X86mmx Type</a></li>
+ <li><a href="#t_void">Void Type</a></li>
+ <li><a href="#t_label">Label Type</a></li>
+ <li><a href="#t_metadata">Metadata Type</a></li>
+ </ol>
+ </li>
+ <li><a href="#t_derived">Derived Types</a>
+ <ol>
+ <li><a href="#t_aggregate">Aggregate Types</a>
+ <ol>
+ <li><a href="#t_array">Array Type</a></li>
+ <li><a href="#t_struct">Structure Type</a></li>
+ <li><a href="#t_opaque">Opaque Structure Types</a></li>
+ <li><a href="#t_vector">Vector Type</a></li>
+ </ol>
+ </li>
+ <li><a href="#t_function">Function Type</a></li>
+ <li><a href="#t_pointer">Pointer Type</a></li>
+ </ol>
+ </li>
+ </ol>
+ </li>
+ <li><a href="#constants">Constants</a>
+ <ol>
+ <li><a href="#simpleconstants">Simple Constants</a></li>
+ <li><a href="#complexconstants">Complex Constants</a></li>
+ <li><a href="#globalconstants">Global Variable and Function Addresses</a></li>
+ <li><a href="#undefvalues">Undefined Values</a></li>
+ <li><a href="#poisonvalues">Poison Values</a></li>
+ <li><a href="#blockaddress">Addresses of Basic Blocks</a></li>
+ <li><a href="#constantexprs">Constant Expressions</a></li>
+ </ol>
+ </li>
+ <li><a href="#othervalues">Other Values</a>
+ <ol>
+ <li><a href="#inlineasm">Inline Assembler Expressions</a></li>
+ <li><a href="#metadata">Metadata Nodes and Metadata Strings</a>
+ <ol>
+ <li><a href="#tbaa">'<tt>tbaa</tt>' Metadata</a></li>
+ <li><a href="#fpmath">'<tt>fpmath</tt>' Metadata</a></li>
+ <li><a href="#range">'<tt>range</tt>' Metadata</a></li>
+ </ol>
+ </li>
+ </ol>
+ </li>
+ <li><a href="#module_flags">Module Flags Metadata</a>
+ <ol>
+ <li><a href="#objc_gc_flags">Objective-C Garbage Collection Module Flags Metadata</a></li>
+ </ol>
+ </li>
+ <li><a href="#intrinsic_globals">Intrinsic Global Variables</a>
+ <ol>
+ <li><a href="#intg_used">The '<tt>llvm.used</tt>' Global Variable</a></li>
+ <li><a href="#intg_compiler_used">The '<tt>llvm.compiler.used</tt>'
+ Global Variable</a></li>
+ <li><a href="#intg_global_ctors">The '<tt>llvm.global_ctors</tt>'
+ Global Variable</a></li>
+ <li><a href="#intg_global_dtors">The '<tt>llvm.global_dtors</tt>'
+ Global Variable</a></li>
+ </ol>
+ </li>
+ <li><a href="#instref">Instruction Reference</a>
+ <ol>
+ <li><a href="#terminators">Terminator Instructions</a>
+ <ol>
+ <li><a href="#i_ret">'<tt>ret</tt>' Instruction</a></li>
+ <li><a href="#i_br">'<tt>br</tt>' Instruction</a></li>
+ <li><a href="#i_switch">'<tt>switch</tt>' Instruction</a></li>
+ <li><a href="#i_indirectbr">'<tt>indirectbr</tt>' Instruction</a></li>
+ <li><a href="#i_invoke">'<tt>invoke</tt>' Instruction</a></li>
+ <li><a href="#i_resume">'<tt>resume</tt>' Instruction</a></li>
+ <li><a href="#i_unreachable">'<tt>unreachable</tt>' Instruction</a></li>
+ </ol>
+ </li>
+ <li><a href="#binaryops">Binary Operations</a>
+ <ol>
+ <li><a href="#i_add">'<tt>add</tt>' Instruction</a></li>
+ <li><a href="#i_fadd">'<tt>fadd</tt>' Instruction</a></li>
+ <li><a href="#i_sub">'<tt>sub</tt>' Instruction</a></li>
+ <li><a href="#i_fsub">'<tt>fsub</tt>' Instruction</a></li>
+ <li><a href="#i_mul">'<tt>mul</tt>' Instruction</a></li>
+ <li><a href="#i_fmul">'<tt>fmul</tt>' Instruction</a></li>
+ <li><a href="#i_udiv">'<tt>udiv</tt>' Instruction</a></li>
+ <li><a href="#i_sdiv">'<tt>sdiv</tt>' Instruction</a></li>
+ <li><a href="#i_fdiv">'<tt>fdiv</tt>' Instruction</a></li>
+ <li><a href="#i_urem">'<tt>urem</tt>' Instruction</a></li>
+ <li><a href="#i_srem">'<tt>srem</tt>' Instruction</a></li>
+ <li><a href="#i_frem">'<tt>frem</tt>' Instruction</a></li>
+ </ol>
+ </li>
+ <li><a href="#bitwiseops">Bitwise Binary Operations</a>
+ <ol>
+ <li><a href="#i_shl">'<tt>shl</tt>' Instruction</a></li>
+ <li><a href="#i_lshr">'<tt>lshr</tt>' Instruction</a></li>
+ <li><a href="#i_ashr">'<tt>ashr</tt>' Instruction</a></li>
+ <li><a href="#i_and">'<tt>and</tt>' Instruction</a></li>
+ <li><a href="#i_or">'<tt>or</tt>' Instruction</a></li>
+ <li><a href="#i_xor">'<tt>xor</tt>' Instruction</a></li>
+ </ol>
+ </li>
+ <li><a href="#vectorops">Vector Operations</a>
+ <ol>
+ <li><a href="#i_extractelement">'<tt>extractelement</tt>' Instruction</a></li>
+ <li><a href="#i_insertelement">'<tt>insertelement</tt>' Instruction</a></li>
+ <li><a href="#i_shufflevector">'<tt>shufflevector</tt>' Instruction</a></li>
+ </ol>
+ </li>
+ <li><a href="#aggregateops">Aggregate Operations</a>
+ <ol>
+ <li><a href="#i_extractvalue">'<tt>extractvalue</tt>' Instruction</a></li>
+ <li><a href="#i_insertvalue">'<tt>insertvalue</tt>' Instruction</a></li>
+ </ol>
+ </li>
+ <li><a href="#memoryops">Memory Access and Addressing Operations</a>
+ <ol>
+ <li><a href="#i_alloca">'<tt>alloca</tt>' Instruction</a></li>
+ <li><a href="#i_load">'<tt>load</tt>' Instruction</a></li>
+ <li><a href="#i_store">'<tt>store</tt>' Instruction</a></li>
+ <li><a href="#i_fence">'<tt>fence</tt>' Instruction</a></li>
+ <li><a href="#i_cmpxchg">'<tt>cmpxchg</tt>' Instruction</a></li>
+ <li><a href="#i_atomicrmw">'<tt>atomicrmw</tt>' Instruction</a></li>
+ <li><a href="#i_getelementptr">'<tt>getelementptr</tt>' Instruction</a></li>
+ </ol>
+ </li>
+ <li><a href="#convertops">Conversion Operations</a>
+ <ol>
+ <li><a href="#i_trunc">'<tt>trunc .. to</tt>' Instruction</a></li>
+ <li><a href="#i_zext">'<tt>zext .. to</tt>' Instruction</a></li>
+ <li><a href="#i_sext">'<tt>sext .. to</tt>' Instruction</a></li>
+ <li><a href="#i_fptrunc">'<tt>fptrunc .. to</tt>' Instruction</a></li>
+ <li><a href="#i_fpext">'<tt>fpext .. to</tt>' Instruction</a></li>
+ <li><a href="#i_fptoui">'<tt>fptoui .. to</tt>' Instruction</a></li>
+ <li><a href="#i_fptosi">'<tt>fptosi .. to</tt>' Instruction</a></li>
+ <li><a href="#i_uitofp">'<tt>uitofp .. to</tt>' Instruction</a></li>
+ <li><a href="#i_sitofp">'<tt>sitofp .. to</tt>' Instruction</a></li>
+ <li><a href="#i_ptrtoint">'<tt>ptrtoint .. to</tt>' Instruction</a></li>
+ <li><a href="#i_inttoptr">'<tt>inttoptr .. to</tt>' Instruction</a></li>
+ <li><a href="#i_bitcast">'<tt>bitcast .. to</tt>' Instruction</a></li>
+ </ol>
+ </li>
+ <li><a href="#otherops">Other Operations</a>
+ <ol>
+ <li><a href="#i_icmp">'<tt>icmp</tt>' Instruction</a></li>
+ <li><a href="#i_fcmp">'<tt>fcmp</tt>' Instruction</a></li>
+ <li><a href="#i_phi">'<tt>phi</tt>' Instruction</a></li>
+ <li><a href="#i_select">'<tt>select</tt>' Instruction</a></li>
+ <li><a href="#i_call">'<tt>call</tt>' Instruction</a></li>
+ <li><a href="#i_va_arg">'<tt>va_arg</tt>' Instruction</a></li>
+ <li><a href="#i_landingpad">'<tt>landingpad</tt>' Instruction</a></li>
+ </ol>
+ </li>
+ </ol>
+ </li>
+ <li><a href="#intrinsics">Intrinsic Functions</a>
+ <ol>
+ <li><a href="#int_varargs">Variable Argument Handling Intrinsics</a>
+ <ol>
+ <li><a href="#int_va_start">'<tt>llvm.va_start</tt>' Intrinsic</a></li>
+ <li><a href="#int_va_end">'<tt>llvm.va_end</tt>' Intrinsic</a></li>
+ <li><a href="#int_va_copy">'<tt>llvm.va_copy</tt>' Intrinsic</a></li>
+ </ol>
+ </li>
+ <li><a href="#int_gc">Accurate Garbage Collection Intrinsics</a>
+ <ol>
+ <li><a href="#int_gcroot">'<tt>llvm.gcroot</tt>' Intrinsic</a></li>
+ <li><a href="#int_gcread">'<tt>llvm.gcread</tt>' Intrinsic</a></li>
+ <li><a href="#int_gcwrite">'<tt>llvm.gcwrite</tt>' Intrinsic</a></li>
+ </ol>
+ </li>
+ <li><a href="#int_codegen">Code Generator Intrinsics</a>
+ <ol>
+ <li><a href="#int_returnaddress">'<tt>llvm.returnaddress</tt>' Intrinsic</a></li>
+ <li><a href="#int_frameaddress">'<tt>llvm.frameaddress</tt>' Intrinsic</a></li>
+ <li><a href="#int_stacksave">'<tt>llvm.stacksave</tt>' Intrinsic</a></li>
+ <li><a href="#int_stackrestore">'<tt>llvm.stackrestore</tt>' Intrinsic</a></li>
+ <li><a href="#int_prefetch">'<tt>llvm.prefetch</tt>' Intrinsic</a></li>
+ <li><a href="#int_pcmarker">'<tt>llvm.pcmarker</tt>' Intrinsic</a></li>
+ <li><a href="#int_readcyclecounter">'<tt>llvm.readcyclecounter</tt>' Intrinsic</a></li>
+ </ol>
+ </li>
+ <li><a href="#int_libc">Standard C Library Intrinsics</a>
+ <ol>
+ <li><a href="#int_memcpy">'<tt>llvm.memcpy.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_memmove">'<tt>llvm.memmove.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_memset">'<tt>llvm.memset.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_sqrt">'<tt>llvm.sqrt.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_powi">'<tt>llvm.powi.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_sin">'<tt>llvm.sin.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_cos">'<tt>llvm.cos.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_pow">'<tt>llvm.pow.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_exp">'<tt>llvm.exp.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_log">'<tt>llvm.log.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_fma">'<tt>llvm.fma.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_fabs">'<tt>llvm.fabs.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_floor">'<tt>llvm.floor.*</tt>' Intrinsic</a></li>
+ </ol>
+ </li>
+ <li><a href="#int_manip">Bit Manipulation Intrinsics</a>
+ <ol>
+ <li><a href="#int_bswap">'<tt>llvm.bswap.*</tt>' Intrinsics</a></li>
+ <li><a href="#int_ctpop">'<tt>llvm.ctpop.*</tt>' Intrinsic </a></li>
+ <li><a href="#int_ctlz">'<tt>llvm.ctlz.*</tt>' Intrinsic </a></li>
+ <li><a href="#int_cttz">'<tt>llvm.cttz.*</tt>' Intrinsic </a></li>
+ </ol>
+ </li>
+ <li><a href="#int_overflow">Arithmetic with Overflow Intrinsics</a>
+ <ol>
+ <li><a href="#int_sadd_overflow">'<tt>llvm.sadd.with.overflow.*</tt> Intrinsics</a></li>
+ <li><a href="#int_uadd_overflow">'<tt>llvm.uadd.with.overflow.*</tt> Intrinsics</a></li>
+ <li><a href="#int_ssub_overflow">'<tt>llvm.ssub.with.overflow.*</tt> Intrinsics</a></li>
+ <li><a href="#int_usub_overflow">'<tt>llvm.usub.with.overflow.*</tt> Intrinsics</a></li>
+ <li><a href="#int_smul_overflow">'<tt>llvm.smul.with.overflow.*</tt> Intrinsics</a></li>
+ <li><a href="#int_umul_overflow">'<tt>llvm.umul.with.overflow.*</tt> Intrinsics</a></li>
+ </ol>
+ </li>
+ <li><a href="#spec_arithmetic">Specialised Arithmetic Intrinsics</a>
+ <ol>
+ <li><a href="#fmuladd">'<tt>llvm.fmuladd</tt> Intrinsic</a></li>
+ </ol>
+ </li>
+ <li><a href="#int_fp16">Half Precision Floating Point Intrinsics</a>
+ <ol>
+ <li><a href="#int_convert_to_fp16">'<tt>llvm.convert.to.fp16</tt>' Intrinsic</a></li>
+ <li><a href="#int_convert_from_fp16">'<tt>llvm.convert.from.fp16</tt>' Intrinsic</a></li>
+ </ol>
+ </li>
+ <li><a href="#int_debugger">Debugger intrinsics</a></li>
+ <li><a href="#int_eh">Exception Handling intrinsics</a></li>
+ <li><a href="#int_trampoline">Trampoline Intrinsics</a>
+ <ol>
+ <li><a href="#int_it">'<tt>llvm.init.trampoline</tt>' Intrinsic</a></li>
+ <li><a href="#int_at">'<tt>llvm.adjust.trampoline</tt>' Intrinsic</a></li>
+ </ol>
+ </li>
+ <li><a href="#int_memorymarkers">Memory Use Markers</a>
+ <ol>
+ <li><a href="#int_lifetime_start">'<tt>llvm.lifetime.start</tt>' Intrinsic</a></li>
+ <li><a href="#int_lifetime_end">'<tt>llvm.lifetime.end</tt>' Intrinsic</a></li>
+ <li><a href="#int_invariant_start">'<tt>llvm.invariant.start</tt>' Intrinsic</a></li>
+ <li><a href="#int_invariant_end">'<tt>llvm.invariant.end</tt>' Intrinsic</a></li>
+ </ol>
+ </li>
+ <li><a href="#int_general">General intrinsics</a>
+ <ol>
+ <li><a href="#int_var_annotation">
+ '<tt>llvm.var.annotation</tt>' Intrinsic</a></li>
+ <li><a href="#int_annotation">
+ '<tt>llvm.annotation.*</tt>' Intrinsic</a></li>
+ <li><a href="#int_trap">
+ '<tt>llvm.trap</tt>' Intrinsic</a></li>
+ <li><a href="#int_debugtrap">
+ '<tt>llvm.debugtrap</tt>' Intrinsic</a></li>
+ <li><a href="#int_stackprotector">
+ '<tt>llvm.stackprotector</tt>' Intrinsic</a></li>
+ <li><a href="#int_objectsize">
+ '<tt>llvm.objectsize</tt>' Intrinsic</a></li>
+ <li><a href="#int_expect">
+ '<tt>llvm.expect</tt>' Intrinsic</a></li>
+ <li><a href="#int_donothing">
+ '<tt>llvm.donothing</tt>' Intrinsic</a></li>
+ </ol>
+ </li>
+ </ol>
+ </li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:vadve@cs.uiuc.edu">Vikram Adve</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="abstract">Abstract</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This document is a reference manual for the LLVM assembly language. LLVM is
+ a Static Single Assignment (SSA) based representation that provides type
+ safety, low-level operations, flexibility, and the capability of representing
+ 'all' high-level languages cleanly. It is the common code representation
+ used throughout all phases of the LLVM compilation strategy.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="introduction">Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The LLVM code representation is designed to be used in three different forms:
+ as an in-memory compiler IR, as an on-disk bitcode representation (suitable
+ for fast loading by a Just-In-Time compiler), and as a human readable
+ assembly language representation. This allows LLVM to provide a powerful
+ intermediate representation for efficient compiler transformations and
+ analysis, while providing a natural means to debug and visualize the
+ transformations. The three different forms of LLVM are all equivalent. This
+ document describes the human readable representation and notation.</p>
+
+<p>The LLVM representation aims to be light-weight and low-level while being
+ expressive, typed, and extensible at the same time. It aims to be a
+ "universal IR" of sorts, by being at a low enough level that high-level ideas
+ may be cleanly mapped to it (similar to how microprocessors are "universal
+ IR's", allowing many source languages to be mapped to them). By providing
+ type information, LLVM can be used as the target of optimizations: for
+ example, through pointer analysis, it can be proven that a C automatic
+ variable is never accessed outside of the current function, allowing it to
+ be promoted to a simple SSA value instead of a memory location.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="wellformed">Well-Formedness</a>
+</h4>
+
+<div>
+
+<p>It is important to note that this document describes 'well formed' LLVM
+ assembly language. There is a difference between what the parser accepts and
+ what is considered 'well formed'. For example, the following instruction is
+ syntactically okay, but not well formed:</p>
+
+<pre class="doc_code">
+%x = <a href="#i_add">add</a> i32 1, %x
+</pre>
+
+<p>because the definition of <tt>%x</tt> does not dominate all of its uses. The
+ LLVM infrastructure provides a verification pass that may be used to verify
+ that an LLVM module is well formed. This pass is automatically run by the
+ parser after parsing input assembly and by the optimizer before it outputs
+ bitcode. The violations pointed out by the verifier pass indicate bugs in
+ transformation passes or input to the parser.</p>
+
+</div>
+
+</div>
+
+<!-- Describe the typesetting conventions here. -->
+
+<!-- *********************************************************************** -->
+<h2><a name="identifiers">Identifiers</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>LLVM identifiers come in two basic types: global and local. Global
+ identifiers (functions, global variables) begin with the <tt>'@'</tt>
+ character. Local identifiers (register names, types) begin with
+ the <tt>'%'</tt> character. Additionally, there are three different formats
+ for identifiers, for different purposes:</p>
+
+<ol>
+ <li>Named values are represented as a string of characters with their prefix.
+ For example, <tt>%foo</tt>, <tt>@DivisionByZero</tt>,
+ <tt>%a.really.long.identifier</tt>. The actual regular expression used is
+ '<tt>[%@][a-zA-Z$._][a-zA-Z$._0-9]*</tt>'. Identifiers which require
+ other characters in their names can be surrounded with quotes. Special
+ characters may be escaped using <tt>"\xx"</tt> where <tt>xx</tt> is the
+ ASCII code for the character in hexadecimal. In this way, any character
+ can be used in a name value, even quotes themselves.</li>
+
+ <li>Unnamed values are represented as an unsigned numeric value with their
+ prefix. For example, <tt>%12</tt>, <tt>@2</tt>, <tt>%44</tt>.</li>
+
+ <li>Constants, which are described in a <a href="#constants">section about
+ constants</a>, below.</li>
+</ol>
+
+<p>LLVM requires that values start with a prefix for two reasons: Compilers
+ don't need to worry about name clashes with reserved words, and the set of
+ reserved words may be expanded in the future without penalty. Additionally,
+ unnamed identifiers allow a compiler to quickly come up with a temporary
+ variable without having to avoid symbol table conflicts.</p>
+
+<p>Reserved words in LLVM are very similar to reserved words in other
+ languages. There are keywords for different opcodes
+ ('<tt><a href="#i_add">add</a></tt>',
+ '<tt><a href="#i_bitcast">bitcast</a></tt>',
+ '<tt><a href="#i_ret">ret</a></tt>', etc...), for primitive type names
+ ('<tt><a href="#t_void">void</a></tt>',
+ '<tt><a href="#t_primitive">i32</a></tt>', etc...), and others. These
+ reserved words cannot conflict with variable names, because none of them
+ start with a prefix character (<tt>'%'</tt> or <tt>'@'</tt>).</p>
+
+<p>Here is an example of LLVM code to multiply the integer variable
+ '<tt>%X</tt>' by 8:</p>
+
+<p>The easy way:</p>
+
+<pre class="doc_code">
+%result = <a href="#i_mul">mul</a> i32 %X, 8
+</pre>
+
+<p>After strength reduction:</p>
+
+<pre class="doc_code">
+%result = <a href="#i_shl">shl</a> i32 %X, i8 3
+</pre>
+
+<p>And the hard way:</p>
+
+<pre class="doc_code">
+%0 = <a href="#i_add">add</a> i32 %X, %X <i>; yields {i32}:%0</i>
+%1 = <a href="#i_add">add</a> i32 %0, %0 <i>; yields {i32}:%1</i>
+%result = <a href="#i_add">add</a> i32 %1, %1
+</pre>
+
+<p>This last way of multiplying <tt>%X</tt> by 8 illustrates several important
+ lexical features of LLVM:</p>
+
+<ol>
+ <li>Comments are delimited with a '<tt>;</tt>' and go until the end of
+ line.</li>
+
+ <li>Unnamed temporaries are created when the result of a computation is not
+ assigned to a named value.</li>
+
+ <li>Unnamed temporaries are numbered sequentially</li>
+</ol>
+
+<p>It also shows a convention that we follow in this document. When
+ demonstrating instructions, we will follow an instruction with a comment that
+ defines the type and name of value produced. Comments are shown in italic
+ text.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="highlevel">High Level Structure</a></h2>
+<!-- *********************************************************************** -->
+<div>
+<!-- ======================================================================= -->
+<h3>
+ <a name="modulestructure">Module Structure</a>
+</h3>
+
+<div>
+
+<p>LLVM programs are composed of <tt>Module</tt>s, each of which is a
+ translation unit of the input programs. Each module consists of functions,
+ global variables, and symbol table entries. Modules may be combined together
+ with the LLVM linker, which merges function (and global variable)
+ definitions, resolves forward declarations, and merges symbol table
+ entries. Here is an example of the "hello world" module:</p>
+
+<pre class="doc_code">
+<i>; Declare the string constant as a global constant.</i>&nbsp;
+<a href="#identifiers">@.str</a> = <a href="#linkage_private">private</a>&nbsp;<a href="#globalvars">unnamed_addr</a>&nbsp;<a href="#globalvars">constant</a>&nbsp;<a href="#t_array">[13 x i8]</a> c"hello world\0A\00"&nbsp;
+
+<i>; External declaration of the puts function</i>&nbsp;
+<a href="#functionstructure">declare</a> i32 @puts(i8* <a href="#nocapture">nocapture</a>) <a href="#fnattrs">nounwind</a>&nbsp;
+
+<i>; Definition of main function</i>
+define i32 @main() { <i>; i32()* </i>&nbsp;
+ <i>; Convert [13 x i8]* to i8 *...</i>&nbsp;
+ %cast210 = <a href="#i_getelementptr">getelementptr</a> [13 x i8]* @.str, i64 0, i64 0
+
+ <i>; Call puts function to write out the string to stdout.</i>&nbsp;
+ <a href="#i_call">call</a> i32 @puts(i8* %cast210)
+ <a href="#i_ret">ret</a> i32 0&nbsp;
+}
+
+<i>; Named metadata</i>
+!1 = metadata !{i32 42}
+!foo = !{!1, null}
+</pre>
+
+<p>This example is made up of a <a href="#globalvars">global variable</a> named
+ "<tt>.str</tt>", an external declaration of the "<tt>puts</tt>" function,
+ a <a href="#functionstructure">function definition</a> for
+ "<tt>main</tt>" and <a href="#namedmetadatastructure">named metadata</a>
+ "<tt>foo</tt>".</p>
+
+<p>In general, a module is made up of a list of global values (where both
+ functions and global variables are global values). Global values are
+ represented by a pointer to a memory location (in this case, a pointer to an
+ array of char, and a pointer to a function), and have one of the
+ following <a href="#linkage">linkage types</a>.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="linkage">Linkage Types</a>
+</h3>
+
+<div>
+
+<p>All Global Variables and Functions have one of the following types of
+ linkage:</p>
+
+<dl>
+ <dt><tt><b><a name="linkage_private">private</a></b></tt></dt>
+ <dd>Global values with "<tt>private</tt>" linkage are only directly accessible
+ by objects in the current module. In particular, linking code into a
+ module with an private global value may cause the private to be renamed as
+ necessary to avoid collisions. Because the symbol is private to the
+ module, all references can be updated. This doesn't show up in any symbol
+ table in the object file.</dd>
+
+ <dt><tt><b><a name="linkage_linker_private">linker_private</a></b></tt></dt>
+ <dd>Similar to <tt>private</tt>, but the symbol is passed through the
+ assembler and evaluated by the linker. Unlike normal strong symbols, they
+ are removed by the linker from the final linked image (executable or
+ dynamic library).</dd>
+
+ <dt><tt><b><a name="linkage_linker_private_weak">linker_private_weak</a></b></tt></dt>
+ <dd>Similar to "<tt>linker_private</tt>", but the symbol is weak. Note that
+ <tt>linker_private_weak</tt> symbols are subject to coalescing by the
+ linker. The symbols are removed by the linker from the final linked image
+ (executable or dynamic library).</dd>
+
+ <dt><tt><b><a name="linkage_internal">internal</a></b></tt></dt>
+ <dd>Similar to private, but the value shows as a local symbol
+ (<tt>STB_LOCAL</tt> in the case of ELF) in the object file. This
+ corresponds to the notion of the '<tt>static</tt>' keyword in C.</dd>
+
+ <dt><tt><b><a name="linkage_available_externally">available_externally</a></b></tt></dt>
+ <dd>Globals with "<tt>available_externally</tt>" linkage are never emitted
+ into the object file corresponding to the LLVM module. They exist to
+ allow inlining and other optimizations to take place given knowledge of
+ the definition of the global, which is known to be somewhere outside the
+ module. Globals with <tt>available_externally</tt> linkage are allowed to
+ be discarded at will, and are otherwise the same as <tt>linkonce_odr</tt>.
+ This linkage type is only allowed on definitions, not declarations.</dd>
+
+ <dt><tt><b><a name="linkage_linkonce">linkonce</a></b></tt></dt>
+ <dd>Globals with "<tt>linkonce</tt>" linkage are merged with other globals of
+ the same name when linkage occurs. This can be used to implement
+ some forms of inline functions, templates, or other code which must be
+ generated in each translation unit that uses it, but where the body may
+ be overridden with a more definitive definition later. Unreferenced
+ <tt>linkonce</tt> globals are allowed to be discarded. Note that
+ <tt>linkonce</tt> linkage does not actually allow the optimizer to
+ inline the body of this function into callers because it doesn't know if
+ this definition of the function is the definitive definition within the
+ program or whether it will be overridden by a stronger definition.
+ To enable inlining and other optimizations, use "<tt>linkonce_odr</tt>"
+ linkage.</dd>
+
+ <dt><tt><b><a name="linkage_weak">weak</a></b></tt></dt>
+ <dd>"<tt>weak</tt>" linkage has the same merging semantics as
+ <tt>linkonce</tt> linkage, except that unreferenced globals with
+ <tt>weak</tt> linkage may not be discarded. This is used for globals that
+ are declared "weak" in C source code.</dd>
+
+ <dt><tt><b><a name="linkage_common">common</a></b></tt></dt>
+ <dd>"<tt>common</tt>" linkage is most similar to "<tt>weak</tt>" linkage, but
+ they are used for tentative definitions in C, such as "<tt>int X;</tt>" at
+ global scope.
+ Symbols with "<tt>common</tt>" linkage are merged in the same way as
+ <tt>weak symbols</tt>, and they may not be deleted if unreferenced.
+ <tt>common</tt> symbols may not have an explicit section,
+ must have a zero initializer, and may not be marked '<a
+ href="#globalvars"><tt>constant</tt></a>'. Functions and aliases may not
+ have common linkage.</dd>
+
+
+ <dt><tt><b><a name="linkage_appending">appending</a></b></tt></dt>
+ <dd>"<tt>appending</tt>" linkage may only be applied to global variables of
+ pointer to array type. When two global variables with appending linkage
+ are linked together, the two global arrays are appended together. This is
+ the LLVM, typesafe, equivalent of having the system linker append together
+ "sections" with identical names when .o files are linked.</dd>
+
+ <dt><tt><b><a name="linkage_externweak">extern_weak</a></b></tt></dt>
+ <dd>The semantics of this linkage follow the ELF object file model: the symbol
+ is weak until linked, if not linked, the symbol becomes null instead of
+ being an undefined reference.</dd>
+
+ <dt><tt><b><a name="linkage_linkonce_odr">linkonce_odr</a></b></tt></dt>
+ <dt><tt><b><a name="linkage_weak_odr">weak_odr</a></b></tt></dt>
+ <dd>Some languages allow differing globals to be merged, such as two functions
+ with different semantics. Other languages, such as <tt>C++</tt>, ensure
+ that only equivalent globals are ever merged (the "one definition rule"
+ &mdash; "ODR"). Such languages can use the <tt>linkonce_odr</tt>
+ and <tt>weak_odr</tt> linkage types to indicate that the global will only
+ be merged with equivalent globals. These linkage types are otherwise the
+ same as their non-<tt>odr</tt> versions.</dd>
+
+ <dt><tt><b><a name="linkage_linkonce_odr_auto_hide">linkonce_odr_auto_hide</a></b></tt></dt>
+ <dd>Similar to "<tt>linkonce_odr</tt>", but nothing in the translation unit
+ takes the address of this definition. For instance, functions that had an
+ inline definition, but the compiler decided not to inline it.
+ <tt>linkonce_odr_auto_hide</tt> may have only <tt>default</tt> visibility.
+ The symbols are removed by the linker from the final linked image
+ (executable or dynamic library).</dd>
+
+ <dt><tt><b><a name="linkage_external">external</a></b></tt></dt>
+ <dd>If none of the above identifiers are used, the global is externally
+ visible, meaning that it participates in linkage and can be used to
+ resolve external symbol references.</dd>
+</dl>
+
+<p>The next two types of linkage are targeted for Microsoft Windows platform
+ only. They are designed to support importing (exporting) symbols from (to)
+ DLLs (Dynamic Link Libraries).</p>
+
+<dl>
+ <dt><tt><b><a name="linkage_dllimport">dllimport</a></b></tt></dt>
+ <dd>"<tt>dllimport</tt>" linkage causes the compiler to reference a function
+ or variable via a global pointer to a pointer that is set up by the DLL
+ exporting the symbol. On Microsoft Windows targets, the pointer name is
+ formed by combining <code>__imp_</code> and the function or variable
+ name.</dd>
+
+ <dt><tt><b><a name="linkage_dllexport">dllexport</a></b></tt></dt>
+ <dd>"<tt>dllexport</tt>" linkage causes the compiler to provide a global
+ pointer to a pointer in a DLL, so that it can be referenced with the
+ <tt>dllimport</tt> attribute. On Microsoft Windows targets, the pointer
+ name is formed by combining <code>__imp_</code> and the function or
+ variable name.</dd>
+</dl>
+
+<p>For example, since the "<tt>.LC0</tt>" variable is defined to be internal, if
+ another module defined a "<tt>.LC0</tt>" variable and was linked with this
+ one, one of the two would be renamed, preventing a collision. Since
+ "<tt>main</tt>" and "<tt>puts</tt>" are external (i.e., lacking any linkage
+ declarations), they are accessible outside of the current module.</p>
+
+<p>It is illegal for a function <i>declaration</i> to have any linkage type
+ other than <tt>external</tt>, <tt>dllimport</tt>
+ or <tt>extern_weak</tt>.</p>
+
+<p>Aliases can have only <tt>external</tt>, <tt>internal</tt>, <tt>weak</tt>
+ or <tt>weak_odr</tt> linkages.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="callingconv">Calling Conventions</a>
+</h3>
+
+<div>
+
+<p>LLVM <a href="#functionstructure">functions</a>, <a href="#i_call">calls</a>
+ and <a href="#i_invoke">invokes</a> can all have an optional calling
+ convention specified for the call. The calling convention of any pair of
+ dynamic caller/callee must match, or the behavior of the program is
+ undefined. The following calling conventions are supported by LLVM, and more
+ may be added in the future:</p>
+
+<dl>
+ <dt><b>"<tt>ccc</tt>" - The C calling convention</b>:</dt>
+ <dd>This calling convention (the default if no other calling convention is
+ specified) matches the target C calling conventions. This calling
+ convention supports varargs function calls and tolerates some mismatch in
+ the declared prototype and implemented declaration of the function (as
+ does normal C).</dd>
+
+ <dt><b>"<tt>fastcc</tt>" - The fast calling convention</b>:</dt>
+ <dd>This calling convention attempts to make calls as fast as possible
+ (e.g. by passing things in registers). This calling convention allows the
+ target to use whatever tricks it wants to produce fast code for the
+ target, without having to conform to an externally specified ABI
+ (Application Binary Interface).
+ <a href="CodeGenerator.html#tailcallopt">Tail calls can only be optimized
+ when this or the GHC convention is used.</a> This calling convention
+ does not support varargs and requires the prototype of all callees to
+ exactly match the prototype of the function definition.</dd>
+
+ <dt><b>"<tt>coldcc</tt>" - The cold calling convention</b>:</dt>
+ <dd>This calling convention attempts to make code in the caller as efficient
+ as possible under the assumption that the call is not commonly executed.
+ As such, these calls often preserve all registers so that the call does
+ not break any live ranges in the caller side. This calling convention
+ does not support varargs and requires the prototype of all callees to
+ exactly match the prototype of the function definition.</dd>
+
+ <dt><b>"<tt>cc <em>10</em></tt>" - GHC convention</b>:</dt>
+ <dd>This calling convention has been implemented specifically for use by the
+ <a href="http://www.haskell.org/ghc">Glasgow Haskell Compiler (GHC)</a>.
+ It passes everything in registers, going to extremes to achieve this by
+ disabling callee save registers. This calling convention should not be
+ used lightly but only for specific situations such as an alternative to
+ the <em>register pinning</em> performance technique often used when
+ implementing functional programming languages.At the moment only X86
+ supports this convention and it has the following limitations:
+ <ul>
+ <li>On <em>X86-32</em> only supports up to 4 bit type parameters. No
+ floating point types are supported.</li>
+ <li>On <em>X86-64</em> only supports up to 10 bit type parameters and
+ 6 floating point parameters.</li>
+ </ul>
+ This calling convention supports
+ <a href="CodeGenerator.html#tailcallopt">tail call optimization</a> but
+ requires both the caller and callee are using it.
+ </dd>
+
+ <dt><b>"<tt>cc &lt;<em>n</em>&gt;</tt>" - Numbered convention</b>:</dt>
+ <dd>Any calling convention may be specified by number, allowing
+ target-specific calling conventions to be used. Target specific calling
+ conventions start at 64.</dd>
+</dl>
+
+<p>More calling conventions can be added/defined on an as-needed basis, to
+ support Pascal conventions or any other well-known target-independent
+ convention.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="visibility">Visibility Styles</a>
+</h3>
+
+<div>
+
+<p>All Global Variables and Functions have one of the following visibility
+ styles:</p>
+
+<dl>
+ <dt><b>"<tt>default</tt>" - Default style</b>:</dt>
+ <dd>On targets that use the ELF object file format, default visibility means
+ that the declaration is visible to other modules and, in shared libraries,
+ means that the declared entity may be overridden. On Darwin, default
+ visibility means that the declaration is visible to other modules. Default
+ visibility corresponds to "external linkage" in the language.</dd>
+
+ <dt><b>"<tt>hidden</tt>" - Hidden style</b>:</dt>
+ <dd>Two declarations of an object with hidden visibility refer to the same
+ object if they are in the same shared object. Usually, hidden visibility
+ indicates that the symbol will not be placed into the dynamic symbol
+ table, so no other module (executable or shared library) can reference it
+ directly.</dd>
+
+ <dt><b>"<tt>protected</tt>" - Protected style</b>:</dt>
+ <dd>On ELF, protected visibility indicates that the symbol will be placed in
+ the dynamic symbol table, but that references within the defining module
+ will bind to the local symbol. That is, the symbol cannot be overridden by
+ another module.</dd>
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="namedtypes">Named Types</a>
+</h3>
+
+<div>
+
+<p>LLVM IR allows you to specify name aliases for certain types. This can make
+ it easier to read the IR and make the IR more condensed (particularly when
+ recursive types are involved). An example of a name specification is:</p>
+
+<pre class="doc_code">
+%mytype = type { %mytype*, i32 }
+</pre>
+
+<p>You may give a name to any <a href="#typesystem">type</a> except
+ "<a href="#t_void">void</a>". Type name aliases may be used anywhere a type
+ is expected with the syntax "%mytype".</p>
+
+<p>Note that type names are aliases for the structural type that they indicate,
+ and that you can therefore specify multiple names for the same type. This
+ often leads to confusing behavior when dumping out a .ll file. Since LLVM IR
+ uses structural typing, the name is not part of the type. When printing out
+ LLVM IR, the printer will pick <em>one name</em> to render all types of a
+ particular shape. This means that if you have code where two different
+ source types end up having the same LLVM type, that the dumper will sometimes
+ print the "wrong" or unexpected type. This is an important design point and
+ isn't going to change.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="globalvars">Global Variables</a>
+</h3>
+
+<div>
+
+<p>Global variables define regions of memory allocated at compilation time
+ instead of run-time. Global variables may optionally be initialized, may
+ have an explicit section to be placed in, and may have an optional explicit
+ alignment specified.</p>
+
+<p>A variable may be defined as <tt>thread_local</tt>, which
+ means that it will not be shared by threads (each thread will have a
+ separated copy of the variable). Not all targets support thread-local
+ variables. Optionally, a TLS model may be specified:</p>
+
+<dl>
+ <dt><b><tt>localdynamic</tt></b>:</dt>
+ <dd>For variables that are only used within the current shared library.</dd>
+
+ <dt><b><tt>initialexec</tt></b>:</dt>
+ <dd>For variables in modules that will not be loaded dynamically.</dd>
+
+ <dt><b><tt>localexec</tt></b>:</dt>
+ <dd>For variables defined in the executable and only used within it.</dd>
+</dl>
+
+<p>The models correspond to the ELF TLS models; see
+ <a href="http://people.redhat.com/drepper/tls.pdf">ELF
+ Handling For Thread-Local Storage</a> for more information on under which
+ circumstances the different models may be used. The target may choose a
+ different TLS model if the specified model is not supported, or if a better
+ choice of model can be made.</p>
+
+<p>A variable may be defined as a global
+ "constant," which indicates that the contents of the variable
+ will <b>never</b> be modified (enabling better optimization, allowing the
+ global data to be placed in the read-only section of an executable, etc).
+ Note that variables that need runtime initialization cannot be marked
+ "constant" as there is a store to the variable.</p>
+
+<p>LLVM explicitly allows <em>declarations</em> of global variables to be marked
+ constant, even if the final definition of the global is not. This capability
+ can be used to enable slightly better optimization of the program, but
+ requires the language definition to guarantee that optimizations based on the
+ 'constantness' are valid for the translation units that do not include the
+ definition.</p>
+
+<p>As SSA values, global variables define pointer values that are in scope
+ (i.e. they dominate) all basic blocks in the program. Global variables
+ always define a pointer to their "content" type because they describe a
+ region of memory, and all memory objects in LLVM are accessed through
+ pointers.</p>
+
+<p>Global variables can be marked with <tt>unnamed_addr</tt> which indicates
+ that the address is not significant, only the content. Constants marked
+ like this can be merged with other constants if they have the same
+ initializer. Note that a constant with significant address <em>can</em>
+ be merged with a <tt>unnamed_addr</tt> constant, the result being a
+ constant whose address is significant.</p>
+
+<p>A global variable may be declared to reside in a target-specific numbered
+ address space. For targets that support them, address spaces may affect how
+ optimizations are performed and/or what target instructions are used to
+ access the variable. The default address space is zero. The address space
+ qualifier must precede any other attributes.</p>
+
+<p>LLVM allows an explicit section to be specified for globals. If the target
+ supports it, it will emit globals to the section specified.</p>
+
+<p>An explicit alignment may be specified for a global, which must be a power
+ of 2. If not present, or if the alignment is set to zero, the alignment of
+ the global is set by the target to whatever it feels convenient. If an
+ explicit alignment is specified, the global is forced to have exactly that
+ alignment. Targets and optimizers are not allowed to over-align the global
+ if the global has an assigned section. In this case, the extra alignment
+ could be observable: for example, code could assume that the globals are
+ densely packed in their section and try to iterate over them as an array,
+ alignment padding would break this iteration.</p>
+
+<p>For example, the following defines a global in a numbered address space with
+ an initializer, section, and alignment:</p>
+
+<pre class="doc_code">
+@G = addrspace(5) constant float 1.0, section "foo", align 4
+</pre>
+
+<p>The following example defines a thread-local global with
+ the <tt>initialexec</tt> TLS model:</p>
+
+<pre class="doc_code">
+@G = thread_local(initialexec) global i32 0, align 4
+</pre>
+
+</div>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="functionstructure">Functions</a>
+</h3>
+
+<div>
+
+<p>LLVM function definitions consist of the "<tt>define</tt>" keyword, an
+ optional <a href="#linkage">linkage type</a>, an optional
+ <a href="#visibility">visibility style</a>, an optional
+ <a href="#callingconv">calling convention</a>,
+ an optional <tt>unnamed_addr</tt> attribute, a return type, an optional
+ <a href="#paramattrs">parameter attribute</a> for the return type, a function
+ name, a (possibly empty) argument list (each with optional
+ <a href="#paramattrs">parameter attributes</a>), optional
+ <a href="#fnattrs">function attributes</a>, an optional section, an optional
+ alignment, an optional <a href="#gc">garbage collector name</a>, an opening
+ curly brace, a list of basic blocks, and a closing curly brace.</p>
+
+<p>LLVM function declarations consist of the "<tt>declare</tt>" keyword, an
+ optional <a href="#linkage">linkage type</a>, an optional
+ <a href="#visibility">visibility style</a>, an optional
+ <a href="#callingconv">calling convention</a>,
+ an optional <tt>unnamed_addr</tt> attribute, a return type, an optional
+ <a href="#paramattrs">parameter attribute</a> for the return type, a function
+ name, a possibly empty list of arguments, an optional alignment, and an
+ optional <a href="#gc">garbage collector name</a>.</p>
+
+<p>A function definition contains a list of basic blocks, forming the CFG
+ (Control Flow Graph) for the function. Each basic block may optionally start
+ with a label (giving the basic block a symbol table entry), contains a list
+ of instructions, and ends with a <a href="#terminators">terminator</a>
+ instruction (such as a branch or function return).</p>
+
+<p>The first basic block in a function is special in two ways: it is immediately
+ executed on entrance to the function, and it is not allowed to have
+ predecessor basic blocks (i.e. there can not be any branches to the entry
+ block of a function). Because the block can have no predecessors, it also
+ cannot have any <a href="#i_phi">PHI nodes</a>.</p>
+
+<p>LLVM allows an explicit section to be specified for functions. If the target
+ supports it, it will emit functions to the section specified.</p>
+
+<p>An explicit alignment may be specified for a function. If not present, or if
+ the alignment is set to zero, the alignment of the function is set by the
+ target to whatever it feels convenient. If an explicit alignment is
+ specified, the function is forced to have at least that much alignment. All
+ alignments must be a power of 2.</p>
+
+<p>If the <tt>unnamed_addr</tt> attribute is given, the address is know to not
+ be significant and two identical functions can be merged.</p>
+
+<h5>Syntax:</h5>
+<pre class="doc_code">
+define [<a href="#linkage">linkage</a>] [<a href="#visibility">visibility</a>]
+ [<a href="#callingconv">cconv</a>] [<a href="#paramattrs">ret attrs</a>]
+ &lt;ResultType&gt; @&lt;FunctionName&gt; ([argument list])
+ [<a href="#fnattrs">fn Attrs</a>] [section "name"] [align N]
+ [<a href="#gc">gc</a>] { ... }
+</pre>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="aliasstructure">Aliases</a>
+</h3>
+
+<div>
+
+<p>Aliases act as "second name" for the aliasee value (which can be either
+ function, global variable, another alias or bitcast of global value). Aliases
+ may have an optional <a href="#linkage">linkage type</a>, and an
+ optional <a href="#visibility">visibility style</a>.</p>
+
+<h5>Syntax:</h5>
+<pre class="doc_code">
+@&lt;Name&gt; = alias [Linkage] [Visibility] &lt;AliaseeTy&gt; @&lt;Aliasee&gt;
+</pre>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="namedmetadatastructure">Named Metadata</a>
+</h3>
+
+<div>
+
+<p>Named metadata is a collection of metadata. <a href="#metadata">Metadata
+ nodes</a> (but not metadata strings) are the only valid operands for
+ a named metadata.</p>
+
+<h5>Syntax:</h5>
+<pre class="doc_code">
+; Some unnamed metadata nodes, which are referenced by the named metadata.
+!0 = metadata !{metadata !"zero"}
+!1 = metadata !{metadata !"one"}
+!2 = metadata !{metadata !"two"}
+; A named metadata.
+!name = !{!0, !1, !2}
+</pre>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="paramattrs">Parameter Attributes</a>
+</h3>
+
+<div>
+
+<p>The return type and each parameter of a function type may have a set of
+ <i>parameter attributes</i> associated with them. Parameter attributes are
+ used to communicate additional information about the result or parameters of
+ a function. Parameter attributes are considered to be part of the function,
+ not of the function type, so functions with different parameter attributes
+ can have the same function type.</p>
+
+<p>Parameter attributes are simple keywords that follow the type specified. If
+ multiple parameter attributes are needed, they are space separated. For
+ example:</p>
+
+<pre class="doc_code">
+declare i32 @printf(i8* noalias nocapture, ...)
+declare i32 @atoi(i8 zeroext)
+declare signext i8 @returns_signed_char()
+</pre>
+
+<p>Note that any attributes for the function result (<tt>nounwind</tt>,
+ <tt>readonly</tt>) come immediately after the argument list.</p>
+
+<p>Currently, only the following parameter attributes are defined:</p>
+
+<dl>
+ <dt><tt><b>zeroext</b></tt></dt>
+ <dd>This indicates to the code generator that the parameter or return value
+ should be zero-extended to the extent required by the target's ABI (which
+ is usually 32-bits, but is 8-bits for a i1 on x86-64) by the caller (for a
+ parameter) or the callee (for a return value).</dd>
+
+ <dt><tt><b>signext</b></tt></dt>
+ <dd>This indicates to the code generator that the parameter or return value
+ should be sign-extended to the extent required by the target's ABI (which
+ is usually 32-bits) by the caller (for a parameter) or the callee (for a
+ return value).</dd>
+
+ <dt><tt><b>inreg</b></tt></dt>
+ <dd>This indicates that this parameter or return value should be treated in a
+ special target-dependent fashion during while emitting code for a function
+ call or return (usually, by putting it in a register as opposed to memory,
+ though some targets use it to distinguish between two different kinds of
+ registers). Use of this attribute is target-specific.</dd>
+
+ <dt><tt><b><a name="byval">byval</a></b></tt></dt>
+ <dd><p>This indicates that the pointer parameter should really be passed by
+ value to the function. The attribute implies that a hidden copy of the
+ pointee
+ is made between the caller and the callee, so the callee is unable to
+ modify the value in the caller. This attribute is only valid on LLVM
+ pointer arguments. It is generally used to pass structs and arrays by
+ value, but is also valid on pointers to scalars. The copy is considered
+ to belong to the caller not the callee (for example,
+ <tt><a href="#readonly">readonly</a></tt> functions should not write to
+ <tt>byval</tt> parameters). This is not a valid attribute for return
+ values.</p>
+
+ <p>The byval attribute also supports specifying an alignment with
+ the align attribute. It indicates the alignment of the stack slot to
+ form and the known alignment of the pointer specified to the call site. If
+ the alignment is not specified, then the code generator makes a
+ target-specific assumption.</p></dd>
+
+ <dt><tt><b><a name="sret">sret</a></b></tt></dt>
+ <dd>This indicates that the pointer parameter specifies the address of a
+ structure that is the return value of the function in the source program.
+ This pointer must be guaranteed by the caller to be valid: loads and
+ stores to the structure may be assumed by the callee to not to trap. This
+ may only be applied to the first parameter. This is not a valid attribute
+ for return values. </dd>
+
+ <dt><tt><b><a name="noalias">noalias</a></b></tt></dt>
+ <dd>This indicates that pointer values
+ <a href="#pointeraliasing"><i>based</i></a> on the argument or return
+ value do not alias pointer values which are not <i>based</i> on it,
+ ignoring certain "irrelevant" dependencies.
+ For a call to the parent function, dependencies between memory
+ references from before or after the call and from those during the call
+ are "irrelevant" to the <tt>noalias</tt> keyword for the arguments and
+ return value used in that call.
+ The caller shares the responsibility with the callee for ensuring that
+ these requirements are met.
+ For further details, please see the discussion of the NoAlias response in
+ <a href="AliasAnalysis.html#MustMayNo">alias analysis</a>.<br>
+<br>
+ Note that this definition of <tt>noalias</tt> is intentionally
+ similar to the definition of <tt>restrict</tt> in C99 for function
+ arguments, though it is slightly weaker.
+<br>
+ For function return values, C99's <tt>restrict</tt> is not meaningful,
+ while LLVM's <tt>noalias</tt> is.
+ </dd>
+
+ <dt><tt><b><a name="nocapture">nocapture</a></b></tt></dt>
+ <dd>This indicates that the callee does not make any copies of the pointer
+ that outlive the callee itself. This is not a valid attribute for return
+ values.</dd>
+
+ <dt><tt><b><a name="nest">nest</a></b></tt></dt>
+ <dd>This indicates that the pointer parameter can be excised using the
+ <a href="#int_trampoline">trampoline intrinsics</a>. This is not a valid
+ attribute for return values.</dd>
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="gc">Garbage Collector Names</a>
+</h3>
+
+<div>
+
+<p>Each function may specify a garbage collector name, which is simply a
+ string:</p>
+
+<pre class="doc_code">
+define void @f() gc "name" { ... }
+</pre>
+
+<p>The compiler declares the supported values of <i>name</i>. Specifying a
+ collector which will cause the compiler to alter its output in order to
+ support the named garbage collection algorithm.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="fnattrs">Function Attributes</a>
+</h3>
+
+<div>
+
+<p>Function attributes are set to communicate additional information about a
+ function. Function attributes are considered to be part of the function, not
+ of the function type, so functions with different parameter attributes can
+ have the same function type.</p>
+
+<p>Function attributes are simple keywords that follow the type specified. If
+ multiple attributes are needed, they are space separated. For example:</p>
+
+<pre class="doc_code">
+define void @f() noinline { ... }
+define void @f() alwaysinline { ... }
+define void @f() alwaysinline optsize { ... }
+define void @f() optsize { ... }
+</pre>
+
+<dl>
+ <dt><tt><b>address_safety</b></tt></dt>
+ <dd>This attribute indicates that the address safety analysis
+ is enabled for this function. </dd>
+
+ <dt><tt><b>alignstack(&lt;<em>n</em>&gt;)</b></tt></dt>
+ <dd>This attribute indicates that, when emitting the prologue and epilogue,
+ the backend should forcibly align the stack pointer. Specify the
+ desired alignment, which must be a power of two, in parentheses.
+
+ <dt><tt><b>alwaysinline</b></tt></dt>
+ <dd>This attribute indicates that the inliner should attempt to inline this
+ function into callers whenever possible, ignoring any active inlining size
+ threshold for this caller.</dd>
+
+ <dt><tt><b>nonlazybind</b></tt></dt>
+ <dd>This attribute suppresses lazy symbol binding for the function. This
+ may make calls to the function faster, at the cost of extra program
+ startup time if the function is not called during program startup.</dd>
+
+ <dt><tt><b>inlinehint</b></tt></dt>
+ <dd>This attribute indicates that the source code contained a hint that inlining
+ this function is desirable (such as the "inline" keyword in C/C++). It
+ is just a hint; it imposes no requirements on the inliner.</dd>
+
+ <dt><tt><b>naked</b></tt></dt>
+ <dd>This attribute disables prologue / epilogue emission for the function.
+ This can have very system-specific consequences.</dd>
+
+ <dt><tt><b>noimplicitfloat</b></tt></dt>
+ <dd>This attributes disables implicit floating point instructions.</dd>
+
+ <dt><tt><b>noinline</b></tt></dt>
+ <dd>This attribute indicates that the inliner should never inline this
+ function in any situation. This attribute may not be used together with
+ the <tt>alwaysinline</tt> attribute.</dd>
+
+ <dt><tt><b>noredzone</b></tt></dt>
+ <dd>This attribute indicates that the code generator should not use a red
+ zone, even if the target-specific ABI normally permits it.</dd>
+
+ <dt><tt><b>noreturn</b></tt></dt>
+ <dd>This function attribute indicates that the function never returns
+ normally. This produces undefined behavior at runtime if the function
+ ever does dynamically return.</dd>
+
+ <dt><tt><b>nounwind</b></tt></dt>
+ <dd>This function attribute indicates that the function never returns with an
+ unwind or exceptional control flow. If the function does unwind, its
+ runtime behavior is undefined.</dd>
+
+ <dt><tt><b>optsize</b></tt></dt>
+ <dd>This attribute suggests that optimization passes and code generator passes
+ make choices that keep the code size of this function low, and otherwise
+ do optimizations specifically to reduce code size.</dd>
+
+ <dt><tt><b>readnone</b></tt></dt>
+ <dd>This attribute indicates that the function computes its result (or decides
+ to unwind an exception) based strictly on its arguments, without
+ dereferencing any pointer arguments or otherwise accessing any mutable
+ state (e.g. memory, control registers, etc) visible to caller functions.
+ It does not write through any pointer arguments
+ (including <tt><a href="#byval">byval</a></tt> arguments) and never
+ changes any state visible to callers. This means that it cannot unwind
+ exceptions by calling the <tt>C++</tt> exception throwing methods.</dd>
+
+ <dt><tt><b><a name="readonly">readonly</a></b></tt></dt>
+ <dd>This attribute indicates that the function does not write through any
+ pointer arguments (including <tt><a href="#byval">byval</a></tt>
+ arguments) or otherwise modify any state (e.g. memory, control registers,
+ etc) visible to caller functions. It may dereference pointer arguments
+ and read state that may be set in the caller. A readonly function always
+ returns the same value (or unwinds an exception identically) when called
+ with the same set of arguments and global state. It cannot unwind an
+ exception by calling the <tt>C++</tt> exception throwing methods.</dd>
+
+ <dt><tt><b><a name="returns_twice">returns_twice</a></b></tt></dt>
+ <dd>This attribute indicates that this function can return twice. The
+ C <code>setjmp</code> is an example of such a function. The compiler
+ disables some optimizations (like tail calls) in the caller of these
+ functions.</dd>
+
+ <dt><tt><b><a name="ssp">ssp</a></b></tt></dt>
+ <dd>This attribute indicates that the function should emit a stack smashing
+ protector. It is in the form of a "canary"&mdash;a random value placed on
+ the stack before the local variables that's checked upon return from the
+ function to see if it has been overwritten. A heuristic is used to
+ determine if a function needs stack protectors or not.<br>
+<br>
+ If a function that has an <tt>ssp</tt> attribute is inlined into a
+ function that doesn't have an <tt>ssp</tt> attribute, then the resulting
+ function will have an <tt>ssp</tt> attribute.</dd>
+
+ <dt><tt><b>sspreq</b></tt></dt>
+ <dd>This attribute indicates that the function should <em>always</em> emit a
+ stack smashing protector. This overrides
+ the <tt><a href="#ssp">ssp</a></tt> function attribute.<br>
+<br>
+ If a function that has an <tt>sspreq</tt> attribute is inlined into a
+ function that doesn't have an <tt>sspreq</tt> attribute or which has
+ an <tt>ssp</tt> attribute, then the resulting function will have
+ an <tt>sspreq</tt> attribute.</dd>
+
+ <dt><tt><b><a name="uwtable">uwtable</a></b></tt></dt>
+ <dd>This attribute indicates that the ABI being targeted requires that
+ an unwind table entry be produce for this function even if we can
+ show that no exceptions passes by it. This is normally the case for
+ the ELF x86-64 abi, but it can be disabled for some compilation
+ units.</dd>
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="moduleasm">Module-Level Inline Assembly</a>
+</h3>
+
+<div>
+
+<p>Modules may contain "module-level inline asm" blocks, which corresponds to
+ the GCC "file scope inline asm" blocks. These blocks are internally
+ concatenated by LLVM and treated as a single unit, but may be separated in
+ the <tt>.ll</tt> file if desired. The syntax is very simple:</p>
+
+<pre class="doc_code">
+module asm "inline asm code goes here"
+module asm "more can go here"
+</pre>
+
+<p>The strings can contain any character by escaping non-printable characters.
+ The escape sequence used is simply "\xx" where "xx" is the two digit hex code
+ for the number.</p>
+
+<p>The inline asm code is simply printed to the machine code .s file when
+ assembly code is generated.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="datalayout">Data Layout</a>
+</h3>
+
+<div>
+
+<p>A module may specify a target specific data layout string that specifies how
+ data is to be laid out in memory. The syntax for the data layout is
+ simply:</p>
+
+<pre class="doc_code">
+target datalayout = "<i>layout specification</i>"
+</pre>
+
+<p>The <i>layout specification</i> consists of a list of specifications
+ separated by the minus sign character ('-'). Each specification starts with
+ a letter and may include other information after the letter to define some
+ aspect of the data layout. The specifications accepted are as follows:</p>
+
+<dl>
+ <dt><tt>E</tt></dt>
+ <dd>Specifies that the target lays out data in big-endian form. That is, the
+ bits with the most significance have the lowest address location.</dd>
+
+ <dt><tt>e</tt></dt>
+ <dd>Specifies that the target lays out data in little-endian form. That is,
+ the bits with the least significance have the lowest address
+ location.</dd>
+
+ <dt><tt>S<i>size</i></tt></dt>
+ <dd>Specifies the natural alignment of the stack in bits. Alignment promotion
+ of stack variables is limited to the natural stack alignment to avoid
+ dynamic stack realignment. The stack alignment must be a multiple of
+ 8-bits. If omitted, the natural stack alignment defaults to "unspecified",
+ which does not prevent any alignment promotions.</dd>
+
+ <dt><tt>p:<i>size</i>:<i>abi</i>:<i>pref</i></tt></dt>
+ <dd>This specifies the <i>size</i> of a pointer and its <i>abi</i> and
+ <i>preferred</i> alignments. All sizes are in bits. Specifying
+ the <i>pref</i> alignment is optional. If omitted, the
+ preceding <tt>:</tt> should be omitted too.</dd>
+
+ <dt><tt>i<i>size</i>:<i>abi</i>:<i>pref</i></tt></dt>
+ <dd>This specifies the alignment for an integer type of a given bit
+ <i>size</i>. The value of <i>size</i> must be in the range [1,2^23).</dd>
+
+ <dt><tt>v<i>size</i>:<i>abi</i>:<i>pref</i></tt></dt>
+ <dd>This specifies the alignment for a vector type of a given bit
+ <i>size</i>.</dd>
+
+ <dt><tt>f<i>size</i>:<i>abi</i>:<i>pref</i></tt></dt>
+ <dd>This specifies the alignment for a floating point type of a given bit
+ <i>size</i>. Only values of <i>size</i> that are supported by the target
+ will work. 32 (float) and 64 (double) are supported on all targets;
+ 80 or 128 (different flavors of long double) are also supported on some
+ targets.
+
+ <dt><tt>a<i>size</i>:<i>abi</i>:<i>pref</i></tt></dt>
+ <dd>This specifies the alignment for an aggregate type of a given bit
+ <i>size</i>.</dd>
+
+ <dt><tt>s<i>size</i>:<i>abi</i>:<i>pref</i></tt></dt>
+ <dd>This specifies the alignment for a stack object of a given bit
+ <i>size</i>.</dd>
+
+ <dt><tt>n<i>size1</i>:<i>size2</i>:<i>size3</i>...</tt></dt>
+ <dd>This specifies a set of native integer widths for the target CPU
+ in bits. For example, it might contain "n32" for 32-bit PowerPC,
+ "n32:64" for PowerPC 64, or "n8:16:32:64" for X86-64. Elements of
+ this set are considered to support most general arithmetic
+ operations efficiently.</dd>
+</dl>
+
+<p>When constructing the data layout for a given target, LLVM starts with a
+ default set of specifications which are then (possibly) overridden by the
+ specifications in the <tt>datalayout</tt> keyword. The default specifications
+ are given in this list:</p>
+
+<ul>
+ <li><tt>E</tt> - big endian</li>
+ <li><tt>p:64:64:64</tt> - 64-bit pointers with 64-bit alignment</li>
+ <li><tt>i1:8:8</tt> - i1 is 8-bit (byte) aligned</li>
+ <li><tt>i8:8:8</tt> - i8 is 8-bit (byte) aligned</li>
+ <li><tt>i16:16:16</tt> - i16 is 16-bit aligned</li>
+ <li><tt>i32:32:32</tt> - i32 is 32-bit aligned</li>
+ <li><tt>i64:32:64</tt> - i64 has ABI alignment of 32-bits but preferred
+ alignment of 64-bits</li>
+ <li><tt>f32:32:32</tt> - float is 32-bit aligned</li>
+ <li><tt>f64:64:64</tt> - double is 64-bit aligned</li>
+ <li><tt>v64:64:64</tt> - 64-bit vector is 64-bit aligned</li>
+ <li><tt>v128:128:128</tt> - 128-bit vector is 128-bit aligned</li>
+ <li><tt>a0:0:1</tt> - aggregates are 8-bit aligned</li>
+ <li><tt>s0:64:64</tt> - stack objects are 64-bit aligned</li>
+</ul>
+
+<p>When LLVM is determining the alignment for a given type, it uses the
+ following rules:</p>
+
+<ol>
+ <li>If the type sought is an exact match for one of the specifications, that
+ specification is used.</li>
+
+ <li>If no match is found, and the type sought is an integer type, then the
+ smallest integer type that is larger than the bitwidth of the sought type
+ is used. If none of the specifications are larger than the bitwidth then
+ the largest integer type is used. For example, given the default
+ specifications above, the i7 type will use the alignment of i8 (next
+ largest) while both i65 and i256 will use the alignment of i64 (largest
+ specified).</li>
+
+ <li>If no match is found, and the type sought is a vector type, then the
+ largest vector type that is smaller than the sought vector type will be
+ used as a fall back. This happens because &lt;128 x double&gt; can be
+ implemented in terms of 64 &lt;2 x double&gt;, for example.</li>
+</ol>
+
+<p>The function of the data layout string may not be what you expect. Notably,
+ this is not a specification from the frontend of what alignment the code
+ generator should use.</p>
+
+<p>Instead, if specified, the target data layout is required to match what the
+ ultimate <em>code generator</em> expects. This string is used by the
+ mid-level optimizers to
+ improve code, and this only works if it matches what the ultimate code
+ generator uses. If you would like to generate IR that does not embed this
+ target-specific detail into the IR, then you don't have to specify the
+ string. This will disable some optimizations that require precise layout
+ information, but this also prevents those optimizations from introducing
+ target specificity into the IR.</p>
+
+
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="pointeraliasing">Pointer Aliasing Rules</a>
+</h3>
+
+<div>
+
+<p>Any memory access must be done through a pointer value associated
+with an address range of the memory access, otherwise the behavior
+is undefined. Pointer values are associated with address ranges
+according to the following rules:</p>
+
+<ul>
+ <li>A pointer value is associated with the addresses associated with
+ any value it is <i>based</i> on.
+ <li>An address of a global variable is associated with the address
+ range of the variable's storage.</li>
+ <li>The result value of an allocation instruction is associated with
+ the address range of the allocated storage.</li>
+ <li>A null pointer in the default address-space is associated with
+ no address.</li>
+ <li>An integer constant other than zero or a pointer value returned
+ from a function not defined within LLVM may be associated with address
+ ranges allocated through mechanisms other than those provided by
+ LLVM. Such ranges shall not overlap with any ranges of addresses
+ allocated by mechanisms provided by LLVM.</li>
+</ul>
+
+<p>A pointer value is <i>based</i> on another pointer value according
+ to the following rules:</p>
+
+<ul>
+ <li>A pointer value formed from a
+ <tt><a href="#i_getelementptr">getelementptr</a></tt> operation
+ is <i>based</i> on the first operand of the <tt>getelementptr</tt>.</li>
+ <li>The result value of a
+ <tt><a href="#i_bitcast">bitcast</a></tt> is <i>based</i> on the operand
+ of the <tt>bitcast</tt>.</li>
+ <li>A pointer value formed by an
+ <tt><a href="#i_inttoptr">inttoptr</a></tt> is <i>based</i> on all
+ pointer values that contribute (directly or indirectly) to the
+ computation of the pointer's value.</li>
+ <li>The "<i>based</i> on" relationship is transitive.</li>
+</ul>
+
+<p>Note that this definition of <i>"based"</i> is intentionally
+ similar to the definition of <i>"based"</i> in C99, though it is
+ slightly weaker.</p>
+
+<p>LLVM IR does not associate types with memory. The result type of a
+<tt><a href="#i_load">load</a></tt> merely indicates the size and
+alignment of the memory from which to load, as well as the
+interpretation of the value. The first operand type of a
+<tt><a href="#i_store">store</a></tt> similarly only indicates the size
+and alignment of the store.</p>
+
+<p>Consequently, type-based alias analysis, aka TBAA, aka
+<tt>-fstrict-aliasing</tt>, is not applicable to general unadorned
+LLVM IR. <a href="#metadata">Metadata</a> may be used to encode
+additional information which specialized optimization passes may use
+to implement type-based alias analysis.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="volatile">Volatile Memory Accesses</a>
+</h3>
+
+<div>
+
+<p>Certain memory accesses, such as <a href="#i_load"><tt>load</tt></a>s, <a
+href="#i_store"><tt>store</tt></a>s, and <a
+href="#int_memcpy"><tt>llvm.memcpy</tt></a>s may be marked <tt>volatile</tt>.
+The optimizers must not change the number of volatile operations or change their
+order of execution relative to other volatile operations. The optimizers
+<i>may</i> change the order of volatile operations relative to non-volatile
+operations. This is not Java's "volatile" and has no cross-thread
+synchronization behavior.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="memmodel">Memory Model for Concurrent Operations</a>
+</h3>
+
+<div>
+
+<p>The LLVM IR does not define any way to start parallel threads of execution
+or to register signal handlers. Nonetheless, there are platform-specific
+ways to create them, and we define LLVM IR's behavior in their presence. This
+model is inspired by the C++0x memory model.</p>
+
+<p>For a more informal introduction to this model, see the
+<a href="Atomics.html">LLVM Atomic Instructions and Concurrency Guide</a>.
+
+<p>We define a <i>happens-before</i> partial order as the least partial order
+that</p>
+<ul>
+ <li>Is a superset of single-thread program order, and</li>
+ <li>When a <i>synchronizes-with</i> <tt>b</tt>, includes an edge from
+ <tt>a</tt> to <tt>b</tt>. <i>Synchronizes-with</i> pairs are introduced
+ by platform-specific techniques, like pthread locks, thread
+ creation, thread joining, etc., and by atomic instructions.
+ (See also <a href="#ordering">Atomic Memory Ordering Constraints</a>).
+ </li>
+</ul>
+
+<p>Note that program order does not introduce <i>happens-before</i> edges
+between a thread and signals executing inside that thread.</p>
+
+<p>Every (defined) read operation (load instructions, memcpy, atomic
+loads/read-modify-writes, etc.) <var>R</var> reads a series of bytes written by
+(defined) write operations (store instructions, atomic
+stores/read-modify-writes, memcpy, etc.). For the purposes of this section,
+initialized globals are considered to have a write of the initializer which is
+atomic and happens before any other read or write of the memory in question.
+For each byte of a read <var>R</var>, <var>R<sub>byte</sub></var> may see
+any write to the same byte, except:</p>
+
+<ul>
+ <li>If <var>write<sub>1</sub></var> happens before
+ <var>write<sub>2</sub></var>, and <var>write<sub>2</sub></var> happens
+ before <var>R<sub>byte</sub></var>, then <var>R<sub>byte</sub></var>
+ does not see <var>write<sub>1</sub></var>.
+ <li>If <var>R<sub>byte</sub></var> happens before
+ <var>write<sub>3</sub></var>, then <var>R<sub>byte</sub></var> does not
+ see <var>write<sub>3</sub></var>.
+</ul>
+
+<p>Given that definition, <var>R<sub>byte</sub></var> is defined as follows:
+<ul>
+ <li>If <var>R</var> is volatile, the result is target-dependent. (Volatile
+ is supposed to give guarantees which can support
+ <code>sig_atomic_t</code> in C/C++, and may be used for accesses to
+ addresses which do not behave like normal memory. It does not generally
+ provide cross-thread synchronization.)
+ <li>Otherwise, if there is no write to the same byte that happens before
+ <var>R<sub>byte</sub></var>, <var>R<sub>byte</sub></var> returns
+ <tt>undef</tt> for that byte.
+ <li>Otherwise, if <var>R<sub>byte</sub></var> may see exactly one write,
+ <var>R<sub>byte</sub></var> returns the value written by that
+ write.</li>
+ <li>Otherwise, if <var>R</var> is atomic, and all the writes
+ <var>R<sub>byte</sub></var> may see are atomic, it chooses one of the
+ values written. See the <a href="#ordering">Atomic Memory Ordering
+ Constraints</a> section for additional constraints on how the choice
+ is made.
+ <li>Otherwise <var>R<sub>byte</sub></var> returns <tt>undef</tt>.</li>
+</ul>
+
+<p><var>R</var> returns the value composed of the series of bytes it read.
+This implies that some bytes within the value may be <tt>undef</tt>
+<b>without</b> the entire value being <tt>undef</tt>. Note that this only
+defines the semantics of the operation; it doesn't mean that targets will
+emit more than one instruction to read the series of bytes.</p>
+
+<p>Note that in cases where none of the atomic intrinsics are used, this model
+places only one restriction on IR transformations on top of what is required
+for single-threaded execution: introducing a store to a byte which might not
+otherwise be stored is not allowed in general. (Specifically, in the case
+where another thread might write to and read from an address, introducing a
+store can change a load that may see exactly one write into a load that may
+see multiple writes.)</p>
+
+<!-- FIXME: This model assumes all targets where concurrency is relevant have
+a byte-size store which doesn't affect adjacent bytes. As far as I can tell,
+none of the backends currently in the tree fall into this category; however,
+there might be targets which care. If there are, we want a paragraph
+like the following:
+
+Targets may specify that stores narrower than a certain width are not
+available; on such a target, for the purposes of this model, treat any
+non-atomic write with an alignment or width less than the minimum width
+as if it writes to the relevant surrounding bytes.
+-->
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ordering">Atomic Memory Ordering Constraints</a>
+</h3>
+
+<div>
+
+<p>Atomic instructions (<a href="#i_cmpxchg"><code>cmpxchg</code></a>,
+<a href="#i_atomicrmw"><code>atomicrmw</code></a>,
+<a href="#i_fence"><code>fence</code></a>,
+<a href="#i_load"><code>atomic load</code></a>, and
+<a href="#i_store"><code>atomic store</code></a>) take an ordering parameter
+that determines which other atomic instructions on the same address they
+<i>synchronize with</i>. These semantics are borrowed from Java and C++0x,
+but are somewhat more colloquial. If these descriptions aren't precise enough,
+check those specs (see spec references in the
+<a href="Atomics.html#introduction">atomics guide</a>).
+<a href="#i_fence"><code>fence</code></a> instructions
+treat these orderings somewhat differently since they don't take an address.
+See that instruction's documentation for details.</p>
+
+<p>For a simpler introduction to the ordering constraints, see the
+<a href="Atomics.html">LLVM Atomic Instructions and Concurrency Guide</a>.</p>
+
+<dl>
+<dt><code>unordered</code></dt>
+<dd>The set of values that can be read is governed by the happens-before
+partial order. A value cannot be read unless some operation wrote it.
+This is intended to provide a guarantee strong enough to model Java's
+non-volatile shared variables. This ordering cannot be specified for
+read-modify-write operations; it is not strong enough to make them atomic
+in any interesting way.</dd>
+<dt><code>monotonic</code></dt>
+<dd>In addition to the guarantees of <code>unordered</code>, there is a single
+total order for modifications by <code>monotonic</code> operations on each
+address. All modification orders must be compatible with the happens-before
+order. There is no guarantee that the modification orders can be combined to
+a global total order for the whole program (and this often will not be
+possible). The read in an atomic read-modify-write operation
+(<a href="#i_cmpxchg"><code>cmpxchg</code></a> and
+<a href="#i_atomicrmw"><code>atomicrmw</code></a>)
+reads the value in the modification order immediately before the value it
+writes. If one atomic read happens before another atomic read of the same
+address, the later read must see the same value or a later value in the
+address's modification order. This disallows reordering of
+<code>monotonic</code> (or stronger) operations on the same address. If an
+address is written <code>monotonic</code>ally by one thread, and other threads
+<code>monotonic</code>ally read that address repeatedly, the other threads must
+eventually see the write. This corresponds to the C++0x/C1x
+<code>memory_order_relaxed</code>.</dd>
+<dt><code>acquire</code></dt>
+<dd>In addition to the guarantees of <code>monotonic</code>,
+a <i>synchronizes-with</i> edge may be formed with a <code>release</code>
+operation. This is intended to model C++'s <code>memory_order_acquire</code>.</dd>
+<dt><code>release</code></dt>
+<dd>In addition to the guarantees of <code>monotonic</code>, if this operation
+writes a value which is subsequently read by an <code>acquire</code> operation,
+it <i>synchronizes-with</i> that operation. (This isn't a complete
+description; see the C++0x definition of a release sequence.) This corresponds
+to the C++0x/C1x <code>memory_order_release</code>.</dd>
+<dt><code>acq_rel</code> (acquire+release)</dt><dd>Acts as both an
+<code>acquire</code> and <code>release</code> operation on its address.
+This corresponds to the C++0x/C1x <code>memory_order_acq_rel</code>.</dd>
+<dt><code>seq_cst</code> (sequentially consistent)</dt><dd>
+<dd>In addition to the guarantees of <code>acq_rel</code>
+(<code>acquire</code> for an operation which only reads, <code>release</code>
+for an operation which only writes), there is a global total order on all
+sequentially-consistent operations on all addresses, which is consistent with
+the <i>happens-before</i> partial order and with the modification orders of
+all the affected addresses. Each sequentially-consistent read sees the last
+preceding write to the same address in this global order. This corresponds
+to the C++0x/C1x <code>memory_order_seq_cst</code> and Java volatile.</dd>
+</dl>
+
+<p id="singlethread">If an atomic operation is marked <code>singlethread</code>,
+it only <i>synchronizes with</i> or participates in modification and seq_cst
+total orderings with other operations running in the same thread (for example,
+in signal handlers).</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="typesystem">Type System</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The LLVM type system is one of the most important features of the
+ intermediate representation. Being typed enables a number of optimizations
+ to be performed on the intermediate representation directly, without having
+ to do extra analyses on the side before the transformation. A strong type
+ system makes it easier to read the generated code and enables novel analyses
+ and transformations that are not feasible to perform on normal three address
+ code representations.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="t_classifications">Type Classifications</a>
+</h3>
+
+<div>
+
+<p>The types fall into a few useful classifications:</p>
+
+<table border="1" cellspacing="0" cellpadding="4">
+ <tbody>
+ <tr><th>Classification</th><th>Types</th></tr>
+ <tr>
+ <td><a href="#t_integer">integer</a></td>
+ <td><tt>i1, i2, i3, ... i8, ... i16, ... i32, ... i64, ... </tt></td>
+ </tr>
+ <tr>
+ <td><a href="#t_floating">floating point</a></td>
+ <td><tt>half, float, double, x86_fp80, fp128, ppc_fp128</tt></td>
+ </tr>
+ <tr>
+ <td><a name="t_firstclass">first class</a></td>
+ <td><a href="#t_integer">integer</a>,
+ <a href="#t_floating">floating point</a>,
+ <a href="#t_pointer">pointer</a>,
+ <a href="#t_vector">vector</a>,
+ <a href="#t_struct">structure</a>,
+ <a href="#t_array">array</a>,
+ <a href="#t_label">label</a>,
+ <a href="#t_metadata">metadata</a>.
+ </td>
+ </tr>
+ <tr>
+ <td><a href="#t_primitive">primitive</a></td>
+ <td><a href="#t_label">label</a>,
+ <a href="#t_void">void</a>,
+ <a href="#t_integer">integer</a>,
+ <a href="#t_floating">floating point</a>,
+ <a href="#t_x86mmx">x86mmx</a>,
+ <a href="#t_metadata">metadata</a>.</td>
+ </tr>
+ <tr>
+ <td><a href="#t_derived">derived</a></td>
+ <td><a href="#t_array">array</a>,
+ <a href="#t_function">function</a>,
+ <a href="#t_pointer">pointer</a>,
+ <a href="#t_struct">structure</a>,
+ <a href="#t_vector">vector</a>,
+ <a href="#t_opaque">opaque</a>.
+ </td>
+ </tr>
+ </tbody>
+</table>
+
+<p>The <a href="#t_firstclass">first class</a> types are perhaps the most
+ important. Values of these types are the only ones which can be produced by
+ instructions.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="t_primitive">Primitive Types</a>
+</h3>
+
+<div>
+
+<p>The primitive types are the fundamental building blocks of the LLVM
+ system.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_integer">Integer Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The integer type is a very simple type that simply specifies an arbitrary
+ bit width for the integer type desired. Any bit width from 1 bit to
+ 2<sup>23</sup>-1 (about 8 million) can be specified.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ iN
+</pre>
+
+<p>The number of bits the integer will occupy is specified by the <tt>N</tt>
+ value.</p>
+
+<h5>Examples:</h5>
+<table class="layout">
+ <tr class="layout">
+ <td class="left"><tt>i1</tt></td>
+ <td class="left">a single-bit integer.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>i32</tt></td>
+ <td class="left">a 32-bit integer.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>i1942652</tt></td>
+ <td class="left">a really big integer of over 1 million bits.</td>
+ </tr>
+</table>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_floating">Floating Point Types</a>
+</h4>
+
+<div>
+
+<table>
+ <tbody>
+ <tr><th>Type</th><th>Description</th></tr>
+ <tr><td><tt>half</tt></td><td>16-bit floating point value</td></tr>
+ <tr><td><tt>float</tt></td><td>32-bit floating point value</td></tr>
+ <tr><td><tt>double</tt></td><td>64-bit floating point value</td></tr>
+ <tr><td><tt>fp128</tt></td><td>128-bit floating point value (112-bit mantissa)</td></tr>
+ <tr><td><tt>x86_fp80</tt></td><td>80-bit floating point value (X87)</td></tr>
+ <tr><td><tt>ppc_fp128</tt></td><td>128-bit floating point value (two 64-bits)</td></tr>
+ </tbody>
+</table>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_x86mmx">X86mmx Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The x86mmx type represents a value held in an MMX register on an x86 machine. The operations allowed on it are quite limited: parameters and return values, load and store, and bitcast. User-specified MMX instructions are represented as intrinsic or asm calls with arguments and/or results of this type. There are no arrays, vectors or constants of this type.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ x86mmx
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_void">Void Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The void type does not represent any value and has no size.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ void
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_label">Label Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The label type represents code labels.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ label
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_metadata">Metadata Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The metadata type represents embedded metadata. No derived types may be
+ created from metadata except for <a href="#t_function">function</a>
+ arguments.
+
+<h5>Syntax:</h5>
+<pre>
+ metadata
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="t_derived">Derived Types</a>
+</h3>
+
+<div>
+
+<p>The real power in LLVM comes from the derived types in the system. This is
+ what allows a programmer to represent arrays, functions, pointers, and other
+ useful types. Each of these types contain one or more element types which
+ may be a primitive type, or another derived type. For example, it is
+ possible to have a two dimensional array, using an array as the element type
+ of another array.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_aggregate">Aggregate Types</a>
+</h4>
+
+<div>
+
+<p>Aggregate Types are a subset of derived types that can contain multiple
+ member types. <a href="#t_array">Arrays</a> and
+ <a href="#t_struct">structs</a> are aggregate types.
+ <a href="#t_vector">Vectors</a> are not considered to be aggregate types.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_array">Array Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The array type is a very simple derived type that arranges elements
+ sequentially in memory. The array type requires a size (number of elements)
+ and an underlying data type.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ [&lt;# elements&gt; x &lt;elementtype&gt;]
+</pre>
+
+<p>The number of elements is a constant integer value; <tt>elementtype</tt> may
+ be any type with a size.</p>
+
+<h5>Examples:</h5>
+<table class="layout">
+ <tr class="layout">
+ <td class="left"><tt>[40 x i32]</tt></td>
+ <td class="left">Array of 40 32-bit integer values.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>[41 x i32]</tt></td>
+ <td class="left">Array of 41 32-bit integer values.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>[4 x i8]</tt></td>
+ <td class="left">Array of 4 8-bit integer values.</td>
+ </tr>
+</table>
+<p>Here are some examples of multidimensional arrays:</p>
+<table class="layout">
+ <tr class="layout">
+ <td class="left"><tt>[3 x [4 x i32]]</tt></td>
+ <td class="left">3x4 array of 32-bit integer values.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>[12 x [10 x float]]</tt></td>
+ <td class="left">12x10 array of single precision floating point values.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>[2 x [3 x [4 x i16]]]</tt></td>
+ <td class="left">2x3x4 array of 16-bit integer values.</td>
+ </tr>
+</table>
+
+<p>There is no restriction on indexing beyond the end of the array implied by
+ a static type (though there are restrictions on indexing beyond the bounds
+ of an allocated object in some cases). This means that single-dimension
+ 'variable sized array' addressing can be implemented in LLVM with a zero
+ length array type. An implementation of 'pascal style arrays' in LLVM could
+ use the type "<tt>{ i32, [0 x float]}</tt>", for example.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_function">Function Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The function type can be thought of as a function signature. It consists of
+ a return type and a list of formal parameter types. The return type of a
+ function type is a first class type or a void type.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;returntype&gt; (&lt;parameter list&gt;)
+</pre>
+
+<p>...where '<tt>&lt;parameter list&gt;</tt>' is a comma-separated list of type
+ specifiers. Optionally, the parameter list may include a type <tt>...</tt>,
+ which indicates that the function takes a variable number of arguments.
+ Variable argument functions can access their arguments with
+ the <a href="#int_varargs">variable argument handling intrinsic</a>
+ functions. '<tt>&lt;returntype&gt;</tt>' is any type except
+ <a href="#t_label">label</a>.</p>
+
+<h5>Examples:</h5>
+<table class="layout">
+ <tr class="layout">
+ <td class="left"><tt>i32 (i32)</tt></td>
+ <td class="left">function taking an <tt>i32</tt>, returning an <tt>i32</tt>
+ </td>
+ </tr><tr class="layout">
+ <td class="left"><tt>float&nbsp;(i16,&nbsp;i32&nbsp;*)&nbsp;*
+ </tt></td>
+ <td class="left"><a href="#t_pointer">Pointer</a> to a function that takes
+ an <tt>i16</tt> and a <a href="#t_pointer">pointer</a> to <tt>i32</tt>,
+ returning <tt>float</tt>.
+ </td>
+ </tr><tr class="layout">
+ <td class="left"><tt>i32 (i8*, ...)</tt></td>
+ <td class="left">A vararg function that takes at least one
+ <a href="#t_pointer">pointer</a> to <tt>i8 </tt> (char in C),
+ which returns an integer. This is the signature for <tt>printf</tt> in
+ LLVM.
+ </td>
+ </tr><tr class="layout">
+ <td class="left"><tt>{i32, i32} (i32)</tt></td>
+ <td class="left">A function taking an <tt>i32</tt>, returning a
+ <a href="#t_struct">structure</a> containing two <tt>i32</tt> values
+ </td>
+ </tr>
+</table>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_struct">Structure Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The structure type is used to represent a collection of data members together
+ in memory. The elements of a structure may be any type that has a size.</p>
+
+<p>Structures in memory are accessed using '<tt><a href="#i_load">load</a></tt>'
+ and '<tt><a href="#i_store">store</a></tt>' by getting a pointer to a field
+ with the '<tt><a href="#i_getelementptr">getelementptr</a></tt>' instruction.
+ Structures in registers are accessed using the
+ '<tt><a href="#i_extractvalue">extractvalue</a></tt>' and
+ '<tt><a href="#i_insertvalue">insertvalue</a></tt>' instructions.</p>
+
+<p>Structures may optionally be "packed" structures, which indicate that the
+ alignment of the struct is one byte, and that there is no padding between
+ the elements. In non-packed structs, padding between field types is inserted
+ as defined by the TargetData string in the module, which is required to match
+ what the underlying code generator expects.</p>
+
+<p>Structures can either be "literal" or "identified". A literal structure is
+ defined inline with other types (e.g. <tt>{i32, i32}*</tt>) whereas identified
+ types are always defined at the top level with a name. Literal types are
+ uniqued by their contents and can never be recursive or opaque since there is
+ no way to write one. Identified types can be recursive, can be opaqued, and are
+ never uniqued.
+</p>
+
+<h5>Syntax:</h5>
+<pre>
+ %T1 = type { &lt;type list&gt; } <i>; Identified normal struct type</i>
+ %T2 = type &lt;{ &lt;type list&gt; }&gt; <i>; Identified packed struct type</i>
+</pre>
+
+<h5>Examples:</h5>
+<table class="layout">
+ <tr class="layout">
+ <td class="left"><tt>{ i32, i32, i32 }</tt></td>
+ <td class="left">A triple of three <tt>i32</tt> values</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>{&nbsp;float,&nbsp;i32&nbsp;(i32)&nbsp;*&nbsp;}</tt></td>
+ <td class="left">A pair, where the first element is a <tt>float</tt> and the
+ second element is a <a href="#t_pointer">pointer</a> to a
+ <a href="#t_function">function</a> that takes an <tt>i32</tt>, returning
+ an <tt>i32</tt>.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>&lt;{ i8, i32 }&gt;</tt></td>
+ <td class="left">A packed struct known to be 5 bytes in size.</td>
+ </tr>
+</table>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_opaque">Opaque Structure Types</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>Opaque structure types are used to represent named structure types that do
+ not have a body specified. This corresponds (for example) to the C notion of
+ a forward declared structure.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ %X = type opaque
+ %52 = type opaque
+</pre>
+
+<h5>Examples:</h5>
+<table class="layout">
+ <tr class="layout">
+ <td class="left"><tt>opaque</tt></td>
+ <td class="left">An opaque type.</td>
+ </tr>
+</table>
+
+</div>
+
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_pointer">Pointer Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>The pointer type is used to specify memory locations.
+ Pointers are commonly used to reference objects in memory.</p>
+
+<p>Pointer types may have an optional address space attribute defining the
+ numbered address space where the pointed-to object resides. The default
+ address space is number zero. The semantics of non-zero address
+ spaces are target-specific.</p>
+
+<p>Note that LLVM does not permit pointers to void (<tt>void*</tt>) nor does it
+ permit pointers to labels (<tt>label*</tt>). Use <tt>i8*</tt> instead.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;type&gt; *
+</pre>
+
+<h5>Examples:</h5>
+<table class="layout">
+ <tr class="layout">
+ <td class="left"><tt>[4 x i32]*</tt></td>
+ <td class="left">A <a href="#t_pointer">pointer</a> to <a
+ href="#t_array">array</a> of four <tt>i32</tt> values.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>i32 (i32*) *</tt></td>
+ <td class="left"> A <a href="#t_pointer">pointer</a> to a <a
+ href="#t_function">function</a> that takes an <tt>i32*</tt>, returning an
+ <tt>i32</tt>.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>i32 addrspace(5)*</tt></td>
+ <td class="left">A <a href="#t_pointer">pointer</a> to an <tt>i32</tt> value
+ that resides in address space #5.</td>
+ </tr>
+</table>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="t_vector">Vector Type</a>
+</h4>
+
+<div>
+
+<h5>Overview:</h5>
+<p>A vector type is a simple derived type that represents a vector of elements.
+ Vector types are used when multiple primitive data are operated in parallel
+ using a single instruction (SIMD). A vector type requires a size (number of
+ elements) and an underlying primitive data type. Vector types are considered
+ <a href="#t_firstclass">first class</a>.</p>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt; &lt;# elements&gt; x &lt;elementtype&gt; &gt;
+</pre>
+
+<p>The number of elements is a constant integer value larger than 0; elementtype
+ may be any integer or floating point type, or a pointer to these types.
+ Vectors of size zero are not allowed. </p>
+
+<h5>Examples:</h5>
+<table class="layout">
+ <tr class="layout">
+ <td class="left"><tt>&lt;4 x i32&gt;</tt></td>
+ <td class="left">Vector of 4 32-bit integer values.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>&lt;8 x float&gt;</tt></td>
+ <td class="left">Vector of 8 32-bit floating-point values.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>&lt;2 x i64&gt;</tt></td>
+ <td class="left">Vector of 2 64-bit integer values.</td>
+ </tr>
+ <tr class="layout">
+ <td class="left"><tt>&lt;4 x i64*&gt;</tt></td>
+ <td class="left">Vector of 4 pointers to 64-bit integer values.</td>
+ </tr>
+</table>
+
+</div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="constants">Constants</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>LLVM has several different basic types of constants. This section describes
+ them all and their syntax.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="simpleconstants">Simple Constants</a>
+</h3>
+
+<div>
+
+<dl>
+ <dt><b>Boolean constants</b></dt>
+ <dd>The two strings '<tt>true</tt>' and '<tt>false</tt>' are both valid
+ constants of the <tt><a href="#t_integer">i1</a></tt> type.</dd>
+
+ <dt><b>Integer constants</b></dt>
+ <dd>Standard integers (such as '4') are constants of
+ the <a href="#t_integer">integer</a> type. Negative numbers may be used
+ with integer types.</dd>
+
+ <dt><b>Floating point constants</b></dt>
+ <dd>Floating point constants use standard decimal notation (e.g. 123.421),
+ exponential notation (e.g. 1.23421e+2), or a more precise hexadecimal
+ notation (see below). The assembler requires the exact decimal value of a
+ floating-point constant. For example, the assembler accepts 1.25 but
+ rejects 1.3 because 1.3 is a repeating decimal in binary. Floating point
+ constants must have a <a href="#t_floating">floating point</a> type. </dd>
+
+ <dt><b>Null pointer constants</b></dt>
+ <dd>The identifier '<tt>null</tt>' is recognized as a null pointer constant
+ and must be of <a href="#t_pointer">pointer type</a>.</dd>
+</dl>
+
+<p>The one non-intuitive notation for constants is the hexadecimal form of
+ floating point constants. For example, the form '<tt>double
+ 0x432ff973cafa8000</tt>' is equivalent to (but harder to read than)
+ '<tt>double 4.5e+15</tt>'. The only time hexadecimal floating point
+ constants are required (and the only time that they are generated by the
+ disassembler) is when a floating point constant must be emitted but it cannot
+ be represented as a decimal floating point number in a reasonable number of
+ digits. For example, NaN's, infinities, and other special values are
+ represented in their IEEE hexadecimal format so that assembly and disassembly
+ do not cause any bits to change in the constants.</p>
+
+<p>When using the hexadecimal form, constants of types half, float, and double are
+ represented using the 16-digit form shown above (which matches the IEEE754
+ representation for double); half and float values must, however, be exactly
+ representable as IEE754 half and single precision, respectively.
+ Hexadecimal format is always used
+ for long double, and there are three forms of long double. The 80-bit format
+ used by x86 is represented as <tt>0xK</tt> followed by 20 hexadecimal digits.
+ The 128-bit format used by PowerPC (two adjacent doubles) is represented
+ by <tt>0xM</tt> followed by 32 hexadecimal digits. The IEEE 128-bit format
+ is represented by <tt>0xL</tt> followed by 32 hexadecimal digits; no
+ currently supported target uses this format. Long doubles will only work if
+ they match the long double format on your target. The IEEE 16-bit format
+ (half precision) is represented by <tt>0xH</tt> followed by 4 hexadecimal
+ digits. All hexadecimal formats are big-endian (sign bit at the left).</p>
+
+<p>There are no constants of type x86mmx.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+<a name="aggregateconstants"></a> <!-- old anchor -->
+<a name="complexconstants">Complex Constants</a>
+</h3>
+
+<div>
+
+<p>Complex constants are a (potentially recursive) combination of simple
+ constants and smaller complex constants.</p>
+
+<dl>
+ <dt><b>Structure constants</b></dt>
+ <dd>Structure constants are represented with notation similar to structure
+ type definitions (a comma separated list of elements, surrounded by braces
+ (<tt>{}</tt>)). For example: "<tt>{ i32 4, float 17.0, i32* @G }</tt>",
+ where "<tt>@G</tt>" is declared as "<tt>@G = external global i32</tt>".
+ Structure constants must have <a href="#t_struct">structure type</a>, and
+ the number and types of elements must match those specified by the
+ type.</dd>
+
+ <dt><b>Array constants</b></dt>
+ <dd>Array constants are represented with notation similar to array type
+ definitions (a comma separated list of elements, surrounded by square
+ brackets (<tt>[]</tt>)). For example: "<tt>[ i32 42, i32 11, i32 74
+ ]</tt>". Array constants must have <a href="#t_array">array type</a>, and
+ the number and types of elements must match those specified by the
+ type.</dd>
+
+ <dt><b>Vector constants</b></dt>
+ <dd>Vector constants are represented with notation similar to vector type
+ definitions (a comma separated list of elements, surrounded by
+ less-than/greater-than's (<tt>&lt;&gt;</tt>)). For example: "<tt>&lt; i32
+ 42, i32 11, i32 74, i32 100 &gt;</tt>". Vector constants must
+ have <a href="#t_vector">vector type</a>, and the number and types of
+ elements must match those specified by the type.</dd>
+
+ <dt><b>Zero initialization</b></dt>
+ <dd>The string '<tt>zeroinitializer</tt>' can be used to zero initialize a
+ value to zero of <em>any</em> type, including scalar and
+ <a href="#t_aggregate">aggregate</a> types.
+ This is often used to avoid having to print large zero initializers
+ (e.g. for large arrays) and is always exactly equivalent to using explicit
+ zero initializers.</dd>
+
+ <dt><b>Metadata node</b></dt>
+ <dd>A metadata node is a structure-like constant with
+ <a href="#t_metadata">metadata type</a>. For example: "<tt>metadata !{
+ i32 0, metadata !"test" }</tt>". Unlike other constants that are meant to
+ be interpreted as part of the instruction stream, metadata is a place to
+ attach additional information such as debug info.</dd>
+</dl>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="globalconstants">Global Variable and Function Addresses</a>
+</h3>
+
+<div>
+
+<p>The addresses of <a href="#globalvars">global variables</a>
+ and <a href="#functionstructure">functions</a> are always implicitly valid
+ (link-time) constants. These constants are explicitly referenced when
+ the <a href="#identifiers">identifier for the global</a> is used and always
+ have <a href="#t_pointer">pointer</a> type. For example, the following is a
+ legal LLVM file:</p>
+
+<pre class="doc_code">
+@X = global i32 17
+@Y = global i32 42
+@Z = global [2 x i32*] [ i32* @X, i32* @Y ]
+</pre>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="undefvalues">Undefined Values</a>
+</h3>
+
+<div>
+
+<p>The string '<tt>undef</tt>' can be used anywhere a constant is expected, and
+ indicates that the user of the value may receive an unspecified bit-pattern.
+ Undefined values may be of any type (other than '<tt>label</tt>'
+ or '<tt>void</tt>') and be used anywhere a constant is permitted.</p>
+
+<p>Undefined values are useful because they indicate to the compiler that the
+ program is well defined no matter what value is used. This gives the
+ compiler more freedom to optimize. Here are some examples of (potentially
+ surprising) transformations that are valid (in pseudo IR):</p>
+
+
+<pre class="doc_code">
+ %A = add %X, undef
+ %B = sub %X, undef
+ %C = xor %X, undef
+Safe:
+ %A = undef
+ %B = undef
+ %C = undef
+</pre>
+
+<p>This is safe because all of the output bits are affected by the undef bits.
+ Any output bit can have a zero or one depending on the input bits.</p>
+
+<pre class="doc_code">
+ %A = or %X, undef
+ %B = and %X, undef
+Safe:
+ %A = -1
+ %B = 0
+Unsafe:
+ %A = undef
+ %B = undef
+</pre>
+
+<p>These logical operations have bits that are not always affected by the input.
+ For example, if <tt>%X</tt> has a zero bit, then the output of the
+ '<tt>and</tt>' operation will always be a zero for that bit, no matter what
+ the corresponding bit from the '<tt>undef</tt>' is. As such, it is unsafe to
+ optimize or assume that the result of the '<tt>and</tt>' is '<tt>undef</tt>'.
+ However, it is safe to assume that all bits of the '<tt>undef</tt>' could be
+ 0, and optimize the '<tt>and</tt>' to 0. Likewise, it is safe to assume that
+ all the bits of the '<tt>undef</tt>' operand to the '<tt>or</tt>' could be
+ set, allowing the '<tt>or</tt>' to be folded to -1.</p>
+
+<pre class="doc_code">
+ %A = select undef, %X, %Y
+ %B = select undef, 42, %Y
+ %C = select %X, %Y, undef
+Safe:
+ %A = %X (or %Y)
+ %B = 42 (or %Y)
+ %C = %Y
+Unsafe:
+ %A = undef
+ %B = undef
+ %C = undef
+</pre>
+
+<p>This set of examples shows that undefined '<tt>select</tt>' (and conditional
+ branch) conditions can go <em>either way</em>, but they have to come from one
+ of the two operands. In the <tt>%A</tt> example, if <tt>%X</tt> and
+ <tt>%Y</tt> were both known to have a clear low bit, then <tt>%A</tt> would
+ have to have a cleared low bit. However, in the <tt>%C</tt> example, the
+ optimizer is allowed to assume that the '<tt>undef</tt>' operand could be the
+ same as <tt>%Y</tt>, allowing the whole '<tt>select</tt>' to be
+ eliminated.</p>
+
+<pre class="doc_code">
+ %A = xor undef, undef
+
+ %B = undef
+ %C = xor %B, %B
+
+ %D = undef
+ %E = icmp lt %D, 4
+ %F = icmp gte %D, 4
+
+Safe:
+ %A = undef
+ %B = undef
+ %C = undef
+ %D = undef
+ %E = undef
+ %F = undef
+</pre>
+
+<p>This example points out that two '<tt>undef</tt>' operands are not
+ necessarily the same. This can be surprising to people (and also matches C
+ semantics) where they assume that "<tt>X^X</tt>" is always zero, even
+ if <tt>X</tt> is undefined. This isn't true for a number of reasons, but the
+ short answer is that an '<tt>undef</tt>' "variable" can arbitrarily change
+ its value over its "live range". This is true because the variable doesn't
+ actually <em>have a live range</em>. Instead, the value is logically read
+ from arbitrary registers that happen to be around when needed, so the value
+ is not necessarily consistent over time. In fact, <tt>%A</tt> and <tt>%C</tt>
+ need to have the same semantics or the core LLVM "replace all uses with"
+ concept would not hold.</p>
+
+<pre class="doc_code">
+ %A = fdiv undef, %X
+ %B = fdiv %X, undef
+Safe:
+ %A = undef
+b: unreachable
+</pre>
+
+<p>These examples show the crucial difference between an <em>undefined
+ value</em> and <em>undefined behavior</em>. An undefined value (like
+ '<tt>undef</tt>') is allowed to have an arbitrary bit-pattern. This means that
+ the <tt>%A</tt> operation can be constant folded to '<tt>undef</tt>', because
+ the '<tt>undef</tt>' could be an SNaN, and <tt>fdiv</tt> is not (currently)
+ defined on SNaN's. However, in the second example, we can make a more
+ aggressive assumption: because the <tt>undef</tt> is allowed to be an
+ arbitrary value, we are allowed to assume that it could be zero. Since a
+ divide by zero has <em>undefined behavior</em>, we are allowed to assume that
+ the operation does not execute at all. This allows us to delete the divide and
+ all code after it. Because the undefined operation "can't happen", the
+ optimizer can assume that it occurs in dead code.</p>
+
+<pre class="doc_code">
+a: store undef -> %X
+b: store %X -> undef
+Safe:
+a: &lt;deleted&gt;
+b: unreachable
+</pre>
+
+<p>These examples reiterate the <tt>fdiv</tt> example: a store <em>of</em> an
+ undefined value can be assumed to not have any effect; we can assume that the
+ value is overwritten with bits that happen to match what was already there.
+ However, a store <em>to</em> an undefined location could clobber arbitrary
+ memory, therefore, it has undefined behavior.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="poisonvalues">Poison Values</a>
+</h3>
+
+<div>
+
+<p>Poison values are similar to <a href="#undefvalues">undef values</a>, however
+ they also represent the fact that an instruction or constant expression which
+ cannot evoke side effects has nevertheless detected a condition which results
+ in undefined behavior.</p>
+
+<p>There is currently no way of representing a poison value in the IR; they
+ only exist when produced by operations such as
+ <a href="#i_add"><tt>add</tt></a> with the <tt>nsw</tt> flag.</p>
+
+<p>Poison value behavior is defined in terms of value <i>dependence</i>:</p>
+
+<ul>
+<li>Values other than <a href="#i_phi"><tt>phi</tt></a> nodes depend on
+ their operands.</li>
+
+<li><a href="#i_phi"><tt>Phi</tt></a> nodes depend on the operand corresponding
+ to their dynamic predecessor basic block.</li>
+
+<li>Function arguments depend on the corresponding actual argument values in
+ the dynamic callers of their functions.</li>
+
+<li><a href="#i_call"><tt>Call</tt></a> instructions depend on the
+ <a href="#i_ret"><tt>ret</tt></a> instructions that dynamically transfer
+ control back to them.</li>
+
+<li><a href="#i_invoke"><tt>Invoke</tt></a> instructions depend on the
+ <a href="#i_ret"><tt>ret</tt></a>, <a href="#i_resume"><tt>resume</tt></a>,
+ or exception-throwing call instructions that dynamically transfer control
+ back to them.</li>
+
+<li>Non-volatile loads and stores depend on the most recent stores to all of the
+ referenced memory addresses, following the order in the IR
+ (including loads and stores implied by intrinsics such as
+ <a href="#int_memcpy"><tt>@llvm.memcpy</tt></a>.)</li>
+
+<!-- TODO: In the case of multiple threads, this only applies if the store
+ "happens-before" the load or store. -->
+
+<!-- TODO: floating-point exception state -->
+
+<li>An instruction with externally visible side effects depends on the most
+ recent preceding instruction with externally visible side effects, following
+ the order in the IR. (This includes
+ <a href="#volatile">volatile operations</a>.)</li>
+
+<li>An instruction <i>control-depends</i> on a
+ <a href="#terminators">terminator instruction</a>
+ if the terminator instruction has multiple successors and the instruction
+ is always executed when control transfers to one of the successors, and
+ may not be executed when control is transferred to another.</li>
+
+<li>Additionally, an instruction also <i>control-depends</i> on a terminator
+ instruction if the set of instructions it otherwise depends on would be
+ different if the terminator had transferred control to a different
+ successor.</li>
+
+<li>Dependence is transitive.</li>
+
+</ul>
+
+<p>Poison Values have the same behavior as <a href="#undefvalues">undef values</a>,
+ with the additional affect that any instruction which has a <i>dependence</i>
+ on a poison value has undefined behavior.</p>
+
+<p>Here are some examples:</p>
+
+<pre class="doc_code">
+entry:
+ %poison = sub nuw i32 0, 1 ; Results in a poison value.
+ %still_poison = and i32 %poison, 0 ; 0, but also poison.
+ %poison_yet_again = getelementptr i32* @h, i32 %still_poison
+ store i32 0, i32* %poison_yet_again ; memory at @h[0] is poisoned
+
+ store i32 %poison, i32* @g ; Poison value stored to memory.
+ %poison2 = load i32* @g ; Poison value loaded back from memory.
+
+ store volatile i32 %poison, i32* @g ; External observation; undefined behavior.
+
+ %narrowaddr = bitcast i32* @g to i16*
+ %wideaddr = bitcast i32* @g to i64*
+ %poison3 = load i16* %narrowaddr ; Returns a poison value.
+ %poison4 = load i64* %wideaddr ; Returns a poison value.
+
+ %cmp = icmp slt i32 %poison, 0 ; Returns a poison value.
+ br i1 %cmp, label %true, label %end ; Branch to either destination.
+
+true:
+ store volatile i32 0, i32* @g ; This is control-dependent on %cmp, so
+ ; it has undefined behavior.
+ br label %end
+
+end:
+ %p = phi i32 [ 0, %entry ], [ 1, %true ]
+ ; Both edges into this PHI are
+ ; control-dependent on %cmp, so this
+ ; always results in a poison value.
+
+ store volatile i32 0, i32* @g ; This would depend on the store in %true
+ ; if %cmp is true, or the store in %entry
+ ; otherwise, so this is undefined behavior.
+
+ br i1 %cmp, label %second_true, label %second_end
+ ; The same branch again, but this time the
+ ; true block doesn't have side effects.
+
+second_true:
+ ; No side effects!
+ ret void
+
+second_end:
+ store volatile i32 0, i32* @g ; This time, the instruction always depends
+ ; on the store in %end. Also, it is
+ ; control-equivalent to %end, so this is
+ ; well-defined (ignoring earlier undefined
+ ; behavior in this example).
+</pre>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="blockaddress">Addresses of Basic Blocks</a>
+</h3>
+
+<div>
+
+<p><b><tt>blockaddress(@function, %block)</tt></b></p>
+
+<p>The '<tt>blockaddress</tt>' constant computes the address of the specified
+ basic block in the specified function, and always has an i8* type. Taking
+ the address of the entry block is illegal.</p>
+
+<p>This value only has defined behavior when used as an operand to the
+ '<a href="#i_indirectbr"><tt>indirectbr</tt></a>' instruction, or for
+ comparisons against null. Pointer equality tests between labels addresses
+ results in undefined behavior &mdash; though, again, comparison against null
+ is ok, and no label is equal to the null pointer. This may be passed around
+ as an opaque pointer sized value as long as the bits are not inspected. This
+ allows <tt>ptrtoint</tt> and arithmetic to be performed on these values so
+ long as the original value is reconstituted before the <tt>indirectbr</tt>
+ instruction.</p>
+
+<p>Finally, some targets may provide defined semantics when using the value as
+ the operand to an inline assembly, but that is target specific.</p>
+
+</div>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="constantexprs">Constant Expressions</a>
+</h3>
+
+<div>
+
+<p>Constant expressions are used to allow expressions involving other constants
+ to be used as constants. Constant expressions may be of
+ any <a href="#t_firstclass">first class</a> type and may involve any LLVM
+ operation that does not have side effects (e.g. load and call are not
+ supported). The following is the syntax for constant expressions:</p>
+
+<dl>
+ <dt><b><tt>trunc (CST to TYPE)</tt></b></dt>
+ <dd>Truncate a constant to another type. The bit size of CST must be larger
+ than the bit size of TYPE. Both types must be integers.</dd>
+
+ <dt><b><tt>zext (CST to TYPE)</tt></b></dt>
+ <dd>Zero extend a constant to another type. The bit size of CST must be
+ smaller than the bit size of TYPE. Both types must be integers.</dd>
+
+ <dt><b><tt>sext (CST to TYPE)</tt></b></dt>
+ <dd>Sign extend a constant to another type. The bit size of CST must be
+ smaller than the bit size of TYPE. Both types must be integers.</dd>
+
+ <dt><b><tt>fptrunc (CST to TYPE)</tt></b></dt>
+ <dd>Truncate a floating point constant to another floating point type. The
+ size of CST must be larger than the size of TYPE. Both types must be
+ floating point.</dd>
+
+ <dt><b><tt>fpext (CST to TYPE)</tt></b></dt>
+ <dd>Floating point extend a constant to another type. The size of CST must be
+ smaller or equal to the size of TYPE. Both types must be floating
+ point.</dd>
+
+ <dt><b><tt>fptoui (CST to TYPE)</tt></b></dt>
+ <dd>Convert a floating point constant to the corresponding unsigned integer
+ constant. TYPE must be a scalar or vector integer type. CST must be of
+ scalar or vector floating point type. Both CST and TYPE must be scalars,
+ or vectors of the same number of elements. If the value won't fit in the
+ integer type, the results are undefined.</dd>
+
+ <dt><b><tt>fptosi (CST to TYPE)</tt></b></dt>
+ <dd>Convert a floating point constant to the corresponding signed integer
+ constant. TYPE must be a scalar or vector integer type. CST must be of
+ scalar or vector floating point type. Both CST and TYPE must be scalars,
+ or vectors of the same number of elements. If the value won't fit in the
+ integer type, the results are undefined.</dd>
+
+ <dt><b><tt>uitofp (CST to TYPE)</tt></b></dt>
+ <dd>Convert an unsigned integer constant to the corresponding floating point
+ constant. TYPE must be a scalar or vector floating point type. CST must be
+ of scalar or vector integer type. Both CST and TYPE must be scalars, or
+ vectors of the same number of elements. If the value won't fit in the
+ floating point type, the results are undefined.</dd>
+
+ <dt><b><tt>sitofp (CST to TYPE)</tt></b></dt>
+ <dd>Convert a signed integer constant to the corresponding floating point
+ constant. TYPE must be a scalar or vector floating point type. CST must be
+ of scalar or vector integer type. Both CST and TYPE must be scalars, or
+ vectors of the same number of elements. If the value won't fit in the
+ floating point type, the results are undefined.</dd>
+
+ <dt><b><tt>ptrtoint (CST to TYPE)</tt></b></dt>
+ <dd>Convert a pointer typed constant to the corresponding integer constant
+ <tt>TYPE</tt> must be an integer type. <tt>CST</tt> must be of pointer
+ type. The <tt>CST</tt> value is zero extended, truncated, or unchanged to
+ make it fit in <tt>TYPE</tt>.</dd>
+
+ <dt><b><tt>inttoptr (CST to TYPE)</tt></b></dt>
+ <dd>Convert an integer constant to a pointer constant. TYPE must be a pointer
+ type. CST must be of integer type. The CST value is zero extended,
+ truncated, or unchanged to make it fit in a pointer size. This one is
+ <i>really</i> dangerous!</dd>
+
+ <dt><b><tt>bitcast (CST to TYPE)</tt></b></dt>
+ <dd>Convert a constant, CST, to another TYPE. The constraints of the operands
+ are the same as those for the <a href="#i_bitcast">bitcast
+ instruction</a>.</dd>
+
+ <dt><b><tt>getelementptr (CSTPTR, IDX0, IDX1, ...)</tt></b></dt>
+ <dt><b><tt>getelementptr inbounds (CSTPTR, IDX0, IDX1, ...)</tt></b></dt>
+ <dd>Perform the <a href="#i_getelementptr">getelementptr operation</a> on
+ constants. As with the <a href="#i_getelementptr">getelementptr</a>
+ instruction, the index list may have zero or more indexes, which are
+ required to make sense for the type of "CSTPTR".</dd>
+
+ <dt><b><tt>select (COND, VAL1, VAL2)</tt></b></dt>
+ <dd>Perform the <a href="#i_select">select operation</a> on constants.</dd>
+
+ <dt><b><tt>icmp COND (VAL1, VAL2)</tt></b></dt>
+ <dd>Performs the <a href="#i_icmp">icmp operation</a> on constants.</dd>
+
+ <dt><b><tt>fcmp COND (VAL1, VAL2)</tt></b></dt>
+ <dd>Performs the <a href="#i_fcmp">fcmp operation</a> on constants.</dd>
+
+ <dt><b><tt>extractelement (VAL, IDX)</tt></b></dt>
+ <dd>Perform the <a href="#i_extractelement">extractelement operation</a> on
+ constants.</dd>
+
+ <dt><b><tt>insertelement (VAL, ELT, IDX)</tt></b></dt>
+ <dd>Perform the <a href="#i_insertelement">insertelement operation</a> on
+ constants.</dd>
+
+ <dt><b><tt>shufflevector (VEC1, VEC2, IDXMASK)</tt></b></dt>
+ <dd>Perform the <a href="#i_shufflevector">shufflevector operation</a> on
+ constants.</dd>
+
+ <dt><b><tt>extractvalue (VAL, IDX0, IDX1, ...)</tt></b></dt>
+ <dd>Perform the <a href="#i_extractvalue">extractvalue operation</a> on
+ constants. The index list is interpreted in a similar manner as indices in
+ a '<a href="#i_getelementptr">getelementptr</a>' operation. At least one
+ index value must be specified.</dd>
+
+ <dt><b><tt>insertvalue (VAL, ELT, IDX0, IDX1, ...)</tt></b></dt>
+ <dd>Perform the <a href="#i_insertvalue">insertvalue operation</a> on
+ constants. The index list is interpreted in a similar manner as indices in
+ a '<a href="#i_getelementptr">getelementptr</a>' operation. At least one
+ index value must be specified.</dd>
+
+ <dt><b><tt>OPCODE (LHS, RHS)</tt></b></dt>
+ <dd>Perform the specified operation of the LHS and RHS constants. OPCODE may
+ be any of the <a href="#binaryops">binary</a>
+ or <a href="#bitwiseops">bitwise binary</a> operations. The constraints
+ on operands are the same as those for the corresponding instruction
+ (e.g. no bitwise operations on floating point values are allowed).</dd>
+</dl>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="othervalues">Other Values</a></h2>
+<!-- *********************************************************************** -->
+<div>
+<!-- ======================================================================= -->
+<h3>
+<a name="inlineasm">Inline Assembler Expressions</a>
+</h3>
+
+<div>
+
+<p>LLVM supports inline assembler expressions (as opposed
+ to <a href="#moduleasm">Module-Level Inline Assembly</a>) through the use of
+ a special value. This value represents the inline assembler as a string
+ (containing the instructions to emit), a list of operand constraints (stored
+ as a string), a flag that indicates whether or not the inline asm
+ expression has side effects, and a flag indicating whether the function
+ containing the asm needs to align its stack conservatively. An example
+ inline assembler expression is:</p>
+
+<pre class="doc_code">
+i32 (i32) asm "bswap $0", "=r,r"
+</pre>
+
+<p>Inline assembler expressions may <b>only</b> be used as the callee operand of
+ a <a href="#i_call"><tt>call</tt></a> or an
+ <a href="#i_invoke"><tt>invoke</tt></a> instruction.
+ Thus, typically we have:</p>
+
+<pre class="doc_code">
+%X = call i32 asm "<a href="#int_bswap">bswap</a> $0", "=r,r"(i32 %Y)
+</pre>
+
+<p>Inline asms with side effects not visible in the constraint list must be
+ marked as having side effects. This is done through the use of the
+ '<tt>sideeffect</tt>' keyword, like so:</p>
+
+<pre class="doc_code">
+call void asm sideeffect "eieio", ""()
+</pre>
+
+<p>In some cases inline asms will contain code that will not work unless the
+ stack is aligned in some way, such as calls or SSE instructions on x86,
+ yet will not contain code that does that alignment within the asm.
+ The compiler should make conservative assumptions about what the asm might
+ contain and should generate its usual stack alignment code in the prologue
+ if the '<tt>alignstack</tt>' keyword is present:</p>
+
+<pre class="doc_code">
+call void asm alignstack "eieio", ""()
+</pre>
+
+<p>Inline asms also support using non-standard assembly dialects. The assumed
+ dialect is ATT. When the '<tt>inteldialect</tt>' keyword is present, the
+ inline asm is using the Intel dialect. Currently, ATT and Intel are the
+ only supported dialects. An example is:</p>
+
+<pre class="doc_code">
+call void asm inteldialect "eieio", ""()
+</pre>
+
+<p>If multiple keywords appear the '<tt>sideeffect</tt>' keyword must come
+ first, the '<tt>alignstack</tt>' keyword second and the
+ '<tt>inteldialect</tt>' keyword last.</p>
+
+<!--
+<p>TODO: The format of the asm and constraints string still need to be
+ documented here. Constraints on what can be done (e.g. duplication, moving,
+ etc need to be documented). This is probably best done by reference to
+ another document that covers inline asm from a holistic perspective.</p>
+ -->
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="inlineasm_md">Inline Asm Metadata</a>
+</h4>
+
+<div>
+
+<p>The call instructions that wrap inline asm nodes may have a
+ "<tt>!srcloc</tt>" MDNode attached to it that contains a list of constant
+ integers. If present, the code generator will use the integer as the
+ location cookie value when report errors through the <tt>LLVMContext</tt>
+ error reporting mechanisms. This allows a front-end to correlate backend
+ errors that occur with inline asm back to the source code that produced it.
+ For example:</p>
+
+<pre class="doc_code">
+call void asm sideeffect "something bad", ""()<b>, !srcloc !42</b>
+...
+!42 = !{ i32 1234567 }
+</pre>
+
+<p>It is up to the front-end to make sense of the magic numbers it places in the
+ IR. If the MDNode contains multiple constants, the code generator will use
+ the one that corresponds to the line of the asm that the error occurs on.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="metadata">Metadata Nodes and Metadata Strings</a>
+</h3>
+
+<div>
+
+<p>LLVM IR allows metadata to be attached to instructions in the program that
+ can convey extra information about the code to the optimizers and code
+ generator. One example application of metadata is source-level debug
+ information. There are two metadata primitives: strings and nodes. All
+ metadata has the <tt>metadata</tt> type and is identified in syntax by a
+ preceding exclamation point ('<tt>!</tt>').</p>
+
+<p>A metadata string is a string surrounded by double quotes. It can contain
+ any character by escaping non-printable characters with "<tt>\xx</tt>" where
+ "<tt>xx</tt>" is the two digit hex code. For example:
+ "<tt>!"test\00"</tt>".</p>
+
+<p>Metadata nodes are represented with notation similar to structure constants
+ (a comma separated list of elements, surrounded by braces and preceded by an
+ exclamation point). Metadata nodes can have any values as their operand. For
+ example:</p>
+
+<div class="doc_code">
+<pre>
+!{ metadata !"test\00", i32 10}
+</pre>
+</div>
+
+<p>A <a href="#namedmetadatastructure">named metadata</a> is a collection of
+ metadata nodes, which can be looked up in the module symbol table. For
+ example:</p>
+
+<div class="doc_code">
+<pre>
+!foo = metadata !{!4, !3}
+</pre>
+</div>
+
+<p>Metadata can be used as function arguments. Here <tt>llvm.dbg.value</tt>
+ function is using two metadata arguments:</p>
+
+<div class="doc_code">
+<pre>
+call void @llvm.dbg.value(metadata !24, i64 0, metadata !25)
+</pre>
+</div>
+
+<p>Metadata can be attached with an instruction. Here metadata <tt>!21</tt> is
+ attached to the <tt>add</tt> instruction using the <tt>!dbg</tt>
+ identifier:</p>
+
+<div class="doc_code">
+<pre>
+%indvar.next = add i64 %indvar, 1, !dbg !21
+</pre>
+</div>
+
+<p>More information about specific metadata nodes recognized by the optimizers
+ and code generator is found below.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="tbaa">'<tt>tbaa</tt>' Metadata</a>
+</h4>
+
+<div>
+
+<p>In LLVM IR, memory does not have types, so LLVM's own type system is not
+ suitable for doing TBAA. Instead, metadata is added to the IR to describe
+ a type system of a higher level language. This can be used to implement
+ typical C/C++ TBAA, but it can also be used to implement custom alias
+ analysis behavior for other languages.</p>
+
+<p>The current metadata format is very simple. TBAA metadata nodes have up to
+ three fields, e.g.:</p>
+
+<div class="doc_code">
+<pre>
+!0 = metadata !{ metadata !"an example type tree" }
+!1 = metadata !{ metadata !"int", metadata !0 }
+!2 = metadata !{ metadata !"float", metadata !0 }
+!3 = metadata !{ metadata !"const float", metadata !2, i64 1 }
+</pre>
+</div>
+
+<p>The first field is an identity field. It can be any value, usually
+ a metadata string, which uniquely identifies the type. The most important
+ name in the tree is the name of the root node. Two trees with
+ different root node names are entirely disjoint, even if they
+ have leaves with common names.</p>
+
+<p>The second field identifies the type's parent node in the tree, or
+ is null or omitted for a root node. A type is considered to alias
+ all of its descendants and all of its ancestors in the tree. Also,
+ a type is considered to alias all types in other trees, so that
+ bitcode produced from multiple front-ends is handled conservatively.</p>
+
+<p>If the third field is present, it's an integer which if equal to 1
+ indicates that the type is "constant" (meaning
+ <tt>pointsToConstantMemory</tt> should return true; see
+ <a href="AliasAnalysis.html#OtherItfs">other useful
+ <tt>AliasAnalysis</tt> methods</a>).</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="fpmath">'<tt>fpmath</tt>' Metadata</a>
+</h4>
+
+<div>
+
+<p><tt>fpmath</tt> metadata may be attached to any instruction of floating point
+ type. It can be used to express the maximum acceptable error in the result of
+ that instruction, in ULPs, thus potentially allowing the compiler to use a
+ more efficient but less accurate method of computing it. ULP is defined as
+ follows:</p>
+
+<blockquote>
+
+<p>If <tt>x</tt> is a real number that lies between two finite consecutive
+ floating-point numbers <tt>a</tt> and <tt>b</tt>, without being equal to one
+ of them, then <tt>ulp(x) = |b - a|</tt>, otherwise <tt>ulp(x)</tt> is the
+ distance between the two non-equal finite floating-point numbers nearest
+ <tt>x</tt>. Moreover, <tt>ulp(NaN)</tt> is <tt>NaN</tt>.</p>
+
+</blockquote>
+
+<p>The metadata node shall consist of a single positive floating point number
+ representing the maximum relative error, for example:</p>
+
+<div class="doc_code">
+<pre>
+!0 = metadata !{ float 2.5 } ; maximum acceptable inaccuracy is 2.5 ULPs
+</pre>
+</div>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="range">'<tt>range</tt>' Metadata</a>
+</h4>
+
+<div>
+<p><tt>range</tt> metadata may be attached only to loads of integer types. It
+ expresses the possible ranges the loaded value is in. The ranges are
+ represented with a flattened list of integers. The loaded value is known to
+ be in the union of the ranges defined by each consecutive pair. Each pair
+ has the following properties:</p>
+<ul>
+ <li>The type must match the type loaded by the instruction.</li>
+ <li>The pair <tt>a,b</tt> represents the range <tt>[a,b)</tt>.</li>
+ <li>Both <tt>a</tt> and <tt>b</tt> are constants.</li>
+ <li>The range is allowed to wrap.</li>
+ <li>The range should not represent the full or empty set. That is,
+ <tt>a!=b</tt>. </li>
+</ul>
+<p> In addition, the pairs must be in signed order of the lower bound and
+ they must be non-contiguous.</p>
+
+<p>Examples:</p>
+<div class="doc_code">
+<pre>
+ %a = load i8* %x, align 1, !range !0 ; Can only be 0 or 1
+ %b = load i8* %y, align 1, !range !1 ; Can only be 255 (-1), 0 or 1
+ %c = load i8* %z, align 1, !range !2 ; Can only be 0, 1, 3, 4 or 5
+ %d = load i8* %z, align 1, !range !3 ; Can only be -2, -1, 3, 4 or 5
+...
+!0 = metadata !{ i8 0, i8 2 }
+!1 = metadata !{ i8 255, i8 2 }
+!2 = metadata !{ i8 0, i8 2, i8 3, i8 6 }
+!3 = metadata !{ i8 -2, i8 0, i8 3, i8 6 }
+</pre>
+</div>
+</div>
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="module_flags">Module Flags Metadata</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Information about the module as a whole is difficult to convey to LLVM's
+ subsystems. The LLVM IR isn't sufficient to transmit this
+ information. The <tt>llvm.module.flags</tt> named metadata exists in order to
+ facilitate this. These flags are in the form of key / value pairs &mdash;
+ much like a dictionary &mdash; making it easy for any subsystem who cares
+ about a flag to look it up.</p>
+
+<p>The <tt>llvm.module.flags</tt> metadata contains a list of metadata
+ triplets. Each triplet has the following form:</p>
+
+<ul>
+ <li>The first element is a <i>behavior</i> flag, which specifies the behavior
+ when two (or more) modules are merged together, and it encounters two (or
+ more) metadata with the same ID. The supported behaviors are described
+ below.</li>
+
+ <li>The second element is a metadata string that is a unique ID for the
+ metadata. How each ID is interpreted is documented below.</li>
+
+ <li>The third element is the value of the flag.</li>
+</ul>
+
+<p>When two (or more) modules are merged together, the resulting
+ <tt>llvm.module.flags</tt> metadata is the union of the
+ modules' <tt>llvm.module.flags</tt> metadata. The only exception being a flag
+ with the <i>Override</i> behavior, which may override another flag's value
+ (see below).</p>
+
+<p>The following behaviors are supported:</p>
+
+<table border="1" cellspacing="0" cellpadding="4">
+ <tbody>
+ <tr>
+ <th>Value</th>
+ <th>Behavior</th>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td align="left">
+ <dl>
+ <dt><b>Error</b></dt>
+ <dd>Emits an error if two values disagree. It is an error to have an ID
+ with both an Error and a Warning behavior.</dd>
+ </dl>
+ </td>
+ </tr>
+ <tr>
+ <td>2</td>
+ <td align="left">
+ <dl>
+ <dt><b>Warning</b></dt>
+ <dd>Emits a warning if two values disagree.</dd>
+ </dl>
+ </td>
+ </tr>
+ <tr>
+ <td>3</td>
+ <td align="left">
+ <dl>
+ <dt><b>Require</b></dt>
+ <dd>Emits an error when the specified value is not present or doesn't
+ have the specified value. It is an error for two (or more)
+ <tt>llvm.module.flags</tt> with the same ID to have the Require
+ behavior but different values. There may be multiple Require flags
+ per ID.</dd>
+ </dl>
+ </td>
+ </tr>
+ <tr>
+ <td>4</td>
+ <td align="left">
+ <dl>
+ <dt><b>Override</b></dt>
+ <dd>Uses the specified value if the two values disagree. It is an
+ error for two (or more) <tt>llvm.module.flags</tt> with the same
+ ID to have the Override behavior but different values.</dd>
+ </dl>
+ </td>
+ </tr>
+ </tbody>
+</table>
+
+<p>An example of module flags:</p>
+
+<pre class="doc_code">
+!0 = metadata !{ i32 1, metadata !"foo", i32 1 }
+!1 = metadata !{ i32 4, metadata !"bar", i32 37 }
+!2 = metadata !{ i32 2, metadata !"qux", i32 42 }
+!3 = metadata !{ i32 3, metadata !"qux",
+ metadata !{
+ metadata !"foo", i32 1
+ }
+}
+!llvm.module.flags = !{ !0, !1, !2, !3 }
+</pre>
+
+<ul>
+ <li><p>Metadata <tt>!0</tt> has the ID <tt>!"foo"</tt> and the value '1'. The
+ behavior if two or more <tt>!"foo"</tt> flags are seen is to emit an
+ error if their values are not equal.</p></li>
+
+ <li><p>Metadata <tt>!1</tt> has the ID <tt>!"bar"</tt> and the value '37'. The
+ behavior if two or more <tt>!"bar"</tt> flags are seen is to use the
+ value '37' if their values are not equal.</p></li>
+
+ <li><p>Metadata <tt>!2</tt> has the ID <tt>!"qux"</tt> and the value '42'. The
+ behavior if two or more <tt>!"qux"</tt> flags are seen is to emit a
+ warning if their values are not equal.</p></li>
+
+ <li><p>Metadata <tt>!3</tt> has the ID <tt>!"qux"</tt> and the value:</p>
+
+<pre class="doc_code">
+metadata !{ metadata !"foo", i32 1 }
+</pre>
+
+ <p>The behavior is to emit an error if the <tt>llvm.module.flags</tt> does
+ not contain a flag with the ID <tt>!"foo"</tt> that has the value
+ '1'. If two or more <tt>!"qux"</tt> flags exist, then they must have
+ the same value or an error will be issued.</p></li>
+</ul>
+
+
+<!-- ======================================================================= -->
+<h3>
+<a name="objc_gc_flags">Objective-C Garbage Collection Module Flags Metadata</a>
+</h3>
+
+<div>
+
+<p>On the Mach-O platform, Objective-C stores metadata about garbage collection
+ in a special section called "image info". The metadata consists of a version
+ number and a bitmask specifying what types of garbage collection are
+ supported (if any) by the file. If two or more modules are linked together
+ their garbage collection metadata needs to be merged rather than appended
+ together.</p>
+
+<p>The Objective-C garbage collection module flags metadata consists of the
+ following key-value pairs:</p>
+
+<table border="1" cellspacing="0" cellpadding="4">
+ <col width="30%">
+ <tbody>
+ <tr>
+ <th>Key</th>
+ <th>Value</th>
+ </tr>
+ <tr>
+ <td><tt>Objective-C&nbsp;Version</tt></td>
+ <td align="left"><b>[Required]</b> &mdash; The Objective-C ABI
+ version. Valid values are 1 and 2.</td>
+ </tr>
+ <tr>
+ <td><tt>Objective-C&nbsp;Image&nbsp;Info&nbsp;Version</tt></td>
+ <td align="left"><b>[Required]</b> &mdash; The version of the image info
+ section. Currently always 0.</td>
+ </tr>
+ <tr>
+ <td><tt>Objective-C&nbsp;Image&nbsp;Info&nbsp;Section</tt></td>
+ <td align="left"><b>[Required]</b> &mdash; The section to place the
+ metadata. Valid values are <tt>"__OBJC, __image_info, regular"</tt> for
+ Objective-C ABI version 1, and <tt>"__DATA,__objc_imageinfo, regular,
+ no_dead_strip"</tt> for Objective-C ABI version 2.</td>
+ </tr>
+ <tr>
+ <td><tt>Objective-C&nbsp;Garbage&nbsp;Collection</tt></td>
+ <td align="left"><b>[Required]</b> &mdash; Specifies whether garbage
+ collection is supported or not. Valid values are 0, for no garbage
+ collection, and 2, for garbage collection supported.</td>
+ </tr>
+ <tr>
+ <td><tt>Objective-C&nbsp;GC&nbsp;Only</tt></td>
+ <td align="left"><b>[Optional]</b> &mdash; Specifies that only garbage
+ collection is supported. If present, its value must be 6. This flag
+ requires that the <tt>Objective-C Garbage Collection</tt> flag have the
+ value 2.</td>
+ </tr>
+ </tbody>
+</table>
+
+<p>Some important flag interactions:</p>
+
+<ul>
+ <li>If a module with <tt>Objective-C Garbage Collection</tt> set to 0 is
+ merged with a module with <tt>Objective-C Garbage Collection</tt> set to
+ 2, then the resulting module has the <tt>Objective-C Garbage
+ Collection</tt> flag set to 0.</li>
+
+ <li>A module with <tt>Objective-C Garbage Collection</tt> set to 0 cannot be
+ merged with a module with <tt>Objective-C GC Only</tt> set to 6.</li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="intrinsic_globals">Intrinsic Global Variables</a>
+</h2>
+<!-- *********************************************************************** -->
+<div>
+<p>LLVM has a number of "magic" global variables that contain data that affect
+code generation or other IR semantics. These are documented here. All globals
+of this sort should have a section specified as "<tt>llvm.metadata</tt>". This
+section and all globals that start with "<tt>llvm.</tt>" are reserved for use
+by LLVM.</p>
+
+<!-- ======================================================================= -->
+<h3>
+<a name="intg_used">The '<tt>llvm.used</tt>' Global Variable</a>
+</h3>
+
+<div>
+
+<p>The <tt>@llvm.used</tt> global is an array with i8* element type which has <a
+href="#linkage_appending">appending linkage</a>. This array contains a list of
+pointers to global variables and functions which may optionally have a pointer
+cast formed of bitcast or getelementptr. For example, a legal use of it is:</p>
+
+<div class="doc_code">
+<pre>
+@X = global i8 4
+@Y = global i32 123
+
+@llvm.used = appending global [2 x i8*] [
+ i8* @X,
+ i8* bitcast (i32* @Y to i8*)
+], section "llvm.metadata"
+</pre>
+</div>
+
+<p>If a global variable appears in the <tt>@llvm.used</tt> list, then the
+ compiler, assembler, and linker are required to treat the symbol as if there
+ is a reference to the global that it cannot see. For example, if a variable
+ has internal linkage and no references other than that from
+ the <tt>@llvm.used</tt> list, it cannot be deleted. This is commonly used to
+ represent references from inline asms and other things the compiler cannot
+ "see", and corresponds to "<tt>attribute((used))</tt>" in GNU C.</p>
+
+<p>On some targets, the code generator must emit a directive to the assembler or
+ object file to prevent the assembler and linker from molesting the
+ symbol.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="intg_compiler_used">
+ The '<tt>llvm.compiler.used</tt>' Global Variable
+ </a>
+</h3>
+
+<div>
+
+<p>The <tt>@llvm.compiler.used</tt> directive is the same as the
+ <tt>@llvm.used</tt> directive, except that it only prevents the compiler from
+ touching the symbol. On targets that support it, this allows an intelligent
+ linker to optimize references to the symbol without being impeded as it would
+ be by <tt>@llvm.used</tt>.</p>
+
+<p>This is a rare construct that should only be used in rare circumstances, and
+ should not be exposed to source languages.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+<a name="intg_global_ctors">The '<tt>llvm.global_ctors</tt>' Global Variable</a>
+</h3>
+
+<div>
+
+<div class="doc_code">
+<pre>
+%0 = type { i32, void ()* }
+@llvm.global_ctors = appending global [1 x %0] [%0 { i32 65535, void ()* @ctor }]
+</pre>
+</div>
+
+<p>The <tt>@llvm.global_ctors</tt> array contains a list of constructor
+ functions and associated priorities. The functions referenced by this array
+ will be called in ascending order of priority (i.e. lowest first) when the
+ module is loaded. The order of functions with the same priority is not
+ defined.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+<a name="intg_global_dtors">The '<tt>llvm.global_dtors</tt>' Global Variable</a>
+</h3>
+
+<div>
+
+<div class="doc_code">
+<pre>
+%0 = type { i32, void ()* }
+@llvm.global_dtors = appending global [1 x %0] [%0 { i32 65535, void ()* @dtor }]
+</pre>
+</div>
+
+<p>The <tt>@llvm.global_dtors</tt> array contains a list of destructor functions
+ and associated priorities. The functions referenced by this array will be
+ called in descending order of priority (i.e. highest first) when the module
+ is loaded. The order of functions with the same priority is not defined.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="instref">Instruction Reference</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The LLVM instruction set consists of several different classifications of
+ instructions: <a href="#terminators">terminator
+ instructions</a>, <a href="#binaryops">binary instructions</a>,
+ <a href="#bitwiseops">bitwise binary instructions</a>,
+ <a href="#memoryops">memory instructions</a>, and
+ <a href="#otherops">other instructions</a>.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="terminators">Terminator Instructions</a>
+</h3>
+
+<div>
+
+<p>As mentioned <a href="#functionstructure">previously</a>, every basic block
+ in a program ends with a "Terminator" instruction, which indicates which
+ block should be executed after the current block is finished. These
+ terminator instructions typically yield a '<tt>void</tt>' value: they produce
+ control flow, not values (the one exception being the
+ '<a href="#i_invoke"><tt>invoke</tt></a>' instruction).</p>
+
+<p>The terminator instructions are:
+ '<a href="#i_ret"><tt>ret</tt></a>',
+ '<a href="#i_br"><tt>br</tt></a>',
+ '<a href="#i_switch"><tt>switch</tt></a>',
+ '<a href="#i_indirectbr"><tt>indirectbr</tt></a>',
+ '<a href="#i_invoke"><tt>invoke</tt></a>',
+ '<a href="#i_resume"><tt>resume</tt></a>', and
+ '<a href="#i_unreachable"><tt>unreachable</tt></a>'.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_ret">'<tt>ret</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ ret &lt;type&gt; &lt;value&gt; <i>; Return a value from a non-void function</i>
+ ret void <i>; Return from void function</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>ret</tt>' instruction is used to return control flow (and optionally
+ a value) from a function back to the caller.</p>
+
+<p>There are two forms of the '<tt>ret</tt>' instruction: one that returns a
+ value and then causes control flow, and one that just causes control flow to
+ occur.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>ret</tt>' instruction optionally accepts a single argument, the
+ return value. The type of the return value must be a
+ '<a href="#t_firstclass">first class</a>' type.</p>
+
+<p>A function is not <a href="#wellformed">well formed</a> if it it has a
+ non-void return type and contains a '<tt>ret</tt>' instruction with no return
+ value or a return value with a type that does not match its type, or if it
+ has a void return type and contains a '<tt>ret</tt>' instruction with a
+ return value.</p>
+
+<h5>Semantics:</h5>
+<p>When the '<tt>ret</tt>' instruction is executed, control flow returns back to
+ the calling function's context. If the caller is a
+ "<a href="#i_call"><tt>call</tt></a>" instruction, execution continues at the
+ instruction after the call. If the caller was an
+ "<a href="#i_invoke"><tt>invoke</tt></a>" instruction, execution continues at
+ the beginning of the "normal" destination block. If the instruction returns
+ a value, that value shall set the call or invoke instruction's return
+ value.</p>
+
+<h5>Example:</h5>
+<pre>
+ ret i32 5 <i>; Return an integer value of 5</i>
+ ret void <i>; Return from a void function</i>
+ ret { i32, i8 } { i32 4, i8 2 } <i>; Return a struct of values 4 and 2</i>
+</pre>
+
+</div>
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_br">'<tt>br</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ br i1 &lt;cond&gt;, label &lt;iftrue&gt;, label &lt;iffalse&gt;
+ br label &lt;dest&gt; <i>; Unconditional branch</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>br</tt>' instruction is used to cause control flow to transfer to a
+ different basic block in the current function. There are two forms of this
+ instruction, corresponding to a conditional branch and an unconditional
+ branch.</p>
+
+<h5>Arguments:</h5>
+<p>The conditional branch form of the '<tt>br</tt>' instruction takes a single
+ '<tt>i1</tt>' value and two '<tt>label</tt>' values. The unconditional form
+ of the '<tt>br</tt>' instruction takes a single '<tt>label</tt>' value as a
+ target.</p>
+
+<h5>Semantics:</h5>
+<p>Upon execution of a conditional '<tt>br</tt>' instruction, the '<tt>i1</tt>'
+ argument is evaluated. If the value is <tt>true</tt>, control flows to the
+ '<tt>iftrue</tt>' <tt>label</tt> argument. If "cond" is <tt>false</tt>,
+ control flows to the '<tt>iffalse</tt>' <tt>label</tt> argument.</p>
+
+<h5>Example:</h5>
+<pre>
+Test:
+ %cond = <a href="#i_icmp">icmp</a> eq i32 %a, %b
+ br i1 %cond, label %IfEqual, label %IfUnequal
+IfEqual:
+ <a href="#i_ret">ret</a> i32 1
+IfUnequal:
+ <a href="#i_ret">ret</a> i32 0
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_switch">'<tt>switch</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ switch &lt;intty&gt; &lt;value&gt;, label &lt;defaultdest&gt; [ &lt;intty&gt; &lt;val&gt;, label &lt;dest&gt; ... ]
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>switch</tt>' instruction is used to transfer control flow to one of
+ several different places. It is a generalization of the '<tt>br</tt>'
+ instruction, allowing a branch to occur to one of many possible
+ destinations.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>switch</tt>' instruction uses three parameters: an integer
+ comparison value '<tt>value</tt>', a default '<tt>label</tt>' destination,
+ and an array of pairs of comparison value constants and '<tt>label</tt>'s.
+ The table is not allowed to contain duplicate constant entries.</p>
+
+<h5>Semantics:</h5>
+<p>The <tt>switch</tt> instruction specifies a table of values and
+ destinations. When the '<tt>switch</tt>' instruction is executed, this table
+ is searched for the given value. If the value is found, control flow is
+ transferred to the corresponding destination; otherwise, control flow is
+ transferred to the default destination.</p>
+
+<h5>Implementation:</h5>
+<p>Depending on properties of the target machine and the particular
+ <tt>switch</tt> instruction, this instruction may be code generated in
+ different ways. For example, it could be generated as a series of chained
+ conditional branches or with a lookup table.</p>
+
+<h5>Example:</h5>
+<pre>
+ <i>; Emulate a conditional br instruction</i>
+ %Val = <a href="#i_zext">zext</a> i1 %value to i32
+ switch i32 %Val, label %truedest [ i32 0, label %falsedest ]
+
+ <i>; Emulate an unconditional br instruction</i>
+ switch i32 0, label %dest [ ]
+
+ <i>; Implement a jump table:</i>
+ switch i32 %val, label %otherwise [ i32 0, label %onzero
+ i32 1, label %onone
+ i32 2, label %ontwo ]
+</pre>
+
+</div>
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_indirectbr">'<tt>indirectbr</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ indirectbr &lt;somety&gt;* &lt;address&gt;, [ label &lt;dest1&gt;, label &lt;dest2&gt;, ... ]
+</pre>
+
+<h5>Overview:</h5>
+
+<p>The '<tt>indirectbr</tt>' instruction implements an indirect branch to a label
+ within the current function, whose address is specified by
+ "<tt>address</tt>". Address must be derived from a <a
+ href="#blockaddress">blockaddress</a> constant.</p>
+
+<h5>Arguments:</h5>
+
+<p>The '<tt>address</tt>' argument is the address of the label to jump to. The
+ rest of the arguments indicate the full set of possible destinations that the
+ address may point to. Blocks are allowed to occur multiple times in the
+ destination list, though this isn't particularly useful.</p>
+
+<p>This destination list is required so that dataflow analysis has an accurate
+ understanding of the CFG.</p>
+
+<h5>Semantics:</h5>
+
+<p>Control transfers to the block specified in the address argument. All
+ possible destination blocks must be listed in the label list, otherwise this
+ instruction has undefined behavior. This implies that jumps to labels
+ defined in other functions have undefined behavior as well.</p>
+
+<h5>Implementation:</h5>
+
+<p>This is typically implemented with a jump through a register.</p>
+
+<h5>Example:</h5>
+<pre>
+ indirectbr i8* %Addr, [ label %bb1, label %bb2, label %bb3 ]
+</pre>
+
+</div>
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_invoke">'<tt>invoke</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = invoke [<a href="#callingconv">cconv</a>] [<a href="#paramattrs">ret attrs</a>] &lt;ptr to function ty&gt; &lt;function ptr val&gt;(&lt;function args&gt;) [<a href="#fnattrs">fn attrs</a>]
+ to label &lt;normal label&gt; unwind label &lt;exception label&gt;
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>invoke</tt>' instruction causes control to transfer to a specified
+ function, with the possibility of control flow transfer to either the
+ '<tt>normal</tt>' label or the '<tt>exception</tt>' label. If the callee
+ function returns with the "<tt><a href="#i_ret">ret</a></tt>" instruction,
+ control flow will return to the "normal" label. If the callee (or any
+ indirect callees) returns via the "<a href="#i_resume"><tt>resume</tt></a>"
+ instruction or other exception handling mechanism, control is interrupted and
+ continued at the dynamically nearest "exception" label.</p>
+
+<p>The '<tt>exception</tt>' label is a
+ <i><a href="ExceptionHandling.html#overview">landing pad</a></i> for the
+ exception. As such, '<tt>exception</tt>' label is required to have the
+ "<a href="#i_landingpad"><tt>landingpad</tt></a>" instruction, which contains
+ the information about the behavior of the program after unwinding
+ happens, as its first non-PHI instruction. The restrictions on the
+ "<tt>landingpad</tt>" instruction's tightly couples it to the
+ "<tt>invoke</tt>" instruction, so that the important information contained
+ within the "<tt>landingpad</tt>" instruction can't be lost through normal
+ code motion.</p>
+
+<h5>Arguments:</h5>
+<p>This instruction requires several arguments:</p>
+
+<ol>
+ <li>The optional "cconv" marker indicates which <a href="#callingconv">calling
+ convention</a> the call should use. If none is specified, the call
+ defaults to using C calling conventions.</li>
+
+ <li>The optional <a href="#paramattrs">Parameter Attributes</a> list for
+ return values. Only '<tt>zeroext</tt>', '<tt>signext</tt>', and
+ '<tt>inreg</tt>' attributes are valid here.</li>
+
+ <li>'<tt>ptr to function ty</tt>': shall be the signature of the pointer to
+ function value being invoked. In most cases, this is a direct function
+ invocation, but indirect <tt>invoke</tt>s are just as possible, branching
+ off an arbitrary pointer to function value.</li>
+
+ <li>'<tt>function ptr val</tt>': An LLVM value containing a pointer to a
+ function to be invoked. </li>
+
+ <li>'<tt>function args</tt>': argument list whose types match the function
+ signature argument types and parameter attributes. All arguments must be
+ of <a href="#t_firstclass">first class</a> type. If the function
+ signature indicates the function accepts a variable number of arguments,
+ the extra arguments can be specified.</li>
+
+ <li>'<tt>normal label</tt>': the label reached when the called function
+ executes a '<tt><a href="#i_ret">ret</a></tt>' instruction. </li>
+
+ <li>'<tt>exception label</tt>': the label reached when a callee returns via
+ the <a href="#i_resume"><tt>resume</tt></a> instruction or other exception
+ handling mechanism.</li>
+
+ <li>The optional <a href="#fnattrs">function attributes</a> list. Only
+ '<tt>noreturn</tt>', '<tt>nounwind</tt>', '<tt>readonly</tt>' and
+ '<tt>readnone</tt>' attributes are valid here.</li>
+</ol>
+
+<h5>Semantics:</h5>
+<p>This instruction is designed to operate as a standard
+ '<tt><a href="#i_call">call</a></tt>' instruction in most regards. The
+ primary difference is that it establishes an association with a label, which
+ is used by the runtime library to unwind the stack.</p>
+
+<p>This instruction is used in languages with destructors to ensure that proper
+ cleanup is performed in the case of either a <tt>longjmp</tt> or a thrown
+ exception. Additionally, this is important for implementation of
+ '<tt>catch</tt>' clauses in high-level languages that support them.</p>
+
+<p>For the purposes of the SSA form, the definition of the value returned by the
+ '<tt>invoke</tt>' instruction is deemed to occur on the edge from the current
+ block to the "normal" label. If the callee unwinds then no return value is
+ available.</p>
+
+<h5>Example:</h5>
+<pre>
+ %retval = invoke i32 @Test(i32 15) to label %Continue
+ unwind label %TestCleanup <i>; {i32}:retval set</i>
+ %retval = invoke <a href="#callingconv">coldcc</a> i32 %Testfnptr(i32 15) to label %Continue
+ unwind label %TestCleanup <i>; {i32}:retval set</i>
+</pre>
+
+</div>
+
+ <!-- _______________________________________________________________________ -->
+
+<h4>
+ <a name="i_resume">'<tt>resume</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ resume &lt;type&gt; &lt;value&gt;
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>resume</tt>' instruction is a terminator instruction that has no
+ successors.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>resume</tt>' instruction requires one argument, which must have the
+ same type as the result of any '<tt>landingpad</tt>' instruction in the same
+ function.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>resume</tt>' instruction resumes propagation of an existing
+ (in-flight) exception whose unwinding was interrupted with
+ a <a href="#i_landingpad"><tt>landingpad</tt></a> instruction.</p>
+
+<h5>Example:</h5>
+<pre>
+ resume { i8*, i32 } %exn
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+
+<h4>
+ <a name="i_unreachable">'<tt>unreachable</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ unreachable
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>unreachable</tt>' instruction has no defined semantics. This
+ instruction is used to inform the optimizer that a particular portion of the
+ code is not reachable. This can be used to indicate that the code after a
+ no-return function cannot be reached, and other facts.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>unreachable</tt>' instruction has no defined semantics.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="binaryops">Binary Operations</a>
+</h3>
+
+<div>
+
+<p>Binary operators are used to do most of the computation in a program. They
+ require two operands of the same type, execute an operation on them, and
+ produce a single value. The operands might represent multiple data, as is
+ the case with the <a href="#t_vector">vector</a> data type. The result value
+ has the same type as its operands.</p>
+
+<p>There are several different binary operators:</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_add">'<tt>add</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = add &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = add nuw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = add nsw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = add nuw nsw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>add</tt>' instruction returns the sum of its two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>add</tt>' instruction must
+ be <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of
+ integer values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the integer sum of the two operands.</p>
+
+<p>If the sum has unsigned overflow, the result returned is the mathematical
+ result modulo 2<sup>n</sup>, where n is the bit width of the result.</p>
+
+<p>Because LLVM integers use a two's complement representation, this instruction
+ is appropriate for both signed and unsigned integers.</p>
+
+<p><tt>nuw</tt> and <tt>nsw</tt> stand for &quot;No Unsigned Wrap&quot;
+ and &quot;No Signed Wrap&quot;, respectively. If the <tt>nuw</tt> and/or
+ <tt>nsw</tt> keywords are present, the result value of the <tt>add</tt>
+ is a <a href="#poisonvalues">poison value</a> if unsigned and/or signed overflow,
+ respectively, occurs.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = add i32 4, %var <i>; yields {i32}:result = 4 + %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fadd">'<tt>fadd</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fadd &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fadd</tt>' instruction returns the sum of its two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>fadd</tt>' instruction must be
+ <a href="#t_floating">floating point</a> or <a href="#t_vector">vector</a> of
+ floating point values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the floating point sum of the two operands.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = fadd float 4.0, %var <i>; yields {float}:result = 4.0 + %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_sub">'<tt>sub</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = sub &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = sub nuw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = sub nsw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = sub nuw nsw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>sub</tt>' instruction returns the difference of its two
+ operands.</p>
+
+<p>Note that the '<tt>sub</tt>' instruction is used to represent the
+ '<tt>neg</tt>' instruction present in most other intermediate
+ representations.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>sub</tt>' instruction must
+ be <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of
+ integer values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the integer difference of the two operands.</p>
+
+<p>If the difference has unsigned overflow, the result returned is the
+ mathematical result modulo 2<sup>n</sup>, where n is the bit width of the
+ result.</p>
+
+<p>Because LLVM integers use a two's complement representation, this instruction
+ is appropriate for both signed and unsigned integers.</p>
+
+<p><tt>nuw</tt> and <tt>nsw</tt> stand for &quot;No Unsigned Wrap&quot;
+ and &quot;No Signed Wrap&quot;, respectively. If the <tt>nuw</tt> and/or
+ <tt>nsw</tt> keywords are present, the result value of the <tt>sub</tt>
+ is a <a href="#poisonvalues">poison value</a> if unsigned and/or signed overflow,
+ respectively, occurs.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = sub i32 4, %var <i>; yields {i32}:result = 4 - %var</i>
+ &lt;result&gt; = sub i32 0, %val <i>; yields {i32}:result = -%var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fsub">'<tt>fsub</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fsub &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fsub</tt>' instruction returns the difference of its two
+ operands.</p>
+
+<p>Note that the '<tt>fsub</tt>' instruction is used to represent the
+ '<tt>fneg</tt>' instruction present in most other intermediate
+ representations.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>fsub</tt>' instruction must be
+ <a href="#t_floating">floating point</a> or <a href="#t_vector">vector</a> of
+ floating point values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the floating point difference of the two operands.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = fsub float 4.0, %var <i>; yields {float}:result = 4.0 - %var</i>
+ &lt;result&gt; = fsub float -0.0, %val <i>; yields {float}:result = -%var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_mul">'<tt>mul</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = mul &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = mul nuw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = mul nsw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = mul nuw nsw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>mul</tt>' instruction returns the product of its two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>mul</tt>' instruction must
+ be <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of
+ integer values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the integer product of the two operands.</p>
+
+<p>If the result of the multiplication has unsigned overflow, the result
+ returned is the mathematical result modulo 2<sup>n</sup>, where n is the bit
+ width of the result.</p>
+
+<p>Because LLVM integers use a two's complement representation, and the result
+ is the same width as the operands, this instruction returns the correct
+ result for both signed and unsigned integers. If a full product
+ (e.g. <tt>i32</tt>x<tt>i32</tt>-><tt>i64</tt>) is needed, the operands should
+ be sign-extended or zero-extended as appropriate to the width of the full
+ product.</p>
+
+<p><tt>nuw</tt> and <tt>nsw</tt> stand for &quot;No Unsigned Wrap&quot;
+ and &quot;No Signed Wrap&quot;, respectively. If the <tt>nuw</tt> and/or
+ <tt>nsw</tt> keywords are present, the result value of the <tt>mul</tt>
+ is a <a href="#poisonvalues">poison value</a> if unsigned and/or signed overflow,
+ respectively, occurs.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = mul i32 4, %var <i>; yields {i32}:result = 4 * %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fmul">'<tt>fmul</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fmul &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fmul</tt>' instruction returns the product of its two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>fmul</tt>' instruction must be
+ <a href="#t_floating">floating point</a> or <a href="#t_vector">vector</a> of
+ floating point values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the floating point product of the two operands.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = fmul float 4.0, %var <i>; yields {float}:result = 4.0 * %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_udiv">'<tt>udiv</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = udiv &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = udiv exact &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>udiv</tt>' instruction returns the quotient of its two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>udiv</tt>' instruction must be
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the unsigned integer quotient of the two operands.</p>
+
+<p>Note that unsigned integer division and signed integer division are distinct
+ operations; for signed integer division, use '<tt>sdiv</tt>'.</p>
+
+<p>Division by zero leads to undefined behavior.</p>
+
+<p>If the <tt>exact</tt> keyword is present, the result value of the
+ <tt>udiv</tt> is a <a href="#poisonvalues">poison value</a> if %op1 is not a
+ multiple of %op2 (as such, "((a udiv exact b) mul b) == a").</p>
+
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = udiv i32 4, %var <i>; yields {i32}:result = 4 / %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_sdiv">'<tt>sdiv</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = sdiv &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = sdiv exact &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>sdiv</tt>' instruction returns the quotient of its two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>sdiv</tt>' instruction must be
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the signed integer quotient of the two operands rounded
+ towards zero.</p>
+
+<p>Note that signed integer division and unsigned integer division are distinct
+ operations; for unsigned integer division, use '<tt>udiv</tt>'.</p>
+
+<p>Division by zero leads to undefined behavior. Overflow also leads to
+ undefined behavior; this is a rare case, but can occur, for example, by doing
+ a 32-bit division of -2147483648 by -1.</p>
+
+<p>If the <tt>exact</tt> keyword is present, the result value of the
+ <tt>sdiv</tt> is a <a href="#poisonvalues">poison value</a> if the result would
+ be rounded.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = sdiv i32 4, %var <i>; yields {i32}:result = 4 / %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fdiv">'<tt>fdiv</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fdiv &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fdiv</tt>' instruction returns the quotient of its two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>fdiv</tt>' instruction must be
+ <a href="#t_floating">floating point</a> or <a href="#t_vector">vector</a> of
+ floating point values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is the floating point quotient of the two operands.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = fdiv float 4.0, %var <i>; yields {float}:result = 4.0 / %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_urem">'<tt>urem</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = urem &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>urem</tt>' instruction returns the remainder from the unsigned
+ division of its two arguments.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>urem</tt>' instruction must be
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>This instruction returns the unsigned integer <i>remainder</i> of a division.
+ This instruction always performs an unsigned division to get the
+ remainder.</p>
+
+<p>Note that unsigned integer remainder and signed integer remainder are
+ distinct operations; for signed integer remainder, use '<tt>srem</tt>'.</p>
+
+<p>Taking the remainder of a division by zero leads to undefined behavior.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = urem i32 4, %var <i>; yields {i32}:result = 4 % %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_srem">'<tt>srem</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = srem &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>srem</tt>' instruction returns the remainder from the signed
+ division of its two operands. This instruction can also take
+ <a href="#t_vector">vector</a> versions of the values in which case the
+ elements must be integers.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>srem</tt>' instruction must be
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>This instruction returns the <i>remainder</i> of a division (where the result
+ is either zero or has the same sign as the dividend, <tt>op1</tt>), not the
+ <i>modulo</i> operator (where the result is either zero or has the same sign
+ as the divisor, <tt>op2</tt>) of a value.
+ For more information about the difference,
+ see <a href="http://mathforum.org/dr.math/problems/anne.4.28.99.html">The
+ Math Forum</a>. For a table of how this is implemented in various languages,
+ please see <a href="http://en.wikipedia.org/wiki/Modulo_operation">
+ Wikipedia: modulo operation</a>.</p>
+
+<p>Note that signed integer remainder and unsigned integer remainder are
+ distinct operations; for unsigned integer remainder, use '<tt>urem</tt>'.</p>
+
+<p>Taking the remainder of a division by zero leads to undefined behavior.
+ Overflow also leads to undefined behavior; this is a rare case, but can
+ occur, for example, by taking the remainder of a 32-bit division of
+ -2147483648 by -1. (The remainder doesn't actually overflow, but this rule
+ lets srem be implemented using instructions that return both the result of
+ the division and the remainder.)</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = srem i32 4, %var <i>; yields {i32}:result = 4 % %var</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_frem">'<tt>frem</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = frem &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>frem</tt>' instruction returns the remainder from the division of
+ its two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>frem</tt>' instruction must be
+ <a href="#t_floating">floating point</a> or <a href="#t_vector">vector</a> of
+ floating point values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>This instruction returns the <i>remainder</i> of a division. The remainder
+ has the same sign as the dividend.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = frem float 4.0, %var <i>; yields {float}:result = 4.0 % %var</i>
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="bitwiseops">Bitwise Binary Operations</a>
+</h3>
+
+<div>
+
+<p>Bitwise binary operators are used to do various forms of bit-twiddling in a
+ program. They are generally very efficient instructions and can commonly be
+ strength reduced from other instructions. They require two operands of the
+ same type, execute an operation on them, and produce a single value. The
+ resulting value is the same type as its operands.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_shl">'<tt>shl</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = shl &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = shl nuw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = shl nsw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = shl nuw nsw &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>shl</tt>' instruction returns the first operand shifted to the left
+ a specified number of bits.</p>
+
+<h5>Arguments:</h5>
+<p>Both arguments to the '<tt>shl</tt>' instruction must be the
+ same <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of
+ integer type. '<tt>op2</tt>' is treated as an unsigned value.</p>
+
+<h5>Semantics:</h5>
+<p>The value produced is <tt>op1</tt> * 2<sup><tt>op2</tt></sup> mod
+ 2<sup>n</sup>, where <tt>n</tt> is the width of the result. If <tt>op2</tt>
+ is (statically or dynamically) negative or equal to or larger than the number
+ of bits in <tt>op1</tt>, the result is undefined. If the arguments are
+ vectors, each vector element of <tt>op1</tt> is shifted by the corresponding
+ shift amount in <tt>op2</tt>.</p>
+
+<p>If the <tt>nuw</tt> keyword is present, then the shift produces a
+ <a href="#poisonvalues">poison value</a> if it shifts out any non-zero bits. If
+ the <tt>nsw</tt> keyword is present, then the shift produces a
+ <a href="#poisonvalues">poison value</a> if it shifts out any bits that disagree
+ with the resultant sign bit. As such, NUW/NSW have the same semantics as
+ they would if the shift were expressed as a mul instruction with the same
+ nsw/nuw bits in (mul %op1, (shl 1, %op2)).</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = shl i32 4, %var <i>; yields {i32}: 4 &lt;&lt; %var</i>
+ &lt;result&gt; = shl i32 4, 2 <i>; yields {i32}: 16</i>
+ &lt;result&gt; = shl i32 1, 10 <i>; yields {i32}: 1024</i>
+ &lt;result&gt; = shl i32 1, 32 <i>; undefined</i>
+ &lt;result&gt; = shl &lt;2 x i32&gt; &lt; i32 1, i32 1&gt;, &lt; i32 1, i32 2&gt; <i>; yields: result=&lt;2 x i32&gt; &lt; i32 2, i32 4&gt;</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_lshr">'<tt>lshr</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = lshr &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = lshr exact &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>lshr</tt>' instruction (logical shift right) returns the first
+ operand shifted to the right a specified number of bits with zero fill.</p>
+
+<h5>Arguments:</h5>
+<p>Both arguments to the '<tt>lshr</tt>' instruction must be the same
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ type. '<tt>op2</tt>' is treated as an unsigned value.</p>
+
+<h5>Semantics:</h5>
+<p>This instruction always performs a logical shift right operation. The most
+ significant bits of the result will be filled with zero bits after the shift.
+ If <tt>op2</tt> is (statically or dynamically) equal to or larger than the
+ number of bits in <tt>op1</tt>, the result is undefined. If the arguments are
+ vectors, each vector element of <tt>op1</tt> is shifted by the corresponding
+ shift amount in <tt>op2</tt>.</p>
+
+<p>If the <tt>exact</tt> keyword is present, the result value of the
+ <tt>lshr</tt> is a <a href="#poisonvalues">poison value</a> if any of the bits
+ shifted out are non-zero.</p>
+
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = lshr i32 4, 1 <i>; yields {i32}:result = 2</i>
+ &lt;result&gt; = lshr i32 4, 2 <i>; yields {i32}:result = 1</i>
+ &lt;result&gt; = lshr i8 4, 3 <i>; yields {i8}:result = 0</i>
+ &lt;result&gt; = lshr i8 -2, 1 <i>; yields {i8}:result = 0x7FFFFFFF </i>
+ &lt;result&gt; = lshr i32 1, 32 <i>; undefined</i>
+ &lt;result&gt; = lshr &lt;2 x i32&gt; &lt; i32 -2, i32 4&gt;, &lt; i32 1, i32 2&gt; <i>; yields: result=&lt;2 x i32&gt; &lt; i32 0x7FFFFFFF, i32 1&gt;</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_ashr">'<tt>ashr</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = ashr &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+ &lt;result&gt; = ashr exact &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>ashr</tt>' instruction (arithmetic shift right) returns the first
+ operand shifted to the right a specified number of bits with sign
+ extension.</p>
+
+<h5>Arguments:</h5>
+<p>Both arguments to the '<tt>ashr</tt>' instruction must be the same
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ type. '<tt>op2</tt>' is treated as an unsigned value.</p>
+
+<h5>Semantics:</h5>
+<p>This instruction always performs an arithmetic shift right operation, The
+ most significant bits of the result will be filled with the sign bit
+ of <tt>op1</tt>. If <tt>op2</tt> is (statically or dynamically) equal to or
+ larger than the number of bits in <tt>op1</tt>, the result is undefined. If
+ the arguments are vectors, each vector element of <tt>op1</tt> is shifted by
+ the corresponding shift amount in <tt>op2</tt>.</p>
+
+<p>If the <tt>exact</tt> keyword is present, the result value of the
+ <tt>ashr</tt> is a <a href="#poisonvalues">poison value</a> if any of the bits
+ shifted out are non-zero.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = ashr i32 4, 1 <i>; yields {i32}:result = 2</i>
+ &lt;result&gt; = ashr i32 4, 2 <i>; yields {i32}:result = 1</i>
+ &lt;result&gt; = ashr i8 4, 3 <i>; yields {i8}:result = 0</i>
+ &lt;result&gt; = ashr i8 -2, 1 <i>; yields {i8}:result = -1</i>
+ &lt;result&gt; = ashr i32 1, 32 <i>; undefined</i>
+ &lt;result&gt; = ashr &lt;2 x i32&gt; &lt; i32 -2, i32 4&gt;, &lt; i32 1, i32 3&gt; <i>; yields: result=&lt;2 x i32&gt; &lt; i32 -1, i32 0&gt;</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_and">'<tt>and</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = and &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>and</tt>' instruction returns the bitwise logical and of its two
+ operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>and</tt>' instruction must be
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The truth table used for the '<tt>and</tt>' instruction is:</p>
+
+<table border="1" cellspacing="0" cellpadding="4">
+ <tbody>
+ <tr>
+ <th>In0</th>
+ <th>In1</th>
+ <th>Out</th>
+ </tr>
+ <tr>
+ <td>0</td>
+ <td>0</td>
+ <td>0</td>
+ </tr>
+ <tr>
+ <td>0</td>
+ <td>1</td>
+ <td>0</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>0</td>
+ <td>0</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>1</td>
+ <td>1</td>
+ </tr>
+ </tbody>
+</table>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = and i32 4, %var <i>; yields {i32}:result = 4 &amp; %var</i>
+ &lt;result&gt; = and i32 15, 40 <i>; yields {i32}:result = 8</i>
+ &lt;result&gt; = and i32 4, 8 <i>; yields {i32}:result = 0</i>
+</pre>
+</div>
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_or">'<tt>or</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = or &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>or</tt>' instruction returns the bitwise logical inclusive or of its
+ two operands.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>or</tt>' instruction must be
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The truth table used for the '<tt>or</tt>' instruction is:</p>
+
+<table border="1" cellspacing="0" cellpadding="4">
+ <tbody>
+ <tr>
+ <th>In0</th>
+ <th>In1</th>
+ <th>Out</th>
+ </tr>
+ <tr>
+ <td>0</td>
+ <td>0</td>
+ <td>0</td>
+ </tr>
+ <tr>
+ <td>0</td>
+ <td>1</td>
+ <td>1</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>0</td>
+ <td>1</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>1</td>
+ <td>1</td>
+ </tr>
+ </tbody>
+</table>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = or i32 4, %var <i>; yields {i32}:result = 4 | %var</i>
+ &lt;result&gt; = or i32 15, 40 <i>; yields {i32}:result = 47</i>
+ &lt;result&gt; = or i32 4, 8 <i>; yields {i32}:result = 12</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_xor">'<tt>xor</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = xor &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {ty}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>xor</tt>' instruction returns the bitwise logical exclusive or of
+ its two operands. The <tt>xor</tt> is used to implement the "one's
+ complement" operation, which is the "~" operator in C.</p>
+
+<h5>Arguments:</h5>
+<p>The two arguments to the '<tt>xor</tt>' instruction must be
+ <a href="#t_integer">integer</a> or <a href="#t_vector">vector</a> of integer
+ values. Both arguments must have identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The truth table used for the '<tt>xor</tt>' instruction is:</p>
+
+<table border="1" cellspacing="0" cellpadding="4">
+ <tbody>
+ <tr>
+ <th>In0</th>
+ <th>In1</th>
+ <th>Out</th>
+ </tr>
+ <tr>
+ <td>0</td>
+ <td>0</td>
+ <td>0</td>
+ </tr>
+ <tr>
+ <td>0</td>
+ <td>1</td>
+ <td>1</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>0</td>
+ <td>1</td>
+ </tr>
+ <tr>
+ <td>1</td>
+ <td>1</td>
+ <td>0</td>
+ </tr>
+ </tbody>
+</table>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = xor i32 4, %var <i>; yields {i32}:result = 4 ^ %var</i>
+ &lt;result&gt; = xor i32 15, 40 <i>; yields {i32}:result = 39</i>
+ &lt;result&gt; = xor i32 4, 8 <i>; yields {i32}:result = 12</i>
+ &lt;result&gt; = xor i32 %V, -1 <i>; yields {i32}:result = ~%V</i>
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="vectorops">Vector Operations</a>
+</h3>
+
+<div>
+
+<p>LLVM supports several instructions to represent vector operations in a
+ target-independent manner. These instructions cover the element-access and
+ vector-specific operations needed to process vectors effectively. While LLVM
+ does directly support these vector operations, many sophisticated algorithms
+ will want to use target-specific intrinsics to take full advantage of a
+ specific target.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_extractelement">'<tt>extractelement</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = extractelement &lt;n x &lt;ty&gt;&gt; &lt;val&gt;, i32 &lt;idx&gt; <i>; yields &lt;ty&gt;</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>extractelement</tt>' instruction extracts a single scalar element
+ from a vector at a specified index.</p>
+
+
+<h5>Arguments:</h5>
+<p>The first operand of an '<tt>extractelement</tt>' instruction is a value
+ of <a href="#t_vector">vector</a> type. The second operand is an index
+ indicating the position from which to extract the element. The index may be
+ a variable.</p>
+
+<h5>Semantics:</h5>
+<p>The result is a scalar of the same type as the element type of
+ <tt>val</tt>. Its value is the value at position <tt>idx</tt> of
+ <tt>val</tt>. If <tt>idx</tt> exceeds the length of <tt>val</tt>, the
+ results are undefined.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = extractelement &lt;4 x i32&gt; %vec, i32 0 <i>; yields i32</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_insertelement">'<tt>insertelement</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = insertelement &lt;n x &lt;ty&gt;&gt; &lt;val&gt;, &lt;ty&gt; &lt;elt&gt;, i32 &lt;idx&gt; <i>; yields &lt;n x &lt;ty&gt;&gt;</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>insertelement</tt>' instruction inserts a scalar element into a
+ vector at a specified index.</p>
+
+<h5>Arguments:</h5>
+<p>The first operand of an '<tt>insertelement</tt>' instruction is a value
+ of <a href="#t_vector">vector</a> type. The second operand is a scalar value
+ whose type must equal the element type of the first operand. The third
+ operand is an index indicating the position at which to insert the value.
+ The index may be a variable.</p>
+
+<h5>Semantics:</h5>
+<p>The result is a vector of the same type as <tt>val</tt>. Its element values
+ are those of <tt>val</tt> except at position <tt>idx</tt>, where it gets the
+ value <tt>elt</tt>. If <tt>idx</tt> exceeds the length of <tt>val</tt>, the
+ results are undefined.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = insertelement &lt;4 x i32&gt; %vec, i32 1, i32 0 <i>; yields &lt;4 x i32&gt;</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_shufflevector">'<tt>shufflevector</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = shufflevector &lt;n x &lt;ty&gt;&gt; &lt;v1&gt;, &lt;n x &lt;ty&gt;&gt; &lt;v2&gt;, &lt;m x i32&gt; &lt;mask&gt; <i>; yields &lt;m x &lt;ty&gt;&gt;</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>shufflevector</tt>' instruction constructs a permutation of elements
+ from two input vectors, returning a vector with the same element type as the
+ input and length that is the same as the shuffle mask.</p>
+
+<h5>Arguments:</h5>
+<p>The first two operands of a '<tt>shufflevector</tt>' instruction are vectors
+ with the same type. The third argument is a shuffle mask whose
+ element type is always 'i32'. The result of the instruction is a vector
+ whose length is the same as the shuffle mask and whose element type is the
+ same as the element type of the first two operands.</p>
+
+<p>The shuffle mask operand is required to be a constant vector with either
+ constant integer or undef values.</p>
+
+<h5>Semantics:</h5>
+<p>The elements of the two input vectors are numbered from left to right across
+ both of the vectors. The shuffle mask operand specifies, for each element of
+ the result vector, which element of the two input vectors the result element
+ gets. The element selector may be undef (meaning "don't care") and the
+ second operand may be undef if performing a shuffle from only one vector.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = shufflevector &lt;4 x i32&gt; %v1, &lt;4 x i32&gt; %v2,
+ &lt;4 x i32&gt; &lt;i32 0, i32 4, i32 1, i32 5&gt; <i>; yields &lt;4 x i32&gt;</i>
+ &lt;result&gt; = shufflevector &lt;4 x i32&gt; %v1, &lt;4 x i32&gt; undef,
+ &lt;4 x i32&gt; &lt;i32 0, i32 1, i32 2, i32 3&gt; <i>; yields &lt;4 x i32&gt;</i> - Identity shuffle.
+ &lt;result&gt; = shufflevector &lt;8 x i32&gt; %v1, &lt;8 x i32&gt; undef,
+ &lt;4 x i32&gt; &lt;i32 0, i32 1, i32 2, i32 3&gt; <i>; yields &lt;4 x i32&gt;</i>
+ &lt;result&gt; = shufflevector &lt;4 x i32&gt; %v1, &lt;4 x i32&gt; %v2,
+ &lt;8 x i32&gt; &lt;i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7 &gt; <i>; yields &lt;8 x i32&gt;</i>
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="aggregateops">Aggregate Operations</a>
+</h3>
+
+<div>
+
+<p>LLVM supports several instructions for working with
+ <a href="#t_aggregate">aggregate</a> values.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_extractvalue">'<tt>extractvalue</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = extractvalue &lt;aggregate type&gt; &lt;val&gt;, &lt;idx&gt;{, &lt;idx&gt;}*
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>extractvalue</tt>' instruction extracts the value of a member field
+ from an <a href="#t_aggregate">aggregate</a> value.</p>
+
+<h5>Arguments:</h5>
+<p>The first operand of an '<tt>extractvalue</tt>' instruction is a value
+ of <a href="#t_struct">struct</a> or
+ <a href="#t_array">array</a> type. The operands are constant indices to
+ specify which value to extract in a similar manner as indices in a
+ '<tt><a href="#i_getelementptr">getelementptr</a></tt>' instruction.</p>
+ <p>The major differences to <tt>getelementptr</tt> indexing are:</p>
+ <ul>
+ <li>Since the value being indexed is not a pointer, the first index is
+ omitted and assumed to be zero.</li>
+ <li>At least one index must be specified.</li>
+ <li>Not only struct indices but also array indices must be in
+ bounds.</li>
+ </ul>
+
+<h5>Semantics:</h5>
+<p>The result is the value at the position in the aggregate specified by the
+ index operands.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = extractvalue {i32, float} %agg, 0 <i>; yields i32</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_insertvalue">'<tt>insertvalue</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = insertvalue &lt;aggregate type&gt; &lt;val&gt;, &lt;ty&gt; &lt;elt&gt;, &lt;idx&gt;{, &lt;idx&gt;}* <i>; yields &lt;aggregate type&gt;</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>insertvalue</tt>' instruction inserts a value into a member field
+ in an <a href="#t_aggregate">aggregate</a> value.</p>
+
+<h5>Arguments:</h5>
+<p>The first operand of an '<tt>insertvalue</tt>' instruction is a value
+ of <a href="#t_struct">struct</a> or
+ <a href="#t_array">array</a> type. The second operand is a first-class
+ value to insert. The following operands are constant indices indicating
+ the position at which to insert the value in a similar manner as indices in a
+ '<tt><a href="#i_extractvalue">extractvalue</a></tt>' instruction. The
+ value to insert must have the same type as the value identified by the
+ indices.</p>
+
+<h5>Semantics:</h5>
+<p>The result is an aggregate of the same type as <tt>val</tt>. Its value is
+ that of <tt>val</tt> except that the value at the position specified by the
+ indices is that of <tt>elt</tt>.</p>
+
+<h5>Example:</h5>
+<pre>
+ %agg1 = insertvalue {i32, float} undef, i32 1, 0 <i>; yields {i32 1, float undef}</i>
+ %agg2 = insertvalue {i32, float} %agg1, float %val, 1 <i>; yields {i32 1, float %val}</i>
+ %agg3 = insertvalue {i32, {float}} %agg1, float %val, 1, 0 <i>; yields {i32 1, float %val}</i>
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="memoryops">Memory Access and Addressing Operations</a>
+</h3>
+
+<div>
+
+<p>A key design point of an SSA-based representation is how it represents
+ memory. In LLVM, no memory locations are in SSA form, which makes things
+ very simple. This section describes how to read, write, and allocate
+ memory in LLVM.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_alloca">'<tt>alloca</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = alloca &lt;type&gt;[, &lt;ty&gt; &lt;NumElements&gt;][, align &lt;alignment&gt;] <i>; yields {type*}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>alloca</tt>' instruction allocates memory on the stack frame of the
+ currently executing function, to be automatically released when this function
+ returns to its caller. The object is always allocated in the generic address
+ space (address space zero).</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>alloca</tt>' instruction
+ allocates <tt>sizeof(&lt;type&gt;)*NumElements</tt> bytes of memory on the
+ runtime stack, returning a pointer of the appropriate type to the program.
+ If "NumElements" is specified, it is the number of elements allocated,
+ otherwise "NumElements" is defaulted to be one. If a constant alignment is
+ specified, the value result of the allocation is guaranteed to be aligned to
+ at least that boundary. If not specified, or if zero, the target can choose
+ to align the allocation on any convenient boundary compatible with the
+ type.</p>
+
+<p>'<tt>type</tt>' may be any sized type.</p>
+
+<h5>Semantics:</h5>
+<p>Memory is allocated; a pointer is returned. The operation is undefined if
+ there is insufficient stack space for the allocation. '<tt>alloca</tt>'d
+ memory is automatically released when the function returns. The
+ '<tt>alloca</tt>' instruction is commonly used to represent automatic
+ variables that must have an address available. When the function returns
+ (either with the <tt><a href="#i_ret">ret</a></tt>
+ or <tt><a href="#i_resume">resume</a></tt> instructions), the memory is
+ reclaimed. Allocating zero bytes is legal, but the result is undefined.
+ The order in which memory is allocated (ie., which way the stack grows) is
+ not specified.</p>
+
+<p>
+
+<h5>Example:</h5>
+<pre>
+ %ptr = alloca i32 <i>; yields {i32*}:ptr</i>
+ %ptr = alloca i32, i32 4 <i>; yields {i32*}:ptr</i>
+ %ptr = alloca i32, i32 4, align 1024 <i>; yields {i32*}:ptr</i>
+ %ptr = alloca i32, align 1024 <i>; yields {i32*}:ptr</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_load">'<tt>load</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = load [volatile] &lt;ty&gt;* &lt;pointer&gt;[, align &lt;alignment&gt;][, !nontemporal !&lt;index&gt;][, !invariant.load !&lt;index&gt;]
+ &lt;result&gt; = load atomic [volatile] &lt;ty&gt;* &lt;pointer&gt; [singlethread] &lt;ordering&gt;, align &lt;alignment&gt;
+ !&lt;index&gt; = !{ i32 1 }
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>load</tt>' instruction is used to read from memory.</p>
+
+<h5>Arguments:</h5>
+<p>The argument to the '<tt>load</tt>' instruction specifies the memory address
+ from which to load. The pointer must point to
+ a <a href="#t_firstclass">first class</a> type. If the <tt>load</tt> is
+ marked as <tt>volatile</tt>, then the optimizer is not allowed to modify the
+ number or order of execution of this <tt>load</tt> with other <a
+ href="#volatile">volatile operations</a>.</p>
+
+<p>If the <code>load</code> is marked as <code>atomic</code>, it takes an extra
+ <a href="#ordering">ordering</a> and optional <code>singlethread</code>
+ argument. The <code>release</code> and <code>acq_rel</code> orderings are
+ not valid on <code>load</code> instructions. Atomic loads produce <a
+ href="#memorymodel">defined</a> results when they may see multiple atomic
+ stores. The type of the pointee must be an integer type whose bit width
+ is a power of two greater than or equal to eight and less than or equal
+ to a target-specific size limit. <code>align</code> must be explicitly
+ specified on atomic loads, and the load has undefined behavior if the
+ alignment is not set to a value which is at least the size in bytes of
+ the pointee. <code>!nontemporal</code> does not have any defined semantics
+ for atomic loads.</p>
+
+<p>The optional constant <tt>align</tt> argument specifies the alignment of the
+ operation (that is, the alignment of the memory address). A value of 0 or an
+ omitted <tt>align</tt> argument means that the operation has the preferential
+ alignment for the target. It is the responsibility of the code emitter to
+ ensure that the alignment information is correct. Overestimating the
+ alignment results in undefined behavior. Underestimating the alignment may
+ produce less efficient code. An alignment of 1 is always safe.</p>
+
+<p>The optional <tt>!nontemporal</tt> metadata must reference a single
+ metatadata name &lt;index&gt; corresponding to a metadata node with
+ one <tt>i32</tt> entry of value 1. The existence of
+ the <tt>!nontemporal</tt> metatadata on the instruction tells the optimizer
+ and code generator that this load is not expected to be reused in the cache.
+ The code generator may select special instructions to save cache bandwidth,
+ such as the <tt>MOVNT</tt> instruction on x86.</p>
+
+<p>The optional <tt>!invariant.load</tt> metadata must reference a single
+ metatadata name &lt;index&gt; corresponding to a metadata node with no
+ entries. The existence of the <tt>!invariant.load</tt> metatadata on the
+ instruction tells the optimizer and code generator that this load address
+ points to memory which does not change value during program execution.
+ The optimizer may then move this load around, for example, by hoisting it
+ out of loops using loop invariant code motion.</p>
+
+<h5>Semantics:</h5>
+<p>The location of memory pointed to is loaded. If the value being loaded is of
+ scalar type then the number of bytes read does not exceed the minimum number
+ of bytes needed to hold all bits of the type. For example, loading an
+ <tt>i24</tt> reads at most three bytes. When loading a value of a type like
+ <tt>i20</tt> with a size that is not an integral number of bytes, the result
+ is undefined if the value was not originally written using a store of the
+ same type.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %ptr = <a href="#i_alloca">alloca</a> i32 <i>; yields {i32*}:ptr</i>
+ <a href="#i_store">store</a> i32 3, i32* %ptr <i>; yields {void}</i>
+ %val = load i32* %ptr <i>; yields {i32}:val = i32 3</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_store">'<tt>store</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ store [volatile] &lt;ty&gt; &lt;value&gt;, &lt;ty&gt;* &lt;pointer&gt;[, align &lt;alignment&gt;][, !nontemporal !&lt;index&gt;] <i>; yields {void}</i>
+ store atomic [volatile] &lt;ty&gt; &lt;value&gt;, &lt;ty&gt;* &lt;pointer&gt; [singlethread] &lt;ordering&gt;, align &lt;alignment&gt; <i>; yields {void}</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>store</tt>' instruction is used to write to memory.</p>
+
+<h5>Arguments:</h5>
+<p>There are two arguments to the '<tt>store</tt>' instruction: a value to store
+ and an address at which to store it. The type of the
+ '<tt>&lt;pointer&gt;</tt>' operand must be a pointer to
+ the <a href="#t_firstclass">first class</a> type of the
+ '<tt>&lt;value&gt;</tt>' operand. If the <tt>store</tt> is marked as
+ <tt>volatile</tt>, then the optimizer is not allowed to modify the number or
+ order of execution of this <tt>store</tt> with other <a
+ href="#volatile">volatile operations</a>.</p>
+
+<p>If the <code>store</code> is marked as <code>atomic</code>, it takes an extra
+ <a href="#ordering">ordering</a> and optional <code>singlethread</code>
+ argument. The <code>acquire</code> and <code>acq_rel</code> orderings aren't
+ valid on <code>store</code> instructions. Atomic loads produce <a
+ href="#memorymodel">defined</a> results when they may see multiple atomic
+ stores. The type of the pointee must be an integer type whose bit width
+ is a power of two greater than or equal to eight and less than or equal
+ to a target-specific size limit. <code>align</code> must be explicitly
+ specified on atomic stores, and the store has undefined behavior if the
+ alignment is not set to a value which is at least the size in bytes of
+ the pointee. <code>!nontemporal</code> does not have any defined semantics
+ for atomic stores.</p>
+
+<p>The optional constant "align" argument specifies the alignment of the
+ operation (that is, the alignment of the memory address). A value of 0 or an
+ omitted "align" argument means that the operation has the preferential
+ alignment for the target. It is the responsibility of the code emitter to
+ ensure that the alignment information is correct. Overestimating the
+ alignment results in an undefined behavior. Underestimating the alignment may
+ produce less efficient code. An alignment of 1 is always safe.</p>
+
+<p>The optional !nontemporal metadata must reference a single metatadata
+ name &lt;index&gt; corresponding to a metadata node with one i32 entry of
+ value 1. The existence of the !nontemporal metatadata on the
+ instruction tells the optimizer and code generator that this load is
+ not expected to be reused in the cache. The code generator may
+ select special instructions to save cache bandwidth, such as the
+ MOVNT instruction on x86.</p>
+
+
+<h5>Semantics:</h5>
+<p>The contents of memory are updated to contain '<tt>&lt;value&gt;</tt>' at the
+ location specified by the '<tt>&lt;pointer&gt;</tt>' operand. If
+ '<tt>&lt;value&gt;</tt>' is of scalar type then the number of bytes written
+ does not exceed the minimum number of bytes needed to hold all bits of the
+ type. For example, storing an <tt>i24</tt> writes at most three bytes. When
+ writing a value of a type like <tt>i20</tt> with a size that is not an
+ integral number of bytes, it is unspecified what happens to the extra bits
+ that do not belong to the type, but they will typically be overwritten.</p>
+
+<h5>Example:</h5>
+<pre>
+ %ptr = <a href="#i_alloca">alloca</a> i32 <i>; yields {i32*}:ptr</i>
+ store i32 3, i32* %ptr <i>; yields {void}</i>
+ %val = <a href="#i_load">load</a> i32* %ptr <i>; yields {i32}:val = i32 3</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+<a name="i_fence">'<tt>fence</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ fence [singlethread] &lt;ordering&gt; <i>; yields {void}</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fence</tt>' instruction is used to introduce happens-before edges
+between operations.</p>
+
+<h5>Arguments:</h5> <p>'<code>fence</code>' instructions take an <a
+href="#ordering">ordering</a> argument which defines what
+<i>synchronizes-with</i> edges they add. They can only be given
+<code>acquire</code>, <code>release</code>, <code>acq_rel</code>, and
+<code>seq_cst</code> orderings.</p>
+
+<h5>Semantics:</h5>
+<p>A fence <var>A</var> which has (at least) <code>release</code> ordering
+semantics <i>synchronizes with</i> a fence <var>B</var> with (at least)
+<code>acquire</code> ordering semantics if and only if there exist atomic
+operations <var>X</var> and <var>Y</var>, both operating on some atomic object
+<var>M</var>, such that <var>A</var> is sequenced before <var>X</var>,
+<var>X</var> modifies <var>M</var> (either directly or through some side effect
+of a sequence headed by <var>X</var>), <var>Y</var> is sequenced before
+<var>B</var>, and <var>Y</var> observes <var>M</var>. This provides a
+<i>happens-before</i> dependency between <var>A</var> and <var>B</var>. Rather
+than an explicit <code>fence</code>, one (but not both) of the atomic operations
+<var>X</var> or <var>Y</var> might provide a <code>release</code> or
+<code>acquire</code> (resp.) ordering constraint and still
+<i>synchronize-with</i> the explicit <code>fence</code> and establish the
+<i>happens-before</i> edge.</p>
+
+<p>A <code>fence</code> which has <code>seq_cst</code> ordering, in addition to
+having both <code>acquire</code> and <code>release</code> semantics specified
+above, participates in the global program order of other <code>seq_cst</code>
+operations and/or fences.</p>
+
+<p>The optional "<a href="#singlethread"><code>singlethread</code></a>" argument
+specifies that the fence only synchronizes with other fences in the same
+thread. (This is useful for interacting with signal handlers.)</p>
+
+<h5>Example:</h5>
+<pre>
+ fence acquire <i>; yields {void}</i>
+ fence singlethread seq_cst <i>; yields {void}</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+<a name="i_cmpxchg">'<tt>cmpxchg</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ cmpxchg [volatile] &lt;ty&gt;* &lt;pointer&gt;, &lt;ty&gt; &lt;cmp&gt;, &lt;ty&gt; &lt;new&gt; [singlethread] &lt;ordering&gt; <i>; yields {ty}</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>cmpxchg</tt>' instruction is used to atomically modify memory.
+It loads a value in memory and compares it to a given value. If they are
+equal, it stores a new value into the memory.</p>
+
+<h5>Arguments:</h5>
+<p>There are three arguments to the '<code>cmpxchg</code>' instruction: an
+address to operate on, a value to compare to the value currently be at that
+address, and a new value to place at that address if the compared values are
+equal. The type of '<var>&lt;cmp&gt;</var>' must be an integer type whose
+bit width is a power of two greater than or equal to eight and less than
+or equal to a target-specific size limit. '<var>&lt;cmp&gt;</var>' and
+'<var>&lt;new&gt;</var>' must have the same type, and the type of
+'<var>&lt;pointer&gt;</var>' must be a pointer to that type. If the
+<code>cmpxchg</code> is marked as <code>volatile</code>, then the
+optimizer is not allowed to modify the number or order of execution
+of this <code>cmpxchg</code> with other <a href="#volatile">volatile
+operations</a>.</p>
+
+<!-- FIXME: Extend allowed types. -->
+
+<p>The <a href="#ordering"><var>ordering</var></a> argument specifies how this
+<code>cmpxchg</code> synchronizes with other atomic operations.</p>
+
+<p>The optional "<code>singlethread</code>" argument declares that the
+<code>cmpxchg</code> is only atomic with respect to code (usually signal
+handlers) running in the same thread as the <code>cmpxchg</code>. Otherwise the
+cmpxchg is atomic with respect to all other code in the system.</p>
+
+<p>The pointer passed into cmpxchg must have alignment greater than or equal to
+the size in memory of the operand.
+
+<h5>Semantics:</h5>
+<p>The contents of memory at the location specified by the
+'<tt>&lt;pointer&gt;</tt>' operand is read and compared to
+'<tt>&lt;cmp&gt;</tt>'; if the read value is the equal,
+'<tt>&lt;new&gt;</tt>' is written. The original value at the location
+is returned.
+
+<p>A successful <code>cmpxchg</code> is a read-modify-write instruction for the
+purpose of identifying <a href="#release_sequence">release sequences</a>. A
+failed <code>cmpxchg</code> is equivalent to an atomic load with an ordering
+parameter determined by dropping any <code>release</code> part of the
+<code>cmpxchg</code>'s ordering.</p>
+
+<!--
+FIXME: Is compare_exchange_weak() necessary? (Consider after we've done
+optimization work on ARM.)
+
+FIXME: Is a weaker ordering constraint on failure helpful in practice?
+-->
+
+<h5>Example:</h5>
+<pre>
+entry:
+ %orig = atomic <a href="#i_load">load</a> i32* %ptr unordered <i>; yields {i32}</i>
+ <a href="#i_br">br</a> label %loop
+
+loop:
+ %cmp = <a href="#i_phi">phi</a> i32 [ %orig, %entry ], [%old, %loop]
+ %squared = <a href="#i_mul">mul</a> i32 %cmp, %cmp
+ %old = cmpxchg i32* %ptr, i32 %cmp, i32 %squared <i>; yields {i32}</i>
+ %success = <a href="#i_icmp">icmp</a> eq i32 %cmp, %old
+ <a href="#i_br">br</a> i1 %success, label %done, label %loop
+
+done:
+ ...
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+<a name="i_atomicrmw">'<tt>atomicrmw</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ atomicrmw [volatile] &lt;operation&gt; &lt;ty&gt;* &lt;pointer&gt;, &lt;ty&gt; &lt;value&gt; [singlethread] &lt;ordering&gt; <i>; yields {ty}</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>atomicrmw</tt>' instruction is used to atomically modify memory.</p>
+
+<h5>Arguments:</h5>
+<p>There are three arguments to the '<code>atomicrmw</code>' instruction: an
+operation to apply, an address whose value to modify, an argument to the
+operation. The operation must be one of the following keywords:</p>
+<ul>
+ <li>xchg</li>
+ <li>add</li>
+ <li>sub</li>
+ <li>and</li>
+ <li>nand</li>
+ <li>or</li>
+ <li>xor</li>
+ <li>max</li>
+ <li>min</li>
+ <li>umax</li>
+ <li>umin</li>
+</ul>
+
+<p>The type of '<var>&lt;value&gt;</var>' must be an integer type whose
+bit width is a power of two greater than or equal to eight and less than
+or equal to a target-specific size limit. The type of the
+'<code>&lt;pointer&gt;</code>' operand must be a pointer to that type.
+If the <code>atomicrmw</code> is marked as <code>volatile</code>, then the
+optimizer is not allowed to modify the number or order of execution of this
+<code>atomicrmw</code> with other <a href="#volatile">volatile
+ operations</a>.</p>
+
+<!-- FIXME: Extend allowed types. -->
+
+<h5>Semantics:</h5>
+<p>The contents of memory at the location specified by the
+'<tt>&lt;pointer&gt;</tt>' operand are atomically read, modified, and written
+back. The original value at the location is returned. The modification is
+specified by the <var>operation</var> argument:</p>
+
+<ul>
+ <li>xchg: <code>*ptr = val</code></li>
+ <li>add: <code>*ptr = *ptr + val</code></li>
+ <li>sub: <code>*ptr = *ptr - val</code></li>
+ <li>and: <code>*ptr = *ptr &amp; val</code></li>
+ <li>nand: <code>*ptr = ~(*ptr &amp; val)</code></li>
+ <li>or: <code>*ptr = *ptr | val</code></li>
+ <li>xor: <code>*ptr = *ptr ^ val</code></li>
+ <li>max: <code>*ptr = *ptr &gt; val ? *ptr : val</code> (using a signed comparison)</li>
+ <li>min: <code>*ptr = *ptr &lt; val ? *ptr : val</code> (using a signed comparison)</li>
+ <li>umax: <code>*ptr = *ptr &gt; val ? *ptr : val</code> (using an unsigned comparison)</li>
+ <li>umin: <code>*ptr = *ptr &lt; val ? *ptr : val</code> (using an unsigned comparison)</li>
+</ul>
+
+<h5>Example:</h5>
+<pre>
+ %old = atomicrmw add i32* %ptr, i32 1 acquire <i>; yields {i32}</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_getelementptr">'<tt>getelementptr</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = getelementptr &lt;pty&gt;* &lt;ptrval&gt;{, &lt;ty&gt; &lt;idx&gt;}*
+ &lt;result&gt; = getelementptr inbounds &lt;pty&gt;* &lt;ptrval&gt;{, &lt;ty&gt; &lt;idx&gt;}*
+ &lt;result&gt; = getelementptr &lt;ptr vector&gt; ptrval, &lt;vector index type&gt; idx
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>getelementptr</tt>' instruction is used to get the address of a
+ subelement of an <a href="#t_aggregate">aggregate</a> data structure.
+ It performs address calculation only and does not access memory.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is always a pointer or a vector of pointers,
+ and forms the basis of the
+ calculation. The remaining arguments are indices that indicate which of the
+ elements of the aggregate object are indexed. The interpretation of each
+ index is dependent on the type being indexed into. The first index always
+ indexes the pointer value given as the first argument, the second index
+ indexes a value of the type pointed to (not necessarily the value directly
+ pointed to, since the first index can be non-zero), etc. The first type
+ indexed into must be a pointer value, subsequent types can be arrays,
+ vectors, and structs. Note that subsequent types being indexed into
+ can never be pointers, since that would require loading the pointer before
+ continuing calculation.</p>
+
+<p>The type of each index argument depends on the type it is indexing into.
+ When indexing into a (optionally packed) structure, only <tt>i32</tt>
+ integer <b>constants</b> are allowed. When indexing into an array, pointer
+ or vector, integers of any width are allowed, and they are not required to be
+ constant. These integers are treated as signed values where relevant.</p>
+
+<p>For example, let's consider a C code fragment and how it gets compiled to
+ LLVM:</p>
+
+<pre class="doc_code">
+struct RT {
+ char A;
+ int B[10][20];
+ char C;
+};
+struct ST {
+ int X;
+ double Y;
+ struct RT Z;
+};
+
+int *foo(struct ST *s) {
+ return &amp;s[1].Z.B[5][13];
+}
+</pre>
+
+<p>The LLVM code generated by Clang is:</p>
+
+<pre class="doc_code">
+%struct.RT = <a href="#namedtypes">type</a> { i8, [10 x [20 x i32]], i8 }
+%struct.ST = <a href="#namedtypes">type</a> { i32, double, %struct.RT }
+
+define i32* @foo(%struct.ST* %s) nounwind uwtable readnone optsize ssp {
+entry:
+ %arrayidx = getelementptr inbounds %struct.ST* %s, i64 1, i32 2, i32 1, i64 5, i64 13
+ ret i32* %arrayidx
+}
+</pre>
+
+<h5>Semantics:</h5>
+<p>In the example above, the first index is indexing into the
+ '<tt>%struct.ST*</tt>' type, which is a pointer, yielding a
+ '<tt>%struct.ST</tt>' = '<tt>{ i32, double, %struct.RT }</tt>' type, a
+ structure. The second index indexes into the third element of the structure,
+ yielding a '<tt>%struct.RT</tt>' = '<tt>{ i8 , [10 x [20 x i32]], i8 }</tt>'
+ type, another structure. The third index indexes into the second element of
+ the structure, yielding a '<tt>[10 x [20 x i32]]</tt>' type, an array. The
+ two dimensions of the array are subscripted into, yielding an '<tt>i32</tt>'
+ type. The '<tt>getelementptr</tt>' instruction returns a pointer to this
+ element, thus computing a value of '<tt>i32*</tt>' type.</p>
+
+<p>Note that it is perfectly legal to index partially through a structure,
+ returning a pointer to an inner element. Because of this, the LLVM code for
+ the given testcase is equivalent to:</p>
+
+<pre class="doc_code">
+define i32* @foo(%struct.ST* %s) {
+ %t1 = getelementptr %struct.ST* %s, i32 1 <i>; yields %struct.ST*:%t1</i>
+ %t2 = getelementptr %struct.ST* %t1, i32 0, i32 2 <i>; yields %struct.RT*:%t2</i>
+ %t3 = getelementptr %struct.RT* %t2, i32 0, i32 1 <i>; yields [10 x [20 x i32]]*:%t3</i>
+ %t4 = getelementptr [10 x [20 x i32]]* %t3, i32 0, i32 5 <i>; yields [20 x i32]*:%t4</i>
+ %t5 = getelementptr [20 x i32]* %t4, i32 0, i32 13 <i>; yields i32*:%t5</i>
+ ret i32* %t5
+}
+</pre>
+
+<p>If the <tt>inbounds</tt> keyword is present, the result value of the
+ <tt>getelementptr</tt> is a <a href="#poisonvalues">poison value</a> if the
+ base pointer is not an <i>in bounds</i> address of an allocated object,
+ or if any of the addresses that would be formed by successive addition of
+ the offsets implied by the indices to the base address with infinitely
+ precise signed arithmetic are not an <i>in bounds</i> address of that
+ allocated object. The <i>in bounds</i> addresses for an allocated object
+ are all the addresses that point into the object, plus the address one
+ byte past the end.
+ In cases where the base is a vector of pointers the <tt>inbounds</tt> keyword
+ applies to each of the computations element-wise. </p>
+
+<p>If the <tt>inbounds</tt> keyword is not present, the offsets are added to
+ the base address with silently-wrapping two's complement arithmetic. If the
+ offsets have a different width from the pointer, they are sign-extended or
+ truncated to the width of the pointer. The result value of the
+ <tt>getelementptr</tt> may be outside the object pointed to by the base
+ pointer. The result value may not necessarily be used to access memory
+ though, even if it happens to point into allocated storage. See the
+ <a href="#pointeraliasing">Pointer Aliasing Rules</a> section for more
+ information.</p>
+
+<p>The getelementptr instruction is often confusing. For some more insight into
+ how it works, see <a href="GetElementPtr.html">the getelementptr FAQ</a>.</p>
+
+<h5>Example:</h5>
+<pre>
+ <i>; yields [12 x i8]*:aptr</i>
+ %aptr = getelementptr {i32, [12 x i8]}* %saptr, i64 0, i32 1
+ <i>; yields i8*:vptr</i>
+ %vptr = getelementptr {i32, &lt;2 x i8&gt;}* %svptr, i64 0, i32 1, i32 1
+ <i>; yields i8*:eptr</i>
+ %eptr = getelementptr [12 x i8]* %aptr, i64 0, i32 1
+ <i>; yields i32*:iptr</i>
+ %iptr = getelementptr [10 x i32]* @arr, i16 0, i16 0
+</pre>
+
+<p>In cases where the pointer argument is a vector of pointers, only a
+ single index may be used, and the number of vector elements has to be
+ the same. For example: </p>
+<pre class="doc_code">
+ %A = getelementptr <4 x i8*> %ptrs, <4 x i64> %offsets,
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="convertops">Conversion Operations</a>
+</h3>
+
+<div>
+
+<p>The instructions in this category are the conversion instructions (casting)
+ which all take a single operand and a type. They perform various bit
+ conversions on the operand.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_trunc">'<tt>trunc .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = trunc &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>trunc</tt>' instruction truncates its operand to the
+ type <tt>ty2</tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>trunc</tt>' instruction takes a value to trunc, and a type to trunc it to.
+ Both types must be of <a href="#t_integer">integer</a> types, or vectors
+ of the same number of integers.
+ The bit size of the <tt>value</tt> must be larger than
+ the bit size of the destination type, <tt>ty2</tt>.
+ Equal sized types are not allowed.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>trunc</tt>' instruction truncates the high order bits
+ in <tt>value</tt> and converts the remaining bits to <tt>ty2</tt>. Since the
+ source size must be larger than the destination size, <tt>trunc</tt> cannot
+ be a <i>no-op cast</i>. It will always truncate bits.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = trunc i32 257 to i8 <i>; yields i8:1</i>
+ %Y = trunc i32 123 to i1 <i>; yields i1:true</i>
+ %Z = trunc i32 122 to i1 <i>; yields i1:false</i>
+ %W = trunc &lt;2 x i16&gt; &lt;i16 8, i16 7&gt; to &lt;2 x i8&gt; <i>; yields &lt;i8 8, i8 7&gt;</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_zext">'<tt>zext .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = zext &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>zext</tt>' instruction zero extends its operand to type
+ <tt>ty2</tt>.</p>
+
+
+<h5>Arguments:</h5>
+<p>The '<tt>zext</tt>' instruction takes a value to cast, and a type to cast it to.
+ Both types must be of <a href="#t_integer">integer</a> types, or vectors
+ of the same number of integers.
+ The bit size of the <tt>value</tt> must be smaller than
+ the bit size of the destination type,
+ <tt>ty2</tt>.</p>
+
+<h5>Semantics:</h5>
+<p>The <tt>zext</tt> fills the high order bits of the <tt>value</tt> with zero
+ bits until it reaches the size of the destination type, <tt>ty2</tt>.</p>
+
+<p>When zero extending from i1, the result will always be either 0 or 1.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = zext i32 257 to i64 <i>; yields i64:257</i>
+ %Y = zext i1 true to i32 <i>; yields i32:1</i>
+ %Z = zext &lt;2 x i16&gt; &lt;i16 8, i16 7&gt; to &lt;2 x i32&gt; <i>; yields &lt;i32 8, i32 7&gt;</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_sext">'<tt>sext .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = sext &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>sext</tt>' sign extends <tt>value</tt> to the type <tt>ty2</tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>sext</tt>' instruction takes a value to cast, and a type to cast it to.
+ Both types must be of <a href="#t_integer">integer</a> types, or vectors
+ of the same number of integers.
+ The bit size of the <tt>value</tt> must be smaller than
+ the bit size of the destination type,
+ <tt>ty2</tt>.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>sext</tt>' instruction performs a sign extension by copying the sign
+ bit (highest order bit) of the <tt>value</tt> until it reaches the bit size
+ of the type <tt>ty2</tt>.</p>
+
+<p>When sign extending from i1, the extension always results in -1 or 0.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = sext i8 -1 to i16 <i>; yields i16 :65535</i>
+ %Y = sext i1 true to i32 <i>; yields i32:-1</i>
+ %Z = sext &lt;2 x i16&gt; &lt;i16 8, i16 7&gt; to &lt;2 x i32&gt; <i>; yields &lt;i32 8, i32 7&gt;</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fptrunc">'<tt>fptrunc .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fptrunc &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fptrunc</tt>' instruction truncates <tt>value</tt> to type
+ <tt>ty2</tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>fptrunc</tt>' instruction takes a <a href="#t_floating">floating
+ point</a> value to cast and a <a href="#t_floating">floating point</a> type
+ to cast it to. The size of <tt>value</tt> must be larger than the size of
+ <tt>ty2</tt>. This implies that <tt>fptrunc</tt> cannot be used to make a
+ <i>no-op cast</i>.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>fptrunc</tt>' instruction truncates a <tt>value</tt> from a larger
+ <a href="#t_floating">floating point</a> type to a smaller
+ <a href="#t_floating">floating point</a> type. If the value cannot fit
+ within the destination type, <tt>ty2</tt>, then the results are
+ undefined.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = fptrunc double 123.0 to float <i>; yields float:123.0</i>
+ %Y = fptrunc double 1.0E+300 to float <i>; yields undefined</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fpext">'<tt>fpext .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fpext &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fpext</tt>' extends a floating point <tt>value</tt> to a larger
+ floating point value.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>fpext</tt>' instruction takes a
+ <a href="#t_floating">floating point</a> <tt>value</tt> to cast, and
+ a <a href="#t_floating">floating point</a> type to cast it to. The source
+ type must be smaller than the destination type.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>fpext</tt>' instruction extends the <tt>value</tt> from a smaller
+ <a href="#t_floating">floating point</a> type to a larger
+ <a href="#t_floating">floating point</a> type. The <tt>fpext</tt> cannot be
+ used to make a <i>no-op cast</i> because it always changes bits. Use
+ <tt>bitcast</tt> to make a <i>no-op cast</i> for a floating point cast.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = fpext float 3.125 to double <i>; yields double:3.125000e+00</i>
+ %Y = fpext double %X to fp128 <i>; yields fp128:0xL00000000000000004000900000000000</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fptoui">'<tt>fptoui .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fptoui &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fptoui</tt>' converts a floating point <tt>value</tt> to its
+ unsigned integer equivalent of type <tt>ty2</tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>fptoui</tt>' instruction takes a value to cast, which must be a
+ scalar or vector <a href="#t_floating">floating point</a> value, and a type
+ to cast it to <tt>ty2</tt>, which must be an <a href="#t_integer">integer</a>
+ type. If <tt>ty</tt> is a vector floating point type, <tt>ty2</tt> must be a
+ vector integer type with the same number of elements as <tt>ty</tt></p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>fptoui</tt>' instruction converts its
+ <a href="#t_floating">floating point</a> operand into the nearest (rounding
+ towards zero) unsigned integer value. If the value cannot fit
+ in <tt>ty2</tt>, the results are undefined.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = fptoui double 123.0 to i32 <i>; yields i32:123</i>
+ %Y = fptoui float 1.0E+300 to i1 <i>; yields undefined:1</i>
+ %Z = fptoui float 1.04E+17 to i8 <i>; yields undefined:1</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fptosi">'<tt>fptosi .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fptosi &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fptosi</tt>' instruction converts
+ <a href="#t_floating">floating point</a> <tt>value</tt> to
+ type <tt>ty2</tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>fptosi</tt>' instruction takes a value to cast, which must be a
+ scalar or vector <a href="#t_floating">floating point</a> value, and a type
+ to cast it to <tt>ty2</tt>, which must be an <a href="#t_integer">integer</a>
+ type. If <tt>ty</tt> is a vector floating point type, <tt>ty2</tt> must be a
+ vector integer type with the same number of elements as <tt>ty</tt></p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>fptosi</tt>' instruction converts its
+ <a href="#t_floating">floating point</a> operand into the nearest (rounding
+ towards zero) signed integer value. If the value cannot fit in <tt>ty2</tt>,
+ the results are undefined.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = fptosi double -123.0 to i32 <i>; yields i32:-123</i>
+ %Y = fptosi float 1.0E-247 to i1 <i>; yields undefined:1</i>
+ %Z = fptosi float 1.04E+17 to i8 <i>; yields undefined:1</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_uitofp">'<tt>uitofp .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = uitofp &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>uitofp</tt>' instruction regards <tt>value</tt> as an unsigned
+ integer and converts that value to the <tt>ty2</tt> type.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>uitofp</tt>' instruction takes a value to cast, which must be a
+ scalar or vector <a href="#t_integer">integer</a> value, and a type to cast
+ it to <tt>ty2</tt>, which must be an <a href="#t_floating">floating point</a>
+ type. If <tt>ty</tt> is a vector integer type, <tt>ty2</tt> must be a vector
+ floating point type with the same number of elements as <tt>ty</tt></p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>uitofp</tt>' instruction interprets its operand as an unsigned
+ integer quantity and converts it to the corresponding floating point
+ value. If the value cannot fit in the floating point value, the results are
+ undefined.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = uitofp i32 257 to float <i>; yields float:257.0</i>
+ %Y = uitofp i8 -1 to double <i>; yields double:255.0</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_sitofp">'<tt>sitofp .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = sitofp &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>sitofp</tt>' instruction regards <tt>value</tt> as a signed integer
+ and converts that value to the <tt>ty2</tt> type.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>sitofp</tt>' instruction takes a value to cast, which must be a
+ scalar or vector <a href="#t_integer">integer</a> value, and a type to cast
+ it to <tt>ty2</tt>, which must be an <a href="#t_floating">floating point</a>
+ type. If <tt>ty</tt> is a vector integer type, <tt>ty2</tt> must be a vector
+ floating point type with the same number of elements as <tt>ty</tt></p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>sitofp</tt>' instruction interprets its operand as a signed integer
+ quantity and converts it to the corresponding floating point value. If the
+ value cannot fit in the floating point value, the results are undefined.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = sitofp i32 257 to float <i>; yields float:257.0</i>
+ %Y = sitofp i8 -1 to double <i>; yields double:-1.0</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_ptrtoint">'<tt>ptrtoint .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = ptrtoint &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>ptrtoint</tt>' instruction converts the pointer or a vector of
+ pointers <tt>value</tt> to
+ the integer (or vector of integers) type <tt>ty2</tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>ptrtoint</tt>' instruction takes a <tt>value</tt> to cast, which
+ must be a a value of type <a href="#t_pointer">pointer</a> or a vector of
+ pointers, and a type to cast it to
+ <tt>ty2</tt>, which must be an <a href="#t_integer">integer</a> or a vector
+ of integers type.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>ptrtoint</tt>' instruction converts <tt>value</tt> to integer type
+ <tt>ty2</tt> by interpreting the pointer value as an integer and either
+ truncating or zero extending that value to the size of the integer type. If
+ <tt>value</tt> is smaller than <tt>ty2</tt> then a zero extension is done. If
+ <tt>value</tt> is larger than <tt>ty2</tt> then a truncation is done. If they
+ are the same size, then nothing is done (<i>no-op cast</i>) other than a type
+ change.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = ptrtoint i32* %P to i8 <i>; yields truncation on 32-bit architecture</i>
+ %Y = ptrtoint i32* %P to i64 <i>; yields zero extension on 32-bit architecture</i>
+ %Z = ptrtoint &lt;4 x i32*&gt; %P to &lt;4 x i64&gt;<i>; yields vector zero extension for a vector of addresses on 32-bit architecture</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_inttoptr">'<tt>inttoptr .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = inttoptr &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>inttoptr</tt>' instruction converts an integer <tt>value</tt> to a
+ pointer type, <tt>ty2</tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>inttoptr</tt>' instruction takes an <a href="#t_integer">integer</a>
+ value to cast, and a type to cast it to, which must be a
+ <a href="#t_pointer">pointer</a> type.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>inttoptr</tt>' instruction converts <tt>value</tt> to type
+ <tt>ty2</tt> by applying either a zero extension or a truncation depending on
+ the size of the integer <tt>value</tt>. If <tt>value</tt> is larger than the
+ size of a pointer then a truncation is done. If <tt>value</tt> is smaller
+ than the size of a pointer then a zero extension is done. If they are the
+ same size, nothing is done (<i>no-op cast</i>).</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = inttoptr i32 255 to i32* <i>; yields zero extension on 64-bit architecture</i>
+ %Y = inttoptr i32 255 to i32* <i>; yields no-op on 32-bit architecture</i>
+ %Z = inttoptr i64 0 to i32* <i>; yields truncation on 32-bit architecture</i>
+ %Z = inttoptr &lt;4 x i32&gt; %G to &lt;4 x i8*&gt;<i>; yields truncation of vector G to four pointers</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_bitcast">'<tt>bitcast .. to</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = bitcast &lt;ty&gt; &lt;value&gt; to &lt;ty2&gt; <i>; yields ty2</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>bitcast</tt>' instruction converts <tt>value</tt> to type
+ <tt>ty2</tt> without changing any bits.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>bitcast</tt>' instruction takes a value to cast, which must be a
+ non-aggregate first class value, and a type to cast it to, which must also be
+ a non-aggregate <a href="#t_firstclass">first class</a> type. The bit sizes
+ of <tt>value</tt> and the destination type, <tt>ty2</tt>, must be
+ identical. If the source type is a pointer, the destination type must also be
+ a pointer. This instruction supports bitwise conversion of vectors to
+ integers and to vectors of other types (as long as they have the same
+ size).</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>bitcast</tt>' instruction converts <tt>value</tt> to type
+ <tt>ty2</tt>. It is always a <i>no-op cast</i> because no bits change with
+ this conversion. The conversion is done as if the <tt>value</tt> had been
+ stored to memory and read back as type <tt>ty2</tt>.
+ Pointer (or vector of pointers) types may only be converted to other pointer
+ (or vector of pointers) types with this instruction. To convert
+ pointers to other types, use the <a href="#i_inttoptr">inttoptr</a> or
+ <a href="#i_ptrtoint">ptrtoint</a> instructions first.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = bitcast i8 255 to i8 <i>; yields i8 :-1</i>
+ %Y = bitcast i32* %x to sint* <i>; yields sint*:%x</i>
+ %Z = bitcast &lt;2 x int&gt; %V to i64; <i>; yields i64: %V</i>
+ %Z = bitcast &lt;2 x i32*&gt; %V to &lt;2 x i64*&gt; <i>; yields &lt;2 x i64*&gt;</i>
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="otherops">Other Operations</a>
+</h3>
+
+<div>
+
+<p>The instructions in this category are the "miscellaneous" instructions, which
+ defy better classification.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_icmp">'<tt>icmp</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = icmp &lt;cond&gt; &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {i1} or {&lt;N x i1&gt;}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>icmp</tt>' instruction returns a boolean value or a vector of
+ boolean values based on comparison of its two integer, integer vector,
+ pointer, or pointer vector operands.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>icmp</tt>' instruction takes three operands. The first operand is
+ the condition code indicating the kind of comparison to perform. It is not a
+ value, just a keyword. The possible condition code are:</p>
+
+<ol>
+ <li><tt>eq</tt>: equal</li>
+ <li><tt>ne</tt>: not equal </li>
+ <li><tt>ugt</tt>: unsigned greater than</li>
+ <li><tt>uge</tt>: unsigned greater or equal</li>
+ <li><tt>ult</tt>: unsigned less than</li>
+ <li><tt>ule</tt>: unsigned less or equal</li>
+ <li><tt>sgt</tt>: signed greater than</li>
+ <li><tt>sge</tt>: signed greater or equal</li>
+ <li><tt>slt</tt>: signed less than</li>
+ <li><tt>sle</tt>: signed less or equal</li>
+</ol>
+
+<p>The remaining two arguments must be <a href="#t_integer">integer</a> or
+ <a href="#t_pointer">pointer</a> or integer <a href="#t_vector">vector</a>
+ typed. They must also be identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>icmp</tt>' compares <tt>op1</tt> and <tt>op2</tt> according to the
+ condition code given as <tt>cond</tt>. The comparison performed always yields
+ either an <a href="#t_integer"><tt>i1</tt></a> or vector of <tt>i1</tt>
+ result, as follows:</p>
+
+<ol>
+ <li><tt>eq</tt>: yields <tt>true</tt> if the operands are equal,
+ <tt>false</tt> otherwise. No sign interpretation is necessary or
+ performed.</li>
+
+ <li><tt>ne</tt>: yields <tt>true</tt> if the operands are unequal,
+ <tt>false</tt> otherwise. No sign interpretation is necessary or
+ performed.</li>
+
+ <li><tt>ugt</tt>: interprets the operands as unsigned values and yields
+ <tt>true</tt> if <tt>op1</tt> is greater than <tt>op2</tt>.</li>
+
+ <li><tt>uge</tt>: interprets the operands as unsigned values and yields
+ <tt>true</tt> if <tt>op1</tt> is greater than or equal
+ to <tt>op2</tt>.</li>
+
+ <li><tt>ult</tt>: interprets the operands as unsigned values and yields
+ <tt>true</tt> if <tt>op1</tt> is less than <tt>op2</tt>.</li>
+
+ <li><tt>ule</tt>: interprets the operands as unsigned values and yields
+ <tt>true</tt> if <tt>op1</tt> is less than or equal to <tt>op2</tt>.</li>
+
+ <li><tt>sgt</tt>: interprets the operands as signed values and yields
+ <tt>true</tt> if <tt>op1</tt> is greater than <tt>op2</tt>.</li>
+
+ <li><tt>sge</tt>: interprets the operands as signed values and yields
+ <tt>true</tt> if <tt>op1</tt> is greater than or equal
+ to <tt>op2</tt>.</li>
+
+ <li><tt>slt</tt>: interprets the operands as signed values and yields
+ <tt>true</tt> if <tt>op1</tt> is less than <tt>op2</tt>.</li>
+
+ <li><tt>sle</tt>: interprets the operands as signed values and yields
+ <tt>true</tt> if <tt>op1</tt> is less than or equal to <tt>op2</tt>.</li>
+</ol>
+
+<p>If the operands are <a href="#t_pointer">pointer</a> typed, the pointer
+ values are compared as if they were integers.</p>
+
+<p>If the operands are integer vectors, then they are compared element by
+ element. The result is an <tt>i1</tt> vector with the same number of elements
+ as the values being compared. Otherwise, the result is an <tt>i1</tt>.</p>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = icmp eq i32 4, 5 <i>; yields: result=false</i>
+ &lt;result&gt; = icmp ne float* %X, %X <i>; yields: result=false</i>
+ &lt;result&gt; = icmp ult i16 4, 5 <i>; yields: result=true</i>
+ &lt;result&gt; = icmp sgt i16 4, 5 <i>; yields: result=false</i>
+ &lt;result&gt; = icmp ule i16 -4, 5 <i>; yields: result=false</i>
+ &lt;result&gt; = icmp sge i16 4, 5 <i>; yields: result=false</i>
+</pre>
+
+<p>Note that the code generator does not yet support vector types with
+ the <tt>icmp</tt> instruction.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_fcmp">'<tt>fcmp</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = fcmp &lt;cond&gt; &lt;ty&gt; &lt;op1&gt;, &lt;op2&gt; <i>; yields {i1} or {&lt;N x i1&gt;}:result</i>
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>fcmp</tt>' instruction returns a boolean value or vector of boolean
+ values based on comparison of its operands.</p>
+
+<p>If the operands are floating point scalars, then the result type is a boolean
+(<a href="#t_integer"><tt>i1</tt></a>).</p>
+
+<p>If the operands are floating point vectors, then the result type is a vector
+ of boolean with the same number of elements as the operands being
+ compared.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>fcmp</tt>' instruction takes three operands. The first operand is
+ the condition code indicating the kind of comparison to perform. It is not a
+ value, just a keyword. The possible condition code are:</p>
+
+<ol>
+ <li><tt>false</tt>: no comparison, always returns false</li>
+ <li><tt>oeq</tt>: ordered and equal</li>
+ <li><tt>ogt</tt>: ordered and greater than </li>
+ <li><tt>oge</tt>: ordered and greater than or equal</li>
+ <li><tt>olt</tt>: ordered and less than </li>
+ <li><tt>ole</tt>: ordered and less than or equal</li>
+ <li><tt>one</tt>: ordered and not equal</li>
+ <li><tt>ord</tt>: ordered (no nans)</li>
+ <li><tt>ueq</tt>: unordered or equal</li>
+ <li><tt>ugt</tt>: unordered or greater than </li>
+ <li><tt>uge</tt>: unordered or greater than or equal</li>
+ <li><tt>ult</tt>: unordered or less than </li>
+ <li><tt>ule</tt>: unordered or less than or equal</li>
+ <li><tt>une</tt>: unordered or not equal</li>
+ <li><tt>uno</tt>: unordered (either nans)</li>
+ <li><tt>true</tt>: no comparison, always returns true</li>
+</ol>
+
+<p><i>Ordered</i> means that neither operand is a QNAN while
+ <i>unordered</i> means that either operand may be a QNAN.</p>
+
+<p>Each of <tt>val1</tt> and <tt>val2</tt> arguments must be either
+ a <a href="#t_floating">floating point</a> type or
+ a <a href="#t_vector">vector</a> of floating point type. They must have
+ identical types.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>fcmp</tt>' instruction compares <tt>op1</tt> and <tt>op2</tt>
+ according to the condition code given as <tt>cond</tt>. If the operands are
+ vectors, then the vectors are compared element by element. Each comparison
+ performed always yields an <a href="#t_integer">i1</a> result, as
+ follows:</p>
+
+<ol>
+ <li><tt>false</tt>: always yields <tt>false</tt>, regardless of operands.</li>
+
+ <li><tt>oeq</tt>: yields <tt>true</tt> if both operands are not a QNAN and
+ <tt>op1</tt> is equal to <tt>op2</tt>.</li>
+
+ <li><tt>ogt</tt>: yields <tt>true</tt> if both operands are not a QNAN and
+ <tt>op1</tt> is greater than <tt>op2</tt>.</li>
+
+ <li><tt>oge</tt>: yields <tt>true</tt> if both operands are not a QNAN and
+ <tt>op1</tt> is greater than or equal to <tt>op2</tt>.</li>
+
+ <li><tt>olt</tt>: yields <tt>true</tt> if both operands are not a QNAN and
+ <tt>op1</tt> is less than <tt>op2</tt>.</li>
+
+ <li><tt>ole</tt>: yields <tt>true</tt> if both operands are not a QNAN and
+ <tt>op1</tt> is less than or equal to <tt>op2</tt>.</li>
+
+ <li><tt>one</tt>: yields <tt>true</tt> if both operands are not a QNAN and
+ <tt>op1</tt> is not equal to <tt>op2</tt>.</li>
+
+ <li><tt>ord</tt>: yields <tt>true</tt> if both operands are not a QNAN.</li>
+
+ <li><tt>ueq</tt>: yields <tt>true</tt> if either operand is a QNAN or
+ <tt>op1</tt> is equal to <tt>op2</tt>.</li>
+
+ <li><tt>ugt</tt>: yields <tt>true</tt> if either operand is a QNAN or
+ <tt>op1</tt> is greater than <tt>op2</tt>.</li>
+
+ <li><tt>uge</tt>: yields <tt>true</tt> if either operand is a QNAN or
+ <tt>op1</tt> is greater than or equal to <tt>op2</tt>.</li>
+
+ <li><tt>ult</tt>: yields <tt>true</tt> if either operand is a QNAN or
+ <tt>op1</tt> is less than <tt>op2</tt>.</li>
+
+ <li><tt>ule</tt>: yields <tt>true</tt> if either operand is a QNAN or
+ <tt>op1</tt> is less than or equal to <tt>op2</tt>.</li>
+
+ <li><tt>une</tt>: yields <tt>true</tt> if either operand is a QNAN or
+ <tt>op1</tt> is not equal to <tt>op2</tt>.</li>
+
+ <li><tt>uno</tt>: yields <tt>true</tt> if either operand is a QNAN.</li>
+
+ <li><tt>true</tt>: always yields <tt>true</tt>, regardless of operands.</li>
+</ol>
+
+<h5>Example:</h5>
+<pre>
+ &lt;result&gt; = fcmp oeq float 4.0, 5.0 <i>; yields: result=false</i>
+ &lt;result&gt; = fcmp one float 4.0, 5.0 <i>; yields: result=true</i>
+ &lt;result&gt; = fcmp olt float 4.0, 5.0 <i>; yields: result=true</i>
+ &lt;result&gt; = fcmp ueq double 1.0, 2.0 <i>; yields: result=false</i>
+</pre>
+
+<p>Note that the code generator does not yet support vector types with
+ the <tt>fcmp</tt> instruction.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_phi">'<tt>phi</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = phi &lt;ty&gt; [ &lt;val0&gt;, &lt;label0&gt;], ...
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>phi</tt>' instruction is used to implement the &#966; node in the
+ SSA graph representing the function.</p>
+
+<h5>Arguments:</h5>
+<p>The type of the incoming values is specified with the first type field. After
+ this, the '<tt>phi</tt>' instruction takes a list of pairs as arguments, with
+ one pair for each predecessor basic block of the current block. Only values
+ of <a href="#t_firstclass">first class</a> type may be used as the value
+ arguments to the PHI node. Only labels may be used as the label
+ arguments.</p>
+
+<p>There must be no non-phi instructions between the start of a basic block and
+ the PHI instructions: i.e. PHI instructions must be first in a basic
+ block.</p>
+
+<p>For the purposes of the SSA form, the use of each incoming value is deemed to
+ occur on the edge from the corresponding predecessor block to the current
+ block (but after any definition of an '<tt>invoke</tt>' instruction's return
+ value on the same edge).</p>
+
+<h5>Semantics:</h5>
+<p>At runtime, the '<tt>phi</tt>' instruction logically takes on the value
+ specified by the pair corresponding to the predecessor basic block that
+ executed just prior to the current block.</p>
+
+<h5>Example:</h5>
+<pre>
+Loop: ; Infinite loop that counts from 0 on up...
+ %indvar = phi i32 [ 0, %LoopHeader ], [ %nextindvar, %Loop ]
+ %nextindvar = add i32 %indvar, 1
+ br label %Loop
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_select">'<tt>select</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = select <i>selty</i> &lt;cond&gt;, &lt;ty&gt; &lt;val1&gt;, &lt;ty&gt; &lt;val2&gt; <i>; yields ty</i>
+
+ <i>selty</i> is either i1 or {&lt;N x i1&gt;}
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>select</tt>' instruction is used to choose one value based on a
+ condition, without branching.</p>
+
+
+<h5>Arguments:</h5>
+<p>The '<tt>select</tt>' instruction requires an 'i1' value or a vector of 'i1'
+ values indicating the condition, and two values of the
+ same <a href="#t_firstclass">first class</a> type. If the val1/val2 are
+ vectors and the condition is a scalar, then entire vectors are selected, not
+ individual elements.</p>
+
+<h5>Semantics:</h5>
+<p>If the condition is an i1 and it evaluates to 1, the instruction returns the
+ first value argument; otherwise, it returns the second value argument.</p>
+
+<p>If the condition is a vector of i1, then the value arguments must be vectors
+ of the same size, and the selection is done element by element.</p>
+
+<h5>Example:</h5>
+<pre>
+ %X = select i1 true, i8 17, i8 42 <i>; yields i8:17</i>
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_call">'<tt>call</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;result&gt; = [tail] call [<a href="#callingconv">cconv</a>] [<a href="#paramattrs">ret attrs</a>] &lt;ty&gt; [&lt;fnty&gt;*] &lt;fnptrval&gt;(&lt;function args&gt;) [<a href="#fnattrs">fn attrs</a>]
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>call</tt>' instruction represents a simple function call.</p>
+
+<h5>Arguments:</h5>
+<p>This instruction requires several arguments:</p>
+
+<ol>
+ <li>The optional "tail" marker indicates that the callee function does not
+ access any allocas or varargs in the caller. Note that calls may be
+ marked "tail" even if they do not occur before
+ a <a href="#i_ret"><tt>ret</tt></a> instruction. If the "tail" marker is
+ present, the function call is eligible for tail call optimization,
+ but <a href="CodeGenerator.html#tailcallopt">might not in fact be
+ optimized into a jump</a>. The code generator may optimize calls marked
+ "tail" with either 1) automatic <a href="CodeGenerator.html#sibcallopt">
+ sibling call optimization</a> when the caller and callee have
+ matching signatures, or 2) forced tail call optimization when the
+ following extra requirements are met:
+ <ul>
+ <li>Caller and callee both have the calling
+ convention <tt>fastcc</tt>.</li>
+ <li>The call is in tail position (ret immediately follows call and ret
+ uses value of call or is void).</li>
+ <li>Option <tt>-tailcallopt</tt> is enabled,
+ or <code>llvm::GuaranteedTailCallOpt</code> is <code>true</code>.</li>
+ <li><a href="CodeGenerator.html#tailcallopt">Platform specific
+ constraints are met.</a></li>
+ </ul>
+ </li>
+
+ <li>The optional "cconv" marker indicates which <a href="#callingconv">calling
+ convention</a> the call should use. If none is specified, the call
+ defaults to using C calling conventions. The calling convention of the
+ call must match the calling convention of the target function, or else the
+ behavior is undefined.</li>
+
+ <li>The optional <a href="#paramattrs">Parameter Attributes</a> list for
+ return values. Only '<tt>zeroext</tt>', '<tt>signext</tt>', and
+ '<tt>inreg</tt>' attributes are valid here.</li>
+
+ <li>'<tt>ty</tt>': the type of the call instruction itself which is also the
+ type of the return value. Functions that return no value are marked
+ <tt><a href="#t_void">void</a></tt>.</li>
+
+ <li>'<tt>fnty</tt>': shall be the signature of the pointer to function value
+ being invoked. The argument types must match the types implied by this
+ signature. This type can be omitted if the function is not varargs and if
+ the function type does not return a pointer to a function.</li>
+
+ <li>'<tt>fnptrval</tt>': An LLVM value containing a pointer to a function to
+ be invoked. In most cases, this is a direct function invocation, but
+ indirect <tt>call</tt>s are just as possible, calling an arbitrary pointer
+ to function value.</li>
+
+ <li>'<tt>function args</tt>': argument list whose types match the function
+ signature argument types and parameter attributes. All arguments must be
+ of <a href="#t_firstclass">first class</a> type. If the function
+ signature indicates the function accepts a variable number of arguments,
+ the extra arguments can be specified.</li>
+
+ <li>The optional <a href="#fnattrs">function attributes</a> list. Only
+ '<tt>noreturn</tt>', '<tt>nounwind</tt>', '<tt>readonly</tt>' and
+ '<tt>readnone</tt>' attributes are valid here.</li>
+</ol>
+
+<h5>Semantics:</h5>
+<p>The '<tt>call</tt>' instruction is used to cause control flow to transfer to
+ a specified function, with its incoming arguments bound to the specified
+ values. Upon a '<tt><a href="#i_ret">ret</a></tt>' instruction in the called
+ function, control flow continues with the instruction after the function
+ call, and the return value of the function is bound to the result
+ argument.</p>
+
+<h5>Example:</h5>
+<pre>
+ %retval = call i32 @test(i32 %argc)
+ call i32 (i8*, ...)* @printf(i8* %msg, i32 12, i8 42) <i>; yields i32</i>
+ %X = tail call i32 @foo() <i>; yields i32</i>
+ %Y = tail call <a href="#callingconv">fastcc</a> i32 @foo() <i>; yields i32</i>
+ call void %foo(i8 97 signext)
+
+ %struct.A = type { i32, i8 }
+ %r = call %struct.A @foo() <i>; yields { 32, i8 }</i>
+ %gr = extractvalue %struct.A %r, 0 <i>; yields i32</i>
+ %gr1 = extractvalue %struct.A %r, 1 <i>; yields i8</i>
+ %Z = call void @foo() noreturn <i>; indicates that %foo never returns normally</i>
+ %ZZ = call zeroext i32 @bar() <i>; Return value is %zero extended</i>
+</pre>
+
+<p>llvm treats calls to some functions with names and arguments that match the
+standard C99 library as being the C99 library functions, and may perform
+optimizations or generate code for them under that assumption. This is
+something we'd like to change in the future to provide better support for
+freestanding environments and non-C-based languages.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_va_arg">'<tt>va_arg</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;resultval&gt; = va_arg &lt;va_list*&gt; &lt;arglist&gt;, &lt;argty&gt;
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>va_arg</tt>' instruction is used to access arguments passed through
+ the "variable argument" area of a function call. It is used to implement the
+ <tt>va_arg</tt> macro in C.</p>
+
+<h5>Arguments:</h5>
+<p>This instruction takes a <tt>va_list*</tt> value and the type of the
+ argument. It returns a value of the specified argument type and increments
+ the <tt>va_list</tt> to point to the next argument. The actual type
+ of <tt>va_list</tt> is target specific.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>va_arg</tt>' instruction loads an argument of the specified type
+ from the specified <tt>va_list</tt> and causes the <tt>va_list</tt> to point
+ to the next argument. For more information, see the variable argument
+ handling <a href="#int_varargs">Intrinsic Functions</a>.</p>
+
+<p>It is legal for this instruction to be called in a function which does not
+ take a variable number of arguments, for example, the <tt>vfprintf</tt>
+ function.</p>
+
+<p><tt>va_arg</tt> is an LLVM instruction instead of
+ an <a href="#intrinsics">intrinsic function</a> because it takes a type as an
+ argument.</p>
+
+<h5>Example:</h5>
+<p>See the <a href="#int_varargs">variable argument processing</a> section.</p>
+
+<p>Note that the code generator does not yet fully support va_arg on many
+ targets. Also, it does not currently support va_arg with aggregate types on
+ any target.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="i_landingpad">'<tt>landingpad</tt>' Instruction</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ &lt;resultval&gt; = landingpad &lt;resultty&gt; personality &lt;type&gt; &lt;pers_fn&gt; &lt;clause&gt;+
+ &lt;resultval&gt; = landingpad &lt;resultty&gt; personality &lt;type&gt; &lt;pers_fn&gt; cleanup &lt;clause&gt;*
+
+ &lt;clause&gt; := catch &lt;type&gt; &lt;value&gt;
+ &lt;clause&gt; := filter &lt;array constant type&gt; &lt;array constant&gt;
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>landingpad</tt>' instruction is used by
+ <a href="ExceptionHandling.html#overview">LLVM's exception handling
+ system</a> to specify that a basic block is a landing pad &mdash; one where
+ the exception lands, and corresponds to the code found in the
+ <i><tt>catch</tt></i> portion of a <i><tt>try/catch</tt></i> sequence. It
+ defines values supplied by the personality function (<tt>pers_fn</tt>) upon
+ re-entry to the function. The <tt>resultval</tt> has the
+ type <tt>resultty</tt>.</p>
+
+<h5>Arguments:</h5>
+<p>This instruction takes a <tt>pers_fn</tt> value. This is the personality
+ function associated with the unwinding mechanism. The optional
+ <tt>cleanup</tt> flag indicates that the landing pad block is a cleanup.</p>
+
+<p>A <tt>clause</tt> begins with the clause type &mdash; <tt>catch</tt>
+ or <tt>filter</tt> &mdash; and contains the global variable representing the
+ "type" that may be caught or filtered respectively. Unlike the
+ <tt>catch</tt> clause, the <tt>filter</tt> clause takes an array constant as
+ its argument. Use "<tt>[0 x i8**] undef</tt>" for a filter which cannot
+ throw. The '<tt>landingpad</tt>' instruction must contain <em>at least</em>
+ one <tt>clause</tt> or the <tt>cleanup</tt> flag.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>landingpad</tt>' instruction defines the values which are set by the
+ personality function (<tt>pers_fn</tt>) upon re-entry to the function, and
+ therefore the "result type" of the <tt>landingpad</tt> instruction. As with
+ calling conventions, how the personality function results are represented in
+ LLVM IR is target specific.</p>
+
+<p>The clauses are applied in order from top to bottom. If two
+ <tt>landingpad</tt> instructions are merged together through inlining, the
+ clauses from the calling function are appended to the list of clauses.
+ When the call stack is being unwound due to an exception being thrown, the
+ exception is compared against each <tt>clause</tt> in turn. If it doesn't
+ match any of the clauses, and the <tt>cleanup</tt> flag is not set, then
+ unwinding continues further up the call stack.</p>
+
+<p>The <tt>landingpad</tt> instruction has several restrictions:</p>
+
+<ul>
+ <li>A landing pad block is a basic block which is the unwind destination of an
+ '<tt>invoke</tt>' instruction.</li>
+ <li>A landing pad block must have a '<tt>landingpad</tt>' instruction as its
+ first non-PHI instruction.</li>
+ <li>There can be only one '<tt>landingpad</tt>' instruction within the landing
+ pad block.</li>
+ <li>A basic block that is not a landing pad block may not include a
+ '<tt>landingpad</tt>' instruction.</li>
+ <li>All '<tt>landingpad</tt>' instructions in a function must have the same
+ personality function.</li>
+</ul>
+
+<h5>Example:</h5>
+<pre>
+ ;; A landing pad which can catch an integer.
+ %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0
+ catch i8** @_ZTIi
+ ;; A landing pad that is a cleanup.
+ %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0
+ cleanup
+ ;; A landing pad which can catch an integer and can only throw a double.
+ %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0
+ catch i8** @_ZTIi
+ filter [1 x i8**] [@_ZTId]
+</pre>
+
+</div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intrinsics">Intrinsic Functions</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>LLVM supports the notion of an "intrinsic function". These functions have
+ well known names and semantics and are required to follow certain
+ restrictions. Overall, these intrinsics represent an extension mechanism for
+ the LLVM language that does not require changing all of the transformations
+ in LLVM when adding to the language (or the bitcode reader/writer, the
+ parser, etc...).</p>
+
+<p>Intrinsic function names must all start with an "<tt>llvm.</tt>" prefix. This
+ prefix is reserved in LLVM for intrinsic names; thus, function names may not
+ begin with this prefix. Intrinsic functions must always be external
+ functions: you cannot define the body of intrinsic functions. Intrinsic
+ functions may only be used in call or invoke instructions: it is illegal to
+ take the address of an intrinsic function. Additionally, because intrinsic
+ functions are part of the LLVM language, it is required if any are added that
+ they be documented here.</p>
+
+<p>Some intrinsic functions can be overloaded, i.e., the intrinsic represents a
+ family of functions that perform the same operation but on different data
+ types. Because LLVM can represent over 8 million different integer types,
+ overloading is used commonly to allow an intrinsic function to operate on any
+ integer type. One or more of the argument types or the result type can be
+ overloaded to accept any integer type. Argument types may also be defined as
+ exactly matching a previous argument's type or the result type. This allows
+ an intrinsic function which accepts multiple arguments, but needs all of them
+ to be of the same type, to only be overloaded with respect to a single
+ argument or the result.</p>
+
+<p>Overloaded intrinsics will have the names of its overloaded argument types
+ encoded into its function name, each preceded by a period. Only those types
+ which are overloaded result in a name suffix. Arguments whose type is matched
+ against another type do not. For example, the <tt>llvm.ctpop</tt> function
+ can take an integer of any width and returns an integer of exactly the same
+ integer width. This leads to a family of functions such as
+ <tt>i8 @llvm.ctpop.i8(i8 %val)</tt> and <tt>i29 @llvm.ctpop.i29(i29
+ %val)</tt>. Only one type, the return type, is overloaded, and only one type
+ suffix is required. Because the argument's type is matched against the return
+ type, it does not require its own name suffix.</p>
+
+<p>To learn how to add an intrinsic function, please see the
+ <a href="ExtendingLLVM.html">Extending LLVM Guide</a>.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_varargs">Variable Argument Handling Intrinsics</a>
+</h3>
+
+<div>
+
+<p>Variable argument support is defined in LLVM with
+ the <a href="#i_va_arg"><tt>va_arg</tt></a> instruction and these three
+ intrinsic functions. These functions are related to the similarly named
+ macros defined in the <tt>&lt;stdarg.h&gt;</tt> header file.</p>
+
+<p>All of these functions operate on arguments that use a target-specific value
+ type "<tt>va_list</tt>". The LLVM assembly language reference manual does
+ not define what this type is, so all transformations should be prepared to
+ handle these functions regardless of the type used.</p>
+
+<p>This example shows how the <a href="#i_va_arg"><tt>va_arg</tt></a>
+ instruction and the variable argument handling intrinsic functions are
+ used.</p>
+
+<pre class="doc_code">
+define i32 @test(i32 %X, ...) {
+ ; Initialize variable argument processing
+ %ap = alloca i8*
+ %ap2 = bitcast i8** %ap to i8*
+ call void @llvm.va_start(i8* %ap2)
+
+ ; Read a single integer argument
+ %tmp = va_arg i8** %ap, i32
+
+ ; Demonstrate usage of llvm.va_copy and llvm.va_end
+ %aq = alloca i8*
+ %aq2 = bitcast i8** %aq to i8*
+ call void @llvm.va_copy(i8* %aq2, i8* %ap2)
+ call void @llvm.va_end(i8* %aq2)
+
+ ; Stop processing of arguments.
+ call void @llvm.va_end(i8* %ap2)
+ ret i32 %tmp
+}
+
+declare void @llvm.va_start(i8*)
+declare void @llvm.va_copy(i8*, i8*)
+declare void @llvm.va_end(i8*)
+</pre>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_va_start">'<tt>llvm.va_start</tt>' Intrinsic</a>
+</h4>
+
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void %llvm.va_start(i8* &lt;arglist&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.va_start</tt>' intrinsic initializes <tt>*&lt;arglist&gt;</tt>
+ for subsequent use by <tt><a href="#i_va_arg">va_arg</a></tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The argument is a pointer to a <tt>va_list</tt> element to initialize.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.va_start</tt>' intrinsic works just like the <tt>va_start</tt>
+ macro available in C. In a target-dependent way, it initializes
+ the <tt>va_list</tt> element to which the argument points, so that the next
+ call to <tt>va_arg</tt> will produce the first variable argument passed to
+ the function. Unlike the C <tt>va_start</tt> macro, this intrinsic does not
+ need to know the last argument of the function as the compiler can figure
+ that out.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_va_end">'<tt>llvm.va_end</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.va_end(i8* &lt;arglist&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.va_end</tt>' intrinsic destroys <tt>*&lt;arglist&gt;</tt>,
+ which has been initialized previously
+ with <tt><a href="#int_va_start">llvm.va_start</a></tt>
+ or <tt><a href="#i_va_copy">llvm.va_copy</a></tt>.</p>
+
+<h5>Arguments:</h5>
+<p>The argument is a pointer to a <tt>va_list</tt> to destroy.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.va_end</tt>' intrinsic works just like the <tt>va_end</tt>
+ macro available in C. In a target-dependent way, it destroys
+ the <tt>va_list</tt> element to which the argument points. Calls
+ to <a href="#int_va_start"><tt>llvm.va_start</tt></a>
+ and <a href="#int_va_copy"> <tt>llvm.va_copy</tt></a> must be matched exactly
+ with calls to <tt>llvm.va_end</tt>.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_va_copy">'<tt>llvm.va_copy</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.va_copy(i8* &lt;destarglist&gt;, i8* &lt;srcarglist&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.va_copy</tt>' intrinsic copies the current argument position
+ from the source argument list to the destination argument list.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is a pointer to a <tt>va_list</tt> element to initialize.
+ The second argument is a pointer to a <tt>va_list</tt> element to copy
+ from.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.va_copy</tt>' intrinsic works just like the <tt>va_copy</tt>
+ macro available in C. In a target-dependent way, it copies the
+ source <tt>va_list</tt> element into the destination <tt>va_list</tt>
+ element. This intrinsic is necessary because
+ the <tt><a href="#int_va_start"> llvm.va_start</a></tt> intrinsic may be
+ arbitrarily complex and require, for example, memory allocation.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_gc">Accurate Garbage Collection Intrinsics</a>
+</h3>
+
+<div>
+
+<p>LLVM support for <a href="GarbageCollection.html">Accurate Garbage
+Collection</a> (GC) requires the implementation and generation of these
+intrinsics. These intrinsics allow identification of <a href="#int_gcroot">GC
+roots on the stack</a>, as well as garbage collector implementations that
+require <a href="#int_gcread">read</a> and <a href="#int_gcwrite">write</a>
+barriers. Front-ends for type-safe garbage collected languages should generate
+these intrinsics to make use of the LLVM garbage collectors. For more details,
+see <a href="GarbageCollection.html">Accurate Garbage Collection with
+LLVM</a>.</p>
+
+<p>The garbage collection intrinsics only operate on objects in the generic
+ address space (address space zero).</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_gcroot">'<tt>llvm.gcroot</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.gcroot</tt>' intrinsic declares the existence of a GC root to
+ the code generator, and allows some metadata to be associated with it.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument specifies the address of a stack object that contains the
+ root pointer. The second pointer (which must be either a constant or a
+ global value address) contains the meta-data to be associated with the
+ root.</p>
+
+<h5>Semantics:</h5>
+<p>At runtime, a call to this intrinsic stores a null pointer into the "ptrloc"
+ location. At compile-time, the code generator generates information to allow
+ the runtime to find the pointer at GC safe points. The '<tt>llvm.gcroot</tt>'
+ intrinsic may only be used in a function which <a href="#gc">specifies a GC
+ algorithm</a>.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_gcread">'<tt>llvm.gcread</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i8* @llvm.gcread(i8* %ObjPtr, i8** %Ptr)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.gcread</tt>' intrinsic identifies reads of references from heap
+ locations, allowing garbage collector implementations that require read
+ barriers.</p>
+
+<h5>Arguments:</h5>
+<p>The second argument is the address to read from, which should be an address
+ allocated from the garbage collector. The first object is a pointer to the
+ start of the referenced object, if needed by the language runtime (otherwise
+ null).</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.gcread</tt>' intrinsic has the same semantics as a load
+ instruction, but may be replaced with substantially more complex code by the
+ garbage collector runtime, as needed. The '<tt>llvm.gcread</tt>' intrinsic
+ may only be used in a function which <a href="#gc">specifies a GC
+ algorithm</a>.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_gcwrite">'<tt>llvm.gcwrite</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.gcwrite(i8* %P1, i8* %Obj, i8** %P2)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.gcwrite</tt>' intrinsic identifies writes of references to heap
+ locations, allowing garbage collector implementations that require write
+ barriers (such as generational or reference counting collectors).</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is the reference to store, the second is the start of the
+ object to store it to, and the third is the address of the field of Obj to
+ store to. If the runtime does not require a pointer to the object, Obj may
+ be null.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.gcwrite</tt>' intrinsic has the same semantics as a store
+ instruction, but may be replaced with substantially more complex code by the
+ garbage collector runtime, as needed. The '<tt>llvm.gcwrite</tt>' intrinsic
+ may only be used in a function which <a href="#gc">specifies a GC
+ algorithm</a>.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_codegen">Code Generator Intrinsics</a>
+</h3>
+
+<div>
+
+<p>These intrinsics are provided by LLVM to expose special features that may
+ only be implemented with code generator support.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_returnaddress">'<tt>llvm.returnaddress</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i8 *@llvm.returnaddress(i32 &lt;level&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.returnaddress</tt>' intrinsic attempts to compute a
+ target-specific value indicating the return address of the current function
+ or one of its callers.</p>
+
+<h5>Arguments:</h5>
+<p>The argument to this intrinsic indicates which function to return the address
+ for. Zero indicates the calling function, one indicates its caller, etc.
+ The argument is <b>required</b> to be a constant integer value.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.returnaddress</tt>' intrinsic either returns a pointer
+ indicating the return address of the specified call frame, or zero if it
+ cannot be identified. The value returned by this intrinsic is likely to be
+ incorrect or 0 for arguments other than zero, so it should only be used for
+ debugging purposes.</p>
+
+<p>Note that calling this intrinsic does not prevent function inlining or other
+ aggressive transformations, so the value returned may not be that of the
+ obvious source-language caller.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_frameaddress">'<tt>llvm.frameaddress</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i8* @llvm.frameaddress(i32 &lt;level&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.frameaddress</tt>' intrinsic attempts to return the
+ target-specific frame pointer value for the specified stack frame.</p>
+
+<h5>Arguments:</h5>
+<p>The argument to this intrinsic indicates which function to return the frame
+ pointer for. Zero indicates the calling function, one indicates its caller,
+ etc. The argument is <b>required</b> to be a constant integer value.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.frameaddress</tt>' intrinsic either returns a pointer
+ indicating the frame address of the specified call frame, or zero if it
+ cannot be identified. The value returned by this intrinsic is likely to be
+ incorrect or 0 for arguments other than zero, so it should only be used for
+ debugging purposes.</p>
+
+<p>Note that calling this intrinsic does not prevent function inlining or other
+ aggressive transformations, so the value returned may not be that of the
+ obvious source-language caller.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_stacksave">'<tt>llvm.stacksave</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i8* @llvm.stacksave()
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.stacksave</tt>' intrinsic is used to remember the current state
+ of the function stack, for use
+ with <a href="#int_stackrestore"> <tt>llvm.stackrestore</tt></a>. This is
+ useful for implementing language features like scoped automatic variable
+ sized arrays in C99.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic returns a opaque pointer value that can be passed
+ to <a href="#int_stackrestore"><tt>llvm.stackrestore</tt></a>. When
+ an <tt>llvm.stackrestore</tt> intrinsic is executed with a value saved
+ from <tt>llvm.stacksave</tt>, it effectively restores the state of the stack
+ to the state it was in when the <tt>llvm.stacksave</tt> intrinsic executed.
+ In practice, this pops any <a href="#i_alloca">alloca</a> blocks from the
+ stack that were allocated after the <tt>llvm.stacksave</tt> was executed.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_stackrestore">'<tt>llvm.stackrestore</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.stackrestore(i8* %ptr)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.stackrestore</tt>' intrinsic is used to restore the state of
+ the function stack to the state it was in when the
+ corresponding <a href="#int_stacksave"><tt>llvm.stacksave</tt></a> intrinsic
+ executed. This is useful for implementing language features like scoped
+ automatic variable sized arrays in C99.</p>
+
+<h5>Semantics:</h5>
+<p>See the description
+ for <a href="#int_stacksave"><tt>llvm.stacksave</tt></a>.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_prefetch">'<tt>llvm.prefetch</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.prefetch(i8* &lt;address&gt;, i32 &lt;rw&gt;, i32 &lt;locality&gt;, i32 &lt;cache type&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.prefetch</tt>' intrinsic is a hint to the code generator to
+ insert a prefetch instruction if supported; otherwise, it is a noop.
+ Prefetches have no effect on the behavior of the program but can change its
+ performance characteristics.</p>
+
+<h5>Arguments:</h5>
+<p><tt>address</tt> is the address to be prefetched, <tt>rw</tt> is the
+ specifier determining if the fetch should be for a read (0) or write (1),
+ and <tt>locality</tt> is a temporal locality specifier ranging from (0) - no
+ locality, to (3) - extremely local keep in cache. The <tt>cache type</tt>
+ specifies whether the prefetch is performed on the data (1) or instruction (0)
+ cache. The <tt>rw</tt>, <tt>locality</tt> and <tt>cache type</tt> arguments
+ must be constant integers.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic does not modify the behavior of the program. In particular,
+ prefetches cannot trap and do not produce a value. On targets that support
+ this intrinsic, the prefetch can provide hints to the processor cache for
+ better performance.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_pcmarker">'<tt>llvm.pcmarker</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.pcmarker(i32 &lt;id&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.pcmarker</tt>' intrinsic is a method to export a Program
+ Counter (PC) in a region of code to simulators and other tools. The method
+ is target specific, but it is expected that the marker will use exported
+ symbols to transmit the PC of the marker. The marker makes no guarantees
+ that it will remain with any specific instruction after optimizations. It is
+ possible that the presence of a marker will inhibit optimizations. The
+ intended use is to be inserted after optimizations to allow correlations of
+ simulation runs.</p>
+
+<h5>Arguments:</h5>
+<p><tt>id</tt> is a numerical id identifying the marker.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic does not modify the behavior of the program. Backends that do
+ not support this intrinsic may ignore it.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_readcyclecounter">'<tt>llvm.readcyclecounter</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i64 @llvm.readcyclecounter()
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.readcyclecounter</tt>' intrinsic provides access to the cycle
+ counter register (or similar low latency, high accuracy clocks) on those
+ targets that support it. On X86, it should map to RDTSC. On Alpha, it
+ should map to RPCC. As the backing counters overflow quickly (on the order
+ of 9 seconds on alpha), this should only be used for small timings.</p>
+
+<h5>Semantics:</h5>
+<p>When directly supported, reading the cycle counter should not modify any
+ memory. Implementations are allowed to either return a application specific
+ value or a system wide value. On backends without support, this is lowered
+ to a constant 0.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_libc">Standard C Library Intrinsics</a>
+</h3>
+
+<div>
+
+<p>LLVM provides intrinsics for a few important standard C library functions.
+ These intrinsics allow source-language front-ends to pass information about
+ the alignment of the pointer arguments to the code generator, providing
+ opportunity for more efficient code generation.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_memcpy">'<tt>llvm.memcpy</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.memcpy</tt> on any
+ integer bit width and for different address spaces. Not all targets support
+ all bit widths however.</p>
+
+<pre>
+ declare void @llvm.memcpy.p0i8.p0i8.i32(i8* &lt;dest&gt;, i8* &lt;src&gt;,
+ i32 &lt;len&gt;, i32 &lt;align&gt;, i1 &lt;isvolatile&gt;)
+ declare void @llvm.memcpy.p0i8.p0i8.i64(i8* &lt;dest&gt;, i8* &lt;src&gt;,
+ i64 &lt;len&gt;, i32 &lt;align&gt;, i1 &lt;isvolatile&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.memcpy.*</tt>' intrinsics copy a block of memory from the
+ source location to the destination location.</p>
+
+<p>Note that, unlike the standard libc function, the <tt>llvm.memcpy.*</tt>
+ intrinsics do not return a value, takes extra alignment/isvolatile arguments
+ and the pointers can be in specified address spaces.</p>
+
+<h5>Arguments:</h5>
+
+<p>The first argument is a pointer to the destination, the second is a pointer
+ to the source. The third argument is an integer argument specifying the
+ number of bytes to copy, the fourth argument is the alignment of the
+ source and destination locations, and the fifth is a boolean indicating a
+ volatile access.</p>
+
+<p>If the call to this intrinsic has an alignment value that is not 0 or 1,
+ then the caller guarantees that both the source and destination pointers are
+ aligned to that boundary.</p>
+
+<p>If the <tt>isvolatile</tt> parameter is <tt>true</tt>, the
+ <tt>llvm.memcpy</tt> call is a <a href="#volatile">volatile operation</a>.
+ The detailed access behavior is not very cleanly specified and it is unwise
+ to depend on it.</p>
+
+<h5>Semantics:</h5>
+
+<p>The '<tt>llvm.memcpy.*</tt>' intrinsics copy a block of memory from the
+ source location to the destination location, which are not allowed to
+ overlap. It copies "len" bytes of memory over. If the argument is known to
+ be aligned to some boundary, this can be specified as the fourth argument,
+ otherwise it should be set to 0 or 1.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_memmove">'<tt>llvm.memmove</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use llvm.memmove on any integer bit
+ width and for different address space. Not all targets support all bit
+ widths however.</p>
+
+<pre>
+ declare void @llvm.memmove.p0i8.p0i8.i32(i8* &lt;dest&gt;, i8* &lt;src&gt;,
+ i32 &lt;len&gt;, i32 &lt;align&gt;, i1 &lt;isvolatile&gt;)
+ declare void @llvm.memmove.p0i8.p0i8.i64(i8* &lt;dest&gt;, i8* &lt;src&gt;,
+ i64 &lt;len&gt;, i32 &lt;align&gt;, i1 &lt;isvolatile&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.memmove.*</tt>' intrinsics move a block of memory from the
+ source location to the destination location. It is similar to the
+ '<tt>llvm.memcpy</tt>' intrinsic but allows the two memory locations to
+ overlap.</p>
+
+<p>Note that, unlike the standard libc function, the <tt>llvm.memmove.*</tt>
+ intrinsics do not return a value, takes extra alignment/isvolatile arguments
+ and the pointers can be in specified address spaces.</p>
+
+<h5>Arguments:</h5>
+
+<p>The first argument is a pointer to the destination, the second is a pointer
+ to the source. The third argument is an integer argument specifying the
+ number of bytes to copy, the fourth argument is the alignment of the
+ source and destination locations, and the fifth is a boolean indicating a
+ volatile access.</p>
+
+<p>If the call to this intrinsic has an alignment value that is not 0 or 1,
+ then the caller guarantees that the source and destination pointers are
+ aligned to that boundary.</p>
+
+<p>If the <tt>isvolatile</tt> parameter is <tt>true</tt>, the
+ <tt>llvm.memmove</tt> call is a <a href="#volatile">volatile operation</a>.
+ The detailed access behavior is not very cleanly specified and it is unwise
+ to depend on it.</p>
+
+<h5>Semantics:</h5>
+
+<p>The '<tt>llvm.memmove.*</tt>' intrinsics copy a block of memory from the
+ source location to the destination location, which may overlap. It copies
+ "len" bytes of memory over. If the argument is known to be aligned to some
+ boundary, this can be specified as the fourth argument, otherwise it should
+ be set to 0 or 1.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_memset">'<tt>llvm.memset.*</tt>' Intrinsics</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use llvm.memset on any integer bit
+ width and for different address spaces. However, not all targets support all
+ bit widths.</p>
+
+<pre>
+ declare void @llvm.memset.p0i8.i32(i8* &lt;dest&gt;, i8 &lt;val&gt;,
+ i32 &lt;len&gt;, i32 &lt;align&gt;, i1 &lt;isvolatile&gt;)
+ declare void @llvm.memset.p0i8.i64(i8* &lt;dest&gt;, i8 &lt;val&gt;,
+ i64 &lt;len&gt;, i32 &lt;align&gt;, i1 &lt;isvolatile&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.memset.*</tt>' intrinsics fill a block of memory with a
+ particular byte value.</p>
+
+<p>Note that, unlike the standard libc function, the <tt>llvm.memset</tt>
+ intrinsic does not return a value and takes extra alignment/volatile
+ arguments. Also, the destination can be in an arbitrary address space.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is a pointer to the destination to fill, the second is the
+ byte value with which to fill it, the third argument is an integer argument
+ specifying the number of bytes to fill, and the fourth argument is the known
+ alignment of the destination location.</p>
+
+<p>If the call to this intrinsic has an alignment value that is not 0 or 1,
+ then the caller guarantees that the destination pointer is aligned to that
+ boundary.</p>
+
+<p>If the <tt>isvolatile</tt> parameter is <tt>true</tt>, the
+ <tt>llvm.memset</tt> call is a <a href="#volatile">volatile operation</a>.
+ The detailed access behavior is not very cleanly specified and it is unwise
+ to depend on it.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.memset.*</tt>' intrinsics fill "len" bytes of memory starting
+ at the destination location. If the argument is known to be aligned to some
+ boundary, this can be specified as the fourth argument, otherwise it should
+ be set to 0 or 1.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_sqrt">'<tt>llvm.sqrt.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.sqrt</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.sqrt.f32(float %Val)
+ declare double @llvm.sqrt.f64(double %Val)
+ declare x86_fp80 @llvm.sqrt.f80(x86_fp80 %Val)
+ declare fp128 @llvm.sqrt.f128(fp128 %Val)
+ declare ppc_fp128 @llvm.sqrt.ppcf128(ppc_fp128 %Val)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.sqrt</tt>' intrinsics return the sqrt of the specified operand,
+ returning the same value as the libm '<tt>sqrt</tt>' functions would.
+ Unlike <tt>sqrt</tt> in libm, however, <tt>llvm.sqrt</tt> has undefined
+ behavior for negative numbers other than -0.0 (which allows for better
+ optimization, because there is no need to worry about errno being
+ set). <tt>llvm.sqrt(-0.0)</tt> is defined to return -0.0 like IEEE sqrt.</p>
+
+<h5>Arguments:</h5>
+<p>The argument and return value are floating point numbers of the same
+ type.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the sqrt of the specified operand if it is a
+ nonnegative floating point number.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_powi">'<tt>llvm.powi.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.powi</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.powi.f32(float %Val, i32 %power)
+ declare double @llvm.powi.f64(double %Val, i32 %power)
+ declare x86_fp80 @llvm.powi.f80(x86_fp80 %Val, i32 %power)
+ declare fp128 @llvm.powi.f128(fp128 %Val, i32 %power)
+ declare ppc_fp128 @llvm.powi.ppcf128(ppc_fp128 %Val, i32 %power)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.powi.*</tt>' intrinsics return the first operand raised to the
+ specified (positive or negative) power. The order of evaluation of
+ multiplications is not defined. When a vector of floating point type is
+ used, the second argument remains a scalar integer value.</p>
+
+<h5>Arguments:</h5>
+<p>The second argument is an integer power, and the first is a value to raise to
+ that power.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the first value raised to the second power with an
+ unspecified sequence of rounding operations.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_sin">'<tt>llvm.sin.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.sin</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.sin.f32(float %Val)
+ declare double @llvm.sin.f64(double %Val)
+ declare x86_fp80 @llvm.sin.f80(x86_fp80 %Val)
+ declare fp128 @llvm.sin.f128(fp128 %Val)
+ declare ppc_fp128 @llvm.sin.ppcf128(ppc_fp128 %Val)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.sin.*</tt>' intrinsics return the sine of the operand.</p>
+
+<h5>Arguments:</h5>
+<p>The argument and return value are floating point numbers of the same
+ type.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the sine of the specified operand, returning the same
+ values as the libm <tt>sin</tt> functions would, and handles error conditions
+ in the same way.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_cos">'<tt>llvm.cos.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.cos</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.cos.f32(float %Val)
+ declare double @llvm.cos.f64(double %Val)
+ declare x86_fp80 @llvm.cos.f80(x86_fp80 %Val)
+ declare fp128 @llvm.cos.f128(fp128 %Val)
+ declare ppc_fp128 @llvm.cos.ppcf128(ppc_fp128 %Val)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.cos.*</tt>' intrinsics return the cosine of the operand.</p>
+
+<h5>Arguments:</h5>
+<p>The argument and return value are floating point numbers of the same
+ type.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the cosine of the specified operand, returning the same
+ values as the libm <tt>cos</tt> functions would, and handles error conditions
+ in the same way.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_pow">'<tt>llvm.pow.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.pow</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.pow.f32(float %Val, float %Power)
+ declare double @llvm.pow.f64(double %Val, double %Power)
+ declare x86_fp80 @llvm.pow.f80(x86_fp80 %Val, x86_fp80 %Power)
+ declare fp128 @llvm.pow.f128(fp128 %Val, fp128 %Power)
+ declare ppc_fp128 @llvm.pow.ppcf128(ppc_fp128 %Val, ppc_fp128 Power)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.pow.*</tt>' intrinsics return the first operand raised to the
+ specified (positive or negative) power.</p>
+
+<h5>Arguments:</h5>
+<p>The second argument is a floating point power, and the first is a value to
+ raise to that power.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the first value raised to the second power, returning
+ the same values as the libm <tt>pow</tt> functions would, and handles error
+ conditions in the same way.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_exp">'<tt>llvm.exp.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.exp</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.exp.f32(float %Val)
+ declare double @llvm.exp.f64(double %Val)
+ declare x86_fp80 @llvm.exp.f80(x86_fp80 %Val)
+ declare fp128 @llvm.exp.f128(fp128 %Val)
+ declare ppc_fp128 @llvm.exp.ppcf128(ppc_fp128 %Val)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.exp.*</tt>' intrinsics perform the exp function.</p>
+
+<h5>Arguments:</h5>
+<p>The argument and return value are floating point numbers of the same
+ type.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the same values as the libm <tt>exp</tt> functions
+ would, and handles error conditions in the same way.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_log">'<tt>llvm.log.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.log</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.log.f32(float %Val)
+ declare double @llvm.log.f64(double %Val)
+ declare x86_fp80 @llvm.log.f80(x86_fp80 %Val)
+ declare fp128 @llvm.log.f128(fp128 %Val)
+ declare ppc_fp128 @llvm.log.ppcf128(ppc_fp128 %Val)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.log.*</tt>' intrinsics perform the log function.</p>
+
+<h5>Arguments:</h5>
+<p>The argument and return value are floating point numbers of the same
+ type.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the same values as the libm <tt>log</tt> functions
+ would, and handles error conditions in the same way.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_fma">'<tt>llvm.fma.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.fma</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.fma.f32(float %a, float %b, float %c)
+ declare double @llvm.fma.f64(double %a, double %b, double %c)
+ declare x86_fp80 @llvm.fma.f80(x86_fp80 %a, x86_fp80 %b, x86_fp80 %c)
+ declare fp128 @llvm.fma.f128(fp128 %a, fp128 %b, fp128 %c)
+ declare ppc_fp128 @llvm.fma.ppcf128(ppc_fp128 %a, ppc_fp128 %b, ppc_fp128 %c)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.fma.*</tt>' intrinsics perform the fused multiply-add
+ operation.</p>
+
+<h5>Arguments:</h5>
+<p>The argument and return value are floating point numbers of the same
+ type.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the same values as the libm <tt>fma</tt> functions
+ would.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_fabs">'<tt>llvm.fabs.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.fabs</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.fabs.f32(float %Val)
+ declare double @llvm.fabs.f64(double %Val)
+ declare x86_fp80 @llvm.fabs.f80(x86_fp80 %Val)
+ declare fp128 @llvm.fabs.f128(fp128 %Val)
+ declare ppc_fp128 @llvm.fabs.ppcf128(ppc_fp128 %Val)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.fabs.*</tt>' intrinsics return the absolute value of
+ the operand.</p>
+
+<h5>Arguments:</h5>
+<p>The argument and return value are floating point numbers of the same
+ type.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the same values as the libm <tt>fabs</tt> functions
+ would, and handles error conditions in the same way.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_floor">'<tt>llvm.floor.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.floor</tt> on any
+ floating point or vector of floating point type. Not all targets support all
+ types however.</p>
+
+<pre>
+ declare float @llvm.floor.f32(float %Val)
+ declare double @llvm.floor.f64(double %Val)
+ declare x86_fp80 @llvm.floor.f80(x86_fp80 %Val)
+ declare fp128 @llvm.floor.f128(fp128 %Val)
+ declare ppc_fp128 @llvm.floor.ppcf128(ppc_fp128 %Val)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.floor.*</tt>' intrinsics return the floor of
+ the operand.</p>
+
+<h5>Arguments:</h5>
+<p>The argument and return value are floating point numbers of the same
+ type.</p>
+
+<h5>Semantics:</h5>
+<p>This function returns the same values as the libm <tt>floor</tt> functions
+ would, and handles error conditions in the same way.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_manip">Bit Manipulation Intrinsics</a>
+</h3>
+
+<div>
+
+<p>LLVM provides intrinsics for a few important bit manipulation operations.
+ These allow efficient code generation for some algorithms.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_bswap">'<tt>llvm.bswap.*</tt>' Intrinsics</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic function. You can use bswap on any integer
+ type that is an even number of bytes (i.e. BitWidth % 16 == 0).</p>
+
+<pre>
+ declare i16 @llvm.bswap.i16(i16 &lt;id&gt;)
+ declare i32 @llvm.bswap.i32(i32 &lt;id&gt;)
+ declare i64 @llvm.bswap.i64(i64 &lt;id&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.bswap</tt>' family of intrinsics is used to byte swap integer
+ values with an even number of bytes (positive multiple of 16 bits). These
+ are useful for performing operations on data that is not in the target's
+ native byte order.</p>
+
+<h5>Semantics:</h5>
+<p>The <tt>llvm.bswap.i16</tt> intrinsic returns an i16 value that has the high
+ and low byte of the input i16 swapped. Similarly,
+ the <tt>llvm.bswap.i32</tt> intrinsic returns an i32 value that has the four
+ bytes of the input i32 swapped, so that if the input bytes are numbered 0, 1,
+ 2, 3 then the returned i32 will have its bytes in 3, 2, 1, 0 order.
+ The <tt>llvm.bswap.i48</tt>, <tt>llvm.bswap.i64</tt> and other intrinsics
+ extend this concept to additional even-byte lengths (6 bytes, 8 bytes and
+ more, respectively).</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_ctpop">'<tt>llvm.ctpop.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use llvm.ctpop on any integer bit
+ width, or on any vector with integer elements. Not all targets support all
+ bit widths or vector types, however.</p>
+
+<pre>
+ declare i8 @llvm.ctpop.i8(i8 &lt;src&gt;)
+ declare i16 @llvm.ctpop.i16(i16 &lt;src&gt;)
+ declare i32 @llvm.ctpop.i32(i32 &lt;src&gt;)
+ declare i64 @llvm.ctpop.i64(i64 &lt;src&gt;)
+ declare i256 @llvm.ctpop.i256(i256 &lt;src&gt;)
+ declare &lt;2 x i32&gt; @llvm.ctpop.v2i32(&lt;2 x i32&gt; &lt;src&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.ctpop</tt>' family of intrinsics counts the number of bits set
+ in a value.</p>
+
+<h5>Arguments:</h5>
+<p>The only argument is the value to be counted. The argument may be of any
+ integer type, or a vector with integer elements.
+ The return type must match the argument type.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.ctpop</tt>' intrinsic counts the 1's in a variable, or within each
+ element of a vector.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_ctlz">'<tt>llvm.ctlz.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.ctlz</tt> on any
+ integer bit width, or any vector whose elements are integers. Not all
+ targets support all bit widths or vector types, however.</p>
+
+<pre>
+ declare i8 @llvm.ctlz.i8 (i8 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declare i16 @llvm.ctlz.i16 (i16 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declare i32 @llvm.ctlz.i32 (i32 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declare i64 @llvm.ctlz.i64 (i64 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declare i256 @llvm.ctlz.i256(i256 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declase &lt;2 x i32&gt; @llvm.ctlz.v2i32(&lt;2 x i32&gt; &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.ctlz</tt>' family of intrinsic functions counts the number of
+ leading zeros in a variable.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is the value to be counted. This argument may be of any
+ integer type, or a vectory with integer element type. The return type
+ must match the first argument type.</p>
+
+<p>The second argument must be a constant and is a flag to indicate whether the
+ intrinsic should ensure that a zero as the first argument produces a defined
+ result. Historically some architectures did not provide a defined result for
+ zero values as efficiently, and many algorithms are now predicated on
+ avoiding zero-value inputs.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.ctlz</tt>' intrinsic counts the leading (most significant)
+ zeros in a variable, or within each element of the vector.
+ If <tt>src == 0</tt> then the result is the size in bits of the type of
+ <tt>src</tt> if <tt>is_zero_undef == 0</tt> and <tt>undef</tt> otherwise.
+ For example, <tt>llvm.ctlz(i32 2) = 30</tt>.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_cttz">'<tt>llvm.cttz.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.cttz</tt> on any
+ integer bit width, or any vector of integer elements. Not all targets
+ support all bit widths or vector types, however.</p>
+
+<pre>
+ declare i8 @llvm.cttz.i8 (i8 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declare i16 @llvm.cttz.i16 (i16 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declare i32 @llvm.cttz.i32 (i32 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declare i64 @llvm.cttz.i64 (i64 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declare i256 @llvm.cttz.i256(i256 &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+ declase &lt;2 x i32&gt; @llvm.cttz.v2i32(&lt;2 x i32&gt; &lt;src&gt;, i1 &lt;is_zero_undef&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.cttz</tt>' family of intrinsic functions counts the number of
+ trailing zeros.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is the value to be counted. This argument may be of any
+ integer type, or a vectory with integer element type. The return type
+ must match the first argument type.</p>
+
+<p>The second argument must be a constant and is a flag to indicate whether the
+ intrinsic should ensure that a zero as the first argument produces a defined
+ result. Historically some architectures did not provide a defined result for
+ zero values as efficiently, and many algorithms are now predicated on
+ avoiding zero-value inputs.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.cttz</tt>' intrinsic counts the trailing (least significant)
+ zeros in a variable, or within each element of a vector.
+ If <tt>src == 0</tt> then the result is the size in bits of the type of
+ <tt>src</tt> if <tt>is_zero_undef == 0</tt> and <tt>undef</tt> otherwise.
+ For example, <tt>llvm.cttz(2) = 1</tt>.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_overflow">Arithmetic with Overflow Intrinsics</a>
+</h3>
+
+<div>
+
+<p>LLVM provides intrinsics for some arithmetic with overflow operations.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_sadd_overflow">
+ '<tt>llvm.sadd.with.overflow.*</tt>' Intrinsics
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.sadd.with.overflow</tt>
+ on any integer bit width.</p>
+
+<pre>
+ declare {i16, i1} @llvm.sadd.with.overflow.i16(i16 %a, i16 %b)
+ declare {i32, i1} @llvm.sadd.with.overflow.i32(i32 %a, i32 %b)
+ declare {i64, i1} @llvm.sadd.with.overflow.i64(i64 %a, i64 %b)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.sadd.with.overflow</tt>' family of intrinsic functions perform
+ a signed addition of the two arguments, and indicate whether an overflow
+ occurred during the signed summation.</p>
+
+<h5>Arguments:</h5>
+<p>The arguments (%a and %b) and the first element of the result structure may
+ be of integer types of any bit width, but they must have the same bit
+ width. The second element of the result structure must be of
+ type <tt>i1</tt>. <tt>%a</tt> and <tt>%b</tt> are the two values that will
+ undergo signed addition.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.sadd.with.overflow</tt>' family of intrinsic functions perform
+ a signed addition of the two variables. They return a structure &mdash; the
+ first element of which is the signed summation, and the second element of
+ which is a bit specifying if the signed summation resulted in an
+ overflow.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %res = call {i32, i1} @llvm.sadd.with.overflow.i32(i32 %a, i32 %b)
+ %sum = extractvalue {i32, i1} %res, 0
+ %obit = extractvalue {i32, i1} %res, 1
+ br i1 %obit, label %overflow, label %normal
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_uadd_overflow">
+ '<tt>llvm.uadd.with.overflow.*</tt>' Intrinsics
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.uadd.with.overflow</tt>
+ on any integer bit width.</p>
+
+<pre>
+ declare {i16, i1} @llvm.uadd.with.overflow.i16(i16 %a, i16 %b)
+ declare {i32, i1} @llvm.uadd.with.overflow.i32(i32 %a, i32 %b)
+ declare {i64, i1} @llvm.uadd.with.overflow.i64(i64 %a, i64 %b)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.uadd.with.overflow</tt>' family of intrinsic functions perform
+ an unsigned addition of the two arguments, and indicate whether a carry
+ occurred during the unsigned summation.</p>
+
+<h5>Arguments:</h5>
+<p>The arguments (%a and %b) and the first element of the result structure may
+ be of integer types of any bit width, but they must have the same bit
+ width. The second element of the result structure must be of
+ type <tt>i1</tt>. <tt>%a</tt> and <tt>%b</tt> are the two values that will
+ undergo unsigned addition.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.uadd.with.overflow</tt>' family of intrinsic functions perform
+ an unsigned addition of the two arguments. They return a structure &mdash;
+ the first element of which is the sum, and the second element of which is a
+ bit specifying if the unsigned summation resulted in a carry.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %res = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %a, i32 %b)
+ %sum = extractvalue {i32, i1} %res, 0
+ %obit = extractvalue {i32, i1} %res, 1
+ br i1 %obit, label %carry, label %normal
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_ssub_overflow">
+ '<tt>llvm.ssub.with.overflow.*</tt>' Intrinsics
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.ssub.with.overflow</tt>
+ on any integer bit width.</p>
+
+<pre>
+ declare {i16, i1} @llvm.ssub.with.overflow.i16(i16 %a, i16 %b)
+ declare {i32, i1} @llvm.ssub.with.overflow.i32(i32 %a, i32 %b)
+ declare {i64, i1} @llvm.ssub.with.overflow.i64(i64 %a, i64 %b)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.ssub.with.overflow</tt>' family of intrinsic functions perform
+ a signed subtraction of the two arguments, and indicate whether an overflow
+ occurred during the signed subtraction.</p>
+
+<h5>Arguments:</h5>
+<p>The arguments (%a and %b) and the first element of the result structure may
+ be of integer types of any bit width, but they must have the same bit
+ width. The second element of the result structure must be of
+ type <tt>i1</tt>. <tt>%a</tt> and <tt>%b</tt> are the two values that will
+ undergo signed subtraction.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.ssub.with.overflow</tt>' family of intrinsic functions perform
+ a signed subtraction of the two arguments. They return a structure &mdash;
+ the first element of which is the subtraction, and the second element of
+ which is a bit specifying if the signed subtraction resulted in an
+ overflow.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %res = call {i32, i1} @llvm.ssub.with.overflow.i32(i32 %a, i32 %b)
+ %sum = extractvalue {i32, i1} %res, 0
+ %obit = extractvalue {i32, i1} %res, 1
+ br i1 %obit, label %overflow, label %normal
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_usub_overflow">
+ '<tt>llvm.usub.with.overflow.*</tt>' Intrinsics
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.usub.with.overflow</tt>
+ on any integer bit width.</p>
+
+<pre>
+ declare {i16, i1} @llvm.usub.with.overflow.i16(i16 %a, i16 %b)
+ declare {i32, i1} @llvm.usub.with.overflow.i32(i32 %a, i32 %b)
+ declare {i64, i1} @llvm.usub.with.overflow.i64(i64 %a, i64 %b)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.usub.with.overflow</tt>' family of intrinsic functions perform
+ an unsigned subtraction of the two arguments, and indicate whether an
+ overflow occurred during the unsigned subtraction.</p>
+
+<h5>Arguments:</h5>
+<p>The arguments (%a and %b) and the first element of the result structure may
+ be of integer types of any bit width, but they must have the same bit
+ width. The second element of the result structure must be of
+ type <tt>i1</tt>. <tt>%a</tt> and <tt>%b</tt> are the two values that will
+ undergo unsigned subtraction.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.usub.with.overflow</tt>' family of intrinsic functions perform
+ an unsigned subtraction of the two arguments. They return a structure &mdash;
+ the first element of which is the subtraction, and the second element of
+ which is a bit specifying if the unsigned subtraction resulted in an
+ overflow.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %res = call {i32, i1} @llvm.usub.with.overflow.i32(i32 %a, i32 %b)
+ %sum = extractvalue {i32, i1} %res, 0
+ %obit = extractvalue {i32, i1} %res, 1
+ br i1 %obit, label %overflow, label %normal
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_smul_overflow">
+ '<tt>llvm.smul.with.overflow.*</tt>' Intrinsics
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.smul.with.overflow</tt>
+ on any integer bit width.</p>
+
+<pre>
+ declare {i16, i1} @llvm.smul.with.overflow.i16(i16 %a, i16 %b)
+ declare {i32, i1} @llvm.smul.with.overflow.i32(i32 %a, i32 %b)
+ declare {i64, i1} @llvm.smul.with.overflow.i64(i64 %a, i64 %b)
+</pre>
+
+<h5>Overview:</h5>
+
+<p>The '<tt>llvm.smul.with.overflow</tt>' family of intrinsic functions perform
+ a signed multiplication of the two arguments, and indicate whether an
+ overflow occurred during the signed multiplication.</p>
+
+<h5>Arguments:</h5>
+<p>The arguments (%a and %b) and the first element of the result structure may
+ be of integer types of any bit width, but they must have the same bit
+ width. The second element of the result structure must be of
+ type <tt>i1</tt>. <tt>%a</tt> and <tt>%b</tt> are the two values that will
+ undergo signed multiplication.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.smul.with.overflow</tt>' family of intrinsic functions perform
+ a signed multiplication of the two arguments. They return a structure &mdash;
+ the first element of which is the multiplication, and the second element of
+ which is a bit specifying if the signed multiplication resulted in an
+ overflow.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %res = call {i32, i1} @llvm.smul.with.overflow.i32(i32 %a, i32 %b)
+ %sum = extractvalue {i32, i1} %res, 0
+ %obit = extractvalue {i32, i1} %res, 1
+ br i1 %obit, label %overflow, label %normal
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_umul_overflow">
+ '<tt>llvm.umul.with.overflow.*</tt>' Intrinsics
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use <tt>llvm.umul.with.overflow</tt>
+ on any integer bit width.</p>
+
+<pre>
+ declare {i16, i1} @llvm.umul.with.overflow.i16(i16 %a, i16 %b)
+ declare {i32, i1} @llvm.umul.with.overflow.i32(i32 %a, i32 %b)
+ declare {i64, i1} @llvm.umul.with.overflow.i64(i64 %a, i64 %b)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.umul.with.overflow</tt>' family of intrinsic functions perform
+ a unsigned multiplication of the two arguments, and indicate whether an
+ overflow occurred during the unsigned multiplication.</p>
+
+<h5>Arguments:</h5>
+<p>The arguments (%a and %b) and the first element of the result structure may
+ be of integer types of any bit width, but they must have the same bit
+ width. The second element of the result structure must be of
+ type <tt>i1</tt>. <tt>%a</tt> and <tt>%b</tt> are the two values that will
+ undergo unsigned multiplication.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.umul.with.overflow</tt>' family of intrinsic functions perform
+ an unsigned multiplication of the two arguments. They return a structure
+ &mdash; the first element of which is the multiplication, and the second
+ element of which is a bit specifying if the unsigned multiplication resulted
+ in an overflow.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %res = call {i32, i1} @llvm.umul.with.overflow.i32(i32 %a, i32 %b)
+ %sum = extractvalue {i32, i1} %res, 0
+ %obit = extractvalue {i32, i1} %res, 1
+ br i1 %obit, label %overflow, label %normal
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="spec_arithmetic">Specialised Arithmetic Intrinsics</a>
+</h3>
+
+<!-- _______________________________________________________________________ -->
+
+<h4>
+ <a name="fmuladd">'<tt>llvm.fmuladd.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare float @llvm.fmuladd.f32(float %a, float %b, float %c)
+ declare double @llvm.fmuladd.f64(double %a, double %b, double %c)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.fmuladd.*</tt>' intrinsic functions represent multiply-add
+expressions that can be fused if the code generator determines that the fused
+expression would be legal and efficient.</p>
+
+<h5>Arguments:</h5>
+<p>The '<tt>llvm.fmuladd.*</tt>' intrinsics each take three arguments: two
+multiplicands, a and b, and an addend c.</p>
+
+<h5>Semantics:</h5>
+<p>The expression:</p>
+<pre>
+ %0 = call float @llvm.fmuladd.f32(%a, %b, %c)
+</pre>
+<p>is equivalent to the expression a * b + c, except that rounding will not be
+performed between the multiplication and addition steps if the code generator
+fuses the operations. Fusion is not guaranteed, even if the target platform
+supports it. If a fused multiply-add is required the corresponding llvm.fma.*
+intrinsic function should be used instead.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %r2 = call float @llvm.fmuladd.f32(float %a, float %b, float %c) ; yields {float}:r2 = (a * b) + c
+</pre>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_fp16">Half Precision Floating Point Intrinsics</a>
+</h3>
+
+<div>
+
+<p>For most target platforms, half precision floating point is a storage-only
+ format. This means that it is
+ a dense encoding (in memory) but does not support computation in the
+ format.</p>
+
+<p>This means that code must first load the half-precision floating point
+ value as an i16, then convert it to float with <a
+ href="#int_convert_from_fp16"><tt>llvm.convert.from.fp16</tt></a>.
+ Computation can then be performed on the float value (including extending to
+ double etc). To store the value back to memory, it is first converted to
+ float if needed, then converted to i16 with
+ <a href="#int_convert_to_fp16"><tt>llvm.convert.to.fp16</tt></a>, then
+ storing as an i16 value.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_convert_to_fp16">
+ '<tt>llvm.convert.to.fp16</tt>' Intrinsic
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i16 @llvm.convert.to.fp16(f32 %a)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.convert.to.fp16</tt>' intrinsic function performs
+ a conversion from single precision floating point format to half precision
+ floating point format.</p>
+
+<h5>Arguments:</h5>
+<p>The intrinsic function contains single argument - the value to be
+ converted.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.convert.to.fp16</tt>' intrinsic function performs
+ a conversion from single precision floating point format to half precision
+ floating point format. The return value is an <tt>i16</tt> which
+ contains the converted number.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %res = call i16 @llvm.convert.to.fp16(f32 %a)
+ store i16 %res, i16* @x, align 2
+</pre>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_convert_from_fp16">
+ '<tt>llvm.convert.from.fp16</tt>' Intrinsic
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare f32 @llvm.convert.from.fp16(i16 %a)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.convert.from.fp16</tt>' intrinsic function performs
+ a conversion from half precision floating point format to single precision
+ floating point format.</p>
+
+<h5>Arguments:</h5>
+<p>The intrinsic function contains single argument - the value to be
+ converted.</p>
+
+<h5>Semantics:</h5>
+<p>The '<tt>llvm.convert.from.fp16</tt>' intrinsic function performs a
+ conversion from half single precision floating point format to single
+ precision floating point format. The input half-float value is represented by
+ an <tt>i16</tt> value.</p>
+
+<h5>Examples:</h5>
+<pre>
+ %a = load i16* @x, align 2
+ %res = call f32 @llvm.convert.from.fp16(i16 %a)
+</pre>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_debugger">Debugger Intrinsics</a>
+</h3>
+
+<div>
+
+<p>The LLVM debugger intrinsics (which all start with <tt>llvm.dbg.</tt>
+ prefix), are described in
+ the <a href="SourceLevelDebugging.html#format_common_intrinsics">LLVM Source
+ Level Debugging</a> document.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_eh">Exception Handling Intrinsics</a>
+</h3>
+
+<div>
+
+<p>The LLVM exception handling intrinsics (which all start with
+ <tt>llvm.eh.</tt> prefix), are described in
+ the <a href="ExceptionHandling.html#format_common_intrinsics">LLVM Exception
+ Handling</a> document.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_trampoline">Trampoline Intrinsics</a>
+</h3>
+
+<div>
+
+<p>These intrinsics make it possible to excise one parameter, marked with
+ the <a href="#nest"><tt>nest</tt></a> attribute, from a function.
+ The result is a callable
+ function pointer lacking the nest parameter - the caller does not need to
+ provide a value for it. Instead, the value to use is stored in advance in a
+ "trampoline", a block of memory usually allocated on the stack, which also
+ contains code to splice the nest value into the argument list. This is used
+ to implement the GCC nested function address extension.</p>
+
+<p>For example, if the function is
+ <tt>i32 f(i8* nest %c, i32 %x, i32 %y)</tt> then the resulting function
+ pointer has signature <tt>i32 (i32, i32)*</tt>. It can be created as
+ follows:</p>
+
+<pre class="doc_code">
+ %tramp = alloca [10 x i8], align 4 ; size and alignment only correct for X86
+ %tramp1 = getelementptr [10 x i8]* %tramp, i32 0, i32 0
+ call i8* @llvm.init.trampoline(i8* %tramp1, i8* bitcast (i32 (i8*, i32, i32)* @f to i8*), i8* %nval)
+ %p = call i8* @llvm.adjust.trampoline(i8* %tramp1)
+ %fp = bitcast i8* %p to i32 (i32, i32)*
+</pre>
+
+<p>The call <tt>%val = call i32 %fp(i32 %x, i32 %y)</tt> is then equivalent
+ to <tt>%val = call i32 %f(i8* %nval, i32 %x, i32 %y)</tt>.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_it">
+ '<tt>llvm.init.trampoline</tt>' Intrinsic
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.init.trampoline(i8* &lt;tramp&gt;, i8* &lt;func&gt;, i8* &lt;nval&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>This fills the memory pointed to by <tt>tramp</tt> with executable code,
+ turning it into a trampoline.</p>
+
+<h5>Arguments:</h5>
+<p>The <tt>llvm.init.trampoline</tt> intrinsic takes three arguments, all
+ pointers. The <tt>tramp</tt> argument must point to a sufficiently large and
+ sufficiently aligned block of memory; this memory is written to by the
+ intrinsic. Note that the size and the alignment are target-specific - LLVM
+ currently provides no portable way of determining them, so a front-end that
+ generates this intrinsic needs to have some target-specific knowledge.
+ The <tt>func</tt> argument must hold a function bitcast to
+ an <tt>i8*</tt>.</p>
+
+<h5>Semantics:</h5>
+<p>The block of memory pointed to by <tt>tramp</tt> is filled with target
+ dependent code, turning it into a function. Then <tt>tramp</tt> needs to be
+ passed to <a href="#int_at">llvm.adjust.trampoline</a> to get a pointer
+ which can be <a href="#int_trampoline">bitcast (to a new function) and
+ called</a>. The new function's signature is the same as that of
+ <tt>func</tt> with any arguments marked with the <tt>nest</tt> attribute
+ removed. At most one such <tt>nest</tt> argument is allowed, and it must be of
+ pointer type. Calling the new function is equivalent to calling <tt>func</tt>
+ with the same argument list, but with <tt>nval</tt> used for the missing
+ <tt>nest</tt> argument. If, after calling <tt>llvm.init.trampoline</tt>, the
+ memory pointed to by <tt>tramp</tt> is modified, then the effect of any later call
+ to the returned function pointer is undefined.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_at">
+ '<tt>llvm.adjust.trampoline</tt>' Intrinsic
+ </a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i8* @llvm.adjust.trampoline(i8* &lt;tramp&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>This performs any required machine-specific adjustment to the address of a
+ trampoline (passed as <tt>tramp</tt>).</p>
+
+<h5>Arguments:</h5>
+<p><tt>tramp</tt> must point to a block of memory which already has trampoline code
+ filled in by a previous call to <a href="#int_it"><tt>llvm.init.trampoline</tt>
+ </a>.</p>
+
+<h5>Semantics:</h5>
+<p>On some architectures the address of the code to be executed needs to be
+ different to the address where the trampoline is actually stored. This
+ intrinsic returns the executable address corresponding to <tt>tramp</tt>
+ after performing the required machine specific adjustments.
+ The pointer returned can then be <a href="#int_trampoline"> bitcast and
+ executed</a>.
+</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_memorymarkers">Memory Use Markers</a>
+</h3>
+
+<div>
+
+<p>This class of intrinsics exists to information about the lifetime of memory
+ objects and ranges where variables are immutable.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_lifetime_start">'<tt>llvm.lifetime.start</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.lifetime.start(i64 &lt;size&gt;, i8* nocapture &lt;ptr&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.lifetime.start</tt>' intrinsic specifies the start of a memory
+ object's lifetime.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is a constant integer representing the size of the
+ object, or -1 if it is variable sized. The second argument is a pointer to
+ the object.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic indicates that before this point in the code, the value of the
+ memory pointed to by <tt>ptr</tt> is dead. This means that it is known to
+ never be used and has an undefined value. A load from the pointer that
+ precedes this intrinsic can be replaced with
+ <tt>'<a href="#undefvalues">undef</a>'</tt>.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_lifetime_end">'<tt>llvm.lifetime.end</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.lifetime.end(i64 &lt;size&gt;, i8* nocapture &lt;ptr&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.lifetime.end</tt>' intrinsic specifies the end of a memory
+ object's lifetime.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is a constant integer representing the size of the
+ object, or -1 if it is variable sized. The second argument is a pointer to
+ the object.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic indicates that after this point in the code, the value of the
+ memory pointed to by <tt>ptr</tt> is dead. This means that it is known to
+ never be used and has an undefined value. Any stores into the memory object
+ following this intrinsic may be removed as dead.
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_invariant_start">'<tt>llvm.invariant.start</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare {}* @llvm.invariant.start(i64 &lt;size&gt;, i8* nocapture &lt;ptr&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.invariant.start</tt>' intrinsic specifies that the contents of
+ a memory object will not change.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is a constant integer representing the size of the
+ object, or -1 if it is variable sized. The second argument is a pointer to
+ the object.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic indicates that until an <tt>llvm.invariant.end</tt> that uses
+ the return value, the referenced memory location is constant and
+ unchanging.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_invariant_end">'<tt>llvm.invariant.end</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.invariant.end({}* &lt;start&gt;, i64 &lt;size&gt;, i8* nocapture &lt;ptr&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.invariant.end</tt>' intrinsic specifies that the contents of
+ a memory object are mutable.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is the matching <tt>llvm.invariant.start</tt> intrinsic.
+ The second argument is a constant integer representing the size of the
+ object, or -1 if it is variable sized and the third argument is a pointer
+ to the object.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic indicates that the memory is mutable again.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="int_general">General Intrinsics</a>
+</h3>
+
+<div>
+
+<p>This class of intrinsics is designed to be generic and has no specific
+ purpose.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_var_annotation">'<tt>llvm.var.annotation</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.var.annotation(i8* &lt;val&gt;, i8* &lt;str&gt;, i8* &lt;str&gt;, i32 &lt;int&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.var.annotation</tt>' intrinsic.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is a pointer to a value, the second is a pointer to a
+ global string, the third is a pointer to a global string which is the source
+ file name, and the last argument is the line number.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic allows annotation of local variables with arbitrary strings.
+ This can be useful for special purpose optimizations that want to look for
+ these annotations. These have no other defined use; they are ignored by code
+ generation and optimization.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_annotation">'<tt>llvm.annotation.*</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<p>This is an overloaded intrinsic. You can use '<tt>llvm.annotation</tt>' on
+ any integer bit width.</p>
+
+<pre>
+ declare i8 @llvm.annotation.i8(i8 &lt;val&gt;, i8* &lt;str&gt;, i8* &lt;str&gt;, i32 &lt;int&gt;)
+ declare i16 @llvm.annotation.i16(i16 &lt;val&gt;, i8* &lt;str&gt;, i8* &lt;str&gt;, i32 &lt;int&gt;)
+ declare i32 @llvm.annotation.i32(i32 &lt;val&gt;, i8* &lt;str&gt;, i8* &lt;str&gt;, i32 &lt;int&gt;)
+ declare i64 @llvm.annotation.i64(i64 &lt;val&gt;, i8* &lt;str&gt;, i8* &lt;str&gt;, i32 &lt;int&gt;)
+ declare i256 @llvm.annotation.i256(i256 &lt;val&gt;, i8* &lt;str&gt;, i8* &lt;str&gt;, i32 &lt;int&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.annotation</tt>' intrinsic.</p>
+
+<h5>Arguments:</h5>
+<p>The first argument is an integer value (result of some expression), the
+ second is a pointer to a global string, the third is a pointer to a global
+ string which is the source file name, and the last argument is the line
+ number. It returns the value of the first argument.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic allows annotations to be put on arbitrary expressions with
+ arbitrary strings. This can be useful for special purpose optimizations that
+ want to look for these annotations. These have no other defined use; they
+ are ignored by code generation and optimization.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_trap">'<tt>llvm.trap</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.trap() noreturn nounwind
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.trap</tt>' intrinsic.</p>
+
+<h5>Arguments:</h5>
+<p>None.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic is lowered to the target dependent trap instruction. If the
+ target does not have a trap instruction, this intrinsic will be lowered to
+ a call of the <tt>abort()</tt> function.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_debugtrap">'<tt>llvm.debugtrap</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.debugtrap() nounwind
+</pre>
+
+<h5>Overview:</h5>
+<p>The '<tt>llvm.debugtrap</tt>' intrinsic.</p>
+
+<h5>Arguments:</h5>
+<p>None.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic is lowered to code which is intended to cause an execution
+ trap with the intention of requesting the attention of a debugger.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_stackprotector">'<tt>llvm.stackprotector</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.stackprotector(i8* &lt;guard&gt;, i8** &lt;slot&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The <tt>llvm.stackprotector</tt> intrinsic takes the <tt>guard</tt> and
+ stores it onto the stack at <tt>slot</tt>. The stack slot is adjusted to
+ ensure that it is placed on the stack before local variables.</p>
+
+<h5>Arguments:</h5>
+<p>The <tt>llvm.stackprotector</tt> intrinsic requires two pointer
+ arguments. The first argument is the value loaded from the stack
+ guard <tt>@__stack_chk_guard</tt>. The second variable is an <tt>alloca</tt>
+ that has enough space to hold the value of the guard.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic causes the prologue/epilogue inserter to force the position of
+ the <tt>AllocaInst</tt> stack slot to be before local variables on the
+ stack. This is to ensure that if a local variable on the stack is
+ overwritten, it will destroy the value of the guard. When the function exits,
+ the guard on the stack is checked against the original guard. If they are
+ different, then the program aborts by calling the <tt>__stack_chk_fail()</tt>
+ function.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_objectsize">'<tt>llvm.objectsize</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i32 @llvm.objectsize.i32(i8* &lt;object&gt;, i1 &lt;min&gt;)
+ declare i64 @llvm.objectsize.i64(i8* &lt;object&gt;, i1 &lt;min&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The <tt>llvm.objectsize</tt> intrinsic is designed to provide information to
+ the optimizers to determine at compile time whether a) an operation (like
+ memcpy) will overflow a buffer that corresponds to an object, or b) that a
+ runtime check for overflow isn't necessary. An object in this context means
+ an allocation of a specific class, structure, array, or other object.</p>
+
+<h5>Arguments:</h5>
+<p>The <tt>llvm.objectsize</tt> intrinsic takes two arguments. The first
+ argument is a pointer to or into the <tt>object</tt>. The second argument
+ is a boolean and determines whether <tt>llvm.objectsize</tt> returns 0 (if
+ true) or -1 (if false) when the object size is unknown.
+ The second argument only accepts constants.</p>
+
+<h5>Semantics:</h5>
+<p>The <tt>llvm.objectsize</tt> intrinsic is lowered to a constant representing
+ the size of the object concerned. If the size cannot be determined at compile
+ time, <tt>llvm.objectsize</tt> returns <tt>i32/i64 -1 or 0</tt>
+ (depending on the <tt>min</tt> argument).</p>
+
+</div>
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_expect">'<tt>llvm.expect</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare i32 @llvm.expect.i32(i32 &lt;val&gt;, i32 &lt;expected_val&gt;)
+ declare i64 @llvm.expect.i64(i64 &lt;val&gt;, i64 &lt;expected_val&gt;)
+</pre>
+
+<h5>Overview:</h5>
+<p>The <tt>llvm.expect</tt> intrinsic provides information about expected (the
+ most probable) value of <tt>val</tt>, which can be used by optimizers.</p>
+
+<h5>Arguments:</h5>
+<p>The <tt>llvm.expect</tt> intrinsic takes two arguments. The first
+ argument is a value. The second argument is an expected value, this needs to
+ be a constant value, variables are not allowed.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic is lowered to the <tt>val</tt>.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="int_donothing">'<tt>llvm.donothing</tt>' Intrinsic</a>
+</h4>
+
+<div>
+
+<h5>Syntax:</h5>
+<pre>
+ declare void @llvm.donothing() nounwind readnone
+</pre>
+
+<h5>Overview:</h5>
+<p>The <tt>llvm.donothing</tt> intrinsic doesn't perform any operation. It's the
+only intrinsic that can be called with an invoke instruction.</p>
+
+<h5>Arguments:</h5>
+<p>None.</p>
+
+<h5>Semantics:</h5>
+<p>This intrinsic does nothing, and it's removed by optimizers and ignored by
+codegen.</p>
+</div>
+
+</div>
+
+</div>
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/Lexicon.rst b/docs/Lexicon.rst
new file mode 100644
index 00000000000..6ebe61429f9
--- /dev/null
+++ b/docs/Lexicon.rst
@@ -0,0 +1,194 @@
+.. _lexicon:
+
+================
+The LLVM Lexicon
+================
+
+.. note::
+
+ This document is a work in progress!
+
+Definitions
+===========
+
+A
+-
+
+**ADCE**
+ Aggressive Dead Code Elimination
+
+B
+-
+
+**BURS**
+
+ Bottom Up Rewriting System --- A method of instruction selection for code
+ generation. An example is the `BURG
+ <http://www.program-transformation.org/Transform/BURG>`_ tool.
+
+C
+-
+
+**CSE**
+ Common Subexpression Elimination. An optimization that removes common
+ subexpression compuation. For example ``(a+b)*(a+b)`` has two subexpressions
+ that are the same: ``(a+b)``. This optimization would perform the addition
+ only once and then perform the multiply (but only if it's compulationally
+ correct/safe).
+
+D
+-
+
+**DAG**
+ Directed Acyclic Graph
+
+.. _derived pointer:
+.. _derived pointers:
+
+**Derived Pointer**
+ A pointer to the interior of an object, such that a garbage collector is
+ unable to use the pointer for reachability analysis. While a derived pointer
+ is live, the corresponding object pointer must be kept in a root, otherwise
+ the collector might free the referenced object. With copying collectors,
+ derived pointers pose an additional hazard that they may be invalidated at
+ any `safe point`_. This term is used in opposition to `object pointer`_.
+
+**DSA**
+ Data Structure Analysis
+
+**DSE**
+ Dead Store Elimination
+
+F
+-
+
+**FCA**
+ First Class Aggregate
+
+G
+-
+
+**GC**
+ Garbage Collection. The practice of using reachability analysis instead of
+ explicit memory management to reclaim unused memory.
+
+H
+-
+
+.. _heap:
+
+**Heap**
+ In garbage collection, the region of memory which is managed using
+ reachability analysis.
+
+I
+-
+
+**IPA**
+ Inter-Procedural Analysis. Refers to any variety of code analysis that
+ occurs between procedures, functions or compilation units (modules).
+
+**IPO**
+ Inter-Procedural Optimization. Refers to any variety of code optimization
+ that occurs between procedures, functions or compilation units (modules).
+
+**ISel**
+ Instruction Selection
+
+L
+-
+
+**LCSSA**
+ Loop-Closed Static Single Assignment Form
+
+**LICM**
+ Loop Invariant Code Motion
+
+**Load-VN**
+ Load Value Numbering
+
+**LTO**
+ Link-Time Optimization
+
+M
+-
+
+**MC**
+ Machine Code
+
+O
+-
+.. _object pointer:
+.. _object pointers:
+
+**Object Pointer**
+ A pointer to an object such that the garbage collector is able to trace
+ references contained within the object. This term is used in opposition to
+ `derived pointer`_.
+
+P
+-
+
+**PRE**
+ Partial Redundancy Elimination
+
+R
+-
+
+**RAUW**
+
+ Replace All Uses With. The functions ``User::replaceUsesOfWith()``,
+ ``Value::replaceAllUsesWith()``, and
+ ``Constant::replaceUsesOfWithOnConstant()`` implement the replacement of one
+ Value with another by iterating over its def/use chain and fixing up all of
+ the pointers to point to the new value. See
+ also `def/use chains <ProgrammersManual.html#iterate_chains>`_.
+
+**Reassociation**
+ Rearranging associative expressions to promote better redundancy elimination
+ and other optimization. For example, changing ``(A+B-A)`` into ``(B+A-A)``,
+ permitting it to be optimized into ``(B+0)`` then ``(B)``.
+
+.. _roots:
+.. _stack roots:
+
+**Root**
+ In garbage collection, a pointer variable lying outside of the `heap`_ from
+ which the collector begins its reachability analysis. In the context of code
+ generation, "root" almost always refers to a "stack root" --- a local or
+ temporary variable within an executing function.</dd>
+
+**RPO**
+ Reverse postorder
+
+S
+-
+
+.. _safe point:
+
+**Safe Point**
+ In garbage collection, it is necessary to identify `stack roots`_ so that
+ reachability analysis may proceed. It may be infeasible to provide this
+ information for every instruction, so instead the information may is
+ calculated only at designated safe points. With a copying collector,
+ `derived pointers`_ must not be retained across safe points and `object
+ pointers`_ must be reloaded from stack roots.
+
+**SDISel**
+ Selection DAG Instruction Selection.
+
+**SCC**
+ Strongly Connected Component
+
+**SCCP**
+ Sparse Conditional Constant Propagation
+
+**SRoA**
+ Scalar Replacement of Aggregates
+
+**SSA**
+ Static Single Assignment
+
+**Stack Map**
+ In garbage collection, metadata emitted by the code generator which
+ identifies `roots`_ within the stack frame of an executing function.
diff --git a/docs/LinkTimeOptimization.rst b/docs/LinkTimeOptimization.rst
new file mode 100644
index 00000000000..53d673e4066
--- /dev/null
+++ b/docs/LinkTimeOptimization.rst
@@ -0,0 +1,298 @@
+.. _lto:
+
+======================================================
+LLVM Link Time Optimization: Design and Implementation
+======================================================
+
+.. contents::
+ :local:
+
+Description
+===========
+
+LLVM features powerful intermodular optimizations which can be used at link
+time. Link Time Optimization (LTO) is another name for intermodular
+optimization when performed during the link stage. This document describes the
+interface and design between the LTO optimizer and the linker.
+
+Design Philosophy
+=================
+
+The LLVM Link Time Optimizer provides complete transparency, while doing
+intermodular optimization, in the compiler tool chain. Its main goal is to let
+the developer take advantage of intermodular optimizations without making any
+significant changes to the developer's makefiles or build system. This is
+achieved through tight integration with the linker. In this model, the linker
+treates LLVM bitcode files like native object files and allows mixing and
+matching among them. The linker uses `libLTO`_, a shared object, to handle LLVM
+bitcode files. This tight integration between the linker and LLVM optimizer
+helps to do optimizations that are not possible in other models. The linker
+input allows the optimizer to avoid relying on conservative escape analysis.
+
+Example of link time optimization
+---------------------------------
+
+The following example illustrates the advantages of LTO's integrated approach
+and clean interface. This example requires a system linker which supports LTO
+through the interface described in this document. Here, clang transparently
+invokes system linker.
+
+* Input source file ``a.c`` is compiled into LLVM bitcode form.
+* Input source file ``main.c`` is compiled into native object code.
+
+.. code-block:: c++
+
+ --- a.h ---
+ extern int foo1(void);
+ extern void foo2(void);
+ extern void foo4(void);
+
+ --- a.c ---
+ #include "a.h"
+
+ static signed int i = 0;
+
+ void foo2(void) {
+ i = -1;
+ }
+
+ static int foo3() {
+ foo4();
+ return 10;
+ }
+
+ int foo1(void) {
+ int data = 0;
+
+ if (i < 0)
+ data = foo3();
+
+ data = data + 42;
+ return data;
+ }
+
+ --- main.c ---
+ #include <stdio.h>
+ #include "a.h"
+
+ void foo4(void) {
+ printf("Hi\n");
+ }
+
+ int main() {
+ return foo1();
+ }
+
+.. code-block:: bash
+
+ --- command lines ---
+ % clang -emit-llvm -c a.c -o a.o # <-- a.o is LLVM bitcode file
+ % clang -c main.c -o main.o # <-- main.o is native object file
+ % clang a.o main.o -o main # <-- standard link command without modifications
+
+* In this example, the linker recognizes that ``foo2()`` is an externally
+ visible symbol defined in LLVM bitcode file. The linker completes its usual
+ symbol resolution pass and finds that ``foo2()`` is not used
+ anywhere. This information is used by the LLVM optimizer and it
+ removes ``foo2()``.</li>
+
+* As soon as ``foo2()`` is removed, the optimizer recognizes that condition ``i
+ < 0`` is always false, which means ``foo3()`` is never used. Hence, the
+ optimizer also removes ``foo3()``.
+
+* And this in turn, enables linker to remove ``foo4()``.
+
+This example illustrates the advantage of tight integration with the
+linker. Here, the optimizer can not remove ``foo3()`` without the linker's
+input.
+
+Alternative Approaches
+----------------------
+
+**Compiler driver invokes link time optimizer separately.**
+ In this model the link time optimizer is not able to take advantage of
+ information collected during the linker's normal symbol resolution phase.
+ In the above example, the optimizer can not remove ``foo2()`` without the
+ linker's input because it is externally visible. This in turn prohibits the
+ optimizer from removing ``foo3()``.
+
+**Use separate tool to collect symbol information from all object files.**
+ In this model, a new, separate, tool or library replicates the linker's
+ capability to collect information for link time optimization. Not only is
+ this code duplication difficult to justify, but it also has several other
+ disadvantages. For example, the linking semantics and the features provided
+ by the linker on various platform are not unique. This means, this new tool
+ needs to support all such features and platforms in one super tool or a
+ separate tool per platform is required. This increases maintenance cost for
+ link time optimizer significantly, which is not necessary. This approach
+ also requires staying synchronized with linker developements on various
+ platforms, which is not the main focus of the link time optimizer. Finally,
+ this approach increases end user's build time due to the duplication of work
+ done by this separate tool and the linker itself.
+
+Multi-phase communication between ``libLTO`` and linker
+=======================================================
+
+The linker collects information about symbol defininitions and uses in various
+link objects which is more accurate than any information collected by other
+tools during typical build cycles. The linker collects this information by
+looking at the definitions and uses of symbols in native .o files and using
+symbol visibility information. The linker also uses user-supplied information,
+such as a list of exported symbols. LLVM optimizer collects control flow
+information, data flow information and knows much more about program structure
+from the optimizer's point of view. Our goal is to take advantage of tight
+integration between the linker and the optimizer by sharing this information
+during various linking phases.
+
+Phase 1 : Read LLVM Bitcode Files
+---------------------------------
+
+The linker first reads all object files in natural order and collects symbol
+information. This includes native object files as well as LLVM bitcode files.
+To minimize the cost to the linker in the case that all .o files are native
+object files, the linker only calls ``lto_module_create()`` when a supplied
+object file is found to not be a native object file. If ``lto_module_create()``
+returns that the file is an LLVM bitcode file, the linker then iterates over the
+module using ``lto_module_get_symbol_name()`` and
+``lto_module_get_symbol_attribute()`` to get all symbols defined and referenced.
+This information is added to the linker's global symbol table.
+
+
+The lto* functions are all implemented in a shared object libLTO. This allows
+the LLVM LTO code to be updated independently of the linker tool. On platforms
+that support it, the shared object is lazily loaded.
+
+Phase 2 : Symbol Resolution
+---------------------------
+
+In this stage, the linker resolves symbols using global symbol table. It may
+report undefined symbol errors, read archive members, replace weak symbols, etc.
+The linker is able to do this seamlessly even though it does not know the exact
+content of input LLVM bitcode files. If dead code stripping is enabled then the
+linker collects the list of live symbols.
+
+Phase 3 : Optimize Bitcode Files
+--------------------------------
+
+After symbol resolution, the linker tells the LTO shared object which symbols
+are needed by native object files. In the example above, the linker reports
+that only ``foo1()`` is used by native object files using
+``lto_codegen_add_must_preserve_symbol()``. Next the linker invokes the LLVM
+optimizer and code generators using ``lto_codegen_compile()`` which returns a
+native object file creating by merging the LLVM bitcode files and applying
+various optimization passes.
+
+Phase 4 : Symbol Resolution after optimization
+----------------------------------------------
+
+In this phase, the linker reads optimized a native object file and updates the
+internal global symbol table to reflect any changes. The linker also collects
+information about any changes in use of external symbols by LLVM bitcode
+files. In the example above, the linker notes that ``foo4()`` is not used any
+more. If dead code stripping is enabled then the linker refreshes the live
+symbol information appropriately and performs dead code stripping.
+
+After this phase, the linker continues linking as if it never saw LLVM bitcode
+files.
+
+.. _libLTO:
+
+``libLTO``
+==========
+
+``libLTO`` is a shared object that is part of the LLVM tools, and is intended
+for use by a linker. ``libLTO`` provides an abstract C interface to use the LLVM
+interprocedural optimizer without exposing details of LLVM's internals. The
+intention is to keep the interface as stable as possible even when the LLVM
+optimizer continues to evolve. It should even be possible for a completely
+different compilation technology to provide a different libLTO that works with
+their object files and the standard linker tool.
+
+``lto_module_t``
+----------------
+
+A non-native object file is handled via an ``lto_module_t``. The following
+functions allow the linker to check if a file (on disk or in a memory buffer) is
+a file which libLTO can process:
+
+.. code-block:: c
+
+ lto_module_is_object_file(const char*)
+ lto_module_is_object_file_for_target(const char*, const char*)
+ lto_module_is_object_file_in_memory(const void*, size_t)
+ lto_module_is_object_file_in_memory_for_target(const void*, size_t, const char*)
+
+If the object file can be processed by ``libLTO``, the linker creates a
+``lto_module_t`` by using one of:
+
+.. code-block:: c
+
+ lto_module_create(const char*)
+ lto_module_create_from_memory(const void*, size_t)
+
+and when done, the handle is released via
+
+.. code-block:: c
+
+ lto_module_dispose(lto_module_t)
+
+
+The linker can introspect the non-native object file by getting the number of
+symbols and getting the name and attributes of each symbol via:
+
+.. code-block:: c
+
+ lto_module_get_num_symbols(lto_module_t)
+ lto_module_get_symbol_name(lto_module_t, unsigned int)
+ lto_module_get_symbol_attribute(lto_module_t, unsigned int)
+
+The attributes of a symbol include the alignment, visibility, and kind.
+
+``lto_code_gen_t``
+------------------
+
+Once the linker has loaded each non-native object files into an
+``lto_module_t``, it can request ``libLTO`` to process them all and generate a
+native object file. This is done in a couple of steps. First, a code generator
+is created with:
+
+.. code-block:: c
+
+ lto_codegen_create()
+
+Then, each non-native object file is added to the code generator with:
+
+.. code-block:: c
+
+ lto_codegen_add_module(lto_code_gen_t, lto_module_t)
+
+The linker then has the option of setting some codegen options. Whether or not
+to generate DWARF debug info is set with:
+
+.. code-block:: c
+
+ lto_codegen_set_debug_model(lto_code_gen_t)
+
+Which kind of position independence is set with:
+
+.. code-block:: c
+
+ lto_codegen_set_pic_model(lto_code_gen_t)
+
+And each symbol that is referenced by a native object file or otherwise must not
+be optimized away is set with:
+
+.. code-block:: c
+
+ lto_codegen_add_must_preserve_symbol(lto_code_gen_t, const char*)
+
+After all these settings are done, the linker requests that a native object file
+be created from the modules with the settings using:
+
+.. code-block:: c
+
+ lto_codegen_compile(lto_code_gen_t, size*)
+
+which returns a pointer to a buffer containing the generated native object file.
+The linker then parses that and links it with the rest of the native object
+files.
diff --git a/docs/Makefile b/docs/Makefile
new file mode 100644
index 00000000000..122c4b834bb
--- /dev/null
+++ b/docs/Makefile
@@ -0,0 +1,127 @@
+##===- docs/Makefile ---------------------------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ..
+DIRS :=
+
+ifdef BUILD_FOR_WEBSITE
+PROJ_OBJ_DIR = .
+DOXYGEN = doxygen
+
+$(PROJ_OBJ_DIR)/doxygen.cfg: doxygen.cfg.in
+ cat $< | sed \
+ -e 's/@abs_top_srcdir@/../g' \
+ -e 's/@DOT@/dot/g' \
+ -e 's/@PACKAGE_VERSION@/mainline/' \
+ -e 's/@abs_top_builddir@/../g' > $@
+endif
+
+include $(LEVEL)/Makefile.common
+
+HTML := $(wildcard $(PROJ_SRC_DIR)/*.html) \
+ $(wildcard $(PROJ_SRC_DIR)/*.css)
+DOXYFILES := doxygen.cfg.in doxygen.css doxygen.footer doxygen.header \
+ doxygen.intro
+EXTRA_DIST := $(HTML) $(DOXYFILES) llvm.css CommandGuide
+
+.PHONY: install-html install-doxygen doxygen install-ocamldoc ocamldoc generated
+
+install_targets := install-html
+ifeq ($(ENABLE_DOXYGEN),1)
+install_targets += install-doxygen
+endif
+ifdef OCAMLDOC
+ifneq (,$(filter ocaml,$(BINDINGS_TO_BUILD)))
+install_targets += install-ocamldoc
+endif
+endif
+install-local:: $(install_targets)
+
+generated_targets := doxygen
+ifdef OCAMLDOC
+generated_targets += ocamldoc
+endif
+
+# Live documentation is generated for the web site using this target:
+# 'make generated BUILD_FOR_WEBSITE=1'
+generated:: $(generated_targets)
+
+install-html: $(PROJ_OBJ_DIR)/html.tar.gz
+ $(Echo) Installing HTML documentation
+ $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/html
+ $(Verb) $(DataInstall) $(HTML) $(DESTDIR)$(PROJ_docsdir)/html
+ $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/html.tar.gz $(DESTDIR)$(PROJ_docsdir)
+
+$(PROJ_OBJ_DIR)/html.tar.gz: $(HTML)
+ $(Echo) Packaging HTML documentation
+ $(Verb) $(RM) -rf $@ $(PROJ_OBJ_DIR)/html.tar
+ $(Verb) cd $(PROJ_SRC_DIR) && \
+ $(TAR) cf $(PROJ_OBJ_DIR)/html.tar *.html
+ $(Verb) $(GZIPBIN) $(PROJ_OBJ_DIR)/html.tar
+
+install-doxygen: doxygen
+ $(Echo) Installing doxygen documentation
+ $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/html/doxygen
+ $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/doxygen.tar.gz $(DESTDIR)$(PROJ_docsdir)
+ $(Verb) cd $(PROJ_OBJ_DIR)/doxygen && \
+ $(FIND) . -type f -exec \
+ $(DataInstall) {} $(DESTDIR)$(PROJ_docsdir)/html/doxygen \;
+
+doxygen: regendoc $(PROJ_OBJ_DIR)/doxygen.tar.gz
+
+regendoc:
+ $(Echo) Building doxygen documentation
+ $(Verb) if test -e $(PROJ_OBJ_DIR)/doxygen ; then \
+ $(RM) -rf $(PROJ_OBJ_DIR)/doxygen ; \
+ fi
+ $(Verb) $(DOXYGEN) $(PROJ_OBJ_DIR)/doxygen.cfg
+
+$(PROJ_OBJ_DIR)/doxygen.tar.gz: $(DOXYFILES) $(PROJ_OBJ_DIR)/doxygen.cfg
+ $(Echo) Packaging doxygen documentation
+ $(Verb) $(RM) -rf $@ $(PROJ_OBJ_DIR)/doxygen.tar
+ $(Verb) $(TAR) cf $(PROJ_OBJ_DIR)/doxygen.tar doxygen
+ $(Verb) $(GZIPBIN) $(PROJ_OBJ_DIR)/doxygen.tar
+ $(Verb) $(CP) $(PROJ_OBJ_DIR)/doxygen.tar.gz $(PROJ_OBJ_DIR)/doxygen/html/
+
+userloc: $(LLVM_SRC_ROOT)/docs/userloc.html
+
+$(LLVM_SRC_ROOT)/docs/userloc.html:
+ $(Echo) Making User LOC Table
+ $(Verb) cd $(LLVM_SRC_ROOT) ; ./utils/userloc.pl -details -recurse \
+ -html lib include tools runtime utils examples autoconf test > docs/userloc.html
+
+install-ocamldoc: ocamldoc
+ $(Echo) Installing ocamldoc documentation
+ $(Verb) $(MKDIR) $(DESTDIR)$(PROJ_docsdir)/ocamldoc/html
+ $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/ocamldoc.tar.gz $(DESTDIR)$(PROJ_docsdir)
+ $(Verb) cd $(PROJ_OBJ_DIR)/ocamldoc && \
+ $(FIND) . -type f -exec \
+ $(DataInstall) {} $(DESTDIR)$(PROJ_docsdir)/ocamldoc/html \;
+
+ocamldoc: regen-ocamldoc
+ $(Echo) Packaging ocamldoc documentation
+ $(Verb) $(RM) -rf $(PROJ_OBJ_DIR)/ocamldoc.tar*
+ $(Verb) $(TAR) cf $(PROJ_OBJ_DIR)/ocamldoc.tar ocamldoc
+ $(Verb) $(GZIPBIN) $(PROJ_OBJ_DIR)/ocamldoc.tar
+ $(Verb) $(CP) $(PROJ_OBJ_DIR)/ocamldoc.tar.gz $(PROJ_OBJ_DIR)/ocamldoc/html/
+
+regen-ocamldoc:
+ $(Echo) Building ocamldoc documentation
+ $(Verb) if test -e $(PROJ_OBJ_DIR)/ocamldoc ; then \
+ $(RM) -rf $(PROJ_OBJ_DIR)/ocamldoc ; \
+ fi
+ $(Verb) $(MAKE) -C $(LEVEL)/bindings/ocaml ocamldoc
+ $(Verb) $(MKDIR) $(PROJ_OBJ_DIR)/ocamldoc/html
+ $(Verb) \
+ $(OCAMLDOC) -d $(PROJ_OBJ_DIR)/ocamldoc/html -sort -colorize-code -html \
+ `$(FIND) $(LEVEL)/bindings/ocaml -name "*.odoc" -exec echo -load '{}' ';'`
+
+uninstall-local::
+ $(Echo) Uninstalling Documentation
+ $(Verb) $(RM) -rf $(DESTDIR)$(PROJ_docsdir)
diff --git a/docs/Makefile.sphinx b/docs/Makefile.sphinx
new file mode 100644
index 00000000000..81c13de9cd9
--- /dev/null
+++ b/docs/Makefile.sphinx
@@ -0,0 +1,159 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER =
+BUILDDIR = _build
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+# the i18n builder cannot share the environment and doctrees with the others
+I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
+
+all: html
+
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " singlehtml to make a single large HTML file"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " devhelp to make HTML files and a Devhelp project"
+ @echo " epub to make an epub"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
+ @echo " text to make text files"
+ @echo " man to make manual pages"
+ @echo " texinfo to make Texinfo files"
+ @echo " info to make Texinfo files and run them through makeinfo"
+ @echo " gettext to make PO message catalogs"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+ -rm -rf $(BUILDDIR)/*
+
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+ @echo
+ @# FIXME: Remove this `cp` once HTML->Sphinx transition is completed.
+ @# Kind of a hack, but HTML-formatted docs are on the way out anyway.
+ @echo "Copying legacy HTML-formatted docs into $(BUILDDIR)/html"
+ @cp -a *.html tutorial $(BUILDDIR)/html
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+ @echo
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/llvm.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/llvm.qhc"
+
+devhelp:
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+ @echo
+ @echo "Build finished."
+ @echo "To view the help file:"
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/llvm"
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/llvm"
+ @echo "# devhelp"
+
+epub:
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+ @echo
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
+ "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo "Running LaTeX files through pdflatex..."
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+ @echo
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+ @echo
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+texinfo:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo
+ @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
+ @echo "Run \`make' in that directory to run these through makeinfo" \
+ "(use \`make info' here to do that automatically)."
+
+info:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo "Running Texinfo files through makeinfo..."
+ make -C $(BUILDDIR)/texinfo info
+ @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
+
+gettext:
+ $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
+ @echo
+ @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
+
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+ @echo
+ @echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in $(BUILDDIR)/doctest/output.txt."
diff --git a/docs/MakefileGuide.rst b/docs/MakefileGuide.rst
new file mode 100644
index 00000000000..d2bdd24a9e7
--- /dev/null
+++ b/docs/MakefileGuide.rst
@@ -0,0 +1,956 @@
+.. _makefile_guide:
+
+===================
+LLVM Makefile Guide
+===================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+This document provides *usage* information about the LLVM makefile system. While
+loosely patterned after the BSD makefile system, LLVM has taken a departure from
+BSD in order to implement additional features needed by LLVM. Although makefile
+systems, such as ``automake``, were attempted at one point, it has become clear
+that the features needed by LLVM and the ``Makefile`` norm are too great to use
+a more limited tool. Consequently, LLVM requires simply GNU Make 3.79, a widely
+portable makefile processor. LLVM unabashedly makes heavy use of the features of
+GNU Make so the dependency on GNU Make is firm. If you're not familiar with
+``make``, it is recommended that you read the `GNU Makefile Manual
+<http://www.gnu.org/software/make/manual/make.html>`_.
+
+While this document is rightly part of the `LLVM Programmer's
+Manual <ProgrammersManual.html>`_, it is treated separately here because of the
+volume of content and because it is often an early source of bewilderment for
+new developers.
+
+General Concepts
+================
+
+The LLVM Makefile System is the component of LLVM that is responsible for
+building the software, testing it, generating distributions, checking those
+distributions, installing and uninstalling, etc. It consists of a several files
+throughout the source tree. These files and other general concepts are described
+in this section.
+
+Projects
+--------
+
+The LLVM Makefile System is quite generous. It not only builds its own software,
+but it can build yours too. Built into the system is knowledge of the
+``llvm/projects`` directory. Any directory under ``projects`` that has both a
+``configure`` script and a ``Makefile`` is assumed to be a project that uses the
+LLVM Makefile system. Building software that uses LLVM does not require the
+LLVM Makefile System nor even placement in the ``llvm/projects``
+directory. However, doing so will allow your project to get up and running
+quickly by utilizing the built-in features that are used to compile LLVM. LLVM
+compiles itself using the same features of the makefile system as used for
+projects.
+
+For complete details on setting up your projects configuration, simply mimic the
+``llvm/projects/sample`` project. Or for further details, consult the
+`Projects <Projects.html>`_ page.
+
+Variable Values
+---------------
+
+To use the makefile system, you simply create a file named ``Makefile`` in your
+directory and declare values for certain variables. The variables and values
+that you select determine what the makefile system will do. These variables
+enable rules and processing in the makefile system that automatically Do The
+Right Thing&trade;.
+
+Including Makefiles
+-------------------
+
+Setting variables alone is not enough. You must include into your Makefile
+additional files that provide the rules of the LLVM Makefile system. The various
+files involved are described in the sections that follow.
+
+``Makefile``
+^^^^^^^^^^^^
+
+Each directory to participate in the build needs to have a file named
+``Makefile``. This is the file first read by ``make``. It has three
+sections:
+
+#. Settable Variables --- Required that must be set first.
+#. ``include $(LEVEL)/Makefile.common`` --- include the LLVM Makefile system.
+#. Override Variables --- Override variables set by the LLVM Makefile system.
+
+.. _$(LEVEL)/Makefile.common:
+
+``Makefile.common``
+^^^^^^^^^^^^^^^^^^^
+
+Every project must have a ``Makefile.common`` file at its top source
+directory. This file serves three purposes:
+
+#. It includes the project's configuration makefile to obtain values determined
+ by the ``configure`` script. This is done by including the
+ `$(LEVEL)/Makefile.config`_ file.
+
+#. It specifies any other (static) values that are needed throughout the
+ project. Only values that are used in all or a large proportion of the
+ project's directories should be placed here.
+
+#. It includes the standard rules for the LLVM Makefile system,
+ `$(LLVM_SRC_ROOT)/Makefile.rules`_. This file is the *guts* of the LLVM
+ ``Makefile`` system.
+
+.. _$(LEVEL)/Makefile.config:
+
+``Makefile.config``
+^^^^^^^^^^^^^^^^^^^
+
+Every project must have a ``Makefile.config`` at the top of its *build*
+directory. This file is **generated** by the ``configure`` script from the
+pattern provided by the ``Makefile.config.in`` file located at the top of the
+project's *source* directory. The contents of this file depend largely on what
+configuration items the project uses, however most projects can get what they
+need by just relying on LLVM's configuration found in
+``$(LLVM_OBJ_ROOT)/Makefile.config``.
+
+.. _$(LLVM_SRC_ROOT)/Makefile.rules:
+
+``Makefile.rules``
+^^^^^^^^^^^^^^^^^^
+
+This file, located at ``$(LLVM_SRC_ROOT)/Makefile.rules`` is the heart of the
+LLVM Makefile System. It provides all the logic, dependencies, and rules for
+building the targets supported by the system. What it does largely depends on
+the values of ``make`` `variables`_ that have been set *before*
+``Makefile.rules`` is included.
+
+Comments
+^^^^^^^^
+
+User ``Makefile``\s need not have comments in them unless the construction is
+unusual or it does not strictly follow the rules and patterns of the LLVM
+makefile system. Makefile comments are invoked with the pound (``#``) character.
+The ``#`` character and any text following it, to the end of the line, are
+ignored by ``make``.
+
+Tutorial
+========
+
+This section provides some examples of the different kinds of modules you can
+build with the LLVM makefile system. In general, each directory you provide will
+build a single object although that object may be composed of additionally
+compiled components.
+
+Libraries
+---------
+
+Only a few variable definitions are needed to build a regular library.
+Normally, the makefile system will build all the software into a single
+``libname.o`` (pre-linked) object. This means the library is not searchable and
+that the distinction between compilation units has been dissolved. Optionally,
+you can ask for a shared library (.so) or archive library (.a) built. Archive
+libraries are the default. For example:
+
+.. code-block:: makefile
+
+ LIBRARYNAME = mylib
+ SHARED_LIBRARY = 1
+ ARCHIVE_LIBRARY = 1
+
+says to build a library named ``mylib`` with both a shared library
+(``mylib.so``) and an archive library (``mylib.a``) version. The contents of all
+the libraries produced will be the same, they are just constructed differently.
+Note that you normally do not need to specify the sources involved. The LLVM
+Makefile system will infer the source files from the contents of the source
+directory.
+
+The ``LOADABLE_MODULE=1`` directive can be used in conjunction with
+``SHARED_LIBRARY=1`` to indicate that the resulting shared library should be
+openable with the ``dlopen`` function and searchable with the ``dlsym`` function
+(or your operating system's equivalents). While this isn't strictly necessary on
+Linux and a few other platforms, it is required on systems like HP-UX and
+Darwin. You should use ``LOADABLE_MODULE`` for any shared library that you
+intend to be loaded into an tool via the ``-load`` option. See the
+`WritingAnLLVMPass.html <WritingAnLLVMPass.html#makefile>`_ document for an
+example of why you might want to do this.
+
+Bitcode Modules
+^^^^^^^^^^^^^^^
+
+In some situations, it is desirable to build a single bitcode module from a
+variety of sources, instead of an archive, shared library, or bitcode
+library. Bitcode modules can be specified in addition to any of the other types
+of libraries by defining the `MODULE_NAME`_ variable. For example:
+
+.. code-block:: makefile
+
+ LIBRARYNAME = mylib
+ BYTECODE_LIBRARY = 1
+ MODULE_NAME = mymod
+
+will build a module named ``mymod.bc`` from the sources in the directory. This
+module will be an aggregation of all the bitcode modules derived from the
+sources. The example will also build a bitcode archive containing a bitcode
+module for each compiled source file. The difference is subtle, but important
+depending on how the module or library is to be linked.
+
+Loadable Modules
+^^^^^^^^^^^^^^^^
+
+In some situations, you need to create a loadable module. Loadable modules can
+be loaded into programs like ``opt`` or ``llc`` to specify additional passes to
+run or targets to support. Loadable modules are also useful for debugging a
+pass or providing a pass with another package if that pass can't be included in
+LLVM.
+
+LLVM provides complete support for building such a module. All you need to do is
+use the ``LOADABLE_MODULE`` variable in your ``Makefile``. For example, to build
+a loadable module named ``MyMod`` that uses the LLVM libraries ``LLVMSupport.a``
+and ``LLVMSystem.a``, you would specify:
+
+.. code-block:: makefile
+
+ LIBRARYNAME := MyMod
+ LOADABLE_MODULE := 1
+ LINK_COMPONENTS := support system
+
+Use of the ``LOADABLE_MODULE`` facility implies several things:
+
+#. There will be no "``lib``" prefix on the module. This differentiates it from
+ a standard shared library of the same name.
+
+#. The `SHARED_LIBRARY`_ variable is turned on.
+
+#. The `LINK_LIBS_IN_SHARED`_ variable is turned on.
+
+A loadable module is loaded by LLVM via the facilities of libtool's libltdl
+library which is part of ``lib/System`` implementation.
+
+Tools
+-----
+
+For building executable programs (tools), you must provide the name of the tool
+and the names of the libraries you wish to link with the tool. For example:
+
+.. code-block:: makefile
+
+ TOOLNAME = mytool
+ USEDLIBS = mylib
+ LINK_COMPONENTS = support system
+
+says that we are to build a tool name ``mytool`` and that it requires three
+libraries: ``mylib``, ``LLVMSupport.a`` and ``LLVMSystem.a``.
+
+Note that two different variables are use to indicate which libraries are
+linked: ``USEDLIBS`` and ``LLVMLIBS``. This distinction is necessary to support
+projects. ``LLVMLIBS`` refers to the LLVM libraries found in the LLVM object
+directory. ``USEDLIBS`` refers to the libraries built by your project. In the
+case of building LLVM tools, ``USEDLIBS`` and ``LLVMLIBS`` can be used
+interchangeably since the "project" is LLVM itself and ``USEDLIBS`` refers to
+the same place as ``LLVMLIBS``.
+
+Also note that there are two different ways of specifying a library: with a
+``.a`` suffix and without. Without the suffix, the entry refers to the re-linked
+(.o) file which will include *all* symbols of the library. This is
+useful, for example, to include all passes from a library of passes. If the
+``.a`` suffix is used then the library is linked as a searchable library (with
+the ``-l`` option). In this case, only the symbols that are unresolved *at
+that point* will be resolved from the library, if they exist. Other
+(unreferenced) symbols will not be included when the ``.a`` syntax is used. Note
+that in order to use the ``.a`` suffix, the library in question must have been
+built with the ``ARCHIVE_LIBRARY`` option set.
+
+JIT Tools
+^^^^^^^^^
+
+Many tools will want to use the JIT features of LLVM. To do this, you simply
+specify that you want an execution 'engine', and the makefiles will
+automatically link in the appropriate JIT for the host or an interpreter if none
+is available:
+
+.. code-block:: makefile
+
+ TOOLNAME = my_jit_tool
+ USEDLIBS = mylib
+ LINK_COMPONENTS = engine
+
+Of course, any additional libraries may be listed as other components. To get a
+full understanding of how this changes the linker command, it is recommended
+that you:
+
+.. code-block:: bash
+
+ % cd examples/Fibonacci
+ % make VERBOSE=1
+
+Targets Supported
+=================
+
+This section describes each of the targets that can be built using the LLVM
+Makefile system. Any target can be invoked from any directory but not all are
+applicable to a given directory (e.g. "check", "dist" and "install" will always
+operate as if invoked from the top level directory).
+
+================= =============== ==================
+Target Name Implied Targets Target Description
+================= =============== ==================
+``all`` \ Compile the software recursively. Default target.
+``all-local`` \ Compile the software in the local directory only.
+``check`` \ Change to the ``test`` directory in a project and run the test suite there.
+``check-local`` \ Run a local test suite. Generally this is only defined in the ``Makefile`` of the project's ``test`` directory.
+``clean`` \ Remove built objects recursively.
+``clean-local`` \ Remove built objects from the local directory only.
+``dist`` ``all`` Prepare a source distribution tarball.
+``dist-check`` ``all`` Prepare a source distribution tarball and check that it builds.
+``dist-clean`` ``clean`` Clean source distribution tarball temporary files.
+``install`` ``all`` Copy built objects to installation directory.
+``preconditions`` ``all`` Check to make sure configuration and makefiles are up to date.
+``printvars`` ``all`` Prints variables defined by the makefile system (for debugging).
+``tags`` \ Make C and C++ tags files for emacs and vi.
+``uninstall`` \ Remove built objects from installation directory.
+================= =============== ==================
+
+.. _all:
+
+``all`` (default)
+-----------------
+
+When you invoke ``make`` with no arguments, you are implicitly instructing it to
+seek the ``all`` target (goal). This target is used for building the software
+recursively and will do different things in different directories. For example,
+in a ``lib`` directory, the ``all`` target will compile source files and
+generate libraries. But, in a ``tools`` directory, it will link libraries and
+generate executables.
+
+``all-local``
+-------------
+
+This target is the same as `all`_ but it operates only on the current directory
+instead of recursively.
+
+``check``
+---------
+
+This target can be invoked from anywhere within a project's directories but
+always invokes the `check-local`_ target in the project's ``test`` directory, if
+it exists and has a ``Makefile``. A warning is produced otherwise. If
+`TESTSUITE`_ is defined on the ``make`` command line, it will be passed down to
+the invocation of ``make check-local`` in the ``test`` directory. The intended
+usage for this is to assist in running specific suites of tests. If
+``TESTSUITE`` is not set, the implementation of ``check-local`` should run all
+normal tests. It is up to the project to define what different values for
+``TESTSUTE`` will do. See the `Testing Guide <TestingGuide.html>`_ for further
+details.
+
+``check-local``
+---------------
+
+This target should be implemented by the ``Makefile`` in the project's ``test``
+directory. It is invoked by the ``check`` target elsewhere. Each project is
+free to define the actions of ``check-local`` as appropriate for that
+project. The LLVM project itself uses dejagnu to run a suite of feature and
+regresson tests. Other projects may choose to use dejagnu or any other testing
+mechanism.
+
+``clean``
+---------
+
+This target cleans the build directory, recursively removing all things that the
+Makefile builds. The cleaning rules have been made guarded so they shouldn't go
+awry (via ``rm -f $(UNSET_VARIABLE)/*`` which will attempt to erase the entire
+directory structure.
+
+``clean-local``
+---------------
+
+This target does the same thing as ``clean`` but only for the current (local)
+directory.
+
+``dist``
+--------
+
+This target builds a distribution tarball. It first builds the entire project
+using the ``all`` target and then tars up the necessary files and compresses
+it. The generated tarball is sufficient for a casual source distribution, but
+probably not for a release (see ``dist-check``).
+
+``dist-check``
+--------------
+
+This target does the same thing as the ``dist`` target but also checks the
+distribution tarball. The check is made by unpacking the tarball to a new
+directory, configuring it, building it, installing it, and then verifying that
+the installation results are correct (by comparing to the original build). This
+target can take a long time to run but should be done before a release goes out
+to make sure that the distributed tarball can actually be built into a working
+release.
+
+``dist-clean``
+--------------
+
+This is a special form of the ``clean`` clean target. It performs a normal
+``clean`` but also removes things pertaining to building the distribution.
+
+``install``
+-----------
+
+This target finalizes shared objects and executables and copies all libraries,
+headers, executables and documentation to the directory given with the
+``--prefix`` option to ``configure``. When completed, the prefix directory will
+have everything needed to **use** LLVM.
+
+The LLVM makefiles can generate complete **internal** documentation for all the
+classes by using ``doxygen``. By default, this feature is **not** enabled
+because it takes a long time and generates a massive amount of data (>100MB). If
+you want this feature, you must configure LLVM with the --enable-doxygen switch
+and ensure that a modern version of doxygen (1.3.7 or later) is available in
+your ``PATH``. You can download doxygen from `here
+<http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc>`_.
+
+``preconditions``
+-----------------
+
+This utility target checks to see if the ``Makefile`` in the object directory is
+older than the ``Makefile`` in the source directory and copies it if so. It also
+reruns the ``configure`` script if that needs to be done and rebuilds the
+``Makefile.config`` file similarly. Users may overload this target to ensure
+that sanity checks are run *before* any building of targets as all the targets
+depend on ``preconditions``.
+
+``printvars``
+-------------
+
+This utility target just causes the LLVM makefiles to print out some of the
+makefile variables so that you can double check how things are set.
+
+``reconfigure``
+---------------
+
+This utility target will force a reconfigure of LLVM or your project. It simply
+runs ``$(PROJ_OBJ_ROOT)/config.status --recheck`` to rerun the configuration
+tests and rebuild the configured files. This isn't generally useful as the
+makefiles will reconfigure themselves whenever its necessary.
+
+``spotless``
+------------
+
+.. warning::
+
+ Use with caution!
+
+This utility target, only available when ``$(PROJ_OBJ_ROOT)`` is not the same as
+``$(PROJ_SRC_ROOT)``, will completely clean the ``$(PROJ_OBJ_ROOT)`` directory
+by removing its content entirely and reconfiguring the directory. This returns
+the ``$(PROJ_OBJ_ROOT)`` directory to a completely fresh state. All content in
+the directory except configured files and top-level makefiles will be lost.
+
+``tags``
+--------
+
+This target will generate a ``TAGS`` file in the top-level source directory. It
+is meant for use with emacs, XEmacs, or ViM. The TAGS file provides an index of
+symbol definitions so that the editor can jump you to the definition
+quickly.
+
+``uninstall``
+-------------
+
+This target is the opposite of the ``install`` target. It removes the header,
+library and executable files from the installation directories. Note that the
+directories themselves are not removed because it is not guaranteed that LLVM is
+the only thing installing there (e.g. ``--prefix=/usr``).
+
+.. _variables:
+
+Variables
+=========
+
+Variables are used to tell the LLVM Makefile System what to do and to obtain
+information from it. Variables are also used internally by the LLVM Makefile
+System. Variable names that contain only the upper case alphabetic letters and
+underscore are intended for use by the end user. All other variables are
+internal to the LLVM Makefile System and should not be relied upon nor
+modified. The sections below describe how to use the LLVM Makefile
+variables.
+
+Control Variables
+-----------------
+
+Variables listed in the table below should be set *before* the inclusion of
+`$(LEVEL)/Makefile.common`_. These variables provide input to the LLVM make
+system that tell it what to do for the current directory.
+
+``BUILD_ARCHIVE``
+ If set to any value, causes an archive (.a) library to be built.
+
+``BUILT_SOURCES``
+ Specifies a set of source files that are generated from other source
+ files. These sources will be built before any other target processing to
+ ensure they are present.
+
+``BYTECODE_LIBRARY``
+ If set to any value, causes a bitcode library (.bc) to be built.
+
+``CONFIG_FILES``
+ Specifies a set of configuration files to be installed.
+
+``DEBUG_SYMBOLS``
+ If set to any value, causes the build to include debugging symbols even in
+ optimized objects, libraries and executables. This alters the flags
+ specified to the compilers and linkers. Debugging isn't fun in an optimized
+ build, but it is possible.
+
+``DIRS``
+ Specifies a set of directories, usually children of the current directory,
+ that should also be made using the same goal. These directories will be
+ built serially.
+
+``DISABLE_AUTO_DEPENDENCIES``
+ If set to any value, causes the makefiles to **not** automatically generate
+ dependencies when running the compiler. Use of this feature is discouraged
+ and it may be removed at a later date.
+
+``ENABLE_OPTIMIZED``
+ If set to 1, causes the build to generate optimized objects, libraries and
+ executables. This alters the flags specified to the compilers and
+ linkers. Generally debugging won't be a fun experience with an optimized
+ build.
+
+``ENABLE_PROFILING``
+ If set to 1, causes the build to generate both optimized and profiled
+ objects, libraries and executables. This alters the flags specified to the
+ compilers and linkers to ensure that profile data can be collected from the
+ tools built. Use the ``gprof`` tool to analyze the output from the profiled
+ tools (``gmon.out``).
+
+``DISABLE_ASSERTIONS``
+ If set to 1, causes the build to disable assertions, even if building a
+ debug or profile build. This will exclude all assertion check code from the
+ build. LLVM will execute faster, but with little help when things go
+ wrong.
+
+``EXPERIMENTAL_DIRS``
+ Specify a set of directories that should be built, but if they fail, it
+ should not cause the build to fail. Note that this should only be used
+ temporarily while code is being written.
+
+``EXPORTED_SYMBOL_FILE``
+ Specifies the name of a single file that contains a list of the symbols to
+ be exported by the linker. One symbol per line.
+
+``EXPORTED_SYMBOL_LIST``
+ Specifies a set of symbols to be exported by the linker.
+
+``EXTRA_DIST``
+ Specifies additional files that should be distributed with LLVM. All source
+ files, all built sources, all Makefiles, and most documentation files will
+ be automatically distributed. Use this variable to distribute any files that
+ are not automatically distributed.
+
+``KEEP_SYMBOLS``
+ If set to any value, specifies that when linking executables the makefiles
+ should retain debug symbols in the executable. Normally, symbols are
+ stripped from the executable.
+
+``LEVEL`` (required)
+ Specify the level of nesting from the top level. This variable must be set
+ in each makefile as it is used to find the top level and thus the other
+ makefiles.
+
+``LIBRARYNAME``
+ Specify the name of the library to be built. (Required For Libraries)
+
+``LINK_COMPONENTS``
+ When specified for building a tool, the value of this variable will be
+ passed to the ``llvm-config`` tool to generate a link line for the
+ tool. Unlike ``USEDLIBS`` and ``LLVMLIBS``, not all libraries need to be
+ specified. The ``llvm-config`` tool will figure out the library dependencies
+ and add any libraries that are needed. The ``USEDLIBS`` variable can still
+ be used in conjunction with ``LINK_COMPONENTS`` so that additional
+ project-specific libraries can be linked with the LLVM libraries specified
+ by ``LINK_COMPONENTS``.
+
+.. _LINK_LIBS_IN_SHARED:
+
+``LINK_LIBS_IN_SHARED``
+ By default, shared library linking will ignore any libraries specified with
+ the `LLVMLIBS`_ or `USEDLIBS`_. This prevents shared libs from including
+ things that will be in the LLVM tool the shared library will be loaded
+ into. However, sometimes it is useful to link certain libraries into your
+ shared library and this option enables that feature.
+
+.. _LLVMLIBS:
+
+``LLVMLIBS``
+ Specifies the set of libraries from the LLVM ``$(ObjDir)`` that will be
+ linked into the tool or library.
+
+``LOADABLE_MODULE``
+ If set to any value, causes the shared library being built to also be a
+ loadable module. Loadable modules can be opened with the dlopen() function
+ and searched with dlsym (or the operating system's equivalent). Note that
+ setting this variable without also setting ``SHARED_LIBRARY`` will have no
+ effect.
+
+.. _MODULE_NAME:
+
+``MODULE_NAME``
+ Specifies the name of a bitcode module to be created. A bitcode module can
+ be specified in conjunction with other kinds of library builds or by
+ itself. It constructs from the sources a single linked bitcode file.
+
+``NO_INSTALL``
+ Specifies that the build products of the directory should not be installed
+ but should be built even if the ``install`` target is given. This is handy
+ for directories that build libraries or tools that are only used as part of
+ the build process, such as code generators (e.g. ``tblgen``).
+
+``OPTIONAL_DIRS``
+ Specify a set of directories that may be built, if they exist, but its not
+ an error for them not to exist.
+
+``PARALLEL_DIRS``
+ Specify a set of directories to build recursively and in parallel if the
+ ``-j`` option was used with ``make``.
+
+.. _SHARED_LIBRARY:
+
+``SHARED_LIBRARY``
+ If set to any value, causes a shared library (``.so``) to be built in
+ addition to any other kinds of libraries. Note that this option will cause
+ all source files to be built twice: once with options for position
+ independent code and once without. Use it only where you really need a
+ shared library.
+
+``SOURCES`` (optional)
+ Specifies the list of source files in the current directory to be
+ built. Source files of any type may be specified (programs, documentation,
+ config files, etc.). If not specified, the makefile system will infer the
+ set of source files from the files present in the current directory.
+
+``SUFFIXES``
+ Specifies a set of filename suffixes that occur in suffix match rules. Only
+ set this if your local ``Makefile`` specifies additional suffix match
+ rules.
+
+``TARGET``
+ Specifies the name of the LLVM code generation target that the current
+ directory builds. Setting this variable enables additional rules to build
+ ``.inc`` files from ``.td`` files.
+
+.. _TESTSUITE:
+
+``TESTSUITE``
+ Specifies the directory of tests to run in ``llvm/test``.
+
+``TOOLNAME``
+ Specifies the name of the tool that the current directory should build.
+
+``TOOL_VERBOSE``
+ Implies ``VERBOSE`` and also tells each tool invoked to be verbose. This is
+ handy when you're trying to see the sub-tools invoked by each tool invoked
+ by the makefile. For example, this will pass ``-v`` to the GCC compilers
+ which causes it to print out the command lines it uses to invoke sub-tools
+ (compiler, assembler, linker).
+
+.. _USEDLIBS:
+
+``USEDLIBS``
+ Specifies the list of project libraries that will be linked into the tool or
+ library.
+
+``VERBOSE``
+ Tells the Makefile system to produce detailed output of what it is doing
+ instead of just summary comments. This will generate a LOT of output.
+
+Override Variables
+------------------
+
+Override variables can be used to override the default values provided by the
+LLVM makefile system. These variables can be set in several ways:
+
+* In the environment (e.g. setenv, export) --- not recommended.
+* On the ``make`` command line --- recommended.
+* On the ``configure`` command line.
+* In the Makefile (only *after* the inclusion of `$(LEVEL)/Makefile.common`_).
+
+The override variables are given below:
+
+``AR`` (defaulted)
+ Specifies the path to the ``ar`` tool.
+
+``PROJ_OBJ_DIR``
+ The directory into which the products of build rules will be placed. This
+ might be the same as `PROJ_SRC_DIR`_ but typically is not.
+
+.. _PROJ_SRC_DIR:
+
+``PROJ_SRC_DIR``
+ The directory which contains the source files to be built.
+
+``BUILD_EXAMPLES``
+ If set to 1, build examples in ``examples`` and (if building Clang)
+ ``tools/clang/examples`` directories.
+
+``BZIP2`` (configured)
+ The path to the ``bzip2`` tool.
+
+``CC`` (configured)
+ The path to the 'C' compiler.
+
+``CFLAGS``
+ Additional flags to be passed to the 'C' compiler.
+
+``CXX``
+ Specifies the path to the C++ compiler.
+
+``CXXFLAGS``
+ Additional flags to be passed to the C++ compiler.
+
+``DATE`` (configured)
+ Specifies the path to the ``date`` program or any program that can generate
+ the current date and time on its standard output.
+
+``DOT`` (configured)
+ Specifies the path to the ``dot`` tool or ``false`` if there isn't one.
+
+``ECHO`` (configured)
+ Specifies the path to the ``echo`` tool for printing output.
+
+``EXEEXT`` (configured)
+ Provides the extension to be used on executables built by the makefiles.
+ The value may be empty on platforms that do not use file extensions for
+ executables (e.g. Unix).
+
+``INSTALL`` (configured)
+ Specifies the path to the ``install`` tool.
+
+``LDFLAGS`` (configured)
+ Allows users to specify additional flags to pass to the linker.
+
+``LIBS`` (configured)
+ The list of libraries that should be linked with each tool.
+
+``LIBTOOL`` (configured)
+ Specifies the path to the ``libtool`` tool. This tool is renamed ``mklib``
+ by the ``configure`` script.
+
+``LLVMAS`` (defaulted)
+ Specifies the path to the ``llvm-as`` tool.
+
+``LLVMCC``
+ Specifies the path to the LLVM capable compiler.
+
+``LLVMCXX``
+ Specifies the path to the LLVM C++ capable compiler.
+
+``LLVMGCC`` (defaulted)
+ Specifies the path to the LLVM version of the GCC 'C' Compiler.
+
+``LLVMGXX`` (defaulted)
+ Specifies the path to the LLVM version of the GCC C++ Compiler.
+
+``LLVMLD`` (defaulted)
+ Specifies the path to the LLVM bitcode linker tool
+
+``LLVM_OBJ_ROOT`` (configured)
+ Specifies the top directory into which the output of the build is placed.
+
+``LLVM_SRC_ROOT`` (configured)
+ Specifies the top directory in which the sources are found.
+
+``LLVM_TARBALL_NAME`` (configured)
+ Specifies the name of the distribution tarball to create. This is configured
+ from the name of the project and its version number.
+
+``MKDIR`` (defaulted)
+ Specifies the path to the ``mkdir`` tool that creates directories.
+
+``ONLY_TOOLS``
+ If set, specifies the list of tools to build.
+
+``PLATFORMSTRIPOPTS``
+ The options to provide to the linker to specify that a stripped (no symbols)
+ executable should be built.
+
+``RANLIB`` (defaulted)
+ Specifies the path to the ``ranlib`` tool.
+
+``RM`` (defaulted)
+ Specifies the path to the ``rm`` tool.
+
+``SED`` (defaulted)
+ Specifies the path to the ``sed`` tool.
+
+``SHLIBEXT`` (configured)
+ Provides the filename extension to use for shared libraries.
+
+``TBLGEN`` (defaulted)
+ Specifies the path to the ``tblgen`` tool.
+
+``TAR`` (defaulted)
+ Specifies the path to the ``tar`` tool.
+
+``ZIP`` (defaulted)
+ Specifies the path to the ``zip`` tool.
+
+Readable Variables
+------------------
+
+Variables listed in the table below can be used by the user's Makefile but
+should not be changed. Changing the value will generally cause the build to go
+wrong, so don't do it.
+
+``bindir``
+ The directory into which executables will ultimately be installed. This
+ value is derived from the ``--prefix`` option given to ``configure``.
+
+``BuildMode``
+ The name of the type of build being performed: Debug, Release, or
+ Profile.
+
+``bytecode_libdir``
+ The directory into which bitcode libraries will ultimately be installed.
+ This value is derived from the ``--prefix`` option given to ``configure``.
+
+``ConfigureScriptFLAGS``
+ Additional flags given to the ``configure`` script when reconfiguring.
+
+``DistDir``
+ The *current* directory for which a distribution copy is being made.
+
+.. _Echo:
+
+``Echo``
+ The LLVM Makefile System output command. This provides the ``llvm[n]``
+ prefix and starts with ``@`` so the command itself is not printed by
+ ``make``.
+
+``EchoCmd``
+ Same as `Echo`_ but without the leading ``@``.
+
+``includedir``
+ The directory into which include files will ultimately be installed. This
+ value is derived from the ``--prefix`` option given to ``configure``.
+
+``libdir``
+ The directory into which native libraries will ultimately be installed.
+ This value is derived from the ``--prefix`` option given to
+ ``configure``.
+
+``LibDir``
+ The configuration specific directory into which libraries are placed before
+ installation.
+
+``MakefileConfig``
+ Full path of the ``Makefile.config`` file.
+
+``MakefileConfigIn``
+ Full path of the ``Makefile.config.in`` file.
+
+``ObjDir``
+ The configuration and directory specific directory where build objects
+ (compilation results) are placed.
+
+``SubDirs``
+ The complete list of sub-directories of the current directory as
+ specified by other variables.
+
+``Sources``
+ The complete list of source files.
+
+``sysconfdir``
+ The directory into which configuration files will ultimately be
+ installed. This value is derived from the ``--prefix`` option given to
+ ``configure``.
+
+``ToolDir``
+ The configuration specific directory into which executables are placed
+ before they are installed.
+
+``TopDistDir``
+ The top most directory into which the distribution files are copied.
+
+``Verb``
+ Use this as the first thing on your build script lines to enable or disable
+ verbose mode. It expands to either an ``@`` (quiet mode) or nothing (verbose
+ mode).
+
+Internal Variables
+------------------
+
+Variables listed below are used by the LLVM Makefile System and considered
+internal. You should not use these variables under any circumstances.
+
+.. code-block:: makefile
+
+ Archive
+ AR.Flags
+ BaseNameSources
+ BCCompile.C
+ BCCompile.CXX
+ BCLinkLib
+ C.Flags
+ Compile.C
+ CompileCommonOpts
+ Compile.CXX
+ ConfigStatusScript
+ ConfigureScript
+ CPP.Flags
+ CPP.Flags
+ CXX.Flags
+ DependFiles
+ DestArchiveLib
+ DestBitcodeLib
+ DestModule
+ DestSharedLib
+ DestTool
+ DistAlways
+ DistCheckDir
+ DistCheckTop
+ DistFiles
+ DistName
+ DistOther
+ DistSources
+ DistSubDirs
+ DistTarBZ2
+ DistTarGZip
+ DistZip
+ ExtraLibs
+ FakeSources
+ INCFiles
+ InternalTargets
+ LD.Flags
+ LibName.A
+ LibName.BC
+ LibName.LA
+ LibName.O
+ LibTool.Flags
+ Link
+ LinkModule
+ LLVMLibDir
+ LLVMLibsOptions
+ LLVMLibsPaths
+ LLVMToolDir
+ LLVMUsedLibs
+ LocalTargets
+ Module
+ ObjectsBC
+ ObjectsLO
+ ObjectsO
+ ObjMakefiles
+ ParallelTargets
+ PreConditions
+ ProjLibsOptions
+ ProjLibsPaths
+ ProjUsedLibs
+ Ranlib
+ RecursiveTargets
+ SrcMakefiles
+ Strip
+ StripWarnMsg
+ TableGen
+ TDFiles
+ ToolBuildPath
+ TopLevelTargets
+ UserTargets
diff --git a/docs/Packaging.rst b/docs/Packaging.rst
new file mode 100644
index 00000000000..6e74158d721
--- /dev/null
+++ b/docs/Packaging.rst
@@ -0,0 +1,75 @@
+.. _packaging:
+
+========================
+Advice on Packaging LLVM
+========================
+
+.. contents::
+ :local:
+
+Overview
+========
+
+LLVM sets certain default configure options to make sure our developers don't
+break things for constrained platforms. These settings are not optimal for most
+desktop systems, and we hope that packagers (e.g., Redhat, Debian, MacPorts,
+etc.) will tweak them. This document lists settings we suggest you tweak.
+
+LLVM's API changes with each release, so users are likely to want, for example,
+both LLVM-2.6 and LLVM-2.7 installed at the same time to support apps developed
+against each.
+
+Compile Flags
+=============
+
+LLVM runs much more quickly when it's optimized and assertions are removed.
+However, such a build is currently incompatible with users who build without
+defining ``NDEBUG``, and the lack of assertions makes it hard to debug problems
+in user code. We recommend allowing users to install both optimized and debug
+versions of LLVM in parallel. The following configure flags are relevant:
+
+``--disable-assertions``
+ Builds LLVM with ``NDEBUG`` defined. Changes the LLVM ABI. Also available
+ by setting ``DISABLE_ASSERTIONS=0|1`` in ``make``'s environment. This
+ defaults to enabled regardless of the optimization setting, but it slows
+ things down.
+
+``--enable-debug-symbols``
+ Builds LLVM with ``-g``. Also available by setting ``DEBUG_SYMBOLS=0|1`` in
+ ``make``'s environment. This defaults to disabled when optimizing, so you
+ should turn it back on to let users debug their programs.
+
+``--enable-optimized``
+ (For svn checkouts) Builds LLVM with ``-O2`` and, by default, turns off
+ debug symbols. Also available by setting ``ENABLE_OPTIMIZED=0|1`` in
+ ``make``'s environment. This defaults to enabled when not in a
+ checkout.
+
+C++ Features
+============
+
+RTTI
+ LLVM disables RTTI by default. Add ``REQUIRES_RTTI=1`` to your environment
+ while running ``make`` to re-enable it. This will allow users to build with
+ RTTI enabled and still inherit from LLVM classes.
+
+Shared Library
+==============
+
+Configure with ``--enable-shared`` to build
+``libLLVM-<major>.<minor>.(so|dylib)`` and link the tools against it. This
+saves lots of binary size at the cost of some startup time.
+
+Dependencies
+============
+
+``--enable-libffi``
+ Depend on `libffi <http://sources.redhat.com/libffi/>`_ to allow the LLVM
+ interpreter to call external functions.
+
+``--with-oprofile``
+
+ Depend on `libopagent
+ <http://oprofile.sourceforge.net/doc/devel/index.html>`_ (>=version 0.9.4)
+ to let the LLVM JIT tell oprofile about function addresses and line
+ numbers.
diff --git a/docs/Passes.html b/docs/Passes.html
new file mode 100644
index 00000000000..85292e37412
--- /dev/null
+++ b/docs/Passes.html
@@ -0,0 +1,2066 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <title>LLVM's Analysis and Transform Passes</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+</head>
+<body>
+
+<!--
+
+If Passes.html is up to date, the following "one-liner" should print
+an empty diff.
+
+egrep -e '^<tr><td><a href="#.*">-.*</a></td><td>.*</td></tr>$' \
+ -e '^ <a name=".*">.*</a>$' < Passes.html >html; \
+perl >help <<'EOT' && diff -u help html; rm -f help html
+open HTML, "<Passes.html" or die "open: Passes.html: $!\n";
+while (<HTML>) {
+ m:^<tr><td><a href="#(.*)">-.*</a></td><td>.*</td></tr>$: or next;
+ $order{$1} = sprintf("%03d", 1 + int %order);
+}
+open HELP, "../Release/bin/opt -help|" or die "open: opt -help: $!\n";
+while (<HELP>) {
+ m:^ -([^ ]+) +- (.*)$: or next;
+ my $o = $order{$1};
+ $o = "000" unless defined $o;
+ push @x, "$o<tr><td><a href=\"#$1\">-$1</a></td><td>$2</td></tr>\n";
+ push @y, "$o <a name=\"$1\">-$1: $2</a>\n";
+}
+@x = map { s/^\d\d\d//; $_ } sort @x;
+@y = map { s/^\d\d\d//; $_ } sort @y;
+print @x, @y;
+EOT
+
+This (real) one-liner can also be helpful when converting comments to HTML:
+
+perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print " <p>\n" if !$on && $_ =~ /\S/; print " </p>\n" if $on && $_ =~ /^\s*$/; print " $_\n"; $on = ($_ =~ /\S/); } print " </p>\n" if $on'
+
+ -->
+
+<h1>LLVM's Analysis and Transform Passes</h1>
+
+<ol>
+ <li><a href="#intro">Introduction</a></li>
+ <li><a href="#analyses">Analysis Passes</a>
+ <li><a href="#transforms">Transform Passes</a></li>
+ <li><a href="#utilities">Utility Passes</a></li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:rspencer@x10sys.com">Reid Spencer</a>
+ and Gordon Henriksen</p>
+</div>
+
+<!-- ======================================================================= -->
+<h2><a name="intro">Introduction</a></h2>
+<div>
+ <p>This document serves as a high level summary of the optimization features
+ that LLVM provides. Optimizations are implemented as Passes that traverse some
+ portion of a program to either collect information or transform the program.
+ The table below divides the passes that LLVM provides into three categories.
+ Analysis passes compute information that other passes can use or for debugging
+ or program visualization purposes. Transform passes can use (or invalidate)
+ the analysis passes. Transform passes all mutate the program in some way.
+ Utility passes provides some utility but don't otherwise fit categorization.
+ For example passes to extract functions to bitcode or write a module to
+ bitcode are neither analysis nor transform passes.
+ <p>The table below provides a quick summary of each pass and links to the more
+ complete pass description later in the document.</p>
+
+<table>
+<tr><th colspan="2"><b>ANALYSIS PASSES</b></th></tr>
+<tr><th>Option</th><th>Name</th></tr>
+<tr><td><a href="#aa-eval">-aa-eval</a></td><td>Exhaustive Alias Analysis Precision Evaluator</td></tr>
+<tr><td><a href="#basicaa">-basicaa</a></td><td>Basic Alias Analysis (stateless AA impl)</td></tr>
+<tr><td><a href="#basiccg">-basiccg</a></td><td>Basic CallGraph Construction</td></tr>
+<tr><td><a href="#count-aa">-count-aa</a></td><td>Count Alias Analysis Query Responses</td></tr>
+<tr><td><a href="#debug-aa">-debug-aa</a></td><td>AA use debugger</td></tr>
+<tr><td><a href="#domfrontier">-domfrontier</a></td><td>Dominance Frontier Construction</td></tr>
+<tr><td><a href="#domtree">-domtree</a></td><td>Dominator Tree Construction</td></tr>
+<tr><td><a href="#dot-callgraph">-dot-callgraph</a></td><td>Print Call Graph to 'dot' file</td></tr>
+<tr><td><a href="#dot-cfg">-dot-cfg</a></td><td>Print CFG of function to 'dot' file</td></tr>
+<tr><td><a href="#dot-cfg-only">-dot-cfg-only</a></td><td>Print CFG of function to 'dot' file (with no function bodies)</td></tr>
+<tr><td><a href="#dot-dom">-dot-dom</a></td><td>Print dominance tree of function to 'dot' file</td></tr>
+<tr><td><a href="#dot-dom-only">-dot-dom-only</a></td><td>Print dominance tree of function to 'dot' file (with no function bodies)</td></tr>
+<tr><td><a href="#dot-postdom">-dot-postdom</a></td><td>Print postdominance tree of function to 'dot' file</td></tr>
+<tr><td><a href="#dot-postdom-only">-dot-postdom-only</a></td><td>Print postdominance tree of function to 'dot' file (with no function bodies)</td></tr>
+<tr><td><a href="#globalsmodref-aa">-globalsmodref-aa</a></td><td>Simple mod/ref analysis for globals</td></tr>
+<tr><td><a href="#instcount">-instcount</a></td><td>Counts the various types of Instructions</td></tr>
+<tr><td><a href="#intervals">-intervals</a></td><td>Interval Partition Construction</td></tr>
+<tr><td><a href="#iv-users">-iv-users</a></td><td>Induction Variable Users</td></tr>
+<tr><td><a href="#lazy-value-info">-lazy-value-info</a></td><td>Lazy Value Information Analysis</td></tr>
+<tr><td><a href="#lda">-lda</a></td><td>Loop Dependence Analysis</td></tr>
+<tr><td><a href="#libcall-aa">-libcall-aa</a></td><td>LibCall Alias Analysis</td></tr>
+<tr><td><a href="#lint">-lint</a></td><td>Statically lint-checks LLVM IR</td></tr>
+<tr><td><a href="#loops">-loops</a></td><td>Natural Loop Information</td></tr>
+<tr><td><a href="#memdep">-memdep</a></td><td>Memory Dependence Analysis</td></tr>
+<tr><td><a href="#module-debuginfo">-module-debuginfo</a></td><td>Decodes module-level debug info</td></tr>
+<tr><td><a href="#no-aa">-no-aa</a></td><td>No Alias Analysis (always returns 'may' alias)</td></tr>
+<tr><td><a href="#no-profile">-no-profile</a></td><td>No Profile Information</td></tr>
+<tr><td><a href="#postdomtree">-postdomtree</a></td><td>Post-Dominator Tree Construction</td></tr>
+<tr><td><a href="#print-alias-sets">-print-alias-sets</a></td><td>Alias Set Printer</td></tr>
+<tr><td><a href="#print-callgraph">-print-callgraph</a></td><td>Print a call graph</td></tr>
+<tr><td><a href="#print-callgraph-sccs">-print-callgraph-sccs</a></td><td>Print SCCs of the Call Graph</td></tr>
+<tr><td><a href="#print-cfg-sccs">-print-cfg-sccs</a></td><td>Print SCCs of each function CFG</td></tr>
+<tr><td><a href="#print-dbginfo">-print-dbginfo</a></td><td>Print debug info in human readable form</td></tr>
+<tr><td><a href="#print-dom-info">-print-dom-info</a></td><td>Dominator Info Printer</td></tr>
+<tr><td><a href="#print-externalfnconstants">-print-externalfnconstants</a></td><td>Print external fn callsites passed constants</td></tr>
+<tr><td><a href="#print-function">-print-function</a></td><td>Print function to stderr</td></tr>
+<tr><td><a href="#print-module">-print-module</a></td><td>Print module to stderr</td></tr>
+<tr><td><a href="#print-used-types">-print-used-types</a></td><td>Find Used Types</td></tr>
+<tr><td><a href="#profile-estimator">-profile-estimator</a></td><td>Estimate profiling information</td></tr>
+<tr><td><a href="#profile-loader">-profile-loader</a></td><td>Load profile information from llvmprof.out</td></tr>
+<tr><td><a href="#profile-verifier">-profile-verifier</a></td><td>Verify profiling information</td></tr>
+<tr><td><a href="#regions">-regions</a></td><td>Detect single entry single exit regions</td></tr>
+<tr><td><a href="#scalar-evolution">-scalar-evolution</a></td><td>Scalar Evolution Analysis</td></tr>
+<tr><td><a href="#scev-aa">-scev-aa</a></td><td>ScalarEvolution-based Alias Analysis</td></tr>
+<tr><td><a href="#targetdata">-targetdata</a></td><td>Target Data Layout</td></tr>
+
+
+<tr><th colspan="2"><b>TRANSFORM PASSES</b></th></tr>
+<tr><th>Option</th><th>Name</th></tr>
+<tr><td><a href="#adce">-adce</a></td><td>Aggressive Dead Code Elimination</td></tr>
+<tr><td><a href="#always-inline">-always-inline</a></td><td>Inliner for always_inline functions</td></tr>
+<tr><td><a href="#argpromotion">-argpromotion</a></td><td>Promote 'by reference' arguments to scalars</td></tr>
+<tr><td><a href="#bb-vectorize">-bb-vectorize</a></td><td>Combine instructions to form vector instructions within basic blocks</td></tr>
+<tr><td><a href="#block-placement">-block-placement</a></td><td>Profile Guided Basic Block Placement</td></tr>
+<tr><td><a href="#break-crit-edges">-break-crit-edges</a></td><td>Break critical edges in CFG</td></tr>
+<tr><td><a href="#codegenprepare">-codegenprepare</a></td><td>Optimize for code generation</td></tr>
+<tr><td><a href="#constmerge">-constmerge</a></td><td>Merge Duplicate Global Constants</td></tr>
+<tr><td><a href="#constprop">-constprop</a></td><td>Simple constant propagation</td></tr>
+<tr><td><a href="#dce">-dce</a></td><td>Dead Code Elimination</td></tr>
+<tr><td><a href="#deadargelim">-deadargelim</a></td><td>Dead Argument Elimination</td></tr>
+<tr><td><a href="#deadtypeelim">-deadtypeelim</a></td><td>Dead Type Elimination</td></tr>
+<tr><td><a href="#die">-die</a></td><td>Dead Instruction Elimination</td></tr>
+<tr><td><a href="#dse">-dse</a></td><td>Dead Store Elimination</td></tr>
+<tr><td><a href="#functionattrs">-functionattrs</a></td><td>Deduce function attributes</td></tr>
+<tr><td><a href="#globaldce">-globaldce</a></td><td>Dead Global Elimination</td></tr>
+<tr><td><a href="#globalopt">-globalopt</a></td><td>Global Variable Optimizer</td></tr>
+<tr><td><a href="#gvn">-gvn</a></td><td>Global Value Numbering</td></tr>
+<tr><td><a href="#indvars">-indvars</a></td><td>Canonicalize Induction Variables</td></tr>
+<tr><td><a href="#inline">-inline</a></td><td>Function Integration/Inlining</td></tr>
+<tr><td><a href="#insert-edge-profiling">-insert-edge-profiling</a></td><td>Insert instrumentation for edge profiling</td></tr>
+<tr><td><a href="#insert-optimal-edge-profiling">-insert-optimal-edge-profiling</a></td><td>Insert optimal instrumentation for edge profiling</td></tr>
+<tr><td><a href="#instcombine">-instcombine</a></td><td>Combine redundant instructions</td></tr>
+<tr><td><a href="#internalize">-internalize</a></td><td>Internalize Global Symbols</td></tr>
+<tr><td><a href="#ipconstprop">-ipconstprop</a></td><td>Interprocedural constant propagation</td></tr>
+<tr><td><a href="#ipsccp">-ipsccp</a></td><td>Interprocedural Sparse Conditional Constant Propagation</td></tr>
+<tr><td><a href="#jump-threading">-jump-threading</a></td><td>Jump Threading</td></tr>
+<tr><td><a href="#lcssa">-lcssa</a></td><td>Loop-Closed SSA Form Pass</td></tr>
+<tr><td><a href="#licm">-licm</a></td><td>Loop Invariant Code Motion</td></tr>
+<tr><td><a href="#loop-deletion">-loop-deletion</a></td><td>Delete dead loops</td></tr>
+<tr><td><a href="#loop-extract">-loop-extract</a></td><td>Extract loops into new functions</td></tr>
+<tr><td><a href="#loop-extract-single">-loop-extract-single</a></td><td>Extract at most one loop into a new function</td></tr>
+<tr><td><a href="#loop-reduce">-loop-reduce</a></td><td>Loop Strength Reduction</td></tr>
+<tr><td><a href="#loop-rotate">-loop-rotate</a></td><td>Rotate Loops</td></tr>
+<tr><td><a href="#loop-simplify">-loop-simplify</a></td><td>Canonicalize natural loops</td></tr>
+<tr><td><a href="#loop-unroll">-loop-unroll</a></td><td>Unroll loops</td></tr>
+<tr><td><a href="#loop-unswitch">-loop-unswitch</a></td><td>Unswitch loops</td></tr>
+<tr><td><a href="#loweratomic">-loweratomic</a></td><td>Lower atomic intrinsics to non-atomic form</td></tr>
+<tr><td><a href="#lowerinvoke">-lowerinvoke</a></td><td>Lower invoke and unwind, for unwindless code generators</td></tr>
+<tr><td><a href="#lowerswitch">-lowerswitch</a></td><td>Lower SwitchInst's to branches</td></tr>
+<tr><td><a href="#mem2reg">-mem2reg</a></td><td>Promote Memory to Register</td></tr>
+<tr><td><a href="#memcpyopt">-memcpyopt</a></td><td>MemCpy Optimization</td></tr>
+<tr><td><a href="#mergefunc">-mergefunc</a></td><td>Merge Functions</td></tr>
+<tr><td><a href="#mergereturn">-mergereturn</a></td><td>Unify function exit nodes</td></tr>
+<tr><td><a href="#partial-inliner">-partial-inliner</a></td><td>Partial Inliner</td></tr>
+<tr><td><a href="#prune-eh">-prune-eh</a></td><td>Remove unused exception handling info</td></tr>
+<tr><td><a href="#reassociate">-reassociate</a></td><td>Reassociate expressions</td></tr>
+<tr><td><a href="#reg2mem">-reg2mem</a></td><td>Demote all values to stack slots</td></tr>
+<tr><td><a href="#scalarrepl">-scalarrepl</a></td><td>Scalar Replacement of Aggregates (DT)</td></tr>
+<tr><td><a href="#sccp">-sccp</a></td><td>Sparse Conditional Constant Propagation</td></tr>
+<tr><td><a href="#simplify-libcalls">-simplify-libcalls</a></td><td>Simplify well-known library calls</td></tr>
+<tr><td><a href="#simplifycfg">-simplifycfg</a></td><td>Simplify the CFG</td></tr>
+<tr><td><a href="#sink">-sink</a></td><td>Code sinking</td></tr>
+<tr><td><a href="#sretpromotion">-sretpromotion</a></td><td>Promote sret arguments to multiple ret values</td></tr>
+<tr><td><a href="#strip">-strip</a></td><td>Strip all symbols from a module</td></tr>
+<tr><td><a href="#strip-dead-debug-info">-strip-dead-debug-info</a></td><td>Strip debug info for unused symbols</td></tr>
+<tr><td><a href="#strip-dead-prototypes">-strip-dead-prototypes</a></td><td>Strip Unused Function Prototypes</td></tr>
+<tr><td><a href="#strip-debug-declare">-strip-debug-declare</a></td><td>Strip all llvm.dbg.declare intrinsics</td></tr>
+<tr><td><a href="#strip-nondebug">-strip-nondebug</a></td><td>Strip all symbols, except dbg symbols, from a module</td></tr>
+<tr><td><a href="#tailcallelim">-tailcallelim</a></td><td>Tail Call Elimination</td></tr>
+<tr><td><a href="#tailduplicate">-tailduplicate</a></td><td>Tail Duplication</td></tr>
+
+
+<tr><th colspan="2"><b>UTILITY PASSES</b></th></tr>
+<tr><th>Option</th><th>Name</th></tr>
+<tr><td><a href="#deadarghaX0r">-deadarghaX0r</a></td><td>Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)</td></tr>
+<tr><td><a href="#extract-blocks">-extract-blocks</a></td><td>Extract Basic Blocks From Module (for bugpoint use)</td></tr>
+<tr><td><a href="#instnamer">-instnamer</a></td><td>Assign names to anonymous instructions</td></tr>
+<tr><td><a href="#preverify">-preverify</a></td><td>Preliminary module verification</td></tr>
+<tr><td><a href="#verify">-verify</a></td><td>Module Verifier</td></tr>
+<tr><td><a href="#view-cfg">-view-cfg</a></td><td>View CFG of function</td></tr>
+<tr><td><a href="#view-cfg-only">-view-cfg-only</a></td><td>View CFG of function (with no function bodies)</td></tr>
+<tr><td><a href="#view-dom">-view-dom</a></td><td>View dominance tree of function</td></tr>
+<tr><td><a href="#view-dom-only">-view-dom-only</a></td><td>View dominance tree of function (with no function bodies)</td></tr>
+<tr><td><a href="#view-postdom">-view-postdom</a></td><td>View postdominance tree of function</td></tr>
+<tr><td><a href="#view-postdom-only">-view-postdom-only</a></td><td>View postdominance tree of function (with no function bodies)</td></tr>
+</table>
+
+</div>
+
+<!-- ======================================================================= -->
+<h2><a name="analyses">Analysis Passes</a></h2>
+<div>
+ <p>This section describes the LLVM Analysis Passes.</p>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="aa-eval">-aa-eval: Exhaustive Alias Analysis Precision Evaluator</a>
+</h3>
+<div>
+ <p>This is a simple N^2 alias analysis accuracy evaluator.
+ Basically, for each function in the program, it simply queries to see how the
+ alias analysis implementation answers alias queries between each pair of
+ pointers in the function.</p>
+
+ <p>This is inspired and adapted from code by: Naveen Neelakantam, Francesco
+ Spadini, and Wojciech Stryjewski.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="basicaa">-basicaa: Basic Alias Analysis (stateless AA impl)</a>
+</h3>
+<div>
+ <p>A basic alias analysis pass that implements identities (two different
+ globals cannot alias, etc), but does no stateful analysis.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="basiccg">-basiccg: Basic CallGraph Construction</a>
+</h3>
+<div>
+ <p>Yet to be written.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="count-aa">-count-aa: Count Alias Analysis Query Responses</a>
+</h3>
+<div>
+ <p>
+ A pass which can be used to count how many alias queries
+ are being made and how the alias analysis implementation being used responds.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="debug-aa">-debug-aa: AA use debugger</a>
+</h3>
+<div>
+ <p>
+ This simple pass checks alias analysis users to ensure that if they
+ create a new value, they do not query AA without informing it of the value.
+ It acts as a shim over any other AA pass you want.
+ </p>
+
+ <p>
+ Yes keeping track of every value in the program is expensive, but this is
+ a debugging pass.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="domfrontier">-domfrontier: Dominance Frontier Construction</a>
+</h3>
+<div>
+ <p>
+ This pass is a simple dominator construction algorithm for finding forward
+ dominator frontiers.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="domtree">-domtree: Dominator Tree Construction</a>
+</h3>
+<div>
+ <p>
+ This pass is a simple dominator construction algorithm for finding forward
+ dominators.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dot-callgraph">-dot-callgraph: Print Call Graph to 'dot' file</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the call graph into a
+ <code>.dot</code> graph. This graph can then be processed with the "dot" tool
+ to convert it to postscript or some other suitable format.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dot-cfg">-dot-cfg: Print CFG of function to 'dot' file</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the control flow graph
+ into a <code>.dot</code> graph. This graph can then be processed with the
+ "dot" tool to convert it to postscript or some other suitable format.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dot-cfg-only">-dot-cfg-only: Print CFG of function to 'dot' file (with no function bodies)</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the control flow graph
+ into a <code>.dot</code> graph, omitting the function bodies. This graph can
+ then be processed with the "dot" tool to convert it to postscript or some
+ other suitable format.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dot-dom">-dot-dom: Print dominance tree of function to 'dot' file</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the dominator tree
+ into a <code>.dot</code> graph. This graph can then be processed with the
+ "dot" tool to convert it to postscript or some other suitable format.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dot-dom-only">-dot-dom-only: Print dominance tree of function to 'dot' file (with no function bodies)</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the dominator tree
+ into a <code>.dot</code> graph, omitting the function bodies. This graph can
+ then be processed with the "dot" tool to convert it to postscript or some
+ other suitable format.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dot-postdom">-dot-postdom: Print postdominance tree of function to 'dot' file</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the post dominator tree
+ into a <code>.dot</code> graph. This graph can then be processed with the
+ "dot" tool to convert it to postscript or some other suitable format.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dot-postdom-only">-dot-postdom-only: Print postdominance tree of function to 'dot' file (with no function bodies)</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the post dominator tree
+ into a <code>.dot</code> graph, omitting the function bodies. This graph can
+ then be processed with the "dot" tool to convert it to postscript or some
+ other suitable format.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="globalsmodref-aa">-globalsmodref-aa: Simple mod/ref analysis for globals</a>
+</h3>
+<div>
+ <p>
+ This simple pass provides alias and mod/ref information for global values
+ that do not have their address taken, and keeps track of whether functions
+ read or write memory (are "pure"). For this simple (but very common) case,
+ we can provide pretty accurate and useful information.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="instcount">-instcount: Counts the various types of Instructions</a>
+</h3>
+<div>
+ <p>
+ This pass collects the count of all instructions and reports them
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="intervals">-intervals: Interval Partition Construction</a>
+</h3>
+<div>
+ <p>
+ This analysis calculates and represents the interval partition of a function,
+ or a preexisting interval partition.
+ </p>
+
+ <p>
+ In this way, the interval partition may be used to reduce a flow graph down
+ to its degenerate single node interval partition (unless it is irreducible).
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="iv-users">-iv-users: Induction Variable Users</a>
+</h3>
+<div>
+ <p>Bookkeeping for "interesting" users of expressions computed from
+ induction variables.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="lazy-value-info">-lazy-value-info: Lazy Value Information Analysis</a>
+</h3>
+<div>
+ <p>Interface for lazy computation of value constraint information.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="lda">-lda: Loop Dependence Analysis</a>
+</h3>
+<div>
+ <p>Loop dependence analysis framework, which is used to detect dependences in
+ memory accesses in loops.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="libcall-aa">-libcall-aa: LibCall Alias Analysis</a>
+</h3>
+<div>
+ <p>LibCall Alias Analysis.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="lint">-lint: Statically lint-checks LLVM IR</a>
+</h3>
+<div>
+ <p>This pass statically checks for common and easily-identified constructs
+ which produce undefined or likely unintended behavior in LLVM IR.</p>
+
+ <p>It is not a guarantee of correctness, in two ways. First, it isn't
+ comprehensive. There are checks which could be done statically which are
+ not yet implemented. Some of these are indicated by TODO comments, but
+ those aren't comprehensive either. Second, many conditions cannot be
+ checked statically. This pass does no dynamic instrumentation, so it
+ can't check for all possible problems.</p>
+
+ <p>Another limitation is that it assumes all code will be executed. A store
+ through a null pointer in a basic block which is never reached is harmless,
+ but this pass will warn about it anyway.</p>
+
+ <p>Optimization passes may make conditions that this pass checks for more or
+ less obvious. If an optimization pass appears to be introducing a warning,
+ it may be that the optimization pass is merely exposing an existing
+ condition in the code.</p>
+
+ <p>This code may be run before instcombine. In many cases, instcombine checks
+ for the same kinds of things and turns instructions with undefined behavior
+ into unreachable (or equivalent). Because of this, this pass makes some
+ effort to look through bitcasts and so on.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loops">-loops: Natural Loop Information</a>
+</h3>
+<div>
+ <p>
+ This analysis is used to identify natural loops and determine the loop depth
+ of various nodes of the CFG. Note that the loops identified may actually be
+ several natural loops that share the same header node... not just a single
+ natural loop.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="memdep">-memdep: Memory Dependence Analysis</a>
+</h3>
+<div>
+ <p>
+ An analysis that determines, for a given memory operation, what preceding
+ memory operations it depends on. It builds on alias analysis information, and
+ tries to provide a lazy, caching interface to a common kind of alias
+ information query.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="module-debuginfo">-module-debuginfo: Decodes module-level debug info</a>
+</h3>
+<div>
+ <p>This pass decodes the debug info metadata in a module and prints in a
+ (sufficiently-prepared-) human-readable form.
+
+ For example, run this pass from opt along with the -analyze option, and
+ it'll print to standard output.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="no-aa">-no-aa: No Alias Analysis (always returns 'may' alias)</a>
+</h3>
+<div>
+ <p>
+ This is the default implementation of the Alias Analysis interface. It always
+ returns "I don't know" for alias queries. NoAA is unlike other alias analysis
+ implementations, in that it does not chain to a previous analysis. As such it
+ doesn't follow many of the rules that other alias analyses must.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="no-profile">-no-profile: No Profile Information</a>
+</h3>
+<div>
+ <p>
+ The default "no profile" implementation of the abstract
+ <code>ProfileInfo</code> interface.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="postdomfrontier">-postdomfrontier: Post-Dominance Frontier Construction</a>
+</h3>
+<div>
+ <p>
+ This pass is a simple post-dominator construction algorithm for finding
+ post-dominator frontiers.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="postdomtree">-postdomtree: Post-Dominator Tree Construction</a>
+</h3>
+<div>
+ <p>
+ This pass is a simple post-dominator construction algorithm for finding
+ post-dominators.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-alias-sets">-print-alias-sets: Alias Set Printer</a>
+</h3>
+<div>
+ <p>Yet to be written.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-callgraph">-print-callgraph: Print a call graph</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the call graph to
+ standard error in a human-readable form.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-callgraph-sccs">-print-callgraph-sccs: Print SCCs of the Call Graph</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the SCCs of the call
+ graph to standard error in a human-readable form.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-cfg-sccs">-print-cfg-sccs: Print SCCs of each function CFG</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints the SCCs of each
+ function CFG to standard error in a human-readable form.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-dbginfo">-print-dbginfo: Print debug info in human readable form</a>
+</h3>
+<div>
+ <p>Pass that prints instructions, and associated debug info:</p>
+ <ul>
+
+ <li>source/line/col information</li>
+ <li>original variable name</li>
+ <li>original type name</li>
+ </ul>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-dom-info">-print-dom-info: Dominator Info Printer</a>
+</h3>
+<div>
+ <p>Dominator Info Printer.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-externalfnconstants">-print-externalfnconstants: Print external fn callsites passed constants</a>
+</h3>
+<div>
+ <p>
+ This pass, only available in <code>opt</code>, prints out call sites to
+ external functions that are called with constant arguments. This can be
+ useful when looking for standard library functions we should constant fold
+ or handle in alias analyses.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-function">-print-function: Print function to stderr</a>
+</h3>
+<div>
+ <p>
+ The <code>PrintFunctionPass</code> class is designed to be pipelined with
+ other <code>FunctionPass</code>es, and prints out the functions of the module
+ as they are processed.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-module">-print-module: Print module to stderr</a>
+</h3>
+<div>
+ <p>
+ This pass simply prints out the entire module when it is executed.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="print-used-types">-print-used-types: Find Used Types</a>
+</h3>
+<div>
+ <p>
+ This pass is used to seek out all of the types in use by the program. Note
+ that this analysis explicitly does not include types only used by the symbol
+ table.
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="profile-estimator">-profile-estimator: Estimate profiling information</a>
+</h3>
+<div>
+ <p>Profiling information that estimates the profiling information
+ in a very crude and unimaginative way.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="profile-loader">-profile-loader: Load profile information from llvmprof.out</a>
+</h3>
+<div>
+ <p>
+ A concrete implementation of profiling information that loads the information
+ from a profile dump file.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="profile-verifier">-profile-verifier: Verify profiling information</a>
+</h3>
+<div>
+ <p>Pass that checks profiling information for plausibility.</p>
+</div>
+<h3>
+ <a name="regions">-regions: Detect single entry single exit regions</a>
+</h3>
+<div>
+ <p>
+ The <code>RegionInfo</code> pass detects single entry single exit regions in a
+ function, where a region is defined as any subgraph that is connected to the
+ remaining graph at only two spots. Furthermore, an hierarchical region tree is
+ built.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="scalar-evolution">-scalar-evolution: Scalar Evolution Analysis</a>
+</h3>
+<div>
+ <p>
+ The <code>ScalarEvolution</code> analysis can be used to analyze and
+ catagorize scalar expressions in loops. It specializes in recognizing general
+ induction variables, representing them with the abstract and opaque
+ <code>SCEV</code> class. Given this analysis, trip counts of loops and other
+ important properties can be obtained.
+ </p>
+
+ <p>
+ This analysis is primarily useful for induction variable substitution and
+ strength reduction.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="scev-aa">-scev-aa: ScalarEvolution-based Alias Analysis</a>
+</h3>
+<div>
+ <p>Simple alias analysis implemented in terms of ScalarEvolution queries.
+
+ This differs from traditional loop dependence analysis in that it tests
+ for dependencies within a single iteration of a loop, rather than
+ dependencies between different iterations.
+
+ ScalarEvolution has a more complete understanding of pointer arithmetic
+ than BasicAliasAnalysis' collection of ad-hoc analyses.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="targetdata">-targetdata: Target Data Layout</a>
+</h3>
+<div>
+ <p>Provides other passes access to information on how the size and alignment
+ required by the target ABI for various data types.</p>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h2><a name="transforms">Transform Passes</a></h2>
+<div>
+ <p>This section describes the LLVM Transform Passes.</p>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="adce">-adce: Aggressive Dead Code Elimination</a>
+</h3>
+<div>
+ <p>ADCE aggressively tries to eliminate code. This pass is similar to
+ <a href="#dce">DCE</a> but it assumes that values are dead until proven
+ otherwise. This is similar to <a href="#sccp">SCCP</a>, except applied to
+ the liveness of values.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="always-inline">-always-inline: Inliner for always_inline functions</a>
+</h3>
+<div>
+ <p>A custom inliner that handles only functions that are marked as
+ "always inline".</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="argpromotion">-argpromotion: Promote 'by reference' arguments to scalars</a>
+</h3>
+<div>
+ <p>
+ This pass promotes "by reference" arguments to be "by value" arguments. In
+ practice, this means looking for internal functions that have pointer
+ arguments. If it can prove, through the use of alias analysis, that an
+ argument is *only* loaded, then it can pass the value into the function
+ instead of the address of the value. This can cause recursive simplification
+ of code and lead to the elimination of allocas (especially in C++ template
+ code like the STL).
+ </p>
+
+ <p>
+ This pass also handles aggregate arguments that are passed into a function,
+ scalarizing them if the elements of the aggregate are only loaded. Note that
+ it refuses to scalarize aggregates which would require passing in more than
+ three operands to the function, because passing thousands of operands for a
+ large array or structure is unprofitable!
+ </p>
+
+ <p>
+ Note that this transformation could also be done for arguments that are only
+ stored to (returning the value instead), but does not currently. This case
+ would be best handled when and if LLVM starts supporting multiple return
+ values from functions.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="bb-vectorize">-bb-vectorize: Basic-Block Vectorization</a>
+</h3>
+<div>
+ <p>This pass combines instructions inside basic blocks to form vector
+ instructions. It iterates over each basic block, attempting to pair
+ compatible instructions, repeating this process until no additional
+ pairs are selected for vectorization. When the outputs of some pair
+ of compatible instructions are used as inputs by some other pair of
+ compatible instructions, those pairs are part of a potential
+ vectorization chain. Instruction pairs are only fused into vector
+ instructions when they are part of a chain longer than some
+ threshold length. Moreover, the pass attempts to find the best
+ possible chain for each pair of compatible instructions. These
+ heuristics are intended to prevent vectorization in cases where
+ it would not yield a performance increase of the resulting code.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="block-placement">-block-placement: Profile Guided Basic Block Placement</a>
+</h3>
+<div>
+ <p>This pass is a very simple profile guided basic block placement algorithm.
+ The idea is to put frequently executed blocks together at the start of the
+ function and hopefully increase the number of fall-through conditional
+ branches. If there is no profile information for a particular function, this
+ pass basically orders blocks in depth-first order.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="break-crit-edges">-break-crit-edges: Break critical edges in CFG</a>
+</h3>
+<div>
+ <p>
+ Break all of the critical edges in the CFG by inserting a dummy basic block.
+ It may be "required" by passes that cannot deal with critical edges. This
+ transformation obviously invalidates the CFG, but can update forward dominator
+ (set, immediate dominators, tree, and frontier) information.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="codegenprepare">-codegenprepare: Optimize for code generation</a>
+</h3>
+<div>
+ This pass munges the code in the input function to better prepare it for
+ SelectionDAG-based code generation. This works around limitations in it's
+ basic-block-at-a-time approach. It should eventually be removed.
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="constmerge">-constmerge: Merge Duplicate Global Constants</a>
+</h3>
+<div>
+ <p>
+ Merges duplicate global constants together into a single constant that is
+ shared. This is useful because some passes (ie TraceValues) insert a lot of
+ string constants into the program, regardless of whether or not an existing
+ string is available.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="constprop">-constprop: Simple constant propagation</a>
+</h3>
+<div>
+ <p>This file implements constant propagation and merging. It looks for
+ instructions involving only constant operands and replaces them with a
+ constant value instead of an instruction. For example:</p>
+ <blockquote><pre>add i32 1, 2</pre></blockquote>
+ <p>becomes</p>
+ <blockquote><pre>i32 3</pre></blockquote>
+ <p>NOTE: this pass has a habit of making definitions be dead. It is a good
+ idea to to run a <a href="#die">DIE</a> (Dead Instruction Elimination) pass
+ sometime after running this pass.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dce">-dce: Dead Code Elimination</a>
+</h3>
+<div>
+ <p>
+ Dead code elimination is similar to <a href="#die">dead instruction
+ elimination</a>, but it rechecks instructions that were used by removed
+ instructions to see if they are newly dead.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="deadargelim">-deadargelim: Dead Argument Elimination</a>
+</h3>
+<div>
+ <p>
+ This pass deletes dead arguments from internal functions. Dead argument
+ elimination removes arguments which are directly dead, as well as arguments
+ only passed into function calls as dead arguments of other functions. This
+ pass also deletes dead arguments in a similar way.
+ </p>
+
+ <p>
+ This pass is often useful as a cleanup pass to run after aggressive
+ interprocedural passes, which add possibly-dead arguments.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="deadtypeelim">-deadtypeelim: Dead Type Elimination</a>
+</h3>
+<div>
+ <p>
+ This pass is used to cleanup the output of GCC. It eliminate names for types
+ that are unused in the entire translation unit, using the <a
+ href="#findusedtypes">find used types</a> pass.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="die">-die: Dead Instruction Elimination</a>
+</h3>
+<div>
+ <p>
+ Dead instruction elimination performs a single pass over the function,
+ removing instructions that are obviously dead.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="dse">-dse: Dead Store Elimination</a>
+</h3>
+<div>
+ <p>
+ A trivial dead store elimination that only considers basic-block local
+ redundant stores.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="functionattrs">-functionattrs: Deduce function attributes</a>
+</h3>
+<div>
+ <p>A simple interprocedural pass which walks the call-graph, looking for
+ functions which do not access or only read non-local memory, and marking them
+ readnone/readonly. In addition, it marks function arguments (of pointer type)
+ 'nocapture' if a call to the function does not create any copies of the pointer
+ value that outlive the call. This more or less means that the pointer is only
+ dereferenced, and not returned from the function or stored in a global.
+ This pass is implemented as a bottom-up traversal of the call-graph.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="globaldce">-globaldce: Dead Global Elimination</a>
+</h3>
+<div>
+ <p>
+ This transform is designed to eliminate unreachable internal globals from the
+ program. It uses an aggressive algorithm, searching out globals that are
+ known to be alive. After it finds all of the globals which are needed, it
+ deletes whatever is left over. This allows it to delete recursive chunks of
+ the program which are unreachable.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="globalopt">-globalopt: Global Variable Optimizer</a>
+</h3>
+<div>
+ <p>
+ This pass transforms simple global variables that never have their address
+ taken. If obviously true, it marks read/write globals as constant, deletes
+ variables only stored to, etc.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="gvn">-gvn: Global Value Numbering</a>
+</h3>
+<div>
+ <p>
+ This pass performs global value numbering to eliminate fully and partially
+ redundant instructions. It also performs redundant load elimination.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="indvars">-indvars: Canonicalize Induction Variables</a>
+</h3>
+<div>
+ <p>
+ This transformation analyzes and transforms the induction variables (and
+ computations derived from them) into simpler forms suitable for subsequent
+ analysis and transformation.
+ </p>
+
+ <p>
+ This transformation makes the following changes to each loop with an
+ identifiable induction variable:
+ </p>
+
+ <ol>
+ <li>All loops are transformed to have a <em>single</em> canonical
+ induction variable which starts at zero and steps by one.</li>
+ <li>The canonical induction variable is guaranteed to be the first PHI node
+ in the loop header block.</li>
+ <li>Any pointer arithmetic recurrences are raised to use array
+ subscripts.</li>
+ </ol>
+
+ <p>
+ If the trip count of a loop is computable, this pass also makes the following
+ changes:
+ </p>
+
+ <ol>
+ <li>The exit condition for the loop is canonicalized to compare the
+ induction value against the exit value. This turns loops like:
+ <blockquote><pre>for (i = 7; i*i < 1000; ++i)</pre></blockquote>
+ into
+ <blockquote><pre>for (i = 0; i != 25; ++i)</pre></blockquote></li>
+ <li>Any use outside of the loop of an expression derived from the indvar
+ is changed to compute the derived value outside of the loop, eliminating
+ the dependence on the exit value of the induction variable. If the only
+ purpose of the loop is to compute the exit value of some derived
+ expression, this transformation will make the loop dead.</li>
+ </ol>
+
+ <p>
+ This transformation should be followed by strength reduction after all of the
+ desired loop transformations have been performed. Additionally, on targets
+ where it is profitable, the loop could be transformed to count down to zero
+ (the "do loop" optimization).
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="inline">-inline: Function Integration/Inlining</a>
+</h3>
+<div>
+ <p>
+ Bottom-up inlining of functions into callees.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="insert-edge-profiling">-insert-edge-profiling: Insert instrumentation for edge profiling</a>
+</h3>
+<div>
+ <p>
+ This pass instruments the specified program with counters for edge profiling.
+ Edge profiling can give a reasonable approximation of the hot paths through a
+ program, and is used for a wide variety of program transformations.
+ </p>
+
+ <p>
+ Note that this implementation is very naïve. It inserts a counter for
+ <em>every</em> edge in the program, instead of using control flow information
+ to prune the number of counters inserted.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="insert-optimal-edge-profiling">-insert-optimal-edge-profiling: Insert optimal instrumentation for edge profiling</a>
+</h3>
+<div>
+ <p>This pass instruments the specified program with counters for edge profiling.
+ Edge profiling can give a reasonable approximation of the hot paths through a
+ program, and is used for a wide variety of program transformations.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="instcombine">-instcombine: Combine redundant instructions</a>
+</h3>
+<div>
+ <p>
+ Combine instructions to form fewer, simple
+ instructions. This pass does not modify the CFG This pass is where algebraic
+ simplification happens.
+ </p>
+
+ <p>
+ This pass combines things like:
+ </p>
+
+<blockquote><pre
+>%Y = add i32 %X, 1
+%Z = add i32 %Y, 1</pre></blockquote>
+
+ <p>
+ into:
+ </p>
+
+<blockquote><pre
+>%Z = add i32 %X, 2</pre></blockquote>
+
+ <p>
+ This is a simple worklist driven algorithm.
+ </p>
+
+ <p>
+ This pass guarantees that the following canonicalizations are performed on
+ the program:
+ </p>
+
+ <ul>
+ <li>If a binary operator has a constant operand, it is moved to the right-
+ hand side.</li>
+ <li>Bitwise operators with constant operands are always grouped so that
+ shifts are performed first, then <code>or</code>s, then
+ <code>and</code>s, then <code>xor</code>s.</li>
+ <li>Compare instructions are converted from <code>&lt;</code>,
+ <code>&gt;</code>, <code>≤</code>, or <code>≥</code> to
+ <code>=</code> or <code>≠</code> if possible.</li>
+ <li>All <code>cmp</code> instructions on boolean values are replaced with
+ logical operations.</li>
+ <li><code>add <var>X</var>, <var>X</var></code> is represented as
+ <code>mul <var>X</var>, 2</code> ⇒ <code>shl <var>X</var>, 1</code></li>
+ <li>Multiplies with a constant power-of-two argument are transformed into
+ shifts.</li>
+ <li>… etc.</li>
+ </ul>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="internalize">-internalize: Internalize Global Symbols</a>
+</h3>
+<div>
+ <p>
+ This pass loops over all of the functions in the input module, looking for a
+ main function. If a main function is found, all other functions and all
+ global variables with initializers are marked as internal.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="ipconstprop">-ipconstprop: Interprocedural constant propagation</a>
+</h3>
+<div>
+ <p>
+ This pass implements an <em>extremely</em> simple interprocedural constant
+ propagation pass. It could certainly be improved in many different ways,
+ like using a worklist. This pass makes arguments dead, but does not remove
+ them. The existing dead argument elimination pass should be run after this
+ to clean up the mess.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="ipsccp">-ipsccp: Interprocedural Sparse Conditional Constant Propagation</a>
+</h3>
+<div>
+ <p>
+ An interprocedural variant of <a href="#sccp">Sparse Conditional Constant
+ Propagation</a>.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="jump-threading">-jump-threading: Jump Threading</a>
+</h3>
+<div>
+ <p>
+ Jump threading tries to find distinct threads of control flow running through
+ a basic block. This pass looks at blocks that have multiple predecessors and
+ multiple successors. If one or more of the predecessors of the block can be
+ proven to always cause a jump to one of the successors, we forward the edge
+ from the predecessor to the successor by duplicating the contents of this
+ block.
+ </p>
+ <p>
+ An example of when this can occur is code like this:
+ </p>
+
+ <pre
+>if () { ...
+ X = 4;
+}
+if (X &lt; 3) {</pre>
+
+ <p>
+ In this case, the unconditional branch at the end of the first if can be
+ revectored to the false side of the second if.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="lcssa">-lcssa: Loop-Closed SSA Form Pass</a>
+</h3>
+<div>
+ <p>
+ This pass transforms loops by placing phi nodes at the end of the loops for
+ all values that are live across the loop boundary. For example, it turns
+ the left into the right code:
+ </p>
+
+ <pre
+>for (...) for (...)
+ if (c) if (c)
+ X1 = ... X1 = ...
+ else else
+ X2 = ... X2 = ...
+ X3 = phi(X1, X2) X3 = phi(X1, X2)
+... = X3 + 4 X4 = phi(X3)
+ ... = X4 + 4</pre>
+
+ <p>
+ This is still valid LLVM; the extra phi nodes are purely redundant, and will
+ be trivially eliminated by <code>InstCombine</code>. The major benefit of
+ this transformation is that it makes many other loop optimizations, such as
+ LoopUnswitching, simpler.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="licm">-licm: Loop Invariant Code Motion</a>
+</h3>
+<div>
+ <p>
+ This pass performs loop invariant code motion, attempting to remove as much
+ code from the body of a loop as possible. It does this by either hoisting
+ code into the preheader block, or by sinking code to the exit blocks if it is
+ safe. This pass also promotes must-aliased memory locations in the loop to
+ live in registers, thus hoisting and sinking "invariant" loads and stores.
+ </p>
+
+ <p>
+ This pass uses alias analysis for two purposes:
+ </p>
+
+ <ul>
+ <li>Moving loop invariant loads and calls out of loops. If we can determine
+ that a load or call inside of a loop never aliases anything stored to,
+ we can hoist it or sink it like any other instruction.</li>
+ <li>Scalar Promotion of Memory - If there is a store instruction inside of
+ the loop, we try to move the store to happen AFTER the loop instead of
+ inside of the loop. This can only happen if a few conditions are true:
+ <ul>
+ <li>The pointer stored through is loop invariant.</li>
+ <li>There are no stores or loads in the loop which <em>may</em> alias
+ the pointer. There are no calls in the loop which mod/ref the
+ pointer.</li>
+ </ul>
+ If these conditions are true, we can promote the loads and stores in the
+ loop of the pointer to use a temporary alloca'd variable. We then use
+ the mem2reg functionality to construct the appropriate SSA form for the
+ variable.</li>
+ </ul>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loop-deletion">-loop-deletion: Delete dead loops</a>
+</h3>
+<div>
+ <p>
+ This file implements the Dead Loop Deletion Pass. This pass is responsible
+ for eliminating loops with non-infinite computable trip counts that have no
+ side effects or volatile instructions, and do not contribute to the
+ computation of the function's return value.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loop-extract">-loop-extract: Extract loops into new functions</a>
+</h3>
+<div>
+ <p>
+ A pass wrapper around the <code>ExtractLoop()</code> scalar transformation to
+ extract each top-level loop into its own new function. If the loop is the
+ <em>only</em> loop in a given function, it is not touched. This is a pass most
+ useful for debugging via bugpoint.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loop-extract-single">-loop-extract-single: Extract at most one loop into a new function</a>
+</h3>
+<div>
+ <p>
+ Similar to <a href="#loop-extract">Extract loops into new functions</a>,
+ this pass extracts one natural loop from the program into a function if it
+ can. This is used by bugpoint.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loop-reduce">-loop-reduce: Loop Strength Reduction</a>
+</h3>
+<div>
+ <p>
+ This pass performs a strength reduction on array references inside loops that
+ have as one or more of their components the loop induction variable. This is
+ accomplished by creating a new value to hold the initial value of the array
+ access for the first iteration, and then creating a new GEP instruction in
+ the loop to increment the value by the appropriate amount.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loop-rotate">-loop-rotate: Rotate Loops</a>
+</h3>
+<div>
+ <p>A simple loop rotation transformation.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loop-simplify">-loop-simplify: Canonicalize natural loops</a>
+</h3>
+<div>
+ <p>
+ This pass performs several transformations to transform natural loops into a
+ simpler form, which makes subsequent analyses and transformations simpler and
+ more effective.
+ </p>
+
+ <p>
+ Loop pre-header insertion guarantees that there is a single, non-critical
+ entry edge from outside of the loop to the loop header. This simplifies a
+ number of analyses and transformations, such as LICM.
+ </p>
+
+ <p>
+ Loop exit-block insertion guarantees that all exit blocks from the loop
+ (blocks which are outside of the loop that have predecessors inside of the
+ loop) only have predecessors from inside of the loop (and are thus dominated
+ by the loop header). This simplifies transformations such as store-sinking
+ that are built into LICM.
+ </p>
+
+ <p>
+ This pass also guarantees that loops will have exactly one backedge.
+ </p>
+
+ <p>
+ Note that the simplifycfg pass will clean up blocks which are split out but
+ end up being unnecessary, so usage of this pass should not pessimize
+ generated code.
+ </p>
+
+ <p>
+ This pass obviously modifies the CFG, but updates loop information and
+ dominator information.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loop-unroll">-loop-unroll: Unroll loops</a>
+</h3>
+<div>
+ <p>
+ This pass implements a simple loop unroller. It works best when loops have
+ been canonicalized by the <a href="#indvars"><tt>-indvars</tt></a> pass,
+ allowing it to determine the trip counts of loops easily.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loop-unswitch">-loop-unswitch: Unswitch loops</a>
+</h3>
+<div>
+ <p>
+ This pass transforms loops that contain branches on loop-invariant conditions
+ to have multiple loops. For example, it turns the left into the right code:
+ </p>
+
+ <pre
+>for (...) if (lic)
+ A for (...)
+ if (lic) A; B; C
+ B else
+ C for (...)
+ A; C</pre>
+
+ <p>
+ This can increase the size of the code exponentially (doubling it every time
+ a loop is unswitched) so we only unswitch if the resultant code will be
+ smaller than a threshold.
+ </p>
+
+ <p>
+ This pass expects LICM to be run before it to hoist invariant conditions out
+ of the loop, to make the unswitching opportunity obvious.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="loweratomic">-loweratomic: Lower atomic intrinsics to non-atomic form</a>
+</h3>
+<div>
+ <p>
+ This pass lowers atomic intrinsics to non-atomic form for use in a known
+ non-preemptible environment.
+ </p>
+
+ <p>
+ The pass does not verify that the environment is non-preemptible (in
+ general this would require knowledge of the entire call graph of the
+ program including any libraries which may not be available in bitcode form);
+ it simply lowers every atomic intrinsic.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="lowerinvoke">-lowerinvoke: Lower invoke and unwind, for unwindless code generators</a>
+</h3>
+<div>
+ <p>
+ This transformation is designed for use by code generators which do not yet
+ support stack unwinding. This pass supports two models of exception handling
+ lowering, the 'cheap' support and the 'expensive' support.
+ </p>
+
+ <p>
+ 'Cheap' exception handling support gives the program the ability to execute
+ any program which does not "throw an exception", by turning 'invoke'
+ instructions into calls and by turning 'unwind' instructions into calls to
+ abort(). If the program does dynamically use the unwind instruction, the
+ program will print a message then abort.
+ </p>
+
+ <p>
+ 'Expensive' exception handling support gives the full exception handling
+ support to the program at the cost of making the 'invoke' instruction
+ really expensive. It basically inserts setjmp/longjmp calls to emulate the
+ exception handling as necessary.
+ </p>
+
+ <p>
+ Because the 'expensive' support slows down programs a lot, and EH is only
+ used for a subset of the programs, it must be specifically enabled by the
+ <tt>-enable-correct-eh-support</tt> option.
+ </p>
+
+ <p>
+ Note that after this pass runs the CFG is not entirely accurate (exceptional
+ control flow edges are not correct anymore) so only very simple things should
+ be done after the lowerinvoke pass has run (like generation of native code).
+ This should not be used as a general purpose "my LLVM-to-LLVM pass doesn't
+ support the invoke instruction yet" lowering pass.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="lowerswitch">-lowerswitch: Lower SwitchInst's to branches</a>
+</h3>
+<div>
+ <p>
+ Rewrites <tt>switch</tt> instructions with a sequence of branches, which
+ allows targets to get away with not implementing the switch instruction until
+ it is convenient.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="mem2reg">-mem2reg: Promote Memory to Register</a>
+</h3>
+<div>
+ <p>
+ This file promotes memory references to be register references. It promotes
+ <tt>alloca</tt> instructions which only have <tt>load</tt>s and
+ <tt>store</tt>s as uses. An <tt>alloca</tt> is transformed by using dominator
+ frontiers to place <tt>phi</tt> nodes, then traversing the function in
+ depth-first order to rewrite <tt>load</tt>s and <tt>store</tt>s as
+ appropriate. This is just the standard SSA construction algorithm to construct
+ "pruned" SSA form.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="memcpyopt">-memcpyopt: MemCpy Optimization</a>
+</h3>
+<div>
+ <p>
+ This pass performs various transformations related to eliminating memcpy
+ calls, or transforming sets of stores into memset's.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="mergefunc">-mergefunc: Merge Functions</a>
+</h3>
+<div>
+ <p>This pass looks for equivalent functions that are mergable and folds them.
+
+ A hash is computed from the function, based on its type and number of
+ basic blocks.
+
+ Once all hashes are computed, we perform an expensive equality comparison
+ on each function pair. This takes n^2/2 comparisons per bucket, so it's
+ important that the hash function be high quality. The equality comparison
+ iterates through each instruction in each basic block.
+
+ When a match is found the functions are folded. If both functions are
+ overridable, we move the functionality into a new internal function and
+ leave two overridable thunks to it.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="mergereturn">-mergereturn: Unify function exit nodes</a>
+</h3>
+<div>
+ <p>
+ Ensure that functions have at most one <tt>ret</tt> instruction in them.
+ Additionally, it keeps track of which node is the new exit node of the CFG.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="partial-inliner">-partial-inliner: Partial Inliner</a>
+</h3>
+<div>
+ <p>This pass performs partial inlining, typically by inlining an if
+ statement that surrounds the body of the function.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="prune-eh">-prune-eh: Remove unused exception handling info</a>
+</h3>
+<div>
+ <p>
+ This file implements a simple interprocedural pass which walks the call-graph,
+ turning <tt>invoke</tt> instructions into <tt>call</tt> instructions if and
+ only if the callee cannot throw an exception. It implements this as a
+ bottom-up traversal of the call-graph.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="reassociate">-reassociate: Reassociate expressions</a>
+</h3>
+<div>
+ <p>
+ This pass reassociates commutative expressions in an order that is designed
+ to promote better constant propagation, GCSE, LICM, PRE, etc.
+ </p>
+
+ <p>
+ For example: 4 + (<var>x</var> + 5) ⇒ <var>x</var> + (4 + 5)
+ </p>
+
+ <p>
+ In the implementation of this algorithm, constants are assigned rank = 0,
+ function arguments are rank = 1, and other values are assigned ranks
+ corresponding to the reverse post order traversal of current function
+ (starting at 2), which effectively gives values in deep loops higher rank
+ than values not in loops.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="reg2mem">-reg2mem: Demote all values to stack slots</a>
+</h3>
+<div>
+ <p>
+ This file demotes all registers to memory references. It is intended to be
+ the inverse of <a href="#mem2reg"><tt>-mem2reg</tt></a>. By converting to
+ <tt>load</tt> instructions, the only values live across basic blocks are
+ <tt>alloca</tt> instructions and <tt>load</tt> instructions before
+ <tt>phi</tt> nodes. It is intended that this should make CFG hacking much
+ easier. To make later hacking easier, the entry block is split into two, such
+ that all introduced <tt>alloca</tt> instructions (and nothing else) are in the
+ entry block.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="scalarrepl">-scalarrepl: Scalar Replacement of Aggregates (DT)</a>
+</h3>
+<div>
+ <p>
+ The well-known scalar replacement of aggregates transformation. This
+ transform breaks up <tt>alloca</tt> instructions of aggregate type (structure
+ or array) into individual <tt>alloca</tt> instructions for each member if
+ possible. Then, if possible, it transforms the individual <tt>alloca</tt>
+ instructions into nice clean scalar SSA form.
+ </p>
+
+ <p>
+ This combines a simple scalar replacement of aggregates algorithm with the <a
+ href="#mem2reg"><tt>mem2reg</tt></a> algorithm because often interact,
+ especially for C++ programs. As such, iterating between <tt>scalarrepl</tt>,
+ then <a href="#mem2reg"><tt>mem2reg</tt></a> until we run out of things to
+ promote works well.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="sccp">-sccp: Sparse Conditional Constant Propagation</a>
+</h3>
+<div>
+ <p>
+ Sparse conditional constant propagation and merging, which can be summarized
+ as:
+ </p>
+
+ <ol>
+ <li>Assumes values are constant unless proven otherwise</li>
+ <li>Assumes BasicBlocks are dead unless proven otherwise</li>
+ <li>Proves values to be constant, and replaces them with constants</li>
+ <li>Proves conditional branches to be unconditional</li>
+ </ol>
+
+ <p>
+ Note that this pass has a habit of making definitions be dead. It is a good
+ idea to to run a DCE pass sometime after running this pass.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="simplify-libcalls">-simplify-libcalls: Simplify well-known library calls</a>
+</h3>
+<div>
+ <p>
+ Applies a variety of small optimizations for calls to specific well-known
+ function calls (e.g. runtime library functions). For example, a call
+ <tt>exit(3)</tt> that occurs within the <tt>main()</tt> function can be
+ transformed into simply <tt>return 3</tt>.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="simplifycfg">-simplifycfg: Simplify the CFG</a>
+</h3>
+<div>
+ <p>
+ Performs dead code elimination and basic block merging. Specifically:
+ </p>
+
+ <ol>
+ <li>Removes basic blocks with no predecessors.</li>
+ <li>Merges a basic block into its predecessor if there is only one and the
+ predecessor only has one successor.</li>
+ <li>Eliminates PHI nodes for basic blocks with a single predecessor.</li>
+ <li>Eliminates a basic block that only contains an unconditional
+ branch.</li>
+ </ol>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="sink">-sink: Code sinking</a>
+</h3>
+<div>
+ <p>This pass moves instructions into successor blocks, when possible, so that
+ they aren't executed on paths where their results aren't needed.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="sretpromotion">-sretpromotion: Promote sret arguments to multiple ret values</a>
+</h3>
+<div>
+ <p>
+ This pass finds functions that return a struct (using a pointer to the struct
+ as the first argument of the function, marked with the '<tt>sret</tt>' attribute) and
+ replaces them with a new function that simply returns each of the elements of
+ that struct (using multiple return values).
+ </p>
+
+ <p>
+ This pass works under a number of conditions:
+ </p>
+
+ <ul>
+ <li>The returned struct must not contain other structs</li>
+ <li>The returned struct must only be used to load values from</li>
+ <li>The placeholder struct passed in is the result of an <tt>alloca</tt></li>
+ </ul>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="strip">-strip: Strip all symbols from a module</a>
+</h3>
+<div>
+ <p>
+ performs code stripping. this transformation can delete:
+ </p>
+
+ <ol>
+ <li>names for virtual registers</li>
+ <li>symbols for internal globals and functions</li>
+ <li>debug information</li>
+ </ol>
+
+ <p>
+ note that this transformation makes code much less readable, so it should
+ only be used in situations where the <tt>strip</tt> utility would be used,
+ such as reducing code size or making it harder to reverse engineer code.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="strip-dead-debug-info">-strip-dead-debug-info: Strip debug info for unused symbols</a>
+</h3>
+<div>
+ <p>
+ performs code stripping. this transformation can delete:
+ </p>
+
+ <ol>
+ <li>names for virtual registers</li>
+ <li>symbols for internal globals and functions</li>
+ <li>debug information</li>
+ </ol>
+
+ <p>
+ note that this transformation makes code much less readable, so it should
+ only be used in situations where the <tt>strip</tt> utility would be used,
+ such as reducing code size or making it harder to reverse engineer code.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="strip-dead-prototypes">-strip-dead-prototypes: Strip Unused Function Prototypes</a>
+</h3>
+<div>
+ <p>
+ This pass loops over all of the functions in the input module, looking for
+ dead declarations and removes them. Dead declarations are declarations of
+ functions for which no implementation is available (i.e., declarations for
+ unused library functions).
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="strip-debug-declare">-strip-debug-declare: Strip all llvm.dbg.declare intrinsics</a>
+</h3>
+<div>
+ <p>This pass implements code stripping. Specifically, it can delete:</p>
+ <ul>
+ <li>names for virtual registers</li>
+ <li>symbols for internal globals and functions</li>
+ <li>debug information</li>
+ </ul>
+ <p>
+ Note that this transformation makes code much less readable, so it should
+ only be used in situations where the 'strip' utility would be used, such as
+ reducing code size or making it harder to reverse engineer code.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="strip-nondebug">-strip-nondebug: Strip all symbols, except dbg symbols, from a module</a>
+</h3>
+<div>
+ <p>This pass implements code stripping. Specifically, it can delete:</p>
+ <ul>
+ <li>names for virtual registers</li>
+ <li>symbols for internal globals and functions</li>
+ <li>debug information</li>
+ </ul>
+ <p>
+ Note that this transformation makes code much less readable, so it should
+ only be used in situations where the 'strip' utility would be used, such as
+ reducing code size or making it harder to reverse engineer code.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="tailcallelim">-tailcallelim: Tail Call Elimination</a>
+</h3>
+<div>
+ <p>
+ This file transforms calls of the current function (self recursion) followed
+ by a return instruction with a branch to the entry of the function, creating
+ a loop. This pass also implements the following extensions to the basic
+ algorithm:
+ </p>
+
+ <ul>
+ <li>Trivial instructions between the call and return do not prevent the
+ transformation from taking place, though currently the analysis cannot
+ support moving any really useful instructions (only dead ones).
+ <li>This pass transforms functions that are prevented from being tail
+ recursive by an associative expression to use an accumulator variable,
+ thus compiling the typical naive factorial or <tt>fib</tt> implementation
+ into efficient code.
+ <li>TRE is performed if the function returns void, if the return
+ returns the result returned by the call, or if the function returns a
+ run-time constant on all exits from the function. It is possible, though
+ unlikely, that the return returns something else (like constant 0), and
+ can still be TRE'd. It can be TRE'd if <em>all other</em> return
+ instructions in the function return the exact same value.
+ <li>If it can prove that callees do not access theier caller stack frame,
+ they are marked as eligible for tail call elimination (by the code
+ generator).
+ </ul>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="tailduplicate">-tailduplicate: Tail Duplication</a>
+</h3>
+<div>
+ <p>
+ This pass performs a limited form of tail duplication, intended to simplify
+ CFGs by removing some unconditional branches. This pass is necessary to
+ straighten out loops created by the C front-end, but also is capable of
+ making other code nicer. After this pass is run, the CFG simplify pass
+ should be run to clean up the mess.
+ </p>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h2><a name="utilities">Utility Passes</a></h2>
+<div>
+ <p>This section describes the LLVM Utility Passes.</p>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="deadarghaX0r">-deadarghaX0r: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)</a>
+</h3>
+<div>
+ <p>
+ Same as dead argument elimination, but deletes arguments to functions which
+ are external. This is only for use by <a
+ href="Bugpoint.html">bugpoint</a>.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="extract-blocks">-extract-blocks: Extract Basic Blocks From Module (for bugpoint use)</a>
+</h3>
+<div>
+ <p>
+ This pass is used by bugpoint to extract all blocks from the module into their
+ own functions.</p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="instnamer">-instnamer: Assign names to anonymous instructions</a>
+</h3>
+<div>
+ <p>This is a little utility pass that gives instructions names, this is mostly
+ useful when diffing the effect of an optimization because deleting an
+ unnamed instruction can change all other instruction numbering, making the
+ diff very noisy.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="preverify">-preverify: Preliminary module verification</a>
+</h3>
+<div>
+ <p>
+ Ensures that the module is in the form required by the <a
+ href="#verifier">Module Verifier</a> pass.
+ </p>
+
+ <p>
+ Running the verifier runs this pass automatically, so there should be no need
+ to use it directly.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="verify">-verify: Module Verifier</a>
+</h3>
+<div>
+ <p>
+ Verifies an LLVM IR code. This is useful to run after an optimization which is
+ undergoing testing. Note that <tt>llvm-as</tt> verifies its input before
+ emitting bitcode, and also that malformed bitcode is likely to make LLVM
+ crash. All language front-ends are therefore encouraged to verify their output
+ before performing optimizing transformations.
+ </p>
+
+ <ul>
+ <li>Both of a binary operator's parameters are of the same type.</li>
+ <li>Verify that the indices of mem access instructions match other
+ operands.</li>
+ <li>Verify that arithmetic and other things are only performed on
+ first-class types. Verify that shifts and logicals only happen on
+ integrals f.e.</li>
+ <li>All of the constants in a switch statement are of the correct type.</li>
+ <li>The code is in valid SSA form.</li>
+ <li>It is illegal to put a label into any other type (like a structure) or
+ to return one.</li>
+ <li>Only phi nodes can be self referential: <tt>%x = add i32 %x, %x</tt> is
+ invalid.</li>
+ <li>PHI nodes must have an entry for each predecessor, with no extras.</li>
+ <li>PHI nodes must be the first thing in a basic block, all grouped
+ together.</li>
+ <li>PHI nodes must have at least one entry.</li>
+ <li>All basic blocks should only end with terminator insts, not contain
+ them.</li>
+ <li>The entry node to a function must not have predecessors.</li>
+ <li>All Instructions must be embedded into a basic block.</li>
+ <li>Functions cannot take a void-typed parameter.</li>
+ <li>Verify that a function's argument list agrees with its declared
+ type.</li>
+ <li>It is illegal to specify a name for a void value.</li>
+ <li>It is illegal to have an internal global value with no initializer.</li>
+ <li>It is illegal to have a ret instruction that returns a value that does
+ not agree with the function return value type.</li>
+ <li>Function call argument types match the function prototype.</li>
+ <li>All other things that are tested by asserts spread about the code.</li>
+ </ul>
+
+ <p>
+ Note that this does not provide full security verification (like Java), but
+ instead just tries to ensure that code is well-formed.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="view-cfg">-view-cfg: View CFG of function</a>
+</h3>
+<div>
+ <p>
+ Displays the control flow graph using the GraphViz tool.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="view-cfg-only">-view-cfg-only: View CFG of function (with no function bodies)</a>
+</h3>
+<div>
+ <p>
+ Displays the control flow graph using the GraphViz tool, but omitting function
+ bodies.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="view-dom">-view-dom: View dominance tree of function</a>
+</h3>
+<div>
+ <p>
+ Displays the dominator tree using the GraphViz tool.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="view-dom-only">-view-dom-only: View dominance tree of function (with no function bodies)</a>
+</h3>
+<div>
+ <p>
+ Displays the dominator tree using the GraphViz tool, but omitting function
+ bodies.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="view-postdom">-view-postdom: View postdominance tree of function</a>
+</h3>
+<div>
+ <p>
+ Displays the post dominator tree using the GraphViz tool.
+ </p>
+</div>
+
+<!-------------------------------------------------------------------------- -->
+<h3>
+ <a name="view-postdom-only">-view-postdom-only: View postdominance tree of function (with no function bodies)</a>
+</h3>
+<div>
+ <p>
+ Displays the post dominator tree using the GraphViz tool, but omitting
+ function bodies.
+ </p>
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="mailto:rspencer@x10sys.com">Reid Spencer</a><br>
+ <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/ProgrammersManual.html b/docs/ProgrammersManual.html
new file mode 100644
index 00000000000..036c387d7a5
--- /dev/null
+++ b/docs/ProgrammersManual.html
@@ -0,0 +1,4137 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
+ <title>LLVM Programmer's Manual</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>
+ LLVM Programmer's Manual
+</h1>
+
+<ol>
+ <li><a href="#introduction">Introduction</a></li>
+ <li><a href="#general">General Information</a>
+ <ul>
+ <li><a href="#stl">The C++ Standard Template Library</a></li>
+<!--
+ <li>The <tt>-time-passes</tt> option</li>
+ <li>How to use the LLVM Makefile system</li>
+ <li>How to write a regression test</li>
+
+-->
+ </ul>
+ </li>
+ <li><a href="#apis">Important and useful LLVM APIs</a>
+ <ul>
+ <li><a href="#isa">The <tt>isa&lt;&gt;</tt>, <tt>cast&lt;&gt;</tt>
+and <tt>dyn_cast&lt;&gt;</tt> templates</a> </li>
+ <li><a href="#string_apis">Passing strings (the <tt>StringRef</tt>
+and <tt>Twine</tt> classes)</a>
+ <ul>
+ <li><a href="#StringRef">The <tt>StringRef</tt> class</a> </li>
+ <li><a href="#Twine">The <tt>Twine</tt> class</a> </li>
+ </ul>
+ </li>
+ <li><a href="#DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt>
+option</a>
+ <ul>
+ <li><a href="#DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt>
+and the <tt>-debug-only</tt> option</a> </li>
+ </ul>
+ </li>
+ <li><a href="#Statistic">The <tt>Statistic</tt> class &amp; <tt>-stats</tt>
+option</a></li>
+<!--
+ <li>The <tt>InstVisitor</tt> template
+ <li>The general graph API
+-->
+ <li><a href="#ViewGraph">Viewing graphs while debugging code</a></li>
+ </ul>
+ </li>
+ <li><a href="#datastructure">Picking the Right Data Structure for a Task</a>
+ <ul>
+ <li><a href="#ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
+ <ul>
+ <li><a href="#dss_arrayref">llvm/ADT/ArrayRef.h</a></li>
+ <li><a href="#dss_fixedarrays">Fixed Size Arrays</a></li>
+ <li><a href="#dss_heaparrays">Heap Allocated Arrays</a></li>
+ <li><a href="#dss_tinyptrvector">"llvm/ADT/TinyPtrVector.h"</a></li>
+ <li><a href="#dss_smallvector">"llvm/ADT/SmallVector.h"</a></li>
+ <li><a href="#dss_vector">&lt;vector&gt;</a></li>
+ <li><a href="#dss_deque">&lt;deque&gt;</a></li>
+ <li><a href="#dss_list">&lt;list&gt;</a></li>
+ <li><a href="#dss_ilist">llvm/ADT/ilist.h</a></li>
+ <li><a href="#dss_packedvector">llvm/ADT/PackedVector.h</a></li>
+ <li><a href="#dss_other">Other Sequential Container Options</a></li>
+ </ul></li>
+ <li><a href="#ds_string">String-like containers</a>
+ <ul>
+ <li><a href="#dss_stringref">llvm/ADT/StringRef.h</a></li>
+ <li><a href="#dss_twine">llvm/ADT/Twine.h</a></li>
+ <li><a href="#dss_smallstring">llvm/ADT/SmallString.h</a></li>
+ <li><a href="#dss_stdstring">std::string</a></li>
+ </ul></li>
+ <li><a href="#ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
+ <ul>
+ <li><a href="#dss_sortedvectorset">A sorted 'vector'</a></li>
+ <li><a href="#dss_smallset">"llvm/ADT/SmallSet.h"</a></li>
+ <li><a href="#dss_smallptrset">"llvm/ADT/SmallPtrSet.h"</a></li>
+ <li><a href="#dss_denseset">"llvm/ADT/DenseSet.h"</a></li>
+ <li><a href="#dss_sparseset">"llvm/ADT/SparseSet.h"</a></li>
+ <li><a href="#dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a></li>
+ <li><a href="#dss_set">&lt;set&gt;</a></li>
+ <li><a href="#dss_setvector">"llvm/ADT/SetVector.h"</a></li>
+ <li><a href="#dss_uniquevector">"llvm/ADT/UniqueVector.h"</a></li>
+ <li><a href="#dss_immutableset">"llvm/ADT/ImmutableSet.h"</a></li>
+ <li><a href="#dss_otherset">Other Set-Like Container Options</a></li>
+ </ul></li>
+ <li><a href="#ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
+ <ul>
+ <li><a href="#dss_sortedvectormap">A sorted 'vector'</a></li>
+ <li><a href="#dss_stringmap">"llvm/ADT/StringMap.h"</a></li>
+ <li><a href="#dss_indexedmap">"llvm/ADT/IndexedMap.h"</a></li>
+ <li><a href="#dss_densemap">"llvm/ADT/DenseMap.h"</a></li>
+ <li><a href="#dss_valuemap">"llvm/ADT/ValueMap.h"</a></li>
+ <li><a href="#dss_intervalmap">"llvm/ADT/IntervalMap.h"</a></li>
+ <li><a href="#dss_map">&lt;map&gt;</a></li>
+ <li><a href="#dss_inteqclasses">"llvm/ADT/IntEqClasses.h"</a></li>
+ <li><a href="#dss_immutablemap">"llvm/ADT/ImmutableMap.h"</a></li>
+ <li><a href="#dss_othermap">Other Map-Like Container Options</a></li>
+ </ul></li>
+ <li><a href="#ds_bit">BitVector-like containers</a>
+ <ul>
+ <li><a href="#dss_bitvector">A dense bitvector</a></li>
+ <li><a href="#dss_smallbitvector">A "small" dense bitvector</a></li>
+ <li><a href="#dss_sparsebitvector">A sparse bitvector</a></li>
+ </ul></li>
+ </ul>
+ </li>
+ <li><a href="#common">Helpful Hints for Common Operations</a>
+ <ul>
+ <li><a href="#inspection">Basic Inspection and Traversal Routines</a>
+ <ul>
+ <li><a href="#iterate_function">Iterating over the <tt>BasicBlock</tt>s
+in a <tt>Function</tt></a> </li>
+ <li><a href="#iterate_basicblock">Iterating over the <tt>Instruction</tt>s
+in a <tt>BasicBlock</tt></a> </li>
+ <li><a href="#iterate_institer">Iterating over the <tt>Instruction</tt>s
+in a <tt>Function</tt></a> </li>
+ <li><a href="#iterate_convert">Turning an iterator into a
+class pointer</a> </li>
+ <li><a href="#iterate_complex">Finding call sites: a more
+complex example</a> </li>
+ <li><a href="#calls_and_invokes">Treating calls and invokes
+the same way</a> </li>
+ <li><a href="#iterate_chains">Iterating over def-use &amp;
+use-def chains</a> </li>
+ <li><a href="#iterate_preds">Iterating over predecessors &amp;
+successors of blocks</a></li>
+ </ul>
+ </li>
+ <li><a href="#simplechanges">Making simple changes</a>
+ <ul>
+ <li><a href="#schanges_creating">Creating and inserting new
+ <tt>Instruction</tt>s</a> </li>
+ <li><a href="#schanges_deleting">Deleting <tt>Instruction</tt>s</a> </li>
+ <li><a href="#schanges_replacing">Replacing an <tt>Instruction</tt>
+with another <tt>Value</tt></a> </li>
+ <li><a href="#schanges_deletingGV">Deleting <tt>GlobalVariable</tt>s</a> </li>
+ </ul>
+ </li>
+ <li><a href="#create_types">How to Create Types</a></li>
+<!--
+ <li>Working with the Control Flow Graph
+ <ul>
+ <li>Accessing predecessors and successors of a <tt>BasicBlock</tt>
+ <li>
+ <li>
+ </ul>
+-->
+ </ul>
+ </li>
+
+ <li><a href="#threading">Threads and LLVM</a>
+ <ul>
+ <li><a href="#startmultithreaded">Entering and Exiting Multithreaded Mode
+ </a></li>
+ <li><a href="#shutdown">Ending execution with <tt>llvm_shutdown()</tt></a></li>
+ <li><a href="#managedstatic">Lazy initialization with <tt>ManagedStatic</tt></a></li>
+ <li><a href="#llvmcontext">Achieving Isolation with <tt>LLVMContext</tt></a></li>
+ <li><a href="#jitthreading">Threads and the JIT</a></li>
+ </ul>
+ </li>
+
+ <li><a href="#advanced">Advanced Topics</a>
+ <ul>
+
+ <li><a href="#SymbolTable">The <tt>ValueSymbolTable</tt> class</a></li>
+ <li><a href="#UserLayout">The <tt>User</tt> and owned <tt>Use</tt> classes' memory layout</a></li>
+ </ul></li>
+
+ <li><a href="#coreclasses">The Core LLVM Class Hierarchy Reference</a>
+ <ul>
+ <li><a href="#Type">The <tt>Type</tt> class</a> </li>
+ <li><a href="#Module">The <tt>Module</tt> class</a></li>
+ <li><a href="#Value">The <tt>Value</tt> class</a>
+ <ul>
+ <li><a href="#User">The <tt>User</tt> class</a>
+ <ul>
+ <li><a href="#Instruction">The <tt>Instruction</tt> class</a></li>
+ <li><a href="#Constant">The <tt>Constant</tt> class</a>
+ <ul>
+ <li><a href="#GlobalValue">The <tt>GlobalValue</tt> class</a>
+ <ul>
+ <li><a href="#Function">The <tt>Function</tt> class</a></li>
+ <li><a href="#GlobalVariable">The <tt>GlobalVariable</tt> class</a></li>
+ </ul>
+ </li>
+ </ul>
+ </li>
+ </ul>
+ </li>
+ <li><a href="#BasicBlock">The <tt>BasicBlock</tt> class</a></li>
+ <li><a href="#Argument">The <tt>Argument</tt> class</a></li>
+ </ul>
+ </li>
+ </ul>
+ </li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>,
+ <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a>,
+ <a href="mailto:ggreif@gmail.com">Gabor Greif</a>,
+ <a href="mailto:jstanley@cs.uiuc.edu">Joel Stanley</a>,
+ <a href="mailto:rspencer@x10sys.com">Reid Spencer</a> and
+ <a href="mailto:owen@apple.com">Owen Anderson</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="introduction">Introduction </a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This document is meant to highlight some of the important classes and
+interfaces available in the LLVM source-base. This manual is not
+intended to explain what LLVM is, how it works, and what LLVM code looks
+like. It assumes that you know the basics of LLVM and are interested
+in writing transformations or otherwise analyzing or manipulating the
+code.</p>
+
+<p>This document should get you oriented so that you can find your
+way in the continuously growing source code that makes up the LLVM
+infrastructure. Note that this manual is not intended to serve as a
+replacement for reading the source code, so if you think there should be
+a method in one of these classes to do something, but it's not listed,
+check the source. Links to the <a href="/doxygen/">doxygen</a> sources
+are provided to make this as easy as possible.</p>
+
+<p>The first section of this document describes general information that is
+useful to know when working in the LLVM infrastructure, and the second describes
+the Core LLVM classes. In the future this manual will be extended with
+information describing how to use extension libraries, such as dominator
+information, CFG traversal routines, and useful utilities like the <tt><a
+href="/doxygen/InstVisitor_8h-source.html">InstVisitor</a></tt> template.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="general">General Information</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This section contains general information that is useful if you are working
+in the LLVM source-base, but that isn't specific to any particular API.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="stl">The C++ Standard Template Library</a>
+</h3>
+
+<div>
+
+<p>LLVM makes heavy use of the C++ Standard Template Library (STL),
+perhaps much more than you are used to, or have seen before. Because of
+this, you might want to do a little background reading in the
+techniques used and capabilities of the library. There are many good
+pages that discuss the STL, and several books on the subject that you
+can get, so it will not be discussed in this document.</p>
+
+<p>Here are some useful links:</p>
+
+<ol>
+
+<li><a href="http://www.dinkumware.com/manuals/#Standard C++ Library">Dinkumware
+C++ Library reference</a> - an excellent reference for the STL and other parts
+of the standard C++ library.</li>
+
+<li><a href="http://www.tempest-sw.com/cpp/">C++ In a Nutshell</a> - This is an
+O'Reilly book in the making. It has a decent Standard Library
+Reference that rivals Dinkumware's, and is unfortunately no longer free since the
+book has been published.</li>
+
+<li><a href="http://www.parashift.com/c++-faq-lite/">C++ Frequently Asked
+Questions</a></li>
+
+<li><a href="http://www.sgi.com/tech/stl/">SGI's STL Programmer's Guide</a> -
+Contains a useful <a
+href="http://www.sgi.com/tech/stl/stl_introduction.html">Introduction to the
+STL</a>.</li>
+
+<li><a href="http://www.research.att.com/%7Ebs/C++.html">Bjarne Stroustrup's C++
+Page</a></li>
+
+<li><a href="http://64.78.49.204/">
+Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0 (even better, get
+the book).</a></li>
+
+</ol>
+
+<p>You are also encouraged to take a look at the <a
+href="CodingStandards.html">LLVM Coding Standards</a> guide which focuses on how
+to write maintainable code more than where to put your curly braces.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="stl">Other useful references</a>
+</h3>
+
+<div>
+
+<ol>
+<li><a href="http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html">Using
+static and shared libraries across platforms</a></li>
+</ol>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="apis">Important and useful LLVM APIs</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Here we highlight some LLVM APIs that are generally useful and good to
+know about when writing transformations.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="isa">The <tt>isa&lt;&gt;</tt>, <tt>cast&lt;&gt;</tt> and
+ <tt>dyn_cast&lt;&gt;</tt> templates</a>
+</h3>
+
+<div>
+
+<p>The LLVM source-base makes extensive use of a custom form of RTTI.
+These templates have many similarities to the C++ <tt>dynamic_cast&lt;&gt;</tt>
+operator, but they don't have some drawbacks (primarily stemming from
+the fact that <tt>dynamic_cast&lt;&gt;</tt> only works on classes that
+have a v-table). Because they are used so often, you must know what they
+do and how they work. All of these templates are defined in the <a
+ href="/doxygen/Casting_8h-source.html"><tt>llvm/Support/Casting.h</tt></a>
+file (note that you very rarely have to include this file directly).</p>
+
+<dl>
+ <dt><tt>isa&lt;&gt;</tt>: </dt>
+
+ <dd><p>The <tt>isa&lt;&gt;</tt> operator works exactly like the Java
+ "<tt>instanceof</tt>" operator. It returns true or false depending on whether
+ a reference or pointer points to an instance of the specified class. This can
+ be very useful for constraint checking of various sorts (example below).</p>
+ </dd>
+
+ <dt><tt>cast&lt;&gt;</tt>: </dt>
+
+ <dd><p>The <tt>cast&lt;&gt;</tt> operator is a "checked cast" operation. It
+ converts a pointer or reference from a base class to a derived class, causing
+ an assertion failure if it is not really an instance of the right type. This
+ should be used in cases where you have some information that makes you believe
+ that something is of the right type. An example of the <tt>isa&lt;&gt;</tt>
+ and <tt>cast&lt;&gt;</tt> template is:</p>
+
+<div class="doc_code">
+<pre>
+static bool isLoopInvariant(const <a href="#Value">Value</a> *V, const Loop *L) {
+ if (isa&lt;<a href="#Constant">Constant</a>&gt;(V) || isa&lt;<a href="#Argument">Argument</a>&gt;(V) || isa&lt;<a href="#GlobalValue">GlobalValue</a>&gt;(V))
+ return true;
+
+ // <i>Otherwise, it must be an instruction...</i>
+ return !L-&gt;contains(cast&lt;<a href="#Instruction">Instruction</a>&gt;(V)-&gt;getParent());
+}
+</pre>
+</div>
+
+ <p>Note that you should <b>not</b> use an <tt>isa&lt;&gt;</tt> test followed
+ by a <tt>cast&lt;&gt;</tt>, for that use the <tt>dyn_cast&lt;&gt;</tt>
+ operator.</p>
+
+ </dd>
+
+ <dt><tt>dyn_cast&lt;&gt;</tt>:</dt>
+
+ <dd><p>The <tt>dyn_cast&lt;&gt;</tt> operator is a "checking cast" operation.
+ It checks to see if the operand is of the specified type, and if so, returns a
+ pointer to it (this operator does not work with references). If the operand is
+ not of the correct type, a null pointer is returned. Thus, this works very
+ much like the <tt>dynamic_cast&lt;&gt;</tt> operator in C++, and should be
+ used in the same circumstances. Typically, the <tt>dyn_cast&lt;&gt;</tt>
+ operator is used in an <tt>if</tt> statement or some other flow control
+ statement like this:</p>
+
+<div class="doc_code">
+<pre>
+if (<a href="#AllocationInst">AllocationInst</a> *AI = dyn_cast&lt;<a href="#AllocationInst">AllocationInst</a>&gt;(Val)) {
+ // <i>...</i>
+}
+</pre>
+</div>
+
+ <p>This form of the <tt>if</tt> statement effectively combines together a call
+ to <tt>isa&lt;&gt;</tt> and a call to <tt>cast&lt;&gt;</tt> into one
+ statement, which is very convenient.</p>
+
+ <p>Note that the <tt>dyn_cast&lt;&gt;</tt> operator, like C++'s
+ <tt>dynamic_cast&lt;&gt;</tt> or Java's <tt>instanceof</tt> operator, can be
+ abused. In particular, you should not use big chained <tt>if/then/else</tt>
+ blocks to check for lots of different variants of classes. If you find
+ yourself wanting to do this, it is much cleaner and more efficient to use the
+ <tt>InstVisitor</tt> class to dispatch over the instruction type directly.</p>
+
+ </dd>
+
+ <dt><tt>cast_or_null&lt;&gt;</tt>: </dt>
+
+ <dd><p>The <tt>cast_or_null&lt;&gt;</tt> operator works just like the
+ <tt>cast&lt;&gt;</tt> operator, except that it allows for a null pointer as an
+ argument (which it then propagates). This can sometimes be useful, allowing
+ you to combine several null checks into one.</p></dd>
+
+ <dt><tt>dyn_cast_or_null&lt;&gt;</tt>: </dt>
+
+ <dd><p>The <tt>dyn_cast_or_null&lt;&gt;</tt> operator works just like the
+ <tt>dyn_cast&lt;&gt;</tt> operator, except that it allows for a null pointer
+ as an argument (which it then propagates). This can sometimes be useful,
+ allowing you to combine several null checks into one.</p></dd>
+
+</dl>
+
+<p>These five templates can be used with any classes, whether they have a
+v-table or not. To add support for these templates, you simply need to add
+<tt>classof</tt> static methods to the class you are interested casting
+to. Describing this is currently outside the scope of this document, but there
+are lots of examples in the LLVM source base.</p>
+
+</div>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="string_apis">Passing strings (the <tt>StringRef</tt>
+and <tt>Twine</tt> classes)</a>
+</h3>
+
+<div>
+
+<p>Although LLVM generally does not do much string manipulation, we do have
+several important APIs which take strings. Two important examples are the
+Value class -- which has names for instructions, functions, etc. -- and the
+StringMap class which is used extensively in LLVM and Clang.</p>
+
+<p>These are generic classes, and they need to be able to accept strings which
+may have embedded null characters. Therefore, they cannot simply take
+a <tt>const char *</tt>, and taking a <tt>const std::string&amp;</tt> requires
+clients to perform a heap allocation which is usually unnecessary. Instead,
+many LLVM APIs use a <tt>StringRef</tt> or a <tt>const Twine&amp;</tt> for
+passing strings efficiently.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="StringRef">The <tt>StringRef</tt> class</a>
+</h4>
+
+<div>
+
+<p>The <tt>StringRef</tt> data type represents a reference to a constant string
+(a character array and a length) and supports the common operations available
+on <tt>std:string</tt>, but does not require heap allocation.</p>
+
+<p>It can be implicitly constructed using a C style null-terminated string,
+an <tt>std::string</tt>, or explicitly with a character pointer and length.
+For example, the <tt>StringRef</tt> find function is declared as:</p>
+
+<pre class="doc_code">
+ iterator find(StringRef Key);
+</pre>
+
+<p>and clients can call it using any one of:</p>
+
+<pre class="doc_code">
+ Map.find("foo"); <i>// Lookup "foo"</i>
+ Map.find(std::string("bar")); <i>// Lookup "bar"</i>
+ Map.find(StringRef("\0baz", 4)); <i>// Lookup "\0baz"</i>
+</pre>
+
+<p>Similarly, APIs which need to return a string may return a <tt>StringRef</tt>
+instance, which can be used directly or converted to an <tt>std::string</tt>
+using the <tt>str</tt> member function. See
+"<tt><a href="/doxygen/classllvm_1_1StringRef_8h-source.html">llvm/ADT/StringRef.h</a></tt>"
+for more information.</p>
+
+<p>You should rarely use the <tt>StringRef</tt> class directly, because it contains
+pointers to external memory it is not generally safe to store an instance of the
+class (unless you know that the external storage will not be freed). StringRef is
+small and pervasive enough in LLVM that it should always be passed by value.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="Twine">The <tt>Twine</tt> class</a>
+</h4>
+
+<div>
+
+<p>The <tt><a href="/doxygen/classllvm_1_1Twine.html">Twine</a></tt> class is an
+efficient way for APIs to accept concatenated strings. For example, a common
+LLVM paradigm is to name one instruction based on
+the name of another instruction with a suffix, for example:</p>
+
+<div class="doc_code">
+<pre>
+ New = CmpInst::Create(<i>...</i>, SO->getName() + ".cmp");
+</pre>
+</div>
+
+<p>The <tt>Twine</tt> class is effectively a lightweight
+<a href="http://en.wikipedia.org/wiki/Rope_(computer_science)">rope</a>
+which points to temporary (stack allocated) objects. Twines can be implicitly
+constructed as the result of the plus operator applied to strings (i.e., a C
+strings, an <tt>std::string</tt>, or a <tt>StringRef</tt>). The twine delays
+the actual concatenation of strings until it is actually required, at which
+point it can be efficiently rendered directly into a character array. This
+avoids unnecessary heap allocation involved in constructing the temporary
+results of string concatenation. See
+"<tt><a href="/doxygen/Twine_8h_source.html">llvm/ADT/Twine.h</a></tt>"
+and <a href="#dss_twine">here</a> for more information.</p>
+
+<p>As with a <tt>StringRef</tt>, <tt>Twine</tt> objects point to external memory
+and should almost never be stored or mentioned directly. They are intended
+solely for use when defining a function which should be able to efficiently
+accept concatenated strings.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt> option</a>
+</h3>
+
+<div>
+
+<p>Often when working on your pass you will put a bunch of debugging printouts
+and other code into your pass. After you get it working, you want to remove
+it, but you may need it again in the future (to work out new bugs that you run
+across).</p>
+
+<p> Naturally, because of this, you don't want to delete the debug printouts,
+but you don't want them to always be noisy. A standard compromise is to comment
+them out, allowing you to enable them if you need them in the future.</p>
+
+<p>The "<tt><a href="/doxygen/Debug_8h-source.html">llvm/Support/Debug.h</a></tt>"
+file provides a macro named <tt>DEBUG()</tt> that is a much nicer solution to
+this problem. Basically, you can put arbitrary code into the argument of the
+<tt>DEBUG</tt> macro, and it is only executed if '<tt>opt</tt>' (or any other
+tool) is run with the '<tt>-debug</tt>' command line argument:</p>
+
+<div class="doc_code">
+<pre>
+DEBUG(errs() &lt;&lt; "I am here!\n");
+</pre>
+</div>
+
+<p>Then you can run your pass like this:</p>
+
+<div class="doc_code">
+<pre>
+$ opt &lt; a.bc &gt; /dev/null -mypass
+<i>&lt;no output&gt;</i>
+$ opt &lt; a.bc &gt; /dev/null -mypass -debug
+I am here!
+</pre>
+</div>
+
+<p>Using the <tt>DEBUG()</tt> macro instead of a home-brewed solution allows you
+to not have to create "yet another" command line option for the debug output for
+your pass. Note that <tt>DEBUG()</tt> macros are disabled for optimized builds,
+so they do not cause a performance impact at all (for the same reason, they
+should also not contain side-effects!).</p>
+
+<p>One additional nice thing about the <tt>DEBUG()</tt> macro is that you can
+enable or disable it directly in gdb. Just use "<tt>set DebugFlag=0</tt>" or
+"<tt>set DebugFlag=1</tt>" from the gdb if the program is running. If the
+program hasn't been started yet, you can always just run it with
+<tt>-debug</tt>.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt> and
+ the <tt>-debug-only</tt> option</a>
+</h4>
+
+<div>
+
+<p>Sometimes you may find yourself in a situation where enabling <tt>-debug</tt>
+just turns on <b>too much</b> information (such as when working on the code
+generator). If you want to enable debug information with more fine-grained
+control, you define the <tt>DEBUG_TYPE</tt> macro and the <tt>-debug</tt> only
+option as follows:</p>
+
+<div class="doc_code">
+<pre>
+#undef DEBUG_TYPE
+DEBUG(errs() &lt;&lt; "No debug type\n");
+#define DEBUG_TYPE "foo"
+DEBUG(errs() &lt;&lt; "'foo' debug type\n");
+#undef DEBUG_TYPE
+#define DEBUG_TYPE "bar"
+DEBUG(errs() &lt;&lt; "'bar' debug type\n"));
+#undef DEBUG_TYPE
+#define DEBUG_TYPE ""
+DEBUG(errs() &lt;&lt; "No debug type (2)\n");
+</pre>
+</div>
+
+<p>Then you can run your pass like this:</p>
+
+<div class="doc_code">
+<pre>
+$ opt &lt; a.bc &gt; /dev/null -mypass
+<i>&lt;no output&gt;</i>
+$ opt &lt; a.bc &gt; /dev/null -mypass -debug
+No debug type
+'foo' debug type
+'bar' debug type
+No debug type (2)
+$ opt &lt; a.bc &gt; /dev/null -mypass -debug-only=foo
+'foo' debug type
+$ opt &lt; a.bc &gt; /dev/null -mypass -debug-only=bar
+'bar' debug type
+</pre>
+</div>
+
+<p>Of course, in practice, you should only set <tt>DEBUG_TYPE</tt> at the top of
+a file, to specify the debug type for the entire module (if you do this before
+you <tt>#include "llvm/Support/Debug.h"</tt>, you don't have to insert the ugly
+<tt>#undef</tt>'s). Also, you should use names more meaningful than "foo" and
+"bar", because there is no system in place to ensure that names do not
+conflict. If two different modules use the same string, they will all be turned
+on when the name is specified. This allows, for example, all debug information
+for instruction scheduling to be enabled with <tt>-debug-type=InstrSched</tt>,
+even if the source lives in multiple files.</p>
+
+<p>The <tt>DEBUG_WITH_TYPE</tt> macro is also available for situations where you
+would like to set <tt>DEBUG_TYPE</tt>, but only for one specific <tt>DEBUG</tt>
+statement. It takes an additional first parameter, which is the type to use. For
+example, the preceding example could be written as:</p>
+
+
+<div class="doc_code">
+<pre>
+DEBUG_WITH_TYPE("", errs() &lt;&lt; "No debug type\n");
+DEBUG_WITH_TYPE("foo", errs() &lt;&lt; "'foo' debug type\n");
+DEBUG_WITH_TYPE("bar", errs() &lt;&lt; "'bar' debug type\n"));
+DEBUG_WITH_TYPE("", errs() &lt;&lt; "No debug type (2)\n");
+</pre>
+</div>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="Statistic">The <tt>Statistic</tt> class &amp; <tt>-stats</tt>
+ option</a>
+</h3>
+
+<div>
+
+<p>The "<tt><a
+href="/doxygen/Statistic_8h-source.html">llvm/ADT/Statistic.h</a></tt>" file
+provides a class named <tt>Statistic</tt> that is used as a unified way to
+keep track of what the LLVM compiler is doing and how effective various
+optimizations are. It is useful to see what optimizations are contributing to
+making a particular program run faster.</p>
+
+<p>Often you may run your pass on some big program, and you're interested to see
+how many times it makes a certain transformation. Although you can do this with
+hand inspection, or some ad-hoc method, this is a real pain and not very useful
+for big programs. Using the <tt>Statistic</tt> class makes it very easy to
+keep track of this information, and the calculated information is presented in a
+uniform manner with the rest of the passes being executed.</p>
+
+<p>There are many examples of <tt>Statistic</tt> uses, but the basics of using
+it are as follows:</p>
+
+<ol>
+ <li><p>Define your statistic like this:</p>
+
+<div class="doc_code">
+<pre>
+#define <a href="#DEBUG_TYPE">DEBUG_TYPE</a> "mypassname" <i>// This goes before any #includes.</i>
+STATISTIC(NumXForms, "The # of times I did stuff");
+</pre>
+</div>
+
+ <p>The <tt>STATISTIC</tt> macro defines a static variable, whose name is
+ specified by the first argument. The pass name is taken from the DEBUG_TYPE
+ macro, and the description is taken from the second argument. The variable
+ defined ("NumXForms" in this case) acts like an unsigned integer.</p></li>
+
+ <li><p>Whenever you make a transformation, bump the counter:</p>
+
+<div class="doc_code">
+<pre>
+++NumXForms; // <i>I did stuff!</i>
+</pre>
+</div>
+
+ </li>
+ </ol>
+
+ <p>That's all you have to do. To get '<tt>opt</tt>' to print out the
+ statistics gathered, use the '<tt>-stats</tt>' option:</p>
+
+<div class="doc_code">
+<pre>
+$ opt -stats -mypassname &lt; program.bc &gt; /dev/null
+<i>... statistics output ...</i>
+</pre>
+</div>
+
+ <p> When running <tt>opt</tt> on a C file from the SPEC benchmark
+suite, it gives a report that looks like this:</p>
+
+<div class="doc_code">
+<pre>
+ 7646 bitcodewriter - Number of normal instructions
+ 725 bitcodewriter - Number of oversized instructions
+ 129996 bitcodewriter - Number of bitcode bytes written
+ 2817 raise - Number of insts DCEd or constprop'd
+ 3213 raise - Number of cast-of-self removed
+ 5046 raise - Number of expression trees converted
+ 75 raise - Number of other getelementptr's formed
+ 138 raise - Number of load/store peepholes
+ 42 deadtypeelim - Number of unused typenames removed from symtab
+ 392 funcresolve - Number of varargs functions resolved
+ 27 globaldce - Number of global variables removed
+ 2 adce - Number of basic blocks removed
+ 134 cee - Number of branches revectored
+ 49 cee - Number of setcc instruction eliminated
+ 532 gcse - Number of loads removed
+ 2919 gcse - Number of instructions removed
+ 86 indvars - Number of canonical indvars added
+ 87 indvars - Number of aux indvars removed
+ 25 instcombine - Number of dead inst eliminate
+ 434 instcombine - Number of insts combined
+ 248 licm - Number of load insts hoisted
+ 1298 licm - Number of insts hoisted to a loop pre-header
+ 3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
+ 75 mem2reg - Number of alloca's promoted
+ 1444 cfgsimplify - Number of blocks simplified
+</pre>
+</div>
+
+<p>Obviously, with so many optimizations, having a unified framework for this
+stuff is very nice. Making your pass fit well into the framework makes it more
+maintainable and useful.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ViewGraph">Viewing graphs while debugging code</a>
+</h3>
+
+<div>
+
+<p>Several of the important data structures in LLVM are graphs: for example
+CFGs made out of LLVM <a href="#BasicBlock">BasicBlock</a>s, CFGs made out of
+LLVM <a href="CodeGenerator.html#machinebasicblock">MachineBasicBlock</a>s, and
+<a href="CodeGenerator.html#selectiondag_intro">Instruction Selection
+DAGs</a>. In many cases, while debugging various parts of the compiler, it is
+nice to instantly visualize these graphs.</p>
+
+<p>LLVM provides several callbacks that are available in a debug build to do
+exactly that. If you call the <tt>Function::viewCFG()</tt> method, for example,
+the current LLVM tool will pop up a window containing the CFG for the function
+where each basic block is a node in the graph, and each node contains the
+instructions in the block. Similarly, there also exists
+<tt>Function::viewCFGOnly()</tt> (does not include the instructions), the
+<tt>MachineFunction::viewCFG()</tt> and <tt>MachineFunction::viewCFGOnly()</tt>,
+and the <tt>SelectionDAG::viewGraph()</tt> methods. Within GDB, for example,
+you can usually use something like <tt>call DAG.viewGraph()</tt> to pop
+up a window. Alternatively, you can sprinkle calls to these functions in your
+code in places you want to debug.</p>
+
+<p>Getting this to work requires a small amount of configuration. On Unix
+systems with X11, install the <a href="http://www.graphviz.org">graphviz</a>
+toolkit, and make sure 'dot' and 'gv' are in your path. If you are running on
+Mac OS/X, download and install the Mac OS/X <a
+href="http://www.pixelglow.com/graphviz/">Graphviz program</a>, and add
+<tt>/Applications/Graphviz.app/Contents/MacOS/</tt> (or wherever you install
+it) to your path. Once in your system and path are set up, rerun the LLVM
+configure script and rebuild LLVM to enable this functionality.</p>
+
+<p><tt>SelectionDAG</tt> has been extended to make it easier to locate
+<i>interesting</i> nodes in large complex graphs. From gdb, if you
+<tt>call DAG.setGraphColor(<i>node</i>, "<i>color</i>")</tt>, then the
+next <tt>call DAG.viewGraph()</tt> would highlight the node in the
+specified color (choices of colors can be found at <a
+href="http://www.graphviz.org/doc/info/colors.html">colors</a>.) More
+complex node attributes can be provided with <tt>call
+DAG.setGraphAttrs(<i>node</i>, "<i>attributes</i>")</tt> (choices can be
+found at <a href="http://www.graphviz.org/doc/info/attrs.html">Graph
+Attributes</a>.) If you want to restart and clear all the current graph
+attributes, then you can <tt>call DAG.clearGraphAttrs()</tt>. </p>
+
+<p>Note that graph visualization features are compiled out of Release builds
+to reduce file size. This means that you need a Debug+Asserts or
+Release+Asserts build to use these features.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="datastructure">Picking the Right Data Structure for a Task</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>LLVM has a plethora of data structures in the <tt>llvm/ADT/</tt> directory,
+ and we commonly use STL data structures. This section describes the trade-offs
+ you should consider when you pick one.</p>
+
+<p>
+The first step is a choose your own adventure: do you want a sequential
+container, a set-like container, or a map-like container? The most important
+thing when choosing a container is the algorithmic properties of how you plan to
+access the container. Based on that, you should use:</p>
+
+<ul>
+<li>a <a href="#ds_map">map-like</a> container if you need efficient look-up
+ of an value based on another value. Map-like containers also support
+ efficient queries for containment (whether a key is in the map). Map-like
+ containers generally do not support efficient reverse mapping (values to
+ keys). If you need that, use two maps. Some map-like containers also
+ support efficient iteration through the keys in sorted order. Map-like
+ containers are the most expensive sort, only use them if you need one of
+ these capabilities.</li>
+
+<li>a <a href="#ds_set">set-like</a> container if you need to put a bunch of
+ stuff into a container that automatically eliminates duplicates. Some
+ set-like containers support efficient iteration through the elements in
+ sorted order. Set-like containers are more expensive than sequential
+ containers.
+</li>
+
+<li>a <a href="#ds_sequential">sequential</a> container provides
+ the most efficient way to add elements and keeps track of the order they are
+ added to the collection. They permit duplicates and support efficient
+ iteration, but do not support efficient look-up based on a key.
+</li>
+
+<li>a <a href="#ds_string">string</a> container is a specialized sequential
+ container or reference structure that is used for character or byte
+ arrays.</li>
+
+<li>a <a href="#ds_bit">bit</a> container provides an efficient way to store and
+ perform set operations on sets of numeric id's, while automatically
+ eliminating duplicates. Bit containers require a maximum of 1 bit for each
+ identifier you want to store.
+</li>
+</ul>
+
+<p>
+Once the proper category of container is determined, you can fine tune the
+memory use, constant factors, and cache behaviors of access by intelligently
+picking a member of the category. Note that constant factors and cache behavior
+can be a big deal. If you have a vector that usually only contains a few
+elements (but could contain many), for example, it's much better to use
+<a href="#dss_smallvector">SmallVector</a> than <a href="#dss_vector">vector</a>
+. Doing so avoids (relatively) expensive malloc/free calls, which dwarf the
+cost of adding the elements to the container. </p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
+</h3>
+
+<div>
+There are a variety of sequential containers available for you, based on your
+needs. Pick the first in this section that will do what you want.
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_arrayref">llvm/ADT/ArrayRef.h</a>
+</h4>
+
+<div>
+<p>The llvm::ArrayRef class is the preferred class to use in an interface that
+ accepts a sequential list of elements in memory and just reads from them. By
+ taking an ArrayRef, the API can be passed a fixed size array, an std::vector,
+ an llvm::SmallVector and anything else that is contiguous in memory.
+</p>
+</div>
+
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_fixedarrays">Fixed Size Arrays</a>
+</h4>
+
+<div>
+<p>Fixed size arrays are very simple and very fast. They are good if you know
+exactly how many elements you have, or you have a (low) upper bound on how many
+you have.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_heaparrays">Heap Allocated Arrays</a>
+</h4>
+
+<div>
+<p>Heap allocated arrays (new[] + delete[]) are also simple. They are good if
+the number of elements is variable, if you know how many elements you will need
+before the array is allocated, and if the array is usually large (if not,
+consider a <a href="#dss_smallvector">SmallVector</a>). The cost of a heap
+allocated array is the cost of the new/delete (aka malloc/free). Also note that
+if you are allocating an array of a type with a constructor, the constructor and
+destructors will be run for every element in the array (re-sizable vectors only
+construct those elements actually used).</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_tinyptrvector">"llvm/ADT/TinyPtrVector.h"</a>
+</h4>
+
+
+<div>
+<p><tt>TinyPtrVector&lt;Type&gt;</tt> is a highly specialized collection class
+that is optimized to avoid allocation in the case when a vector has zero or one
+elements. It has two major restrictions: 1) it can only hold values of pointer
+type, and 2) it cannot hold a null pointer.</p>
+
+<p>Since this container is highly specialized, it is rarely used.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_smallvector">"llvm/ADT/SmallVector.h"</a>
+</h4>
+
+<div>
+<p><tt>SmallVector&lt;Type, N&gt;</tt> is a simple class that looks and smells
+just like <tt>vector&lt;Type&gt;</tt>:
+it supports efficient iteration, lays out elements in memory order (so you can
+do pointer arithmetic between elements), supports efficient push_back/pop_back
+operations, supports efficient random access to its elements, etc.</p>
+
+<p>The advantage of SmallVector is that it allocates space for
+some number of elements (N) <b>in the object itself</b>. Because of this, if
+the SmallVector is dynamically smaller than N, no malloc is performed. This can
+be a big win in cases where the malloc/free call is far more expensive than the
+code that fiddles around with the elements.</p>
+
+<p>This is good for vectors that are "usually small" (e.g. the number of
+predecessors/successors of a block is usually less than 8). On the other hand,
+this makes the size of the SmallVector itself large, so you don't want to
+allocate lots of them (doing so will waste a lot of space). As such,
+SmallVectors are most useful when on the stack.</p>
+
+<p>SmallVector also provides a nice portable and efficient replacement for
+<tt>alloca</tt>.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_vector">&lt;vector&gt;</a>
+</h4>
+
+<div>
+<p>
+std::vector is well loved and respected. It is useful when SmallVector isn't:
+when the size of the vector is often large (thus the small optimization will
+rarely be a benefit) or if you will be allocating many instances of the vector
+itself (which would waste space for elements that aren't in the container).
+vector is also useful when interfacing with code that expects vectors :).
+</p>
+
+<p>One worthwhile note about std::vector: avoid code like this:</p>
+
+<div class="doc_code">
+<pre>
+for ( ... ) {
+ std::vector&lt;foo&gt; V;
+ // make use of V.
+}
+</pre>
+</div>
+
+<p>Instead, write this as:</p>
+
+<div class="doc_code">
+<pre>
+std::vector&lt;foo&gt; V;
+for ( ... ) {
+ // make use of V.
+ V.clear();
+}
+</pre>
+</div>
+
+<p>Doing so will save (at least) one heap allocation and free per iteration of
+the loop.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_deque">&lt;deque&gt;</a>
+</h4>
+
+<div>
+<p>std::deque is, in some senses, a generalized version of std::vector. Like
+std::vector, it provides constant time random access and other similar
+properties, but it also provides efficient access to the front of the list. It
+does not guarantee continuity of elements within memory.</p>
+
+<p>In exchange for this extra flexibility, std::deque has significantly higher
+constant factor costs than std::vector. If possible, use std::vector or
+something cheaper.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_list">&lt;list&gt;</a>
+</h4>
+
+<div>
+<p>std::list is an extremely inefficient class that is rarely useful.
+It performs a heap allocation for every element inserted into it, thus having an
+extremely high constant factor, particularly for small data types. std::list
+also only supports bidirectional iteration, not random access iteration.</p>
+
+<p>In exchange for this high cost, std::list supports efficient access to both
+ends of the list (like std::deque, but unlike std::vector or SmallVector). In
+addition, the iterator invalidation characteristics of std::list are stronger
+than that of a vector class: inserting or removing an element into the list does
+not invalidate iterator or pointers to other elements in the list.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_ilist">llvm/ADT/ilist.h</a>
+</h4>
+
+<div>
+<p><tt>ilist&lt;T&gt;</tt> implements an 'intrusive' doubly-linked list. It is
+intrusive, because it requires the element to store and provide access to the
+prev/next pointers for the list.</p>
+
+<p><tt>ilist</tt> has the same drawbacks as <tt>std::list</tt>, and additionally
+requires an <tt>ilist_traits</tt> implementation for the element type, but it
+provides some novel characteristics. In particular, it can efficiently store
+polymorphic objects, the traits class is informed when an element is inserted or
+removed from the list, and <tt>ilist</tt>s are guaranteed to support a
+constant-time splice operation.</p>
+
+<p>These properties are exactly what we want for things like
+<tt>Instruction</tt>s and basic blocks, which is why these are implemented with
+<tt>ilist</tt>s.</p>
+
+Related classes of interest are explained in the following subsections:
+ <ul>
+ <li><a href="#dss_ilist_traits">ilist_traits</a></li>
+ <li><a href="#dss_iplist">iplist</a></li>
+ <li><a href="#dss_ilist_node">llvm/ADT/ilist_node.h</a></li>
+ <li><a href="#dss_ilist_sentinel">Sentinels</a></li>
+ </ul>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_packedvector">llvm/ADT/PackedVector.h</a>
+</h4>
+
+<div>
+<p>
+Useful for storing a vector of values using only a few number of bits for each
+value. Apart from the standard operations of a vector-like container, it can
+also perform an 'or' set operation.
+</p>
+
+<p>For example:</p>
+
+<div class="doc_code">
+<pre>
+enum State {
+ None = 0x0,
+ FirstCondition = 0x1,
+ SecondCondition = 0x2,
+ Both = 0x3
+};
+
+State get() {
+ PackedVector&lt;State, 2&gt; Vec1;
+ Vec1.push_back(FirstCondition);
+
+ PackedVector&lt;State, 2&gt; Vec2;
+ Vec2.push_back(SecondCondition);
+
+ Vec1 |= Vec2;
+ return Vec1[0]; // returns 'Both'.
+}
+</pre>
+</div>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_ilist_traits">ilist_traits</a>
+</h4>
+
+<div>
+<p><tt>ilist_traits&lt;T&gt;</tt> is <tt>ilist&lt;T&gt;</tt>'s customization
+mechanism. <tt>iplist&lt;T&gt;</tt> (and consequently <tt>ilist&lt;T&gt;</tt>)
+publicly derive from this traits class.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_iplist">iplist</a>
+</h4>
+
+<div>
+<p><tt>iplist&lt;T&gt;</tt> is <tt>ilist&lt;T&gt;</tt>'s base and as such
+supports a slightly narrower interface. Notably, inserters from
+<tt>T&amp;</tt> are absent.</p>
+
+<p><tt>ilist_traits&lt;T&gt;</tt> is a public base of this class and can be
+used for a wide variety of customizations.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_ilist_node">llvm/ADT/ilist_node.h</a>
+</h4>
+
+<div>
+<p><tt>ilist_node&lt;T&gt;</tt> implements a the forward and backward links
+that are expected by the <tt>ilist&lt;T&gt;</tt> (and analogous containers)
+in the default manner.</p>
+
+<p><tt>ilist_node&lt;T&gt;</tt>s are meant to be embedded in the node type
+<tt>T</tt>, usually <tt>T</tt> publicly derives from
+<tt>ilist_node&lt;T&gt;</tt>.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_ilist_sentinel">Sentinels</a>
+</h4>
+
+<div>
+<p><tt>ilist</tt>s have another specialty that must be considered. To be a good
+citizen in the C++ ecosystem, it needs to support the standard container
+operations, such as <tt>begin</tt> and <tt>end</tt> iterators, etc. Also, the
+<tt>operator--</tt> must work correctly on the <tt>end</tt> iterator in the
+case of non-empty <tt>ilist</tt>s.</p>
+
+<p>The only sensible solution to this problem is to allocate a so-called
+<i>sentinel</i> along with the intrusive list, which serves as the <tt>end</tt>
+iterator, providing the back-link to the last element. However conforming to the
+C++ convention it is illegal to <tt>operator++</tt> beyond the sentinel and it
+also must not be dereferenced.</p>
+
+<p>These constraints allow for some implementation freedom to the <tt>ilist</tt>
+how to allocate and store the sentinel. The corresponding policy is dictated
+by <tt>ilist_traits&lt;T&gt;</tt>. By default a <tt>T</tt> gets heap-allocated
+whenever the need for a sentinel arises.</p>
+
+<p>While the default policy is sufficient in most cases, it may break down when
+<tt>T</tt> does not provide a default constructor. Also, in the case of many
+instances of <tt>ilist</tt>s, the memory overhead of the associated sentinels
+is wasted. To alleviate the situation with numerous and voluminous
+<tt>T</tt>-sentinels, sometimes a trick is employed, leading to <i>ghostly
+sentinels</i>.</p>
+
+<p>Ghostly sentinels are obtained by specially-crafted <tt>ilist_traits&lt;T&gt;</tt>
+which superpose the sentinel with the <tt>ilist</tt> instance in memory. Pointer
+arithmetic is used to obtain the sentinel, which is relative to the
+<tt>ilist</tt>'s <tt>this</tt> pointer. The <tt>ilist</tt> is augmented by an
+extra pointer, which serves as the back-link of the sentinel. This is the only
+field in the ghostly sentinel which can be legally accessed.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_other">Other Sequential Container options</a>
+</h4>
+
+<div>
+<p>Other STL containers are available, such as std::string.</p>
+
+<p>There are also various STL adapter classes such as std::queue,
+std::priority_queue, std::stack, etc. These provide simplified access to an
+underlying container but don't affect the cost of the container itself.</p>
+
+</div>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ds_string">String-like containers</a>
+</h3>
+
+<div>
+
+<p>
+There are a variety of ways to pass around and use strings in C and C++, and
+LLVM adds a few new options to choose from. Pick the first option on this list
+that will do what you need, they are ordered according to their relative cost.
+</p>
+<p>
+Note that is is generally preferred to <em>not</em> pass strings around as
+"<tt>const char*</tt>"'s. These have a number of problems, including the fact
+that they cannot represent embedded nul ("\0") characters, and do not have a
+length available efficiently. The general replacement for '<tt>const
+char*</tt>' is StringRef.
+</p>
+
+<p>For more information on choosing string containers for APIs, please see
+<a href="#string_apis">Passing strings</a>.</p>
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_stringref">llvm/ADT/StringRef.h</a>
+</h4>
+
+<div>
+<p>
+The StringRef class is a simple value class that contains a pointer to a
+character and a length, and is quite related to the <a
+href="#dss_arrayref">ArrayRef</a> class (but specialized for arrays of
+characters). Because StringRef carries a length with it, it safely handles
+strings with embedded nul characters in it, getting the length does not require
+a strlen call, and it even has very convenient APIs for slicing and dicing the
+character range that it represents.
+</p>
+
+<p>
+StringRef is ideal for passing simple strings around that are known to be live,
+either because they are C string literals, std::string, a C array, or a
+SmallVector. Each of these cases has an efficient implicit conversion to
+StringRef, which doesn't result in a dynamic strlen being executed.
+</p>
+
+<p>StringRef has a few major limitations which make more powerful string
+containers useful:</p>
+
+<ol>
+<li>You cannot directly convert a StringRef to a 'const char*' because there is
+no way to add a trailing nul (unlike the .c_str() method on various stronger
+classes).</li>
+
+
+<li>StringRef doesn't own or keep alive the underlying string bytes.
+As such it can easily lead to dangling pointers, and is not suitable for
+embedding in datastructures in most cases (instead, use an std::string or
+something like that).</li>
+
+<li>For the same reason, StringRef cannot be used as the return value of a
+method if the method "computes" the result string. Instead, use
+std::string.</li>
+
+<li>StringRef's do not allow you to mutate the pointed-to string bytes and it
+doesn't allow you to insert or remove bytes from the range. For editing
+operations like this, it interoperates with the <a
+href="#dss_twine">Twine</a> class.</li>
+</ol>
+
+<p>Because of its strengths and limitations, it is very common for a function to
+take a StringRef and for a method on an object to return a StringRef that
+points into some string that it owns.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_twine">llvm/ADT/Twine.h</a>
+</h4>
+
+<div>
+ <p>
+ The Twine class is used as an intermediary datatype for APIs that want to take
+ a string that can be constructed inline with a series of concatenations.
+ Twine works by forming recursive instances of the Twine datatype (a simple
+ value object) on the stack as temporary objects, linking them together into a
+ tree which is then linearized when the Twine is consumed. Twine is only safe
+ to use as the argument to a function, and should always be a const reference,
+ e.g.:
+ </p>
+
+ <pre>
+ void foo(const Twine &amp;T);
+ ...
+ StringRef X = ...
+ unsigned i = ...
+ foo(X + "." + Twine(i));
+ </pre>
+
+ <p>This example forms a string like "blarg.42" by concatenating the values
+ together, and does not form intermediate strings containing "blarg" or
+ "blarg.".
+ </p>
+
+ <p>Because Twine is constructed with temporary objects on the stack, and
+ because these instances are destroyed at the end of the current statement,
+ it is an inherently dangerous API. For example, this simple variant contains
+ undefined behavior and will probably crash:</p>
+
+ <pre>
+ void foo(const Twine &amp;T);
+ ...
+ StringRef X = ...
+ unsigned i = ...
+ const Twine &amp;Tmp = X + "." + Twine(i);
+ foo(Tmp);
+ </pre>
+
+ <p>... because the temporaries are destroyed before the call. That said,
+ Twine's are much more efficient than intermediate std::string temporaries, and
+ they work really well with StringRef. Just be aware of their limitations.</p>
+
+</div>
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_smallstring">llvm/ADT/SmallString.h</a>
+</h4>
+
+<div>
+
+<p>SmallString is a subclass of <a href="#dss_smallvector">SmallVector</a> that
+adds some convenience APIs like += that takes StringRef's. SmallString avoids
+allocating memory in the case when the preallocated space is enough to hold its
+data, and it calls back to general heap allocation when required. Since it owns
+its data, it is very safe to use and supports full mutation of the string.</p>
+
+<p>Like SmallVector's, the big downside to SmallString is their sizeof. While
+they are optimized for small strings, they themselves are not particularly
+small. This means that they work great for temporary scratch buffers on the
+stack, but should not generally be put into the heap: it is very rare to
+see a SmallString as the member of a frequently-allocated heap data structure
+or returned by-value.
+</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_stdstring">std::string</a>
+</h4>
+
+<div>
+
+ <p>The standard C++ std::string class is a very general class that (like
+ SmallString) owns its underlying data. sizeof(std::string) is very reasonable
+ so it can be embedded into heap data structures and returned by-value.
+ On the other hand, std::string is highly inefficient for inline editing (e.g.
+ concatenating a bunch of stuff together) and because it is provided by the
+ standard library, its performance characteristics depend a lot of the host
+ standard library (e.g. libc++ and MSVC provide a highly optimized string
+ class, GCC contains a really slow implementation).
+ </p>
+
+ <p>The major disadvantage of std::string is that almost every operation that
+ makes them larger can allocate memory, which is slow. As such, it is better
+ to use SmallVector or Twine as a scratch buffer, but then use std::string to
+ persist the result.</p>
+
+
+</div>
+
+<!-- end of strings -->
+</div>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
+</h3>
+
+<div>
+
+<p>Set-like containers are useful when you need to canonicalize multiple values
+into a single representation. There are several different choices for how to do
+this, providing various trade-offs.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_sortedvectorset">A sorted 'vector'</a>
+</h4>
+
+<div>
+
+<p>If you intend to insert a lot of elements, then do a lot of queries, a
+great approach is to use a vector (or other sequential container) with
+std::sort+std::unique to remove duplicates. This approach works really well if
+your usage pattern has these two distinct phases (insert then query), and can be
+coupled with a good choice of <a href="#ds_sequential">sequential container</a>.
+</p>
+
+<p>
+This combination provides the several nice properties: the result data is
+contiguous in memory (good for cache locality), has few allocations, is easy to
+address (iterators in the final vector are just indices or pointers), and can be
+efficiently queried with a standard binary or radix search.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_smallset">"llvm/ADT/SmallSet.h"</a>
+</h4>
+
+<div>
+
+<p>If you have a set-like data structure that is usually small and whose elements
+are reasonably small, a <tt>SmallSet&lt;Type, N&gt;</tt> is a good choice. This set
+has space for N elements in place (thus, if the set is dynamically smaller than
+N, no malloc traffic is required) and accesses them with a simple linear search.
+When the set grows beyond 'N' elements, it allocates a more expensive representation that
+guarantees efficient access (for most types, it falls back to std::set, but for
+pointers it uses something far better, <a
+href="#dss_smallptrset">SmallPtrSet</a>).</p>
+
+<p>The magic of this class is that it handles small sets extremely efficiently,
+but gracefully handles extremely large sets without loss of efficiency. The
+drawback is that the interface is quite small: it supports insertion, queries
+and erasing, but does not support iteration.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_smallptrset">"llvm/ADT/SmallPtrSet.h"</a>
+</h4>
+
+<div>
+
+<p>SmallPtrSet has all the advantages of <tt>SmallSet</tt> (and a <tt>SmallSet</tt> of pointers is
+transparently implemented with a <tt>SmallPtrSet</tt>), but also supports iterators. If
+more than 'N' insertions are performed, a single quadratically
+probed hash table is allocated and grows as needed, providing extremely
+efficient access (constant time insertion/deleting/queries with low constant
+factors) and is very stingy with malloc traffic.</p>
+
+<p>Note that, unlike <tt>std::set</tt>, the iterators of <tt>SmallPtrSet</tt> are invalidated
+whenever an insertion occurs. Also, the values visited by the iterators are not
+visited in sorted order.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_denseset">"llvm/ADT/DenseSet.h"</a>
+</h4>
+
+<div>
+
+<p>
+DenseSet is a simple quadratically probed hash table. It excels at supporting
+small values: it uses a single allocation to hold all of the pairs that
+are currently inserted in the set. DenseSet is a great way to unique small
+values that are not simple pointers (use <a
+href="#dss_smallptrset">SmallPtrSet</a> for pointers). Note that DenseSet has
+the same requirements for the value type that <a
+href="#dss_densemap">DenseMap</a> has.
+</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_sparseset">"llvm/ADT/SparseSet.h"</a>
+</h4>
+
+<div>
+
+<p>SparseSet holds a small number of objects identified by unsigned keys of
+moderate size. It uses a lot of memory, but provides operations that are
+almost as fast as a vector. Typical keys are physical registers, virtual
+registers, or numbered basic blocks.</p>
+
+<p>SparseSet is useful for algorithms that need very fast clear/find/insert/erase
+and fast iteration over small sets. It is not intended for building composite
+data structures.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a>
+</h4>
+
+<div>
+
+<p>
+FoldingSet is an aggregate class that is really good at uniquing
+expensive-to-create or polymorphic objects. It is a combination of a chained
+hash table with intrusive links (uniqued objects are required to inherit from
+FoldingSetNode) that uses <a href="#dss_smallvector">SmallVector</a> as part of
+its ID process.</p>
+
+<p>Consider a case where you want to implement a "getOrCreateFoo" method for
+a complex object (for example, a node in the code generator). The client has a
+description of *what* it wants to generate (it knows the opcode and all the
+operands), but we don't want to 'new' a node, then try inserting it into a set
+only to find out it already exists, at which point we would have to delete it
+and return the node that already exists.
+</p>
+
+<p>To support this style of client, FoldingSet perform a query with a
+FoldingSetNodeID (which wraps SmallVector) that can be used to describe the
+element that we want to query for. The query either returns the element
+matching the ID or it returns an opaque ID that indicates where insertion should
+take place. Construction of the ID usually does not require heap traffic.</p>
+
+<p>Because FoldingSet uses intrusive links, it can support polymorphic objects
+in the set (for example, you can have SDNode instances mixed with LoadSDNodes).
+Because the elements are individually allocated, pointers to the elements are
+stable: inserting or removing elements does not invalidate any pointers to other
+elements.
+</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_set">&lt;set&gt;</a>
+</h4>
+
+<div>
+
+<p><tt>std::set</tt> is a reasonable all-around set class, which is decent at
+many things but great at nothing. std::set allocates memory for each element
+inserted (thus it is very malloc intensive) and typically stores three pointers
+per element in the set (thus adding a large amount of per-element space
+overhead). It offers guaranteed log(n) performance, which is not particularly
+fast from a complexity standpoint (particularly if the elements of the set are
+expensive to compare, like strings), and has extremely high constant factors for
+lookup, insertion and removal.</p>
+
+<p>The advantages of std::set are that its iterators are stable (deleting or
+inserting an element from the set does not affect iterators or pointers to other
+elements) and that iteration over the set is guaranteed to be in sorted order.
+If the elements in the set are large, then the relative overhead of the pointers
+and malloc traffic is not a big deal, but if the elements of the set are small,
+std::set is almost never a good choice.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_setvector">"llvm/ADT/SetVector.h"</a>
+</h4>
+
+<div>
+<p>LLVM's SetVector&lt;Type&gt; is an adapter class that combines your choice of
+a set-like container along with a <a href="#ds_sequential">Sequential
+Container</a>. The important property
+that this provides is efficient insertion with uniquing (duplicate elements are
+ignored) with iteration support. It implements this by inserting elements into
+both a set-like container and the sequential container, using the set-like
+container for uniquing and the sequential container for iteration.
+</p>
+
+<p>The difference between SetVector and other sets is that the order of
+iteration is guaranteed to match the order of insertion into the SetVector.
+This property is really important for things like sets of pointers. Because
+pointer values are non-deterministic (e.g. vary across runs of the program on
+different machines), iterating over the pointers in the set will
+not be in a well-defined order.</p>
+
+<p>
+The drawback of SetVector is that it requires twice as much space as a normal
+set and has the sum of constant factors from the set-like container and the
+sequential container that it uses. Use it *only* if you need to iterate over
+the elements in a deterministic order. SetVector is also expensive to delete
+elements out of (linear time), unless you use it's "pop_back" method, which is
+faster.
+</p>
+
+<p><tt>SetVector</tt> is an adapter class that defaults to
+ using <tt>std::vector</tt> and a size 16 <tt>SmallSet</tt> for the underlying
+ containers, so it is quite expensive. However,
+ <tt>"llvm/ADT/SetVector.h"</tt> also provides a <tt>SmallSetVector</tt>
+ class, which defaults to using a <tt>SmallVector</tt> and <tt>SmallSet</tt>
+ of a specified size. If you use this, and if your sets are dynamically
+ smaller than <tt>N</tt>, you will save a lot of heap traffic.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_uniquevector">"llvm/ADT/UniqueVector.h"</a>
+</h4>
+
+<div>
+
+<p>
+UniqueVector is similar to <a href="#dss_setvector">SetVector</a>, but it
+retains a unique ID for each element inserted into the set. It internally
+contains a map and a vector, and it assigns a unique ID for each value inserted
+into the set.</p>
+
+<p>UniqueVector is very expensive: its cost is the sum of the cost of
+maintaining both the map and vector, it has high complexity, high constant
+factors, and produces a lot of malloc traffic. It should be avoided.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_immutableset">"llvm/ADT/ImmutableSet.h"</a>
+</h4>
+
+<div>
+
+<p>
+ImmutableSet is an immutable (functional) set implementation based on an AVL
+tree.
+Adding or removing elements is done through a Factory object and results in the
+creation of a new ImmutableSet object.
+If an ImmutableSet already exists with the given contents, then the existing one
+is returned; equality is compared with a FoldingSetNodeID.
+The time and space complexity of add or remove operations is logarithmic in the
+size of the original set.
+
+<p>
+There is no method for returning an element of the set, you can only check for
+membership.
+
+</div>
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_otherset">Other Set-Like Container Options</a>
+</h4>
+
+<div>
+
+<p>
+The STL provides several other options, such as std::multiset and the various
+"hash_set" like containers (whether from C++ TR1 or from the SGI library). We
+never use hash_set and unordered_set because they are generally very expensive
+(each insertion requires a malloc) and very non-portable.
+</p>
+
+<p>std::multiset is useful if you're not interested in elimination of
+duplicates, but has all the drawbacks of std::set. A sorted vector (where you
+don't delete duplicate entries) or some other approach is almost always
+better.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
+</h3>
+
+<div>
+Map-like containers are useful when you want to associate data to a key. As
+usual, there are a lot of different ways to do this. :)
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_sortedvectormap">A sorted 'vector'</a>
+</h4>
+
+<div>
+
+<p>
+If your usage pattern follows a strict insert-then-query approach, you can
+trivially use the same approach as <a href="#dss_sortedvectorset">sorted vectors
+for set-like containers</a>. The only difference is that your query function
+(which uses std::lower_bound to get efficient log(n) lookup) should only compare
+the key, not both the key and value. This yields the same advantages as sorted
+vectors for sets.
+</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_stringmap">"llvm/ADT/StringMap.h"</a>
+</h4>
+
+<div>
+
+<p>
+Strings are commonly used as keys in maps, and they are difficult to support
+efficiently: they are variable length, inefficient to hash and compare when
+long, expensive to copy, etc. StringMap is a specialized container designed to
+cope with these issues. It supports mapping an arbitrary range of bytes to an
+arbitrary other object.</p>
+
+<p>The StringMap implementation uses a quadratically-probed hash table, where
+the buckets store a pointer to the heap allocated entries (and some other
+stuff). The entries in the map must be heap allocated because the strings are
+variable length. The string data (key) and the element object (value) are
+stored in the same allocation with the string data immediately after the element
+object. This container guarantees the "<tt>(char*)(&amp;Value+1)</tt>" points
+to the key string for a value.</p>
+
+<p>The StringMap is very fast for several reasons: quadratic probing is very
+cache efficient for lookups, the hash value of strings in buckets is not
+recomputed when looking up an element, StringMap rarely has to touch the
+memory for unrelated objects when looking up a value (even when hash collisions
+happen), hash table growth does not recompute the hash values for strings
+already in the table, and each pair in the map is store in a single allocation
+(the string data is stored in the same allocation as the Value of a pair).</p>
+
+<p>StringMap also provides query methods that take byte ranges, so it only ever
+copies a string if a value is inserted into the table.</p>
+
+<p>StringMap iteratation order, however, is not guaranteed to be deterministic,
+so any uses which require that should instead use a std::map.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_indexedmap">"llvm/ADT/IndexedMap.h"</a>
+</h4>
+
+<div>
+<p>
+IndexedMap is a specialized container for mapping small dense integers (or
+values that can be mapped to small dense integers) to some other type. It is
+internally implemented as a vector with a mapping function that maps the keys to
+the dense integer range.
+</p>
+
+<p>
+This is useful for cases like virtual registers in the LLVM code generator: they
+have a dense mapping that is offset by a compile-time constant (the first
+virtual register ID).</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_densemap">"llvm/ADT/DenseMap.h"</a>
+</h4>
+
+<div>
+
+<p>
+DenseMap is a simple quadratically probed hash table. It excels at supporting
+small keys and values: it uses a single allocation to hold all of the pairs that
+are currently inserted in the map. DenseMap is a great way to map pointers to
+pointers, or map other small types to each other.
+</p>
+
+<p>
+There are several aspects of DenseMap that you should be aware of, however. The
+iterators in a DenseMap are invalidated whenever an insertion occurs, unlike
+map. Also, because DenseMap allocates space for a large number of key/value
+pairs (it starts with 64 by default), it will waste a lot of space if your keys
+or values are large. Finally, you must implement a partial specialization of
+DenseMapInfo for the key that you want, if it isn't already supported. This
+is required to tell DenseMap about two special marker values (which can never be
+inserted into the map) that it needs internally.</p>
+
+<p>
+DenseMap's find_as() method supports lookup operations using an alternate key
+type. This is useful in cases where the normal key type is expensive to
+construct, but cheap to compare against. The DenseMapInfo is responsible for
+defining the appropriate comparison and hashing methods for each alternate
+key type used.
+</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_valuemap">"llvm/ADT/ValueMap.h"</a>
+</h4>
+
+<div>
+
+<p>
+ValueMap is a wrapper around a <a href="#dss_densemap">DenseMap</a> mapping
+Value*s (or subclasses) to another type. When a Value is deleted or RAUW'ed,
+ValueMap will update itself so the new version of the key is mapped to the same
+value, just as if the key were a WeakVH. You can configure exactly how this
+happens, and what else happens on these two events, by passing
+a <code>Config</code> parameter to the ValueMap template.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_intervalmap">"llvm/ADT/IntervalMap.h"</a>
+</h4>
+
+<div>
+
+<p> IntervalMap is a compact map for small keys and values. It maps key
+intervals instead of single keys, and it will automatically coalesce adjacent
+intervals. When then map only contains a few intervals, they are stored in the
+map object itself to avoid allocations.</p>
+
+<p> The IntervalMap iterators are quite big, so they should not be passed around
+as STL iterators. The heavyweight iterators allow a smaller data structure.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_map">&lt;map&gt;</a>
+</h4>
+
+<div>
+
+<p>
+std::map has similar characteristics to <a href="#dss_set">std::set</a>: it uses
+a single allocation per pair inserted into the map, it offers log(n) lookup with
+an extremely large constant factor, imposes a space penalty of 3 pointers per
+pair in the map, etc.</p>
+
+<p>std::map is most useful when your keys or values are very large, if you need
+to iterate over the collection in sorted order, or if you need stable iterators
+into the map (i.e. they don't get invalidated if an insertion or deletion of
+another element takes place).</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_inteqclasses">"llvm/ADT/IntEqClasses.h"</a>
+</h4>
+
+<div>
+
+<p>IntEqClasses provides a compact representation of equivalence classes of
+small integers. Initially, each integer in the range 0..n-1 has its own
+equivalence class. Classes can be joined by passing two class representatives to
+the join(a, b) method. Two integers are in the same class when findLeader()
+returns the same representative.</p>
+
+<p>Once all equivalence classes are formed, the map can be compressed so each
+integer 0..n-1 maps to an equivalence class number in the range 0..m-1, where m
+is the total number of equivalence classes. The map must be uncompressed before
+it can be edited again.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_immutablemap">"llvm/ADT/ImmutableMap.h"</a>
+</h4>
+
+<div>
+
+<p>
+ImmutableMap is an immutable (functional) map implementation based on an AVL
+tree.
+Adding or removing elements is done through a Factory object and results in the
+creation of a new ImmutableMap object.
+If an ImmutableMap already exists with the given key set, then the existing one
+is returned; equality is compared with a FoldingSetNodeID.
+The time and space complexity of add or remove operations is logarithmic in the
+size of the original map.
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_othermap">Other Map-Like Container Options</a>
+</h4>
+
+<div>
+
+<p>
+The STL provides several other options, such as std::multimap and the various
+"hash_map" like containers (whether from C++ TR1 or from the SGI library). We
+never use hash_set and unordered_set because they are generally very expensive
+(each insertion requires a malloc) and very non-portable.</p>
+
+<p>std::multimap is useful if you want to map a key to multiple values, but has
+all the drawbacks of std::map. A sorted vector or some other approach is almost
+always better.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ds_bit">Bit storage containers (BitVector, SparseBitVector)</a>
+</h3>
+
+<div>
+<p>Unlike the other containers, there are only two bit storage containers, and
+choosing when to use each is relatively straightforward.</p>
+
+<p>One additional option is
+<tt>std::vector&lt;bool&gt;</tt>: we discourage its use for two reasons 1) the
+implementation in many common compilers (e.g. commonly available versions of
+GCC) is extremely inefficient and 2) the C++ standards committee is likely to
+deprecate this container and/or change it significantly somehow. In any case,
+please don't use it.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_bitvector">BitVector</a>
+</h4>
+
+<div>
+<p> The BitVector container provides a dynamic size set of bits for manipulation.
+It supports individual bit setting/testing, as well as set operations. The set
+operations take time O(size of bitvector), but operations are performed one word
+at a time, instead of one bit at a time. This makes the BitVector very fast for
+set operations compared to other containers. Use the BitVector when you expect
+the number of set bits to be high (IE a dense set).
+</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_smallbitvector">SmallBitVector</a>
+</h4>
+
+<div>
+<p> The SmallBitVector container provides the same interface as BitVector, but
+it is optimized for the case where only a small number of bits, less than
+25 or so, are needed. It also transparently supports larger bit counts, but
+slightly less efficiently than a plain BitVector, so SmallBitVector should
+only be used when larger counts are rare.
+</p>
+
+<p>
+At this time, SmallBitVector does not support set operations (and, or, xor),
+and its operator[] does not provide an assignable lvalue.
+</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="dss_sparsebitvector">SparseBitVector</a>
+</h4>
+
+<div>
+<p> The SparseBitVector container is much like BitVector, with one major
+difference: Only the bits that are set, are stored. This makes the
+SparseBitVector much more space efficient than BitVector when the set is sparse,
+as well as making set operations O(number of set bits) instead of O(size of
+universe). The downside to the SparseBitVector is that setting and testing of random bits is O(N), and on large SparseBitVectors, this can be slower than BitVector. In our implementation, setting or testing bits in sorted order
+(either forwards or reverse) is O(1) worst case. Testing and setting bits within 128 bits (depends on size) of the current bit is also O(1). As a general statement, testing/setting bits in a SparseBitVector is O(distance away from last set bit).
+</p>
+</div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="common">Helpful Hints for Common Operations</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This section describes how to perform some very simple transformations of
+LLVM code. This is meant to give examples of common idioms used, showing the
+practical side of LLVM transformations. <p> Because this is a "how-to" section,
+you should also read about the main classes that you will be working with. The
+<a href="#coreclasses">Core LLVM Class Hierarchy Reference</a> contains details
+and descriptions of the main classes that you should know about.</p>
+
+<!-- NOTE: this section should be heavy on example code -->
+<!-- ======================================================================= -->
+<h3>
+ <a name="inspection">Basic Inspection and Traversal Routines</a>
+</h3>
+
+<div>
+
+<p>The LLVM compiler infrastructure have many different data structures that may
+be traversed. Following the example of the C++ standard template library, the
+techniques used to traverse these various data structures are all basically the
+same. For a enumerable sequence of values, the <tt>XXXbegin()</tt> function (or
+method) returns an iterator to the start of the sequence, the <tt>XXXend()</tt>
+function returns an iterator pointing to one past the last valid element of the
+sequence, and there is some <tt>XXXiterator</tt> data type that is common
+between the two operations.</p>
+
+<p>Because the pattern for iteration is common across many different aspects of
+the program representation, the standard template library algorithms may be used
+on them, and it is easier to remember how to iterate. First we show a few common
+examples of the data structures that need to be traversed. Other data
+structures are traversed in very similar ways.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="iterate_function">Iterating over the </a><a
+ href="#BasicBlock"><tt>BasicBlock</tt></a>s in a <a
+ href="#Function"><tt>Function</tt></a>
+</h4>
+
+<div>
+
+<p>It's quite common to have a <tt>Function</tt> instance that you'd like to
+transform in some way; in particular, you'd like to manipulate its
+<tt>BasicBlock</tt>s. To facilitate this, you'll need to iterate over all of
+the <tt>BasicBlock</tt>s that constitute the <tt>Function</tt>. The following is
+an example that prints the name of a <tt>BasicBlock</tt> and the number of
+<tt>Instruction</tt>s it contains:</p>
+
+<div class="doc_code">
+<pre>
+// <i>func is a pointer to a Function instance</i>
+for (Function::iterator i = func-&gt;begin(), e = func-&gt;end(); i != e; ++i)
+ // <i>Print out the name of the basic block if it has one, and then the</i>
+ // <i>number of instructions that it contains</i>
+ errs() &lt;&lt; "Basic block (name=" &lt;&lt; i-&gt;getName() &lt;&lt; ") has "
+ &lt;&lt; i-&gt;size() &lt;&lt; " instructions.\n";
+</pre>
+</div>
+
+<p>Note that i can be used as if it were a pointer for the purposes of
+invoking member functions of the <tt>Instruction</tt> class. This is
+because the indirection operator is overloaded for the iterator
+classes. In the above code, the expression <tt>i-&gt;size()</tt> is
+exactly equivalent to <tt>(*i).size()</tt> just like you'd expect.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="iterate_basicblock">Iterating over the </a><a
+ href="#Instruction"><tt>Instruction</tt></a>s in a <a
+ href="#BasicBlock"><tt>BasicBlock</tt></a>
+</h4>
+
+<div>
+
+<p>Just like when dealing with <tt>BasicBlock</tt>s in <tt>Function</tt>s, it's
+easy to iterate over the individual instructions that make up
+<tt>BasicBlock</tt>s. Here's a code snippet that prints out each instruction in
+a <tt>BasicBlock</tt>:</p>
+
+<div class="doc_code">
+<pre>
+// <i>blk is a pointer to a BasicBlock instance</i>
+for (BasicBlock::iterator i = blk-&gt;begin(), e = blk-&gt;end(); i != e; ++i)
+ // <i>The next statement works since operator&lt;&lt;(ostream&amp;,...)</i>
+ // <i>is overloaded for Instruction&amp;</i>
+ errs() &lt;&lt; *i &lt;&lt; "\n";
+</pre>
+</div>
+
+<p>However, this isn't really the best way to print out the contents of a
+<tt>BasicBlock</tt>! Since the ostream operators are overloaded for virtually
+anything you'll care about, you could have just invoked the print routine on the
+basic block itself: <tt>errs() &lt;&lt; *blk &lt;&lt; "\n";</tt>.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="iterate_institer">Iterating over the </a><a
+ href="#Instruction"><tt>Instruction</tt></a>s in a <a
+ href="#Function"><tt>Function</tt></a>
+</h4>
+
+<div>
+
+<p>If you're finding that you commonly iterate over a <tt>Function</tt>'s
+<tt>BasicBlock</tt>s and then that <tt>BasicBlock</tt>'s <tt>Instruction</tt>s,
+<tt>InstIterator</tt> should be used instead. You'll need to include <a
+href="/doxygen/InstIterator_8h-source.html"><tt>llvm/Support/InstIterator.h</tt></a>,
+and then instantiate <tt>InstIterator</tt>s explicitly in your code. Here's a
+small example that shows how to dump all instructions in a function to the standard error stream:<p>
+
+<div class="doc_code">
+<pre>
+#include "<a href="/doxygen/InstIterator_8h-source.html">llvm/Support/InstIterator.h</a>"
+
+// <i>F is a pointer to a Function instance</i>
+for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
+ errs() &lt;&lt; *I &lt;&lt; "\n";
+</pre>
+</div>
+
+<p>Easy, isn't it? You can also use <tt>InstIterator</tt>s to fill a
+work list with its initial contents. For example, if you wanted to
+initialize a work list to contain all instructions in a <tt>Function</tt>
+F, all you would need to do is something like:</p>
+
+<div class="doc_code">
+<pre>
+std::set&lt;Instruction*&gt; worklist;
+// or better yet, SmallPtrSet&lt;Instruction*, 64&gt; worklist;
+
+for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
+ worklist.insert(&amp;*I);
+</pre>
+</div>
+
+<p>The STL set <tt>worklist</tt> would now contain all instructions in the
+<tt>Function</tt> pointed to by F.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="iterate_convert">Turning an iterator into a class pointer (and
+ vice-versa)</a>
+</h4>
+
+<div>
+
+<p>Sometimes, it'll be useful to grab a reference (or pointer) to a class
+instance when all you've got at hand is an iterator. Well, extracting
+a reference or a pointer from an iterator is very straight-forward.
+Assuming that <tt>i</tt> is a <tt>BasicBlock::iterator</tt> and <tt>j</tt>
+is a <tt>BasicBlock::const_iterator</tt>:</p>
+
+<div class="doc_code">
+<pre>
+Instruction&amp; inst = *i; // <i>Grab reference to instruction reference</i>
+Instruction* pinst = &amp;*i; // <i>Grab pointer to instruction reference</i>
+const Instruction&amp; inst = *j;
+</pre>
+</div>
+
+<p>However, the iterators you'll be working with in the LLVM framework are
+special: they will automatically convert to a ptr-to-instance type whenever they
+need to. Instead of dereferencing the iterator and then taking the address of
+the result, you can simply assign the iterator to the proper pointer type and
+you get the dereference and address-of operation as a result of the assignment
+(behind the scenes, this is a result of overloading casting mechanisms). Thus
+the last line of the last example,</p>
+
+<div class="doc_code">
+<pre>
+Instruction *pinst = &amp;*i;
+</pre>
+</div>
+
+<p>is semantically equivalent to</p>
+
+<div class="doc_code">
+<pre>
+Instruction *pinst = i;
+</pre>
+</div>
+
+<p>It's also possible to turn a class pointer into the corresponding iterator,
+and this is a constant time operation (very efficient). The following code
+snippet illustrates use of the conversion constructors provided by LLVM
+iterators. By using these, you can explicitly grab the iterator of something
+without actually obtaining it via iteration over some structure:</p>
+
+<div class="doc_code">
+<pre>
+void printNextInstruction(Instruction* inst) {
+ BasicBlock::iterator it(inst);
+ ++it; // <i>After this line, it refers to the instruction after *inst</i>
+ if (it != inst-&gt;getParent()-&gt;end()) errs() &lt;&lt; *it &lt;&lt; "\n";
+}
+</pre>
+</div>
+
+<p>Unfortunately, these implicit conversions come at a cost; they prevent
+these iterators from conforming to standard iterator conventions, and thus
+from being usable with standard algorithms and containers. For example, they
+prevent the following code, where <tt>B</tt> is a <tt>BasicBlock</tt>,
+from compiling:</p>
+
+<div class="doc_code">
+<pre>
+ llvm::SmallVector&lt;llvm::Instruction *, 16&gt;(B-&gt;begin(), B-&gt;end());
+</pre>
+</div>
+
+<p>Because of this, these implicit conversions may be removed some day,
+and <tt>operator*</tt> changed to return a pointer instead of a reference.</p>
+
+</div>
+
+<!--_______________________________________________________________________-->
+<h4>
+ <a name="iterate_complex">Finding call sites: a slightly more complex
+ example</a>
+</h4>
+
+<div>
+
+<p>Say that you're writing a FunctionPass and would like to count all the
+locations in the entire module (that is, across every <tt>Function</tt>) where a
+certain function (i.e., some <tt>Function</tt>*) is already in scope. As you'll
+learn later, you may want to use an <tt>InstVisitor</tt> to accomplish this in a
+much more straight-forward manner, but this example will allow us to explore how
+you'd do it if you didn't have <tt>InstVisitor</tt> around. In pseudo-code, this
+is what we want to do:</p>
+
+<div class="doc_code">
+<pre>
+initialize callCounter to zero
+for each Function f in the Module
+ for each BasicBlock b in f
+ for each Instruction i in b
+ if (i is a CallInst and calls the given function)
+ increment callCounter
+</pre>
+</div>
+
+<p>And the actual code is (remember, because we're writing a
+<tt>FunctionPass</tt>, our <tt>FunctionPass</tt>-derived class simply has to
+override the <tt>runOnFunction</tt> method):</p>
+
+<div class="doc_code">
+<pre>
+Function* targetFunc = ...;
+
+class OurFunctionPass : public FunctionPass {
+ public:
+ OurFunctionPass(): callCounter(0) { }
+
+ virtual runOnFunction(Function&amp; F) {
+ for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
+ for (BasicBlock::iterator i = b-&gt;begin(), ie = b-&gt;end(); i != ie; ++i) {
+ if (<a href="#CallInst">CallInst</a>* callInst = <a href="#isa">dyn_cast</a>&lt;<a
+ href="#CallInst">CallInst</a>&gt;(&amp;*i)) {
+ // <i>We know we've encountered a call instruction, so we</i>
+ // <i>need to determine if it's a call to the</i>
+ // <i>function pointed to by m_func or not.</i>
+ if (callInst-&gt;getCalledFunction() == targetFunc)
+ ++callCounter;
+ }
+ }
+ }
+ }
+
+ private:
+ unsigned callCounter;
+};
+</pre>
+</div>
+
+</div>
+
+<!--_______________________________________________________________________-->
+<h4>
+ <a name="calls_and_invokes">Treating calls and invokes the same way</a>
+</h4>
+
+<div>
+
+<p>You may have noticed that the previous example was a bit oversimplified in
+that it did not deal with call sites generated by 'invoke' instructions. In
+this, and in other situations, you may find that you want to treat
+<tt>CallInst</tt>s and <tt>InvokeInst</tt>s the same way, even though their
+most-specific common base class is <tt>Instruction</tt>, which includes lots of
+less closely-related things. For these cases, LLVM provides a handy wrapper
+class called <a
+href="http://llvm.org/doxygen/classllvm_1_1CallSite.html"><tt>CallSite</tt></a>.
+It is essentially a wrapper around an <tt>Instruction</tt> pointer, with some
+methods that provide functionality common to <tt>CallInst</tt>s and
+<tt>InvokeInst</tt>s.</p>
+
+<p>This class has "value semantics": it should be passed by value, not by
+reference and it should not be dynamically allocated or deallocated using
+<tt>operator new</tt> or <tt>operator delete</tt>. It is efficiently copyable,
+assignable and constructable, with costs equivalents to that of a bare pointer.
+If you look at its definition, it has only a single pointer member.</p>
+
+</div>
+
+<!--_______________________________________________________________________-->
+<h4>
+ <a name="iterate_chains">Iterating over def-use &amp; use-def chains</a>
+</h4>
+
+<div>
+
+<p>Frequently, we might have an instance of the <a
+href="/doxygen/classllvm_1_1Value.html">Value Class</a> and we want to
+determine which <tt>User</tt>s use the <tt>Value</tt>. The list of all
+<tt>User</tt>s of a particular <tt>Value</tt> is called a <i>def-use</i> chain.
+For example, let's say we have a <tt>Function*</tt> named <tt>F</tt> to a
+particular function <tt>foo</tt>. Finding all of the instructions that
+<i>use</i> <tt>foo</tt> is as simple as iterating over the <i>def-use</i> chain
+of <tt>F</tt>:</p>
+
+<div class="doc_code">
+<pre>
+Function *F = ...;
+
+for (Value::use_iterator i = F-&gt;use_begin(), e = F-&gt;use_end(); i != e; ++i)
+ if (Instruction *Inst = dyn_cast&lt;Instruction&gt;(*i)) {
+ errs() &lt;&lt; "F is used in instruction:\n";
+ errs() &lt;&lt; *Inst &lt;&lt; "\n";
+ }
+</pre>
+</div>
+
+<p>Note that dereferencing a <tt>Value::use_iterator</tt> is not a very cheap
+operation. Instead of performing <tt>*i</tt> above several times, consider
+doing it only once in the loop body and reusing its result.</p>
+
+<p>Alternatively, it's common to have an instance of the <a
+href="/doxygen/classllvm_1_1User.html">User Class</a> and need to know what
+<tt>Value</tt>s are used by it. The list of all <tt>Value</tt>s used by a
+<tt>User</tt> is known as a <i>use-def</i> chain. Instances of class
+<tt>Instruction</tt> are common <tt>User</tt>s, so we might want to iterate over
+all of the values that a particular instruction uses (that is, the operands of
+the particular <tt>Instruction</tt>):</p>
+
+<div class="doc_code">
+<pre>
+Instruction *pi = ...;
+
+for (User::op_iterator i = pi-&gt;op_begin(), e = pi-&gt;op_end(); i != e; ++i) {
+ Value *v = *i;
+ // <i>...</i>
+}
+</pre>
+</div>
+
+<p>Declaring objects as <tt>const</tt> is an important tool of enforcing
+mutation free algorithms (such as analyses, etc.). For this purpose above
+iterators come in constant flavors as <tt>Value::const_use_iterator</tt>
+and <tt>Value::const_op_iterator</tt>. They automatically arise when
+calling <tt>use/op_begin()</tt> on <tt>const Value*</tt>s or
+<tt>const User*</tt>s respectively. Upon dereferencing, they return
+<tt>const Use*</tt>s. Otherwise the above patterns remain unchanged.</p>
+
+</div>
+
+<!--_______________________________________________________________________-->
+<h4>
+ <a name="iterate_preds">Iterating over predecessors &amp;
+successors of blocks</a>
+</h4>
+
+<div>
+
+<p>Iterating over the predecessors and successors of a block is quite easy
+with the routines defined in <tt>"llvm/Support/CFG.h"</tt>. Just use code like
+this to iterate over all predecessors of BB:</p>
+
+<div class="doc_code">
+<pre>
+#include "llvm/Support/CFG.h"
+BasicBlock *BB = ...;
+
+for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
+ BasicBlock *Pred = *PI;
+ // <i>...</i>
+}
+</pre>
+</div>
+
+<p>Similarly, to iterate over successors use
+succ_iterator/succ_begin/succ_end.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="simplechanges">Making simple changes</a>
+</h3>
+
+<div>
+
+<p>There are some primitive transformation operations present in the LLVM
+infrastructure that are worth knowing about. When performing
+transformations, it's fairly common to manipulate the contents of basic
+blocks. This section describes some of the common methods for doing so
+and gives example code.</p>
+
+<!--_______________________________________________________________________-->
+<h4>
+ <a name="schanges_creating">Creating and inserting new
+ <tt>Instruction</tt>s</a>
+</h4>
+
+<div>
+
+<p><i>Instantiating Instructions</i></p>
+
+<p>Creation of <tt>Instruction</tt>s is straight-forward: simply call the
+constructor for the kind of instruction to instantiate and provide the necessary
+parameters. For example, an <tt>AllocaInst</tt> only <i>requires</i> a
+(const-ptr-to) <tt>Type</tt>. Thus:</p>
+
+<div class="doc_code">
+<pre>
+AllocaInst* ai = new AllocaInst(Type::Int32Ty);
+</pre>
+</div>
+
+<p>will create an <tt>AllocaInst</tt> instance that represents the allocation of
+one integer in the current stack frame, at run time. Each <tt>Instruction</tt>
+subclass is likely to have varying default parameters which change the semantics
+of the instruction, so refer to the <a
+href="/doxygen/classllvm_1_1Instruction.html">doxygen documentation for the subclass of
+Instruction</a> that you're interested in instantiating.</p>
+
+<p><i>Naming values</i></p>
+
+<p>It is very useful to name the values of instructions when you're able to, as
+this facilitates the debugging of your transformations. If you end up looking
+at generated LLVM machine code, you definitely want to have logical names
+associated with the results of instructions! By supplying a value for the
+<tt>Name</tt> (default) parameter of the <tt>Instruction</tt> constructor, you
+associate a logical name with the result of the instruction's execution at
+run time. For example, say that I'm writing a transformation that dynamically
+allocates space for an integer on the stack, and that integer is going to be
+used as some kind of index by some other code. To accomplish this, I place an
+<tt>AllocaInst</tt> at the first point in the first <tt>BasicBlock</tt> of some
+<tt>Function</tt>, and I'm intending to use it within the same
+<tt>Function</tt>. I might do:</p>
+
+<div class="doc_code">
+<pre>
+AllocaInst* pa = new AllocaInst(Type::Int32Ty, 0, "indexLoc");
+</pre>
+</div>
+
+<p>where <tt>indexLoc</tt> is now the logical name of the instruction's
+execution value, which is a pointer to an integer on the run time stack.</p>
+
+<p><i>Inserting instructions</i></p>
+
+<p>There are essentially two ways to insert an <tt>Instruction</tt>
+into an existing sequence of instructions that form a <tt>BasicBlock</tt>:</p>
+
+<ul>
+ <li>Insertion into an explicit instruction list
+
+ <p>Given a <tt>BasicBlock* pb</tt>, an <tt>Instruction* pi</tt> within that
+ <tt>BasicBlock</tt>, and a newly-created instruction we wish to insert
+ before <tt>*pi</tt>, we do the following: </p>
+
+<div class="doc_code">
+<pre>
+BasicBlock *pb = ...;
+Instruction *pi = ...;
+Instruction *newInst = new Instruction(...);
+
+pb-&gt;getInstList().insert(pi, newInst); // <i>Inserts newInst before pi in pb</i>
+</pre>
+</div>
+
+ <p>Appending to the end of a <tt>BasicBlock</tt> is so common that
+ the <tt>Instruction</tt> class and <tt>Instruction</tt>-derived
+ classes provide constructors which take a pointer to a
+ <tt>BasicBlock</tt> to be appended to. For example code that
+ looked like: </p>
+
+<div class="doc_code">
+<pre>
+BasicBlock *pb = ...;
+Instruction *newInst = new Instruction(...);
+
+pb-&gt;getInstList().push_back(newInst); // <i>Appends newInst to pb</i>
+</pre>
+</div>
+
+ <p>becomes: </p>
+
+<div class="doc_code">
+<pre>
+BasicBlock *pb = ...;
+Instruction *newInst = new Instruction(..., pb);
+</pre>
+</div>
+
+ <p>which is much cleaner, especially if you are creating
+ long instruction streams.</p></li>
+
+ <li>Insertion into an implicit instruction list
+
+ <p><tt>Instruction</tt> instances that are already in <tt>BasicBlock</tt>s
+ are implicitly associated with an existing instruction list: the instruction
+ list of the enclosing basic block. Thus, we could have accomplished the same
+ thing as the above code without being given a <tt>BasicBlock</tt> by doing:
+ </p>
+
+<div class="doc_code">
+<pre>
+Instruction *pi = ...;
+Instruction *newInst = new Instruction(...);
+
+pi-&gt;getParent()-&gt;getInstList().insert(pi, newInst);
+</pre>
+</div>
+
+ <p>In fact, this sequence of steps occurs so frequently that the
+ <tt>Instruction</tt> class and <tt>Instruction</tt>-derived classes provide
+ constructors which take (as a default parameter) a pointer to an
+ <tt>Instruction</tt> which the newly-created <tt>Instruction</tt> should
+ precede. That is, <tt>Instruction</tt> constructors are capable of
+ inserting the newly-created instance into the <tt>BasicBlock</tt> of a
+ provided instruction, immediately before that instruction. Using an
+ <tt>Instruction</tt> constructor with a <tt>insertBefore</tt> (default)
+ parameter, the above code becomes:</p>
+
+<div class="doc_code">
+<pre>
+Instruction* pi = ...;
+Instruction* newInst = new Instruction(..., pi);
+</pre>
+</div>
+
+ <p>which is much cleaner, especially if you're creating a lot of
+ instructions and adding them to <tt>BasicBlock</tt>s.</p></li>
+</ul>
+
+</div>
+
+<!--_______________________________________________________________________-->
+<h4>
+ <a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a>
+</h4>
+
+<div>
+
+<p>Deleting an instruction from an existing sequence of instructions that form a
+<a href="#BasicBlock"><tt>BasicBlock</tt></a> is very straight-forward: just
+call the instruction's eraseFromParent() method. For example:</p>
+
+<div class="doc_code">
+<pre>
+<a href="#Instruction">Instruction</a> *I = .. ;
+I-&gt;eraseFromParent();
+</pre>
+</div>
+
+<p>This unlinks the instruction from its containing basic block and deletes
+it. If you'd just like to unlink the instruction from its containing basic
+block but not delete it, you can use the <tt>removeFromParent()</tt> method.</p>
+
+</div>
+
+<!--_______________________________________________________________________-->
+<h4>
+ <a name="schanges_replacing">Replacing an <tt>Instruction</tt> with another
+ <tt>Value</tt></a>
+</h4>
+
+<div>
+
+<h5><i>Replacing individual instructions</i></h5>
+
+<p>Including "<a href="/doxygen/BasicBlockUtils_8h-source.html">llvm/Transforms/Utils/BasicBlockUtils.h</a>"
+permits use of two very useful replace functions: <tt>ReplaceInstWithValue</tt>
+and <tt>ReplaceInstWithInst</tt>.</p>
+
+<h5><a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a></h5>
+
+<div>
+<ul>
+ <li><tt>ReplaceInstWithValue</tt>
+
+ <p>This function replaces all uses of a given instruction with a value,
+ and then removes the original instruction. The following example
+ illustrates the replacement of the result of a particular
+ <tt>AllocaInst</tt> that allocates memory for a single integer with a null
+ pointer to an integer.</p>
+
+<div class="doc_code">
+<pre>
+AllocaInst* instToReplace = ...;
+BasicBlock::iterator ii(instToReplace);
+
+ReplaceInstWithValue(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
+ Constant::getNullValue(PointerType::getUnqual(Type::Int32Ty)));
+</pre></div></li>
+
+ <li><tt>ReplaceInstWithInst</tt>
+
+ <p>This function replaces a particular instruction with another
+ instruction, inserting the new instruction into the basic block at the
+ location where the old instruction was, and replacing any uses of the old
+ instruction with the new instruction. The following example illustrates
+ the replacement of one <tt>AllocaInst</tt> with another.</p>
+
+<div class="doc_code">
+<pre>
+AllocaInst* instToReplace = ...;
+BasicBlock::iterator ii(instToReplace);
+
+ReplaceInstWithInst(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
+ new AllocaInst(Type::Int32Ty, 0, "ptrToReplacedInt"));
+</pre></div></li>
+</ul>
+
+</div>
+
+<h5><i>Replacing multiple uses of <tt>User</tt>s and <tt>Value</tt>s</i></h5>
+
+<p>You can use <tt>Value::replaceAllUsesWith</tt> and
+<tt>User::replaceUsesOfWith</tt> to change more than one use at a time. See the
+doxygen documentation for the <a href="/doxygen/classllvm_1_1Value.html">Value Class</a>
+and <a href="/doxygen/classllvm_1_1User.html">User Class</a>, respectively, for more
+information.</p>
+
+<!-- Value::replaceAllUsesWith User::replaceUsesOfWith Point out:
+include/llvm/Transforms/Utils/ especially BasicBlockUtils.h with:
+ReplaceInstWithValue, ReplaceInstWithInst -->
+
+</div>
+
+<!--_______________________________________________________________________-->
+<h4>
+ <a name="schanges_deletingGV">Deleting <tt>GlobalVariable</tt>s</a>
+</h4>
+
+<div>
+
+<p>Deleting a global variable from a module is just as easy as deleting an
+Instruction. First, you must have a pointer to the global variable that you wish
+ to delete. You use this pointer to erase it from its parent, the module.
+ For example:</p>
+
+<div class="doc_code">
+<pre>
+<a href="#GlobalVariable">GlobalVariable</a> *GV = .. ;
+
+GV-&gt;eraseFromParent();
+</pre>
+</div>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="create_types">How to Create Types</a>
+</h3>
+
+<div>
+
+<p>In generating IR, you may need some complex types. If you know these types
+statically, you can use <tt>TypeBuilder&lt;...&gt;::get()</tt>, defined
+in <tt>llvm/Support/TypeBuilder.h</tt>, to retrieve them. <tt>TypeBuilder</tt>
+has two forms depending on whether you're building types for cross-compilation
+or native library use. <tt>TypeBuilder&lt;T, true&gt;</tt> requires
+that <tt>T</tt> be independent of the host environment, meaning that it's built
+out of types from
+the <a href="/doxygen/namespacellvm_1_1types.html"><tt>llvm::types</tt></a>
+namespace and pointers, functions, arrays, etc. built of
+those. <tt>TypeBuilder&lt;T, false&gt;</tt> additionally allows native C types
+whose size may depend on the host compiler. For example,</p>
+
+<div class="doc_code">
+<pre>
+FunctionType *ft = TypeBuilder&lt;types::i&lt;8&gt;(types::i&lt;32&gt;*), true&gt;::get();
+</pre>
+</div>
+
+<p>is easier to read and write than the equivalent</p>
+
+<div class="doc_code">
+<pre>
+std::vector&lt;const Type*&gt; params;
+params.push_back(PointerType::getUnqual(Type::Int32Ty));
+FunctionType *ft = FunctionType::get(Type::Int8Ty, params, false);
+</pre>
+</div>
+
+<p>See the <a href="/doxygen/TypeBuilder_8h-source.html#l00001">class
+comment</a> for more details.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="threading">Threads and LLVM</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+<p>
+This section describes the interaction of the LLVM APIs with multithreading,
+both on the part of client applications, and in the JIT, in the hosted
+application.
+</p>
+
+<p>
+Note that LLVM's support for multithreading is still relatively young. Up
+through version 2.5, the execution of threaded hosted applications was
+supported, but not threaded client access to the APIs. While this use case is
+now supported, clients <em>must</em> adhere to the guidelines specified below to
+ensure proper operation in multithreaded mode.
+</p>
+
+<p>
+Note that, on Unix-like platforms, LLVM requires the presence of GCC's atomic
+intrinsics in order to support threaded operation. If you need a
+multhreading-capable LLVM on a platform without a suitably modern system
+compiler, consider compiling LLVM and LLVM-GCC in single-threaded mode, and
+using the resultant compiler to build a copy of LLVM with multithreading
+support.
+</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="startmultithreaded">Entering and Exiting Multithreaded Mode</a>
+</h3>
+
+<div>
+
+<p>
+In order to properly protect its internal data structures while avoiding
+excessive locking overhead in the single-threaded case, the LLVM must intialize
+certain data structures necessary to provide guards around its internals. To do
+so, the client program must invoke <tt>llvm_start_multithreaded()</tt> before
+making any concurrent LLVM API calls. To subsequently tear down these
+structures, use the <tt>llvm_stop_multithreaded()</tt> call. You can also use
+the <tt>llvm_is_multithreaded()</tt> call to check the status of multithreaded
+mode.
+</p>
+
+<p>
+Note that both of these calls must be made <em>in isolation</em>. That is to
+say that no other LLVM API calls may be executing at any time during the
+execution of <tt>llvm_start_multithreaded()</tt> or <tt>llvm_stop_multithreaded
+</tt>. It's is the client's responsibility to enforce this isolation.
+</p>
+
+<p>
+The return value of <tt>llvm_start_multithreaded()</tt> indicates the success or
+failure of the initialization. Failure typically indicates that your copy of
+LLVM was built without multithreading support, typically because GCC atomic
+intrinsics were not found in your system compiler. In this case, the LLVM API
+will not be safe for concurrent calls. However, it <em>will</em> be safe for
+hosting threaded applications in the JIT, though <a href="#jitthreading">care
+must be taken</a> to ensure that side exits and the like do not accidentally
+result in concurrent LLVM API calls.
+</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="shutdown">Ending Execution with <tt>llvm_shutdown()</tt></a>
+</h3>
+
+<div>
+<p>
+When you are done using the LLVM APIs, you should call <tt>llvm_shutdown()</tt>
+to deallocate memory used for internal structures. This will also invoke
+<tt>llvm_stop_multithreaded()</tt> if LLVM is operating in multithreaded mode.
+As such, <tt>llvm_shutdown()</tt> requires the same isolation guarantees as
+<tt>llvm_stop_multithreaded()</tt>.
+</p>
+
+<p>
+Note that, if you use scope-based shutdown, you can use the
+<tt>llvm_shutdown_obj</tt> class, which calls <tt>llvm_shutdown()</tt> in its
+destructor.
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="managedstatic">Lazy Initialization with <tt>ManagedStatic</tt></a>
+</h3>
+
+<div>
+<p>
+<tt>ManagedStatic</tt> is a utility class in LLVM used to implement static
+initialization of static resources, such as the global type tables. Before the
+invocation of <tt>llvm_shutdown()</tt>, it implements a simple lazy
+initialization scheme. Once <tt>llvm_start_multithreaded()</tt> returns,
+however, it uses double-checked locking to implement thread-safe lazy
+initialization.
+</p>
+
+<p>
+Note that, because no other threads are allowed to issue LLVM API calls before
+<tt>llvm_start_multithreaded()</tt> returns, it is possible to have
+<tt>ManagedStatic</tt>s of <tt>llvm::sys::Mutex</tt>s.
+</p>
+
+<p>
+The <tt>llvm_acquire_global_lock()</tt> and <tt>llvm_release_global_lock</tt>
+APIs provide access to the global lock used to implement the double-checked
+locking for lazy initialization. These should only be used internally to LLVM,
+and only if you know what you're doing!
+</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="llvmcontext">Achieving Isolation with <tt>LLVMContext</tt></a>
+</h3>
+
+<div>
+<p>
+<tt>LLVMContext</tt> is an opaque class in the LLVM API which clients can use
+to operate multiple, isolated instances of LLVM concurrently within the same
+address space. For instance, in a hypothetical compile-server, the compilation
+of an individual translation unit is conceptually independent from all the
+others, and it would be desirable to be able to compile incoming translation
+units concurrently on independent server threads. Fortunately,
+<tt>LLVMContext</tt> exists to enable just this kind of scenario!
+</p>
+
+<p>
+Conceptually, <tt>LLVMContext</tt> provides isolation. Every LLVM entity
+(<tt>Module</tt>s, <tt>Value</tt>s, <tt>Type</tt>s, <tt>Constant</tt>s, etc.)
+in LLVM's in-memory IR belongs to an <tt>LLVMContext</tt>. Entities in
+different contexts <em>cannot</em> interact with each other: <tt>Module</tt>s in
+different contexts cannot be linked together, <tt>Function</tt>s cannot be added
+to <tt>Module</tt>s in different contexts, etc. What this means is that is is
+safe to compile on multiple threads simultaneously, as long as no two threads
+operate on entities within the same context.
+</p>
+
+<p>
+In practice, very few places in the API require the explicit specification of a
+<tt>LLVMContext</tt>, other than the <tt>Type</tt> creation/lookup APIs.
+Because every <tt>Type</tt> carries a reference to its owning context, most
+other entities can determine what context they belong to by looking at their
+own <tt>Type</tt>. If you are adding new entities to LLVM IR, please try to
+maintain this interface design.
+</p>
+
+<p>
+For clients that do <em>not</em> require the benefits of isolation, LLVM
+provides a convenience API <tt>getGlobalContext()</tt>. This returns a global,
+lazily initialized <tt>LLVMContext</tt> that may be used in situations where
+isolation is not a concern.
+</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="jitthreading">Threads and the JIT</a>
+</h3>
+
+<div>
+<p>
+LLVM's "eager" JIT compiler is safe to use in threaded programs. Multiple
+threads can call <tt>ExecutionEngine::getPointerToFunction()</tt> or
+<tt>ExecutionEngine::runFunction()</tt> concurrently, and multiple threads can
+run code output by the JIT concurrently. The user must still ensure that only
+one thread accesses IR in a given <tt>LLVMContext</tt> while another thread
+might be modifying it. One way to do that is to always hold the JIT lock while
+accessing IR outside the JIT (the JIT <em>modifies</em> the IR by adding
+<tt>CallbackVH</tt>s). Another way is to only
+call <tt>getPointerToFunction()</tt> from the <tt>LLVMContext</tt>'s thread.
+</p>
+
+<p>When the JIT is configured to compile lazily (using
+<tt>ExecutionEngine::DisableLazyCompilation(false)</tt>), there is currently a
+<a href="http://llvm.org/bugs/show_bug.cgi?id=5184">race condition</a> in
+updating call sites after a function is lazily-jitted. It's still possible to
+use the lazy JIT in a threaded program if you ensure that only one thread at a
+time can call any particular lazy stub and that the JIT lock guards any IR
+access, but we suggest using only the eager JIT in threaded programs.
+</p>
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="advanced">Advanced Topics</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+<p>
+This section describes some of the advanced or obscure API's that most clients
+do not need to be aware of. These API's tend manage the inner workings of the
+LLVM system, and only need to be accessed in unusual circumstances.
+</p>
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="SymbolTable">The <tt>ValueSymbolTable</tt> class</a>
+</h3>
+
+<div>
+<p>The <tt><a href="http://llvm.org/doxygen/classllvm_1_1ValueSymbolTable.html">
+ValueSymbolTable</a></tt> class provides a symbol table that the <a
+href="#Function"><tt>Function</tt></a> and <a href="#Module">
+<tt>Module</tt></a> classes use for naming value definitions. The symbol table
+can provide a name for any <a href="#Value"><tt>Value</tt></a>.
+</p>
+
+<p>Note that the <tt>SymbolTable</tt> class should not be directly accessed
+by most clients. It should only be used when iteration over the symbol table
+names themselves are required, which is very special purpose. Note that not
+all LLVM
+<tt><a href="#Value">Value</a></tt>s have names, and those without names (i.e. they have
+an empty name) do not exist in the symbol table.
+</p>
+
+<p>Symbol tables support iteration over the values in the symbol
+table with <tt>begin/end/iterator</tt> and supports querying to see if a
+specific name is in the symbol table (with <tt>lookup</tt>). The
+<tt>ValueSymbolTable</tt> class exposes no public mutator methods, instead,
+simply call <tt>setName</tt> on a value, which will autoinsert it into the
+appropriate symbol table.</p>
+
+</div>
+
+
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="UserLayout">The <tt>User</tt> and owned <tt>Use</tt> classes' memory layout</a>
+</h3>
+
+<div>
+<p>The <tt><a href="http://llvm.org/doxygen/classllvm_1_1User.html">
+User</a></tt> class provides a basis for expressing the ownership of <tt>User</tt>
+towards other <tt><a href="http://llvm.org/doxygen/classllvm_1_1Value.html">
+Value</a></tt>s. The <tt><a href="http://llvm.org/doxygen/classllvm_1_1Use.html">
+Use</a></tt> helper class is employed to do the bookkeeping and to facilitate <i>O(1)</i>
+addition and removal.</p>
+
+<!-- ______________________________________________________________________ -->
+<h4>
+ <a name="Use2User">
+ Interaction and relationship between <tt>User</tt> and <tt>Use</tt> objects
+ </a>
+</h4>
+
+<div>
+<p>
+A subclass of <tt>User</tt> can choose between incorporating its <tt>Use</tt> objects
+or refer to them out-of-line by means of a pointer. A mixed variant
+(some <tt>Use</tt>s inline others hung off) is impractical and breaks the invariant
+that the <tt>Use</tt> objects belonging to the same <tt>User</tt> form a contiguous array.
+</p>
+
+<p>
+We have 2 different layouts in the <tt>User</tt> (sub)classes:
+<ul>
+<li><p>Layout a)
+The <tt>Use</tt> object(s) are inside (resp. at fixed offset) of the <tt>User</tt>
+object and there are a fixed number of them.</p>
+
+<li><p>Layout b)
+The <tt>Use</tt> object(s) are referenced by a pointer to an
+array from the <tt>User</tt> object and there may be a variable
+number of them.</p>
+</ul>
+<p>
+As of v2.4 each layout still possesses a direct pointer to the
+start of the array of <tt>Use</tt>s. Though not mandatory for layout a),
+we stick to this redundancy for the sake of simplicity.
+The <tt>User</tt> object also stores the number of <tt>Use</tt> objects it
+has. (Theoretically this information can also be calculated
+given the scheme presented below.)</p>
+<p>
+Special forms of allocation operators (<tt>operator new</tt>)
+enforce the following memory layouts:</p>
+
+<ul>
+<li><p>Layout a) is modelled by prepending the <tt>User</tt> object by the <tt>Use[]</tt> array.</p>
+
+<pre>
+...---.---.---.---.-------...
+ | P | P | P | P | User
+'''---'---'---'---'-------'''
+</pre>
+
+<li><p>Layout b) is modelled by pointing at the <tt>Use[]</tt> array.</p>
+<pre>
+.-------...
+| User
+'-------'''
+ |
+ v
+ .---.---.---.---...
+ | P | P | P | P |
+ '---'---'---'---'''
+</pre>
+</ul>
+<i>(In the above figures '<tt>P</tt>' stands for the <tt>Use**</tt> that
+ is stored in each <tt>Use</tt> object in the member <tt>Use::Prev</tt>)</i>
+
+</div>
+
+<!-- ______________________________________________________________________ -->
+<h4>
+ <a name="Waymarking">The waymarking algorithm</a>
+</h4>
+
+<div>
+<p>
+Since the <tt>Use</tt> objects are deprived of the direct (back)pointer to
+their <tt>User</tt> objects, there must be a fast and exact method to
+recover it. This is accomplished by the following scheme:</p>
+
+A bit-encoding in the 2 LSBits (least significant bits) of the <tt>Use::Prev</tt> allows to find the
+start of the <tt>User</tt> object:
+<ul>
+<li><tt>00</tt> &mdash;&gt; binary digit 0</li>
+<li><tt>01</tt> &mdash;&gt; binary digit 1</li>
+<li><tt>10</tt> &mdash;&gt; stop and calculate (<tt>s</tt>)</li>
+<li><tt>11</tt> &mdash;&gt; full stop (<tt>S</tt>)</li>
+</ul>
+<p>
+Given a <tt>Use*</tt>, all we have to do is to walk till we get
+a stop and we either have a <tt>User</tt> immediately behind or
+we have to walk to the next stop picking up digits
+and calculating the offset:</p>
+<pre>
+.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.----------------
+| 1 | s | 1 | 0 | 1 | 0 | s | 1 | 1 | 0 | s | 1 | 1 | s | 1 | S | User (or User*)
+'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'----------------
+ |+15 |+10 |+6 |+3 |+1
+ | | | | |__>
+ | | | |__________>
+ | | |______________________>
+ | |______________________________________>
+ |__________________________________________________________>
+</pre>
+<p>
+Only the significant number of bits need to be stored between the
+stops, so that the <i>worst case is 20 memory accesses</i> when there are
+1000 <tt>Use</tt> objects associated with a <tt>User</tt>.</p>
+
+</div>
+
+<!-- ______________________________________________________________________ -->
+<h4>
+ <a name="ReferenceImpl">Reference implementation</a>
+</h4>
+
+<div>
+<p>
+The following literate Haskell fragment demonstrates the concept:</p>
+
+<div class="doc_code">
+<pre>
+> import Test.QuickCheck
+>
+> digits :: Int -> [Char] -> [Char]
+> digits 0 acc = '0' : acc
+> digits 1 acc = '1' : acc
+> digits n acc = digits (n `div` 2) $ digits (n `mod` 2) acc
+>
+> dist :: Int -> [Char] -> [Char]
+> dist 0 [] = ['S']
+> dist 0 acc = acc
+> dist 1 acc = let r = dist 0 acc in 's' : digits (length r) r
+> dist n acc = dist (n - 1) $ dist 1 acc
+>
+> takeLast n ss = reverse $ take n $ reverse ss
+>
+> test = takeLast 40 $ dist 20 []
+>
+</pre>
+</div>
+<p>
+Printing &lt;test&gt; gives: <tt>"1s100000s11010s10100s1111s1010s110s11s1S"</tt></p>
+<p>
+The reverse algorithm computes the length of the string just by examining
+a certain prefix:</p>
+
+<div class="doc_code">
+<pre>
+> pref :: [Char] -> Int
+> pref "S" = 1
+> pref ('s':'1':rest) = decode 2 1 rest
+> pref (_:rest) = 1 + pref rest
+>
+> decode walk acc ('0':rest) = decode (walk + 1) (acc * 2) rest
+> decode walk acc ('1':rest) = decode (walk + 1) (acc * 2 + 1) rest
+> decode walk acc _ = walk + acc
+>
+</pre>
+</div>
+<p>
+Now, as expected, printing &lt;pref test&gt; gives <tt>40</tt>.</p>
+<p>
+We can <i>quickCheck</i> this with following property:</p>
+
+<div class="doc_code">
+<pre>
+> testcase = dist 2000 []
+> testcaseLength = length testcase
+>
+> identityProp n = n > 0 && n <= testcaseLength ==> length arr == pref arr
+> where arr = takeLast n testcase
+>
+</pre>
+</div>
+<p>
+As expected &lt;quickCheck identityProp&gt; gives:</p>
+
+<pre>
+*Main> quickCheck identityProp
+OK, passed 100 tests.
+</pre>
+<p>
+Let's be a bit more exhaustive:</p>
+
+<div class="doc_code">
+<pre>
+>
+> deepCheck p = check (defaultConfig { configMaxTest = 500 }) p
+>
+</pre>
+</div>
+<p>
+And here is the result of &lt;deepCheck identityProp&gt;:</p>
+
+<pre>
+*Main> deepCheck identityProp
+OK, passed 500 tests.
+</pre>
+
+</div>
+
+<!-- ______________________________________________________________________ -->
+<h4>
+ <a name="Tagging">Tagging considerations</a>
+</h4>
+
+<div>
+
+<p>
+To maintain the invariant that the 2 LSBits of each <tt>Use**</tt> in <tt>Use</tt>
+never change after being set up, setters of <tt>Use::Prev</tt> must re-tag the
+new <tt>Use**</tt> on every modification. Accordingly getters must strip the
+tag bits.</p>
+<p>
+For layout b) instead of the <tt>User</tt> we find a pointer (<tt>User*</tt> with LSBit set).
+Following this pointer brings us to the <tt>User</tt>. A portable trick ensures
+that the first bytes of <tt>User</tt> (if interpreted as a pointer) never has
+the LSBit set. (Portability is relying on the fact that all known compilers place the
+<tt>vptr</tt> in the first word of the instances.)</p>
+
+</div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="coreclasses">The Core LLVM Class Hierarchy Reference </a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+<p><tt>#include "<a href="/doxygen/Type_8h-source.html">llvm/Type.h</a>"</tt>
+<br>doxygen info: <a href="/doxygen/classllvm_1_1Type.html">Type Class</a></p>
+
+<p>The Core LLVM classes are the primary means of representing the program
+being inspected or transformed. The core LLVM classes are defined in
+header files in the <tt>include/llvm/</tt> directory, and implemented in
+the <tt>lib/VMCore</tt> directory.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="Type">The <tt>Type</tt> class and Derived Types</a>
+</h3>
+
+<div>
+
+ <p><tt>Type</tt> is a superclass of all type classes. Every <tt>Value</tt> has
+ a <tt>Type</tt>. <tt>Type</tt> cannot be instantiated directly but only
+ through its subclasses. Certain primitive types (<tt>VoidType</tt>,
+ <tt>LabelType</tt>, <tt>FloatType</tt> and <tt>DoubleType</tt>) have hidden
+ subclasses. They are hidden because they offer no useful functionality beyond
+ what the <tt>Type</tt> class offers except to distinguish themselves from
+ other subclasses of <tt>Type</tt>.</p>
+ <p>All other types are subclasses of <tt>DerivedType</tt>. Types can be
+ named, but this is not a requirement. There exists exactly
+ one instance of a given shape at any one time. This allows type equality to
+ be performed with address equality of the Type Instance. That is, given two
+ <tt>Type*</tt> values, the types are identical if the pointers are identical.
+ </p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_Type">Important Public Methods</a>
+</h4>
+
+<div>
+
+<ul>
+ <li><tt>bool isIntegerTy() const</tt>: Returns true for any integer type.</li>
+
+ <li><tt>bool isFloatingPointTy()</tt>: Return true if this is one of the five
+ floating point types.</li>
+
+ <li><tt>bool isSized()</tt>: Return true if the type has known size. Things
+ that don't have a size are abstract types, labels and void.</li>
+
+</ul>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="derivedtypes">Important Derived Types</a>
+</h4>
+<div>
+<dl>
+ <dt><tt>IntegerType</tt></dt>
+ <dd>Subclass of DerivedType that represents integer types of any bit width.
+ Any bit width between <tt>IntegerType::MIN_INT_BITS</tt> (1) and
+ <tt>IntegerType::MAX_INT_BITS</tt> (~8 million) can be represented.
+ <ul>
+ <li><tt>static const IntegerType* get(unsigned NumBits)</tt>: get an integer
+ type of a specific bit width.</li>
+ <li><tt>unsigned getBitWidth() const</tt>: Get the bit width of an integer
+ type.</li>
+ </ul>
+ </dd>
+ <dt><tt>SequentialType</tt></dt>
+ <dd>This is subclassed by ArrayType, PointerType and VectorType.
+ <ul>
+ <li><tt>const Type * getElementType() const</tt>: Returns the type of each
+ of the elements in the sequential type. </li>
+ </ul>
+ </dd>
+ <dt><tt>ArrayType</tt></dt>
+ <dd>This is a subclass of SequentialType and defines the interface for array
+ types.
+ <ul>
+ <li><tt>unsigned getNumElements() const</tt>: Returns the number of
+ elements in the array. </li>
+ </ul>
+ </dd>
+ <dt><tt>PointerType</tt></dt>
+ <dd>Subclass of SequentialType for pointer types.</dd>
+ <dt><tt>VectorType</tt></dt>
+ <dd>Subclass of SequentialType for vector types. A
+ vector type is similar to an ArrayType but is distinguished because it is
+ a first class type whereas ArrayType is not. Vector types are used for
+ vector operations and are usually small vectors of of an integer or floating
+ point type.</dd>
+ <dt><tt>StructType</tt></dt>
+ <dd>Subclass of DerivedTypes for struct types.</dd>
+ <dt><tt><a name="FunctionType">FunctionType</a></tt></dt>
+ <dd>Subclass of DerivedTypes for function types.
+ <ul>
+ <li><tt>bool isVarArg() const</tt>: Returns true if it's a vararg
+ function</li>
+ <li><tt> const Type * getReturnType() const</tt>: Returns the
+ return type of the function.</li>
+ <li><tt>const Type * getParamType (unsigned i)</tt>: Returns
+ the type of the ith parameter.</li>
+ <li><tt> const unsigned getNumParams() const</tt>: Returns the
+ number of formal parameters.</li>
+ </ul>
+ </dd>
+</dl>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="Module">The <tt>Module</tt> class</a>
+</h3>
+
+<div>
+
+<p><tt>#include "<a
+href="/doxygen/Module_8h-source.html">llvm/Module.h</a>"</tt><br> doxygen info:
+<a href="/doxygen/classllvm_1_1Module.html">Module Class</a></p>
+
+<p>The <tt>Module</tt> class represents the top level structure present in LLVM
+programs. An LLVM module is effectively either a translation unit of the
+original program or a combination of several translation units merged by the
+linker. The <tt>Module</tt> class keeps track of a list of <a
+href="#Function"><tt>Function</tt></a>s, a list of <a
+href="#GlobalVariable"><tt>GlobalVariable</tt></a>s, and a <a
+href="#SymbolTable"><tt>SymbolTable</tt></a>. Additionally, it contains a few
+helpful member functions that try to make common operations easy.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_Module">Important Public Members of the <tt>Module</tt> class</a>
+</h4>
+
+<div>
+
+<ul>
+ <li><tt>Module::Module(std::string name = "")</tt>
+
+ <p>Constructing a <a href="#Module">Module</a> is easy. You can optionally
+provide a name for it (probably based on the name of the translation unit).</p>
+ </li>
+
+ <li><tt>Module::iterator</tt> - Typedef for function list iterator<br>
+ <tt>Module::const_iterator</tt> - Typedef for const_iterator.<br>
+
+ <tt>begin()</tt>, <tt>end()</tt>
+ <tt>size()</tt>, <tt>empty()</tt>
+
+ <p>These are forwarding methods that make it easy to access the contents of
+ a <tt>Module</tt> object's <a href="#Function"><tt>Function</tt></a>
+ list.</p></li>
+
+ <li><tt>Module::FunctionListType &amp;getFunctionList()</tt>
+
+ <p> Returns the list of <a href="#Function"><tt>Function</tt></a>s. This is
+ necessary to use when you need to update the list or perform a complex
+ action that doesn't have a forwarding method.</p>
+
+ <p><!-- Global Variable --></p></li>
+</ul>
+
+<hr>
+
+<ul>
+ <li><tt>Module::global_iterator</tt> - Typedef for global variable list iterator<br>
+
+ <tt>Module::const_global_iterator</tt> - Typedef for const_iterator.<br>
+
+ <tt>global_begin()</tt>, <tt>global_end()</tt>
+ <tt>global_size()</tt>, <tt>global_empty()</tt>
+
+ <p> These are forwarding methods that make it easy to access the contents of
+ a <tt>Module</tt> object's <a
+ href="#GlobalVariable"><tt>GlobalVariable</tt></a> list.</p></li>
+
+ <li><tt>Module::GlobalListType &amp;getGlobalList()</tt>
+
+ <p>Returns the list of <a
+ href="#GlobalVariable"><tt>GlobalVariable</tt></a>s. This is necessary to
+ use when you need to update the list or perform a complex action that
+ doesn't have a forwarding method.</p>
+
+ <p><!-- Symbol table stuff --> </p></li>
+</ul>
+
+<hr>
+
+<ul>
+ <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
+
+ <p>Return a reference to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
+ for this <tt>Module</tt>.</p>
+
+ <p><!-- Convenience methods --></p></li>
+</ul>
+
+<hr>
+
+<ul>
+
+ <li><tt><a href="#Function">Function</a> *getFunction(StringRef Name) const
+ </tt>
+
+ <p>Look up the specified function in the <tt>Module</tt> <a
+ href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, return
+ <tt>null</tt>.</p></li>
+
+ <li><tt><a href="#Function">Function</a> *getOrInsertFunction(const
+ std::string &amp;Name, const <a href="#FunctionType">FunctionType</a> *T)</tt>
+
+ <p>Look up the specified function in the <tt>Module</tt> <a
+ href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, add an
+ external declaration for the function and return it.</p></li>
+
+ <li><tt>std::string getTypeName(const <a href="#Type">Type</a> *Ty)</tt>
+
+ <p>If there is at least one entry in the <a
+ href="#SymbolTable"><tt>SymbolTable</tt></a> for the specified <a
+ href="#Type"><tt>Type</tt></a>, return it. Otherwise return the empty
+ string.</p></li>
+
+ <li><tt>bool addTypeName(const std::string &amp;Name, const <a
+ href="#Type">Type</a> *Ty)</tt>
+
+ <p>Insert an entry in the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
+ mapping <tt>Name</tt> to <tt>Ty</tt>. If there is already an entry for this
+ name, true is returned and the <a
+ href="#SymbolTable"><tt>SymbolTable</tt></a> is not modified.</p></li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="Value">The <tt>Value</tt> class</a>
+</h3>
+
+<div>
+
+<p><tt>#include "<a href="/doxygen/Value_8h-source.html">llvm/Value.h</a>"</tt>
+<br>
+doxygen info: <a href="/doxygen/classllvm_1_1Value.html">Value Class</a></p>
+
+<p>The <tt>Value</tt> class is the most important class in the LLVM Source
+base. It represents a typed value that may be used (among other things) as an
+operand to an instruction. There are many different types of <tt>Value</tt>s,
+such as <a href="#Constant"><tt>Constant</tt></a>s,<a
+href="#Argument"><tt>Argument</tt></a>s. Even <a
+href="#Instruction"><tt>Instruction</tt></a>s and <a
+href="#Function"><tt>Function</tt></a>s are <tt>Value</tt>s.</p>
+
+<p>A particular <tt>Value</tt> may be used many times in the LLVM representation
+for a program. For example, an incoming argument to a function (represented
+with an instance of the <a href="#Argument">Argument</a> class) is "used" by
+every instruction in the function that references the argument. To keep track
+of this relationship, the <tt>Value</tt> class keeps a list of all of the <a
+href="#User"><tt>User</tt></a>s that is using it (the <a
+href="#User"><tt>User</tt></a> class is a base class for all nodes in the LLVM
+graph that can refer to <tt>Value</tt>s). This use list is how LLVM represents
+def-use information in the program, and is accessible through the <tt>use_</tt>*
+methods, shown below.</p>
+
+<p>Because LLVM is a typed representation, every LLVM <tt>Value</tt> is typed,
+and this <a href="#Type">Type</a> is available through the <tt>getType()</tt>
+method. In addition, all LLVM values can be named. The "name" of the
+<tt>Value</tt> is a symbolic string printed in the LLVM code:</p>
+
+<div class="doc_code">
+<pre>
+%<b>foo</b> = add i32 1, 2
+</pre>
+</div>
+
+<p><a name="nameWarning">The name of this instruction is "foo".</a> <b>NOTE</b>
+that the name of any value may be missing (an empty string), so names should
+<b>ONLY</b> be used for debugging (making the source code easier to read,
+debugging printouts), they should not be used to keep track of values or map
+between them. For this purpose, use a <tt>std::map</tt> of pointers to the
+<tt>Value</tt> itself instead.</p>
+
+<p>One important aspect of LLVM is that there is no distinction between an SSA
+variable and the operation that produces it. Because of this, any reference to
+the value produced by an instruction (or the value available as an incoming
+argument, for example) is represented as a direct pointer to the instance of
+the class that
+represents this value. Although this may take some getting used to, it
+simplifies the representation and makes it easier to manipulate.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_Value">Important Public Members of the <tt>Value</tt> class</a>
+</h4>
+
+<div>
+
+<ul>
+ <li><tt>Value::use_iterator</tt> - Typedef for iterator over the
+use-list<br>
+ <tt>Value::const_use_iterator</tt> - Typedef for const_iterator over
+the use-list<br>
+ <tt>unsigned use_size()</tt> - Returns the number of users of the
+value.<br>
+ <tt>bool use_empty()</tt> - Returns true if there are no users.<br>
+ <tt>use_iterator use_begin()</tt> - Get an iterator to the start of
+the use-list.<br>
+ <tt>use_iterator use_end()</tt> - Get an iterator to the end of the
+use-list.<br>
+ <tt><a href="#User">User</a> *use_back()</tt> - Returns the last
+element in the list.
+ <p> These methods are the interface to access the def-use
+information in LLVM. As with all other iterators in LLVM, the naming
+conventions follow the conventions defined by the <a href="#stl">STL</a>.</p>
+ </li>
+ <li><tt><a href="#Type">Type</a> *getType() const</tt>
+ <p>This method returns the Type of the Value.</p>
+ </li>
+ <li><tt>bool hasName() const</tt><br>
+ <tt>std::string getName() const</tt><br>
+ <tt>void setName(const std::string &amp;Name)</tt>
+ <p> This family of methods is used to access and assign a name to a <tt>Value</tt>,
+be aware of the <a href="#nameWarning">precaution above</a>.</p>
+ </li>
+ <li><tt>void replaceAllUsesWith(Value *V)</tt>
+
+ <p>This method traverses the use list of a <tt>Value</tt> changing all <a
+ href="#User"><tt>User</tt>s</a> of the current value to refer to
+ "<tt>V</tt>" instead. For example, if you detect that an instruction always
+ produces a constant value (for example through constant folding), you can
+ replace all uses of the instruction with the constant like this:</p>
+
+<div class="doc_code">
+<pre>
+Inst-&gt;replaceAllUsesWith(ConstVal);
+</pre>
+</div>
+
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="User">The <tt>User</tt> class</a>
+</h3>
+
+<div>
+
+<p>
+<tt>#include "<a href="/doxygen/User_8h-source.html">llvm/User.h</a>"</tt><br>
+doxygen info: <a href="/doxygen/classllvm_1_1User.html">User Class</a><br>
+Superclass: <a href="#Value"><tt>Value</tt></a></p>
+
+<p>The <tt>User</tt> class is the common base class of all LLVM nodes that may
+refer to <a href="#Value"><tt>Value</tt></a>s. It exposes a list of "Operands"
+that are all of the <a href="#Value"><tt>Value</tt></a>s that the User is
+referring to. The <tt>User</tt> class itself is a subclass of
+<tt>Value</tt>.</p>
+
+<p>The operands of a <tt>User</tt> point directly to the LLVM <a
+href="#Value"><tt>Value</tt></a> that it refers to. Because LLVM uses Static
+Single Assignment (SSA) form, there can only be one definition referred to,
+allowing this direct connection. This connection provides the use-def
+information in LLVM.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_User">Important Public Members of the <tt>User</tt> class</a>
+</h4>
+
+<div>
+
+<p>The <tt>User</tt> class exposes the operand list in two ways: through
+an index access interface and through an iterator based interface.</p>
+
+<ul>
+ <li><tt>Value *getOperand(unsigned i)</tt><br>
+ <tt>unsigned getNumOperands()</tt>
+ <p> These two methods expose the operands of the <tt>User</tt> in a
+convenient form for direct access.</p></li>
+
+ <li><tt>User::op_iterator</tt> - Typedef for iterator over the operand
+list<br>
+ <tt>op_iterator op_begin()</tt> - Get an iterator to the start of
+the operand list.<br>
+ <tt>op_iterator op_end()</tt> - Get an iterator to the end of the
+operand list.
+ <p> Together, these methods make up the iterator based interface to
+the operands of a <tt>User</tt>.</p></li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="Instruction">The <tt>Instruction</tt> class</a>
+</h3>
+
+<div>
+
+<p><tt>#include "</tt><tt><a
+href="/doxygen/Instruction_8h-source.html">llvm/Instruction.h</a>"</tt><br>
+doxygen info: <a href="/doxygen/classllvm_1_1Instruction.html">Instruction Class</a><br>
+Superclasses: <a href="#User"><tt>User</tt></a>, <a
+href="#Value"><tt>Value</tt></a></p>
+
+<p>The <tt>Instruction</tt> class is the common base class for all LLVM
+instructions. It provides only a few methods, but is a very commonly used
+class. The primary data tracked by the <tt>Instruction</tt> class itself is the
+opcode (instruction type) and the parent <a
+href="#BasicBlock"><tt>BasicBlock</tt></a> the <tt>Instruction</tt> is embedded
+into. To represent a specific type of instruction, one of many subclasses of
+<tt>Instruction</tt> are used.</p>
+
+<p> Because the <tt>Instruction</tt> class subclasses the <a
+href="#User"><tt>User</tt></a> class, its operands can be accessed in the same
+way as for other <a href="#User"><tt>User</tt></a>s (with the
+<tt>getOperand()</tt>/<tt>getNumOperands()</tt> and
+<tt>op_begin()</tt>/<tt>op_end()</tt> methods).</p> <p> An important file for
+the <tt>Instruction</tt> class is the <tt>llvm/Instruction.def</tt> file. This
+file contains some meta-data about the various different types of instructions
+in LLVM. It describes the enum values that are used as opcodes (for example
+<tt>Instruction::Add</tt> and <tt>Instruction::ICmp</tt>), as well as the
+concrete sub-classes of <tt>Instruction</tt> that implement the instruction (for
+example <tt><a href="#BinaryOperator">BinaryOperator</a></tt> and <tt><a
+href="#CmpInst">CmpInst</a></tt>). Unfortunately, the use of macros in
+this file confuses doxygen, so these enum values don't show up correctly in the
+<a href="/doxygen/classllvm_1_1Instruction.html">doxygen output</a>.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="s_Instruction">
+ Important Subclasses of the <tt>Instruction</tt> class
+ </a>
+</h4>
+<div>
+ <ul>
+ <li><tt><a name="BinaryOperator">BinaryOperator</a></tt>
+ <p>This subclasses represents all two operand instructions whose operands
+ must be the same type, except for the comparison instructions.</p></li>
+ <li><tt><a name="CastInst">CastInst</a></tt>
+ <p>This subclass is the parent of the 12 casting instructions. It provides
+ common operations on cast instructions.</p>
+ <li><tt><a name="CmpInst">CmpInst</a></tt>
+ <p>This subclass respresents the two comparison instructions,
+ <a href="LangRef.html#i_icmp">ICmpInst</a> (integer opreands), and
+ <a href="LangRef.html#i_fcmp">FCmpInst</a> (floating point operands).</p>
+ <li><tt><a name="TerminatorInst">TerminatorInst</a></tt>
+ <p>This subclass is the parent of all terminator instructions (those which
+ can terminate a block).</p>
+ </ul>
+ </div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_Instruction">
+ Important Public Members of the <tt>Instruction</tt> class
+ </a>
+</h4>
+
+<div>
+
+<ul>
+ <li><tt><a href="#BasicBlock">BasicBlock</a> *getParent()</tt>
+ <p>Returns the <a href="#BasicBlock"><tt>BasicBlock</tt></a> that
+this <tt>Instruction</tt> is embedded into.</p></li>
+ <li><tt>bool mayWriteToMemory()</tt>
+ <p>Returns true if the instruction writes to memory, i.e. it is a
+ <tt>call</tt>,<tt>free</tt>,<tt>invoke</tt>, or <tt>store</tt>.</p></li>
+ <li><tt>unsigned getOpcode()</tt>
+ <p>Returns the opcode for the <tt>Instruction</tt>.</p></li>
+ <li><tt><a href="#Instruction">Instruction</a> *clone() const</tt>
+ <p>Returns another instance of the specified instruction, identical
+in all ways to the original except that the instruction has no parent
+(ie it's not embedded into a <a href="#BasicBlock"><tt>BasicBlock</tt></a>),
+and it has no name</p></li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="Constant">The <tt>Constant</tt> class and subclasses</a>
+</h3>
+
+<div>
+
+<p>Constant represents a base class for different types of constants. It
+is subclassed by ConstantInt, ConstantArray, etc. for representing
+the various types of Constants. <a href="#GlobalValue">GlobalValue</a> is also
+a subclass, which represents the address of a global variable or function.
+</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>Important Subclasses of Constant</h4>
+<div>
+<ul>
+ <li>ConstantInt : This subclass of Constant represents an integer constant of
+ any width.
+ <ul>
+ <li><tt>const APInt&amp; getValue() const</tt>: Returns the underlying
+ value of this constant, an APInt value.</li>
+ <li><tt>int64_t getSExtValue() const</tt>: Converts the underlying APInt
+ value to an int64_t via sign extension. If the value (not the bit width)
+ of the APInt is too large to fit in an int64_t, an assertion will result.
+ For this reason, use of this method is discouraged.</li>
+ <li><tt>uint64_t getZExtValue() const</tt>: Converts the underlying APInt
+ value to a uint64_t via zero extension. IF the value (not the bit width)
+ of the APInt is too large to fit in a uint64_t, an assertion will result.
+ For this reason, use of this method is discouraged.</li>
+ <li><tt>static ConstantInt* get(const APInt&amp; Val)</tt>: Returns the
+ ConstantInt object that represents the value provided by <tt>Val</tt>.
+ The type is implied as the IntegerType that corresponds to the bit width
+ of <tt>Val</tt>.</li>
+ <li><tt>static ConstantInt* get(const Type *Ty, uint64_t Val)</tt>:
+ Returns the ConstantInt object that represents the value provided by
+ <tt>Val</tt> for integer type <tt>Ty</tt>.</li>
+ </ul>
+ </li>
+ <li>ConstantFP : This class represents a floating point constant.
+ <ul>
+ <li><tt>double getValue() const</tt>: Returns the underlying value of
+ this constant. </li>
+ </ul>
+ </li>
+ <li>ConstantArray : This represents a constant array.
+ <ul>
+ <li><tt>const std::vector&lt;Use&gt; &amp;getValues() const</tt>: Returns
+ a vector of component constants that makeup this array. </li>
+ </ul>
+ </li>
+ <li>ConstantStruct : This represents a constant struct.
+ <ul>
+ <li><tt>const std::vector&lt;Use&gt; &amp;getValues() const</tt>: Returns
+ a vector of component constants that makeup this array. </li>
+ </ul>
+ </li>
+ <li>GlobalValue : This represents either a global variable or a function. In
+ either case, the value is a constant fixed address (after linking).
+ </li>
+</ul>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="GlobalValue">The <tt>GlobalValue</tt> class</a>
+</h3>
+
+<div>
+
+<p><tt>#include "<a
+href="/doxygen/GlobalValue_8h-source.html">llvm/GlobalValue.h</a>"</tt><br>
+doxygen info: <a href="/doxygen/classllvm_1_1GlobalValue.html">GlobalValue
+Class</a><br>
+Superclasses: <a href="#Constant"><tt>Constant</tt></a>,
+<a href="#User"><tt>User</tt></a>, <a href="#Value"><tt>Value</tt></a></p>
+
+<p>Global values (<a href="#GlobalVariable"><tt>GlobalVariable</tt></a>s or <a
+href="#Function"><tt>Function</tt></a>s) are the only LLVM values that are
+visible in the bodies of all <a href="#Function"><tt>Function</tt></a>s.
+Because they are visible at global scope, they are also subject to linking with
+other globals defined in different translation units. To control the linking
+process, <tt>GlobalValue</tt>s know their linkage rules. Specifically,
+<tt>GlobalValue</tt>s know whether they have internal or external linkage, as
+defined by the <tt>LinkageTypes</tt> enumeration.</p>
+
+<p>If a <tt>GlobalValue</tt> has internal linkage (equivalent to being
+<tt>static</tt> in C), it is not visible to code outside the current translation
+unit, and does not participate in linking. If it has external linkage, it is
+visible to external code, and does participate in linking. In addition to
+linkage information, <tt>GlobalValue</tt>s keep track of which <a
+href="#Module"><tt>Module</tt></a> they are currently part of.</p>
+
+<p>Because <tt>GlobalValue</tt>s are memory objects, they are always referred to
+by their <b>address</b>. As such, the <a href="#Type"><tt>Type</tt></a> of a
+global is always a pointer to its contents. It is important to remember this
+when using the <tt>GetElementPtrInst</tt> instruction because this pointer must
+be dereferenced first. For example, if you have a <tt>GlobalVariable</tt> (a
+subclass of <tt>GlobalValue)</tt> that is an array of 24 ints, type <tt>[24 x
+i32]</tt>, then the <tt>GlobalVariable</tt> is a pointer to that array. Although
+the address of the first element of this array and the value of the
+<tt>GlobalVariable</tt> are the same, they have different types. The
+<tt>GlobalVariable</tt>'s type is <tt>[24 x i32]</tt>. The first element's type
+is <tt>i32.</tt> Because of this, accessing a global value requires you to
+dereference the pointer with <tt>GetElementPtrInst</tt> first, then its elements
+can be accessed. This is explained in the <a href="LangRef.html#globalvars">LLVM
+Language Reference Manual</a>.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_GlobalValue">
+ Important Public Members of the <tt>GlobalValue</tt> class
+ </a>
+</h4>
+
+<div>
+
+<ul>
+ <li><tt>bool hasInternalLinkage() const</tt><br>
+ <tt>bool hasExternalLinkage() const</tt><br>
+ <tt>void setInternalLinkage(bool HasInternalLinkage)</tt>
+ <p> These methods manipulate the linkage characteristics of the <tt>GlobalValue</tt>.</p>
+ <p> </p>
+ </li>
+ <li><tt><a href="#Module">Module</a> *getParent()</tt>
+ <p> This returns the <a href="#Module"><tt>Module</tt></a> that the
+GlobalValue is currently embedded into.</p></li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="Function">The <tt>Function</tt> class</a>
+</h3>
+
+<div>
+
+<p><tt>#include "<a
+href="/doxygen/Function_8h-source.html">llvm/Function.h</a>"</tt><br> doxygen
+info: <a href="/doxygen/classllvm_1_1Function.html">Function Class</a><br>
+Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>,
+<a href="#Constant"><tt>Constant</tt></a>,
+<a href="#User"><tt>User</tt></a>,
+<a href="#Value"><tt>Value</tt></a></p>
+
+<p>The <tt>Function</tt> class represents a single procedure in LLVM. It is
+actually one of the more complex classes in the LLVM hierarchy because it must
+keep track of a large amount of data. The <tt>Function</tt> class keeps track
+of a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, a list of formal
+<a href="#Argument"><tt>Argument</tt></a>s, and a
+<a href="#SymbolTable"><tt>SymbolTable</tt></a>.</p>
+
+<p>The list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s is the most
+commonly used part of <tt>Function</tt> objects. The list imposes an implicit
+ordering of the blocks in the function, which indicate how the code will be
+laid out by the backend. Additionally, the first <a
+href="#BasicBlock"><tt>BasicBlock</tt></a> is the implicit entry node for the
+<tt>Function</tt>. It is not legal in LLVM to explicitly branch to this initial
+block. There are no implicit exit nodes, and in fact there may be multiple exit
+nodes from a single <tt>Function</tt>. If the <a
+href="#BasicBlock"><tt>BasicBlock</tt></a> list is empty, this indicates that
+the <tt>Function</tt> is actually a function declaration: the actual body of the
+function hasn't been linked in yet.</p>
+
+<p>In addition to a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, the
+<tt>Function</tt> class also keeps track of the list of formal <a
+href="#Argument"><tt>Argument</tt></a>s that the function receives. This
+container manages the lifetime of the <a href="#Argument"><tt>Argument</tt></a>
+nodes, just like the <a href="#BasicBlock"><tt>BasicBlock</tt></a> list does for
+the <a href="#BasicBlock"><tt>BasicBlock</tt></a>s.</p>
+
+<p>The <a href="#SymbolTable"><tt>SymbolTable</tt></a> is a very rarely used
+LLVM feature that is only used when you have to look up a value by name. Aside
+from that, the <a href="#SymbolTable"><tt>SymbolTable</tt></a> is used
+internally to make sure that there are not conflicts between the names of <a
+href="#Instruction"><tt>Instruction</tt></a>s, <a
+href="#BasicBlock"><tt>BasicBlock</tt></a>s, or <a
+href="#Argument"><tt>Argument</tt></a>s in the function body.</p>
+
+<p>Note that <tt>Function</tt> is a <a href="#GlobalValue">GlobalValue</a>
+and therefore also a <a href="#Constant">Constant</a>. The value of the function
+is its address (after linking) which is guaranteed to be constant.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_Function">
+ Important Public Members of the <tt>Function</tt> class
+ </a>
+</h4>
+
+<div>
+
+<ul>
+ <li><tt>Function(const </tt><tt><a href="#FunctionType">FunctionType</a>
+ *Ty, LinkageTypes Linkage, const std::string &amp;N = "", Module* Parent = 0)</tt>
+
+ <p>Constructor used when you need to create new <tt>Function</tt>s to add
+ the program. The constructor must specify the type of the function to
+ create and what type of linkage the function should have. The <a
+ href="#FunctionType"><tt>FunctionType</tt></a> argument
+ specifies the formal arguments and return value for the function. The same
+ <a href="#FunctionType"><tt>FunctionType</tt></a> value can be used to
+ create multiple functions. The <tt>Parent</tt> argument specifies the Module
+ in which the function is defined. If this argument is provided, the function
+ will automatically be inserted into that module's list of
+ functions.</p></li>
+
+ <li><tt>bool isDeclaration()</tt>
+
+ <p>Return whether or not the <tt>Function</tt> has a body defined. If the
+ function is "external", it does not have a body, and thus must be resolved
+ by linking with a function defined in a different translation unit.</p></li>
+
+ <li><tt>Function::iterator</tt> - Typedef for basic block list iterator<br>
+ <tt>Function::const_iterator</tt> - Typedef for const_iterator.<br>
+
+ <tt>begin()</tt>, <tt>end()</tt>
+ <tt>size()</tt>, <tt>empty()</tt>
+
+ <p>These are forwarding methods that make it easy to access the contents of
+ a <tt>Function</tt> object's <a href="#BasicBlock"><tt>BasicBlock</tt></a>
+ list.</p></li>
+
+ <li><tt>Function::BasicBlockListType &amp;getBasicBlockList()</tt>
+
+ <p>Returns the list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s. This
+ is necessary to use when you need to update the list or perform a complex
+ action that doesn't have a forwarding method.</p></li>
+
+ <li><tt>Function::arg_iterator</tt> - Typedef for the argument list
+iterator<br>
+ <tt>Function::const_arg_iterator</tt> - Typedef for const_iterator.<br>
+
+ <tt>arg_begin()</tt>, <tt>arg_end()</tt>
+ <tt>arg_size()</tt>, <tt>arg_empty()</tt>
+
+ <p>These are forwarding methods that make it easy to access the contents of
+ a <tt>Function</tt> object's <a href="#Argument"><tt>Argument</tt></a>
+ list.</p></li>
+
+ <li><tt>Function::ArgumentListType &amp;getArgumentList()</tt>
+
+ <p>Returns the list of <a href="#Argument"><tt>Argument</tt></a>s. This is
+ necessary to use when you need to update the list or perform a complex
+ action that doesn't have a forwarding method.</p></li>
+
+ <li><tt><a href="#BasicBlock">BasicBlock</a> &amp;getEntryBlock()</tt>
+
+ <p>Returns the entry <a href="#BasicBlock"><tt>BasicBlock</tt></a> for the
+ function. Because the entry block for the function is always the first
+ block, this returns the first block of the <tt>Function</tt>.</p></li>
+
+ <li><tt><a href="#Type">Type</a> *getReturnType()</tt><br>
+ <tt><a href="#FunctionType">FunctionType</a> *getFunctionType()</tt>
+
+ <p>This traverses the <a href="#Type"><tt>Type</tt></a> of the
+ <tt>Function</tt> and returns the return type of the function, or the <a
+ href="#FunctionType"><tt>FunctionType</tt></a> of the actual
+ function.</p></li>
+
+ <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
+
+ <p> Return a pointer to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
+ for this <tt>Function</tt>.</p></li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="GlobalVariable">The <tt>GlobalVariable</tt> class</a>
+</h3>
+
+<div>
+
+<p><tt>#include "<a
+href="/doxygen/GlobalVariable_8h-source.html">llvm/GlobalVariable.h</a>"</tt>
+<br>
+doxygen info: <a href="/doxygen/classllvm_1_1GlobalVariable.html">GlobalVariable
+ Class</a><br>
+Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>,
+<a href="#Constant"><tt>Constant</tt></a>,
+<a href="#User"><tt>User</tt></a>,
+<a href="#Value"><tt>Value</tt></a></p>
+
+<p>Global variables are represented with the (surprise surprise)
+<tt>GlobalVariable</tt> class. Like functions, <tt>GlobalVariable</tt>s are also
+subclasses of <a href="#GlobalValue"><tt>GlobalValue</tt></a>, and as such are
+always referenced by their address (global values must live in memory, so their
+"name" refers to their constant address). See
+<a href="#GlobalValue"><tt>GlobalValue</tt></a> for more on this. Global
+variables may have an initial value (which must be a
+<a href="#Constant"><tt>Constant</tt></a>), and if they have an initializer,
+they may be marked as "constant" themselves (indicating that their contents
+never change at runtime).</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_GlobalVariable">
+ Important Public Members of the <tt>GlobalVariable</tt> class
+ </a>
+</h4>
+
+<div>
+
+<ul>
+ <li><tt>GlobalVariable(const </tt><tt><a href="#Type">Type</a> *Ty, bool
+ isConstant, LinkageTypes&amp; Linkage, <a href="#Constant">Constant</a>
+ *Initializer = 0, const std::string &amp;Name = "", Module* Parent = 0)</tt>
+
+ <p>Create a new global variable of the specified type. If
+ <tt>isConstant</tt> is true then the global variable will be marked as
+ unchanging for the program. The Linkage parameter specifies the type of
+ linkage (internal, external, weak, linkonce, appending) for the variable.
+ If the linkage is InternalLinkage, WeakAnyLinkage, WeakODRLinkage,
+ LinkOnceAnyLinkage or LinkOnceODRLinkage,&nbsp; then the resultant
+ global variable will have internal linkage. AppendingLinkage concatenates
+ together all instances (in different translation units) of the variable
+ into a single variable but is only applicable to arrays. &nbsp;See
+ the <a href="LangRef.html#modulestructure">LLVM Language Reference</a> for
+ further details on linkage types. Optionally an initializer, a name, and the
+ module to put the variable into may be specified for the global variable as
+ well.</p></li>
+
+ <li><tt>bool isConstant() const</tt>
+
+ <p>Returns true if this is a global variable that is known not to
+ be modified at runtime.</p></li>
+
+ <li><tt>bool hasInitializer()</tt>
+
+ <p>Returns true if this <tt>GlobalVariable</tt> has an intializer.</p></li>
+
+ <li><tt><a href="#Constant">Constant</a> *getInitializer()</tt>
+
+ <p>Returns the initial value for a <tt>GlobalVariable</tt>. It is not legal
+ to call this method if there is no initializer.</p></li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="BasicBlock">The <tt>BasicBlock</tt> class</a>
+</h3>
+
+<div>
+
+<p><tt>#include "<a
+href="/doxygen/BasicBlock_8h-source.html">llvm/BasicBlock.h</a>"</tt><br>
+doxygen info: <a href="/doxygen/classllvm_1_1BasicBlock.html">BasicBlock
+Class</a><br>
+Superclass: <a href="#Value"><tt>Value</tt></a></p>
+
+<p>This class represents a single entry single exit section of the code,
+commonly known as a basic block by the compiler community. The
+<tt>BasicBlock</tt> class maintains a list of <a
+href="#Instruction"><tt>Instruction</tt></a>s, which form the body of the block.
+Matching the language definition, the last element of this list of instructions
+is always a terminator instruction (a subclass of the <a
+href="#TerminatorInst"><tt>TerminatorInst</tt></a> class).</p>
+
+<p>In addition to tracking the list of instructions that make up the block, the
+<tt>BasicBlock</tt> class also keeps track of the <a
+href="#Function"><tt>Function</tt></a> that it is embedded into.</p>
+
+<p>Note that <tt>BasicBlock</tt>s themselves are <a
+href="#Value"><tt>Value</tt></a>s, because they are referenced by instructions
+like branches and can go in the switch tables. <tt>BasicBlock</tt>s have type
+<tt>label</tt>.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="m_BasicBlock">
+ Important Public Members of the <tt>BasicBlock</tt> class
+ </a>
+</h4>
+
+<div>
+<ul>
+
+<li><tt>BasicBlock(const std::string &amp;Name = "", </tt><tt><a
+ href="#Function">Function</a> *Parent = 0)</tt>
+
+<p>The <tt>BasicBlock</tt> constructor is used to create new basic blocks for
+insertion into a function. The constructor optionally takes a name for the new
+block, and a <a href="#Function"><tt>Function</tt></a> to insert it into. If
+the <tt>Parent</tt> parameter is specified, the new <tt>BasicBlock</tt> is
+automatically inserted at the end of the specified <a
+href="#Function"><tt>Function</tt></a>, if not specified, the BasicBlock must be
+manually inserted into the <a href="#Function"><tt>Function</tt></a>.</p></li>
+
+<li><tt>BasicBlock::iterator</tt> - Typedef for instruction list iterator<br>
+<tt>BasicBlock::const_iterator</tt> - Typedef for const_iterator.<br>
+<tt>begin()</tt>, <tt>end()</tt>, <tt>front()</tt>, <tt>back()</tt>,
+<tt>size()</tt>, <tt>empty()</tt>
+STL-style functions for accessing the instruction list.
+
+<p>These methods and typedefs are forwarding functions that have the same
+semantics as the standard library methods of the same names. These methods
+expose the underlying instruction list of a basic block in a way that is easy to
+manipulate. To get the full complement of container operations (including
+operations to update the list), you must use the <tt>getInstList()</tt>
+method.</p></li>
+
+<li><tt>BasicBlock::InstListType &amp;getInstList()</tt>
+
+<p>This method is used to get access to the underlying container that actually
+holds the Instructions. This method must be used when there isn't a forwarding
+function in the <tt>BasicBlock</tt> class for the operation that you would like
+to perform. Because there are no forwarding functions for "updating"
+operations, you need to use this if you want to update the contents of a
+<tt>BasicBlock</tt>.</p></li>
+
+<li><tt><a href="#Function">Function</a> *getParent()</tt>
+
+<p> Returns a pointer to <a href="#Function"><tt>Function</tt></a> the block is
+embedded into, or a null pointer if it is homeless.</p></li>
+
+<li><tt><a href="#TerminatorInst">TerminatorInst</a> *getTerminator()</tt>
+
+<p> Returns a pointer to the terminator instruction that appears at the end of
+the <tt>BasicBlock</tt>. If there is no terminator instruction, or if the last
+instruction in the block is not a terminator, then a null pointer is
+returned.</p></li>
+
+</ul>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="Argument">The <tt>Argument</tt> class</a>
+</h3>
+
+<div>
+
+<p>This subclass of Value defines the interface for incoming formal
+arguments to a function. A Function maintains a list of its formal
+arguments. An argument has a pointer to the parent Function.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Strict"></a>
+
+ <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a> and
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/Projects.rst b/docs/Projects.rst
new file mode 100644
index 00000000000..63132887a59
--- /dev/null
+++ b/docs/Projects.rst
@@ -0,0 +1,327 @@
+.. _projects:
+
+========================
+Creating an LLVM Project
+========================
+
+.. contents::
+ :local:
+
+Overview
+========
+
+The LLVM build system is designed to facilitate the building of third party
+projects that use LLVM header files, libraries, and tools. In order to use
+these facilities, a ``Makefile`` from a project must do the following things:
+
+* Set ``make`` variables. There are several variables that a ``Makefile`` needs
+ to set to use the LLVM build system:
+
+ * ``PROJECT_NAME`` - The name by which your project is known.
+ * ``LLVM_SRC_ROOT`` - The root of the LLVM source tree.
+ * ``LLVM_OBJ_ROOT`` - The root of the LLVM object tree.
+ * ``PROJ_SRC_ROOT`` - The root of the project's source tree.
+ * ``PROJ_OBJ_ROOT`` - The root of the project's object tree.
+ * ``PROJ_INSTALL_ROOT`` - The root installation directory.
+ * ``LEVEL`` - The relative path from the current directory to the
+ project's root ``($PROJ_OBJ_ROOT)``.
+
+* Include ``Makefile.config`` from ``$(LLVM_OBJ_ROOT)``.
+
+* Include ``Makefile.rules`` from ``$(LLVM_SRC_ROOT)``.
+
+There are two ways that you can set all of these variables:
+
+* You can write your own ``Makefiles`` which hard-code these values.
+
+* You can use the pre-made LLVM sample project. This sample project includes
+ ``Makefiles``, a configure script that can be used to configure the location
+ of LLVM, and the ability to support multiple object directories from a single
+ source directory.
+
+This document assumes that you will base your project on the LLVM sample project
+found in ``llvm/projects/sample``. If you want to devise your own build system,
+studying the sample project and LLVM ``Makefiles`` will probably provide enough
+information on how to write your own ``Makefiles``.
+
+Create a Project from the Sample Project
+========================================
+
+Follow these simple steps to start your project:
+
+1. Copy the ``llvm/projects/sample`` directory to any place of your choosing.
+ You can place it anywhere you like. Rename the directory to match the name
+ of your project.
+
+2. If you downloaded LLVM using Subversion, remove all the directories named
+ ``.svn`` (and all the files therein) from your project's new source tree.
+ This will keep Subversion from thinking that your project is inside
+ ``llvm/trunk/projects/sample``.
+
+3. Add your source code and Makefiles to your source tree.
+
+4. If you want your project to be configured with the ``configure`` script then
+ you need to edit ``autoconf/configure.ac`` as follows:
+
+ * **AC_INIT** - Place the name of your project, its version number and a
+ contact email address for your project as the arguments to this macro
+
+ * **AC_CONFIG_AUX_DIR** - If your project isn't in the ``llvm/projects``
+ directory then you might need to adjust this so that it specifies a
+ relative path to the ``llvm/autoconf`` directory.
+
+ * **LLVM_CONFIG_PROJECT** - Just leave this alone.
+
+ * **AC_CONFIG_SRCDIR** - Specify a path to a file name that identifies your
+ project; or just leave it at ``Makefile.common.in``.
+
+ * **AC_CONFIG_FILES** - Do not change.
+
+ * **AC_CONFIG_MAKEFILE** - Use one of these macros for each Makefile that
+ your project uses. This macro arranges for your makefiles to be copied from
+ the source directory, unmodified, to the build directory.
+
+5. After updating ``autoconf/configure.ac``, regenerate the configure script
+ with these commands. (You must be using ``Autoconf`` version 2.59 or later
+ and your ``aclocal`` version should be 1.9 or later.)
+
+ .. code-block:: bash
+
+ % cd autoconf
+ % ./AutoRegen.sh
+
+6. Run ``configure`` in the directory in which you want to place object code.
+ Use the following options to tell your project where it can find LLVM:
+
+ ``--with-llvmsrc=<directory>``
+ Tell your project where the LLVM source tree is located.
+
+ ``--with-llvmobj=<directory>``
+ Tell your project where the LLVM object tree is located.
+
+ ``--prefix=<directory>``
+ Tell your project where it should get installed.
+
+That's it! Now all you have to do is type ``gmake`` (or ``make`` if you're on a
+GNU/Linux system) in the root of your object directory, and your project should
+build.
+
+Source Tree Layout
+==================
+
+In order to use the LLVM build system, you will want to organize your source
+code so that it can benefit from the build system's features. Mainly, you want
+your source tree layout to look similar to the LLVM source tree layout. The
+best way to do this is to just copy the project tree from
+``llvm/projects/sample`` and modify it to meet your needs, but you can certainly
+add to it if you want.
+
+Underneath your top level directory, you should have the following directories:
+
+**lib**
+
+ This subdirectory should contain all of your library source code. For each
+ library that you build, you will have one directory in **lib** that will
+ contain that library's source code.
+
+ Libraries can be object files, archives, or dynamic libraries. The **lib**
+ directory is just a convenient place for libraries as it places them all in
+ a directory from which they can be linked later.
+
+**include**
+
+ This subdirectory should contain any header files that are global to your
+ project. By global, we mean that they are used by more than one library or
+ executable of your project.
+
+ By placing your header files in **include**, they will be found
+ automatically by the LLVM build system. For example, if you have a file
+ **include/jazz/note.h**, then your source files can include it simply with
+ **#include "jazz/note.h"**.
+
+**tools**
+
+ This subdirectory should contain all of your source code for executables.
+ For each program that you build, you will have one directory in **tools**
+ that will contain that program's source code.
+
+**test**
+
+ This subdirectory should contain tests that verify that your code works
+ correctly. Automated tests are especially useful.
+
+ Currently, the LLVM build system provides basic support for tests. The LLVM
+ system provides the following:
+
+* LLVM provides a ``tcl`` procedure that is used by ``Dejagnu`` to run tests.
+ It can be found in ``llvm/lib/llvm-dg.exp``. This test procedure uses ``RUN``
+ lines in the actual test case to determine how to run the test. See the
+ `TestingGuide <TestingGuide.html>`_ for more details. You can easily write
+ Makefile support similar to the Makefiles in ``llvm/test`` to use ``Dejagnu``
+ to run your project's tests.
+
+* LLVM contains an optional package called ``llvm-test``, which provides
+ benchmarks and programs that are known to compile with the Clang front
+ end. You can use these programs to test your code, gather statistical
+ information, and compare it to the current LLVM performance statistics.
+
+ Currently, there is no way to hook your tests directly into the ``llvm/test``
+ testing harness. You will simply need to find a way to use the source
+ provided within that directory on your own.
+
+Typically, you will want to build your **lib** directory first followed by your
+**tools** directory.
+
+Writing LLVM Style Makefiles
+============================
+
+The LLVM build system provides a convenient way to build libraries and
+executables. Most of your project Makefiles will only need to define a few
+variables. Below is a list of the variables one can set and what they can
+do:
+
+Required Variables
+------------------
+
+``LEVEL``
+
+ This variable is the relative path from this ``Makefile`` to the top
+ directory of your project's source code. For example, if your source code
+ is in ``/tmp/src``, then the ``Makefile`` in ``/tmp/src/jump/high``
+ would set ``LEVEL`` to ``"../.."``.
+
+Variables for Building Subdirectories
+-------------------------------------
+
+``DIRS``
+
+ This is a space separated list of subdirectories that should be built. They
+ will be built, one at a time, in the order specified.
+
+``PARALLEL_DIRS``
+
+ This is a list of directories that can be built in parallel. These will be
+ built after the directories in DIRS have been built.
+
+``OPTIONAL_DIRS``
+
+ This is a list of directories that can be built if they exist, but will not
+ cause an error if they do not exist. They are built serially in the order
+ in which they are listed.
+
+Variables for Building Libraries
+--------------------------------
+
+``LIBRARYNAME``
+
+ This variable contains the base name of the library that will be built. For
+ example, to build a library named ``libsample.a``, ``LIBRARYNAME`` should
+ be set to ``sample``.
+
+``BUILD_ARCHIVE``
+
+ By default, a library is a ``.o`` file that is linked directly into a
+ program. To build an archive (also known as a static library), set the
+ ``BUILD_ARCHIVE`` variable.
+
+``SHARED_LIBRARY``
+
+ If ``SHARED_LIBRARY`` is defined in your Makefile, a shared (or dynamic)
+ library will be built.
+
+Variables for Building Programs
+-------------------------------
+
+``TOOLNAME``
+
+ This variable contains the name of the program that will be built. For
+ example, to build an executable named ``sample``, ``TOOLNAME`` should be set
+ to ``sample``.
+
+``USEDLIBS``
+
+ This variable holds a space separated list of libraries that should be
+ linked into the program. These libraries must be libraries that come from
+ your **lib** directory. The libraries must be specified without their
+ ``lib`` prefix. For example, to link ``libsample.a``, you would set
+ ``USEDLIBS`` to ``sample.a``.
+
+ Note that this works only for statically linked libraries.
+
+``LLVMLIBS``
+
+ This variable holds a space separated list of libraries that should be
+ linked into the program. These libraries must be LLVM libraries. The
+ libraries must be specified without their ``lib`` prefix. For example, to
+ link with a driver that performs an IR transformation you might set
+ ``LLVMLIBS`` to this minimal set of libraries ``LLVMSupport.a LLVMCore.a
+ LLVMBitReader.a LLVMAsmParser.a LLVMAnalysis.a LLVMTransformUtils.a
+ LLVMScalarOpts.a LLVMTarget.a``.
+
+ Note that this works only for statically linked libraries. LLVM is split
+ into a large number of static libraries, and the list of libraries you
+ require may be much longer than the list above. To see a full list of
+ libraries use: ``llvm-config --libs all``. Using ``LINK_COMPONENTS`` as
+ described below, obviates the need to set ``LLVMLIBS``.
+
+``LINK_COMPONENTS``
+
+ This variable holds a space separated list of components that the LLVM
+ ``Makefiles`` pass to the ``llvm-config`` tool to generate a link line for
+ the program. For example, to link with all LLVM libraries use
+ ``LINK_COMPONENTS = all``.
+
+``LIBS``
+
+ To link dynamic libraries, add ``-l<library base name>`` to the ``LIBS``
+ variable. The LLVM build system will look in the same places for dynamic
+ libraries as it does for static libraries.
+
+ For example, to link ``libsample.so``, you would have the following line in
+ your ``Makefile``:
+
+ .. code-block:: makefile
+
+ LIBS += -lsample
+
+Note that ``LIBS`` must occur in the Makefile after the inclusion of
+``Makefile.common``.
+
+Miscellaneous Variables
+-----------------------
+
+``CFLAGS`` & ``CPPFLAGS``
+
+ This variable can be used to add options to the C and C++ compiler,
+ respectively. It is typically used to add options that tell the compiler
+ the location of additional directories to search for header files.
+
+ It is highly suggested that you append to ``CFLAGS`` and ``CPPFLAGS`` as
+ opposed to overwriting them. The master ``Makefiles`` may already have
+ useful options in them that you may not want to overwrite.
+
+Placement of Object Code
+========================
+
+The final location of built libraries and executables will depend upon whether
+you do a ``Debug``, ``Release``, or ``Profile`` build.
+
+Libraries
+
+ All libraries (static and dynamic) will be stored in
+ ``PROJ_OBJ_ROOT/<type>/lib``, where *type* is ``Debug``, ``Release``, or
+ ``Profile`` for a debug, optimized, or profiled build, respectively.
+
+Executables
+
+ All executables will be stored in ``PROJ_OBJ_ROOT/<type>/bin``, where *type*
+ is ``Debug``, ``Release``, or ``Profile`` for a debug, optimized, or
+ profiled build, respectively.
+
+Further Help
+============
+
+If you have any questions or need any help creating an LLVM project, the LLVM
+team would be more than happy to help. You can always post your questions to
+the `LLVM Developers Mailing List
+<http://lists.cs.uiuc.edu/pipermail/llvmdev/>`_.
diff --git a/docs/README.txt b/docs/README.txt
new file mode 100644
index 00000000000..2fbbf987405
--- /dev/null
+++ b/docs/README.txt
@@ -0,0 +1,12 @@
+LLVM Documentation
+==================
+
+The LLVM documentation is currently written in two formats:
+
+ * Plain HTML documentation.
+
+ * reStructured Text documentation using the Sphinx documentation generator. It
+ is currently tested with Sphinx 1.1.3.
+
+ For more information, see the "Sphinx Introduction for LLVM Developers"
+ document.
diff --git a/docs/ReleaseNotes.html b/docs/ReleaseNotes.html
new file mode 100644
index 00000000000..75a6fd1ca10
--- /dev/null
+++ b/docs/ReleaseNotes.html
@@ -0,0 +1,755 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+ <title>LLVM 3.2 Release Notes</title>
+</head>
+<body>
+
+<h1>LLVM 3.2 Release Notes</h1>
+
+<div>
+<img style="float:right" src="http://llvm.org/img/DragonSmall.png"
+ width="136" height="136" alt="LLVM Dragon Logo">
+</div>
+
+<ol>
+ <li><a href="#intro">Introduction</a></li>
+ <li><a href="#subproj">Sub-project Status Update</a></li>
+ <li><a href="#externalproj">External Projects Using LLVM 3.2</a></li>
+ <li><a href="#whatsnew">What's New in LLVM?</a></li>
+ <li><a href="GettingStarted.html">Installation Instructions</a></li>
+ <li><a href="#knownproblems">Known Problems</a></li>
+ <li><a href="#additionalinfo">Additional Information</a></li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by the <a href="http://llvm.org/">LLVM Team</a></p>
+</div>
+
+<h1 style="color:red">These are in-progress notes for the upcoming LLVM 3.2
+release.<br>
+You may prefer the
+<a href="http://llvm.org/releases/3.1/docs/ReleaseNotes.html">LLVM 3.1
+Release Notes</a>.</h1>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="intro">Introduction</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This document contains the release notes for the LLVM Compiler
+ Infrastructure, release 3.2. Here we describe the status of LLVM, including
+ major improvements from the previous release, improvements in various
+ subprojects of LLVM, and some of the current users of the code. All LLVM
+ releases may be downloaded from the <a href="http://llvm.org/releases/">LLVM
+ releases web site</a>.</p>
+
+<p>For more information about LLVM, including information about the latest
+ release, please check out the <a href="http://llvm.org/">main LLVM web
+ site</a>. If you have questions or comments,
+ the <a href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">LLVM
+ Developer's Mailing List</a> is a good place to send them.</p>
+
+<p>Note that if you are reading this file from a Subversion checkout or the main
+ LLVM web page, this document applies to the <i>next</i> release, not the
+ current one. To see the release notes for a specific release, please see the
+ <a href="http://llvm.org/releases/">releases page</a>.</p>
+
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="subproj">Sub-project Status Update</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The LLVM 3.2 distribution currently consists of code from the core LLVM
+ repository, which roughly includes the LLVM optimizers, code generators and
+ supporting tools, and the Clang repository. In addition to this code, the
+ LLVM Project includes other sub-projects that are in development. Here we
+ include updates on these subprojects.</p>
+
+<!--=========================================================================-->
+<h3>
+<a name="clang">Clang: C/C++/Objective-C Frontend Toolkit</a>
+</h3>
+
+<div>
+
+<p><a href="http://clang.llvm.org/">Clang</a> is an LLVM front end for the C,
+ C++, and Objective-C languages. Clang aims to provide a better user
+ experience through expressive diagnostics, a high level of conformance to
+ language standards, fast compilation, and low memory use. Like LLVM, Clang
+ provides a modular, library-based architecture that makes it suitable for
+ creating or integrating with other development tools. Clang is considered a
+ production-quality compiler for C, Objective-C, C++ and Objective-C++ on x86
+ (32- and 64-bit), and for Darwin/ARM targets.</p>
+
+<p>In the LLVM 3.2 time-frame, the Clang team has made many improvements.
+ Highlights include:</p>
+<ul>
+ <li>...</li>
+</ul>
+
+<p>For more details about the changes to Clang since the 3.1 release, see the
+ <a href="http://clang.llvm.org/docs/ReleaseNotes.html">Clang release
+ notes.</a></p>
+
+<p>If Clang rejects your code but another compiler accepts it, please take a
+ look at the <a href="http://clang.llvm.org/compatibility.html">language
+ compatibility</a> guide to make sure this is not intentional or a known
+ issue.</p>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="dragonegg">DragonEgg: GCC front-ends, LLVM back-end</a>
+</h3>
+
+<div>
+
+<p><a href="http://dragonegg.llvm.org/">DragonEgg</a> is a
+ <a href="http://gcc.gnu.org/wiki/plugins">gcc plugin</a> that replaces GCC's
+ optimizers and code generators with LLVM's. It works with gcc-4.5 and gcc-4.6
+ (and partially with gcc-4.7), can target the x86-32/x86-64 and ARM processor
+ families, and has been successfully used on the Darwin, FreeBSD, KFreeBSD,
+ Linux and OpenBSD platforms. It fully supports Ada, C, C++ and Fortran. It
+ has partial support for Go, Java, Obj-C and Obj-C++.</p>
+
+<p>The 3.2 release has the following notable changes:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="compiler-rt">compiler-rt: Compiler Runtime Library</a>
+</h3>
+
+<div>
+
+<p>The new LLVM <a href="http://compiler-rt.llvm.org/">compiler-rt project</a>
+ is a simple library that provides an implementation of the low-level
+ target-specific hooks required by code generation and other runtime
+ components. For example, when compiling for a 32-bit target, converting a
+ double to a 64-bit unsigned integer is compiled into a runtime call to the
+ <code>__fixunsdfdi</code> function. The compiler-rt library provides highly
+ optimized implementations of this and other low-level routines (some are 3x
+ faster than the equivalent libgcc routines).</p>
+
+<p>The 3.2 release has the following notable changes:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="lldb">LLDB: Low Level Debugger</a>
+</h3>
+
+<div>
+
+<p><a href="http://lldb.llvm.org">LLDB</a> is a ground-up implementation of a
+ command line debugger, as well as a debugger API that can be used from other
+ applications. LLDB makes use of the Clang parser to provide high-fidelity
+ expression parsing (particularly for C++) and uses the LLVM JIT for target
+ support.</p>
+
+<p>The 3.2 release has the following notable changes:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="libc++">libc++: C++ Standard Library</a>
+</h3>
+
+<div>
+
+<p>Like compiler_rt, libc++ is now <a href="DeveloperPolicy.html#license">dual
+ licensed</a> under the MIT and UIUC license, allowing it to be used more
+ permissively.</p>
+
+<p>Within the LLVM 3.2 time-frame there were the following highlights:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="vmkit">VMKit</a>
+</h3>
+
+<div>
+
+<p>The <a href="http://vmkit.llvm.org/">VMKit project</a> is an implementation
+ of a Java Virtual Machine (Java VM or JVM) that uses LLVM for static and
+ just-in-time compilation.</p>
+
+<p>The 3.2 release has the following notable changes:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+
+<!--=========================================================================-->
+<h3>
+<a name="Polly">Polly: Polyhedral Optimizer</a>
+</h3>
+
+<div>
+
+<p><a href="http://polly.llvm.org/">Polly</a> is an <em>experimental</em>
+ optimizer for data locality and parallelism. It currently provides high-level
+ loop optimizations and automatic parallelisation (using the OpenMP run time).
+ Work in the area of automatic SIMD and accelerator code generation was
+ started.</p>
+
+<p>Within the LLVM 3.2 time-frame there were the following highlights:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="externalproj">External Open Source Projects Using LLVM 3.2</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>An exciting aspect of LLVM is that it is used as an enabling technology for
+ a lot of other language and tools projects. This section lists some of the
+ projects that have already been updated to work with LLVM 3.2.</p>
+
+<h3>Crack</h3>
+
+<div>
+
+<p><a href="http://code.google.com/p/crack-language/">Crack</a> aims to provide
+ the ease of development of a scripting language with the performance of a
+ compiled language. The language derives concepts from C++, Java and Python,
+ incorporating object-oriented programming, operator overloading and strong
+ typing.</p>
+
+</div>
+
+<h3>FAUST</h3>
+
+<div>
+
+<p><a href="http://faust.grame.fr/">FAUST</a> is a compiled language for
+ real-time audio signal processing. The name FAUST stands for Functional
+ AUdio STream. Its programming model combines two approaches: functional
+ programming and block diagram composition. In addition with the C, C++, Java,
+ JavaScript output formats, the Faust compiler can generate LLVM bitcode, and
+ works with LLVM 2.7-3.1.</p>
+
+</div>
+
+<h3>Glasgow Haskell Compiler (GHC)</h3>
+
+<div>
+
+<p><a href="http://www.haskell.org/ghc/">GHC</a> is an open source compiler and
+ programming suite for Haskell, a lazy functional programming language. It
+ includes an optimizing static compiler generating good code for a variety of
+ platforms, together with an interactive system for convenient, quick
+ development.</p>
+
+<p>GHC 7.0 and onwards include an LLVM code generator, supporting LLVM 2.8 and
+ later.</p>
+
+</div>
+
+<h3>Julia</h3>
+
+<div>
+
+<p><a href="https://github.com/JuliaLang/julia">Julia</a> is a high-level,
+ high-performance dynamic language for technical computing. It provides a
+ sophisticated compiler, distributed parallel execution, numerical accuracy,
+ and an extensive mathematical function library. The compiler uses type
+ inference to generate fast code without any type declarations, and uses
+ LLVM's optimization passes and JIT compiler. The
+ <a href="http://julialang.org/"> Julia Language</a> is designed
+ around multiple dispatch, giving programs a large degree of flexibility. It
+ is ready for use on many kinds of problems.</p>
+
+</div>
+
+<h3>LLVM D Compiler</h3>
+
+<div>
+
+<p><a href="https://github.com/ldc-developers/ldc">LLVM D Compiler</a> (LDC) is
+ a compiler for the D programming Language. It is based on the DMD frontend
+ and uses LLVM as backend.</p>
+
+</div>
+
+<h3>Open Shading Language</h3>
+
+<div>
+
+<p><a href="https://github.com/imageworks/OpenShadingLanguage/">Open Shading
+ Language (OSL)</a> is a small but rich language for programmable shading in
+ advanced global illumination renderers and other applications, ideal for
+ describing materials, lights, displacement, and pattern generation. It uses
+ LLVM to JIT complex shader networks to x86 code at runtime.</p>
+
+<p>OSL was developed by Sony Pictures Imageworks for use in its in-house
+ renderer used for feature film animation and visual effects, and is
+ distributed as open source software with the "New BSD" license.</p>
+
+</div>
+
+<h3>Portable OpenCL (pocl)</h3>
+
+<div>
+
+<p>In addition to producing an easily portable open source OpenCL
+ implementation, another major goal of <a href="http://pocl.sourceforge.net/">
+ pocl</a> is improving performance portability of OpenCL programs with
+ compiler optimizations, reducing the need for target-dependent manual
+ optimizations. An important part of pocl is a set of LLVM passes used to
+ statically parallelize multiple work-items with the kernel compiler, even in
+ the presence of work-group barriers. This enables static parallelization of
+ the fine-grained static concurrency in the work groups in multiple ways
+ (SIMD, VLIW, superscalar,...).</p>
+
+</div>
+
+<h3>Pure</h3>
+
+<div>
+
+<p><a href="http://pure-lang.googlecode.com/">Pure</a> is an
+ algebraic/functional programming language based on term rewriting. Programs
+ are collections of equations which are used to evaluate expressions in a
+ symbolic fashion. The interpreter uses LLVM as a backend to JIT-compile Pure
+ programs to fast native code. Pure offers dynamic typing, eager and lazy
+ evaluation, lexical closures, a hygienic macro system (also based on term
+ rewriting), built-in list and matrix support (including list and matrix
+ comprehensions) and an easy-to-use interface to C and other programming
+ languages (including the ability to load LLVM bitcode modules, and inline C,
+ C++, Fortran and Faust code in Pure programs if the corresponding
+ LLVM-enabled compilers are installed).</p>
+
+<p>Pure version 0.54 has been tested and is known to work with LLVM 3.1 (and
+ continues to work with older LLVM releases >= 2.5).</p>
+
+</div>
+
+<h3>TTA-based Co-design Environment (TCE)</h3>
+
+<div>
+
+<p><a href="http://tce.cs.tut.fi/">TCE</a> is a toolset for designing
+ application-specific processors (ASP) based on the Transport triggered
+ architecture (TTA). The toolset provides a complete co-design flow from C/C++
+ programs down to synthesizable VHDL/Verilog and parallel program binaries.
+ Processor customization points include the register files, function units,
+ supported operations, and the interconnection network.</p>
+
+<p>TCE uses Clang and LLVM for C/C++ language support, target independent
+ optimizations and also for parts of code generation. It generates new
+ LLVM-based code generators "on the fly" for the designed TTA processors and
+ loads them in to the compiler backend as runtime libraries to avoid
+ per-target recompilation of larger parts of the compiler chain.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="whatsnew">What's New in LLVM 3.2?</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This release includes a huge number of bug fixes, performance tweaks and
+ minor improvements. Some of the major improvements and new features are
+ listed in this section.</p>
+
+<!--=========================================================================-->
+<h3>
+<a name="majorfeatures">Major New Features</a>
+</h3>
+
+<div>
+
+ <!-- Features that need text if they're finished for 3.2:
+ ARM EHABI
+ combiner-aa?
+ strong phi elim
+ loop dependence analysis
+ CorrelatedValuePropagation
+ lib/Transforms/IPO/MergeFunctions.cpp => consider for 3.2.
+ Integrated assembler on by default for arm/thumb?
+
+ -->
+
+ <!-- Near dead:
+ Analysis/RegionInfo.h + Dom Frontiers
+ SparseBitVector: used in LiveVar.
+ llvm/lib/Archive - replace with lib object?
+ -->
+
+<p>LLVM 3.2 includes several major changes and big features:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+
+<!--=========================================================================-->
+<h3>
+<a name="coreimprovements">LLVM IR and Core Improvements</a>
+</h3>
+
+<div>
+
+<p>LLVM IR has several new features for better support of new targets and that
+ expose new optimization opportunities:</p>
+
+<ul>
+ <li>Thread local variables may have a specified TLS model. See the
+ <a href="LangRef.html#globalvars">Language Reference Manual</a>.</li>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="optimizer">Optimizer Improvements</a>
+</h3>
+
+<div>
+
+<p>In addition to many minor performance tweaks and bug fixes, this release
+ includes a few major enhancements and additions to the optimizers:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="mc">MC Level Improvements</a>
+</h3>
+
+<div>
+
+<p>The LLVM Machine Code (aka MC) subsystem was created to solve a number of
+ problems in the realm of assembly, disassembly, object file format handling,
+ and a number of other related areas that CPU instruction-set level tools work
+ in. For more information, please see the
+ <a href="http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html">Intro
+ to the LLVM MC Project Blog Post</a>.</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="codegen">Target Independent Code Generator Improvements</a>
+</h3>
+
+<div>
+
+<p>Stack Coloring - We have implemented a new optimization pass
+ to merge stack objects which are used in disjoin areas of the code.
+ This optimization reduces the required stack space significantly, in cases
+ where it is clear to the optimizer that the stack slot is not shared.
+ We use the lifetime markers to tell the codegen that a certain alloca
+ is used within a region.</p>
+
+<p>We have put a significant amount of work into the code generator
+ infrastructure, which allows us to implement more aggressive algorithms and
+ make it run faster:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+<p> We added new TableGen infrastructure to support bundling for
+ Very Long Instruction Word (VLIW) architectures. TableGen can now
+ automatically generate a deterministic finite automaton from a VLIW
+ target's schedule description which can be queried to determine
+ legal groupings of instructions in a bundle.</p>
+
+<p> We have added a new target independent VLIW packetizer based on the
+ DFA infrastructure to group machine instructions into bundles.</p>
+
+</div>
+
+<h4>
+<a name="blockplacement">Basic Block Placement</a>
+</h4>
+
+<div>
+
+<p>A probability based block placement and code layout algorithm was added to
+ LLVM's code generator. This layout pass supports probabilities derived from
+ static heuristics as well as source code annotations such as
+ <code>__builtin_expect</code>.</p>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="x86">X86-32 and X86-64 Target Improvements</a>
+</h3>
+
+<div>
+
+<p>New features and major changes in the X86 target include:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="ARM">ARM Target Improvements</a>
+</h3>
+
+<div>
+
+<p>New features of the ARM target include:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+<!--_________________________________________________________________________-->
+
+<h4>
+<a name="armintegratedassembler">ARM Integrated Assembler</a>
+</h4>
+
+<div>
+
+<p>The ARM target now includes a full featured macro assembler, including
+ direct-to-object module support for clang. The assembler is currently enabled
+ by default for Darwin only pending testing and any additional necessary
+ platform specific support for Linux.</p>
+
+<p>Full support is included for Thumb1, Thumb2 and ARM modes, along with
+ subtarget and CPU specific extensions for VFP2, VFP3 and NEON.</p>
+
+<p>The assembler is Unified Syntax only (see ARM Architecural Reference Manual
+ for details). While there is some, and growing, support for pre-unfied
+ (divided) syntax, there are still significant gaps in that support.</p>
+
+</div>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="MIPS">MIPS Target Improvements</a>
+</h3>
+
+<div>
+
+<p>New features and major changes in the MIPS target include:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="OtherTS">Other Target Specific Improvements</a>
+</h3>
+
+<div>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="changes">Major Changes and Removed Features</a>
+</h3>
+
+<div>
+
+<p>If you're already an LLVM user or developer with out-of-tree changes based on
+ LLVM 3.2, this section lists some "gotchas" that you may run into upgrading
+ from the previous release.</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="api_changes">Internal API Changes</a>
+</h3>
+
+<div>
+
+<p>In addition, many APIs have changed in this release. Some of the major
+ LLVM API changes are:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+<!--=========================================================================-->
+<h3>
+<a name="tools_changes">Tools Changes</a>
+</h3>
+
+<div>
+
+<p>In addition, some tools have changed in this release. Some of the changes
+ are:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+
+<!--=========================================================================-->
+<h3>
+<a name="python">Python Bindings</a>
+</h3>
+
+<div>
+
+<p>Officially supported Python bindings have been added! Feature support is far
+ from complete. The current bindings support interfaces to:</p>
+
+<ul>
+ <li>...</li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="knownproblems">Known Problems</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>LLVM is generally a production quality compiler, and is used by a broad range
+ of applications and shipping in many products. That said, not every
+ subsystem is as mature as the aggregate, particularly the more obscure
+ targets. If you run into a problem, please check
+ the <a href="http://llvm.org/bugs/">LLVM bug database</a> and submit a bug if
+ there isn't already one or ask on
+ the <a href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">LLVMdev
+ list</a>.</p>
+
+ <p>Known problem areas include:</p>
+
+<ul>
+ <li>The CellSPU, MSP430, PTX and XCore backends are experimental.</li>
+
+ <li>The integrated assembler, disassembler, and JIT is not supported by
+ several targets. If an integrated assembler is not supported, then a
+ system assembler is required. For more details, see the <a
+ href="CodeGenerator.html#targetfeatures">Target Features Matrix</a>.
+ </li>
+</ul>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="additionalinfo">Additional Information</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>A wide variety of additional information is available on
+ the <a href="http://llvm.org/">LLVM web page</a>, in particular in
+ the <a href="http://llvm.org/docs/">documentation</a> section. The web page
+ also contains versions of the API documentation which is up-to-date with the
+ Subversion version of the source code. You can access versions of these
+ documents specific to this release by going into the "<tt>llvm/doc/</tt>"
+ directory in the LLVM tree.</p>
+
+<p>If you have any questions or comments about LLVM, please feel free to contact
+ us via the <a href="http://llvm.org/docs/#maillist"> mailing lists</a>.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/SegmentedStacks.rst b/docs/SegmentedStacks.rst
new file mode 100644
index 00000000000..f97d62abda0
--- /dev/null
+++ b/docs/SegmentedStacks.rst
@@ -0,0 +1,80 @@
+.. _segmented_stacks:
+
+========================
+Segmented Stacks in LLVM
+========================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+Segmented stack allows stack space to be allocated incrementally than as a
+monolithic chunk (of some worst case size) at thread initialization. This is
+done by allocating stack blocks (henceforth called *stacklets*) and linking them
+into a doubly linked list. The function prologue is responsible for checking if
+the current stacklet has enough space for the function to execute; and if not,
+call into the libgcc runtime to allocate more stack space. When using ``llc``,
+segmented stacks can be enabled by adding ``-segmented-stacks`` to the command
+line.
+
+The runtime functionality is `already there in libgcc
+<http://gcc.gnu.org/wiki/SplitStacks>`_.
+
+Implementation Details
+======================
+
+.. _allocating stacklets:
+
+Allocating Stacklets
+--------------------
+
+As mentioned above, the function prologue checks if the current stacklet has
+enough space. The current approach is to use a slot in the TCB to store the
+current stack limit (minus the amount of space needed to allocate a new block) -
+this slot's offset is again dictated by ``libgcc``. The generated
+assembly looks like this on x86-64:
+
+.. code-block:: nasm
+
+ leaq -8(%rsp), %r10
+ cmpq %fs:112, %r10
+ jg .LBB0_2
+
+ # More stack space needs to be allocated
+ movabsq $8, %r10 # The amount of space needed
+ movabsq $0, %r11 # The total size of arguments passed on stack
+ callq __morestack
+ ret # The reason for this extra return is explained below
+ .LBB0_2:
+ # Usual prologue continues here
+
+The size of function arguments on the stack needs to be passed to
+``__morestack`` (this function is implemented in ``libgcc``) since that number
+of bytes has to be copied from the previous stacklet to the current one. This is
+so that SP (and FP) relative addressing of function arguments work as expected.
+
+The unusual ``ret`` is needed to have the function which made a call to
+``__morestack`` return correctly. ``__morestack``, instead of returning, calls
+into ``.LBB0_2``. This is possible since both, the size of the ``ret``
+instruction and the PC of call to ``__morestack`` are known. When the function
+body returns, control is transferred back to ``__morestack``. ``__morestack``
+then de-allocates the new stacklet, restores the correct SP value, and does a
+second return, which returns control to the correct caller.
+
+Variable Sized Allocas
+----------------------
+
+The section on `allocating stacklets`_ automatically assumes that every stack
+frame will be of fixed size. However, LLVM allows the use of the ``llvm.alloca``
+intrinsic to allocate dynamically sized blocks of memory on the stack. When
+faced with such a variable-sized alloca, code is generated to:
+
+* Check if the current stacklet has enough space. If yes, just bump the SP, like
+ in the normal case.
+* If not, generate a call to ``libgcc``, which allocates the memory from the
+ heap.
+
+The memory allocated from the heap is linked into a list in the current
+stacklet, and freed along with the same. This prevents a memory leak.
diff --git a/docs/SourceLevelDebugging.html b/docs/SourceLevelDebugging.html
new file mode 100644
index 00000000000..918383bc213
--- /dev/null
+++ b/docs/SourceLevelDebugging.html
@@ -0,0 +1,2858 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Source Level Debugging with LLVM</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>Source Level Debugging with LLVM</h1>
+
+<table class="layout" style="width:100%">
+ <tr class="layout">
+ <td class="left">
+<ul>
+ <li><a href="#introduction">Introduction</a>
+ <ol>
+ <li><a href="#phil">Philosophy behind LLVM debugging information</a></li>
+ <li><a href="#consumers">Debug information consumers</a></li>
+ <li><a href="#debugopt">Debugging optimized code</a></li>
+ </ol></li>
+ <li><a href="#format">Debugging information format</a>
+ <ol>
+ <li><a href="#debug_info_descriptors">Debug information descriptors</a>
+ <ul>
+ <li><a href="#format_compile_units">Compile unit descriptors</a></li>
+ <li><a href="#format_files">File descriptors</a></li>
+ <li><a href="#format_global_variables">Global variable descriptors</a></li>
+ <li><a href="#format_subprograms">Subprogram descriptors</a></li>
+ <li><a href="#format_blocks">Block descriptors</a></li>
+ <li><a href="#format_basic_type">Basic type descriptors</a></li>
+ <li><a href="#format_derived_type">Derived type descriptors</a></li>
+ <li><a href="#format_composite_type">Composite type descriptors</a></li>
+ <li><a href="#format_subrange">Subrange descriptors</a></li>
+ <li><a href="#format_enumeration">Enumerator descriptors</a></li>
+ <li><a href="#format_variables">Local variables</a></li>
+ </ul></li>
+ <li><a href="#format_common_intrinsics">Debugger intrinsic functions</a>
+ <ul>
+ <li><a href="#format_common_declare">llvm.dbg.declare</a></li>
+ <li><a href="#format_common_value">llvm.dbg.value</a></li>
+ </ul></li>
+ </ol></li>
+ <li><a href="#format_common_lifetime">Object lifetimes and scoping</a></li>
+ <li><a href="#ccxx_frontend">C/C++ front-end specific debug information</a>
+ <ol>
+ <li><a href="#ccxx_compile_units">C/C++ source file information</a></li>
+ <li><a href="#ccxx_global_variable">C/C++ global variable information</a></li>
+ <li><a href="#ccxx_subprogram">C/C++ function information</a></li>
+ <li><a href="#ccxx_basic_types">C/C++ basic types</a></li>
+ <li><a href="#ccxx_derived_types">C/C++ derived types</a></li>
+ <li><a href="#ccxx_composite_types">C/C++ struct/union types</a></li>
+ <li><a href="#ccxx_enumeration_types">C/C++ enumeration types</a></li>
+ </ol></li>
+ <li><a href="#llvmdwarfextension">LLVM Dwarf Extensions</a>
+ <ol>
+ <li><a href="#objcproperty">Debugging Information Extension
+ for Objective C Properties</a>
+ <ul>
+ <li><a href="#objcpropertyintroduction">Introduction</a></li>
+ <li><a href="#objcpropertyproposal">Proposal</a></li>
+ <li><a href="#objcpropertynewattributes">New DWARF Attributes</a></li>
+ <li><a href="#objcpropertynewconstants">New DWARF Constants</a></li>
+ </ul>
+ </li>
+ <li><a href="#acceltable">Name Accelerator Tables</a>
+ <ul>
+ <li><a href="#acceltableintroduction">Introduction</a></li>
+ <li><a href="#acceltablehashes">Hash Tables</a></li>
+ <li><a href="#acceltabledetails">Details</a></li>
+ <li><a href="#acceltablecontents">Contents</a></li>
+ <li><a href="#acceltableextensions">Language Extensions and File Format Changes</a></li>
+ </ul>
+ </li>
+ </ol>
+ </li>
+</ul>
+</td>
+</tr></table>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:jlaskey@mac.com">Jim Laskey</a></p>
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2><a name="introduction">Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This document is the central repository for all information pertaining to
+ debug information in LLVM. It describes the <a href="#format">actual format
+ that the LLVM debug information</a> takes, which is useful for those
+ interested in creating front-ends or dealing directly with the information.
+ Further, this document provides specific examples of what debug information
+ for C/C++ looks like.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="phil">Philosophy behind LLVM debugging information</a>
+</h3>
+
+<div>
+
+<p>The idea of the LLVM debugging information is to capture how the important
+ pieces of the source-language's Abstract Syntax Tree map onto LLVM code.
+ Several design aspects have shaped the solution that appears here. The
+ important ones are:</p>
+
+<ul>
+ <li>Debugging information should have very little impact on the rest of the
+ compiler. No transformations, analyses, or code generators should need to
+ be modified because of debugging information.</li>
+
+ <li>LLVM optimizations should interact in <a href="#debugopt">well-defined and
+ easily described ways</a> with the debugging information.</li>
+
+ <li>Because LLVM is designed to support arbitrary programming languages,
+ LLVM-to-LLVM tools should not need to know anything about the semantics of
+ the source-level-language.</li>
+
+ <li>Source-level languages are often <b>widely</b> different from one another.
+ LLVM should not put any restrictions of the flavor of the source-language,
+ and the debugging information should work with any language.</li>
+
+ <li>With code generator support, it should be possible to use an LLVM compiler
+ to compile a program to native machine code and standard debugging
+ formats. This allows compatibility with traditional machine-code level
+ debuggers, like GDB or DBX.</li>
+</ul>
+
+<p>The approach used by the LLVM implementation is to use a small set
+ of <a href="#format_common_intrinsics">intrinsic functions</a> to define a
+ mapping between LLVM program objects and the source-level objects. The
+ description of the source-level program is maintained in LLVM metadata
+ in an <a href="#ccxx_frontend">implementation-defined format</a>
+ (the C/C++ front-end currently uses working draft 7 of
+ the <a href="http://www.eagercon.com/dwarf/dwarf3std.htm">DWARF 3
+ standard</a>).</p>
+
+<p>When a program is being debugged, a debugger interacts with the user and
+ turns the stored debug information into source-language specific information.
+ As such, a debugger must be aware of the source-language, and is thus tied to
+ a specific language or family of languages.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="consumers">Debug information consumers</a>
+</h3>
+
+<div>
+
+<p>The role of debug information is to provide meta information normally
+ stripped away during the compilation process. This meta information provides
+ an LLVM user a relationship between generated code and the original program
+ source code.</p>
+
+<p>Currently, debug information is consumed by DwarfDebug to produce dwarf
+ information used by the gdb debugger. Other targets could use the same
+ information to produce stabs or other debug forms.</p>
+
+<p>It would also be reasonable to use debug information to feed profiling tools
+ for analysis of generated code, or, tools for reconstructing the original
+ source from generated code.</p>
+
+<p>TODO - expound a bit more.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="debugopt">Debugging optimized code</a>
+</h3>
+
+<div>
+
+<p>An extremely high priority of LLVM debugging information is to make it
+ interact well with optimizations and analysis. In particular, the LLVM debug
+ information provides the following guarantees:</p>
+
+<ul>
+ <li>LLVM debug information <b>always provides information to accurately read
+ the source-level state of the program</b>, regardless of which LLVM
+ optimizations have been run, and without any modification to the
+ optimizations themselves. However, some optimizations may impact the
+ ability to modify the current state of the program with a debugger, such
+ as setting program variables, or calling functions that have been
+ deleted.</li>
+
+ <li>As desired, LLVM optimizations can be upgraded to be aware of the LLVM
+ debugging information, allowing them to update the debugging information
+ as they perform aggressive optimizations. This means that, with effort,
+ the LLVM optimizers could optimize debug code just as well as non-debug
+ code.</li>
+
+ <li>LLVM debug information does not prevent optimizations from
+ happening (for example inlining, basic block reordering/merging/cleanup,
+ tail duplication, etc).</li>
+
+ <li>LLVM debug information is automatically optimized along with the rest of
+ the program, using existing facilities. For example, duplicate
+ information is automatically merged by the linker, and unused information
+ is automatically removed.</li>
+</ul>
+
+<p>Basically, the debug information allows you to compile a program with
+ "<tt>-O0 -g</tt>" and get full debug information, allowing you to arbitrarily
+ modify the program as it executes from a debugger. Compiling a program with
+ "<tt>-O3 -g</tt>" gives you full debug information that is always available
+ and accurate for reading (e.g., you get accurate stack traces despite tail
+ call elimination and inlining), but you might lose the ability to modify the
+ program and call functions where were optimized out of the program, or
+ inlined away completely.</p>
+
+<p><a href="TestingGuide.html#quicktestsuite">LLVM test suite</a> provides a
+ framework to test optimizer's handling of debugging information. It can be
+ run like this:</p>
+
+<div class="doc_code">
+<pre>
+% cd llvm/projects/test-suite/MultiSource/Benchmarks # or some other level
+% make TEST=dbgopt
+</pre>
+</div>
+
+<p>This will test impact of debugging information on optimization passes. If
+ debugging information influences optimization passes then it will be reported
+ as a failure. See <a href="TestingGuide.html">TestingGuide</a> for more
+ information on LLVM test infrastructure and how to run various tests.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="format">Debugging information format</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>LLVM debugging information has been carefully designed to make it possible
+ for the optimizer to optimize the program and debugging information without
+ necessarily having to know anything about debugging information. In
+ particular, the use of metadata avoids duplicated debugging information from
+ the beginning, and the global dead code elimination pass automatically
+ deletes debugging information for a function if it decides to delete the
+ function. </p>
+
+<p>To do this, most of the debugging information (descriptors for types,
+ variables, functions, source files, etc) is inserted by the language
+ front-end in the form of LLVM metadata. </p>
+
+<p>Debug information is designed to be agnostic about the target debugger and
+ debugging information representation (e.g. DWARF/Stabs/etc). It uses a
+ generic pass to decode the information that represents variables, types,
+ functions, namespaces, etc: this allows for arbitrary source-language
+ semantics and type-systems to be used, as long as there is a module
+ written for the target debugger to interpret the information. </p>
+
+<p>To provide basic functionality, the LLVM debugger does have to make some
+ assumptions about the source-level language being debugged, though it keeps
+ these to a minimum. The only common features that the LLVM debugger assumes
+ exist are <a href="#format_files">source files</a>,
+ and <a href="#format_global_variables">program objects</a>. These abstract
+ objects are used by a debugger to form stack traces, show information about
+ local variables, etc.</p>
+
+<p>This section of the documentation first describes the representation aspects
+ common to any source-language. The <a href="#ccxx_frontend">next section</a>
+ describes the data layout conventions used by the C and C++ front-ends.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="debug_info_descriptors">Debug information descriptors</a>
+</h3>
+
+<div>
+
+<p>In consideration of the complexity and volume of debug information, LLVM
+ provides a specification for well formed debug descriptors. </p>
+
+<p>Consumers of LLVM debug information expect the descriptors for program
+ objects to start in a canonical format, but the descriptors can include
+ additional information appended at the end that is source-language
+ specific. All LLVM debugging information is versioned, allowing backwards
+ compatibility in the case that the core structures need to change in some
+ way. Also, all debugging information objects start with a tag to indicate
+ what type of object it is. The source-language is allowed to define its own
+ objects, by using unreserved tag numbers. We recommend using with tags in
+ the range 0x1000 through 0x2000 (there is a defined enum DW_TAG_user_base =
+ 0x1000.)</p>
+
+<p>The fields of debug descriptors used internally by LLVM
+ are restricted to only the simple data types <tt>i32</tt>, <tt>i1</tt>,
+ <tt>float</tt>, <tt>double</tt>, <tt>mdstring</tt> and <tt>mdnode</tt>. </p>
+
+<div class="doc_code">
+<pre>
+!1 = metadata !{
+ i32, ;; A tag
+ ...
+}
+</pre>
+</div>
+
+<p><a name="LLVMDebugVersion">The first field of a descriptor is always an
+ <tt>i32</tt> containing a tag value identifying the content of the
+ descriptor. The remaining fields are specific to the descriptor. The values
+ of tags are loosely bound to the tag values of DWARF information entries.
+ However, that does not restrict the use of the information supplied to DWARF
+ targets. To facilitate versioning of debug information, the tag is augmented
+ with the current debug version (LLVMDebugVersion = 8 &lt;&lt; 16 or
+ 0x80000 or 524288.)</a></p>
+
+<p>The details of the various descriptors follow.</p>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_compile_units">Compile unit descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!0 = metadata !{
+ i32, ;; Tag = 17 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a>
+ ;; (DW_TAG_compile_unit)
+ i32, ;; Unused field.
+ i32, ;; DWARF language identifier (ex. DW_LANG_C89)
+ metadata, ;; Source file name
+ metadata, ;; Source file directory (includes trailing slash)
+ metadata ;; Producer (ex. "4.0.1 LLVM (LLVM research group)")
+ i1, ;; True if this is a main compile unit.
+ i1, ;; True if this is optimized.
+ metadata, ;; Flags
+ i32 ;; Runtime version
+ metadata ;; List of enums types
+ metadata ;; List of retained types
+ metadata ;; List of subprograms
+ metadata ;; List of global variables
+}
+</pre>
+</div>
+
+<p>These descriptors contain a source language ID for the file (we use the DWARF
+ 3.0 ID numbers, such as <tt>DW_LANG_C89</tt>, <tt>DW_LANG_C_plus_plus</tt>,
+ <tt>DW_LANG_Cobol74</tt>, etc), three strings describing the filename,
+ working directory of the compiler, and an identifier string for the compiler
+ that produced it.</p>
+
+<p>Compile unit descriptors provide the root context for objects declared in a
+ specific compilation unit. File descriptors are defined using this context.
+ These descriptors are collected by a named metadata
+ <tt>!llvm.dbg.cu</tt>. Compile unit descriptor keeps track of subprograms,
+ global variables and type information.
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_files">File descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!0 = metadata !{
+ i32, ;; Tag = 41 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a>
+ ;; (DW_TAG_file_type)
+ metadata, ;; Source file name
+ metadata, ;; Source file directory (includes trailing slash)
+ metadata ;; Unused
+}
+</pre>
+</div>
+
+<p>These descriptors contain information for a file. Global variables and top
+ level functions would be defined using this context.k File descriptors also
+ provide context for source line correspondence. </p>
+
+<p>Each input file is encoded as a separate file descriptor in LLVM debugging
+ information output. </p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_global_variables">Global variable descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!1 = metadata !{
+ i32, ;; Tag = 52 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a>
+ ;; (DW_TAG_variable)
+ i32, ;; Unused field.
+ metadata, ;; Reference to context descriptor
+ metadata, ;; Name
+ metadata, ;; Display name (fully qualified C++ name)
+ metadata, ;; MIPS linkage name (for C++)
+ metadata, ;; Reference to file where defined
+ i32, ;; Line number where defined
+ metadata, ;; Reference to type descriptor
+ i1, ;; True if the global is local to compile unit (static)
+ i1, ;; True if the global is defined in the compile unit (not extern)
+ {}* ;; Reference to the global variable
+}
+</pre>
+</div>
+
+<p>These descriptors provide debug information about globals variables. The
+provide details such as name, type and where the variable is defined. All
+global variables are collected inside the named metadata
+<tt>!llvm.dbg.cu</tt>.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_subprograms">Subprogram descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32, ;; Tag = 46 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a>
+ ;; (DW_TAG_subprogram)
+ i32, ;; Unused field.
+ metadata, ;; Reference to context descriptor
+ metadata, ;; Name
+ metadata, ;; Display name (fully qualified C++ name)
+ metadata, ;; MIPS linkage name (for C++)
+ metadata, ;; Reference to file where defined
+ i32, ;; Line number where defined
+ metadata, ;; Reference to type descriptor
+ i1, ;; True if the global is local to compile unit (static)
+ i1, ;; True if the global is defined in the compile unit (not extern)
+ i32, ;; Line number where the scope of the subprogram begins
+ i32, ;; Virtuality, e.g. dwarf::DW_VIRTUALITY__virtual
+ i32, ;; Index into a virtual function
+ metadata, ;; indicates which base type contains the vtable pointer for the
+ ;; derived class
+ i32, ;; Flags - Artifical, Private, Protected, Explicit, Prototyped.
+ i1, ;; isOptimized
+ Function *,;; Pointer to LLVM function
+ metadata, ;; Lists function template parameters
+ metadata ;; Function declaration descriptor
+ metadata ;; List of function variables
+}
+</pre>
+</div>
+
+<p>These descriptors provide debug information about functions, methods and
+ subprograms. They provide details such as name, return types and the source
+ location where the subprogram is defined.
+</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_blocks">Block descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!3 = metadata !{
+ i32, ;; Tag = 11 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a> (DW_TAG_lexical_block)
+ metadata,;; Reference to context descriptor
+ i32, ;; Line number
+ i32, ;; Column number
+ metadata,;; Reference to source file
+ i32 ;; Unique ID to identify blocks from a template function
+}
+</pre>
+</div>
+
+<p>This descriptor provides debug information about nested blocks within a
+ subprogram. The line number and column numbers are used to dinstinguish
+ two lexical blocks at same depth. </p>
+
+<div class="doc_code">
+<pre>
+!3 = metadata !{
+ i32, ;; Tag = 11 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a> (DW_TAG_lexical_block)
+ metadata ;; Reference to the scope we're annotating with a file change
+ metadata,;; Reference to the file the scope is enclosed in.
+}
+</pre>
+</div>
+
+<p>This descriptor provides a wrapper around a lexical scope to handle file
+ changes in the middle of a lexical block.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_basic_type">Basic type descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!4 = metadata !{
+ i32, ;; Tag = 36 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a>
+ ;; (DW_TAG_base_type)
+ metadata, ;; Reference to context
+ metadata, ;; Name (may be "" for anonymous types)
+ metadata, ;; Reference to file where defined (may be NULL)
+ i32, ;; Line number where defined (may be 0)
+ i64, ;; Size in bits
+ i64, ;; Alignment in bits
+ i64, ;; Offset in bits
+ i32, ;; Flags
+ i32 ;; DWARF type encoding
+}
+</pre>
+</div>
+
+<p>These descriptors define primitive types used in the code. Example int, bool
+ and float. The context provides the scope of the type, which is usually the
+ top level. Since basic types are not usually user defined the context
+ and line number can be left as NULL and 0. The size, alignment and offset
+ are expressed in bits and can be 64 bit values. The alignment is used to
+ round the offset when embedded in a
+ <a href="#format_composite_type">composite type</a> (example to keep float
+ doubles on 64 bit boundaries.) The offset is the bit offset if embedded in
+ a <a href="#format_composite_type">composite type</a>.</p>
+
+<p>The type encoding provides the details of the type. The values are typically
+ one of the following:</p>
+
+<div class="doc_code">
+<pre>
+DW_ATE_address = 1
+DW_ATE_boolean = 2
+DW_ATE_float = 4
+DW_ATE_signed = 5
+DW_ATE_signed_char = 6
+DW_ATE_unsigned = 7
+DW_ATE_unsigned_char = 8
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_derived_type">Derived type descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!5 = metadata !{
+ i32, ;; Tag (see below)
+ metadata, ;; Reference to context
+ metadata, ;; Name (may be "" for anonymous types)
+ metadata, ;; Reference to file where defined (may be NULL)
+ i32, ;; Line number where defined (may be 0)
+ i64, ;; Size in bits
+ i64, ;; Alignment in bits
+ i64, ;; Offset in bits
+ i32, ;; Flags to encode attributes, e.g. private
+ metadata, ;; Reference to type derived from
+ metadata, ;; (optional) Name of the Objective C property associated with
+ ;; Objective-C an ivar
+ metadata, ;; (optional) Name of the Objective C property getter selector.
+ metadata, ;; (optional) Name of the Objective C property setter selector.
+ i32 ;; (optional) Objective C property attributes.
+}
+</pre>
+</div>
+
+<p>These descriptors are used to define types derived from other types. The
+value of the tag varies depending on the meaning. The following are possible
+tag values:</p>
+
+<div class="doc_code">
+<pre>
+DW_TAG_formal_parameter = 5
+DW_TAG_member = 13
+DW_TAG_pointer_type = 15
+DW_TAG_reference_type = 16
+DW_TAG_typedef = 22
+DW_TAG_const_type = 38
+DW_TAG_volatile_type = 53
+DW_TAG_restrict_type = 55
+</pre>
+</div>
+
+<p><tt>DW_TAG_member</tt> is used to define a member of
+ a <a href="#format_composite_type">composite type</a>
+ or <a href="#format_subprograms">subprogram</a>. The type of the member is
+ the <a href="#format_derived_type">derived
+ type</a>. <tt>DW_TAG_formal_parameter</tt> is used to define a member which
+ is a formal argument of a subprogram.</p>
+
+<p><tt>DW_TAG_typedef</tt> is used to provide a name for the derived type.</p>
+
+<p><tt>DW_TAG_pointer_type</tt>, <tt>DW_TAG_reference_type</tt>,
+ <tt>DW_TAG_const_type</tt>, <tt>DW_TAG_volatile_type</tt> and
+ <tt>DW_TAG_restrict_type</tt> are used to qualify
+ the <a href="#format_derived_type">derived type</a>. </p>
+
+<p><a href="#format_derived_type">Derived type</a> location can be determined
+ from the context and line number. The size, alignment and offset are
+ expressed in bits and can be 64 bit values. The alignment is used to round
+ the offset when embedded in a <a href="#format_composite_type">composite
+ type</a> (example to keep float doubles on 64 bit boundaries.) The offset is
+ the bit offset if embedded in a <a href="#format_composite_type">composite
+ type</a>.</p>
+
+<p>Note that the <tt>void *</tt> type is expressed as a type derived from NULL.
+</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_composite_type">Composite type descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!6 = metadata !{
+ i32, ;; Tag (see below)
+ metadata, ;; Reference to context
+ metadata, ;; Name (may be "" for anonymous types)
+ metadata, ;; Reference to file where defined (may be NULL)
+ i32, ;; Line number where defined (may be 0)
+ i64, ;; Size in bits
+ i64, ;; Alignment in bits
+ i64, ;; Offset in bits
+ i32, ;; Flags
+ metadata, ;; Reference to type derived from
+ metadata, ;; Reference to array of member descriptors
+ i32 ;; Runtime languages
+}
+</pre>
+</div>
+
+<p>These descriptors are used to define types that are composed of 0 or more
+elements. The value of the tag varies depending on the meaning. The following
+are possible tag values:</p>
+
+<div class="doc_code">
+<pre>
+DW_TAG_array_type = 1
+DW_TAG_enumeration_type = 4
+DW_TAG_structure_type = 19
+DW_TAG_union_type = 23
+DW_TAG_vector_type = 259
+DW_TAG_subroutine_type = 21
+DW_TAG_inheritance = 28
+</pre>
+</div>
+
+<p>The vector flag indicates that an array type is a native packed vector.</p>
+
+<p>The members of array types (tag = <tt>DW_TAG_array_type</tt>) or vector types
+ (tag = <tt>DW_TAG_vector_type</tt>) are <a href="#format_subrange">subrange
+ descriptors</a>, each representing the range of subscripts at that level of
+ indexing.</p>
+
+<p>The members of enumeration types (tag = <tt>DW_TAG_enumeration_type</tt>) are
+ <a href="#format_enumeration">enumerator descriptors</a>, each representing
+ the definition of enumeration value for the set. All enumeration type
+ descriptors are collected inside the named metadata
+ <tt>!llvm.dbg.cu</tt>.</p>
+
+<p>The members of structure (tag = <tt>DW_TAG_structure_type</tt>) or union (tag
+ = <tt>DW_TAG_union_type</tt>) types are any one of
+ the <a href="#format_basic_type">basic</a>,
+ <a href="#format_derived_type">derived</a>
+ or <a href="#format_composite_type">composite</a> type descriptors, each
+ representing a field member of the structure or union.</p>
+
+<p>For C++ classes (tag = <tt>DW_TAG_structure_type</tt>), member descriptors
+ provide information about base classes, static members and member
+ functions. If a member is a <a href="#format_derived_type">derived type
+ descriptor</a> and has a tag of <tt>DW_TAG_inheritance</tt>, then the type
+ represents a base class. If the member of is
+ a <a href="#format_global_variables">global variable descriptor</a> then it
+ represents a static member. And, if the member is
+ a <a href="#format_subprograms">subprogram descriptor</a> then it represents
+ a member function. For static members and member
+ functions, <tt>getName()</tt> returns the members link or the C++ mangled
+ name. <tt>getDisplayName()</tt> the simplied version of the name.</p>
+
+<p>The first member of subroutine (tag = <tt>DW_TAG_subroutine_type</tt>) type
+ elements is the return type for the subroutine. The remaining elements are
+ the formal arguments to the subroutine.</p>
+
+<p><a href="#format_composite_type">Composite type</a> location can be
+ determined from the context and line number. The size, alignment and
+ offset are expressed in bits and can be 64 bit values. The alignment is used
+ to round the offset when embedded in
+ a <a href="#format_composite_type">composite type</a> (as an example, to keep
+ float doubles on 64 bit boundaries.) The offset is the bit offset if embedded
+ in a <a href="#format_composite_type">composite type</a>.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_subrange">Subrange descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!42 = metadata !{
+ i32, ;; Tag = 33 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a> (DW_TAG_subrange_type)
+ i64, ;; Low value
+ i64 ;; High value
+}
+</pre>
+</div>
+
+<p>These descriptors are used to define ranges of array subscripts for an array
+ <a href="#format_composite_type">composite type</a>. The low value defines
+ the lower bounds typically zero for C/C++. The high value is the upper
+ bounds. Values are 64 bit. High - low + 1 is the size of the array. If low
+ > high the array bounds are not included in generated debugging information.
+</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_enumeration">Enumerator descriptors</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!6 = metadata !{
+ i32, ;; Tag = 40 + <a href="#LLVMDebugVersion">LLVMDebugVersion</a>
+ ;; (DW_TAG_enumerator)
+ metadata, ;; Name
+ i64 ;; Value
+}
+</pre>
+</div>
+
+<p>These descriptors are used to define members of an
+ enumeration <a href="#format_composite_type">composite type</a>, it
+ associates the name to the value.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_variables">Local variables</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!7 = metadata !{
+ i32, ;; Tag (see below)
+ metadata, ;; Context
+ metadata, ;; Name
+ metadata, ;; Reference to file where defined
+ i32, ;; 24 bit - Line number where defined
+ ;; 8 bit - Argument number. 1 indicates 1st argument.
+ metadata, ;; Type descriptor
+ i32, ;; flags
+ metadata ;; (optional) Reference to inline location
+}
+</pre>
+</div>
+
+<p>These descriptors are used to define variables local to a sub program. The
+ value of the tag depends on the usage of the variable:</p>
+
+<div class="doc_code">
+<pre>
+DW_TAG_auto_variable = 256
+DW_TAG_arg_variable = 257
+DW_TAG_return_variable = 258
+</pre>
+</div>
+
+<p>An auto variable is any variable declared in the body of the function. An
+ argument variable is any variable that appears as a formal argument to the
+ function. A return variable is used to track the result of a function and
+ has no source correspondent.</p>
+
+<p>The context is either the subprogram or block where the variable is defined.
+ Name the source variable name. Context and line indicate where the
+ variable was defined. Type descriptor defines the declared type of the
+ variable.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="format_common_intrinsics">Debugger intrinsic functions</a>
+</h3>
+
+<div>
+
+<p>LLVM uses several intrinsic functions (name prefixed with "llvm.dbg") to
+ provide debug information at various points in generated code.</p>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_common_declare">llvm.dbg.declare</a>
+</h4>
+
+<div>
+<pre>
+ void %<a href="#format_common_declare">llvm.dbg.declare</a>(metadata, metadata)
+</pre>
+
+<p>This intrinsic provides information about a local element (e.g., variable). The
+ first argument is metadata holding the alloca for the variable. The
+ second argument is metadata containing a description of the variable.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="format_common_value">llvm.dbg.value</a>
+</h4>
+
+<div>
+<pre>
+ void %<a href="#format_common_value">llvm.dbg.value</a>(metadata, i64, metadata)
+</pre>
+
+<p>This intrinsic provides information when a user source variable is set to a
+ new value. The first argument is the new value (wrapped as metadata). The
+ second argument is the offset in the user source variable where the new value
+ is written. The third argument is metadata containing a description of the
+ user source variable.</p>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="format_common_lifetime">Object lifetimes and scoping</a>
+</h3>
+
+<div>
+<p>In many languages, the local variables in functions can have their lifetimes
+ or scopes limited to a subset of a function. In the C family of languages,
+ for example, variables are only live (readable and writable) within the
+ source block that they are defined in. In functional languages, values are
+ only readable after they have been defined. Though this is a very obvious
+ concept, it is non-trivial to model in LLVM, because it has no notion of
+ scoping in this sense, and does not want to be tied to a language's scoping
+ rules.</p>
+
+<p>In order to handle this, the LLVM debug format uses the metadata attached to
+ llvm instructions to encode line number and scoping information. Consider
+ the following C fragment, for example:</p>
+
+<div class="doc_code">
+<pre>
+1. void foo() {
+2. int X = 21;
+3. int Y = 22;
+4. {
+5. int Z = 23;
+6. Z = X;
+7. }
+8. X = Y;
+9. }
+</pre>
+</div>
+
+<p>Compiled to LLVM, this function would be represented like this:</p>
+
+<div class="doc_code">
+<pre>
+define void @foo() nounwind ssp {
+entry:
+ %X = alloca i32, align 4 ; &lt;i32*&gt; [#uses=4]
+ %Y = alloca i32, align 4 ; &lt;i32*&gt; [#uses=4]
+ %Z = alloca i32, align 4 ; &lt;i32*&gt; [#uses=3]
+ %0 = bitcast i32* %X to {}* ; &lt;{}*&gt; [#uses=1]
+ call void @llvm.dbg.declare(metadata !{i32 * %X}, metadata !0), !dbg !7
+ store i32 21, i32* %X, !dbg !8
+ %1 = bitcast i32* %Y to {}* ; &lt;{}*&gt; [#uses=1]
+ call void @llvm.dbg.declare(metadata !{i32 * %Y}, metadata !9), !dbg !10
+ store i32 22, i32* %Y, !dbg !11
+ %2 = bitcast i32* %Z to {}* ; &lt;{}*&gt; [#uses=1]
+ call void @llvm.dbg.declare(metadata !{i32 * %Z}, metadata !12), !dbg !14
+ store i32 23, i32* %Z, !dbg !15
+ %tmp = load i32* %X, !dbg !16 ; &lt;i32&gt; [#uses=1]
+ %tmp1 = load i32* %Y, !dbg !16 ; &lt;i32&gt; [#uses=1]
+ %add = add nsw i32 %tmp, %tmp1, !dbg !16 ; &lt;i32&gt; [#uses=1]
+ store i32 %add, i32* %Z, !dbg !16
+ %tmp2 = load i32* %Y, !dbg !17 ; &lt;i32&gt; [#uses=1]
+ store i32 %tmp2, i32* %X, !dbg !17
+ ret void, !dbg !18
+}
+
+declare void @llvm.dbg.declare(metadata, metadata) nounwind readnone
+
+!0 = metadata !{i32 459008, metadata !1, metadata !"X",
+ metadata !3, i32 2, metadata !6}; [ DW_TAG_auto_variable ]
+!1 = metadata !{i32 458763, metadata !2}; [DW_TAG_lexical_block ]
+!2 = metadata !{i32 458798, i32 0, metadata !3, metadata !"foo", metadata !"foo",
+ metadata !"foo", metadata !3, i32 1, metadata !4,
+ i1 false, i1 true}; [DW_TAG_subprogram ]
+!3 = metadata !{i32 458769, i32 0, i32 12, metadata !"foo.c",
+ metadata !"/private/tmp", metadata !"clang 1.1", i1 true,
+ i1 false, metadata !"", i32 0}; [DW_TAG_compile_unit ]
+!4 = metadata !{i32 458773, metadata !3, metadata !"", null, i32 0, i64 0, i64 0,
+ i64 0, i32 0, null, metadata !5, i32 0}; [DW_TAG_subroutine_type ]
+!5 = metadata !{null}
+!6 = metadata !{i32 458788, metadata !3, metadata !"int", metadata !3, i32 0,
+ i64 32, i64 32, i64 0, i32 0, i32 5}; [DW_TAG_base_type ]
+!7 = metadata !{i32 2, i32 7, metadata !1, null}
+!8 = metadata !{i32 2, i32 3, metadata !1, null}
+!9 = metadata !{i32 459008, metadata !1, metadata !"Y", metadata !3, i32 3,
+ metadata !6}; [ DW_TAG_auto_variable ]
+!10 = metadata !{i32 3, i32 7, metadata !1, null}
+!11 = metadata !{i32 3, i32 3, metadata !1, null}
+!12 = metadata !{i32 459008, metadata !13, metadata !"Z", metadata !3, i32 5,
+ metadata !6}; [ DW_TAG_auto_variable ]
+!13 = metadata !{i32 458763, metadata !1}; [DW_TAG_lexical_block ]
+!14 = metadata !{i32 5, i32 9, metadata !13, null}
+!15 = metadata !{i32 5, i32 5, metadata !13, null}
+!16 = metadata !{i32 6, i32 5, metadata !13, null}
+!17 = metadata !{i32 8, i32 3, metadata !1, null}
+!18 = metadata !{i32 9, i32 1, metadata !2, null}
+</pre>
+</div>
+
+<p>This example illustrates a few important details about LLVM debugging
+ information. In particular, it shows how the <tt>llvm.dbg.declare</tt>
+ intrinsic and location information, which are attached to an instruction,
+ are applied together to allow a debugger to analyze the relationship between
+ statements, variable definitions, and the code used to implement the
+ function.</p>
+
+<div class="doc_code">
+<pre>
+call void @llvm.dbg.declare(metadata, metadata !0), !dbg !7
+</pre>
+</div>
+
+<p>The first intrinsic
+ <tt>%<a href="#format_common_declare">llvm.dbg.declare</a></tt>
+ encodes debugging information for the variable <tt>X</tt>. The metadata
+ <tt>!dbg !7</tt> attached to the intrinsic provides scope information for the
+ variable <tt>X</tt>.</p>
+
+<div class="doc_code">
+<pre>
+!7 = metadata !{i32 2, i32 7, metadata !1, null}
+!1 = metadata !{i32 458763, metadata !2}; [DW_TAG_lexical_block ]
+!2 = metadata !{i32 458798, i32 0, metadata !3, metadata !"foo",
+ metadata !"foo", metadata !"foo", metadata !3, i32 1,
+ metadata !4, i1 false, i1 true}; [DW_TAG_subprogram ]
+</pre>
+</div>
+
+<p>Here <tt>!7</tt> is metadata providing location information. It has four
+ fields: line number, column number, scope, and original scope. The original
+ scope represents inline location if this instruction is inlined inside a
+ caller, and is null otherwise. In this example, scope is encoded by
+ <tt>!1</tt>. <tt>!1</tt> represents a lexical block inside the scope
+ <tt>!2</tt>, where <tt>!2</tt> is a
+ <a href="#format_subprograms">subprogram descriptor</a>. This way the
+ location information attached to the intrinsics indicates that the
+ variable <tt>X</tt> is declared at line number 2 at a function level scope in
+ function <tt>foo</tt>.</p>
+
+<p>Now lets take another example.</p>
+
+<div class="doc_code">
+<pre>
+call void @llvm.dbg.declare(metadata, metadata !12), !dbg !14
+</pre>
+</div>
+
+<p>The second intrinsic
+ <tt>%<a href="#format_common_declare">llvm.dbg.declare</a></tt>
+ encodes debugging information for variable <tt>Z</tt>. The metadata
+ <tt>!dbg !14</tt> attached to the intrinsic provides scope information for
+ the variable <tt>Z</tt>.</p>
+
+<div class="doc_code">
+<pre>
+!13 = metadata !{i32 458763, metadata !1}; [DW_TAG_lexical_block ]
+!14 = metadata !{i32 5, i32 9, metadata !13, null}
+</pre>
+</div>
+
+<p>Here <tt>!14</tt> indicates that <tt>Z</tt> is declared at line number 5 and
+ column number 9 inside of lexical scope <tt>!13</tt>. The lexical scope
+ itself resides inside of lexical scope <tt>!1</tt> described above.</p>
+
+<p>The scope information attached with each instruction provides a
+ straightforward way to find instructions covered by a scope.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="ccxx_frontend">C/C++ front-end specific debug information</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The C and C++ front-ends represent information about the program in a format
+ that is effectively identical
+ to <a href="http://www.eagercon.com/dwarf/dwarf3std.htm">DWARF 3.0</a> in
+ terms of information content. This allows code generators to trivially
+ support native debuggers by generating standard dwarf information, and
+ contains enough information for non-dwarf targets to translate it as
+ needed.</p>
+
+<p>This section describes the forms used to represent C and C++ programs. Other
+ languages could pattern themselves after this (which itself is tuned to
+ representing programs in the same way that DWARF 3 does), or they could
+ choose to provide completely different forms if they don't fit into the DWARF
+ model. As support for debugging information gets added to the various LLVM
+ source-language front-ends, the information used should be documented
+ here.</p>
+
+<p>The following sections provide examples of various C/C++ constructs and the
+ debug information that would best describe those constructs.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ccxx_compile_units">C/C++ source file information</a>
+</h3>
+
+<div>
+
+<p>Given the source files <tt>MySource.cpp</tt> and <tt>MyHeader.h</tt> located
+ in the directory <tt>/Users/mine/sources</tt>, the following code:</p>
+
+<div class="doc_code">
+<pre>
+#include "MyHeader.h"
+
+int main(int argc, char *argv[]) {
+ return 0;
+}
+</pre>
+</div>
+
+<p>a C/C++ front-end would generate the following descriptors:</p>
+
+<div class="doc_code">
+<pre>
+...
+;;
+;; Define the compile unit for the main source file "/Users/mine/sources/MySource.cpp".
+;;
+!2 = metadata !{
+ i32 524305, ;; Tag
+ i32 0, ;; Unused
+ i32 4, ;; Language Id
+ metadata !"MySource.cpp",
+ metadata !"/Users/mine/sources",
+ metadata !"4.2.1 (Based on Apple Inc. build 5649) (LLVM build 00)",
+ i1 true, ;; Main Compile Unit
+ i1 false, ;; Optimized compile unit
+ metadata !"", ;; Compiler flags
+ i32 0} ;; Runtime version
+
+;;
+;; Define the file for the file "/Users/mine/sources/MySource.cpp".
+;;
+!1 = metadata !{
+ i32 524329, ;; Tag
+ metadata !"MySource.cpp",
+ metadata !"/Users/mine/sources",
+ metadata !2 ;; Compile unit
+}
+
+;;
+;; Define the file for the file "/Users/mine/sources/Myheader.h"
+;;
+!3 = metadata !{
+ i32 524329, ;; Tag
+ metadata !"Myheader.h"
+ metadata !"/Users/mine/sources",
+ metadata !2 ;; Compile unit
+}
+
+...
+</pre>
+</div>
+
+<p>llvm::Instruction provides easy access to metadata attached with an
+instruction. One can extract line number information encoded in LLVM IR
+using <tt>Instruction::getMetadata()</tt> and
+<tt>DILocation::getLineNumber()</tt>.
+<pre>
+ if (MDNode *N = I->getMetadata("dbg")) { // Here I is an LLVM instruction
+ DILocation Loc(N); // DILocation is in DebugInfo.h
+ unsigned Line = Loc.getLineNumber();
+ StringRef File = Loc.getFilename();
+ StringRef Dir = Loc.getDirectory();
+ }
+</pre>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ccxx_global_variable">C/C++ global variable information</a>
+</h3>
+
+<div>
+
+<p>Given an integer global variable declared as follows:</p>
+
+<div class="doc_code">
+<pre>
+int MyGlobal = 100;
+</pre>
+</div>
+
+<p>a C/C++ front-end would generate the following descriptors:</p>
+
+<div class="doc_code">
+<pre>
+;;
+;; Define the global itself.
+;;
+%MyGlobal = global int 100
+...
+;;
+;; List of debug info of globals
+;;
+!llvm.dbg.cu = !{!0}
+
+;; Define the compile unit.
+!0 = metadata !{
+ i32 786449, ;; Tag
+ i32 0, ;; Context
+ i32 4, ;; Language
+ metadata !"foo.cpp", ;; File
+ metadata !"/Volumes/Data/tmp", ;; Directory
+ metadata !"clang version 3.1 ", ;; Producer
+ i1 true, ;; Deprecated field
+ i1 false, ;; "isOptimized"?
+ metadata !"", ;; Flags
+ i32 0, ;; Runtime Version
+ metadata !1, ;; Enum Types
+ metadata !1, ;; Retained Types
+ metadata !1, ;; Subprograms
+ metadata !3 ;; Global Variables
+} ; [ DW_TAG_compile_unit ]
+
+;; The Array of Global Variables
+!3 = metadata !{
+ metadata !4
+}
+
+!4 = metadata !{
+ metadata !5
+}
+
+;;
+;; Define the global variable itself.
+;;
+!5 = metadata !{
+ i32 786484, ;; Tag
+ i32 0, ;; Unused
+ null, ;; Unused
+ metadata !"MyGlobal", ;; Name
+ metadata !"MyGlobal", ;; Display Name
+ metadata !"", ;; Linkage Name
+ metadata !6, ;; File
+ i32 1, ;; Line
+ metadata !7, ;; Type
+ i32 0, ;; IsLocalToUnit
+ i32 1, ;; IsDefinition
+ i32* @MyGlobal ;; LLVM-IR Value
+} ; [ DW_TAG_variable ]
+
+;;
+;; Define the file
+;;
+!6 = metadata !{
+ i32 786473, ;; Tag
+ metadata !"foo.cpp", ;; File
+ metadata !"/Volumes/Data/tmp", ;; Directory
+ null ;; Unused
+} ; [ DW_TAG_file_type ]
+
+;;
+;; Define the type
+;;
+!7 = metadata !{
+ i32 786468, ;; Tag
+ null, ;; Unused
+ metadata !"int", ;; Name
+ null, ;; Unused
+ i32 0, ;; Line
+ i64 32, ;; Size in Bits
+ i64 32, ;; Align in Bits
+ i64 0, ;; Offset
+ i32 0, ;; Flags
+ i32 5 ;; Encoding
+} ; [ DW_TAG_base_type ]
+
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ccxx_subprogram">C/C++ function information</a>
+</h3>
+
+<div>
+
+<p>Given a function declared as follows:</p>
+
+<div class="doc_code">
+<pre>
+int main(int argc, char *argv[]) {
+ return 0;
+}
+</pre>
+</div>
+
+<p>a C/C++ front-end would generate the following descriptors:</p>
+
+<div class="doc_code">
+<pre>
+;;
+;; Define the anchor for subprograms. Note that the second field of the
+;; anchor is 46, which is the same as the tag for subprograms
+;; (46 = DW_TAG_subprogram.)
+;;
+!6 = metadata !{
+ i32 524334, ;; Tag
+ i32 0, ;; Unused
+ metadata !1, ;; Context
+ metadata !"main", ;; Name
+ metadata !"main", ;; Display name
+ metadata !"main", ;; Linkage name
+ metadata !1, ;; File
+ i32 1, ;; Line number
+ metadata !4, ;; Type
+ i1 false, ;; Is local
+ i1 true, ;; Is definition
+ i32 0, ;; Virtuality attribute, e.g. pure virtual function
+ i32 0, ;; Index into virtual table for C++ methods
+ i32 0, ;; Type that holds virtual table.
+ i32 0, ;; Flags
+ i1 false, ;; True if this function is optimized
+ Function *, ;; Pointer to llvm::Function
+ null ;; Function template parameters
+}
+;;
+;; Define the subprogram itself.
+;;
+define i32 @main(i32 %argc, i8** %argv) {
+...
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ccxx_basic_types">C/C++ basic types</a>
+</h3>
+
+<div>
+
+<p>The following are the basic type descriptors for C/C++ core types:</p>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_type_bool">bool</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"bool", ;; Name
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 8, ;; Size in Bits
+ i64 8, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 2 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_char">char</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"char", ;; Name
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 8, ;; Size in Bits
+ i64 8, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 6 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_unsigned_char">unsigned char</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"unsigned char",
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 8, ;; Size in Bits
+ i64 8, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 8 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_short">short</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"short int",
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 16, ;; Size in Bits
+ i64 16, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 5 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_unsigned_short">unsigned short</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"short unsigned int",
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 16, ;; Size in Bits
+ i64 16, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 7 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_int">int</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"int", ;; Name
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 32, ;; Size in Bits
+ i64 32, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 5 ;; Encoding
+}
+</pre></div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_unsigned_int">unsigned int</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"unsigned int",
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 32, ;; Size in Bits
+ i64 32, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 7 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_long_long">long long</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"long long int",
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 64, ;; Size in Bits
+ i64 64, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 5 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_unsigned_long_long">unsigned long long</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"long long unsigned int",
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 64, ;; Size in Bits
+ i64 64, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 7 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_float">float</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"float",
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 32, ;; Size in Bits
+ i64 32, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 4 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="ccxx_basic_double">double</a>
+</h4>
+
+<div>
+
+<div class="doc_code">
+<pre>
+!2 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"double",;; Name
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 64, ;; Size in Bits
+ i64 64, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 4 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ccxx_derived_types">C/C++ derived types</a>
+</h3>
+
+<div>
+
+<p>Given the following as an example of C/C++ derived type:</p>
+
+<div class="doc_code">
+<pre>
+typedef const int *IntPtr;
+</pre>
+</div>
+
+<p>a C/C++ front-end would generate the following descriptors:</p>
+
+<div class="doc_code">
+<pre>
+;;
+;; Define the typedef "IntPtr".
+;;
+!2 = metadata !{
+ i32 524310, ;; Tag
+ metadata !1, ;; Context
+ metadata !"IntPtr", ;; Name
+ metadata !3, ;; File
+ i32 0, ;; Line number
+ i64 0, ;; Size in bits
+ i64 0, ;; Align in bits
+ i64 0, ;; Offset in bits
+ i32 0, ;; Flags
+ metadata !4 ;; Derived From type
+}
+
+;;
+;; Define the pointer type.
+;;
+!4 = metadata !{
+ i32 524303, ;; Tag
+ metadata !1, ;; Context
+ metadata !"", ;; Name
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 64, ;; Size in bits
+ i64 64, ;; Align in bits
+ i64 0, ;; Offset in bits
+ i32 0, ;; Flags
+ metadata !5 ;; Derived From type
+}
+;;
+;; Define the const type.
+;;
+!5 = metadata !{
+ i32 524326, ;; Tag
+ metadata !1, ;; Context
+ metadata !"", ;; Name
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 32, ;; Size in bits
+ i64 32, ;; Align in bits
+ i64 0, ;; Offset in bits
+ i32 0, ;; Flags
+ metadata !6 ;; Derived From type
+}
+;;
+;; Define the int type.
+;;
+!6 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"int", ;; Name
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 32, ;; Size in bits
+ i64 32, ;; Align in bits
+ i64 0, ;; Offset in bits
+ i32 0, ;; Flags
+ 5 ;; Encoding
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ccxx_composite_types">C/C++ struct/union types</a>
+</h3>
+
+<div>
+
+<p>Given the following as an example of C/C++ struct type:</p>
+
+<div class="doc_code">
+<pre>
+struct Color {
+ unsigned Red;
+ unsigned Green;
+ unsigned Blue;
+};
+</pre>
+</div>
+
+<p>a C/C++ front-end would generate the following descriptors:</p>
+
+<div class="doc_code">
+<pre>
+;;
+;; Define basic type for unsigned int.
+;;
+!5 = metadata !{
+ i32 524324, ;; Tag
+ metadata !1, ;; Context
+ metadata !"unsigned int",
+ metadata !1, ;; File
+ i32 0, ;; Line number
+ i64 32, ;; Size in Bits
+ i64 32, ;; Align in Bits
+ i64 0, ;; Offset in Bits
+ i32 0, ;; Flags
+ i32 7 ;; Encoding
+}
+;;
+;; Define composite type for struct Color.
+;;
+!2 = metadata !{
+ i32 524307, ;; Tag
+ metadata !1, ;; Context
+ metadata !"Color", ;; Name
+ metadata !1, ;; Compile unit
+ i32 1, ;; Line number
+ i64 96, ;; Size in bits
+ i64 32, ;; Align in bits
+ i64 0, ;; Offset in bits
+ i32 0, ;; Flags
+ null, ;; Derived From
+ metadata !3, ;; Elements
+ i32 0 ;; Runtime Language
+}
+
+;;
+;; Define the Red field.
+;;
+!4 = metadata !{
+ i32 524301, ;; Tag
+ metadata !1, ;; Context
+ metadata !"Red", ;; Name
+ metadata !1, ;; File
+ i32 2, ;; Line number
+ i64 32, ;; Size in bits
+ i64 32, ;; Align in bits
+ i64 0, ;; Offset in bits
+ i32 0, ;; Flags
+ metadata !5 ;; Derived From type
+}
+
+;;
+;; Define the Green field.
+;;
+!6 = metadata !{
+ i32 524301, ;; Tag
+ metadata !1, ;; Context
+ metadata !"Green", ;; Name
+ metadata !1, ;; File
+ i32 3, ;; Line number
+ i64 32, ;; Size in bits
+ i64 32, ;; Align in bits
+ i64 32, ;; Offset in bits
+ i32 0, ;; Flags
+ metadata !5 ;; Derived From type
+}
+
+;;
+;; Define the Blue field.
+;;
+!7 = metadata !{
+ i32 524301, ;; Tag
+ metadata !1, ;; Context
+ metadata !"Blue", ;; Name
+ metadata !1, ;; File
+ i32 4, ;; Line number
+ i64 32, ;; Size in bits
+ i64 32, ;; Align in bits
+ i64 64, ;; Offset in bits
+ i32 0, ;; Flags
+ metadata !5 ;; Derived From type
+}
+
+;;
+;; Define the array of fields used by the composite type Color.
+;;
+!3 = metadata !{metadata !4, metadata !6, metadata !7}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ccxx_enumeration_types">C/C++ enumeration types</a>
+</h3>
+
+<div>
+
+<p>Given the following as an example of C/C++ enumeration type:</p>
+
+<div class="doc_code">
+<pre>
+enum Trees {
+ Spruce = 100,
+ Oak = 200,
+ Maple = 300
+};
+</pre>
+</div>
+
+<p>a C/C++ front-end would generate the following descriptors:</p>
+
+<div class="doc_code">
+<pre>
+;;
+;; Define composite type for enum Trees
+;;
+!2 = metadata !{
+ i32 524292, ;; Tag
+ metadata !1, ;; Context
+ metadata !"Trees", ;; Name
+ metadata !1, ;; File
+ i32 1, ;; Line number
+ i64 32, ;; Size in bits
+ i64 32, ;; Align in bits
+ i64 0, ;; Offset in bits
+ i32 0, ;; Flags
+ null, ;; Derived From type
+ metadata !3, ;; Elements
+ i32 0 ;; Runtime language
+}
+
+;;
+;; Define the array of enumerators used by composite type Trees.
+;;
+!3 = metadata !{metadata !4, metadata !5, metadata !6}
+
+;;
+;; Define Spruce enumerator.
+;;
+!4 = metadata !{i32 524328, metadata !"Spruce", i64 100}
+
+;;
+;; Define Oak enumerator.
+;;
+!5 = metadata !{i32 524328, metadata !"Oak", i64 200}
+
+;;
+;; Define Maple enumerator.
+;;
+!6 = metadata !{i32 524328, metadata !"Maple", i64 300}
+
+</pre>
+</div>
+
+</div>
+
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="llvmdwarfextension">Debugging information format</a>
+</h2>
+<!-- *********************************************************************** -->
+<div>
+<!-- ======================================================================= -->
+<h3>
+ <a name="objcproperty">Debugging Information Extension for Objective C Properties</a>
+</h3>
+<div>
+<!-- *********************************************************************** -->
+<h4>
+ <a name="objcpropertyintroduction">Introduction</a>
+</h4>
+<!-- *********************************************************************** -->
+
+<div>
+<p>Objective C provides a simpler way to declare and define accessor methods
+using declared properties. The language provides features to declare a
+property and to let compiler synthesize accessor methods.
+</p>
+
+<p>The debugger lets developer inspect Objective C interfaces and their
+instance variables and class variables. However, the debugger does not know
+anything about the properties defined in Objective C interfaces. The debugger
+consumes information generated by compiler in DWARF format. The format does
+not support encoding of Objective C properties. This proposal describes DWARF
+extensions to encode Objective C properties, which the debugger can use to let
+developers inspect Objective C properties.
+</p>
+
+</div>
+
+
+<!-- *********************************************************************** -->
+<h4>
+ <a name="objcpropertyproposal">Proposal</a>
+</h4>
+<!-- *********************************************************************** -->
+
+<div>
+<p>Objective C properties exist separately from class members. A property
+can be defined only by &quot;setter&quot; and &quot;getter&quot; selectors, and
+be calculated anew on each access. Or a property can just be a direct access
+to some declared ivar. Finally it can have an ivar &quot;automatically
+synthesized&quot; for it by the compiler, in which case the property can be
+referred to in user code directly using the standard C dereference syntax as
+well as through the property &quot;dot&quot; syntax, but there is no entry in
+the @interface declaration corresponding to this ivar.
+</p>
+<p>
+To facilitate debugging, these properties we will add a new DWARF TAG into the
+DW_TAG_structure_type definition for the class to hold the description of a
+given property, and a set of DWARF attributes that provide said description.
+The property tag will also contain the name and declared type of the property.
+</p>
+<p>
+If there is a related ivar, there will also be a DWARF property attribute placed
+in the DW_TAG_member DIE for that ivar referring back to the property TAG for
+that property. And in the case where the compiler synthesizes the ivar directly,
+the compiler is expected to generate a DW_TAG_member for that ivar (with the
+DW_AT_artificial set to 1), whose name will be the name used to access this
+ivar directly in code, and with the property attribute pointing back to the
+property it is backing.
+</p>
+<p>
+The following examples will serve as illustration for our discussion:
+</p>
+
+<div class="doc_code">
+<pre>
+@interface I1 {
+ int n2;
+}
+
+@property int p1;
+@property int p2;
+@end
+
+@implementation I1
+@synthesize p1;
+@synthesize p2 = n2;
+@end
+</pre>
+</div>
+
+<p>
+This produces the following DWARF (this is a &quot;pseudo dwarfdump&quot; output):
+</p>
+<div class="doc_code">
+<pre>
+0x00000100: TAG_structure_type [7] *
+ AT_APPLE_runtime_class( 0x10 )
+ AT_name( "I1" )
+ AT_decl_file( "Objc_Property.m" )
+ AT_decl_line( 3 )
+
+0x00000110 TAG_APPLE_property
+ AT_name ( "p1" )
+ AT_type ( {0x00000150} ( int ) )
+
+0x00000120: TAG_APPLE_property
+ AT_name ( "p2" )
+ AT_type ( {0x00000150} ( int ) )
+
+0x00000130: TAG_member [8]
+ AT_name( "_p1" )
+ AT_APPLE_property ( {0x00000110} "p1" )
+ AT_type( {0x00000150} ( int ) )
+ AT_artificial ( 0x1 )
+
+0x00000140: TAG_member [8]
+ AT_name( "n2" )
+ AT_APPLE_property ( {0x00000120} "p2" )
+ AT_type( {0x00000150} ( int ) )
+
+0x00000150: AT_type( ( int ) )
+</pre>
+</div>
+
+<p> Note, the current convention is that the name of the ivar for an
+auto-synthesized property is the name of the property from which it derives with
+an underscore prepended, as is shown in the example.
+But we actually don't need to know this convention, since we are given the name
+of the ivar directly.
+</p>
+
+<p>
+Also, it is common practice in ObjC to have different property declarations in
+the @interface and @implementation - e.g. to provide a read-only property in
+the interface,and a read-write interface in the implementation. In that case,
+the compiler should emit whichever property declaration will be in force in the
+current translation unit.
+</p>
+
+<p> Developers can decorate a property with attributes which are encoded using
+DW_AT_APPLE_property_attribute.
+</p>
+
+<div class="doc_code">
+<pre>
+@property (readonly, nonatomic) int pr;
+</pre>
+</div>
+<p>
+Which produces a property tag:
+<p>
+<div class="doc_code">
+<pre>
+TAG_APPLE_property [8]
+ AT_name( "pr" )
+ AT_type ( {0x00000147} (int) )
+ AT_APPLE_property_attribute (DW_APPLE_PROPERTY_readonly, DW_APPLE_PROPERTY_nonatomic)
+</pre>
+</div>
+
+<p> The setter and getter method names are attached to the property using
+DW_AT_APPLE_property_setter and DW_AT_APPLE_property_getter attributes.
+</p>
+<div class="doc_code">
+<pre>
+@interface I1
+@property (setter=myOwnP3Setter:) int p3;
+-(void)myOwnP3Setter:(int)a;
+@end
+
+@implementation I1
+@synthesize p3;
+-(void)myOwnP3Setter:(int)a{ }
+@end
+</pre>
+</div>
+
+<p>
+The DWARF for this would be:
+</p>
+<div class="doc_code">
+<pre>
+0x000003bd: TAG_structure_type [7] *
+ AT_APPLE_runtime_class( 0x10 )
+ AT_name( "I1" )
+ AT_decl_file( "Objc_Property.m" )
+ AT_decl_line( 3 )
+
+0x000003cd TAG_APPLE_property
+ AT_name ( "p3" )
+ AT_APPLE_property_setter ( "myOwnP3Setter:" )
+ AT_type( {0x00000147} ( int ) )
+
+0x000003f3: TAG_member [8]
+ AT_name( "_p3" )
+ AT_type ( {0x00000147} ( int ) )
+ AT_APPLE_property ( {0x000003cd} )
+ AT_artificial ( 0x1 )
+</pre>
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h4>
+ <a name="objcpropertynewtags">New DWARF Tags</a>
+</h4>
+<!-- *********************************************************************** -->
+
+<div>
+<table border="1" cellspacing="0">
+ <col width="200">
+ <col width="200">
+ <tr>
+ <th>TAG</th>
+ <th>Value</th>
+ </tr>
+ <tr>
+ <td>DW_TAG_APPLE_property</td>
+ <td>0x4200</td>
+ </tr>
+</table>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h4>
+ <a name="objcpropertynewattributes">New DWARF Attributes</a>
+</h4>
+<!-- *********************************************************************** -->
+
+<div>
+<table border="1" cellspacing="0">
+ <col width="200">
+ <col width="200">
+ <col width="200">
+ <tr>
+ <th>Attribute</th>
+ <th>Value</th>
+ <th>Classes</th>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_property</td>
+ <td>0x3fed</td>
+ <td>Reference</td>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_property_getter</td>
+ <td>0x3fe9</td>
+ <td>String</td>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_property_setter</td>
+ <td>0x3fea</td>
+ <td>String</td>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_property_attribute</td>
+ <td>0x3feb</td>
+ <td>Constant</td>
+ </tr>
+</table>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h4>
+ <a name="objcpropertynewconstants">New DWARF Constants</a>
+</h4>
+<!-- *********************************************************************** -->
+
+<div>
+<table border="1" cellspacing="0">
+ <col width="200">
+ <col width="200">
+ <tr>
+ <th>Name</th>
+ <th>Value</th>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_PROPERTY_readonly</td>
+ <td>0x1</td>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_PROPERTY_readwrite</td>
+ <td>0x2</td>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_PROPERTY_assign</td>
+ <td>0x4</td>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_PROPERTY_retain</td>
+ <td>0x8</td>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_PROPERTY_copy</td>
+ <td>0x10</td>
+ </tr>
+ <tr>
+ <td>DW_AT_APPLE_PROPERTY_nonatomic</td>
+ <td>0x20</td>
+ </tr>
+</table>
+
+</div>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="acceltable">Name Accelerator Tables</a>
+</h3>
+<!-- ======================================================================= -->
+<div>
+<!-- ======================================================================= -->
+<h4>
+ <a name="acceltableintroduction">Introduction</a>
+</h4>
+<!-- ======================================================================= -->
+<div>
+<p>The .debug_pubnames and .debug_pubtypes formats are not what a debugger
+ needs. The "pub" in the section name indicates that the entries in the
+ table are publicly visible names only. This means no static or hidden
+ functions show up in the .debug_pubnames. No static variables or private class
+ variables are in the .debug_pubtypes. Many compilers add different things to
+ these tables, so we can't rely upon the contents between gcc, icc, or clang.</p>
+
+<p>The typical query given by users tends not to match up with the contents of
+ these tables. For example, the DWARF spec states that "In the case of the
+ name of a function member or static data member of a C++ structure, class or
+ union, the name presented in the .debug_pubnames section is not the simple
+ name given by the DW_AT_name attribute of the referenced debugging information
+ entry, but rather the fully qualified name of the data or function member."
+ So the only names in these tables for complex C++ entries is a fully
+ qualified name. Debugger users tend not to enter their search strings as
+ "a::b::c(int,const Foo&) const", but rather as "c", "b::c" , or "a::b::c". So
+ the name entered in the name table must be demangled in order to chop it up
+ appropriately and additional names must be manually entered into the table
+ to make it effective as a name lookup table for debuggers to use.</p>
+
+<p>All debuggers currently ignore the .debug_pubnames table as a result of
+ its inconsistent and useless public-only name content making it a waste of
+ space in the object file. These tables, when they are written to disk, are
+ not sorted in any way, leaving every debugger to do its own parsing
+ and sorting. These tables also include an inlined copy of the string values
+ in the table itself making the tables much larger than they need to be on
+ disk, especially for large C++ programs.</p>
+
+<p>Can't we just fix the sections by adding all of the names we need to this
+ table? No, because that is not what the tables are defined to contain and we
+ won't know the difference between the old bad tables and the new good tables.
+ At best we could make our own renamed sections that contain all of the data
+ we need.</p>
+
+<p>These tables are also insufficient for what a debugger like LLDB needs.
+ LLDB uses clang for its expression parsing where LLDB acts as a PCH. LLDB is
+ then often asked to look for type "foo" or namespace "bar", or list items in
+ namespace "baz". Namespaces are not included in the pubnames or pubtypes
+ tables. Since clang asks a lot of questions when it is parsing an expression,
+ we need to be very fast when looking up names, as it happens a lot. Having new
+ accelerator tables that are optimized for very quick lookups will benefit
+ this type of debugging experience greatly.</p>
+
+<p>We would like to generate name lookup tables that can be mapped into
+ memory from disk, and used as is, with little or no up-front parsing. We would
+ also be able to control the exact content of these different tables so they
+ contain exactly what we need. The Name Accelerator Tables were designed
+ to fix these issues. In order to solve these issues we need to:</p>
+
+<ul>
+ <li>Have a format that can be mapped into memory from disk and used as is</li>
+ <li>Lookups should be very fast</li>
+ <li>Extensible table format so these tables can be made by many producers</li>
+ <li>Contain all of the names needed for typical lookups out of the box</li>
+ <li>Strict rules for the contents of tables</li>
+</ul>
+
+<p>Table size is important and the accelerator table format should allow the
+ reuse of strings from common string tables so the strings for the names are
+ not duplicated. We also want to make sure the table is ready to be used as-is
+ by simply mapping the table into memory with minimal header parsing.</p>
+
+<p>The name lookups need to be fast and optimized for the kinds of lookups
+ that debuggers tend to do. Optimally we would like to touch as few parts of
+ the mapped table as possible when doing a name lookup and be able to quickly
+ find the name entry we are looking for, or discover there are no matches. In
+ the case of debuggers we optimized for lookups that fail most of the time.</p>
+
+<p>Each table that is defined should have strict rules on exactly what is in
+ the accelerator tables and documented so clients can rely on the content.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="acceltablehashes">Hash Tables</a>
+</h4>
+<!-- ======================================================================= -->
+
+<div>
+<h5>Standard Hash Tables</h5>
+
+<p>Typical hash tables have a header, buckets, and each bucket points to the
+bucket contents:
+</p>
+
+<div class="doc_code">
+<pre>
+.------------.
+| HEADER |
+|------------|
+| BUCKETS |
+|------------|
+| DATA |
+`------------'
+</pre>
+</div>
+
+<p>The BUCKETS are an array of offsets to DATA for each hash:</p>
+
+<div class="doc_code">
+<pre>
+.------------.
+| 0x00001000 | BUCKETS[0]
+| 0x00002000 | BUCKETS[1]
+| 0x00002200 | BUCKETS[2]
+| 0x000034f0 | BUCKETS[3]
+| | ...
+| 0xXXXXXXXX | BUCKETS[n_buckets]
+'------------'
+</pre>
+</div>
+
+<p>So for bucket[3] in the example above, we have an offset into the table
+ 0x000034f0 which points to a chain of entries for the bucket. Each bucket
+ must contain a next pointer, full 32 bit hash value, the string itself,
+ and the data for the current string value.</p>
+
+<div class="doc_code">
+<pre>
+ .------------.
+0x000034f0: | 0x00003500 | next pointer
+ | 0x12345678 | 32 bit hash
+ | "erase" | string value
+ | data[n] | HashData for this bucket
+ |------------|
+0x00003500: | 0x00003550 | next pointer
+ | 0x29273623 | 32 bit hash
+ | "dump" | string value
+ | data[n] | HashData for this bucket
+ |------------|
+0x00003550: | 0x00000000 | next pointer
+ | 0x82638293 | 32 bit hash
+ | "main" | string value
+ | data[n] | HashData for this bucket
+ `------------'
+</pre>
+</div>
+
+<p>The problem with this layout for debuggers is that we need to optimize for
+ the negative lookup case where the symbol we're searching for is not present.
+ So if we were to lookup "printf" in the table above, we would make a 32 hash
+ for "printf", it might match bucket[3]. We would need to go to the offset
+ 0x000034f0 and start looking to see if our 32 bit hash matches. To do so, we
+ need to read the next pointer, then read the hash, compare it, and skip to
+ the next bucket. Each time we are skipping many bytes in memory and touching
+ new cache pages just to do the compare on the full 32 bit hash. All of these
+ accesses then tell us that we didn't have a match.</p>
+
+<h5>Name Hash Tables</h5>
+
+<p>To solve the issues mentioned above we have structured the hash tables
+ a bit differently: a header, buckets, an array of all unique 32 bit hash
+ values, followed by an array of hash value data offsets, one for each hash
+ value, then the data for all hash values:</p>
+
+<div class="doc_code">
+<pre>
+.-------------.
+| HEADER |
+|-------------|
+| BUCKETS |
+|-------------|
+| HASHES |
+|-------------|
+| OFFSETS |
+|-------------|
+| DATA |
+`-------------'
+</pre>
+</div>
+
+<p>The BUCKETS in the name tables are an index into the HASHES array. By
+ making all of the full 32 bit hash values contiguous in memory, we allow
+ ourselves to efficiently check for a match while touching as little
+ memory as possible. Most often checking the 32 bit hash values is as far as
+ the lookup goes. If it does match, it usually is a match with no collisions.
+ So for a table with "n_buckets" buckets, and "n_hashes" unique 32 bit hash
+ values, we can clarify the contents of the BUCKETS, HASHES and OFFSETS as:</p>
+
+<div class="doc_code">
+<pre>
+.-------------------------.
+| HEADER.magic | uint32_t
+| HEADER.version | uint16_t
+| HEADER.hash_function | uint16_t
+| HEADER.bucket_count | uint32_t
+| HEADER.hashes_count | uint32_t
+| HEADER.header_data_len | uint32_t
+| HEADER_DATA | HeaderData
+|-------------------------|
+| BUCKETS | uint32_t[n_buckets] // 32 bit hash indexes
+|-------------------------|
+| HASHES | uint32_t[n_buckets] // 32 bit hash values
+|-------------------------|
+| OFFSETS | uint32_t[n_buckets] // 32 bit offsets to hash value data
+|-------------------------|
+| ALL HASH DATA |
+`-------------------------'
+</pre>
+</div>
+
+<p>So taking the exact same data from the standard hash example above we end up
+ with:</p>
+
+<div class="doc_code">
+<pre>
+ .------------.
+ | HEADER |
+ |------------|
+ | 0 | BUCKETS[0]
+ | 2 | BUCKETS[1]
+ | 5 | BUCKETS[2]
+ | 6 | BUCKETS[3]
+ | | ...
+ | ... | BUCKETS[n_buckets]
+ |------------|
+ | 0x........ | HASHES[0]
+ | 0x........ | HASHES[1]
+ | 0x........ | HASHES[2]
+ | 0x........ | HASHES[3]
+ | 0x........ | HASHES[4]
+ | 0x........ | HASHES[5]
+ | 0x12345678 | HASHES[6] hash for BUCKETS[3]
+ | 0x29273623 | HASHES[7] hash for BUCKETS[3]
+ | 0x82638293 | HASHES[8] hash for BUCKETS[3]
+ | 0x........ | HASHES[9]
+ | 0x........ | HASHES[10]
+ | 0x........ | HASHES[11]
+ | 0x........ | HASHES[12]
+ | 0x........ | HASHES[13]
+ | 0x........ | HASHES[n_hashes]
+ |------------|
+ | 0x........ | OFFSETS[0]
+ | 0x........ | OFFSETS[1]
+ | 0x........ | OFFSETS[2]
+ | 0x........ | OFFSETS[3]
+ | 0x........ | OFFSETS[4]
+ | 0x........ | OFFSETS[5]
+ | 0x000034f0 | OFFSETS[6] offset for BUCKETS[3]
+ | 0x00003500 | OFFSETS[7] offset for BUCKETS[3]
+ | 0x00003550 | OFFSETS[8] offset for BUCKETS[3]
+ | 0x........ | OFFSETS[9]
+ | 0x........ | OFFSETS[10]
+ | 0x........ | OFFSETS[11]
+ | 0x........ | OFFSETS[12]
+ | 0x........ | OFFSETS[13]
+ | 0x........ | OFFSETS[n_hashes]
+ |------------|
+ | |
+ | |
+ | |
+ | |
+ | |
+ |------------|
+0x000034f0: | 0x00001203 | .debug_str ("erase")
+ | 0x00000004 | A 32 bit array count - number of HashData with name "erase"
+ | 0x........ | HashData[0]
+ | 0x........ | HashData[1]
+ | 0x........ | HashData[2]
+ | 0x........ | HashData[3]
+ | 0x00000000 | String offset into .debug_str (terminate data for hash)
+ |------------|
+0x00003500: | 0x00001203 | String offset into .debug_str ("collision")
+ | 0x00000002 | A 32 bit array count - number of HashData with name "collision"
+ | 0x........ | HashData[0]
+ | 0x........ | HashData[1]
+ | 0x00001203 | String offset into .debug_str ("dump")
+ | 0x00000003 | A 32 bit array count - number of HashData with name "dump"
+ | 0x........ | HashData[0]
+ | 0x........ | HashData[1]
+ | 0x........ | HashData[2]
+ | 0x00000000 | String offset into .debug_str (terminate data for hash)
+ |------------|
+0x00003550: | 0x00001203 | String offset into .debug_str ("main")
+ | 0x00000009 | A 32 bit array count - number of HashData with name "main"
+ | 0x........ | HashData[0]
+ | 0x........ | HashData[1]
+ | 0x........ | HashData[2]
+ | 0x........ | HashData[3]
+ | 0x........ | HashData[4]
+ | 0x........ | HashData[5]
+ | 0x........ | HashData[6]
+ | 0x........ | HashData[7]
+ | 0x........ | HashData[8]
+ | 0x00000000 | String offset into .debug_str (terminate data for hash)
+ `------------'
+</pre>
+</div>
+
+<p>So we still have all of the same data, we just organize it more efficiently
+ for debugger lookup. If we repeat the same "printf" lookup from above, we
+ would hash "printf" and find it matches BUCKETS[3] by taking the 32 bit hash
+ value and modulo it by n_buckets. BUCKETS[3] contains "6" which is the index
+ into the HASHES table. We would then compare any consecutive 32 bit hashes
+ values in the HASHES array as long as the hashes would be in BUCKETS[3]. We
+ do this by verifying that each subsequent hash value modulo n_buckets is still
+ 3. In the case of a failed lookup we would access the memory for BUCKETS[3], and
+ then compare a few consecutive 32 bit hashes before we know that we have no match.
+ We don't end up marching through multiple words of memory and we really keep the
+ number of processor data cache lines being accessed as small as possible.</p>
+
+<p>The string hash that is used for these lookup tables is the Daniel J.
+ Bernstein hash which is also used in the ELF GNU_HASH sections. It is a very
+ good hash for all kinds of names in programs with very few hash collisions.</p>
+
+<p>Empty buckets are designated by using an invalid hash index of UINT32_MAX.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="acceltabledetails">Details</a>
+</h4>
+<!-- ======================================================================= -->
+<div>
+<p>These name hash tables are designed to be generic where specializations of
+ the table get to define additional data that goes into the header
+ ("HeaderData"), how the string value is stored ("KeyType") and the content
+ of the data for each hash value.</p>
+
+<h5>Header Layout</h5>
+<p>The header has a fixed part, and the specialized part. The exact format of
+ the header is:</p>
+<div class="doc_code">
+<pre>
+struct Header
+{
+ uint32_t magic; // 'HASH' magic value to allow endian detection
+ uint16_t version; // Version number
+ uint16_t hash_function; // The hash function enumeration that was used
+ uint32_t bucket_count; // The number of buckets in this hash table
+ uint32_t hashes_count; // The total number of unique hash values and hash data offsets in this table
+ uint32_t header_data_len; // The bytes to skip to get to the hash indexes (buckets) for correct alignment
+ // Specifically the length of the following HeaderData field - this does not
+ // include the size of the preceding fields
+ HeaderData header_data; // Implementation specific header data
+};
+</pre>
+</div>
+<p>The header starts with a 32 bit "magic" value which must be 'HASH' encoded as
+ an ASCII integer. This allows the detection of the start of the hash table and
+ also allows the table's byte order to be determined so the table can be
+ correctly extracted. The "magic" value is followed by a 16 bit version number
+ which allows the table to be revised and modified in the future. The current
+ version number is 1. "hash_function" is a uint16_t enumeration that specifies
+ which hash function was used to produce this table. The current values for the
+ hash function enumerations include:</p>
+<div class="doc_code">
+<pre>
+enum HashFunctionType
+{
+ eHashFunctionDJB = 0u, // Daniel J Bernstein hash function
+};
+</pre>
+</div>
+<p>"bucket_count" is a 32 bit unsigned integer that represents how many buckets
+ are in the BUCKETS array. "hashes_count" is the number of unique 32 bit hash
+ values that are in the HASHES array, and is the same number of offsets are
+ contained in the OFFSETS array. "header_data_len" specifies the size in
+ bytes of the HeaderData that is filled in by specialized versions of this
+ table.</p>
+
+<h5>Fixed Lookup</h5>
+<p>The header is followed by the buckets, hashes, offsets, and hash value
+ data.
+<div class="doc_code">
+<pre>
+struct FixedTable
+{
+ uint32_t buckets[Header.bucket_count]; // An array of hash indexes into the "hashes[]" array below
+ uint32_t hashes [Header.hashes_count]; // Every unique 32 bit hash for the entire table is in this table
+ uint32_t offsets[Header.hashes_count]; // An offset that corresponds to each item in the "hashes[]" array above
+};
+</pre>
+</div>
+<p>"buckets" is an array of 32 bit indexes into the "hashes" array. The
+ "hashes" array contains all of the 32 bit hash values for all names in the
+ hash table. Each hash in the "hashes" table has an offset in the "offsets"
+ array that points to the data for the hash value.</p>
+
+<p>This table setup makes it very easy to repurpose these tables to contain
+ different data, while keeping the lookup mechanism the same for all tables.
+ This layout also makes it possible to save the table to disk and map it in
+ later and do very efficient name lookups with little or no parsing.</p>
+
+<p>DWARF lookup tables can be implemented in a variety of ways and can store
+ a lot of information for each name. We want to make the DWARF tables
+ extensible and able to store the data efficiently so we have used some of the
+ DWARF features that enable efficient data storage to define exactly what kind
+ of data we store for each name.</p>
+
+<p>The "HeaderData" contains a definition of the contents of each HashData
+ chunk. We might want to store an offset to all of the debug information
+ entries (DIEs) for each name. To keep things extensible, we create a list of
+ items, or Atoms, that are contained in the data for each name. First comes the
+ type of the data in each atom:</p>
+<div class="doc_code">
+<pre>
+enum AtomType
+{
+ eAtomTypeNULL = 0u,
+ eAtomTypeDIEOffset = 1u, // DIE offset, check form for encoding
+ eAtomTypeCUOffset = 2u, // DIE offset of the compiler unit header that contains the item in question
+ eAtomTypeTag = 3u, // DW_TAG_xxx value, should be encoded as DW_FORM_data1 (if no tags exceed 255) or DW_FORM_data2
+ eAtomTypeNameFlags = 4u, // Flags from enum NameFlags
+ eAtomTypeTypeFlags = 5u, // Flags from enum TypeFlags
+};
+</pre>
+</div>
+<p>The enumeration values and their meanings are:</p>
+<div class="doc_code">
+<pre>
+ eAtomTypeNULL - a termination atom that specifies the end of the atom list
+ eAtomTypeDIEOffset - an offset into the .debug_info section for the DWARF DIE for this name
+ eAtomTypeCUOffset - an offset into the .debug_info section for the CU that contains the DIE
+ eAtomTypeDIETag - The DW_TAG_XXX enumeration value so you don't have to parse the DWARF to see what it is
+ eAtomTypeNameFlags - Flags for functions and global variables (isFunction, isInlined, isExternal...)
+ eAtomTypeTypeFlags - Flags for types (isCXXClass, isObjCClass, ...)
+</pre>
+</div>
+<p>Then we allow each atom type to define the atom type and how the data for
+ each atom type data is encoded:</p>
+<div class="doc_code">
+<pre>
+struct Atom
+{
+ uint16_t type; // AtomType enum value
+ uint16_t form; // DWARF DW_FORM_XXX defines
+};
+</pre>
+</div>
+<p>The "form" type above is from the DWARF specification and defines the
+ exact encoding of the data for the Atom type. See the DWARF specification for
+ the DW_FORM_ definitions.</p>
+<div class="doc_code">
+<pre>
+struct HeaderData
+{
+ uint32_t die_offset_base;
+ uint32_t atom_count;
+ Atoms atoms[atom_count0];
+};
+</pre>
+</div>
+<p>"HeaderData" defines the base DIE offset that should be added to any atoms
+ that are encoded using the DW_FORM_ref1, DW_FORM_ref2, DW_FORM_ref4,
+ DW_FORM_ref8 or DW_FORM_ref_udata. It also defines what is contained in
+ each "HashData" object -- Atom.form tells us how large each field will be in
+ the HashData and the Atom.type tells us how this data should be interpreted.</p>
+
+<p>For the current implementations of the ".apple_names" (all functions + globals),
+ the ".apple_types" (names of all types that are defined), and the
+ ".apple_namespaces" (all namespaces), we currently set the Atom array to be:</p>
+<div class="doc_code">
+<pre>
+HeaderData.atom_count = 1;
+HeaderData.atoms[0].type = eAtomTypeDIEOffset;
+HeaderData.atoms[0].form = DW_FORM_data4;
+</pre>
+</div>
+<p>This defines the contents to be the DIE offset (eAtomTypeDIEOffset) that is
+ encoded as a 32 bit value (DW_FORM_data4). This allows a single name to have
+ multiple matching DIEs in a single file, which could come up with an inlined
+ function for instance. Future tables could include more information about the
+ DIE such as flags indicating if the DIE is a function, method, block,
+ or inlined.</p>
+
+<p>The KeyType for the DWARF table is a 32 bit string table offset into the
+ ".debug_str" table. The ".debug_str" is the string table for the DWARF which
+ may already contain copies of all of the strings. This helps make sure, with
+ help from the compiler, that we reuse the strings between all of the DWARF
+ sections and keeps the hash table size down. Another benefit to having the
+ compiler generate all strings as DW_FORM_strp in the debug info, is that
+ DWARF parsing can be made much faster.</p>
+
+<p>After a lookup is made, we get an offset into the hash data. The hash data
+ needs to be able to deal with 32 bit hash collisions, so the chunk of data
+ at the offset in the hash data consists of a triple:</p>
+<div class="doc_code">
+<pre>
+uint32_t str_offset
+uint32_t hash_data_count
+HashData[hash_data_count]
+</pre>
+</div>
+<p>If "str_offset" is zero, then the bucket contents are done. 99.9% of the
+ hash data chunks contain a single item (no 32 bit hash collision):</p>
+<div class="doc_code">
+<pre>
+.------------.
+| 0x00001023 | uint32_t KeyType (.debug_str[0x0001023] => "main")
+| 0x00000004 | uint32_t HashData count
+| 0x........ | uint32_t HashData[0] DIE offset
+| 0x........ | uint32_t HashData[1] DIE offset
+| 0x........ | uint32_t HashData[2] DIE offset
+| 0x........ | uint32_t HashData[3] DIE offset
+| 0x00000000 | uint32_t KeyType (end of hash chain)
+`------------'
+</pre>
+</div>
+<p>If there are collisions, you will have multiple valid string offsets:</p>
+<div class="doc_code">
+<pre>
+.------------.
+| 0x00001023 | uint32_t KeyType (.debug_str[0x0001023] => "main")
+| 0x00000004 | uint32_t HashData count
+| 0x........ | uint32_t HashData[0] DIE offset
+| 0x........ | uint32_t HashData[1] DIE offset
+| 0x........ | uint32_t HashData[2] DIE offset
+| 0x........ | uint32_t HashData[3] DIE offset
+| 0x00002023 | uint32_t KeyType (.debug_str[0x0002023] => "print")
+| 0x00000002 | uint32_t HashData count
+| 0x........ | uint32_t HashData[0] DIE offset
+| 0x........ | uint32_t HashData[1] DIE offset
+| 0x00000000 | uint32_t KeyType (end of hash chain)
+`------------'
+</pre>
+</div>
+<p>Current testing with real world C++ binaries has shown that there is around 1
+ 32 bit hash collision per 100,000 name entries.</p>
+</div>
+<!-- ======================================================================= -->
+<h4>
+ <a name="acceltablecontents">Contents</a>
+</h4>
+<!-- ======================================================================= -->
+<div>
+<p>As we said, we want to strictly define exactly what is included in the
+ different tables. For DWARF, we have 3 tables: ".apple_names", ".apple_types",
+ and ".apple_namespaces".</p>
+
+<p>".apple_names" sections should contain an entry for each DWARF DIE whose
+ DW_TAG is a DW_TAG_label, DW_TAG_inlined_subroutine, or DW_TAG_subprogram that
+ has address attributes: DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges or
+ DW_AT_entry_pc. It also contains DW_TAG_variable DIEs that have a DW_OP_addr
+ in the location (global and static variables). All global and static variables
+ should be included, including those scoped within functions and classes. For
+ example using the following code:</p>
+<div class="doc_code">
+<pre>
+static int var = 0;
+
+void f ()
+{
+ static int var = 0;
+}
+</pre>
+</div>
+<p>Both of the static "var" variables would be included in the table. All
+ functions should emit both their full names and their basenames. For C or C++,
+ the full name is the mangled name (if available) which is usually in the
+ DW_AT_MIPS_linkage_name attribute, and the DW_AT_name contains the function
+ basename. If global or static variables have a mangled name in a
+ DW_AT_MIPS_linkage_name attribute, this should be emitted along with the
+ simple name found in the DW_AT_name attribute.</p>
+
+<p>".apple_types" sections should contain an entry for each DWARF DIE whose
+ tag is one of:</p>
+<ul>
+ <li>DW_TAG_array_type</li>
+ <li>DW_TAG_class_type</li>
+ <li>DW_TAG_enumeration_type</li>
+ <li>DW_TAG_pointer_type</li>
+ <li>DW_TAG_reference_type</li>
+ <li>DW_TAG_string_type</li>
+ <li>DW_TAG_structure_type</li>
+ <li>DW_TAG_subroutine_type</li>
+ <li>DW_TAG_typedef</li>
+ <li>DW_TAG_union_type</li>
+ <li>DW_TAG_ptr_to_member_type</li>
+ <li>DW_TAG_set_type</li>
+ <li>DW_TAG_subrange_type</li>
+ <li>DW_TAG_base_type</li>
+ <li>DW_TAG_const_type</li>
+ <li>DW_TAG_constant</li>
+ <li>DW_TAG_file_type</li>
+ <li>DW_TAG_namelist</li>
+ <li>DW_TAG_packed_type</li>
+ <li>DW_TAG_volatile_type</li>
+ <li>DW_TAG_restrict_type</li>
+ <li>DW_TAG_interface_type</li>
+ <li>DW_TAG_unspecified_type</li>
+ <li>DW_TAG_shared_type</li>
+</ul>
+<p>Only entries with a DW_AT_name attribute are included, and the entry must
+ not be a forward declaration (DW_AT_declaration attribute with a non-zero value).
+ For example, using the following code:</p>
+<div class="doc_code">
+<pre>
+int main ()
+{
+ int *b = 0;
+ return *b;
+}
+</pre>
+</div>
+<p>We get a few type DIEs:</p>
+<div class="doc_code">
+<pre>
+0x00000067: TAG_base_type [5]
+ AT_encoding( DW_ATE_signed )
+ AT_name( "int" )
+ AT_byte_size( 0x04 )
+
+0x0000006e: TAG_pointer_type [6]
+ AT_type( {0x00000067} ( int ) )
+ AT_byte_size( 0x08 )
+</pre>
+</div>
+<p>The DW_TAG_pointer_type is not included because it does not have a DW_AT_name.</p>
+
+<p>".apple_namespaces" section should contain all DW_TAG_namespace DIEs. If
+ we run into a namespace that has no name this is an anonymous namespace,
+ and the name should be output as "(anonymous namespace)" (without the quotes).
+ Why? This matches the output of the abi::cxa_demangle() that is in the standard
+ C++ library that demangles mangled names.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h4>
+ <a name="acceltableextensions">Language Extensions and File Format Changes</a>
+</h4>
+<!-- ======================================================================= -->
+<div>
+<h5>Objective-C Extensions</h5>
+<p>".apple_objc" section should contain all DW_TAG_subprogram DIEs for an
+ Objective-C class. The name used in the hash table is the name of the
+ Objective-C class itself. If the Objective-C class has a category, then an
+ entry is made for both the class name without the category, and for the class
+ name with the category. So if we have a DIE at offset 0x1234 with a name
+ of method "-[NSString(my_additions) stringWithSpecialString:]", we would add
+ an entry for "NSString" that points to DIE 0x1234, and an entry for
+ "NSString(my_additions)" that points to 0x1234. This allows us to quickly
+ track down all Objective-C methods for an Objective-C class when doing
+ expressions. It is needed because of the dynamic nature of Objective-C where
+ anyone can add methods to a class. The DWARF for Objective-C methods is also
+ emitted differently from C++ classes where the methods are not usually
+ contained in the class definition, they are scattered about across one or more
+ compile units. Categories can also be defined in different shared libraries.
+ So we need to be able to quickly find all of the methods and class functions
+ given the Objective-C class name, or quickly find all methods and class
+ functions for a class + category name. This table does not contain any selector
+ names, it just maps Objective-C class names (or class names + category) to all
+ of the methods and class functions. The selectors are added as function
+ basenames in the .debug_names section.</p>
+
+<p>In the ".apple_names" section for Objective-C functions, the full name is the
+ entire function name with the brackets ("-[NSString stringWithCString:]") and the
+ basename is the selector only ("stringWithCString:").</p>
+
+<h5>Mach-O Changes</h5>
+<p>The sections names for the apple hash tables are for non mach-o files. For
+ mach-o files, the sections should be contained in the "__DWARF" segment with
+ names as follows:</p>
+<ul>
+ <li>".apple_names" -> "__apple_names"</li>
+ <li>".apple_types" -> "__apple_types"</li>
+ <li>".apple_namespaces" -> "__apple_namespac" (16 character limit)</li>
+ <li> ".apple_objc" -> "__apple_objc"</li>
+</ul>
+</div>
+</div>
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/SystemLibrary.html b/docs/SystemLibrary.html
new file mode 100644
index 00000000000..1ef221fa274
--- /dev/null
+++ b/docs/SystemLibrary.html
@@ -0,0 +1,316 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>System Library</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>System Library</h1>
+<ul>
+ <li><a href="#abstract">Abstract</a></li>
+ <li><a href="#requirements">Keeping LLVM Portable</a>
+ <ol>
+ <li><a href="#headers">Don't Include System Headers</a></li>
+ <li><a href="#expose">Don't Expose System Headers</a></li>
+ <li><a href="#c_headers">Allow Standard C Header Files</a></li>
+ <li><a href="#cpp_headers">Allow Standard C++ Header Files</a></li>
+ <li><a href="#highlev">High-Level Interface</a></li>
+ <li><a href="#nofunc">No Exposed Functions</a></li>
+ <li><a href="#nodata">No Exposed Data</a></li>
+ <li><a href="#nodupl">No Duplicate Implementations</a></li>
+ <li><a href="#nounused">No Unused Functionality</a></li>
+ <li><a href="#virtuals">No Virtual Methods</a></li>
+ <li><a href="#softerrors">Minimize Soft Errors</a></li>
+ <li><a href="#throw_spec">No throw() Specifications</a></li>
+ <li><a href="#organization">Code Organization</a></li>
+ <li><a href="#semantics">Consistent Semantics</a></li>
+ <li><a href="#bug">Tracking Bugzilla Bug: 351</a></li>
+ </ol></li>
+</ul>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:rspencer@x10sys.com">Reid Spencer</a></p>
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2><a name="abstract">Abstract</a></h2>
+<div>
+ <p>This document provides some details on LLVM's System Library, located in
+ the source at <tt>lib/System</tt> and <tt>include/llvm/System</tt>. The
+ library's purpose is to shield LLVM from the differences between operating
+ systems for the few services LLVM needs from the operating system. Much of
+ LLVM is written using portability features of standard C++. However, in a few
+ areas, system dependent facilities are needed and the System Library is the
+ wrapper around those system calls.</p>
+ <p>By centralizing LLVM's use of operating system interfaces, we make it
+ possible for the LLVM tool chain and runtime libraries to be more easily
+ ported to new platforms since (theoretically) only <tt>lib/System</tt> needs
+ to be ported. This library also unclutters the rest of LLVM from #ifdef use
+ and special cases for specific operating systems. Such uses are replaced
+ with simple calls to the interfaces provided in <tt>include/llvm/System</tt>.
+ </p>
+ <p>Note that the System Library is not intended to be a complete operating
+ system wrapper (such as the Adaptive Communications Environment (ACE) or
+ Apache Portable Runtime (APR)), but only provides the functionality necessary
+ to support LLVM.
+ <p>The System Library was written by Reid Spencer who formulated the
+ design based on similar work originating from the eXtensible Programming
+ System (XPS). Several people helped with the effort; especially,
+ Jeff Cohen and Henrik Bach on the Win32 port.</p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="requirements">Keeping LLVM Portable</a>
+</h2>
+<div>
+ <p>In order to keep LLVM portable, LLVM developers should adhere to a set of
+ portability rules associated with the System Library. Adherence to these rules
+ should help the System Library achieve its goal of shielding LLVM from the
+ variations in operating system interfaces and doing so efficiently. The
+ following sections define the rules needed to fulfill this objective.</p>
+
+<!-- ======================================================================= -->
+<h3><a name="headers">Don't Include System Headers</a></h3>
+<div>
+ <p>Except in <tt>lib/System</tt>, no LLVM source code should directly
+ <tt>#include</tt> a system header. Care has been taken to remove all such
+ <tt>#includes</tt> from LLVM while <tt>lib/System</tt> was being
+ developed. Specifically this means that header files like "unistd.h",
+ "windows.h", "stdio.h", and "string.h" are forbidden to be included by LLVM
+ source code outside the implementation of <tt>lib/System</tt>.</p>
+ <p>To obtain system-dependent functionality, existing interfaces to the system
+ found in <tt>include/llvm/System</tt> should be used. If an appropriate
+ interface is not available, it should be added to <tt>include/llvm/System</tt>
+ and implemented in <tt>lib/System</tt> for all supported platforms.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="expose">Don't Expose System Headers</a></h3>
+<div>
+ <p>The System Library must shield LLVM from <em>all</em> system headers. To
+ obtain system level functionality, LLVM source must
+ <tt>#include "llvm/System/Thing.h"</tt> and nothing else. This means that
+ <tt>Thing.h</tt> cannot expose any system header files. This protects LLVM
+ from accidentally using system specific functionality and only allows it
+ via the <tt>lib/System</tt> interface.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="c_headers">Use Standard C Headers</a></h3>
+<div>
+ <p>The <em>standard</em> C headers (the ones beginning with "c") are allowed
+ to be exposed through the <tt>lib/System</tt> interface. These headers and
+ the things they declare are considered to be platform agnostic. LLVM source
+ files may include them directly or obtain their inclusion through
+ <tt>lib/System</tt> interfaces.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="cpp_headers">Use Standard C++ Headers</a></h3>
+<div>
+ <p>The <em>standard</em> C++ headers from the standard C++ library and
+ standard template library may be exposed through the <tt>lib/System</tt>
+ interface. These headers and the things they declare are considered to be
+ platform agnostic. LLVM source files may include them or obtain their
+ inclusion through lib/System interfaces.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="highlev">High Level Interface</a></h3>
+<div>
+ <p>The entry points specified in the interface of lib/System must be aimed at
+ completing some reasonably high level task needed by LLVM. We do not want to
+ simply wrap each operating system call. It would be preferable to wrap several
+ operating system calls that are always used in conjunction with one another by
+ LLVM.</p>
+ <p>For example, consider what is needed to execute a program, wait for it to
+ complete, and return its result code. On Unix, this involves the following
+ operating system calls: <tt>getenv, fork, execve,</tt> and <tt>wait</tt>. The
+ correct thing for lib/System to provide is a function, say
+ <tt>ExecuteProgramAndWait</tt>, that implements the functionality completely.
+ what we don't want is wrappers for the operating system calls involved.</p>
+ <p>There must <em>not</em> be a one-to-one relationship between operating
+ system calls and the System library's interface. Any such interface function
+ will be suspicious.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="nounused">No Unused Functionality</a></h3>
+<div>
+ <p>There must be no functionality specified in the interface of lib/System
+ that isn't actually used by LLVM. We're not writing a general purpose
+ operating system wrapper here, just enough to satisfy LLVM's needs. And, LLVM
+ doesn't need much. This design goal aims to keep the lib/System interface
+ small and understandable which should foster its actual use and adoption.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="nodupl">No Duplicate Implementations</a></h3>
+<div>
+ <p>The implementation of a function for a given platform must be written
+ exactly once. This implies that it must be possible to apply a function's
+ implementation to multiple operating systems if those operating systems can
+ share the same implementation. This rule applies to the set of operating
+ systems supported for a given class of operating system (e.g. Unix, Win32).
+ </p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="virtuals">No Virtual Methods</a></h3>
+<div>
+ <p>The System Library interfaces can be called quite frequently by LLVM. In
+ order to make those calls as efficient as possible, we discourage the use of
+ virtual methods. There is no need to use inheritance for implementation
+ differences, it just adds complexity. The <tt>#include</tt> mechanism works
+ just fine.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="nofunc">No Exposed Functions</a></h3>
+<div>
+ <p>Any functions defined by system libraries (i.e. not defined by lib/System)
+ must not be exposed through the lib/System interface, even if the header file
+ for that function is not exposed. This prevents inadvertent use of system
+ specific functionality.</p>
+ <p>For example, the <tt>stat</tt> system call is notorious for having
+ variations in the data it provides. <tt>lib/System</tt> must not declare
+ <tt>stat</tt> nor allow it to be declared. Instead it should provide its own
+ interface to discovering information about files and directories. Those
+ interfaces may be implemented in terms of <tt>stat</tt> but that is strictly
+ an implementation detail. The interface provided by the System Library must
+ be implemented on all platforms (even those without <tt>stat</tt>).</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="nodata">No Exposed Data</a></h3>
+<div>
+ <p>Any data defined by system libraries (i.e. not defined by lib/System) must
+ not be exposed through the lib/System interface, even if the header file for
+ that function is not exposed. As with functions, this prevents inadvertent use
+ of data that might not exist on all platforms.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="softerrors">Minimize Soft Errors</a></h3>
+<div>
+ <p>Operating system interfaces will generally provide error results for every
+ little thing that could go wrong. In almost all cases, you can divide these
+ error results into two groups: normal/good/soft and abnormal/bad/hard. That
+ is, some of the errors are simply information like "file not found",
+ "insufficient privileges", etc. while other errors are much harder like
+ "out of space", "bad disk sector", or "system call interrupted". We'll call
+ the first group "<i>soft</i>" errors and the second group "<i>hard</i>"
+ errors.<p>
+ <p>lib/System must always attempt to minimize soft errors.
+ This is a design requirement because the
+ minimization of soft errors can affect the granularity and the nature of the
+ interface. In general, if you find that you're wanting to throw soft errors,
+ you must review the granularity of the interface because it is likely you're
+ trying to implement something that is too low level. The rule of thumb is to
+ provide interface functions that <em>can't</em> fail, except when faced with
+ hard errors.</p>
+ <p>For a trivial example, suppose we wanted to add an "OpenFileForWriting"
+ function. For many operating systems, if the file doesn't exist, attempting
+ to open the file will produce an error. However, lib/System should not
+ simply throw that error if it occurs because its a soft error. The problem
+ is that the interface function, OpenFileForWriting is too low level. It should
+ be OpenOrCreateFileForWriting. In the case of the soft "doesn't exist" error,
+ this function would just create it and then open it for writing.</p>
+ <p>This design principle needs to be maintained in lib/System because it
+ avoids the propagation of soft error handling throughout the rest of LLVM.
+ Hard errors will generally just cause a termination for an LLVM tool so don't
+ be bashful about throwing them.</p>
+ <p>Rules of thumb:</p>
+ <ol>
+ <li>Don't throw soft errors, only hard errors.</li>
+ <li>If you're tempted to throw a soft error, re-think the interface.</li>
+ <li>Handle internally the most common normal/good/soft error conditions
+ so the rest of LLVM doesn't have to.</li>
+ </ol>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="throw_spec">No throw Specifications</a></h3>
+<div>
+ <p>None of the lib/System interface functions may be declared with C++
+ <tt>throw()</tt> specifications on them. This requirement makes sure that the
+ compiler does not insert additional exception handling code into the interface
+ functions. This is a performance consideration: lib/System functions are at
+ the bottom of many call chains and as such can be frequently called. We
+ need them to be as efficient as possible. However, no routines in the
+ system library should actually throw exceptions.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="organization">Code Organization</a></h3>
+<div>
+ <p>Implementations of the System Library interface are separated by their
+ general class of operating system. Currently only Unix and Win32 classes are
+ defined but more could be added for other operating system classifications.
+ To distinguish which implementation to compile, the code in lib/System uses
+ the LLVM_ON_UNIX and LLVM_ON_WIN32 #defines provided via configure through the
+ llvm/Config/config.h file. Each source file in lib/System, after implementing
+ the generic (operating system independent) functionality needs to include the
+ correct implementation using a set of <tt>#if defined(LLVM_ON_XYZ)</tt>
+ directives. For example, if we had lib/System/File.cpp, we'd expect to see in
+ that file:</p>
+ <pre><tt>
+ #if defined(LLVM_ON_UNIX)
+ #include "Unix/File.cpp"
+ #endif
+ #if defined(LLVM_ON_WIN32)
+ #include "Win32/File.cpp"
+ #endif
+ </tt></pre>
+ <p>The implementation in lib/System/Unix/File.cpp should handle all Unix
+ variants. The implementation in lib/System/Win32/File.cpp should handle all
+ Win32 variants. What this does is quickly differentiate the basic class of
+ operating system that will provide the implementation. The specific details
+ for a given platform must still be determined through the use of
+ <tt>#ifdef</tt>.</p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="semantics">Consistent Semantics</a></h3>
+<div>
+ <p>The implementation of a lib/System interface can vary drastically between
+ platforms. That's okay as long as the end result of the interface function
+ is the same. For example, a function to create a directory is pretty straight
+ forward on all operating system. System V IPC on the other hand isn't even
+ supported on all platforms. Instead of "supporting" System V IPC, lib/System
+ should provide an interface to the basic concept of inter-process
+ communications. The implementations might use System V IPC if that was
+ available or named pipes, or whatever gets the job done effectively for a
+ given operating system. In all cases, the interface and the implementation
+ must be semantically consistent. </p>
+</div>
+
+<!-- ======================================================================= -->
+<h3><a name="bug">Bug 351</a></h3>
+<div>
+ <p>See <a href="http://llvm.org/PR351">bug 351</a>
+ for further details on the progress of this work</p>
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="mailto:rspencer@x10sys.com">Reid Spencer</a><br>
+ <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/TableGenFundamentals.rst b/docs/TableGenFundamentals.rst
new file mode 100644
index 00000000000..bfb2618998a
--- /dev/null
+++ b/docs/TableGenFundamentals.rst
@@ -0,0 +1,799 @@
+.. _tablegen:
+
+=====================
+TableGen Fundamentals
+=====================
+
+.. contents::
+ :local:
+
+Introduction
+============
+
+TableGen's purpose is to help a human develop and maintain records of
+domain-specific information. Because there may be a large number of these
+records, it is specifically designed to allow writing flexible descriptions and
+for common features of these records to be factored out. This reduces the
+amount of duplication in the description, reduces the chance of error, and makes
+it easier to structure domain specific information.
+
+The core part of TableGen `parses a file`_, instantiates the declarations, and
+hands the result off to a domain-specific `TableGen backend`_ for processing.
+The current major user of TableGen is the `LLVM code
+generator <CodeGenerator.html>`_.
+
+Note that if you work on TableGen much, and use emacs or vim, that you can find
+an emacs "TableGen mode" and a vim language file in the ``llvm/utils/emacs`` and
+``llvm/utils/vim`` directories of your LLVM distribution, respectively.
+
+.. _intro:
+
+Basic concepts
+--------------
+
+TableGen files consist of two key parts: 'classes' and 'definitions', both of
+which are considered 'records'.
+
+**TableGen records** have a unique name, a list of values, and a list of
+superclasses. The list of values is the main data that TableGen builds for each
+record; it is this that holds the domain specific information for the
+application. The interpretation of this data is left to a specific `TableGen
+backend`_, but the structure and format rules are taken care of and are fixed by
+TableGen.
+
+**TableGen definitions** are the concrete form of 'records'. These generally do
+not have any undefined values, and are marked with the '``def``' keyword.
+
+**TableGen classes** are abstract records that are used to build and describe
+other records. These 'classes' allow the end-user to build abstractions for
+either the domain they are targeting (such as "Register", "RegisterClass", and
+"Instruction" in the LLVM code generator) or for the implementor to help factor
+out common properties of records (such as "FPInst", which is used to represent
+floating point instructions in the X86 backend). TableGen keeps track of all of
+the classes that are used to build up a definition, so the backend can find all
+definitions of a particular class, such as "Instruction".
+
+**TableGen multiclasses** are groups of abstract records that are instantiated
+all at once. Each instantiation can result in multiple TableGen definitions.
+If a multiclass inherits from another multiclass, the definitions in the
+sub-multiclass become part of the current multiclass, as if they were declared
+in the current multiclass.
+
+.. _described above:
+
+An example record
+-----------------
+
+With no other arguments, TableGen parses the specified file and prints out all
+of the classes, then all of the definitions. This is a good way to see what the
+various definitions expand to fully. Running this on the ``X86.td`` file prints
+this (at the time of this writing):
+
+.. code-block:: llvm
+
+ ...
+ def ADD32rr { // Instruction X86Inst I
+ string Namespace = "X86";
+ dag OutOperandList = (outs GR32:$dst);
+ dag InOperandList = (ins GR32:$src1, GR32:$src2);
+ string AsmString = "add{l}\t{$src2, $dst|$dst, $src2}";
+ list<dag> Pattern = [(set GR32:$dst, (add GR32:$src1, GR32:$src2))];
+ list<Register> Uses = [];
+ list<Register> Defs = [EFLAGS];
+ list<Predicate> Predicates = [];
+ int CodeSize = 3;
+ int AddedComplexity = 0;
+ bit isReturn = 0;
+ bit isBranch = 0;
+ bit isIndirectBranch = 0;
+ bit isBarrier = 0;
+ bit isCall = 0;
+ bit canFoldAsLoad = 0;
+ bit mayLoad = 0;
+ bit mayStore = 0;
+ bit isImplicitDef = 0;
+ bit isConvertibleToThreeAddress = 1;
+ bit isCommutable = 1;
+ bit isTerminator = 0;
+ bit isReMaterializable = 0;
+ bit isPredicable = 0;
+ bit hasDelaySlot = 0;
+ bit usesCustomInserter = 0;
+ bit hasCtrlDep = 0;
+ bit isNotDuplicable = 0;
+ bit hasSideEffects = 0;
+ bit neverHasSideEffects = 0;
+ InstrItinClass Itinerary = NoItinerary;
+ string Constraints = "";
+ string DisableEncoding = "";
+ bits<8> Opcode = { 0, 0, 0, 0, 0, 0, 0, 1 };
+ Format Form = MRMDestReg;
+ bits<6> FormBits = { 0, 0, 0, 0, 1, 1 };
+ ImmType ImmT = NoImm;
+ bits<3> ImmTypeBits = { 0, 0, 0 };
+ bit hasOpSizePrefix = 0;
+ bit hasAdSizePrefix = 0;
+ bits<4> Prefix = { 0, 0, 0, 0 };
+ bit hasREX_WPrefix = 0;
+ FPFormat FPForm = ?;
+ bits<3> FPFormBits = { 0, 0, 0 };
+ }
+ ...
+
+This definition corresponds to a 32-bit register-register add instruction in the
+X86. The string after the '``def``' string indicates the name of the
+record---"``ADD32rr``" in this case---and the comment at the end of the line
+indicates the superclasses of the definition. The body of the record contains
+all of the data that TableGen assembled for the record, indicating that the
+instruction is part of the "X86" namespace, the pattern indicating how the the
+instruction should be emitted into the assembly file, that it is a two-address
+instruction, has a particular encoding, etc. The contents and semantics of the
+information in the record is specific to the needs of the X86 backend, and is
+only shown as an example.
+
+As you can see, a lot of information is needed for every instruction supported
+by the code generator, and specifying it all manually would be unmaintainable,
+prone to bugs, and tiring to do in the first place. Because we are using
+TableGen, all of the information was derived from the following definition:
+
+.. code-block:: llvm
+
+ let Defs = [EFLAGS],
+ isCommutable = 1, // X = ADD Y,Z --> X = ADD Z,Y
+ isConvertibleToThreeAddress = 1 in // Can transform into LEA.
+ def ADD32rr : I<0x01, MRMDestReg, (outs GR32:$dst),
+ (ins GR32:$src1, GR32:$src2),
+ "add{l}\t{$src2, $dst|$dst, $src2}",
+ [(set GR32:$dst, (add GR32:$src1, GR32:$src2))]>;
+
+This definition makes use of the custom class ``I`` (extended from the custom
+class ``X86Inst``), which is defined in the X86-specific TableGen file, to
+factor out the common features that instructions of its class share. A key
+feature of TableGen is that it allows the end-user to define the abstractions
+they prefer to use when describing their information.
+
+Each def record has a special entry called "``NAME``." This is the name of the
+def ("``ADD32rr``" above). In the general case def names can be formed from
+various kinds of string processing expressions and ``NAME`` resolves to the
+final value obtained after resolving all of those expressions. The user may
+refer to ``NAME`` anywhere she desires to use the ultimate name of the def.
+``NAME`` should not be defined anywhere else in user code to avoid conflict
+problems.
+
+Running TableGen
+----------------
+
+TableGen runs just like any other LLVM tool. The first (optional) argument
+specifies the file to read. If a filename is not specified, ``llvm-tblgen``
+reads from standard input.
+
+To be useful, one of the `TableGen backends`_ must be used. These backends are
+selectable on the command line (type '``llvm-tblgen -help``' for a list). For
+example, to get a list of all of the definitions that subclass a particular type
+(which can be useful for building up an enum list of these records), use the
+``-print-enums`` option:
+
+.. code-block:: bash
+
+ $ llvm-tblgen X86.td -print-enums -class=Register
+ AH, AL, AX, BH, BL, BP, BPL, BX, CH, CL, CX, DH, DI, DIL, DL, DX, EAX, EBP, EBX,
+ ECX, EDI, EDX, EFLAGS, EIP, ESI, ESP, FP0, FP1, FP2, FP3, FP4, FP5, FP6, IP,
+ MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7, R10, R10B, R10D, R10W, R11, R11B, R11D,
+ R11W, R12, R12B, R12D, R12W, R13, R13B, R13D, R13W, R14, R14B, R14D, R14W, R15,
+ R15B, R15D, R15W, R8, R8B, R8D, R8W, R9, R9B, R9D, R9W, RAX, RBP, RBX, RCX, RDI,
+ RDX, RIP, RSI, RSP, SI, SIL, SP, SPL, ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7,
+ XMM0, XMM1, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15, XMM2, XMM3, XMM4, XMM5,
+ XMM6, XMM7, XMM8, XMM9,
+
+ $ llvm-tblgen X86.td -print-enums -class=Instruction
+ ABS_F, ABS_Fp32, ABS_Fp64, ABS_Fp80, ADC32mi, ADC32mi8, ADC32mr, ADC32ri,
+ ADC32ri8, ADC32rm, ADC32rr, ADC64mi32, ADC64mi8, ADC64mr, ADC64ri32, ADC64ri8,
+ ADC64rm, ADC64rr, ADD16mi, ADD16mi8, ADD16mr, ADD16ri, ADD16ri8, ADD16rm,
+ ADD16rr, ADD32mi, ADD32mi8, ADD32mr, ADD32ri, ADD32ri8, ADD32rm, ADD32rr,
+ ADD64mi32, ADD64mi8, ADD64mr, ADD64ri32, ...
+
+The default backend prints out all of the records, as `described above`_.
+
+If you plan to use TableGen, you will most likely have to `write a backend`_
+that extracts the information specific to what you need and formats it in the
+appropriate way.
+
+.. _parses a file:
+
+TableGen syntax
+===============
+
+TableGen doesn't care about the meaning of data (that is up to the backend to
+define), but it does care about syntax, and it enforces a simple type system.
+This section describes the syntax and the constructs allowed in a TableGen file.
+
+TableGen primitives
+-------------------
+
+TableGen comments
+^^^^^^^^^^^^^^^^^
+
+TableGen supports BCPL style "``//``" comments, which run to the end of the
+line, and it also supports **nestable** "``/* */``" comments.
+
+.. _TableGen type:
+
+The TableGen type system
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+TableGen files are strongly typed, in a simple (but complete) type-system.
+These types are used to perform automatic conversions, check for errors, and to
+help interface designers constrain the input that they allow. Every `value
+definition`_ is required to have an associated type.
+
+TableGen supports a mixture of very low-level types (such as ``bit``) and very
+high-level types (such as ``dag``). This flexibility is what allows it to
+describe a wide range of information conveniently and compactly. The TableGen
+types are:
+
+``bit``
+ A 'bit' is a boolean value that can hold either 0 or 1.
+
+``int``
+ The 'int' type represents a simple 32-bit integer value, such as 5.
+
+``string``
+ The 'string' type represents an ordered sequence of characters of arbitrary
+ length.
+
+``bits<n>``
+ A 'bits' type is an arbitrary, but fixed, size integer that is broken up
+ into individual bits. This type is useful because it can handle some bits
+ being defined while others are undefined.
+
+``list<ty>``
+ This type represents a list whose elements are some other type. The
+ contained type is arbitrary: it can even be another list type.
+
+Class type
+ Specifying a class name in a type context means that the defined value must
+ be a subclass of the specified class. This is useful in conjunction with
+ the ``list`` type, for example, to constrain the elements of the list to a
+ common base class (e.g., a ``list<Register>`` can only contain definitions
+ derived from the "``Register``" class).
+
+``dag``
+ This type represents a nestable directed graph of elements.
+
+``code``
+ This represents a big hunk of text. This is lexically distinct from string
+ values because it doesn't require escaping double quotes and other common
+ characters that occur in code.
+
+To date, these types have been sufficient for describing things that TableGen
+has been used for, but it is straight-forward to extend this list if needed.
+
+.. _TableGen expressions:
+
+TableGen values and expressions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+TableGen allows for a pretty reasonable number of different expression forms
+when building up values. These forms allow the TableGen file to be written in a
+natural syntax and flavor for the application. The current expression forms
+supported include:
+
+``?``
+ uninitialized field
+
+``0b1001011``
+ binary integer value
+
+``07654321``
+ octal integer value (indicated by a leading 0)
+
+``7``
+ decimal integer value
+
+``0x7F``
+ hexadecimal integer value
+
+``"foo"``
+ string value
+
+``[{ ... }]``
+ code fragment
+
+``[ X, Y, Z ]<type>``
+ list value. <type> is the type of the list element and is usually optional.
+ In rare cases, TableGen is unable to deduce the element type in which case
+ the user must specify it explicitly.
+
+``{ a, b, c }``
+ initializer for a "bits<3>" value
+
+``value``
+ value reference
+
+``value{17}``
+ access to one bit of a value
+
+``value{15-17}``
+ access to multiple bits of a value
+
+``DEF``
+ reference to a record definition
+
+``CLASS<val list>``
+ reference to a new anonymous definition of CLASS with the specified template
+ arguments.
+
+``X.Y``
+ reference to the subfield of a value
+
+``list[4-7,17,2-3]``
+ A slice of the 'list' list, including elements 4,5,6,7,17,2, and 3 from it.
+ Elements may be included multiple times.
+
+``foreach <var> = [ <list> ] in { <body> }``
+
+``foreach <var> = [ <list> ] in <def>``
+ Replicate <body> or <def>, replacing instances of <var> with each value
+ in <list>. <var> is scoped at the level of the ``foreach`` loop and must
+ not conflict with any other object introduced in <body> or <def>. Currently
+ only ``def``\s are expanded within <body>.
+
+``foreach <var> = 0-15 in ...``
+
+``foreach <var> = {0-15,32-47} in ...``
+ Loop over ranges of integers. The braces are required for multiple ranges.
+
+``(DEF a, b)``
+ a dag value. The first element is required to be a record definition, the
+ remaining elements in the list may be arbitrary other values, including
+ nested ```dag``' values.
+
+``!strconcat(a, b)``
+ A string value that is the result of concatenating the 'a' and 'b' strings.
+
+``str1#str2``
+ "#" (paste) is a shorthand for !strconcat. It may concatenate things that
+ are not quoted strings, in which case an implicit !cast<string> is done on
+ the operand of the paste.
+
+``!cast<type>(a)``
+ A symbol of type *type* obtained by looking up the string 'a' in the symbol
+ table. If the type of 'a' does not match *type*, TableGen aborts with an
+ error. !cast<string> is a special case in that the argument must be an
+ object defined by a 'def' construct.
+
+``!subst(a, b, c)``
+ If 'a' and 'b' are of string type or are symbol references, substitute 'b'
+ for 'a' in 'c.' This operation is analogous to $(subst) in GNU make.
+
+``!foreach(a, b, c)``
+ For each member 'b' of dag or list 'a' apply operator 'c.' 'b' is a dummy
+ variable that should be declared as a member variable of an instantiated
+ class. This operation is analogous to $(foreach) in GNU make.
+
+``!head(a)``
+ The first element of list 'a.'
+
+``!tail(a)``
+ The 2nd-N elements of list 'a.'
+
+``!empty(a)``
+ An integer {0,1} indicating whether list 'a' is empty.
+
+``!if(a,b,c)``
+ 'b' if the result of 'int' or 'bit' operator 'a' is nonzero, 'c' otherwise.
+
+``!eq(a,b)``
+ 'bit 1' if string a is equal to string b, 0 otherwise. This only operates
+ on string, int and bit objects. Use !cast<string> to compare other types of
+ objects.
+
+Note that all of the values have rules specifying how they convert to values
+for different types. These rules allow you to assign a value like "``7``"
+to a "``bits<4>``" value, for example.
+
+Classes and definitions
+-----------------------
+
+As mentioned in the `intro`_, classes and definitions (collectively known as
+'records') in TableGen are the main high-level unit of information that TableGen
+collects. Records are defined with a ``def`` or ``class`` keyword, the record
+name, and an optional list of "`template arguments`_". If the record has
+superclasses, they are specified as a comma separated list that starts with a
+colon character ("``:``"). If `value definitions`_ or `let expressions`_ are
+needed for the class, they are enclosed in curly braces ("``{}``"); otherwise,
+the record ends with a semicolon.
+
+Here is a simple TableGen file:
+
+.. code-block:: llvm
+
+ class C { bit V = 1; }
+ def X : C;
+ def Y : C {
+ string Greeting = "hello";
+ }
+
+This example defines two definitions, ``X`` and ``Y``, both of which derive from
+the ``C`` class. Because of this, they both get the ``V`` bit value. The ``Y``
+definition also gets the Greeting member as well.
+
+In general, classes are useful for collecting together the commonality between a
+group of records and isolating it in a single place. Also, classes permit the
+specification of default values for their subclasses, allowing the subclasses to
+override them as they wish.
+
+.. _value definition:
+.. _value definitions:
+
+Value definitions
+^^^^^^^^^^^^^^^^^
+
+Value definitions define named entries in records. A value must be defined
+before it can be referred to as the operand for another value definition or
+before the value is reset with a `let expression`_. A value is defined by
+specifying a `TableGen type`_ and a name. If an initial value is available, it
+may be specified after the type with an equal sign. Value definitions require
+terminating semicolons.
+
+.. _let expression:
+.. _let expressions:
+.. _"let" expressions within a record:
+
+'let' expressions
+^^^^^^^^^^^^^^^^^
+
+A record-level let expression is used to change the value of a value definition
+in a record. This is primarily useful when a superclass defines a value that a
+derived class or definition wants to override. Let expressions consist of the
+'``let``' keyword followed by a value name, an equal sign ("``=``"), and a new
+value. For example, a new class could be added to the example above, redefining
+the ``V`` field for all of its subclasses:
+
+.. code-block:: llvm
+
+ class D : C { let V = 0; }
+ def Z : D;
+
+In this case, the ``Z`` definition will have a zero value for its ``V`` value,
+despite the fact that it derives (indirectly) from the ``C`` class, because the
+``D`` class overrode its value.
+
+.. _template arguments:
+
+Class template arguments
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+TableGen permits the definition of parameterized classes as well as normal
+concrete classes. Parameterized TableGen classes specify a list of variable
+bindings (which may optionally have defaults) that are bound when used. Here is
+a simple example:
+
+.. code-block:: llvm
+
+ class FPFormat<bits<3> val> {
+ bits<3> Value = val;
+ }
+ def NotFP : FPFormat<0>;
+ def ZeroArgFP : FPFormat<1>;
+ def OneArgFP : FPFormat<2>;
+ def OneArgFPRW : FPFormat<3>;
+ def TwoArgFP : FPFormat<4>;
+ def CompareFP : FPFormat<5>;
+ def CondMovFP : FPFormat<6>;
+ def SpecialFP : FPFormat<7>;
+
+In this case, template arguments are used as a space efficient way to specify a
+list of "enumeration values", each with a "``Value``" field set to the specified
+integer.
+
+The more esoteric forms of `TableGen expressions`_ are useful in conjunction
+with template arguments. As an example:
+
+.. code-block:: llvm
+
+ class ModRefVal<bits<2> val> {
+ bits<2> Value = val;
+ }
+
+ def None : ModRefVal<0>;
+ def Mod : ModRefVal<1>;
+ def Ref : ModRefVal<2>;
+ def ModRef : ModRefVal<3>;
+
+ class Value<ModRefVal MR> {
+ // Decode some information into a more convenient format, while providing
+ // a nice interface to the user of the "Value" class.
+ bit isMod = MR.Value{0};
+ bit isRef = MR.Value{1};
+
+ // other stuff...
+ }
+
+ // Example uses
+ def bork : Value<Mod>;
+ def zork : Value<Ref>;
+ def hork : Value<ModRef>;
+
+This is obviously a contrived example, but it shows how template arguments can
+be used to decouple the interface provided to the user of the class from the
+actual internal data representation expected by the class. In this case,
+running ``llvm-tblgen`` on the example prints the following definitions:
+
+.. code-block:: llvm
+
+ def bork { // Value
+ bit isMod = 1;
+ bit isRef = 0;
+ }
+ def hork { // Value
+ bit isMod = 1;
+ bit isRef = 1;
+ }
+ def zork { // Value
+ bit isMod = 0;
+ bit isRef = 1;
+ }
+
+This shows that TableGen was able to dig into the argument and extract a piece
+of information that was requested by the designer of the "Value" class. For
+more realistic examples, please see existing users of TableGen, such as the X86
+backend.
+
+Multiclass definitions and instances
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+While classes with template arguments are a good way to factor commonality
+between two instances of a definition, multiclasses allow a convenient notation
+for defining multiple definitions at once (instances of implicitly constructed
+classes). For example, consider an 3-address instruction set whose instructions
+come in two forms: "``reg = reg op reg``" and "``reg = reg op imm``"
+(e.g. SPARC). In this case, you'd like to specify in one place that this
+commonality exists, then in a separate place indicate what all the ops are.
+
+Here is an example TableGen fragment that shows this idea:
+
+.. code-block:: llvm
+
+ def ops;
+ def GPR;
+ def Imm;
+ class inst<int opc, string asmstr, dag operandlist>;
+
+ multiclass ri_inst<int opc, string asmstr> {
+ def _rr : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),
+ (ops GPR:$dst, GPR:$src1, GPR:$src2)>;
+ def _ri : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),
+ (ops GPR:$dst, GPR:$src1, Imm:$src2)>;
+ }
+
+ // Instantiations of the ri_inst multiclass.
+ defm ADD : ri_inst<0b111, "add">;
+ defm SUB : ri_inst<0b101, "sub">;
+ defm MUL : ri_inst<0b100, "mul">;
+ ...
+
+The name of the resultant definitions has the multidef fragment names appended
+to them, so this defines ``ADD_rr``, ``ADD_ri``, ``SUB_rr``, etc. A defm may
+inherit from multiple multiclasses, instantiating definitions from each
+multiclass. Using a multiclass this way is exactly equivalent to instantiating
+the classes multiple times yourself, e.g. by writing:
+
+.. code-block:: llvm
+
+ def ops;
+ def GPR;
+ def Imm;
+ class inst<int opc, string asmstr, dag operandlist>;
+
+ class rrinst<int opc, string asmstr>
+ : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),
+ (ops GPR:$dst, GPR:$src1, GPR:$src2)>;
+
+ class riinst<int opc, string asmstr>
+ : inst<opc, !strconcat(asmstr, " $dst, $src1, $src2"),
+ (ops GPR:$dst, GPR:$src1, Imm:$src2)>;
+
+ // Instantiations of the ri_inst multiclass.
+ def ADD_rr : rrinst<0b111, "add">;
+ def ADD_ri : riinst<0b111, "add">;
+ def SUB_rr : rrinst<0b101, "sub">;
+ def SUB_ri : riinst<0b101, "sub">;
+ def MUL_rr : rrinst<0b100, "mul">;
+ def MUL_ri : riinst<0b100, "mul">;
+ ...
+
+A ``defm`` can also be used inside a multiclass providing several levels of
+multiclass instanciations.
+
+.. code-block:: llvm
+
+ class Instruction<bits<4> opc, string Name> {
+ bits<4> opcode = opc;
+ string name = Name;
+ }
+
+ multiclass basic_r<bits<4> opc> {
+ def rr : Instruction<opc, "rr">;
+ def rm : Instruction<opc, "rm">;
+ }
+
+ multiclass basic_s<bits<4> opc> {
+ defm SS : basic_r<opc>;
+ defm SD : basic_r<opc>;
+ def X : Instruction<opc, "x">;
+ }
+
+ multiclass basic_p<bits<4> opc> {
+ defm PS : basic_r<opc>;
+ defm PD : basic_r<opc>;
+ def Y : Instruction<opc, "y">;
+ }
+
+ defm ADD : basic_s<0xf>, basic_p<0xf>;
+ ...
+
+ // Results
+ def ADDPDrm { ...
+ def ADDPDrr { ...
+ def ADDPSrm { ...
+ def ADDPSrr { ...
+ def ADDSDrm { ...
+ def ADDSDrr { ...
+ def ADDY { ...
+ def ADDX { ...
+
+``defm`` declarations can inherit from classes too, the rule to follow is that
+the class list must start after the last multiclass, and there must be at least
+one multiclass before them.
+
+.. code-block:: llvm
+
+ class XD { bits<4> Prefix = 11; }
+ class XS { bits<4> Prefix = 12; }
+
+ class I<bits<4> op> {
+ bits<4> opcode = op;
+ }
+
+ multiclass R {
+ def rr : I<4>;
+ def rm : I<2>;
+ }
+
+ multiclass Y {
+ defm SS : R, XD;
+ defm SD : R, XS;
+ }
+
+ defm Instr : Y;
+
+ // Results
+ def InstrSDrm {
+ bits<4> opcode = { 0, 0, 1, 0 };
+ bits<4> Prefix = { 1, 1, 0, 0 };
+ }
+ ...
+ def InstrSSrr {
+ bits<4> opcode = { 0, 1, 0, 0 };
+ bits<4> Prefix = { 1, 0, 1, 1 };
+ }
+
+File scope entities
+-------------------
+
+File inclusion
+^^^^^^^^^^^^^^
+
+TableGen supports the '``include``' token, which textually substitutes the
+specified file in place of the include directive. The filename should be
+specified as a double quoted string immediately after the '``include``' keyword.
+Example:
+
+.. code-block:: llvm
+
+ include "foo.td"
+
+'let' expressions
+^^^^^^^^^^^^^^^^^
+
+"Let" expressions at file scope are similar to `"let" expressions within a
+record`_, except they can specify a value binding for multiple records at a
+time, and may be useful in certain other cases. File-scope let expressions are
+really just another way that TableGen allows the end-user to factor out
+commonality from the records.
+
+File-scope "let" expressions take a comma-separated list of bindings to apply,
+and one or more records to bind the values in. Here are some examples:
+
+.. code-block:: llvm
+
+ let isTerminator = 1, isReturn = 1, isBarrier = 1, hasCtrlDep = 1 in
+ def RET : I<0xC3, RawFrm, (outs), (ins), "ret", [(X86retflag 0)]>;
+
+ let isCall = 1 in
+ // All calls clobber the non-callee saved registers...
+ let Defs = [EAX, ECX, EDX, FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0,
+ MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7,
+ XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7, EFLAGS] in {
+ def CALLpcrel32 : Ii32<0xE8, RawFrm, (outs), (ins i32imm:$dst,variable_ops),
+ "call\t${dst:call}", []>;
+ def CALL32r : I<0xFF, MRM2r, (outs), (ins GR32:$dst, variable_ops),
+ "call\t{*}$dst", [(X86call GR32:$dst)]>;
+ def CALL32m : I<0xFF, MRM2m, (outs), (ins i32mem:$dst, variable_ops),
+ "call\t{*}$dst", []>;
+ }
+
+File-scope "let" expressions are often useful when a couple of definitions need
+to be added to several records, and the records do not otherwise need to be
+opened, as in the case with the ``CALL*`` instructions above.
+
+It's also possible to use "let" expressions inside multiclasses, providing more
+ways to factor out commonality from the records, specially if using several
+levels of multiclass instanciations. This also avoids the need of using "let"
+expressions within subsequent records inside a multiclass.
+
+.. code-block:: llvm
+
+ multiclass basic_r<bits<4> opc> {
+ let Predicates = [HasSSE2] in {
+ def rr : Instruction<opc, "rr">;
+ def rm : Instruction<opc, "rm">;
+ }
+ let Predicates = [HasSSE3] in
+ def rx : Instruction<opc, "rx">;
+ }
+
+ multiclass basic_ss<bits<4> opc> {
+ let IsDouble = 0 in
+ defm SS : basic_r<opc>;
+
+ let IsDouble = 1 in
+ defm SD : basic_r<opc>;
+ }
+
+ defm ADD : basic_ss<0xf>;
+
+Looping
+^^^^^^^
+
+TableGen supports the '``foreach``' block, which textually replicates the loop
+body, substituting iterator values for iterator references in the body.
+Example:
+
+.. code-block:: llvm
+
+ foreach i = [0, 1, 2, 3] in {
+ def R#i : Register<...>;
+ def F#i : Register<...>;
+ }
+
+This will create objects ``R0``, ``R1``, ``R2`` and ``R3``. ``foreach`` blocks
+may be nested. If there is only one item in the body the braces may be
+elided:
+
+.. code-block:: llvm
+
+ foreach i = [0, 1, 2, 3] in
+ def R#i : Register<...>;
+
+Code Generator backend info
+===========================
+
+Expressions used by code generator to describe instructions and isel patterns:
+
+``(implicit a)``
+ an implicitly defined physical register. This tells the dag instruction
+ selection emitter the input pattern's extra definitions matches implicit
+ physical register definitions.
+
+.. _TableGen backend:
+.. _TableGen backends:
+.. _write a backend:
+
+TableGen backends
+=================
+
+TODO: How they work, how to write one. This section should not contain details
+about any particular backend, except maybe ``-print-enums`` as an example. This
+should highlight the APIs in ``TableGen/Record.h``.
diff --git a/docs/TestSuiteMakefileGuide.html b/docs/TestSuiteMakefileGuide.html
new file mode 100644
index 00000000000..1b24250380f
--- /dev/null
+++ b/docs/TestSuiteMakefileGuide.html
@@ -0,0 +1,351 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>LLVM test-suite Makefile Guide</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>
+ LLVM test-suite Makefile Guide
+</h1>
+
+<ol>
+ <li><a href="#overview">Overview</a></li>
+ <li><a href="#testsuitestructure">Test suite structure</a></li>
+ <li><a href="#testsuiterun">Running the test suite</a>
+ <ul>
+ <li><a href="#testsuiteexternal">Configuring External Tests</a></li>
+ <li><a href="#testsuitetests">Running different tests</a></li>
+ <li><a href="#testsuiteoutput">Generating test output</a></li>
+ <li><a href="#testsuitecustom">Writing custom tests for test-suite</a></li>
+ </ul>
+ </li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by John T. Criswell, Daniel Dunbar, Reid Spencer, and Tanya Lattner</p>
+</div>
+
+<!--=========================================================================-->
+<h2><a name="overview">Overview</a></h2>
+<!--=========================================================================-->
+
+<div>
+
+<p>This document describes the features of the Makefile-based LLVM
+test-suite. This way of interacting with the test-suite is deprecated in favor
+of running the test-suite using LNT, but may continue to prove useful for some
+users. See the Testing
+Guide's <a href="TestingGuide.html#testsuitequickstart">test-suite
+Quickstart</a> section for more information.</p>
+
+</div>
+
+<!--=========================================================================-->
+<h2><a name="testsuitestructure">Test suite Structure</a></h2>
+<!--=========================================================================-->
+
+<div>
+
+<p>The <tt>test-suite</tt> module contains a number of programs that can be compiled
+with LLVM and executed. These programs are compiled using the native compiler
+and various LLVM backends. The output from the program compiled with the
+native compiler is assumed correct; the results from the other programs are
+compared to the native program output and pass if they match.</p>
+
+<p>When executing tests, it is usually a good idea to start out with a subset of
+the available tests or programs. This makes test run times smaller at first and
+later on this is useful to investigate individual test failures. To run some
+test only on a subset of programs, simply change directory to the programs you
+want tested and run <tt>gmake</tt> there. Alternatively, you can run a different
+test using the <tt>TEST</tt> variable to change what tests or run on the
+selected programs (see below for more info).</p>
+
+<p>In addition for testing correctness, the <tt>test-suite</tt> directory also
+performs timing tests of various LLVM optimizations. It also records
+compilation times for the compilers and the JIT. This information can be
+used to compare the effectiveness of LLVM's optimizations and code
+generation.</p>
+
+<p><tt>test-suite</tt> tests are divided into three types of tests: MultiSource,
+SingleSource, and External.</p>
+
+<ul>
+<li><tt>test-suite/SingleSource</tt>
+<p>The SingleSource directory contains test programs that are only a single
+source file in size. These are usually small benchmark programs or small
+programs that calculate a particular value. Several such programs are grouped
+together in each directory.</p></li>
+
+<li><tt>test-suite/MultiSource</tt>
+<p>The MultiSource directory contains subdirectories which contain entire
+programs with multiple source files. Large benchmarks and whole applications
+go here.</p></li>
+
+<li><tt>test-suite/External</tt>
+<p>The External directory contains Makefiles for building code that is external
+to (i.e., not distributed with) LLVM. The most prominent members of this
+directory are the SPEC 95 and SPEC 2000 benchmark suites. The <tt>External</tt>
+directory does not contain these actual tests, but only the Makefiles that know
+how to properly compile these programs from somewhere else. The presence and
+location of these external programs is configured by the test-suite
+<tt>configure</tt> script.</p></li>
+</ul>
+
+<p>Each tree is then subdivided into several categories, including applications,
+benchmarks, regression tests, code that is strange grammatically, etc. These
+organizations should be relatively self explanatory.</p>
+
+<p>Some tests are known to fail. Some are bugs that we have not fixed yet;
+others are features that we haven't added yet (or may never add). In the
+regression tests, the result for such tests will be XFAIL (eXpected FAILure).
+In this way, you can tell the difference between an expected and unexpected
+failure.</p>
+
+<p>The tests in the test suite have no such feature at this time. If the
+test passes, only warnings and other miscellaneous output will be generated. If
+a test fails, a large &lt;program&gt; FAILED message will be displayed. This
+will help you separate benign warnings from actual test failures.</p>
+
+</div>
+
+<!--=========================================================================-->
+<h2><a name="testsuiterun">Running the test suite</a></h2>
+<!--=========================================================================-->
+
+<div>
+
+<p>First, all tests are executed within the LLVM object directory tree. They
+<i>are not</i> executed inside of the LLVM source tree. This is because the
+test suite creates temporary files during execution.</p>
+
+<p>To run the test suite, you need to use the following steps:</p>
+
+<ol>
+ <li><tt>cd</tt> into the <tt>llvm/projects</tt> directory in your source tree.
+ </li>
+
+ <li><p>Check out the <tt>test-suite</tt> module with:</p>
+
+<div class="doc_code">
+<pre>
+% svn co http://llvm.org/svn/llvm-project/test-suite/trunk test-suite
+</pre>
+</div>
+ <p>This will get the test suite into <tt>llvm/projects/test-suite</tt>.</p>
+ </li>
+ <li><p>Configure and build <tt>llvm</tt>.</p></li>
+ <li><p>Configure and build <tt>llvm-gcc</tt>.</p></li>
+ <li><p>Install <tt>llvm-gcc</tt> somewhere.</p></li>
+ <li><p><em>Re-configure</em> <tt>llvm</tt> from the top level of
+ each build tree (LLVM object directory tree) in which you want
+ to run the test suite, just as you do before building LLVM.</p>
+ <p>During the <em>re-configuration</em>, you must either: (1)
+ have <tt>llvm-gcc</tt> you just built in your path, or (2)
+ specify the directory where your just-built <tt>llvm-gcc</tt> is
+ installed using <tt>--with-llvmgccdir=$LLVM_GCC_DIR</tt>.</p>
+ <p>You must also tell the configure machinery that the test suite
+ is available so it can be configured for your build tree:</p>
+<div class="doc_code">
+<pre>
+% cd $LLVM_OBJ_ROOT ; $LLVM_SRC_ROOT/configure [--with-llvmgccdir=$LLVM_GCC_DIR]
+</pre>
+</div>
+ <p>[Remember that <tt>$LLVM_GCC_DIR</tt> is the directory where you
+ <em>installed</em> llvm-gcc, not its src or obj directory.]</p>
+ </li>
+
+ <li><p>You can now run the test suite from your build tree as follows:</p>
+<div class="doc_code">
+<pre>
+% cd $LLVM_OBJ_ROOT/projects/test-suite
+% make
+</pre>
+</div>
+ </li>
+</ol>
+<p>Note that the second and third steps only need to be done once. After you
+have the suite checked out and configured, you don't need to do it again (unless
+the test code or configure script changes).</p>
+
+<!-- _______________________________________________________________________ -->
+<h3>
+ <a name="testsuiteexternal">Configuring External Tests</a>
+</h3>
+<!-- _______________________________________________________________________ -->
+
+<div>
+<p>In order to run the External tests in the <tt>test-suite</tt>
+ module, you must specify <i>--with-externals</i>. This
+ must be done during the <em>re-configuration</em> step (see above),
+ and the <tt>llvm</tt> re-configuration must recognize the
+ previously-built <tt>llvm-gcc</tt>. If any of these is missing or
+ neglected, the External tests won't work.</p>
+<dl>
+<dt><i>--with-externals</i></dt>
+<dt><i>--with-externals=&lt;<tt>directory</tt>&gt;</i></dt>
+</dl>
+ This tells LLVM where to find any external tests. They are expected to be
+ in specifically named subdirectories of &lt;<tt>directory</tt>&gt;.
+ If <tt>directory</tt> is left unspecified,
+ <tt>configure</tt> uses the default value
+ <tt>/home/vadve/shared/benchmarks/speccpu2000/benchspec</tt>.
+ Subdirectory names known to LLVM include:
+ <dl>
+ <dt>spec95</dt>
+ <dt>speccpu2000</dt>
+ <dt>speccpu2006</dt>
+ <dt>povray31</dt>
+ </dl>
+ Others are added from time to time, and can be determined from
+ <tt>configure</tt>.
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3>
+ <a name="testsuitetests">Running different tests</a>
+</h3>
+<!-- _______________________________________________________________________ -->
+<div>
+<p>In addition to the regular "whole program" tests, the <tt>test-suite</tt>
+module also provides a mechanism for compiling the programs in different ways.
+If the variable TEST is defined on the <tt>gmake</tt> command line, the test system will
+include a Makefile named <tt>TEST.&lt;value of TEST variable&gt;.Makefile</tt>.
+This Makefile can modify build rules to yield different results.</p>
+
+<p>For example, the LLVM nightly tester uses <tt>TEST.nightly.Makefile</tt> to
+create the nightly test reports. To run the nightly tests, run <tt>gmake
+TEST=nightly</tt>.</p>
+
+<p>There are several TEST Makefiles available in the tree. Some of them are
+designed for internal LLVM research and will not work outside of the LLVM
+research group. They may still be valuable, however, as a guide to writing your
+own TEST Makefile for any optimization or analysis passes that you develop with
+LLVM.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3>
+ <a name="testsuiteoutput">Generating test output</a>
+</h3>
+<!-- _______________________________________________________________________ -->
+<div>
+ <p>There are a number of ways to run the tests and generate output. The most
+ simple one is simply running <tt>gmake</tt> with no arguments. This will
+ compile and run all programs in the tree using a number of different methods
+ and compare results. Any failures are reported in the output, but are likely
+ drowned in the other output. Passes are not reported explicitly.</p>
+
+ <p>Somewhat better is running <tt>gmake TEST=sometest test</tt>, which runs
+ the specified test and usually adds per-program summaries to the output
+ (depending on which sometest you use). For example, the <tt>nightly</tt> test
+ explicitly outputs TEST-PASS or TEST-FAIL for every test after each program.
+ Though these lines are still drowned in the output, it's easy to grep the
+ output logs in the Output directories.</p>
+
+ <p>Even better are the <tt>report</tt> and <tt>report.format</tt> targets
+ (where <tt>format</tt> is one of <tt>html</tt>, <tt>csv</tt>, <tt>text</tt> or
+ <tt>graphs</tt>). The exact contents of the report are dependent on which
+ <tt>TEST</tt> you are running, but the text results are always shown at the
+ end of the run and the results are always stored in the
+ <tt>report.&lt;type&gt;.format</tt> file (when running with
+ <tt>TEST=&lt;type&gt;</tt>).
+
+ The <tt>report</tt> also generate a file called
+ <tt>report.&lt;type&gt;.raw.out</tt> containing the output of the entire test
+ run.
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3>
+ <a name="testsuitecustom">Writing custom tests for the test suite</a>
+</h3>
+<!-- _______________________________________________________________________ -->
+
+<div>
+
+<p>Assuming you can run the test suite, (e.g. "<tt>gmake TEST=nightly report</tt>"
+should work), it is really easy to run optimizations or code generator
+components against every program in the tree, collecting statistics or running
+custom checks for correctness. At base, this is how the nightly tester works,
+it's just one example of a general framework.</p>
+
+<p>Lets say that you have an LLVM optimization pass, and you want to see how
+many times it triggers. First thing you should do is add an LLVM
+<a href="ProgrammersManual.html#Statistic">statistic</a> to your pass, which
+will tally counts of things you care about.</p>
+
+<p>Following this, you can set up a test and a report that collects these and
+formats them for easy viewing. This consists of two files, a
+"<tt>test-suite/TEST.XXX.Makefile</tt>" fragment (where XXX is the name of your
+test) and a "<tt>test-suite/TEST.XXX.report</tt>" file that indicates how to
+format the output into a table. There are many example reports of various
+levels of sophistication included with the test suite, and the framework is very
+general.</p>
+
+<p>If you are interested in testing an optimization pass, check out the
+"libcalls" test as an example. It can be run like this:<p>
+
+<div class="doc_code">
+<pre>
+% cd llvm/projects/test-suite/MultiSource/Benchmarks # or some other level
+% make TEST=libcalls report
+</pre>
+</div>
+
+<p>This will do a bunch of stuff, then eventually print a table like this:</p>
+
+<div class="doc_code">
+<pre>
+Name | total | #exit |
+...
+FreeBench/analyzer/analyzer | 51 | 6 |
+FreeBench/fourinarow/fourinarow | 1 | 1 |
+FreeBench/neural/neural | 19 | 9 |
+FreeBench/pifft/pifft | 5 | 3 |
+MallocBench/cfrac/cfrac | 1 | * |
+MallocBench/espresso/espresso | 52 | 12 |
+MallocBench/gs/gs | 4 | * |
+Prolangs-C/TimberWolfMC/timberwolfmc | 302 | * |
+Prolangs-C/agrep/agrep | 33 | 12 |
+Prolangs-C/allroots/allroots | * | * |
+Prolangs-C/assembler/assembler | 47 | * |
+Prolangs-C/bison/mybison | 74 | * |
+...
+</pre>
+</div>
+
+<p>This basically is grepping the -stats output and displaying it in a table.
+You can also use the "TEST=libcalls report.html" target to get the table in HTML
+form, similarly for report.csv and report.tex.</p>
+
+<p>The source for this is in test-suite/TEST.libcalls.*. The format is pretty
+simple: the Makefile indicates how to run the test (in this case,
+"<tt>opt -simplify-libcalls -stats</tt>"), and the report contains one line for
+each column of the output. The first value is the header for the column and the
+second is the regex to grep the output of the command for. There are lots of
+example reports that can do fancy stuff.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ John T. Criswell, Daniel Dunbar, Reid Spencer, and Tanya Lattner<br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/TestingGuide.html b/docs/TestingGuide.html
new file mode 100644
index 00000000000..1f9c9157306
--- /dev/null
+++ b/docs/TestingGuide.html
@@ -0,0 +1,915 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>LLVM Testing Infrastructure Guide</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>
+ LLVM Testing Infrastructure Guide
+</h1>
+
+<ol>
+ <li><a href="#overview">Overview</a></li>
+ <li><a href="#requirements">Requirements</a></li>
+ <li><a href="#org">LLVM testing infrastructure organization</a>
+ <ul>
+ <li><a href="#regressiontests">Regression tests</a></li>
+ <li><a href="#testsuite"><tt>test-suite</tt></a></li>
+ <li><a href="#debuginfotests">Debugging Information tests</a></li>
+ </ul>
+ </li>
+ <li><a href="#quick">Quick start</a>
+ <ul>
+ <li><a href="#quickregressiontests">Regression tests</a></li>
+ <li><a href="#quickdebuginfotests">Debugging Information tests</a></li>
+ </ul>
+ </li>
+ <li><a href="#rtstructure">Regression test structure</a>
+ <ul>
+ <li><a href="#rtcustom">Writing new regression tests</a></li>
+ <li><a href="#FileCheck">The FileCheck utility</a></li>
+ <li><a href="#rtvars">Variables and substitutions</a></li>
+ <li><a href="#rtfeatures">Other features</a></li>
+ </ul>
+ </li>
+ <li><a href="#testsuiteoverview"><tt>test-suite</tt> Overview</a>
+ <ul>
+ <li><a href="#testsuitequickstart"><tt>test-suite</tt> Quickstart</a></li>
+ <li><a href="#testsuitemakefiles"><tt>test-suite</tt> Makefiles</a></li>
+ </ul>
+ </li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by John T. Criswell, Daniel Dunbar, Reid Spencer, and Tanya Lattner</p>
+</div>
+
+<!--=========================================================================-->
+<h2><a name="overview">Overview</a></h2>
+<!--=========================================================================-->
+
+<div>
+
+<p>This document is the reference manual for the LLVM testing infrastructure. It
+documents the structure of the LLVM testing infrastructure, the tools needed to
+use it, and how to add and run tests.</p>
+
+</div>
+
+<!--=========================================================================-->
+<h2><a name="requirements">Requirements</a></h2>
+<!--=========================================================================-->
+
+<div>
+
+<p>In order to use the LLVM testing infrastructure, you will need all of the
+software required to build LLVM, as well
+as <a href="http://python.org">Python</a> 2.4 or later.</p>
+
+</div>
+
+<!--=========================================================================-->
+<h2><a name="org">LLVM testing infrastructure organization</a></h2>
+<!--=========================================================================-->
+
+<div>
+
+<p>The LLVM testing infrastructure contains two major categories of tests:
+regression tests and whole programs. The regression tests are contained inside
+the LLVM repository itself under <tt>llvm/test</tt> and are expected to always
+pass -- they should be run before every commit.</p>
+
+<p>The whole programs tests are referred to as the "LLVM test suite" (or
+"test-suite") and are in the <tt>test-suite</tt> module in subversion. For
+historical reasons, these tests are also referred to as the "nightly tests" in
+places, which is less ambiguous than "test-suite" and remains in use although we
+run them much more often than nightly.</p>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="regressiontests">Regression tests</a></h3>
+<!-- _______________________________________________________________________ -->
+
+<div>
+
+<p>The regression tests are small pieces of code that test a specific feature of
+LLVM or trigger a specific bug in LLVM. They are usually written in LLVM
+assembly language, but can be written in other languages if the test targets a
+particular language front end (and the appropriate <tt>--with-llvmgcc</tt>
+options were used at <tt>configure</tt> time of the <tt>llvm</tt> module). These
+tests are driven by the 'lit' testing tool, which is part of LLVM.</p>
+
+<p>These code fragments are not complete programs. The code generated
+from them is never executed to determine correct behavior.</p>
+
+<p>These code fragment tests are located in the <tt>llvm/test</tt>
+directory.</p>
+
+<p>Typically when a bug is found in LLVM, a regression test containing
+just enough code to reproduce the problem should be written and placed
+somewhere underneath this directory. In most cases, this will be a small
+piece of LLVM assembly language code, often distilled from an actual
+application or benchmark.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="testsuite"><tt>test-suite</tt></a></h3>
+<!-- _______________________________________________________________________ -->
+
+<div>
+
+<p>The test suite contains whole programs, which are pieces of code which can be
+compiled and linked into a stand-alone program that can be executed. These
+programs are generally written in high level languages such as C or C++.</p>
+
+<p>These programs are compiled using a user specified compiler and set of flags,
+and then executed to capture the program output and timing information. The
+output of these programs is compared to a reference output to ensure that the
+program is being compiled correctly.</p>
+
+<p>In addition to compiling and executing programs, whole program tests serve as
+a way of benchmarking LLVM performance, both in terms of the efficiency of the
+programs generated as well as the speed with which LLVM compiles, optimizes, and
+generates code.</p>
+
+<p>The test-suite is located in the <tt>test-suite</tt> Subversion module.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="debuginfotests">Debugging Information tests</a></h3>
+<!-- _______________________________________________________________________ -->
+
+<div>
+
+<p>The test suite contains tests to check quality of debugging information.
+The test are written in C based languages or in LLVM assembly language. </p>
+
+<p>These tests are compiled and run under a debugger. The debugger output
+is checked to validate of debugging information. See README.txt in the
+test suite for more information . This test suite is located in the
+<tt>debuginfo-tests</tt> Subversion module. </p>
+
+</div>
+
+</div>
+
+<!--=========================================================================-->
+<h2><a name="quick">Quick start</a></h2>
+<!--=========================================================================-->
+
+<div>
+
+ <p>The tests are located in two separate Subversion modules. The regressions
+ tests are in the main "llvm" module under the directory
+ <tt>llvm/test</tt> (so you get these tests for free with the main llvm
+ tree). Use "make check-all" to run the regression tests after building
+ LLVM.</p>
+
+ <p>The more comprehensive test suite that includes whole programs in C and C++
+ is in the <tt>test-suite</tt>
+ module. See <a href="#testsuitequickstart"><tt>test-suite</tt> Quickstart</a>
+ for more information on running these tests.</p>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="quickregressiontests">Regression tests</a></h3>
+<div>
+<!-- _______________________________________________________________________ -->
+<p>To run all of the LLVM regression tests, use master Makefile in
+ the <tt>llvm/test</tt> directory:</p>
+
+<div class="doc_code">
+<pre>
+% gmake -C llvm/test
+</pre>
+</div>
+
+<p>or</p>
+
+<div class="doc_code">
+<pre>
+% gmake check
+</pre>
+</div>
+
+<p>If you have <a href="http://clang.llvm.org/">Clang</a> checked out and built,
+you can run the LLVM and Clang tests simultaneously using:</p>
+
+<p>or</p>
+
+<div class="doc_code">
+<pre>
+% gmake check-all
+</pre>
+</div>
+
+<p>To run the tests with Valgrind (Memcheck by default), just append
+<tt>VG=1</tt> to the commands above, e.g.:</p>
+
+<div class="doc_code">
+<pre>
+% gmake check VG=1
+</pre>
+</div>
+
+<p>To run individual tests or subsets of tests, you can use the 'llvm-lit'
+script which is built as part of LLVM. For example, to run the
+'Integer/BitCast.ll' test by itself you can run:</p>
+
+<div class="doc_code">
+<pre>
+% llvm-lit ~/llvm/test/Integer/BitCast.ll
+</pre>
+</div>
+
+<p>or to run all of the ARM CodeGen tests:</p>
+
+<div class="doc_code">
+<pre>
+% llvm-lit ~/llvm/test/CodeGen/ARM
+</pre>
+</div>
+
+<p>For more information on using the 'lit' tool, see 'llvm-lit --help' or the
+'lit' man page.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="quickdebuginfotests">Debugging Information tests</a></h3>
+<div>
+<!-- _______________________________________________________________________ -->
+<div>
+
+<p> To run debugging information tests simply checkout the tests inside
+clang/test directory. </p>
+
+<div class="doc_code">
+<pre>
+%cd clang/test
+% svn co http://llvm.org/svn/llvm-project/debuginfo-tests/trunk debuginfo-tests
+</pre>
+</div>
+
+<p> These tests are already set up to run as part of clang regression tests.</p>
+
+</div>
+
+</div>
+
+</div>
+
+<!--=========================================================================-->
+<h2><a name="rtstructure">Regression test structure</a></h2>
+<!--=========================================================================-->
+<div>
+ <p>The LLVM regression tests are driven by 'lit' and are located in
+ the <tt>llvm/test</tt> directory.
+
+ <p>This directory contains a large array of small tests
+ that exercise various features of LLVM and to ensure that regressions do not
+ occur. The directory is broken into several sub-directories, each focused on
+ a particular area of LLVM. A few of the important ones are:</p>
+
+ <ul>
+ <li><tt>Analysis</tt>: checks Analysis passes.</li>
+ <li><tt>Archive</tt>: checks the Archive library.</li>
+ <li><tt>Assembler</tt>: checks Assembly reader/writer functionality.</li>
+ <li><tt>Bitcode</tt>: checks Bitcode reader/writer functionality.</li>
+ <li><tt>CodeGen</tt>: checks code generation and each target.</li>
+ <li><tt>Features</tt>: checks various features of the LLVM language.</li>
+ <li><tt>Linker</tt>: tests bitcode linking.</li>
+ <li><tt>Transforms</tt>: tests each of the scalar, IPO, and utility
+ transforms to ensure they make the right transformations.</li>
+ <li><tt>Verifier</tt>: tests the IR verifier.</li>
+ </ul>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="rtcustom">Writing new regression tests</a></h3>
+<!-- _______________________________________________________________________ -->
+<div>
+ <p>The regression test structure is very simple, but does require some
+ information to be set. This information is gathered via <tt>configure</tt> and
+ is written to a file, <tt>lit.site.cfg</tt>
+ in <tt>llvm/test</tt>. The <tt>llvm/test</tt> Makefile does this work for
+ you.</p>
+
+ <p>In order for the regression tests to work, each directory of tests must
+ have a <tt>lit.local.cfg</tt> file. Lit looks for this file to determine how
+ to run the tests. This file is just Python code and thus is very flexible,
+ but we've standardized it for the LLVM regression tests. If you're adding a
+ directory of tests, just copy <tt>lit.local.cfg</tt> from another directory to
+ get running. The standard <tt>lit.local.cfg</tt> simply specifies which files
+ to look in for tests. Any directory that contains only directories does not
+ need the <tt>lit.local.cfg</tt> file. Read the
+ <a href="http://llvm.org/cmds/lit.html">Lit documentation</a> for more
+ information. </p>
+
+ <p>The <tt>llvm-runtests</tt> function looks at each file that is passed to
+ it and gathers any lines together that match "RUN:". These are the "RUN" lines
+ that specify how the test is to be run. So, each test script must contain
+ RUN lines if it is to do anything. If there are no RUN lines, the
+ <tt>llvm-runtests</tt> function will issue an error and the test will
+ fail.</p>
+
+ <p>RUN lines are specified in the comments of the test program using the
+ keyword <tt>RUN</tt> followed by a colon, and lastly the command (pipeline)
+ to execute. Together, these lines form the "script" that
+ <tt>llvm-runtests</tt> executes to run the test case. The syntax of the
+ RUN lines is similar to a shell's syntax for pipelines including I/O
+ redirection and variable substitution. However, even though these lines
+ may <i>look</i> like a shell script, they are not. RUN lines are interpreted
+ directly by the Tcl <tt>exec</tt> command. They are never executed by a
+ shell. Consequently the syntax differs from normal shell script syntax in a
+ few ways. You can specify as many RUN lines as needed.</p>
+
+ <p>lit performs substitution on each RUN line to replace LLVM tool
+ names with the full paths to the executable built for each tool (in
+ $(LLVM_OBJ_ROOT)/$(BuildMode)/bin). This ensures that lit does not
+ invoke any stray LLVM tools in the user's path during testing.</p>
+
+ <p>Each RUN line is executed on its own, distinct from other lines unless
+ its last character is <tt>\</tt>. This continuation character causes the RUN
+ line to be concatenated with the next one. In this way you can build up long
+ pipelines of commands without making huge line lengths. The lines ending in
+ <tt>\</tt> are concatenated until a RUN line that doesn't end in <tt>\</tt> is
+ found. This concatenated set of RUN lines then constitutes one execution.
+ Tcl will substitute variables and arrange for the pipeline to be executed. If
+ any process in the pipeline fails, the entire line (and test case) fails too.
+ </p>
+
+ <p> Below is an example of legal RUN lines in a <tt>.ll</tt> file:</p>
+
+<div class="doc_code">
+<pre>
+; RUN: llvm-as &lt; %s | llvm-dis &gt; %t1
+; RUN: llvm-dis &lt; %s.bc-13 &gt; %t2
+; RUN: diff %t1 %t2
+</pre>
+</div>
+
+ <p>As with a Unix shell, the RUN: lines permit pipelines and I/O redirection
+ to be used. However, the usage is slightly different than for Bash. To check
+ what's legal, see the documentation for the
+ <a href="http://www.tcl.tk/man/tcl8.5/TclCmd/exec.htm#M2">Tcl exec</a>
+ command and the
+ <a href="http://www.tcl.tk/man/tcl8.5/tutorial/Tcl26.html">tutorial</a>.
+ The major differences are:</p>
+ <ul>
+ <li>You can't do <tt>2&gt;&amp;1</tt>. That will cause Tcl to write to a
+ file named <tt>&amp;1</tt>. Usually this is done to get stderr to go through
+ a pipe. You can do that in tcl with <tt>|&amp;</tt> so replace this idiom:
+ <tt>... 2&gt;&amp;1 | grep</tt> with <tt>... |&amp; grep</tt></li>
+ <li>You can only redirect to a file, not to another descriptor and not from
+ a here document.</li>
+ <li>tcl supports redirecting to open files with the @ syntax but you
+ shouldn't use that here.</li>
+ </ul>
+
+ <p>There are some quoting rules that you must pay attention to when writing
+ your RUN lines. In general nothing needs to be quoted. Tcl won't strip off any
+ quote characters so they will get passed to the invoked program. For
+ example:</p>
+
+<div class="doc_code">
+<pre>
+... | grep 'find this string'
+</pre>
+</div>
+
+ <p>This will fail because the ' characters are passed to grep. This would
+ instruction grep to look for <tt>'find</tt> in the files <tt>this</tt> and
+ <tt>string'</tt>. To avoid this use curly braces to tell Tcl that it should
+ treat everything enclosed as one value. So our example would become:</p>
+
+<div class="doc_code">
+<pre>
+... | grep {find this string}
+</pre>
+</div>
+
+ <p>Additionally, the characters <tt>[</tt> and <tt>]</tt> are treated
+ specially by Tcl. They tell Tcl to interpret the content as a command to
+ execute. Since these characters are often used in regular expressions this can
+ have disastrous results and cause the entire test run in a directory to fail.
+ For example, a common idiom is to look for some basicblock number:</p>
+
+<div class="doc_code">
+<pre>
+... | grep bb[2-8]
+</pre>
+</div>
+
+ <p>This, however, will cause Tcl to fail because its going to try to execute
+ a program named "2-8". Instead, what you want is this:</p>
+
+<div class="doc_code">
+<pre>
+... | grep {bb\[2-8\]}
+</pre>
+</div>
+
+ <p>Finally, if you need to pass the <tt>\</tt> character down to a program,
+ then it must be doubled. This is another Tcl special character. So, suppose
+ you had:
+
+<div class="doc_code">
+<pre>
+... | grep 'i32\*'
+</pre>
+</div>
+
+ <p>This will fail to match what you want (a pointer to i32). First, the
+ <tt>'</tt> do not get stripped off. Second, the <tt>\</tt> gets stripped off
+ by Tcl so what grep sees is: <tt>'i32*'</tt>. That's not likely to match
+ anything. To resolve this you must use <tt>\\</tt> and the <tt>{}</tt>, like
+ this:</p>
+
+<div class="doc_code">
+<pre>
+... | grep {i32\\*}
+</pre>
+</div>
+
+<p>If your system includes GNU <tt>grep</tt>, make sure
+that <tt>GREP_OPTIONS</tt> is not set in your environment. Otherwise,
+you may get invalid results (both false positives and false
+negatives).</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="FileCheck">The FileCheck utility</a></h3>
+<!-- _______________________________________________________________________ -->
+
+<div>
+
+<p>A powerful feature of the RUN: lines is that it allows any arbitrary commands
+ to be executed as part of the test harness. While standard (portable) unix
+ tools like 'grep' work fine on run lines, as you see above, there are a lot
+ of caveats due to interaction with Tcl syntax, and we want to make sure the
+ run lines are portable to a wide range of systems. Another major problem is
+ that grep is not very good at checking to verify that the output of a tools
+ contains a series of different output in a specific order. The FileCheck
+ tool was designed to help with these problems.</p>
+
+<p>FileCheck (whose basic command line arguments are described in <a
+ href="http://llvm.org/cmds/FileCheck.html">the FileCheck man page</a> is
+ designed to read a file to check from standard input, and the set of things
+ to verify from a file specified as a command line argument. A simple example
+ of using FileCheck from a RUN line looks like this:</p>
+
+<div class="doc_code">
+<pre>
+; RUN: llvm-as &lt; %s | llc -march=x86-64 | <b>FileCheck %s</b>
+</pre>
+</div>
+
+<p>This syntax says to pipe the current file ("%s") into llvm-as, pipe that into
+llc, then pipe the output of llc into FileCheck. This means that FileCheck will
+be verifying its standard input (the llc output) against the filename argument
+specified (the original .ll file specified by "%s"). To see how this works,
+let's look at the rest of the .ll file (after the RUN line):</p>
+
+<div class="doc_code">
+<pre>
+define void @sub1(i32* %p, i32 %v) {
+entry:
+; <b>CHECK: sub1:</b>
+; <b>CHECK: subl</b>
+ %0 = tail call i32 @llvm.atomic.load.sub.i32.p0i32(i32* %p, i32 %v)
+ ret void
+}
+
+define void @inc4(i64* %p) {
+entry:
+; <b>CHECK: inc4:</b>
+; <b>CHECK: incq</b>
+ %0 = tail call i64 @llvm.atomic.load.add.i64.p0i64(i64* %p, i64 1)
+ ret void
+}
+</pre>
+</div>
+
+<p>Here you can see some "CHECK:" lines specified in comments. Now you can see
+how the file is piped into llvm-as, then llc, and the machine code output is
+what we are verifying. FileCheck checks the machine code output to verify that
+it matches what the "CHECK:" lines specify.</p>
+
+<p>The syntax of the CHECK: lines is very simple: they are fixed strings that
+must occur in order. FileCheck defaults to ignoring horizontal whitespace
+differences (e.g. a space is allowed to match a tab) but otherwise, the contents
+of the CHECK: line is required to match some thing in the test file exactly.</p>
+
+<p>One nice thing about FileCheck (compared to grep) is that it allows merging
+test cases together into logical groups. For example, because the test above
+is checking for the "sub1:" and "inc4:" labels, it will not match unless there
+is a "subl" in between those labels. If it existed somewhere else in the file,
+that would not count: "grep subl" matches if subl exists anywhere in the
+file.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="FileCheck-check-prefix">The FileCheck -check-prefix option</a>
+</h4>
+
+<div>
+
+<p>The FileCheck -check-prefix option allows multiple test configurations to be
+driven from one .ll file. This is useful in many circumstances, for example,
+testing different architectural variants with llc. Here's a simple example:</p>
+
+<div class="doc_code">
+<pre>
+; RUN: llvm-as &lt; %s | llc -mtriple=i686-apple-darwin9 -mattr=sse41 \
+; RUN: | <b>FileCheck %s -check-prefix=X32</b>
+; RUN: llvm-as &lt; %s | llc -mtriple=x86_64-apple-darwin9 -mattr=sse41 \
+; RUN: | <b>FileCheck %s -check-prefix=X64</b>
+
+define &lt;4 x i32&gt; @pinsrd_1(i32 %s, &lt;4 x i32&gt; %tmp) nounwind {
+ %tmp1 = insertelement &lt;4 x i32&gt; %tmp, i32 %s, i32 1
+ ret &lt;4 x i32&gt; %tmp1
+; <b>X32:</b> pinsrd_1:
+; <b>X32:</b> pinsrd $1, 4(%esp), %xmm0
+
+; <b>X64:</b> pinsrd_1:
+; <b>X64:</b> pinsrd $1, %edi, %xmm0
+}
+</pre>
+</div>
+
+<p>In this case, we're testing that we get the expected code generation with
+both 32-bit and 64-bit code generation.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="FileCheck-CHECK-NEXT">The "CHECK-NEXT:" directive</a>
+</h4>
+
+<div>
+
+<p>Sometimes you want to match lines and would like to verify that matches
+happen on exactly consecutive lines with no other lines in between them. In
+this case, you can use CHECK: and CHECK-NEXT: directives to specify this. If
+you specified a custom check prefix, just use "&lt;PREFIX&gt;-NEXT:". For
+example, something like this works as you'd expect:</p>
+
+<div class="doc_code">
+<pre>
+define void @t2(&lt;2 x double&gt;* %r, &lt;2 x double&gt;* %A, double %B) {
+ %tmp3 = load &lt;2 x double&gt;* %A, align 16
+ %tmp7 = insertelement &lt;2 x double&gt; undef, double %B, i32 0
+ %tmp9 = shufflevector &lt;2 x double&gt; %tmp3,
+ &lt;2 x double&gt; %tmp7,
+ &lt;2 x i32&gt; &lt; i32 0, i32 2 &gt;
+ store &lt;2 x double&gt; %tmp9, &lt;2 x double&gt;* %r, align 16
+ ret void
+
+; <b>CHECK:</b> t2:
+; <b>CHECK:</b> movl 8(%esp), %eax
+; <b>CHECK-NEXT:</b> movapd (%eax), %xmm0
+; <b>CHECK-NEXT:</b> movhpd 12(%esp), %xmm0
+; <b>CHECK-NEXT:</b> movl 4(%esp), %eax
+; <b>CHECK-NEXT:</b> movapd %xmm0, (%eax)
+; <b>CHECK-NEXT:</b> ret
+}
+</pre>
+</div>
+
+<p>CHECK-NEXT: directives reject the input unless there is exactly one newline
+between it an the previous directive. A CHECK-NEXT cannot be the first
+directive in a file.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="FileCheck-CHECK-NOT">The "CHECK-NOT:" directive</a>
+</h4>
+
+<div>
+
+<p>The CHECK-NOT: directive is used to verify that a string doesn't occur
+between two matches (or the first match and the beginning of the file). For
+example, to verify that a load is removed by a transformation, a test like this
+can be used:</p>
+
+<div class="doc_code">
+<pre>
+define i8 @coerce_offset0(i32 %V, i32* %P) {
+ store i32 %V, i32* %P
+
+ %P2 = bitcast i32* %P to i8*
+ %P3 = getelementptr i8* %P2, i32 2
+
+ %A = load i8* %P3
+ ret i8 %A
+; <b>CHECK:</b> @coerce_offset0
+; <b>CHECK-NOT:</b> load
+; <b>CHECK:</b> ret i8
+}
+</pre>
+</div>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="FileCheck-Matching">FileCheck Pattern Matching Syntax</a>
+</h4>
+
+<div>
+
+<!-- {% raw %} -->
+
+<p>The CHECK: and CHECK-NOT: directives both take a pattern to match. For most
+uses of FileCheck, fixed string matching is perfectly sufficient. For some
+things, a more flexible form of matching is desired. To support this, FileCheck
+allows you to specify regular expressions in matching strings, surrounded by
+double braces: <b>{{yourregex}}</b>. Because we want to use fixed string
+matching for a majority of what we do, FileCheck has been designed to support
+mixing and matching fixed string matching with regular expressions. This allows
+you to write things like this:</p>
+
+<div class="doc_code">
+<pre>
+; CHECK: movhpd <b>{{[0-9]+}}</b>(%esp), <b>{{%xmm[0-7]}}</b>
+</pre>
+</div>
+
+<p>In this case, any offset from the ESP register will be allowed, and any xmm
+register will be allowed.</p>
+
+<p>Because regular expressions are enclosed with double braces, they are
+visually distinct, and you don't need to use escape characters within the double
+braces like you would in C. In the rare case that you want to match double
+braces explicitly from the input, you can use something ugly like
+<b>{{[{][{]}}</b> as your pattern.</p>
+
+<!-- {% endraw %} -->
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="FileCheck-Variables">FileCheck Variables</a>
+</h4>
+
+<div>
+
+
+<!-- {% raw %} -->
+
+<p>It is often useful to match a pattern and then verify that it occurs again
+later in the file. For codegen tests, this can be useful to allow any register,
+but verify that that register is used consistently later. To do this, FileCheck
+allows named variables to be defined and substituted into patterns. Here is a
+simple example:</p>
+
+<div class="doc_code">
+<pre>
+; CHECK: test5:
+; CHECK: notw <b>[[REGISTER:%[a-z]+]]</b>
+; CHECK: andw {{.*}}<b>[[REGISTER]]</b>
+</pre>
+</div>
+
+<p>The first check line matches a regex (<tt>%[a-z]+</tt>) and captures it into
+the variables "REGISTER". The second line verifies that whatever is in REGISTER
+occurs later in the file after an "andw". FileCheck variable references are
+always contained in <tt>[[ ]]</tt> pairs, are named, and their names can be
+formed with the regex "<tt>[a-zA-Z][a-zA-Z0-9]*</tt>". If a colon follows the
+name, then it is a definition of the variable, if not, it is a use.</p>
+
+<p>FileCheck variables can be defined multiple times, and uses always get the
+latest value. Note that variables are all read at the start of a "CHECK" line
+and are all defined at the end. This means that if you have something like
+"<tt>CHECK: [[XYZ:.*]]x[[XYZ]]</tt>" that the check line will read the previous
+value of the XYZ variable and define a new one after the match is performed. If
+you need to do something like this you can probably take advantage of the fact
+that FileCheck is not actually line-oriented when it matches, this allows you to
+define two separate CHECK lines that match on the same line.
+</p>
+
+<!-- {% endraw %} -->
+
+</div>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="rtvars">Variables and substitutions</a></h3>
+<!-- _______________________________________________________________________ -->
+<div>
+ <p>With a RUN line there are a number of substitutions that are permitted. In
+ general, any Tcl variable that is available in the <tt>substitute</tt>
+ function (in <tt>test/lib/llvm.exp</tt>) can be substituted into a RUN line.
+ To make a substitution just write the variable's name preceded by a $.
+ Additionally, for compatibility reasons with previous versions of the test
+ library, certain names can be accessed with an alternate syntax: a % prefix.
+ These alternates are deprecated and may go away in a future version.
+ </p>
+ <p>Here are the available variable names. The alternate syntax is listed in
+ parentheses.</p>
+
+ <dl style="margin-left: 25px">
+ <dt><b>$test</b> (%s)</dt>
+ <dd>The full path to the test case's source. This is suitable for passing
+ on the command line as the input to an llvm tool.</dd>
+
+ <dt><b>$srcdir</b></dt>
+ <dd>The source directory from where the "<tt>make check</tt>" was run.</dd>
+
+ <dt><b>objdir</b></dt>
+ <dd>The object directory that corresponds to the <tt>$srcdir</tt>.</dd>
+
+ <dt><b>subdir</b></dt>
+ <dd>A partial path from the <tt>test</tt> directory that contains the
+ sub-directory that contains the test source being executed.</dd>
+
+ <dt><b>srcroot</b></dt>
+ <dd>The root directory of the LLVM src tree.</dd>
+
+ <dt><b>objroot</b></dt>
+ <dd>The root directory of the LLVM object tree. This could be the same
+ as the srcroot.</dd>
+
+ <dt><b>path</b><dt>
+ <dd>The path to the directory that contains the test case source. This is
+ for locating any supporting files that are not generated by the test, but
+ used by the test.</dd>
+
+ <dt><b>tmp</b></dt>
+ <dd>The path to a temporary file name that could be used for this test case.
+ The file name won't conflict with other test cases. You can append to it if
+ you need multiple temporaries. This is useful as the destination of some
+ redirected output.</dd>
+
+ <dt><b>target_triplet</b> (%target_triplet)</dt>
+ <dd>The target triplet that corresponds to the current host machine (the one
+ running the test cases). This should probably be called "host".<dd>
+
+ <dt><b>link</b> (%link)</dt>
+ <dd>This full link command used to link LLVM executables. This has all the
+ configured -I, -L and -l options.</dd>
+
+ <dt><b>shlibext</b> (%shlibext)</dt>
+ <dd>The suffix for the host platforms share library (dll) files. This
+ includes the period as the first character.</dd>
+ </dl>
+ <p>To add more variables, two things need to be changed. First, add a line in
+ the <tt>test/Makefile</tt> that creates the <tt>site.exp</tt> file. This will
+ "set" the variable as a global in the site.exp file. Second, in the
+ <tt>test/lib/llvm.exp</tt> file, in the substitute proc, add the variable name
+ to the list of "global" declarations at the beginning of the proc. That's it,
+ the variable can then be used in test scripts.</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h3><a name="rtfeatures">Other Features</a></h3>
+<!-- _______________________________________________________________________ -->
+<div>
+ <p>To make RUN line writing easier, there are several shell scripts located
+ in the <tt>llvm/test/Scripts</tt> directory. This directory is in the PATH
+ when running tests, so you can just call these scripts using their name. For
+ example:</p>
+ <dl>
+ <dt><b>ignore</b></dt>
+ <dd>This script runs its arguments and then always returns 0. This is useful
+ in cases where the test needs to cause a tool to generate an error (e.g. to
+ check the error output). However, any program in a pipeline that returns a
+ non-zero result will cause the test to fail. This script overcomes that
+ issue and nicely documents that the test case is purposefully ignoring the
+ result code of the tool</dd>
+
+ <dt><b>not</b></dt>
+ <dd>This script runs its arguments and then inverts the result code from
+ it. Zero result codes become 1. Non-zero result codes become 0. This is
+ useful to invert the result of a grep. For example "not grep X" means
+ succeed only if you don't find X in the input.</dd>
+ </dl>
+
+ <p>Sometimes it is necessary to mark a test case as "expected fail" or XFAIL.
+ You can easily mark a test as XFAIL just by including <tt>XFAIL: </tt> on a
+ line near the top of the file. This signals that the test case should succeed
+ if the test fails. Such test cases are counted separately by the testing tool. To
+ specify an expected fail, use the XFAIL keyword in the comments of the test
+ program followed by a colon and one or more regular expressions (separated by
+ a comma). The regular expressions allow you to XFAIL the test conditionally by
+ host platform. The regular expressions following the : are matched against the
+ target triplet for the host machine. If there is a match, the test is expected
+ to fail. If not, the test is expected to succeed. To XFAIL everywhere just
+ specify <tt>XFAIL: *</tt>. Here is an example of an <tt>XFAIL</tt> line:</p>
+
+<div class="doc_code">
+<pre>
+; XFAIL: darwin,sun
+</pre>
+</div>
+
+ <p>To make the output more useful, the <tt>llvm_runtest</tt> function wil
+ scan the lines of the test case for ones that contain a pattern that matches
+ PR[0-9]+. This is the syntax for specifying a PR (Problem Report) number that
+ is related to the test case. The number after "PR" specifies the LLVM bugzilla
+ number. When a PR number is specified, it will be used in the pass/fail
+ reporting. This is useful to quickly get some context when a test fails.</p>
+
+ <p>Finally, any line that contains "END." will cause the special
+ interpretation of lines to terminate. This is generally done right after the
+ last RUN: line. This has two side effects: (a) it prevents special
+ interpretation of lines that are part of the test program, not the
+ instructions to the test case, and (b) it speeds things up for really big test
+ cases by avoiding interpretation of the remainder of the file.</p>
+
+</div>
+
+</div>
+
+<!--=========================================================================-->
+<h2><a name="testsuiteoverview"><tt>test-suite</tt> Overview</a></h2>
+<!--=========================================================================-->
+
+<div>
+
+<p>The <tt>test-suite</tt> module contains a number of programs that can be
+compiled and executed. The <tt>test-suite</tt> includes reference outputs for
+all of the programs, so that the output of the executed program can be checked
+for correctness.</p>
+
+<p><tt>test-suite</tt> tests are divided into three types of tests: MultiSource,
+SingleSource, and External.</p>
+
+<ul>
+<li><tt>test-suite/SingleSource</tt>
+<p>The SingleSource directory contains test programs that are only a single
+source file in size. These are usually small benchmark programs or small
+programs that calculate a particular value. Several such programs are grouped
+together in each directory.</p></li>
+
+<li><tt>test-suite/MultiSource</tt>
+<p>The MultiSource directory contains subdirectories which contain entire
+programs with multiple source files. Large benchmarks and whole applications
+go here.</p></li>
+
+<li><tt>test-suite/External</tt>
+<p>The External directory contains Makefiles for building code that is external
+to (i.e., not distributed with) LLVM. The most prominent members of this
+directory are the SPEC 95 and SPEC 2000 benchmark suites. The <tt>External</tt>
+directory does not contain these actual tests, but only the Makefiles that know
+how to properly compile these programs from somewhere else. When
+using <tt>LNT</tt>, use the <tt>--test-externals</tt> option to include these
+tests in the results.</p></li>
+</ul>
+</div>
+
+<!--=========================================================================-->
+<h2><a name="testsuitequickstart"><tt>test-suite</tt> Quickstart</a></h2>
+<!--=========================================================================-->
+
+<div>
+<p>The modern way of running the <tt>test-suite</tt> is focused on testing and
+benchmarking complete compilers using
+the <a href="http://llvm.org/docs/lnt">LNT</a> testing infrastructure.</p>
+
+<p>For more information on using LNT to execute the <tt>test-suite</tt>, please
+see the <a href="http://llvm.org/docs/lnt/quickstart.html">LNT Quickstart</a>
+documentation.</p>
+</div>
+
+<!--=========================================================================-->
+<h2><a name="testsuitemakefiles"><tt>test-suite</tt> Makefiles</a></h2>
+<!--=========================================================================-->
+
+<div>
+<p>Historically, the <tt>test-suite</tt> was executed using a complicated setup
+of Makefiles. The LNT based approach above is recommended for most users, but
+there are some testing scenarios which are not supported by the LNT approach. In
+addition, LNT currently uses the Makefile setup under the covers and so
+developers who are interested in how LNT works under the hood may want to
+understand the Makefile based setup.</p>
+
+<p>For more information on the <tt>test-suite</tt> Makefile setup, please see
+the <a href="TestSuiteMakefileGuide.html">Test Suite Makefile Guide.</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ John T. Criswell, Daniel Dunbar, Reid Spencer, and Tanya Lattner<br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/WritingAnLLVMBackend.html b/docs/WritingAnLLVMBackend.html
new file mode 100644
index 00000000000..441d122f539
--- /dev/null
+++ b/docs/WritingAnLLVMBackend.html
@@ -0,0 +1,2533 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Writing an LLVM Compiler Backend</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>
+ Writing an LLVM Compiler Backend
+</h1>
+
+<ol>
+ <li><a href="#intro">Introduction</a>
+ <ul>
+ <li><a href="#Audience">Audience</a></li>
+ <li><a href="#Prerequisite">Prerequisite Reading</a></li>
+ <li><a href="#Basic">Basic Steps</a></li>
+ <li><a href="#Preliminaries">Preliminaries</a></li>
+ </ul>
+ <li><a href="#TargetMachine">Target Machine</a></li>
+ <li><a href="#TargetRegistration">Target Registration</a></li>
+ <li><a href="#RegisterSet">Register Set and Register Classes</a>
+ <ul>
+ <li><a href="#RegisterDef">Defining a Register</a></li>
+ <li><a href="#RegisterClassDef">Defining a Register Class</a></li>
+ <li><a href="#implementRegister">Implement a subclass of TargetRegisterInfo</a></li>
+ </ul></li>
+ <li><a href="#InstructionSet">Instruction Set</a>
+ <ul>
+ <li><a href="#operandMapping">Instruction Operand Mapping</a></li>
+ <li><a href="#implementInstr">Implement a subclass of TargetInstrInfo</a></li>
+ <li><a href="#branchFolding">Branch Folding and If Conversion</a></li>
+ </ul></li>
+ <li><a href="#InstructionSelector">Instruction Selector</a>
+ <ul>
+ <li><a href="#LegalizePhase">The SelectionDAG Legalize Phase</a>
+ <ul>
+ <li><a href="#promote">Promote</a></li>
+ <li><a href="#expand">Expand</a></li>
+ <li><a href="#custom">Custom</a></li>
+ <li><a href="#legal">Legal</a></li>
+ </ul></li>
+ <li><a href="#callingConventions">Calling Conventions</a></li>
+ </ul></li>
+ <li><a href="#assemblyPrinter">Assembly Printer</a></li>
+ <li><a href="#subtargetSupport">Subtarget Support</a></li>
+ <li><a href="#jitSupport">JIT Support</a>
+ <ul>
+ <li><a href="#mce">Machine Code Emitter</a></li>
+ <li><a href="#targetJITInfo">Target JIT Info</a></li>
+ </ul></li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by <a href="http://www.woo.com">Mason Woo</a> and
+ <a href="http://misha.brukman.net">Misha Brukman</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="intro">Introduction</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+This document describes techniques for writing compiler backends that convert
+the LLVM Intermediate Representation (IR) to code for a specified machine or
+other languages. Code intended for a specific machine can take the form of
+either assembly code or binary code (usable for a JIT compiler).
+</p>
+
+<p>
+The backend of LLVM features a target-independent code generator that may create
+output for several types of target CPUs &mdash; including X86, PowerPC, ARM,
+and SPARC. The backend may also be used to generate code targeted at SPUs of the
+Cell processor or GPUs to support the execution of compute kernels.
+</p>
+
+<p>
+The document focuses on existing examples found in subdirectories
+of <tt>llvm/lib/Target</tt> in a downloaded LLVM release. In particular, this
+document focuses on the example of creating a static compiler (one that emits
+text assembly) for a SPARC target, because SPARC has fairly standard
+characteristics, such as a RISC instruction set and straightforward calling
+conventions.
+</p>
+
+<h3>
+ <a name="Audience">Audience</a>
+</h3>
+
+<div>
+
+<p>
+The audience for this document is anyone who needs to write an LLVM backend to
+generate code for a specific hardware or software target.
+</p>
+
+</div>
+
+<h3>
+ <a name="Prerequisite">Prerequisite Reading</a>
+</h3>
+
+<div>
+
+<p>
+These essential documents must be read before reading this document:
+</p>
+
+<ul>
+<li><i><a href="LangRef.html">LLVM Language Reference
+ Manual</a></i> &mdash; a reference manual for the LLVM assembly language.</li>
+
+<li><i><a href="CodeGenerator.html">The LLVM
+ Target-Independent Code Generator</a></i> &mdash; a guide to the components
+ (classes and code generation algorithms) for translating the LLVM internal
+ representation into machine code for a specified target. Pay particular
+ attention to the descriptions of code generation stages: Instruction
+ Selection, Scheduling and Formation, SSA-based Optimization, Register
+ Allocation, Prolog/Epilog Code Insertion, Late Machine Code Optimizations,
+ and Code Emission.</li>
+
+<li><i><a href="TableGenFundamentals.html">TableGen
+ Fundamentals</a></i> &mdash;a document that describes the TableGen
+ (<tt>tblgen</tt>) application that manages domain-specific information to
+ support LLVM code generation. TableGen processes input from a target
+ description file (<tt>.td</tt> suffix) and generates C++ code that can be
+ used for code generation.</li>
+
+<li><i><a href="WritingAnLLVMPass.html">Writing an LLVM
+ Pass</a></i> &mdash; The assembly printer is a <tt>FunctionPass</tt>, as are
+ several SelectionDAG processing steps.</li>
+</ul>
+
+<p>
+To follow the SPARC examples in this document, have a copy of
+<i><a href="http://www.sparc.org/standards/V8.pdf">The SPARC Architecture
+Manual, Version 8</a></i> for reference. For details about the ARM instruction
+set, refer to the <i><a href="http://infocenter.arm.com/">ARM Architecture
+Reference Manual</a></i>. For more about the GNU Assembler format
+(<tt>GAS</tt>), see
+<i><a href="http://sourceware.org/binutils/docs/as/index.html">Using As</a></i>,
+especially for the assembly printer. <i>Using As</i> contains a list of target
+machine dependent features.
+</p>
+
+</div>
+
+<h3>
+ <a name="Basic">Basic Steps</a>
+</h3>
+
+<div>
+
+<p>
+To write a compiler backend for LLVM that converts the LLVM IR to code for a
+specified target (machine or other language), follow these steps:
+</p>
+
+<ul>
+<li>Create a subclass of the TargetMachine class that describes characteristics
+ of your target machine. Copy existing examples of specific TargetMachine
+ class and header files; for example, start with
+ <tt>SparcTargetMachine.cpp</tt> and <tt>SparcTargetMachine.h</tt>, but
+ change the file names for your target. Similarly, change code that
+ references "Sparc" to reference your target. </li>
+
+<li>Describe the register set of the target. Use TableGen to generate code for
+ register definition, register aliases, and register classes from a
+ target-specific <tt>RegisterInfo.td</tt> input file. You should also write
+ additional code for a subclass of the TargetRegisterInfo class that
+ represents the class register file data used for register allocation and
+ also describes the interactions between registers.</li>
+
+<li>Describe the instruction set of the target. Use TableGen to generate code
+ for target-specific instructions from target-specific versions of
+ <tt>TargetInstrFormats.td</tt> and <tt>TargetInstrInfo.td</tt>. You should
+ write additional code for a subclass of the TargetInstrInfo class to
+ represent machine instructions supported by the target machine. </li>
+
+<li>Describe the selection and conversion of the LLVM IR from a Directed Acyclic
+ Graph (DAG) representation of instructions to native target-specific
+ instructions. Use TableGen to generate code that matches patterns and
+ selects instructions based on additional information in a target-specific
+ version of <tt>TargetInstrInfo.td</tt>. Write code
+ for <tt>XXXISelDAGToDAG.cpp</tt>, where XXX identifies the specific target,
+ to perform pattern matching and DAG-to-DAG instruction selection. Also write
+ code in <tt>XXXISelLowering.cpp</tt> to replace or remove operations and
+ data types that are not supported natively in a SelectionDAG. </li>
+
+<li>Write code for an assembly printer that converts LLVM IR to a GAS format for
+ your target machine. You should add assembly strings to the instructions
+ defined in your target-specific version of <tt>TargetInstrInfo.td</tt>. You
+ should also write code for a subclass of AsmPrinter that performs the
+ LLVM-to-assembly conversion and a trivial subclass of TargetAsmInfo.</li>
+
+<li>Optionally, add support for subtargets (i.e., variants with different
+ capabilities). You should also write code for a subclass of the
+ TargetSubtarget class, which allows you to use the <tt>-mcpu=</tt>
+ and <tt>-mattr=</tt> command-line options.</li>
+
+<li>Optionally, add JIT support and create a machine code emitter (subclass of
+ TargetJITInfo) that is used to emit binary code directly into memory. </li>
+</ul>
+
+<p>
+In the <tt>.cpp</tt> and <tt>.h</tt>. files, initially stub up these methods and
+then implement them later. Initially, you may not know which private members
+that the class will need and which components will need to be subclassed.
+</p>
+
+</div>
+
+<h3>
+ <a name="Preliminaries">Preliminaries</a>
+</h3>
+
+<div>
+
+<p>
+To actually create your compiler backend, you need to create and modify a few
+files. The absolute minimum is discussed here. But to actually use the LLVM
+target-independent code generator, you must perform the steps described in
+the <a href="CodeGenerator.html">LLVM
+Target-Independent Code Generator</a> document.
+</p>
+
+<p>
+First, you should create a subdirectory under <tt>lib/Target</tt> to hold all
+the files related to your target. If your target is called "Dummy," create the
+directory <tt>lib/Target/Dummy</tt>.
+</p>
+
+<p>
+In this new
+directory, create a <tt>Makefile</tt>. It is easiest to copy a
+<tt>Makefile</tt> of another target and modify it. It should at least contain
+the <tt>LEVEL</tt>, <tt>LIBRARYNAME</tt> and <tt>TARGET</tt> variables, and then
+include <tt>$(LEVEL)/Makefile.common</tt>. The library can be
+named <tt>LLVMDummy</tt> (for example, see the MIPS target). Alternatively, you
+can split the library into <tt>LLVMDummyCodeGen</tt>
+and <tt>LLVMDummyAsmPrinter</tt>, the latter of which should be implemented in a
+subdirectory below <tt>lib/Target/Dummy</tt> (for example, see the PowerPC
+target).
+</p>
+
+<p>
+Note that these two naming schemes are hardcoded into <tt>llvm-config</tt>.
+Using any other naming scheme will confuse <tt>llvm-config</tt> and produce a
+lot of (seemingly unrelated) linker errors when linking <tt>llc</tt>.
+</p>
+
+<p>
+To make your target actually do something, you need to implement a subclass of
+<tt>TargetMachine</tt>. This implementation should typically be in the file
+<tt>lib/Target/DummyTargetMachine.cpp</tt>, but any file in
+the <tt>lib/Target</tt> directory will be built and should work. To use LLVM's
+target independent code generator, you should do what all current machine
+backends do: create a subclass of <tt>LLVMTargetMachine</tt>. (To create a
+target from scratch, create a subclass of <tt>TargetMachine</tt>.)
+</p>
+
+<p>
+To get LLVM to actually build and link your target, you need to add it to
+the <tt>TARGETS_TO_BUILD</tt> variable. To do this, you modify the configure
+script to know about your target when parsing the <tt>--enable-targets</tt>
+option. Search the configure script for <tt>TARGETS_TO_BUILD</tt>, add your
+target to the lists there (some creativity required), and then
+reconfigure. Alternatively, you can change <tt>autotools/configure.ac</tt> and
+regenerate configure by running <tt>./autoconf/AutoRegen.sh</tt>.
+</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="TargetMachine">Target Machine</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+<tt>LLVMTargetMachine</tt> is designed as a base class for targets implemented
+with the LLVM target-independent code generator. The <tt>LLVMTargetMachine</tt>
+class should be specialized by a concrete target class that implements the
+various virtual methods. <tt>LLVMTargetMachine</tt> is defined as a subclass of
+<tt>TargetMachine</tt> in <tt>include/llvm/Target/TargetMachine.h</tt>. The
+<tt>TargetMachine</tt> class implementation (<tt>TargetMachine.cpp</tt>) also
+processes numerous command-line options.
+</p>
+
+<p>
+To create a concrete target-specific subclass of <tt>LLVMTargetMachine</tt>,
+start by copying an existing <tt>TargetMachine</tt> class and header. You
+should name the files that you create to reflect your specific target. For
+instance, for the SPARC target, name the files <tt>SparcTargetMachine.h</tt> and
+<tt>SparcTargetMachine.cpp</tt>.
+</p>
+
+<p>
+For a target machine <tt>XXX</tt>, the implementation of
+<tt>XXXTargetMachine</tt> must have access methods to obtain objects that
+represent target components. These methods are named <tt>get*Info</tt>, and are
+intended to obtain the instruction set (<tt>getInstrInfo</tt>), register set
+(<tt>getRegisterInfo</tt>), stack frame layout (<tt>getFrameInfo</tt>), and
+similar information. <tt>XXXTargetMachine</tt> must also implement the
+<tt>getTargetData</tt> method to access an object with target-specific data
+characteristics, such as data type size and alignment requirements.
+</p>
+
+<p>
+For instance, for the SPARC target, the header file
+<tt>SparcTargetMachine.h</tt> declares prototypes for several <tt>get*Info</tt>
+and <tt>getTargetData</tt> methods that simply return a class member.
+</p>
+
+<div class="doc_code">
+<pre>
+namespace llvm {
+
+class Module;
+
+class SparcTargetMachine : public LLVMTargetMachine {
+ const TargetData DataLayout; // Calculates type size &amp; alignment
+ SparcSubtarget Subtarget;
+ SparcInstrInfo InstrInfo;
+ TargetFrameInfo FrameInfo;
+
+protected:
+ virtual const TargetAsmInfo *createTargetAsmInfo() const;
+
+public:
+ SparcTargetMachine(const Module &amp;M, const std::string &amp;FS);
+
+ virtual const SparcInstrInfo *getInstrInfo() const {return &amp;InstrInfo; }
+ virtual const TargetFrameInfo *getFrameInfo() const {return &amp;FrameInfo; }
+ virtual const TargetSubtarget *getSubtargetImpl() const{return &amp;Subtarget; }
+ virtual const TargetRegisterInfo *getRegisterInfo() const {
+ return &amp;InstrInfo.getRegisterInfo();
+ }
+ virtual const TargetData *getTargetData() const { return &amp;DataLayout; }
+ static unsigned getModuleMatchQuality(const Module &amp;M);
+
+ // Pass Pipeline Configuration
+ virtual bool addInstSelector(PassManagerBase &amp;PM, bool Fast);
+ virtual bool addPreEmitPass(PassManagerBase &amp;PM, bool Fast);
+};
+
+} // end namespace llvm
+</pre>
+</div>
+
+<ul>
+<li><tt>getInstrInfo()</tt></li>
+<li><tt>getRegisterInfo()</tt></li>
+<li><tt>getFrameInfo()</tt></li>
+<li><tt>getTargetData()</tt></li>
+<li><tt>getSubtargetImpl()</tt></li>
+</ul>
+
+<p>For some targets, you also need to support the following methods:</p>
+
+<ul>
+<li><tt>getTargetLowering()</tt></li>
+<li><tt>getJITInfo()</tt></li>
+</ul>
+
+<p>
+In addition, the <tt>XXXTargetMachine</tt> constructor should specify a
+<tt>TargetDescription</tt> string that determines the data layout for the target
+machine, including characteristics such as pointer size, alignment, and
+endianness. For example, the constructor for SparcTargetMachine contains the
+following:
+</p>
+
+<div class="doc_code">
+<pre>
+SparcTargetMachine::SparcTargetMachine(const Module &amp;M, const std::string &amp;FS)
+ : DataLayout("E-p:32:32-f128:128:128"),
+ Subtarget(M, FS), InstrInfo(Subtarget),
+ FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {
+}
+</pre>
+</div>
+
+<p>Hyphens separate portions of the <tt>TargetDescription</tt> string.</p>
+
+<ul>
+<li>An upper-case "<tt>E</tt>" in the string indicates a big-endian target data
+ model. a lower-case "<tt>e</tt>" indicates little-endian.</li>
+
+<li>"<tt>p:</tt>" is followed by pointer information: size, ABI alignment, and
+ preferred alignment. If only two figures follow "<tt>p:</tt>", then the
+ first value is pointer size, and the second value is both ABI and preferred
+ alignment.</li>
+
+<li>Then a letter for numeric type alignment: "<tt>i</tt>", "<tt>f</tt>",
+ "<tt>v</tt>", or "<tt>a</tt>" (corresponding to integer, floating point,
+ vector, or aggregate). "<tt>i</tt>", "<tt>v</tt>", or "<tt>a</tt>" are
+ followed by ABI alignment and preferred alignment. "<tt>f</tt>" is followed
+ by three values: the first indicates the size of a long double, then ABI
+ alignment, and then ABI preferred alignment.</li>
+</ul>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="TargetRegistration">Target Registration</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+You must also register your target with the <tt>TargetRegistry</tt>, which is
+what other LLVM tools use to be able to lookup and use your target at
+runtime. The <tt>TargetRegistry</tt> can be used directly, but for most targets
+there are helper templates which should take care of the work for you.</p>
+
+<p>
+All targets should declare a global <tt>Target</tt> object which is used to
+represent the target during registration. Then, in the target's TargetInfo
+library, the target should define that object and use
+the <tt>RegisterTarget</tt> template to register the target. For example, the Sparc registration code looks like this:
+</p>
+
+<div class="doc_code">
+<pre>
+Target llvm::TheSparcTarget;
+
+extern "C" void LLVMInitializeSparcTargetInfo() {
+ RegisterTarget&lt;Triple::sparc, /*HasJIT=*/false&gt;
+ X(TheSparcTarget, "sparc", "Sparc");
+}
+</pre>
+</div>
+
+<p>
+This allows the <tt>TargetRegistry</tt> to look up the target by name or by
+target triple. In addition, most targets will also register additional features
+which are available in separate libraries. These registration steps are
+separate, because some clients may wish to only link in some parts of the target
+-- the JIT code generator does not require the use of the assembler printer, for
+example. Here is an example of registering the Sparc assembly printer:
+</p>
+
+<div class="doc_code">
+<pre>
+extern "C" void LLVMInitializeSparcAsmPrinter() {
+ RegisterAsmPrinter&lt;SparcAsmPrinter&gt; X(TheSparcTarget);
+}
+</pre>
+</div>
+
+<p>
+For more information, see
+"<a href="/doxygen/TargetRegistry_8h-source.html">llvm/Target/TargetRegistry.h</a>".
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="RegisterSet">Register Set and Register Classes</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+You should describe a concrete target-specific class that represents the
+register file of a target machine. This class is called <tt>XXXRegisterInfo</tt>
+(where <tt>XXX</tt> identifies the target) and represents the class register
+file data that is used for register allocation. It also describes the
+interactions between registers.
+</p>
+
+<p>
+You also need to define register classes to categorize related registers. A
+register class should be added for groups of registers that are all treated the
+same way for some instruction. Typical examples are register classes for
+integer, floating-point, or vector registers. A register allocator allows an
+instruction to use any register in a specified register class to perform the
+instruction in a similar manner. Register classes allocate virtual registers to
+instructions from these sets, and register classes let the target-independent
+register allocator automatically choose the actual registers.
+</p>
+
+<p>
+Much of the code for registers, including register definition, register aliases,
+and register classes, is generated by TableGen from <tt>XXXRegisterInfo.td</tt>
+input files and placed in <tt>XXXGenRegisterInfo.h.inc</tt> and
+<tt>XXXGenRegisterInfo.inc</tt> output files. Some of the code in the
+implementation of <tt>XXXRegisterInfo</tt> requires hand-coding.
+</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="RegisterDef">Defining a Register</a>
+</h3>
+
+<div>
+
+<p>
+The <tt>XXXRegisterInfo.td</tt> file typically starts with register definitions
+for a target machine. The <tt>Register</tt> class (specified
+in <tt>Target.td</tt>) is used to define an object for each register. The
+specified string <tt>n</tt> becomes the <tt>Name</tt> of the register. The
+basic <tt>Register</tt> object does not have any subregisters and does not
+specify any aliases.
+</p>
+
+<div class="doc_code">
+<pre>
+class Register&lt;string n&gt; {
+ string Namespace = "";
+ string AsmName = n;
+ string Name = n;
+ int SpillSize = 0;
+ int SpillAlignment = 0;
+ list&lt;Register&gt; Aliases = [];
+ list&lt;Register&gt; SubRegs = [];
+ list&lt;int&gt; DwarfNumbers = [];
+}
+</pre>
+</div>
+
+<p>
+For example, in the <tt>X86RegisterInfo.td</tt> file, there are register
+definitions that utilize the Register class, such as:
+</p>
+
+<div class="doc_code">
+<pre>
+def AL : Register&lt;"AL"&gt;, DwarfRegNum&lt;[0, 0, 0]&gt;;
+</pre>
+</div>
+
+<p>
+This defines the register <tt>AL</tt> and assigns it values (with
+<tt>DwarfRegNum</tt>) that are used by <tt>gcc</tt>, <tt>gdb</tt>, or a debug
+information writer to identify a register. For register
+<tt>AL</tt>, <tt>DwarfRegNum</tt> takes an array of 3 values representing 3
+different modes: the first element is for X86-64, the second for exception
+handling (EH) on X86-32, and the third is generic. -1 is a special Dwarf number
+that indicates the gcc number is undefined, and -2 indicates the register number
+is invalid for this mode.
+</p>
+
+<p>
+From the previously described line in the <tt>X86RegisterInfo.td</tt> file,
+TableGen generates this code in the <tt>X86GenRegisterInfo.inc</tt> file:
+</p>
+
+<div class="doc_code">
+<pre>
+static const unsigned GR8[] = { X86::AL, ... };
+
+const unsigned AL_AliasSet[] = { X86::AX, X86::EAX, X86::RAX, 0 };
+
+const TargetRegisterDesc RegisterDescriptors[] = {
+ ...
+{ "AL", "AL", AL_AliasSet, Empty_SubRegsSet, Empty_SubRegsSet, AL_SuperRegsSet }, ...
+</pre>
+</div>
+
+<p>
+From the register info file, TableGen generates a <tt>TargetRegisterDesc</tt>
+object for each register. <tt>TargetRegisterDesc</tt> is defined in
+<tt>include/llvm/Target/TargetRegisterInfo.h</tt> with the following fields:
+</p>
+
+<div class="doc_code">
+<pre>
+struct TargetRegisterDesc {
+ const char *AsmName; // Assembly language name for the register
+ const char *Name; // Printable name for the reg (for debugging)
+ const unsigned *AliasSet; // Register Alias Set
+ const unsigned *SubRegs; // Sub-register set
+ const unsigned *ImmSubRegs; // Immediate sub-register set
+ const unsigned *SuperRegs; // Super-register set
+};</pre>
+</div>
+
+<p>
+TableGen uses the entire target description file (<tt>.td</tt>) to determine
+text names for the register (in the <tt>AsmName</tt> and <tt>Name</tt> fields of
+<tt>TargetRegisterDesc</tt>) and the relationships of other registers to the
+defined register (in the other <tt>TargetRegisterDesc</tt> fields). In this
+example, other definitions establish the registers "<tt>AX</tt>",
+"<tt>EAX</tt>", and "<tt>RAX</tt>" as aliases for one another, so TableGen
+generates a null-terminated array (<tt>AL_AliasSet</tt>) for this register alias
+set.
+</p>
+
+<p>
+The <tt>Register</tt> class is commonly used as a base class for more complex
+classes. In <tt>Target.td</tt>, the <tt>Register</tt> class is the base for the
+<tt>RegisterWithSubRegs</tt> class that is used to define registers that need to
+specify subregisters in the <tt>SubRegs</tt> list, as shown here:
+</p>
+
+<div class="doc_code">
+<pre>
+class RegisterWithSubRegs&lt;string n,
+list&lt;Register&gt; subregs&gt; : Register&lt;n&gt; {
+ let SubRegs = subregs;
+}
+</pre>
+</div>
+
+<p>
+In <tt>SparcRegisterInfo.td</tt>, additional register classes are defined for
+SPARC: a Register subclass, SparcReg, and further subclasses: <tt>Ri</tt>,
+<tt>Rf</tt>, and <tt>Rd</tt>. SPARC registers are identified by 5-bit ID
+numbers, which is a feature common to these subclasses. Note the use of
+'<tt>let</tt>' expressions to override values that are initially defined in a
+superclass (such as <tt>SubRegs</tt> field in the <tt>Rd</tt> class).
+</p>
+
+<div class="doc_code">
+<pre>
+class SparcReg&lt;string n&gt; : Register&lt;n&gt; {
+ field bits&lt;5&gt; Num;
+ let Namespace = "SP";
+}
+// Ri - 32-bit integer registers
+class Ri&lt;bits&lt;5&gt; num, string n&gt; :
+SparcReg&lt;n&gt; {
+ let Num = num;
+}
+// Rf - 32-bit floating-point registers
+class Rf&lt;bits&lt;5&gt; num, string n&gt; :
+SparcReg&lt;n&gt; {
+ let Num = num;
+}
+// Rd - Slots in the FP register file for 64-bit
+floating-point values.
+class Rd&lt;bits&lt;5&gt; num, string n,
+list&lt;Register&gt; subregs&gt; : SparcReg&lt;n&gt; {
+ let Num = num;
+ let SubRegs = subregs;
+}
+</pre>
+</div>
+
+<p>
+In the <tt>SparcRegisterInfo.td</tt> file, there are register definitions that
+utilize these subclasses of <tt>Register</tt>, such as:
+</p>
+
+<div class="doc_code">
+<pre>
+def G0 : Ri&lt; 0, "G0"&gt;,
+DwarfRegNum&lt;[0]&gt;;
+def G1 : Ri&lt; 1, "G1"&gt;, DwarfRegNum&lt;[1]&gt;;
+...
+def F0 : Rf&lt; 0, "F0"&gt;,
+DwarfRegNum&lt;[32]&gt;;
+def F1 : Rf&lt; 1, "F1"&gt;,
+DwarfRegNum&lt;[33]&gt;;
+...
+def D0 : Rd&lt; 0, "F0", [F0, F1]&gt;,
+DwarfRegNum&lt;[32]&gt;;
+def D1 : Rd&lt; 2, "F2", [F2, F3]&gt;,
+DwarfRegNum&lt;[34]&gt;;
+</pre>
+</div>
+
+<p>
+The last two registers shown above (<tt>D0</tt> and <tt>D1</tt>) are
+double-precision floating-point registers that are aliases for pairs of
+single-precision floating-point sub-registers. In addition to aliases, the
+sub-register and super-register relationships of the defined register are in
+fields of a register's TargetRegisterDesc.
+</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="RegisterClassDef">Defining a Register Class</a>
+</h3>
+
+<div>
+
+<p>
+The <tt>RegisterClass</tt> class (specified in <tt>Target.td</tt>) is used to
+define an object that represents a group of related registers and also defines
+the default allocation order of the registers. A target description file
+<tt>XXXRegisterInfo.td</tt> that uses <tt>Target.td</tt> can construct register
+classes using the following class:
+</p>
+
+<div class="doc_code">
+<pre>
+class RegisterClass&lt;string namespace,
+list&lt;ValueType&gt; regTypes, int alignment, dag regList&gt; {
+ string Namespace = namespace;
+ list&lt;ValueType&gt; RegTypes = regTypes;
+ int Size = 0; // spill size, in bits; zero lets tblgen pick the size
+ int Alignment = alignment;
+
+ // CopyCost is the cost of copying a value between two registers
+ // default value 1 means a single instruction
+ // A negative value means copying is extremely expensive or impossible
+ int CopyCost = 1;
+ dag MemberList = regList;
+
+ // for register classes that are subregisters of this class
+ list&lt;RegisterClass&gt; SubRegClassList = [];
+
+ code MethodProtos = [{}]; // to insert arbitrary code
+ code MethodBodies = [{}];
+}
+</pre>
+</div>
+
+<p>To define a RegisterClass, use the following 4 arguments:</p>
+
+<ul>
+<li>The first argument of the definition is the name of the namespace.</li>
+
+<li>The second argument is a list of <tt>ValueType</tt> register type values
+ that are defined in <tt>include/llvm/CodeGen/ValueTypes.td</tt>. Defined
+ values include integer types (such as <tt>i16</tt>, <tt>i32</tt>,
+ and <tt>i1</tt> for Boolean), floating-point types
+ (<tt>f32</tt>, <tt>f64</tt>), and vector types (for example, <tt>v8i16</tt>
+ for an <tt>8 x i16</tt> vector). All registers in a <tt>RegisterClass</tt>
+ must have the same <tt>ValueType</tt>, but some registers may store vector
+ data in different configurations. For example a register that can process a
+ 128-bit vector may be able to handle 16 8-bit integer elements, 8 16-bit
+ integers, 4 32-bit integers, and so on. </li>
+
+<li>The third argument of the <tt>RegisterClass</tt> definition specifies the
+ alignment required of the registers when they are stored or loaded to
+ memory.</li>
+
+<li>The final argument, <tt>regList</tt>, specifies which registers are in this
+ class. If an alternative allocation order method is not specified, then
+ <tt>regList</tt> also defines the order of allocation used by the register
+ allocator. Besides simply listing registers with <tt>(add R0, R1, ...)</tt>,
+ more advanced set operators are available. See
+ <tt>include/llvm/Target/Target.td</tt> for more information.</li>
+</ul>
+
+<p>
+In <tt>SparcRegisterInfo.td</tt>, three RegisterClass objects are defined:
+<tt>FPRegs</tt>, <tt>DFPRegs</tt>, and <tt>IntRegs</tt>. For all three register
+classes, the first argument defines the namespace with the string
+'<tt>SP</tt>'. <tt>FPRegs</tt> defines a group of 32 single-precision
+floating-point registers (<tt>F0</tt> to <tt>F31</tt>); <tt>DFPRegs</tt> defines
+a group of 16 double-precision registers
+(<tt>D0-D15</tt>).
+</p>
+
+<div class="doc_code">
+<pre>
+// F0, F1, F2, ..., F31
+def FPRegs : RegisterClass&lt;"SP", [f32], 32, (sequence "F%u", 0, 31)&gt;;
+
+def DFPRegs : RegisterClass&lt;"SP", [f64], 64,
+ (add D0, D1, D2, D3, D4, D5, D6, D7, D8,
+ D9, D10, D11, D12, D13, D14, D15)&gt;;
+&nbsp;
+def IntRegs : RegisterClass&lt;"SP", [i32], 32,
+ (add L0, L1, L2, L3, L4, L5, L6, L7,
+ I0, I1, I2, I3, I4, I5,
+ O0, O1, O2, O3, O4, O5, O7,
+ G1,
+ // Non-allocatable regs:
+ G2, G3, G4,
+ O6, // stack ptr
+ I6, // frame ptr
+ I7, // return address
+ G0, // constant zero
+ G5, G6, G7 // reserved for kernel
+ )&gt;;
+</pre>
+</div>
+
+<p>
+Using <tt>SparcRegisterInfo.td</tt> with TableGen generates several output files
+that are intended for inclusion in other source code that you write.
+<tt>SparcRegisterInfo.td</tt> generates <tt>SparcGenRegisterInfo.h.inc</tt>,
+which should be included in the header file for the implementation of the SPARC
+register implementation that you write (<tt>SparcRegisterInfo.h</tt>). In
+<tt>SparcGenRegisterInfo.h.inc</tt> a new structure is defined called
+<tt>SparcGenRegisterInfo</tt> that uses <tt>TargetRegisterInfo</tt> as its
+base. It also specifies types, based upon the defined register
+classes: <tt>DFPRegsClass</tt>, <tt>FPRegsClass</tt>, and <tt>IntRegsClass</tt>.
+</p>
+
+<p>
+<tt>SparcRegisterInfo.td</tt> also generates <tt>SparcGenRegisterInfo.inc</tt>,
+which is included at the bottom of <tt>SparcRegisterInfo.cpp</tt>, the SPARC
+register implementation. The code below shows only the generated integer
+registers and associated register classes. The order of registers
+in <tt>IntRegs</tt> reflects the order in the definition of <tt>IntRegs</tt> in
+the target description file.
+</p>
+
+<div class="doc_code">
+<pre> // IntRegs Register Class...
+ static const unsigned IntRegs[] = {
+ SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5,
+ SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3,
+ SP::I4, SP::I5, SP::O0, SP::O1, SP::O2, SP::O3,
+ SP::O4, SP::O5, SP::O7, SP::G1, SP::G2, SP::G3,
+ SP::G4, SP::O6, SP::I6, SP::I7, SP::G0, SP::G5,
+ SP::G6, SP::G7,
+ };
+
+ // IntRegsVTs Register Class Value Types...
+ static const MVT::ValueType IntRegsVTs[] = {
+ MVT::i32, MVT::Other
+ };
+
+namespace SP { // Register class instances
+ DFPRegsClass&nbsp;&nbsp;&nbsp; DFPRegsRegClass;
+ FPRegsClass&nbsp;&nbsp;&nbsp;&nbsp; FPRegsRegClass;
+ IntRegsClass&nbsp;&nbsp;&nbsp; IntRegsRegClass;
+...
+ // IntRegs Sub-register Classess...
+ static const TargetRegisterClass* const IntRegsSubRegClasses [] = {
+ NULL
+ };
+...
+ // IntRegs Super-register Classess...
+ static const TargetRegisterClass* const IntRegsSuperRegClasses [] = {
+ NULL
+ };
+...
+ // IntRegs Register Class sub-classes...
+ static const TargetRegisterClass* const IntRegsSubclasses [] = {
+ NULL
+ };
+...
+ // IntRegs Register Class super-classes...
+ static const TargetRegisterClass* const IntRegsSuperclasses [] = {
+ NULL
+ };
+
+ IntRegsClass::IntRegsClass() : TargetRegisterClass(IntRegsRegClassID,
+ IntRegsVTs, IntRegsSubclasses, IntRegsSuperclasses, IntRegsSubRegClasses,
+ IntRegsSuperRegClasses, 4, 4, 1, IntRegs, IntRegs + 32) {}
+}
+</pre>
+</div>
+
+<p>
+The register allocators will avoid using reserved registers, and callee saved
+registers are not used until all the volatile registers have been used. That
+is usually good enough, but in some cases it may be necessary to provide custom
+allocation orders.
+</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="implementRegister">Implement a subclass of</a>
+ <a href="CodeGenerator.html#targetregisterinfo">TargetRegisterInfo</a>
+</h3>
+
+<div>
+
+<p>
+The final step is to hand code portions of <tt>XXXRegisterInfo</tt>, which
+implements the interface described in <tt>TargetRegisterInfo.h</tt>. These
+functions return <tt>0</tt>, <tt>NULL</tt>, or <tt>false</tt>, unless
+overridden. Here is a list of functions that are overridden for the SPARC
+implementation in <tt>SparcRegisterInfo.cpp</tt>:
+</p>
+
+<ul>
+<li><tt>getCalleeSavedRegs</tt> &mdash; Returns a list of callee-saved registers
+ in the order of the desired callee-save stack frame offset.</li>
+
+<li><tt>getReservedRegs</tt> &mdash; Returns a bitset indexed by physical
+ register numbers, indicating if a particular register is unavailable.</li>
+
+<li><tt>hasFP</tt> &mdash; Return a Boolean indicating if a function should have
+ a dedicated frame pointer register.</li>
+
+<li><tt>eliminateCallFramePseudoInstr</tt> &mdash; If call frame setup or
+ destroy pseudo instructions are used, this can be called to eliminate
+ them.</li>
+
+<li><tt>eliminateFrameIndex</tt> &mdash; Eliminate abstract frame indices from
+ instructions that may use them.</li>
+
+<li><tt>emitPrologue</tt> &mdash; Insert prologue code into the function.</li>
+
+<li><tt>emitEpilogue</tt> &mdash; Insert epilogue code into the function.</li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="InstructionSet">Instruction Set</a>
+</h2>
+
+<!-- *********************************************************************** -->
+<div>
+
+<p>
+During the early stages of code generation, the LLVM IR code is converted to a
+<tt>SelectionDAG</tt> with nodes that are instances of the <tt>SDNode</tt> class
+containing target instructions. An <tt>SDNode</tt> has an opcode, operands, type
+requirements, and operation properties. For example, is an operation
+commutative, does an operation load from memory. The various operation node
+types are described in the <tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt>
+file (values of the <tt>NodeType</tt> enum in the <tt>ISD</tt> namespace).
+</p>
+
+<p>
+TableGen uses the following target description (<tt>.td</tt>) input files to
+generate much of the code for instruction definition:
+</p>
+
+<ul>
+<li><tt>Target.td</tt> &mdash; Where the <tt>Instruction</tt>, <tt>Operand</tt>,
+ <tt>InstrInfo</tt>, and other fundamental classes are defined.</li>
+
+<li><tt>TargetSelectionDAG.td</tt>&mdash; Used by <tt>SelectionDAG</tt>
+ instruction selection generators, contains <tt>SDTC*</tt> classes (selection
+ DAG type constraint), definitions of <tt>SelectionDAG</tt> nodes (such as
+ <tt>imm</tt>, <tt>cond</tt>, <tt>bb</tt>, <tt>add</tt>, <tt>fadd</tt>,
+ <tt>sub</tt>), and pattern support (<tt>Pattern</tt>, <tt>Pat</tt>,
+ <tt>PatFrag</tt>, <tt>PatLeaf</tt>, <tt>ComplexPattern</tt>.</li>
+
+<li><tt>XXXInstrFormats.td</tt> &mdash; Patterns for definitions of
+ target-specific instructions.</li>
+
+<li><tt>XXXInstrInfo.td</tt> &mdash; Target-specific definitions of instruction
+ templates, condition codes, and instructions of an instruction set. For
+ architecture modifications, a different file name may be used. For example,
+ for Pentium with SSE instruction, this file is <tt>X86InstrSSE.td</tt>, and
+ for Pentium with MMX, this file is <tt>X86InstrMMX.td</tt>.</li>
+</ul>
+
+<p>
+There is also a target-specific <tt>XXX.td</tt> file, where <tt>XXX</tt> is the
+name of the target. The <tt>XXX.td</tt> file includes the other <tt>.td</tt>
+input files, but its contents are only directly important for subtargets.
+</p>
+
+<p>
+You should describe a concrete target-specific class <tt>XXXInstrInfo</tt> that
+represents machine instructions supported by a target machine.
+<tt>XXXInstrInfo</tt> contains an array of <tt>XXXInstrDescriptor</tt> objects,
+each of which describes one instruction. An instruction descriptor defines:</p>
+
+<ul>
+<li>Opcode mnemonic</li>
+
+<li>Number of operands</li>
+
+<li>List of implicit register definitions and uses</li>
+
+<li>Target-independent properties (such as memory access, is commutable)</li>
+
+<li>Target-specific flags </li>
+</ul>
+
+<p>
+The Instruction class (defined in <tt>Target.td</tt>) is mostly used as a base
+for more complex instruction classes.
+</p>
+
+<div class="doc_code">
+<pre>class Instruction {
+ string Namespace = "";
+ dag OutOperandList; // An dag containing the MI def operand list.
+ dag InOperandList; // An dag containing the MI use operand list.
+ string AsmString = ""; // The .s format to print the instruction with.
+ list&lt;dag&gt; Pattern; // Set to the DAG pattern for this instruction
+ list&lt;Register&gt; Uses = [];
+ list&lt;Register&gt; Defs = [];
+ list&lt;Predicate&gt; Predicates = []; // predicates turned into isel match code
+ ... remainder not shown for space ...
+}
+</pre>
+</div>
+
+<p>
+A <tt>SelectionDAG</tt> node (<tt>SDNode</tt>) should contain an object
+representing a target-specific instruction that is defined
+in <tt>XXXInstrInfo.td</tt>. The instruction objects should represent
+instructions from the architecture manual of the target machine (such as the
+SPARC Architecture Manual for the SPARC target).
+</p>
+
+<p>
+A single instruction from the architecture manual is often modeled as multiple
+target instructions, depending upon its operands. For example, a manual might
+describe an add instruction that takes a register or an immediate operand. An
+LLVM target could model this with two instructions named <tt>ADDri</tt> and
+<tt>ADDrr</tt>.
+</p>
+
+<p>
+You should define a class for each instruction category and define each opcode
+as a subclass of the category with appropriate parameters such as the fixed
+binary encoding of opcodes and extended opcodes. You should map the register
+bits to the bits of the instruction in which they are encoded (for the
+JIT). Also you should specify how the instruction should be printed when the
+automatic assembly printer is used.
+</p>
+
+<p>
+As is described in the SPARC Architecture Manual, Version 8, there are three
+major 32-bit formats for instructions. Format 1 is only for the <tt>CALL</tt>
+instruction. Format 2 is for branch on condition codes and <tt>SETHI</tt> (set
+high bits of a register) instructions. Format 3 is for other instructions.
+</p>
+
+<p>
+Each of these formats has corresponding classes in <tt>SparcInstrFormat.td</tt>.
+<tt>InstSP</tt> is a base class for other instruction classes. Additional base
+classes are specified for more precise formats: for example
+in <tt>SparcInstrFormat.td</tt>, <tt>F2_1</tt> is for <tt>SETHI</tt>,
+and <tt>F2_2</tt> is for branches. There are three other base
+classes: <tt>F3_1</tt> for register/register operations, <tt>F3_2</tt> for
+register/immediate operations, and <tt>F3_3</tt> for floating-point
+operations. <tt>SparcInstrInfo.td</tt> also adds the base class Pseudo for
+synthetic SPARC instructions.
+</p>
+
+<p>
+<tt>SparcInstrInfo.td</tt> largely consists of operand and instruction
+definitions for the SPARC target. In <tt>SparcInstrInfo.td</tt>, the following
+target description file entry, <tt>LDrr</tt>, defines the Load Integer
+instruction for a Word (the <tt>LD</tt> SPARC opcode) from a memory address to a
+register. The first parameter, the value 3 (<tt>11<sub>2</sub></tt>), is the
+operation value for this category of operation. The second parameter
+(<tt>000000<sub>2</sub></tt>) is the specific operation value
+for <tt>LD</tt>/Load Word. The third parameter is the output destination, which
+is a register operand and defined in the <tt>Register</tt> target description
+file (<tt>IntRegs</tt>).
+</p>
+
+<div class="doc_code">
+<pre>def LDrr : F3_1 &lt;3, 0b000000, (outs IntRegs:$dst), (ins MEMrr:$addr),
+ "ld [$addr], $dst",
+ [(set IntRegs:$dst, (load ADDRrr:$addr))]&gt;;
+</pre>
+</div>
+
+<p>
+The fourth parameter is the input source, which uses the address
+operand <tt>MEMrr</tt> that is defined earlier in <tt>SparcInstrInfo.td</tt>:
+</p>
+
+<div class="doc_code">
+<pre>def MEMrr : Operand&lt;i32&gt; {
+ let PrintMethod = "printMemOperand";
+ let MIOperandInfo = (ops IntRegs, IntRegs);
+}
+</pre>
+</div>
+
+<p>
+The fifth parameter is a string that is used by the assembly printer and can be
+left as an empty string until the assembly printer interface is implemented. The
+sixth and final parameter is the pattern used to match the instruction during
+the SelectionDAG Select Phase described in
+(<a href="CodeGenerator.html">The LLVM
+Target-Independent Code Generator</a>). This parameter is detailed in the next
+section, <a href="#InstructionSelector">Instruction Selector</a>.
+</p>
+
+<p>
+Instruction class definitions are not overloaded for different operand types, so
+separate versions of instructions are needed for register, memory, or immediate
+value operands. For example, to perform a Load Integer instruction for a Word
+from an immediate operand to a register, the following instruction class is
+defined:
+</p>
+
+<div class="doc_code">
+<pre>def LDri : F3_2 &lt;3, 0b000000, (outs IntRegs:$dst), (ins MEMri:$addr),
+ "ld [$addr], $dst",
+ [(set IntRegs:$dst, (load ADDRri:$addr))]&gt;;
+</pre>
+</div>
+
+<p>
+Writing these definitions for so many similar instructions can involve a lot of
+cut and paste. In td files, the <tt>multiclass</tt> directive enables the
+creation of templates to define several instruction classes at once (using
+the <tt>defm</tt> directive). For example in <tt>SparcInstrInfo.td</tt>, the
+<tt>multiclass</tt> pattern <tt>F3_12</tt> is defined to create 2 instruction
+classes each time <tt>F3_12</tt> is invoked:
+</p>
+
+<div class="doc_code">
+<pre>multiclass F3_12 &lt;string OpcStr, bits&lt;6&gt; Op3Val, SDNode OpNode&gt; {
+ def rr : F3_1 &lt;2, Op3Val,
+ (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
+ !strconcat(OpcStr, " $b, $c, $dst"),
+ [(set IntRegs:$dst, (OpNode IntRegs:$b, IntRegs:$c))]&gt;;
+ def ri : F3_2 &lt;2, Op3Val,
+ (outs IntRegs:$dst), (ins IntRegs:$b, i32imm:$c),
+ !strconcat(OpcStr, " $b, $c, $dst"),
+ [(set IntRegs:$dst, (OpNode IntRegs:$b, simm13:$c))]&gt;;
+}
+</pre>
+</div>
+
+<p>
+So when the <tt>defm</tt> directive is used for the <tt>XOR</tt>
+and <tt>ADD</tt> instructions, as seen below, it creates four instruction
+objects: <tt>XORrr</tt>, <tt>XORri</tt>, <tt>ADDrr</tt>, and <tt>ADDri</tt>.
+</p>
+
+<div class="doc_code">
+<pre>
+defm XOR : F3_12&lt;"xor", 0b000011, xor&gt;;
+defm ADD : F3_12&lt;"add", 0b000000, add&gt;;
+</pre>
+</div>
+
+<p>
+<tt>SparcInstrInfo.td</tt> also includes definitions for condition codes that
+are referenced by branch instructions. The following definitions
+in <tt>SparcInstrInfo.td</tt> indicate the bit location of the SPARC condition
+code. For example, the 10<sup>th</sup> bit represents the 'greater than'
+condition for integers, and the 22<sup>nd</sup> bit represents the 'greater
+than' condition for floats.
+</p>
+
+<div class="doc_code">
+<pre>
+def ICC_NE : ICC_VAL&lt; 9&gt;; // Not Equal
+def ICC_E : ICC_VAL&lt; 1&gt;; // Equal
+def ICC_G : ICC_VAL&lt;10&gt;; // Greater
+...
+def FCC_U : FCC_VAL&lt;23&gt;; // Unordered
+def FCC_G : FCC_VAL&lt;22&gt;; // Greater
+def FCC_UG : FCC_VAL&lt;21&gt;; // Unordered or Greater
+...
+</pre>
+</div>
+
+<p>
+(Note that <tt>Sparc.h</tt> also defines enums that correspond to the same SPARC
+condition codes. Care must be taken to ensure the values in <tt>Sparc.h</tt>
+correspond to the values in <tt>SparcInstrInfo.td</tt>. I.e.,
+<tt>SPCC::ICC_NE = 9</tt>, <tt>SPCC::FCC_U = 23</tt> and so on.)
+</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="operandMapping">Instruction Operand Mapping</a>
+</h3>
+
+<div>
+
+<p>
+The code generator backend maps instruction operands to fields in the
+instruction. Operands are assigned to unbound fields in the instruction in the
+order they are defined. Fields are bound when they are assigned a value. For
+example, the Sparc target defines the <tt>XNORrr</tt> instruction as
+a <tt>F3_1</tt> format instruction having three operands.
+</p>
+
+<div class="doc_code">
+<pre>
+def XNORrr : F3_1&lt;2, 0b000111,
+ (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
+ "xnor $b, $c, $dst",
+ [(set IntRegs:$dst, (not (xor IntRegs:$b, IntRegs:$c)))]&gt;;
+</pre>
+</div>
+
+<p>
+The instruction templates in <tt>SparcInstrFormats.td</tt> show the base class
+for <tt>F3_1</tt> is <tt>InstSP</tt>.
+</p>
+
+<div class="doc_code">
+<pre>
+class InstSP&lt;dag outs, dag ins, string asmstr, list&lt;dag&gt; pattern&gt; : Instruction {
+ field bits&lt;32&gt; Inst;
+ let Namespace = "SP";
+ bits&lt;2&gt; op;
+ let Inst{31-30} = op;
+ dag OutOperandList = outs;
+ dag InOperandList = ins;
+ let AsmString = asmstr;
+ let Pattern = pattern;
+}
+</pre>
+</div>
+
+<p><tt>InstSP</tt> leaves the <tt>op</tt> field unbound.</p>
+
+<div class="doc_code">
+<pre>
+class F3&lt;dag outs, dag ins, string asmstr, list&lt;dag&gt; pattern&gt;
+ : InstSP&lt;outs, ins, asmstr, pattern&gt; {
+ bits&lt;5&gt; rd;
+ bits&lt;6&gt; op3;
+ bits&lt;5&gt; rs1;
+ let op{1} = 1; // Op = 2 or 3
+ let Inst{29-25} = rd;
+ let Inst{24-19} = op3;
+ let Inst{18-14} = rs1;
+}
+</pre>
+</div>
+
+<p>
+<tt>F3</tt> binds the <tt>op</tt> field and defines the <tt>rd</tt>,
+<tt>op3</tt>, and <tt>rs1</tt> fields. <tt>F3</tt> format instructions will
+bind the operands <tt>rd</tt>, <tt>op3</tt>, and <tt>rs1</tt> fields.
+</p>
+
+<div class="doc_code">
+<pre>
+class F3_1&lt;bits&lt;2&gt; opVal, bits&lt;6&gt; op3val, dag outs, dag ins,
+ string asmstr, list&lt;dag&gt; pattern&gt; : F3&lt;outs, ins, asmstr, pattern&gt; {
+ bits&lt;8&gt; asi = 0; // asi not currently used
+ bits&lt;5&gt; rs2;
+ let op = opVal;
+ let op3 = op3val;
+ let Inst{13} = 0; // i field = 0
+ let Inst{12-5} = asi; // address space identifier
+ let Inst{4-0} = rs2;
+}
+</pre>
+</div>
+
+<p>
+<tt>F3_1</tt> binds the <tt>op3</tt> field and defines the <tt>rs2</tt>
+fields. <tt>F3_1</tt> format instructions will bind the operands to the <tt>rd</tt>,
+<tt>rs1</tt>, and <tt>rs2</tt> fields. This results in the <tt>XNORrr</tt>
+instruction binding <tt>$dst</tt>, <tt>$b</tt>, and <tt>$c</tt> operands to
+the <tt>rd</tt>, <tt>rs1</tt>, and <tt>rs2</tt> fields respectively.
+</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="implementInstr">Implement a subclass of </a>
+ <a href="CodeGenerator.html#targetinstrinfo">TargetInstrInfo</a>
+</h3>
+
+<div>
+
+<p>
+The final step is to hand code portions of <tt>XXXInstrInfo</tt>, which
+implements the interface described in <tt>TargetInstrInfo.h</tt>. These
+functions return <tt>0</tt> or a Boolean or they assert, unless
+overridden. Here's a list of functions that are overridden for the SPARC
+implementation in <tt>SparcInstrInfo.cpp</tt>:
+</p>
+
+<ul>
+<li><tt>isLoadFromStackSlot</tt> &mdash; If the specified machine instruction is
+ a direct load from a stack slot, return the register number of the
+ destination and the <tt>FrameIndex</tt> of the stack slot.</li>
+
+<li><tt>isStoreToStackSlot</tt> &mdash; If the specified machine instruction is
+ a direct store to a stack slot, return the register number of the
+ destination and the <tt>FrameIndex</tt> of the stack slot.</li>
+
+<li><tt>copyPhysReg</tt> &mdash; Copy values between a pair of physical
+ registers.</li>
+
+<li><tt>storeRegToStackSlot</tt> &mdash; Store a register value to a stack
+ slot.</li>
+
+<li><tt>loadRegFromStackSlot</tt> &mdash; Load a register value from a stack
+ slot.</li>
+
+<li><tt>storeRegToAddr</tt> &mdash; Store a register value to memory.</li>
+
+<li><tt>loadRegFromAddr</tt> &mdash; Load a register value from memory.</li>
+
+<li><tt>foldMemoryOperand</tt> &mdash; Attempt to combine instructions of any
+ load or store instruction for the specified operand(s).</li>
+</ul>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="branchFolding">Branch Folding and If Conversion</a>
+</h3>
+<div>
+
+<p>
+Performance can be improved by combining instructions or by eliminating
+instructions that are never reached. The <tt>AnalyzeBranch</tt> method
+in <tt>XXXInstrInfo</tt> may be implemented to examine conditional instructions
+and remove unnecessary instructions. <tt>AnalyzeBranch</tt> looks at the end of
+a machine basic block (MBB) for opportunities for improvement, such as branch
+folding and if conversion. The <tt>BranchFolder</tt> and <tt>IfConverter</tt>
+machine function passes (see the source files <tt>BranchFolding.cpp</tt> and
+<tt>IfConversion.cpp</tt> in the <tt>lib/CodeGen</tt> directory) call
+<tt>AnalyzeBranch</tt> to improve the control flow graph that represents the
+instructions.
+</p>
+
+<p>
+Several implementations of <tt>AnalyzeBranch</tt> (for ARM, Alpha, and X86) can
+be examined as models for your own <tt>AnalyzeBranch</tt> implementation. Since
+SPARC does not implement a useful <tt>AnalyzeBranch</tt>, the ARM target
+implementation is shown below.
+</p>
+
+<p><tt>AnalyzeBranch</tt> returns a Boolean value and takes four parameters:</p>
+
+<ul>
+<li><tt>MachineBasicBlock &amp;MBB</tt> &mdash; The incoming block to be
+ examined.</li>
+
+<li><tt>MachineBasicBlock *&amp;TBB</tt> &mdash; A destination block that is
+ returned. For a conditional branch that evaluates to true, <tt>TBB</tt> is
+ the destination.</li>
+
+<li><tt>MachineBasicBlock *&amp;FBB</tt> &mdash; For a conditional branch that
+ evaluates to false, <tt>FBB</tt> is returned as the destination.</li>
+
+<li><tt>std::vector&lt;MachineOperand&gt; &amp;Cond</tt> &mdash; List of
+ operands to evaluate a condition for a conditional branch.</li>
+</ul>
+
+<p>
+In the simplest case, if a block ends without a branch, then it falls through to
+the successor block. No destination blocks are specified for either <tt>TBB</tt>
+or <tt>FBB</tt>, so both parameters return <tt>NULL</tt>. The start of
+the <tt>AnalyzeBranch</tt> (see code below for the ARM target) shows the
+function parameters and the code for the simplest case.
+</p>
+
+<div class="doc_code">
+<pre>bool ARMInstrInfo::AnalyzeBranch(MachineBasicBlock &amp;MBB,
+ MachineBasicBlock *&amp;TBB, MachineBasicBlock *&amp;FBB,
+ std::vector&lt;MachineOperand&gt; &amp;Cond) const
+{
+ MachineBasicBlock::iterator I = MBB.end();
+ if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
+ return false;
+</pre>
+</div>
+
+<p>
+If a block ends with a single unconditional branch instruction, then
+<tt>AnalyzeBranch</tt> (shown below) should return the destination of that
+branch in the <tt>TBB</tt> parameter.
+</p>
+
+<div class="doc_code">
+<pre>
+ if (LastOpc == ARM::B || LastOpc == ARM::tB) {
+ TBB = LastInst-&gt;getOperand(0).getMBB();
+ return false;
+ }
+</pre>
+</div>
+
+<p>
+If a block ends with two unconditional branches, then the second branch is never
+reached. In that situation, as shown below, remove the last branch instruction
+and return the penultimate branch in the <tt>TBB</tt> parameter.
+</p>
+
+<div class="doc_code">
+<pre>
+ if ((SecondLastOpc == ARM::B || SecondLastOpc==ARM::tB) &amp;&amp;
+ (LastOpc == ARM::B || LastOpc == ARM::tB)) {
+ TBB = SecondLastInst-&gt;getOperand(0).getMBB();
+ I = LastInst;
+ I-&gt;eraseFromParent();
+ return false;
+ }
+</pre>
+</div>
+
+<p>
+A block may end with a single conditional branch instruction that falls through
+to successor block if the condition evaluates to false. In that case,
+<tt>AnalyzeBranch</tt> (shown below) should return the destination of that
+conditional branch in the <tt>TBB</tt> parameter and a list of operands in
+the <tt>Cond</tt> parameter to evaluate the condition.
+</p>
+
+<div class="doc_code">
+<pre>
+ if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {
+ // Block ends with fall-through condbranch.
+ TBB = LastInst-&gt;getOperand(0).getMBB();
+ Cond.push_back(LastInst-&gt;getOperand(1));
+ Cond.push_back(LastInst-&gt;getOperand(2));
+ return false;
+ }
+</pre>
+</div>
+
+<p>
+If a block ends with both a conditional branch and an ensuing unconditional
+branch, then <tt>AnalyzeBranch</tt> (shown below) should return the conditional
+branch destination (assuming it corresponds to a conditional evaluation of
+'<tt>true</tt>') in the <tt>TBB</tt> parameter and the unconditional branch
+destination in the <tt>FBB</tt> (corresponding to a conditional evaluation of
+'<tt>false</tt>'). A list of operands to evaluate the condition should be
+returned in the <tt>Cond</tt> parameter.
+</p>
+
+<div class="doc_code">
+<pre>
+ unsigned SecondLastOpc = SecondLastInst-&gt;getOpcode();
+
+ if ((SecondLastOpc == ARM::Bcc &amp;&amp; LastOpc == ARM::B) ||
+ (SecondLastOpc == ARM::tBcc &amp;&amp; LastOpc == ARM::tB)) {
+ TBB = SecondLastInst-&gt;getOperand(0).getMBB();
+ Cond.push_back(SecondLastInst-&gt;getOperand(1));
+ Cond.push_back(SecondLastInst-&gt;getOperand(2));
+ FBB = LastInst-&gt;getOperand(0).getMBB();
+ return false;
+ }
+</pre>
+</div>
+
+<p>
+For the last two cases (ending with a single conditional branch or ending with
+one conditional and one unconditional branch), the operands returned in
+the <tt>Cond</tt> parameter can be passed to methods of other instructions to
+create new branches or perform other operations. An implementation
+of <tt>AnalyzeBranch</tt> requires the helper methods <tt>RemoveBranch</tt>
+and <tt>InsertBranch</tt> to manage subsequent operations.
+</p>
+
+<p>
+<tt>AnalyzeBranch</tt> should return false indicating success in most circumstances.
+<tt>AnalyzeBranch</tt> should only return true when the method is stumped about what to
+do, for example, if a block has three terminating branches. <tt>AnalyzeBranch</tt> may
+return true if it encounters a terminator it cannot handle, such as an indirect
+branch.
+</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="InstructionSelector">Instruction Selector</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+LLVM uses a <tt>SelectionDAG</tt> to represent LLVM IR instructions, and nodes
+of the <tt>SelectionDAG</tt> ideally represent native target
+instructions. During code generation, instruction selection passes are performed
+to convert non-native DAG instructions into native target-specific
+instructions. The pass described in <tt>XXXISelDAGToDAG.cpp</tt> is used to
+match patterns and perform DAG-to-DAG instruction selection. Optionally, a pass
+may be defined (in <tt>XXXBranchSelector.cpp</tt>) to perform similar DAG-to-DAG
+operations for branch instructions. Later, the code in
+<tt>XXXISelLowering.cpp</tt> replaces or removes operations and data types not
+supported natively (legalizes) in a <tt>SelectionDAG</tt>.
+</p>
+
+<p>
+TableGen generates code for instruction selection using the following target
+description input files:
+</p>
+
+<ul>
+<li><tt>XXXInstrInfo.td</tt> &mdash; Contains definitions of instructions in a
+ target-specific instruction set, generates <tt>XXXGenDAGISel.inc</tt>, which
+ is included in <tt>XXXISelDAGToDAG.cpp</tt>.</li>
+
+<li><tt>XXXCallingConv.td</tt> &mdash; Contains the calling and return value
+ conventions for the target architecture, and it generates
+ <tt>XXXGenCallingConv.inc</tt>, which is included in
+ <tt>XXXISelLowering.cpp</tt>.</li>
+</ul>
+
+<p>
+The implementation of an instruction selection pass must include a header that
+declares the <tt>FunctionPass</tt> class or a subclass of <tt>FunctionPass</tt>. In
+<tt>XXXTargetMachine.cpp</tt>, a Pass Manager (PM) should add each instruction
+selection pass into the queue of passes to run.
+</p>
+
+<p>
+The LLVM static compiler (<tt>llc</tt>) is an excellent tool for visualizing the
+contents of DAGs. To display the <tt>SelectionDAG</tt> before or after specific
+processing phases, use the command line options for <tt>llc</tt>, described
+at <a href="CodeGenerator.html#selectiondag_process">
+SelectionDAG Instruction Selection Process</a>.
+</p>
+
+<p>
+To describe instruction selector behavior, you should add patterns for lowering
+LLVM code into a <tt>SelectionDAG</tt> as the last parameter of the instruction
+definitions in <tt>XXXInstrInfo.td</tt>. For example, in
+<tt>SparcInstrInfo.td</tt>, this entry defines a register store operation, and
+the last parameter describes a pattern with the store DAG operator.
+</p>
+
+<div class="doc_code">
+<pre>
+def STrr : F3_1&lt; 3, 0b000100, (outs), (ins MEMrr:$addr, IntRegs:$src),
+ "st $src, [$addr]", [(store IntRegs:$src, ADDRrr:$addr)]&gt;;
+</pre>
+</div>
+
+<p>
+<tt>ADDRrr</tt> is a memory mode that is also defined in
+<tt>SparcInstrInfo.td</tt>:
+</p>
+
+<div class="doc_code">
+<pre>
+def ADDRrr : ComplexPattern&lt;i32, 2, "SelectADDRrr", [], []&gt;;
+</pre>
+</div>
+
+<p>
+The definition of <tt>ADDRrr</tt> refers to <tt>SelectADDRrr</tt>, which is a
+function defined in an implementation of the Instructor Selector (such
+as <tt>SparcISelDAGToDAG.cpp</tt>).
+</p>
+
+<p>
+In <tt>lib/Target/TargetSelectionDAG.td</tt>, the DAG operator for store is
+defined below:
+</p>
+
+<div class="doc_code">
+<pre>
+def store : PatFrag&lt;(ops node:$val, node:$ptr),
+ (st node:$val, node:$ptr), [{
+ if (StoreSDNode *ST = dyn_cast&lt;StoreSDNode&gt;(N))
+ return !ST-&gt;isTruncatingStore() &amp;&amp;
+ ST-&gt;getAddressingMode() == ISD::UNINDEXED;
+ return false;
+}]&gt;;
+</pre>
+</div>
+
+<p>
+<tt>XXXInstrInfo.td</tt> also generates (in <tt>XXXGenDAGISel.inc</tt>) the
+<tt>SelectCode</tt> method that is used to call the appropriate processing
+method for an instruction. In this example, <tt>SelectCode</tt>
+calls <tt>Select_ISD_STORE</tt> for the <tt>ISD::STORE</tt> opcode.
+</p>
+
+<div class="doc_code">
+<pre>
+SDNode *SelectCode(SDValue N) {
+ ...
+ MVT::ValueType NVT = N.getNode()-&gt;getValueType(0);
+ switch (N.getOpcode()) {
+ case ISD::STORE: {
+ switch (NVT) {
+ default:
+ return Select_ISD_STORE(N);
+ break;
+ }
+ break;
+ }
+ ...
+</pre>
+</div>
+
+<p>
+The pattern for <tt>STrr</tt> is matched, so elsewhere in
+<tt>XXXGenDAGISel.inc</tt>, code for <tt>STrr</tt> is created for
+<tt>Select_ISD_STORE</tt>. The <tt>Emit_22</tt> method is also generated
+in <tt>XXXGenDAGISel.inc</tt> to complete the processing of this
+instruction.
+</p>
+
+<div class="doc_code">
+<pre>
+SDNode *Select_ISD_STORE(const SDValue &amp;N) {
+ SDValue Chain = N.getOperand(0);
+ if (Predicate_store(N.getNode())) {
+ SDValue N1 = N.getOperand(1);
+ SDValue N2 = N.getOperand(2);
+ SDValue CPTmp0;
+ SDValue CPTmp1;
+
+ // Pattern: (st:void IntRegs:i32:$src,
+ // ADDRrr:i32:$addr)&lt;&lt;P:Predicate_store&gt;&gt;
+ // Emits: (STrr:void ADDRrr:i32:$addr, IntRegs:i32:$src)
+ // Pattern complexity = 13 cost = 1 size = 0
+ if (SelectADDRrr(N, N2, CPTmp0, CPTmp1) &amp;&amp;
+ N1.getNode()-&gt;getValueType(0) == MVT::i32 &amp;&amp;
+ N2.getNode()-&gt;getValueType(0) == MVT::i32) {
+ return Emit_22(N, SP::STrr, CPTmp0, CPTmp1);
+ }
+...
+</pre>
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="LegalizePhase">The SelectionDAG Legalize Phase</a>
+</h3>
+
+<div>
+
+<p>
+The Legalize phase converts a DAG to use types and operations that are natively
+supported by the target. For natively unsupported types and operations, you need
+to add code to the target-specific XXXTargetLowering implementation to convert
+unsupported types and operations to supported ones.
+</p>
+
+<p>
+In the constructor for the <tt>XXXTargetLowering</tt> class, first use the
+<tt>addRegisterClass</tt> method to specify which types are supports and which
+register classes are associated with them. The code for the register classes are
+generated by TableGen from <tt>XXXRegisterInfo.td</tt> and placed
+in <tt>XXXGenRegisterInfo.h.inc</tt>. For example, the implementation of the
+constructor for the SparcTargetLowering class (in
+<tt>SparcISelLowering.cpp</tt>) starts with the following code:
+</p>
+
+<div class="doc_code">
+<pre>
+addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
+addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
+addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
+</pre>
+</div>
+
+<p>
+You should examine the node types in the <tt>ISD</tt> namespace
+(<tt>include/llvm/CodeGen/SelectionDAGNodes.h</tt>) and determine which
+operations the target natively supports. For operations that do <b>not</b> have
+native support, add a callback to the constructor for the XXXTargetLowering
+class, so the instruction selection process knows what to do. The TargetLowering
+class callback methods (declared in <tt>llvm/Target/TargetLowering.h</tt>) are:
+</p>
+
+<ul>
+<li><tt>setOperationAction</tt> &mdash; General operation.</li>
+
+<li><tt>setLoadExtAction</tt> &mdash; Load with extension.</li>
+
+<li><tt>setTruncStoreAction</tt> &mdash; Truncating store.</li>
+
+<li><tt>setIndexedLoadAction</tt> &mdash; Indexed load.</li>
+
+<li><tt>setIndexedStoreAction</tt> &mdash; Indexed store.</li>
+
+<li><tt>setConvertAction</tt> &mdash; Type conversion.</li>
+
+<li><tt>setCondCodeAction</tt> &mdash; Support for a given condition code.</li>
+</ul>
+
+<p>
+Note: on older releases, <tt>setLoadXAction</tt> is used instead
+of <tt>setLoadExtAction</tt>. Also, on older releases,
+<tt>setCondCodeAction</tt> may not be supported. Examine your release
+to see what methods are specifically supported.
+</p>
+
+<p>
+These callbacks are used to determine that an operation does or does not work
+with a specified type (or types). And in all cases, the third parameter is
+a <tt>LegalAction</tt> type enum value: <tt>Promote</tt>, <tt>Expand</tt>,
+<tt>Custom</tt>, or <tt>Legal</tt>. <tt>SparcISelLowering.cpp</tt>
+contains examples of all four <tt>LegalAction</tt> values.
+</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="promote">Promote</a>
+</h4>
+
+<div>
+
+<p>
+For an operation without native support for a given type, the specified type may
+be promoted to a larger type that is supported. For example, SPARC does not
+support a sign-extending load for Boolean values (<tt>i1</tt> type), so
+in <tt>SparcISelLowering.cpp</tt> the third parameter below, <tt>Promote</tt>,
+changes <tt>i1</tt> type values to a large type before loading.
+</p>
+
+<div class="doc_code">
+<pre>
+setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
+</pre>
+</div>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="expand">Expand</a>
+</h4>
+
+<div>
+
+<p>
+For a type without native support, a value may need to be broken down further,
+rather than promoted. For an operation without native support, a combination of
+other operations may be used to similar effect. In SPARC, the floating-point
+sine and cosine trig operations are supported by expansion to other operations,
+as indicated by the third parameter, <tt>Expand</tt>, to
+<tt>setOperationAction</tt>:
+</p>
+
+<div class="doc_code">
+<pre>
+setOperationAction(ISD::FSIN, MVT::f32, Expand);
+setOperationAction(ISD::FCOS, MVT::f32, Expand);
+</pre>
+</div>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="custom">Custom</a>
+</h4>
+
+<div>
+
+<p>
+For some operations, simple type promotion or operation expansion may be
+insufficient. In some cases, a special intrinsic function must be implemented.
+</p>
+
+<p>
+For example, a constant value may require special treatment, or an operation may
+require spilling and restoring registers in the stack and working with register
+allocators.
+</p>
+
+<p>
+As seen in <tt>SparcISelLowering.cpp</tt> code below, to perform a type
+conversion from a floating point value to a signed integer, first the
+<tt>setOperationAction</tt> should be called with <tt>Custom</tt> as the third
+parameter:
+</p>
+
+<div class="doc_code">
+<pre>
+setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
+</pre>
+</div>
+
+<p>
+In the <tt>LowerOperation</tt> method, for each <tt>Custom</tt> operation, a
+case statement should be added to indicate what function to call. In the
+following code, an <tt>FP_TO_SINT</tt> opcode will call
+the <tt>LowerFP_TO_SINT</tt> method:
+</p>
+
+<div class="doc_code">
+<pre>
+SDValue SparcTargetLowering::LowerOperation(SDValue Op, SelectionDAG &amp;DAG) {
+ switch (Op.getOpcode()) {
+ case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
+ ...
+ }
+}
+</pre>
+</div>
+
+<p>
+Finally, the <tt>LowerFP_TO_SINT</tt> method is implemented, using an FP
+register to convert the floating-point value to an integer.
+</p>
+
+<div class="doc_code">
+<pre>
+static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &amp;DAG) {
+ assert(Op.getValueType() == MVT::i32);
+ Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
+ return DAG.getNode(ISD::BITCAST, MVT::i32, Op);
+}
+</pre>
+</div>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="legal">Legal</a>
+</h4>
+
+<div>
+
+<p>
+The <tt>Legal</tt> LegalizeAction enum value simply indicates that an
+operation <b>is</b> natively supported. <tt>Legal</tt> represents the default
+condition, so it is rarely used. In <tt>SparcISelLowering.cpp</tt>, the action
+for <tt>CTPOP</tt> (an operation to count the bits set in an integer) is
+natively supported only for SPARC v9. The following code enables
+the <tt>Expand</tt> conversion technique for non-v9 SPARC implementations.
+</p>
+
+<div class="doc_code">
+<pre>
+setOperationAction(ISD::CTPOP, MVT::i32, Expand);
+...
+if (TM.getSubtarget&lt;SparcSubtarget&gt;().isV9())
+ setOperationAction(ISD::CTPOP, MVT::i32, Legal);
+ case ISD::SETULT: return SPCC::ICC_CS;
+ case ISD::SETULE: return SPCC::ICC_LEU;
+ case ISD::SETUGT: return SPCC::ICC_GU;
+ case ISD::SETUGE: return SPCC::ICC_CC;
+ }
+}
+</pre>
+</div>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="callingConventions">Calling Conventions</a>
+</h3>
+
+<div>
+
+<p>
+To support target-specific calling conventions, <tt>XXXGenCallingConv.td</tt>
+uses interfaces (such as CCIfType and CCAssignToReg) that are defined in
+<tt>lib/Target/TargetCallingConv.td</tt>. TableGen can take the target
+descriptor file <tt>XXXGenCallingConv.td</tt> and generate the header
+file <tt>XXXGenCallingConv.inc</tt>, which is typically included
+in <tt>XXXISelLowering.cpp</tt>. You can use the interfaces in
+<tt>TargetCallingConv.td</tt> to specify:
+</p>
+
+<ul>
+<li>The order of parameter allocation.</li>
+
+<li>Where parameters and return values are placed (that is, on the stack or in
+ registers).</li>
+
+<li>Which registers may be used.</li>
+
+<li>Whether the caller or callee unwinds the stack.</li>
+</ul>
+
+<p>
+The following example demonstrates the use of the <tt>CCIfType</tt> and
+<tt>CCAssignToReg</tt> interfaces. If the <tt>CCIfType</tt> predicate is true
+(that is, if the current argument is of type <tt>f32</tt> or <tt>f64</tt>), then
+the action is performed. In this case, the <tt>CCAssignToReg</tt> action assigns
+the argument value to the first available register: either <tt>R0</tt>
+or <tt>R1</tt>.
+</p>
+
+<div class="doc_code">
+<pre>
+CCIfType&lt;[f32,f64], CCAssignToReg&lt;[R0, R1]&gt;&gt;
+</pre>
+</div>
+
+<p>
+<tt>SparcCallingConv.td</tt> contains definitions for a target-specific
+return-value calling convention (RetCC_Sparc32) and a basic 32-bit C calling
+convention (<tt>CC_Sparc32</tt>). The definition of <tt>RetCC_Sparc32</tt>
+(shown below) indicates which registers are used for specified scalar return
+types. A single-precision float is returned to register <tt>F0</tt>, and a
+double-precision float goes to register <tt>D0</tt>. A 32-bit integer is
+returned in register <tt>I0</tt> or <tt>I1</tt>.
+</p>
+
+<div class="doc_code">
+<pre>
+def RetCC_Sparc32 : CallingConv&lt;[
+ CCIfType&lt;[i32], CCAssignToReg&lt;[I0, I1]&gt;&gt;,
+ CCIfType&lt;[f32], CCAssignToReg&lt;[F0]&gt;&gt;,
+ CCIfType&lt;[f64], CCAssignToReg&lt;[D0]&gt;&gt;
+]&gt;;
+</pre>
+</div>
+
+<p>
+The definition of <tt>CC_Sparc32</tt> in <tt>SparcCallingConv.td</tt> introduces
+<tt>CCAssignToStack</tt>, which assigns the value to a stack slot with the
+specified size and alignment. In the example below, the first parameter, 4,
+indicates the size of the slot, and the second parameter, also 4, indicates the
+stack alignment along 4-byte units. (Special cases: if size is zero, then the
+ABI size is used; if alignment is zero, then the ABI alignment is used.)
+</p>
+
+<div class="doc_code">
+<pre>
+def CC_Sparc32 : CallingConv&lt;[
+ // All arguments get passed in integer registers if there is space.
+ CCIfType&lt;[i32, f32, f64], CCAssignToReg&lt;[I0, I1, I2, I3, I4, I5]&gt;&gt;,
+ CCAssignToStack&lt;4, 4&gt;
+]&gt;;
+</pre>
+</div>
+
+<p>
+<tt>CCDelegateTo</tt> is another commonly used interface, which tries to find a
+specified sub-calling convention, and, if a match is found, it is invoked. In
+the following example (in <tt>X86CallingConv.td</tt>), the definition of
+<tt>RetCC_X86_32_C</tt> ends with <tt>CCDelegateTo</tt>. After the current value
+is assigned to the register <tt>ST0</tt> or <tt>ST1</tt>,
+the <tt>RetCC_X86Common</tt> is invoked.
+</p>
+
+<div class="doc_code">
+<pre>
+def RetCC_X86_32_C : CallingConv&lt;[
+ CCIfType&lt;[f32], CCAssignToReg&lt;[ST0, ST1]&gt;&gt;,
+ CCIfType&lt;[f64], CCAssignToReg&lt;[ST0, ST1]&gt;&gt;,
+ CCDelegateTo&lt;RetCC_X86Common&gt;
+]&gt;;
+</pre>
+</div>
+
+<p>
+<tt>CCIfCC</tt> is an interface that attempts to match the given name to the
+current calling convention. If the name identifies the current calling
+convention, then a specified action is invoked. In the following example (in
+<tt>X86CallingConv.td</tt>), if the <tt>Fast</tt> calling convention is in use,
+then <tt>RetCC_X86_32_Fast</tt> is invoked. If the <tt>SSECall</tt> calling
+convention is in use, then <tt>RetCC_X86_32_SSE</tt> is invoked.
+</p>
+
+<div class="doc_code">
+<pre>
+def RetCC_X86_32 : CallingConv&lt;[
+ CCIfCC&lt;"CallingConv::Fast", CCDelegateTo&lt;RetCC_X86_32_Fast&gt;&gt;,
+ CCIfCC&lt;"CallingConv::X86_SSECall", CCDelegateTo&lt;RetCC_X86_32_SSE&gt;&gt;,
+ CCDelegateTo&lt;RetCC_X86_32_C&gt;
+]&gt;;
+</pre>
+</div>
+
+<p>Other calling convention interfaces include:</p>
+
+<ul>
+<li><tt>CCIf &lt;predicate, action&gt;</tt> &mdash; If the predicate matches,
+ apply the action.</li>
+
+<li><tt>CCIfInReg &lt;action&gt;</tt> &mdash; If the argument is marked with the
+ '<tt>inreg</tt>' attribute, then apply the action.</li>
+
+<li><tt>CCIfNest &lt;action&gt;</tt> &mdash; Inf the argument is marked with the
+ '<tt>nest</tt>' attribute, then apply the action.</li>
+
+<li><tt>CCIfNotVarArg &lt;action&gt;</tt> &mdash; If the current function does
+ not take a variable number of arguments, apply the action.</li>
+
+<li><tt>CCAssignToRegWithShadow &lt;registerList, shadowList&gt;</tt> &mdash;
+ similar to <tt>CCAssignToReg</tt>, but with a shadow list of registers.</li>
+
+<li><tt>CCPassByVal &lt;size, align&gt;</tt> &mdash; Assign value to a stack
+ slot with the minimum specified size and alignment.</li>
+
+<li><tt>CCPromoteToType &lt;type&gt;</tt> &mdash; Promote the current value to
+ the specified type.</li>
+
+<li><tt>CallingConv &lt;[actions]&gt;</tt> &mdash; Define each calling
+ convention that is supported.</li>
+</ul>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="assemblyPrinter">Assembly Printer</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+During the code emission stage, the code generator may utilize an LLVM pass to
+produce assembly output. To do this, you want to implement the code for a
+printer that converts LLVM IR to a GAS-format assembly language for your target
+machine, using the following steps:
+</p>
+
+<ul>
+<li>Define all the assembly strings for your target, adding them to the
+ instructions defined in the <tt>XXXInstrInfo.td</tt> file.
+ (See <a href="#InstructionSet">Instruction Set</a>.) TableGen will produce
+ an output file (<tt>XXXGenAsmWriter.inc</tt>) with an implementation of
+ the <tt>printInstruction</tt> method for the XXXAsmPrinter class.</li>
+
+<li>Write <tt>XXXTargetAsmInfo.h</tt>, which contains the bare-bones declaration
+ of the <tt>XXXTargetAsmInfo</tt> class (a subclass
+ of <tt>TargetAsmInfo</tt>).</li>
+
+<li>Write <tt>XXXTargetAsmInfo.cpp</tt>, which contains target-specific values
+ for <tt>TargetAsmInfo</tt> properties and sometimes new implementations for
+ methods.</li>
+
+<li>Write <tt>XXXAsmPrinter.cpp</tt>, which implements the <tt>AsmPrinter</tt>
+ class that performs the LLVM-to-assembly conversion.</li>
+</ul>
+
+<p>
+The code in <tt>XXXTargetAsmInfo.h</tt> is usually a trivial declaration of the
+<tt>XXXTargetAsmInfo</tt> class for use in <tt>XXXTargetAsmInfo.cpp</tt>.
+Similarly, <tt>XXXTargetAsmInfo.cpp</tt> usually has a few declarations of
+<tt>XXXTargetAsmInfo</tt> replacement values that override the default values
+in <tt>TargetAsmInfo.cpp</tt>. For example in <tt>SparcTargetAsmInfo.cpp</tt>:
+</p>
+
+<div class="doc_code">
+<pre>
+SparcTargetAsmInfo::SparcTargetAsmInfo(const SparcTargetMachine &amp;TM) {
+ Data16bitsDirective = "\t.half\t";
+ Data32bitsDirective = "\t.word\t";
+ Data64bitsDirective = 0; // .xword is only supported by V9.
+ ZeroDirective = "\t.skip\t";
+ CommentString = "!";
+ ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
+}
+</pre>
+</div>
+
+<p>
+The X86 assembly printer implementation (<tt>X86TargetAsmInfo</tt>) is an
+example where the target specific <tt>TargetAsmInfo</tt> class uses an
+overridden methods: <tt>ExpandInlineAsm</tt>.
+</p>
+
+<p>
+A target-specific implementation of AsmPrinter is written in
+<tt>XXXAsmPrinter.cpp</tt>, which implements the <tt>AsmPrinter</tt> class that
+converts the LLVM to printable assembly. The implementation must include the
+following headers that have declarations for the <tt>AsmPrinter</tt> and
+<tt>MachineFunctionPass</tt> classes. The <tt>MachineFunctionPass</tt> is a
+subclass of <tt>FunctionPass</tt>.
+</p>
+
+<div class="doc_code">
+<pre>
+#include "llvm/CodeGen/AsmPrinter.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+</pre>
+</div>
+
+<p>
+As a <tt>FunctionPass</tt>, <tt>AsmPrinter</tt> first
+calls <tt>doInitialization</tt> to set up the <tt>AsmPrinter</tt>. In
+<tt>SparcAsmPrinter</tt>, a <tt>Mangler</tt> object is instantiated to process
+variable names.
+</p>
+
+<p>
+In <tt>XXXAsmPrinter.cpp</tt>, the <tt>runOnMachineFunction</tt> method
+(declared in <tt>MachineFunctionPass</tt>) must be implemented
+for <tt>XXXAsmPrinter</tt>. In <tt>MachineFunctionPass</tt>,
+the <tt>runOnFunction</tt> method invokes <tt>runOnMachineFunction</tt>.
+Target-specific implementations of <tt>runOnMachineFunction</tt> differ, but
+generally do the following to process each machine function:
+</p>
+
+<ul>
+<li>Call <tt>SetupMachineFunction</tt> to perform initialization.</li>
+
+<li>Call <tt>EmitConstantPool</tt> to print out (to the output stream) constants
+ which have been spilled to memory.</li>
+
+<li>Call <tt>EmitJumpTableInfo</tt> to print out jump tables used by the current
+ function.</li>
+
+<li>Print out the label for the current function.</li>
+
+<li>Print out the code for the function, including basic block labels and the
+ assembly for the instruction (using <tt>printInstruction</tt>)</li>
+</ul>
+
+<p>
+The <tt>XXXAsmPrinter</tt> implementation must also include the code generated
+by TableGen that is output in the <tt>XXXGenAsmWriter.inc</tt> file. The code
+in <tt>XXXGenAsmWriter.inc</tt> contains an implementation of the
+<tt>printInstruction</tt> method that may call these methods:
+</p>
+
+<ul>
+<li><tt>printOperand</tt></li>
+
+<li><tt>printMemOperand</tt></li>
+
+<li><tt>printCCOperand (for conditional statements)</tt></li>
+
+<li><tt>printDataDirective</tt></li>
+
+<li><tt>printDeclare</tt></li>
+
+<li><tt>printImplicitDef</tt></li>
+
+<li><tt>printInlineAsm</tt></li>
+</ul>
+
+<p>
+The implementations of <tt>printDeclare</tt>, <tt>printImplicitDef</tt>,
+<tt>printInlineAsm</tt>, and <tt>printLabel</tt> in <tt>AsmPrinter.cpp</tt> are
+generally adequate for printing assembly and do not need to be
+overridden.
+</p>
+
+<p>
+The <tt>printOperand</tt> method is implemented with a long switch/case
+statement for the type of operand: register, immediate, basic block, external
+symbol, global address, constant pool index, or jump table index. For an
+instruction with a memory address operand, the <tt>printMemOperand</tt> method
+should be implemented to generate the proper output. Similarly,
+<tt>printCCOperand</tt> should be used to print a conditional operand.
+</p>
+
+<p><tt>doFinalization</tt> should be overridden in <tt>XXXAsmPrinter</tt>, and
+it should be called to shut down the assembly printer. During
+<tt>doFinalization</tt>, global variables and constants are printed to
+output.
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="subtargetSupport">Subtarget Support</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Subtarget support is used to inform the code generation process of instruction
+set variations for a given chip set. For example, the LLVM SPARC implementation
+provided covers three major versions of the SPARC microprocessor architecture:
+Version 8 (V8, which is a 32-bit architecture), Version 9 (V9, a 64-bit
+architecture), and the UltraSPARC architecture. V8 has 16 double-precision
+floating-point registers that are also usable as either 32 single-precision or 8
+quad-precision registers. V8 is also purely big-endian. V9 has 32
+double-precision floating-point registers that are also usable as 16
+quad-precision registers, but cannot be used as single-precision registers. The
+UltraSPARC architecture combines V9 with UltraSPARC Visual Instruction Set
+extensions.
+</p>
+
+<p>
+If subtarget support is needed, you should implement a target-specific
+XXXSubtarget class for your architecture. This class should process the
+command-line options <tt>-mcpu=</tt> and <tt>-mattr=</tt>.
+</p>
+
+<p>
+TableGen uses definitions in the <tt>Target.td</tt> and <tt>Sparc.td</tt> files
+to generate code in <tt>SparcGenSubtarget.inc</tt>. In <tt>Target.td</tt>, shown
+below, the <tt>SubtargetFeature</tt> interface is defined. The first 4 string
+parameters of the <tt>SubtargetFeature</tt> interface are a feature name, an
+attribute set by the feature, the value of the attribute, and a description of
+the feature. (The fifth parameter is a list of features whose presence is
+implied, and its default value is an empty array.)
+</p>
+
+<div class="doc_code">
+<pre>
+class SubtargetFeature&lt;string n, string a, string v, string d,
+ list&lt;SubtargetFeature&gt; i = []&gt; {
+ string Name = n;
+ string Attribute = a;
+ string Value = v;
+ string Desc = d;
+ list&lt;SubtargetFeature&gt; Implies = i;
+}
+</pre>
+</div>
+
+<p>
+In the <tt>Sparc.td</tt> file, the SubtargetFeature is used to define the
+following features.
+</p>
+
+<div class="doc_code">
+<pre>
+def FeatureV9 : SubtargetFeature&lt;"v9", "IsV9", "true",
+ "Enable SPARC-V9 instructions"&gt;;
+def FeatureV8Deprecated : SubtargetFeature&lt;"deprecated-v8",
+ "V8DeprecatedInsts", "true",
+ "Enable deprecated V8 instructions in V9 mode"&gt;;
+def FeatureVIS : SubtargetFeature&lt;"vis", "IsVIS", "true",
+ "Enable UltraSPARC Visual Instruction Set extensions"&gt;;
+</pre>
+</div>
+
+<p>
+Elsewhere in <tt>Sparc.td</tt>, the Proc class is defined and then is used to
+define particular SPARC processor subtypes that may have the previously
+described features.
+</p>
+
+<div class="doc_code">
+<pre>
+class Proc&lt;string Name, list&lt;SubtargetFeature&gt; Features&gt;
+ : Processor&lt;Name, NoItineraries, Features&gt;;
+&nbsp;
+def : Proc&lt;"generic", []&gt;;
+def : Proc&lt;"v8", []&gt;;
+def : Proc&lt;"supersparc", []&gt;;
+def : Proc&lt;"sparclite", []&gt;;
+def : Proc&lt;"f934", []&gt;;
+def : Proc&lt;"hypersparc", []&gt;;
+def : Proc&lt;"sparclite86x", []&gt;;
+def : Proc&lt;"sparclet", []&gt;;
+def : Proc&lt;"tsc701", []&gt;;
+def : Proc&lt;"v9", [FeatureV9]&gt;;
+def : Proc&lt;"ultrasparc", [FeatureV9, FeatureV8Deprecated]&gt;;
+def : Proc&lt;"ultrasparc3", [FeatureV9, FeatureV8Deprecated]&gt;;
+def : Proc&lt;"ultrasparc3-vis", [FeatureV9, FeatureV8Deprecated, FeatureVIS]&gt;;
+</pre>
+</div>
+
+<p>
+From <tt>Target.td</tt> and <tt>Sparc.td</tt> files, the resulting
+SparcGenSubtarget.inc specifies enum values to identify the features, arrays of
+constants to represent the CPU features and CPU subtypes, and the
+ParseSubtargetFeatures method that parses the features string that sets
+specified subtarget options. The generated <tt>SparcGenSubtarget.inc</tt> file
+should be included in the <tt>SparcSubtarget.cpp</tt>. The target-specific
+implementation of the XXXSubtarget method should follow this pseudocode:
+</p>
+
+<div class="doc_code">
+<pre>
+XXXSubtarget::XXXSubtarget(const Module &amp;M, const std::string &amp;FS) {
+ // Set the default features
+ // Determine default and user specified characteristics of the CPU
+ // Call ParseSubtargetFeatures(FS, CPU) to parse the features string
+ // Perform any additional operations
+}
+</pre>
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="jitSupport">JIT Support</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+The implementation of a target machine optionally includes a Just-In-Time (JIT)
+code generator that emits machine code and auxiliary structures as binary output
+that can be written directly to memory. To do this, implement JIT code
+generation by performing the following steps:
+</p>
+
+<ul>
+<li>Write an <tt>XXXCodeEmitter.cpp</tt> file that contains a machine function
+ pass that transforms target-machine instructions into relocatable machine
+ code.</li>
+
+<li>Write an <tt>XXXJITInfo.cpp</tt> file that implements the JIT interfaces for
+ target-specific code-generation activities, such as emitting machine code
+ and stubs.</li>
+
+<li>Modify <tt>XXXTargetMachine</tt> so that it provides a
+ <tt>TargetJITInfo</tt> object through its <tt>getJITInfo</tt> method.</li>
+</ul>
+
+<p>
+There are several different approaches to writing the JIT support code. For
+instance, TableGen and target descriptor files may be used for creating a JIT
+code generator, but are not mandatory. For the Alpha and PowerPC target
+machines, TableGen is used to generate <tt>XXXGenCodeEmitter.inc</tt>, which
+contains the binary coding of machine instructions and the
+<tt>getBinaryCodeForInstr</tt> method to access those codes. Other JIT
+implementations do not.
+</p>
+
+<p>
+Both <tt>XXXJITInfo.cpp</tt> and <tt>XXXCodeEmitter.cpp</tt> must include the
+<tt>llvm/CodeGen/MachineCodeEmitter.h</tt> header file that defines the
+<tt>MachineCodeEmitter</tt> class containing code for several callback functions
+that write data (in bytes, words, strings, etc.) to the output stream.
+</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="mce">Machine Code Emitter</a>
+</h3>
+
+<div>
+
+<p>
+In <tt>XXXCodeEmitter.cpp</tt>, a target-specific of the <tt>Emitter</tt> class
+is implemented as a function pass (subclass
+of <tt>MachineFunctionPass</tt>). The target-specific implementation
+of <tt>runOnMachineFunction</tt> (invoked by
+<tt>runOnFunction</tt> in <tt>MachineFunctionPass</tt>) iterates through the
+<tt>MachineBasicBlock</tt> calls <tt>emitInstruction</tt> to process each
+instruction and emit binary code. <tt>emitInstruction</tt> is largely
+implemented with case statements on the instruction types defined in
+<tt>XXXInstrInfo.h</tt>. For example, in <tt>X86CodeEmitter.cpp</tt>,
+the <tt>emitInstruction</tt> method is built around the following switch/case
+statements:
+</p>
+
+<div class="doc_code">
+<pre>
+switch (Desc-&gt;TSFlags &amp; X86::FormMask) {
+case X86II::Pseudo: // for not yet implemented instructions
+ ... // or pseudo-instructions
+ break;
+case X86II::RawFrm: // for instructions with a fixed opcode value
+ ...
+ break;
+case X86II::AddRegFrm: // for instructions that have one register operand
+ ... // added to their opcode
+ break;
+case X86II::MRMDestReg:// for instructions that use the Mod/RM byte
+ ... // to specify a destination (register)
+ break;
+case X86II::MRMDestMem:// for instructions that use the Mod/RM byte
+ ... // to specify a destination (memory)
+ break;
+case X86II::MRMSrcReg: // for instructions that use the Mod/RM byte
+ ... // to specify a source (register)
+ break;
+case X86II::MRMSrcMem: // for instructions that use the Mod/RM byte
+ ... // to specify a source (memory)
+ break;
+case X86II::MRM0r: case X86II::MRM1r: // for instructions that operate on
+case X86II::MRM2r: case X86II::MRM3r: // a REGISTER r/m operand and
+case X86II::MRM4r: case X86II::MRM5r: // use the Mod/RM byte and a field
+case X86II::MRM6r: case X86II::MRM7r: // to hold extended opcode data
+ ...
+ break;
+case X86II::MRM0m: case X86II::MRM1m: // for instructions that operate on
+case X86II::MRM2m: case X86II::MRM3m: // a MEMORY r/m operand and
+case X86II::MRM4m: case X86II::MRM5m: // use the Mod/RM byte and a field
+case X86II::MRM6m: case X86II::MRM7m: // to hold extended opcode data
+ ...
+ break;
+case X86II::MRMInitReg: // for instructions whose source and
+ ... // destination are the same register
+ break;
+}
+</pre>
+</div>
+
+<p>
+The implementations of these case statements often first emit the opcode and
+then get the operand(s). Then depending upon the operand, helper methods may be
+called to process the operand(s). For example, in <tt>X86CodeEmitter.cpp</tt>,
+for the <tt>X86II::AddRegFrm</tt> case, the first data emitted
+(by <tt>emitByte</tt>) is the opcode added to the register operand. Then an
+object representing the machine operand, <tt>MO1</tt>, is extracted. The helper
+methods such as <tt>isImmediate</tt>,
+<tt>isGlobalAddress</tt>, <tt>isExternalSymbol</tt>, <tt>isConstantPoolIndex</tt>, and
+<tt>isJumpTableIndex</tt> determine the operand
+type. (<tt>X86CodeEmitter.cpp</tt> also has private methods such
+as <tt>emitConstant</tt>, <tt>emitGlobalAddress</tt>,
+<tt>emitExternalSymbolAddress</tt>, <tt>emitConstPoolAddress</tt>,
+and <tt>emitJumpTableAddress</tt> that emit the data into the output stream.)
+</p>
+
+<div class="doc_code">
+<pre>
+case X86II::AddRegFrm:
+ MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
+
+ if (CurOp != NumOps) {
+ const MachineOperand &amp;MO1 = MI.getOperand(CurOp++);
+ unsigned Size = X86InstrInfo::sizeOfImm(Desc);
+ if (MO1.isImmediate())
+ emitConstant(MO1.getImm(), Size);
+ else {
+ unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
+ : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
+ if (Opcode == X86::MOV64ri)
+ rt = X86::reloc_absolute_dword; // FIXME: add X86II flag?
+ if (MO1.isGlobalAddress()) {
+ bool NeedStub = isa&lt;Function&gt;(MO1.getGlobal());
+ bool isLazy = gvNeedsLazyPtr(MO1.getGlobal());
+ emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
+ NeedStub, isLazy);
+ } else if (MO1.isExternalSymbol())
+ emitExternalSymbolAddress(MO1.getSymbolName(), rt);
+ else if (MO1.isConstantPoolIndex())
+ emitConstPoolAddress(MO1.getIndex(), rt);
+ else if (MO1.isJumpTableIndex())
+ emitJumpTableAddress(MO1.getIndex(), rt);
+ }
+ }
+ break;
+</pre>
+</div>
+
+<p>
+In the previous example, <tt>XXXCodeEmitter.cpp</tt> uses the
+variable <tt>rt</tt>, which is a RelocationType enum that may be used to
+relocate addresses (for example, a global address with a PIC base offset). The
+<tt>RelocationType</tt> enum for that target is defined in the short
+target-specific <tt>XXXRelocations.h</tt> file. The <tt>RelocationType</tt> is used by
+the <tt>relocate</tt> method defined in <tt>XXXJITInfo.cpp</tt> to rewrite
+addresses for referenced global symbols.
+</p>
+
+<p>
+For example, <tt>X86Relocations.h</tt> specifies the following relocation types
+for the X86 addresses. In all four cases, the relocated value is added to the
+value already in memory. For <tt>reloc_pcrel_word</tt>
+and <tt>reloc_picrel_word</tt>, there is an additional initial adjustment.
+</p>
+
+<div class="doc_code">
+<pre>
+enum RelocationType {
+ reloc_pcrel_word = 0, // add reloc value after adjusting for the PC loc
+ reloc_picrel_word = 1, // add reloc value after adjusting for the PIC base
+ reloc_absolute_word = 2, // absolute relocation; no additional adjustment
+ reloc_absolute_dword = 3 // absolute relocation; no additional adjustment
+};
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="targetJITInfo">Target JIT Info</a>
+</h3>
+
+<div>
+
+<p>
+<tt>XXXJITInfo.cpp</tt> implements the JIT interfaces for target-specific
+code-generation activities, such as emitting machine code and stubs. At minimum,
+a target-specific version of <tt>XXXJITInfo</tt> implements the following:
+</p>
+
+<ul>
+<li><tt>getLazyResolverFunction</tt> &mdash; Initializes the JIT, gives the
+ target a function that is used for compilation.</li>
+
+<li><tt>emitFunctionStub</tt> &mdash; Returns a native function with a specified
+ address for a callback function.</li>
+
+<li><tt>relocate</tt> &mdash; Changes the addresses of referenced globals, based
+ on relocation types.</li>
+
+<li>Callback function that are wrappers to a function stub that is used when the
+ real target is not initially known.</li>
+</ul>
+
+<p>
+<tt>getLazyResolverFunction</tt> is generally trivial to implement. It makes the
+incoming parameter as the global <tt>JITCompilerFunction</tt> and returns the
+callback function that will be used a function wrapper. For the Alpha target
+(in <tt>AlphaJITInfo.cpp</tt>), the <tt>getLazyResolverFunction</tt>
+implementation is simply:
+</p>
+
+<div class="doc_code">
+<pre>
+TargetJITInfo::LazyResolverFn AlphaJITInfo::getLazyResolverFunction(
+ JITCompilerFn F) {
+ JITCompilerFunction = F;
+ return AlphaCompilationCallback;
+}
+</pre>
+</div>
+
+<p>
+For the X86 target, the <tt>getLazyResolverFunction</tt> implementation is a
+little more complication, because it returns a different callback function for
+processors with SSE instructions and XMM registers.
+</p>
+
+<p>
+The callback function initially saves and later restores the callee register
+values, incoming arguments, and frame and return address. The callback function
+needs low-level access to the registers or stack, so it is typically implemented
+with assembler.
+</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="http://www.woo.com">Mason Woo</a> and <a href="http://misha.brukman.net">Misha Brukman</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a>
+ <br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/WritingAnLLVMPass.html b/docs/WritingAnLLVMPass.html
new file mode 100644
index 00000000000..af1ffa4fb7a
--- /dev/null
+++ b/docs/WritingAnLLVMPass.html
@@ -0,0 +1,1954 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Writing an LLVM Pass</title>
+ <link rel="stylesheet" href="_static/llvm.css" type="text/css">
+</head>
+<body>
+
+<h1>
+ Writing an LLVM Pass
+</h1>
+
+<ol>
+ <li><a href="#introduction">Introduction - What is a pass?</a></li>
+ <li><a href="#quickstart">Quick Start - Writing hello world</a>
+ <ul>
+ <li><a href="#makefile">Setting up the build environment</a></li>
+ <li><a href="#basiccode">Basic code required</a></li>
+ <li><a href="#running">Running a pass with <tt>opt</tt></a></li>
+ </ul></li>
+ <li><a href="#passtype">Pass classes and requirements</a>
+ <ul>
+ <li><a href="#ImmutablePass">The <tt>ImmutablePass</tt> class</a></li>
+ <li><a href="#ModulePass">The <tt>ModulePass</tt> class</a>
+ <ul>
+ <li><a href="#runOnModule">The <tt>runOnModule</tt> method</a></li>
+ </ul></li>
+ <li><a href="#CallGraphSCCPass">The <tt>CallGraphSCCPass</tt> class</a>
+ <ul>
+ <li><a href="#doInitialization_scc">The <tt>doInitialization(CallGraph
+ &amp;)</tt> method</a></li>
+ <li><a href="#runOnSCC">The <tt>runOnSCC</tt> method</a></li>
+ <li><a href="#doFinalization_scc">The <tt>doFinalization(CallGraph
+ &amp;)</tt> method</a></li>
+ </ul></li>
+ <li><a href="#FunctionPass">The <tt>FunctionPass</tt> class</a>
+ <ul>
+ <li><a href="#doInitialization_mod">The <tt>doInitialization(Module
+ &amp;)</tt> method</a></li>
+ <li><a href="#runOnFunction">The <tt>runOnFunction</tt> method</a></li>
+ <li><a href="#doFinalization_mod">The <tt>doFinalization(Module
+ &amp;)</tt> method</a></li>
+ </ul></li>
+ <li><a href="#LoopPass">The <tt>LoopPass</tt> class</a>
+ <ul>
+ <li><a href="#doInitialization_loop">The <tt>doInitialization(Loop *,
+ LPPassManager &amp;)</tt> method</a></li>
+ <li><a href="#runOnLoop">The <tt>runOnLoop</tt> method</a></li>
+ <li><a href="#doFinalization_loop">The <tt>doFinalization()
+ </tt> method</a></li>
+ </ul></li>
+ <li><a href="#RegionPass">The <tt>RegionPass</tt> class</a>
+ <ul>
+ <li><a href="#doInitialization_region">The <tt>doInitialization(Region *,
+ RGPassManager &amp;)</tt> method</a></li>
+ <li><a href="#runOnRegion">The <tt>runOnRegion</tt> method</a></li>
+ <li><a href="#doFinalization_region">The <tt>doFinalization()
+ </tt> method</a></li>
+ </ul></li>
+ <li><a href="#BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
+ <ul>
+ <li><a href="#doInitialization_fn">The <tt>doInitialization(Function
+ &amp;)</tt> method</a></li>
+ <li><a href="#runOnBasicBlock">The <tt>runOnBasicBlock</tt>
+ method</a></li>
+ <li><a href="#doFinalization_fn">The <tt>doFinalization(Function
+ &amp;)</tt> method</a></li>
+ </ul></li>
+ <li><a href="#MachineFunctionPass">The <tt>MachineFunctionPass</tt>
+ class</a>
+ <ul>
+ <li><a href="#runOnMachineFunction">The
+ <tt>runOnMachineFunction(MachineFunction &amp;)</tt> method</a></li>
+ </ul></li>
+ </ul>
+ <li><a href="#registration">Pass Registration</a>
+ <ul>
+ <li><a href="#print">The <tt>print</tt> method</a></li>
+ </ul></li>
+ <li><a href="#interaction">Specifying interactions between passes</a>
+ <ul>
+ <li><a href="#getAnalysisUsage">The <tt>getAnalysisUsage</tt>
+ method</a></li>
+ <li><a href="#AU::addRequired">The <tt>AnalysisUsage::addRequired&lt;&gt;</tt> and <tt>AnalysisUsage::addRequiredTransitive&lt;&gt;</tt> methods</a></li>
+ <li><a href="#AU::addPreserved">The <tt>AnalysisUsage::addPreserved&lt;&gt;</tt> method</a></li>
+ <li><a href="#AU::examples">Example implementations of <tt>getAnalysisUsage</tt></a></li>
+ <li><a href="#getAnalysis">The <tt>getAnalysis&lt;&gt;</tt> and
+<tt>getAnalysisIfAvailable&lt;&gt;</tt> methods</a></li>
+ </ul></li>
+ <li><a href="#analysisgroup">Implementing Analysis Groups</a>
+ <ul>
+ <li><a href="#agconcepts">Analysis Group Concepts</a></li>
+ <li><a href="#registerag">Using <tt>RegisterAnalysisGroup</tt></a></li>
+ </ul></li>
+ <li><a href="#passStatistics">Pass Statistics</a>
+ <li><a href="#passmanager">What PassManager does</a>
+ <ul>
+ <li><a href="#releaseMemory">The <tt>releaseMemory</tt> method</a></li>
+ </ul></li>
+ <li><a href="#registering">Registering dynamically loaded passes</a>
+ <ul>
+ <li><a href="#registering_existing">Using existing registries</a></li>
+ <li><a href="#registering_new">Creating new registries</a></li>
+ </ul></li>
+ <li><a href="#debughints">Using GDB with dynamically loaded passes</a>
+ <ul>
+ <li><a href="#breakpoint">Setting a breakpoint in your pass</a></li>
+ <li><a href="#debugmisc">Miscellaneous Problems</a></li>
+ </ul></li>
+ <li><a href="#future">Future extensions planned</a>
+ <ul>
+ <li><a href="#SMP">Multithreaded LLVM</a></li>
+ </ul></li>
+</ol>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a> and
+ <a href="mailto:jlaskey@mac.com">Jim Laskey</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="introduction">Introduction - What is a pass?</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The LLVM Pass Framework is an important part of the LLVM system, because LLVM
+passes are where most of the interesting parts of the compiler exist. Passes
+perform the transformations and optimizations that make up the compiler, they
+build the analysis results that are used by these transformations, and they are,
+above all, a structuring technique for compiler code.</p>
+
+<p>All LLVM passes are subclasses of the <tt><a
+href="http://llvm.org/doxygen/classllvm_1_1Pass.html">Pass</a></tt>
+class, which implement functionality by overriding virtual methods inherited
+from <tt>Pass</tt>. Depending on how your pass works, you should inherit from
+the <tt><a href="#ModulePass">ModulePass</a></tt>, <tt><a
+href="#CallGraphSCCPass">CallGraphSCCPass</a></tt>, <tt><a
+href="#FunctionPass">FunctionPass</a></tt>, or <tt><a
+href="#LoopPass">LoopPass</a></tt>, or <tt><a
+href="#RegionPass">RegionPass</a></tt>, or <tt><a
+href="#BasicBlockPass">BasicBlockPass</a></tt> classes, which gives the system
+more information about what your pass does, and how it can be combined with
+other passes. One of the main features of the LLVM Pass Framework is that it
+schedules passes to run in an efficient way based on the constraints that your
+pass meets (which are indicated by which class they derive from).</p>
+
+<p>We start by showing you how to construct a pass, everything from setting up
+the code, to compiling, loading, and executing it. After the basics are down,
+more advanced features are discussed.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="quickstart">Quick Start - Writing hello world</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Here we describe how to write the "hello world" of passes. The "Hello" pass
+is designed to simply print out the name of non-external functions that exist in
+the program being compiled. It does not modify the program at all, it just
+inspects it. The source code and files for this pass are available in the LLVM
+source tree in the <tt>lib/Transforms/Hello</tt> directory.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="makefile">Setting up the build environment</a>
+</h3>
+
+<div>
+
+ <p>First, configure and build LLVM. This needs to be done directly inside the
+ LLVM source tree rather than in a separate objects directory.
+ Next, you need to create a new directory somewhere in the LLVM source
+ base. For this example, we'll assume that you made
+ <tt>lib/Transforms/Hello</tt>. Finally, you must set up a build script
+ (Makefile) that will compile the source code for the new pass. To do this,
+ copy the following into <tt>Makefile</tt>:</p>
+ <hr>
+
+<div class="doc_code"><pre>
+# Makefile for hello pass
+
+# Path to top level of LLVM hierarchy
+LEVEL = ../../..
+
+# Name of the library to build
+LIBRARYNAME = Hello
+
+# Make the shared library become a loadable module so the tools can
+# dlopen/dlsym on the resulting library.
+LOADABLE_MODULE = 1
+
+# Include the makefile implementation stuff
+include $(LEVEL)/Makefile.common
+</pre></div>
+
+<p>This makefile specifies that all of the <tt>.cpp</tt> files in the current
+directory are to be compiled and linked together into a shared object
+<tt>$(LEVEL)/Debug+Asserts/lib/Hello.so</tt> that can be dynamically loaded by
+the <tt>opt</tt> or <tt>bugpoint</tt> tools via their <tt>-load</tt> options.
+If your operating system uses a suffix other than .so (such as windows or
+Mac OS/X), the appropriate extension will be used.</p>
+
+<p>If you are used CMake to build LLVM, see
+<a href="CMake.html#passdev">Developing an LLVM pass with CMake</a>.</p>
+
+<p>Now that we have the build scripts set up, we just need to write the code for
+the pass itself.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="basiccode">Basic code required</a>
+</h3>
+
+<div>
+
+<p>Now that we have a way to compile our new pass, we just have to write it.
+Start out with:</p>
+
+<div class="doc_code">
+<pre>
+<b>#include</b> "<a href="http://llvm.org/doxygen/Pass_8h-source.html">llvm/Pass.h</a>"
+<b>#include</b> "<a href="http://llvm.org/doxygen/Function_8h-source.html">llvm/Function.h</a>"
+<b>#include</b> "<a href="http://llvm.org/doxygen/raw__ostream_8h.html">llvm/Support/raw_ostream.h</a>"
+</pre>
+</div>
+
+<p>Which are needed because we are writing a <tt><a
+href="http://llvm.org/doxygen/classllvm_1_1Pass.html">Pass</a></tt>,
+we are operating on <tt><a
+href="http://llvm.org/doxygen/classllvm_1_1Function.html">Function</a></tt>'s,
+and we will be doing some printing.</p>
+
+<p>Next we have:</p>
+
+<div class="doc_code">
+<pre>
+<b>using namespace llvm;</b>
+</pre>
+</div>
+
+<p>... which is required because the functions from the include files
+live in the llvm namespace.</p>
+
+<p>Next we have:</p>
+
+<div class="doc_code">
+<pre>
+<b>namespace</b> {
+</pre>
+</div>
+
+<p>... which starts out an anonymous namespace. Anonymous namespaces are to C++
+what the "<tt>static</tt>" keyword is to C (at global scope). It makes the
+things declared inside of the anonymous namespace visible only to the current
+file. If you're not familiar with them, consult a decent C++ book for more
+information.</p>
+
+<p>Next, we declare our pass itself:</p>
+
+<div class="doc_code">
+<pre>
+ <b>struct</b> Hello : <b>public</b> <a href="#FunctionPass">FunctionPass</a> {
+</pre>
+</div>
+
+<p>This declares a "<tt>Hello</tt>" class that is a subclass of <tt><a
+href="http://llvm.org/doxygen/classllvm_1_1FunctionPass.html">FunctionPass</a></tt>.
+The different builtin pass subclasses are described in detail <a
+href="#passtype">later</a>, but for now, know that <a
+href="#FunctionPass"><tt>FunctionPass</tt></a>'s operate on a function at a
+time.</p>
+
+<div class="doc_code">
+<pre>
+ static char ID;
+ Hello() : FunctionPass(ID) {}
+</pre>
+</div>
+
+<p>This declares pass identifier used by LLVM to identify pass. This allows LLVM
+to avoid using expensive C++ runtime information.</p>
+
+<div class="doc_code">
+<pre>
+ <b>virtual bool</b> <a href="#runOnFunction">runOnFunction</a>(Function &amp;F) {
+ errs() &lt;&lt; "<i>Hello: </i>";
+ errs().write_escaped(F.getName()) &lt;&lt; "\n";
+ <b>return false</b>;
+ }
+ }; <i>// end of struct Hello</i>
+} <i>// end of anonymous namespace</i>
+</pre>
+</div>
+
+<p>We declare a "<a href="#runOnFunction"><tt>runOnFunction</tt></a>" method,
+which overloads an abstract virtual method inherited from <a
+href="#FunctionPass"><tt>FunctionPass</tt></a>. This is where we are supposed
+to do our thing, so we just print out our message with the name of each
+function.</p>
+
+<div class="doc_code">
+<pre>
+char Hello::ID = 0;
+</pre>
+</div>
+
+<p>We initialize pass ID here. LLVM uses ID's address to identify a pass, so
+initialization value is not important.</p>
+
+<div class="doc_code">
+<pre>
+static RegisterPass&lt;Hello&gt; X("<i>hello</i>", "<i>Hello World Pass</i>",
+ false /* Only looks at CFG */,
+ false /* Analysis Pass */);
+</pre>
+</div>
+
+<p>Lastly, we <a href="#registration">register our class</a> <tt>Hello</tt>,
+giving it a command line argument "<tt>hello</tt>", and a name "<tt>Hello World
+Pass</tt>". The last two arguments describe its behavior: if a pass walks CFG
+without modifying it then the third argument is set to <tt>true</tt>; if a pass
+is an analysis pass, for example dominator tree pass, then <tt>true</tt> is
+supplied as the fourth argument.</p>
+
+<p>As a whole, the <tt>.cpp</tt> file looks like:</p>
+
+<div class="doc_code">
+<pre>
+<b>#include</b> "<a href="http://llvm.org/doxygen/Pass_8h-source.html">llvm/Pass.h</a>"
+<b>#include</b> "<a href="http://llvm.org/doxygen/Function_8h-source.html">llvm/Function.h</a>"
+<b>#include</b> "<a href="http://llvm.org/doxygen/raw__ostream_8h.html">llvm/Support/raw_ostream.h</a>"
+
+<b>using namespace llvm;</b>
+
+<b>namespace</b> {
+ <b>struct Hello</b> : <b>public</b> <a href="#FunctionPass">FunctionPass</a> {
+
+ static char ID;
+ Hello() : FunctionPass(ID) {}
+
+ <b>virtual bool</b> <a href="#runOnFunction">runOnFunction</a>(Function &amp;F) {
+ errs() &lt;&lt; "<i>Hello: </i>";
+ errs().write_escaped(F.getName()) &lt;&lt; '\n';
+ <b>return false</b>;
+ }
+
+ };
+}
+
+char Hello::ID = 0;
+static RegisterPass&lt;Hello&gt; X("hello", "Hello World Pass", false, false);
+</pre>
+</div>
+
+<p>Now that it's all together, compile the file with a simple "<tt>gmake</tt>"
+command in the local directory and you should get a new file
+"<tt>Debug+Asserts/lib/Hello.so</tt>" under the top level directory of the LLVM
+source tree (not in the local directory). Note that everything in this file is
+contained in an anonymous namespace &mdash; this reflects the fact that passes
+are self contained units that do not need external interfaces (although they can
+have them) to be useful.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="running">Running a pass with <tt>opt</tt></a>
+</h3>
+
+<div>
+
+<p>Now that you have a brand new shiny shared object file, we can use the
+<tt>opt</tt> command to run an LLVM program through your pass. Because you
+registered your pass with <tt>RegisterPass</tt>, you will be able to
+use the <tt>opt</tt> tool to access it, once loaded.</p>
+
+<p>To test it, follow the example at the end of the <a
+href="GettingStarted.html">Getting Started Guide</a> to compile "Hello World" to
+LLVM. We can now run the bitcode file (<tt>hello.bc</tt>) for the program
+through our transformation like this (or course, any bitcode file will
+work):</p>
+
+<div class="doc_code"><pre>
+$ opt -load ../../../Debug+Asserts/lib/Hello.so -hello &lt; hello.bc &gt; /dev/null
+Hello: __main
+Hello: puts
+Hello: main
+</pre></div>
+
+<p>The '<tt>-load</tt>' option specifies that '<tt>opt</tt>' should load your
+pass as a shared object, which makes '<tt>-hello</tt>' a valid command line
+argument (which is one reason you need to <a href="#registration">register your
+pass</a>). Because the hello pass does not modify the program in any
+interesting way, we just throw away the result of <tt>opt</tt> (sending it to
+<tt>/dev/null</tt>).</p>
+
+<p>To see what happened to the other string you registered, try running
+<tt>opt</tt> with the <tt>-help</tt> option:</p>
+
+<div class="doc_code"><pre>
+$ opt -load ../../../Debug+Asserts/lib/Hello.so -help
+OVERVIEW: llvm .bc -&gt; .bc modular optimizer
+
+USAGE: opt [options] &lt;input bitcode&gt;
+
+OPTIONS:
+ Optimizations available:
+...
+ -globalopt - Global Variable Optimizer
+ -globalsmodref-aa - Simple mod/ref analysis for globals
+ -gvn - Global Value Numbering
+ <b>-hello - Hello World Pass</b>
+ -indvars - Induction Variable Simplification
+ -inline - Function Integration/Inlining
+ -insert-edge-profiling - Insert instrumentation for edge profiling
+...
+</pre></div>
+
+<p>The pass name gets added as the information string for your pass, giving some
+documentation to users of <tt>opt</tt>. Now that you have a working pass, you
+would go ahead and make it do the cool transformations you want. Once you get
+it all working and tested, it may become useful to find out how fast your pass
+is. The <a href="#passManager"><tt>PassManager</tt></a> provides a nice command
+line option (<tt>--time-passes</tt>) that allows you to get information about
+the execution time of your pass along with the other passes you queue up. For
+example:</p>
+
+<div class="doc_code"><pre>
+$ opt -load ../../../Debug+Asserts/lib/Hello.so -hello -time-passes &lt; hello.bc &gt; /dev/null
+Hello: __main
+Hello: puts
+Hello: main
+===============================================================================
+ ... Pass execution timing report ...
+===============================================================================
+ Total Execution Time: 0.02 seconds (0.0479059 wall clock)
+
+ ---User Time--- --System Time-- --User+System-- ---Wall Time--- --- Pass Name ---
+ 0.0100 (100.0%) 0.0000 ( 0.0%) 0.0100 ( 50.0%) 0.0402 ( 84.0%) Bitcode Writer
+ 0.0000 ( 0.0%) 0.0100 (100.0%) 0.0100 ( 50.0%) 0.0031 ( 6.4%) Dominator Set Construction
+ 0.0000 ( 0.0%) 0.0000 ( 0.0%) 0.0000 ( 0.0%) 0.0013 ( 2.7%) Module Verifier
+ <b> 0.0000 ( 0.0%) 0.0000 ( 0.0%) 0.0000 ( 0.0%) 0.0033 ( 6.9%) Hello World Pass</b>
+ 0.0100 (100.0%) 0.0100 (100.0%) 0.0200 (100.0%) 0.0479 (100.0%) TOTAL
+</pre></div>
+
+<p>As you can see, our implementation above is pretty fast :). The additional
+passes listed are automatically inserted by the '<tt>opt</tt>' tool to verify
+that the LLVM emitted by your pass is still valid and well formed LLVM, which
+hasn't been broken somehow.</p>
+
+<p>Now that you have seen the basics of the mechanics behind passes, we can talk
+about some more details of how they work and how to use them.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="passtype">Pass classes and requirements</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>One of the first things that you should do when designing a new pass is to
+decide what class you should subclass for your pass. The <a
+href="#basiccode">Hello World</a> example uses the <tt><a
+href="#FunctionPass">FunctionPass</a></tt> class for its implementation, but we
+did not discuss why or when this should occur. Here we talk about the classes
+available, from the most general to the most specific.</p>
+
+<p>When choosing a superclass for your Pass, you should choose the <b>most
+specific</b> class possible, while still being able to meet the requirements
+listed. This gives the LLVM Pass Infrastructure information necessary to
+optimize how passes are run, so that the resultant compiler isn't unnecessarily
+slow.</p>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ImmutablePass">The <tt>ImmutablePass</tt> class</a>
+</h3>
+
+<div>
+
+<p>The most plain and boring type of pass is the "<tt><a
+href="http://llvm.org/doxygen/classllvm_1_1ImmutablePass.html">ImmutablePass</a></tt>"
+class. This pass type is used for passes that do not have to be run, do not
+change state, and never need to be updated. This is not a normal type of
+transformation or analysis, but can provide information about the current
+compiler configuration.</p>
+
+<p>Although this pass class is very infrequently used, it is important for
+providing information about the current target machine being compiled for, and
+other static information that can affect the various transformations.</p>
+
+<p><tt>ImmutablePass</tt>es never invalidate other transformations, are never
+invalidated, and are never "run".</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="ModulePass">The <tt>ModulePass</tt> class</a>
+</h3>
+
+<div>
+
+<p>The "<tt><a
+href="http://llvm.org/doxygen/classllvm_1_1ModulePass.html">ModulePass</a></tt>"
+class is the most general of all superclasses that you can use. Deriving from
+<tt>ModulePass</tt> indicates that your pass uses the entire program as a unit,
+referring to function bodies in no predictable order, or adding and removing
+functions. Because nothing is known about the behavior of <tt>ModulePass</tt>
+subclasses, no optimization can be done for their execution.</p>
+
+<p>A module pass can use function level passes (e.g. dominators) using
+the getAnalysis interface
+<tt>getAnalysis&lt;DominatorTree&gt;(llvm::Function *)</tt> to provide the
+function to retrieve analysis result for, if the function pass does not require
+any module or immutable passes. Note that this can only be done for functions for which the
+analysis ran, e.g. in the case of dominators you should only ask for the
+DominatorTree for function definitions, not declarations.</p>
+
+<p>To write a correct <tt>ModulePass</tt> subclass, derive from
+<tt>ModulePass</tt> and overload the <tt>runOnModule</tt> method with the
+following signature:</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="runOnModule">The <tt>runOnModule</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> runOnModule(Module &amp;M) = 0;
+</pre></div>
+
+<p>The <tt>runOnModule</tt> method performs the interesting work of the pass.
+It should return true if the module was modified by the transformation and
+false otherwise.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="CallGraphSCCPass">The <tt>CallGraphSCCPass</tt> class</a>
+</h3>
+
+<div>
+
+<p>The "<tt><a
+href="http://llvm.org/doxygen/classllvm_1_1CallGraphSCCPass.html">CallGraphSCCPass</a></tt>"
+is used by passes that need to traverse the program bottom-up on the call graph
+(callees before callers). Deriving from CallGraphSCCPass provides some
+mechanics for building and traversing the CallGraph, but also allows the system
+to optimize execution of CallGraphSCCPass's. If your pass meets the
+requirements outlined below, and doesn't meet the requirements of a <tt><a
+href="#FunctionPass">FunctionPass</a></tt> or <tt><a
+href="#BasicBlockPass">BasicBlockPass</a></tt>, you should derive from
+<tt>CallGraphSCCPass</tt>.</p>
+
+<p><b>TODO</b>: explain briefly what SCC, Tarjan's algo, and B-U mean.</p>
+
+<p>To be explicit, <tt>CallGraphSCCPass</tt> subclasses are:</p>
+
+<ol>
+
+<li>... <em>not allowed</em> to inspect or modify any <tt>Function</tt>s other
+than those in the current SCC and the direct callers and direct callees of the
+SCC.</li>
+
+<li>... <em>required</em> to preserve the current CallGraph object, updating it
+to reflect any changes made to the program.</li>
+
+<li>... <em>not allowed</em> to add or remove SCC's from the current Module,
+though they may change the contents of an SCC.</li>
+
+<li>... <em>allowed</em> to add or remove global variables from the current
+Module.</li>
+
+<li>... <em>allowed</em> to maintain state across invocations of
+ <a href="#runOnSCC"><tt>runOnSCC</tt></a> (including global data).</li>
+</ol>
+
+<p>Implementing a <tt>CallGraphSCCPass</tt> is slightly tricky in some cases
+because it has to handle SCCs with more than one node in it. All of the virtual
+methods described below should return true if they modified the program, or
+false if they didn't.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doInitialization_scc">
+ The <tt>doInitialization(CallGraph &amp;)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doInitialization(CallGraph &amp;CG);
+</pre></div>
+
+<p>The <tt>doIninitialize</tt> method is allowed to do most of the things that
+<tt>CallGraphSCCPass</tt>'s are not allowed to do. They can add and remove
+functions, get pointers to functions, etc. The <tt>doInitialization</tt> method
+is designed to do simple initialization type of stuff that does not depend on
+the SCCs being processed. The <tt>doInitialization</tt> method call is not
+scheduled to overlap with any other pass executions (thus it should be very
+fast).</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="runOnSCC">The <tt>runOnSCC</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> runOnSCC(CallGraphSCC &amp;SCC) = 0;
+</pre></div>
+
+<p>The <tt>runOnSCC</tt> method performs the interesting work of the pass, and
+should return true if the module was modified by the transformation, false
+otherwise.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doFinalization_scc">
+ The <tt>doFinalization(CallGraph &amp;)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doFinalization(CallGraph &amp;CG);
+</pre></div>
+
+<p>The <tt>doFinalization</tt> method is an infrequently used method that is
+called when the pass framework has finished calling <a
+href="#runOnFunction"><tt>runOnFunction</tt></a> for every function in the
+program being compiled.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="FunctionPass">The <tt>FunctionPass</tt> class</a>
+</h3>
+
+<div>
+
+<p>In contrast to <tt>ModulePass</tt> subclasses, <tt><a
+href="http://llvm.org/doxygen/classllvm_1_1Pass.html">FunctionPass</a></tt>
+subclasses do have a predictable, local behavior that can be expected by the
+system. All <tt>FunctionPass</tt> execute on each function in the program
+independent of all of the other functions in the program.
+<tt>FunctionPass</tt>'s do not require that they are executed in a particular
+order, and <tt>FunctionPass</tt>'s do not modify external functions.</p>
+
+<p>To be explicit, <tt>FunctionPass</tt> subclasses are not allowed to:</p>
+
+<ol>
+<li>Modify a Function other than the one currently being processed.</li>
+<li>Add or remove Function's from the current Module.</li>
+<li>Add or remove global variables from the current Module.</li>
+<li>Maintain state across invocations of
+ <a href="#runOnFunction"><tt>runOnFunction</tt></a> (including global data)</li>
+</ol>
+
+<p>Implementing a <tt>FunctionPass</tt> is usually straightforward (See the <a
+href="#basiccode">Hello World</a> pass for example). <tt>FunctionPass</tt>'s
+may overload three virtual methods to do their work. All of these methods
+should return true if they modified the program, or false if they didn't.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doInitialization_mod">
+ The <tt>doInitialization(Module &amp;)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doInitialization(Module &amp;M);
+</pre></div>
+
+<p>The <tt>doIninitialize</tt> method is allowed to do most of the things that
+<tt>FunctionPass</tt>'s are not allowed to do. They can add and remove
+functions, get pointers to functions, etc. The <tt>doInitialization</tt> method
+is designed to do simple initialization type of stuff that does not depend on
+the functions being processed. The <tt>doInitialization</tt> method call is not
+scheduled to overlap with any other pass executions (thus it should be very
+fast).</p>
+
+<p>A good example of how this method should be used is the <a
+href="http://llvm.org/doxygen/LowerAllocations_8cpp-source.html">LowerAllocations</a>
+pass. This pass converts <tt>malloc</tt> and <tt>free</tt> instructions into
+platform dependent <tt>malloc()</tt> and <tt>free()</tt> function calls. It
+uses the <tt>doInitialization</tt> method to get a reference to the malloc and
+free functions that it needs, adding prototypes to the module if necessary.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="runOnFunction">The <tt>runOnFunction</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> runOnFunction(Function &amp;F) = 0;
+</pre></div><p>
+
+<p>The <tt>runOnFunction</tt> method must be implemented by your subclass to do
+the transformation or analysis work of your pass. As usual, a true value should
+be returned if the function is modified.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doFinalization_mod">
+ The <tt>doFinalization(Module &amp;)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doFinalization(Module &amp;M);
+</pre></div>
+
+<p>The <tt>doFinalization</tt> method is an infrequently used method that is
+called when the pass framework has finished calling <a
+href="#runOnFunction"><tt>runOnFunction</tt></a> for every function in the
+program being compiled.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="LoopPass">The <tt>LoopPass</tt> class </a>
+</h3>
+
+<div>
+
+<p> All <tt>LoopPass</tt> execute on each loop in the function independent of
+all of the other loops in the function. <tt>LoopPass</tt> processes loops in
+loop nest order such that outer most loop is processed last. </p>
+
+<p> <tt>LoopPass</tt> subclasses are allowed to update loop nest using
+<tt>LPPassManager</tt> interface. Implementing a loop pass is usually
+straightforward. <tt>LoopPass</tt>'s may overload three virtual methods to
+do their work. All these methods should return true if they modified the
+program, or false if they didn't. </p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doInitialization_loop">
+ The <tt>doInitialization(Loop *,LPPassManager &amp;)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doInitialization(Loop *, LPPassManager &amp;LPM);
+</pre></div>
+
+<p>The <tt>doInitialization</tt> method is designed to do simple initialization
+type of stuff that does not depend on the functions being processed. The
+<tt>doInitialization</tt> method call is not scheduled to overlap with any
+other pass executions (thus it should be very fast). LPPassManager
+interface should be used to access Function or Module level analysis
+information.</p>
+
+</div>
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="runOnLoop">The <tt>runOnLoop</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> runOnLoop(Loop *, LPPassManager &amp;LPM) = 0;
+</pre></div><p>
+
+<p>The <tt>runOnLoop</tt> method must be implemented by your subclass to do
+the transformation or analysis work of your pass. As usual, a true value should
+be returned if the function is modified. <tt>LPPassManager</tt> interface
+should be used to update loop nest.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doFinalization_loop">The <tt>doFinalization()</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doFinalization();
+</pre></div>
+
+<p>The <tt>doFinalization</tt> method is an infrequently used method that is
+called when the pass framework has finished calling <a
+href="#runOnLoop"><tt>runOnLoop</tt></a> for every loop in the
+program being compiled. </p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="RegionPass">The <tt>RegionPass</tt> class </a>
+</h3>
+
+<div>
+
+<p> <tt>RegionPass</tt> is similar to <a href="#LoopPass"><tt>LoopPass</tt></a>,
+but executes on each single entry single exit region in the function.
+<tt>RegionPass</tt> processes regions in nested order such that the outer most
+region is processed last. </p>
+
+<p> <tt>RegionPass</tt> subclasses are allowed to update the region tree by using
+the <tt>RGPassManager</tt> interface. You may overload three virtual methods of
+<tt>RegionPass</tt> to implement your own region pass. All these
+methods should return true if they modified the program, or false if they didn not.
+</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doInitialization_region">
+ The <tt>doInitialization(Region *, RGPassManager &amp;)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doInitialization(Region *, RGPassManager &amp;RGM);
+</pre></div>
+
+<p>The <tt>doInitialization</tt> method is designed to do simple initialization
+type of stuff that does not depend on the functions being processed. The
+<tt>doInitialization</tt> method call is not scheduled to overlap with any
+other pass executions (thus it should be very fast). RPPassManager
+interface should be used to access Function or Module level analysis
+information.</p>
+
+</div>
+
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="runOnRegion">The <tt>runOnRegion</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> runOnRegion(Region *, RGPassManager &amp;RGM) = 0;
+</pre></div><p>
+
+<p>The <tt>runOnRegion</tt> method must be implemented by your subclass to do
+the transformation or analysis work of your pass. As usual, a true value should
+be returned if the region is modified. <tt>RGPassManager</tt> interface
+should be used to update region tree.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doFinalization_region">The <tt>doFinalization()</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doFinalization();
+</pre></div>
+
+<p>The <tt>doFinalization</tt> method is an infrequently used method that is
+called when the pass framework has finished calling <a
+href="#runOnRegion"><tt>runOnRegion</tt></a> for every region in the
+program being compiled. </p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
+</h3>
+
+<div>
+
+<p><tt>BasicBlockPass</tt>'s are just like <a
+href="#FunctionPass"><tt>FunctionPass</tt></a>'s, except that they must limit
+their scope of inspection and modification to a single basic block at a time.
+As such, they are <b>not</b> allowed to do any of the following:</p>
+
+<ol>
+<li>Modify or inspect any basic blocks outside of the current one</li>
+<li>Maintain state across invocations of
+ <a href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a></li>
+<li>Modify the control flow graph (by altering terminator instructions)</li>
+<li>Any of the things forbidden for
+ <a href="#FunctionPass"><tt>FunctionPass</tt></a>es.</li>
+</ol>
+
+<p><tt>BasicBlockPass</tt>es are useful for traditional local and "peephole"
+optimizations. They may override the same <a
+href="#doInitialization_mod"><tt>doInitialization(Module &amp;)</tt></a> and <a
+href="#doFinalization_mod"><tt>doFinalization(Module &amp;)</tt></a> methods that <a
+href="#FunctionPass"><tt>FunctionPass</tt></a>'s have, but also have the following virtual methods that may also be implemented:</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doInitialization_fn">
+ The <tt>doInitialization(Function &amp;)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doInitialization(Function &amp;F);
+</pre></div>
+
+<p>The <tt>doIninitialize</tt> method is allowed to do most of the things that
+<tt>BasicBlockPass</tt>'s are not allowed to do, but that
+<tt>FunctionPass</tt>'s can. The <tt>doInitialization</tt> method is designed
+to do simple initialization that does not depend on the
+BasicBlocks being processed. The <tt>doInitialization</tt> method call is not
+scheduled to overlap with any other pass executions (thus it should be very
+fast).</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="runOnBasicBlock">The <tt>runOnBasicBlock</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> runOnBasicBlock(BasicBlock &amp;BB) = 0;
+</pre></div>
+
+<p>Override this function to do the work of the <tt>BasicBlockPass</tt>. This
+function is not allowed to inspect or modify basic blocks other than the
+parameter, and are not allowed to modify the CFG. A true value must be returned
+if the basic block is modified.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="doFinalization_fn">
+ The <tt>doFinalization(Function &amp;)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> doFinalization(Function &amp;F);
+</pre></div>
+
+<p>The <tt>doFinalization</tt> method is an infrequently used method that is
+called when the pass framework has finished calling <a
+href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a> for every BasicBlock in the
+program being compiled. This can be used to perform per-function
+finalization.</p>
+
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h3>
+ <a name="MachineFunctionPass">The <tt>MachineFunctionPass</tt> class</a>
+</h3>
+
+<div>
+
+<p>A <tt>MachineFunctionPass</tt> is a part of the LLVM code generator that
+executes on the machine-dependent representation of each LLVM function in the
+program.</p>
+
+<p>Code generator passes are registered and initialized specially by
+<tt>TargetMachine::addPassesToEmitFile</tt> and similar routines, so they
+cannot generally be run from the <tt>opt</tt> or <tt>bugpoint</tt>
+commands.</p>
+
+<p>A <tt>MachineFunctionPass</tt> is also a <tt>FunctionPass</tt>, so all
+the restrictions that apply to a <tt>FunctionPass</tt> also apply to it.
+<tt>MachineFunctionPass</tt>es also have additional restrictions. In particular,
+<tt>MachineFunctionPass</tt>es are not allowed to do any of the following:</p>
+
+<ol>
+<li>Modify or create any LLVM IR Instructions, BasicBlocks, Arguments,
+ Functions, GlobalVariables, GlobalAliases, or Modules.</li>
+<li>Modify a MachineFunction other than the one currently being processed.</li>
+<li>Maintain state across invocations of <a
+href="#runOnMachineFunction"><tt>runOnMachineFunction</tt></a> (including global
+data)</li>
+</ol>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="runOnMachineFunction">
+ The <tt>runOnMachineFunction(MachineFunction &amp;MF)</tt> method
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual bool</b> runOnMachineFunction(MachineFunction &amp;MF) = 0;
+</pre></div>
+
+<p><tt>runOnMachineFunction</tt> can be considered the main entry point of a
+<tt>MachineFunctionPass</tt>; that is, you should override this method to do the
+work of your <tt>MachineFunctionPass</tt>.</p>
+
+<p>The <tt>runOnMachineFunction</tt> method is called on every
+<tt>MachineFunction</tt> in a <tt>Module</tt>, so that the
+<tt>MachineFunctionPass</tt> may perform optimizations on the machine-dependent
+representation of the function. If you want to get at the LLVM <tt>Function</tt>
+for the <tt>MachineFunction</tt> you're working on, use
+<tt>MachineFunction</tt>'s <tt>getFunction()</tt> accessor method -- but
+remember, you may not modify the LLVM <tt>Function</tt> or its contents from a
+<tt>MachineFunctionPass</tt>.</p>
+
+</div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="registration">Pass registration</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>In the <a href="#basiccode">Hello World</a> example pass we illustrated how
+pass registration works, and discussed some of the reasons that it is used and
+what it does. Here we discuss how and why passes are registered.</p>
+
+<p>As we saw above, passes are registered with the <b><tt>RegisterPass</tt></b>
+template. The template parameter is the name of the pass that is to be used on
+the command line to specify that the pass should be added to a program (for
+example, with <tt>opt</tt> or <tt>bugpoint</tt>). The first argument is the
+name of the pass, which is to be used for the <tt>-help</tt> output of
+programs, as
+well as for debug output generated by the <tt>--debug-pass</tt> option.</p>
+
+<p>If you want your pass to be easily dumpable, you should
+implement the virtual <tt>print</tt> method:</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="print">The <tt>print</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual void</b> print(std::ostream &amp;O, <b>const</b> Module *M) <b>const</b>;
+</pre></div>
+
+<p>The <tt>print</tt> method must be implemented by "analyses" in order to print
+a human readable version of the analysis results. This is useful for debugging
+an analysis itself, as well as for other people to figure out how an analysis
+works. Use the <tt>opt -analyze</tt> argument to invoke this method.</p>
+
+<p>The <tt>llvm::OStream</tt> parameter specifies the stream to write the results on,
+and the <tt>Module</tt> parameter gives a pointer to the top level module of the
+program that has been analyzed. Note however that this pointer may be null in
+certain circumstances (such as calling the <tt>Pass::dump()</tt> from a
+debugger), so it should only be used to enhance debug output, it should not be
+depended on.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="interaction">Specifying interactions between passes</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>One of the main responsibilities of the <tt>PassManager</tt> is to make sure
+that passes interact with each other correctly. Because <tt>PassManager</tt>
+tries to <a href="#passmanager">optimize the execution of passes</a> it must
+know how the passes interact with each other and what dependencies exist between
+the various passes. To track this, each pass can declare the set of passes that
+are required to be executed before the current pass, and the passes which are
+invalidated by the current pass.</p>
+
+<p>Typically this functionality is used to require that analysis results are
+computed before your pass is run. Running arbitrary transformation passes can
+invalidate the computed analysis results, which is what the invalidation set
+specifies. If a pass does not implement the <tt><a
+href="#getAnalysisUsage">getAnalysisUsage</a></tt> method, it defaults to not
+having any prerequisite passes, and invalidating <b>all</b> other passes.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="getAnalysisUsage">The <tt>getAnalysisUsage</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<b>virtual void</b> getAnalysisUsage(AnalysisUsage &amp;Info) <b>const</b>;
+</pre></div>
+
+<p>By implementing the <tt>getAnalysisUsage</tt> method, the required and
+invalidated sets may be specified for your transformation. The implementation
+should fill in the <tt><a
+href="http://llvm.org/doxygen/classllvm_1_1AnalysisUsage.html">AnalysisUsage</a></tt>
+object with information about which passes are required and not invalidated. To
+do this, a pass may call any of the following methods on the AnalysisUsage
+object:</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="AU::addRequired">
+ The <tt>AnalysisUsage::addRequired&lt;&gt;</tt>
+ and <tt>AnalysisUsage::addRequiredTransitive&lt;&gt;</tt> methods
+ </a>
+</h4>
+
+<div>
+<p>
+If your pass requires a previous pass to be executed (an analysis for example),
+it can use one of these methods to arrange for it to be run before your pass.
+LLVM has many different types of analyses and passes that can be required,
+spanning the range from <tt>DominatorSet</tt> to <tt>BreakCriticalEdges</tt>.
+Requiring <tt>BreakCriticalEdges</tt>, for example, guarantees that there will
+be no critical edges in the CFG when your pass has been run.
+</p>
+
+<p>
+Some analyses chain to other analyses to do their job. For example, an <a
+href="AliasAnalysis.html">AliasAnalysis</a> implementation is required to <a
+href="AliasAnalysis.html#chaining">chain</a> to other alias analysis passes. In
+cases where analyses chain, the <tt>addRequiredTransitive</tt> method should be
+used instead of the <tt>addRequired</tt> method. This informs the PassManager
+that the transitively required pass should be alive as long as the requiring
+pass is.
+</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="AU::addPreserved">
+ The <tt>AnalysisUsage::addPreserved&lt;&gt;</tt> method
+ </a>
+</h4>
+
+<div>
+<p>
+One of the jobs of the PassManager is to optimize how and when analyses are run.
+In particular, it attempts to avoid recomputing data unless it needs to. For
+this reason, passes are allowed to declare that they preserve (i.e., they don't
+invalidate) an existing analysis if it's available. For example, a simple
+constant folding pass would not modify the CFG, so it can't possibly affect the
+results of dominator analysis. By default, all passes are assumed to invalidate
+all others.
+</p>
+
+<p>
+The <tt>AnalysisUsage</tt> class provides several methods which are useful in
+certain circumstances that are related to <tt>addPreserved</tt>. In particular,
+the <tt>setPreservesAll</tt> method can be called to indicate that the pass does
+not modify the LLVM program at all (which is true for analyses), and the
+<tt>setPreservesCFG</tt> method can be used by transformations that change
+instructions in the program but do not modify the CFG or terminator instructions
+(note that this property is implicitly set for <a
+href="#BasicBlockPass">BasicBlockPass</a>'s).
+</p>
+
+<p>
+<tt>addPreserved</tt> is particularly useful for transformations like
+<tt>BreakCriticalEdges</tt>. This pass knows how to update a small set of loop
+and dominator related analyses if they exist, so it can preserve them, despite
+the fact that it hacks on the CFG.
+</p>
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="AU::examples">
+ Example implementations of <tt>getAnalysisUsage</tt>
+ </a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+<i>// This example modifies the program, but does not modify the CFG</i>
+<b>void</b> <a href="http://llvm.org/doxygen/structLICM.html">LICM</a>::getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
+ AU.setPreservesCFG();
+ AU.addRequired&lt;<a href="http://llvm.org/doxygen/classllvm_1_1LoopInfo.html">LoopInfo</a>&gt;();
+}
+</pre></div>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="getAnalysis">
+ The <tt>getAnalysis&lt;&gt;</tt> and
+ <tt>getAnalysisIfAvailable&lt;&gt;</tt> methods
+ </a>
+</h4>
+
+<div>
+
+<p>The <tt>Pass::getAnalysis&lt;&gt;</tt> method is automatically inherited by
+your class, providing you with access to the passes that you declared that you
+required with the <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a>
+method. It takes a single template argument that specifies which pass class you
+want, and returns a reference to that pass. For example:</p>
+
+<div class="doc_code"><pre>
+bool LICM::runOnFunction(Function &amp;F) {
+ LoopInfo &amp;LI = getAnalysis&lt;LoopInfo&gt;();
+ ...
+}
+</pre></div>
+
+<p>This method call returns a reference to the pass desired. You may get a
+runtime assertion failure if you attempt to get an analysis that you did not
+declare as required in your <a
+href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> implementation. This
+method can be called by your <tt>run*</tt> method implementation, or by any
+other local method invoked by your <tt>run*</tt> method.
+
+A module level pass can use function level analysis info using this interface.
+For example:</p>
+
+<div class="doc_code"><pre>
+bool ModuleLevelPass::runOnModule(Module &amp;M) {
+ ...
+ DominatorTree &amp;DT = getAnalysis&lt;DominatorTree&gt;(Func);
+ ...
+}
+</pre></div>
+
+<p>In above example, runOnFunction for DominatorTree is called by pass manager
+before returning a reference to the desired pass.</p>
+
+<p>
+If your pass is capable of updating analyses if they exist (e.g.,
+<tt>BreakCriticalEdges</tt>, as described above), you can use the
+<tt>getAnalysisIfAvailable</tt> method, which returns a pointer to the analysis
+if it is active. For example:</p>
+
+<div class="doc_code"><pre>
+...
+if (DominatorSet *DS = getAnalysisIfAvailable&lt;DominatorSet&gt;()) {
+ <i>// A DominatorSet is active. This code will update it.</i>
+}
+...
+</pre></div>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="analysisgroup">Implementing Analysis Groups</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Now that we understand the basics of how passes are defined, how they are
+used, and how they are required from other passes, it's time to get a little bit
+fancier. All of the pass relationships that we have seen so far are very
+simple: one pass depends on one other specific pass to be run before it can run.
+For many applications, this is great, for others, more flexibility is
+required.</p>
+
+<p>In particular, some analyses are defined such that there is a single simple
+interface to the analysis results, but multiple ways of calculating them.
+Consider alias analysis for example. The most trivial alias analysis returns
+"may alias" for any alias query. The most sophisticated analysis a
+flow-sensitive, context-sensitive interprocedural analysis that can take a
+significant amount of time to execute (and obviously, there is a lot of room
+between these two extremes for other implementations). To cleanly support
+situations like this, the LLVM Pass Infrastructure supports the notion of
+Analysis Groups.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="agconcepts">Analysis Group Concepts</a>
+</h4>
+
+<div>
+
+<p>An Analysis Group is a single simple interface that may be implemented by
+multiple different passes. Analysis Groups can be given human readable names
+just like passes, but unlike passes, they need not derive from the <tt>Pass</tt>
+class. An analysis group may have one or more implementations, one of which is
+the "default" implementation.</p>
+
+<p>Analysis groups are used by client passes just like other passes are: the
+<tt>AnalysisUsage::addRequired()</tt> and <tt>Pass::getAnalysis()</tt> methods.
+In order to resolve this requirement, the <a href="#passmanager">PassManager</a>
+scans the available passes to see if any implementations of the analysis group
+are available. If none is available, the default implementation is created for
+the pass to use. All standard rules for <A href="#interaction">interaction
+between passes</a> still apply.</p>
+
+<p>Although <a href="#registration">Pass Registration</a> is optional for normal
+passes, all analysis group implementations must be registered, and must use the
+<A href="#registerag"><tt>INITIALIZE_AG_PASS</tt></a> template to join the
+implementation pool. Also, a default implementation of the interface
+<b>must</b> be registered with <A
+href="#registerag"><tt>RegisterAnalysisGroup</tt></a>.</p>
+
+<p>As a concrete example of an Analysis Group in action, consider the <a
+href="http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a>
+analysis group. The default implementation of the alias analysis interface (the
+<tt><a
+href="http://llvm.org/doxygen/structBasicAliasAnalysis.html">basicaa</a></tt>
+pass) just does a few simple checks that don't require significant analysis to
+compute (such as: two different globals can never alias each other, etc).
+Passes that use the <tt><a
+href="http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a></tt>
+interface (for example the <tt><a
+href="http://llvm.org/doxygen/structGCSE.html">gcse</a></tt> pass), do
+not care which implementation of alias analysis is actually provided, they just
+use the designated interface.</p>
+
+<p>From the user's perspective, commands work just like normal. Issuing the
+command '<tt>opt -gcse ...</tt>' will cause the <tt>basicaa</tt> class to be
+instantiated and added to the pass sequence. Issuing the command '<tt>opt
+-somefancyaa -gcse ...</tt>' will cause the <tt>gcse</tt> pass to use the
+<tt>somefancyaa</tt> alias analysis (which doesn't actually exist, it's just a
+hypothetical example) instead.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="registerag">Using <tt>RegisterAnalysisGroup</tt></a>
+</h4>
+
+<div>
+
+<p>The <tt>RegisterAnalysisGroup</tt> template is used to register the analysis
+group itself, while the <tt>INITIALIZE_AG_PASS</tt> is used to add pass
+implementations to the analysis group. First,
+an analysis group should be registered, with a human readable name
+provided for it.
+Unlike registration of passes, there is no command line argument to be specified
+for the Analysis Group Interface itself, because it is "abstract":</p>
+
+<div class="doc_code"><pre>
+<b>static</b> RegisterAnalysisGroup&lt;<a href="http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a>&gt; A("<i>Alias Analysis</i>");
+</pre></div>
+
+<p>Once the analysis is registered, passes can declare that they are valid
+implementations of the interface by using the following code:</p>
+
+<div class="doc_code"><pre>
+<b>namespace</b> {
+ //<i> Declare that we implement the AliasAnalysis interface</i>
+ INITIALIZE_AG_PASS(FancyAA, <a href="http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a>, "<i>somefancyaa</i>",
+ "<i>A more complex alias analysis implementation</i>",
+ false, // <i>Is CFG Only?</i>
+ true, // <i>Is Analysis?</i>
+ false); // <i>Is default Analysis Group implementation?</i>
+}
+</pre></div>
+
+<p>This just shows a class <tt>FancyAA</tt> that
+uses the <tt>INITIALIZE_AG_PASS</tt> macro both to register and
+to "join" the <tt><a href="http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a></tt>
+analysis group. Every implementation of an analysis group should join using
+this macro.</p>
+
+<div class="doc_code"><pre>
+<b>namespace</b> {
+ //<i> Declare that we implement the AliasAnalysis interface</i>
+ INITIALIZE_AG_PASS(BasicAA, <a href="http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html">AliasAnalysis</a>, "<i>basicaa</i>",
+ "<i>Basic Alias Analysis (default AA impl)</i>",
+ false, // <i>Is CFG Only?</i>
+ true, // <i>Is Analysis?</i>
+ true); // <i>Is default Analysis Group implementation?</i>
+}
+</pre></div>
+
+<p>Here we show how the default implementation is specified (using the final
+argument to the <tt>INITIALIZE_AG_PASS</tt> template). There must be exactly
+one default implementation available at all times for an Analysis Group to be
+used. Only default implementation can derive from <tt>ImmutablePass</tt>.
+Here we declare that the
+ <tt><a href="http://llvm.org/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a></tt>
+pass is the default implementation for the interface.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="passStatistics">Pass Statistics</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+<p>The <a
+href="http://llvm.org/doxygen/Statistic_8h-source.html"><tt>Statistic</tt></a>
+class is designed to be an easy way to expose various success
+metrics from passes. These statistics are printed at the end of a
+run, when the -stats command line option is enabled on the command
+line. See the <a href="http://llvm.org/docs/ProgrammersManual.html#Statistic">Statistics section</a> in the Programmer's Manual for details.
+
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="passmanager">What PassManager does</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The <a
+href="http://llvm.org/doxygen/PassManager_8h-source.html"><tt>PassManager</tt></a>
+<a
+href="http://llvm.org/doxygen/classllvm_1_1PassManager.html">class</a>
+takes a list of passes, ensures their <a href="#interaction">prerequisites</a>
+are set up correctly, and then schedules passes to run efficiently. All of the
+LLVM tools that run passes use the <tt>PassManager</tt> for execution of these
+passes.</p>
+
+<p>The <tt>PassManager</tt> does two main things to try to reduce the execution
+time of a series of passes:</p>
+
+<ol>
+<li><b>Share analysis results</b> - The PassManager attempts to avoid
+recomputing analysis results as much as possible. This means keeping track of
+which analyses are available already, which analyses get invalidated, and which
+analyses are needed to be run for a pass. An important part of work is that the
+<tt>PassManager</tt> tracks the exact lifetime of all analysis results, allowing
+it to <a href="#releaseMemory">free memory</a> allocated to holding analysis
+results as soon as they are no longer needed.</li>
+
+<li><b>Pipeline the execution of passes on the program</b> - The
+<tt>PassManager</tt> attempts to get better cache and memory usage behavior out
+of a series of passes by pipelining the passes together. This means that, given
+a series of consecutive <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s, it
+will execute all of the <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s on
+the first function, then all of the <a
+href="#FunctionPass"><tt>FunctionPass</tt></a>es on the second function,
+etc... until the entire program has been run through the passes.
+
+<p>This improves the cache behavior of the compiler, because it is only touching
+the LLVM program representation for a single function at a time, instead of
+traversing the entire program. It reduces the memory consumption of compiler,
+because, for example, only one <a
+href="http://llvm.org/doxygen/classllvm_1_1DominatorSet.html"><tt>DominatorSet</tt></a>
+needs to be calculated at a time. This also makes it possible to implement
+some <a
+href="#SMP">interesting enhancements</a> in the future.</p></li>
+
+</ol>
+
+<p>The effectiveness of the <tt>PassManager</tt> is influenced directly by how
+much information it has about the behaviors of the passes it is scheduling. For
+example, the "preserved" set is intentionally conservative in the face of an
+unimplemented <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method.
+Not implementing when it should be implemented will have the effect of not
+allowing any analysis results to live across the execution of your pass.</p>
+
+<p>The <tt>PassManager</tt> class exposes a <tt>--debug-pass</tt> command line
+options that is useful for debugging pass execution, seeing how things work, and
+diagnosing when you should be preserving more analyses than you currently are
+(To get information about all of the variants of the <tt>--debug-pass</tt>
+option, just type '<tt>opt -help-hidden</tt>').</p>
+
+<p>By using the <tt>--debug-pass=Structure</tt> option, for example, we can see
+how our <a href="#basiccode">Hello World</a> pass interacts with other passes.
+Lets try it out with the <tt>gcse</tt> and <tt>licm</tt> passes:</p>
+
+<div class="doc_code"><pre>
+$ opt -load ../../../Debug+Asserts/lib/Hello.so -gcse -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
+Module Pass Manager
+ Function Pass Manager
+ Dominator Set Construction
+ Immediate Dominators Construction
+ Global Common Subexpression Elimination
+-- Immediate Dominators Construction
+-- Global Common Subexpression Elimination
+ Natural Loop Construction
+ Loop Invariant Code Motion
+-- Natural Loop Construction
+-- Loop Invariant Code Motion
+ Module Verifier
+-- Dominator Set Construction
+-- Module Verifier
+ Bitcode Writer
+--Bitcode Writer
+</pre></div>
+
+<p>This output shows us when passes are constructed and when the analysis
+results are known to be dead (prefixed with '<tt>--</tt>'). Here we see that
+GCSE uses dominator and immediate dominator information to do its job. The LICM
+pass uses natural loop information, which uses dominator sets, but not immediate
+dominators. Because immediate dominators are no longer useful after the GCSE
+pass, it is immediately destroyed. The dominator sets are then reused to
+compute natural loop information, which is then used by the LICM pass.</p>
+
+<p>After the LICM pass, the module verifier runs (which is automatically added
+by the '<tt>opt</tt>' tool), which uses the dominator set to check that the
+resultant LLVM code is well formed. After it finishes, the dominator set
+information is destroyed, after being computed once, and shared by three
+passes.</p>
+
+<p>Lets see how this changes when we run the <a href="#basiccode">Hello
+World</a> pass in between the two passes:</p>
+
+<div class="doc_code"><pre>
+$ opt -load ../../../Debug+Asserts/lib/Hello.so -gcse -hello -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
+Module Pass Manager
+ Function Pass Manager
+ Dominator Set Construction
+ Immediate Dominators Construction
+ Global Common Subexpression Elimination
+<b>-- Dominator Set Construction</b>
+-- Immediate Dominators Construction
+-- Global Common Subexpression Elimination
+<b> Hello World Pass
+-- Hello World Pass
+ Dominator Set Construction</b>
+ Natural Loop Construction
+ Loop Invariant Code Motion
+-- Natural Loop Construction
+-- Loop Invariant Code Motion
+ Module Verifier
+-- Dominator Set Construction
+-- Module Verifier
+ Bitcode Writer
+--Bitcode Writer
+Hello: __main
+Hello: puts
+Hello: main
+</pre></div>
+
+<p>Here we see that the <a href="#basiccode">Hello World</a> pass has killed the
+Dominator Set pass, even though it doesn't modify the code at all! To fix this,
+we need to add the following <a
+href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method to our pass:</p>
+
+<div class="doc_code"><pre>
+<i>// We don't modify the program, so we preserve all analyses</i>
+<b>virtual void</b> getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
+ AU.setPreservesAll();
+}
+</pre></div>
+
+<p>Now when we run our pass, we get this output:</p>
+
+<div class="doc_code"><pre>
+$ opt -load ../../../Debug+Asserts/lib/Hello.so -gcse -hello -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
+Pass Arguments: -gcse -hello -licm
+Module Pass Manager
+ Function Pass Manager
+ Dominator Set Construction
+ Immediate Dominators Construction
+ Global Common Subexpression Elimination
+-- Immediate Dominators Construction
+-- Global Common Subexpression Elimination
+ Hello World Pass
+-- Hello World Pass
+ Natural Loop Construction
+ Loop Invariant Code Motion
+-- Loop Invariant Code Motion
+-- Natural Loop Construction
+ Module Verifier
+-- Dominator Set Construction
+-- Module Verifier
+ Bitcode Writer
+--Bitcode Writer
+Hello: __main
+Hello: puts
+Hello: main
+</pre></div>
+
+<p>Which shows that we don't accidentally invalidate dominator information
+anymore, and therefore do not have to compute it twice.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="releaseMemory">The <tt>releaseMemory</tt> method</a>
+</h4>
+
+<div>
+
+<div class="doc_code"><pre>
+ <b>virtual void</b> releaseMemory();
+</pre></div>
+
+<p>The <tt>PassManager</tt> automatically determines when to compute analysis
+results, and how long to keep them around for. Because the lifetime of the pass
+object itself is effectively the entire duration of the compilation process, we
+need some way to free analysis results when they are no longer useful. The
+<tt>releaseMemory</tt> virtual method is the way to do this.</p>
+
+<p>If you are writing an analysis or any other pass that retains a significant
+amount of state (for use by another pass which "requires" your pass and uses the
+<a href="#getAnalysis">getAnalysis</a> method) you should implement
+<tt>releaseMemory</tt> to, well, release the memory allocated to maintain this
+internal state. This method is called after the <tt>run*</tt> method for the
+class, before the next call of <tt>run*</tt> in your pass.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="registering">Registering dynamically loaded passes</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p><i>Size matters</i> when constructing production quality tools using llvm,
+both for the purposes of distribution, and for regulating the resident code size
+when running on the target system. Therefore, it becomes desirable to
+selectively use some passes, while omitting others and maintain the flexibility
+to change configurations later on. You want to be able to do all this, and,
+provide feedback to the user. This is where pass registration comes into
+play.</p>
+
+<p>The fundamental mechanisms for pass registration are the
+<tt>MachinePassRegistry</tt> class and subclasses of
+<tt>MachinePassRegistryNode</tt>.</p>
+
+<p>An instance of <tt>MachinePassRegistry</tt> is used to maintain a list of
+<tt>MachinePassRegistryNode</tt> objects. This instance maintains the list and
+communicates additions and deletions to the command line interface.</p>
+
+<p>An instance of <tt>MachinePassRegistryNode</tt> subclass is used to maintain
+information provided about a particular pass. This information includes the
+command line name, the command help string and the address of the function used
+to create an instance of the pass. A global static constructor of one of these
+instances <i>registers</i> with a corresponding <tt>MachinePassRegistry</tt>,
+the static destructor <i>unregisters</i>. Thus a pass that is statically linked
+in the tool will be registered at start up. A dynamically loaded pass will
+register on load and unregister at unload.</p>
+
+<!-- _______________________________________________________________________ -->
+<h3>
+ <a name="registering_existing">Using existing registries</a>
+</h3>
+
+<div>
+
+<p>There are predefined registries to track instruction scheduling
+(<tt>RegisterScheduler</tt>) and register allocation (<tt>RegisterRegAlloc</tt>)
+machine passes. Here we will describe how to <i>register</i> a register
+allocator machine pass.</p>
+
+<p>Implement your register allocator machine pass. In your register allocator
+<tt>.cpp</tt> file add the following include;</p>
+
+<div class="doc_code"><pre>
+#include "llvm/CodeGen/RegAllocRegistry.h"
+</pre></div>
+
+<p>Also in your register allocator .cpp file, define a creator function in the
+form; </p>
+
+<div class="doc_code"><pre>
+FunctionPass *createMyRegisterAllocator() {
+ return new MyRegisterAllocator();
+}
+</pre></div>
+
+<p>Note that the signature of this function should match the type of
+<tt>RegisterRegAlloc::FunctionPassCtor</tt>. In the same file add the
+"installing" declaration, in the form;</p>
+
+<div class="doc_code"><pre>
+static RegisterRegAlloc myRegAlloc("myregalloc",
+ "my register allocator help string",
+ createMyRegisterAllocator);
+</pre></div>
+
+<p>Note the two spaces prior to the help string produces a tidy result on the
+-help query.</p>
+
+<div class="doc_code"><pre>
+$ llc -help
+ ...
+ -regalloc - Register allocator to use (default=linearscan)
+ =linearscan - linear scan register allocator
+ =local - local register allocator
+ =simple - simple register allocator
+ =myregalloc - my register allocator help string
+ ...
+</pre></div>
+
+<p>And that's it. The user is now free to use <tt>-regalloc=myregalloc</tt> as
+an option. Registering instruction schedulers is similar except use the
+<tt>RegisterScheduler</tt> class. Note that the
+<tt>RegisterScheduler::FunctionPassCtor</tt> is significantly different from
+<tt>RegisterRegAlloc::FunctionPassCtor</tt>.</p>
+
+<p>To force the load/linking of your register allocator into the llc/lli tools,
+add your creator function's global declaration to "Passes.h" and add a "pseudo"
+call line to <tt>llvm/Codegen/LinkAllCodegenComponents.h</tt>.</p>
+
+</div>
+
+
+<!-- _______________________________________________________________________ -->
+<h3>
+ <a name="registering_new">Creating new registries</a>
+</h3>
+
+<div>
+
+<p>The easiest way to get started is to clone one of the existing registries; we
+recommend <tt>llvm/CodeGen/RegAllocRegistry.h</tt>. The key things to modify
+are the class name and the <tt>FunctionPassCtor</tt> type.</p>
+
+<p>Then you need to declare the registry. Example: if your pass registry is
+<tt>RegisterMyPasses</tt> then define;</p>
+
+<div class="doc_code"><pre>
+MachinePassRegistry RegisterMyPasses::Registry;
+</pre></div>
+
+<p>And finally, declare the command line option for your passes. Example:</p>
+
+<div class="doc_code"><pre>
+cl::opt&lt;RegisterMyPasses::FunctionPassCtor, false,
+ RegisterPassParser&lt;RegisterMyPasses&gt; &gt;
+MyPassOpt("mypass",
+ cl::init(&amp;createDefaultMyPass),
+ cl::desc("my pass option help"));
+</pre></div>
+
+<p>Here the command option is "mypass", with createDefaultMyPass as the default
+creator.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="debughints">Using GDB with dynamically loaded passes</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Unfortunately, using GDB with dynamically loaded passes is not as easy as it
+should be. First of all, you can't set a breakpoint in a shared object that has
+not been loaded yet, and second of all there are problems with inlined functions
+in shared objects. Here are some suggestions to debugging your pass with
+GDB.</p>
+
+<p>For sake of discussion, I'm going to assume that you are debugging a
+transformation invoked by <tt>opt</tt>, although nothing described here depends
+on that.</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="breakpoint">Setting a breakpoint in your pass</a>
+</h4>
+
+<div>
+
+<p>First thing you do is start <tt>gdb</tt> on the <tt>opt</tt> process:</p>
+
+<div class="doc_code"><pre>
+$ <b>gdb opt</b>
+GNU gdb 5.0
+Copyright 2000 Free Software Foundation, Inc.
+GDB is free software, covered by the GNU General Public License, and you are
+welcome to change it and/or distribute copies of it under certain conditions.
+Type "show copying" to see the conditions.
+There is absolutely no warranty for GDB. Type "show warranty" for details.
+This GDB was configured as "sparc-sun-solaris2.6"...
+(gdb)
+</pre></div>
+
+<p>Note that <tt>opt</tt> has a lot of debugging information in it, so it takes
+time to load. Be patient. Since we cannot set a breakpoint in our pass yet
+(the shared object isn't loaded until runtime), we must execute the process, and
+have it stop before it invokes our pass, but after it has loaded the shared
+object. The most foolproof way of doing this is to set a breakpoint in
+<tt>PassManager::run</tt> and then run the process with the arguments you
+want:</p>
+
+<div class="doc_code"><pre>
+(gdb) <b>break llvm::PassManager::run</b>
+Breakpoint 1 at 0x2413bc: file Pass.cpp, line 70.
+(gdb) <b>run test.bc -load $(LLVMTOP)/llvm/Debug+Asserts/lib/[libname].so -[passoption]</b>
+Starting program: opt test.bc -load $(LLVMTOP)/llvm/Debug+Asserts/lib/[libname].so -[passoption]
+Breakpoint 1, PassManager::run (this=0xffbef174, M=@0x70b298) at Pass.cpp:70
+70 bool PassManager::run(Module &amp;M) { return PM-&gt;run(M); }
+(gdb)
+</pre></div>
+
+<p>Once the <tt>opt</tt> stops in the <tt>PassManager::run</tt> method you are
+now free to set breakpoints in your pass so that you can trace through execution
+or do other standard debugging stuff.</p>
+
+</div>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="debugmisc">Miscellaneous Problems</a>
+</h4>
+
+<div>
+
+<p>Once you have the basics down, there are a couple of problems that GDB has,
+some with solutions, some without.</p>
+
+<ul>
+<li>Inline functions have bogus stack information. In general, GDB does a
+pretty good job getting stack traces and stepping through inline functions.
+When a pass is dynamically loaded however, it somehow completely loses this
+capability. The only solution I know of is to de-inline a function (move it
+from the body of a class to a .cpp file).</li>
+
+<li>Restarting the program breaks breakpoints. After following the information
+above, you have succeeded in getting some breakpoints planted in your pass. Nex
+thing you know, you restart the program (i.e., you type '<tt>run</tt>' again),
+and you start getting errors about breakpoints being unsettable. The only way I
+have found to "fix" this problem is to <tt>delete</tt> the breakpoints that are
+already set in your pass, run the program, and re-set the breakpoints once
+execution stops in <tt>PassManager::run</tt>.</li>
+
+</ul>
+
+<p>Hopefully these tips will help with common case debugging situations. If
+you'd like to contribute some tips of your own, just contact <a
+href="mailto:sabre@nondot.org">Chris</a>.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2>
+ <a name="future">Future extensions planned</a>
+</h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Although the LLVM Pass Infrastructure is very capable as it stands, and does
+some nifty stuff, there are things we'd like to add in the future. Here is
+where we are going:</p>
+
+<!-- _______________________________________________________________________ -->
+<h4>
+ <a name="SMP">Multithreaded LLVM</a>
+</h4>
+
+<div>
+
+<p>Multiple CPU machines are becoming more common and compilation can never be
+fast enough: obviously we should allow for a multithreaded compiler. Because of
+the semantics defined for passes above (specifically they cannot maintain state
+across invocations of their <tt>run*</tt> methods), a nice clean way to
+implement a multithreaded compiler would be for the <tt>PassManager</tt> class
+to create multiple instances of each pass object, and allow the separate
+instances to be hacking on different parts of the program at the same time.</p>
+
+<p>This implementation would prevent each of the passes from having to implement
+multithreaded constructs, requiring only the LLVM core to have locking in a few
+places (for global resources). Although this is a simple extension, we simply
+haven't had time (or multiprocessor machines, thus a reason) to implement this.
+Despite that, we have kept the LLVM passes SMP ready, and you should too.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+
+</body>
+</html>
diff --git a/docs/_static/lines.gif b/docs/_static/lines.gif
new file mode 100644
index 00000000000..88f491edc30
--- /dev/null
+++ b/docs/_static/lines.gif
Binary files differ
diff --git a/docs/_static/llvm.css b/docs/_static/llvm.css
new file mode 100644
index 00000000000..d7b5dae5a93
--- /dev/null
+++ b/docs/_static/llvm.css
@@ -0,0 +1,112 @@
+/*
+ * LLVM documentation style sheet
+ */
+
+/* Common styles */
+.body { color: black; background: white; margin: 0 0 0 0 }
+
+/* No borders on image links */
+a:link img, a:visited img { border-style: none }
+
+address img { float: right; width: 88px; height: 31px; }
+address { clear: right; }
+
+table { text-align: center; border: 2px solid black;
+ border-collapse: collapse; margin-top: 1em; margin-left: 1em;
+ margin-right: 1em; margin-bottom: 1em; }
+tr, td { border: 2px solid gray; padding: 4pt 4pt 2pt 2pt; }
+th { border: 2px solid gray; font-weight: bold; font-size: 105%;
+ background: url("lines.gif");
+ font-family: "Georgia,Palatino,Times,Roman,SanSerif";
+ text-align: center; vertical-align: middle; }
+/*
+ * Documentation
+ */
+/* Common for title and header */
+.doc_title, .doc_section, .doc_subsection, h1, h2, h3 {
+ color: black; background: url("lines.gif");
+ font-family: "Georgia,Palatino,Times,Roman,SanSerif"; font-weight: bold;
+ border-width: 1px;
+ border-style: solid none solid none;
+ text-align: center;
+ vertical-align: middle;
+ padding-left: 8pt;
+ padding-top: 1px;
+ padding-bottom: 2px
+}
+
+h1, .doc_title, .title { text-align: left; font-size: 25pt }
+
+h2, .doc_section { text-align: center; font-size: 22pt;
+ margin: 20pt 0pt 5pt 0pt; }
+
+h3, .doc_subsection { width: 75%;
+ text-align: left; font-size: 12pt;
+ padding: 4pt 4pt 4pt 4pt;
+ margin: 1.5em 0.5em 0.5em 0.5em }
+
+h4, .doc_subsubsection { margin: 2.0em 0.5em 0.5em 0.5em;
+ font-weight: bold; font-style: oblique;
+ border-bottom: 1px solid #999999; font-size: 12pt;
+ width: 75%; }
+
+.doc_author { text-align: left; font-weight: bold; padding-left: 20pt }
+.doc_text { text-align: left; padding-left: 20pt; padding-right: 10pt }
+
+.doc_footer { text-align: left; padding: 0 0 0 0 }
+
+.doc_hilite { color: blue; font-weight: bold; }
+
+.doc_table { text-align: center; width: 90%;
+ padding: 1px 1px 1px 1px; border: 1px; }
+
+.doc_warning { color: red; font-weight: bold }
+
+/* <div class="doc_code"> would use this class, and <div> adds more padding */
+.doc_code, .literal-block
+ { border: solid 1px gray; background: #eeeeee;
+ margin: 0 1em 0 1em;
+ padding: 0 1em 0 1em;
+ display: table;
+ }
+
+blockquote pre {
+ padding: 1em 2em 1em 1em;
+ border: solid 1px gray;
+ background: #eeeeee;
+ margin: 0 1em 0 1em;
+ display: table;
+}
+
+h2+div, h2+p {text-align: left; padding-left: 20pt; padding-right: 10pt;}
+h3+div, h3+p {text-align: left; padding-left: 20pt; padding-right: 10pt;}
+h4+div, h4+p {text-align: left; padding-left: 20pt; padding-right: 10pt;}
+
+/* It is preferrable to use <pre class="doc_code"> everywhere instead of the
+ * <div class="doc_code"><pre>...</ptr></div> construct.
+ *
+ * Once all docs use <pre> for code regions, this style can be merged with the
+ * one above, and we can drop the [pre] qualifier.
+ */
+pre.doc_code, .literal-block { padding: 1em 2em 1em 1em }
+
+.doc_notes { background: #fafafa; border: 1px solid #cecece;
+ display: table; padding: 0 1em 0 .1em }
+
+table.layout { text-align: left; border: none; border-collapse: collapse;
+ padding: 4px 4px 4px 4px; }
+tr.layout, td.layout, td.left, td.right
+ { border: none; padding: 4pt 4pt 2pt 2pt; vertical-align: top; }
+td.left { text-align: left }
+td.right { text-align: right }
+th.layout { border: none; font-weight: bold; font-size: 105%;
+ text-align: center; vertical-align: middle; }
+
+/* Left align table cell */
+.td_left { border: 2px solid gray; text-align: left; }
+
+/* ReST-specific */
+.title { margin-top: 0 }
+.topic-title{ display: none }
+div.contents ul { list-style-type: decimal }
+.toc-backref { color: black; text-decoration: none; }
diff --git a/docs/_templates/indexsidebar.html b/docs/_templates/indexsidebar.html
new file mode 100644
index 00000000000..416174279ce
--- /dev/null
+++ b/docs/_templates/indexsidebar.html
@@ -0,0 +1,7 @@
+{# This template defines sidebar which can be used to provide common links on
+ all documentation pages. #}
+
+<h3>Bugs</h3>
+
+<p>LLVM bugs should be reported to
+ <a href="http://llvm.org/bugs">Bugzilla</a>.</p>
diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html
new file mode 100644
index 00000000000..de5db5caf14
--- /dev/null
+++ b/docs/_templates/layout.html
@@ -0,0 +1,13 @@
+{% extends "!layout.html" %}
+
+{% block extrahead %}
+<style type="text/css">
+ table.right { float: right; margin-left: 20px; }
+ table.right td { border: 1px solid #ccc; }
+</style>
+{% endblock %}
+
+{% block rootrellink %}
+ <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
+ <li><a href="{{ pathto('index') }}">Documentation</a>&raquo;</li>
+{% endblock %}
diff --git a/docs/_themes/llvm-theme/layout.html b/docs/_themes/llvm-theme/layout.html
new file mode 100644
index 00000000000..746c2f56c82
--- /dev/null
+++ b/docs/_themes/llvm-theme/layout.html
@@ -0,0 +1,23 @@
+{#
+ sphinxdoc/layout.html
+ ~~~~~~~~~~~~~~~~~~~~~
+
+ Sphinx layout template for the sphinxdoc theme.
+
+ :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+#}
+{% extends "basic/layout.html" %}
+
+{% block relbar1 %}
+<div class="logo">
+ <a href="{{ pathto('index') }}">
+ <img src="{{pathto("_static/logo.png", 1) }}"
+ alt="LLVM Logo" width="250" height="88"/></a>
+</div>
+{{ super() }}
+{% endblock %}
+
+{# put the sidebar before the body #}
+{% block sidebar1 %}{{ sidebar() }}{% endblock %}
+{% block sidebar2 %}{% endblock %}
diff --git a/docs/_themes/llvm-theme/static/contents.png b/docs/_themes/llvm-theme/static/contents.png
new file mode 100644
index 00000000000..7fb82154a17
--- /dev/null
+++ b/docs/_themes/llvm-theme/static/contents.png
Binary files differ
diff --git a/docs/_themes/llvm-theme/static/llvm-theme.css b/docs/_themes/llvm-theme/static/llvm-theme.css
new file mode 100644
index 00000000000..f684d00ce43
--- /dev/null
+++ b/docs/_themes/llvm-theme/static/llvm-theme.css
@@ -0,0 +1,374 @@
+/*
+ * sphinxdoc.css_t
+ * ~~~~~~~~~~~~~~~
+ *
+ * Sphinx stylesheet -- sphinxdoc theme. Originally created by
+ * Armin Ronacher for Werkzeug.
+ *
+ * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
+ * :license: BSD, see LICENSE for details.
+ *
+ */
+
+@import url("basic.css");
+
+/* -- page layout ----------------------------------------------------------- */
+
+body {
+ font-family: 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva',
+ 'Verdana', sans-serif;
+ font-size: 14px;
+ letter-spacing: -0.01em;
+ line-height: 150%;
+ text-align: center;
+ background-color: #BFD1D4;
+ color: black;
+ padding: 0;
+ border: 1px solid #aaa;
+
+ margin: 0px 80px 0px 80px;
+ min-width: 740px;
+}
+
+div.logo {
+ background-color: white;
+ text-align: left;
+ padding: 10px 10px 15px 15px;
+}
+
+div.document {
+ background-color: white;
+ text-align: left;
+ background-image: url(contents.png);
+ background-repeat: repeat-x;
+}
+
+div.bodywrapper {
+ margin: 0 240px 0 0;
+ border-right: 1px solid #ccc;
+}
+
+div.body {
+ margin: 0;
+ padding: 0.5em 20px 20px 20px;
+}
+
+div.related {
+ font-size: 1em;
+}
+
+div.related ul {
+ background-image: url(navigation.png);
+ height: 2em;
+ border-top: 1px solid #ddd;
+ border-bottom: 1px solid #ddd;
+}
+
+div.related ul li {
+ margin: 0;
+ padding: 0;
+ height: 2em;
+ float: left;
+}
+
+div.related ul li.right {
+ float: right;
+ margin-right: 5px;
+}
+
+div.related ul li a {
+ margin: 0;
+ padding: 0 5px 0 5px;
+ line-height: 1.75em;
+ color: #EE9816;
+}
+
+div.related ul li a:hover {
+ color: #3CA8E7;
+}
+
+div.sphinxsidebarwrapper {
+ padding: 0;
+}
+
+div.sphinxsidebar {
+ margin: 0;
+ padding: 0.5em 15px 15px 0;
+ width: 210px;
+ float: right;
+ font-size: 1em;
+ text-align: left;
+}
+
+div.sphinxsidebar h3, div.sphinxsidebar h4 {
+ margin: 1em 0 0.5em 0;
+ font-size: 1em;
+ padding: 0.1em 0 0.1em 0.5em;
+ color: white;
+ border: 1px solid #86989B;
+ background-color: #AFC1C4;
+}
+
+div.sphinxsidebar h3 a {
+ color: white;
+}
+
+div.sphinxsidebar ul {
+ padding-left: 1.5em;
+ margin-top: 7px;
+ padding: 0;
+ line-height: 130%;
+}
+
+div.sphinxsidebar ul ul {
+ margin-left: 20px;
+}
+
+div.footer {
+ background-color: #E3EFF1;
+ color: #86989B;
+ padding: 3px 8px 3px 0;
+ clear: both;
+ font-size: 0.8em;
+ text-align: right;
+}
+
+div.footer a {
+ color: #86989B;
+ text-decoration: underline;
+}
+
+/* -- body styles ----------------------------------------------------------- */
+
+p {
+ margin: 0.8em 0 0.5em 0;
+}
+
+a {
+ color: #CA7900;
+ text-decoration: none;
+}
+
+a:hover {
+ color: #2491CF;
+}
+
+div.body p a{
+ text-decoration: underline;
+}
+
+h1 {
+ margin: 0;
+ padding: 0.7em 0 0.3em 0;
+ font-size: 1.5em;
+ color: #11557C;
+}
+
+h2 {
+ margin: 1.3em 0 0.2em 0;
+ font-size: 1.35em;
+ padding: 0;
+}
+
+h3 {
+ margin: 1em 0 -0.3em 0;
+ font-size: 1.2em;
+}
+
+h3 a:hover {
+ text-decoration: underline;
+}
+
+div.body h1 a, div.body h2 a, div.body h3 a, div.body h4 a, div.body h5 a, div.body h6 a {
+ color: black!important;
+}
+
+div.body h1,
+div.body h2,
+div.body h3,
+div.body h4,
+div.body h5,
+div.body h6 {
+ background-color: #f2f2f2;
+ font-weight: normal;
+ color: #20435c;
+ border-bottom: 1px solid #ccc;
+ margin: 20px -20px 10px -20px;
+ padding: 3px 0 3px 10px;
+}
+
+div.body h1 { margin-top: 0; font-size: 200%; }
+div.body h2 { font-size: 160%; }
+div.body h3 { font-size: 140%; }
+div.body h4 { font-size: 120%; }
+div.body h5 { font-size: 110%; }
+div.body h6 { font-size: 100%; }
+
+h1 a.anchor, h2 a.anchor, h3 a.anchor, h4 a.anchor, h5 a.anchor, h6 a.anchor {
+ display: none;
+ margin: 0 0 0 0.3em;
+ padding: 0 0.2em 0 0.2em;
+ color: #aaa!important;
+}
+
+h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor,
+h5:hover a.anchor, h6:hover a.anchor {
+ display: inline;
+}
+
+h1 a.anchor:hover, h2 a.anchor:hover, h3 a.anchor:hover, h4 a.anchor:hover,
+h5 a.anchor:hover, h6 a.anchor:hover {
+ color: #777;
+ background-color: #eee;
+}
+
+a.headerlink {
+ color: #c60f0f!important;
+ font-size: 1em;
+ margin-left: 6px;
+ padding: 0 4px 0 4px;
+ text-decoration: none!important;
+}
+
+a.headerlink:hover {
+ background-color: #ccc;
+ color: white!important;
+}
+
+cite, code, tt {
+ font-family: 'Consolas', 'Deja Vu Sans Mono',
+ 'Bitstream Vera Sans Mono', monospace;
+ font-size: 0.95em;
+ letter-spacing: 0.01em;
+}
+
+:not(a.reference) > tt {
+ background-color: #f2f2f2;
+ border-bottom: 1px solid #ddd;
+ color: #333;
+}
+
+tt.descname, tt.descclassname, tt.xref {
+ border: 0;
+}
+
+hr {
+ border: 1px solid #abc;
+ margin: 2em;
+}
+
+p a tt {
+ border: 0;
+ color: #CA7900;
+}
+
+p a tt:hover {
+ color: #2491CF;
+}
+
+a tt {
+ border: none;
+}
+
+pre {
+ font-family: 'Consolas', 'Deja Vu Sans Mono',
+ 'Bitstream Vera Sans Mono', monospace;
+ font-size: 0.95em;
+ letter-spacing: 0.015em;
+ line-height: 120%;
+ padding: 0.5em;
+ border: 1px solid #ccc;
+ background-color: #f8f8f8;
+}
+
+pre a {
+ color: inherit;
+ text-decoration: underline;
+}
+
+td.linenos pre {
+ padding: 0.5em 0;
+}
+
+div.quotebar {
+ background-color: #f8f8f8;
+ max-width: 250px;
+ float: right;
+ padding: 2px 7px;
+ border: 1px solid #ccc;
+}
+
+div.topic {
+ background-color: #f8f8f8;
+}
+
+table {
+ border-collapse: collapse;
+ margin: 0 -0.5em 0 -0.5em;
+}
+
+table td, table th {
+ padding: 0.2em 0.5em 0.2em 0.5em;
+}
+
+div.admonition, div.warning {
+ font-size: 0.9em;
+ margin: 1em 0 1em 0;
+ border: 1px solid #86989B;
+ background-color: #f7f7f7;
+ padding: 0;
+}
+
+div.admonition p, div.warning p {
+ margin: 0.5em 1em 0.5em 1em;
+ padding: 0;
+}
+
+div.admonition pre, div.warning pre {
+ margin: 0.4em 1em 0.4em 1em;
+}
+
+div.admonition p.admonition-title,
+div.warning p.admonition-title {
+ margin: 0;
+ padding: 0.1em 0 0.1em 0.5em;
+ color: white;
+ border-bottom: 1px solid #86989B;
+ font-weight: bold;
+ background-color: #AFC1C4;
+}
+
+div.warning {
+ border: 1px solid #940000;
+}
+
+div.warning p.admonition-title {
+ background-color: #CF0000;
+ border-bottom-color: #940000;
+}
+
+div.admonition ul, div.admonition ol,
+div.warning ul, div.warning ol {
+ margin: 0.1em 0.5em 0.5em 3em;
+ padding: 0;
+}
+
+div.versioninfo {
+ margin: 1em 0 0 0;
+ border: 1px solid #ccc;
+ background-color: #DDEAF0;
+ padding: 8px;
+ line-height: 1.3em;
+ font-size: 0.9em;
+}
+
+.viewcode-back {
+ font-family: 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva',
+ 'Verdana', sans-serif;
+}
+
+div.viewcode-block:target {
+ background-color: #f4debf;
+ border-top: 1px solid #ac9;
+ border-bottom: 1px solid #ac9;
+}
diff --git a/docs/_themes/llvm-theme/static/logo.png b/docs/_themes/llvm-theme/static/logo.png
new file mode 100644
index 00000000000..18d424c53c0
--- /dev/null
+++ b/docs/_themes/llvm-theme/static/logo.png
Binary files differ
diff --git a/docs/_themes/llvm-theme/static/navigation.png b/docs/_themes/llvm-theme/static/navigation.png
new file mode 100644
index 00000000000..1081dc1439f
--- /dev/null
+++ b/docs/_themes/llvm-theme/static/navigation.png
Binary files differ
diff --git a/docs/_themes/llvm-theme/theme.conf b/docs/_themes/llvm-theme/theme.conf
new file mode 100644
index 00000000000..573fd78aba9
--- /dev/null
+++ b/docs/_themes/llvm-theme/theme.conf
@@ -0,0 +1,4 @@
+[theme]
+inherit = basic
+stylesheet = llvm-theme.css
+pygments_style = friendly
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 00000000000..a1e9b5f6e28
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,252 @@
+# -*- coding: utf-8 -*-
+#
+# LLVM documentation build configuration file.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.intersphinx', 'sphinx.ext.todo']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'LLVM'
+copyright = u'2012, LLVM Project'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '3.2'
+# The full version, including alpha/beta/rc tags.
+release = '3.2'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+today_fmt = '%Y-%m-%d'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+show_authors = True
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'friendly'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = 'llvm-theme'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+html_theme_path = ["_themes"]
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+html_last_updated_fmt = '%Y-%m-%d'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+html_sidebars = {'index': 'indexsidebar.html'}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'LLVMdoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+ ('index', 'LLVM.tex', u'LLVM Documentation',
+ u'LLVM project', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = []
+
+# Automatically derive the list of man pages from the contents of the command
+# guide subdirectory.
+basedir = os.path.dirname(__file__)
+man_page_authors = "Maintained by The LLVM Team (http://llvm.org/)."
+command_guide_subpath = 'CommandGuide'
+command_guide_path = os.path.join(basedir, command_guide_subpath)
+for name in os.listdir(command_guide_path):
+ # Ignore non-ReST files and the index page.
+ if not name.endswith('.rst') or name in ('index.rst',):
+ continue
+
+ # Otherwise, automatically extract the description.
+ file_subpath = os.path.join(command_guide_subpath, name)
+ with open(os.path.join(command_guide_path, name)) as f:
+ title = f.readline().rstrip('\n')
+ header = f.readline().rstrip('\n')
+
+ if len(header) != len(title):
+ print >>sys.stderr, (
+ "error: invalid header in %r (does not match title)" % (
+ file_subpath,))
+ if ' - ' not in title:
+ print >>sys.stderr, (
+ ("error: invalid title in %r "
+ "(expected '<name> - <description>')") % (
+ file_subpath,))
+
+ # Split the name out of the title.
+ name,description = title.split(' - ', 1)
+ man_pages.append((file_subpath.replace('.rst',''), name,
+ description, man_page_authors, 1))
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+# FIXME: Define intersphinx configration.
+intersphinx_mapping = {}
diff --git a/docs/design_and_overview.rst b/docs/design_and_overview.rst
new file mode 100644
index 00000000000..ea684155e00
--- /dev/null
+++ b/docs/design_and_overview.rst
@@ -0,0 +1,36 @@
+.. _design_and_overview:
+
+LLVM Design & Overview
+======================
+
+.. toctree::
+ :hidden:
+
+ GetElementPtr
+
+* `LLVM Language Reference Manual <LangRef.html>`_
+
+ Defines the LLVM intermediate representation.
+
+* `Introduction to the LLVM Compiler <http://llvm.org/pubs/2008-10-04-ACAT-LLVM-Intro.html>`_
+
+ Presentation providing a users introduction to LLVM.
+
+* `Intro to LLVM <http://www.aosabook.org/en/llvm.html>`_
+
+ Book chapter providing a compiler hacker's introduction to LLVM.
+
+* `LLVM: A Compilation Framework forLifelong Program Analysis & Transformation
+ <http://llvm.org/pubs/2004-01-30-CGO-LLVM.html>`_
+
+ Design overview.
+
+* `LLVM: An Infrastructure for Multi-Stage Optimization
+ <http://llvm.org/pubs/2002-12-LattnerMSThesis.html>`_
+
+ More details (quite old now).
+
+* :ref:`gep`
+
+ Answers to some very frequent questions about LLVM's most frequently
+ misunderstood instruction.
diff --git a/docs/development_process.rst b/docs/development_process.rst
new file mode 100644
index 00000000000..4fc20b34129
--- /dev/null
+++ b/docs/development_process.rst
@@ -0,0 +1,30 @@
+.. _development_process:
+
+Development Process Documentation
+=================================
+
+.. toctree::
+ :hidden:
+
+ MakefileGuide
+ Projects
+
+* :ref:`projects`
+
+ How-to guide and templates for new projects that *use* the LLVM
+ infrastructure. The templates (directory organization, Makefiles, and test
+ tree) allow the project code to be located outside (or inside) the ``llvm/``
+ tree, while using LLVM header files and libraries.
+
+* `LLVMBuild Documentation <LLVMBuild.html>`_
+
+ Describes the LLVMBuild organization and files used by LLVM to specify
+ component descriptions.
+
+* :ref:`makefile_guide`
+
+ Describes how the LLVM makefiles work and how to use them.
+
+* `How To Release LLVM To The Public <HowToReleaseLLVM.html>`_
+
+ This is a guide to preparing LLVM releases. Most developers can ignore it.
diff --git a/docs/doxygen.cfg.in b/docs/doxygen.cfg.in
new file mode 100644
index 00000000000..20de0773f40
--- /dev/null
+++ b/docs/doxygen.cfg.in
@@ -0,0 +1,1632 @@
+# Doxyfile 1.7.1
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+# TAG = value [value, ...]
+# For lists items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
+# by quotes) that should identify the project.
+
+PROJECT_NAME = LLVM
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER = @PACKAGE_VERSION@
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY = @abs_top_builddir@/docs/doxygen
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH = ../..
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful is your file systems
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE = 2
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given extension.
+# Doxygen has a built-in mapping, but you can override or extend it using this
+# tag. The format is ext=language, where ext is a file extension, and language
+# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C,
+# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make
+# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C
+# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions
+# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
+
+EXTENSION_MAPPING =
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter
+# and setter methods for a property. Setting this option to YES (the default)
+# will make doxygen to replace the get and set methods by a property in the
+# documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING = YES
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT = NO
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
+# determine which symbols to keep in memory and which to flush to disk.
+# When the cache is full, less often used symbols will be written to disk.
+# For small to medium size projects (<1000 input files) the default value is
+# probably good enough. For larger projects a too small cache size can cause
+# doxygen to be busy swapping symbols to and from disk most of the time
+# causing a significant performance penality.
+# If the system has enough physical memory increasing the cache will improve the
+# performance by keeping more symbols in memory. Note that the value works on
+# a logarithmic scale so increasing the size by one will rougly double the
+# memory usage. The cache size is given by this formula:
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols
+
+SYMBOL_CACHE_SIZE = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC = YES
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespace are hidden.
+
+EXTRACT_ANON_NSPACES = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
+# will sort the (brief and detailed) documentation of class members so that
+# constructors and destructors are listed first. If set to NO (the default)
+# the constructors will appear in the respective orders defined by
+# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
+# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
+# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or define consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and defines in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES = YES
+
+# If the sources in your project are distributed over multiple directories
+# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
+# in the documentation. The default is NO.
+
+SHOW_DIRECTORIES = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.
+# This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. The create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option.
+# You can optionally specify a file name after the option, if omitted
+# DoxygenLayout.xml will be used as the name of the layout file.
+
+LAYOUT_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS = NO
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED = NO
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR = YES
+
+# This WARN_NO_PARAMDOC option can be abled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT =
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT = @abs_top_srcdir@/include \
+ @abs_top_srcdir@/lib \
+ @abs_top_srcdir@/docs/doxygen.intro
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
+
+FILE_PATTERNS =
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+
+EXCLUDE =
+
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
+# directories that are symbolic links (a Unix filesystem feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH = @abs_top_srcdir@/examples
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE = YES
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH = @abs_top_srcdir@/docs/img
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.
+# If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.
+# Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.
+# The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
+# is applied to all files.
+
+FILTER_PATTERNS =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER = YES
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C and C++ comments will always remain visible.
+
+STRIP_CODE_COMMENTS = NO
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = YES
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION = YES
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.
+# Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX = YES
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX = 4
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX = llvm::
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header.
+
+HTML_HEADER = @abs_top_srcdir@/docs/doxygen.header
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER = @abs_top_srcdir@/docs/doxygen.footer
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If the tag is left blank doxygen
+# will generate a default style sheet. Note that doxygen will try to copy
+# the style sheet file to the HTML output directory, so don't put your own
+# stylesheet in the HTML output directory as well, or it will be erased!
+
+HTML_STYLESHEET = @abs_top_srcdir@/docs/doxygen.css
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
+# Doxygen will adjust the colors in the stylesheet and background images
+# according to this color. Hue is specified as an angle on a colorwheel,
+# see http://en.wikipedia.org/wiki/Hue for more information.
+# For instance the value 0 represents red, 60 is yellow, 120 is green,
+# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
+# The allowed range is 0 to 359.
+
+HTML_COLORSTYLE_HUE = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
+# the colors in the HTML output. For a value of 0 the output will use
+# grayscales only. A value of 255 will produce the most vivid colors.
+
+HTML_COLORSTYLE_SAT = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
+# the luminance component of the colors in the HTML output. Values below
+# 100 gradually make the output lighter, whereas values above 100 make
+# the output darker. The value divided by 100 is the actual gamma applied,
+# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
+# and 100 does not change the gamma.
+
+HTML_COLORSTYLE_GAMMA = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP = YES
+
+# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
+# files or namespaces will be aligned in HTML using tables. If set to
+# NO a bullet list will be used.
+
+HTML_ALIGN_MEMBERS = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded. For this to work a browser that supports
+# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
+# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+
+HTML_DYNAMIC_SECTIONS = NO
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+
+GENERATE_DOCSET = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID = org.doxygen.Project
+
+# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+DOCSET_PUBLISHER_NAME = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
+# that can be used as input for Qt's qhelpgenerator to generate a
+# Qt Compressed Help (.qch) of the generated HTML documentation.
+
+GENERATE_QHP = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
+# add. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">
+# Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">
+# Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
+# the help appears.
+
+GENERATE_ECLIPSEHELP = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
+# top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it.
+
+DISABLE_INDEX = NO
+
+# This tag can be used to set the number of enum values (range [1..20])
+# that doxygen will group on one line in the generated HTML documentation.
+
+ENUM_VALUES_PER_LINE = 4
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+
+GENERATE_TREEVIEW = NO
+
+# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
+# and Class Hierarchy pages using a tree view instead of an ordered list.
+
+USE_INLINE_TREES = NO
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
+# links to external symbols imported via tag files in a separate window.
+
+EXT_LINKS_IN_WINDOW = NO
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are
+# not supported properly for IE 6.0, but are supported on all modern browsers.
+# Note that when changing this option you need to delete any form_*.png files
+# in the HTML output before the changes have effect.
+
+FORMULA_TRANSPARENT = YES
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box
+# for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using
+# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
+# (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE = NO
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a PHP enabled web server instead of at the web client
+# using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server
+# based approach is that it scales better to large projects and allows
+# full text search. The disadvances is that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT =
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, a4wide, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE = letter
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS = NO
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX = NO
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include
+# source code with syntax highlighting in the LaTeX output.
+# Note that which sources are shown also depends on other settings
+# such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT =
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT =
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION =
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_SCHEMA =
+
+# The XML_DTD tag can be used to specify an XML DTD,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_DTD =
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.
+# This is useful
+# if you want to understand what is going on.
+# On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# in the INCLUDE_PATH (see below) will be search if a #include is found.
+
+SEARCH_INCLUDES = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH = ../include
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition.
+
+EXPAND_AS_DEFINED =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all function-like macros that are alone
+# on a line, have an all uppercase name, and do not end with a semicolon. Such
+# function macros are typically used for boiler-plate code, and will confuse
+# the parser if not removed.
+
+SKIP_FUNCTION_MACROS = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles.
+# Optionally an initial location of the external documentation
+# can be added for each tagfile. The format of a tag file without
+# this location is as follows:
+#
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths or
+# URLs. If a location is present for each tag, the installdox tool
+# does not have to be run to correct the links.
+# Note that each tag file must have a unique name
+# (where the name does NOT include the path)
+# If a tag file is not located in the directory in which doxygen
+# is run, you must also specify the path to the tagfile here.
+
+TAGFILES =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS = YES
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option is superseded by the HAVE_DOT option below. This is only a
+# fallback. It is recommended to install and use dot, since it yields more
+# powerful graphs.
+
+CLASS_DIAGRAMS = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS = NO
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT = YES
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
+# allowed to run in parallel. When set to 0 (the default) doxygen will
+# base this on the number of processors available in the system. You can set it
+# explicitly to a value larger than 0 to get control over the balance
+# between CPU load and processing speed.
+
+DOT_NUM_THREADS = 0
+
+# By default doxygen will write a font called FreeSans.ttf to the output
+# directory and reference it in all dot files that doxygen generates. This
+# font does not include all possible unicode characters however, so when you need
+# these (or just want a differently looking font) you can specify the font name
+# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
+# which can be done by putting it in a standard location or by setting the
+# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
+# containing the font.
+
+DOT_FONTNAME = FreeSans
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE = 10
+
+# By default doxygen will tell dot to use the output directory to look for the
+# FreeSans.ttf font (which doxygen will put there itself). If you specify a
+# different font using DOT_FONTNAME you can set the path where dot
+# can find it using this tag.
+
+DOT_FONTPATH =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# the CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK = NO
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY = YES
+
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are png, jpg, or gif
+# If left blank png will be used.
+
+DOT_IMAGE_FORMAT = png
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH = @DOT@
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT = YES
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP = YES
diff --git a/docs/doxygen.css b/docs/doxygen.css
new file mode 100644
index 00000000000..83951f673db
--- /dev/null
+++ b/docs/doxygen.css
@@ -0,0 +1,408 @@
+BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV {
+ font-family: Verdana,Geneva,Arial,Helvetica,sans-serif;
+}
+BODY,TD {
+ font-size: 90%;
+}
+H1 {
+ text-align: center;
+ font-size: 140%;
+ font-weight: bold;
+}
+H2 {
+ font-size: 120%;
+ font-style: italic;
+}
+H3 {
+ font-size: 100%;
+}
+CAPTION { font-weight: bold }
+DIV.qindex {
+ width: 100%;
+ background-color: #eeeeff;
+ border: 1px solid #b0b0b0;
+ text-align: center;
+ margin: 2px;
+ padding: 2px;
+ line-height: 140%;
+}
+DIV.nav {
+ width: 100%;
+ background-color: #eeeeff;
+ border: 1px solid #b0b0b0;
+ text-align: center;
+ margin: 2px;
+ padding: 2px;
+ line-height: 140%;
+}
+DIV.navtab {
+ background-color: #eeeeff;
+ border: 1px solid #b0b0b0;
+ text-align: center;
+ margin: 2px;
+ margin-right: 15px;
+ padding: 2px;
+}
+TD.navtab {
+ font-size: 70%;
+}
+A.qindex {
+ text-decoration: none;
+ font-weight: bold;
+ color: #1A419D;
+}
+A.qindex:visited {
+ text-decoration: none;
+ font-weight: bold;
+ color: #1A419D
+}
+A.qindex:hover {
+ text-decoration: none;
+ background-color: #ddddff;
+}
+A.qindexHL {
+ text-decoration: none;
+ font-weight: bold;
+ background-color: #6666cc;
+ color: #ffffff;
+ border: 1px double #9295C2;
+}
+A.qindexHL:hover {
+ text-decoration: none;
+ background-color: #6666cc;
+ color: #ffffff;
+}
+A.qindexHL:visited {
+ text-decoration: none; background-color: #6666cc; color: #ffffff }
+A.el { text-decoration: none; font-weight: bold }
+A.elRef { font-weight: bold }
+A.code:link { text-decoration: none; font-weight: normal; color: #0000FF}
+A.code:visited { text-decoration: none; font-weight: normal; color: #0000FF}
+A.codeRef:link { font-weight: normal; color: #0000FF}
+A.codeRef:visited { font-weight: normal; color: #0000FF}
+A:hover { text-decoration: none; background-color: #f2f2ff }
+DL.el { margin-left: -1cm }
+.fragment {
+ font-family: Fixed, monospace;
+ font-size: 95%;
+}
+PRE.fragment {
+ border: 1px solid #CCCCCC;
+ background-color: #f5f5f5;
+ margin-top: 4px;
+ margin-bottom: 4px;
+ margin-left: 2px;
+ margin-right: 8px;
+ padding-left: 6px;
+ padding-right: 6px;
+ padding-top: 4px;
+ padding-bottom: 4px;
+}
+DIV.ah { background-color: black; font-weight: bold; color: #ffffff; margin-bottom: 3px; margin-top: 3px }
+TD.md { background-color: #F4F4FB; font-weight: bold; }
+TD.mdPrefix {
+ background-color: #F4F4FB;
+ color: #606060;
+ font-size: 80%;
+}
+TD.mdname1 { background-color: #F4F4FB; font-weight: bold; color: #602020; }
+TD.mdname { background-color: #F4F4FB; font-weight: bold; color: #602020; width: 600px; }
+DIV.groupHeader {
+ margin-left: 16px;
+ margin-top: 12px;
+ margin-bottom: 6px;
+ font-weight: bold;
+}
+DIV.groupText { margin-left: 16px; font-style: italic; font-size: 90% }
+BODY {
+ background: white;
+ color: black;
+ margin-right: 20px;
+ margin-left: 20px;
+}
+TD.indexkey {
+ background-color: #eeeeff;
+ font-weight: bold;
+ padding-right : 10px;
+ padding-top : 2px;
+ padding-left : 10px;
+ padding-bottom : 2px;
+ margin-left : 0px;
+ margin-right : 0px;
+ margin-top : 2px;
+ margin-bottom : 2px;
+ border: 1px solid #CCCCCC;
+}
+TD.indexvalue {
+ background-color: #eeeeff;
+ font-style: italic;
+ padding-right : 10px;
+ padding-top : 2px;
+ padding-left : 10px;
+ padding-bottom : 2px;
+ margin-left : 0px;
+ margin-right : 0px;
+ margin-top : 2px;
+ margin-bottom : 2px;
+ border: 1px solid #CCCCCC;
+}
+TR.memlist {
+ background-color: #f0f0f0;
+}
+P.formulaDsp { text-align: center; }
+IMG.formulaDsp { }
+IMG.formulaInl { vertical-align: middle; }
+SPAN.keyword { color: #008000 }
+SPAN.keywordtype { color: #604020 }
+SPAN.keywordflow { color: #e08000 }
+SPAN.comment { color: #800000 }
+SPAN.preprocessor { color: #806020 }
+SPAN.stringliteral { color: #002080 }
+SPAN.charliteral { color: #008080 }
+.mdTable {
+ border: 1px solid #868686;
+ background-color: #F4F4FB;
+}
+.mdRow {
+ padding: 8px 10px;
+}
+.mdescLeft {
+ padding: 0px 8px 4px 8px;
+ font-size: 80%;
+ font-style: italic;
+ background-color: #FAFAFA;
+ border-top: 1px none #E0E0E0;
+ border-right: 1px none #E0E0E0;
+ border-bottom: 1px none #E0E0E0;
+ border-left: 1px none #E0E0E0;
+ margin: 0px;
+}
+.mdescRight {
+ padding: 0px 8px 4px 8px;
+ font-size: 80%;
+ font-style: italic;
+ background-color: #FAFAFA;
+ border-top: 1px none #E0E0E0;
+ border-right: 1px none #E0E0E0;
+ border-bottom: 1px none #E0E0E0;
+ border-left: 1px none #E0E0E0;
+ margin: 0px;
+}
+.memItemLeft {
+ padding: 1px 0px 0px 8px;
+ margin: 4px;
+ border-top-width: 1px;
+ border-right-width: 1px;
+ border-bottom-width: 1px;
+ border-left-width: 1px;
+ border-top-color: #E0E0E0;
+ border-right-color: #E0E0E0;
+ border-bottom-color: #E0E0E0;
+ border-left-color: #E0E0E0;
+ border-top-style: solid;
+ border-right-style: none;
+ border-bottom-style: none;
+ border-left-style: none;
+ background-color: #FAFAFA;
+ font-size: 80%;
+}
+.memItemRight {
+ padding: 1px 8px 0px 8px;
+ margin: 4px;
+ border-top-width: 1px;
+ border-right-width: 1px;
+ border-bottom-width: 1px;
+ border-left-width: 1px;
+ border-top-color: #E0E0E0;
+ border-right-color: #E0E0E0;
+ border-bottom-color: #E0E0E0;
+ border-left-color: #E0E0E0;
+ border-top-style: solid;
+ border-right-style: none;
+ border-bottom-style: none;
+ border-left-style: none;
+ background-color: #FAFAFA;
+ font-size: 80%;
+}
+.memTemplItemLeft {
+ padding: 1px 0px 0px 8px;
+ margin: 4px;
+ border-top-width: 1px;
+ border-right-width: 1px;
+ border-bottom-width: 1px;
+ border-left-width: 1px;
+ border-top-color: #E0E0E0;
+ border-right-color: #E0E0E0;
+ border-bottom-color: #E0E0E0;
+ border-left-color: #E0E0E0;
+ border-top-style: none;
+ border-right-style: none;
+ border-bottom-style: none;
+ border-left-style: none;
+ background-color: #FAFAFA;
+ font-size: 80%;
+}
+.memTemplItemRight {
+ padding: 1px 8px 0px 8px;
+ margin: 4px;
+ border-top-width: 1px;
+ border-right-width: 1px;
+ border-bottom-width: 1px;
+ border-left-width: 1px;
+ border-top-color: #E0E0E0;
+ border-right-color: #E0E0E0;
+ border-bottom-color: #E0E0E0;
+ border-left-color: #E0E0E0;
+ border-top-style: none;
+ border-right-style: none;
+ border-bottom-style: none;
+ border-left-style: none;
+ background-color: #FAFAFA;
+ font-size: 80%;
+}
+.memTemplParams {
+ padding: 1px 0px 0px 8px;
+ margin: 4px;
+ border-top-width: 1px;
+ border-right-width: 1px;
+ border-bottom-width: 1px;
+ border-left-width: 1px;
+ border-top-color: #E0E0E0;
+ border-right-color: #E0E0E0;
+ border-bottom-color: #E0E0E0;
+ border-left-color: #E0E0E0;
+ border-top-style: solid;
+ border-right-style: none;
+ border-bottom-style: none;
+ border-left-style: none;
+ color: #606060;
+ background-color: #FAFAFA;
+ font-size: 80%;
+}
+.search { color: #003399;
+ font-weight: bold;
+}
+FORM.search {
+ margin-bottom: 0px;
+ margin-top: 0px;
+}
+INPUT.search { font-size: 75%;
+ color: #000080;
+ font-weight: normal;
+ background-color: #eeeeff;
+}
+TD.tiny { font-size: 75%;
+}
+a {
+ color: #252E78;
+}
+a:visited {
+ color: #3D2185;
+}
+.dirtab { padding: 4px;
+ border-collapse: collapse;
+ border: 1px solid #b0b0b0;
+}
+TH.dirtab { background: #eeeeff;
+ font-weight: bold;
+}
+HR { height: 1px;
+ border: none;
+ border-top: 1px solid black;
+}
+
+/*
+ * LLVM Modifications.
+ * Note: Everything above here is generated with "doxygen -w htlm" command. See
+ * "doxygen --help" for details. What follows are CSS overrides for LLVM
+ * specific formatting. We want to keep the above so it can be replaced with
+ * subsequent doxygen upgrades.
+ */
+
+.footer {
+ font-size: 80%;
+ font-weight: bold;
+ text-align: center;
+ vertical-align: middle;
+}
+.title {
+ font-size: 25pt;
+ color: black;
+ font-weight: bold;
+ border-width: 1px;
+ border-style: solid none solid none;
+ text-align: center;
+ vertical-align: middle;
+ padding-left: 8pt;
+ padding-top: 1px;
+ padding-bottom: 2px
+}
+A:link {
+ cursor: pointer;
+ text-decoration: none;
+ font-weight: bolder;
+}
+A:visited {
+ cursor: pointer;
+ text-decoration: underline;
+ font-weight: bolder;
+}
+A:hover {
+ cursor: pointer;
+ text-decoration: underline;
+ font-weight: bolder;
+}
+A:active {
+ cursor: pointer;
+ text-decoration: underline;
+ font-weight: bolder;
+ font-style: italic;
+}
+H1 {
+ text-align: center;
+ font-size: 140%;
+ font-weight: bold;
+}
+H2 {
+ font-size: 120%;
+ font-style: italic;
+}
+H3 {
+ font-size: 100%;
+}
+
+H2, H3 {
+ border-bottom: 2px solid;
+ margin-top: 2em;
+}
+
+A.qindex {}
+A.qindexRef {}
+A.el { text-decoration: none; font-weight: bold }
+A.elRef { font-weight: bold }
+A.code { text-decoration: none; font-weight: normal; color: #4444ee }
+A.codeRef { font-weight: normal; color: #4444ee }
+
+div.memitem {
+ border: 1px solid #999999;
+ margin-top: 1.0em;
+ margin-bottom: 1.0em;
+ -webkit-border-radius: 0.5em;
+ -webkit-box-shadow: 3px 3px 6px #777777;
+ -moz-border-radius: 0.5em;
+ -moz-box-shadow: black 3px 3px 3px;
+}
+
+div.memproto {
+ background-color: #E3E4E5;
+ padding: 0.25em 0.5em;
+ -webkit-border-top-left-radius: 0.5em;
+ -webkit-border-top-right-radius: 0.5em;
+ -moz-border-radius-topleft: 0.5em;
+ -moz-border-radius-topright: 0.5em;
+}
+
+div.memdoc {
+ padding-left: 1em;
+ padding-right: 1em;
+}
diff --git a/docs/doxygen.footer b/docs/doxygen.footer
new file mode 100644
index 00000000000..c492e7df6cb
--- /dev/null
+++ b/docs/doxygen.footer
@@ -0,0 +1,13 @@
+<hr>
+<p class="footer">
+Generated on $datetime for <a href="http://llvm.org/">$projectname</a> by
+<a href="http://www.doxygen.org"><img src="doxygen.png" alt="Doxygen"
+align="middle" border="0"/>$doxygenversion</a><br>
+Copyright &copy; 2003-2012 University of Illinois at Urbana-Champaign.
+All Rights Reserved.</p>
+
+<hr>
+<!--#include virtual="/attrib.incl" -->
+
+</body>
+</html>
diff --git a/docs/doxygen.header b/docs/doxygen.header
new file mode 100644
index 00000000000..56fb77fafdd
--- /dev/null
+++ b/docs/doxygen.header
@@ -0,0 +1,9 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<html><head>
+<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
+<meta name="keywords" content="LLVM,Low Level Virtual Machine,C++,doxygen,API,documentation"/>
+<meta name="description" content="C++ source code API documentation for LLVM."/>
+<title>LLVM: $title</title>
+<link href="doxygen.css" rel="stylesheet" type="text/css"/>
+</head><body>
+<p class="title">LLVM API Documentation</p>
diff --git a/docs/doxygen.intro b/docs/doxygen.intro
new file mode 100644
index 00000000000..699dadc27e8
--- /dev/null
+++ b/docs/doxygen.intro
@@ -0,0 +1,18 @@
+/// @mainpage LLVM
+///
+/// @section main_intro Introduction
+/// Welcome to LLVM.
+///
+/// This documentation describes the @b internal software that makes
+/// up LLVM, not the @b external use of LLVM. There are no instructions
+/// here on how to use LLVM, only the APIs that make up the software. For usage
+/// instructions, please see the programmer's guide or reference manual.
+///
+/// @section main_caveat Caveat
+/// This documentation is generated directly from the source code with doxygen.
+/// Since LLVM is constantly under active development, what you're about to
+/// read is out of date! However, it may still be useful since certain portions
+/// of LLVM are very stable.
+///
+/// @section main_changelog Change Log
+/// - Original content written 12/30/2003 by Reid Spencer
diff --git a/docs/index.rst b/docs/index.rst
new file mode 100644
index 00000000000..53d3e7c01b7
--- /dev/null
+++ b/docs/index.rst
@@ -0,0 +1,70 @@
+.. _contents:
+
+Overview
+========
+
+.. warning::
+
+ If you are using a released version of LLVM, see `the download page
+ <http://llvm.org/releases/>`_ to find your documentation.
+
+The LLVM compiler infrastructure supports a wide range of projects, from
+industrial strength compilers to specialized JIT applications to small
+research projects.
+
+Similarly, documentation is broken down into several high-level groupings
+targeted at different audiences:
+
+ * **Design & Overview**
+
+ Several introductory papers and presentations are available at
+ :ref:`design_and_overview`.
+
+ * **Publications**
+
+ The list of `publications <http://llvm.org/pubs>`_ based on LLVM.
+
+ * **User Guides**
+
+ Those new to the LLVM system should first vist the :ref:`userguides`.
+
+ NOTE: If you are a user who is only interested in using LLVM-based
+ compilers, you should look into `Clang <http://clang.llvm.org>`_ or
+ `DragonEgg <http://dragonegg.llvm.org>`_ instead. The documentation here is
+ intended for users who have a need to work with the intermediate LLVM
+ representation.
+
+ * **API Clients**
+
+ Developers of applications which use LLVM as a library should visit the
+ :ref:`programming`.
+
+ * **Subsystems**
+
+ API clients and LLVM developers may be interested in the
+ :ref:`subsystems` documentation.
+
+ * **Development Process**
+
+ Additional documentation on the LLVM project can be found at
+ :ref:`development_process`.
+
+ * **Mailing Lists**
+
+ For more information, consider consulting the LLVM :ref:`mailing_lists`.
+
+.. toctree::
+ :maxdepth: 2
+
+ design_and_overview
+ userguides
+ programming
+ subsystems
+ development_process
+ mailing_lists
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`search`
diff --git a/docs/mailing_lists.rst b/docs/mailing_lists.rst
new file mode 100644
index 00000000000..106f1da48f8
--- /dev/null
+++ b/docs/mailing_lists.rst
@@ -0,0 +1,35 @@
+.. _mailing_lists:
+
+Mailing Lists
+=============
+
+ * `LLVM Announcements List
+ <http://lists.cs.uiuc.edu/mailman/listinfo/llvm-announce>`_
+
+ This is a low volume list that provides important announcements regarding
+ LLVM. It gets email about once a month.
+
+ * `Developer's List <http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev>`_
+
+ This list is for people who want to be included in technical discussions of
+ LLVM. People post to this list when they have questions about writing code
+ for or using the LLVM tools. It is relatively low volume.
+
+ * `Bugs & Patches Archive <http://lists.cs.uiuc.edu/pipermail/llvmbugs/>`_
+
+ This list gets emailed every time a bug is opened and closed, and when people
+ submit patches to be included in LLVM. It is higher volume than the LLVMdev
+ list.
+
+ * `Commits Archive <http://lists.cs.uiuc.edu/pipermail/llvm-commits/>`_
+
+ This list contains all commit messages that are made when LLVM developers
+ commit code changes to the repository. It is useful for those who want to
+ stay on the bleeding edge of LLVM development. This list is very high volume.
+
+ * `Test Results Archive
+ <http://lists.cs.uiuc.edu/pipermail/llvm-testresults/>`_
+
+ A message is automatically sent to this list by every active nightly tester
+ when it completes. As such, this list gets email several times each day,
+ making it a high volume list.
diff --git a/docs/make.bat b/docs/make.bat
new file mode 100644
index 00000000000..8dfec039fdc
--- /dev/null
+++ b/docs/make.bat
@@ -0,0 +1,190 @@
+@ECHO OFF
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set BUILDDIR=_build
+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
+set I18NSPHINXOPTS=%SPHINXOPTS% .
+if NOT "%PAPER%" == "" (
+ set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
+ set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
+)
+
+if "%1" == "" goto help
+
+if "%1" == "help" (
+ :help
+ echo.Please use `make ^<target^>` where ^<target^> is one of
+ echo. html to make standalone HTML files
+ echo. dirhtml to make HTML files named index.html in directories
+ echo. singlehtml to make a single large HTML file
+ echo. pickle to make pickle files
+ echo. json to make JSON files
+ echo. htmlhelp to make HTML files and a HTML help project
+ echo. qthelp to make HTML files and a qthelp project
+ echo. devhelp to make HTML files and a Devhelp project
+ echo. epub to make an epub
+ echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
+ echo. text to make text files
+ echo. man to make manual pages
+ echo. texinfo to make Texinfo files
+ echo. gettext to make PO message catalogs
+ echo. changes to make an overview over all changed/added/deprecated items
+ echo. linkcheck to check all external links for integrity
+ echo. doctest to run all doctests embedded in the documentation if enabled
+ goto end
+)
+
+if "%1" == "clean" (
+ for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
+ del /q /s %BUILDDIR%\*
+ goto end
+)
+
+if "%1" == "html" (
+ %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/html.
+ goto end
+)
+
+if "%1" == "dirhtml" (
+ %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
+ goto end
+)
+
+if "%1" == "singlehtml" (
+ %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
+ goto end
+)
+
+if "%1" == "pickle" (
+ %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can process the pickle files.
+ goto end
+)
+
+if "%1" == "json" (
+ %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can process the JSON files.
+ goto end
+)
+
+if "%1" == "htmlhelp" (
+ %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can run HTML Help Workshop with the ^
+.hhp project file in %BUILDDIR%/htmlhelp.
+ goto end
+)
+
+if "%1" == "qthelp" (
+ %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can run "qcollectiongenerator" with the ^
+.qhcp project file in %BUILDDIR%/qthelp, like this:
+ echo.^> qcollectiongenerator %BUILDDIR%\qthelp\llvm.qhcp
+ echo.To view the help file:
+ echo.^> assistant -collectionFile %BUILDDIR%\qthelp\llvm.ghc
+ goto end
+)
+
+if "%1" == "devhelp" (
+ %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished.
+ goto end
+)
+
+if "%1" == "epub" (
+ %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The epub file is in %BUILDDIR%/epub.
+ goto end
+)
+
+if "%1" == "latex" (
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
+ goto end
+)
+
+if "%1" == "text" (
+ %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The text files are in %BUILDDIR%/text.
+ goto end
+)
+
+if "%1" == "man" (
+ %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The manual pages are in %BUILDDIR%/man.
+ goto end
+)
+
+if "%1" == "texinfo" (
+ %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
+ goto end
+)
+
+if "%1" == "gettext" (
+ %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
+ goto end
+)
+
+if "%1" == "changes" (
+ %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.The overview file is in %BUILDDIR%/changes.
+ goto end
+)
+
+if "%1" == "linkcheck" (
+ %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Link check complete; look for any errors in the above output ^
+or in %BUILDDIR%/linkcheck/output.txt.
+ goto end
+)
+
+if "%1" == "doctest" (
+ %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Testing of doctests in the sources finished, look at the ^
+results in %BUILDDIR%/doctest/output.txt.
+ goto end
+)
+
+:end
diff --git a/docs/programming.rst b/docs/programming.rst
new file mode 100644
index 00000000000..27e43014ee3
--- /dev/null
+++ b/docs/programming.rst
@@ -0,0 +1,40 @@
+.. _programming:
+
+Programming Documentation
+=========================
+
+.. toctree::
+ :hidden:
+
+ CodingStandards
+ CommandLine
+
+* `LLVM Language Reference Manual <LangRef.html>`_
+
+ Defines the LLVM intermediate representation and the assembly form of the
+ different nodes.
+
+* `The LLVM Programmers Manual <ProgrammersManual.html>`_
+
+ Introduction to the general layout of the LLVM sourcebase, important classes
+ and APIs, and some tips & tricks.
+
+* :ref:`commandline`
+
+ Provides information on using the command line parsing library.
+
+* :ref:`coding_standards`
+
+ Details the LLVM coding standards and provides useful information on writing
+ efficient C++ code.
+
+* `Extending LLVM <ExtendingLLVM.html>`_
+
+ Look here to see how to add instructions and intrinsics to LLVM.
+
+* `Doxygen generated documentation <http://llvm.org/doxygen/>`_
+
+ (`classes <http://llvm.org/doxygen/inherits.html>`_)
+ (`tarball <http://llvm.org/doxygen/doxygen.tar.gz>`_)
+
+* `ViewVC Repository Browser <http://llvm.org/viewvc/>`_
diff --git a/docs/re_format.7 b/docs/re_format.7
new file mode 100644
index 00000000000..0c0928716f4
--- /dev/null
+++ b/docs/re_format.7
@@ -0,0 +1,756 @@
+.\" $OpenBSD: re_format.7,v 1.14 2007/05/31 19:19:30 jmc Exp $
+.\"
+.\" Copyright (c) 1997, Phillip F Knaack. All rights reserved.
+.\"
+.\" Copyright (c) 1992, 1993, 1994 Henry Spencer.
+.\" Copyright (c) 1992, 1993, 1994
+.\" The Regents of the University of California. All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Henry Spencer.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\" 3. Neither the name of the University nor the names of its contributors
+.\" may be used to endorse or promote products derived from this software
+.\" without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" @(#)re_format.7 8.3 (Berkeley) 3/20/94
+.\"
+.Dd $Mdocdate: May 31 2007 $
+.Dt RE_FORMAT 7
+.Os
+.Sh NAME
+.Nm re_format
+.Nd POSIX regular expressions
+.Sh DESCRIPTION
+Regular expressions (REs),
+as defined in
+.St -p1003.1-2004 ,
+come in two forms:
+basic regular expressions
+(BREs)
+and extended regular expressions
+(EREs).
+Both forms of regular expressions are supported
+by the interfaces described in
+.Xr regex 3 .
+Applications dealing with regular expressions
+may use one or the other form
+(or indeed both).
+For example,
+.Xr ed 1
+uses BREs,
+whilst
+.Xr egrep 1
+talks EREs.
+Consult the manual page for the specific application to find out which
+it uses.
+.Pp
+POSIX leaves some aspects of RE syntax and semantics open;
+.Sq **
+marks decisions on these aspects that
+may not be fully portable to other POSIX implementations.
+.Pp
+This manual page first describes regular expressions in general,
+specifically extended regular expressions,
+and then discusses differences between them and basic regular expressions.
+.Sh EXTENDED REGULAR EXPRESSIONS
+An ERE is one** or more non-empty**
+.Em branches ,
+separated by
+.Sq \*(Ba .
+It matches anything that matches one of the branches.
+.Pp
+A branch is one** or more
+.Em pieces ,
+concatenated.
+It matches a match for the first, followed by a match for the second, etc.
+.Pp
+A piece is an
+.Em atom
+possibly followed by a single**
+.Sq * ,
+.Sq + ,
+.Sq ?\& ,
+or
+.Em bound .
+An atom followed by
+.Sq *
+matches a sequence of 0 or more matches of the atom.
+An atom followed by
+.Sq +
+matches a sequence of 1 or more matches of the atom.
+An atom followed by
+.Sq ?\&
+matches a sequence of 0 or 1 matches of the atom.
+.Pp
+A bound is
+.Sq {
+followed by an unsigned decimal integer,
+possibly followed by
+.Sq ,\&
+possibly followed by another unsigned decimal integer,
+always followed by
+.Sq } .
+The integers must lie between 0 and
+.Dv RE_DUP_MAX
+(255**) inclusive,
+and if there are two of them, the first may not exceed the second.
+An atom followed by a bound containing one integer
+.Ar i
+and no comma matches
+a sequence of exactly
+.Ar i
+matches of the atom.
+An atom followed by a bound
+containing one integer
+.Ar i
+and a comma matches
+a sequence of
+.Ar i
+or more matches of the atom.
+An atom followed by a bound
+containing two integers
+.Ar i
+and
+.Ar j
+matches a sequence of
+.Ar i
+through
+.Ar j
+(inclusive) matches of the atom.
+.Pp
+An atom is a regular expression enclosed in
+.Sq ()
+(matching a part of the regular expression),
+an empty set of
+.Sq ()
+(matching the null string)**,
+a
+.Em bracket expression
+(see below),
+.Sq .\&
+(matching any single character),
+.Sq ^
+(matching the null string at the beginning of a line),
+.Sq $
+(matching the null string at the end of a line),
+a
+.Sq \e
+followed by one of the characters
+.Sq ^.[$()|*+?{\e
+(matching that character taken as an ordinary character),
+a
+.Sq \e
+followed by any other character**
+(matching that character taken as an ordinary character,
+as if the
+.Sq \e
+had not been present**),
+or a single character with no other significance (matching that character).
+A
+.Sq {
+followed by a character other than a digit is an ordinary character,
+not the beginning of a bound**.
+It is illegal to end an RE with
+.Sq \e .
+.Pp
+A bracket expression is a list of characters enclosed in
+.Sq [] .
+It normally matches any single character from the list (but see below).
+If the list begins with
+.Sq ^ ,
+it matches any single character
+.Em not
+from the rest of the list
+(but see below).
+If two characters in the list are separated by
+.Sq - ,
+this is shorthand for the full
+.Em range
+of characters between those two (inclusive) in the
+collating sequence, e.g.\&
+.Sq [0-9]
+in ASCII matches any decimal digit.
+It is illegal** for two ranges to share an endpoint, e.g.\&
+.Sq a-c-e .
+Ranges are very collating-sequence-dependent,
+and portable programs should avoid relying on them.
+.Pp
+To include a literal
+.Sq ]\&
+in the list, make it the first character
+(following a possible
+.Sq ^ ) .
+To include a literal
+.Sq - ,
+make it the first or last character,
+or the second endpoint of a range.
+To use a literal
+.Sq -
+as the first endpoint of a range,
+enclose it in
+.Sq [.
+and
+.Sq .]
+to make it a collating element (see below).
+With the exception of these and some combinations using
+.Sq [
+(see next paragraphs),
+all other special characters, including
+.Sq \e ,
+lose their special significance within a bracket expression.
+.Pp
+Within a bracket expression, a collating element
+(a character,
+a multi-character sequence that collates as if it were a single character,
+or a collating-sequence name for either)
+enclosed in
+.Sq [.
+and
+.Sq .]
+stands for the sequence of characters of that collating element.
+The sequence is a single element of the bracket expression's list.
+A bracket expression containing a multi-character collating element
+can thus match more than one character,
+e.g. if the collating sequence includes a
+.Sq ch
+collating element,
+then the RE
+.Sq [[.ch.]]*c
+matches the first five characters of
+.Sq chchcc .
+.Pp
+Within a bracket expression, a collating element enclosed in
+.Sq [=
+and
+.Sq =]
+is an equivalence class, standing for the sequences of characters
+of all collating elements equivalent to that one, including itself.
+(If there are no other equivalent collating elements,
+the treatment is as if the enclosing delimiters were
+.Sq [.
+and
+.Sq .] . )
+For example, if
+.Sq x
+and
+.Sq y
+are the members of an equivalence class,
+then
+.Sq [[=x=]] ,
+.Sq [[=y=]] ,
+and
+.Sq [xy]
+are all synonymous.
+An equivalence class may not** be an endpoint of a range.
+.Pp
+Within a bracket expression, the name of a
+.Em character class
+enclosed
+in
+.Sq [:
+and
+.Sq :]
+stands for the list of all characters belonging to that class.
+Standard character class names are:
+.Bd -literal -offset indent
+alnum digit punct
+alpha graph space
+blank lower upper
+cntrl print xdigit
+.Ed
+.Pp
+These stand for the character classes defined in
+.Xr ctype 3 .
+A locale may provide others.
+A character class may not be used as an endpoint of a range.
+.Pp
+There are two special cases** of bracket expressions:
+the bracket expressions
+.Sq [[:<:]]
+and
+.Sq [[:>:]]
+match the null string at the beginning and end of a word, respectively.
+A word is defined as a sequence of
+characters starting and ending with a word character
+which is neither preceded nor followed by
+word characters.
+A word character is an
+.Em alnum
+character (as defined by
+.Xr ctype 3 )
+or an underscore.
+This is an extension,
+compatible with but not specified by POSIX,
+and should be used with
+caution in software intended to be portable to other systems.
+.Pp
+In the event that an RE could match more than one substring of a given
+string,
+the RE matches the one starting earliest in the string.
+If the RE could match more than one substring starting at that point,
+it matches the longest.
+Subexpressions also match the longest possible substrings, subject to
+the constraint that the whole match be as long as possible,
+with subexpressions starting earlier in the RE taking priority over
+ones starting later.
+Note that higher-level subexpressions thus take priority over
+their lower-level component subexpressions.
+.Pp
+Match lengths are measured in characters, not collating elements.
+A null string is considered longer than no match at all.
+For example,
+.Sq bb*
+matches the three middle characters of
+.Sq abbbc ;
+.Sq (wee|week)(knights|nights)
+matches all ten characters of
+.Sq weeknights ;
+when
+.Sq (.*).*
+is matched against
+.Sq abc ,
+the parenthesized subexpression matches all three characters;
+and when
+.Sq (a*)*
+is matched against
+.Sq bc ,
+both the whole RE and the parenthesized subexpression match the null string.
+.Pp
+If case-independent matching is specified,
+the effect is much as if all case distinctions had vanished from the
+alphabet.
+When an alphabetic that exists in multiple cases appears as an
+ordinary character outside a bracket expression, it is effectively
+transformed into a bracket expression containing both cases,
+e.g.\&
+.Sq x
+becomes
+.Sq [xX] .
+When it appears inside a bracket expression,
+all case counterparts of it are added to the bracket expression,
+so that, for example,
+.Sq [x]
+becomes
+.Sq [xX]
+and
+.Sq [^x]
+becomes
+.Sq [^xX] .
+.Pp
+No particular limit is imposed on the length of REs**.
+Programs intended to be portable should not employ REs longer
+than 256 bytes,
+as an implementation can refuse to accept such REs and remain
+POSIX-compliant.
+.Pp
+The following is a list of extended regular expressions:
+.Bl -tag -width Ds
+.It Ar c
+Any character
+.Ar c
+not listed below matches itself.
+.It \e Ns Ar c
+Any backslash-escaped character
+.Ar c
+matches itself.
+.It \&.
+Matches any single character that is not a newline
+.Pq Sq \en .
+.It Bq Ar char-class
+Matches any single character in
+.Ar char-class .
+To include a
+.Ql \&]
+in
+.Ar char-class ,
+it must be the first character.
+A range of characters may be specified by separating the end characters
+of the range with a
+.Ql - ;
+e.g.\&
+.Ar a-z
+specifies the lower case characters.
+The following literal expressions can also be used in
+.Ar char-class
+to specify sets of characters:
+.Bd -unfilled -offset indent
+[:alnum:] [:cntrl:] [:lower:] [:space:]
+[:alpha:] [:digit:] [:print:] [:upper:]
+[:blank:] [:graph:] [:punct:] [:xdigit:]
+.Ed
+.Pp
+If
+.Ql -
+appears as the first or last character of
+.Ar char-class ,
+then it matches itself.
+All other characters in
+.Ar char-class
+match themselves.
+.Pp
+Patterns in
+.Ar char-class
+of the form
+.Eo [.
+.Ar col-elm
+.Ec .]\&
+or
+.Eo [=
+.Ar col-elm
+.Ec =]\& ,
+where
+.Ar col-elm
+is a collating element, are interpreted according to
+.Xr setlocale 3
+.Pq not currently supported .
+.It Bq ^ Ns Ar char-class
+Matches any single character, other than newline, not in
+.Ar char-class .
+.Ar char-class
+is defined as above.
+.It ^
+If
+.Sq ^
+is the first character of a regular expression, then it
+anchors the regular expression to the beginning of a line.
+Otherwise, it matches itself.
+.It $
+If
+.Sq $
+is the last character of a regular expression,
+it anchors the regular expression to the end of a line.
+Otherwise, it matches itself.
+.It [[:<:]]
+Anchors the single character regular expression or subexpression
+immediately following it to the beginning of a word.
+.It [[:>:]]
+Anchors the single character regular expression or subexpression
+immediately following it to the end of a word.
+.It Pq Ar re
+Defines a subexpression
+.Ar re .
+Any set of characters enclosed in parentheses
+matches whatever the set of characters without parentheses matches
+(that is a long-winded way of saying the constructs
+.Sq (re)
+and
+.Sq re
+match identically).
+.It *
+Matches the single character regular expression or subexpression
+immediately preceding it zero or more times.
+If
+.Sq *
+is the first character of a regular expression or subexpression,
+then it matches itself.
+The
+.Sq *
+operator sometimes yields unexpected results.
+For example, the regular expression
+.Ar b*
+matches the beginning of the string
+.Qq abbb
+(as opposed to the substring
+.Qq bbb ) ,
+since a null match is the only leftmost match.
+.It +
+Matches the singular character regular expression
+or subexpression immediately preceding it
+one or more times.
+.It ?
+Matches the singular character regular expression
+or subexpression immediately preceding it
+0 or 1 times.
+.Sm off
+.It Xo
+.Pf { Ar n , m No }\ \&
+.Pf { Ar n , No }\ \&
+.Pf { Ar n No }
+.Xc
+.Sm on
+Matches the single character regular expression or subexpression
+immediately preceding it at least
+.Ar n
+and at most
+.Ar m
+times.
+If
+.Ar m
+is omitted, then it matches at least
+.Ar n
+times.
+If the comma is also omitted, then it matches exactly
+.Ar n
+times.
+.It \*(Ba
+Used to separate patterns.
+For example,
+the pattern
+.Sq cat\*(Badog
+matches either
+.Sq cat
+or
+.Sq dog .
+.El
+.Sh BASIC REGULAR EXPRESSIONS
+Basic regular expressions differ in several respects:
+.Bl -bullet -offset 3n
+.It
+.Sq \*(Ba ,
+.Sq + ,
+and
+.Sq ?\&
+are ordinary characters and there is no equivalent
+for their functionality.
+.It
+The delimiters for bounds are
+.Sq \e{
+and
+.Sq \e} ,
+with
+.Sq {
+and
+.Sq }
+by themselves ordinary characters.
+.It
+The parentheses for nested subexpressions are
+.Sq \e(
+and
+.Sq \e) ,
+with
+.Sq (
+and
+.Sq )\&
+by themselves ordinary characters.
+.It
+.Sq ^
+is an ordinary character except at the beginning of the
+RE or** the beginning of a parenthesized subexpression.
+.It
+.Sq $
+is an ordinary character except at the end of the
+RE or** the end of a parenthesized subexpression.
+.It
+.Sq *
+is an ordinary character if it appears at the beginning of the
+RE or the beginning of a parenthesized subexpression
+(after a possible leading
+.Sq ^ ) .
+.It
+Finally, there is one new type of atom, a
+.Em back-reference :
+.Sq \e
+followed by a non-zero decimal digit
+.Ar d
+matches the same sequence of characters matched by the
+.Ar d Ns th
+parenthesized subexpression
+(numbering subexpressions by the positions of their opening parentheses,
+left to right),
+so that, for example,
+.Sq \e([bc]\e)\e1
+matches
+.Sq bb\&
+or
+.Sq cc
+but not
+.Sq bc .
+.El
+.Pp
+The following is a list of basic regular expressions:
+.Bl -tag -width Ds
+.It Ar c
+Any character
+.Ar c
+not listed below matches itself.
+.It \e Ns Ar c
+Any backslash-escaped character
+.Ar c ,
+except for
+.Sq { ,
+.Sq } ,
+.Sq \&( ,
+and
+.Sq \&) ,
+matches itself.
+.It \&.
+Matches any single character that is not a newline
+.Pq Sq \en .
+.It Bq Ar char-class
+Matches any single character in
+.Ar char-class .
+To include a
+.Ql \&]
+in
+.Ar char-class ,
+it must be the first character.
+A range of characters may be specified by separating the end characters
+of the range with a
+.Ql - ;
+e.g.\&
+.Ar a-z
+specifies the lower case characters.
+The following literal expressions can also be used in
+.Ar char-class
+to specify sets of characters:
+.Bd -unfilled -offset indent
+[:alnum:] [:cntrl:] [:lower:] [:space:]
+[:alpha:] [:digit:] [:print:] [:upper:]
+[:blank:] [:graph:] [:punct:] [:xdigit:]
+.Ed
+.Pp
+If
+.Ql -
+appears as the first or last character of
+.Ar char-class ,
+then it matches itself.
+All other characters in
+.Ar char-class
+match themselves.
+.Pp
+Patterns in
+.Ar char-class
+of the form
+.Eo [.
+.Ar col-elm
+.Ec .]\&
+or
+.Eo [=
+.Ar col-elm
+.Ec =]\& ,
+where
+.Ar col-elm
+is a collating element, are interpreted according to
+.Xr setlocale 3
+.Pq not currently supported .
+.It Bq ^ Ns Ar char-class
+Matches any single character, other than newline, not in
+.Ar char-class .
+.Ar char-class
+is defined as above.
+.It ^
+If
+.Sq ^
+is the first character of a regular expression, then it
+anchors the regular expression to the beginning of a line.
+Otherwise, it matches itself.
+.It $
+If
+.Sq $
+is the last character of a regular expression,
+it anchors the regular expression to the end of a line.
+Otherwise, it matches itself.
+.It [[:<:]]
+Anchors the single character regular expression or subexpression
+immediately following it to the beginning of a word.
+.It [[:>:]]
+Anchors the single character regular expression or subexpression
+immediately following it to the end of a word.
+.It \e( Ns Ar re Ns \e)
+Defines a subexpression
+.Ar re .
+Subexpressions may be nested.
+A subsequent backreference of the form
+.Pf \e Ns Ar n ,
+where
+.Ar n
+is a number in the range [1,9], expands to the text matched by the
+.Ar n Ns th
+subexpression.
+For example, the regular expression
+.Ar \e(.*\e)\e1
+matches any string consisting of identical adjacent substrings.
+Subexpressions are ordered relative to their left delimiter.
+.It *
+Matches the single character regular expression or subexpression
+immediately preceding it zero or more times.
+If
+.Sq *
+is the first character of a regular expression or subexpression,
+then it matches itself.
+The
+.Sq *
+operator sometimes yields unexpected results.
+For example, the regular expression
+.Ar b*
+matches the beginning of the string
+.Qq abbb
+(as opposed to the substring
+.Qq bbb ) ,
+since a null match is the only leftmost match.
+.Sm off
+.It Xo
+.Pf \e{ Ar n , m No \e}\ \&
+.Pf \e{ Ar n , No \e}\ \&
+.Pf \e{ Ar n No \e}
+.Xc
+.Sm on
+Matches the single character regular expression or subexpression
+immediately preceding it at least
+.Ar n
+and at most
+.Ar m
+times.
+If
+.Ar m
+is omitted, then it matches at least
+.Ar n
+times.
+If the comma is also omitted, then it matches exactly
+.Ar n
+times.
+.El
+.Sh SEE ALSO
+.Xr ctype 3 ,
+.Xr regex 3
+.Sh STANDARDS
+.St -p1003.1-2004 :
+Base Definitions, Chapter 9 (Regular Expressions).
+.Sh BUGS
+Having two kinds of REs is a botch.
+.Pp
+The current POSIX spec says that
+.Sq )\&
+is an ordinary character in the absence of an unmatched
+.Sq ( ;
+this was an unintentional result of a wording error,
+and change is likely.
+Avoid relying on it.
+.Pp
+Back-references are a dreadful botch,
+posing major problems for efficient implementations.
+They are also somewhat vaguely defined
+(does
+.Sq a\e(\e(b\e)*\e2\e)*d
+match
+.Sq abbbd ? ) .
+Avoid using them.
+.Pp
+POSIX's specification of case-independent matching is vague.
+The
+.Dq one case implies all cases
+definition given above
+is the current consensus among implementors as to the right interpretation.
+.Pp
+The syntax for word boundaries is incredibly ugly.
diff --git a/docs/subsystems.rst b/docs/subsystems.rst
new file mode 100644
index 00000000000..be33295a151
--- /dev/null
+++ b/docs/subsystems.rst
@@ -0,0 +1,91 @@
+.. _subsystems:
+
+Subsystem Documentation
+=======================
+
+.. toctree::
+ :hidden:
+
+ AliasAnalysis
+ BitCodeFormat
+ BranchWeightMetadata
+ Bugpoint
+ CodeGenerator
+ ExceptionHandling
+ LinkTimeOptimization
+ SegmentedStacks
+ TableGenFundamentals
+
+* `Writing an LLVM Pass <WritingAnLLVMPass.html>`_
+
+ Information on how to write LLVM transformations and analyses.
+
+* `Writing an LLVM Backend <WritingAnLLVMBackend.html>`_
+
+ Information on how to write LLVM backends for machine targets.
+
+* :ref:`code_generator`
+
+ The design and implementation of the LLVM code generator. Useful if you are
+ working on retargetting LLVM to a new architecture, designing a new codegen
+ pass, or enhancing existing components.
+
+* :ref:`tablegen`
+
+ Describes the TableGen tool, which is used heavily by the LLVM code
+ generator.
+
+* :ref:`alias_analysis`
+
+ Information on how to write a new alias analysis implementation or how to
+ use existing analyses.
+
+* `Accurate Garbage Collection with LLVM <GarbageCollection.html>`_
+
+ The interfaces source-language compilers should use for compiling GC'd
+ programs.
+
+* `Source Level Debugging with LLVM <SourceLevelDebugging.html>`_
+
+ This document describes the design and philosophy behind the LLVM
+ source-level debugger.
+
+* :ref:`exception_handling`
+
+ This document describes the design and implementation of exception handling
+ in LLVM.
+
+* :ref:`bugpoint`
+
+ Automatic bug finder and test-case reducer description and usage
+ information.
+
+* :ref:`bitcode_format`
+
+ This describes the file format and encoding used for LLVM "bc" files.
+
+* `System Library <SystemLibrary.html>`_
+
+ This document describes the LLVM System Library (<tt>lib/System</tt>) and
+ how to keep LLVM source code portable
+
+* :ref:`lto`
+
+ This document describes the interface between LLVM intermodular optimizer
+ and the linker and its design
+
+* `The LLVM gold plugin <GoldPlugin.html>`_
+
+ How to build your programs with link-time optimization on Linux.
+
+* `The GDB JIT interface <DebuggingJITedCode.html>`_
+
+ How to debug JITed code with GDB.
+
+* :ref:`branch_weight`
+
+ Provides information about Branch Prediction Information.
+
+* :ref:`segmented_stacks`
+
+ This document describes segmented stacks and how they are used in LLVM.
diff --git a/docs/tutorial/LangImpl1.html b/docs/tutorial/LangImpl1.html
new file mode 100644
index 00000000000..a65646f2866
--- /dev/null
+++ b/docs/tutorial/LangImpl1.html
@@ -0,0 +1,348 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Tutorial Introduction and the Lexer</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Tutorial Introduction and the Lexer</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 1
+ <ol>
+ <li><a href="#intro">Tutorial Introduction</a></li>
+ <li><a href="#language">The Basic Language</a></li>
+ <li><a href="#lexer">The Lexer</a></li>
+ </ol>
+</li>
+<li><a href="LangImpl2.html">Chapter 2</a>: Implementing a Parser and AST</li>
+</ul>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Tutorial Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to the "Implementing a language with LLVM" tutorial. This tutorial
+runs through the implementation of a simple language, showing how fun and
+easy it can be. This tutorial will get you up and started as well as help to
+build a framework you can extend to other languages. The code in this tutorial
+can also be used as a playground to hack on other LLVM specific things.
+</p>
+
+<p>
+The goal of this tutorial is to progressively unveil our language, describing
+how it is built up over time. This will let us cover a fairly broad range of
+language design and LLVM-specific usage issues, showing and explaining the code
+for it all along the way, without overwhelming you with tons of details up
+front.</p>
+
+<p>It is useful to point out ahead of time that this tutorial is really about
+teaching compiler techniques and LLVM specifically, <em>not</em> about teaching
+modern and sane software engineering principles. In practice, this means that
+we'll take a number of shortcuts to simplify the exposition. For example, the
+code leaks memory, uses global variables all over the place, doesn't use nice
+design patterns like <a
+href="http://en.wikipedia.org/wiki/Visitor_pattern">visitors</a>, etc... but it
+is very simple. If you dig in and use the code as a basis for future projects,
+fixing these deficiencies shouldn't be hard.</p>
+
+<p>I've tried to put this tutorial together in a way that makes chapters easy to
+skip over if you are already familiar with or are uninterested in the various
+pieces. The structure of the tutorial is:
+</p>
+
+<ul>
+<li><b><a href="#language">Chapter #1</a>: Introduction to the Kaleidoscope
+language, and the definition of its Lexer</b> - This shows where we are going
+and the basic functionality that we want it to do. In order to make this
+tutorial maximally understandable and hackable, we choose to implement
+everything in C++ instead of using lexer and parser generators. LLVM obviously
+works just fine with such tools, feel free to use one if you prefer.</li>
+<li><b><a href="LangImpl2.html">Chapter #2</a>: Implementing a Parser and
+AST</b> - With the lexer in place, we can talk about parsing techniques and
+basic AST construction. This tutorial describes recursive descent parsing and
+operator precedence parsing. Nothing in Chapters 1 or 2 is LLVM-specific,
+the code doesn't even link in LLVM at this point. :)</li>
+<li><b><a href="LangImpl3.html">Chapter #3</a>: Code generation to LLVM IR</b> -
+With the AST ready, we can show off how easy generation of LLVM IR really
+is.</li>
+<li><b><a href="LangImpl4.html">Chapter #4</a>: Adding JIT and Optimizer
+Support</b> - Because a lot of people are interested in using LLVM as a JIT,
+we'll dive right into it and show you the 3 lines it takes to add JIT support.
+LLVM is also useful in many other ways, but this is one simple and "sexy" way
+to shows off its power. :)</li>
+<li><b><a href="LangImpl5.html">Chapter #5</a>: Extending the Language: Control
+Flow</b> - With the language up and running, we show how to extend it with
+control flow operations (if/then/else and a 'for' loop). This gives us a chance
+to talk about simple SSA construction and control flow.</li>
+<li><b><a href="LangImpl6.html">Chapter #6</a>: Extending the Language:
+User-defined Operators</b> - This is a silly but fun chapter that talks about
+extending the language to let the user program define their own arbitrary
+unary and binary operators (with assignable precedence!). This lets us build a
+significant piece of the "language" as library routines.</li>
+<li><b><a href="LangImpl7.html">Chapter #7</a>: Extending the Language: Mutable
+Variables</b> - This chapter talks about adding user-defined local variables
+along with an assignment operator. The interesting part about this is how
+easy and trivial it is to construct SSA form in LLVM: no, LLVM does <em>not</em>
+require your front-end to construct SSA form!</li>
+<li><b><a href="LangImpl8.html">Chapter #8</a>: Conclusion and other useful LLVM
+tidbits</b> - This chapter wraps up the series by talking about potential
+ways to extend the language, but also includes a bunch of pointers to info about
+"special topics" like adding garbage collection support, exceptions, debugging,
+support for "spaghetti stacks", and a bunch of other tips and tricks.</li>
+
+</ul>
+
+<p>By the end of the tutorial, we'll have written a bit less than 700 lines of
+non-comment, non-blank, lines of code. With this small amount of code, we'll
+have built up a very reasonable compiler for a non-trivial language including
+a hand-written lexer, parser, AST, as well as code generation support with a JIT
+compiler. While other systems may have interesting "hello world" tutorials,
+I think the breadth of this tutorial is a great testament to the strengths of
+LLVM and why you should consider it if you're interested in language or compiler
+design.</p>
+
+<p>A note about this tutorial: we expect you to extend the language and play
+with it on your own. Take the code and go crazy hacking away at it, compilers
+don't need to be scary creatures - it can be a lot of fun to play with
+languages!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="language">The Basic Language</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This tutorial will be illustrated with a toy language that we'll call
+"<a href="http://en.wikipedia.org/wiki/Kaleidoscope">Kaleidoscope</a>" (derived
+from "meaning beautiful, form, and view").
+Kaleidoscope is a procedural language that allows you to define functions, use
+conditionals, math, etc. Over the course of the tutorial, we'll extend
+Kaleidoscope to support the if/then/else construct, a for loop, user defined
+operators, JIT compilation with a simple command line interface, etc.</p>
+
+<p>Because we want to keep things simple, the only datatype in Kaleidoscope is a
+64-bit floating point type (aka 'double' in C parlance). As such, all values
+are implicitly double precision and the language doesn't require type
+declarations. This gives the language a very nice and simple syntax. For
+example, the following simple example computes <a
+href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers:</a></p>
+
+<div class="doc_code">
+<pre>
+# Compute the x'th fibonacci number.
+def fib(x)
+ if x &lt; 3 then
+ 1
+ else
+ fib(x-1)+fib(x-2)
+
+# This expression will compute the 40th number.
+fib(40)
+</pre>
+</div>
+
+<p>We also allow Kaleidoscope to call into standard library functions (the LLVM
+JIT makes this completely trivial). This means that you can use the 'extern'
+keyword to define a function before you use it (this is also useful for mutually
+recursive functions). For example:</p>
+
+<div class="doc_code">
+<pre>
+extern sin(arg);
+extern cos(arg);
+extern atan2(arg1 arg2);
+
+atan2(sin(.4), cos(42))
+</pre>
+</div>
+
+<p>A more interesting example is included in Chapter 6 where we write a little
+Kaleidoscope application that <a href="LangImpl6.html#example">displays
+a Mandelbrot Set</a> at various levels of magnification.</p>
+
+<p>Lets dive into the implementation of this language!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="lexer">The Lexer</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>When it comes to implementing a language, the first thing needed is
+the ability to process a text file and recognize what it says. The traditional
+way to do this is to use a "<a
+href="http://en.wikipedia.org/wiki/Lexical_analysis">lexer</a>" (aka 'scanner')
+to break the input up into "tokens". Each token returned by the lexer includes
+a token code and potentially some metadata (e.g. the numeric value of a number).
+First, we define the possibilities:
+</p>
+
+<div class="doc_code">
+<pre>
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5,
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+</pre>
+</div>
+
+<p>Each token returned by our lexer will either be one of the Token enum values
+or it will be an 'unknown' character like '+', which is returned as its ASCII
+value. If the current token is an identifier, the <tt>IdentifierStr</tt>
+global variable holds the name of the identifier. If the current token is a
+numeric literal (like 1.0), <tt>NumVal</tt> holds its value. Note that we use
+global variables for simplicity, this is not the best choice for a real language
+implementation :).
+</p>
+
+<p>The actual implementation of the lexer is a single function named
+<tt>gettok</tt>. The <tt>gettok</tt> function is called to return the next token
+from standard input. Its definition starts as:</p>
+
+<div class="doc_code">
+<pre>
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+</pre>
+</div>
+
+<p>
+<tt>gettok</tt> works by calling the C <tt>getchar()</tt> function to read
+characters one at a time from standard input. It eats them as it recognizes
+them and stores the last character read, but not processed, in LastChar. The
+first thing that it has to do is ignore whitespace between tokens. This is
+accomplished with the loop above.</p>
+
+<p>The next thing <tt>gettok</tt> needs to do is recognize identifiers and
+specific keywords like "def". Kaleidoscope does this with this simple loop:</p>
+
+<div class="doc_code">
+<pre>
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ return tok_identifier;
+ }
+</pre>
+</div>
+
+<p>Note that this code sets the '<tt>IdentifierStr</tt>' global whenever it
+lexes an identifier. Also, since language keywords are matched by the same
+loop, we handle them here inline. Numeric values are similar:</p>
+
+<div class="doc_code">
+<pre>
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+</pre>
+</div>
+
+<p>This is all pretty straight-forward code for processing input. When reading
+a numeric value from input, we use the C <tt>strtod</tt> function to convert it
+to a numeric value that we store in <tt>NumVal</tt>. Note that this isn't doing
+sufficient error checking: it will incorrectly read "1.23.45.67" and handle it as
+if you typed in "1.23". Feel free to extend it :). Next we handle comments:
+</p>
+
+<div class="doc_code">
+<pre>
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+</pre>
+</div>
+
+<p>We handle comments by skipping to the end of the line and then return the
+next token. Finally, if the input doesn't match one of the above cases, it is
+either an operator character like '+' or the end of the file. These are handled
+with this code:</p>
+
+<div class="doc_code">
+<pre>
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+</pre>
+</div>
+
+<p>With this, we have the complete lexer for the basic Kaleidoscope language
+(the <a href="LangImpl2.html#code">full code listing</a> for the Lexer is
+available in the <a href="LangImpl2.html">next chapter</a> of the tutorial).
+Next we'll <a href="LangImpl2.html">build a simple parser that uses this to
+build an Abstract Syntax Tree</a>. When we have that, we'll include a driver
+so that you can use the lexer and parser together.
+</p>
+
+<a href="LangImpl2.html">Next: Implementing a Parser and AST</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/LangImpl2.html b/docs/tutorial/LangImpl2.html
new file mode 100644
index 00000000000..292dd4e516c
--- /dev/null
+++ b/docs/tutorial/LangImpl2.html
@@ -0,0 +1,1231 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Implementing a Parser and AST</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Implementing a Parser and AST</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 2
+ <ol>
+ <li><a href="#intro">Chapter 2 Introduction</a></li>
+ <li><a href="#ast">The Abstract Syntax Tree (AST)</a></li>
+ <li><a href="#parserbasics">Parser Basics</a></li>
+ <li><a href="#parserprimexprs">Basic Expression Parsing</a></li>
+ <li><a href="#parserbinops">Binary Expression Parsing</a></li>
+ <li><a href="#parsertop">Parsing the Rest</a></li>
+ <li><a href="#driver">The Driver</a></li>
+ <li><a href="#conclusions">Conclusions</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="LangImpl3.html">Chapter 3</a>: Code generation to LLVM IR</li>
+</ul>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 2 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 2 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. This chapter shows you how to use the lexer, built in
+<a href="LangImpl1.html">Chapter 1</a>, to build a full <a
+href="http://en.wikipedia.org/wiki/Parsing">parser</a> for
+our Kaleidoscope language. Once we have a parser, we'll define and build an <a
+href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax
+Tree</a> (AST).</p>
+
+<p>The parser we will build uses a combination of <a
+href="http://en.wikipedia.org/wiki/Recursive_descent_parser">Recursive Descent
+Parsing</a> and <a href=
+"http://en.wikipedia.org/wiki/Operator-precedence_parser">Operator-Precedence
+Parsing</a> to parse the Kaleidoscope language (the latter for
+binary expressions and the former for everything else). Before we get to
+parsing though, lets talk about the output of the parser: the Abstract Syntax
+Tree.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="ast">The Abstract Syntax Tree (AST)</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The AST for a program captures its behavior in such a way that it is easy for
+later stages of the compiler (e.g. code generation) to interpret. We basically
+want one object for each construct in the language, and the AST should closely
+model the language. In Kaleidoscope, we have expressions, a prototype, and a
+function object. We'll start with expressions first:</p>
+
+<div class="doc_code">
+<pre>
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+};
+</pre>
+</div>
+
+<p>The code above shows the definition of the base ExprAST class and one
+subclass which we use for numeric literals. The important thing to note about
+this code is that the NumberExprAST class captures the numeric value of the
+literal as an instance variable. This allows later phases of the compiler to
+know what the stored numeric value is.</p>
+
+<p>Right now we only create the AST, so there are no useful accessor methods on
+them. It would be very easy to add a virtual method to pretty print the code,
+for example. Here are the other expression AST node definitions that we'll use
+in the basic form of the Kaleidoscope language:
+</p>
+
+<div class="doc_code">
+<pre>
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &amp;name) : Name(name) {}
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector&lt;ExprAST*&gt; Args;
+public:
+ CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
+ : Callee(callee), Args(args) {}
+};
+</pre>
+</div>
+
+<p>This is all (intentionally) rather straight-forward: variables capture the
+variable name, binary operators capture their opcode (e.g. '+'), and calls
+capture a function name as well as a list of any argument expressions. One thing
+that is nice about our AST is that it captures the language features without
+talking about the syntax of the language. Note that there is no discussion about
+precedence of binary operators, lexical structure, etc.</p>
+
+<p>For our basic language, these are all of the expression nodes we'll define.
+Because it doesn't have conditional control flow, it isn't Turing-complete;
+we'll fix that in a later installment. The two things we need next are a way
+to talk about the interface to a function, and a way to talk about functions
+themselves:</p>
+
+<div class="doc_code">
+<pre>
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector&lt;std::string&gt; Args;
+public:
+ PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
+ : Name(name), Args(args) {}
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+};
+</pre>
+</div>
+
+<p>In Kaleidoscope, functions are typed with just a count of their arguments.
+Since all values are double precision floating point, the type of each argument
+doesn't need to be stored anywhere. In a more aggressive and realistic
+language, the "ExprAST" class would probably have a type field.</p>
+
+<p>With this scaffolding, we can now talk about parsing expressions and function
+bodies in Kaleidoscope.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="parserbasics">Parser Basics</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Now that we have an AST to build, we need to define the parser code to build
+it. The idea here is that we want to parse something like "x+y" (which is
+returned as three tokens by the lexer) into an AST that could be generated with
+calls like this:</p>
+
+<div class="doc_code">
+<pre>
+ ExprAST *X = new VariableExprAST("x");
+ ExprAST *Y = new VariableExprAST("y");
+ ExprAST *Result = new BinaryExprAST('+', X, Y);
+</pre>
+</div>
+
+<p>In order to do this, we'll start by defining some basic helper routines:</p>
+
+<div class="doc_code">
+<pre>
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+</pre>
+</div>
+
+<p>
+This implements a simple token buffer around the lexer. This allows
+us to look one token ahead at what the lexer is returning. Every function in
+our parser will assume that CurTok is the current token that needs to be
+parsed.</p>
+
+<div class="doc_code">
+<pre>
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+</pre>
+</div>
+
+<p>
+The <tt>Error</tt> routines are simple helper routines that our parser will use
+to handle errors. The error recovery in our parser will not be the best and
+is not particular user-friendly, but it will be enough for our tutorial. These
+routines make it easier to handle errors in routines that have various return
+types: they always return null.</p>
+
+<p>With these basic helper functions, we can implement the first
+piece of our grammar: numeric literals.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="parserprimexprs">Basic Expression Parsing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>We start with numeric literals, because they are the simplest to process.
+For each production in our grammar, we'll define a function which parses that
+production. For numeric literals, we have:
+</p>
+
+<div class="doc_code">
+<pre>
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+</pre>
+</div>
+
+<p>This routine is very simple: it expects to be called when the current token
+is a <tt>tok_number</tt> token. It takes the current number value, creates
+a <tt>NumberExprAST</tt> node, advances the lexer to the next token, and finally
+returns.</p>
+
+<p>There are some interesting aspects to this. The most important one is that
+this routine eats all of the tokens that correspond to the production and
+returns the lexer buffer with the next token (which is not part of the grammar
+production) ready to go. This is a fairly standard way to go for recursive
+descent parsers. For a better example, the parenthesis operator is defined like
+this:</p>
+
+<div class="doc_code">
+<pre>
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+</pre>
+</div>
+
+<p>This function illustrates a number of interesting things about the
+parser:</p>
+
+<p>
+1) It shows how we use the Error routines. When called, this function expects
+that the current token is a '(' token, but after parsing the subexpression, it
+is possible that there is no ')' waiting. For example, if the user types in
+"(4 x" instead of "(4)", the parser should emit an error. Because errors can
+occur, the parser needs a way to indicate that they happened: in our parser, we
+return null on an error.</p>
+
+<p>2) Another interesting aspect of this function is that it uses recursion by
+calling <tt>ParseExpression</tt> (we will soon see that <tt>ParseExpression</tt> can call
+<tt>ParseParenExpr</tt>). This is powerful because it allows us to handle
+recursive grammars, and keeps each production very simple. Note that
+parentheses do not cause construction of AST nodes themselves. While we could
+do it this way, the most important role of parentheses are to guide the parser
+and provide grouping. Once the parser constructs the AST, parentheses are not
+needed.</p>
+
+<p>The next simple production is for handling variable references and function
+calls:</p>
+
+<div class="doc_code">
+<pre>
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector&lt;ExprAST*&gt; Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+</pre>
+</div>
+
+<p>This routine follows the same style as the other routines. (It expects to be
+called if the current token is a <tt>tok_identifier</tt> token). It also has
+recursion and error handling. One interesting aspect of this is that it uses
+<em>look-ahead</em> to determine if the current identifier is a stand alone
+variable reference or if it is a function call expression. It handles this by
+checking to see if the token after the identifier is a '(' token, constructing
+either a <tt>VariableExprAST</tt> or <tt>CallExprAST</tt> node as appropriate.
+</p>
+
+<p>Now that we have all of our simple expression-parsing logic in place, we can
+define a helper function to wrap it together into one entry point. We call this
+class of expressions "primary" expressions, for reasons that will become more
+clear <a href="LangImpl6.html#unary">later in the tutorial</a>. In order to
+parse an arbitrary primary expression, we need to determine what sort of
+expression it is:</p>
+
+<div class="doc_code">
+<pre>
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ }
+}
+</pre>
+</div>
+
+<p>Now that you see the definition of this function, it is more obvious why we
+can assume the state of CurTok in the various functions. This uses look-ahead
+to determine which sort of expression is being inspected, and then parses it
+with a function call.</p>
+
+<p>Now that basic expressions are handled, we need to handle binary expressions.
+They are a bit more complex.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="parserbinops">Binary Expression Parsing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Binary expressions are significantly harder to parse because they are often
+ambiguous. For example, when given the string "x+y*z", the parser can choose
+to parse it as either "(x+y)*z" or "x+(y*z)". With common definitions from
+mathematics, we expect the later parse, because "*" (multiplication) has
+higher <em>precedence</em> than "+" (addition).</p>
+
+<p>There are many ways to handle this, but an elegant and efficient way is to
+use <a href=
+"http://en.wikipedia.org/wiki/Operator-precedence_parser">Operator-Precedence
+Parsing</a>. This parsing technique uses the precedence of binary operators to
+guide recursion. To start with, we need a table of precedences:</p>
+
+<div class="doc_code">
+<pre>
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map&lt;char, int&gt; BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec &lt;= 0) return -1;
+ return TokPrec;
+}
+
+int main() {
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['&lt;'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+ ...
+}
+</pre>
+</div>
+
+<p>For the basic form of Kaleidoscope, we will only support 4 binary operators
+(this can obviously be extended by you, our brave and intrepid reader). The
+<tt>GetTokPrecedence</tt> function returns the precedence for the current token,
+or -1 if the token is not a binary operator. Having a map makes it easy to add
+new operators and makes it clear that the algorithm doesn't depend on the
+specific operators involved, but it would be easy enough to eliminate the map
+and do the comparisons in the <tt>GetTokPrecedence</tt> function. (Or just use
+a fixed-size array).</p>
+
+<p>With the helper above defined, we can now start parsing binary expressions.
+The basic idea of operator precedence parsing is to break down an expression
+with potentially ambiguous binary operators into pieces. Consider ,for example,
+the expression "a+b+(c+d)*e*f+g". Operator precedence parsing considers this
+as a stream of primary expressions separated by binary operators. As such,
+it will first parse the leading primary expression "a", then it will see the
+pairs [+, b] [+, (c+d)] [*, e] [*, f] and [+, g]. Note that because parentheses
+are primary expressions, the binary expression parser doesn't need to worry
+about nested subexpressions like (c+d) at all.
+</p>
+
+<p>
+To start, an expression is a primary expression potentially followed by a
+sequence of [binop,primaryexpr] pairs:</p>
+
+<div class="doc_code">
+<pre>
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+</pre>
+</div>
+
+<p><tt>ParseBinOpRHS</tt> is the function that parses the sequence of pairs for
+us. It takes a precedence and a pointer to an expression for the part that has been
+parsed so far. Note that "x" is a perfectly valid expression: As such, "binoprhs" is
+allowed to be empty, in which case it returns the expression that is passed into
+it. In our example above, the code passes the expression for "a" into
+<tt>ParseBinOpRHS</tt> and the current token is "+".</p>
+
+<p>The precedence value passed into <tt>ParseBinOpRHS</tt> indicates the <em>
+minimal operator precedence</em> that the function is allowed to eat. For
+example, if the current pair stream is [+, x] and <tt>ParseBinOpRHS</tt> is
+passed in a precedence of 40, it will not consume any tokens (because the
+precedence of '+' is only 20). With this in mind, <tt>ParseBinOpRHS</tt> starts
+with:</p>
+
+<div class="doc_code">
+<pre>
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec &lt; ExprPrec)
+ return LHS;
+</pre>
+</div>
+
+<p>This code gets the precedence of the current token and checks to see if if is
+too low. Because we defined invalid tokens to have a precedence of -1, this
+check implicitly knows that the pair-stream ends when the token stream runs out
+of binary operators. If this check succeeds, we know that the token is a binary
+operator and that it will be included in this expression:</p>
+
+<div class="doc_code">
+<pre>
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+</pre>
+</div>
+
+<p>As such, this code eats (and remembers) the binary operator and then parses
+the primary expression that follows. This builds up the whole pair, the first of
+which is [+, b] for the running example.</p>
+
+<p>Now that we parsed the left-hand side of an expression and one pair of the
+RHS sequence, we have to decide which way the expression associates. In
+particular, we could have "(a+b) binop unparsed" or "a + (b binop unparsed)".
+To determine this, we look ahead at "binop" to determine its precedence and
+compare it to BinOp's precedence (which is '+' in this case):</p>
+
+<div class="doc_code">
+<pre>
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec &lt; NextPrec) {
+</pre>
+</div>
+
+<p>If the precedence of the binop to the right of "RHS" is lower or equal to the
+precedence of our current operator, then we know that the parentheses associate
+as "(a+b) binop ...". In our example, the current operator is "+" and the next
+operator is "+", we know that they have the same precedence. In this case we'll
+create the AST node for "a+b", and then continue parsing:</p>
+
+<div class="doc_code">
+<pre>
+ ... if body omitted ...
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ } // loop around to the top of the while loop.
+}
+</pre>
+</div>
+
+<p>In our example above, this will turn "a+b+" into "(a+b)" and execute the next
+iteration of the loop, with "+" as the current token. The code above will eat,
+remember, and parse "(c+d)" as the primary expression, which makes the
+current pair equal to [+, (c+d)]. It will then evaluate the 'if' conditional above with
+"*" as the binop to the right of the primary. In this case, the precedence of "*" is
+higher than the precedence of "+" so the if condition will be entered.</p>
+
+<p>The critical question left here is "how can the if condition parse the right
+hand side in full"? In particular, to build the AST correctly for our example,
+it needs to get all of "(c+d)*e*f" as the RHS expression variable. The code to
+do this is surprisingly simple (code from the above two blocks duplicated for
+context):</p>
+
+<div class="doc_code">
+<pre>
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec &lt; NextPrec) {
+ <b>RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;</b>
+ }
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ } // loop around to the top of the while loop.
+}
+</pre>
+</div>
+
+<p>At this point, we know that the binary operator to the RHS of our primary
+has higher precedence than the binop we are currently parsing. As such, we know
+that any sequence of pairs whose operators are all higher precedence than "+"
+should be parsed together and returned as "RHS". To do this, we recursively
+invoke the <tt>ParseBinOpRHS</tt> function specifying "TokPrec+1" as the minimum
+precedence required for it to continue. In our example above, this will cause
+it to return the AST node for "(c+d)*e*f" as RHS, which is then set as the RHS
+of the '+' expression.</p>
+
+<p>Finally, on the next iteration of the while loop, the "+g" piece is parsed
+and added to the AST. With this little bit of code (14 non-trivial lines), we
+correctly handle fully general binary expression parsing in a very elegant way.
+This was a whirlwind tour of this code, and it is somewhat subtle. I recommend
+running through it with a few tough examples to see how it works.
+</p>
+
+<p>This wraps up handling of expressions. At this point, we can point the
+parser at an arbitrary token stream and build an expression from it, stopping
+at the first token that is not part of the expression. Next up we need to
+handle function definitions, etc.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="parsertop">Parsing the Rest</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+The next thing missing is handling of function prototypes. In Kaleidoscope,
+these are used both for 'extern' function declarations as well as function body
+definitions. The code to do this is straight-forward and not very interesting
+(once you've survived expressions):
+</p>
+
+<div class="doc_code">
+<pre>
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ // Read the list of argument names.
+ std::vector&lt;std::string&gt; ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+</pre>
+</div>
+
+<p>Given this, a function definition is very simple, just a prototype plus
+an expression to implement the body:</p>
+
+<div class="doc_code">
+<pre>
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+</pre>
+</div>
+
+<p>In addition, we support 'extern' to declare functions like 'sin' and 'cos' as
+well as to support forward declaration of user functions. These 'extern's are just
+prototypes with no body:</p>
+
+<div class="doc_code">
+<pre>
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+</pre>
+</div>
+
+<p>Finally, we'll also let the user type in arbitrary top-level expressions and
+evaluate them on the fly. We will handle this by defining anonymous nullary
+(zero argument) functions for them:</p>
+
+<div class="doc_code">
+<pre>
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+</pre>
+</div>
+
+<p>Now that we have all the pieces, let's build a little driver that will let us
+actually <em>execute</em> this code we've built!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="driver">The Driver</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The driver for this simply invokes all of the parsing pieces with a top-level
+dispatch loop. There isn't much interesting here, so I'll just include the
+top-level loop. See <a href="#code">below</a> for full code in the "Top-Level
+Parsing" section.</p>
+
+<div class="doc_code">
+<pre>
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready&gt; ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+</pre>
+</div>
+
+<p>The most interesting part of this is that we ignore top-level semicolons.
+Why is this, you ask? The basic reason is that if you type "4 + 5" at the
+command line, the parser doesn't know whether that is the end of what you will type
+or not. For example, on the next line you could type "def foo..." in which case
+4+5 is the end of a top-level expression. Alternatively you could type "* 6",
+which would continue the expression. Having top-level semicolons allows you to
+type "4+5;", and the parser will know you are done.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="conclusions">Conclusions</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>With just under 400 lines of commented code (240 lines of non-comment,
+non-blank code), we fully defined our minimal language, including a lexer,
+parser, and AST builder. With this done, the executable will validate
+Kaleidoscope code and tell us if it is grammatically invalid. For
+example, here is a sample interaction:</p>
+
+<div class="doc_code">
+<pre>
+$ <b>./a.out</b>
+ready&gt; <b>def foo(x y) x+foo(y, 4.0);</b>
+Parsed a function definition.
+ready&gt; <b>def foo(x y) x+y y;</b>
+Parsed a function definition.
+Parsed a top-level expr
+ready&gt; <b>def foo(x y) x+y );</b>
+Parsed a function definition.
+Error: unknown token when expecting an expression
+ready&gt; <b>extern sin(a);</b>
+ready&gt; Parsed an extern
+ready&gt; <b>^D</b>
+$
+</pre>
+</div>
+
+<p>There is a lot of room for extension here. You can define new AST nodes,
+extend the language in many ways, etc. In the <a href="LangImpl3.html">next
+installment</a>, we will describe how to generate LLVM Intermediate
+Representation (IR) from the AST.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for this and the previous chapter.
+Note that it is fully self-contained: you don't need LLVM or any external
+libraries at all for this. (Besides the C and C++ standard libraries, of
+course.) To build this, just compile with:</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+clang++ -g -O3 toy.cpp
+# Run
+./a.out
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<div class="doc_code">
+<pre>
+#include &lt;cstdio&gt;
+#include &lt;cstdlib&gt;
+#include &lt;string&gt;
+#include &lt;map&gt;
+#include &lt;vector&gt;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &amp;name) : Name(name) {}
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector&lt;ExprAST*&gt; Args;
+public:
+ CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
+ : Callee(callee), Args(args) {}
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector&lt;std::string&gt; Args;
+public:
+ PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
+ : Name(name), Args(args) {}
+
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map&lt;char, int&gt; BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec &lt;= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector&lt;ExprAST*&gt; Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ }
+}
+
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec &lt; ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec &lt; NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector&lt;std::string&gt; ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing
+//===----------------------------------------------------------------------===//
+
+static void HandleDefinition() {
+ if (ParseDefinition()) {
+ fprintf(stderr, "Parsed a function definition.\n");
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (ParseExtern()) {
+ fprintf(stderr, "Parsed an extern\n");
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (ParseTopLevelExpr()) {
+ fprintf(stderr, "Parsed a top-level expr\n");
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready&gt; ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['&lt;'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready&gt; ");
+ getNextToken();
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ return 0;
+}
+</pre>
+</div>
+<a href="LangImpl3.html">Next: Implementing Code Generation to LLVM IR</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/LangImpl3.html b/docs/tutorial/LangImpl3.html
new file mode 100644
index 00000000000..57ff7373f69
--- /dev/null
+++ b/docs/tutorial/LangImpl3.html
@@ -0,0 +1,1268 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Implementing code generation to LLVM IR</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Code generation to LLVM IR</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 3
+ <ol>
+ <li><a href="#intro">Chapter 3 Introduction</a></li>
+ <li><a href="#basics">Code Generation Setup</a></li>
+ <li><a href="#exprs">Expression Code Generation</a></li>
+ <li><a href="#funcs">Function Code Generation</a></li>
+ <li><a href="#driver">Driver Changes and Closing Thoughts</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="LangImpl4.html">Chapter 4</a>: Adding JIT and Optimizer
+Support</li>
+</ul>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 3 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 3 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. This chapter shows you how to transform the <a
+href="LangImpl2.html">Abstract Syntax Tree</a>, built in Chapter 2, into LLVM IR.
+This will teach you a little bit about how LLVM does things, as well as
+demonstrate how easy it is to use. It's much more work to build a lexer and
+parser than it is to generate LLVM IR code. :)
+</p>
+
+<p><b>Please note</b>: the code in this chapter and later require LLVM 2.2 or
+later. LLVM 2.1 and before will not work with it. Also note that you need
+to use a version of this tutorial that matches your LLVM release: If you are
+using an official LLVM release, use the version of the documentation included
+with your release or on the <a href="http://llvm.org/releases/">llvm.org
+releases page</a>.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="basics">Code Generation Setup</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+In order to generate LLVM IR, we want some simple setup to get started. First
+we define virtual code generation (codegen) methods in each AST class:</p>
+
+<div class="doc_code">
+<pre>
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ <b>virtual Value *Codegen() = 0;</b>
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ <b>virtual Value *Codegen();</b>
+};
+...
+</pre>
+</div>
+
+<p>The Codegen() method says to emit IR for that AST node along with all the things it
+depends on, and they all return an LLVM Value object.
+"Value" is the class used to represent a "<a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
+Assignment (SSA)</a> register" or "SSA value" in LLVM. The most distinct aspect
+of SSA values is that their value is computed as the related instruction
+executes, and it does not get a new value until (and if) the instruction
+re-executes. In other words, there is no way to "change" an SSA value. For
+more information, please read up on <a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
+Assignment</a> - the concepts are really quite natural once you grok them.</p>
+
+<p>Note that instead of adding virtual methods to the ExprAST class hierarchy,
+it could also make sense to use a <a
+href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a> or some
+other way to model this. Again, this tutorial won't dwell on good software
+engineering practices: for our purposes, adding a virtual method is
+simplest.</p>
+
+<p>The
+second thing we want is an "Error" method like we used for the parser, which will
+be used to report errors found during code generation (for example, use of an
+undeclared parameter):</p>
+
+<div class="doc_code">
+<pre>
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+static Module *TheModule;
+static IRBuilder&lt;&gt; Builder(getGlobalContext());
+static std::map&lt;std::string, Value*&gt; NamedValues;
+</pre>
+</div>
+
+<p>The static variables will be used during code generation. <tt>TheModule</tt>
+is the LLVM construct that contains all of the functions and global variables in
+a chunk of code. In many ways, it is the top-level structure that the LLVM IR
+uses to contain code.</p>
+
+<p>The <tt>Builder</tt> object is a helper object that makes it easy to generate
+LLVM instructions. Instances of the <a
+href="http://llvm.org/doxygen/IRBuilder_8h-source.html"><tt>IRBuilder</tt></a>
+class template keep track of the current place to insert instructions and has
+methods to create new instructions.</p>
+
+<p>The <tt>NamedValues</tt> map keeps track of which values are defined in the
+current scope and what their LLVM representation is. (In other words, it is a
+symbol table for the code). In this form of Kaleidoscope, the only things that
+can be referenced are function parameters. As such, function parameters will
+be in this map when generating code for their function body.</p>
+
+<p>
+With these basics in place, we can start talking about how to generate code for
+each expression. Note that this assumes that the <tt>Builder</tt> has been set
+up to generate code <em>into</em> something. For now, we'll assume that this
+has already been done, and we'll just use it to emit code.
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="exprs">Expression Code Generation</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Generating LLVM code for expression nodes is very straightforward: less
+than 45 lines of commented code for all four of our expression nodes. First
+we'll do numeric literals:</p>
+
+<div class="doc_code">
+<pre>
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+</pre>
+</div>
+
+<p>In the LLVM IR, numeric constants are represented with the
+<tt>ConstantFP</tt> class, which holds the numeric value in an <tt>APFloat</tt>
+internally (<tt>APFloat</tt> has the capability of holding floating point
+constants of <em>A</em>rbitrary <em>P</em>recision). This code basically just
+creates and returns a <tt>ConstantFP</tt>. Note that in the LLVM IR
+that constants are all uniqued together and shared. For this reason, the API
+uses the "foo::get(...)" idiom instead of "new foo(..)" or "foo::Create(..)".</p>
+
+<div class="doc_code">
+<pre>
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+</pre>
+</div>
+
+<p>References to variables are also quite simple using LLVM. In the simple version
+of Kaleidoscope, we assume that the variable has already been emitted somewhere
+and its value is available. In practice, the only values that can be in the
+<tt>NamedValues</tt> map are function arguments. This
+code simply checks to see that the specified name is in the map (if not, an
+unknown variable is being referenced) and returns the value for it. In future
+chapters, we'll add support for <a href="LangImpl5.html#for">loop induction
+variables</a> in the symbol table, and for <a
+href="LangImpl7.html#localvars">local variables</a>.</p>
+
+<div class="doc_code">
+<pre>
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS-&gt;Codegen();
+ Value *R = RHS-&gt;Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '&lt;':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: return ErrorV("invalid binary operator");
+ }
+}
+</pre>
+</div>
+
+<p>Binary operators start to get more interesting. The basic idea here is that
+we recursively emit code for the left-hand side of the expression, then the
+right-hand side, then we compute the result of the binary expression. In this
+code, we do a simple switch on the opcode to create the right LLVM instruction.
+</p>
+
+<p>In the example above, the LLVM builder class is starting to show its value.
+IRBuilder knows where to insert the newly created instruction, all you have to
+do is specify what instruction to create (e.g. with <tt>CreateFAdd</tt>), which
+operands to use (<tt>L</tt> and <tt>R</tt> here) and optionally provide a name
+for the generated instruction.</p>
+
+<p>One nice thing about LLVM is that the name is just a hint. For instance, if
+the code above emits multiple "addtmp" variables, LLVM will automatically
+provide each one with an increasing, unique numeric suffix. Local value names
+for instructions are purely optional, but it makes it much easier to read the
+IR dumps.</p>
+
+<p><a href="../LangRef.html#instref">LLVM instructions</a> are constrained by
+strict rules: for example, the Left and Right operators of
+an <a href="../LangRef.html#i_add">add instruction</a> must have the same
+type, and the result type of the add must match the operand types. Because
+all values in Kaleidoscope are doubles, this makes for very simple code for add,
+sub and mul.</p>
+
+<p>On the other hand, LLVM specifies that the <a
+href="../LangRef.html#i_fcmp">fcmp instruction</a> always returns an 'i1' value
+(a one bit integer). The problem with this is that Kaleidoscope wants the value to be a 0.0 or 1.0 value. In order to get these semantics, we combine the fcmp instruction with
+a <a href="../LangRef.html#i_uitofp">uitofp instruction</a>. This instruction
+converts its input integer into a floating point value by treating the input
+as an unsigned value. In contrast, if we used the <a
+href="../LangRef.html#i_sitofp">sitofp instruction</a>, the Kaleidoscope '&lt;'
+operator would return 0.0 and -1.0, depending on the input value.</p>
+
+<div class="doc_code">
+<pre>
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule-&gt;getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF-&gt;arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector&lt;Value*&gt; ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]-&gt;Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+</pre>
+</div>
+
+<p>Code generation for function calls is quite straightforward with LLVM. The
+code above initially does a function name lookup in the LLVM Module's symbol
+table. Recall that the LLVM Module is the container that holds all of the
+functions we are JIT'ing. By giving each function the same name as what the
+user specifies, we can use the LLVM symbol table to resolve function names for
+us.</p>
+
+<p>Once we have the function to call, we recursively codegen each argument that
+is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
+instruction</a>. Note that LLVM uses the native C calling conventions by
+default, allowing these calls to also call into standard library functions like
+"sin" and "cos", with no additional effort.</p>
+
+<p>This wraps up our handling of the four basic expressions that we have so far
+in Kaleidoscope. Feel free to go in and add some more. For example, by
+browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
+several other interesting instructions that are really easy to plug into our
+basic framework.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="funcs">Function Code Generation</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Code generation for prototypes and functions must handle a number of
+details, which make their code less beautiful than expression code
+generation, but allows us to illustrate some important points. First, lets
+talk about code generation for prototypes: they are used both for function
+bodies and external function declarations. The code starts with:</p>
+
+<div class="doc_code">
+<pre>
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector&lt;Type*&gt; Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+</pre>
+</div>
+
+<p>This code packs a lot of power into a few lines. Note first that this
+function returns a "Function*" instead of a "Value*". Because a "prototype"
+really talks about the external interface for a function (not the value computed
+by an expression), it makes sense for it to return the LLVM Function it
+corresponds to when codegen'd.</p>
+
+<p>The call to <tt>FunctionType::get</tt> creates
+the <tt>FunctionType</tt> that should be used for a given Prototype. Since all
+function arguments in Kaleidoscope are of type double, the first line creates
+a vector of "N" LLVM double types. It then uses the <tt>Functiontype::get</tt>
+method to create a function type that takes "N" doubles as arguments, returns
+one double as a result, and that is not vararg (the false parameter indicates
+this). Note that Types in LLVM are uniqued just like Constants are, so you
+don't "new" a type, you "get" it.</p>
+
+<p>The final line above actually creates the function that the prototype will
+correspond to. This indicates the type, linkage and name to use, as well as which
+module to insert into. "<a href="../LangRef.html#linkage">external linkage</a>"
+means that the function may be defined outside the current module and/or that it
+is callable by functions outside the module. The Name passed in is the name the
+user specified: since "<tt>TheModule</tt>" is specified, this name is registered
+in "<tt>TheModule</tt>"s symbol table, which is used by the function call code
+above.</p>
+
+<div class="doc_code">
+<pre>
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F-&gt;getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F-&gt;eraseFromParent();
+ F = TheModule-&gt;getFunction(Name);
+</pre>
+</div>
+
+<p>The Module symbol table works just like the Function symbol table when it
+comes to name conflicts: if a new function is created with a name that was previously
+added to the symbol table, the new function will get implicitly renamed when added to the
+Module. The code above exploits this fact to determine if there was a previous
+definition of this function.</p>
+
+<p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
+first, we want to allow 'extern'ing a function more than once, as long as the
+prototypes for the externs match (since all arguments have the same type, we
+just have to check that the number of arguments match). Second, we want to
+allow 'extern'ing a function and then defining a body for it. This is useful
+when defining mutually recursive functions.</p>
+
+<p>In order to implement this, the code above first checks to see if there is
+a collision on the name of the function. If so, it deletes the function we just
+created (by calling <tt>eraseFromParent</tt>) and then calling
+<tt>getFunction</tt> to get the existing function with the specified name. Note
+that many APIs in LLVM have "erase" forms and "remove" forms. The "remove" form
+unlinks the object from its parent (e.g. a Function from a Module) and returns
+it. The "erase" form unlinks the object and then deletes it.</p>
+
+<div class="doc_code">
+<pre>
+ // If F already has a body, reject this.
+ if (!F-&gt;empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F-&gt;arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+</pre>
+</div>
+
+<p>In order to verify the logic above, we first check to see if the pre-existing
+function is "empty". In this case, empty means that it has no basic blocks in
+it, which means it has no body. If it has no body, it is a forward
+declaration. Since we don't allow anything after a full definition of the
+function, the code rejects this case. If the previous reference to a function
+was an 'extern', we simply verify that the number of arguments for that
+definition and this one match up. If not, we emit an error.</p>
+
+<div class="doc_code">
+<pre>
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI-&gt;setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+ return F;
+}
+</pre>
+</div>
+
+<p>The last bit of code for prototypes loops over all of the arguments in the
+function, setting the name of the LLVM Argument objects to match, and registering
+the arguments in the <tt>NamedValues</tt> map for future use by the
+<tt>VariableExprAST</tt> AST node. Once this is set up, it returns the Function
+object to the caller. Note that we don't check for conflicting
+argument names here (e.g. "extern foo(a b a)"). Doing so would be very
+straight-forward with the mechanics we have already used above.</p>
+
+<div class="doc_code">
+<pre>
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto-&gt;Codegen();
+ if (TheFunction == 0)
+ return 0;
+</pre>
+</div>
+
+<p>Code generation for function definitions starts out simply enough: we just
+codegen the prototype (Proto) and verify that it is ok. We then clear out the
+<tt>NamedValues</tt> map to make sure that there isn't anything in it from the
+last function we compiled. Code generation of the prototype ensures that there
+is an LLVM Function object that is ready to go for us.</p>
+
+<div class="doc_code">
+<pre>
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body-&gt;Codegen()) {
+</pre>
+</div>
+
+<p>Now we get to the point where the <tt>Builder</tt> is set up. The first
+line creates a new <a href="http://en.wikipedia.org/wiki/Basic_block">basic
+block</a> (named "entry"), which is inserted into <tt>TheFunction</tt>. The
+second line then tells the builder that new instructions should be inserted into
+the end of the new basic block. Basic blocks in LLVM are an important part
+of functions that define the <a
+href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
+Since we don't have any control flow, our functions will only contain one
+block at this point. We'll fix this in <a href="LangImpl5.html">Chapter 5</a> :).</p>
+
+<div class="doc_code">
+<pre>
+ if (Value *RetVal = Body-&gt;Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ return TheFunction;
+ }
+</pre>
+</div>
+
+<p>Once the insertion point is set up, we call the <tt>CodeGen()</tt> method for
+the root expression of the function. If no error happens, this emits code to
+compute the expression into the entry block and returns the value that was
+computed. Assuming no error, we then create an LLVM <a
+href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
+Once the function is built, we call <tt>verifyFunction</tt>, which
+is provided by LLVM. This function does a variety of consistency checks on the
+generated code, to determine if our compiler is doing everything right. Using
+this is important: it can catch a lot of bugs. Once the function is finished
+and validated, we return it.</p>
+
+<div class="doc_code">
+<pre>
+ // Error reading body, remove function.
+ TheFunction-&gt;eraseFromParent();
+ return 0;
+}
+</pre>
+</div>
+
+<p>The only piece left here is handling of the error case. For simplicity, we
+handle this by merely deleting the function we produced with the
+<tt>eraseFromParent</tt> method. This allows the user to redefine a function
+that they incorrectly typed in before: if we didn't delete it, it would live in
+the symbol table, with a body, preventing future redefinition.</p>
+
+<p>This code does have a bug, though. Since the <tt>PrototypeAST::Codegen</tt>
+can return a previously defined forward declaration, our code can actually delete
+a forward declaration. There are a number of ways to fix this bug, see what you
+can come up with! Here is a testcase:</p>
+
+<div class="doc_code">
+<pre>
+extern foo(a b); # ok, defines foo.
+def foo(a b) c; # error, 'c' is invalid.
+def bar() foo(1, 2); # error, unknown function "foo"
+</pre>
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="driver">Driver Changes and Closing Thoughts</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+For now, code generation to LLVM doesn't really get us much, except that we can
+look at the pretty IR calls. The sample code inserts calls to Codegen into the
+"<tt>HandleDefinition</tt>", "<tt>HandleExtern</tt>" etc functions, and then
+dumps out the LLVM IR. This gives a nice way to look at the LLVM IR for simple
+functions. For example:
+</p>
+
+<div class="doc_code">
+<pre>
+ready> <b>4+5</b>;
+Read top-level expression:
+define double @0() {
+entry:
+ ret double 9.000000e+00
+}
+</pre>
+</div>
+
+<p>Note how the parser turns the top-level expression into anonymous functions
+for us. This will be handy when we add <a href="LangImpl4.html#jit">JIT
+support</a> in the next chapter. Also note that the code is very literally
+transcribed, no optimizations are being performed except simple constant
+folding done by IRBuilder. We will
+<a href="LangImpl4.html#trivialconstfold">add optimizations</a> explicitly in
+the next chapter.</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def foo(a b) a*a + 2*a*b + b*b;</b>
+Read function definition:
+define double @foo(double %a, double %b) {
+entry:
+ %multmp = fmul double %a, %a
+ %multmp1 = fmul double 2.000000e+00, %a
+ %multmp2 = fmul double %multmp1, %b
+ %addtmp = fadd double %multmp, %multmp2
+ %multmp3 = fmul double %b, %b
+ %addtmp4 = fadd double %addtmp, %multmp3
+ ret double %addtmp4
+}
+</pre>
+</div>
+
+<p>This shows some simple arithmetic. Notice the striking similarity to the
+LLVM builder calls that we use to create the instructions.</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def bar(a) foo(a, 4.0) + bar(31337);</b>
+Read function definition:
+define double @bar(double %a) {
+entry:
+ %calltmp = call double @foo(double %a, double 4.000000e+00)
+ %calltmp1 = call double @bar(double 3.133700e+04)
+ %addtmp = fadd double %calltmp, %calltmp1
+ ret double %addtmp
+}
+</pre>
+</div>
+
+<p>This shows some function calls. Note that this function will take a long
+time to execute if you call it. In the future we'll add conditional control
+flow to actually make recursion useful :).</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>extern cos(x);</b>
+Read extern:
+declare double @cos(double)
+
+ready&gt; <b>cos(1.234);</b>
+Read top-level expression:
+define double @1() {
+entry:
+ %calltmp = call double @cos(double 1.234000e+00)
+ ret double %calltmp
+}
+</pre>
+</div>
+
+<p>This shows an extern for the libm "cos" function, and a call to it.</p>
+
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>^D</b>
+; ModuleID = 'my cool jit'
+
+define double @0() {
+entry:
+ %addtmp = fadd double 4.000000e+00, 5.000000e+00
+ ret double %addtmp
+}
+
+define double @foo(double %a, double %b) {
+entry:
+ %multmp = fmul double %a, %a
+ %multmp1 = fmul double 2.000000e+00, %a
+ %multmp2 = fmul double %multmp1, %b
+ %addtmp = fadd double %multmp, %multmp2
+ %multmp3 = fmul double %b, %b
+ %addtmp4 = fadd double %addtmp, %multmp3
+ ret double %addtmp4
+}
+
+define double @bar(double %a) {
+entry:
+ %calltmp = call double @foo(double %a, double 4.000000e+00)
+ %calltmp1 = call double @bar(double 3.133700e+04)
+ %addtmp = fadd double %calltmp, %calltmp1
+ ret double %addtmp
+}
+
+declare double @cos(double)
+
+define double @1() {
+entry:
+ %calltmp = call double @cos(double 1.234000e+00)
+ ret double %calltmp
+}
+</pre>
+</div>
+
+<p>When you quit the current demo, it dumps out the IR for the entire module
+generated. Here you can see the big picture with all the functions referencing
+each other.</p>
+
+<p>This wraps up the third chapter of the Kaleidoscope tutorial. Up next, we'll
+describe how to <a href="LangImpl4.html">add JIT codegen and optimizer
+support</a> to this so we can actually start running code!</p>
+
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with the
+LLVM code generator. Because this uses the LLVM libraries, we need to link
+them in. To do this, we use the <a
+href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
+our makefile/command line about which options to use:</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+clang++ -g -O3 toy.cpp `llvm-config --cppflags --ldflags --libs core` -o toy
+# Run
+./toy
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<div class="doc_code">
+<pre>
+// To build this:
+// See example below.
+
+#include "llvm/DerivedTypes.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/Analysis/Verifier.h"
+#include &lt;cstdio&gt;
+#include &lt;string&gt;
+#include &lt;map&gt;
+#include &lt;vector&gt;
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &amp;name) : Name(name) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector&lt;ExprAST*&gt; Args;
+public:
+ CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector&lt;std::string&gt; Args;
+public:
+ PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
+ : Name(name), Args(args) {}
+
+ Function *Codegen();
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map&lt;char, int&gt; BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec &lt;= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector&lt;ExprAST*&gt; Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ }
+}
+
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec &lt; ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec &lt; NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector&lt;std::string&gt; ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder&lt;&gt; Builder(getGlobalContext());
+static std::map&lt;std::string, Value*&gt; NamedValues;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS-&gt;Codegen();
+ Value *R = RHS-&gt;Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '&lt;':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: return ErrorV("invalid binary operator");
+ }
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule-&gt;getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF-&gt;arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector&lt;Value*&gt; ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]-&gt;Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector&lt;Type*&gt; Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F-&gt;getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F-&gt;eraseFromParent();
+ F = TheModule-&gt;getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F-&gt;empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F-&gt;arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI-&gt;setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+
+ return F;
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto-&gt;Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body-&gt;Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction-&gt;eraseFromParent();
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P-&gt;Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ fprintf(stderr, "Read top-level expression:");
+ LF-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready&gt; ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ LLVMContext &amp;Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['&lt;'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready&gt; ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ // Print out all of the generated code.
+ TheModule-&gt;dump();
+
+ return 0;
+}
+</pre>
+</div>
+<a href="LangImpl4.html">Next: Adding JIT and Optimizer Support</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/LangImpl4.html b/docs/tutorial/LangImpl4.html
new file mode 100644
index 00000000000..453e43a02e5
--- /dev/null
+++ b/docs/tutorial/LangImpl4.html
@@ -0,0 +1,1152 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Adding JIT and Optimizer Support</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Adding JIT and Optimizer Support</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 4
+ <ol>
+ <li><a href="#intro">Chapter 4 Introduction</a></li>
+ <li><a href="#trivialconstfold">Trivial Constant Folding</a></li>
+ <li><a href="#optimizerpasses">LLVM Optimization Passes</a></li>
+ <li><a href="#jit">Adding a JIT Compiler</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="LangImpl5.html">Chapter 5</a>: Extending the Language: Control
+Flow</li>
+</ul>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 4 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 4 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. Chapters 1-3 described the implementation of a simple
+language and added support for generating LLVM IR. This chapter describes
+two new techniques: adding optimizer support to your language, and adding JIT
+compiler support. These additions will demonstrate how to get nice, efficient code
+for the Kaleidoscope language.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="trivialconstfold">Trivial Constant Folding</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Our demonstration for Chapter 3 is elegant and easy to extend. Unfortunately,
+it does not produce wonderful code. The IRBuilder, however, does give us
+obvious optimizations when compiling simple code:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def test(x) 1+2+x;</b>
+Read function definition:
+define double @test(double %x) {
+entry:
+ %addtmp = fadd double 3.000000e+00, %x
+ ret double %addtmp
+}
+</pre>
+</div>
+
+<p>This code is not a literal transcription of the AST built by parsing the
+input. That would be:
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def test(x) 1+2+x;</b>
+Read function definition:
+define double @test(double %x) {
+entry:
+ %addtmp = fadd double 2.000000e+00, 1.000000e+00
+ %addtmp1 = fadd double %addtmp, %x
+ ret double %addtmp1
+}
+</pre>
+</div>
+
+<p>Constant folding, as seen above, in particular, is a very common and very
+important optimization: so much so that many language implementors implement
+constant folding support in their AST representation.</p>
+
+<p>With LLVM, you don't need this support in the AST. Since all calls to build
+LLVM IR go through the LLVM IR builder, the builder itself checked to see if
+there was a constant folding opportunity when you call it. If so, it just does
+the constant fold and return the constant instead of creating an instruction.
+
+<p>Well, that was easy :). In practice, we recommend always using
+<tt>IRBuilder</tt> when generating code like this. It has no
+"syntactic overhead" for its use (you don't have to uglify your compiler with
+constant checks everywhere) and it can dramatically reduce the amount of
+LLVM IR that is generated in some cases (particular for languages with a macro
+preprocessor or that use a lot of constants).</p>
+
+<p>On the other hand, the <tt>IRBuilder</tt> is limited by the fact
+that it does all of its analysis inline with the code as it is built. If you
+take a slightly more complex example:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
+ready> Read function definition:
+define double @test(double %x) {
+entry:
+ %addtmp = fadd double 3.000000e+00, %x
+ %addtmp1 = fadd double %x, 3.000000e+00
+ %multmp = fmul double %addtmp, %addtmp1
+ ret double %multmp
+}
+</pre>
+</div>
+
+<p>In this case, the LHS and RHS of the multiplication are the same value. We'd
+really like to see this generate "<tt>tmp = x+3; result = tmp*tmp;</tt>" instead
+of computing "<tt>x+3</tt>" twice.</p>
+
+<p>Unfortunately, no amount of local analysis will be able to detect and correct
+this. This requires two transformations: reassociation of expressions (to
+make the add's lexically identical) and Common Subexpression Elimination (CSE)
+to delete the redundant add instruction. Fortunately, LLVM provides a broad
+range of optimizations that you can use, in the form of "passes".</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="optimizerpasses">LLVM Optimization Passes</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>LLVM provides many optimization passes, which do many different sorts of
+things and have different tradeoffs. Unlike other systems, LLVM doesn't hold
+to the mistaken notion that one set of optimizations is right for all languages
+and for all situations. LLVM allows a compiler implementor to make complete
+decisions about what optimizations to use, in which order, and in what
+situation.</p>
+
+<p>As a concrete example, LLVM supports both "whole module" passes, which look
+across as large of body of code as they can (often a whole file, but if run
+at link time, this can be a substantial portion of the whole program). It also
+supports and includes "per-function" passes which just operate on a single
+function at a time, without looking at other functions. For more information
+on passes and how they are run, see the <a href="../WritingAnLLVMPass.html">How
+to Write a Pass</a> document and the <a href="../Passes.html">List of LLVM
+Passes</a>.</p>
+
+<p>For Kaleidoscope, we are currently generating functions on the fly, one at
+a time, as the user types them in. We aren't shooting for the ultimate
+optimization experience in this setting, but we also want to catch the easy and
+quick stuff where possible. As such, we will choose to run a few per-function
+optimizations as the user types the function in. If we wanted to make a "static
+Kaleidoscope compiler", we would use exactly the code we have now, except that
+we would defer running the optimizer until the entire file has been parsed.</p>
+
+<p>In order to get per-function optimizations going, we need to set up a
+<a href="../WritingAnLLVMPass.html#passmanager">FunctionPassManager</a> to hold and
+organize the LLVM optimizations that we want to run. Once we have that, we can
+add a set of optimizations to run. The code looks like this:</p>
+
+<div class="doc_code">
+<pre>
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &amp;OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+</pre>
+</div>
+
+<p>This code defines a <tt>FunctionPassManager</tt>, "<tt>OurFPM</tt>". It
+requires a pointer to the <tt>Module</tt> to construct itself. Once it is set
+up, we use a series of "add" calls to add a bunch of LLVM passes. The first
+pass is basically boilerplate, it adds a pass so that later optimizations know
+how the data structures in the program are laid out. The
+"<tt>TheExecutionEngine</tt>" variable is related to the JIT, which we will get
+to in the next section.</p>
+
+<p>In this case, we choose to add 4 optimization passes. The passes we chose
+here are a pretty standard set of "cleanup" optimizations that are useful for
+a wide variety of code. I won't delve into what they do but, believe me,
+they are a good starting place :).</p>
+
+<p>Once the PassManager is set up, we need to make use of it. We do this by
+running it after our newly created function is constructed (in
+<tt>FunctionAST::Codegen</tt>), but before it is returned to the client:</p>
+
+<div class="doc_code">
+<pre>
+ if (Value *RetVal = Body->Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ <b>// Optimize the function.
+ TheFPM-&gt;run(*TheFunction);</b>
+
+ return TheFunction;
+ }
+</pre>
+</div>
+
+<p>As you can see, this is pretty straightforward. The
+<tt>FunctionPassManager</tt> optimizes and updates the LLVM Function* in place,
+improving (hopefully) its body. With this in place, we can try our test above
+again:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
+ready> Read function definition:
+define double @test(double %x) {
+entry:
+ %addtmp = fadd double %x, 3.000000e+00
+ %multmp = fmul double %addtmp, %addtmp
+ ret double %multmp
+}
+</pre>
+</div>
+
+<p>As expected, we now get our nicely optimized code, saving a floating point
+add instruction from every execution of this function.</p>
+
+<p>LLVM provides a wide variety of optimizations that can be used in certain
+circumstances. Some <a href="../Passes.html">documentation about the various
+passes</a> is available, but it isn't very complete. Another good source of
+ideas can come from looking at the passes that <tt>Clang</tt> runs to get
+started. The "<tt>opt</tt>" tool allows you to experiment with passes from the
+command line, so you can see if they do anything.</p>
+
+<p>Now that we have reasonable code coming out of our front-end, lets talk about
+executing it!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="jit">Adding a JIT Compiler</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Code that is available in LLVM IR can have a wide variety of tools
+applied to it. For example, you can run optimizations on it (as we did above),
+you can dump it out in textual or binary forms, you can compile the code to an
+assembly file (.s) for some target, or you can JIT compile it. The nice thing
+about the LLVM IR representation is that it is the "common currency" between
+many different parts of the compiler.
+</p>
+
+<p>In this section, we'll add JIT compiler support to our interpreter. The
+basic idea that we want for Kaleidoscope is to have the user enter function
+bodies as they do now, but immediately evaluate the top-level expressions they
+type in. For example, if they type in "1 + 2;", we should evaluate and print
+out 3. If they define a function, they should be able to call it from the
+command line.</p>
+
+<p>In order to do this, we first declare and initialize the JIT. This is done
+by adding a global variable and a call in <tt>main</tt>:</p>
+
+<div class="doc_code">
+<pre>
+<b>static ExecutionEngine *TheExecutionEngine;</b>
+...
+int main() {
+ ..
+ <b>// Create the JIT. This takes ownership of the module.
+ TheExecutionEngine = EngineBuilder(TheModule).create();</b>
+ ..
+}
+</pre>
+</div>
+
+<p>This creates an abstract "Execution Engine" which can be either a JIT
+compiler or the LLVM interpreter. LLVM will automatically pick a JIT compiler
+for you if one is available for your platform, otherwise it will fall back to
+the interpreter.</p>
+
+<p>Once the <tt>ExecutionEngine</tt> is created, the JIT is ready to be used.
+There are a variety of APIs that are useful, but the simplest one is the
+"<tt>getPointerToFunction(F)</tt>" method. This method JIT compiles the
+specified LLVM Function and returns a function pointer to the generated machine
+code. In our case, this means that we can change the code that parses a
+top-level expression to look like this:</p>
+
+<div class="doc_code">
+<pre>
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ LF->dump(); // Dump the function for exposition purposes.
+
+ <b>// JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());</b>
+ }
+</pre>
+</div>
+
+<p>Recall that we compile top-level expressions into a self-contained LLVM
+function that takes no arguments and returns the computed double. Because the
+LLVM JIT compiler matches the native platform ABI, this means that you can just
+cast the result pointer to a function pointer of that type and call it directly.
+This means, there is no difference between JIT compiled code and native machine
+code that is statically linked into your application.</p>
+
+<p>With just these two changes, lets see how Kaleidoscope works now!</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>4+5;</b>
+Read top-level expression:
+define double @0() {
+entry:
+ ret double 9.000000e+00
+}
+
+<em>Evaluated to 9.000000</em>
+</pre>
+</div>
+
+<p>Well this looks like it is basically working. The dump of the function
+shows the "no argument function that always returns double" that we synthesize
+for each top-level expression that is typed in. This demonstrates very basic
+functionality, but can we do more?</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def testfunc(x y) x + y*2; </b>
+Read function definition:
+define double @testfunc(double %x, double %y) {
+entry:
+ %multmp = fmul double %y, 2.000000e+00
+ %addtmp = fadd double %multmp, %x
+ ret double %addtmp
+}
+
+ready&gt; <b>testfunc(4, 10);</b>
+Read top-level expression:
+define double @1() {
+entry:
+ %calltmp = call double @testfunc(double 4.000000e+00, double 1.000000e+01)
+ ret double %calltmp
+}
+
+<em>Evaluated to 24.000000</em>
+</pre>
+</div>
+
+<p>This illustrates that we can now call user code, but there is something a bit
+subtle going on here. Note that we only invoke the JIT on the anonymous
+functions that <em>call testfunc</em>, but we never invoked it
+on <em>testfunc</em> itself. What actually happened here is that the JIT
+scanned for all non-JIT'd functions transitively called from the anonymous
+function and compiled all of them before returning
+from <tt>getPointerToFunction()</tt>.</p>
+
+<p>The JIT provides a number of other more advanced interfaces for things like
+freeing allocated machine code, rejit'ing functions to update them, etc.
+However, even with this simple code, we get some surprisingly powerful
+capabilities - check this out (I removed the dump of the anonymous functions,
+you should get the idea by now :) :</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>extern sin(x);</b>
+Read extern:
+declare double @sin(double)
+
+ready&gt; <b>extern cos(x);</b>
+Read extern:
+declare double @cos(double)
+
+ready&gt; <b>sin(1.0);</b>
+Read top-level expression:
+define double @2() {
+entry:
+ ret double 0x3FEAED548F090CEE
+}
+
+<em>Evaluated to 0.841471</em>
+
+ready&gt; <b>def foo(x) sin(x)*sin(x) + cos(x)*cos(x);</b>
+Read function definition:
+define double @foo(double %x) {
+entry:
+ %calltmp = call double @sin(double %x)
+ %multmp = fmul double %calltmp, %calltmp
+ %calltmp2 = call double @cos(double %x)
+ %multmp4 = fmul double %calltmp2, %calltmp2
+ %addtmp = fadd double %multmp, %multmp4
+ ret double %addtmp
+}
+
+ready&gt; <b>foo(4.0);</b>
+Read top-level expression:
+define double @3() {
+entry:
+ %calltmp = call double @foo(double 4.000000e+00)
+ ret double %calltmp
+}
+
+<em>Evaluated to 1.000000</em>
+</pre>
+</div>
+
+<p>Whoa, how does the JIT know about sin and cos? The answer is surprisingly
+simple: in this
+example, the JIT started execution of a function and got to a function call. It
+realized that the function was not yet JIT compiled and invoked the standard set
+of routines to resolve the function. In this case, there is no body defined
+for the function, so the JIT ended up calling "<tt>dlsym("sin")</tt>" on the
+Kaleidoscope process itself.
+Since "<tt>sin</tt>" is defined within the JIT's address space, it simply
+patches up calls in the module to call the libm version of <tt>sin</tt>
+directly.</p>
+
+<p>The LLVM JIT provides a number of interfaces (look in the
+<tt>ExecutionEngine.h</tt> file) for controlling how unknown functions get
+resolved. It allows you to establish explicit mappings between IR objects and
+addresses (useful for LLVM global variables that you want to map to static
+tables, for example), allows you to dynamically decide on the fly based on the
+function name, and even allows you to have the JIT compile functions lazily the
+first time they're called.</p>
+
+<p>One interesting application of this is that we can now extend the language
+by writing arbitrary C++ code to implement operations. For example, if we add:
+</p>
+
+<div class="doc_code">
+<pre>
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+</pre>
+</div>
+
+<p>Now we can produce simple output to the console by using things like:
+"<tt>extern putchard(x); putchard(120);</tt>", which prints a lowercase 'x' on
+the console (120 is the ASCII code for 'x'). Similar code could be used to
+implement file I/O, console input, and many other capabilities in
+Kaleidoscope.</p>
+
+<p>This completes the JIT and optimizer chapter of the Kaleidoscope tutorial. At
+this point, we can compile a non-Turing-complete programming language, optimize
+and JIT compile it in a user-driven way. Next up we'll look into <a
+href="LangImpl5.html">extending the language with control flow constructs</a>,
+tackling some interesting LLVM IR issues along the way.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with the
+LLVM JIT and optimizer. To build this example, use:
+</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+clang++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
+# Run
+./toy
+</pre>
+</div>
+
+<p>
+If you are compiling this on Linux, make sure to add the "-rdynamic" option
+as well. This makes sure that the external functions are resolved properly
+at runtime.</p>
+
+<p>Here is the code:</p>
+
+<div class="doc_code">
+<pre>
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/TargetSelect.h"
+#include &lt;cstdio&gt;
+#include &lt;string&gt;
+#include &lt;map&gt;
+#include &lt;vector&gt;
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &amp;name) : Name(name) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector&lt;ExprAST*&gt; Args;
+public:
+ CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector&lt;std::string&gt; Args;
+public:
+ PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
+ : Name(name), Args(args) {}
+
+ Function *Codegen();
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map&lt;char, int&gt; BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec &lt;= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector&lt;ExprAST*&gt; Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ }
+}
+
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec &lt; ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec &lt; NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector&lt;std::string&gt; ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder&lt;&gt; Builder(getGlobalContext());
+static std::map&lt;std::string, Value*&gt; NamedValues;
+static FunctionPassManager *TheFPM;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS-&gt;Codegen();
+ Value *R = RHS-&gt;Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '&lt;':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: return ErrorV("invalid binary operator");
+ }
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule-&gt;getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF-&gt;arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector&lt;Value*&gt; ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]-&gt;Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector&lt;Type*&gt; Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F-&gt;getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F-&gt;eraseFromParent();
+ F = TheModule-&gt;getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F-&gt;empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F-&gt;arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI-&gt;setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+
+ return F;
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto-&gt;Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body-&gt;Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ // Optimize the function.
+ TheFPM-&gt;run(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction-&gt;eraseFromParent();
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static ExecutionEngine *TheExecutionEngine;
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P-&gt;Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ fprintf(stderr, "Read top-level expression:");
+ LF->dump();
+
+ // JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready&gt; ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext &amp;Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['&lt;'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready&gt; ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Create the JIT. This takes ownership of the module.
+ std::string ErrStr;
+ TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&amp;ErrStr).create();
+ if (!TheExecutionEngine) {
+ fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+ exit(1);
+ }
+
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &amp;OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ TheFPM = 0;
+
+ // Print out all of the generated code.
+ TheModule-&gt;dump();
+
+ return 0;
+}
+</pre>
+</div>
+
+<a href="LangImpl5.html">Next: Extending the language: control flow</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/LangImpl5-cfg.png b/docs/tutorial/LangImpl5-cfg.png
new file mode 100644
index 00000000000..cdba92ff6c5
--- /dev/null
+++ b/docs/tutorial/LangImpl5-cfg.png
Binary files differ
diff --git a/docs/tutorial/LangImpl5.html b/docs/tutorial/LangImpl5.html
new file mode 100644
index 00000000000..2d406df3aaf
--- /dev/null
+++ b/docs/tutorial/LangImpl5.html
@@ -0,0 +1,1772 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Extending the Language: Control Flow</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Extending the Language: Control Flow</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 5
+ <ol>
+ <li><a href="#intro">Chapter 5 Introduction</a></li>
+ <li><a href="#ifthen">If/Then/Else</a>
+ <ol>
+ <li><a href="#iflexer">Lexer Extensions</a></li>
+ <li><a href="#ifast">AST Extensions</a></li>
+ <li><a href="#ifparser">Parser Extensions</a></li>
+ <li><a href="#ifir">LLVM IR</a></li>
+ <li><a href="#ifcodegen">Code Generation</a></li>
+ </ol>
+ </li>
+ <li><a href="#for">'for' Loop Expression</a>
+ <ol>
+ <li><a href="#forlexer">Lexer Extensions</a></li>
+ <li><a href="#forast">AST Extensions</a></li>
+ <li><a href="#forparser">Parser Extensions</a></li>
+ <li><a href="#forir">LLVM IR</a></li>
+ <li><a href="#forcodegen">Code Generation</a></li>
+ </ol>
+ </li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="LangImpl6.html">Chapter 6</a>: Extending the Language:
+User-defined Operators</li>
+</ul>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 5 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 5 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. Parts 1-4 described the implementation of the simple
+Kaleidoscope language and included support for generating LLVM IR, followed by
+optimizations and a JIT compiler. Unfortunately, as presented, Kaleidoscope is
+mostly useless: it has no control flow other than call and return. This means
+that you can't have conditional branches in the code, significantly limiting its
+power. In this episode of "build that compiler", we'll extend Kaleidoscope to
+have an if/then/else expression plus a simple 'for' loop.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="ifthen">If/Then/Else</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Extending Kaleidoscope to support if/then/else is quite straightforward. It
+basically requires adding support for this "new" concept to the lexer,
+parser, AST, and LLVM code emitter. This example is nice, because it shows how
+easy it is to "grow" a language over time, incrementally extending it as new
+ideas are discovered.</p>
+
+<p>Before we get going on "how" we add this extension, lets talk about "what" we
+want. The basic idea is that we want to be able to write this sort of thing:
+</p>
+
+<div class="doc_code">
+<pre>
+def fib(x)
+ if x &lt; 3 then
+ 1
+ else
+ fib(x-1)+fib(x-2);
+</pre>
+</div>
+
+<p>In Kaleidoscope, every construct is an expression: there are no statements.
+As such, the if/then/else expression needs to return a value like any other.
+Since we're using a mostly functional form, we'll have it evaluate its
+conditional, then return the 'then' or 'else' value based on how the condition
+was resolved. This is very similar to the C "?:" expression.</p>
+
+<p>The semantics of the if/then/else expression is that it evaluates the
+condition to a boolean equality value: 0.0 is considered to be false and
+everything else is considered to be true.
+If the condition is true, the first subexpression is evaluated and returned, if
+the condition is false, the second subexpression is evaluated and returned.
+Since Kaleidoscope allows side-effects, this behavior is important to nail down.
+</p>
+
+<p>Now that we know what we "want", lets break this down into its constituent
+pieces.</p>
+
+<!-- ======================================================================= -->
+<h4><a name="iflexer">Lexer Extensions for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+
+<div>
+
+<p>The lexer extensions are straightforward. First we add new enum values
+for the relevant tokens:</p>
+
+<div class="doc_code">
+<pre>
+ // control
+ tok_if = -6, tok_then = -7, tok_else = -8,
+</pre>
+</div>
+
+<p>Once we have that, we recognize the new keywords in the lexer. This is pretty simple
+stuff:</p>
+
+<div class="doc_code">
+<pre>
+ ...
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ <b>if (IdentifierStr == "if") return tok_if;
+ if (IdentifierStr == "then") return tok_then;
+ if (IdentifierStr == "else") return tok_else;</b>
+ return tok_identifier;
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="ifast">AST Extensions for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>To represent the new expression we add a new AST node for it:</p>
+
+<div class="doc_code">
+<pre>
+/// IfExprAST - Expression class for if/then/else.
+class IfExprAST : public ExprAST {
+ ExprAST *Cond, *Then, *Else;
+public:
+ IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
+ : Cond(cond), Then(then), Else(_else) {}
+ virtual Value *Codegen();
+};
+</pre>
+</div>
+
+<p>The AST node just has pointers to the various subexpressions.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="ifparser">Parser Extensions for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Now that we have the relevant tokens coming from the lexer and we have the
+AST node to build, our parsing logic is relatively straightforward. First we
+define a new parsing function:</p>
+
+<div class="doc_code">
+<pre>
+/// ifexpr ::= 'if' expression 'then' expression 'else' expression
+static ExprAST *ParseIfExpr() {
+ getNextToken(); // eat the if.
+
+ // condition.
+ ExprAST *Cond = ParseExpression();
+ if (!Cond) return 0;
+
+ if (CurTok != tok_then)
+ return Error("expected then");
+ getNextToken(); // eat the then
+
+ ExprAST *Then = ParseExpression();
+ if (Then == 0) return 0;
+
+ if (CurTok != tok_else)
+ return Error("expected else");
+
+ getNextToken();
+
+ ExprAST *Else = ParseExpression();
+ if (!Else) return 0;
+
+ return new IfExprAST(Cond, Then, Else);
+}
+</pre>
+</div>
+
+<p>Next we hook it up as a primary expression:</p>
+
+<div class="doc_code">
+<pre>
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ <b>case tok_if: return ParseIfExpr();</b>
+ }
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="ifir">LLVM IR for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Now that we have it parsing and building the AST, the final piece is adding
+LLVM code generation support. This is the most interesting part of the
+if/then/else example, because this is where it starts to introduce new concepts.
+All of the code above has been thoroughly described in previous chapters.
+</p>
+
+<p>To motivate the code we want to produce, lets take a look at a simple
+example. Consider:</p>
+
+<div class="doc_code">
+<pre>
+extern foo();
+extern bar();
+def baz(x) if x then foo() else bar();
+</pre>
+</div>
+
+<p>If you disable optimizations, the code you'll (soon) get from Kaleidoscope
+looks like this:</p>
+
+<div class="doc_code">
+<pre>
+declare double @foo()
+
+declare double @bar()
+
+define double @baz(double %x) {
+entry:
+ %ifcond = fcmp one double %x, 0.000000e+00
+ br i1 %ifcond, label %then, label %else
+
+then: ; preds = %entry
+ %calltmp = call double @foo()
+ br label %ifcont
+
+else: ; preds = %entry
+ %calltmp1 = call double @bar()
+ br label %ifcont
+
+ifcont: ; preds = %else, %then
+ %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
+ ret double %iftmp
+}
+</pre>
+</div>
+
+<p>To visualize the control flow graph, you can use a nifty feature of the LLVM
+'<a href="http://llvm.org/cmds/opt.html">opt</a>' tool. If you put this LLVM IR
+into "t.ll" and run "<tt>llvm-as &lt; t.ll | opt -analyze -view-cfg</tt>", <a
+href="../ProgrammersManual.html#ViewGraph">a window will pop up</a> and you'll
+see this graph:</p>
+
+<div style="text-align: center"><img src="LangImpl5-cfg.png" alt="Example CFG" width="423"
+height="315"></div>
+
+<p>Another way to get this is to call "<tt>F-&gt;viewCFG()</tt>" or
+"<tt>F-&gt;viewCFGOnly()</tt>" (where F is a "<tt>Function*</tt>") either by
+inserting actual calls into the code and recompiling or by calling these in the
+debugger. LLVM has many nice features for visualizing various graphs.</p>
+
+<p>Getting back to the generated code, it is fairly simple: the entry block
+evaluates the conditional expression ("x" in our case here) and compares the
+result to 0.0 with the "<tt><a href="../LangRef.html#i_fcmp">fcmp</a> one</tt>"
+instruction ('one' is "Ordered and Not Equal"). Based on the result of this
+expression, the code jumps to either the "then" or "else" blocks, which contain
+the expressions for the true/false cases.</p>
+
+<p>Once the then/else blocks are finished executing, they both branch back to the
+'ifcont' block to execute the code that happens after the if/then/else. In this
+case the only thing left to do is to return to the caller of the function. The
+question then becomes: how does the code know which expression to return?</p>
+
+<p>The answer to this question involves an important SSA operation: the
+<a href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Phi
+operation</a>. If you're not familiar with SSA, <a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">the wikipedia
+article</a> is a good introduction and there are various other introductions to
+it available on your favorite search engine. The short version is that
+"execution" of the Phi operation requires "remembering" which block control came
+from. The Phi operation takes on the value corresponding to the input control
+block. In this case, if control comes in from the "then" block, it gets the
+value of "calltmp". If control comes from the "else" block, it gets the value
+of "calltmp1".</p>
+
+<p>At this point, you are probably starting to think "Oh no! This means my
+simple and elegant front-end will have to start generating SSA form in order to
+use LLVM!". Fortunately, this is not the case, and we strongly advise
+<em>not</em> implementing an SSA construction algorithm in your front-end
+unless there is an amazingly good reason to do so. In practice, there are two
+sorts of values that float around in code written for your average imperative
+programming language that might need Phi nodes:</p>
+
+<ol>
+<li>Code that involves user variables: <tt>x = 1; x = x + 1; </tt></li>
+<li>Values that are implicit in the structure of your AST, such as the Phi node
+in this case.</li>
+</ol>
+
+<p>In <a href="LangImpl7.html">Chapter 7</a> of this tutorial ("mutable
+variables"), we'll talk about #1
+in depth. For now, just believe me that you don't need SSA construction to
+handle this case. For #2, you have the choice of using the techniques that we will
+describe for #1, or you can insert Phi nodes directly, if convenient. In this
+case, it is really really easy to generate the Phi node, so we choose to do it
+directly.</p>
+
+<p>Okay, enough of the motivation and overview, lets generate code!</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="ifcodegen">Code Generation for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>In order to generate code for this, we implement the <tt>Codegen</tt> method
+for <tt>IfExprAST</tt>:</p>
+
+<div class="doc_code">
+<pre>
+Value *IfExprAST::Codegen() {
+ Value *CondV = Cond-&gt;Codegen();
+ if (CondV == 0) return 0;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ CondV = Builder.CreateFCmpONE(CondV,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "ifcond");
+</pre>
+</div>
+
+<p>This code is straightforward and similar to what we saw before. We emit the
+expression for the condition, then compare that value to zero to get a truth
+value as a 1-bit (bool) value.</p>
+
+<div class="doc_code">
+<pre>
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+
+ // Create blocks for the then and else cases. Insert the 'then' block at the
+ // end of the function.
+ BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
+ BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
+ BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+
+ Builder.CreateCondBr(CondV, ThenBB, ElseBB);
+</pre>
+</div>
+
+<p>This code creates the basic blocks that are related to the if/then/else
+statement, and correspond directly to the blocks in the example above. The
+first line gets the current Function object that is being built. It
+gets this by asking the builder for the current BasicBlock, and asking that
+block for its "parent" (the function it is currently embedded into).</p>
+
+<p>Once it has that, it creates three blocks. Note that it passes "TheFunction"
+into the constructor for the "then" block. This causes the constructor to
+automatically insert the new block into the end of the specified function. The
+other two blocks are created, but aren't yet inserted into the function.</p>
+
+<p>Once the blocks are created, we can emit the conditional branch that chooses
+between them. Note that creating new blocks does not implicitly affect the
+IRBuilder, so it is still inserting into the block that the condition
+went into. Also note that it is creating a branch to the "then" block and the
+"else" block, even though the "else" block isn't inserted into the function yet.
+This is all ok: it is the standard way that LLVM supports forward
+references.</p>
+
+<div class="doc_code">
+<pre>
+ // Emit then value.
+ Builder.SetInsertPoint(ThenBB);
+
+ Value *ThenV = Then-&gt;Codegen();
+ if (ThenV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
+ ThenBB = Builder.GetInsertBlock();
+</pre>
+</div>
+
+<p>After the conditional branch is inserted, we move the builder to start
+inserting into the "then" block. Strictly speaking, this call moves the
+insertion point to be at the end of the specified block. However, since the
+"then" block is empty, it also starts out by inserting at the beginning of the
+block. :)</p>
+
+<p>Once the insertion point is set, we recursively codegen the "then" expression
+from the AST. To finish off the "then" block, we create an unconditional branch
+to the merge block. One interesting (and very important) aspect of the LLVM IR
+is that it <a href="../LangRef.html#functionstructure">requires all basic blocks
+to be "terminated"</a> with a <a href="../LangRef.html#terminators">control flow
+instruction</a> such as return or branch. This means that all control flow,
+<em>including fall throughs</em> must be made explicit in the LLVM IR. If you
+violate this rule, the verifier will emit an error.</p>
+
+<p>The final line here is quite subtle, but is very important. The basic issue
+is that when we create the Phi node in the merge block, we need to set up the
+block/value pairs that indicate how the Phi will work. Importantly, the Phi
+node expects to have an entry for each predecessor of the block in the CFG. Why
+then, are we getting the current block when we just set it to ThenBB 5 lines
+above? The problem is that the "Then" expression may actually itself change the
+block that the Builder is emitting into if, for example, it contains a nested
+"if/then/else" expression. Because calling Codegen recursively could
+arbitrarily change the notion of the current block, we are required to get an
+up-to-date value for code that will set up the Phi node.</p>
+
+<div class="doc_code">
+<pre>
+ // Emit else block.
+ TheFunction-&gt;getBasicBlockList().push_back(ElseBB);
+ Builder.SetInsertPoint(ElseBB);
+
+ Value *ElseV = Else-&gt;Codegen();
+ if (ElseV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
+ ElseBB = Builder.GetInsertBlock();
+</pre>
+</div>
+
+<p>Code generation for the 'else' block is basically identical to codegen for
+the 'then' block. The only significant difference is the first line, which adds
+the 'else' block to the function. Recall previously that the 'else' block was
+created, but not added to the function. Now that the 'then' and 'else' blocks
+are emitted, we can finish up with the merge code:</p>
+
+<div class="doc_code">
+<pre>
+ // Emit merge block.
+ TheFunction->getBasicBlockList().push_back(MergeBB);
+ Builder.SetInsertPoint(MergeBB);
+ PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+ "iftmp");
+
+ PN->addIncoming(ThenV, ThenBB);
+ PN->addIncoming(ElseV, ElseBB);
+ return PN;
+}
+</pre>
+</div>
+
+<p>The first two lines here are now familiar: the first adds the "merge" block
+to the Function object (it was previously floating, like the else block above).
+The second block changes the insertion point so that newly created code will go
+into the "merge" block. Once that is done, we need to create the PHI node and
+set up the block/value pairs for the PHI.</p>
+
+<p>Finally, the CodeGen function returns the phi node as the value computed by
+the if/then/else expression. In our example above, this returned value will
+feed into the code for the top-level function, which will create the return
+instruction.</p>
+
+<p>Overall, we now have the ability to execute conditional code in
+Kaleidoscope. With this extension, Kaleidoscope is a fairly complete language
+that can calculate a wide variety of numeric functions. Next up we'll add
+another useful expression that is familiar from non-functional languages...</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="for">'for' Loop Expression</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Now that we know how to add basic control flow constructs to the language,
+we have the tools to add more powerful things. Lets add something more
+aggressive, a 'for' expression:</p>
+
+<div class="doc_code">
+<pre>
+ extern putchard(char)
+ def printstar(n)
+ for i = 1, i &lt; n, 1.0 in
+ putchard(42); # ascii 42 = '*'
+
+ # print 100 '*' characters
+ printstar(100);
+</pre>
+</div>
+
+<p>This expression defines a new variable ("i" in this case) which iterates from
+a starting value, while the condition ("i &lt; n" in this case) is true,
+incrementing by an optional step value ("1.0" in this case). If the step value
+is omitted, it defaults to 1.0. While the loop is true, it executes its
+body expression. Because we don't have anything better to return, we'll just
+define the loop as always returning 0.0. In the future when we have mutable
+variables, it will get more useful.</p>
+
+<p>As before, lets talk about the changes that we need to Kaleidoscope to
+support this.</p>
+
+<!-- ======================================================================= -->
+<h4><a name="forlexer">Lexer Extensions for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>The lexer extensions are the same sort of thing as for if/then/else:</p>
+
+<div class="doc_code">
+<pre>
+ ... in enum Token ...
+ // control
+ tok_if = -6, tok_then = -7, tok_else = -8,
+<b> tok_for = -9, tok_in = -10</b>
+
+ ... in gettok ...
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ if (IdentifierStr == "if") return tok_if;
+ if (IdentifierStr == "then") return tok_then;
+ if (IdentifierStr == "else") return tok_else;
+ <b>if (IdentifierStr == "for") return tok_for;
+ if (IdentifierStr == "in") return tok_in;</b>
+ return tok_identifier;
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="forast">AST Extensions for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>The AST node is just as simple. It basically boils down to capturing
+the variable name and the constituent expressions in the node.</p>
+
+<div class="doc_code">
+<pre>
+/// ForExprAST - Expression class for for/in.
+class ForExprAST : public ExprAST {
+ std::string VarName;
+ ExprAST *Start, *End, *Step, *Body;
+public:
+ ForExprAST(const std::string &amp;varname, ExprAST *start, ExprAST *end,
+ ExprAST *step, ExprAST *body)
+ : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
+ virtual Value *Codegen();
+};
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="forparser">Parser Extensions for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>The parser code is also fairly standard. The only interesting thing here is
+handling of the optional step value. The parser code handles it by checking to
+see if the second comma is present. If not, it sets the step value to null in
+the AST node:</p>
+
+<div class="doc_code">
+<pre>
+/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
+static ExprAST *ParseForExpr() {
+ getNextToken(); // eat the for.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after for");
+
+ std::string IdName = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '=')
+ return Error("expected '=' after for");
+ getNextToken(); // eat '='.
+
+
+ ExprAST *Start = ParseExpression();
+ if (Start == 0) return 0;
+ if (CurTok != ',')
+ return Error("expected ',' after for start value");
+ getNextToken();
+
+ ExprAST *End = ParseExpression();
+ if (End == 0) return 0;
+
+ // The step value is optional.
+ ExprAST *Step = 0;
+ if (CurTok == ',') {
+ getNextToken();
+ Step = ParseExpression();
+ if (Step == 0) return 0;
+ }
+
+ if (CurTok != tok_in)
+ return Error("expected 'in' after for");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new ForExprAST(IdName, Start, End, Step, Body);
+}
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="forir">LLVM IR for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Now we get to the good part: the LLVM IR we want to generate for this thing.
+With the simple example above, we get this LLVM IR (note that this dump is
+generated with optimizations disabled for clarity):
+</p>
+
+<div class="doc_code">
+<pre>
+declare double @putchard(double)
+
+define double @printstar(double %n) {
+entry:
+ ; initial value = 1.0 (inlined into phi)
+ br label %loop
+
+loop: ; preds = %loop, %entry
+ %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
+ ; body
+ %calltmp = call double @putchard(double 4.200000e+01)
+ ; increment
+ %nextvar = fadd double %i, 1.000000e+00
+
+ ; termination test
+ %cmptmp = fcmp ult double %i, %n
+ %booltmp = uitofp i1 %cmptmp to double
+ %loopcond = fcmp one double %booltmp, 0.000000e+00
+ br i1 %loopcond, label %loop, label %afterloop
+
+afterloop: ; preds = %loop
+ ; loop always returns 0.0
+ ret double 0.000000e+00
+}
+</pre>
+</div>
+
+<p>This loop contains all the same constructs we saw before: a phi node, several
+expressions, and some basic blocks. Lets see how this fits together.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="forcodegen">Code Generation for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>The first part of Codegen is very simple: we just output the start expression
+for the loop value:</p>
+
+<div class="doc_code">
+<pre>
+Value *ForExprAST::Codegen() {
+ // Emit the start code first, without 'variable' in scope.
+ Value *StartVal = Start-&gt;Codegen();
+ if (StartVal == 0) return 0;
+</pre>
+</div>
+
+<p>With this out of the way, the next step is to set up the LLVM basic block
+for the start of the loop body. In the case above, the whole loop body is one
+block, but remember that the body code itself could consist of multiple blocks
+(e.g. if it contains an if/then/else or a for/in expression).</p>
+
+<div class="doc_code">
+<pre>
+ // Make the new basic block for the loop header, inserting after current
+ // block.
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+ BasicBlock *PreheaderBB = Builder.GetInsertBlock();
+ BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+
+ // Insert an explicit fall through from the current block to the LoopBB.
+ Builder.CreateBr(LoopBB);
+</pre>
+</div>
+
+<p>This code is similar to what we saw for if/then/else. Because we will need
+it to create the Phi node, we remember the block that falls through into the
+loop. Once we have that, we create the actual block that starts the loop and
+create an unconditional branch for the fall-through between the two blocks.</p>
+
+<div class="doc_code">
+<pre>
+ // Start insertion in LoopBB.
+ Builder.SetInsertPoint(LoopBB);
+
+ // Start the PHI node with an entry for Start.
+ PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
+ Variable-&gt;addIncoming(StartVal, PreheaderBB);
+</pre>
+</div>
+
+<p>Now that the "preheader" for the loop is set up, we switch to emitting code
+for the loop body. To begin with, we move the insertion point and create the
+PHI node for the loop induction variable. Since we already know the incoming
+value for the starting value, we add it to the Phi node. Note that the Phi will
+eventually get a second value for the backedge, but we can't set it up yet
+(because it doesn't exist!).</p>
+
+<div class="doc_code">
+<pre>
+ // Within the loop, the variable is defined equal to the PHI node. If it
+ // shadows an existing variable, we have to restore it, so save it now.
+ Value *OldVal = NamedValues[VarName];
+ NamedValues[VarName] = Variable;
+
+ // Emit the body of the loop. This, like any other expr, can change the
+ // current BB. Note that we ignore the value computed by the body, but don't
+ // allow an error.
+ if (Body-&gt;Codegen() == 0)
+ return 0;
+</pre>
+</div>
+
+<p>Now the code starts to get more interesting. Our 'for' loop introduces a new
+variable to the symbol table. This means that our symbol table can now contain
+either function arguments or loop variables. To handle this, before we codegen
+the body of the loop, we add the loop variable as the current value for its
+name. Note that it is possible that there is a variable of the same name in the
+outer scope. It would be easy to make this an error (emit an error and return
+null if there is already an entry for VarName) but we choose to allow shadowing
+of variables. In order to handle this correctly, we remember the Value that
+we are potentially shadowing in <tt>OldVal</tt> (which will be null if there is
+no shadowed variable).</p>
+
+<p>Once the loop variable is set into the symbol table, the code recursively
+codegen's the body. This allows the body to use the loop variable: any
+references to it will naturally find it in the symbol table.</p>
+
+<div class="doc_code">
+<pre>
+ // Emit the step value.
+ Value *StepVal;
+ if (Step) {
+ StepVal = Step-&gt;Codegen();
+ if (StepVal == 0) return 0;
+ } else {
+ // If not specified, use 1.0.
+ StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+ }
+
+ Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
+</pre>
+</div>
+
+<p>Now that the body is emitted, we compute the next value of the iteration
+variable by adding the step value, or 1.0 if it isn't present. '<tt>NextVar</tt>'
+will be the value of the loop variable on the next iteration of the loop.</p>
+
+<div class="doc_code">
+<pre>
+ // Compute the end condition.
+ Value *EndCond = End-&gt;Codegen();
+ if (EndCond == 0) return EndCond;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ EndCond = Builder.CreateFCmpONE(EndCond,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "loopcond");
+</pre>
+</div>
+
+<p>Finally, we evaluate the exit value of the loop, to determine whether the
+loop should exit. This mirrors the condition evaluation for the if/then/else
+statement.</p>
+
+<div class="doc_code">
+<pre>
+ // Create the "after loop" block and insert it.
+ BasicBlock *LoopEndBB = Builder.GetInsertBlock();
+ BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+
+ // Insert the conditional branch into the end of LoopEndBB.
+ Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
+
+ // Any new code will be inserted in AfterBB.
+ Builder.SetInsertPoint(AfterBB);
+</pre>
+</div>
+
+<p>With the code for the body of the loop complete, we just need to finish up
+the control flow for it. This code remembers the end block (for the phi node),
+then creates the block for the loop exit ("afterloop"). Based on the value of
+the exit condition, it creates a conditional branch that chooses between
+executing the loop again and exiting the loop. Any future code is emitted in
+the "afterloop" block, so it sets the insertion position to it.</p>
+
+<div class="doc_code">
+<pre>
+ // Add a new entry to the PHI node for the backedge.
+ Variable-&gt;addIncoming(NextVar, LoopEndBB);
+
+ // Restore the unshadowed variable.
+ if (OldVal)
+ NamedValues[VarName] = OldVal;
+ else
+ NamedValues.erase(VarName);
+
+ // for expr always returns 0.0.
+ return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+}
+</pre>
+</div>
+
+<p>The final code handles various cleanups: now that we have the "NextVar"
+value, we can add the incoming value to the loop PHI node. After that, we
+remove the loop variable from the symbol table, so that it isn't in scope after
+the for loop. Finally, code generation of the for loop always returns 0.0, so
+that is what we return from <tt>ForExprAST::Codegen</tt>.</p>
+
+<p>With this, we conclude the "adding control flow to Kaleidoscope" chapter of
+the tutorial. In this chapter we added two control flow constructs, and used them to motivate a couple of aspects of the LLVM IR that are important for front-end implementors
+to know. In the next chapter of our saga, we will get a bit crazier and add
+<a href="LangImpl6.html">user-defined operators</a> to our poor innocent
+language.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with the
+if/then/else and for expressions.. To build this example, use:
+</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+clang++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
+# Run
+./toy
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<div class="doc_code">
+<pre>
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/TargetSelect.h"
+#include &lt;cstdio&gt;
+#include &lt;string&gt;
+#include &lt;map&gt;
+#include &lt;vector&gt;
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5,
+
+ // control
+ tok_if = -6, tok_then = -7, tok_else = -8,
+ tok_for = -9, tok_in = -10
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ if (IdentifierStr == "if") return tok_if;
+ if (IdentifierStr == "then") return tok_then;
+ if (IdentifierStr == "else") return tok_else;
+ if (IdentifierStr == "for") return tok_for;
+ if (IdentifierStr == "in") return tok_in;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &amp;name) : Name(name) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector&lt;ExprAST*&gt; Args;
+public:
+ CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// IfExprAST - Expression class for if/then/else.
+class IfExprAST : public ExprAST {
+ ExprAST *Cond, *Then, *Else;
+public:
+ IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
+ : Cond(cond), Then(then), Else(_else) {}
+ virtual Value *Codegen();
+};
+
+/// ForExprAST - Expression class for for/in.
+class ForExprAST : public ExprAST {
+ std::string VarName;
+ ExprAST *Start, *End, *Step, *Body;
+public:
+ ForExprAST(const std::string &amp;varname, ExprAST *start, ExprAST *end,
+ ExprAST *step, ExprAST *body)
+ : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector&lt;std::string&gt; Args;
+public:
+ PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
+ : Name(name), Args(args) {}
+
+ Function *Codegen();
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map&lt;char, int&gt; BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec &lt;= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector&lt;ExprAST*&gt; Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// ifexpr ::= 'if' expression 'then' expression 'else' expression
+static ExprAST *ParseIfExpr() {
+ getNextToken(); // eat the if.
+
+ // condition.
+ ExprAST *Cond = ParseExpression();
+ if (!Cond) return 0;
+
+ if (CurTok != tok_then)
+ return Error("expected then");
+ getNextToken(); // eat the then
+
+ ExprAST *Then = ParseExpression();
+ if (Then == 0) return 0;
+
+ if (CurTok != tok_else)
+ return Error("expected else");
+
+ getNextToken();
+
+ ExprAST *Else = ParseExpression();
+ if (!Else) return 0;
+
+ return new IfExprAST(Cond, Then, Else);
+}
+
+/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
+static ExprAST *ParseForExpr() {
+ getNextToken(); // eat the for.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after for");
+
+ std::string IdName = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '=')
+ return Error("expected '=' after for");
+ getNextToken(); // eat '='.
+
+
+ ExprAST *Start = ParseExpression();
+ if (Start == 0) return 0;
+ if (CurTok != ',')
+ return Error("expected ',' after for start value");
+ getNextToken();
+
+ ExprAST *End = ParseExpression();
+ if (End == 0) return 0;
+
+ // The step value is optional.
+ ExprAST *Step = 0;
+ if (CurTok == ',') {
+ getNextToken();
+ Step = ParseExpression();
+ if (Step == 0) return 0;
+ }
+
+ if (CurTok != tok_in)
+ return Error("expected 'in' after for");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new ForExprAST(IdName, Start, End, Step, Body);
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+/// ::= ifexpr
+/// ::= forexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ case tok_if: return ParseIfExpr();
+ case tok_for: return ParseForExpr();
+ }
+}
+
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec &lt; ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec &lt; NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector&lt;std::string&gt; ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder&lt;&gt; Builder(getGlobalContext());
+static std::map&lt;std::string, Value*&gt; NamedValues;
+static FunctionPassManager *TheFPM;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS-&gt;Codegen();
+ Value *R = RHS-&gt;Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '&lt;':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: return ErrorV("invalid binary operator");
+ }
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule-&gt;getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF-&gt;arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector&lt;Value*&gt; ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]-&gt;Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Value *IfExprAST::Codegen() {
+ Value *CondV = Cond-&gt;Codegen();
+ if (CondV == 0) return 0;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ CondV = Builder.CreateFCmpONE(CondV,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "ifcond");
+
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+
+ // Create blocks for the then and else cases. Insert the 'then' block at the
+ // end of the function.
+ BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
+ BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
+ BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+
+ Builder.CreateCondBr(CondV, ThenBB, ElseBB);
+
+ // Emit then value.
+ Builder.SetInsertPoint(ThenBB);
+
+ Value *ThenV = Then-&gt;Codegen();
+ if (ThenV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
+ ThenBB = Builder.GetInsertBlock();
+
+ // Emit else block.
+ TheFunction-&gt;getBasicBlockList().push_back(ElseBB);
+ Builder.SetInsertPoint(ElseBB);
+
+ Value *ElseV = Else-&gt;Codegen();
+ if (ElseV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
+ ElseBB = Builder.GetInsertBlock();
+
+ // Emit merge block.
+ TheFunction-&gt;getBasicBlockList().push_back(MergeBB);
+ Builder.SetInsertPoint(MergeBB);
+ PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+ "iftmp");
+
+ PN-&gt;addIncoming(ThenV, ThenBB);
+ PN-&gt;addIncoming(ElseV, ElseBB);
+ return PN;
+}
+
+Value *ForExprAST::Codegen() {
+ // Output this as:
+ // ...
+ // start = startexpr
+ // goto loop
+ // loop:
+ // variable = phi [start, loopheader], [nextvariable, loopend]
+ // ...
+ // bodyexpr
+ // ...
+ // loopend:
+ // step = stepexpr
+ // nextvariable = variable + step
+ // endcond = endexpr
+ // br endcond, loop, endloop
+ // outloop:
+
+ // Emit the start code first, without 'variable' in scope.
+ Value *StartVal = Start-&gt;Codegen();
+ if (StartVal == 0) return 0;
+
+ // Make the new basic block for the loop header, inserting after current
+ // block.
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+ BasicBlock *PreheaderBB = Builder.GetInsertBlock();
+ BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+
+ // Insert an explicit fall through from the current block to the LoopBB.
+ Builder.CreateBr(LoopBB);
+
+ // Start insertion in LoopBB.
+ Builder.SetInsertPoint(LoopBB);
+
+ // Start the PHI node with an entry for Start.
+ PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
+ Variable-&gt;addIncoming(StartVal, PreheaderBB);
+
+ // Within the loop, the variable is defined equal to the PHI node. If it
+ // shadows an existing variable, we have to restore it, so save it now.
+ Value *OldVal = NamedValues[VarName];
+ NamedValues[VarName] = Variable;
+
+ // Emit the body of the loop. This, like any other expr, can change the
+ // current BB. Note that we ignore the value computed by the body, but don't
+ // allow an error.
+ if (Body-&gt;Codegen() == 0)
+ return 0;
+
+ // Emit the step value.
+ Value *StepVal;
+ if (Step) {
+ StepVal = Step-&gt;Codegen();
+ if (StepVal == 0) return 0;
+ } else {
+ // If not specified, use 1.0.
+ StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+ }
+
+ Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
+
+ // Compute the end condition.
+ Value *EndCond = End-&gt;Codegen();
+ if (EndCond == 0) return EndCond;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ EndCond = Builder.CreateFCmpONE(EndCond,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "loopcond");
+
+ // Create the "after loop" block and insert it.
+ BasicBlock *LoopEndBB = Builder.GetInsertBlock();
+ BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+
+ // Insert the conditional branch into the end of LoopEndBB.
+ Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
+
+ // Any new code will be inserted in AfterBB.
+ Builder.SetInsertPoint(AfterBB);
+
+ // Add a new entry to the PHI node for the backedge.
+ Variable-&gt;addIncoming(NextVar, LoopEndBB);
+
+ // Restore the unshadowed variable.
+ if (OldVal)
+ NamedValues[VarName] = OldVal;
+ else
+ NamedValues.erase(VarName);
+
+
+ // for expr always returns 0.0.
+ return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector&lt;Type*&gt; Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F-&gt;getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F-&gt;eraseFromParent();
+ F = TheModule-&gt;getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F-&gt;empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F-&gt;arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI-&gt;setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+
+ return F;
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto-&gt;Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body-&gt;Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ // Optimize the function.
+ TheFPM-&gt;run(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction-&gt;eraseFromParent();
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static ExecutionEngine *TheExecutionEngine;
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P-&gt;Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ // JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready&gt; ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext &amp;Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['&lt;'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready&gt; ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Create the JIT. This takes ownership of the module.
+ std::string ErrStr;
+ TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&amp;ErrStr).create();
+ if (!TheExecutionEngine) {
+ fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+ exit(1);
+ }
+
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &amp;OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ TheFPM = 0;
+
+ // Print out all of the generated code.
+ TheModule-&gt;dump();
+
+ return 0;
+}
+</pre>
+</div>
+
+<a href="LangImpl6.html">Next: Extending the language: user-defined operators</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/LangImpl6.html b/docs/tutorial/LangImpl6.html
new file mode 100644
index 00000000000..a76298012fd
--- /dev/null
+++ b/docs/tutorial/LangImpl6.html
@@ -0,0 +1,1829 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Extending the Language: User-defined Operators</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Extending the Language: User-defined Operators</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 6
+ <ol>
+ <li><a href="#intro">Chapter 6 Introduction</a></li>
+ <li><a href="#idea">User-defined Operators: the Idea</a></li>
+ <li><a href="#binary">User-defined Binary Operators</a></li>
+ <li><a href="#unary">User-defined Unary Operators</a></li>
+ <li><a href="#example">Kicking the Tires</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="LangImpl7.html">Chapter 7</a>: Extending the Language: Mutable
+Variables / SSA Construction</li>
+</ul>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 6 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 6 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. At this point in our tutorial, we now have a fully
+functional language that is fairly minimal, but also useful. There
+is still one big problem with it, however. Our language doesn't have many
+useful operators (like division, logical negation, or even any comparisons
+besides less-than).</p>
+
+<p>This chapter of the tutorial takes a wild digression into adding user-defined
+operators to the simple and beautiful Kaleidoscope language. This digression now gives
+us a simple and ugly language in some ways, but also a powerful one at the same time.
+One of the great things about creating your own language is that you get to
+decide what is good or bad. In this tutorial we'll assume that it is okay to
+use this as a way to show some interesting parsing techniques.</p>
+
+<p>At the end of this tutorial, we'll run through an example Kaleidoscope
+application that <a href="#example">renders the Mandelbrot set</a>. This gives
+an example of what you can build with Kaleidoscope and its feature set.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="idea">User-defined Operators: the Idea</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+The "operator overloading" that we will add to Kaleidoscope is more general than
+languages like C++. In C++, you are only allowed to redefine existing
+operators: you can't programatically change the grammar, introduce new
+operators, change precedence levels, etc. In this chapter, we will add this
+capability to Kaleidoscope, which will let the user round out the set of
+operators that are supported.</p>
+
+<p>The point of going into user-defined operators in a tutorial like this is to
+show the power and flexibility of using a hand-written parser. Thus far, the parser
+we have been implementing uses recursive descent for most parts of the grammar and
+operator precedence parsing for the expressions. See <a
+href="LangImpl2.html">Chapter 2</a> for details. Without using operator
+precedence parsing, it would be very difficult to allow the programmer to
+introduce new operators into the grammar: the grammar is dynamically extensible
+as the JIT runs.</p>
+
+<p>The two specific features we'll add are programmable unary operators (right
+now, Kaleidoscope has no unary operators at all) as well as binary operators.
+An example of this is:</p>
+
+<div class="doc_code">
+<pre>
+# Logical unary not.
+def unary!(v)
+ if v then
+ 0
+ else
+ 1;
+
+# Define &gt; with the same precedence as &lt;.
+def binary&gt; 10 (LHS RHS)
+ RHS &lt; LHS;
+
+# Binary "logical or", (note that it does not "short circuit")
+def binary| 5 (LHS RHS)
+ if LHS then
+ 1
+ else if RHS then
+ 1
+ else
+ 0;
+
+# Define = with slightly lower precedence than relationals.
+def binary= 9 (LHS RHS)
+ !(LHS &lt; RHS | LHS &gt; RHS);
+</pre>
+</div>
+
+<p>Many languages aspire to being able to implement their standard runtime
+library in the language itself. In Kaleidoscope, we can implement significant
+parts of the language in the library!</p>
+
+<p>We will break down implementation of these features into two parts:
+implementing support for user-defined binary operators and adding unary
+operators.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="binary">User-defined Binary Operators</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Adding support for user-defined binary operators is pretty simple with our
+current framework. We'll first add support for the unary/binary keywords:</p>
+
+<div class="doc_code">
+<pre>
+enum Token {
+ ...
+ <b>// operators
+ tok_binary = -11, tok_unary = -12</b>
+};
+...
+static int gettok() {
+...
+ if (IdentifierStr == "for") return tok_for;
+ if (IdentifierStr == "in") return tok_in;
+ <b>if (IdentifierStr == "binary") return tok_binary;
+ if (IdentifierStr == "unary") return tok_unary;</b>
+ return tok_identifier;
+</pre>
+</div>
+
+<p>This just adds lexer support for the unary and binary keywords, like we
+did in <a href="LangImpl5.html#iflexer">previous chapters</a>. One nice thing
+about our current AST, is that we represent binary operators with full generalisation
+by using their ASCII code as the opcode. For our extended operators, we'll use this
+same representation, so we don't need any new AST or parser support.</p>
+
+<p>On the other hand, we have to be able to represent the definitions of these
+new operators, in the "def binary| 5" part of the function definition. In our
+grammar so far, the "name" for the function definition is parsed as the
+"prototype" production and into the <tt>PrototypeAST</tt> AST node. To
+represent our new user-defined operators as prototypes, we have to extend
+the <tt>PrototypeAST</tt> AST node like this:</p>
+
+<div class="doc_code">
+<pre>
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its argument names as well as if it is an operator.
+class PrototypeAST {
+ std::string Name;
+ std::vector&lt;std::string&gt; Args;
+ <b>bool isOperator;
+ unsigned Precedence; // Precedence if a binary op.</b>
+public:
+ PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args,
+ <b>bool isoperator = false, unsigned prec = 0</b>)
+ : Name(name), Args(args), <b>isOperator(isoperator), Precedence(prec)</b> {}
+
+ <b>bool isUnaryOp() const { return isOperator &amp;&amp; Args.size() == 1; }
+ bool isBinaryOp() const { return isOperator &amp;&amp; Args.size() == 2; }
+
+ char getOperatorName() const {
+ assert(isUnaryOp() || isBinaryOp());
+ return Name[Name.size()-1];
+ }
+
+ unsigned getBinaryPrecedence() const { return Precedence; }</b>
+
+ Function *Codegen();
+};
+</pre>
+</div>
+
+<p>Basically, in addition to knowing a name for the prototype, we now keep track
+of whether it was an operator, and if it was, what precedence level the operator
+is at. The precedence is only used for binary operators (as you'll see below,
+it just doesn't apply for unary operators). Now that we have a way to represent
+the prototype for a user-defined operator, we need to parse it:</p>
+
+<div class="doc_code">
+<pre>
+/// prototype
+/// ::= id '(' id* ')'
+<b>/// ::= binary LETTER number? (id, id)</b>
+static PrototypeAST *ParsePrototype() {
+ std::string FnName;
+
+ <b>unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
+ unsigned BinaryPrecedence = 30;</b>
+
+ switch (CurTok) {
+ default:
+ return ErrorP("Expected function name in prototype");
+ case tok_identifier:
+ FnName = IdentifierStr;
+ Kind = 0;
+ getNextToken();
+ break;
+ <b>case tok_binary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected binary operator");
+ FnName = "binary";
+ FnName += (char)CurTok;
+ Kind = 2;
+ getNextToken();
+
+ // Read the precedence if present.
+ if (CurTok == tok_number) {
+ if (NumVal &lt; 1 || NumVal &gt; 100)
+ return ErrorP("Invalid precedecnce: must be 1..100");
+ BinaryPrecedence = (unsigned)NumVal;
+ getNextToken();
+ }
+ break;</b>
+ }
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector&lt;std::string&gt; ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ <b>// Verify right number of names for operator.
+ if (Kind &amp;&amp; ArgNames.size() != Kind)
+ return ErrorP("Invalid number of operands for operator");
+
+ return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);</b>
+}
+</pre>
+</div>
+
+<p>This is all fairly straightforward parsing code, and we have already seen
+a lot of similar code in the past. One interesting part about the code above is
+the couple lines that set up <tt>FnName</tt> for binary operators. This builds names
+like "binary@" for a newly defined "@" operator. This then takes advantage of the
+fact that symbol names in the LLVM symbol table are allowed to have any character in
+them, including embedded nul characters.</p>
+
+<p>The next interesting thing to add, is codegen support for these binary operators.
+Given our current structure, this is a simple addition of a default case for our
+existing binary operator node:</p>
+
+<div class="doc_code">
+<pre>
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS-&gt;Codegen();
+ Value *R = RHS-&gt;Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '&lt;':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ <b>default: break;</b>
+ }
+
+ <b>// If it wasn't a builtin binary operator, it must be a user defined one. Emit
+ // a call to it.
+ Function *F = TheModule-&gt;getFunction(std::string("binary")+Op);
+ assert(F &amp;&amp; "binary operator not found!");
+
+ Value *Ops[2] = { L, R };
+ return Builder.CreateCall(F, Ops, "binop");</b>
+}
+
+</pre>
+</div>
+
+<p>As you can see above, the new code is actually really simple. It just does
+a lookup for the appropriate operator in the symbol table and generates a
+function call to it. Since user-defined operators are just built as normal
+functions (because the "prototype" boils down to a function with the right
+name) everything falls into place.</p>
+
+<p>The final piece of code we are missing, is a bit of top-level magic:</p>
+
+<div class="doc_code">
+<pre>
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto->Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ <b>// If this is an operator, install it.
+ if (Proto-&gt;isBinaryOp())
+ BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();</b>
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body-&gt;Codegen()) {
+ ...
+</pre>
+</div>
+
+<p>Basically, before codegening a function, if it is a user-defined operator, we
+register it in the precedence table. This allows the binary operator parsing
+logic we already have in place to handle it. Since we are working on a fully-general operator precedence parser, this is all we need to do to "extend the grammar".</p>
+
+<p>Now we have useful user-defined binary operators. This builds a lot
+on the previous framework we built for other operators. Adding unary operators
+is a bit more challenging, because we don't have any framework for it yet - lets
+see what it takes.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="unary">User-defined Unary Operators</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Since we don't currently support unary operators in the Kaleidoscope
+language, we'll need to add everything to support them. Above, we added simple
+support for the 'unary' keyword to the lexer. In addition to that, we need an
+AST node:</p>
+
+<div class="doc_code">
+<pre>
+/// UnaryExprAST - Expression class for a unary operator.
+class UnaryExprAST : public ExprAST {
+ char Opcode;
+ ExprAST *Operand;
+public:
+ UnaryExprAST(char opcode, ExprAST *operand)
+ : Opcode(opcode), Operand(operand) {}
+ virtual Value *Codegen();
+};
+</pre>
+</div>
+
+<p>This AST node is very simple and obvious by now. It directly mirrors the
+binary operator AST node, except that it only has one child. With this, we
+need to add the parsing logic. Parsing a unary operator is pretty simple: we'll
+add a new function to do it:</p>
+
+<div class="doc_code">
+<pre>
+/// unary
+/// ::= primary
+/// ::= '!' unary
+static ExprAST *ParseUnary() {
+ // If the current token is not an operator, it must be a primary expr.
+ if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
+ return ParsePrimary();
+
+ // If this is a unary operator, read it.
+ int Opc = CurTok;
+ getNextToken();
+ if (ExprAST *Operand = ParseUnary())
+ return new UnaryExprAST(Opc, Operand);
+ return 0;
+}
+</pre>
+</div>
+
+<p>The grammar we add is pretty straightforward here. If we see a unary
+operator when parsing a primary operator, we eat the operator as a prefix and
+parse the remaining piece as another unary operator. This allows us to handle
+multiple unary operators (e.g. "!!x"). Note that unary operators can't have
+ambiguous parses like binary operators can, so there is no need for precedence
+information.</p>
+
+<p>The problem with this function, is that we need to call ParseUnary from somewhere.
+To do this, we change previous callers of ParsePrimary to call ParseUnary
+instead:</p>
+
+<div class="doc_code">
+<pre>
+/// binoprhs
+/// ::= ('+' unary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ ...
+ <b>// Parse the unary expression after the binary operator.
+ ExprAST *RHS = ParseUnary();
+ if (!RHS) return 0;</b>
+ ...
+}
+/// expression
+/// ::= unary binoprhs
+///
+static ExprAST *ParseExpression() {
+ <b>ExprAST *LHS = ParseUnary();</b>
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+</pre>
+</div>
+
+<p>With these two simple changes, we are now able to parse unary operators and build the
+AST for them. Next up, we need to add parser support for prototypes, to parse
+the unary operator prototype. We extend the binary operator code above
+with:</p>
+
+<div class="doc_code">
+<pre>
+/// prototype
+/// ::= id '(' id* ')'
+/// ::= binary LETTER number? (id, id)
+<b>/// ::= unary LETTER (id)</b>
+static PrototypeAST *ParsePrototype() {
+ std::string FnName;
+
+ unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
+ unsigned BinaryPrecedence = 30;
+
+ switch (CurTok) {
+ default:
+ return ErrorP("Expected function name in prototype");
+ case tok_identifier:
+ FnName = IdentifierStr;
+ Kind = 0;
+ getNextToken();
+ break;
+ <b>case tok_unary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected unary operator");
+ FnName = "unary";
+ FnName += (char)CurTok;
+ Kind = 1;
+ getNextToken();
+ break;</b>
+ case tok_binary:
+ ...
+</pre>
+</div>
+
+<p>As with binary operators, we name unary operators with a name that includes
+the operator character. This assists us at code generation time. Speaking of,
+the final piece we need to add is codegen support for unary operators. It looks
+like this:</p>
+
+<div class="doc_code">
+<pre>
+Value *UnaryExprAST::Codegen() {
+ Value *OperandV = Operand->Codegen();
+ if (OperandV == 0) return 0;
+
+ Function *F = TheModule->getFunction(std::string("unary")+Opcode);
+ if (F == 0)
+ return ErrorV("Unknown unary operator");
+
+ return Builder.CreateCall(F, OperandV, "unop");
+}
+</pre>
+</div>
+
+<p>This code is similar to, but simpler than, the code for binary operators. It
+is simpler primarily because it doesn't need to handle any predefined operators.
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="example">Kicking the Tires</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>It is somewhat hard to believe, but with a few simple extensions we've
+covered in the last chapters, we have grown a real-ish language. With this, we
+can do a lot of interesting things, including I/O, math, and a bunch of other
+things. For example, we can now add a nice sequencing operator (printd is
+defined to print out the specified value and a newline):</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>extern printd(x);</b>
+Read extern:
+declare double @printd(double)
+
+ready&gt; <b>def binary : 1 (x y) 0; # Low-precedence operator that ignores operands.</b>
+..
+ready&gt; <b>printd(123) : printd(456) : printd(789);</b>
+123.000000
+456.000000
+789.000000
+Evaluated to 0.000000
+</pre>
+</div>
+
+<p>We can also define a bunch of other "primitive" operations, such as:</p>
+
+<div class="doc_code">
+<pre>
+# Logical unary not.
+def unary!(v)
+ if v then
+ 0
+ else
+ 1;
+
+# Unary negate.
+def unary-(v)
+ 0-v;
+
+# Define &gt; with the same precedence as &lt;.
+def binary&gt; 10 (LHS RHS)
+ RHS &lt; LHS;
+
+# Binary logical or, which does not short circuit.
+def binary| 5 (LHS RHS)
+ if LHS then
+ 1
+ else if RHS then
+ 1
+ else
+ 0;
+
+# Binary logical and, which does not short circuit.
+def binary&amp; 6 (LHS RHS)
+ if !LHS then
+ 0
+ else
+ !!RHS;
+
+# Define = with slightly lower precedence than relationals.
+def binary = 9 (LHS RHS)
+ !(LHS &lt; RHS | LHS &gt; RHS);
+
+# Define ':' for sequencing: as a low-precedence operator that ignores operands
+# and just returns the RHS.
+def binary : 1 (x y) y;
+</pre>
+</div>
+
+
+<p>Given the previous if/then/else support, we can also define interesting
+functions for I/O. For example, the following prints out a character whose
+"density" reflects the value passed in: the lower the value, the denser the
+character:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt;
+<b>
+extern putchard(char)
+def printdensity(d)
+ if d &gt; 8 then
+ putchard(32) # ' '
+ else if d &gt; 4 then
+ putchard(46) # '.'
+ else if d &gt; 2 then
+ putchard(43) # '+'
+ else
+ putchard(42); # '*'</b>
+...
+ready&gt; <b>printdensity(1): printdensity(2): printdensity(3):
+ printdensity(4): printdensity(5): printdensity(9):
+ putchard(10);</b>
+**++.
+Evaluated to 0.000000
+</pre>
+</div>
+
+<p>Based on these simple primitive operations, we can start to define more
+interesting things. For example, here's a little function that solves for the
+number of iterations it takes a function in the complex plane to
+converge:</p>
+
+<div class="doc_code">
+<pre>
+# Determine whether the specific location diverges.
+# Solve for z = z^2 + c in the complex plane.
+def mandleconverger(real imag iters creal cimag)
+ if iters &gt; 255 | (real*real + imag*imag &gt; 4) then
+ iters
+ else
+ mandleconverger(real*real - imag*imag + creal,
+ 2*real*imag + cimag,
+ iters+1, creal, cimag);
+
+# Return the number of iterations required for the iteration to escape
+def mandleconverge(real imag)
+ mandleconverger(real, imag, 0, real, imag);
+</pre>
+</div>
+
+<p>This "<code>z = z<sup>2</sup> + c</code>" function is a beautiful little
+creature that is the basis for computation of
+the <a href="http://en.wikipedia.org/wiki/Mandelbrot_set">Mandelbrot Set</a>.
+Our <tt>mandelconverge</tt> function returns the number of iterations that it
+takes for a complex orbit to escape, saturating to 255. This is not a very
+useful function by itself, but if you plot its value over a two-dimensional
+plane, you can see the Mandelbrot set. Given that we are limited to using
+putchard here, our amazing graphical output is limited, but we can whip together
+something using the density plotter above:</p>
+
+<div class="doc_code">
+<pre>
+# Compute and plot the mandlebrot set with the specified 2 dimensional range
+# info.
+def mandelhelp(xmin xmax xstep ymin ymax ystep)
+ for y = ymin, y &lt; ymax, ystep in (
+ (for x = xmin, x &lt; xmax, xstep in
+ printdensity(mandleconverge(x,y)))
+ : putchard(10)
+ )
+
+# mandel - This is a convenient helper function for plotting the mandelbrot set
+# from the specified position with the specified Magnification.
+def mandel(realstart imagstart realmag imagmag)
+ mandelhelp(realstart, realstart+realmag*78, realmag,
+ imagstart, imagstart+imagmag*40, imagmag);
+</pre>
+</div>
+
+<p>Given this, we can try plotting out the mandlebrot set! Lets try it out:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>mandel(-2.3, -1.3, 0.05, 0.07);</b>
+*******************************+++++++++++*************************************
+*************************+++++++++++++++++++++++*******************************
+**********************+++++++++++++++++++++++++++++****************************
+*******************+++++++++++++++++++++.. ...++++++++*************************
+*****************++++++++++++++++++++++.... ...+++++++++***********************
+***************+++++++++++++++++++++++..... ...+++++++++*********************
+**************+++++++++++++++++++++++.... ....+++++++++********************
+*************++++++++++++++++++++++...... .....++++++++*******************
+************+++++++++++++++++++++....... .......+++++++******************
+***********+++++++++++++++++++.... ... .+++++++*****************
+**********+++++++++++++++++....... .+++++++****************
+*********++++++++++++++........... ...+++++++***************
+********++++++++++++............ ...++++++++**************
+********++++++++++... .......... .++++++++**************
+*******+++++++++..... .+++++++++*************
+*******++++++++...... ..+++++++++*************
+*******++++++....... ..+++++++++*************
+*******+++++...... ..+++++++++*************
+*******.... .... ...+++++++++*************
+*******.... . ...+++++++++*************
+*******+++++...... ...+++++++++*************
+*******++++++....... ..+++++++++*************
+*******++++++++...... .+++++++++*************
+*******+++++++++..... ..+++++++++*************
+********++++++++++... .......... .++++++++**************
+********++++++++++++............ ...++++++++**************
+*********++++++++++++++.......... ...+++++++***************
+**********++++++++++++++++........ .+++++++****************
+**********++++++++++++++++++++.... ... ..+++++++****************
+***********++++++++++++++++++++++....... .......++++++++*****************
+************+++++++++++++++++++++++...... ......++++++++******************
+**************+++++++++++++++++++++++.... ....++++++++********************
+***************+++++++++++++++++++++++..... ...+++++++++*********************
+*****************++++++++++++++++++++++.... ...++++++++***********************
+*******************+++++++++++++++++++++......++++++++*************************
+*********************++++++++++++++++++++++.++++++++***************************
+*************************+++++++++++++++++++++++*******************************
+******************************+++++++++++++************************************
+*******************************************************************************
+*******************************************************************************
+*******************************************************************************
+Evaluated to 0.000000
+ready&gt; <b>mandel(-2, -1, 0.02, 0.04);</b>
+**************************+++++++++++++++++++++++++++++++++++++++++++++++++++++
+***********************++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+*********************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
+*******************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++...
+*****************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.....
+***************++++++++++++++++++++++++++++++++++++++++++++++++++++++++........
+**************++++++++++++++++++++++++++++++++++++++++++++++++++++++...........
+************+++++++++++++++++++++++++++++++++++++++++++++++++++++..............
+***********++++++++++++++++++++++++++++++++++++++++++++++++++........ .
+**********++++++++++++++++++++++++++++++++++++++++++++++.............
+********+++++++++++++++++++++++++++++++++++++++++++..................
+*******+++++++++++++++++++++++++++++++++++++++.......................
+******+++++++++++++++++++++++++++++++++++...........................
+*****++++++++++++++++++++++++++++++++............................
+*****++++++++++++++++++++++++++++...............................
+****++++++++++++++++++++++++++...... .........................
+***++++++++++++++++++++++++......... ...... ...........
+***++++++++++++++++++++++............
+**+++++++++++++++++++++..............
+**+++++++++++++++++++................
+*++++++++++++++++++.................
+*++++++++++++++++............ ...
+*++++++++++++++..............
+*+++....++++................
+*.......... ...........
+*
+*.......... ...........
+*+++....++++................
+*++++++++++++++..............
+*++++++++++++++++............ ...
+*++++++++++++++++++.................
+**+++++++++++++++++++................
+**+++++++++++++++++++++..............
+***++++++++++++++++++++++............
+***++++++++++++++++++++++++......... ...... ...........
+****++++++++++++++++++++++++++...... .........................
+*****++++++++++++++++++++++++++++...............................
+*****++++++++++++++++++++++++++++++++............................
+******+++++++++++++++++++++++++++++++++++...........................
+*******+++++++++++++++++++++++++++++++++++++++.......................
+********+++++++++++++++++++++++++++++++++++++++++++..................
+Evaluated to 0.000000
+ready&gt; <b>mandel(-0.9, -1.4, 0.02, 0.03);</b>
+*******************************************************************************
+*******************************************************************************
+*******************************************************************************
+**********+++++++++++++++++++++************************************************
+*+++++++++++++++++++++++++++++++++++++++***************************************
++++++++++++++++++++++++++++++++++++++++++++++**********************************
+++++++++++++++++++++++++++++++++++++++++++++++++++*****************************
+++++++++++++++++++++++++++++++++++++++++++++++++++++++*************************
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++**********************
++++++++++++++++++++++++++++++++++.........++++++++++++++++++*******************
++++++++++++++++++++++++++++++++.... ......+++++++++++++++++++****************
++++++++++++++++++++++++++++++....... ........+++++++++++++++++++**************
+++++++++++++++++++++++++++++........ ........++++++++++++++++++++************
++++++++++++++++++++++++++++......... .. ...+++++++++++++++++++++**********
+++++++++++++++++++++++++++........... ....++++++++++++++++++++++********
+++++++++++++++++++++++++............. .......++++++++++++++++++++++******
++++++++++++++++++++++++............. ........+++++++++++++++++++++++****
+++++++++++++++++++++++........... ..........++++++++++++++++++++++***
+++++++++++++++++++++........... .........++++++++++++++++++++++*
+++++++++++++++++++............ ...........++++++++++++++++++++
+++++++++++++++++............... .............++++++++++++++++++
+++++++++++++++................. ...............++++++++++++++++
+++++++++++++.................. .................++++++++++++++
++++++++++.................. .................+++++++++++++
+++++++........ . ......... ..++++++++++++
+++............ ...... ....++++++++++
+.............. ...++++++++++
+.............. ....+++++++++
+.............. .....++++++++
+............. ......++++++++
+........... .......++++++++
+......... ........+++++++
+......... ........+++++++
+......... ....+++++++
+........ ...+++++++
+....... ...+++++++
+ ....+++++++
+ .....+++++++
+ ....+++++++
+ ....+++++++
+ ....+++++++
+Evaluated to 0.000000
+ready&gt; <b>^D</b>
+</pre>
+</div>
+
+<p>At this point, you may be starting to realize that Kaleidoscope is a real
+and powerful language. It may not be self-similar :), but it can be used to
+plot things that are!</p>
+
+<p>With this, we conclude the "adding user-defined operators" chapter of the
+tutorial. We have successfully augmented our language, adding the ability to extend the
+language in the library, and we have shown how this can be used to build a simple but
+interesting end-user application in Kaleidoscope. At this point, Kaleidoscope
+can build a variety of applications that are functional and can call functions
+with side-effects, but it can't actually define and mutate a variable itself.
+</p>
+
+<p>Strikingly, variable mutation is an important feature of some
+languages, and it is not at all obvious how to <a href="LangImpl7.html">add
+support for mutable variables</a> without having to add an "SSA construction"
+phase to your front-end. In the next chapter, we will describe how you can
+add variable mutation without building SSA in your front-end.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with the
+if/then/else and for expressions.. To build this example, use:
+</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+clang++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
+# Run
+./toy
+</pre>
+</div>
+
+<p>On some platforms, you will need to specify -rdynamic or -Wl,--export-dynamic
+when linking. This ensures that symbols defined in the main executable are
+exported to the dynamic linker and so are available for symbol resolution at
+run time. This is not needed if you compile your support code into a shared
+library, although doing that will cause problems on Windows.</p>
+
+<p>Here is the code:</p>
+
+<div class="doc_code">
+<pre>
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/TargetSelect.h"
+#include &lt;cstdio&gt;
+#include &lt;string&gt;
+#include &lt;map&gt;
+#include &lt;vector&gt;
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5,
+
+ // control
+ tok_if = -6, tok_then = -7, tok_else = -8,
+ tok_for = -9, tok_in = -10,
+
+ // operators
+ tok_binary = -11, tok_unary = -12
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ if (IdentifierStr == "if") return tok_if;
+ if (IdentifierStr == "then") return tok_then;
+ if (IdentifierStr == "else") return tok_else;
+ if (IdentifierStr == "for") return tok_for;
+ if (IdentifierStr == "in") return tok_in;
+ if (IdentifierStr == "binary") return tok_binary;
+ if (IdentifierStr == "unary") return tok_unary;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &amp;name) : Name(name) {}
+ virtual Value *Codegen();
+};
+
+/// UnaryExprAST - Expression class for a unary operator.
+class UnaryExprAST : public ExprAST {
+ char Opcode;
+ ExprAST *Operand;
+public:
+ UnaryExprAST(char opcode, ExprAST *operand)
+ : Opcode(opcode), Operand(operand) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector&lt;ExprAST*&gt; Args;
+public:
+ CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// IfExprAST - Expression class for if/then/else.
+class IfExprAST : public ExprAST {
+ ExprAST *Cond, *Then, *Else;
+public:
+ IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
+ : Cond(cond), Then(then), Else(_else) {}
+ virtual Value *Codegen();
+};
+
+/// ForExprAST - Expression class for for/in.
+class ForExprAST : public ExprAST {
+ std::string VarName;
+ ExprAST *Start, *End, *Step, *Body;
+public:
+ ForExprAST(const std::string &amp;varname, ExprAST *start, ExprAST *end,
+ ExprAST *step, ExprAST *body)
+ : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes), as well as if it is an operator.
+class PrototypeAST {
+ std::string Name;
+ std::vector&lt;std::string&gt; Args;
+ bool isOperator;
+ unsigned Precedence; // Precedence if a binary op.
+public:
+ PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args,
+ bool isoperator = false, unsigned prec = 0)
+ : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
+
+ bool isUnaryOp() const { return isOperator &amp;&amp; Args.size() == 1; }
+ bool isBinaryOp() const { return isOperator &amp;&amp; Args.size() == 2; }
+
+ char getOperatorName() const {
+ assert(isUnaryOp() || isBinaryOp());
+ return Name[Name.size()-1];
+ }
+
+ unsigned getBinaryPrecedence() const { return Precedence; }
+
+ Function *Codegen();
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map&lt;char, int&gt; BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec &lt;= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector&lt;ExprAST*&gt; Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// ifexpr ::= 'if' expression 'then' expression 'else' expression
+static ExprAST *ParseIfExpr() {
+ getNextToken(); // eat the if.
+
+ // condition.
+ ExprAST *Cond = ParseExpression();
+ if (!Cond) return 0;
+
+ if (CurTok != tok_then)
+ return Error("expected then");
+ getNextToken(); // eat the then
+
+ ExprAST *Then = ParseExpression();
+ if (Then == 0) return 0;
+
+ if (CurTok != tok_else)
+ return Error("expected else");
+
+ getNextToken();
+
+ ExprAST *Else = ParseExpression();
+ if (!Else) return 0;
+
+ return new IfExprAST(Cond, Then, Else);
+}
+
+/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
+static ExprAST *ParseForExpr() {
+ getNextToken(); // eat the for.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after for");
+
+ std::string IdName = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '=')
+ return Error("expected '=' after for");
+ getNextToken(); // eat '='.
+
+
+ ExprAST *Start = ParseExpression();
+ if (Start == 0) return 0;
+ if (CurTok != ',')
+ return Error("expected ',' after for start value");
+ getNextToken();
+
+ ExprAST *End = ParseExpression();
+ if (End == 0) return 0;
+
+ // The step value is optional.
+ ExprAST *Step = 0;
+ if (CurTok == ',') {
+ getNextToken();
+ Step = ParseExpression();
+ if (Step == 0) return 0;
+ }
+
+ if (CurTok != tok_in)
+ return Error("expected 'in' after for");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new ForExprAST(IdName, Start, End, Step, Body);
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+/// ::= ifexpr
+/// ::= forexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ case tok_if: return ParseIfExpr();
+ case tok_for: return ParseForExpr();
+ }
+}
+
+/// unary
+/// ::= primary
+/// ::= '!' unary
+static ExprAST *ParseUnary() {
+ // If the current token is not an operator, it must be a primary expr.
+ if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
+ return ParsePrimary();
+
+ // If this is a unary operator, read it.
+ int Opc = CurTok;
+ getNextToken();
+ if (ExprAST *Operand = ParseUnary())
+ return new UnaryExprAST(Opc, Operand);
+ return 0;
+}
+
+/// binoprhs
+/// ::= ('+' unary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec &lt; ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the unary expression after the binary operator.
+ ExprAST *RHS = ParseUnary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec &lt; NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= unary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParseUnary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+/// ::= binary LETTER number? (id, id)
+/// ::= unary LETTER (id)
+static PrototypeAST *ParsePrototype() {
+ std::string FnName;
+
+ unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
+ unsigned BinaryPrecedence = 30;
+
+ switch (CurTok) {
+ default:
+ return ErrorP("Expected function name in prototype");
+ case tok_identifier:
+ FnName = IdentifierStr;
+ Kind = 0;
+ getNextToken();
+ break;
+ case tok_unary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected unary operator");
+ FnName = "unary";
+ FnName += (char)CurTok;
+ Kind = 1;
+ getNextToken();
+ break;
+ case tok_binary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected binary operator");
+ FnName = "binary";
+ FnName += (char)CurTok;
+ Kind = 2;
+ getNextToken();
+
+ // Read the precedence if present.
+ if (CurTok == tok_number) {
+ if (NumVal &lt; 1 || NumVal &gt; 100)
+ return ErrorP("Invalid precedecnce: must be 1..100");
+ BinaryPrecedence = (unsigned)NumVal;
+ getNextToken();
+ }
+ break;
+ }
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector&lt;std::string&gt; ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ // Verify right number of names for operator.
+ if (Kind &amp;&amp; ArgNames.size() != Kind)
+ return ErrorP("Invalid number of operands for operator");
+
+ return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder&lt;&gt; Builder(getGlobalContext());
+static std::map&lt;std::string, Value*&gt; NamedValues;
+static FunctionPassManager *TheFPM;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+
+Value *UnaryExprAST::Codegen() {
+ Value *OperandV = Operand-&gt;Codegen();
+ if (OperandV == 0) return 0;
+
+ Function *F = TheModule-&gt;getFunction(std::string("unary")+Opcode);
+ if (F == 0)
+ return ErrorV("Unknown unary operator");
+
+ return Builder.CreateCall(F, OperandV, "unop");
+}
+
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS-&gt;Codegen();
+ Value *R = RHS-&gt;Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '&lt;':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: break;
+ }
+
+ // If it wasn't a builtin binary operator, it must be a user defined one. Emit
+ // a call to it.
+ Function *F = TheModule-&gt;getFunction(std::string("binary")+Op);
+ assert(F &amp;&amp; "binary operator not found!");
+
+ Value *Ops[2] = { L, R };
+ return Builder.CreateCall(F, Ops, "binop");
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule-&gt;getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF-&gt;arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector&lt;Value*&gt; ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]-&gt;Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Value *IfExprAST::Codegen() {
+ Value *CondV = Cond-&gt;Codegen();
+ if (CondV == 0) return 0;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ CondV = Builder.CreateFCmpONE(CondV,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "ifcond");
+
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+
+ // Create blocks for the then and else cases. Insert the 'then' block at the
+ // end of the function.
+ BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
+ BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
+ BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+
+ Builder.CreateCondBr(CondV, ThenBB, ElseBB);
+
+ // Emit then value.
+ Builder.SetInsertPoint(ThenBB);
+
+ Value *ThenV = Then-&gt;Codegen();
+ if (ThenV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
+ ThenBB = Builder.GetInsertBlock();
+
+ // Emit else block.
+ TheFunction-&gt;getBasicBlockList().push_back(ElseBB);
+ Builder.SetInsertPoint(ElseBB);
+
+ Value *ElseV = Else-&gt;Codegen();
+ if (ElseV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
+ ElseBB = Builder.GetInsertBlock();
+
+ // Emit merge block.
+ TheFunction-&gt;getBasicBlockList().push_back(MergeBB);
+ Builder.SetInsertPoint(MergeBB);
+ PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+ "iftmp");
+
+ PN-&gt;addIncoming(ThenV, ThenBB);
+ PN-&gt;addIncoming(ElseV, ElseBB);
+ return PN;
+}
+
+Value *ForExprAST::Codegen() {
+ // Output this as:
+ // ...
+ // start = startexpr
+ // goto loop
+ // loop:
+ // variable = phi [start, loopheader], [nextvariable, loopend]
+ // ...
+ // bodyexpr
+ // ...
+ // loopend:
+ // step = stepexpr
+ // nextvariable = variable + step
+ // endcond = endexpr
+ // br endcond, loop, endloop
+ // outloop:
+
+ // Emit the start code first, without 'variable' in scope.
+ Value *StartVal = Start-&gt;Codegen();
+ if (StartVal == 0) return 0;
+
+ // Make the new basic block for the loop header, inserting after current
+ // block.
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+ BasicBlock *PreheaderBB = Builder.GetInsertBlock();
+ BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+
+ // Insert an explicit fall through from the current block to the LoopBB.
+ Builder.CreateBr(LoopBB);
+
+ // Start insertion in LoopBB.
+ Builder.SetInsertPoint(LoopBB);
+
+ // Start the PHI node with an entry for Start.
+ PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
+ Variable-&gt;addIncoming(StartVal, PreheaderBB);
+
+ // Within the loop, the variable is defined equal to the PHI node. If it
+ // shadows an existing variable, we have to restore it, so save it now.
+ Value *OldVal = NamedValues[VarName];
+ NamedValues[VarName] = Variable;
+
+ // Emit the body of the loop. This, like any other expr, can change the
+ // current BB. Note that we ignore the value computed by the body, but don't
+ // allow an error.
+ if (Body-&gt;Codegen() == 0)
+ return 0;
+
+ // Emit the step value.
+ Value *StepVal;
+ if (Step) {
+ StepVal = Step-&gt;Codegen();
+ if (StepVal == 0) return 0;
+ } else {
+ // If not specified, use 1.0.
+ StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+ }
+
+ Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
+
+ // Compute the end condition.
+ Value *EndCond = End-&gt;Codegen();
+ if (EndCond == 0) return EndCond;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ EndCond = Builder.CreateFCmpONE(EndCond,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "loopcond");
+
+ // Create the "after loop" block and insert it.
+ BasicBlock *LoopEndBB = Builder.GetInsertBlock();
+ BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+
+ // Insert the conditional branch into the end of LoopEndBB.
+ Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
+
+ // Any new code will be inserted in AfterBB.
+ Builder.SetInsertPoint(AfterBB);
+
+ // Add a new entry to the PHI node for the backedge.
+ Variable-&gt;addIncoming(NextVar, LoopEndBB);
+
+ // Restore the unshadowed variable.
+ if (OldVal)
+ NamedValues[VarName] = OldVal;
+ else
+ NamedValues.erase(VarName);
+
+
+ // for expr always returns 0.0.
+ return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector&lt;Type*&gt; Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F-&gt;getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F-&gt;eraseFromParent();
+ F = TheModule-&gt;getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F-&gt;empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F-&gt;arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI-&gt;setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+
+ return F;
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto-&gt;Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // If this is an operator, install it.
+ if (Proto-&gt;isBinaryOp())
+ BinopPrecedence[Proto-&gt;getOperatorName()] = Proto-&gt;getBinaryPrecedence();
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body-&gt;Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ // Optimize the function.
+ TheFPM-&gt;run(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction-&gt;eraseFromParent();
+
+ if (Proto-&gt;isBinaryOp())
+ BinopPrecedence.erase(Proto-&gt;getOperatorName());
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static ExecutionEngine *TheExecutionEngine;
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P-&gt;Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ // JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready&gt; ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+/// printd - printf that takes a double prints it as "%f\n", returning 0.
+extern "C"
+double printd(double X) {
+ printf("%f\n", X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext &amp;Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['&lt;'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready&gt; ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Create the JIT. This takes ownership of the module.
+ std::string ErrStr;
+ TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&amp;ErrStr).create();
+ if (!TheExecutionEngine) {
+ fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+ exit(1);
+ }
+
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &amp;OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ TheFPM = 0;
+
+ // Print out all of the generated code.
+ TheModule-&gt;dump();
+
+ return 0;
+}
+</pre>
+</div>
+
+<a href="LangImpl7.html">Next: Extending the language: mutable variables / SSA construction</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/LangImpl7.html b/docs/tutorial/LangImpl7.html
new file mode 100644
index 00000000000..08c0c716b6f
--- /dev/null
+++ b/docs/tutorial/LangImpl7.html
@@ -0,0 +1,2164 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Extending the Language: Mutable Variables / SSA
+ construction</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Extending the Language: Mutable Variables</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 7
+ <ol>
+ <li><a href="#intro">Chapter 7 Introduction</a></li>
+ <li><a href="#why">Why is this a hard problem?</a></li>
+ <li><a href="#memory">Memory in LLVM</a></li>
+ <li><a href="#kalvars">Mutable Variables in Kaleidoscope</a></li>
+ <li><a href="#adjustments">Adjusting Existing Variables for
+ Mutation</a></li>
+ <li><a href="#assignment">New Assignment Operator</a></li>
+ <li><a href="#localvars">User-defined Local Variables</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="LangImpl8.html">Chapter 8</a>: Conclusion and other useful LLVM
+ tidbits</li>
+</ul>
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 7 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 7 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. In chapters 1 through 6, we've built a very
+respectable, albeit simple, <a
+href="http://en.wikipedia.org/wiki/Functional_programming">functional
+programming language</a>. In our journey, we learned some parsing techniques,
+how to build and represent an AST, how to build LLVM IR, and how to optimize
+the resultant code as well as JIT compile it.</p>
+
+<p>While Kaleidoscope is interesting as a functional language, the fact that it
+is functional makes it "too easy" to generate LLVM IR for it. In particular, a
+functional language makes it very easy to build LLVM IR directly in <a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">SSA form</a>.
+Since LLVM requires that the input code be in SSA form, this is a very nice
+property and it is often unclear to newcomers how to generate code for an
+imperative language with mutable variables.</p>
+
+<p>The short (and happy) summary of this chapter is that there is no need for
+your front-end to build SSA form: LLVM provides highly tuned and well tested
+support for this, though the way it works is a bit unexpected for some.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="why">Why is this a hard problem?</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+To understand why mutable variables cause complexities in SSA construction,
+consider this extremely simple C example:
+</p>
+
+<div class="doc_code">
+<pre>
+int G, H;
+int test(_Bool Condition) {
+ int X;
+ if (Condition)
+ X = G;
+ else
+ X = H;
+ return X;
+}
+</pre>
+</div>
+
+<p>In this case, we have the variable "X", whose value depends on the path
+executed in the program. Because there are two different possible values for X
+before the return instruction, a PHI node is inserted to merge the two values.
+The LLVM IR that we want for this example looks like this:</p>
+
+<div class="doc_code">
+<pre>
+@G = weak global i32 0 ; type of @G is i32*
+@H = weak global i32 0 ; type of @H is i32*
+
+define i32 @test(i1 %Condition) {
+entry:
+ br i1 %Condition, label %cond_true, label %cond_false
+
+cond_true:
+ %X.0 = load i32* @G
+ br label %cond_next
+
+cond_false:
+ %X.1 = load i32* @H
+ br label %cond_next
+
+cond_next:
+ %X.2 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
+ ret i32 %X.2
+}
+</pre>
+</div>
+
+<p>In this example, the loads from the G and H global variables are explicit in
+the LLVM IR, and they live in the then/else branches of the if statement
+(cond_true/cond_false). In order to merge the incoming values, the X.2 phi node
+in the cond_next block selects the right value to use based on where control
+flow is coming from: if control flow comes from the cond_false block, X.2 gets
+the value of X.1. Alternatively, if control flow comes from cond_true, it gets
+the value of X.0. The intent of this chapter is not to explain the details of
+SSA form. For more information, see one of the many <a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">online
+references</a>.</p>
+
+<p>The question for this article is "who places the phi nodes when lowering
+assignments to mutable variables?". The issue here is that LLVM
+<em>requires</em> that its IR be in SSA form: there is no "non-ssa" mode for it.
+However, SSA construction requires non-trivial algorithms and data structures,
+so it is inconvenient and wasteful for every front-end to have to reproduce this
+logic.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="memory">Memory in LLVM</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The 'trick' here is that while LLVM does require all register values to be
+in SSA form, it does not require (or permit) memory objects to be in SSA form.
+In the example above, note that the loads from G and H are direct accesses to
+G and H: they are not renamed or versioned. This differs from some other
+compiler systems, which do try to version memory objects. In LLVM, instead of
+encoding dataflow analysis of memory into the LLVM IR, it is handled with <a
+href="../WritingAnLLVMPass.html">Analysis Passes</a> which are computed on
+demand.</p>
+
+<p>
+With this in mind, the high-level idea is that we want to make a stack variable
+(which lives in memory, because it is on the stack) for each mutable object in
+a function. To take advantage of this trick, we need to talk about how LLVM
+represents stack variables.
+</p>
+
+<p>In LLVM, all memory accesses are explicit with load/store instructions, and
+it is carefully designed not to have (or need) an "address-of" operator. Notice
+how the type of the @G/@H global variables is actually "i32*" even though the
+variable is defined as "i32". What this means is that @G defines <em>space</em>
+for an i32 in the global data area, but its <em>name</em> actually refers to the
+address for that space. Stack variables work the same way, except that instead of
+being declared with global variable definitions, they are declared with the
+<a href="../LangRef.html#i_alloca">LLVM alloca instruction</a>:</p>
+
+<div class="doc_code">
+<pre>
+define i32 @example() {
+entry:
+ %X = alloca i32 ; type of %X is i32*.
+ ...
+ %tmp = load i32* %X ; load the stack value %X from the stack.
+ %tmp2 = add i32 %tmp, 1 ; increment it
+ store i32 %tmp2, i32* %X ; store it back
+ ...
+</pre>
+</div>
+
+<p>This code shows an example of how you can declare and manipulate a stack
+variable in the LLVM IR. Stack memory allocated with the alloca instruction is
+fully general: you can pass the address of the stack slot to functions, you can
+store it in other variables, etc. In our example above, we could rewrite the
+example to use the alloca technique to avoid using a PHI node:</p>
+
+<div class="doc_code">
+<pre>
+@G = weak global i32 0 ; type of @G is i32*
+@H = weak global i32 0 ; type of @H is i32*
+
+define i32 @test(i1 %Condition) {
+entry:
+ %X = alloca i32 ; type of %X is i32*.
+ br i1 %Condition, label %cond_true, label %cond_false
+
+cond_true:
+ %X.0 = load i32* @G
+ store i32 %X.0, i32* %X ; Update X
+ br label %cond_next
+
+cond_false:
+ %X.1 = load i32* @H
+ store i32 %X.1, i32* %X ; Update X
+ br label %cond_next
+
+cond_next:
+ %X.2 = load i32* %X ; Read X
+ ret i32 %X.2
+}
+</pre>
+</div>
+
+<p>With this, we have discovered a way to handle arbitrary mutable variables
+without the need to create Phi nodes at all:</p>
+
+<ol>
+<li>Each mutable variable becomes a stack allocation.</li>
+<li>Each read of the variable becomes a load from the stack.</li>
+<li>Each update of the variable becomes a store to the stack.</li>
+<li>Taking the address of a variable just uses the stack address directly.</li>
+</ol>
+
+<p>While this solution has solved our immediate problem, it introduced another
+one: we have now apparently introduced a lot of stack traffic for very simple
+and common operations, a major performance problem. Fortunately for us, the
+LLVM optimizer has a highly-tuned optimization pass named "mem2reg" that handles
+this case, promoting allocas like this into SSA registers, inserting Phi nodes
+as appropriate. If you run this example through the pass, for example, you'll
+get:</p>
+
+<div class="doc_code">
+<pre>
+$ <b>llvm-as &lt; example.ll | opt -mem2reg | llvm-dis</b>
+@G = weak global i32 0
+@H = weak global i32 0
+
+define i32 @test(i1 %Condition) {
+entry:
+ br i1 %Condition, label %cond_true, label %cond_false
+
+cond_true:
+ %X.0 = load i32* @G
+ br label %cond_next
+
+cond_false:
+ %X.1 = load i32* @H
+ br label %cond_next
+
+cond_next:
+ %X.01 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
+ ret i32 %X.01
+}
+</pre>
+</div>
+
+<p>The mem2reg pass implements the standard "iterated dominance frontier"
+algorithm for constructing SSA form and has a number of optimizations that speed
+up (very common) degenerate cases. The mem2reg optimization pass is the answer to dealing
+with mutable variables, and we highly recommend that you depend on it. Note that
+mem2reg only works on variables in certain circumstances:</p>
+
+<ol>
+<li>mem2reg is alloca-driven: it looks for allocas and if it can handle them, it
+promotes them. It does not apply to global variables or heap allocations.</li>
+
+<li>mem2reg only looks for alloca instructions in the entry block of the
+function. Being in the entry block guarantees that the alloca is only executed
+once, which makes analysis simpler.</li>
+
+<li>mem2reg only promotes allocas whose uses are direct loads and stores. If
+the address of the stack object is passed to a function, or if any funny pointer
+arithmetic is involved, the alloca will not be promoted.</li>
+
+<li>mem2reg only works on allocas of <a
+href="../LangRef.html#t_classifications">first class</a>
+values (such as pointers, scalars and vectors), and only if the array size
+of the allocation is 1 (or missing in the .ll file). mem2reg is not capable of
+promoting structs or arrays to registers. Note that the "scalarrepl" pass is
+more powerful and can promote structs, "unions", and arrays in many cases.</li>
+
+</ol>
+
+<p>
+All of these properties are easy to satisfy for most imperative languages, and
+we'll illustrate it below with Kaleidoscope. The final question you may be
+asking is: should I bother with this nonsense for my front-end? Wouldn't it be
+better if I just did SSA construction directly, avoiding use of the mem2reg
+optimization pass? In short, we strongly recommend that you use this technique
+for building SSA form, unless there is an extremely good reason not to. Using
+this technique is:</p>
+
+<ul>
+<li>Proven and well tested: llvm-gcc and clang both use this technique for local
+mutable variables. As such, the most common clients of LLVM are using this to
+handle a bulk of their variables. You can be sure that bugs are found fast and
+fixed early.</li>
+
+<li>Extremely Fast: mem2reg has a number of special cases that make it fast in
+common cases as well as fully general. For example, it has fast-paths for
+variables that are only used in a single block, variables that only have one
+assignment point, good heuristics to avoid insertion of unneeded phi nodes, etc.
+</li>
+
+<li>Needed for debug info generation: <a href="../SourceLevelDebugging.html">
+Debug information in LLVM</a> relies on having the address of the variable
+exposed so that debug info can be attached to it. This technique dovetails
+very naturally with this style of debug info.</li>
+</ul>
+
+<p>If nothing else, this makes it much easier to get your front-end up and
+running, and is very simple to implement. Lets extend Kaleidoscope with mutable
+variables now!
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="kalvars">Mutable Variables in Kaleidoscope</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Now that we know the sort of problem we want to tackle, lets see what this
+looks like in the context of our little Kaleidoscope language. We're going to
+add two features:</p>
+
+<ol>
+<li>The ability to mutate variables with the '=' operator.</li>
+<li>The ability to define new variables.</li>
+</ol>
+
+<p>While the first item is really what this is about, we only have variables
+for incoming arguments as well as for induction variables, and redefining those only
+goes so far :). Also, the ability to define new variables is a
+useful thing regardless of whether you will be mutating them. Here's a
+motivating example that shows how we could use these:</p>
+
+<div class="doc_code">
+<pre>
+# Define ':' for sequencing: as a low-precedence operator that ignores operands
+# and just returns the RHS.
+def binary : 1 (x y) y;
+
+# Recursive fib, we could do this before.
+def fib(x)
+ if (x &lt; 3) then
+ 1
+ else
+ fib(x-1)+fib(x-2);
+
+# Iterative fib.
+def fibi(x)
+ <b>var a = 1, b = 1, c in</b>
+ (for i = 3, i &lt; x in
+ <b>c = a + b</b> :
+ <b>a = b</b> :
+ <b>b = c</b>) :
+ b;
+
+# Call it.
+fibi(10);
+</pre>
+</div>
+
+<p>
+In order to mutate variables, we have to change our existing variables to use
+the "alloca trick". Once we have that, we'll add our new operator, then extend
+Kaleidoscope to support new variable definitions.
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="adjustments">Adjusting Existing Variables for Mutation</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+The symbol table in Kaleidoscope is managed at code generation time by the
+'<tt>NamedValues</tt>' map. This map currently keeps track of the LLVM "Value*"
+that holds the double value for the named variable. In order to support
+mutation, we need to change this slightly, so that it <tt>NamedValues</tt> holds
+the <em>memory location</em> of the variable in question. Note that this
+change is a refactoring: it changes the structure of the code, but does not
+(by itself) change the behavior of the compiler. All of these changes are
+isolated in the Kaleidoscope code generator.</p>
+
+<p>
+At this point in Kaleidoscope's development, it only supports variables for two
+things: incoming arguments to functions and the induction variable of 'for'
+loops. For consistency, we'll allow mutation of these variables in addition to
+other user-defined variables. This means that these will both need memory
+locations.
+</p>
+
+<p>To start our transformation of Kaleidoscope, we'll change the NamedValues
+map so that it maps to AllocaInst* instead of Value*. Once we do this, the C++
+compiler will tell us what parts of the code we need to update:</p>
+
+<div class="doc_code">
+<pre>
+static std::map&lt;std::string, AllocaInst*&gt; NamedValues;
+</pre>
+</div>
+
+<p>Also, since we will need to create these alloca's, we'll use a helper
+function that ensures that the allocas are created in the entry block of the
+function:</p>
+
+<div class="doc_code">
+<pre>
+/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
+/// the function. This is used for mutable variables etc.
+static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
+ const std::string &amp;VarName) {
+ IRBuilder&lt;&gt; TmpB(&amp;TheFunction-&gt;getEntryBlock(),
+ TheFunction-&gt;getEntryBlock().begin());
+ return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+ VarName.c_str());
+}
+</pre>
+</div>
+
+<p>This funny looking code creates an IRBuilder object that is pointing at
+the first instruction (.begin()) of the entry block. It then creates an alloca
+with the expected name and returns it. Because all values in Kaleidoscope are
+doubles, there is no need to pass in a type to use.</p>
+
+<p>With this in place, the first functionality change we want to make is to
+variable references. In our new scheme, variables live on the stack, so code
+generating a reference to them actually needs to produce a load from the stack
+slot:</p>
+
+<div class="doc_code">
+<pre>
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ if (V == 0) return ErrorV("Unknown variable name");
+
+ <b>// Load the value.
+ return Builder.CreateLoad(V, Name.c_str());</b>
+}
+</pre>
+</div>
+
+<p>As you can see, this is pretty straightforward. Now we need to update the
+things that define the variables to set up the alloca. We'll start with
+<tt>ForExprAST::Codegen</tt> (see the <a href="#code">full code listing</a> for
+the unabridged code):</p>
+
+<div class="doc_code">
+<pre>
+ Function *TheFunction = Builder.GetInsertBlock()->getParent();
+
+ <b>// Create an alloca for the variable in the entry block.
+ AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);</b>
+
+ // Emit the start code first, without 'variable' in scope.
+ Value *StartVal = Start-&gt;Codegen();
+ if (StartVal == 0) return 0;
+
+ <b>// Store the value into the alloca.
+ Builder.CreateStore(StartVal, Alloca);</b>
+ ...
+
+ // Compute the end condition.
+ Value *EndCond = End-&gt;Codegen();
+ if (EndCond == 0) return EndCond;
+
+ <b>// Reload, increment, and restore the alloca. This handles the case where
+ // the body of the loop mutates the variable.
+ Value *CurVar = Builder.CreateLoad(Alloca);
+ Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
+ Builder.CreateStore(NextVar, Alloca);</b>
+ ...
+</pre>
+</div>
+
+<p>This code is virtually identical to the code <a
+href="LangImpl5.html#forcodegen">before we allowed mutable variables</a>. The
+big difference is that we no longer have to construct a PHI node, and we use
+load/store to access the variable as needed.</p>
+
+<p>To support mutable argument variables, we need to also make allocas for them.
+The code for this is also pretty simple:</p>
+
+<div class="doc_code">
+<pre>
+/// CreateArgumentAllocas - Create an alloca for each argument and register the
+/// argument in the symbol table so that references to it will succeed.
+void PrototypeAST::CreateArgumentAllocas(Function *F) {
+ Function::arg_iterator AI = F-&gt;arg_begin();
+ for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
+ // Create an alloca for this variable.
+ AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
+
+ // Store the initial value into the alloca.
+ Builder.CreateStore(AI, Alloca);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = Alloca;
+ }
+}
+</pre>
+</div>
+
+<p>For each argument, we make an alloca, store the input value to the function
+into the alloca, and register the alloca as the memory location for the
+argument. This method gets invoked by <tt>FunctionAST::Codegen</tt> right after
+it sets up the entry block for the function.</p>
+
+<p>The final missing piece is adding the mem2reg pass, which allows us to get
+good codegen once again:</p>
+
+<div class="doc_code">
+<pre>
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
+ <b>// Promote allocas to registers.
+ OurFPM.add(createPromoteMemoryToRegisterPass());</b>
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+</pre>
+</div>
+
+<p>It is interesting to see what the code looks like before and after the
+mem2reg optimization runs. For example, this is the before/after code for our
+recursive fib function. Before the optimization:</p>
+
+<div class="doc_code">
+<pre>
+define double @fib(double %x) {
+entry:
+ <b>%x1 = alloca double
+ store double %x, double* %x1
+ %x2 = load double* %x1</b>
+ %cmptmp = fcmp ult double %x2, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
+ %ifcond = fcmp one double %booltmp, 0.000000e+00
+ br i1 %ifcond, label %then, label %else
+
+then: ; preds = %entry
+ br label %ifcont
+
+else: ; preds = %entry
+ <b>%x3 = load double* %x1</b>
+ %subtmp = fsub double %x3, 1.000000e+00
+ %calltmp = call double @fib(double %subtmp)
+ <b>%x4 = load double* %x1</b>
+ %subtmp5 = fsub double %x4, 2.000000e+00
+ %calltmp6 = call double @fib(double %subtmp5)
+ %addtmp = fadd double %calltmp, %calltmp6
+ br label %ifcont
+
+ifcont: ; preds = %else, %then
+ %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
+ ret double %iftmp
+}
+</pre>
+</div>
+
+<p>Here there is only one variable (x, the input argument) but you can still
+see the extremely simple-minded code generation strategy we are using. In the
+entry block, an alloca is created, and the initial input value is stored into
+it. Each reference to the variable does a reload from the stack. Also, note
+that we didn't modify the if/then/else expression, so it still inserts a PHI
+node. While we could make an alloca for it, it is actually easier to create a
+PHI node for it, so we still just make the PHI.</p>
+
+<p>Here is the code after the mem2reg pass runs:</p>
+
+<div class="doc_code">
+<pre>
+define double @fib(double %x) {
+entry:
+ %cmptmp = fcmp ult double <b>%x</b>, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
+ %ifcond = fcmp one double %booltmp, 0.000000e+00
+ br i1 %ifcond, label %then, label %else
+
+then:
+ br label %ifcont
+
+else:
+ %subtmp = fsub double <b>%x</b>, 1.000000e+00
+ %calltmp = call double @fib(double %subtmp)
+ %subtmp5 = fsub double <b>%x</b>, 2.000000e+00
+ %calltmp6 = call double @fib(double %subtmp5)
+ %addtmp = fadd double %calltmp, %calltmp6
+ br label %ifcont
+
+ifcont: ; preds = %else, %then
+ %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
+ ret double %iftmp
+}
+</pre>
+</div>
+
+<p>This is a trivial case for mem2reg, since there are no redefinitions of the
+variable. The point of showing this is to calm your tension about inserting
+such blatent inefficiencies :).</p>
+
+<p>After the rest of the optimizers run, we get:</p>
+
+<div class="doc_code">
+<pre>
+define double @fib(double %x) {
+entry:
+ %cmptmp = fcmp ult double %x, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
+ %ifcond = fcmp ueq double %booltmp, 0.000000e+00
+ br i1 %ifcond, label %else, label %ifcont
+
+else:
+ %subtmp = fsub double %x, 1.000000e+00
+ %calltmp = call double @fib(double %subtmp)
+ %subtmp5 = fsub double %x, 2.000000e+00
+ %calltmp6 = call double @fib(double %subtmp5)
+ %addtmp = fadd double %calltmp, %calltmp6
+ ret double %addtmp
+
+ifcont:
+ ret double 1.000000e+00
+}
+</pre>
+</div>
+
+<p>Here we see that the simplifycfg pass decided to clone the return instruction
+into the end of the 'else' block. This allowed it to eliminate some branches
+and the PHI node.</p>
+
+<p>Now that all symbol table references are updated to use stack variables,
+we'll add the assignment operator.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="assignment">New Assignment Operator</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>With our current framework, adding a new assignment operator is really
+simple. We will parse it just like any other binary operator, but handle it
+internally (instead of allowing the user to define it). The first step is to
+set a precedence:</p>
+
+<div class="doc_code">
+<pre>
+ int main() {
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ <b>BinopPrecedence['='] = 2;</b>
+ BinopPrecedence['&lt;'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+</pre>
+</div>
+
+<p>Now that the parser knows the precedence of the binary operator, it takes
+care of all the parsing and AST generation. We just need to implement codegen
+for the assignment operator. This looks like:</p>
+
+<div class="doc_code">
+<pre>
+Value *BinaryExprAST::Codegen() {
+ // Special case '=' because we don't want to emit the LHS as an expression.
+ if (Op == '=') {
+ // Assignment requires the LHS to be an identifier.
+ VariableExprAST *LHSE = dynamic_cast&lt;VariableExprAST*&gt;(LHS);
+ if (!LHSE)
+ return ErrorV("destination of '=' must be a variable");
+</pre>
+</div>
+
+<p>Unlike the rest of the binary operators, our assignment operator doesn't
+follow the "emit LHS, emit RHS, do computation" model. As such, it is handled
+as a special case before the other binary operators are handled. The other
+strange thing is that it requires the LHS to be a variable. It is invalid to
+have "(x+1) = expr" - only things like "x = expr" are allowed.
+</p>
+
+<div class="doc_code">
+<pre>
+ // Codegen the RHS.
+ Value *Val = RHS-&gt;Codegen();
+ if (Val == 0) return 0;
+
+ // Look up the name.
+ Value *Variable = NamedValues[LHSE-&gt;getName()];
+ if (Variable == 0) return ErrorV("Unknown variable name");
+
+ Builder.CreateStore(Val, Variable);
+ return Val;
+ }
+ ...
+</pre>
+</div>
+
+<p>Once we have the variable, codegen'ing the assignment is straightforward:
+we emit the RHS of the assignment, create a store, and return the computed
+value. Returning a value allows for chained assignments like "X = (Y = Z)".</p>
+
+<p>Now that we have an assignment operator, we can mutate loop variables and
+arguments. For example, we can now run code like this:</p>
+
+<div class="doc_code">
+<pre>
+# Function to print a double.
+extern printd(x);
+
+# Define ':' for sequencing: as a low-precedence operator that ignores operands
+# and just returns the RHS.
+def binary : 1 (x y) y;
+
+def test(x)
+ printd(x) :
+ x = 4 :
+ printd(x);
+
+test(123);
+</pre>
+</div>
+
+<p>When run, this example prints "123" and then "4", showing that we did
+actually mutate the value! Okay, we have now officially implemented our goal:
+getting this to work requires SSA construction in the general case. However,
+to be really useful, we want the ability to define our own local variables, lets
+add this next!
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="localvars">User-defined Local Variables</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Adding var/in is just like any other other extensions we made to
+Kaleidoscope: we extend the lexer, the parser, the AST and the code generator.
+The first step for adding our new 'var/in' construct is to extend the lexer.
+As before, this is pretty trivial, the code looks like this:</p>
+
+<div class="doc_code">
+<pre>
+enum Token {
+ ...
+ <b>// var definition
+ tok_var = -13</b>
+...
+}
+...
+static int gettok() {
+...
+ if (IdentifierStr == "in") return tok_in;
+ if (IdentifierStr == "binary") return tok_binary;
+ if (IdentifierStr == "unary") return tok_unary;
+ <b>if (IdentifierStr == "var") return tok_var;</b>
+ return tok_identifier;
+...
+</pre>
+</div>
+
+<p>The next step is to define the AST node that we will construct. For var/in,
+it looks like this:</p>
+
+<div class="doc_code">
+<pre>
+/// VarExprAST - Expression class for var/in
+class VarExprAST : public ExprAST {
+ std::vector&lt;std::pair&lt;std::string, ExprAST*&gt; &gt; VarNames;
+ ExprAST *Body;
+public:
+ VarExprAST(const std::vector&lt;std::pair&lt;std::string, ExprAST*&gt; &gt; &amp;varnames,
+ ExprAST *body)
+ : VarNames(varnames), Body(body) {}
+
+ virtual Value *Codegen();
+};
+</pre>
+</div>
+
+<p>var/in allows a list of names to be defined all at once, and each name can
+optionally have an initializer value. As such, we capture this information in
+the VarNames vector. Also, var/in has a body, this body is allowed to access
+the variables defined by the var/in.</p>
+
+<p>With this in place, we can define the parser pieces. The first thing we do is add
+it as a primary expression:</p>
+
+<div class="doc_code">
+<pre>
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+/// ::= ifexpr
+/// ::= forexpr
+<b>/// ::= varexpr</b>
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ case tok_if: return ParseIfExpr();
+ case tok_for: return ParseForExpr();
+ <b>case tok_var: return ParseVarExpr();</b>
+ }
+}
+</pre>
+</div>
+
+<p>Next we define ParseVarExpr:</p>
+
+<div class="doc_code">
+<pre>
+/// varexpr ::= 'var' identifier ('=' expression)?
+// (',' identifier ('=' expression)?)* 'in' expression
+static ExprAST *ParseVarExpr() {
+ getNextToken(); // eat the var.
+
+ std::vector&lt;std::pair&lt;std::string, ExprAST*&gt; &gt; VarNames;
+
+ // At least one variable name is required.
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after var");
+</pre>
+</div>
+
+<p>The first part of this code parses the list of identifier/expr pairs into the
+local <tt>VarNames</tt> vector.
+
+<div class="doc_code">
+<pre>
+ while (1) {
+ std::string Name = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ // Read the optional initializer.
+ ExprAST *Init = 0;
+ if (CurTok == '=') {
+ getNextToken(); // eat the '='.
+
+ Init = ParseExpression();
+ if (Init == 0) return 0;
+ }
+
+ VarNames.push_back(std::make_pair(Name, Init));
+
+ // End of var list, exit loop.
+ if (CurTok != ',') break;
+ getNextToken(); // eat the ','.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier list after var");
+ }
+</pre>
+</div>
+
+<p>Once all the variables are parsed, we then parse the body and create the
+AST node:</p>
+
+<div class="doc_code">
+<pre>
+ // At this point, we have to have 'in'.
+ if (CurTok != tok_in)
+ return Error("expected 'in' keyword after 'var'");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new VarExprAST(VarNames, Body);
+}
+</pre>
+</div>
+
+<p>Now that we can parse and represent the code, we need to support emission of
+LLVM IR for it. This code starts out with:</p>
+
+<div class="doc_code">
+<pre>
+Value *VarExprAST::Codegen() {
+ std::vector&lt;AllocaInst *&gt; OldBindings;
+
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+
+ // Register all variables and emit their initializer.
+ for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
+ const std::string &amp;VarName = VarNames[i].first;
+ ExprAST *Init = VarNames[i].second;
+</pre>
+</div>
+
+<p>Basically it loops over all the variables, installing them one at a time.
+For each variable we put into the symbol table, we remember the previous value
+that we replace in OldBindings.</p>
+
+<div class="doc_code">
+<pre>
+ // Emit the initializer before adding the variable to scope, this prevents
+ // the initializer from referencing the variable itself, and permits stuff
+ // like this:
+ // var a = 1 in
+ // var a = a in ... # refers to outer 'a'.
+ Value *InitVal;
+ if (Init) {
+ InitVal = Init-&gt;Codegen();
+ if (InitVal == 0) return 0;
+ } else { // If not specified, use 0.0.
+ InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+ }
+
+ AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
+ Builder.CreateStore(InitVal, Alloca);
+
+ // Remember the old variable binding so that we can restore the binding when
+ // we unrecurse.
+ OldBindings.push_back(NamedValues[VarName]);
+
+ // Remember this binding.
+ NamedValues[VarName] = Alloca;
+ }
+</pre>
+</div>
+
+<p>There are more comments here than code. The basic idea is that we emit the
+initializer, create the alloca, then update the symbol table to point to it.
+Once all the variables are installed in the symbol table, we evaluate the body
+of the var/in expression:</p>
+
+<div class="doc_code">
+<pre>
+ // Codegen the body, now that all vars are in scope.
+ Value *BodyVal = Body-&gt;Codegen();
+ if (BodyVal == 0) return 0;
+</pre>
+</div>
+
+<p>Finally, before returning, we restore the previous variable bindings:</p>
+
+<div class="doc_code">
+<pre>
+ // Pop all our variables from scope.
+ for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
+ NamedValues[VarNames[i].first] = OldBindings[i];
+
+ // Return the body computation.
+ return BodyVal;
+}
+</pre>
+</div>
+
+<p>The end result of all of this is that we get properly scoped variable
+definitions, and we even (trivially) allow mutation of them :).</p>
+
+<p>With this, we completed what we set out to do. Our nice iterative fib
+example from the intro compiles and runs just fine. The mem2reg pass optimizes
+all of our stack variables into SSA registers, inserting PHI nodes where needed,
+and our front-end remains simple: no "iterated dominance frontier" computation
+anywhere in sight.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with mutable
+variables and var/in support. To build this example, use:
+</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+clang++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
+# Run
+./toy
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<div class="doc_code">
+<pre>
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/TargetSelect.h"
+#include &lt;cstdio&gt;
+#include &lt;string&gt;
+#include &lt;map&gt;
+#include &lt;vector&gt;
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5,
+
+ // control
+ tok_if = -6, tok_then = -7, tok_else = -8,
+ tok_for = -9, tok_in = -10,
+
+ // operators
+ tok_binary = -11, tok_unary = -12,
+
+ // var definition
+ tok_var = -13
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ if (IdentifierStr == "if") return tok_if;
+ if (IdentifierStr == "then") return tok_then;
+ if (IdentifierStr == "else") return tok_else;
+ if (IdentifierStr == "for") return tok_for;
+ if (IdentifierStr == "in") return tok_in;
+ if (IdentifierStr == "binary") return tok_binary;
+ if (IdentifierStr == "unary") return tok_unary;
+ if (IdentifierStr == "var") return tok_var;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &amp;name) : Name(name) {}
+ const std::string &amp;getName() const { return Name; }
+ virtual Value *Codegen();
+};
+
+/// UnaryExprAST - Expression class for a unary operator.
+class UnaryExprAST : public ExprAST {
+ char Opcode;
+ ExprAST *Operand;
+public:
+ UnaryExprAST(char opcode, ExprAST *operand)
+ : Opcode(opcode), Operand(operand) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector&lt;ExprAST*&gt; Args;
+public:
+ CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// IfExprAST - Expression class for if/then/else.
+class IfExprAST : public ExprAST {
+ ExprAST *Cond, *Then, *Else;
+public:
+ IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
+ : Cond(cond), Then(then), Else(_else) {}
+ virtual Value *Codegen();
+};
+
+/// ForExprAST - Expression class for for/in.
+class ForExprAST : public ExprAST {
+ std::string VarName;
+ ExprAST *Start, *End, *Step, *Body;
+public:
+ ForExprAST(const std::string &amp;varname, ExprAST *start, ExprAST *end,
+ ExprAST *step, ExprAST *body)
+ : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
+ virtual Value *Codegen();
+};
+
+/// VarExprAST - Expression class for var/in
+class VarExprAST : public ExprAST {
+ std::vector&lt;std::pair&lt;std::string, ExprAST*&gt; &gt; VarNames;
+ ExprAST *Body;
+public:
+ VarExprAST(const std::vector&lt;std::pair&lt;std::string, ExprAST*&gt; &gt; &amp;varnames,
+ ExprAST *body)
+ : VarNames(varnames), Body(body) {}
+
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes), as well as if it is an operator.
+class PrototypeAST {
+ std::string Name;
+ std::vector&lt;std::string&gt; Args;
+ bool isOperator;
+ unsigned Precedence; // Precedence if a binary op.
+public:
+ PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args,
+ bool isoperator = false, unsigned prec = 0)
+ : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
+
+ bool isUnaryOp() const { return isOperator &amp;&amp; Args.size() == 1; }
+ bool isBinaryOp() const { return isOperator &amp;&amp; Args.size() == 2; }
+
+ char getOperatorName() const {
+ assert(isUnaryOp() || isBinaryOp());
+ return Name[Name.size()-1];
+ }
+
+ unsigned getBinaryPrecedence() const { return Precedence; }
+
+ Function *Codegen();
+
+ void CreateArgumentAllocas(Function *F);
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map&lt;char, int&gt; BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec &lt;= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector&lt;ExprAST*&gt; Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// ifexpr ::= 'if' expression 'then' expression 'else' expression
+static ExprAST *ParseIfExpr() {
+ getNextToken(); // eat the if.
+
+ // condition.
+ ExprAST *Cond = ParseExpression();
+ if (!Cond) return 0;
+
+ if (CurTok != tok_then)
+ return Error("expected then");
+ getNextToken(); // eat the then
+
+ ExprAST *Then = ParseExpression();
+ if (Then == 0) return 0;
+
+ if (CurTok != tok_else)
+ return Error("expected else");
+
+ getNextToken();
+
+ ExprAST *Else = ParseExpression();
+ if (!Else) return 0;
+
+ return new IfExprAST(Cond, Then, Else);
+}
+
+/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
+static ExprAST *ParseForExpr() {
+ getNextToken(); // eat the for.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after for");
+
+ std::string IdName = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '=')
+ return Error("expected '=' after for");
+ getNextToken(); // eat '='.
+
+
+ ExprAST *Start = ParseExpression();
+ if (Start == 0) return 0;
+ if (CurTok != ',')
+ return Error("expected ',' after for start value");
+ getNextToken();
+
+ ExprAST *End = ParseExpression();
+ if (End == 0) return 0;
+
+ // The step value is optional.
+ ExprAST *Step = 0;
+ if (CurTok == ',') {
+ getNextToken();
+ Step = ParseExpression();
+ if (Step == 0) return 0;
+ }
+
+ if (CurTok != tok_in)
+ return Error("expected 'in' after for");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new ForExprAST(IdName, Start, End, Step, Body);
+}
+
+/// varexpr ::= 'var' identifier ('=' expression)?
+// (',' identifier ('=' expression)?)* 'in' expression
+static ExprAST *ParseVarExpr() {
+ getNextToken(); // eat the var.
+
+ std::vector&lt;std::pair&lt;std::string, ExprAST*&gt; &gt; VarNames;
+
+ // At least one variable name is required.
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after var");
+
+ while (1) {
+ std::string Name = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ // Read the optional initializer.
+ ExprAST *Init = 0;
+ if (CurTok == '=') {
+ getNextToken(); // eat the '='.
+
+ Init = ParseExpression();
+ if (Init == 0) return 0;
+ }
+
+ VarNames.push_back(std::make_pair(Name, Init));
+
+ // End of var list, exit loop.
+ if (CurTok != ',') break;
+ getNextToken(); // eat the ','.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier list after var");
+ }
+
+ // At this point, we have to have 'in'.
+ if (CurTok != tok_in)
+ return Error("expected 'in' keyword after 'var'");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new VarExprAST(VarNames, Body);
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+/// ::= ifexpr
+/// ::= forexpr
+/// ::= varexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ case tok_if: return ParseIfExpr();
+ case tok_for: return ParseForExpr();
+ case tok_var: return ParseVarExpr();
+ }
+}
+
+/// unary
+/// ::= primary
+/// ::= '!' unary
+static ExprAST *ParseUnary() {
+ // If the current token is not an operator, it must be a primary expr.
+ if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
+ return ParsePrimary();
+
+ // If this is a unary operator, read it.
+ int Opc = CurTok;
+ getNextToken();
+ if (ExprAST *Operand = ParseUnary())
+ return new UnaryExprAST(Opc, Operand);
+ return 0;
+}
+
+/// binoprhs
+/// ::= ('+' unary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec &lt; ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the unary expression after the binary operator.
+ ExprAST *RHS = ParseUnary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec &lt; NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= unary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParseUnary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+/// ::= binary LETTER number? (id, id)
+/// ::= unary LETTER (id)
+static PrototypeAST *ParsePrototype() {
+ std::string FnName;
+
+ unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
+ unsigned BinaryPrecedence = 30;
+
+ switch (CurTok) {
+ default:
+ return ErrorP("Expected function name in prototype");
+ case tok_identifier:
+ FnName = IdentifierStr;
+ Kind = 0;
+ getNextToken();
+ break;
+ case tok_unary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected unary operator");
+ FnName = "unary";
+ FnName += (char)CurTok;
+ Kind = 1;
+ getNextToken();
+ break;
+ case tok_binary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected binary operator");
+ FnName = "binary";
+ FnName += (char)CurTok;
+ Kind = 2;
+ getNextToken();
+
+ // Read the precedence if present.
+ if (CurTok == tok_number) {
+ if (NumVal &lt; 1 || NumVal &gt; 100)
+ return ErrorP("Invalid precedecnce: must be 1..100");
+ BinaryPrecedence = (unsigned)NumVal;
+ getNextToken();
+ }
+ break;
+ }
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector&lt;std::string&gt; ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ // Verify right number of names for operator.
+ if (Kind &amp;&amp; ArgNames.size() != Kind)
+ return ErrorP("Invalid number of operands for operator");
+
+ return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder&lt;&gt; Builder(getGlobalContext());
+static std::map&lt;std::string, AllocaInst*&gt; NamedValues;
+static FunctionPassManager *TheFPM;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
+/// the function. This is used for mutable variables etc.
+static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
+ const std::string &amp;VarName) {
+ IRBuilder&lt;&gt; TmpB(&amp;TheFunction-&gt;getEntryBlock(),
+ TheFunction-&gt;getEntryBlock().begin());
+ return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+ VarName.c_str());
+}
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ if (V == 0) return ErrorV("Unknown variable name");
+
+ // Load the value.
+ return Builder.CreateLoad(V, Name.c_str());
+}
+
+Value *UnaryExprAST::Codegen() {
+ Value *OperandV = Operand-&gt;Codegen();
+ if (OperandV == 0) return 0;
+
+ Function *F = TheModule-&gt;getFunction(std::string("unary")+Opcode);
+ if (F == 0)
+ return ErrorV("Unknown unary operator");
+
+ return Builder.CreateCall(F, OperandV, "unop");
+}
+
+Value *BinaryExprAST::Codegen() {
+ // Special case '=' because we don't want to emit the LHS as an expression.
+ if (Op == '=') {
+ // Assignment requires the LHS to be an identifier.
+ VariableExprAST *LHSE = dynamic_cast&lt;VariableExprAST*&gt;(LHS);
+ if (!LHSE)
+ return ErrorV("destination of '=' must be a variable");
+ // Codegen the RHS.
+ Value *Val = RHS-&gt;Codegen();
+ if (Val == 0) return 0;
+
+ // Look up the name.
+ Value *Variable = NamedValues[LHSE-&gt;getName()];
+ if (Variable == 0) return ErrorV("Unknown variable name");
+
+ Builder.CreateStore(Val, Variable);
+ return Val;
+ }
+
+ Value *L = LHS-&gt;Codegen();
+ Value *R = RHS-&gt;Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '&lt;':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: break;
+ }
+
+ // If it wasn't a builtin binary operator, it must be a user defined one. Emit
+ // a call to it.
+ Function *F = TheModule-&gt;getFunction(std::string("binary")+Op);
+ assert(F &amp;&amp; "binary operator not found!");
+
+ Value *Ops[2] = { L, R };
+ return Builder.CreateCall(F, Ops, "binop");
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule-&gt;getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF-&gt;arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector&lt;Value*&gt; ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]-&gt;Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Value *IfExprAST::Codegen() {
+ Value *CondV = Cond-&gt;Codegen();
+ if (CondV == 0) return 0;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ CondV = Builder.CreateFCmpONE(CondV,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "ifcond");
+
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+
+ // Create blocks for the then and else cases. Insert the 'then' block at the
+ // end of the function.
+ BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
+ BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
+ BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+
+ Builder.CreateCondBr(CondV, ThenBB, ElseBB);
+
+ // Emit then value.
+ Builder.SetInsertPoint(ThenBB);
+
+ Value *ThenV = Then-&gt;Codegen();
+ if (ThenV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
+ ThenBB = Builder.GetInsertBlock();
+
+ // Emit else block.
+ TheFunction-&gt;getBasicBlockList().push_back(ElseBB);
+ Builder.SetInsertPoint(ElseBB);
+
+ Value *ElseV = Else-&gt;Codegen();
+ if (ElseV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
+ ElseBB = Builder.GetInsertBlock();
+
+ // Emit merge block.
+ TheFunction-&gt;getBasicBlockList().push_back(MergeBB);
+ Builder.SetInsertPoint(MergeBB);
+ PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+ "iftmp");
+
+ PN-&gt;addIncoming(ThenV, ThenBB);
+ PN-&gt;addIncoming(ElseV, ElseBB);
+ return PN;
+}
+
+Value *ForExprAST::Codegen() {
+ // Output this as:
+ // var = alloca double
+ // ...
+ // start = startexpr
+ // store start -&gt; var
+ // goto loop
+ // loop:
+ // ...
+ // bodyexpr
+ // ...
+ // loopend:
+ // step = stepexpr
+ // endcond = endexpr
+ //
+ // curvar = load var
+ // nextvar = curvar + step
+ // store nextvar -&gt; var
+ // br endcond, loop, endloop
+ // outloop:
+
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+
+ // Create an alloca for the variable in the entry block.
+ AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
+
+ // Emit the start code first, without 'variable' in scope.
+ Value *StartVal = Start-&gt;Codegen();
+ if (StartVal == 0) return 0;
+
+ // Store the value into the alloca.
+ Builder.CreateStore(StartVal, Alloca);
+
+ // Make the new basic block for the loop header, inserting after current
+ // block.
+ BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+
+ // Insert an explicit fall through from the current block to the LoopBB.
+ Builder.CreateBr(LoopBB);
+
+ // Start insertion in LoopBB.
+ Builder.SetInsertPoint(LoopBB);
+
+ // Within the loop, the variable is defined equal to the PHI node. If it
+ // shadows an existing variable, we have to restore it, so save it now.
+ AllocaInst *OldVal = NamedValues[VarName];
+ NamedValues[VarName] = Alloca;
+
+ // Emit the body of the loop. This, like any other expr, can change the
+ // current BB. Note that we ignore the value computed by the body, but don't
+ // allow an error.
+ if (Body-&gt;Codegen() == 0)
+ return 0;
+
+ // Emit the step value.
+ Value *StepVal;
+ if (Step) {
+ StepVal = Step-&gt;Codegen();
+ if (StepVal == 0) return 0;
+ } else {
+ // If not specified, use 1.0.
+ StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+ }
+
+ // Compute the end condition.
+ Value *EndCond = End-&gt;Codegen();
+ if (EndCond == 0) return EndCond;
+
+ // Reload, increment, and restore the alloca. This handles the case where
+ // the body of the loop mutates the variable.
+ Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
+ Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
+ Builder.CreateStore(NextVar, Alloca);
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ EndCond = Builder.CreateFCmpONE(EndCond,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "loopcond");
+
+ // Create the "after loop" block and insert it.
+ BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+
+ // Insert the conditional branch into the end of LoopEndBB.
+ Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
+
+ // Any new code will be inserted in AfterBB.
+ Builder.SetInsertPoint(AfterBB);
+
+ // Restore the unshadowed variable.
+ if (OldVal)
+ NamedValues[VarName] = OldVal;
+ else
+ NamedValues.erase(VarName);
+
+
+ // for expr always returns 0.0.
+ return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+}
+
+Value *VarExprAST::Codegen() {
+ std::vector&lt;AllocaInst *&gt; OldBindings;
+
+ Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
+
+ // Register all variables and emit their initializer.
+ for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
+ const std::string &amp;VarName = VarNames[i].first;
+ ExprAST *Init = VarNames[i].second;
+
+ // Emit the initializer before adding the variable to scope, this prevents
+ // the initializer from referencing the variable itself, and permits stuff
+ // like this:
+ // var a = 1 in
+ // var a = a in ... # refers to outer 'a'.
+ Value *InitVal;
+ if (Init) {
+ InitVal = Init-&gt;Codegen();
+ if (InitVal == 0) return 0;
+ } else { // If not specified, use 0.0.
+ InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+ }
+
+ AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
+ Builder.CreateStore(InitVal, Alloca);
+
+ // Remember the old variable binding so that we can restore the binding when
+ // we unrecurse.
+ OldBindings.push_back(NamedValues[VarName]);
+
+ // Remember this binding.
+ NamedValues[VarName] = Alloca;
+ }
+
+ // Codegen the body, now that all vars are in scope.
+ Value *BodyVal = Body-&gt;Codegen();
+ if (BodyVal == 0) return 0;
+
+ // Pop all our variables from scope.
+ for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
+ NamedValues[VarNames[i].first] = OldBindings[i];
+
+ // Return the body computation.
+ return BodyVal;
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector&lt;Type*&gt; Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F-&gt;getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F-&gt;eraseFromParent();
+ F = TheModule-&gt;getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F-&gt;empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F-&gt;arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
+ ++AI, ++Idx)
+ AI-&gt;setName(Args[Idx]);
+
+ return F;
+}
+
+/// CreateArgumentAllocas - Create an alloca for each argument and register the
+/// argument in the symbol table so that references to it will succeed.
+void PrototypeAST::CreateArgumentAllocas(Function *F) {
+ Function::arg_iterator AI = F-&gt;arg_begin();
+ for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
+ // Create an alloca for this variable.
+ AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
+
+ // Store the initial value into the alloca.
+ Builder.CreateStore(AI, Alloca);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = Alloca;
+ }
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto-&gt;Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // If this is an operator, install it.
+ if (Proto-&gt;isBinaryOp())
+ BinopPrecedence[Proto-&gt;getOperatorName()] = Proto-&gt;getBinaryPrecedence();
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ // Add all arguments to the symbol table and create their allocas.
+ Proto-&gt;CreateArgumentAllocas(TheFunction);
+
+ if (Value *RetVal = Body-&gt;Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ // Optimize the function.
+ TheFPM-&gt;run(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction-&gt;eraseFromParent();
+
+ if (Proto-&gt;isBinaryOp())
+ BinopPrecedence.erase(Proto-&gt;getOperatorName());
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static ExecutionEngine *TheExecutionEngine;
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P-&gt;Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F-&gt;dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F-&gt;Codegen()) {
+ // JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready&gt; ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+/// printd - printf that takes a double prints it as "%f\n", returning 0.
+extern "C"
+double printd(double X) {
+ printf("%f\n", X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext &amp;Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['='] = 2;
+ BinopPrecedence['&lt;'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready&gt; ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Create the JIT. This takes ownership of the module.
+ std::string ErrStr;
+ TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&amp;ErrStr).create();
+ if (!TheExecutionEngine) {
+ fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+ exit(1);
+ }
+
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Promote allocas to registers.
+ OurFPM.add(createPromoteMemoryToRegisterPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &amp;OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ TheFPM = 0;
+
+ // Print out all of the generated code.
+ TheModule-&gt;dump();
+
+ return 0;
+}
+</pre>
+</div>
+
+<a href="LangImpl8.html">Next: Conclusion and other useful LLVM tidbits</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/LangImpl8.html b/docs/tutorial/LangImpl8.html
new file mode 100644
index 00000000000..7c1a500a21b
--- /dev/null
+++ b/docs/tutorial/LangImpl8.html
@@ -0,0 +1,359 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Conclusion and other useful LLVM tidbits</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Conclusion and other useful LLVM tidbits</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 8
+ <ol>
+ <li><a href="#conclusion">Tutorial Conclusion</a></li>
+ <li><a href="#llvmirproperties">Properties of LLVM IR</a>
+ <ul>
+ <li><a href="#targetindep">Target Independence</a></li>
+ <li><a href="#safety">Safety Guarantees</a></li>
+ <li><a href="#langspecific">Language-Specific Optimizations</a></li>
+ </ul>
+ </li>
+ <li><a href="#tipsandtricks">Tips and Tricks</a>
+ <ul>
+ <li><a href="#offsetofsizeof">Implementing portable
+ offsetof/sizeof</a></li>
+ <li><a href="#gcstack">Garbage Collected Stack Frames</a></li>
+ </ul>
+ </li>
+ </ol>
+</li>
+</ul>
+
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="conclusion">Tutorial Conclusion</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to the final chapter of the "<a href="index.html">Implementing a
+language with LLVM</a>" tutorial. In the course of this tutorial, we have grown
+our little Kaleidoscope language from being a useless toy, to being a
+semi-interesting (but probably still useless) toy. :)</p>
+
+<p>It is interesting to see how far we've come, and how little code it has
+taken. We built the entire lexer, parser, AST, code generator, and an
+interactive run-loop (with a JIT!) by-hand in under 700 lines of
+(non-comment/non-blank) code.</p>
+
+<p>Our little language supports a couple of interesting features: it supports
+user defined binary and unary operators, it uses JIT compilation for immediate
+evaluation, and it supports a few control flow constructs with SSA construction.
+</p>
+
+<p>Part of the idea of this tutorial was to show you how easy and fun it can be
+to define, build, and play with languages. Building a compiler need not be a
+scary or mystical process! Now that you've seen some of the basics, I strongly
+encourage you to take the code and hack on it. For example, try adding:</p>
+
+<ul>
+<li><b>global variables</b> - While global variables have questional value in
+modern software engineering, they are often useful when putting together quick
+little hacks like the Kaleidoscope compiler itself. Fortunately, our current
+setup makes it very easy to add global variables: just have value lookup check
+to see if an unresolved variable is in the global variable symbol table before
+rejecting it. To create a new global variable, make an instance of the LLVM
+<tt>GlobalVariable</tt> class.</li>
+
+<li><b>typed variables</b> - Kaleidoscope currently only supports variables of
+type double. This gives the language a very nice elegance, because only
+supporting one type means that you never have to specify types. Different
+languages have different ways of handling this. The easiest way is to require
+the user to specify types for every variable definition, and record the type
+of the variable in the symbol table along with its Value*.</li>
+
+<li><b>arrays, structs, vectors, etc</b> - Once you add types, you can start
+extending the type system in all sorts of interesting ways. Simple arrays are
+very easy and are quite useful for many different applications. Adding them is
+mostly an exercise in learning how the LLVM <a
+href="../LangRef.html#i_getelementptr">getelementptr</a> instruction works: it
+is so nifty/unconventional, it <a
+href="../GetElementPtr.html">has its own FAQ</a>! If you add support
+for recursive types (e.g. linked lists), make sure to read the <a
+href="../ProgrammersManual.html#TypeResolve">section in the LLVM
+Programmer's Manual</a> that describes how to construct them.</li>
+
+<li><b>standard runtime</b> - Our current language allows the user to access
+arbitrary external functions, and we use it for things like "printd" and
+"putchard". As you extend the language to add higher-level constructs, often
+these constructs make the most sense if they are lowered to calls into a
+language-supplied runtime. For example, if you add hash tables to the language,
+it would probably make sense to add the routines to a runtime, instead of
+inlining them all the way.</li>
+
+<li><b>memory management</b> - Currently we can only access the stack in
+Kaleidoscope. It would also be useful to be able to allocate heap memory,
+either with calls to the standard libc malloc/free interface or with a garbage
+collector. If you would like to use garbage collection, note that LLVM fully
+supports <a href="../GarbageCollection.html">Accurate Garbage Collection</a>
+including algorithms that move objects and need to scan/update the stack.</li>
+
+<li><b>debugger support</b> - LLVM supports generation of <a
+href="../SourceLevelDebugging.html">DWARF Debug info</a> which is understood by
+common debuggers like GDB. Adding support for debug info is fairly
+straightforward. The best way to understand it is to compile some C/C++ code
+with "<tt>llvm-gcc -g -O0</tt>" and taking a look at what it produces.</li>
+
+<li><b>exception handling support</b> - LLVM supports generation of <a
+href="../ExceptionHandling.html">zero cost exceptions</a> which interoperate
+with code compiled in other languages. You could also generate code by
+implicitly making every function return an error value and checking it. You
+could also make explicit use of setjmp/longjmp. There are many different ways
+to go here.</li>
+
+<li><b>object orientation, generics, database access, complex numbers,
+geometric programming, ...</b> - Really, there is
+no end of crazy features that you can add to the language.</li>
+
+<li><b>unusual domains</b> - We've been talking about applying LLVM to a domain
+that many people are interested in: building a compiler for a specific language.
+However, there are many other domains that can use compiler technology that are
+not typically considered. For example, LLVM has been used to implement OpenGL
+graphics acceleration, translate C++ code to ActionScript, and many other
+cute and clever things. Maybe you will be the first to JIT compile a regular
+expression interpreter into native code with LLVM?</li>
+
+</ul>
+
+<p>
+Have fun - try doing something crazy and unusual. Building a language like
+everyone else always has, is much less fun than trying something a little crazy
+or off the wall and seeing how it turns out. If you get stuck or want to talk
+about it, feel free to email the <a
+href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">llvmdev mailing
+list</a>: it has lots of people who are interested in languages and are often
+willing to help out.
+</p>
+
+<p>Before we end this tutorial, I want to talk about some "tips and tricks" for generating
+LLVM IR. These are some of the more subtle things that may not be obvious, but
+are very useful if you want to take advantage of LLVM's capabilities.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="llvmirproperties">Properties of the LLVM IR</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>We have a couple common questions about code in the LLVM IR form - lets just
+get these out of the way right now, shall we?</p>
+
+<!-- ======================================================================= -->
+<h4><a name="targetindep">Target Independence</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Kaleidoscope is an example of a "portable language": any program written in
+Kaleidoscope will work the same way on any target that it runs on. Many other
+languages have this property, e.g. lisp, java, haskell, javascript, python, etc
+(note that while these languages are portable, not all their libraries are).</p>
+
+<p>One nice aspect of LLVM is that it is often capable of preserving target
+independence in the IR: you can take the LLVM IR for a Kaleidoscope-compiled
+program and run it on any target that LLVM supports, even emitting C code and
+compiling that on targets that LLVM doesn't support natively. You can trivially
+tell that the Kaleidoscope compiler generates target-independent code because it
+never queries for any target-specific information when generating code.</p>
+
+<p>The fact that LLVM provides a compact, target-independent, representation for
+code gets a lot of people excited. Unfortunately, these people are usually
+thinking about C or a language from the C family when they are asking questions
+about language portability. I say "unfortunately", because there is really no
+way to make (fully general) C code portable, other than shipping the source code
+around (and of course, C source code is not actually portable in general
+either - ever port a really old application from 32- to 64-bits?).</p>
+
+<p>The problem with C (again, in its full generality) is that it is heavily
+laden with target specific assumptions. As one simple example, the preprocessor
+often destructively removes target-independence from the code when it processes
+the input text:</p>
+
+<div class="doc_code">
+<pre>
+#ifdef __i386__
+ int X = 1;
+#else
+ int X = 42;
+#endif
+</pre>
+</div>
+
+<p>While it is possible to engineer more and more complex solutions to problems
+like this, it cannot be solved in full generality in a way that is better than shipping
+the actual source code.</p>
+
+<p>That said, there are interesting subsets of C that can be made portable. If
+you are willing to fix primitive types to a fixed size (say int = 32-bits,
+and long = 64-bits), don't care about ABI compatibility with existing binaries,
+and are willing to give up some other minor features, you can have portable
+code. This can make sense for specialized domains such as an
+in-kernel language.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="safety">Safety Guarantees</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Many of the languages above are also "safe" languages: it is impossible for
+a program written in Java to corrupt its address space and crash the process
+(assuming the JVM has no bugs).
+Safety is an interesting property that requires a combination of language
+design, runtime support, and often operating system support.</p>
+
+<p>It is certainly possible to implement a safe language in LLVM, but LLVM IR
+does not itself guarantee safety. The LLVM IR allows unsafe pointer casts,
+use after free bugs, buffer over-runs, and a variety of other problems. Safety
+needs to be implemented as a layer on top of LLVM and, conveniently, several
+groups have investigated this. Ask on the <a
+href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">llvmdev mailing
+list</a> if you are interested in more details.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="langspecific">Language-Specific Optimizations</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>One thing about LLVM that turns off many people is that it does not solve all
+the world's problems in one system (sorry 'world hunger', someone else will have
+to solve you some other day). One specific complaint is that people perceive
+LLVM as being incapable of performing high-level language-specific optimization:
+LLVM "loses too much information".</p>
+
+<p>Unfortunately, this is really not the place to give you a full and unified
+version of "Chris Lattner's theory of compiler design". Instead, I'll make a
+few observations:</p>
+
+<p>First, you're right that LLVM does lose information. For example, as of this
+writing, there is no way to distinguish in the LLVM IR whether an SSA-value came
+from a C "int" or a C "long" on an ILP32 machine (other than debug info). Both
+get compiled down to an 'i32' value and the information about what it came from
+is lost. The more general issue here, is that the LLVM type system uses
+"structural equivalence" instead of "name equivalence". Another place this
+surprises people is if you have two types in a high-level language that have the
+same structure (e.g. two different structs that have a single int field): these
+types will compile down into a single LLVM type and it will be impossible to
+tell what it came from.</p>
+
+<p>Second, while LLVM does lose information, LLVM is not a fixed target: we
+continue to enhance and improve it in many different ways. In addition to
+adding new features (LLVM did not always support exceptions or debug info), we
+also extend the IR to capture important information for optimization (e.g.
+whether an argument is sign or zero extended, information about pointers
+aliasing, etc). Many of the enhancements are user-driven: people want LLVM to
+include some specific feature, so they go ahead and extend it.</p>
+
+<p>Third, it is <em>possible and easy</em> to add language-specific
+optimizations, and you have a number of choices in how to do it. As one trivial
+example, it is easy to add language-specific optimization passes that
+"know" things about code compiled for a language. In the case of the C family,
+there is an optimization pass that "knows" about the standard C library
+functions. If you call "exit(0)" in main(), it knows that it is safe to
+optimize that into "return 0;" because C specifies what the 'exit'
+function does.</p>
+
+<p>In addition to simple library knowledge, it is possible to embed a variety of
+other language-specific information into the LLVM IR. If you have a specific
+need and run into a wall, please bring the topic up on the llvmdev list. At the
+very worst, you can always treat LLVM as if it were a "dumb code generator" and
+implement the high-level optimizations you desire in your front-end, on the
+language-specific AST.
+</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="tipsandtricks">Tips and Tricks</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>There is a variety of useful tips and tricks that you come to know after
+working on/with LLVM that aren't obvious at first glance. Instead of letting
+everyone rediscover them, this section talks about some of these issues.</p>
+
+<!-- ======================================================================= -->
+<h4><a name="offsetofsizeof">Implementing portable offsetof/sizeof</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>One interesting thing that comes up, if you are trying to keep the code
+generated by your compiler "target independent", is that you often need to know
+the size of some LLVM type or the offset of some field in an llvm structure.
+For example, you might need to pass the size of a type into a function that
+allocates memory.</p>
+
+<p>Unfortunately, this can vary widely across targets: for example the width of
+a pointer is trivially target-specific. However, there is a <a
+href="http://nondot.org/sabre/LLVMNotes/SizeOf-OffsetOf-VariableSizedStructs.txt">clever
+way to use the getelementptr instruction</a> that allows you to compute this
+in a portable way.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="gcstack">Garbage Collected Stack Frames</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Some languages want to explicitly manage their stack frames, often so that
+they are garbage collected or to allow easy implementation of closures. There
+are often better ways to implement these features than explicit stack frames,
+but <a
+href="http://nondot.org/sabre/LLVMNotes/ExplicitlyManagedStackFrames.txt">LLVM
+does support them,</a> if you want. It requires your front-end to convert the
+code into <a
+href="http://en.wikipedia.org/wiki/Continuation-passing_style">Continuation
+Passing Style</a> and the use of tail calls (which LLVM also supports).</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/OCamlLangImpl1.html b/docs/tutorial/OCamlLangImpl1.html
new file mode 100644
index 00000000000..73fe07bb840
--- /dev/null
+++ b/docs/tutorial/OCamlLangImpl1.html
@@ -0,0 +1,365 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Tutorial Introduction and the Lexer</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <meta name="author" content="Erick Tryzelaar">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Tutorial Introduction and the Lexer</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 1
+ <ol>
+ <li><a href="#intro">Tutorial Introduction</a></li>
+ <li><a href="#language">The Basic Language</a></li>
+ <li><a href="#lexer">The Lexer</a></li>
+ </ol>
+</li>
+<li><a href="OCamlLangImpl2.html">Chapter 2</a>: Implementing a Parser and
+AST</li>
+</ul>
+
+<div class="doc_author">
+ <p>
+ Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
+ </p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Tutorial Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to the "Implementing a language with LLVM" tutorial. This tutorial
+runs through the implementation of a simple language, showing how fun and
+easy it can be. This tutorial will get you up and started as well as help to
+build a framework you can extend to other languages. The code in this tutorial
+can also be used as a playground to hack on other LLVM specific things.
+</p>
+
+<p>
+The goal of this tutorial is to progressively unveil our language, describing
+how it is built up over time. This will let us cover a fairly broad range of
+language design and LLVM-specific usage issues, showing and explaining the code
+for it all along the way, without overwhelming you with tons of details up
+front.</p>
+
+<p>It is useful to point out ahead of time that this tutorial is really about
+teaching compiler techniques and LLVM specifically, <em>not</em> about teaching
+modern and sane software engineering principles. In practice, this means that
+we'll take a number of shortcuts to simplify the exposition. For example, the
+code leaks memory, uses global variables all over the place, doesn't use nice
+design patterns like <a
+href="http://en.wikipedia.org/wiki/Visitor_pattern">visitors</a>, etc... but it
+is very simple. If you dig in and use the code as a basis for future projects,
+fixing these deficiencies shouldn't be hard.</p>
+
+<p>I've tried to put this tutorial together in a way that makes chapters easy to
+skip over if you are already familiar with or are uninterested in the various
+pieces. The structure of the tutorial is:
+</p>
+
+<ul>
+<li><b><a href="#language">Chapter #1</a>: Introduction to the Kaleidoscope
+language, and the definition of its Lexer</b> - This shows where we are going
+and the basic functionality that we want it to do. In order to make this
+tutorial maximally understandable and hackable, we choose to implement
+everything in Objective Caml instead of using lexer and parser generators.
+LLVM obviously works just fine with such tools, feel free to use one if you
+prefer.</li>
+<li><b><a href="OCamlLangImpl2.html">Chapter #2</a>: Implementing a Parser and
+AST</b> - With the lexer in place, we can talk about parsing techniques and
+basic AST construction. This tutorial describes recursive descent parsing and
+operator precedence parsing. Nothing in Chapters 1 or 2 is LLVM-specific,
+the code doesn't even link in LLVM at this point. :)</li>
+<li><b><a href="OCamlLangImpl3.html">Chapter #3</a>: Code generation to LLVM
+IR</b> - With the AST ready, we can show off how easy generation of LLVM IR
+really is.</li>
+<li><b><a href="OCamlLangImpl4.html">Chapter #4</a>: Adding JIT and Optimizer
+Support</b> - Because a lot of people are interested in using LLVM as a JIT,
+we'll dive right into it and show you the 3 lines it takes to add JIT support.
+LLVM is also useful in many other ways, but this is one simple and "sexy" way
+to shows off its power. :)</li>
+<li><b><a href="OCamlLangImpl5.html">Chapter #5</a>: Extending the Language:
+Control Flow</b> - With the language up and running, we show how to extend it
+with control flow operations (if/then/else and a 'for' loop). This gives us a
+chance to talk about simple SSA construction and control flow.</li>
+<li><b><a href="OCamlLangImpl6.html">Chapter #6</a>: Extending the Language:
+User-defined Operators</b> - This is a silly but fun chapter that talks about
+extending the language to let the user program define their own arbitrary
+unary and binary operators (with assignable precedence!). This lets us build a
+significant piece of the "language" as library routines.</li>
+<li><b><a href="OCamlLangImpl7.html">Chapter #7</a>: Extending the Language:
+Mutable Variables</b> - This chapter talks about adding user-defined local
+variables along with an assignment operator. The interesting part about this
+is how easy and trivial it is to construct SSA form in LLVM: no, LLVM does
+<em>not</em> require your front-end to construct SSA form!</li>
+<li><b><a href="OCamlLangImpl8.html">Chapter #8</a>: Conclusion and other
+useful LLVM tidbits</b> - This chapter wraps up the series by talking about
+potential ways to extend the language, but also includes a bunch of pointers to
+info about "special topics" like adding garbage collection support, exceptions,
+debugging, support for "spaghetti stacks", and a bunch of other tips and
+tricks.</li>
+
+</ul>
+
+<p>By the end of the tutorial, we'll have written a bit less than 700 lines of
+non-comment, non-blank, lines of code. With this small amount of code, we'll
+have built up a very reasonable compiler for a non-trivial language including
+a hand-written lexer, parser, AST, as well as code generation support with a JIT
+compiler. While other systems may have interesting "hello world" tutorials,
+I think the breadth of this tutorial is a great testament to the strengths of
+LLVM and why you should consider it if you're interested in language or compiler
+design.</p>
+
+<p>A note about this tutorial: we expect you to extend the language and play
+with it on your own. Take the code and go crazy hacking away at it, compilers
+don't need to be scary creatures - it can be a lot of fun to play with
+languages!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="language">The Basic Language</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>This tutorial will be illustrated with a toy language that we'll call
+"<a href="http://en.wikipedia.org/wiki/Kaleidoscope">Kaleidoscope</a>" (derived
+from "meaning beautiful, form, and view").
+Kaleidoscope is a procedural language that allows you to define functions, use
+conditionals, math, etc. Over the course of the tutorial, we'll extend
+Kaleidoscope to support the if/then/else construct, a for loop, user defined
+operators, JIT compilation with a simple command line interface, etc.</p>
+
+<p>Because we want to keep things simple, the only datatype in Kaleidoscope is a
+64-bit floating point type (aka 'float' in O'Caml parlance). As such, all
+values are implicitly double precision and the language doesn't require type
+declarations. This gives the language a very nice and simple syntax. For
+example, the following simple example computes <a
+href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers:</a></p>
+
+<div class="doc_code">
+<pre>
+# Compute the x'th fibonacci number.
+def fib(x)
+ if x &lt; 3 then
+ 1
+ else
+ fib(x-1)+fib(x-2)
+
+# This expression will compute the 40th number.
+fib(40)
+</pre>
+</div>
+
+<p>We also allow Kaleidoscope to call into standard library functions (the LLVM
+JIT makes this completely trivial). This means that you can use the 'extern'
+keyword to define a function before you use it (this is also useful for mutually
+recursive functions). For example:</p>
+
+<div class="doc_code">
+<pre>
+extern sin(arg);
+extern cos(arg);
+extern atan2(arg1 arg2);
+
+atan2(sin(.4), cos(42))
+</pre>
+</div>
+
+<p>A more interesting example is included in Chapter 6 where we write a little
+Kaleidoscope application that <a href="OCamlLangImpl6.html#example">displays
+a Mandelbrot Set</a> at various levels of magnification.</p>
+
+<p>Lets dive into the implementation of this language!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="lexer">The Lexer</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>When it comes to implementing a language, the first thing needed is
+the ability to process a text file and recognize what it says. The traditional
+way to do this is to use a "<a
+href="http://en.wikipedia.org/wiki/Lexical_analysis">lexer</a>" (aka 'scanner')
+to break the input up into "tokens". Each token returned by the lexer includes
+a token code and potentially some metadata (e.g. the numeric value of a number).
+First, we define the possibilities:
+</p>
+
+<div class="doc_code">
+<pre>
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+</pre>
+</div>
+
+<p>Each token returned by our lexer will be one of the token variant values.
+An unknown character like '+' will be returned as <tt>Token.Kwd '+'</tt>. If
+the curr token is an identifier, the value will be <tt>Token.Ident s</tt>. If
+the current token is a numeric literal (like 1.0), the value will be
+<tt>Token.Number 1.0</tt>.
+</p>
+
+<p>The actual implementation of the lexer is a collection of functions driven
+by a function named <tt>Lexer.lex</tt>. The <tt>Lexer.lex</tt> function is
+called to return the next token from standard input. We will use
+<a href="http://caml.inria.fr/pub/docs/manual-camlp4/index.html">Camlp4</a>
+to simplify the tokenization of the standard input. Its definition starts
+as:</p>
+
+<div class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
+</pre>
+</div>
+
+<p>
+<tt>Lexer.lex</tt> works by recursing over a <tt>char Stream.t</tt> to read
+characters one at a time from the standard input. It eats them as it recognizes
+them and stores them in in a <tt>Token.token</tt> variant. The first thing that
+it has to do is ignore whitespace between tokens. This is accomplished with the
+recursive call above.</p>
+
+<p>The next thing <tt>Lexer.lex</tt> needs to do is recognize identifiers and
+specific keywords like "def". Kaleidoscope does this with a pattern match
+and a helper function.<p>
+
+<div class="doc_code">
+<pre>
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+...
+
+and lex_ident buffer = parser
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+</pre>
+</div>
+
+<p>Numeric values are similar:</p>
+
+<div class="doc_code">
+<pre>
+ (* number: [0-9.]+ *)
+ | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+...
+
+and lex_number buffer = parser
+ | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
+</pre>
+</div>
+
+<p>This is all pretty straight-forward code for processing input. When reading
+a numeric value from input, we use the ocaml <tt>float_of_string</tt> function
+to convert it to a numeric value that we store in <tt>Token.Number</tt>. Note
+that this isn't doing sufficient error checking: it will raise <tt>Failure</tt>
+if the string "1.23.45.67". Feel free to extend it :). Next we handle
+comments:
+</p>
+
+<div class="doc_code">
+<pre>
+ (* Comment until end of line. *)
+ | [&lt; ' ('#'); stream &gt;] -&gt;
+ lex_comment stream
+
+...
+
+and lex_comment = parser
+ | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
+ | [&lt; 'c; e=lex_comment &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+</pre>
+</div>
+
+<p>We handle comments by skipping to the end of the line and then return the
+next token. Finally, if the input doesn't match one of the above cases, it is
+either an operator character like '+' or the end of the file. These are handled
+with this code:</p>
+
+<div class="doc_code">
+<pre>
+ (* Otherwise, just return the character as its ascii value. *)
+ | [&lt; 'c; stream &gt;] -&gt;
+ [&lt; 'Token.Kwd c; lex stream &gt;]
+
+ (* end of stream. *)
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+</pre>
+</div>
+
+<p>With this, we have the complete lexer for the basic Kaleidoscope language
+(the <a href="OCamlLangImpl2.html#code">full code listing</a> for the Lexer is
+available in the <a href="OCamlLangImpl2.html">next chapter</a> of the
+tutorial). Next we'll <a href="OCamlLangImpl2.html">build a simple parser that
+uses this to build an Abstract Syntax Tree</a>. When we have that, we'll
+include a driver so that you can use the lexer and parser together.
+</p>
+
+<a href="OCamlLangImpl2.html">Next: Implementing a Parser and AST</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/OCamlLangImpl2.html b/docs/tutorial/OCamlLangImpl2.html
new file mode 100644
index 00000000000..dd7e07b4224
--- /dev/null
+++ b/docs/tutorial/OCamlLangImpl2.html
@@ -0,0 +1,1043 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Implementing a Parser and AST</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <meta name="author" content="Erick Tryzelaar">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Implementing a Parser and AST</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 2
+ <ol>
+ <li><a href="#intro">Chapter 2 Introduction</a></li>
+ <li><a href="#ast">The Abstract Syntax Tree (AST)</a></li>
+ <li><a href="#parserbasics">Parser Basics</a></li>
+ <li><a href="#parserprimexprs">Basic Expression Parsing</a></li>
+ <li><a href="#parserbinops">Binary Expression Parsing</a></li>
+ <li><a href="#parsertop">Parsing the Rest</a></li>
+ <li><a href="#driver">The Driver</a></li>
+ <li><a href="#conclusions">Conclusions</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="OCamlLangImpl3.html">Chapter 3</a>: Code generation to LLVM IR</li>
+</ul>
+
+<div class="doc_author">
+ <p>
+ Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
+ </p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 2 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 2 of the "<a href="index.html">Implementing a language
+with LLVM in Objective Caml</a>" tutorial. This chapter shows you how to use
+the lexer, built in <a href="OCamlLangImpl1.html">Chapter 1</a>, to build a
+full <a href="http://en.wikipedia.org/wiki/Parsing">parser</a> for our
+Kaleidoscope language. Once we have a parser, we'll define and build an <a
+href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax
+Tree</a> (AST).</p>
+
+<p>The parser we will build uses a combination of <a
+href="http://en.wikipedia.org/wiki/Recursive_descent_parser">Recursive Descent
+Parsing</a> and <a href=
+"http://en.wikipedia.org/wiki/Operator-precedence_parser">Operator-Precedence
+Parsing</a> to parse the Kaleidoscope language (the latter for
+binary expressions and the former for everything else). Before we get to
+parsing though, lets talk about the output of the parser: the Abstract Syntax
+Tree.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="ast">The Abstract Syntax Tree (AST)</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The AST for a program captures its behavior in such a way that it is easy for
+later stages of the compiler (e.g. code generation) to interpret. We basically
+want one object for each construct in the language, and the AST should closely
+model the language. In Kaleidoscope, we have expressions, a prototype, and a
+function object. We'll start with expressions first:</p>
+
+<div class="doc_code">
+<pre>
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+</pre>
+</div>
+
+<p>The code above shows the definition of the base ExprAST class and one
+subclass which we use for numeric literals. The important thing to note about
+this code is that the Number variant captures the numeric value of the
+literal as an instance variable. This allows later phases of the compiler to
+know what the stored numeric value is.</p>
+
+<p>Right now we only create the AST, so there are no useful functions on
+them. It would be very easy to add a function to pretty print the code,
+for example. Here are the other expression AST node definitions that we'll use
+in the basic form of the Kaleidoscope language:
+</p>
+
+<div class="doc_code">
+<pre>
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+</pre>
+</div>
+
+<p>This is all (intentionally) rather straight-forward: variables capture the
+variable name, binary operators capture their opcode (e.g. '+'), and calls
+capture a function name as well as a list of any argument expressions. One thing
+that is nice about our AST is that it captures the language features without
+talking about the syntax of the language. Note that there is no discussion about
+precedence of binary operators, lexical structure, etc.</p>
+
+<p>For our basic language, these are all of the expression nodes we'll define.
+Because it doesn't have conditional control flow, it isn't Turing-complete;
+we'll fix that in a later installment. The two things we need next are a way
+to talk about the interface to a function, and a way to talk about functions
+themselves:</p>
+
+<div class="doc_code">
+<pre>
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
+</pre>
+</div>
+
+<p>In Kaleidoscope, functions are typed with just a count of their arguments.
+Since all values are double precision floating point, the type of each argument
+doesn't need to be stored anywhere. In a more aggressive and realistic
+language, the "expr" variants would probably have a type field.</p>
+
+<p>With this scaffolding, we can now talk about parsing expressions and function
+bodies in Kaleidoscope.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="parserbasics">Parser Basics</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Now that we have an AST to build, we need to define the parser code to build
+it. The idea here is that we want to parse something like "x+y" (which is
+returned as three tokens by the lexer) into an AST that could be generated with
+calls like this:</p>
+
+<div class="doc_code">
+<pre>
+ let x = Variable "x" in
+ let y = Variable "y" in
+ let result = Binary ('+', x, y) in
+ ...
+</pre>
+</div>
+
+<p>
+The error handling routines make use of the builtin <tt>Stream.Failure</tt> and
+<tt>Stream.Error</tt>s. <tt>Stream.Failure</tt> is raised when the parser is
+unable to find any matching token in the first position of a pattern.
+<tt>Stream.Error</tt> is raised when the first token matches, but the rest do
+not. The error recovery in our parser will not be the best and is not
+particular user-friendly, but it will be enough for our tutorial. These
+exceptions make it easier to handle errors in routines that have various return
+types.</p>
+
+<p>With these basic types and exceptions, we can implement the first
+piece of our grammar: numeric literals.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="parserprimexprs">Basic Expression Parsing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>We start with numeric literals, because they are the simplest to process.
+For each production in our grammar, we'll define a function which parses that
+production. We call this class of expressions "primary" expressions, for
+reasons that will become more clear <a href="OCamlLangImpl6.html#unary">
+later in the tutorial</a>. In order to parse an arbitrary primary expression,
+we need to determine what sort of expression it is. For numeric literals, we
+have:</p>
+
+<div class="doc_code">
+<pre>
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr *)
+parse_primary = parser
+ (* numberexpr ::= number *)
+ | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
+</pre>
+</div>
+
+<p>This routine is very simple: it expects to be called when the current token
+is a <tt>Token.Number</tt> token. It takes the current number value, creates
+a <tt>Ast.Number</tt> node, advances the lexer to the next token, and finally
+returns.</p>
+
+<p>There are some interesting aspects to this. The most important one is that
+this routine eats all of the tokens that correspond to the production and
+returns the lexer buffer with the next token (which is not part of the grammar
+production) ready to go. This is a fairly standard way to go for recursive
+descent parsers. For a better example, the parenthesis operator is defined like
+this:</p>
+
+<div class="doc_code">
+<pre>
+ (* parenexpr ::= '(' expression ')' *)
+ | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
+</pre>
+</div>
+
+<p>This function illustrates a number of interesting things about the
+parser:</p>
+
+<p>
+1) It shows how we use the <tt>Stream.Error</tt> exception. When called, this
+function expects that the current token is a '(' token, but after parsing the
+subexpression, it is possible that there is no ')' waiting. For example, if
+the user types in "(4 x" instead of "(4)", the parser should emit an error.
+Because errors can occur, the parser needs a way to indicate that they
+happened. In our parser, we use the camlp4 shortcut syntax <tt>token ?? "parse
+error"</tt>, where if the token before the <tt>??</tt> does not match, then
+<tt>Stream.Error "parse error"</tt> will be raised.</p>
+
+<p>2) Another interesting aspect of this function is that it uses recursion by
+calling <tt>Parser.parse_primary</tt> (we will soon see that
+<tt>Parser.parse_primary</tt> can call <tt>Parser.parse_primary</tt>). This is
+powerful because it allows us to handle recursive grammars, and keeps each
+production very simple. Note that parentheses do not cause construction of AST
+nodes themselves. While we could do it this way, the most important role of
+parentheses are to guide the parser and provide grouping. Once the parser
+constructs the AST, parentheses are not needed.</p>
+
+<p>The next simple production is for handling variable references and function
+calls:</p>
+
+<div class="doc_code">
+<pre>
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [&lt; 'Token.Ident id; stream &gt;] -&gt;
+ let rec parse_args accumulator = parser
+ | [&lt; e=parse_expr; stream &gt;] -&gt;
+ begin parser
+ | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; e :: accumulator
+ end stream
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [&lt; 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [&lt; &gt;] -&gt; Ast.Variable id
+ in
+ parse_ident id stream
+</pre>
+</div>
+
+<p>This routine follows the same style as the other routines. (It expects to be
+called if the current token is a <tt>Token.Ident</tt> token). It also has
+recursion and error handling. One interesting aspect of this is that it uses
+<em>look-ahead</em> to determine if the current identifier is a stand alone
+variable reference or if it is a function call expression. It handles this by
+checking to see if the token after the identifier is a '(' token, constructing
+either a <tt>Ast.Variable</tt> or <tt>Ast.Call</tt> node as appropriate.
+</p>
+
+<p>We finish up by raising an exception if we received a token we didn't
+expect:</p>
+
+<div class="doc_code">
+<pre>
+ | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
+</pre>
+</div>
+
+<p>Now that basic expressions are handled, we need to handle binary expressions.
+They are a bit more complex.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="parserbinops">Binary Expression Parsing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Binary expressions are significantly harder to parse because they are often
+ambiguous. For example, when given the string "x+y*z", the parser can choose
+to parse it as either "(x+y)*z" or "x+(y*z)". With common definitions from
+mathematics, we expect the later parse, because "*" (multiplication) has
+higher <em>precedence</em> than "+" (addition).</p>
+
+<p>There are many ways to handle this, but an elegant and efficient way is to
+use <a href=
+"http://en.wikipedia.org/wiki/Operator-precedence_parser">Operator-Precedence
+Parsing</a>. This parsing technique uses the precedence of binary operators to
+guide recursion. To start with, we need a table of precedences:</p>
+
+<div class="doc_code">
+<pre>
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
+
+...
+
+let main () =
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '&lt;' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+ ...
+</pre>
+</div>
+
+<p>For the basic form of Kaleidoscope, we will only support 4 binary operators
+(this can obviously be extended by you, our brave and intrepid reader). The
+<tt>Parser.precedence</tt> function returns the precedence for the current
+token, or -1 if the token is not a binary operator. Having a <tt>Hashtbl.t</tt>
+makes it easy to add new operators and makes it clear that the algorithm doesn't
+depend on the specific operators involved, but it would be easy enough to
+eliminate the <tt>Hashtbl.t</tt> and do the comparisons in the
+<tt>Parser.precedence</tt> function. (Or just use a fixed-size array).</p>
+
+<p>With the helper above defined, we can now start parsing binary expressions.
+The basic idea of operator precedence parsing is to break down an expression
+with potentially ambiguous binary operators into pieces. Consider ,for example,
+the expression "a+b+(c+d)*e*f+g". Operator precedence parsing considers this
+as a stream of primary expressions separated by binary operators. As such,
+it will first parse the leading primary expression "a", then it will see the
+pairs [+, b] [+, (c+d)] [*, e] [*, f] and [+, g]. Note that because parentheses
+are primary expressions, the binary expression parser doesn't need to worry
+about nested subexpressions like (c+d) at all.
+</p>
+
+<p>
+To start, an expression is a primary expression potentially followed by a
+sequence of [binop,primaryexpr] pairs:</p>
+
+<div class="doc_code">
+<pre>
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [&lt; lhs=parse_primary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
+</pre>
+</div>
+
+<p><tt>Parser.parse_bin_rhs</tt> is the function that parses the sequence of
+pairs for us. It takes a precedence and a pointer to an expression for the part
+that has been parsed so far. Note that "x" is a perfectly valid expression: As
+such, "binoprhs" is allowed to be empty, in which case it returns the expression
+that is passed into it. In our example above, the code passes the expression for
+"a" into <tt>Parser.parse_bin_rhs</tt> and the current token is "+".</p>
+
+<p>The precedence value passed into <tt>Parser.parse_bin_rhs</tt> indicates the
+<em>minimal operator precedence</em> that the function is allowed to eat. For
+example, if the current pair stream is [+, x] and <tt>Parser.parse_bin_rhs</tt>
+is passed in a precedence of 40, it will not consume any tokens (because the
+precedence of '+' is only 20). With this in mind, <tt>Parser.parse_bin_rhs</tt>
+starts with:</p>
+
+<div class="doc_code">
+<pre>
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec &lt; expr_prec then lhs else begin
+</pre>
+</div>
+
+<p>This code gets the precedence of the current token and checks to see if if is
+too low. Because we defined invalid tokens to have a precedence of -1, this
+check implicitly knows that the pair-stream ends when the token stream runs out
+of binary operators. If this check succeeds, we know that the token is a binary
+operator and that it will be included in this expression:</p>
+
+<div class="doc_code">
+<pre>
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) -&gt;
+</pre>
+</div>
+
+<p>As such, this code eats (and remembers) the binary operator and then parses
+the primary expression that follows. This builds up the whole pair, the first of
+which is [+, b] for the running example.</p>
+
+<p>Now that we parsed the left-hand side of an expression and one pair of the
+RHS sequence, we have to decide which way the expression associates. In
+particular, we could have "(a+b) binop unparsed" or "a + (b binop unparsed)".
+To determine this, we look ahead at "binop" to determine its precedence and
+compare it to BinOp's precedence (which is '+' in this case):</p>
+
+<div class="doc_code">
+<pre>
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec &lt; next_prec
+</pre>
+</div>
+
+<p>If the precedence of the binop to the right of "RHS" is lower or equal to the
+precedence of our current operator, then we know that the parentheses associate
+as "(a+b) binop ...". In our example, the current operator is "+" and the next
+operator is "+", we know that they have the same precedence. In this case we'll
+create the AST node for "a+b", and then continue parsing:</p>
+
+<div class="doc_code">
+<pre>
+ ... if body omitted ...
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+</pre>
+</div>
+
+<p>In our example above, this will turn "a+b+" into "(a+b)" and execute the next
+iteration of the loop, with "+" as the current token. The code above will eat,
+remember, and parse "(c+d)" as the primary expression, which makes the
+current pair equal to [+, (c+d)]. It will then evaluate the 'if' conditional above with
+"*" as the binop to the right of the primary. In this case, the precedence of "*" is
+higher than the precedence of "+" so the if condition will be entered.</p>
+
+<p>The critical question left here is "how can the if condition parse the right
+hand side in full"? In particular, to build the AST correctly for our example,
+it needs to get all of "(c+d)*e*f" as the RHS expression variable. The code to
+do this is surprisingly simple (code from the above two blocks duplicated for
+context):</p>
+
+<div class="doc_code">
+<pre>
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) -&gt;
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ if token_prec &lt; precedence c2
+ then <b>parse_bin_rhs (token_prec + 1) rhs stream</b>
+ else rhs
+ | _ -&gt; rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+</pre>
+</div>
+
+<p>At this point, we know that the binary operator to the RHS of our primary
+has higher precedence than the binop we are currently parsing. As such, we know
+that any sequence of pairs whose operators are all higher precedence than "+"
+should be parsed together and returned as "RHS". To do this, we recursively
+invoke the <tt>Parser.parse_bin_rhs</tt> function specifying "token_prec+1" as
+the minimum precedence required for it to continue. In our example above, this
+will cause it to return the AST node for "(c+d)*e*f" as RHS, which is then set
+as the RHS of the '+' expression.</p>
+
+<p>Finally, on the next iteration of the while loop, the "+g" piece is parsed
+and added to the AST. With this little bit of code (14 non-trivial lines), we
+correctly handle fully general binary expression parsing in a very elegant way.
+This was a whirlwind tour of this code, and it is somewhat subtle. I recommend
+running through it with a few tough examples to see how it works.
+</p>
+
+<p>This wraps up handling of expressions. At this point, we can point the
+parser at an arbitrary token stream and build an expression from it, stopping
+at the first token that is not part of the expression. Next up we need to
+handle function definitions, etc.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="parsertop">Parsing the Rest</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+The next thing missing is handling of function prototypes. In Kaleidoscope,
+these are used both for 'extern' function declarations as well as function body
+definitions. The code to do this is straight-forward and not very interesting
+(once you've survived expressions):
+</p>
+
+<div class="doc_code">
+<pre>
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+</pre>
+</div>
+
+<p>Given this, a function definition is very simple, just a prototype plus
+an expression to implement the body:</p>
+
+<div class="doc_code">
+<pre>
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
+ Ast.Function (p, e)
+</pre>
+</div>
+
+<p>In addition, we support 'extern' to declare functions like 'sin' and 'cos' as
+well as to support forward declaration of user functions. These 'extern's are just
+prototypes with no body:</p>
+
+<div class="doc_code">
+<pre>
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
+</pre>
+</div>
+
+<p>Finally, we'll also let the user type in arbitrary top-level expressions and
+evaluate them on the fly. We will handle this by defining anonymous nullary
+(zero argument) functions for them:</p>
+
+<div class="doc_code">
+<pre>
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [&lt; e=parse_expr &gt;] -&gt;
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+</pre>
+</div>
+
+<p>Now that we have all the pieces, let's build a little driver that will let us
+actually <em>execute</em> this code we've built!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="driver">The Driver</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The driver for this simply invokes all of the parsing pieces with a top-level
+dispatch loop. There isn't much interesting here, so I'll just include the
+top-level loop. See <a href="#code">below</a> for full code in the "Top-Level
+Parsing" section.</p>
+
+<div class="doc_code">
+<pre>
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop stream =
+ match Stream.peek stream with
+ | None -&gt; ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') -&gt;
+ Stream.junk stream;
+ main_loop stream
+
+ | Some token -&gt;
+ begin
+ try match token with
+ | Token.Def -&gt;
+ ignore(Parser.parse_definition stream);
+ print_endline "parsed a function definition.";
+ | Token.Extern -&gt;
+ ignore(Parser.parse_extern stream);
+ print_endline "parsed an extern.";
+ | _ -&gt;
+ (* Evaluate a top-level expression into an anonymous function. *)
+ ignore(Parser.parse_toplevel stream);
+ print_endline "parsed a top-level expr";
+ with Stream.Error s -&gt;
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready&gt; "; flush stdout;
+ main_loop stream
+</pre>
+</div>
+
+<p>The most interesting part of this is that we ignore top-level semicolons.
+Why is this, you ask? The basic reason is that if you type "4 + 5" at the
+command line, the parser doesn't know whether that is the end of what you will type
+or not. For example, on the next line you could type "def foo..." in which case
+4+5 is the end of a top-level expression. Alternatively you could type "* 6",
+which would continue the expression. Having top-level semicolons allows you to
+type "4+5;", and the parser will know you are done.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="conclusions">Conclusions</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>With just under 300 lines of commented code (240 lines of non-comment,
+non-blank code), we fully defined our minimal language, including a lexer,
+parser, and AST builder. With this done, the executable will validate
+Kaleidoscope code and tell us if it is grammatically invalid. For
+example, here is a sample interaction:</p>
+
+<div class="doc_code">
+<pre>
+$ <b>./toy.byte</b>
+ready&gt; <b>def foo(x y) x+foo(y, 4.0);</b>
+Parsed a function definition.
+ready&gt; <b>def foo(x y) x+y y;</b>
+Parsed a function definition.
+Parsed a top-level expr
+ready&gt; <b>def foo(x y) x+y );</b>
+Parsed a function definition.
+Error: unknown token when expecting an expression
+ready&gt; <b>extern sin(a);</b>
+ready&gt; Parsed an extern
+ready&gt; <b>^D</b>
+$
+</pre>
+</div>
+
+<p>There is a lot of room for extension here. You can define new AST nodes,
+extend the language in many ways, etc. In the <a href="OCamlLangImpl3.html">
+next installment</a>, we will describe how to generate LLVM Intermediate
+Representation (IR) from the AST.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for this and the previous chapter.
+Note that it is fully self-contained: you don't need LLVM or any external
+libraries at all for this. (Besides the ocaml standard libraries, of
+course.) To build this, just compile with:</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+ocamlbuild toy.byte
+# Run
+./toy.byte
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<dl>
+<dt>_tags:</dt>
+<dd class="doc_code">
+<pre>
+&lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
+</pre>
+</dd>
+
+<dt>token.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+</pre>
+</dd>
+
+<dt>lexer.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [&lt; ' ('#'); stream &gt;] -&gt;
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [&lt; 'c; stream &gt;] -&gt;
+ [&lt; 'Token.Kwd c; lex stream &gt;]
+
+ (* end of stream. *)
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+
+and lex_number buffer = parser
+ | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
+
+and lex_ident buffer = parser
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+
+and lex_comment = parser
+ | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
+ | [&lt; 'c; e=lex_comment &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+</pre>
+</dd>
+
+<dt>ast.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
+</pre>
+</dd>
+
+<dt>parser.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [&lt; 'Token.Ident id; stream &gt;] -&gt;
+ let rec parse_args accumulator = parser
+ | [&lt; e=parse_expr; stream &gt;] -&gt;
+ begin parser
+ | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; e :: accumulator
+ end stream
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [&lt; 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [&lt; &gt;] -&gt; Ast.Variable id
+ in
+ parse_ident id stream
+
+ | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec &lt; expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_primary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) -&gt;
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec &lt; next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -&gt; rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -&gt; lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [&lt; lhs=parse_primary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [&lt; e=parse_expr &gt;] -&gt;
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
+</pre>
+</dd>
+
+<dt>toplevel.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop stream =
+ match Stream.peek stream with
+ | None -&gt; ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') -&gt;
+ Stream.junk stream;
+ main_loop stream
+
+ | Some token -&gt;
+ begin
+ try match token with
+ | Token.Def -&gt;
+ ignore(Parser.parse_definition stream);
+ print_endline "parsed a function definition.";
+ | Token.Extern -&gt;
+ ignore(Parser.parse_extern stream);
+ print_endline "parsed an extern.";
+ | _ -&gt;
+ (* Evaluate a top-level expression into an anonymous function. *)
+ ignore(Parser.parse_toplevel stream);
+ print_endline "parsed a top-level expr";
+ with Stream.Error s -&gt;
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready&gt; "; flush stdout;
+ main_loop stream
+</pre>
+</dd>
+
+<dt>toy.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+let main () =
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '&lt;' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready&gt; "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop stream;
+;;
+
+main ()
+</pre>
+</dd>
+</dl>
+
+<a href="OCamlLangImpl3.html">Next: Implementing Code Generation to LLVM IR</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ <a href="mailto:erickt@users.sourceforge.net">Erick Tryzelaar</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/OCamlLangImpl3.html b/docs/tutorial/OCamlLangImpl3.html
new file mode 100644
index 00000000000..a49a0b5d9c6
--- /dev/null
+++ b/docs/tutorial/OCamlLangImpl3.html
@@ -0,0 +1,1093 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Implementing code generation to LLVM IR</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <meta name="author" content="Erick Tryzelaar">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Code generation to LLVM IR</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 3
+ <ol>
+ <li><a href="#intro">Chapter 3 Introduction</a></li>
+ <li><a href="#basics">Code Generation Setup</a></li>
+ <li><a href="#exprs">Expression Code Generation</a></li>
+ <li><a href="#funcs">Function Code Generation</a></li>
+ <li><a href="#driver">Driver Changes and Closing Thoughts</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="OCamlLangImpl4.html">Chapter 4</a>: Adding JIT and Optimizer
+Support</li>
+</ul>
+
+<div class="doc_author">
+ <p>
+ Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
+ </p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 3 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 3 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. This chapter shows you how to transform the <a
+href="OCamlLangImpl2.html">Abstract Syntax Tree</a>, built in Chapter 2, into
+LLVM IR. This will teach you a little bit about how LLVM does things, as well
+as demonstrate how easy it is to use. It's much more work to build a lexer and
+parser than it is to generate LLVM IR code. :)
+</p>
+
+<p><b>Please note</b>: the code in this chapter and later require LLVM 2.3 or
+LLVM SVN to work. LLVM 2.2 and before will not work with it.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="basics">Code Generation Setup</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+In order to generate LLVM IR, we want some simple setup to get started. First
+we define virtual code generation (codegen) methods in each AST class:</p>
+
+<div class="doc_code">
+<pre>
+let rec codegen_expr = function
+ | Ast.Number n -&gt; ...
+ | Ast.Variable name -&gt; ...
+</pre>
+</div>
+
+<p>The <tt>Codegen.codegen_expr</tt> function says to emit IR for that AST node
+along with all the things it depends on, and they all return an LLVM Value
+object. "Value" is the class used to represent a "<a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
+Assignment (SSA)</a> register" or "SSA value" in LLVM. The most distinct aspect
+of SSA values is that their value is computed as the related instruction
+executes, and it does not get a new value until (and if) the instruction
+re-executes. In other words, there is no way to "change" an SSA value. For
+more information, please read up on <a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
+Assignment</a> - the concepts are really quite natural once you grok them.</p>
+
+<p>The
+second thing we want is an "Error" exception like we used for the parser, which
+will be used to report errors found during code generation (for example, use of
+an undeclared parameter):</p>
+
+<div class="doc_code">
+<pre>
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+</pre>
+</div>
+
+<p>The static variables will be used during code generation.
+<tt>Codgen.the_module</tt> is the LLVM construct that contains all of the
+functions and global variables in a chunk of code. In many ways, it is the
+top-level structure that the LLVM IR uses to contain code.</p>
+
+<p>The <tt>Codegen.builder</tt> object is a helper object that makes it easy to
+generate LLVM instructions. Instances of the <a
+href="http://llvm.org/doxygen/IRBuilder_8h-source.html"><tt>IRBuilder</tt></a>
+class keep track of the current place to insert instructions and has methods to
+create new instructions.</p>
+
+<p>The <tt>Codegen.named_values</tt> map keeps track of which values are defined
+in the current scope and what their LLVM representation is. (In other words, it
+is a symbol table for the code). In this form of Kaleidoscope, the only things
+that can be referenced are function parameters. As such, function parameters
+will be in this map when generating code for their function body.</p>
+
+<p>
+With these basics in place, we can start talking about how to generate code for
+each expression. Note that this assumes that the <tt>Codgen.builder</tt> has
+been set up to generate code <em>into</em> something. For now, we'll assume
+that this has already been done, and we'll just use it to emit code.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="exprs">Expression Code Generation</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Generating LLVM code for expression nodes is very straightforward: less
+than 30 lines of commented code for all four of our expression nodes. First
+we'll do numeric literals:</p>
+
+<div class="doc_code">
+<pre>
+ | Ast.Number n -&gt; const_float double_type n
+</pre>
+</div>
+
+<p>In the LLVM IR, numeric constants are represented with the
+<tt>ConstantFP</tt> class, which holds the numeric value in an <tt>APFloat</tt>
+internally (<tt>APFloat</tt> has the capability of holding floating point
+constants of <em>A</em>rbitrary <em>P</em>recision). This code basically just
+creates and returns a <tt>ConstantFP</tt>. Note that in the LLVM IR
+that constants are all uniqued together and shared. For this reason, the API
+uses "the foo::get(..)" idiom instead of "new foo(..)" or "foo::Create(..)".</p>
+
+<div class="doc_code">
+<pre>
+ | Ast.Variable name -&gt;
+ (try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name"))
+</pre>
+</div>
+
+<p>References to variables are also quite simple using LLVM. In the simple
+version of Kaleidoscope, we assume that the variable has already been emitted
+somewhere and its value is available. In practice, the only values that can be
+in the <tt>Codegen.named_values</tt> map are function arguments. This code
+simply checks to see that the specified name is in the map (if not, an unknown
+variable is being referenced) and returns the value for it. In future chapters,
+we'll add support for <a href="LangImpl5.html#for">loop induction variables</a>
+in the symbol table, and for <a href="LangImpl7.html#localvars">local
+variables</a>.</p>
+
+<div class="doc_code">
+<pre>
+ | Ast.Binary (op, lhs, rhs) -&gt;
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -&gt; build_fadd lhs_val rhs_val "addtmp" builder
+ | '-' -&gt; build_fsub lhs_val rhs_val "subtmp" builder
+ | '*' -&gt; build_fmul lhs_val rhs_val "multmp" builder
+ | '&lt;' -&gt;
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -&gt; raise (Error "invalid binary operator")
+ end
+</pre>
+</div>
+
+<p>Binary operators start to get more interesting. The basic idea here is that
+we recursively emit code for the left-hand side of the expression, then the
+right-hand side, then we compute the result of the binary expression. In this
+code, we do a simple switch on the opcode to create the right LLVM instruction.
+</p>
+
+<p>In the example above, the LLVM builder class is starting to show its value.
+IRBuilder knows where to insert the newly created instruction, all you have to
+do is specify what instruction to create (e.g. with <tt>Llvm.create_add</tt>),
+which operands to use (<tt>lhs</tt> and <tt>rhs</tt> here) and optionally
+provide a name for the generated instruction.</p>
+
+<p>One nice thing about LLVM is that the name is just a hint. For instance, if
+the code above emits multiple "addtmp" variables, LLVM will automatically
+provide each one with an increasing, unique numeric suffix. Local value names
+for instructions are purely optional, but it makes it much easier to read the
+IR dumps.</p>
+
+<p><a href="../LangRef.html#instref">LLVM instructions</a> are constrained by
+strict rules: for example, the Left and Right operators of
+an <a href="../LangRef.html#i_add">add instruction</a> must have the same
+type, and the result type of the add must match the operand types. Because
+all values in Kaleidoscope are doubles, this makes for very simple code for add,
+sub and mul.</p>
+
+<p>On the other hand, LLVM specifies that the <a
+href="../LangRef.html#i_fcmp">fcmp instruction</a> always returns an 'i1' value
+(a one bit integer). The problem with this is that Kaleidoscope wants the value to be a 0.0 or 1.0 value. In order to get these semantics, we combine the fcmp instruction with
+a <a href="../LangRef.html#i_uitofp">uitofp instruction</a>. This instruction
+converts its input integer into a floating point value by treating the input
+as an unsigned value. In contrast, if we used the <a
+href="../LangRef.html#i_sitofp">sitofp instruction</a>, the Kaleidoscope '&lt;'
+operator would return 0.0 and -1.0, depending on the input value.</p>
+
+<div class="doc_code">
+<pre>
+ | Ast.Call (callee, args) -&gt;
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+</pre>
+</div>
+
+<p>Code generation for function calls is quite straightforward with LLVM. The
+code above initially does a function name lookup in the LLVM Module's symbol
+table. Recall that the LLVM Module is the container that holds all of the
+functions we are JIT'ing. By giving each function the same name as what the
+user specifies, we can use the LLVM symbol table to resolve function names for
+us.</p>
+
+<p>Once we have the function to call, we recursively codegen each argument that
+is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
+instruction</a>. Note that LLVM uses the native C calling conventions by
+default, allowing these calls to also call into standard library functions like
+"sin" and "cos", with no additional effort.</p>
+
+<p>This wraps up our handling of the four basic expressions that we have so far
+in Kaleidoscope. Feel free to go in and add some more. For example, by
+browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
+several other interesting instructions that are really easy to plug into our
+basic framework.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="funcs">Function Code Generation</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Code generation for prototypes and functions must handle a number of
+details, which make their code less beautiful than expression code
+generation, but allows us to illustrate some important points. First, lets
+talk about code generation for prototypes: they are used both for function
+bodies and external function declarations. The code starts with:</p>
+
+<div class="doc_code">
+<pre>
+let codegen_proto = function
+ | Ast.Prototype (name, args) -&gt;
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+</pre>
+</div>
+
+<p>This code packs a lot of power into a few lines. Note first that this
+function returns a "Function*" instead of a "Value*" (although at the moment
+they both are modeled by <tt>llvalue</tt> in ocaml). Because a "prototype"
+really talks about the external interface for a function (not the value computed
+by an expression), it makes sense for it to return the LLVM Function it
+corresponds to when codegen'd.</p>
+
+<p>The call to <tt>Llvm.function_type</tt> creates the <tt>Llvm.llvalue</tt>
+that should be used for a given Prototype. Since all function arguments in
+Kaleidoscope are of type double, the first line creates a vector of "N" LLVM
+double types. It then uses the <tt>Llvm.function_type</tt> method to create a
+function type that takes "N" doubles as arguments, returns one double as a
+result, and that is not vararg (that uses the function
+<tt>Llvm.var_arg_function_type</tt>). Note that Types in LLVM are uniqued just
+like <tt>Constant</tt>s are, so you don't "new" a type, you "get" it.</p>
+
+<p>The final line above checks if the function has already been defined in
+<tt>Codegen.the_module</tt>. If not, we will create it.</p>
+
+<div class="doc_code">
+<pre>
+ | None -&gt; declare_function name ft the_module
+</pre>
+</div>
+
+<p>This indicates the type and name to use, as well as which module to insert
+into. By default we assume a function has
+<tt>Llvm.Linkage.ExternalLinkage</tt>. "<a href="LangRef.html#linkage">external
+linkage</a>" means that the function may be defined outside the current module
+and/or that it is callable by functions outside the module. The "<tt>name</tt>"
+passed in is the name the user specified: this name is registered in
+"<tt>Codegen.the_module</tt>"s symbol table, which is used by the function call
+code above.</p>
+
+<p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
+first, we want to allow 'extern'ing a function more than once, as long as the
+prototypes for the externs match (since all arguments have the same type, we
+just have to check that the number of arguments match). Second, we want to
+allow 'extern'ing a function and then defining a body for it. This is useful
+when defining mutually recursive functions.</p>
+
+<div class="doc_code">
+<pre>
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f -&gt;
+ (* If 'f' already has a body, reject this. *)
+ if Array.length (basic_blocks f) == 0 then () else
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if Array.length (params f) == Array.length args then () else
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+</pre>
+</div>
+
+<p>In order to verify the logic above, we first check to see if the pre-existing
+function is "empty". In this case, empty means that it has no basic blocks in
+it, which means it has no body. If it has no body, it is a forward
+declaration. Since we don't allow anything after a full definition of the
+function, the code rejects this case. If the previous reference to a function
+was an 'extern', we simply verify that the number of arguments for that
+definition and this one match up. If not, we emit an error.</p>
+
+<div class="doc_code">
+<pre>
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a -&gt;
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+</pre>
+</div>
+
+<p>The last bit of code for prototypes loops over all of the arguments in the
+function, setting the name of the LLVM Argument objects to match, and registering
+the arguments in the <tt>Codegen.named_values</tt> map for future use by the
+<tt>Ast.Variable</tt> variant. Once this is set up, it returns the Function
+object to the caller. Note that we don't check for conflicting
+argument names here (e.g. "extern foo(a b a)"). Doing so would be very
+straight-forward with the mechanics we have already used above.</p>
+
+<div class="doc_code">
+<pre>
+let codegen_func = function
+ | Ast.Function (proto, body) -&gt;
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+</pre>
+</div>
+
+<p>Code generation for function definitions starts out simply enough: we just
+codegen the prototype (Proto) and verify that it is ok. We then clear out the
+<tt>Codegen.named_values</tt> map to make sure that there isn't anything in it
+from the last function we compiled. Code generation of the prototype ensures
+that there is an LLVM Function object that is ready to go for us.</p>
+
+<div class="doc_code">
+<pre>
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+</pre>
+</div>
+
+<p>Now we get to the point where the <tt>Codegen.builder</tt> is set up. The
+first line creates a new
+<a href="http://en.wikipedia.org/wiki/Basic_block">basic block</a> (named
+"entry"), which is inserted into <tt>the_function</tt>. The second line then
+tells the builder that new instructions should be inserted into the end of the
+new basic block. Basic blocks in LLVM are an important part of functions that
+define the <a
+href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
+Since we don't have any control flow, our functions will only contain one
+block at this point. We'll fix this in <a href="OCamlLangImpl5.html">Chapter
+5</a> :).</p>
+
+<div class="doc_code">
+<pre>
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ the_function
+</pre>
+</div>
+
+<p>Once the insertion point is set up, we call the <tt>Codegen.codegen_func</tt>
+method for the root expression of the function. If no error happens, this emits
+code to compute the expression into the entry block and returns the value that
+was computed. Assuming no error, we then create an LLVM <a
+href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
+Once the function is built, we call
+<tt>Llvm_analysis.assert_valid_function</tt>, which is provided by LLVM. This
+function does a variety of consistency checks on the generated code, to
+determine if our compiler is doing everything right. Using this is important:
+it can catch a lot of bugs. Once the function is finished and validated, we
+return it.</p>
+
+<div class="doc_code">
+<pre>
+ with e -&gt;
+ delete_function the_function;
+ raise e
+</pre>
+</div>
+
+<p>The only piece left here is handling of the error case. For simplicity, we
+handle this by merely deleting the function we produced with the
+<tt>Llvm.delete_function</tt> method. This allows the user to redefine a
+function that they incorrectly typed in before: if we didn't delete it, it
+would live in the symbol table, with a body, preventing future redefinition.</p>
+
+<p>This code does have a bug, though. Since the <tt>Codegen.codegen_proto</tt>
+can return a previously defined forward declaration, our code can actually delete
+a forward declaration. There are a number of ways to fix this bug, see what you
+can come up with! Here is a testcase:</p>
+
+<div class="doc_code">
+<pre>
+extern foo(a b); # ok, defines foo.
+def foo(a b) c; # error, 'c' is invalid.
+def bar() foo(1, 2); # error, unknown function "foo"
+</pre>
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="driver">Driver Changes and Closing Thoughts</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+For now, code generation to LLVM doesn't really get us much, except that we can
+look at the pretty IR calls. The sample code inserts calls to Codegen into the
+"<tt>Toplevel.main_loop</tt>", and then dumps out the LLVM IR. This gives a
+nice way to look at the LLVM IR for simple functions. For example:
+</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>4+5</b>;
+Read top-level expression:
+define double @""() {
+entry:
+ %addtmp = fadd double 4.000000e+00, 5.000000e+00
+ ret double %addtmp
+}
+</pre>
+</div>
+
+<p>Note how the parser turns the top-level expression into anonymous functions
+for us. This will be handy when we add <a href="OCamlLangImpl4.html#jit">JIT
+support</a> in the next chapter. Also note that the code is very literally
+transcribed, no optimizations are being performed. We will
+<a href="OCamlLangImpl4.html#trivialconstfold">add optimizations</a> explicitly
+in the next chapter.</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def foo(a b) a*a + 2*a*b + b*b;</b>
+Read function definition:
+define double @foo(double %a, double %b) {
+entry:
+ %multmp = fmul double %a, %a
+ %multmp1 = fmul double 2.000000e+00, %a
+ %multmp2 = fmul double %multmp1, %b
+ %addtmp = fadd double %multmp, %multmp2
+ %multmp3 = fmul double %b, %b
+ %addtmp4 = fadd double %addtmp, %multmp3
+ ret double %addtmp4
+}
+</pre>
+</div>
+
+<p>This shows some simple arithmetic. Notice the striking similarity to the
+LLVM builder calls that we use to create the instructions.</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def bar(a) foo(a, 4.0) + bar(31337);</b>
+Read function definition:
+define double @bar(double %a) {
+entry:
+ %calltmp = call double @foo(double %a, double 4.000000e+00)
+ %calltmp1 = call double @bar(double 3.133700e+04)
+ %addtmp = fadd double %calltmp, %calltmp1
+ ret double %addtmp
+}
+</pre>
+</div>
+
+<p>This shows some function calls. Note that this function will take a long
+time to execute if you call it. In the future we'll add conditional control
+flow to actually make recursion useful :).</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>extern cos(x);</b>
+Read extern:
+declare double @cos(double)
+
+ready&gt; <b>cos(1.234);</b>
+Read top-level expression:
+define double @""() {
+entry:
+ %calltmp = call double @cos(double 1.234000e+00)
+ ret double %calltmp
+}
+</pre>
+</div>
+
+<p>This shows an extern for the libm "cos" function, and a call to it.</p>
+
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>^D</b>
+; ModuleID = 'my cool jit'
+
+define double @""() {
+entry:
+ %addtmp = fadd double 4.000000e+00, 5.000000e+00
+ ret double %addtmp
+}
+
+define double @foo(double %a, double %b) {
+entry:
+ %multmp = fmul double %a, %a
+ %multmp1 = fmul double 2.000000e+00, %a
+ %multmp2 = fmul double %multmp1, %b
+ %addtmp = fadd double %multmp, %multmp2
+ %multmp3 = fmul double %b, %b
+ %addtmp4 = fadd double %addtmp, %multmp3
+ ret double %addtmp4
+}
+
+define double @bar(double %a) {
+entry:
+ %calltmp = call double @foo(double %a, double 4.000000e+00)
+ %calltmp1 = call double @bar(double 3.133700e+04)
+ %addtmp = fadd double %calltmp, %calltmp1
+ ret double %addtmp
+}
+
+declare double @cos(double)
+
+define double @""() {
+entry:
+ %calltmp = call double @cos(double 1.234000e+00)
+ ret double %calltmp
+}
+</pre>
+</div>
+
+<p>When you quit the current demo, it dumps out the IR for the entire module
+generated. Here you can see the big picture with all the functions referencing
+each other.</p>
+
+<p>This wraps up the third chapter of the Kaleidoscope tutorial. Up next, we'll
+describe how to <a href="OCamlLangImpl4.html">add JIT codegen and optimizer
+support</a> to this so we can actually start running code!</p>
+
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with the
+LLVM code generator. Because this uses the LLVM libraries, we need to link
+them in. To do this, we use the <a
+href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
+our makefile/command line about which options to use:</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+ocamlbuild toy.byte
+# Run
+./toy.byte
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<dl>
+<dt>_tags:</dt>
+<dd class="doc_code">
+<pre>
+&lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
+&lt;*.{byte,native}&gt;: g++, use_llvm, use_llvm_analysis
+</pre>
+</dd>
+
+<dt>myocamlbuild.ml:</dt>
+<dd class="doc_code">
+<pre>
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
+</pre>
+</dd>
+
+<dt>token.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+</pre>
+</dd>
+
+<dt>lexer.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [&lt; ' ('#'); stream &gt;] -&gt;
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [&lt; 'c; stream &gt;] -&gt;
+ [&lt; 'Token.Kwd c; lex stream &gt;]
+
+ (* end of stream. *)
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+
+and lex_number buffer = parser
+ | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
+
+and lex_ident buffer = parser
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+
+and lex_comment = parser
+ | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
+ | [&lt; 'c; e=lex_comment &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+</pre>
+</dd>
+
+<dt>ast.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
+</pre>
+</dd>
+
+<dt>parser.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [&lt; 'Token.Ident id; stream &gt;] -&gt;
+ let rec parse_args accumulator = parser
+ | [&lt; e=parse_expr; stream &gt;] -&gt;
+ begin parser
+ | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; e :: accumulator
+ end stream
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [&lt; 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [&lt; &gt;] -&gt; Ast.Variable id
+ in
+ parse_ident id stream
+
+ | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec &lt; expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_primary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) -&gt;
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec &lt; next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -&gt; rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -&gt; lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [&lt; lhs=parse_primary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [&lt; e=parse_expr &gt;] -&gt;
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
+</pre>
+</dd>
+
+<dt>codegen.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+let rec codegen_expr = function
+ | Ast.Number n -&gt; const_float double_type n
+ | Ast.Variable name -&gt;
+ (try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name"))
+ | Ast.Binary (op, lhs, rhs) -&gt;
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -&gt; build_add lhs_val rhs_val "addtmp" builder
+ | '-' -&gt; build_sub lhs_val rhs_val "subtmp" builder
+ | '*' -&gt; build_mul lhs_val rhs_val "multmp" builder
+ | '&lt;' -&gt;
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -&gt; raise (Error "invalid binary operator")
+ end
+ | Ast.Call (callee, args) -&gt;
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) -&gt;
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -&gt; declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f -&gt;
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f &lt;&gt; At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) &lt;&gt; ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a -&gt;
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+let codegen_func = function
+ | Ast.Function (proto, body) -&gt;
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ the_function
+ with e -&gt;
+ delete_function the_function;
+ raise e
+</pre>
+</dd>
+
+<dt>toplevel.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop stream =
+ match Stream.peek stream with
+ | None -&gt; ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') -&gt;
+ Stream.junk stream;
+ main_loop stream
+
+ | Some token -&gt;
+ begin
+ try match token with
+ | Token.Def -&gt;
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func e);
+ | Token.Extern -&gt;
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ -&gt;
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ dump_value (Codegen.codegen_func e);
+ with Stream.Error s | Codegen.Error s -&gt;
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready&gt; "; flush stdout;
+ main_loop stream
+</pre>
+</dd>
+
+<dt>toy.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+let main () =
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '&lt;' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready&gt; "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
+</pre>
+</dd>
+</dl>
+
+<a href="OCamlLangImpl4.html">Next: Adding JIT and Optimizer Support</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/OCamlLangImpl4.html b/docs/tutorial/OCamlLangImpl4.html
new file mode 100644
index 00000000000..ca427eb0e08
--- /dev/null
+++ b/docs/tutorial/OCamlLangImpl4.html
@@ -0,0 +1,1026 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Adding JIT and Optimizer Support</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <meta name="author" content="Erick Tryzelaar">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Adding JIT and Optimizer Support</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 4
+ <ol>
+ <li><a href="#intro">Chapter 4 Introduction</a></li>
+ <li><a href="#trivialconstfold">Trivial Constant Folding</a></li>
+ <li><a href="#optimizerpasses">LLVM Optimization Passes</a></li>
+ <li><a href="#jit">Adding a JIT Compiler</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="OCamlLangImpl5.html">Chapter 5</a>: Extending the Language: Control
+Flow</li>
+</ul>
+
+<div class="doc_author">
+ <p>
+ Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
+ </p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 4 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 4 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. Chapters 1-3 described the implementation of a simple
+language and added support for generating LLVM IR. This chapter describes
+two new techniques: adding optimizer support to your language, and adding JIT
+compiler support. These additions will demonstrate how to get nice, efficient code
+for the Kaleidoscope language.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="trivialconstfold">Trivial Constant Folding</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p><b>Note:</b> the default <tt>IRBuilder</tt> now always includes the constant
+folding optimisations below.<p>
+
+<p>
+Our demonstration for Chapter 3 is elegant and easy to extend. Unfortunately,
+it does not produce wonderful code. For example, when compiling simple code,
+we don't get obvious optimizations:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def test(x) 1+2+x;</b>
+Read function definition:
+define double @test(double %x) {
+entry:
+ %addtmp = fadd double 1.000000e+00, 2.000000e+00
+ %addtmp1 = fadd double %addtmp, %x
+ ret double %addtmp1
+}
+</pre>
+</div>
+
+<p>This code is a very, very literal transcription of the AST built by parsing
+the input. As such, this transcription lacks optimizations like constant folding
+(we'd like to get "<tt>add x, 3.0</tt>" in the example above) as well as other
+more important optimizations. Constant folding, in particular, is a very common
+and very important optimization: so much so that many language implementors
+implement constant folding support in their AST representation.</p>
+
+<p>With LLVM, you don't need this support in the AST. Since all calls to build
+LLVM IR go through the LLVM builder, it would be nice if the builder itself
+checked to see if there was a constant folding opportunity when you call it.
+If so, it could just do the constant fold and return the constant instead of
+creating an instruction. This is exactly what the <tt>LLVMFoldingBuilder</tt>
+class does.
+
+<p>All we did was switch from <tt>LLVMBuilder</tt> to
+<tt>LLVMFoldingBuilder</tt>. Though we change no other code, we now have all of our
+instructions implicitly constant folded without us having to do anything
+about it. For example, the input above now compiles to:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def test(x) 1+2+x;</b>
+Read function definition:
+define double @test(double %x) {
+entry:
+ %addtmp = fadd double 3.000000e+00, %x
+ ret double %addtmp
+}
+</pre>
+</div>
+
+<p>Well, that was easy :). In practice, we recommend always using
+<tt>LLVMFoldingBuilder</tt> when generating code like this. It has no
+"syntactic overhead" for its use (you don't have to uglify your compiler with
+constant checks everywhere) and it can dramatically reduce the amount of
+LLVM IR that is generated in some cases (particular for languages with a macro
+preprocessor or that use a lot of constants).</p>
+
+<p>On the other hand, the <tt>LLVMFoldingBuilder</tt> is limited by the fact
+that it does all of its analysis inline with the code as it is built. If you
+take a slightly more complex example:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
+ready&gt; Read function definition:
+define double @test(double %x) {
+entry:
+ %addtmp = fadd double 3.000000e+00, %x
+ %addtmp1 = fadd double %x, 3.000000e+00
+ %multmp = fmul double %addtmp, %addtmp1
+ ret double %multmp
+}
+</pre>
+</div>
+
+<p>In this case, the LHS and RHS of the multiplication are the same value. We'd
+really like to see this generate "<tt>tmp = x+3; result = tmp*tmp;</tt>" instead
+of computing "<tt>x*3</tt>" twice.</p>
+
+<p>Unfortunately, no amount of local analysis will be able to detect and correct
+this. This requires two transformations: reassociation of expressions (to
+make the add's lexically identical) and Common Subexpression Elimination (CSE)
+to delete the redundant add instruction. Fortunately, LLVM provides a broad
+range of optimizations that you can use, in the form of "passes".</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="optimizerpasses">LLVM Optimization Passes</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>LLVM provides many optimization passes, which do many different sorts of
+things and have different tradeoffs. Unlike other systems, LLVM doesn't hold
+to the mistaken notion that one set of optimizations is right for all languages
+and for all situations. LLVM allows a compiler implementor to make complete
+decisions about what optimizations to use, in which order, and in what
+situation.</p>
+
+<p>As a concrete example, LLVM supports both "whole module" passes, which look
+across as large of body of code as they can (often a whole file, but if run
+at link time, this can be a substantial portion of the whole program). It also
+supports and includes "per-function" passes which just operate on a single
+function at a time, without looking at other functions. For more information
+on passes and how they are run, see the <a href="../WritingAnLLVMPass.html">How
+to Write a Pass</a> document and the <a href="../Passes.html">List of LLVM
+Passes</a>.</p>
+
+<p>For Kaleidoscope, we are currently generating functions on the fly, one at
+a time, as the user types them in. We aren't shooting for the ultimate
+optimization experience in this setting, but we also want to catch the easy and
+quick stuff where possible. As such, we will choose to run a few per-function
+optimizations as the user types the function in. If we wanted to make a "static
+Kaleidoscope compiler", we would use exactly the code we have now, except that
+we would defer running the optimizer until the entire file has been parsed.</p>
+
+<p>In order to get per-function optimizations going, we need to set up a
+<a href="../WritingAnLLVMPass.html#passmanager">Llvm.PassManager</a> to hold and
+organize the LLVM optimizations that we want to run. Once we have that, we can
+add a set of optimizations to run. The code looks like this:</p>
+
+<div class="doc_code">
+<pre>
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combining the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+</pre>
+</div>
+
+<p>The meat of the matter here, is the definition of "<tt>the_fpm</tt>". It
+requires a pointer to the <tt>the_module</tt> to construct itself. Once it is
+set up, we use a series of "add" calls to add a bunch of LLVM passes. The
+first pass is basically boilerplate, it adds a pass so that later optimizations
+know how the data structures in the program are laid out. The
+"<tt>the_execution_engine</tt>" variable is related to the JIT, which we will
+get to in the next section.</p>
+
+<p>In this case, we choose to add 4 optimization passes. The passes we chose
+here are a pretty standard set of "cleanup" optimizations that are useful for
+a wide variety of code. I won't delve into what they do but, believe me,
+they are a good starting place :).</p>
+
+<p>Once the <tt>Llvm.PassManager.</tt> is set up, we need to make use of it.
+We do this by running it after our newly created function is constructed (in
+<tt>Codegen.codegen_func</tt>), but before it is returned to the client:</p>
+
+<div class="doc_code">
+<pre>
+let codegen_func the_fpm = function
+ ...
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+</pre>
+</div>
+
+<p>As you can see, this is pretty straightforward. The <tt>the_fpm</tt>
+optimizes and updates the LLVM Function* in place, improving (hopefully) its
+body. With this in place, we can try our test above again:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
+ready&gt; Read function definition:
+define double @test(double %x) {
+entry:
+ %addtmp = fadd double %x, 3.000000e+00
+ %multmp = fmul double %addtmp, %addtmp
+ ret double %multmp
+}
+</pre>
+</div>
+
+<p>As expected, we now get our nicely optimized code, saving a floating point
+add instruction from every execution of this function.</p>
+
+<p>LLVM provides a wide variety of optimizations that can be used in certain
+circumstances. Some <a href="../Passes.html">documentation about the various
+passes</a> is available, but it isn't very complete. Another good source of
+ideas can come from looking at the passes that <tt>Clang</tt> runs to get
+started. The "<tt>opt</tt>" tool allows you to experiment with passes from the
+command line, so you can see if they do anything.</p>
+
+<p>Now that we have reasonable code coming out of our front-end, lets talk about
+executing it!</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="jit">Adding a JIT Compiler</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Code that is available in LLVM IR can have a wide variety of tools
+applied to it. For example, you can run optimizations on it (as we did above),
+you can dump it out in textual or binary forms, you can compile the code to an
+assembly file (.s) for some target, or you can JIT compile it. The nice thing
+about the LLVM IR representation is that it is the "common currency" between
+many different parts of the compiler.
+</p>
+
+<p>In this section, we'll add JIT compiler support to our interpreter. The
+basic idea that we want for Kaleidoscope is to have the user enter function
+bodies as they do now, but immediately evaluate the top-level expressions they
+type in. For example, if they type in "1 + 2;", we should evaluate and print
+out 3. If they define a function, they should be able to call it from the
+command line.</p>
+
+<p>In order to do this, we first declare and initialize the JIT. This is done
+by adding a global variable and a call in <tt>main</tt>:</p>
+
+<div class="doc_code">
+<pre>
+...
+let main () =
+ ...
+ <b>(* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in</b>
+ ...
+</pre>
+</div>
+
+<p>This creates an abstract "Execution Engine" which can be either a JIT
+compiler or the LLVM interpreter. LLVM will automatically pick a JIT compiler
+for you if one is available for your platform, otherwise it will fall back to
+the interpreter.</p>
+
+<p>Once the <tt>Llvm_executionengine.ExecutionEngine.t</tt> is created, the JIT
+is ready to be used. There are a variety of APIs that are useful, but the
+simplest one is the "<tt>Llvm_executionengine.ExecutionEngine.run_function</tt>"
+function. This method JIT compiles the specified LLVM Function and returns a
+function pointer to the generated machine code. In our case, this means that we
+can change the code that parses a top-level expression to look like this:</p>
+
+<div class="doc_code">
+<pre>
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+</pre>
+</div>
+
+<p>Recall that we compile top-level expressions into a self-contained LLVM
+function that takes no arguments and returns the computed double. Because the
+LLVM JIT compiler matches the native platform ABI, this means that you can just
+cast the result pointer to a function pointer of that type and call it directly.
+This means, there is no difference between JIT compiled code and native machine
+code that is statically linked into your application.</p>
+
+<p>With just these two changes, lets see how Kaleidoscope works now!</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>4+5;</b>
+define double @""() {
+entry:
+ ret double 9.000000e+00
+}
+
+<em>Evaluated to 9.000000</em>
+</pre>
+</div>
+
+<p>Well this looks like it is basically working. The dump of the function
+shows the "no argument function that always returns double" that we synthesize
+for each top level expression that is typed in. This demonstrates very basic
+functionality, but can we do more?</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>def testfunc(x y) x + y*2; </b>
+Read function definition:
+define double @testfunc(double %x, double %y) {
+entry:
+ %multmp = fmul double %y, 2.000000e+00
+ %addtmp = fadd double %multmp, %x
+ ret double %addtmp
+}
+
+ready&gt; <b>testfunc(4, 10);</b>
+define double @""() {
+entry:
+ %calltmp = call double @testfunc(double 4.000000e+00, double 1.000000e+01)
+ ret double %calltmp
+}
+
+<em>Evaluated to 24.000000</em>
+</pre>
+</div>
+
+<p>This illustrates that we can now call user code, but there is something a bit
+subtle going on here. Note that we only invoke the JIT on the anonymous
+functions that <em>call testfunc</em>, but we never invoked it
+on <em>testfunc</em> itself. What actually happened here is that the JIT
+scanned for all non-JIT'd functions transitively called from the anonymous
+function and compiled all of them before returning
+from <tt>run_function</tt>.</p>
+
+<p>The JIT provides a number of other more advanced interfaces for things like
+freeing allocated machine code, rejit'ing functions to update them, etc.
+However, even with this simple code, we get some surprisingly powerful
+capabilities - check this out (I removed the dump of the anonymous functions,
+you should get the idea by now :) :</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>extern sin(x);</b>
+Read extern:
+declare double @sin(double)
+
+ready&gt; <b>extern cos(x);</b>
+Read extern:
+declare double @cos(double)
+
+ready&gt; <b>sin(1.0);</b>
+<em>Evaluated to 0.841471</em>
+
+ready&gt; <b>def foo(x) sin(x)*sin(x) + cos(x)*cos(x);</b>
+Read function definition:
+define double @foo(double %x) {
+entry:
+ %calltmp = call double @sin(double %x)
+ %multmp = fmul double %calltmp, %calltmp
+ %calltmp2 = call double @cos(double %x)
+ %multmp4 = fmul double %calltmp2, %calltmp2
+ %addtmp = fadd double %multmp, %multmp4
+ ret double %addtmp
+}
+
+ready&gt; <b>foo(4.0);</b>
+<em>Evaluated to 1.000000</em>
+</pre>
+</div>
+
+<p>Whoa, how does the JIT know about sin and cos? The answer is surprisingly
+simple: in this example, the JIT started execution of a function and got to a
+function call. It realized that the function was not yet JIT compiled and
+invoked the standard set of routines to resolve the function. In this case,
+there is no body defined for the function, so the JIT ended up calling
+"<tt>dlsym("sin")</tt>" on the Kaleidoscope process itself. Since
+"<tt>sin</tt>" is defined within the JIT's address space, it simply patches up
+calls in the module to call the libm version of <tt>sin</tt> directly.</p>
+
+<p>The LLVM JIT provides a number of interfaces (look in the
+<tt>llvm_executionengine.mli</tt> file) for controlling how unknown functions
+get resolved. It allows you to establish explicit mappings between IR objects
+and addresses (useful for LLVM global variables that you want to map to static
+tables, for example), allows you to dynamically decide on the fly based on the
+function name, and even allows you to have the JIT compile functions lazily the
+first time they're called.</p>
+
+<p>One interesting application of this is that we can now extend the language
+by writing arbitrary C code to implement operations. For example, if we add:
+</p>
+
+<div class="doc_code">
+<pre>
+/* putchard - putchar that takes a double and returns 0. */
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+</pre>
+</div>
+
+<p>Now we can produce simple output to the console by using things like:
+"<tt>extern putchard(x); putchard(120);</tt>", which prints a lowercase 'x' on
+the console (120 is the ASCII code for 'x'). Similar code could be used to
+implement file I/O, console input, and many other capabilities in
+Kaleidoscope.</p>
+
+<p>This completes the JIT and optimizer chapter of the Kaleidoscope tutorial. At
+this point, we can compile a non-Turing-complete programming language, optimize
+and JIT compile it in a user-driven way. Next up we'll look into <a
+href="OCamlLangImpl5.html">extending the language with control flow
+constructs</a>, tackling some interesting LLVM IR issues along the way.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with the
+LLVM JIT and optimizer. To build this example, use:
+</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+ocamlbuild toy.byte
+# Run
+./toy.byte
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<dl>
+<dt>_tags:</dt>
+<dd class="doc_code">
+<pre>
+&lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
+&lt;*.{byte,native}&gt;: g++, use_llvm, use_llvm_analysis
+&lt;*.{byte,native}&gt;: use_llvm_executionengine, use_llvm_target
+&lt;*.{byte,native}&gt;: use_llvm_scalar_opts, use_bindings
+</pre>
+</dd>
+
+<dt>myocamlbuild.ml:</dt>
+<dd class="doc_code">
+<pre>
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+ocaml_lib ~extern:true "llvm_executionengine";;
+ocaml_lib ~extern:true "llvm_target";;
+ocaml_lib ~extern:true "llvm_scalar_opts";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
+dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
+</pre>
+</dd>
+
+<dt>token.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+</pre>
+</dd>
+
+<dt>lexer.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [&lt; ' ('#'); stream &gt;] -&gt;
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [&lt; 'c; stream &gt;] -&gt;
+ [&lt; 'Token.Kwd c; lex stream &gt;]
+
+ (* end of stream. *)
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+
+and lex_number buffer = parser
+ | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
+
+and lex_ident buffer = parser
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+
+and lex_comment = parser
+ | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
+ | [&lt; 'c; e=lex_comment &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+</pre>
+</dd>
+
+<dt>ast.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
+</pre>
+</dd>
+
+<dt>parser.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [&lt; 'Token.Ident id; stream &gt;] -&gt;
+ let rec parse_args accumulator = parser
+ | [&lt; e=parse_expr; stream &gt;] -&gt;
+ begin parser
+ | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; e :: accumulator
+ end stream
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [&lt; 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [&lt; &gt;] -&gt; Ast.Variable id
+ in
+ parse_ident id stream
+
+ | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec &lt; expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_primary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) -&gt;
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec &lt; next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -&gt; rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -&gt; lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [&lt; lhs=parse_primary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [&lt; e=parse_expr &gt;] -&gt;
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
+</pre>
+</dd>
+
+<dt>codegen.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+let rec codegen_expr = function
+ | Ast.Number n -&gt; const_float double_type n
+ | Ast.Variable name -&gt;
+ (try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name"))
+ | Ast.Binary (op, lhs, rhs) -&gt;
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -&gt; build_add lhs_val rhs_val "addtmp" builder
+ | '-' -&gt; build_sub lhs_val rhs_val "subtmp" builder
+ | '*' -&gt; build_mul lhs_val rhs_val "multmp" builder
+ | '&lt;' -&gt;
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -&gt; raise (Error "invalid binary operator")
+ end
+ | Ast.Call (callee, args) -&gt;
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) -&gt;
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -&gt; declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f -&gt;
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f &lt;&gt; At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) &lt;&gt; ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a -&gt;
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) -&gt;
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+ with e -&gt;
+ delete_function the_function;
+ raise e
+</pre>
+</dd>
+
+<dt>toplevel.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop the_fpm the_execution_engine stream =
+ match Stream.peek stream with
+ | None -&gt; ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') -&gt;
+ Stream.junk stream;
+ main_loop the_fpm the_execution_engine stream
+
+ | Some token -&gt;
+ begin
+ try match token with
+ | Token.Def -&gt;
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func the_fpm e);
+ | Token.Extern -&gt;
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ -&gt;
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+ with Stream.Error s | Codegen.Error s -&gt;
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready&gt; "; flush stdout;
+ main_loop the_fpm the_execution_engine stream
+</pre>
+</dd>
+
+<dt>toy.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+open Llvm_target
+open Llvm_scalar_opts
+
+let main () =
+ ignore (initialize_native_target ());
+
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '&lt;' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready&gt; "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combination the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
+</pre>
+</dd>
+
+<dt>bindings.c</dt>
+<dd class="doc_code">
+<pre>
+#include &lt;stdio.h&gt;
+
+/* putchard - putchar that takes a double and returns 0. */
+extern double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+</pre>
+</dd>
+</dl>
+
+<a href="OCamlLangImpl5.html">Next: Extending the language: control flow</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/OCamlLangImpl5.html b/docs/tutorial/OCamlLangImpl5.html
new file mode 100644
index 00000000000..feeed6a5337
--- /dev/null
+++ b/docs/tutorial/OCamlLangImpl5.html
@@ -0,0 +1,1560 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Extending the Language: Control Flow</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <meta name="author" content="Erick Tryzelaar">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Extending the Language: Control Flow</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 5
+ <ol>
+ <li><a href="#intro">Chapter 5 Introduction</a></li>
+ <li><a href="#ifthen">If/Then/Else</a>
+ <ol>
+ <li><a href="#iflexer">Lexer Extensions</a></li>
+ <li><a href="#ifast">AST Extensions</a></li>
+ <li><a href="#ifparser">Parser Extensions</a></li>
+ <li><a href="#ifir">LLVM IR</a></li>
+ <li><a href="#ifcodegen">Code Generation</a></li>
+ </ol>
+ </li>
+ <li><a href="#for">'for' Loop Expression</a>
+ <ol>
+ <li><a href="#forlexer">Lexer Extensions</a></li>
+ <li><a href="#forast">AST Extensions</a></li>
+ <li><a href="#forparser">Parser Extensions</a></li>
+ <li><a href="#forir">LLVM IR</a></li>
+ <li><a href="#forcodegen">Code Generation</a></li>
+ </ol>
+ </li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="OCamlLangImpl6.html">Chapter 6</a>: Extending the Language:
+User-defined Operators</li>
+</ul>
+
+<div class="doc_author">
+ <p>
+ Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
+ </p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 5 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 5 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. Parts 1-4 described the implementation of the simple
+Kaleidoscope language and included support for generating LLVM IR, followed by
+optimizations and a JIT compiler. Unfortunately, as presented, Kaleidoscope is
+mostly useless: it has no control flow other than call and return. This means
+that you can't have conditional branches in the code, significantly limiting its
+power. In this episode of "build that compiler", we'll extend Kaleidoscope to
+have an if/then/else expression plus a simple 'for' loop.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="ifthen">If/Then/Else</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Extending Kaleidoscope to support if/then/else is quite straightforward. It
+basically requires adding lexer support for this "new" concept to the lexer,
+parser, AST, and LLVM code emitter. This example is nice, because it shows how
+easy it is to "grow" a language over time, incrementally extending it as new
+ideas are discovered.</p>
+
+<p>Before we get going on "how" we add this extension, lets talk about "what" we
+want. The basic idea is that we want to be able to write this sort of thing:
+</p>
+
+<div class="doc_code">
+<pre>
+def fib(x)
+ if x &lt; 3 then
+ 1
+ else
+ fib(x-1)+fib(x-2);
+</pre>
+</div>
+
+<p>In Kaleidoscope, every construct is an expression: there are no statements.
+As such, the if/then/else expression needs to return a value like any other.
+Since we're using a mostly functional form, we'll have it evaluate its
+conditional, then return the 'then' or 'else' value based on how the condition
+was resolved. This is very similar to the C "?:" expression.</p>
+
+<p>The semantics of the if/then/else expression is that it evaluates the
+condition to a boolean equality value: 0.0 is considered to be false and
+everything else is considered to be true.
+If the condition is true, the first subexpression is evaluated and returned, if
+the condition is false, the second subexpression is evaluated and returned.
+Since Kaleidoscope allows side-effects, this behavior is important to nail down.
+</p>
+
+<p>Now that we know what we "want", lets break this down into its constituent
+pieces.</p>
+
+<!-- ======================================================================= -->
+<h4><a name="iflexer">Lexer Extensions for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+
+<div>
+
+<p>The lexer extensions are straightforward. First we add new variants
+for the relevant tokens:</p>
+
+<div class="doc_code">
+<pre>
+ (* control *)
+ | If | Then | Else | For | In
+</pre>
+</div>
+
+<p>Once we have that, we recognize the new keywords in the lexer. This is pretty simple
+stuff:</p>
+
+<div class="doc_code">
+<pre>
+ ...
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | "if" -&gt; [&lt; 'Token.If; stream &gt;]
+ | "then" -&gt; [&lt; 'Token.Then; stream &gt;]
+ | "else" -&gt; [&lt; 'Token.Else; stream &gt;]
+ | "for" -&gt; [&lt; 'Token.For; stream &gt;]
+ | "in" -&gt; [&lt; 'Token.In; stream &gt;]
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="ifast">AST Extensions for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>To represent the new expression we add a new AST variant for it:</p>
+
+<div class="doc_code">
+<pre>
+type expr =
+ ...
+ (* variant for if/then/else. *)
+ | If of expr * expr * expr
+</pre>
+</div>
+
+<p>The AST variant just has pointers to the various subexpressions.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="ifparser">Parser Extensions for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Now that we have the relevant tokens coming from the lexer and we have the
+AST node to build, our parsing logic is relatively straightforward. First we
+define a new parsing function:</p>
+
+<div class="doc_code">
+<pre>
+let rec parse_primary = parser
+ ...
+ (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
+ | [&lt; 'Token.If; c=parse_expr;
+ 'Token.Then ?? "expected 'then'"; t=parse_expr;
+ 'Token.Else ?? "expected 'else'"; e=parse_expr &gt;] -&gt;
+ Ast.If (c, t, e)
+</pre>
+</div>
+
+<p>Next we hook it up as a primary expression:</p>
+
+<div class="doc_code">
+<pre>
+let rec parse_primary = parser
+ ...
+ (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
+ | [&lt; 'Token.If; c=parse_expr;
+ 'Token.Then ?? "expected 'then'"; t=parse_expr;
+ 'Token.Else ?? "expected 'else'"; e=parse_expr &gt;] -&gt;
+ Ast.If (c, t, e)
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="ifir">LLVM IR for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Now that we have it parsing and building the AST, the final piece is adding
+LLVM code generation support. This is the most interesting part of the
+if/then/else example, because this is where it starts to introduce new concepts.
+All of the code above has been thoroughly described in previous chapters.
+</p>
+
+<p>To motivate the code we want to produce, lets take a look at a simple
+example. Consider:</p>
+
+<div class="doc_code">
+<pre>
+extern foo();
+extern bar();
+def baz(x) if x then foo() else bar();
+</pre>
+</div>
+
+<p>If you disable optimizations, the code you'll (soon) get from Kaleidoscope
+looks like this:</p>
+
+<div class="doc_code">
+<pre>
+declare double @foo()
+
+declare double @bar()
+
+define double @baz(double %x) {
+entry:
+ %ifcond = fcmp one double %x, 0.000000e+00
+ br i1 %ifcond, label %then, label %else
+
+then: ; preds = %entry
+ %calltmp = call double @foo()
+ br label %ifcont
+
+else: ; preds = %entry
+ %calltmp1 = call double @bar()
+ br label %ifcont
+
+ifcont: ; preds = %else, %then
+ %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
+ ret double %iftmp
+}
+</pre>
+</div>
+
+<p>To visualize the control flow graph, you can use a nifty feature of the LLVM
+'<a href="http://llvm.org/cmds/opt.html">opt</a>' tool. If you put this LLVM IR
+into "t.ll" and run "<tt>llvm-as &lt; t.ll | opt -analyze -view-cfg</tt>", <a
+href="../ProgrammersManual.html#ViewGraph">a window will pop up</a> and you'll
+see this graph:</p>
+
+<div style="text-align: center"><img src="LangImpl5-cfg.png" alt="Example CFG" width="423"
+height="315"></div>
+
+<p>Another way to get this is to call "<tt>Llvm_analysis.view_function_cfg
+f</tt>" or "<tt>Llvm_analysis.view_function_cfg_only f</tt>" (where <tt>f</tt>
+is a "<tt>Function</tt>") either by inserting actual calls into the code and
+recompiling or by calling these in the debugger. LLVM has many nice features
+for visualizing various graphs.</p>
+
+<p>Getting back to the generated code, it is fairly simple: the entry block
+evaluates the conditional expression ("x" in our case here) and compares the
+result to 0.0 with the "<tt><a href="../LangRef.html#i_fcmp">fcmp</a> one</tt>"
+instruction ('one' is "Ordered and Not Equal"). Based on the result of this
+expression, the code jumps to either the "then" or "else" blocks, which contain
+the expressions for the true/false cases.</p>
+
+<p>Once the then/else blocks are finished executing, they both branch back to the
+'ifcont' block to execute the code that happens after the if/then/else. In this
+case the only thing left to do is to return to the caller of the function. The
+question then becomes: how does the code know which expression to return?</p>
+
+<p>The answer to this question involves an important SSA operation: the
+<a href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Phi
+operation</a>. If you're not familiar with SSA, <a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">the wikipedia
+article</a> is a good introduction and there are various other introductions to
+it available on your favorite search engine. The short version is that
+"execution" of the Phi operation requires "remembering" which block control came
+from. The Phi operation takes on the value corresponding to the input control
+block. In this case, if control comes in from the "then" block, it gets the
+value of "calltmp". If control comes from the "else" block, it gets the value
+of "calltmp1".</p>
+
+<p>At this point, you are probably starting to think "Oh no! This means my
+simple and elegant front-end will have to start generating SSA form in order to
+use LLVM!". Fortunately, this is not the case, and we strongly advise
+<em>not</em> implementing an SSA construction algorithm in your front-end
+unless there is an amazingly good reason to do so. In practice, there are two
+sorts of values that float around in code written for your average imperative
+programming language that might need Phi nodes:</p>
+
+<ol>
+<li>Code that involves user variables: <tt>x = 1; x = x + 1; </tt></li>
+<li>Values that are implicit in the structure of your AST, such as the Phi node
+in this case.</li>
+</ol>
+
+<p>In <a href="OCamlLangImpl7.html">Chapter 7</a> of this tutorial ("mutable
+variables"), we'll talk about #1
+in depth. For now, just believe me that you don't need SSA construction to
+handle this case. For #2, you have the choice of using the techniques that we will
+describe for #1, or you can insert Phi nodes directly, if convenient. In this
+case, it is really really easy to generate the Phi node, so we choose to do it
+directly.</p>
+
+<p>Okay, enough of the motivation and overview, lets generate code!</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="ifcodegen">Code Generation for If/Then/Else</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>In order to generate code for this, we implement the <tt>Codegen</tt> method
+for <tt>IfExprAST</tt>:</p>
+
+<div class="doc_code">
+<pre>
+let rec codegen_expr = function
+ ...
+ | Ast.If (cond, then_, else_) -&gt;
+ let cond = codegen_expr cond in
+
+ (* Convert condition to a bool by comparing equal to 0.0 *)
+ let zero = const_float double_type 0.0 in
+ let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
+</pre>
+</div>
+
+<p>This code is straightforward and similar to what we saw before. We emit the
+expression for the condition, then compare that value to zero to get a truth
+value as a 1-bit (bool) value.</p>
+
+<div class="doc_code">
+<pre>
+ (* Grab the first block so that we might later add the conditional branch
+ * to it at the end of the function. *)
+ let start_bb = insertion_block builder in
+ let the_function = block_parent start_bb in
+
+ let then_bb = append_block context "then" the_function in
+ position_at_end then_bb builder;
+</pre>
+</div>
+
+<p>
+As opposed to the <a href="LangImpl5.html">C++ tutorial</a>, we have to build
+our basic blocks bottom up since we can't have dangling BasicBlocks. We start
+off by saving a pointer to the first block (which might not be the entry
+block), which we'll need to build a conditional branch later. We do this by
+asking the <tt>builder</tt> for the current BasicBlock. The fourth line
+gets the current Function object that is being built. It gets this by the
+<tt>start_bb</tt> for its "parent" (the function it is currently embedded
+into).</p>
+
+<p>Once it has that, it creates one block. It is automatically appended into
+the function's list of blocks.</p>
+
+<div class="doc_code">
+<pre>
+ (* Emit 'then' value. *)
+ position_at_end then_bb builder;
+ let then_val = codegen_expr then_ in
+
+ (* Codegen of 'then' can change the current block, update then_bb for the
+ * phi. We create a new name because one is used for the phi node, and the
+ * other is used for the conditional branch. *)
+ let new_then_bb = insertion_block builder in
+</pre>
+</div>
+
+<p>We move the builder to start inserting into the "then" block. Strictly
+speaking, this call moves the insertion point to be at the end of the specified
+block. However, since the "then" block is empty, it also starts out by
+inserting at the beginning of the block. :)</p>
+
+<p>Once the insertion point is set, we recursively codegen the "then" expression
+from the AST.</p>
+
+<p>The final line here is quite subtle, but is very important. The basic issue
+is that when we create the Phi node in the merge block, we need to set up the
+block/value pairs that indicate how the Phi will work. Importantly, the Phi
+node expects to have an entry for each predecessor of the block in the CFG. Why
+then, are we getting the current block when we just set it to ThenBB 5 lines
+above? The problem is that the "Then" expression may actually itself change the
+block that the Builder is emitting into if, for example, it contains a nested
+"if/then/else" expression. Because calling Codegen recursively could
+arbitrarily change the notion of the current block, we are required to get an
+up-to-date value for code that will set up the Phi node.</p>
+
+<div class="doc_code">
+<pre>
+ (* Emit 'else' value. *)
+ let else_bb = append_block context "else" the_function in
+ position_at_end else_bb builder;
+ let else_val = codegen_expr else_ in
+
+ (* Codegen of 'else' can change the current block, update else_bb for the
+ * phi. *)
+ let new_else_bb = insertion_block builder in
+</pre>
+</div>
+
+<p>Code generation for the 'else' block is basically identical to codegen for
+the 'then' block.</p>
+
+<div class="doc_code">
+<pre>
+ (* Emit merge block. *)
+ let merge_bb = append_block context "ifcont" the_function in
+ position_at_end merge_bb builder;
+ let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
+ let phi = build_phi incoming "iftmp" builder in
+</pre>
+</div>
+
+<p>The first two lines here are now familiar: the first adds the "merge" block
+to the Function object. The second block changes the insertion point so that
+newly created code will go into the "merge" block. Once that is done, we need
+to create the PHI node and set up the block/value pairs for the PHI.</p>
+
+<div class="doc_code">
+<pre>
+ (* Return to the start block to add the conditional branch. *)
+ position_at_end start_bb builder;
+ ignore (build_cond_br cond_val then_bb else_bb builder);
+</pre>
+</div>
+
+<p>Once the blocks are created, we can emit the conditional branch that chooses
+between them. Note that creating new blocks does not implicitly affect the
+IRBuilder, so it is still inserting into the block that the condition
+went into. This is why we needed to save the "start" block.</p>
+
+<div class="doc_code">
+<pre>
+ (* Set a unconditional branch at the end of the 'then' block and the
+ * 'else' block to the 'merge' block. *)
+ position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
+ position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
+
+ (* Finally, set the builder to the end of the merge block. *)
+ position_at_end merge_bb builder;
+
+ phi
+</pre>
+</div>
+
+<p>To finish off the blocks, we create an unconditional branch
+to the merge block. One interesting (and very important) aspect of the LLVM IR
+is that it <a href="../LangRef.html#functionstructure">requires all basic blocks
+to be "terminated"</a> with a <a href="../LangRef.html#terminators">control flow
+instruction</a> such as return or branch. This means that all control flow,
+<em>including fall throughs</em> must be made explicit in the LLVM IR. If you
+violate this rule, the verifier will emit an error.
+
+<p>Finally, the CodeGen function returns the phi node as the value computed by
+the if/then/else expression. In our example above, this returned value will
+feed into the code for the top-level function, which will create the return
+instruction.</p>
+
+<p>Overall, we now have the ability to execute conditional code in
+Kaleidoscope. With this extension, Kaleidoscope is a fairly complete language
+that can calculate a wide variety of numeric functions. Next up we'll add
+another useful expression that is familiar from non-functional languages...</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="for">'for' Loop Expression</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Now that we know how to add basic control flow constructs to the language,
+we have the tools to add more powerful things. Lets add something more
+aggressive, a 'for' expression:</p>
+
+<div class="doc_code">
+<pre>
+ extern putchard(char);
+ def printstar(n)
+ for i = 1, i &lt; n, 1.0 in
+ putchard(42); # ascii 42 = '*'
+
+ # print 100 '*' characters
+ printstar(100);
+</pre>
+</div>
+
+<p>This expression defines a new variable ("i" in this case) which iterates from
+a starting value, while the condition ("i &lt; n" in this case) is true,
+incrementing by an optional step value ("1.0" in this case). If the step value
+is omitted, it defaults to 1.0. While the loop is true, it executes its
+body expression. Because we don't have anything better to return, we'll just
+define the loop as always returning 0.0. In the future when we have mutable
+variables, it will get more useful.</p>
+
+<p>As before, lets talk about the changes that we need to Kaleidoscope to
+support this.</p>
+
+<!-- ======================================================================= -->
+<h4><a name="forlexer">Lexer Extensions for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>The lexer extensions are the same sort of thing as for if/then/else:</p>
+
+<div class="doc_code">
+<pre>
+ ... in Token.token ...
+ (* control *)
+ | If | Then | Else
+ <b>| For | In</b>
+
+ ... in Lexer.lex_ident...
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | "if" -&gt; [&lt; 'Token.If; stream &gt;]
+ | "then" -&gt; [&lt; 'Token.Then; stream &gt;]
+ | "else" -&gt; [&lt; 'Token.Else; stream &gt;]
+ <b>| "for" -&gt; [&lt; 'Token.For; stream &gt;]
+ | "in" -&gt; [&lt; 'Token.In; stream &gt;]</b>
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="forast">AST Extensions for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>The AST variant is just as simple. It basically boils down to capturing
+the variable name and the constituent expressions in the node.</p>
+
+<div class="doc_code">
+<pre>
+type expr =
+ ...
+ (* variant for for/in. *)
+ | For of string * expr * expr * expr option * expr
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="forparser">Parser Extensions for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>The parser code is also fairly standard. The only interesting thing here is
+handling of the optional step value. The parser code handles it by checking to
+see if the second comma is present. If not, it sets the step value to null in
+the AST node:</p>
+
+<div class="doc_code">
+<pre>
+let rec parse_primary = parser
+ ...
+ (* forexpr
+ ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
+ | [&lt; 'Token.For;
+ 'Token.Ident id ?? "expected identifier after for";
+ 'Token.Kwd '=' ?? "expected '=' after for";
+ stream &gt;] -&gt;
+ begin parser
+ | [&lt;
+ start=parse_expr;
+ 'Token.Kwd ',' ?? "expected ',' after for";
+ end_=parse_expr;
+ stream &gt;] -&gt;
+ let step =
+ begin parser
+ | [&lt; 'Token.Kwd ','; step=parse_expr &gt;] -&gt; Some step
+ | [&lt; &gt;] -&gt; None
+ end stream
+ in
+ begin parser
+ | [&lt; 'Token.In; body=parse_expr &gt;] -&gt;
+ Ast.For (id, start, end_, step, body)
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected 'in' after for")
+ end stream
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected '=' after for")
+ end stream
+</pre>
+</div>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="forir">LLVM IR for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Now we get to the good part: the LLVM IR we want to generate for this thing.
+With the simple example above, we get this LLVM IR (note that this dump is
+generated with optimizations disabled for clarity):
+</p>
+
+<div class="doc_code">
+<pre>
+declare double @putchard(double)
+
+define double @printstar(double %n) {
+entry:
+ ; initial value = 1.0 (inlined into phi)
+ br label %loop
+
+loop: ; preds = %loop, %entry
+ %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
+ ; body
+ %calltmp = call double @putchard(double 4.200000e+01)
+ ; increment
+ %nextvar = fadd double %i, 1.000000e+00
+
+ ; termination test
+ %cmptmp = fcmp ult double %i, %n
+ %booltmp = uitofp i1 %cmptmp to double
+ %loopcond = fcmp one double %booltmp, 0.000000e+00
+ br i1 %loopcond, label %loop, label %afterloop
+
+afterloop: ; preds = %loop
+ ; loop always returns 0.0
+ ret double 0.000000e+00
+}
+</pre>
+</div>
+
+<p>This loop contains all the same constructs we saw before: a phi node, several
+expressions, and some basic blocks. Lets see how this fits together.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="forcodegen">Code Generation for the 'for' Loop</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>The first part of Codegen is very simple: we just output the start expression
+for the loop value:</p>
+
+<div class="doc_code">
+<pre>
+let rec codegen_expr = function
+ ...
+ | Ast.For (var_name, start, end_, step, body) -&gt;
+ (* Emit the start code first, without 'variable' in scope. *)
+ let start_val = codegen_expr start in
+</pre>
+</div>
+
+<p>With this out of the way, the next step is to set up the LLVM basic block
+for the start of the loop body. In the case above, the whole loop body is one
+block, but remember that the body code itself could consist of multiple blocks
+(e.g. if it contains an if/then/else or a for/in expression).</p>
+
+<div class="doc_code">
+<pre>
+ (* Make the new basic block for the loop header, inserting after current
+ * block. *)
+ let preheader_bb = insertion_block builder in
+ let the_function = block_parent preheader_bb in
+ let loop_bb = append_block context "loop" the_function in
+
+ (* Insert an explicit fall through from the current block to the
+ * loop_bb. *)
+ ignore (build_br loop_bb builder);
+</pre>
+</div>
+
+<p>This code is similar to what we saw for if/then/else. Because we will need
+it to create the Phi node, we remember the block that falls through into the
+loop. Once we have that, we create the actual block that starts the loop and
+create an unconditional branch for the fall-through between the two blocks.</p>
+
+<div class="doc_code">
+<pre>
+ (* Start insertion in loop_bb. *)
+ position_at_end loop_bb builder;
+
+ (* Start the PHI node with an entry for start. *)
+ let variable = build_phi [(start_val, preheader_bb)] var_name builder in
+</pre>
+</div>
+
+<p>Now that the "preheader" for the loop is set up, we switch to emitting code
+for the loop body. To begin with, we move the insertion point and create the
+PHI node for the loop induction variable. Since we already know the incoming
+value for the starting value, we add it to the Phi node. Note that the Phi will
+eventually get a second value for the backedge, but we can't set it up yet
+(because it doesn't exist!).</p>
+
+<div class="doc_code">
+<pre>
+ (* Within the loop, the variable is defined equal to the PHI node. If it
+ * shadows an existing variable, we have to restore it, so save it
+ * now. *)
+ let old_val =
+ try Some (Hashtbl.find named_values var_name) with Not_found -&gt; None
+ in
+ Hashtbl.add named_values var_name variable;
+
+ (* Emit the body of the loop. This, like any other expr, can change the
+ * current BB. Note that we ignore the value computed by the body, but
+ * don't allow an error *)
+ ignore (codegen_expr body);
+</pre>
+</div>
+
+<p>Now the code starts to get more interesting. Our 'for' loop introduces a new
+variable to the symbol table. This means that our symbol table can now contain
+either function arguments or loop variables. To handle this, before we codegen
+the body of the loop, we add the loop variable as the current value for its
+name. Note that it is possible that there is a variable of the same name in the
+outer scope. It would be easy to make this an error (emit an error and return
+null if there is already an entry for VarName) but we choose to allow shadowing
+of variables. In order to handle this correctly, we remember the Value that
+we are potentially shadowing in <tt>old_val</tt> (which will be None if there is
+no shadowed variable).</p>
+
+<p>Once the loop variable is set into the symbol table, the code recursively
+codegen's the body. This allows the body to use the loop variable: any
+references to it will naturally find it in the symbol table.</p>
+
+<div class="doc_code">
+<pre>
+ (* Emit the step value. *)
+ let step_val =
+ match step with
+ | Some step -&gt; codegen_expr step
+ (* If not specified, use 1.0. *)
+ | None -&gt; const_float double_type 1.0
+ in
+
+ let next_var = build_add variable step_val "nextvar" builder in
+</pre>
+</div>
+
+<p>Now that the body is emitted, we compute the next value of the iteration
+variable by adding the step value, or 1.0 if it isn't present.
+'<tt>next_var</tt>' will be the value of the loop variable on the next iteration
+of the loop.</p>
+
+<div class="doc_code">
+<pre>
+ (* Compute the end condition. *)
+ let end_cond = codegen_expr end_ in
+
+ (* Convert condition to a bool by comparing equal to 0.0. *)
+ let zero = const_float double_type 0.0 in
+ let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
+</pre>
+</div>
+
+<p>Finally, we evaluate the exit value of the loop, to determine whether the
+loop should exit. This mirrors the condition evaluation for the if/then/else
+statement.</p>
+
+<div class="doc_code">
+<pre>
+ (* Create the "after loop" block and insert it. *)
+ let loop_end_bb = insertion_block builder in
+ let after_bb = append_block context "afterloop" the_function in
+
+ (* Insert the conditional branch into the end of loop_end_bb. *)
+ ignore (build_cond_br end_cond loop_bb after_bb builder);
+
+ (* Any new code will be inserted in after_bb. *)
+ position_at_end after_bb builder;
+</pre>
+</div>
+
+<p>With the code for the body of the loop complete, we just need to finish up
+the control flow for it. This code remembers the end block (for the phi node), then creates the block for the loop exit ("afterloop"). Based on the value of the
+exit condition, it creates a conditional branch that chooses between executing
+the loop again and exiting the loop. Any future code is emitted in the
+"afterloop" block, so it sets the insertion position to it.</p>
+
+<div class="doc_code">
+<pre>
+ (* Add a new entry to the PHI node for the backedge. *)
+ add_incoming (next_var, loop_end_bb) variable;
+
+ (* Restore the unshadowed variable. *)
+ begin match old_val with
+ | Some old_val -&gt; Hashtbl.add named_values var_name old_val
+ | None -&gt; ()
+ end;
+
+ (* for expr always returns 0.0. *)
+ const_null double_type
+</pre>
+</div>
+
+<p>The final code handles various cleanups: now that we have the
+"<tt>next_var</tt>" value, we can add the incoming value to the loop PHI node.
+After that, we remove the loop variable from the symbol table, so that it isn't
+in scope after the for loop. Finally, code generation of the for loop always
+returns 0.0, so that is what we return from <tt>Codegen.codegen_expr</tt>.</p>
+
+<p>With this, we conclude the "adding control flow to Kaleidoscope" chapter of
+the tutorial. In this chapter we added two control flow constructs, and used
+them to motivate a couple of aspects of the LLVM IR that are important for
+front-end implementors to know. In the next chapter of our saga, we will get
+a bit crazier and add <a href="OCamlLangImpl6.html">user-defined operators</a>
+to our poor innocent language.</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with the
+if/then/else and for expressions.. To build this example, use:
+</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+ocamlbuild toy.byte
+# Run
+./toy.byte
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<dl>
+<dt>_tags:</dt>
+<dd class="doc_code">
+<pre>
+&lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
+&lt;*.{byte,native}&gt;: g++, use_llvm, use_llvm_analysis
+&lt;*.{byte,native}&gt;: use_llvm_executionengine, use_llvm_target
+&lt;*.{byte,native}&gt;: use_llvm_scalar_opts, use_bindings
+</pre>
+</dd>
+
+<dt>myocamlbuild.ml:</dt>
+<dd class="doc_code">
+<pre>
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+ocaml_lib ~extern:true "llvm_executionengine";;
+ocaml_lib ~extern:true "llvm_target";;
+ocaml_lib ~extern:true "llvm_scalar_opts";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
+dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
+</pre>
+</dd>
+
+<dt>token.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+
+ (* control *)
+ | If | Then | Else
+ | For | In
+</pre>
+</dd>
+
+<dt>lexer.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [&lt; ' ('#'); stream &gt;] -&gt;
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [&lt; 'c; stream &gt;] -&gt;
+ [&lt; 'Token.Kwd c; lex stream &gt;]
+
+ (* end of stream. *)
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+
+and lex_number buffer = parser
+ | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
+
+and lex_ident buffer = parser
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | "if" -&gt; [&lt; 'Token.If; stream &gt;]
+ | "then" -&gt; [&lt; 'Token.Then; stream &gt;]
+ | "else" -&gt; [&lt; 'Token.Else; stream &gt;]
+ | "for" -&gt; [&lt; 'Token.For; stream &gt;]
+ | "in" -&gt; [&lt; 'Token.In; stream &gt;]
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+
+and lex_comment = parser
+ | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
+ | [&lt; 'c; e=lex_comment &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+</pre>
+</dd>
+
+<dt>ast.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+ (* variant for if/then/else. *)
+ | If of expr * expr * expr
+
+ (* variant for for/in. *)
+ | For of string * expr * expr * expr option * expr
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
+</pre>
+</dd>
+
+<dt>parser.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr
+ * ::= ifexpr
+ * ::= forexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [&lt; 'Token.Ident id; stream &gt;] -&gt;
+ let rec parse_args accumulator = parser
+ | [&lt; e=parse_expr; stream &gt;] -&gt;
+ begin parser
+ | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; e :: accumulator
+ end stream
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [&lt; 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [&lt; &gt;] -&gt; Ast.Variable id
+ in
+ parse_ident id stream
+
+ (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
+ | [&lt; 'Token.If; c=parse_expr;
+ 'Token.Then ?? "expected 'then'"; t=parse_expr;
+ 'Token.Else ?? "expected 'else'"; e=parse_expr &gt;] -&gt;
+ Ast.If (c, t, e)
+
+ (* forexpr
+ ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
+ | [&lt; 'Token.For;
+ 'Token.Ident id ?? "expected identifier after for";
+ 'Token.Kwd '=' ?? "expected '=' after for";
+ stream &gt;] -&gt;
+ begin parser
+ | [&lt;
+ start=parse_expr;
+ 'Token.Kwd ',' ?? "expected ',' after for";
+ end_=parse_expr;
+ stream &gt;] -&gt;
+ let step =
+ begin parser
+ | [&lt; 'Token.Kwd ','; step=parse_expr &gt;] -&gt; Some step
+ | [&lt; &gt;] -&gt; None
+ end stream
+ in
+ begin parser
+ | [&lt; 'Token.In; body=parse_expr &gt;] -&gt;
+ Ast.For (id, start, end_, step, body)
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected 'in' after for")
+ end stream
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected '=' after for")
+ end stream
+
+ | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec &lt; expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_primary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) -&gt;
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec &lt; next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -&gt; rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -&gt; lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [&lt; lhs=parse_primary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [&lt; e=parse_expr &gt;] -&gt;
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
+</pre>
+</dd>
+
+<dt>codegen.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+let rec codegen_expr = function
+ | Ast.Number n -&gt; const_float double_type n
+ | Ast.Variable name -&gt;
+ (try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name"))
+ | Ast.Binary (op, lhs, rhs) -&gt;
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -&gt; build_add lhs_val rhs_val "addtmp" builder
+ | '-' -&gt; build_sub lhs_val rhs_val "subtmp" builder
+ | '*' -&gt; build_mul lhs_val rhs_val "multmp" builder
+ | '&lt;' -&gt;
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -&gt; raise (Error "invalid binary operator")
+ end
+ | Ast.Call (callee, args) -&gt;
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+ | Ast.If (cond, then_, else_) -&gt;
+ let cond = codegen_expr cond in
+
+ (* Convert condition to a bool by comparing equal to 0.0 *)
+ let zero = const_float double_type 0.0 in
+ let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
+
+ (* Grab the first block so that we might later add the conditional branch
+ * to it at the end of the function. *)
+ let start_bb = insertion_block builder in
+ let the_function = block_parent start_bb in
+
+ let then_bb = append_block context "then" the_function in
+
+ (* Emit 'then' value. *)
+ position_at_end then_bb builder;
+ let then_val = codegen_expr then_ in
+
+ (* Codegen of 'then' can change the current block, update then_bb for the
+ * phi. We create a new name because one is used for the phi node, and the
+ * other is used for the conditional branch. *)
+ let new_then_bb = insertion_block builder in
+
+ (* Emit 'else' value. *)
+ let else_bb = append_block context "else" the_function in
+ position_at_end else_bb builder;
+ let else_val = codegen_expr else_ in
+
+ (* Codegen of 'else' can change the current block, update else_bb for the
+ * phi. *)
+ let new_else_bb = insertion_block builder in
+
+ (* Emit merge block. *)
+ let merge_bb = append_block context "ifcont" the_function in
+ position_at_end merge_bb builder;
+ let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
+ let phi = build_phi incoming "iftmp" builder in
+
+ (* Return to the start block to add the conditional branch. *)
+ position_at_end start_bb builder;
+ ignore (build_cond_br cond_val then_bb else_bb builder);
+
+ (* Set a unconditional branch at the end of the 'then' block and the
+ * 'else' block to the 'merge' block. *)
+ position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
+ position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
+
+ (* Finally, set the builder to the end of the merge block. *)
+ position_at_end merge_bb builder;
+
+ phi
+ | Ast.For (var_name, start, end_, step, body) -&gt;
+ (* Emit the start code first, without 'variable' in scope. *)
+ let start_val = codegen_expr start in
+
+ (* Make the new basic block for the loop header, inserting after current
+ * block. *)
+ let preheader_bb = insertion_block builder in
+ let the_function = block_parent preheader_bb in
+ let loop_bb = append_block context "loop" the_function in
+
+ (* Insert an explicit fall through from the current block to the
+ * loop_bb. *)
+ ignore (build_br loop_bb builder);
+
+ (* Start insertion in loop_bb. *)
+ position_at_end loop_bb builder;
+
+ (* Start the PHI node with an entry for start. *)
+ let variable = build_phi [(start_val, preheader_bb)] var_name builder in
+
+ (* Within the loop, the variable is defined equal to the PHI node. If it
+ * shadows an existing variable, we have to restore it, so save it
+ * now. *)
+ let old_val =
+ try Some (Hashtbl.find named_values var_name) with Not_found -&gt; None
+ in
+ Hashtbl.add named_values var_name variable;
+
+ (* Emit the body of the loop. This, like any other expr, can change the
+ * current BB. Note that we ignore the value computed by the body, but
+ * don't allow an error *)
+ ignore (codegen_expr body);
+
+ (* Emit the step value. *)
+ let step_val =
+ match step with
+ | Some step -&gt; codegen_expr step
+ (* If not specified, use 1.0. *)
+ | None -&gt; const_float double_type 1.0
+ in
+
+ let next_var = build_add variable step_val "nextvar" builder in
+
+ (* Compute the end condition. *)
+ let end_cond = codegen_expr end_ in
+
+ (* Convert condition to a bool by comparing equal to 0.0. *)
+ let zero = const_float double_type 0.0 in
+ let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
+
+ (* Create the "after loop" block and insert it. *)
+ let loop_end_bb = insertion_block builder in
+ let after_bb = append_block context "afterloop" the_function in
+
+ (* Insert the conditional branch into the end of loop_end_bb. *)
+ ignore (build_cond_br end_cond loop_bb after_bb builder);
+
+ (* Any new code will be inserted in after_bb. *)
+ position_at_end after_bb builder;
+
+ (* Add a new entry to the PHI node for the backedge. *)
+ add_incoming (next_var, loop_end_bb) variable;
+
+ (* Restore the unshadowed variable. *)
+ begin match old_val with
+ | Some old_val -&gt; Hashtbl.add named_values var_name old_val
+ | None -&gt; ()
+ end;
+
+ (* for expr always returns 0.0. *)
+ const_null double_type
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) -&gt;
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -&gt; declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f -&gt;
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f &lt;&gt; At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) &lt;&gt; ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a -&gt;
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) -&gt;
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+ with e -&gt;
+ delete_function the_function;
+ raise e
+</pre>
+</dd>
+
+<dt>toplevel.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop the_fpm the_execution_engine stream =
+ match Stream.peek stream with
+ | None -&gt; ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') -&gt;
+ Stream.junk stream;
+ main_loop the_fpm the_execution_engine stream
+
+ | Some token -&gt;
+ begin
+ try match token with
+ | Token.Def -&gt;
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func the_fpm e);
+ | Token.Extern -&gt;
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ -&gt;
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+ with Stream.Error s | Codegen.Error s -&gt;
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready&gt; "; flush stdout;
+ main_loop the_fpm the_execution_engine stream
+</pre>
+</dd>
+
+<dt>toy.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+open Llvm_target
+open Llvm_scalar_opts
+
+let main () =
+ ignore (initialize_native_target ());
+
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '&lt;' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready&gt; "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combination the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
+</pre>
+</dd>
+
+<dt>bindings.c</dt>
+<dd class="doc_code">
+<pre>
+#include &lt;stdio.h&gt;
+
+/* putchard - putchar that takes a double and returns 0. */
+extern double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+</pre>
+</dd>
+</dl>
+
+<a href="OCamlLangImpl6.html">Next: Extending the language: user-defined
+operators</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/OCamlLangImpl6.html b/docs/tutorial/OCamlLangImpl6.html
new file mode 100644
index 00000000000..2ee5089721c
--- /dev/null
+++ b/docs/tutorial/OCamlLangImpl6.html
@@ -0,0 +1,1574 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Extending the Language: User-defined Operators</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <meta name="author" content="Erick Tryzelaar">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Extending the Language: User-defined Operators</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 6
+ <ol>
+ <li><a href="#intro">Chapter 6 Introduction</a></li>
+ <li><a href="#idea">User-defined Operators: the Idea</a></li>
+ <li><a href="#binary">User-defined Binary Operators</a></li>
+ <li><a href="#unary">User-defined Unary Operators</a></li>
+ <li><a href="#example">Kicking the Tires</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="OCamlLangImpl7.html">Chapter 7</a>: Extending the Language: Mutable
+Variables / SSA Construction</li>
+</ul>
+
+<div class="doc_author">
+ <p>
+ Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
+ </p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 6 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 6 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. At this point in our tutorial, we now have a fully
+functional language that is fairly minimal, but also useful. There
+is still one big problem with it, however. Our language doesn't have many
+useful operators (like division, logical negation, or even any comparisons
+besides less-than).</p>
+
+<p>This chapter of the tutorial takes a wild digression into adding user-defined
+operators to the simple and beautiful Kaleidoscope language. This digression now
+gives us a simple and ugly language in some ways, but also a powerful one at the
+same time. One of the great things about creating your own language is that you
+get to decide what is good or bad. In this tutorial we'll assume that it is
+okay to use this as a way to show some interesting parsing techniques.</p>
+
+<p>At the end of this tutorial, we'll run through an example Kaleidoscope
+application that <a href="#example">renders the Mandelbrot set</a>. This gives
+an example of what you can build with Kaleidoscope and its feature set.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="idea">User-defined Operators: the Idea</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+The "operator overloading" that we will add to Kaleidoscope is more general than
+languages like C++. In C++, you are only allowed to redefine existing
+operators: you can't programatically change the grammar, introduce new
+operators, change precedence levels, etc. In this chapter, we will add this
+capability to Kaleidoscope, which will let the user round out the set of
+operators that are supported.</p>
+
+<p>The point of going into user-defined operators in a tutorial like this is to
+show the power and flexibility of using a hand-written parser. Thus far, the parser
+we have been implementing uses recursive descent for most parts of the grammar and
+operator precedence parsing for the expressions. See <a
+href="OCamlLangImpl2.html">Chapter 2</a> for details. Without using operator
+precedence parsing, it would be very difficult to allow the programmer to
+introduce new operators into the grammar: the grammar is dynamically extensible
+as the JIT runs.</p>
+
+<p>The two specific features we'll add are programmable unary operators (right
+now, Kaleidoscope has no unary operators at all) as well as binary operators.
+An example of this is:</p>
+
+<div class="doc_code">
+<pre>
+# Logical unary not.
+def unary!(v)
+ if v then
+ 0
+ else
+ 1;
+
+# Define &gt; with the same precedence as &lt;.
+def binary&gt; 10 (LHS RHS)
+ RHS &lt; LHS;
+
+# Binary "logical or", (note that it does not "short circuit")
+def binary| 5 (LHS RHS)
+ if LHS then
+ 1
+ else if RHS then
+ 1
+ else
+ 0;
+
+# Define = with slightly lower precedence than relationals.
+def binary= 9 (LHS RHS)
+ !(LHS &lt; RHS | LHS &gt; RHS);
+</pre>
+</div>
+
+<p>Many languages aspire to being able to implement their standard runtime
+library in the language itself. In Kaleidoscope, we can implement significant
+parts of the language in the library!</p>
+
+<p>We will break down implementation of these features into two parts:
+implementing support for user-defined binary operators and adding unary
+operators.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="binary">User-defined Binary Operators</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Adding support for user-defined binary operators is pretty simple with our
+current framework. We'll first add support for the unary/binary keywords:</p>
+
+<div class="doc_code">
+<pre>
+type token =
+ ...
+ <b>(* operators *)
+ | Binary | Unary</b>
+
+...
+
+and lex_ident buffer = parser
+ ...
+ | "for" -&gt; [&lt; 'Token.For; stream &gt;]
+ | "in" -&gt; [&lt; 'Token.In; stream &gt;]
+ <b>| "binary" -&gt; [&lt; 'Token.Binary; stream &gt;]
+ | "unary" -&gt; [&lt; 'Token.Unary; stream &gt;]</b>
+</pre>
+</div>
+
+<p>This just adds lexer support for the unary and binary keywords, like we
+did in <a href="OCamlLangImpl5.html#iflexer">previous chapters</a>. One nice
+thing about our current AST, is that we represent binary operators with full
+generalisation by using their ASCII code as the opcode. For our extended
+operators, we'll use this same representation, so we don't need any new AST or
+parser support.</p>
+
+<p>On the other hand, we have to be able to represent the definitions of these
+new operators, in the "def binary| 5" part of the function definition. In our
+grammar so far, the "name" for the function definition is parsed as the
+"prototype" production and into the <tt>Ast.Prototype</tt> AST node. To
+represent our new user-defined operators as prototypes, we have to extend
+the <tt>Ast.Prototype</tt> AST node like this:</p>
+
+<div class="doc_code">
+<pre>
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto =
+ | Prototype of string * string array
+ <b>| BinOpPrototype of string * string array * int</b>
+</pre>
+</div>
+
+<p>Basically, in addition to knowing a name for the prototype, we now keep track
+of whether it was an operator, and if it was, what precedence level the operator
+is at. The precedence is only used for binary operators (as you'll see below,
+it just doesn't apply for unary operators). Now that we have a way to represent
+the prototype for a user-defined operator, we need to parse it:</p>
+
+<div class="doc_code">
+<pre>
+(* prototype
+ * ::= id '(' id* ')'
+ <b>* ::= binary LETTER number? (id, id)
+ * ::= unary LETTER number? (id) *)</b>
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let parse_operator = parser
+ | [&lt; 'Token.Unary &gt;] -&gt; "unary", 1
+ | [&lt; 'Token.Binary &gt;] -&gt; "binary", 2
+ in
+ let parse_binary_precedence = parser
+ | [&lt; 'Token.Number n &gt;] -&gt; int_of_float n
+ | [&lt; &gt;] -&gt; 30
+ in
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+ <b>| [&lt; (prefix, kind)=parse_operator;
+ 'Token.Kwd op ?? "expected an operator";
+ (* Read the precedence if present. *)
+ binary_precedence=parse_binary_precedence;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ let name = prefix ^ (String.make 1 op) in
+ let args = Array.of_list (List.rev args) in
+
+ (* Verify right number of arguments for operator. *)
+ if Array.length args != kind
+ then raise (Stream.Error "invalid number of operands for operator")
+ else
+ if kind == 1 then
+ Ast.Prototype (name, args)
+ else
+ Ast.BinOpPrototype (name, args, binary_precedence)</b>
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+</pre>
+</div>
+
+<p>This is all fairly straightforward parsing code, and we have already seen
+a lot of similar code in the past. One interesting part about the code above is
+the couple lines that set up <tt>name</tt> for binary operators. This builds
+names like "binary@" for a newly defined "@" operator. This then takes
+advantage of the fact that symbol names in the LLVM symbol table are allowed to
+have any character in them, including embedded nul characters.</p>
+
+<p>The next interesting thing to add, is codegen support for these binary
+operators. Given our current structure, this is a simple addition of a default
+case for our existing binary operator node:</p>
+
+<div class="doc_code">
+<pre>
+let codegen_expr = function
+ ...
+ | Ast.Binary (op, lhs, rhs) -&gt;
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -&gt; build_add lhs_val rhs_val "addtmp" builder
+ | '-' -&gt; build_sub lhs_val rhs_val "subtmp" builder
+ | '*' -&gt; build_mul lhs_val rhs_val "multmp" builder
+ | '&lt;' -&gt;
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ <b>| _ -&gt;
+ (* If it wasn't a builtin binary operator, it must be a user defined
+ * one. Emit a call to it. *)
+ let callee = "binary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "binary operator not found!")
+ in
+ build_call callee [|lhs_val; rhs_val|] "binop" builder</b>
+ end
+</pre>
+</div>
+
+<p>As you can see above, the new code is actually really simple. It just does
+a lookup for the appropriate operator in the symbol table and generates a
+function call to it. Since user-defined operators are just built as normal
+functions (because the "prototype" boils down to a function with the right
+name) everything falls into place.</p>
+
+<p>The final piece of code we are missing, is a bit of top level magic:</p>
+
+<div class="doc_code">
+<pre>
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) -&gt;
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ <b>(* If this is an operator, install it. *)
+ begin match proto with
+ | Ast.BinOpPrototype (name, args, prec) -&gt;
+ let op = name.[String.length name - 1] in
+ Hashtbl.add Parser.binop_precedence op prec;
+ | _ -&gt; ()
+ end;</b>
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+ ...
+</pre>
+</div>
+
+<p>Basically, before codegening a function, if it is a user-defined operator, we
+register it in the precedence table. This allows the binary operator parsing
+logic we already have in place to handle it. Since we are working on a
+fully-general operator precedence parser, this is all we need to do to "extend
+the grammar".</p>
+
+<p>Now we have useful user-defined binary operators. This builds a lot
+on the previous framework we built for other operators. Adding unary operators
+is a bit more challenging, because we don't have any framework for it yet - lets
+see what it takes.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="unary">User-defined Unary Operators</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Since we don't currently support unary operators in the Kaleidoscope
+language, we'll need to add everything to support them. Above, we added simple
+support for the 'unary' keyword to the lexer. In addition to that, we need an
+AST node:</p>
+
+<div class="doc_code">
+<pre>
+type expr =
+ ...
+ (* variant for a unary operator. *)
+ | Unary of char * expr
+ ...
+</pre>
+</div>
+
+<p>This AST node is very simple and obvious by now. It directly mirrors the
+binary operator AST node, except that it only has one child. With this, we
+need to add the parsing logic. Parsing a unary operator is pretty simple: we'll
+add a new function to do it:</p>
+
+<div class="doc_code">
+<pre>
+(* unary
+ * ::= primary
+ * ::= '!' unary *)
+and parse_unary = parser
+ (* If this is a unary operator, read it. *)
+ | [&lt; 'Token.Kwd op when op != '(' &amp;&amp; op != ')'; operand=parse_expr &gt;] -&gt;
+ Ast.Unary (op, operand)
+
+ (* If the current token is not an operator, it must be a primary expr. *)
+ | [&lt; stream &gt;] -&gt; parse_primary stream
+</pre>
+</div>
+
+<p>The grammar we add is pretty straightforward here. If we see a unary
+operator when parsing a primary operator, we eat the operator as a prefix and
+parse the remaining piece as another unary operator. This allows us to handle
+multiple unary operators (e.g. "!!x"). Note that unary operators can't have
+ambiguous parses like binary operators can, so there is no need for precedence
+information.</p>
+
+<p>The problem with this function, is that we need to call ParseUnary from
+somewhere. To do this, we change previous callers of ParsePrimary to call
+<tt>parse_unary</tt> instead:</p>
+
+<div class="doc_code">
+<pre>
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ ...
+ <b>(* Parse the unary expression after the binary operator. *)
+ let rhs = parse_unary stream in</b>
+ ...
+
+...
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [&lt; lhs=<b>parse_unary</b>; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
+</pre>
+</div>
+
+<p>With these two simple changes, we are now able to parse unary operators and build the
+AST for them. Next up, we need to add parser support for prototypes, to parse
+the unary operator prototype. We extend the binary operator code above
+with:</p>
+
+<div class="doc_code">
+<pre>
+(* prototype
+ * ::= id '(' id* ')'
+ * ::= binary LETTER number? (id, id)
+ <b>* ::= unary LETTER number? (id)</b> *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ <b>let parse_operator = parser
+ | [&lt; 'Token.Unary &gt;] -&gt; "unary", 1
+ | [&lt; 'Token.Binary &gt;] -&gt; "binary", 2
+ in</b>
+ let parse_binary_precedence = parser
+ | [&lt; 'Token.Number n &gt;] -&gt; int_of_float n
+ | [&lt; &gt;] -&gt; 30
+ in
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+ <b>| [&lt; (prefix, kind)=parse_operator;
+ 'Token.Kwd op ?? "expected an operator";
+ (* Read the precedence if present. *)
+ binary_precedence=parse_binary_precedence;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ let name = prefix ^ (String.make 1 op) in
+ let args = Array.of_list (List.rev args) in
+
+ (* Verify right number of arguments for operator. *)
+ if Array.length args != kind
+ then raise (Stream.Error "invalid number of operands for operator")
+ else
+ if kind == 1 then
+ Ast.Prototype (name, args)
+ else
+ Ast.BinOpPrototype (name, args, binary_precedence)</b>
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+</pre>
+</div>
+
+<p>As with binary operators, we name unary operators with a name that includes
+the operator character. This assists us at code generation time. Speaking of,
+the final piece we need to add is codegen support for unary operators. It looks
+like this:</p>
+
+<div class="doc_code">
+<pre>
+let rec codegen_expr = function
+ ...
+ | Ast.Unary (op, operand) -&gt;
+ let operand = codegen_expr operand in
+ let callee = "unary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown unary operator")
+ in
+ build_call callee [|operand|] "unop" builder
+</pre>
+</div>
+
+<p>This code is similar to, but simpler than, the code for binary operators. It
+is simpler primarily because it doesn't need to handle any predefined operators.
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="example">Kicking the Tires</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>It is somewhat hard to believe, but with a few simple extensions we've
+covered in the last chapters, we have grown a real-ish language. With this, we
+can do a lot of interesting things, including I/O, math, and a bunch of other
+things. For example, we can now add a nice sequencing operator (printd is
+defined to print out the specified value and a newline):</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>extern printd(x);</b>
+Read extern: declare double @printd(double)
+ready&gt; <b>def binary : 1 (x y) 0; # Low-precedence operator that ignores operands.</b>
+..
+ready&gt; <b>printd(123) : printd(456) : printd(789);</b>
+123.000000
+456.000000
+789.000000
+Evaluated to 0.000000
+</pre>
+</div>
+
+<p>We can also define a bunch of other "primitive" operations, such as:</p>
+
+<div class="doc_code">
+<pre>
+# Logical unary not.
+def unary!(v)
+ if v then
+ 0
+ else
+ 1;
+
+# Unary negate.
+def unary-(v)
+ 0-v;
+
+# Define &gt; with the same precedence as &lt;.
+def binary&gt; 10 (LHS RHS)
+ RHS &lt; LHS;
+
+# Binary logical or, which does not short circuit.
+def binary| 5 (LHS RHS)
+ if LHS then
+ 1
+ else if RHS then
+ 1
+ else
+ 0;
+
+# Binary logical and, which does not short circuit.
+def binary&amp; 6 (LHS RHS)
+ if !LHS then
+ 0
+ else
+ !!RHS;
+
+# Define = with slightly lower precedence than relationals.
+def binary = 9 (LHS RHS)
+ !(LHS &lt; RHS | LHS &gt; RHS);
+
+</pre>
+</div>
+
+
+<p>Given the previous if/then/else support, we can also define interesting
+functions for I/O. For example, the following prints out a character whose
+"density" reflects the value passed in: the lower the value, the denser the
+character:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt;
+<b>
+extern putchard(char)
+def printdensity(d)
+ if d &gt; 8 then
+ putchard(32) # ' '
+ else if d &gt; 4 then
+ putchard(46) # '.'
+ else if d &gt; 2 then
+ putchard(43) # '+'
+ else
+ putchard(42); # '*'</b>
+...
+ready&gt; <b>printdensity(1): printdensity(2): printdensity(3) :
+ printdensity(4): printdensity(5): printdensity(9): putchard(10);</b>
+*++..
+Evaluated to 0.000000
+</pre>
+</div>
+
+<p>Based on these simple primitive operations, we can start to define more
+interesting things. For example, here's a little function that solves for the
+number of iterations it takes a function in the complex plane to
+converge:</p>
+
+<div class="doc_code">
+<pre>
+# determine whether the specific location diverges.
+# Solve for z = z^2 + c in the complex plane.
+def mandleconverger(real imag iters creal cimag)
+ if iters &gt; 255 | (real*real + imag*imag &gt; 4) then
+ iters
+ else
+ mandleconverger(real*real - imag*imag + creal,
+ 2*real*imag + cimag,
+ iters+1, creal, cimag);
+
+# return the number of iterations required for the iteration to escape
+def mandleconverge(real imag)
+ mandleconverger(real, imag, 0, real, imag);
+</pre>
+</div>
+
+<p>This "z = z<sup>2</sup> + c" function is a beautiful little creature that is the basis
+for computation of the <a
+href="http://en.wikipedia.org/wiki/Mandelbrot_set">Mandelbrot Set</a>. Our
+<tt>mandelconverge</tt> function returns the number of iterations that it takes
+for a complex orbit to escape, saturating to 255. This is not a very useful
+function by itself, but if you plot its value over a two-dimensional plane,
+you can see the Mandelbrot set. Given that we are limited to using putchard
+here, our amazing graphical output is limited, but we can whip together
+something using the density plotter above:</p>
+
+<div class="doc_code">
+<pre>
+# compute and plot the mandlebrot set with the specified 2 dimensional range
+# info.
+def mandelhelp(xmin xmax xstep ymin ymax ystep)
+ for y = ymin, y &lt; ymax, ystep in (
+ (for x = xmin, x &lt; xmax, xstep in
+ printdensity(mandleconverge(x,y)))
+ : putchard(10)
+ )
+
+# mandel - This is a convenient helper function for plotting the mandelbrot set
+# from the specified position with the specified Magnification.
+def mandel(realstart imagstart realmag imagmag)
+ mandelhelp(realstart, realstart+realmag*78, realmag,
+ imagstart, imagstart+imagmag*40, imagmag);
+</pre>
+</div>
+
+<p>Given this, we can try plotting out the mandlebrot set! Lets try it out:</p>
+
+<div class="doc_code">
+<pre>
+ready&gt; <b>mandel(-2.3, -1.3, 0.05, 0.07);</b>
+*******************************+++++++++++*************************************
+*************************+++++++++++++++++++++++*******************************
+**********************+++++++++++++++++++++++++++++****************************
+*******************+++++++++++++++++++++.. ...++++++++*************************
+*****************++++++++++++++++++++++.... ...+++++++++***********************
+***************+++++++++++++++++++++++..... ...+++++++++*********************
+**************+++++++++++++++++++++++.... ....+++++++++********************
+*************++++++++++++++++++++++...... .....++++++++*******************
+************+++++++++++++++++++++....... .......+++++++******************
+***********+++++++++++++++++++.... ... .+++++++*****************
+**********+++++++++++++++++....... .+++++++****************
+*********++++++++++++++........... ...+++++++***************
+********++++++++++++............ ...++++++++**************
+********++++++++++... .......... .++++++++**************
+*******+++++++++..... .+++++++++*************
+*******++++++++...... ..+++++++++*************
+*******++++++....... ..+++++++++*************
+*******+++++...... ..+++++++++*************
+*******.... .... ...+++++++++*************
+*******.... . ...+++++++++*************
+*******+++++...... ...+++++++++*************
+*******++++++....... ..+++++++++*************
+*******++++++++...... .+++++++++*************
+*******+++++++++..... ..+++++++++*************
+********++++++++++... .......... .++++++++**************
+********++++++++++++............ ...++++++++**************
+*********++++++++++++++.......... ...+++++++***************
+**********++++++++++++++++........ .+++++++****************
+**********++++++++++++++++++++.... ... ..+++++++****************
+***********++++++++++++++++++++++....... .......++++++++*****************
+************+++++++++++++++++++++++...... ......++++++++******************
+**************+++++++++++++++++++++++.... ....++++++++********************
+***************+++++++++++++++++++++++..... ...+++++++++*********************
+*****************++++++++++++++++++++++.... ...++++++++***********************
+*******************+++++++++++++++++++++......++++++++*************************
+*********************++++++++++++++++++++++.++++++++***************************
+*************************+++++++++++++++++++++++*******************************
+******************************+++++++++++++************************************
+*******************************************************************************
+*******************************************************************************
+*******************************************************************************
+Evaluated to 0.000000
+ready&gt; <b>mandel(-2, -1, 0.02, 0.04);</b>
+**************************+++++++++++++++++++++++++++++++++++++++++++++++++++++
+***********************++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+*********************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
+*******************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++...
+*****************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.....
+***************++++++++++++++++++++++++++++++++++++++++++++++++++++++++........
+**************++++++++++++++++++++++++++++++++++++++++++++++++++++++...........
+************+++++++++++++++++++++++++++++++++++++++++++++++++++++..............
+***********++++++++++++++++++++++++++++++++++++++++++++++++++........ .
+**********++++++++++++++++++++++++++++++++++++++++++++++.............
+********+++++++++++++++++++++++++++++++++++++++++++..................
+*******+++++++++++++++++++++++++++++++++++++++.......................
+******+++++++++++++++++++++++++++++++++++...........................
+*****++++++++++++++++++++++++++++++++............................
+*****++++++++++++++++++++++++++++...............................
+****++++++++++++++++++++++++++...... .........................
+***++++++++++++++++++++++++......... ...... ...........
+***++++++++++++++++++++++............
+**+++++++++++++++++++++..............
+**+++++++++++++++++++................
+*++++++++++++++++++.................
+*++++++++++++++++............ ...
+*++++++++++++++..............
+*+++....++++................
+*.......... ...........
+*
+*.......... ...........
+*+++....++++................
+*++++++++++++++..............
+*++++++++++++++++............ ...
+*++++++++++++++++++.................
+**+++++++++++++++++++................
+**+++++++++++++++++++++..............
+***++++++++++++++++++++++............
+***++++++++++++++++++++++++......... ...... ...........
+****++++++++++++++++++++++++++...... .........................
+*****++++++++++++++++++++++++++++...............................
+*****++++++++++++++++++++++++++++++++............................
+******+++++++++++++++++++++++++++++++++++...........................
+*******+++++++++++++++++++++++++++++++++++++++.......................
+********+++++++++++++++++++++++++++++++++++++++++++..................
+Evaluated to 0.000000
+ready&gt; <b>mandel(-0.9, -1.4, 0.02, 0.03);</b>
+*******************************************************************************
+*******************************************************************************
+*******************************************************************************
+**********+++++++++++++++++++++************************************************
+*+++++++++++++++++++++++++++++++++++++++***************************************
++++++++++++++++++++++++++++++++++++++++++++++**********************************
+++++++++++++++++++++++++++++++++++++++++++++++++++*****************************
+++++++++++++++++++++++++++++++++++++++++++++++++++++++*************************
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++**********************
++++++++++++++++++++++++++++++++++.........++++++++++++++++++*******************
++++++++++++++++++++++++++++++++.... ......+++++++++++++++++++****************
++++++++++++++++++++++++++++++....... ........+++++++++++++++++++**************
+++++++++++++++++++++++++++++........ ........++++++++++++++++++++************
++++++++++++++++++++++++++++......... .. ...+++++++++++++++++++++**********
+++++++++++++++++++++++++++........... ....++++++++++++++++++++++********
+++++++++++++++++++++++++............. .......++++++++++++++++++++++******
++++++++++++++++++++++++............. ........+++++++++++++++++++++++****
+++++++++++++++++++++++........... ..........++++++++++++++++++++++***
+++++++++++++++++++++........... .........++++++++++++++++++++++*
+++++++++++++++++++............ ...........++++++++++++++++++++
+++++++++++++++++............... .............++++++++++++++++++
+++++++++++++++................. ...............++++++++++++++++
+++++++++++++.................. .................++++++++++++++
++++++++++.................. .................+++++++++++++
+++++++........ . ......... ..++++++++++++
+++............ ...... ....++++++++++
+.............. ...++++++++++
+.............. ....+++++++++
+.............. .....++++++++
+............. ......++++++++
+........... .......++++++++
+......... ........+++++++
+......... ........+++++++
+......... ....+++++++
+........ ...+++++++
+....... ...+++++++
+ ....+++++++
+ .....+++++++
+ ....+++++++
+ ....+++++++
+ ....+++++++
+Evaluated to 0.000000
+ready&gt; <b>^D</b>
+</pre>
+</div>
+
+<p>At this point, you may be starting to realize that Kaleidoscope is a real
+and powerful language. It may not be self-similar :), but it can be used to
+plot things that are!</p>
+
+<p>With this, we conclude the "adding user-defined operators" chapter of the
+tutorial. We have successfully augmented our language, adding the ability to
+extend the language in the library, and we have shown how this can be used to
+build a simple but interesting end-user application in Kaleidoscope. At this
+point, Kaleidoscope can build a variety of applications that are functional and
+can call functions with side-effects, but it can't actually define and mutate a
+variable itself.</p>
+
+<p>Strikingly, variable mutation is an important feature of some
+languages, and it is not at all obvious how to <a href="OCamlLangImpl7.html">add
+support for mutable variables</a> without having to add an "SSA construction"
+phase to your front-end. In the next chapter, we will describe how you can
+add variable mutation without building SSA in your front-end.</p>
+
+</div>
+
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with the
+if/then/else and for expressions.. To build this example, use:
+</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+ocamlbuild toy.byte
+# Run
+./toy.byte
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<dl>
+<dt>_tags:</dt>
+<dd class="doc_code">
+<pre>
+&lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
+&lt;*.{byte,native}&gt;: g++, use_llvm, use_llvm_analysis
+&lt;*.{byte,native}&gt;: use_llvm_executionengine, use_llvm_target
+&lt;*.{byte,native}&gt;: use_llvm_scalar_opts, use_bindings
+</pre>
+</dd>
+
+<dt>myocamlbuild.ml:</dt>
+<dd class="doc_code">
+<pre>
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+ocaml_lib ~extern:true "llvm_executionengine";;
+ocaml_lib ~extern:true "llvm_target";;
+ocaml_lib ~extern:true "llvm_scalar_opts";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"; A"-cclib"; A"-rdynamic"]);;
+dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
+</pre>
+</dd>
+
+<dt>token.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+
+ (* control *)
+ | If | Then | Else
+ | For | In
+
+ (* operators *)
+ | Binary | Unary
+</pre>
+</dd>
+
+<dt>lexer.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [&lt; ' ('#'); stream &gt;] -&gt;
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [&lt; 'c; stream &gt;] -&gt;
+ [&lt; 'Token.Kwd c; lex stream &gt;]
+
+ (* end of stream. *)
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+
+and lex_number buffer = parser
+ | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
+
+and lex_ident buffer = parser
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | "if" -&gt; [&lt; 'Token.If; stream &gt;]
+ | "then" -&gt; [&lt; 'Token.Then; stream &gt;]
+ | "else" -&gt; [&lt; 'Token.Else; stream &gt;]
+ | "for" -&gt; [&lt; 'Token.For; stream &gt;]
+ | "in" -&gt; [&lt; 'Token.In; stream &gt;]
+ | "binary" -&gt; [&lt; 'Token.Binary; stream &gt;]
+ | "unary" -&gt; [&lt; 'Token.Unary; stream &gt;]
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+
+and lex_comment = parser
+ | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
+ | [&lt; 'c; e=lex_comment &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+</pre>
+</dd>
+
+<dt>ast.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a unary operator. *)
+ | Unary of char * expr
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+ (* variant for if/then/else. *)
+ | If of expr * expr * expr
+
+ (* variant for for/in. *)
+ | For of string * expr * expr * expr option * expr
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto =
+ | Prototype of string * string array
+ | BinOpPrototype of string * string array * int
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
+</pre>
+</dd>
+
+<dt>parser.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr
+ * ::= ifexpr
+ * ::= forexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [&lt; 'Token.Ident id; stream &gt;] -&gt;
+ let rec parse_args accumulator = parser
+ | [&lt; e=parse_expr; stream &gt;] -&gt;
+ begin parser
+ | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; e :: accumulator
+ end stream
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [&lt; 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [&lt; &gt;] -&gt; Ast.Variable id
+ in
+ parse_ident id stream
+
+ (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
+ | [&lt; 'Token.If; c=parse_expr;
+ 'Token.Then ?? "expected 'then'"; t=parse_expr;
+ 'Token.Else ?? "expected 'else'"; e=parse_expr &gt;] -&gt;
+ Ast.If (c, t, e)
+
+ (* forexpr
+ ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
+ | [&lt; 'Token.For;
+ 'Token.Ident id ?? "expected identifier after for";
+ 'Token.Kwd '=' ?? "expected '=' after for";
+ stream &gt;] -&gt;
+ begin parser
+ | [&lt;
+ start=parse_expr;
+ 'Token.Kwd ',' ?? "expected ',' after for";
+ end_=parse_expr;
+ stream &gt;] -&gt;
+ let step =
+ begin parser
+ | [&lt; 'Token.Kwd ','; step=parse_expr &gt;] -&gt; Some step
+ | [&lt; &gt;] -&gt; None
+ end stream
+ in
+ begin parser
+ | [&lt; 'Token.In; body=parse_expr &gt;] -&gt;
+ Ast.For (id, start, end_, step, body)
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected 'in' after for")
+ end stream
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected '=' after for")
+ end stream
+
+ | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
+
+(* unary
+ * ::= primary
+ * ::= '!' unary *)
+and parse_unary = parser
+ (* If this is a unary operator, read it. *)
+ | [&lt; 'Token.Kwd op when op != '(' &amp;&amp; op != ')'; operand=parse_expr &gt;] -&gt;
+ Ast.Unary (op, operand)
+
+ (* If the current token is not an operator, it must be a primary expr. *)
+ | [&lt; stream &gt;] -&gt; parse_primary stream
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec &lt; expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the unary expression after the binary operator. *)
+ let rhs = parse_unary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) -&gt;
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec &lt; next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -&gt; rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -&gt; lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [&lt; lhs=parse_unary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')'
+ * ::= binary LETTER number? (id, id)
+ * ::= unary LETTER number? (id) *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let parse_operator = parser
+ | [&lt; 'Token.Unary &gt;] -&gt; "unary", 1
+ | [&lt; 'Token.Binary &gt;] -&gt; "binary", 2
+ in
+ let parse_binary_precedence = parser
+ | [&lt; 'Token.Number n &gt;] -&gt; int_of_float n
+ | [&lt; &gt;] -&gt; 30
+ in
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+ | [&lt; (prefix, kind)=parse_operator;
+ 'Token.Kwd op ?? "expected an operator";
+ (* Read the precedence if present. *)
+ binary_precedence=parse_binary_precedence;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ let name = prefix ^ (String.make 1 op) in
+ let args = Array.of_list (List.rev args) in
+
+ (* Verify right number of arguments for operator. *)
+ if Array.length args != kind
+ then raise (Stream.Error "invalid number of operands for operator")
+ else
+ if kind == 1 then
+ Ast.Prototype (name, args)
+ else
+ Ast.BinOpPrototype (name, args, binary_precedence)
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [&lt; e=parse_expr &gt;] -&gt;
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
+</pre>
+</dd>
+
+<dt>codegen.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+let rec codegen_expr = function
+ | Ast.Number n -&gt; const_float double_type n
+ | Ast.Variable name -&gt;
+ (try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name"))
+ | Ast.Unary (op, operand) -&gt;
+ let operand = codegen_expr operand in
+ let callee = "unary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown unary operator")
+ in
+ build_call callee [|operand|] "unop" builder
+ | Ast.Binary (op, lhs, rhs) -&gt;
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -&gt; build_add lhs_val rhs_val "addtmp" builder
+ | '-' -&gt; build_sub lhs_val rhs_val "subtmp" builder
+ | '*' -&gt; build_mul lhs_val rhs_val "multmp" builder
+ | '&lt;' -&gt;
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -&gt;
+ (* If it wasn't a builtin binary operator, it must be a user defined
+ * one. Emit a call to it. *)
+ let callee = "binary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "binary operator not found!")
+ in
+ build_call callee [|lhs_val; rhs_val|] "binop" builder
+ end
+ | Ast.Call (callee, args) -&gt;
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+ | Ast.If (cond, then_, else_) -&gt;
+ let cond = codegen_expr cond in
+
+ (* Convert condition to a bool by comparing equal to 0.0 *)
+ let zero = const_float double_type 0.0 in
+ let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
+
+ (* Grab the first block so that we might later add the conditional branch
+ * to it at the end of the function. *)
+ let start_bb = insertion_block builder in
+ let the_function = block_parent start_bb in
+
+ let then_bb = append_block context "then" the_function in
+
+ (* Emit 'then' value. *)
+ position_at_end then_bb builder;
+ let then_val = codegen_expr then_ in
+
+ (* Codegen of 'then' can change the current block, update then_bb for the
+ * phi. We create a new name because one is used for the phi node, and the
+ * other is used for the conditional branch. *)
+ let new_then_bb = insertion_block builder in
+
+ (* Emit 'else' value. *)
+ let else_bb = append_block context "else" the_function in
+ position_at_end else_bb builder;
+ let else_val = codegen_expr else_ in
+
+ (* Codegen of 'else' can change the current block, update else_bb for the
+ * phi. *)
+ let new_else_bb = insertion_block builder in
+
+ (* Emit merge block. *)
+ let merge_bb = append_block context "ifcont" the_function in
+ position_at_end merge_bb builder;
+ let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
+ let phi = build_phi incoming "iftmp" builder in
+
+ (* Return to the start block to add the conditional branch. *)
+ position_at_end start_bb builder;
+ ignore (build_cond_br cond_val then_bb else_bb builder);
+
+ (* Set a unconditional branch at the end of the 'then' block and the
+ * 'else' block to the 'merge' block. *)
+ position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
+ position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
+
+ (* Finally, set the builder to the end of the merge block. *)
+ position_at_end merge_bb builder;
+
+ phi
+ | Ast.For (var_name, start, end_, step, body) -&gt;
+ (* Emit the start code first, without 'variable' in scope. *)
+ let start_val = codegen_expr start in
+
+ (* Make the new basic block for the loop header, inserting after current
+ * block. *)
+ let preheader_bb = insertion_block builder in
+ let the_function = block_parent preheader_bb in
+ let loop_bb = append_block context "loop" the_function in
+
+ (* Insert an explicit fall through from the current block to the
+ * loop_bb. *)
+ ignore (build_br loop_bb builder);
+
+ (* Start insertion in loop_bb. *)
+ position_at_end loop_bb builder;
+
+ (* Start the PHI node with an entry for start. *)
+ let variable = build_phi [(start_val, preheader_bb)] var_name builder in
+
+ (* Within the loop, the variable is defined equal to the PHI node. If it
+ * shadows an existing variable, we have to restore it, so save it
+ * now. *)
+ let old_val =
+ try Some (Hashtbl.find named_values var_name) with Not_found -&gt; None
+ in
+ Hashtbl.add named_values var_name variable;
+
+ (* Emit the body of the loop. This, like any other expr, can change the
+ * current BB. Note that we ignore the value computed by the body, but
+ * don't allow an error *)
+ ignore (codegen_expr body);
+
+ (* Emit the step value. *)
+ let step_val =
+ match step with
+ | Some step -&gt; codegen_expr step
+ (* If not specified, use 1.0. *)
+ | None -&gt; const_float double_type 1.0
+ in
+
+ let next_var = build_add variable step_val "nextvar" builder in
+
+ (* Compute the end condition. *)
+ let end_cond = codegen_expr end_ in
+
+ (* Convert condition to a bool by comparing equal to 0.0. *)
+ let zero = const_float double_type 0.0 in
+ let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
+
+ (* Create the "after loop" block and insert it. *)
+ let loop_end_bb = insertion_block builder in
+ let after_bb = append_block context "afterloop" the_function in
+
+ (* Insert the conditional branch into the end of loop_end_bb. *)
+ ignore (build_cond_br end_cond loop_bb after_bb builder);
+
+ (* Any new code will be inserted in after_bb. *)
+ position_at_end after_bb builder;
+
+ (* Add a new entry to the PHI node for the backedge. *)
+ add_incoming (next_var, loop_end_bb) variable;
+
+ (* Restore the unshadowed variable. *)
+ begin match old_val with
+ | Some old_val -&gt; Hashtbl.add named_values var_name old_val
+ | None -&gt; ()
+ end;
+
+ (* for expr always returns 0.0. *)
+ const_null double_type
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) | Ast.BinOpPrototype (name, args, _) -&gt;
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -&gt; declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f -&gt;
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f &lt;&gt; At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) &lt;&gt; ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a -&gt;
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) -&gt;
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* If this is an operator, install it. *)
+ begin match proto with
+ | Ast.BinOpPrototype (name, args, prec) -&gt;
+ let op = name.[String.length name - 1] in
+ Hashtbl.add Parser.binop_precedence op prec;
+ | _ -&gt; ()
+ end;
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+ with e -&gt;
+ delete_function the_function;
+ raise e
+</pre>
+</dd>
+
+<dt>toplevel.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop the_fpm the_execution_engine stream =
+ match Stream.peek stream with
+ | None -&gt; ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') -&gt;
+ Stream.junk stream;
+ main_loop the_fpm the_execution_engine stream
+
+ | Some token -&gt;
+ begin
+ try match token with
+ | Token.Def -&gt;
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func the_fpm e);
+ | Token.Extern -&gt;
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ -&gt;
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+ with Stream.Error s | Codegen.Error s -&gt;
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready&gt; "; flush stdout;
+ main_loop the_fpm the_execution_engine stream
+</pre>
+</dd>
+
+<dt>toy.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+open Llvm_target
+open Llvm_scalar_opts
+
+let main () =
+ ignore (initialize_native_target ());
+
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '&lt;' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready&gt; "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combination the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
+</pre>
+</dd>
+
+<dt>bindings.c</dt>
+<dd class="doc_code">
+<pre>
+#include &lt;stdio.h&gt;
+
+/* putchard - putchar that takes a double and returns 0. */
+extern double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+/* printd - printf that takes a double prints it as "%f\n", returning 0. */
+extern double printd(double X) {
+ printf("%f\n", X);
+ return 0;
+}
+</pre>
+</dd>
+</dl>
+
+<a href="OCamlLangImpl7.html">Next: Extending the language: mutable variables /
+SSA construction</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/OCamlLangImpl7.html b/docs/tutorial/OCamlLangImpl7.html
new file mode 100644
index 00000000000..d106ad0701c
--- /dev/null
+++ b/docs/tutorial/OCamlLangImpl7.html
@@ -0,0 +1,1904 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Extending the Language: Mutable Variables / SSA
+ construction</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <meta name="author" content="Erick Tryzelaar">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Extending the Language: Mutable Variables</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 7
+ <ol>
+ <li><a href="#intro">Chapter 7 Introduction</a></li>
+ <li><a href="#why">Why is this a hard problem?</a></li>
+ <li><a href="#memory">Memory in LLVM</a></li>
+ <li><a href="#kalvars">Mutable Variables in Kaleidoscope</a></li>
+ <li><a href="#adjustments">Adjusting Existing Variables for
+ Mutation</a></li>
+ <li><a href="#assignment">New Assignment Operator</a></li>
+ <li><a href="#localvars">User-defined Local Variables</a></li>
+ <li><a href="#code">Full Code Listing</a></li>
+ </ol>
+</li>
+<li><a href="OCamlLangImpl8.html">Chapter 8</a>: Conclusion and other useful LLVM
+ tidbits</li>
+</ul>
+
+<div class="doc_author">
+ <p>
+ Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
+ and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
+ </p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="intro">Chapter 7 Introduction</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to Chapter 7 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial. In chapters 1 through 6, we've built a very
+respectable, albeit simple, <a
+href="http://en.wikipedia.org/wiki/Functional_programming">functional
+programming language</a>. In our journey, we learned some parsing techniques,
+how to build and represent an AST, how to build LLVM IR, and how to optimize
+the resultant code as well as JIT compile it.</p>
+
+<p>While Kaleidoscope is interesting as a functional language, the fact that it
+is functional makes it "too easy" to generate LLVM IR for it. In particular, a
+functional language makes it very easy to build LLVM IR directly in <a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">SSA form</a>.
+Since LLVM requires that the input code be in SSA form, this is a very nice
+property and it is often unclear to newcomers how to generate code for an
+imperative language with mutable variables.</p>
+
+<p>The short (and happy) summary of this chapter is that there is no need for
+your front-end to build SSA form: LLVM provides highly tuned and well tested
+support for this, though the way it works is a bit unexpected for some.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="why">Why is this a hard problem?</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+To understand why mutable variables cause complexities in SSA construction,
+consider this extremely simple C example:
+</p>
+
+<div class="doc_code">
+<pre>
+int G, H;
+int test(_Bool Condition) {
+ int X;
+ if (Condition)
+ X = G;
+ else
+ X = H;
+ return X;
+}
+</pre>
+</div>
+
+<p>In this case, we have the variable "X", whose value depends on the path
+executed in the program. Because there are two different possible values for X
+before the return instruction, a PHI node is inserted to merge the two values.
+The LLVM IR that we want for this example looks like this:</p>
+
+<div class="doc_code">
+<pre>
+@G = weak global i32 0 ; type of @G is i32*
+@H = weak global i32 0 ; type of @H is i32*
+
+define i32 @test(i1 %Condition) {
+entry:
+ br i1 %Condition, label %cond_true, label %cond_false
+
+cond_true:
+ %X.0 = load i32* @G
+ br label %cond_next
+
+cond_false:
+ %X.1 = load i32* @H
+ br label %cond_next
+
+cond_next:
+ %X.2 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
+ ret i32 %X.2
+}
+</pre>
+</div>
+
+<p>In this example, the loads from the G and H global variables are explicit in
+the LLVM IR, and they live in the then/else branches of the if statement
+(cond_true/cond_false). In order to merge the incoming values, the X.2 phi node
+in the cond_next block selects the right value to use based on where control
+flow is coming from: if control flow comes from the cond_false block, X.2 gets
+the value of X.1. Alternatively, if control flow comes from cond_true, it gets
+the value of X.0. The intent of this chapter is not to explain the details of
+SSA form. For more information, see one of the many <a
+href="http://en.wikipedia.org/wiki/Static_single_assignment_form">online
+references</a>.</p>
+
+<p>The question for this article is "who places the phi nodes when lowering
+assignments to mutable variables?". The issue here is that LLVM
+<em>requires</em> that its IR be in SSA form: there is no "non-ssa" mode for it.
+However, SSA construction requires non-trivial algorithms and data structures,
+so it is inconvenient and wasteful for every front-end to have to reproduce this
+logic.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="memory">Memory in LLVM</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>The 'trick' here is that while LLVM does require all register values to be
+in SSA form, it does not require (or permit) memory objects to be in SSA form.
+In the example above, note that the loads from G and H are direct accesses to
+G and H: they are not renamed or versioned. This differs from some other
+compiler systems, which do try to version memory objects. In LLVM, instead of
+encoding dataflow analysis of memory into the LLVM IR, it is handled with <a
+href="../WritingAnLLVMPass.html">Analysis Passes</a> which are computed on
+demand.</p>
+
+<p>
+With this in mind, the high-level idea is that we want to make a stack variable
+(which lives in memory, because it is on the stack) for each mutable object in
+a function. To take advantage of this trick, we need to talk about how LLVM
+represents stack variables.
+</p>
+
+<p>In LLVM, all memory accesses are explicit with load/store instructions, and
+it is carefully designed not to have (or need) an "address-of" operator. Notice
+how the type of the @G/@H global variables is actually "i32*" even though the
+variable is defined as "i32". What this means is that @G defines <em>space</em>
+for an i32 in the global data area, but its <em>name</em> actually refers to the
+address for that space. Stack variables work the same way, except that instead of
+being declared with global variable definitions, they are declared with the
+<a href="../LangRef.html#i_alloca">LLVM alloca instruction</a>:</p>
+
+<div class="doc_code">
+<pre>
+define i32 @example() {
+entry:
+ %X = alloca i32 ; type of %X is i32*.
+ ...
+ %tmp = load i32* %X ; load the stack value %X from the stack.
+ %tmp2 = add i32 %tmp, 1 ; increment it
+ store i32 %tmp2, i32* %X ; store it back
+ ...
+</pre>
+</div>
+
+<p>This code shows an example of how you can declare and manipulate a stack
+variable in the LLVM IR. Stack memory allocated with the alloca instruction is
+fully general: you can pass the address of the stack slot to functions, you can
+store it in other variables, etc. In our example above, we could rewrite the
+example to use the alloca technique to avoid using a PHI node:</p>
+
+<div class="doc_code">
+<pre>
+@G = weak global i32 0 ; type of @G is i32*
+@H = weak global i32 0 ; type of @H is i32*
+
+define i32 @test(i1 %Condition) {
+entry:
+ %X = alloca i32 ; type of %X is i32*.
+ br i1 %Condition, label %cond_true, label %cond_false
+
+cond_true:
+ %X.0 = load i32* @G
+ store i32 %X.0, i32* %X ; Update X
+ br label %cond_next
+
+cond_false:
+ %X.1 = load i32* @H
+ store i32 %X.1, i32* %X ; Update X
+ br label %cond_next
+
+cond_next:
+ %X.2 = load i32* %X ; Read X
+ ret i32 %X.2
+}
+</pre>
+</div>
+
+<p>With this, we have discovered a way to handle arbitrary mutable variables
+without the need to create Phi nodes at all:</p>
+
+<ol>
+<li>Each mutable variable becomes a stack allocation.</li>
+<li>Each read of the variable becomes a load from the stack.</li>
+<li>Each update of the variable becomes a store to the stack.</li>
+<li>Taking the address of a variable just uses the stack address directly.</li>
+</ol>
+
+<p>While this solution has solved our immediate problem, it introduced another
+one: we have now apparently introduced a lot of stack traffic for very simple
+and common operations, a major performance problem. Fortunately for us, the
+LLVM optimizer has a highly-tuned optimization pass named "mem2reg" that handles
+this case, promoting allocas like this into SSA registers, inserting Phi nodes
+as appropriate. If you run this example through the pass, for example, you'll
+get:</p>
+
+<div class="doc_code">
+<pre>
+$ <b>llvm-as &lt; example.ll | opt -mem2reg | llvm-dis</b>
+@G = weak global i32 0
+@H = weak global i32 0
+
+define i32 @test(i1 %Condition) {
+entry:
+ br i1 %Condition, label %cond_true, label %cond_false
+
+cond_true:
+ %X.0 = load i32* @G
+ br label %cond_next
+
+cond_false:
+ %X.1 = load i32* @H
+ br label %cond_next
+
+cond_next:
+ %X.01 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
+ ret i32 %X.01
+}
+</pre>
+</div>
+
+<p>The mem2reg pass implements the standard "iterated dominance frontier"
+algorithm for constructing SSA form and has a number of optimizations that speed
+up (very common) degenerate cases. The mem2reg optimization pass is the answer
+to dealing with mutable variables, and we highly recommend that you depend on
+it. Note that mem2reg only works on variables in certain circumstances:</p>
+
+<ol>
+<li>mem2reg is alloca-driven: it looks for allocas and if it can handle them, it
+promotes them. It does not apply to global variables or heap allocations.</li>
+
+<li>mem2reg only looks for alloca instructions in the entry block of the
+function. Being in the entry block guarantees that the alloca is only executed
+once, which makes analysis simpler.</li>
+
+<li>mem2reg only promotes allocas whose uses are direct loads and stores. If
+the address of the stack object is passed to a function, or if any funny pointer
+arithmetic is involved, the alloca will not be promoted.</li>
+
+<li>mem2reg only works on allocas of <a
+href="../LangRef.html#t_classifications">first class</a>
+values (such as pointers, scalars and vectors), and only if the array size
+of the allocation is 1 (or missing in the .ll file). mem2reg is not capable of
+promoting structs or arrays to registers. Note that the "scalarrepl" pass is
+more powerful and can promote structs, "unions", and arrays in many cases.</li>
+
+</ol>
+
+<p>
+All of these properties are easy to satisfy for most imperative languages, and
+we'll illustrate it below with Kaleidoscope. The final question you may be
+asking is: should I bother with this nonsense for my front-end? Wouldn't it be
+better if I just did SSA construction directly, avoiding use of the mem2reg
+optimization pass? In short, we strongly recommend that you use this technique
+for building SSA form, unless there is an extremely good reason not to. Using
+this technique is:</p>
+
+<ul>
+<li>Proven and well tested: llvm-gcc and clang both use this technique for local
+mutable variables. As such, the most common clients of LLVM are using this to
+handle a bulk of their variables. You can be sure that bugs are found fast and
+fixed early.</li>
+
+<li>Extremely Fast: mem2reg has a number of special cases that make it fast in
+common cases as well as fully general. For example, it has fast-paths for
+variables that are only used in a single block, variables that only have one
+assignment point, good heuristics to avoid insertion of unneeded phi nodes, etc.
+</li>
+
+<li>Needed for debug info generation: <a href="../SourceLevelDebugging.html">
+Debug information in LLVM</a> relies on having the address of the variable
+exposed so that debug info can be attached to it. This technique dovetails
+very naturally with this style of debug info.</li>
+</ul>
+
+<p>If nothing else, this makes it much easier to get your front-end up and
+running, and is very simple to implement. Lets extend Kaleidoscope with mutable
+variables now!
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="kalvars">Mutable Variables in Kaleidoscope</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Now that we know the sort of problem we want to tackle, lets see what this
+looks like in the context of our little Kaleidoscope language. We're going to
+add two features:</p>
+
+<ol>
+<li>The ability to mutate variables with the '=' operator.</li>
+<li>The ability to define new variables.</li>
+</ol>
+
+<p>While the first item is really what this is about, we only have variables
+for incoming arguments as well as for induction variables, and redefining those only
+goes so far :). Also, the ability to define new variables is a
+useful thing regardless of whether you will be mutating them. Here's a
+motivating example that shows how we could use these:</p>
+
+<div class="doc_code">
+<pre>
+# Define ':' for sequencing: as a low-precedence operator that ignores operands
+# and just returns the RHS.
+def binary : 1 (x y) y;
+
+# Recursive fib, we could do this before.
+def fib(x)
+ if (x &lt; 3) then
+ 1
+ else
+ fib(x-1)+fib(x-2);
+
+# Iterative fib.
+def fibi(x)
+ <b>var a = 1, b = 1, c in</b>
+ (for i = 3, i &lt; x in
+ <b>c = a + b</b> :
+ <b>a = b</b> :
+ <b>b = c</b>) :
+ b;
+
+# Call it.
+fibi(10);
+</pre>
+</div>
+
+<p>
+In order to mutate variables, we have to change our existing variables to use
+the "alloca trick". Once we have that, we'll add our new operator, then extend
+Kaleidoscope to support new variable definitions.
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="adjustments">Adjusting Existing Variables for Mutation</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+The symbol table in Kaleidoscope is managed at code generation time by the
+'<tt>named_values</tt>' map. This map currently keeps track of the LLVM
+"Value*" that holds the double value for the named variable. In order to
+support mutation, we need to change this slightly, so that it
+<tt>named_values</tt> holds the <em>memory location</em> of the variable in
+question. Note that this change is a refactoring: it changes the structure of
+the code, but does not (by itself) change the behavior of the compiler. All of
+these changes are isolated in the Kaleidoscope code generator.</p>
+
+<p>
+At this point in Kaleidoscope's development, it only supports variables for two
+things: incoming arguments to functions and the induction variable of 'for'
+loops. For consistency, we'll allow mutation of these variables in addition to
+other user-defined variables. This means that these will both need memory
+locations.
+</p>
+
+<p>To start our transformation of Kaleidoscope, we'll change the
+<tt>named_values</tt> map so that it maps to AllocaInst* instead of Value*.
+Once we do this, the C++ compiler will tell us what parts of the code we need to
+update:</p>
+
+<p><b>Note:</b> the ocaml bindings currently model both <tt>Value*</tt>s and
+<tt>AllocInst*</tt>s as <tt>Llvm.llvalue</tt>s, but this may change in the
+future to be more type safe.</p>
+
+<div class="doc_code">
+<pre>
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+</pre>
+</div>
+
+<p>Also, since we will need to create these alloca's, we'll use a helper
+function that ensures that the allocas are created in the entry block of the
+function:</p>
+
+<div class="doc_code">
+<pre>
+(* Create an alloca instruction in the entry block of the function. This
+ * is used for mutable variables etc. *)
+let create_entry_block_alloca the_function var_name =
+ let builder = builder_at (instr_begin (entry_block the_function)) in
+ build_alloca double_type var_name builder
+</pre>
+</div>
+
+<p>This funny looking code creates an <tt>Llvm.llbuilder</tt> object that is
+pointing at the first instruction of the entry block. It then creates an alloca
+with the expected name and returns it. Because all values in Kaleidoscope are
+doubles, there is no need to pass in a type to use.</p>
+
+<p>With this in place, the first functionality change we want to make is to
+variable references. In our new scheme, variables live on the stack, so code
+generating a reference to them actually needs to produce a load from the stack
+slot:</p>
+
+<div class="doc_code">
+<pre>
+let rec codegen_expr = function
+ ...
+ | Ast.Variable name -&gt;
+ let v = try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name")
+ in
+ <b>(* Load the value. *)
+ build_load v name builder</b>
+</pre>
+</div>
+
+<p>As you can see, this is pretty straightforward. Now we need to update the
+things that define the variables to set up the alloca. We'll start with
+<tt>codegen_expr Ast.For ...</tt> (see the <a href="#code">full code listing</a>
+for the unabridged code):</p>
+
+<div class="doc_code">
+<pre>
+ | Ast.For (var_name, start, end_, step, body) -&gt;
+ let the_function = block_parent (insertion_block builder) in
+
+ (* Create an alloca for the variable in the entry block. *)
+ <b>let alloca = create_entry_block_alloca the_function var_name in</b>
+
+ (* Emit the start code first, without 'variable' in scope. *)
+ let start_val = codegen_expr start in
+
+ <b>(* Store the value into the alloca. *)
+ ignore(build_store start_val alloca builder);</b>
+
+ ...
+
+ (* Within the loop, the variable is defined equal to the PHI node. If it
+ * shadows an existing variable, we have to restore it, so save it
+ * now. *)
+ let old_val =
+ try Some (Hashtbl.find named_values var_name) with Not_found -&gt; None
+ in
+ <b>Hashtbl.add named_values var_name alloca;</b>
+
+ ...
+
+ (* Compute the end condition. *)
+ let end_cond = codegen_expr end_ in
+
+ <b>(* Reload, increment, and restore the alloca. This handles the case where
+ * the body of the loop mutates the variable. *)
+ let cur_var = build_load alloca var_name builder in
+ let next_var = build_add cur_var step_val "nextvar" builder in
+ ignore(build_store next_var alloca builder);</b>
+ ...
+</pre>
+</div>
+
+<p>This code is virtually identical to the code <a
+href="OCamlLangImpl5.html#forcodegen">before we allowed mutable variables</a>.
+The big difference is that we no longer have to construct a PHI node, and we use
+load/store to access the variable as needed.</p>
+
+<p>To support mutable argument variables, we need to also make allocas for them.
+The code for this is also pretty simple:</p>
+
+<div class="doc_code">
+<pre>
+(* Create an alloca for each argument and register the argument in the symbol
+ * table so that references to it will succeed. *)
+let create_argument_allocas the_function proto =
+ let args = match proto with
+ | Ast.Prototype (_, args) | Ast.BinOpPrototype (_, args, _) -&gt; args
+ in
+ Array.iteri (fun i ai -&gt;
+ let var_name = args.(i) in
+ (* Create an alloca for this variable. *)
+ let alloca = create_entry_block_alloca the_function var_name in
+
+ (* Store the initial value into the alloca. *)
+ ignore(build_store ai alloca builder);
+
+ (* Add arguments to variable symbol table. *)
+ Hashtbl.add named_values var_name alloca;
+ ) (params the_function)
+</pre>
+</div>
+
+<p>For each argument, we make an alloca, store the input value to the function
+into the alloca, and register the alloca as the memory location for the
+argument. This method gets invoked by <tt>Codegen.codegen_func</tt> right after
+it sets up the entry block for the function.</p>
+
+<p>The final missing piece is adding the mem2reg pass, which allows us to get
+good codegen once again:</p>
+
+<div class="doc_code">
+<pre>
+let main () =
+ ...
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ <b>(* Promote allocas to registers. *)
+ add_memory_to_register_promotion the_fpm;</b>
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combining the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+</pre>
+</div>
+
+<p>It is interesting to see what the code looks like before and after the
+mem2reg optimization runs. For example, this is the before/after code for our
+recursive fib function. Before the optimization:</p>
+
+<div class="doc_code">
+<pre>
+define double @fib(double %x) {
+entry:
+ <b>%x1 = alloca double
+ store double %x, double* %x1
+ %x2 = load double* %x1</b>
+ %cmptmp = fcmp ult double %x2, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
+ %ifcond = fcmp one double %booltmp, 0.000000e+00
+ br i1 %ifcond, label %then, label %else
+
+then: ; preds = %entry
+ br label %ifcont
+
+else: ; preds = %entry
+ <b>%x3 = load double* %x1</b>
+ %subtmp = fsub double %x3, 1.000000e+00
+ %calltmp = call double @fib(double %subtmp)
+ <b>%x4 = load double* %x1</b>
+ %subtmp5 = fsub double %x4, 2.000000e+00
+ %calltmp6 = call double @fib(double %subtmp5)
+ %addtmp = fadd double %calltmp, %calltmp6
+ br label %ifcont
+
+ifcont: ; preds = %else, %then
+ %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
+ ret double %iftmp
+}
+</pre>
+</div>
+
+<p>Here there is only one variable (x, the input argument) but you can still
+see the extremely simple-minded code generation strategy we are using. In the
+entry block, an alloca is created, and the initial input value is stored into
+it. Each reference to the variable does a reload from the stack. Also, note
+that we didn't modify the if/then/else expression, so it still inserts a PHI
+node. While we could make an alloca for it, it is actually easier to create a
+PHI node for it, so we still just make the PHI.</p>
+
+<p>Here is the code after the mem2reg pass runs:</p>
+
+<div class="doc_code">
+<pre>
+define double @fib(double %x) {
+entry:
+ %cmptmp = fcmp ult double <b>%x</b>, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
+ %ifcond = fcmp one double %booltmp, 0.000000e+00
+ br i1 %ifcond, label %then, label %else
+
+then:
+ br label %ifcont
+
+else:
+ %subtmp = fsub double <b>%x</b>, 1.000000e+00
+ %calltmp = call double @fib(double %subtmp)
+ %subtmp5 = fsub double <b>%x</b>, 2.000000e+00
+ %calltmp6 = call double @fib(double %subtmp5)
+ %addtmp = fadd double %calltmp, %calltmp6
+ br label %ifcont
+
+ifcont: ; preds = %else, %then
+ %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
+ ret double %iftmp
+}
+</pre>
+</div>
+
+<p>This is a trivial case for mem2reg, since there are no redefinitions of the
+variable. The point of showing this is to calm your tension about inserting
+such blatent inefficiencies :).</p>
+
+<p>After the rest of the optimizers run, we get:</p>
+
+<div class="doc_code">
+<pre>
+define double @fib(double %x) {
+entry:
+ %cmptmp = fcmp ult double %x, 3.000000e+00
+ %booltmp = uitofp i1 %cmptmp to double
+ %ifcond = fcmp ueq double %booltmp, 0.000000e+00
+ br i1 %ifcond, label %else, label %ifcont
+
+else:
+ %subtmp = fsub double %x, 1.000000e+00
+ %calltmp = call double @fib(double %subtmp)
+ %subtmp5 = fsub double %x, 2.000000e+00
+ %calltmp6 = call double @fib(double %subtmp5)
+ %addtmp = fadd double %calltmp, %calltmp6
+ ret double %addtmp
+
+ifcont:
+ ret double 1.000000e+00
+}
+</pre>
+</div>
+
+<p>Here we see that the simplifycfg pass decided to clone the return instruction
+into the end of the 'else' block. This allowed it to eliminate some branches
+and the PHI node.</p>
+
+<p>Now that all symbol table references are updated to use stack variables,
+we'll add the assignment operator.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="assignment">New Assignment Operator</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>With our current framework, adding a new assignment operator is really
+simple. We will parse it just like any other binary operator, but handle it
+internally (instead of allowing the user to define it). The first step is to
+set a precedence:</p>
+
+<div class="doc_code">
+<pre>
+let main () =
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ <b>Hashtbl.add Parser.binop_precedence '=' 2;</b>
+ Hashtbl.add Parser.binop_precedence '&lt;' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ ...
+</pre>
+</div>
+
+<p>Now that the parser knows the precedence of the binary operator, it takes
+care of all the parsing and AST generation. We just need to implement codegen
+for the assignment operator. This looks like:</p>
+
+<div class="doc_code">
+<pre>
+let rec codegen_expr = function
+ begin match op with
+ | '=' -&gt;
+ (* Special case '=' because we don't want to emit the LHS as an
+ * expression. *)
+ let name =
+ match lhs with
+ | Ast.Variable name -&gt; name
+ | _ -&gt; raise (Error "destination of '=' must be a variable")
+ in
+</pre>
+</div>
+
+<p>Unlike the rest of the binary operators, our assignment operator doesn't
+follow the "emit LHS, emit RHS, do computation" model. As such, it is handled
+as a special case before the other binary operators are handled. The other
+strange thing is that it requires the LHS to be a variable. It is invalid to
+have "(x+1) = expr" - only things like "x = expr" are allowed.
+</p>
+
+
+<div class="doc_code">
+<pre>
+ (* Codegen the rhs. *)
+ let val_ = codegen_expr rhs in
+
+ (* Lookup the name. *)
+ let variable = try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name")
+ in
+ ignore(build_store val_ variable builder);
+ val_
+ | _ -&gt;
+ ...
+</pre>
+</div>
+
+<p>Once we have the variable, codegen'ing the assignment is straightforward:
+we emit the RHS of the assignment, create a store, and return the computed
+value. Returning a value allows for chained assignments like "X = (Y = Z)".</p>
+
+<p>Now that we have an assignment operator, we can mutate loop variables and
+arguments. For example, we can now run code like this:</p>
+
+<div class="doc_code">
+<pre>
+# Function to print a double.
+extern printd(x);
+
+# Define ':' for sequencing: as a low-precedence operator that ignores operands
+# and just returns the RHS.
+def binary : 1 (x y) y;
+
+def test(x)
+ printd(x) :
+ x = 4 :
+ printd(x);
+
+test(123);
+</pre>
+</div>
+
+<p>When run, this example prints "123" and then "4", showing that we did
+actually mutate the value! Okay, we have now officially implemented our goal:
+getting this to work requires SSA construction in the general case. However,
+to be really useful, we want the ability to define our own local variables, lets
+add this next!
+</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="localvars">User-defined Local Variables</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Adding var/in is just like any other other extensions we made to
+Kaleidoscope: we extend the lexer, the parser, the AST and the code generator.
+The first step for adding our new 'var/in' construct is to extend the lexer.
+As before, this is pretty trivial, the code looks like this:</p>
+
+<div class="doc_code">
+<pre>
+type token =
+ ...
+ <b>(* var definition *)
+ | Var</b>
+
+...
+
+and lex_ident buffer = parser
+ ...
+ | "in" -&gt; [&lt; 'Token.In; stream &gt;]
+ | "binary" -&gt; [&lt; 'Token.Binary; stream &gt;]
+ | "unary" -&gt; [&lt; 'Token.Unary; stream &gt;]
+ <b>| "var" -&gt; [&lt; 'Token.Var; stream &gt;]</b>
+ ...
+</pre>
+</div>
+
+<p>The next step is to define the AST node that we will construct. For var/in,
+it looks like this:</p>
+
+<div class="doc_code">
+<pre>
+type expr =
+ ...
+ (* variant for var/in. *)
+ | Var of (string * expr option) array * expr
+ ...
+</pre>
+</div>
+
+<p>var/in allows a list of names to be defined all at once, and each name can
+optionally have an initializer value. As such, we capture this information in
+the VarNames vector. Also, var/in has a body, this body is allowed to access
+the variables defined by the var/in.</p>
+
+<p>With this in place, we can define the parser pieces. The first thing we do
+is add it as a primary expression:</p>
+
+<div class="doc_code">
+<pre>
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr
+ * ::= ifexpr
+ * ::= forexpr
+ <b>* ::= varexpr</b> *)
+let rec parse_primary = parser
+ ...
+ <b>(* varexpr
+ * ::= 'var' identifier ('=' expression?
+ * (',' identifier ('=' expression)?)* 'in' expression *)
+ | [&lt; 'Token.Var;
+ (* At least one variable name is required. *)
+ 'Token.Ident id ?? "expected identifier after var";
+ init=parse_var_init;
+ var_names=parse_var_names [(id, init)];
+ (* At this point, we have to have 'in'. *)
+ 'Token.In ?? "expected 'in' keyword after 'var'";
+ body=parse_expr &gt;] -&gt;
+ Ast.Var (Array.of_list (List.rev var_names), body)</b>
+
+...
+
+and parse_var_init = parser
+ (* read in the optional initializer. *)
+ | [&lt; 'Token.Kwd '='; e=parse_expr &gt;] -&gt; Some e
+ | [&lt; &gt;] -&gt; None
+
+and parse_var_names accumulator = parser
+ | [&lt; 'Token.Kwd ',';
+ 'Token.Ident id ?? "expected identifier list after var";
+ init=parse_var_init;
+ e=parse_var_names ((id, init) :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+</pre>
+</div>
+
+<p>Now that we can parse and represent the code, we need to support emission of
+LLVM IR for it. This code starts out with:</p>
+
+<div class="doc_code">
+<pre>
+let rec codegen_expr = function
+ ...
+ | Ast.Var (var_names, body)
+ let old_bindings = ref [] in
+
+ let the_function = block_parent (insertion_block builder) in
+
+ (* Register all variables and emit their initializer. *)
+ Array.iter (fun (var_name, init) -&gt;
+</pre>
+</div>
+
+<p>Basically it loops over all the variables, installing them one at a time.
+For each variable we put into the symbol table, we remember the previous value
+that we replace in OldBindings.</p>
+
+<div class="doc_code">
+<pre>
+ (* Emit the initializer before adding the variable to scope, this
+ * prevents the initializer from referencing the variable itself, and
+ * permits stuff like this:
+ * var a = 1 in
+ * var a = a in ... # refers to outer 'a'. *)
+ let init_val =
+ match init with
+ | Some init -&gt; codegen_expr init
+ (* If not specified, use 0.0. *)
+ | None -&gt; const_float double_type 0.0
+ in
+
+ let alloca = create_entry_block_alloca the_function var_name in
+ ignore(build_store init_val alloca builder);
+
+ (* Remember the old variable binding so that we can restore the binding
+ * when we unrecurse. *)
+
+ begin
+ try
+ let old_value = Hashtbl.find named_values var_name in
+ old_bindings := (var_name, old_value) :: !old_bindings;
+ with Not_found &gt; ()
+ end;
+
+ (* Remember this binding. *)
+ Hashtbl.add named_values var_name alloca;
+ ) var_names;
+</pre>
+</div>
+
+<p>There are more comments here than code. The basic idea is that we emit the
+initializer, create the alloca, then update the symbol table to point to it.
+Once all the variables are installed in the symbol table, we evaluate the body
+of the var/in expression:</p>
+
+<div class="doc_code">
+<pre>
+ (* Codegen the body, now that all vars are in scope. *)
+ let body_val = codegen_expr body in
+</pre>
+</div>
+
+<p>Finally, before returning, we restore the previous variable bindings:</p>
+
+<div class="doc_code">
+<pre>
+ (* Pop all our variables from scope. *)
+ List.iter (fun (var_name, old_value) -&gt;
+ Hashtbl.add named_values var_name old_value
+ ) !old_bindings;
+
+ (* Return the body computation. *)
+ body_val
+</pre>
+</div>
+
+<p>The end result of all of this is that we get properly scoped variable
+definitions, and we even (trivially) allow mutation of them :).</p>
+
+<p>With this, we completed what we set out to do. Our nice iterative fib
+example from the intro compiles and runs just fine. The mem2reg pass optimizes
+all of our stack variables into SSA registers, inserting PHI nodes where needed,
+and our front-end remains simple: no "iterated dominance frontier" computation
+anywhere in sight.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="code">Full Code Listing</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>
+Here is the complete code listing for our running example, enhanced with mutable
+variables and var/in support. To build this example, use:
+</p>
+
+<div class="doc_code">
+<pre>
+# Compile
+ocamlbuild toy.byte
+# Run
+./toy.byte
+</pre>
+</div>
+
+<p>Here is the code:</p>
+
+<dl>
+<dt>_tags:</dt>
+<dd class="doc_code">
+<pre>
+&lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
+&lt;*.{byte,native}&gt;: g++, use_llvm, use_llvm_analysis
+&lt;*.{byte,native}&gt;: use_llvm_executionengine, use_llvm_target
+&lt;*.{byte,native}&gt;: use_llvm_scalar_opts, use_bindings
+</pre>
+</dd>
+
+<dt>myocamlbuild.ml:</dt>
+<dd class="doc_code">
+<pre>
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+ocaml_lib ~extern:true "llvm_executionengine";;
+ocaml_lib ~extern:true "llvm_target";;
+ocaml_lib ~extern:true "llvm_scalar_opts";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"; A"-cclib"; A"-rdynamic"]);;
+dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
+</pre>
+</dd>
+
+<dt>token.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+
+ (* control *)
+ | If | Then | Else
+ | For | In
+
+ (* operators *)
+ | Binary | Unary
+
+ (* var definition *)
+ | Var
+</pre>
+</dd>
+
+<dt>lexer.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [&lt; ' ('#'); stream &gt;] -&gt;
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [&lt; 'c; stream &gt;] -&gt;
+ [&lt; 'Token.Kwd c; lex stream &gt;]
+
+ (* end of stream. *)
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+
+and lex_number buffer = parser
+ | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
+
+and lex_ident buffer = parser
+ | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [&lt; stream=lex &gt;] -&gt;
+ match Buffer.contents buffer with
+ | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
+ | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
+ | "if" -&gt; [&lt; 'Token.If; stream &gt;]
+ | "then" -&gt; [&lt; 'Token.Then; stream &gt;]
+ | "else" -&gt; [&lt; 'Token.Else; stream &gt;]
+ | "for" -&gt; [&lt; 'Token.For; stream &gt;]
+ | "in" -&gt; [&lt; 'Token.In; stream &gt;]
+ | "binary" -&gt; [&lt; 'Token.Binary; stream &gt;]
+ | "unary" -&gt; [&lt; 'Token.Unary; stream &gt;]
+ | "var" -&gt; [&lt; 'Token.Var; stream &gt;]
+ | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
+
+and lex_comment = parser
+ | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
+ | [&lt; 'c; e=lex_comment &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; [&lt; &gt;]
+</pre>
+</dd>
+
+<dt>ast.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a unary operator. *)
+ | Unary of char * expr
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+ (* variant for if/then/else. *)
+ | If of expr * expr * expr
+
+ (* variant for for/in. *)
+ | For of string * expr * expr * expr option * expr
+
+ (* variant for var/in. *)
+ | Var of (string * expr option) array * expr
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto =
+ | Prototype of string * string array
+ | BinOpPrototype of string * string array * int
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
+</pre>
+</dd>
+
+<dt>parser.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr
+ * ::= ifexpr
+ * ::= forexpr
+ * ::= varexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [&lt; 'Token.Ident id; stream &gt;] -&gt;
+ let rec parse_args accumulator = parser
+ | [&lt; e=parse_expr; stream &gt;] -&gt;
+ begin parser
+ | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; e :: accumulator
+ end stream
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [&lt; 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [&lt; &gt;] -&gt; Ast.Variable id
+ in
+ parse_ident id stream
+
+ (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
+ | [&lt; 'Token.If; c=parse_expr;
+ 'Token.Then ?? "expected 'then'"; t=parse_expr;
+ 'Token.Else ?? "expected 'else'"; e=parse_expr &gt;] -&gt;
+ Ast.If (c, t, e)
+
+ (* forexpr
+ ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
+ | [&lt; 'Token.For;
+ 'Token.Ident id ?? "expected identifier after for";
+ 'Token.Kwd '=' ?? "expected '=' after for";
+ stream &gt;] -&gt;
+ begin parser
+ | [&lt;
+ start=parse_expr;
+ 'Token.Kwd ',' ?? "expected ',' after for";
+ end_=parse_expr;
+ stream &gt;] -&gt;
+ let step =
+ begin parser
+ | [&lt; 'Token.Kwd ','; step=parse_expr &gt;] -&gt; Some step
+ | [&lt; &gt;] -&gt; None
+ end stream
+ in
+ begin parser
+ | [&lt; 'Token.In; body=parse_expr &gt;] -&gt;
+ Ast.For (id, start, end_, step, body)
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected 'in' after for")
+ end stream
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected '=' after for")
+ end stream
+
+ (* varexpr
+ * ::= 'var' identifier ('=' expression?
+ * (',' identifier ('=' expression)?)* 'in' expression *)
+ | [&lt; 'Token.Var;
+ (* At least one variable name is required. *)
+ 'Token.Ident id ?? "expected identifier after var";
+ init=parse_var_init;
+ var_names=parse_var_names [(id, init)];
+ (* At this point, we have to have 'in'. *)
+ 'Token.In ?? "expected 'in' keyword after 'var'";
+ body=parse_expr &gt;] -&gt;
+ Ast.Var (Array.of_list (List.rev var_names), body)
+
+ | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
+
+(* unary
+ * ::= primary
+ * ::= '!' unary *)
+and parse_unary = parser
+ (* If this is a unary operator, read it. *)
+ | [&lt; 'Token.Kwd op when op != '(' &amp;&amp; op != ')'; operand=parse_expr &gt;] -&gt;
+ Ast.Unary (op, operand)
+
+ (* If the current token is not an operator, it must be a primary expr. *)
+ | [&lt; stream &gt;] -&gt; parse_primary stream
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec &lt; expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_unary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) -&gt;
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec &lt; next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -&gt; rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -&gt; lhs
+
+and parse_var_init = parser
+ (* read in the optional initializer. *)
+ | [&lt; 'Token.Kwd '='; e=parse_expr &gt;] -&gt; Some e
+ | [&lt; &gt;] -&gt; None
+
+and parse_var_names accumulator = parser
+ | [&lt; 'Token.Kwd ',';
+ 'Token.Ident id ?? "expected identifier list after var";
+ init=parse_var_init;
+ e=parse_var_names ((id, init) :: accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [&lt; lhs=parse_unary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')'
+ * ::= binary LETTER number? (id, id)
+ * ::= unary LETTER number? (id) *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
+ | [&lt; &gt;] -&gt; accumulator
+ in
+ let parse_operator = parser
+ | [&lt; 'Token.Unary &gt;] -&gt; "unary", 1
+ | [&lt; 'Token.Binary &gt;] -&gt; "binary", 2
+ in
+ let parse_binary_precedence = parser
+ | [&lt; 'Token.Number n &gt;] -&gt; int_of_float n
+ | [&lt; &gt;] -&gt; 30
+ in
+ parser
+ | [&lt; 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+ | [&lt; (prefix, kind)=parse_operator;
+ 'Token.Kwd op ?? "expected an operator";
+ (* Read the precedence if present. *)
+ binary_precedence=parse_binary_precedence;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
+ let name = prefix ^ (String.make 1 op) in
+ let args = Array.of_list (List.rev args) in
+
+ (* Verify right number of arguments for operator. *)
+ if Array.length args != kind
+ then raise (Stream.Error "invalid number of operands for operator")
+ else
+ if kind == 1 then
+ Ast.Prototype (name, args)
+ else
+ Ast.BinOpPrototype (name, args, binary_precedence)
+ | [&lt; &gt;] -&gt;
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [&lt; e=parse_expr &gt;] -&gt;
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
+</pre>
+</dd>
+
+<dt>codegen.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+(* Create an alloca instruction in the entry block of the function. This
+ * is used for mutable variables etc. *)
+let create_entry_block_alloca the_function var_name =
+ let builder = builder_at context (instr_begin (entry_block the_function)) in
+ build_alloca double_type var_name builder
+
+let rec codegen_expr = function
+ | Ast.Number n -&gt; const_float double_type n
+ | Ast.Variable name -&gt;
+ let v = try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name")
+ in
+ (* Load the value. *)
+ build_load v name builder
+ | Ast.Unary (op, operand) -&gt;
+ let operand = codegen_expr operand in
+ let callee = "unary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown unary operator")
+ in
+ build_call callee [|operand|] "unop" builder
+ | Ast.Binary (op, lhs, rhs) -&gt;
+ begin match op with
+ | '=' -&gt;
+ (* Special case '=' because we don't want to emit the LHS as an
+ * expression. *)
+ let name =
+ match lhs with
+ | Ast.Variable name -&gt; name
+ | _ -&gt; raise (Error "destination of '=' must be a variable")
+ in
+
+ (* Codegen the rhs. *)
+ let val_ = codegen_expr rhs in
+
+ (* Lookup the name. *)
+ let variable = try Hashtbl.find named_values name with
+ | Not_found -&gt; raise (Error "unknown variable name")
+ in
+ ignore(build_store val_ variable builder);
+ val_
+ | _ -&gt;
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -&gt; build_add lhs_val rhs_val "addtmp" builder
+ | '-' -&gt; build_sub lhs_val rhs_val "subtmp" builder
+ | '*' -&gt; build_mul lhs_val rhs_val "multmp" builder
+ | '&lt;' -&gt;
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -&gt;
+ (* If it wasn't a builtin binary operator, it must be a user defined
+ * one. Emit a call to it. *)
+ let callee = "binary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "binary operator not found!")
+ in
+ build_call callee [|lhs_val; rhs_val|] "binop" builder
+ end
+ end
+ | Ast.Call (callee, args) -&gt;
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -&gt; callee
+ | None -&gt; raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+ | Ast.If (cond, then_, else_) -&gt;
+ let cond = codegen_expr cond in
+
+ (* Convert condition to a bool by comparing equal to 0.0 *)
+ let zero = const_float double_type 0.0 in
+ let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
+
+ (* Grab the first block so that we might later add the conditional branch
+ * to it at the end of the function. *)
+ let start_bb = insertion_block builder in
+ let the_function = block_parent start_bb in
+
+ let then_bb = append_block context "then" the_function in
+
+ (* Emit 'then' value. *)
+ position_at_end then_bb builder;
+ let then_val = codegen_expr then_ in
+
+ (* Codegen of 'then' can change the current block, update then_bb for the
+ * phi. We create a new name because one is used for the phi node, and the
+ * other is used for the conditional branch. *)
+ let new_then_bb = insertion_block builder in
+
+ (* Emit 'else' value. *)
+ let else_bb = append_block context "else" the_function in
+ position_at_end else_bb builder;
+ let else_val = codegen_expr else_ in
+
+ (* Codegen of 'else' can change the current block, update else_bb for the
+ * phi. *)
+ let new_else_bb = insertion_block builder in
+
+ (* Emit merge block. *)
+ let merge_bb = append_block context "ifcont" the_function in
+ position_at_end merge_bb builder;
+ let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
+ let phi = build_phi incoming "iftmp" builder in
+
+ (* Return to the start block to add the conditional branch. *)
+ position_at_end start_bb builder;
+ ignore (build_cond_br cond_val then_bb else_bb builder);
+
+ (* Set a unconditional branch at the end of the 'then' block and the
+ * 'else' block to the 'merge' block. *)
+ position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
+ position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
+
+ (* Finally, set the builder to the end of the merge block. *)
+ position_at_end merge_bb builder;
+
+ phi
+ | Ast.For (var_name, start, end_, step, body) -&gt;
+ (* Output this as:
+ * var = alloca double
+ * ...
+ * start = startexpr
+ * store start -&gt; var
+ * goto loop
+ * loop:
+ * ...
+ * bodyexpr
+ * ...
+ * loopend:
+ * step = stepexpr
+ * endcond = endexpr
+ *
+ * curvar = load var
+ * nextvar = curvar + step
+ * store nextvar -&gt; var
+ * br endcond, loop, endloop
+ * outloop: *)
+
+ let the_function = block_parent (insertion_block builder) in
+
+ (* Create an alloca for the variable in the entry block. *)
+ let alloca = create_entry_block_alloca the_function var_name in
+
+ (* Emit the start code first, without 'variable' in scope. *)
+ let start_val = codegen_expr start in
+
+ (* Store the value into the alloca. *)
+ ignore(build_store start_val alloca builder);
+
+ (* Make the new basic block for the loop header, inserting after current
+ * block. *)
+ let loop_bb = append_block context "loop" the_function in
+
+ (* Insert an explicit fall through from the current block to the
+ * loop_bb. *)
+ ignore (build_br loop_bb builder);
+
+ (* Start insertion in loop_bb. *)
+ position_at_end loop_bb builder;
+
+ (* Within the loop, the variable is defined equal to the PHI node. If it
+ * shadows an existing variable, we have to restore it, so save it
+ * now. *)
+ let old_val =
+ try Some (Hashtbl.find named_values var_name) with Not_found -&gt; None
+ in
+ Hashtbl.add named_values var_name alloca;
+
+ (* Emit the body of the loop. This, like any other expr, can change the
+ * current BB. Note that we ignore the value computed by the body, but
+ * don't allow an error *)
+ ignore (codegen_expr body);
+
+ (* Emit the step value. *)
+ let step_val =
+ match step with
+ | Some step -&gt; codegen_expr step
+ (* If not specified, use 1.0. *)
+ | None -&gt; const_float double_type 1.0
+ in
+
+ (* Compute the end condition. *)
+ let end_cond = codegen_expr end_ in
+
+ (* Reload, increment, and restore the alloca. This handles the case where
+ * the body of the loop mutates the variable. *)
+ let cur_var = build_load alloca var_name builder in
+ let next_var = build_add cur_var step_val "nextvar" builder in
+ ignore(build_store next_var alloca builder);
+
+ (* Convert condition to a bool by comparing equal to 0.0. *)
+ let zero = const_float double_type 0.0 in
+ let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
+
+ (* Create the "after loop" block and insert it. *)
+ let after_bb = append_block context "afterloop" the_function in
+
+ (* Insert the conditional branch into the end of loop_end_bb. *)
+ ignore (build_cond_br end_cond loop_bb after_bb builder);
+
+ (* Any new code will be inserted in after_bb. *)
+ position_at_end after_bb builder;
+
+ (* Restore the unshadowed variable. *)
+ begin match old_val with
+ | Some old_val -&gt; Hashtbl.add named_values var_name old_val
+ | None -&gt; ()
+ end;
+
+ (* for expr always returns 0.0. *)
+ const_null double_type
+ | Ast.Var (var_names, body) -&gt;
+ let old_bindings = ref [] in
+
+ let the_function = block_parent (insertion_block builder) in
+
+ (* Register all variables and emit their initializer. *)
+ Array.iter (fun (var_name, init) -&gt;
+ (* Emit the initializer before adding the variable to scope, this
+ * prevents the initializer from referencing the variable itself, and
+ * permits stuff like this:
+ * var a = 1 in
+ * var a = a in ... # refers to outer 'a'. *)
+ let init_val =
+ match init with
+ | Some init -&gt; codegen_expr init
+ (* If not specified, use 0.0. *)
+ | None -&gt; const_float double_type 0.0
+ in
+
+ let alloca = create_entry_block_alloca the_function var_name in
+ ignore(build_store init_val alloca builder);
+
+ (* Remember the old variable binding so that we can restore the binding
+ * when we unrecurse. *)
+ begin
+ try
+ let old_value = Hashtbl.find named_values var_name in
+ old_bindings := (var_name, old_value) :: !old_bindings;
+ with Not_found -&gt; ()
+ end;
+
+ (* Remember this binding. *)
+ Hashtbl.add named_values var_name alloca;
+ ) var_names;
+
+ (* Codegen the body, now that all vars are in scope. *)
+ let body_val = codegen_expr body in
+
+ (* Pop all our variables from scope. *)
+ List.iter (fun (var_name, old_value) -&gt;
+ Hashtbl.add named_values var_name old_value
+ ) !old_bindings;
+
+ (* Return the body computation. *)
+ body_val
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) | Ast.BinOpPrototype (name, args, _) -&gt;
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -&gt; declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f -&gt;
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f &lt;&gt; At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) &lt;&gt; ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a -&gt;
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+(* Create an alloca for each argument and register the argument in the symbol
+ * table so that references to it will succeed. *)
+let create_argument_allocas the_function proto =
+ let args = match proto with
+ | Ast.Prototype (_, args) | Ast.BinOpPrototype (_, args, _) -&gt; args
+ in
+ Array.iteri (fun i ai -&gt;
+ let var_name = args.(i) in
+ (* Create an alloca for this variable. *)
+ let alloca = create_entry_block_alloca the_function var_name in
+
+ (* Store the initial value into the alloca. *)
+ ignore(build_store ai alloca builder);
+
+ (* Add arguments to variable symbol table. *)
+ Hashtbl.add named_values var_name alloca;
+ ) (params the_function)
+
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) -&gt;
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* If this is an operator, install it. *)
+ begin match proto with
+ | Ast.BinOpPrototype (name, args, prec) -&gt;
+ let op = name.[String.length name - 1] in
+ Hashtbl.add Parser.binop_precedence op prec;
+ | _ -&gt; ()
+ end;
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ (* Add all arguments to the symbol table and create their allocas. *)
+ create_argument_allocas the_function proto;
+
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+ with e -&gt;
+ delete_function the_function;
+ raise e
+</pre>
+</dd>
+
+<dt>toplevel.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop the_fpm the_execution_engine stream =
+ match Stream.peek stream with
+ | None -&gt; ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') -&gt;
+ Stream.junk stream;
+ main_loop the_fpm the_execution_engine stream
+
+ | Some token -&gt;
+ begin
+ try match token with
+ | Token.Def -&gt;
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func the_fpm e);
+ | Token.Extern -&gt;
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ -&gt;
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+ with Stream.Error s | Codegen.Error s -&gt;
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready&gt; "; flush stdout;
+ main_loop the_fpm the_execution_engine stream
+</pre>
+</dd>
+
+<dt>toy.ml:</dt>
+<dd class="doc_code">
+<pre>
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+open Llvm_target
+open Llvm_scalar_opts
+
+let main () =
+ ignore (initialize_native_target ());
+
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '=' 2;
+ Hashtbl.add Parser.binop_precedence '&lt;' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready&gt; "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Promote allocas to registers. *)
+ add_memory_to_register_promotion the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combination the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
+</pre>
+</dd>
+
+<dt>bindings.c</dt>
+<dd class="doc_code">
+<pre>
+#include &lt;stdio.h&gt;
+
+/* putchard - putchar that takes a double and returns 0. */
+extern double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+/* printd - printf that takes a double prints it as "%f\n", returning 0. */
+extern double printd(double X) {
+ printf("%f\n", X);
+ return 0;
+}
+</pre>
+</dd>
+</dl>
+
+<a href="OCamlLangImpl8.html">Next: Conclusion and other useful LLVM tidbits</a>
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/OCamlLangImpl8.html b/docs/tutorial/OCamlLangImpl8.html
new file mode 100644
index 00000000000..7c1a500a21b
--- /dev/null
+++ b/docs/tutorial/OCamlLangImpl8.html
@@ -0,0 +1,359 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+
+<html>
+<head>
+ <title>Kaleidoscope: Conclusion and other useful LLVM tidbits</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Chris Lattner">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>Kaleidoscope: Conclusion and other useful LLVM tidbits</h1>
+
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 8
+ <ol>
+ <li><a href="#conclusion">Tutorial Conclusion</a></li>
+ <li><a href="#llvmirproperties">Properties of LLVM IR</a>
+ <ul>
+ <li><a href="#targetindep">Target Independence</a></li>
+ <li><a href="#safety">Safety Guarantees</a></li>
+ <li><a href="#langspecific">Language-Specific Optimizations</a></li>
+ </ul>
+ </li>
+ <li><a href="#tipsandtricks">Tips and Tricks</a>
+ <ul>
+ <li><a href="#offsetofsizeof">Implementing portable
+ offsetof/sizeof</a></li>
+ <li><a href="#gcstack">Garbage Collected Stack Frames</a></li>
+ </ul>
+ </li>
+ </ol>
+</li>
+</ul>
+
+
+<div class="doc_author">
+ <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="conclusion">Tutorial Conclusion</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>Welcome to the final chapter of the "<a href="index.html">Implementing a
+language with LLVM</a>" tutorial. In the course of this tutorial, we have grown
+our little Kaleidoscope language from being a useless toy, to being a
+semi-interesting (but probably still useless) toy. :)</p>
+
+<p>It is interesting to see how far we've come, and how little code it has
+taken. We built the entire lexer, parser, AST, code generator, and an
+interactive run-loop (with a JIT!) by-hand in under 700 lines of
+(non-comment/non-blank) code.</p>
+
+<p>Our little language supports a couple of interesting features: it supports
+user defined binary and unary operators, it uses JIT compilation for immediate
+evaluation, and it supports a few control flow constructs with SSA construction.
+</p>
+
+<p>Part of the idea of this tutorial was to show you how easy and fun it can be
+to define, build, and play with languages. Building a compiler need not be a
+scary or mystical process! Now that you've seen some of the basics, I strongly
+encourage you to take the code and hack on it. For example, try adding:</p>
+
+<ul>
+<li><b>global variables</b> - While global variables have questional value in
+modern software engineering, they are often useful when putting together quick
+little hacks like the Kaleidoscope compiler itself. Fortunately, our current
+setup makes it very easy to add global variables: just have value lookup check
+to see if an unresolved variable is in the global variable symbol table before
+rejecting it. To create a new global variable, make an instance of the LLVM
+<tt>GlobalVariable</tt> class.</li>
+
+<li><b>typed variables</b> - Kaleidoscope currently only supports variables of
+type double. This gives the language a very nice elegance, because only
+supporting one type means that you never have to specify types. Different
+languages have different ways of handling this. The easiest way is to require
+the user to specify types for every variable definition, and record the type
+of the variable in the symbol table along with its Value*.</li>
+
+<li><b>arrays, structs, vectors, etc</b> - Once you add types, you can start
+extending the type system in all sorts of interesting ways. Simple arrays are
+very easy and are quite useful for many different applications. Adding them is
+mostly an exercise in learning how the LLVM <a
+href="../LangRef.html#i_getelementptr">getelementptr</a> instruction works: it
+is so nifty/unconventional, it <a
+href="../GetElementPtr.html">has its own FAQ</a>! If you add support
+for recursive types (e.g. linked lists), make sure to read the <a
+href="../ProgrammersManual.html#TypeResolve">section in the LLVM
+Programmer's Manual</a> that describes how to construct them.</li>
+
+<li><b>standard runtime</b> - Our current language allows the user to access
+arbitrary external functions, and we use it for things like "printd" and
+"putchard". As you extend the language to add higher-level constructs, often
+these constructs make the most sense if they are lowered to calls into a
+language-supplied runtime. For example, if you add hash tables to the language,
+it would probably make sense to add the routines to a runtime, instead of
+inlining them all the way.</li>
+
+<li><b>memory management</b> - Currently we can only access the stack in
+Kaleidoscope. It would also be useful to be able to allocate heap memory,
+either with calls to the standard libc malloc/free interface or with a garbage
+collector. If you would like to use garbage collection, note that LLVM fully
+supports <a href="../GarbageCollection.html">Accurate Garbage Collection</a>
+including algorithms that move objects and need to scan/update the stack.</li>
+
+<li><b>debugger support</b> - LLVM supports generation of <a
+href="../SourceLevelDebugging.html">DWARF Debug info</a> which is understood by
+common debuggers like GDB. Adding support for debug info is fairly
+straightforward. The best way to understand it is to compile some C/C++ code
+with "<tt>llvm-gcc -g -O0</tt>" and taking a look at what it produces.</li>
+
+<li><b>exception handling support</b> - LLVM supports generation of <a
+href="../ExceptionHandling.html">zero cost exceptions</a> which interoperate
+with code compiled in other languages. You could also generate code by
+implicitly making every function return an error value and checking it. You
+could also make explicit use of setjmp/longjmp. There are many different ways
+to go here.</li>
+
+<li><b>object orientation, generics, database access, complex numbers,
+geometric programming, ...</b> - Really, there is
+no end of crazy features that you can add to the language.</li>
+
+<li><b>unusual domains</b> - We've been talking about applying LLVM to a domain
+that many people are interested in: building a compiler for a specific language.
+However, there are many other domains that can use compiler technology that are
+not typically considered. For example, LLVM has been used to implement OpenGL
+graphics acceleration, translate C++ code to ActionScript, and many other
+cute and clever things. Maybe you will be the first to JIT compile a regular
+expression interpreter into native code with LLVM?</li>
+
+</ul>
+
+<p>
+Have fun - try doing something crazy and unusual. Building a language like
+everyone else always has, is much less fun than trying something a little crazy
+or off the wall and seeing how it turns out. If you get stuck or want to talk
+about it, feel free to email the <a
+href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">llvmdev mailing
+list</a>: it has lots of people who are interested in languages and are often
+willing to help out.
+</p>
+
+<p>Before we end this tutorial, I want to talk about some "tips and tricks" for generating
+LLVM IR. These are some of the more subtle things that may not be obvious, but
+are very useful if you want to take advantage of LLVM's capabilities.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="llvmirproperties">Properties of the LLVM IR</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>We have a couple common questions about code in the LLVM IR form - lets just
+get these out of the way right now, shall we?</p>
+
+<!-- ======================================================================= -->
+<h4><a name="targetindep">Target Independence</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Kaleidoscope is an example of a "portable language": any program written in
+Kaleidoscope will work the same way on any target that it runs on. Many other
+languages have this property, e.g. lisp, java, haskell, javascript, python, etc
+(note that while these languages are portable, not all their libraries are).</p>
+
+<p>One nice aspect of LLVM is that it is often capable of preserving target
+independence in the IR: you can take the LLVM IR for a Kaleidoscope-compiled
+program and run it on any target that LLVM supports, even emitting C code and
+compiling that on targets that LLVM doesn't support natively. You can trivially
+tell that the Kaleidoscope compiler generates target-independent code because it
+never queries for any target-specific information when generating code.</p>
+
+<p>The fact that LLVM provides a compact, target-independent, representation for
+code gets a lot of people excited. Unfortunately, these people are usually
+thinking about C or a language from the C family when they are asking questions
+about language portability. I say "unfortunately", because there is really no
+way to make (fully general) C code portable, other than shipping the source code
+around (and of course, C source code is not actually portable in general
+either - ever port a really old application from 32- to 64-bits?).</p>
+
+<p>The problem with C (again, in its full generality) is that it is heavily
+laden with target specific assumptions. As one simple example, the preprocessor
+often destructively removes target-independence from the code when it processes
+the input text:</p>
+
+<div class="doc_code">
+<pre>
+#ifdef __i386__
+ int X = 1;
+#else
+ int X = 42;
+#endif
+</pre>
+</div>
+
+<p>While it is possible to engineer more and more complex solutions to problems
+like this, it cannot be solved in full generality in a way that is better than shipping
+the actual source code.</p>
+
+<p>That said, there are interesting subsets of C that can be made portable. If
+you are willing to fix primitive types to a fixed size (say int = 32-bits,
+and long = 64-bits), don't care about ABI compatibility with existing binaries,
+and are willing to give up some other minor features, you can have portable
+code. This can make sense for specialized domains such as an
+in-kernel language.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="safety">Safety Guarantees</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Many of the languages above are also "safe" languages: it is impossible for
+a program written in Java to corrupt its address space and crash the process
+(assuming the JVM has no bugs).
+Safety is an interesting property that requires a combination of language
+design, runtime support, and often operating system support.</p>
+
+<p>It is certainly possible to implement a safe language in LLVM, but LLVM IR
+does not itself guarantee safety. The LLVM IR allows unsafe pointer casts,
+use after free bugs, buffer over-runs, and a variety of other problems. Safety
+needs to be implemented as a layer on top of LLVM and, conveniently, several
+groups have investigated this. Ask on the <a
+href="http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev">llvmdev mailing
+list</a> if you are interested in more details.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="langspecific">Language-Specific Optimizations</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>One thing about LLVM that turns off many people is that it does not solve all
+the world's problems in one system (sorry 'world hunger', someone else will have
+to solve you some other day). One specific complaint is that people perceive
+LLVM as being incapable of performing high-level language-specific optimization:
+LLVM "loses too much information".</p>
+
+<p>Unfortunately, this is really not the place to give you a full and unified
+version of "Chris Lattner's theory of compiler design". Instead, I'll make a
+few observations:</p>
+
+<p>First, you're right that LLVM does lose information. For example, as of this
+writing, there is no way to distinguish in the LLVM IR whether an SSA-value came
+from a C "int" or a C "long" on an ILP32 machine (other than debug info). Both
+get compiled down to an 'i32' value and the information about what it came from
+is lost. The more general issue here, is that the LLVM type system uses
+"structural equivalence" instead of "name equivalence". Another place this
+surprises people is if you have two types in a high-level language that have the
+same structure (e.g. two different structs that have a single int field): these
+types will compile down into a single LLVM type and it will be impossible to
+tell what it came from.</p>
+
+<p>Second, while LLVM does lose information, LLVM is not a fixed target: we
+continue to enhance and improve it in many different ways. In addition to
+adding new features (LLVM did not always support exceptions or debug info), we
+also extend the IR to capture important information for optimization (e.g.
+whether an argument is sign or zero extended, information about pointers
+aliasing, etc). Many of the enhancements are user-driven: people want LLVM to
+include some specific feature, so they go ahead and extend it.</p>
+
+<p>Third, it is <em>possible and easy</em> to add language-specific
+optimizations, and you have a number of choices in how to do it. As one trivial
+example, it is easy to add language-specific optimization passes that
+"know" things about code compiled for a language. In the case of the C family,
+there is an optimization pass that "knows" about the standard C library
+functions. If you call "exit(0)" in main(), it knows that it is safe to
+optimize that into "return 0;" because C specifies what the 'exit'
+function does.</p>
+
+<p>In addition to simple library knowledge, it is possible to embed a variety of
+other language-specific information into the LLVM IR. If you have a specific
+need and run into a wall, please bring the topic up on the llvmdev list. At the
+very worst, you can always treat LLVM as if it were a "dumb code generator" and
+implement the high-level optimizations you desire in your front-end, on the
+language-specific AST.
+</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<h2><a name="tipsandtricks">Tips and Tricks</a></h2>
+<!-- *********************************************************************** -->
+
+<div>
+
+<p>There is a variety of useful tips and tricks that you come to know after
+working on/with LLVM that aren't obvious at first glance. Instead of letting
+everyone rediscover them, this section talks about some of these issues.</p>
+
+<!-- ======================================================================= -->
+<h4><a name="offsetofsizeof">Implementing portable offsetof/sizeof</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>One interesting thing that comes up, if you are trying to keep the code
+generated by your compiler "target independent", is that you often need to know
+the size of some LLVM type or the offset of some field in an llvm structure.
+For example, you might need to pass the size of a type into a function that
+allocates memory.</p>
+
+<p>Unfortunately, this can vary widely across targets: for example the width of
+a pointer is trivially target-specific. However, there is a <a
+href="http://nondot.org/sabre/LLVMNotes/SizeOf-OffsetOf-VariableSizedStructs.txt">clever
+way to use the getelementptr instruction</a> that allows you to compute this
+in a portable way.</p>
+
+</div>
+
+<!-- ======================================================================= -->
+<h4><a name="gcstack">Garbage Collected Stack Frames</a></h4>
+<!-- ======================================================================= -->
+
+<div>
+
+<p>Some languages want to explicitly manage their stack frames, often so that
+they are garbage collected or to allow easy implementation of closures. There
+are often better ways to implement these features than explicit stack frames,
+but <a
+href="http://nondot.org/sabre/LLVMNotes/ExplicitlyManagedStackFrames.txt">LLVM
+does support them,</a> if you want. It requires your front-end to convert the
+code into <a
+href="http://en.wikipedia.org/wiki/Continuation-passing_style">Continuation
+Passing Style</a> and the use of tail calls (which LLVM also supports).</p>
+
+</div>
+
+</div>
+
+<!-- *********************************************************************** -->
+<hr>
+<address>
+ <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
+ src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
+ <a href="http://validator.w3.org/check/referer"><img
+ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
+
+ <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
+ <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+ Last modified: $Date$
+</address>
+</body>
+</html>
diff --git a/docs/tutorial/index.html b/docs/tutorial/index.html
new file mode 100644
index 00000000000..2c11a9a48b3
--- /dev/null
+++ b/docs/tutorial/index.html
@@ -0,0 +1,48 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+ <title>LLVM Tutorial: Table of Contents</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="author" content="Owen Anderson">
+ <meta name="description"
+ content="LLVM Tutorial: Table of Contents.">
+ <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
+</head>
+
+<body>
+
+<h1>LLVM Tutorial: Table of Contents</h1>
+
+<ol>
+ <li>Kaleidoscope: Implementing a Language with LLVM
+ <ol>
+ <li><a href="LangImpl1.html">Tutorial Introduction and the Lexer</a></li>
+ <li><a href="LangImpl2.html">Implementing a Parser and AST</a></li>
+ <li><a href="LangImpl3.html">Implementing Code Generation to LLVM IR</a></li>
+ <li><a href="LangImpl4.html">Adding JIT and Optimizer Support</a></li>
+ <li><a href="LangImpl5.html">Extending the language: control flow</a></li>
+ <li><a href="LangImpl6.html">Extending the language: user-defined operators</a></li>
+ <li><a href="LangImpl7.html">Extending the language: mutable variables / SSA construction</a></li>
+ <li><a href="LangImpl8.html">Conclusion and other useful LLVM tidbits</a></li>
+ </ol></li>
+ <li>Kaleidoscope: Implementing a Language with LLVM in Objective Caml
+ <ol>
+ <li><a href="OCamlLangImpl1.html">Tutorial Introduction and the Lexer</a></li>
+ <li><a href="OCamlLangImpl2.html">Implementing a Parser and AST</a></li>
+ <li><a href="OCamlLangImpl3.html">Implementing Code Generation to LLVM IR</a></li>
+ <li><a href="OCamlLangImpl4.html">Adding JIT and Optimizer Support</a></li>
+ <li><a href="OCamlLangImpl5.html">Extending the language: control flow</a></li>
+ <li><a href="OCamlLangImpl6.html">Extending the language: user-defined operators</a></li>
+ <li><a href="OCamlLangImpl7.html">Extending the language: mutable variables / SSA construction</a></li>
+ <li><a href="OCamlLangImpl8.html">Conclusion and other useful LLVM tidbits</a></li>
+ </ol></li>
+ <li>Advanced Topics
+ <ol>
+ <li><a href="http://llvm.org/pubs/2004-09-22-LCPCLLVMTutorial.html">Writing
+ an Optimization for LLVM</a></li>
+ </ol></li>
+</ol>
+
+</body>
+</html>
diff --git a/docs/userguides.rst b/docs/userguides.rst
new file mode 100644
index 00000000000..fa6e3cfff23
--- /dev/null
+++ b/docs/userguides.rst
@@ -0,0 +1,90 @@
+.. _userguides:
+
+User Guides
+===========
+
+.. toctree::
+ :hidden:
+
+ CMake
+ CommandGuide/index
+ DeveloperPolicy
+ GettingStartedVS
+ FAQ
+ Lexicon
+ Packaging
+ HowToAddABuilder
+
+* `The LLVM Getting Started Guide <GettingStarted.html>`_
+
+ Discusses how to get up and running quickly with the LLVM infrastructure.
+ Everything from unpacking and compilation of the distribution to execution
+ of some tools.
+
+* :ref:`building-with-cmake`
+
+ An addendum to the main Getting Started guide for those using the `CMake
+ build system <http://www.cmake.org>`_.
+
+* `Getting Started with the LLVM System using Microsoft Visual Studio
+ <GettingStartedVS.html>`_
+
+ An addendum to the main Getting Started guide for those using Visual Studio
+ on Windows.
+
+* `LLVM Tutorial <tutorial/>`_
+
+ A walk through the process of using LLVM for a custom language, and the
+ facilities LLVM offers in tutorial form.
+
+* :ref:`developer_policy`
+
+ The LLVM project's policy towards developers and their contributions.
+
+* :ref:`LLVM Command Guide <commands>`
+
+ A reference manual for the LLVM command line utilities ("man" pages for LLVM
+ tools).
+
+* `LLVM's Analysis and Transform Passes <Passes.html>`_
+
+ A list of optimizations and analyses implemented in LLVM.
+
+* :ref:`faq`
+
+ A list of common questions and problems and their solutions.
+
+* `Release notes for the current release <ReleaseNotes.html>`_
+
+ This describes new features, known bugs, and other limitations.
+
+* `How to Submit A Bug Report <HowToSubmitABug.html>`_
+
+ Instructions for properly submitting information about any bugs you run into
+ in the LLVM system.
+
+* `LLVM Testing Infrastructure Guide <TestingGuide.html>`_
+
+ A reference manual for using the LLVM testing infrastructure.
+
+* `How to build the C, C++, ObjC, and ObjC++ front end <http://clang.llvm.org/get_started.html>`_
+
+ Instructions for building the clang front-end from source.
+
+* :ref:`packaging`
+
+ Advice on packaging LLVM into a distribution.
+
+* :ref:`lexicon`
+
+ Definition of acronyms, terms and concepts used in LLVM.
+
+* :ref:`how_to_add_a_builder`
+
+ Instructions for adding new builder to LLVM buildbot master.
+
+* **IRC** -- You can probably find help on the unofficial LLVM IRC.
+
+ We often are on irc.oftc.net in the #llvm channel. If you are using the
+ mozilla browser, and have chatzilla installed, you can `join #llvm on
+ irc.oftc.net <irc://irc.oftc.net/llvm>`_.
diff --git a/docs/yaml2obj.rst b/docs/yaml2obj.rst
new file mode 100644
index 00000000000..cb59162e5ac
--- /dev/null
+++ b/docs/yaml2obj.rst
@@ -0,0 +1,222 @@
+.. _yaml2obj:
+
+yaml2obj
+========
+
+yaml2obj takes a YAML description of an object file and converts it to a binary
+file.
+
+ $ yaml2py input-file
+
+.. program:: yaml2py
+
+Outputs the binary to stdout.
+
+COFF Syntax
+-----------
+
+Here's a sample COFF file.
+
+.. code-block:: yaml
+
+ header:
+ Machine: IMAGE_FILE_MACHINE_I386 # (0x14C)
+
+ sections:
+ - Name: .text
+ Characteristics: [ IMAGE_SCN_CNT_CODE
+ , IMAGE_SCN_ALIGN_16BYTES
+ , IMAGE_SCN_MEM_EXECUTE
+ , IMAGE_SCN_MEM_READ
+ ] # 0x60500020
+ SectionData:
+ "\x83\xEC\x0C\xC7\x44\x24\x08\x00\x00\x00\x00\xC7\x04\x24\x00\x00\x00\x00\xE8\x00\x00\x00\x00\xE8\x00\x00\x00\x00\x8B\x44\x24\x08\x83\xC4\x0C\xC3" # |....D$.......$...............D$.....|
+
+ symbols:
+ - Name: .text
+ Value: 0
+ SectionNumber: 1
+ SimpleType: IMAGE_SYM_TYPE_NULL # (0)
+ ComplexType: IMAGE_SYM_DTYPE_NULL # (0)
+ StorageClass: IMAGE_SYM_CLASS_STATIC # (3)
+ NumberOfAuxSymbols: 1
+ AuxillaryData:
+ "\x24\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00" # |$.................|
+
+ - Name: _main
+ Value: 0
+ SectionNumber: 1
+ SimpleType: IMAGE_SYM_TYPE_NULL # (0)
+ ComplexType: IMAGE_SYM_DTYPE_NULL # (0)
+ StorageClass: IMAGE_SYM_CLASS_EXTERNAL # (2)
+
+Here's a simplified Kwalify_ schema with an extension to allow alternate types.
+
+.. _Kwalify: http://www.kuwata-lab.com/kwalify/ruby/users-guide.html
+
+.. code-block:: yaml
+
+ type: map
+ mapping:
+ header:
+ type: map
+ mapping:
+ Machine: [ {type: str, enum:
+ [ IMAGE_FILE_MACHINE_UNKNOWN
+ , IMAGE_FILE_MACHINE_AM33
+ , IMAGE_FILE_MACHINE_AMD64
+ , IMAGE_FILE_MACHINE_ARM
+ , IMAGE_FILE_MACHINE_ARMV7
+ , IMAGE_FILE_MACHINE_EBC
+ , IMAGE_FILE_MACHINE_I386
+ , IMAGE_FILE_MACHINE_IA64
+ , IMAGE_FILE_MACHINE_M32R
+ , IMAGE_FILE_MACHINE_MIPS16
+ , IMAGE_FILE_MACHINE_MIPSFPU
+ , IMAGE_FILE_MACHINE_MIPSFPU16
+ , IMAGE_FILE_MACHINE_POWERPC
+ , IMAGE_FILE_MACHINE_POWERPCFP
+ , IMAGE_FILE_MACHINE_R4000
+ , IMAGE_FILE_MACHINE_SH3
+ , IMAGE_FILE_MACHINE_SH3DSP
+ , IMAGE_FILE_MACHINE_SH4
+ , IMAGE_FILE_MACHINE_SH5
+ , IMAGE_FILE_MACHINE_THUMB
+ , IMAGE_FILE_MACHINE_WCEMIPSV2
+ ]}
+ , {type: int}
+ ]
+ Characteristics:
+ - type: seq
+ sequence:
+ - type: str
+ enum: [ IMAGE_FILE_RELOCS_STRIPPED
+ , IMAGE_FILE_EXECUTABLE_IMAGE
+ , IMAGE_FILE_LINE_NUMS_STRIPPED
+ , IMAGE_FILE_LOCAL_SYMS_STRIPPED
+ , IMAGE_FILE_AGGRESSIVE_WS_TRIM
+ , IMAGE_FILE_LARGE_ADDRESS_AWARE
+ , IMAGE_FILE_BYTES_REVERSED_LO
+ , IMAGE_FILE_32BIT_MACHINE
+ , IMAGE_FILE_DEBUG_STRIPPED
+ , IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP
+ , IMAGE_FILE_NET_RUN_FROM_SWAP
+ , IMAGE_FILE_SYSTEM
+ , IMAGE_FILE_DLL
+ , IMAGE_FILE_UP_SYSTEM_ONLY
+ , IMAGE_FILE_BYTES_REVERSED_HI
+ ]
+ - type: int
+ sections:
+ type: seq
+ sequence:
+ - type: map
+ mapping:
+ Name: {type: str}
+ Characteristics:
+ - type: seq
+ sequence:
+ - type: str
+ enum: [ IMAGE_SCN_TYPE_NO_PAD
+ , IMAGE_SCN_CNT_CODE
+ , IMAGE_SCN_CNT_INITIALIZED_DATA
+ , IMAGE_SCN_CNT_UNINITIALIZED_DATA
+ , IMAGE_SCN_LNK_OTHER
+ , IMAGE_SCN_LNK_INFO
+ , IMAGE_SCN_LNK_REMOVE
+ , IMAGE_SCN_LNK_COMDAT
+ , IMAGE_SCN_GPREL
+ , IMAGE_SCN_MEM_PURGEABLE
+ , IMAGE_SCN_MEM_16BIT
+ , IMAGE_SCN_MEM_LOCKED
+ , IMAGE_SCN_MEM_PRELOAD
+ , IMAGE_SCN_ALIGN_1BYTES
+ , IMAGE_SCN_ALIGN_2BYTES
+ , IMAGE_SCN_ALIGN_4BYTES
+ , IMAGE_SCN_ALIGN_8BYTES
+ , IMAGE_SCN_ALIGN_16BYTES
+ , IMAGE_SCN_ALIGN_32BYTES
+ , IMAGE_SCN_ALIGN_64BYTES
+ , IMAGE_SCN_ALIGN_128BYTES
+ , IMAGE_SCN_ALIGN_256BYTES
+ , IMAGE_SCN_ALIGN_512BYTES
+ , IMAGE_SCN_ALIGN_1024BYTES
+ , IMAGE_SCN_ALIGN_2048BYTES
+ , IMAGE_SCN_ALIGN_4096BYTES
+ , IMAGE_SCN_ALIGN_8192BYTES
+ , IMAGE_SCN_LNK_NRELOC_OVFL
+ , IMAGE_SCN_MEM_DISCARDABLE
+ , IMAGE_SCN_MEM_NOT_CACHED
+ , IMAGE_SCN_MEM_NOT_PAGED
+ , IMAGE_SCN_MEM_SHARED
+ , IMAGE_SCN_MEM_EXECUTE
+ , IMAGE_SCN_MEM_READ
+ , IMAGE_SCN_MEM_WRITE
+ ]
+ - type: int
+ SectionData: {type: str}
+ symbols:
+ type: seq
+ sequence:
+ - type: map
+ mapping:
+ Name: {type: str}
+ Value: {type: int}
+ SectionNumber: {type: int}
+ SimpleType: [ {type: str, enum: [ IMAGE_SYM_TYPE_NULL
+ , IMAGE_SYM_TYPE_VOID
+ , IMAGE_SYM_TYPE_CHAR
+ , IMAGE_SYM_TYPE_SHORT
+ , IMAGE_SYM_TYPE_INT
+ , IMAGE_SYM_TYPE_LONG
+ , IMAGE_SYM_TYPE_FLOAT
+ , IMAGE_SYM_TYPE_DOUBLE
+ , IMAGE_SYM_TYPE_STRUCT
+ , IMAGE_SYM_TYPE_UNION
+ , IMAGE_SYM_TYPE_ENUM
+ , IMAGE_SYM_TYPE_MOE
+ , IMAGE_SYM_TYPE_BYTE
+ , IMAGE_SYM_TYPE_WORD
+ , IMAGE_SYM_TYPE_UINT
+ , IMAGE_SYM_TYPE_DWORD
+ ]}
+ , {type: int}
+ ]
+ ComplexType: [ {type: str, enum: [ IMAGE_SYM_DTYPE_NULL
+ , IMAGE_SYM_DTYPE_POINTER
+ , IMAGE_SYM_DTYPE_FUNCTION
+ , IMAGE_SYM_DTYPE_ARRAY
+ ]}
+ , {type: int}
+ ]
+ StorageClass: [ {type: str, enum:
+ [ IMAGE_SYM_CLASS_END_OF_FUNCTION
+ , IMAGE_SYM_CLASS_NULL
+ , IMAGE_SYM_CLASS_AUTOMATIC
+ , IMAGE_SYM_CLASS_EXTERNAL
+ , IMAGE_SYM_CLASS_STATIC
+ , IMAGE_SYM_CLASS_REGISTER
+ , IMAGE_SYM_CLASS_EXTERNAL_DEF
+ , IMAGE_SYM_CLASS_LABEL
+ , IMAGE_SYM_CLASS_UNDEFINED_LABEL
+ , IMAGE_SYM_CLASS_MEMBER_OF_STRUCT
+ , IMAGE_SYM_CLASS_ARGUMENT
+ , IMAGE_SYM_CLASS_STRUCT_TAG
+ , IMAGE_SYM_CLASS_MEMBER_OF_UNION
+ , IMAGE_SYM_CLASS_UNION_TAG
+ , IMAGE_SYM_CLASS_TYPE_DEFINITION
+ , IMAGE_SYM_CLASS_UNDEFINED_STATIC
+ , IMAGE_SYM_CLASS_ENUM_TAG
+ , IMAGE_SYM_CLASS_MEMBER_OF_ENUM
+ , IMAGE_SYM_CLASS_REGISTER_PARAM
+ , IMAGE_SYM_CLASS_BIT_FIELD
+ , IMAGE_SYM_CLASS_BLOCK
+ , IMAGE_SYM_CLASS_FUNCTION
+ , IMAGE_SYM_CLASS_END_OF_STRUCT
+ , IMAGE_SYM_CLASS_FILE
+ , IMAGE_SYM_CLASS_SECTION
+ , IMAGE_SYM_CLASS_WEAK_EXTERNAL
+ , IMAGE_SYM_CLASS_CLR_TOKEN
+ ]}
+ , {type: int}
+ ]
diff --git a/examples/BrainF/BrainF.cpp b/examples/BrainF/BrainF.cpp
new file mode 100644
index 00000000000..b002d1f496d
--- /dev/null
+++ b/examples/BrainF/BrainF.cpp
@@ -0,0 +1,467 @@
+//===-- BrainF.cpp - BrainF compiler example ----------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--------------------------------------------------------------------===//
+//
+// This class compiles the BrainF language into LLVM assembly.
+//
+// The BrainF language has 8 commands:
+// Command Equivalent C Action
+// ------- ------------ ------
+// , *h=getchar(); Read a character from stdin, 255 on EOF
+// . putchar(*h); Write a character to stdout
+// - --*h; Decrement tape
+// + ++*h; Increment tape
+// < --h; Move head left
+// > ++h; Move head right
+// [ while(*h) { Start loop
+// ] } End loop
+//
+//===--------------------------------------------------------------------===//
+
+#include "BrainF.h"
+#include "llvm/Constants.h"
+#include "llvm/Instructions.h"
+#include "llvm/Intrinsics.h"
+#include "llvm/ADT/STLExtras.h"
+#include <iostream>
+using namespace llvm;
+
+//Set the constants for naming
+const char *BrainF::tapereg = "tape";
+const char *BrainF::headreg = "head";
+const char *BrainF::label = "brainf";
+const char *BrainF::testreg = "test";
+
+Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf,
+ LLVMContext& Context) {
+ in = in1;
+ memtotal = mem;
+ comflag = cf;
+
+ header(Context);
+ readloop(0, 0, 0, Context);
+ delete builder;
+ return module;
+}
+
+void BrainF::header(LLVMContext& C) {
+ module = new Module("BrainF", C);
+
+ //Function prototypes
+
+ //declare void @llvm.memset.p0i8.i32(i8 *, i8, i32, i32, i1)
+ Type *Tys[] = { Type::getInt8PtrTy(C), Type::getInt32Ty(C) };
+ Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset,
+ Tys);
+
+ //declare i32 @getchar()
+ getchar_func = cast<Function>(module->
+ getOrInsertFunction("getchar", IntegerType::getInt32Ty(C), NULL));
+
+ //declare i32 @putchar(i32)
+ putchar_func = cast<Function>(module->
+ getOrInsertFunction("putchar", IntegerType::getInt32Ty(C),
+ IntegerType::getInt32Ty(C), NULL));
+
+
+ //Function header
+
+ //define void @brainf()
+ brainf_func = cast<Function>(module->
+ getOrInsertFunction("brainf", Type::getVoidTy(C), NULL));
+
+ builder = new IRBuilder<>(BasicBlock::Create(C, label, brainf_func));
+
+ //%arr = malloc i8, i32 %d
+ ConstantInt *val_mem = ConstantInt::get(C, APInt(32, memtotal));
+ BasicBlock* BB = builder->GetInsertBlock();
+ Type* IntPtrTy = IntegerType::getInt32Ty(C);
+ Type* Int8Ty = IntegerType::getInt8Ty(C);
+ Constant* allocsize = ConstantExpr::getSizeOf(Int8Ty);
+ allocsize = ConstantExpr::getTruncOrBitCast(allocsize, IntPtrTy);
+ ptr_arr = CallInst::CreateMalloc(BB, IntPtrTy, Int8Ty, allocsize, val_mem,
+ NULL, "arr");
+ BB->getInstList().push_back(cast<Instruction>(ptr_arr));
+
+ //call void @llvm.memset.p0i8.i32(i8 *%arr, i8 0, i32 %d, i32 1, i1 0)
+ {
+ Value *memset_params[] = {
+ ptr_arr,
+ ConstantInt::get(C, APInt(8, 0)),
+ val_mem,
+ ConstantInt::get(C, APInt(32, 1)),
+ ConstantInt::get(C, APInt(1, 0))
+ };
+
+ CallInst *memset_call = builder->
+ CreateCall(memset_func, memset_params);
+ memset_call->setTailCall(false);
+ }
+
+ //%arrmax = getelementptr i8 *%arr, i32 %d
+ if (comflag & flag_arraybounds) {
+ ptr_arrmax = builder->
+ CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal)), "arrmax");
+ }
+
+ //%head.%d = getelementptr i8 *%arr, i32 %d
+ curhead = builder->CreateGEP(ptr_arr,
+ ConstantInt::get(C, APInt(32, memtotal/2)),
+ headreg);
+
+
+
+ //Function footer
+
+ //brainf.end:
+ endbb = BasicBlock::Create(C, label, brainf_func);
+
+ //call free(i8 *%arr)
+ endbb->getInstList().push_back(CallInst::CreateFree(ptr_arr, endbb));
+
+ //ret void
+ ReturnInst::Create(C, endbb);
+
+
+
+ //Error block for array out of bounds
+ if (comflag & flag_arraybounds)
+ {
+ //@aberrormsg = internal constant [%d x i8] c"\00"
+ Constant *msg_0 =
+ ConstantDataArray::getString(C, "Error: The head has left the tape.",
+ true);
+
+ GlobalVariable *aberrormsg = new GlobalVariable(
+ *module,
+ msg_0->getType(),
+ true,
+ GlobalValue::InternalLinkage,
+ msg_0,
+ "aberrormsg");
+
+ //declare i32 @puts(i8 *)
+ Function *puts_func = cast<Function>(module->
+ getOrInsertFunction("puts", IntegerType::getInt32Ty(C),
+ PointerType::getUnqual(IntegerType::getInt8Ty(C)), NULL));
+
+ //brainf.aberror:
+ aberrorbb = BasicBlock::Create(C, label, brainf_func);
+
+ //call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0))
+ {
+ Constant *zero_32 = Constant::getNullValue(IntegerType::getInt32Ty(C));
+
+ Constant *gep_params[] = {
+ zero_32,
+ zero_32
+ };
+
+ Constant *msgptr = ConstantExpr::
+ getGetElementPtr(aberrormsg, gep_params);
+
+ Value *puts_params[] = {
+ msgptr
+ };
+
+ CallInst *puts_call =
+ CallInst::Create(puts_func,
+ puts_params,
+ "", aberrorbb);
+ puts_call->setTailCall(false);
+ }
+
+ //br label %brainf.end
+ BranchInst::Create(endbb, aberrorbb);
+ }
+}
+
+void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb,
+ LLVMContext &C) {
+ Symbol cursym = SYM_NONE;
+ int curvalue = 0;
+ Symbol nextsym = SYM_NONE;
+ int nextvalue = 0;
+ char c;
+ int loop;
+ int direction;
+
+ while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) {
+ // Write out commands
+ switch(cursym) {
+ case SYM_NONE:
+ // Do nothing
+ break;
+
+ case SYM_READ:
+ {
+ //%tape.%d = call i32 @getchar()
+ CallInst *getchar_call = builder->CreateCall(getchar_func, tapereg);
+ getchar_call->setTailCall(false);
+ Value *tape_0 = getchar_call;
+
+ //%tape.%d = trunc i32 %tape.%d to i8
+ Value *tape_1 = builder->
+ CreateTrunc(tape_0, IntegerType::getInt8Ty(C), tapereg);
+
+ //store i8 %tape.%d, i8 *%head.%d
+ builder->CreateStore(tape_1, curhead);
+ }
+ break;
+
+ case SYM_WRITE:
+ {
+ //%tape.%d = load i8 *%head.%d
+ LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
+
+ //%tape.%d = sext i8 %tape.%d to i32
+ Value *tape_1 = builder->
+ CreateSExt(tape_0, IntegerType::getInt32Ty(C), tapereg);
+
+ //call i32 @putchar(i32 %tape.%d)
+ Value *putchar_params[] = {
+ tape_1
+ };
+ CallInst *putchar_call = builder->
+ CreateCall(putchar_func,
+ putchar_params);
+ putchar_call->setTailCall(false);
+ }
+ break;
+
+ case SYM_MOVE:
+ {
+ //%head.%d = getelementptr i8 *%head.%d, i32 %d
+ curhead = builder->
+ CreateGEP(curhead, ConstantInt::get(C, APInt(32, curvalue)),
+ headreg);
+
+ //Error block for array out of bounds
+ if (comflag & flag_arraybounds)
+ {
+ //%test.%d = icmp uge i8 *%head.%d, %arrmax
+ Value *test_0 = builder->
+ CreateICmpUGE(curhead, ptr_arrmax, testreg);
+
+ //%test.%d = icmp ult i8 *%head.%d, %arr
+ Value *test_1 = builder->
+ CreateICmpULT(curhead, ptr_arr, testreg);
+
+ //%test.%d = or i1 %test.%d, %test.%d
+ Value *test_2 = builder->
+ CreateOr(test_0, test_1, testreg);
+
+ //br i1 %test.%d, label %main.%d, label %main.%d
+ BasicBlock *nextbb = BasicBlock::Create(C, label, brainf_func);
+ builder->CreateCondBr(test_2, aberrorbb, nextbb);
+
+ //main.%d:
+ builder->SetInsertPoint(nextbb);
+ }
+ }
+ break;
+
+ case SYM_CHANGE:
+ {
+ //%tape.%d = load i8 *%head.%d
+ LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
+
+ //%tape.%d = add i8 %tape.%d, %d
+ Value *tape_1 = builder->
+ CreateAdd(tape_0, ConstantInt::get(C, APInt(8, curvalue)), tapereg);
+
+ //store i8 %tape.%d, i8 *%head.%d\n"
+ builder->CreateStore(tape_1, curhead);
+ }
+ break;
+
+ case SYM_LOOP:
+ {
+ //br label %main.%d
+ BasicBlock *testbb = BasicBlock::Create(C, label, brainf_func);
+ builder->CreateBr(testbb);
+
+ //main.%d:
+ BasicBlock *bb_0 = builder->GetInsertBlock();
+ BasicBlock *bb_1 = BasicBlock::Create(C, label, brainf_func);
+ builder->SetInsertPoint(bb_1);
+
+ // Make part of PHI instruction now, wait until end of loop to finish
+ PHINode *phi_0 =
+ PHINode::Create(PointerType::getUnqual(IntegerType::getInt8Ty(C)),
+ 2, headreg, testbb);
+ phi_0->addIncoming(curhead, bb_0);
+ curhead = phi_0;
+
+ readloop(phi_0, bb_1, testbb, C);
+ }
+ break;
+
+ default:
+ std::cerr << "Error: Unknown symbol.\n";
+ abort();
+ break;
+ }
+
+ cursym = nextsym;
+ curvalue = nextvalue;
+ nextsym = SYM_NONE;
+
+ // Reading stdin loop
+ loop = (cursym == SYM_NONE)
+ || (cursym == SYM_MOVE)
+ || (cursym == SYM_CHANGE);
+ while(loop) {
+ *in>>c;
+ if (in->eof()) {
+ if (cursym == SYM_NONE) {
+ cursym = SYM_EOF;
+ } else {
+ nextsym = SYM_EOF;
+ }
+ loop = 0;
+ } else {
+ direction = 1;
+ switch(c) {
+ case '-':
+ direction = -1;
+ // Fall through
+
+ case '+':
+ if (cursym == SYM_CHANGE) {
+ curvalue += direction;
+ // loop = 1
+ } else {
+ if (cursym == SYM_NONE) {
+ cursym = SYM_CHANGE;
+ curvalue = direction;
+ // loop = 1
+ } else {
+ nextsym = SYM_CHANGE;
+ nextvalue = direction;
+ loop = 0;
+ }
+ }
+ break;
+
+ case '<':
+ direction = -1;
+ // Fall through
+
+ case '>':
+ if (cursym == SYM_MOVE) {
+ curvalue += direction;
+ // loop = 1
+ } else {
+ if (cursym == SYM_NONE) {
+ cursym = SYM_MOVE;
+ curvalue = direction;
+ // loop = 1
+ } else {
+ nextsym = SYM_MOVE;
+ nextvalue = direction;
+ loop = 0;
+ }
+ }
+ break;
+
+ case ',':
+ if (cursym == SYM_NONE) {
+ cursym = SYM_READ;
+ } else {
+ nextsym = SYM_READ;
+ }
+ loop = 0;
+ break;
+
+ case '.':
+ if (cursym == SYM_NONE) {
+ cursym = SYM_WRITE;
+ } else {
+ nextsym = SYM_WRITE;
+ }
+ loop = 0;
+ break;
+
+ case '[':
+ if (cursym == SYM_NONE) {
+ cursym = SYM_LOOP;
+ } else {
+ nextsym = SYM_LOOP;
+ }
+ loop = 0;
+ break;
+
+ case ']':
+ if (cursym == SYM_NONE) {
+ cursym = SYM_ENDLOOP;
+ } else {
+ nextsym = SYM_ENDLOOP;
+ }
+ loop = 0;
+ break;
+
+ // Ignore other characters
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+ if (cursym == SYM_ENDLOOP) {
+ if (!phi) {
+ std::cerr << "Error: Extra ']'\n";
+ abort();
+ }
+
+ // Write loop test
+ {
+ //br label %main.%d
+ builder->CreateBr(testbb);
+
+ //main.%d:
+
+ //%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d]
+ //Finish phi made at beginning of loop
+ phi->addIncoming(curhead, builder->GetInsertBlock());
+ Value *head_0 = phi;
+
+ //%tape.%d = load i8 *%head.%d
+ LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb);
+
+ //%test.%d = icmp eq i8 %tape.%d, 0
+ ICmpInst *test_0 = new ICmpInst(*testbb, ICmpInst::ICMP_EQ, tape_0,
+ ConstantInt::get(C, APInt(8, 0)), testreg);
+
+ //br i1 %test.%d, label %main.%d, label %main.%d
+ BasicBlock *bb_0 = BasicBlock::Create(C, label, brainf_func);
+ BranchInst::Create(bb_0, oldbb, test_0, testbb);
+
+ //main.%d:
+ builder->SetInsertPoint(bb_0);
+
+ //%head.%d = phi i8 *[%head.%d, %main.%d]
+ PHINode *phi_1 = builder->
+ CreatePHI(PointerType::getUnqual(IntegerType::getInt8Ty(C)), 1,
+ headreg);
+ phi_1->addIncoming(head_0, testbb);
+ curhead = phi_1;
+ }
+
+ return;
+ }
+
+ //End of the program, so go to return block
+ builder->CreateBr(endbb);
+
+ if (phi) {
+ std::cerr << "Error: Missing ']'\n";
+ abort();
+ }
+}
diff --git a/examples/BrainF/BrainF.h b/examples/BrainF/BrainF.h
new file mode 100644
index 00000000000..c069feb51e7
--- /dev/null
+++ b/examples/BrainF/BrainF.h
@@ -0,0 +1,94 @@
+//===-- BrainF.h - BrainF compiler class ----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--------------------------------------------------------------------===//
+//
+// This class stores the data for the BrainF compiler so it doesn't have
+// to pass all of it around. The main method is parse.
+//
+//===--------------------------------------------------------------------===//
+
+#ifndef BRAINF_H
+#define BRAINF_H
+
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+
+using namespace llvm;
+
+/// This class provides a parser for the BrainF language.
+/// The class itself is made to store values during
+/// parsing so they don't have to be passed around
+/// as much.
+class BrainF {
+ public:
+ /// Options for how BrainF should compile
+ enum CompileFlags {
+ flag_off = 0,
+ flag_arraybounds = 1
+ };
+
+ /// This is the main method. It parses BrainF from in1
+ /// and returns the module with a function
+ /// void brainf()
+ /// containing the resulting code.
+ /// On error, it calls abort.
+ /// The caller must delete the returned module.
+ Module *parse(std::istream *in1, int mem, CompileFlags cf,
+ LLVMContext& C);
+
+ protected:
+ /// The different symbols in the BrainF language
+ enum Symbol {
+ SYM_NONE,
+ SYM_READ,
+ SYM_WRITE,
+ SYM_MOVE,
+ SYM_CHANGE,
+ SYM_LOOP,
+ SYM_ENDLOOP,
+ SYM_EOF
+ };
+
+ /// Names of the different parts of the language.
+ /// Tape is used for reading and writing the tape.
+ /// headreg is used for the position of the head.
+ /// label is used for the labels for the BasicBlocks.
+ /// testreg is used for testing the loop exit condition.
+ static const char *tapereg;
+ static const char *headreg;
+ static const char *label;
+ static const char *testreg;
+
+ /// Put the brainf function preamble and other fixed pieces of code
+ void header(LLVMContext& C);
+
+ /// The main loop for parsing. It calls itself recursively
+ /// to handle the depth of nesting of "[]".
+ void readloop(PHINode *phi, BasicBlock *oldbb,
+ BasicBlock *testbb, LLVMContext &Context);
+
+ /// Constants during parsing
+ int memtotal;
+ CompileFlags comflag;
+ std::istream *in;
+ Module *module;
+ Function *brainf_func;
+ Function *getchar_func;
+ Function *putchar_func;
+ Value *ptr_arr;
+ Value *ptr_arrmax;
+ BasicBlock *endbb;
+ BasicBlock *aberrorbb;
+
+ /// Variables
+ IRBuilder<> *builder;
+ Value *curhead;
+};
+
+#endif
diff --git a/examples/BrainF/BrainFDriver.cpp b/examples/BrainF/BrainFDriver.cpp
new file mode 100644
index 00000000000..58617b7f380
--- /dev/null
+++ b/examples/BrainF/BrainFDriver.cpp
@@ -0,0 +1,159 @@
+//===-- BrainFDriver.cpp - BrainF compiler driver -----------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--------------------------------------------------------------------===//
+//
+// This program converts the BrainF language into LLVM assembly,
+// which it can then run using the JIT or output as BitCode.
+//
+// This implementation has a tape of 65536 bytes,
+// with the head starting in the middle.
+// Range checking is off by default, so be careful.
+// It can be enabled with -abc.
+//
+// Use:
+// ./BrainF -jit prog.bf #Run program now
+// ./BrainF -jit -abc prog.bf #Run program now safely
+// ./BrainF prog.bf #Write as BitCode
+//
+// lli prog.bf.bc #Run generated BitCode
+//
+//===--------------------------------------------------------------------===//
+
+#include "BrainF.h"
+#include "llvm/Constants.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Bitcode/ReaderWriter.h"
+#include "llvm/ExecutionEngine/GenericValue.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ManagedStatic.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/raw_ostream.h"
+#include <iostream>
+#include <fstream>
+using namespace llvm;
+
+//Command line options
+
+static cl::opt<std::string>
+InputFilename(cl::Positional, cl::desc("<input brainf>"));
+
+static cl::opt<std::string>
+OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
+
+static cl::opt<bool>
+ArrayBoundsChecking("abc", cl::desc("Enable array bounds checking"));
+
+static cl::opt<bool>
+JIT("jit", cl::desc("Run program Just-In-Time"));
+
+
+//Add main function so can be fully compiled
+void addMainFunction(Module *mod) {
+ //define i32 @main(i32 %argc, i8 **%argv)
+ Function *main_func = cast<Function>(mod->
+ getOrInsertFunction("main", IntegerType::getInt32Ty(mod->getContext()),
+ IntegerType::getInt32Ty(mod->getContext()),
+ PointerType::getUnqual(PointerType::getUnqual(
+ IntegerType::getInt8Ty(mod->getContext()))), NULL));
+ {
+ Function::arg_iterator args = main_func->arg_begin();
+ Value *arg_0 = args++;
+ arg_0->setName("argc");
+ Value *arg_1 = args++;
+ arg_1->setName("argv");
+ }
+
+ //main.0:
+ BasicBlock *bb = BasicBlock::Create(mod->getContext(), "main.0", main_func);
+
+ //call void @brainf()
+ {
+ CallInst *brainf_call = CallInst::Create(mod->getFunction("brainf"),
+ "", bb);
+ brainf_call->setTailCall(false);
+ }
+
+ //ret i32 0
+ ReturnInst::Create(mod->getContext(),
+ ConstantInt::get(mod->getContext(), APInt(32, 0)), bb);
+}
+
+int main(int argc, char **argv) {
+ cl::ParseCommandLineOptions(argc, argv, " BrainF compiler\n");
+
+ LLVMContext &Context = getGlobalContext();
+
+ if (InputFilename == "") {
+ errs() << "Error: You must specify the filename of the program to "
+ "be compiled. Use --help to see the options.\n";
+ abort();
+ }
+
+ //Get the output stream
+ raw_ostream *out = &outs();
+ if (!JIT) {
+ if (OutputFilename == "") {
+ std::string base = InputFilename;
+ if (InputFilename == "-") { base = "a"; }
+
+ // Use default filename.
+ OutputFilename = base+".bc";
+ }
+ if (OutputFilename != "-") {
+ std::string ErrInfo;
+ out = new raw_fd_ostream(OutputFilename.c_str(), ErrInfo,
+ raw_fd_ostream::F_Binary);
+ }
+ }
+
+ //Get the input stream
+ std::istream *in = &std::cin;
+ if (InputFilename != "-")
+ in = new std::ifstream(InputFilename.c_str());
+
+ //Gather the compile flags
+ BrainF::CompileFlags cf = BrainF::flag_off;
+ if (ArrayBoundsChecking)
+ cf = BrainF::CompileFlags(cf | BrainF::flag_arraybounds);
+
+ //Read the BrainF program
+ BrainF bf;
+ Module *mod = bf.parse(in, 65536, cf, Context); //64 KiB
+ if (in != &std::cin)
+ delete in;
+ addMainFunction(mod);
+
+ //Verify generated code
+ if (verifyModule(*mod)) {
+ errs() << "Error: module failed verification. This shouldn't happen.\n";
+ abort();
+ }
+
+ //Write it out
+ if (JIT) {
+ InitializeNativeTarget();
+
+ outs() << "------- Running JIT -------\n";
+ ExecutionEngine *ee = EngineBuilder(mod).create();
+ std::vector<GenericValue> args;
+ Function *brainf_func = mod->getFunction("brainf");
+ GenericValue gv = ee->runFunction(brainf_func, args);
+ } else {
+ WriteBitcodeToFile(mod, *out);
+ }
+
+ //Clean up
+ if (out != &outs())
+ delete out;
+ delete mod;
+
+ llvm_shutdown();
+
+ return 0;
+}
diff --git a/examples/BrainF/CMakeLists.txt b/examples/BrainF/CMakeLists.txt
new file mode 100644
index 00000000000..7bec105cdc8
--- /dev/null
+++ b/examples/BrainF/CMakeLists.txt
@@ -0,0 +1,6 @@
+set(LLVM_LINK_COMPONENTS jit bitwriter nativecodegen interpreter)
+
+add_llvm_example(BrainF
+ BrainF.cpp
+ BrainFDriver.cpp
+ )
diff --git a/examples/BrainF/Makefile b/examples/BrainF/Makefile
new file mode 100644
index 00000000000..2c3e0662523
--- /dev/null
+++ b/examples/BrainF/Makefile
@@ -0,0 +1,15 @@
+##===- examples/BrainF/Makefile ----------------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../..
+TOOLNAME = BrainF
+EXAMPLE_TOOL = 1
+
+LINK_COMPONENTS := jit bitwriter nativecodegen interpreter
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
new file mode 100644
index 00000000000..54ee6cc3a3a
--- /dev/null
+++ b/examples/CMakeLists.txt
@@ -0,0 +1,13 @@
+add_subdirectory(BrainF)
+add_subdirectory(Fibonacci)
+add_subdirectory(HowToUseJIT)
+add_subdirectory(Kaleidoscope)
+add_subdirectory(ModuleMaker)
+
+if( NOT WIN32 )
+ add_subdirectory(ExceptionDemo)
+endif()
+
+if( HAVE_PTHREAD_H )
+ add_subdirectory(ParallelJIT)
+endif( HAVE_PTHREAD_H )
diff --git a/examples/ExceptionDemo/CMakeLists.txt b/examples/ExceptionDemo/CMakeLists.txt
new file mode 100644
index 00000000000..88c9ab7c181
--- /dev/null
+++ b/examples/ExceptionDemo/CMakeLists.txt
@@ -0,0 +1,6 @@
+set(LLVM_LINK_COMPONENTS jit nativecodegen)
+set(LLVM_REQUIRES_EH 1)
+
+add_llvm_example(ExceptionDemo
+ ExceptionDemo.cpp
+ )
diff --git a/examples/ExceptionDemo/ExceptionDemo.cpp b/examples/ExceptionDemo/ExceptionDemo.cpp
new file mode 100644
index 00000000000..6dbd6626de9
--- /dev/null
+++ b/examples/ExceptionDemo/ExceptionDemo.cpp
@@ -0,0 +1,2006 @@
+//===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Demo program which implements an example LLVM exception implementation, and
+// shows several test cases including the handling of foreign exceptions.
+// It is run with type info types arguments to throw. A test will
+// be run for each given type info type. While type info types with the value
+// of -1 will trigger a foreign C++ exception to be thrown; type info types
+// <= 6 and >= 1 will cause the associated generated exceptions to be thrown
+// and caught by generated test functions; and type info types > 6
+// will result in exceptions which pass through to the test harness. All other
+// type info types are not supported and could cause a crash. In all cases,
+// the "finally" blocks of every generated test functions will executed
+// regardless of whether or not that test function ignores or catches the
+// thrown exception.
+//
+// examples:
+//
+// ExceptionDemo
+//
+// causes a usage to be printed to stderr
+//
+// ExceptionDemo 2 3 7 -1
+//
+// results in the following cases:
+// - Value 2 causes an exception with a type info type of 2 to be
+// thrown and caught by an inner generated test function.
+// - Value 3 causes an exception with a type info type of 3 to be
+// thrown and caught by an outer generated test function.
+// - Value 7 causes an exception with a type info type of 7 to be
+// thrown and NOT be caught by any generated function.
+// - Value -1 causes a foreign C++ exception to be thrown and not be
+// caught by any generated function
+//
+// Cases -1 and 7 are caught by a C++ test harness where the validity of
+// of a C++ catch(...) clause catching a generated exception with a
+// type info type of 7 is explained by: example in rules 1.6.4 in
+// http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
+//
+// This code uses code from the llvm compiler-rt project and the llvm
+// Kaleidoscope project.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/LLVMContext.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Intrinsics.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetOptions.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/Dwarf.h"
+#include "llvm/Support/TargetSelect.h"
+
+// FIXME: Although all systems tested with (Linux, OS X), do not need this
+// header file included. A user on ubuntu reported, undefined symbols
+// for stderr, and fprintf, and the addition of this include fixed the
+// issue for them. Given that LLVM's best practices include the goal
+// of reducing the number of redundant header files included, the
+// correct solution would be to find out why these symbols are not
+// defined for the system in question, and fix the issue by finding out
+// which LLVM header file, if any, would include these symbols.
+#include <cstdio>
+
+#include <sstream>
+#include <stdexcept>
+
+
+#ifndef USE_GLOBAL_STR_CONSTS
+#define USE_GLOBAL_STR_CONSTS true
+#endif
+
+// System C++ ABI unwind types from:
+// http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
+
+extern "C" {
+
+ typedef enum {
+ _URC_NO_REASON = 0,
+ _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
+ _URC_FATAL_PHASE2_ERROR = 2,
+ _URC_FATAL_PHASE1_ERROR = 3,
+ _URC_NORMAL_STOP = 4,
+ _URC_END_OF_STACK = 5,
+ _URC_HANDLER_FOUND = 6,
+ _URC_INSTALL_CONTEXT = 7,
+ _URC_CONTINUE_UNWIND = 8
+ } _Unwind_Reason_Code;
+
+ typedef enum {
+ _UA_SEARCH_PHASE = 1,
+ _UA_CLEANUP_PHASE = 2,
+ _UA_HANDLER_FRAME = 4,
+ _UA_FORCE_UNWIND = 8,
+ _UA_END_OF_STACK = 16
+ } _Unwind_Action;
+
+ struct _Unwind_Exception;
+
+ typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
+ struct _Unwind_Exception *);
+
+ struct _Unwind_Exception {
+ uint64_t exception_class;
+ _Unwind_Exception_Cleanup_Fn exception_cleanup;
+
+ uintptr_t private_1;
+ uintptr_t private_2;
+
+ // @@@ The IA-64 ABI says that this structure must be double-word aligned.
+ // Taking that literally does not make much sense generically. Instead
+ // we provide the maximum alignment required by any type for the machine.
+ } __attribute__((__aligned__));
+
+ struct _Unwind_Context;
+ typedef struct _Unwind_Context *_Unwind_Context_t;
+
+ extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
+ extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
+ extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
+ extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
+ extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
+ extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
+
+} // extern "C"
+
+//
+// Example types
+//
+
+/// This is our simplistic type info
+struct OurExceptionType_t {
+ /// type info type
+ int type;
+};
+
+
+/// This is our Exception class which relies on a negative offset to calculate
+/// pointers to its instances from pointers to its unwindException member.
+///
+/// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
+/// on a double word boundary. This is necessary to match the standard:
+/// http://refspecs.freestandards.org/abi-eh-1.21.html
+struct OurBaseException_t {
+ struct OurExceptionType_t type;
+
+ // Note: This is properly aligned in unwind.h
+ struct _Unwind_Exception unwindException;
+};
+
+
+// Note: Not needed since we are C++
+typedef struct OurBaseException_t OurException;
+typedef struct _Unwind_Exception OurUnwindException;
+
+//
+// Various globals used to support typeinfo and generatted exceptions in
+// general
+//
+
+static std::map<std::string, llvm::Value*> namedValues;
+
+int64_t ourBaseFromUnwindOffset;
+
+const unsigned char ourBaseExcpClassChars[] =
+{'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
+
+
+static uint64_t ourBaseExceptionClass = 0;
+
+static std::vector<std::string> ourTypeInfoNames;
+static std::map<int, std::string> ourTypeInfoNamesIndex;
+
+static llvm::StructType *ourTypeInfoType;
+static llvm::StructType *ourCaughtResultType;
+static llvm::StructType *ourExceptionType;
+static llvm::StructType *ourUnwindExceptionType;
+
+static llvm::ConstantInt *ourExceptionNotThrownState;
+static llvm::ConstantInt *ourExceptionThrownState;
+static llvm::ConstantInt *ourExceptionCaughtState;
+
+typedef std::vector<std::string> ArgNames;
+typedef std::vector<llvm::Type*> ArgTypes;
+
+//
+// Code Generation Utilities
+//
+
+/// Utility used to create a function, both declarations and definitions
+/// @param module for module instance
+/// @param retType function return type
+/// @param theArgTypes function's ordered argument types
+/// @param theArgNames function's ordered arguments needed if use of this
+/// function corresponds to a function definition. Use empty
+/// aggregate for function declarations.
+/// @param functName function name
+/// @param linkage function linkage
+/// @param declarationOnly for function declarations
+/// @param isVarArg function uses vararg arguments
+/// @returns function instance
+llvm::Function *createFunction(llvm::Module &module,
+ llvm::Type *retType,
+ const ArgTypes &theArgTypes,
+ const ArgNames &theArgNames,
+ const std::string &functName,
+ llvm::GlobalValue::LinkageTypes linkage,
+ bool declarationOnly,
+ bool isVarArg) {
+ llvm::FunctionType *functType =
+ llvm::FunctionType::get(retType, theArgTypes, isVarArg);
+ llvm::Function *ret =
+ llvm::Function::Create(functType, linkage, functName, &module);
+ if (!ret || declarationOnly)
+ return(ret);
+
+ namedValues.clear();
+ unsigned i = 0;
+ for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
+ i != theArgNames.size();
+ ++argIndex, ++i) {
+
+ argIndex->setName(theArgNames[i]);
+ namedValues[theArgNames[i]] = argIndex;
+ }
+
+ return(ret);
+}
+
+
+/// Create an alloca instruction in the entry block of
+/// the parent function. This is used for mutable variables etc.
+/// @param function parent instance
+/// @param varName stack variable name
+/// @param type stack variable type
+/// @param initWith optional constant initialization value
+/// @returns AllocaInst instance
+static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
+ const std::string &varName,
+ llvm::Type *type,
+ llvm::Constant *initWith = 0) {
+ llvm::BasicBlock &block = function.getEntryBlock();
+ llvm::IRBuilder<> tmp(&block, block.begin());
+ llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
+
+ if (initWith)
+ tmp.CreateStore(initWith, ret);
+
+ return(ret);
+}
+
+
+//
+// Code Generation Utilities End
+//
+
+//
+// Runtime C Library functions
+//
+
+// Note: using an extern "C" block so that static functions can be used
+extern "C" {
+
+// Note: Better ways to decide on bit width
+//
+/// Prints a 32 bit number, according to the format, to stderr.
+/// @param intToPrint integer to print
+/// @param format printf like format to use when printing
+void print32Int(int intToPrint, const char *format) {
+ if (format) {
+ // Note: No NULL check
+ fprintf(stderr, format, intToPrint);
+ }
+ else {
+ // Note: No NULL check
+ fprintf(stderr, "::print32Int(...):NULL arg.\n");
+ }
+}
+
+
+// Note: Better ways to decide on bit width
+//
+/// Prints a 64 bit number, according to the format, to stderr.
+/// @param intToPrint integer to print
+/// @param format printf like format to use when printing
+void print64Int(long int intToPrint, const char *format) {
+ if (format) {
+ // Note: No NULL check
+ fprintf(stderr, format, intToPrint);
+ }
+ else {
+ // Note: No NULL check
+ fprintf(stderr, "::print64Int(...):NULL arg.\n");
+ }
+}
+
+
+/// Prints a C string to stderr
+/// @param toPrint string to print
+void printStr(char *toPrint) {
+ if (toPrint) {
+ fprintf(stderr, "%s", toPrint);
+ }
+ else {
+ fprintf(stderr, "::printStr(...):NULL arg.\n");
+ }
+}
+
+
+/// Deletes the true previosly allocated exception whose address
+/// is calculated from the supplied OurBaseException_t::unwindException
+/// member address. Handles (ignores), NULL pointers.
+/// @param expToDelete exception to delete
+void deleteOurException(OurUnwindException *expToDelete) {
+#ifdef DEBUG
+ fprintf(stderr,
+ "deleteOurException(...).\n");
+#endif
+
+ if (expToDelete &&
+ (expToDelete->exception_class == ourBaseExceptionClass)) {
+
+ free(((char*) expToDelete) + ourBaseFromUnwindOffset);
+ }
+}
+
+
+/// This function is the struct _Unwind_Exception API mandated delete function
+/// used by foreign exception handlers when deleting our exception
+/// (OurException), instances.
+/// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
+/// @unlink
+/// @param expToDelete exception instance to delete
+void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
+ OurUnwindException *expToDelete) {
+#ifdef DEBUG
+ fprintf(stderr,
+ "deleteFromUnwindOurException(...).\n");
+#endif
+
+ deleteOurException(expToDelete);
+}
+
+
+/// Creates (allocates on the heap), an exception (OurException instance),
+/// of the supplied type info type.
+/// @param type type info type
+OurUnwindException *createOurException(int type) {
+ size_t size = sizeof(OurException);
+ OurException *ret = (OurException*) memset(malloc(size), 0, size);
+ (ret->type).type = type;
+ (ret->unwindException).exception_class = ourBaseExceptionClass;
+ (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
+
+ return(&(ret->unwindException));
+}
+
+
+/// Read a uleb128 encoded value and advance pointer
+/// See Variable Length Data in:
+/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
+/// @param data reference variable holding memory pointer to decode from
+/// @returns decoded value
+static uintptr_t readULEB128(const uint8_t **data) {
+ uintptr_t result = 0;
+ uintptr_t shift = 0;
+ unsigned char byte;
+ const uint8_t *p = *data;
+
+ do {
+ byte = *p++;
+ result |= (byte & 0x7f) << shift;
+ shift += 7;
+ }
+ while (byte & 0x80);
+
+ *data = p;
+
+ return result;
+}
+
+
+/// Read a sleb128 encoded value and advance pointer
+/// See Variable Length Data in:
+/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
+/// @param data reference variable holding memory pointer to decode from
+/// @returns decoded value
+static uintptr_t readSLEB128(const uint8_t **data) {
+ uintptr_t result = 0;
+ uintptr_t shift = 0;
+ unsigned char byte;
+ const uint8_t *p = *data;
+
+ do {
+ byte = *p++;
+ result |= (byte & 0x7f) << shift;
+ shift += 7;
+ }
+ while (byte & 0x80);
+
+ *data = p;
+
+ if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
+ result |= (~0 << shift);
+ }
+
+ return result;
+}
+
+
+/// Read a pointer encoded value and advance pointer
+/// See Variable Length Data in:
+/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
+/// @param data reference variable holding memory pointer to decode from
+/// @param encoding dwarf encoding type
+/// @returns decoded value
+static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
+ uintptr_t result = 0;
+ const uint8_t *p = *data;
+
+ if (encoding == llvm::dwarf::DW_EH_PE_omit)
+ return(result);
+
+ // first get value
+ switch (encoding & 0x0F) {
+ case llvm::dwarf::DW_EH_PE_absptr:
+ result = *((uintptr_t*)p);
+ p += sizeof(uintptr_t);
+ break;
+ case llvm::dwarf::DW_EH_PE_uleb128:
+ result = readULEB128(&p);
+ break;
+ // Note: This case has not been tested
+ case llvm::dwarf::DW_EH_PE_sleb128:
+ result = readSLEB128(&p);
+ break;
+ case llvm::dwarf::DW_EH_PE_udata2:
+ result = *((uint16_t*)p);
+ p += sizeof(uint16_t);
+ break;
+ case llvm::dwarf::DW_EH_PE_udata4:
+ result = *((uint32_t*)p);
+ p += sizeof(uint32_t);
+ break;
+ case llvm::dwarf::DW_EH_PE_udata8:
+ result = *((uint64_t*)p);
+ p += sizeof(uint64_t);
+ break;
+ case llvm::dwarf::DW_EH_PE_sdata2:
+ result = *((int16_t*)p);
+ p += sizeof(int16_t);
+ break;
+ case llvm::dwarf::DW_EH_PE_sdata4:
+ result = *((int32_t*)p);
+ p += sizeof(int32_t);
+ break;
+ case llvm::dwarf::DW_EH_PE_sdata8:
+ result = *((int64_t*)p);
+ p += sizeof(int64_t);
+ break;
+ default:
+ // not supported
+ abort();
+ break;
+ }
+
+ // then add relative offset
+ switch (encoding & 0x70) {
+ case llvm::dwarf::DW_EH_PE_absptr:
+ // do nothing
+ break;
+ case llvm::dwarf::DW_EH_PE_pcrel:
+ result += (uintptr_t)(*data);
+ break;
+ case llvm::dwarf::DW_EH_PE_textrel:
+ case llvm::dwarf::DW_EH_PE_datarel:
+ case llvm::dwarf::DW_EH_PE_funcrel:
+ case llvm::dwarf::DW_EH_PE_aligned:
+ default:
+ // not supported
+ abort();
+ break;
+ }
+
+ // then apply indirection
+ if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
+ result = *((uintptr_t*)result);
+ }
+
+ *data = p;
+
+ return result;
+}
+
+
+/// Deals with Dwarf actions matching our type infos
+/// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
+/// action matches the supplied exception type. If such a match succeeds,
+/// the resultAction argument will be set with > 0 index value. Only
+/// corresponding llvm.eh.selector type info arguments, cleanup arguments
+/// are supported. Filters are not supported.
+/// See Variable Length Data in:
+/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
+/// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
+/// @param resultAction reference variable which will be set with result
+/// @param classInfo our array of type info pointers (to globals)
+/// @param actionEntry index into above type info array or 0 (clean up).
+/// We do not support filters.
+/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
+/// of thrown exception.
+/// @param exceptionObject thrown _Unwind_Exception instance.
+/// @returns whether or not a type info was found. False is returned if only
+/// a cleanup was found
+static bool handleActionValue(int64_t *resultAction,
+ struct OurExceptionType_t **classInfo,
+ uintptr_t actionEntry,
+ uint64_t exceptionClass,
+ struct _Unwind_Exception *exceptionObject) {
+ bool ret = false;
+
+ if (!resultAction ||
+ !exceptionObject ||
+ (exceptionClass != ourBaseExceptionClass))
+ return(ret);
+
+ struct OurBaseException_t *excp = (struct OurBaseException_t*)
+ (((char*) exceptionObject) + ourBaseFromUnwindOffset);
+ struct OurExceptionType_t *excpType = &(excp->type);
+ int type = excpType->type;
+
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleActionValue(...): exceptionObject = <%p>, "
+ "excp = <%p>.\n",
+ exceptionObject,
+ excp);
+#endif
+
+ const uint8_t *actionPos = (uint8_t*) actionEntry,
+ *tempActionPos;
+ int64_t typeOffset = 0,
+ actionOffset;
+
+ for (int i = 0; true; ++i) {
+ // Each emitted dwarf action corresponds to a 2 tuple of
+ // type info address offset, and action offset to the next
+ // emitted action.
+ typeOffset = readSLEB128(&actionPos);
+ tempActionPos = actionPos;
+ actionOffset = readSLEB128(&tempActionPos);
+
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleActionValue(...):typeOffset: <%lld>, "
+ "actionOffset: <%lld>.\n",
+ typeOffset,
+ actionOffset);
+#endif
+ assert((typeOffset >= 0) &&
+ "handleActionValue(...):filters are not supported.");
+
+ // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
+ // argument has been matched.
+ if ((typeOffset > 0) &&
+ (type == (classInfo[-typeOffset])->type)) {
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleActionValue(...):actionValue <%d> found.\n",
+ i);
+#endif
+ *resultAction = i + 1;
+ ret = true;
+ break;
+ }
+
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleActionValue(...):actionValue not found.\n");
+#endif
+ if (!actionOffset)
+ break;
+
+ actionPos += actionOffset;
+ }
+
+ return(ret);
+}
+
+
+/// Deals with the Language specific data portion of the emitted dwarf code.
+/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
+/// @param version unsupported (ignored), unwind version
+/// @param lsda language specific data area
+/// @param _Unwind_Action actions minimally supported unwind stage
+/// (forced specifically not supported)
+/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
+/// of thrown exception.
+/// @param exceptionObject thrown _Unwind_Exception instance.
+/// @param context unwind system context
+/// @returns minimally supported unwinding control indicator
+static _Unwind_Reason_Code handleLsda(int version,
+ const uint8_t *lsda,
+ _Unwind_Action actions,
+ uint64_t exceptionClass,
+ struct _Unwind_Exception *exceptionObject,
+ _Unwind_Context_t context) {
+ _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
+
+ if (!lsda)
+ return(ret);
+
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleLsda(...):lsda is non-zero.\n");
+#endif
+
+ // Get the current instruction pointer and offset it before next
+ // instruction in the current frame which threw the exception.
+ uintptr_t pc = _Unwind_GetIP(context)-1;
+
+ // Get beginning current frame's code (as defined by the
+ // emitted dwarf code)
+ uintptr_t funcStart = _Unwind_GetRegionStart(context);
+ uintptr_t pcOffset = pc - funcStart;
+ struct OurExceptionType_t **classInfo = NULL;
+
+ // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
+ // dwarf emission
+
+ // Parse LSDA header.
+ uint8_t lpStartEncoding = *lsda++;
+
+ if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
+ readEncodedPointer(&lsda, lpStartEncoding);
+ }
+
+ uint8_t ttypeEncoding = *lsda++;
+ uintptr_t classInfoOffset;
+
+ if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
+ // Calculate type info locations in emitted dwarf code which
+ // were flagged by type info arguments to llvm.eh.selector
+ // intrinsic
+ classInfoOffset = readULEB128(&lsda);
+ classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
+ }
+
+ // Walk call-site table looking for range that
+ // includes current PC.
+
+ uint8_t callSiteEncoding = *lsda++;
+ uint32_t callSiteTableLength = readULEB128(&lsda);
+ const uint8_t *callSiteTableStart = lsda;
+ const uint8_t *callSiteTableEnd = callSiteTableStart +
+ callSiteTableLength;
+ const uint8_t *actionTableStart = callSiteTableEnd;
+ const uint8_t *callSitePtr = callSiteTableStart;
+
+ bool foreignException = false;
+
+ while (callSitePtr < callSiteTableEnd) {
+ uintptr_t start = readEncodedPointer(&callSitePtr,
+ callSiteEncoding);
+ uintptr_t length = readEncodedPointer(&callSitePtr,
+ callSiteEncoding);
+ uintptr_t landingPad = readEncodedPointer(&callSitePtr,
+ callSiteEncoding);
+
+ // Note: Action value
+ uintptr_t actionEntry = readULEB128(&callSitePtr);
+
+ if (exceptionClass != ourBaseExceptionClass) {
+ // We have been notified of a foreign exception being thrown,
+ // and we therefore need to execute cleanup landing pads
+ actionEntry = 0;
+ foreignException = true;
+ }
+
+ if (landingPad == 0) {
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleLsda(...): No landing pad found.\n");
+#endif
+
+ continue; // no landing pad for this entry
+ }
+
+ if (actionEntry) {
+ actionEntry += ((uintptr_t) actionTableStart) - 1;
+ }
+ else {
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleLsda(...):No action table found.\n");
+#endif
+ }
+
+ bool exceptionMatched = false;
+
+ if ((start <= pcOffset) && (pcOffset < (start + length))) {
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleLsda(...): Landing pad found.\n");
+#endif
+ int64_t actionValue = 0;
+
+ if (actionEntry) {
+ exceptionMatched = handleActionValue(&actionValue,
+ classInfo,
+ actionEntry,
+ exceptionClass,
+ exceptionObject);
+ }
+
+ if (!(actions & _UA_SEARCH_PHASE)) {
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleLsda(...): installed landing pad "
+ "context.\n");
+#endif
+
+ // Found landing pad for the PC.
+ // Set Instruction Pointer to so we re-enter function
+ // at landing pad. The landing pad is created by the
+ // compiler to take two parameters in registers.
+ _Unwind_SetGR(context,
+ __builtin_eh_return_data_regno(0),
+ (uintptr_t)exceptionObject);
+
+ // Note: this virtual register directly corresponds
+ // to the return of the llvm.eh.selector intrinsic
+ if (!actionEntry || !exceptionMatched) {
+ // We indicate cleanup only
+ _Unwind_SetGR(context,
+ __builtin_eh_return_data_regno(1),
+ 0);
+ }
+ else {
+ // Matched type info index of llvm.eh.selector intrinsic
+ // passed here.
+ _Unwind_SetGR(context,
+ __builtin_eh_return_data_regno(1),
+ actionValue);
+ }
+
+ // To execute landing pad set here
+ _Unwind_SetIP(context, funcStart + landingPad);
+ ret = _URC_INSTALL_CONTEXT;
+ }
+ else if (exceptionMatched) {
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleLsda(...): setting handler found.\n");
+#endif
+ ret = _URC_HANDLER_FOUND;
+ }
+ else {
+ // Note: Only non-clean up handlers are marked as
+ // found. Otherwise the clean up handlers will be
+ // re-found and executed during the clean up
+ // phase.
+#ifdef DEBUG
+ fprintf(stderr,
+ "handleLsda(...): cleanup handler found.\n");
+#endif
+ }
+
+ break;
+ }
+ }
+
+ return(ret);
+}
+
+
+/// This is the personality function which is embedded (dwarf emitted), in the
+/// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
+/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
+/// @param version unsupported (ignored), unwind version
+/// @param _Unwind_Action actions minimally supported unwind stage
+/// (forced specifically not supported)
+/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
+/// of thrown exception.
+/// @param exceptionObject thrown _Unwind_Exception instance.
+/// @param context unwind system context
+/// @returns minimally supported unwinding control indicator
+_Unwind_Reason_Code ourPersonality(int version,
+ _Unwind_Action actions,
+ uint64_t exceptionClass,
+ struct _Unwind_Exception *exceptionObject,
+ _Unwind_Context_t context) {
+#ifdef DEBUG
+ fprintf(stderr,
+ "We are in ourPersonality(...):actions is <%d>.\n",
+ actions);
+
+ if (actions & _UA_SEARCH_PHASE) {
+ fprintf(stderr, "ourPersonality(...):In search phase.\n");
+ }
+ else {
+ fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
+ }
+#endif
+
+ const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
+
+#ifdef DEBUG
+ fprintf(stderr,
+ "ourPersonality(...):lsda = <%p>.\n",
+ lsda);
+#endif
+
+ // The real work of the personality function is captured here
+ return(handleLsda(version,
+ lsda,
+ actions,
+ exceptionClass,
+ exceptionObject,
+ context));
+}
+
+
+/// Generates our _Unwind_Exception class from a given character array.
+/// thereby handling arbitrary lengths (not in standard), and handling
+/// embedded \0s.
+/// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
+/// @param classChars char array to encode. NULL values not checkedf
+/// @param classCharsSize number of chars in classChars. Value is not checked.
+/// @returns class value
+uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
+{
+ uint64_t ret = classChars[0];
+
+ for (unsigned i = 1; i < classCharsSize; ++i) {
+ ret <<= 8;
+ ret += classChars[i];
+ }
+
+ return(ret);
+}
+
+} // extern "C"
+
+//
+// Runtime C Library functions End
+//
+
+//
+// Code generation functions
+//
+
+/// Generates code to print given constant string
+/// @param context llvm context
+/// @param module code for module instance
+/// @param builder builder instance
+/// @param toPrint string to print
+/// @param useGlobal A value of true (default) indicates a GlobalValue is
+/// generated, and is used to hold the constant string. A value of
+/// false indicates that the constant string will be stored on the
+/// stack.
+void generateStringPrint(llvm::LLVMContext &context,
+ llvm::Module &module,
+ llvm::IRBuilder<> &builder,
+ std::string toPrint,
+ bool useGlobal = true) {
+ llvm::Function *printFunct = module.getFunction("printStr");
+
+ llvm::Value *stringVar;
+ llvm::Constant *stringConstant =
+ llvm::ConstantDataArray::getString(context, toPrint);
+
+ if (useGlobal) {
+ // Note: Does not work without allocation
+ stringVar =
+ new llvm::GlobalVariable(module,
+ stringConstant->getType(),
+ true,
+ llvm::GlobalValue::LinkerPrivateLinkage,
+ stringConstant,
+ "");
+ }
+ else {
+ stringVar = builder.CreateAlloca(stringConstant->getType());
+ builder.CreateStore(stringConstant, stringVar);
+ }
+
+ llvm::Value *cast = builder.CreatePointerCast(stringVar,
+ builder.getInt8PtrTy());
+ builder.CreateCall(printFunct, cast);
+}
+
+
+/// Generates code to print given runtime integer according to constant
+/// string format, and a given print function.
+/// @param context llvm context
+/// @param module code for module instance
+/// @param builder builder instance
+/// @param printFunct function used to "print" integer
+/// @param toPrint string to print
+/// @param format printf like formating string for print
+/// @param useGlobal A value of true (default) indicates a GlobalValue is
+/// generated, and is used to hold the constant string. A value of
+/// false indicates that the constant string will be stored on the
+/// stack.
+void generateIntegerPrint(llvm::LLVMContext &context,
+ llvm::Module &module,
+ llvm::IRBuilder<> &builder,
+ llvm::Function &printFunct,
+ llvm::Value &toPrint,
+ std::string format,
+ bool useGlobal = true) {
+ llvm::Constant *stringConstant =
+ llvm::ConstantDataArray::getString(context, format);
+ llvm::Value *stringVar;
+
+ if (useGlobal) {
+ // Note: Does not seem to work without allocation
+ stringVar =
+ new llvm::GlobalVariable(module,
+ stringConstant->getType(),
+ true,
+ llvm::GlobalValue::LinkerPrivateLinkage,
+ stringConstant,
+ "");
+ }
+ else {
+ stringVar = builder.CreateAlloca(stringConstant->getType());
+ builder.CreateStore(stringConstant, stringVar);
+ }
+
+ llvm::Value *cast = builder.CreateBitCast(stringVar,
+ builder.getInt8PtrTy());
+ builder.CreateCall2(&printFunct, &toPrint, cast);
+}
+
+
+/// Generates code to handle finally block type semantics: always runs
+/// regardless of whether a thrown exception is passing through or the
+/// parent function is simply exiting. In addition to printing some state
+/// to stderr, this code will resume the exception handling--runs the
+/// unwind resume block, if the exception has not been previously caught
+/// by a catch clause, and will otherwise execute the end block (terminator
+/// block). In addition this function creates the corresponding function's
+/// stack storage for the exception pointer and catch flag status.
+/// @param context llvm context
+/// @param module code for module instance
+/// @param builder builder instance
+/// @param toAddTo parent function to add block to
+/// @param blockName block name of new "finally" block.
+/// @param functionId output id used for printing
+/// @param terminatorBlock terminator "end" block
+/// @param unwindResumeBlock unwind resume block
+/// @param exceptionCaughtFlag reference exception caught/thrown status storage
+/// @param exceptionStorage reference to exception pointer storage
+/// @param caughtResultStorage reference to landingpad result storage
+/// @returns newly created block
+static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
+ llvm::Module &module,
+ llvm::IRBuilder<> &builder,
+ llvm::Function &toAddTo,
+ std::string &blockName,
+ std::string &functionId,
+ llvm::BasicBlock &terminatorBlock,
+ llvm::BasicBlock &unwindResumeBlock,
+ llvm::Value **exceptionCaughtFlag,
+ llvm::Value **exceptionStorage,
+ llvm::Value **caughtResultStorage) {
+ assert(exceptionCaughtFlag &&
+ "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
+ "is NULL");
+ assert(exceptionStorage &&
+ "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
+ "is NULL");
+ assert(caughtResultStorage &&
+ "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
+ "is NULL");
+
+ *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
+ "exceptionCaught",
+ ourExceptionNotThrownState->getType(),
+ ourExceptionNotThrownState);
+
+ llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
+ *exceptionStorage = createEntryBlockAlloca(toAddTo,
+ "exceptionStorage",
+ exceptionStorageType,
+ llvm::ConstantPointerNull::get(
+ exceptionStorageType));
+ *caughtResultStorage = createEntryBlockAlloca(toAddTo,
+ "caughtResultStorage",
+ ourCaughtResultType,
+ llvm::ConstantAggregateZero::get(
+ ourCaughtResultType));
+
+ llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
+ blockName,
+ &toAddTo);
+
+ builder.SetInsertPoint(ret);
+
+ std::ostringstream bufferToPrint;
+ bufferToPrint << "Gen: Executing finally block "
+ << blockName << " in " << functionId << "\n";
+ generateStringPrint(context,
+ module,
+ builder,
+ bufferToPrint.str(),
+ USE_GLOBAL_STR_CONSTS);
+
+ llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
+ *exceptionCaughtFlag),
+ &terminatorBlock,
+ 2);
+ theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
+ theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
+
+ return(ret);
+}
+
+
+/// Generates catch block semantics which print a string to indicate type of
+/// catch executed, sets an exception caught flag, and executes passed in
+/// end block (terminator block).
+/// @param context llvm context
+/// @param module code for module instance
+/// @param builder builder instance
+/// @param toAddTo parent function to add block to
+/// @param blockName block name of new "catch" block.
+/// @param functionId output id used for printing
+/// @param terminatorBlock terminator "end" block
+/// @param exceptionCaughtFlag exception caught/thrown status
+/// @returns newly created block
+static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
+ llvm::Module &module,
+ llvm::IRBuilder<> &builder,
+ llvm::Function &toAddTo,
+ std::string &blockName,
+ std::string &functionId,
+ llvm::BasicBlock &terminatorBlock,
+ llvm::Value &exceptionCaughtFlag) {
+
+ llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
+ blockName,
+ &toAddTo);
+
+ builder.SetInsertPoint(ret);
+
+ std::ostringstream bufferToPrint;
+ bufferToPrint << "Gen: Executing catch block "
+ << blockName
+ << " in "
+ << functionId
+ << std::endl;
+ generateStringPrint(context,
+ module,
+ builder,
+ bufferToPrint.str(),
+ USE_GLOBAL_STR_CONSTS);
+ builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
+ builder.CreateBr(&terminatorBlock);
+
+ return(ret);
+}
+
+
+/// Generates a function which invokes a function (toInvoke) and, whose
+/// unwind block will "catch" the type info types correspondingly held in the
+/// exceptionTypesToCatch argument. If the toInvoke function throws an
+/// exception which does not match any type info types contained in
+/// exceptionTypesToCatch, the generated code will call _Unwind_Resume
+/// with the raised exception. On the other hand the generated code will
+/// normally exit if the toInvoke function does not throw an exception.
+/// The generated "finally" block is always run regardless of the cause of
+/// the generated function exit.
+/// The generated function is returned after being verified.
+/// @param module code for module instance
+/// @param builder builder instance
+/// @param fpm a function pass manager holding optional IR to IR
+/// transformations
+/// @param toInvoke inner function to invoke
+/// @param ourId id used to printing purposes
+/// @param numExceptionsToCatch length of exceptionTypesToCatch array
+/// @param exceptionTypesToCatch array of type info types to "catch"
+/// @returns generated function
+static
+llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
+ llvm::IRBuilder<> &builder,
+ llvm::FunctionPassManager &fpm,
+ llvm::Function &toInvoke,
+ std::string ourId,
+ unsigned numExceptionsToCatch,
+ unsigned exceptionTypesToCatch[]) {
+
+ llvm::LLVMContext &context = module.getContext();
+ llvm::Function *toPrint32Int = module.getFunction("print32Int");
+
+ ArgTypes argTypes;
+ argTypes.push_back(builder.getInt32Ty());
+
+ ArgNames argNames;
+ argNames.push_back("exceptTypeToThrow");
+
+ llvm::Function *ret = createFunction(module,
+ builder.getVoidTy(),
+ argTypes,
+ argNames,
+ ourId,
+ llvm::Function::ExternalLinkage,
+ false,
+ false);
+
+ // Block which calls invoke
+ llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
+ "entry",
+ ret);
+ // Normal block for invoke
+ llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
+ "normal",
+ ret);
+ // Unwind block for invoke
+ llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
+ "exception",
+ ret);
+
+ // Block which routes exception to correct catch handler block
+ llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
+ "exceptionRoute",
+ ret);
+
+ // Foreign exception handler
+ llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
+ "externalException",
+ ret);
+
+ // Block which calls _Unwind_Resume
+ llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
+ "unwindResume",
+ ret);
+
+ // Clean up block which delete exception if needed
+ llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
+
+ std::string nextName;
+ std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
+ llvm::Value *exceptionCaughtFlag = NULL;
+ llvm::Value *exceptionStorage = NULL;
+ llvm::Value *caughtResultStorage = NULL;
+
+ // Finally block which will branch to unwindResumeBlock if
+ // exception is not caught. Initializes/allocates stack locations.
+ llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
+ module,
+ builder,
+ *ret,
+ nextName = "finally",
+ ourId,
+ *endBlock,
+ *unwindResumeBlock,
+ &exceptionCaughtFlag,
+ &exceptionStorage,
+ &caughtResultStorage
+ );
+
+ for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
+ nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
+
+ // One catch block per type info to be caught
+ catchBlocks[i] = createCatchBlock(context,
+ module,
+ builder,
+ *ret,
+ nextName,
+ ourId,
+ *finallyBlock,
+ *exceptionCaughtFlag);
+ }
+
+ // Entry Block
+
+ builder.SetInsertPoint(entryBlock);
+
+ std::vector<llvm::Value*> args;
+ args.push_back(namedValues["exceptTypeToThrow"]);
+ builder.CreateInvoke(&toInvoke,
+ normalBlock,
+ exceptionBlock,
+ args);
+
+ // End Block
+
+ builder.SetInsertPoint(endBlock);
+
+ generateStringPrint(context,
+ module,
+ builder,
+ "Gen: In end block: exiting in " + ourId + ".\n",
+ USE_GLOBAL_STR_CONSTS);
+ llvm::Function *deleteOurException = module.getFunction("deleteOurException");
+
+ // Note: function handles NULL exceptions
+ builder.CreateCall(deleteOurException,
+ builder.CreateLoad(exceptionStorage));
+ builder.CreateRetVoid();
+
+ // Normal Block
+
+ builder.SetInsertPoint(normalBlock);
+
+ generateStringPrint(context,
+ module,
+ builder,
+ "Gen: No exception in " + ourId + "!\n",
+ USE_GLOBAL_STR_CONSTS);
+
+ // Finally block is always called
+ builder.CreateBr(finallyBlock);
+
+ // Unwind Resume Block
+
+ builder.SetInsertPoint(unwindResumeBlock);
+
+ builder.CreateResume(builder.CreateLoad(caughtResultStorage));
+
+ // Exception Block
+
+ builder.SetInsertPoint(exceptionBlock);
+
+ llvm::Function *personality = module.getFunction("ourPersonality");
+
+ llvm::LandingPadInst *caughtResult =
+ builder.CreateLandingPad(ourCaughtResultType,
+ personality,
+ numExceptionsToCatch,
+ "landingPad");
+
+ caughtResult->setCleanup(true);
+
+ for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
+ // Set up type infos to be caught
+ caughtResult->addClause(module.getGlobalVariable(
+ ourTypeInfoNames[exceptionTypesToCatch[i]]));
+ }
+
+ llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
+ llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
+
+ // FIXME: Redundant storage which, beyond utilizing value of
+ // caughtResultStore for unwindException storage, may be alleviated
+ // altogether with a block rearrangement
+ builder.CreateStore(caughtResult, caughtResultStorage);
+ builder.CreateStore(unwindException, exceptionStorage);
+ builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
+
+ // Retrieve exception_class member from thrown exception
+ // (_Unwind_Exception instance). This member tells us whether or not
+ // the exception is foreign.
+ llvm::Value *unwindExceptionClass =
+ builder.CreateLoad(builder.CreateStructGEP(
+ builder.CreatePointerCast(unwindException,
+ ourUnwindExceptionType->getPointerTo()),
+ 0));
+
+ // Branch to the externalExceptionBlock if the exception is foreign or
+ // to a catch router if not. Either way the finally block will be run.
+ builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
+ llvm::ConstantInt::get(builder.getInt64Ty(),
+ ourBaseExceptionClass)),
+ exceptionRouteBlock,
+ externalExceptionBlock);
+
+ // External Exception Block
+
+ builder.SetInsertPoint(externalExceptionBlock);
+
+ generateStringPrint(context,
+ module,
+ builder,
+ "Gen: Foreign exception received.\n",
+ USE_GLOBAL_STR_CONSTS);
+
+ // Branch to the finally block
+ builder.CreateBr(finallyBlock);
+
+ // Exception Route Block
+
+ builder.SetInsertPoint(exceptionRouteBlock);
+
+ // Casts exception pointer (_Unwind_Exception instance) to parent
+ // (OurException instance).
+ //
+ // Note: ourBaseFromUnwindOffset is usually negative
+ llvm::Value *typeInfoThrown = builder.CreatePointerCast(
+ builder.CreateConstGEP1_64(unwindException,
+ ourBaseFromUnwindOffset),
+ ourExceptionType->getPointerTo());
+
+ // Retrieve thrown exception type info type
+ //
+ // Note: Index is not relative to pointer but instead to structure
+ // unlike a true getelementptr (GEP) instruction
+ typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
+
+ llvm::Value *typeInfoThrownType =
+ builder.CreateStructGEP(typeInfoThrown, 0);
+
+ generateIntegerPrint(context,
+ module,
+ builder,
+ *toPrint32Int,
+ *(builder.CreateLoad(typeInfoThrownType)),
+ "Gen: Exception type <%d> received (stack unwound) "
+ " in " +
+ ourId +
+ ".\n",
+ USE_GLOBAL_STR_CONSTS);
+
+ // Route to matched type info catch block or run cleanup finally block
+ llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,
+ finallyBlock,
+ numExceptionsToCatch);
+
+ unsigned nextTypeToCatch;
+
+ for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
+ nextTypeToCatch = i - 1;
+ switchToCatchBlock->addCase(llvm::ConstantInt::get(
+ llvm::Type::getInt32Ty(context), i),
+ catchBlocks[nextTypeToCatch]);
+ }
+
+ llvm::verifyFunction(*ret);
+ fpm.run(*ret);
+
+ return(ret);
+}
+
+
+/// Generates function which throws either an exception matched to a runtime
+/// determined type info type (argument to generated function), or if this
+/// runtime value matches nativeThrowType, throws a foreign exception by
+/// calling nativeThrowFunct.
+/// @param module code for module instance
+/// @param builder builder instance
+/// @param fpm a function pass manager holding optional IR to IR
+/// transformations
+/// @param ourId id used to printing purposes
+/// @param nativeThrowType a runtime argument of this value results in
+/// nativeThrowFunct being called to generate/throw exception.
+/// @param nativeThrowFunct function which will throw a foreign exception
+/// if the above nativeThrowType matches generated function's arg.
+/// @returns generated function
+static
+llvm::Function *createThrowExceptionFunction(llvm::Module &module,
+ llvm::IRBuilder<> &builder,
+ llvm::FunctionPassManager &fpm,
+ std::string ourId,
+ int32_t nativeThrowType,
+ llvm::Function &nativeThrowFunct) {
+ llvm::LLVMContext &context = module.getContext();
+ namedValues.clear();
+ ArgTypes unwindArgTypes;
+ unwindArgTypes.push_back(builder.getInt32Ty());
+ ArgNames unwindArgNames;
+ unwindArgNames.push_back("exceptTypeToThrow");
+
+ llvm::Function *ret = createFunction(module,
+ builder.getVoidTy(),
+ unwindArgTypes,
+ unwindArgNames,
+ ourId,
+ llvm::Function::ExternalLinkage,
+ false,
+ false);
+
+ // Throws either one of our exception or a native C++ exception depending
+ // on a runtime argument value containing a type info type.
+ llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
+ "entry",
+ ret);
+ // Throws a foreign exception
+ llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
+ "nativeThrow",
+ ret);
+ // Throws one of our Exceptions
+ llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
+ "generatedThrow",
+ ret);
+ // Retrieved runtime type info type to throw
+ llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
+
+ // nativeThrowBlock block
+
+ builder.SetInsertPoint(nativeThrowBlock);
+
+ // Throws foreign exception
+ builder.CreateCall(&nativeThrowFunct, exceptionType);
+ builder.CreateUnreachable();
+
+ // entry block
+
+ builder.SetInsertPoint(entryBlock);
+
+ llvm::Function *toPrint32Int = module.getFunction("print32Int");
+ generateIntegerPrint(context,
+ module,
+ builder,
+ *toPrint32Int,
+ *exceptionType,
+ "\nGen: About to throw exception type <%d> in " +
+ ourId +
+ ".\n",
+ USE_GLOBAL_STR_CONSTS);
+
+ // Switches on runtime type info type value to determine whether or not
+ // a foreign exception is thrown. Defaults to throwing one of our
+ // generated exceptions.
+ llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
+ generatedThrowBlock,
+ 1);
+
+ theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
+ nativeThrowType),
+ nativeThrowBlock);
+
+ // generatedThrow block
+
+ builder.SetInsertPoint(generatedThrowBlock);
+
+ llvm::Function *createOurException = module.getFunction("createOurException");
+ llvm::Function *raiseOurException = module.getFunction(
+ "_Unwind_RaiseException");
+
+ // Creates exception to throw with runtime type info type.
+ llvm::Value *exception = builder.CreateCall(createOurException,
+ namedValues["exceptTypeToThrow"]);
+
+ // Throw generated Exception
+ builder.CreateCall(raiseOurException, exception);
+ builder.CreateUnreachable();
+
+ llvm::verifyFunction(*ret);
+ fpm.run(*ret);
+
+ return(ret);
+}
+
+static void createStandardUtilityFunctions(unsigned numTypeInfos,
+ llvm::Module &module,
+ llvm::IRBuilder<> &builder);
+
+/// Creates test code by generating and organizing these functions into the
+/// test case. The test case consists of an outer function setup to invoke
+/// an inner function within an environment having multiple catch and single
+/// finally blocks. This inner function is also setup to invoke a throw
+/// function within an evironment similar in nature to the outer function's
+/// catch and finally blocks. Each of these two functions catch mutually
+/// exclusive subsets (even or odd) of the type info types configured
+/// for this this. All generated functions have a runtime argument which
+/// holds a type info type to throw that each function takes and passes it
+/// to the inner one if such a inner function exists. This type info type is
+/// looked at by the generated throw function to see whether or not it should
+/// throw a generated exception with the same type info type, or instead call
+/// a supplied a function which in turn will throw a foreign exception.
+/// @param module code for module instance
+/// @param builder builder instance
+/// @param fpm a function pass manager holding optional IR to IR
+/// transformations
+/// @param nativeThrowFunctName name of external function which will throw
+/// a foreign exception
+/// @returns outermost generated test function.
+llvm::Function *createUnwindExceptionTest(llvm::Module &module,
+ llvm::IRBuilder<> &builder,
+ llvm::FunctionPassManager &fpm,
+ std::string nativeThrowFunctName) {
+ // Number of type infos to generate
+ unsigned numTypeInfos = 6;
+
+ // Initialze intrisics and external functions to use along with exception
+ // and type info globals.
+ createStandardUtilityFunctions(numTypeInfos,
+ module,
+ builder);
+ llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
+
+ // Create exception throw function using the value ~0 to cause
+ // foreign exceptions to be thrown.
+ llvm::Function *throwFunct = createThrowExceptionFunction(module,
+ builder,
+ fpm,
+ "throwFunct",
+ ~0,
+ *nativeThrowFunct);
+ // Inner function will catch even type infos
+ unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
+ size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
+ sizeof(unsigned);
+
+ // Generate inner function.
+ llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
+ builder,
+ fpm,
+ *throwFunct,
+ "innerCatchFunct",
+ numExceptionTypesToCatch,
+ innerExceptionTypesToCatch);
+
+ // Outer function will catch odd type infos
+ unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
+ numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
+ sizeof(unsigned);
+
+ // Generate outer function
+ llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
+ builder,
+ fpm,
+ *innerCatchFunct,
+ "outerCatchFunct",
+ numExceptionTypesToCatch,
+ outerExceptionTypesToCatch);
+
+ // Return outer function to run
+ return(outerCatchFunct);
+}
+
+
+/// Represents our foreign exceptions
+class OurCppRunException : public std::runtime_error {
+public:
+ OurCppRunException(const std::string reason) :
+ std::runtime_error(reason) {}
+
+ OurCppRunException (const OurCppRunException &toCopy) :
+ std::runtime_error(toCopy) {}
+
+ OurCppRunException &operator = (const OurCppRunException &toCopy) {
+ return(reinterpret_cast<OurCppRunException&>(
+ std::runtime_error::operator=(toCopy)));
+ }
+
+ ~OurCppRunException (void) throw () {}
+};
+
+
+/// Throws foreign C++ exception.
+/// @param ignoreIt unused parameter that allows function to match implied
+/// generated function contract.
+extern "C"
+void throwCppException (int32_t ignoreIt) {
+ throw(OurCppRunException("thrown by throwCppException(...)"));
+}
+
+typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
+
+/// This is a test harness which runs test by executing generated
+/// function with a type info type to throw. Harness wraps the execution
+/// of generated function in a C++ try catch clause.
+/// @param engine execution engine to use for executing generated function.
+/// This demo program expects this to be a JIT instance for demo
+/// purposes.
+/// @param function generated test function to run
+/// @param typeToThrow type info type of generated exception to throw, or
+/// indicator to cause foreign exception to be thrown.
+static
+void runExceptionThrow(llvm::ExecutionEngine *engine,
+ llvm::Function *function,
+ int32_t typeToThrow) {
+
+ // Find test's function pointer
+ OurExceptionThrowFunctType functPtr =
+ reinterpret_cast<OurExceptionThrowFunctType>(
+ reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
+
+ try {
+ // Run test
+ (*functPtr)(typeToThrow);
+ }
+ catch (OurCppRunException exc) {
+ // Catch foreign C++ exception
+ fprintf(stderr,
+ "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
+ "with reason: %s.\n",
+ exc.what());
+ }
+ catch (...) {
+ // Catch all exceptions including our generated ones. This latter
+ // functionality works according to the example in rules 1.6.4 of
+ // http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22),
+ // given that these will be exceptions foreign to C++
+ // (the _Unwind_Exception::exception_class should be different from
+ // the one used by C++).
+ fprintf(stderr,
+ "\nrunExceptionThrow(...):In C++ catch all.\n");
+ }
+}
+
+//
+// End test functions
+//
+
+typedef llvm::ArrayRef<llvm::Type*> TypeArray;
+
+/// This initialization routine creates type info globals and
+/// adds external function declarations to module.
+/// @param numTypeInfos number of linear type info associated type info types
+/// to create as GlobalVariable instances, starting with the value 1.
+/// @param module code for module instance
+/// @param builder builder instance
+static void createStandardUtilityFunctions(unsigned numTypeInfos,
+ llvm::Module &module,
+ llvm::IRBuilder<> &builder) {
+
+ llvm::LLVMContext &context = module.getContext();
+
+ // Exception initializations
+
+ // Setup exception catch state
+ ourExceptionNotThrownState =
+ llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
+ ourExceptionThrownState =
+ llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
+ ourExceptionCaughtState =
+ llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
+
+
+
+ // Create our type info type
+ ourTypeInfoType = llvm::StructType::get(context,
+ TypeArray(builder.getInt32Ty()));
+
+ llvm::Type *caughtResultFieldTypes[] = {
+ builder.getInt8PtrTy(),
+ builder.getInt32Ty()
+ };
+
+ // Create our landingpad result type
+ ourCaughtResultType = llvm::StructType::get(context,
+ TypeArray(caughtResultFieldTypes));
+
+ // Create OurException type
+ ourExceptionType = llvm::StructType::get(context,
+ TypeArray(ourTypeInfoType));
+
+ // Create portion of _Unwind_Exception type
+ //
+ // Note: Declaring only a portion of the _Unwind_Exception struct.
+ // Does this cause problems?
+ ourUnwindExceptionType =
+ llvm::StructType::get(context,
+ TypeArray(builder.getInt64Ty()));
+
+ struct OurBaseException_t dummyException;
+
+ // Calculate offset of OurException::unwindException member.
+ ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
+ ((uintptr_t) &(dummyException.unwindException));
+
+#ifdef DEBUG
+ fprintf(stderr,
+ "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
+ "= %lld, sizeof(struct OurBaseException_t) - "
+ "sizeof(struct _Unwind_Exception) = %lu.\n",
+ ourBaseFromUnwindOffset,
+ sizeof(struct OurBaseException_t) -
+ sizeof(struct _Unwind_Exception));
+#endif
+
+ size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
+
+ // Create our _Unwind_Exception::exception_class value
+ ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
+
+ // Type infos
+
+ std::string baseStr = "typeInfo", typeInfoName;
+ std::ostringstream typeInfoNameBuilder;
+ std::vector<llvm::Constant*> structVals;
+
+ llvm::Constant *nextStruct;
+ llvm::GlobalVariable *nextGlobal = NULL;
+
+ // Generate each type info
+ //
+ // Note: First type info is not used.
+ for (unsigned i = 0; i <= numTypeInfos; ++i) {
+ structVals.clear();
+ structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
+ nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
+
+ typeInfoNameBuilder.str("");
+ typeInfoNameBuilder << baseStr << i;
+ typeInfoName = typeInfoNameBuilder.str();
+
+ // Note: Does not seem to work without allocation
+ nextGlobal =
+ new llvm::GlobalVariable(module,
+ ourTypeInfoType,
+ true,
+ llvm::GlobalValue::ExternalLinkage,
+ nextStruct,
+ typeInfoName);
+
+ ourTypeInfoNames.push_back(typeInfoName);
+ ourTypeInfoNamesIndex[i] = typeInfoName;
+ }
+
+ ArgNames argNames;
+ ArgTypes argTypes;
+ llvm::Function *funct = NULL;
+
+ // print32Int
+
+ llvm::Type *retType = builder.getVoidTy();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt32Ty());
+ argTypes.push_back(builder.getInt8PtrTy());
+
+ argNames.clear();
+
+ createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "print32Int",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ // print64Int
+
+ retType = builder.getVoidTy();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt64Ty());
+ argTypes.push_back(builder.getInt8PtrTy());
+
+ argNames.clear();
+
+ createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "print64Int",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ // printStr
+
+ retType = builder.getVoidTy();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt8PtrTy());
+
+ argNames.clear();
+
+ createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "printStr",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ // throwCppException
+
+ retType = builder.getVoidTy();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt32Ty());
+
+ argNames.clear();
+
+ createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "throwCppException",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ // deleteOurException
+
+ retType = builder.getVoidTy();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt8PtrTy());
+
+ argNames.clear();
+
+ createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "deleteOurException",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ // createOurException
+
+ retType = builder.getInt8PtrTy();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt32Ty());
+
+ argNames.clear();
+
+ createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "createOurException",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ // _Unwind_RaiseException
+
+ retType = builder.getInt32Ty();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt8PtrTy());
+
+ argNames.clear();
+
+ funct = createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "_Unwind_RaiseException",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ funct->addFnAttr(llvm::Attribute::NoReturn);
+
+ // _Unwind_Resume
+
+ retType = builder.getInt32Ty();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt8PtrTy());
+
+ argNames.clear();
+
+ funct = createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "_Unwind_Resume",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ funct->addFnAttr(llvm::Attribute::NoReturn);
+
+ // ourPersonality
+
+ retType = builder.getInt32Ty();
+
+ argTypes.clear();
+ argTypes.push_back(builder.getInt32Ty());
+ argTypes.push_back(builder.getInt32Ty());
+ argTypes.push_back(builder.getInt64Ty());
+ argTypes.push_back(builder.getInt8PtrTy());
+ argTypes.push_back(builder.getInt8PtrTy());
+
+ argNames.clear();
+
+ createFunction(module,
+ retType,
+ argTypes,
+ argNames,
+ "ourPersonality",
+ llvm::Function::ExternalLinkage,
+ true,
+ false);
+
+ // llvm.eh.typeid.for intrinsic
+
+ getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
+}
+
+
+//===----------------------------------------------------------------------===//
+// Main test driver code.
+//===----------------------------------------------------------------------===//
+
+/// Demo main routine which takes the type info types to throw. A test will
+/// be run for each given type info type. While type info types with the value
+/// of -1 will trigger a foreign C++ exception to be thrown; type info types
+/// <= 6 and >= 1 will be caught by test functions; and type info types > 6
+/// will result in exceptions which pass through to the test harness. All other
+/// type info types are not supported and could cause a crash.
+int main(int argc, char *argv[]) {
+ if (argc == 1) {
+ fprintf(stderr,
+ "\nUsage: ExceptionDemo <exception type to throw> "
+ "[<type 2>...<type n>].\n"
+ " Each type must have the value of 1 - 6 for "
+ "generated exceptions to be caught;\n"
+ " the value -1 for foreign C++ exceptions to be "
+ "generated and thrown;\n"
+ " or the values > 6 for exceptions to be ignored.\n"
+ "\nTry: ExceptionDemo 2 3 7 -1\n"
+ " for a full test.\n\n");
+ return(0);
+ }
+
+ // If not set, exception handling will not be turned on
+ llvm::TargetOptions Opts;
+ Opts.JITExceptionHandling = true;
+
+ llvm::InitializeNativeTarget();
+ llvm::LLVMContext &context = llvm::getGlobalContext();
+ llvm::IRBuilder<> theBuilder(context);
+
+ // Make the module, which holds all the code.
+ llvm::Module *module = new llvm::Module("my cool jit", context);
+
+ // Build engine with JIT
+ llvm::EngineBuilder factory(module);
+ factory.setEngineKind(llvm::EngineKind::JIT);
+ factory.setAllocateGVsWithCode(false);
+ factory.setTargetOptions(Opts);
+ llvm::ExecutionEngine *executionEngine = factory.create();
+
+ {
+ llvm::FunctionPassManager fpm(module);
+
+ // Set up the optimizer pipeline.
+ // Start with registering info about how the
+ // target lays out data structures.
+ fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
+
+ // Optimizations turned on
+#ifdef ADD_OPT_PASSES
+
+ // Basic AliasAnslysis support for GVN.
+ fpm.add(llvm::createBasicAliasAnalysisPass());
+
+ // Promote allocas to registers.
+ fpm.add(llvm::createPromoteMemoryToRegisterPass());
+
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ fpm.add(llvm::createInstructionCombiningPass());
+
+ // Reassociate expressions.
+ fpm.add(llvm::createReassociatePass());
+
+ // Eliminate Common SubExpressions.
+ fpm.add(llvm::createGVNPass());
+
+ // Simplify the control flow graph (deleting unreachable
+ // blocks, etc).
+ fpm.add(llvm::createCFGSimplificationPass());
+#endif // ADD_OPT_PASSES
+
+ fpm.doInitialization();
+
+ // Generate test code using function throwCppException(...) as
+ // the function which throws foreign exceptions.
+ llvm::Function *toRun =
+ createUnwindExceptionTest(*module,
+ theBuilder,
+ fpm,
+ "throwCppException");
+
+ fprintf(stderr, "\nBegin module dump:\n\n");
+
+ module->dump();
+
+ fprintf(stderr, "\nEnd module dump:\n");
+
+ fprintf(stderr, "\n\nBegin Test:\n");
+
+ for (int i = 1; i < argc; ++i) {
+ // Run test for each argument whose value is the exception
+ // type to throw.
+ runExceptionThrow(executionEngine,
+ toRun,
+ (unsigned) strtoul(argv[i], NULL, 10));
+ }
+
+ fprintf(stderr, "\nEnd Test:\n\n");
+ }
+
+ delete executionEngine;
+
+ return 0;
+}
+
diff --git a/examples/ExceptionDemo/Makefile b/examples/ExceptionDemo/Makefile
new file mode 100644
index 00000000000..480744730eb
--- /dev/null
+++ b/examples/ExceptionDemo/Makefile
@@ -0,0 +1,16 @@
+##===- examples/ExceptionDemo/Makefile --------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===---------------------------------------------------------------------===##
+LEVEL = ../..
+TOOLNAME = ExceptionDemo
+EXAMPLE_TOOL = 1
+REQUIRES_EH = 1
+
+LINK_COMPONENTS := jit interpreter nativecodegen
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Fibonacci/CMakeLists.txt b/examples/Fibonacci/CMakeLists.txt
new file mode 100644
index 00000000000..693761241fc
--- /dev/null
+++ b/examples/Fibonacci/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(LLVM_LINK_COMPONENTS jit interpreter nativecodegen)
+
+add_llvm_example(Fibonacci
+ fibonacci.cpp
+ )
diff --git a/examples/Fibonacci/Makefile b/examples/Fibonacci/Makefile
new file mode 100644
index 00000000000..71f6ba0ef52
--- /dev/null
+++ b/examples/Fibonacci/Makefile
@@ -0,0 +1,17 @@
+##===- examples/Fibonacci/Makefile -------------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL = ../..
+TOOLNAME = Fibonacci
+EXAMPLE_TOOL = 1
+
+# Link in JIT support
+LINK_COMPONENTS := jit interpreter nativecodegen
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Fibonacci/fibonacci.cpp b/examples/Fibonacci/fibonacci.cpp
new file mode 100644
index 00000000000..cfd9b1e33cf
--- /dev/null
+++ b/examples/Fibonacci/fibonacci.cpp
@@ -0,0 +1,137 @@
+//===--- examples/Fibonacci/fibonacci.cpp - An example use of the JIT -----===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This small program provides an example of how to build quickly a small module
+// with function Fibonacci and execute it with the JIT.
+//
+// The goal of this snippet is to create in the memory the LLVM module
+// consisting of one function as follow:
+//
+// int fib(int x) {
+// if(x<=2) return 1;
+// return fib(x-1)+fib(x-2);
+// }
+//
+// Once we have this, we compile the module via JIT, then execute the `fib'
+// function and return result to a driver, i.e. to a "host program".
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/Constants.h"
+#include "llvm/Instructions.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/ExecutionEngine/Interpreter.h"
+#include "llvm/ExecutionEngine/GenericValue.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/TargetSelect.h"
+using namespace llvm;
+
+static Function *CreateFibFunction(Module *M, LLVMContext &Context) {
+ // Create the fib function and insert it into module M. This function is said
+ // to return an int and take an int parameter.
+ Function *FibF =
+ cast<Function>(M->getOrInsertFunction("fib", Type::getInt32Ty(Context),
+ Type::getInt32Ty(Context),
+ (Type *)0));
+
+ // Add a basic block to the function.
+ BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", FibF);
+
+ // Get pointers to the constants.
+ Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
+ Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
+
+ // Get pointer to the integer argument of the add1 function...
+ Argument *ArgX = FibF->arg_begin(); // Get the arg.
+ ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
+
+ // Create the true_block.
+ BasicBlock *RetBB = BasicBlock::Create(Context, "return", FibF);
+ // Create an exit block.
+ BasicBlock* RecurseBB = BasicBlock::Create(Context, "recurse", FibF);
+
+ // Create the "if (arg <= 2) goto exitbb"
+ Value *CondInst = new ICmpInst(*BB, ICmpInst::ICMP_SLE, ArgX, Two, "cond");
+ BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
+
+ // Create: ret int 1
+ ReturnInst::Create(Context, One, RetBB);
+
+ // create fib(x-1)
+ Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
+ CallInst *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
+ CallFibX1->setTailCall();
+
+ // create fib(x-2)
+ Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
+ CallInst *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
+ CallFibX2->setTailCall();
+
+
+ // fib(x-1)+fib(x-2)
+ Value *Sum = BinaryOperator::CreateAdd(CallFibX1, CallFibX2,
+ "addresult", RecurseBB);
+
+ // Create the return instruction and add it to the basic block
+ ReturnInst::Create(Context, Sum, RecurseBB);
+
+ return FibF;
+}
+
+
+int main(int argc, char **argv) {
+ int n = argc > 1 ? atol(argv[1]) : 24;
+
+ InitializeNativeTarget();
+ LLVMContext Context;
+
+ // Create some module to put our function into it.
+ OwningPtr<Module> M(new Module("test", Context));
+
+ // We are about to create the "fib" function:
+ Function *FibF = CreateFibFunction(M.get(), Context);
+
+ // Now we going to create JIT
+ std::string errStr;
+ ExecutionEngine *EE =
+ EngineBuilder(M.get())
+ .setErrorStr(&errStr)
+ .setEngineKind(EngineKind::JIT)
+ .create();
+
+ if (!EE) {
+ errs() << argv[0] << ": Failed to construct ExecutionEngine: " << errStr
+ << "\n";
+ return 1;
+ }
+
+ errs() << "verifying... ";
+ if (verifyModule(*M)) {
+ errs() << argv[0] << ": Error constructing function!\n";
+ return 1;
+ }
+
+ errs() << "OK\n";
+ errs() << "We just constructed this LLVM module:\n\n---------\n" << *M;
+ errs() << "---------\nstarting fibonacci(" << n << ") with JIT...\n";
+
+ // Call the Fibonacci function with argument n:
+ std::vector<GenericValue> Args(1);
+ Args[0].IntVal = APInt(32, n);
+ GenericValue GV = EE->runFunction(FibF, Args);
+
+ // import result of execution
+ outs() << "Result: " << GV.IntVal << "\n";
+
+ return 0;
+}
diff --git a/examples/HowToUseJIT/CMakeLists.txt b/examples/HowToUseJIT/CMakeLists.txt
new file mode 100644
index 00000000000..428b53ffb9b
--- /dev/null
+++ b/examples/HowToUseJIT/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(LLVM_LINK_COMPONENTS jit interpreter nativecodegen)
+
+add_llvm_example(HowToUseJIT
+ HowToUseJIT.cpp
+ )
diff --git a/examples/HowToUseJIT/HowToUseJIT.cpp b/examples/HowToUseJIT/HowToUseJIT.cpp
new file mode 100644
index 00000000000..5588e923df8
--- /dev/null
+++ b/examples/HowToUseJIT/HowToUseJIT.cpp
@@ -0,0 +1,133 @@
+//===-- examples/HowToUseJIT/HowToUseJIT.cpp - An example use of the JIT --===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This small program provides an example of how to quickly build a small
+// module with two functions and execute it with the JIT.
+//
+// Goal:
+// The goal of this snippet is to create in the memory
+// the LLVM module consisting of two functions as follow:
+//
+// int add1(int x) {
+// return x+1;
+// }
+//
+// int foo() {
+// return add1(10);
+// }
+//
+// then compile the module via JIT, then execute the `foo'
+// function and return result to a driver, i.e. to a "host program".
+//
+// Some remarks and questions:
+//
+// - could we invoke some code using noname functions too?
+// e.g. evaluate "foo()+foo()" without fears to introduce
+// conflict of temporary function name with some real
+// existing function name?
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Constants.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/Instructions.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/ExecutionEngine/Interpreter.h"
+#include "llvm/ExecutionEngine/GenericValue.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/ManagedStatic.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace llvm;
+
+int main() {
+
+ InitializeNativeTarget();
+
+ LLVMContext Context;
+
+ // Create some module to put our function into it.
+ Module *M = new Module("test", Context);
+
+ // Create the add1 function entry and insert this entry into module M. The
+ // function will have a return type of "int" and take an argument of "int".
+ // The '0' terminates the list of argument types.
+ Function *Add1F =
+ cast<Function>(M->getOrInsertFunction("add1", Type::getInt32Ty(Context),
+ Type::getInt32Ty(Context),
+ (Type *)0));
+
+ // Add a basic block to the function. As before, it automatically inserts
+ // because of the last argument.
+ BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", Add1F);
+
+ // Create a basic block builder with default parameters. The builder will
+ // automatically append instructions to the basic block `BB'.
+ IRBuilder<> builder(BB);
+
+ // Get pointers to the constant `1'.
+ Value *One = builder.getInt32(1);
+
+ // Get pointers to the integer argument of the add1 function...
+ assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
+ Argument *ArgX = Add1F->arg_begin(); // Get the arg
+ ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
+
+ // Create the add instruction, inserting it into the end of BB.
+ Value *Add = builder.CreateAdd(One, ArgX);
+
+ // Create the return instruction and add it to the basic block
+ builder.CreateRet(Add);
+
+ // Now, function add1 is ready.
+
+
+ // Now we're going to create function `foo', which returns an int and takes no
+ // arguments.
+ Function *FooF =
+ cast<Function>(M->getOrInsertFunction("foo", Type::getInt32Ty(Context),
+ (Type *)0));
+
+ // Add a basic block to the FooF function.
+ BB = BasicBlock::Create(Context, "EntryBlock", FooF);
+
+ // Tell the basic block builder to attach itself to the new basic block
+ builder.SetInsertPoint(BB);
+
+ // Get pointer to the constant `10'.
+ Value *Ten = builder.getInt32(10);
+
+ // Pass Ten to the call to Add1F
+ CallInst *Add1CallRes = builder.CreateCall(Add1F, Ten);
+ Add1CallRes->setTailCall(true);
+
+ // Create the return instruction and add it to the basic block.
+ builder.CreateRet(Add1CallRes);
+
+ // Now we create the JIT.
+ ExecutionEngine* EE = EngineBuilder(M).create();
+
+ outs() << "We just constructed this LLVM module:\n\n" << *M;
+ outs() << "\n\nRunning foo: ";
+ outs().flush();
+
+ // Call the `foo' function with no arguments:
+ std::vector<GenericValue> noargs;
+ GenericValue gv = EE->runFunction(FooF, noargs);
+
+ // Import result of execution:
+ outs() << "Result: " << gv.IntVal << "\n";
+ EE->freeMachineCodeForFunction(FooF);
+ delete EE;
+ llvm_shutdown();
+ return 0;
+}
diff --git a/examples/HowToUseJIT/Makefile b/examples/HowToUseJIT/Makefile
new file mode 100644
index 00000000000..c8919db90cc
--- /dev/null
+++ b/examples/HowToUseJIT/Makefile
@@ -0,0 +1,15 @@
+##===- examples/HowToUseJIT/Makefile -----------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../..
+TOOLNAME = HowToUseJIT
+EXAMPLE_TOOL = 1
+
+LINK_COMPONENTS := jit interpreter nativecodegen
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Kaleidoscope/CMakeLists.txt b/examples/Kaleidoscope/CMakeLists.txt
new file mode 100644
index 00000000000..8c87ac50b7a
--- /dev/null
+++ b/examples/Kaleidoscope/CMakeLists.txt
@@ -0,0 +1,6 @@
+add_subdirectory(Chapter2)
+add_subdirectory(Chapter3)
+add_subdirectory(Chapter4)
+add_subdirectory(Chapter5)
+add_subdirectory(Chapter6)
+add_subdirectory(Chapter7)
diff --git a/examples/Kaleidoscope/Chapter2/CMakeLists.txt b/examples/Kaleidoscope/Chapter2/CMakeLists.txt
new file mode 100644
index 00000000000..79f2b172d0d
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter2/CMakeLists.txt
@@ -0,0 +1,3 @@
+add_llvm_example(Kaleidoscope-Ch2
+ toy.cpp
+ )
diff --git a/examples/Kaleidoscope/Chapter2/Makefile b/examples/Kaleidoscope/Chapter2/Makefile
new file mode 100644
index 00000000000..1a9b94ce541
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter2/Makefile
@@ -0,0 +1,13 @@
+##===- examples/Kaleidoscope/Chapter2/Makefile -------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../../..
+TOOLNAME = Kaleidoscope-Ch2
+EXAMPLE_TOOL = 1
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Kaleidoscope/Chapter2/toy.cpp b/examples/Kaleidoscope/Chapter2/toy.cpp
new file mode 100644
index 00000000000..f4f09d0b351
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter2/toy.cpp
@@ -0,0 +1,398 @@
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+#include <map>
+#include <vector>
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &name) : Name(name) {}
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector<ExprAST*> Args;
+public:
+ CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
+ : Callee(callee), Args(args) {}
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector<std::string> Args;
+public:
+ PrototypeAST(const std::string &name, const std::vector<std::string> &args)
+ : Name(name), Args(args) {}
+
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map<char, int> BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec <= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector<ExprAST*> Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ }
+}
+
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec < ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec < NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector<std::string> ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing
+//===----------------------------------------------------------------------===//
+
+static void HandleDefinition() {
+ if (ParseDefinition()) {
+ fprintf(stderr, "Parsed a function definition.\n");
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (ParseExtern()) {
+ fprintf(stderr, "Parsed an extern\n");
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (ParseTopLevelExpr()) {
+ fprintf(stderr, "Parsed a top-level expr\n");
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready> ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['<'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready> ");
+ getNextToken();
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ return 0;
+}
diff --git a/examples/Kaleidoscope/Chapter3/CMakeLists.txt b/examples/Kaleidoscope/Chapter3/CMakeLists.txt
new file mode 100644
index 00000000000..1af8db00a17
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter3/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(LLVM_LINK_COMPONENTS core)
+
+add_llvm_example(Kaleidoscope-Ch3
+ toy.cpp
+ )
diff --git a/examples/Kaleidoscope/Chapter3/Makefile b/examples/Kaleidoscope/Chapter3/Makefile
new file mode 100644
index 00000000000..4cc6948d803
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter3/Makefile
@@ -0,0 +1,15 @@
+##===- examples/Kaleidoscope/Chapter3/Makefile -------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../../..
+TOOLNAME = Kaleidoscope-Ch3
+EXAMPLE_TOOL = 1
+
+LINK_COMPONENTS := core
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Kaleidoscope/Chapter3/toy.cpp b/examples/Kaleidoscope/Chapter3/toy.cpp
new file mode 100644
index 00000000000..c1e34b2f09a
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter3/toy.cpp
@@ -0,0 +1,563 @@
+#include "llvm/DerivedTypes.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/Analysis/Verifier.h"
+#include <cstdio>
+#include <string>
+#include <map>
+#include <vector>
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &name) : Name(name) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector<ExprAST*> Args;
+public:
+ CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector<std::string> Args;
+public:
+ PrototypeAST(const std::string &name, const std::vector<std::string> &args)
+ : Name(name), Args(args) {}
+
+ Function *Codegen();
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map<char, int> BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec <= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector<ExprAST*> Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ }
+}
+
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec < ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec < NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector<std::string> ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder<> Builder(getGlobalContext());
+static std::map<std::string, Value*> NamedValues;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS->Codegen();
+ Value *R = RHS->Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '<':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: return ErrorV("invalid binary operator");
+ }
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule->getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF->arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector<Value*> ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]->Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector<Type*> Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F->getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F->eraseFromParent();
+ F = TheModule->getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F->empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F->arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI->setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+
+ return F;
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto->Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body->Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction->eraseFromParent();
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F->Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P->Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F->Codegen()) {
+ fprintf(stderr, "Read top-level expression:");
+ LF->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready> ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ LLVMContext &Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['<'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready> ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ // Print out all of the generated code.
+ TheModule->dump();
+
+ return 0;
+}
diff --git a/examples/Kaleidoscope/Chapter4/CMakeLists.txt b/examples/Kaleidoscope/Chapter4/CMakeLists.txt
new file mode 100644
index 00000000000..0d1ac533f02
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter4/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(LLVM_LINK_COMPONENTS core jit interpreter native)
+
+add_llvm_example(Kaleidoscope-Ch4
+ toy.cpp
+ )
diff --git a/examples/Kaleidoscope/Chapter4/Makefile b/examples/Kaleidoscope/Chapter4/Makefile
new file mode 100644
index 00000000000..30162d94bce
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter4/Makefile
@@ -0,0 +1,15 @@
+##===- examples/Kaleidoscope/Chapter4/Makefile -------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../../..
+TOOLNAME = Kaleidoscope-Ch4
+EXAMPLE_TOOL = 1
+
+LINK_COMPONENTS := core jit native
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Kaleidoscope/Chapter4/toy.cpp b/examples/Kaleidoscope/Chapter4/toy.cpp
new file mode 100644
index 00000000000..cce4466ed57
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter4/toy.cpp
@@ -0,0 +1,613 @@
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/TargetSelect.h"
+#include <cstdio>
+#include <string>
+#include <map>
+#include <vector>
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &name) : Name(name) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector<ExprAST*> Args;
+public:
+ CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector<std::string> Args;
+public:
+ PrototypeAST(const std::string &name, const std::vector<std::string> &args)
+ : Name(name), Args(args) {}
+
+ Function *Codegen();
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map<char, int> BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec <= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector<ExprAST*> Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ }
+}
+
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec < ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec < NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector<std::string> ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder<> Builder(getGlobalContext());
+static std::map<std::string, Value*> NamedValues;
+static FunctionPassManager *TheFPM;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS->Codegen();
+ Value *R = RHS->Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '<':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: return ErrorV("invalid binary operator");
+ }
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule->getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF->arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector<Value*> ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]->Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector<Type*> Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F->getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F->eraseFromParent();
+ F = TheModule->getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F->empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F->arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI->setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+
+ return F;
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto->Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body->Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ // Optimize the function.
+ TheFPM->run(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction->eraseFromParent();
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static ExecutionEngine *TheExecutionEngine;
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F->Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P->Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F->Codegen()) {
+ // JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready> ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext &Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['<'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready> ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Create the JIT. This takes ownership of the module.
+ std::string ErrStr;
+ TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
+ if (!TheExecutionEngine) {
+ fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+ exit(1);
+ }
+
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ TheFPM = 0;
+
+ // Print out all of the generated code.
+ TheModule->dump();
+
+ return 0;
+}
diff --git a/examples/Kaleidoscope/Chapter5/CMakeLists.txt b/examples/Kaleidoscope/Chapter5/CMakeLists.txt
new file mode 100644
index 00000000000..2d75ad35923
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter5/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(LLVM_LINK_COMPONENTS core jit interpreter native)
+
+add_llvm_example(Kaleidoscope-Ch5
+ toy.cpp
+ )
diff --git a/examples/Kaleidoscope/Chapter5/Makefile b/examples/Kaleidoscope/Chapter5/Makefile
new file mode 100644
index 00000000000..d1f5e2035b4
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter5/Makefile
@@ -0,0 +1,15 @@
+##===- examples/Kaleidoscope/Chapter5/Makefile -------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../../..
+TOOLNAME = Kaleidoscope-Ch5
+EXAMPLE_TOOL = 1
+
+LINK_COMPONENTS := core jit native
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Kaleidoscope/Chapter5/toy.cpp b/examples/Kaleidoscope/Chapter5/toy.cpp
new file mode 100644
index 00000000000..36dd760e5ff
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter5/toy.cpp
@@ -0,0 +1,858 @@
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/TargetSelect.h"
+#include <cstdio>
+#include <string>
+#include <map>
+#include <vector>
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5,
+
+ // control
+ tok_if = -6, tok_then = -7, tok_else = -8,
+ tok_for = -9, tok_in = -10
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ if (IdentifierStr == "if") return tok_if;
+ if (IdentifierStr == "then") return tok_then;
+ if (IdentifierStr == "else") return tok_else;
+ if (IdentifierStr == "for") return tok_for;
+ if (IdentifierStr == "in") return tok_in;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &name) : Name(name) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector<ExprAST*> Args;
+public:
+ CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// IfExprAST - Expression class for if/then/else.
+class IfExprAST : public ExprAST {
+ ExprAST *Cond, *Then, *Else;
+public:
+ IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
+ : Cond(cond), Then(then), Else(_else) {}
+ virtual Value *Codegen();
+};
+
+/// ForExprAST - Expression class for for/in.
+class ForExprAST : public ExprAST {
+ std::string VarName;
+ ExprAST *Start, *End, *Step, *Body;
+public:
+ ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
+ ExprAST *step, ExprAST *body)
+ : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes).
+class PrototypeAST {
+ std::string Name;
+ std::vector<std::string> Args;
+public:
+ PrototypeAST(const std::string &name, const std::vector<std::string> &args)
+ : Name(name), Args(args) {}
+
+ Function *Codegen();
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map<char, int> BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec <= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector<ExprAST*> Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// ifexpr ::= 'if' expression 'then' expression 'else' expression
+static ExprAST *ParseIfExpr() {
+ getNextToken(); // eat the if.
+
+ // condition.
+ ExprAST *Cond = ParseExpression();
+ if (!Cond) return 0;
+
+ if (CurTok != tok_then)
+ return Error("expected then");
+ getNextToken(); // eat the then
+
+ ExprAST *Then = ParseExpression();
+ if (Then == 0) return 0;
+
+ if (CurTok != tok_else)
+ return Error("expected else");
+
+ getNextToken();
+
+ ExprAST *Else = ParseExpression();
+ if (!Else) return 0;
+
+ return new IfExprAST(Cond, Then, Else);
+}
+
+/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
+static ExprAST *ParseForExpr() {
+ getNextToken(); // eat the for.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after for");
+
+ std::string IdName = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '=')
+ return Error("expected '=' after for");
+ getNextToken(); // eat '='.
+
+
+ ExprAST *Start = ParseExpression();
+ if (Start == 0) return 0;
+ if (CurTok != ',')
+ return Error("expected ',' after for start value");
+ getNextToken();
+
+ ExprAST *End = ParseExpression();
+ if (End == 0) return 0;
+
+ // The step value is optional.
+ ExprAST *Step = 0;
+ if (CurTok == ',') {
+ getNextToken();
+ Step = ParseExpression();
+ if (Step == 0) return 0;
+ }
+
+ if (CurTok != tok_in)
+ return Error("expected 'in' after for");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new ForExprAST(IdName, Start, End, Step, Body);
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+/// ::= ifexpr
+/// ::= forexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ case tok_if: return ParseIfExpr();
+ case tok_for: return ParseForExpr();
+ }
+}
+
+/// binoprhs
+/// ::= ('+' primary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec < ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the primary expression after the binary operator.
+ ExprAST *RHS = ParsePrimary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec < NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= primary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParsePrimary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+static PrototypeAST *ParsePrototype() {
+ if (CurTok != tok_identifier)
+ return ErrorP("Expected function name in prototype");
+
+ std::string FnName = IdentifierStr;
+ getNextToken();
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector<std::string> ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ return new PrototypeAST(FnName, ArgNames);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder<> Builder(getGlobalContext());
+static std::map<std::string, Value*> NamedValues;
+static FunctionPassManager *TheFPM;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS->Codegen();
+ Value *R = RHS->Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '<':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: return ErrorV("invalid binary operator");
+ }
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule->getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF->arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector<Value*> ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]->Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Value *IfExprAST::Codegen() {
+ Value *CondV = Cond->Codegen();
+ if (CondV == 0) return 0;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ CondV = Builder.CreateFCmpONE(CondV,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "ifcond");
+
+ Function *TheFunction = Builder.GetInsertBlock()->getParent();
+
+ // Create blocks for the then and else cases. Insert the 'then' block at the
+ // end of the function.
+ BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
+ BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
+ BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+
+ Builder.CreateCondBr(CondV, ThenBB, ElseBB);
+
+ // Emit then value.
+ Builder.SetInsertPoint(ThenBB);
+
+ Value *ThenV = Then->Codegen();
+ if (ThenV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
+ ThenBB = Builder.GetInsertBlock();
+
+ // Emit else block.
+ TheFunction->getBasicBlockList().push_back(ElseBB);
+ Builder.SetInsertPoint(ElseBB);
+
+ Value *ElseV = Else->Codegen();
+ if (ElseV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
+ ElseBB = Builder.GetInsertBlock();
+
+ // Emit merge block.
+ TheFunction->getBasicBlockList().push_back(MergeBB);
+ Builder.SetInsertPoint(MergeBB);
+ PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+ "iftmp");
+
+ PN->addIncoming(ThenV, ThenBB);
+ PN->addIncoming(ElseV, ElseBB);
+ return PN;
+}
+
+Value *ForExprAST::Codegen() {
+ // Output this as:
+ // ...
+ // start = startexpr
+ // goto loop
+ // loop:
+ // variable = phi [start, loopheader], [nextvariable, loopend]
+ // ...
+ // bodyexpr
+ // ...
+ // loopend:
+ // step = stepexpr
+ // nextvariable = variable + step
+ // endcond = endexpr
+ // br endcond, loop, endloop
+ // outloop:
+
+ // Emit the start code first, without 'variable' in scope.
+ Value *StartVal = Start->Codegen();
+ if (StartVal == 0) return 0;
+
+ // Make the new basic block for the loop header, inserting after current
+ // block.
+ Function *TheFunction = Builder.GetInsertBlock()->getParent();
+ BasicBlock *PreheaderBB = Builder.GetInsertBlock();
+ BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+
+ // Insert an explicit fall through from the current block to the LoopBB.
+ Builder.CreateBr(LoopBB);
+
+ // Start insertion in LoopBB.
+ Builder.SetInsertPoint(LoopBB);
+
+ // Start the PHI node with an entry for Start.
+ PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
+ Variable->addIncoming(StartVal, PreheaderBB);
+
+ // Within the loop, the variable is defined equal to the PHI node. If it
+ // shadows an existing variable, we have to restore it, so save it now.
+ Value *OldVal = NamedValues[VarName];
+ NamedValues[VarName] = Variable;
+
+ // Emit the body of the loop. This, like any other expr, can change the
+ // current BB. Note that we ignore the value computed by the body, but don't
+ // allow an error.
+ if (Body->Codegen() == 0)
+ return 0;
+
+ // Emit the step value.
+ Value *StepVal;
+ if (Step) {
+ StepVal = Step->Codegen();
+ if (StepVal == 0) return 0;
+ } else {
+ // If not specified, use 1.0.
+ StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+ }
+
+ Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
+
+ // Compute the end condition.
+ Value *EndCond = End->Codegen();
+ if (EndCond == 0) return EndCond;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ EndCond = Builder.CreateFCmpONE(EndCond,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "loopcond");
+
+ // Create the "after loop" block and insert it.
+ BasicBlock *LoopEndBB = Builder.GetInsertBlock();
+ BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+
+ // Insert the conditional branch into the end of LoopEndBB.
+ Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
+
+ // Any new code will be inserted in AfterBB.
+ Builder.SetInsertPoint(AfterBB);
+
+ // Add a new entry to the PHI node for the backedge.
+ Variable->addIncoming(NextVar, LoopEndBB);
+
+ // Restore the unshadowed variable.
+ if (OldVal)
+ NamedValues[VarName] = OldVal;
+ else
+ NamedValues.erase(VarName);
+
+
+ // for expr always returns 0.0.
+ return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector<Type*> Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F->getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F->eraseFromParent();
+ F = TheModule->getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F->empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F->arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI->setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+
+ return F;
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto->Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body->Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ // Optimize the function.
+ TheFPM->run(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction->eraseFromParent();
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static ExecutionEngine *TheExecutionEngine;
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F->Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P->Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F->Codegen()) {
+ // JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready> ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext &Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['<'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready> ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Create the JIT. This takes ownership of the module.
+ std::string ErrStr;
+ TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
+ if (!TheExecutionEngine) {
+ fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+ exit(1);
+ }
+
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ TheFPM = 0;
+
+ // Print out all of the generated code.
+ TheModule->dump();
+
+ return 0;
+}
diff --git a/examples/Kaleidoscope/Chapter6/CMakeLists.txt b/examples/Kaleidoscope/Chapter6/CMakeLists.txt
new file mode 100644
index 00000000000..2e15a5f7dfc
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter6/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(LLVM_LINK_COMPONENTS core jit interpreter native)
+
+add_llvm_example(Kaleidoscope-Ch6
+ toy.cpp
+ )
diff --git a/examples/Kaleidoscope/Chapter6/Makefile b/examples/Kaleidoscope/Chapter6/Makefile
new file mode 100644
index 00000000000..a5fbcbdf9b2
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter6/Makefile
@@ -0,0 +1,15 @@
+##===- examples/Kaleidoscope/Chapter6/Makefile -------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../../..
+TOOLNAME = Kaleidoscope-Ch6
+EXAMPLE_TOOL = 1
+
+LINK_COMPONENTS := core jit native
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Kaleidoscope/Chapter6/toy.cpp b/examples/Kaleidoscope/Chapter6/toy.cpp
new file mode 100644
index 00000000000..db3495dcc98
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter6/toy.cpp
@@ -0,0 +1,976 @@
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/TargetSelect.h"
+#include <cstdio>
+#include <string>
+#include <map>
+#include <vector>
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5,
+
+ // control
+ tok_if = -6, tok_then = -7, tok_else = -8,
+ tok_for = -9, tok_in = -10,
+
+ // operators
+ tok_binary = -11, tok_unary = -12
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ if (IdentifierStr == "if") return tok_if;
+ if (IdentifierStr == "then") return tok_then;
+ if (IdentifierStr == "else") return tok_else;
+ if (IdentifierStr == "for") return tok_for;
+ if (IdentifierStr == "in") return tok_in;
+ if (IdentifierStr == "binary") return tok_binary;
+ if (IdentifierStr == "unary") return tok_unary;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &name) : Name(name) {}
+ virtual Value *Codegen();
+};
+
+/// UnaryExprAST - Expression class for a unary operator.
+class UnaryExprAST : public ExprAST {
+ char Opcode;
+ ExprAST *Operand;
+public:
+ UnaryExprAST(char opcode, ExprAST *operand)
+ : Opcode(opcode), Operand(operand) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector<ExprAST*> Args;
+public:
+ CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// IfExprAST - Expression class for if/then/else.
+class IfExprAST : public ExprAST {
+ ExprAST *Cond, *Then, *Else;
+public:
+ IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
+ : Cond(cond), Then(then), Else(_else) {}
+ virtual Value *Codegen();
+};
+
+/// ForExprAST - Expression class for for/in.
+class ForExprAST : public ExprAST {
+ std::string VarName;
+ ExprAST *Start, *End, *Step, *Body;
+public:
+ ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
+ ExprAST *step, ExprAST *body)
+ : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes), as well as if it is an operator.
+class PrototypeAST {
+ std::string Name;
+ std::vector<std::string> Args;
+ bool isOperator;
+ unsigned Precedence; // Precedence if a binary op.
+public:
+ PrototypeAST(const std::string &name, const std::vector<std::string> &args,
+ bool isoperator = false, unsigned prec = 0)
+ : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
+
+ bool isUnaryOp() const { return isOperator && Args.size() == 1; }
+ bool isBinaryOp() const { return isOperator && Args.size() == 2; }
+
+ char getOperatorName() const {
+ assert(isUnaryOp() || isBinaryOp());
+ return Name[Name.size()-1];
+ }
+
+ unsigned getBinaryPrecedence() const { return Precedence; }
+
+ Function *Codegen();
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map<char, int> BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec <= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector<ExprAST*> Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// ifexpr ::= 'if' expression 'then' expression 'else' expression
+static ExprAST *ParseIfExpr() {
+ getNextToken(); // eat the if.
+
+ // condition.
+ ExprAST *Cond = ParseExpression();
+ if (!Cond) return 0;
+
+ if (CurTok != tok_then)
+ return Error("expected then");
+ getNextToken(); // eat the then
+
+ ExprAST *Then = ParseExpression();
+ if (Then == 0) return 0;
+
+ if (CurTok != tok_else)
+ return Error("expected else");
+
+ getNextToken();
+
+ ExprAST *Else = ParseExpression();
+ if (!Else) return 0;
+
+ return new IfExprAST(Cond, Then, Else);
+}
+
+/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
+static ExprAST *ParseForExpr() {
+ getNextToken(); // eat the for.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after for");
+
+ std::string IdName = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '=')
+ return Error("expected '=' after for");
+ getNextToken(); // eat '='.
+
+
+ ExprAST *Start = ParseExpression();
+ if (Start == 0) return 0;
+ if (CurTok != ',')
+ return Error("expected ',' after for start value");
+ getNextToken();
+
+ ExprAST *End = ParseExpression();
+ if (End == 0) return 0;
+
+ // The step value is optional.
+ ExprAST *Step = 0;
+ if (CurTok == ',') {
+ getNextToken();
+ Step = ParseExpression();
+ if (Step == 0) return 0;
+ }
+
+ if (CurTok != tok_in)
+ return Error("expected 'in' after for");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new ForExprAST(IdName, Start, End, Step, Body);
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+/// ::= ifexpr
+/// ::= forexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ case tok_if: return ParseIfExpr();
+ case tok_for: return ParseForExpr();
+ }
+}
+
+/// unary
+/// ::= primary
+/// ::= '!' unary
+static ExprAST *ParseUnary() {
+ // If the current token is not an operator, it must be a primary expr.
+ if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
+ return ParsePrimary();
+
+ // If this is a unary operator, read it.
+ int Opc = CurTok;
+ getNextToken();
+ if (ExprAST *Operand = ParseUnary())
+ return new UnaryExprAST(Opc, Operand);
+ return 0;
+}
+
+/// binoprhs
+/// ::= ('+' unary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec < ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the unary expression after the binary operator.
+ ExprAST *RHS = ParseUnary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec < NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= unary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParseUnary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+/// ::= binary LETTER number? (id, id)
+/// ::= unary LETTER (id)
+static PrototypeAST *ParsePrototype() {
+ std::string FnName;
+
+ unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
+ unsigned BinaryPrecedence = 30;
+
+ switch (CurTok) {
+ default:
+ return ErrorP("Expected function name in prototype");
+ case tok_identifier:
+ FnName = IdentifierStr;
+ Kind = 0;
+ getNextToken();
+ break;
+ case tok_unary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected unary operator");
+ FnName = "unary";
+ FnName += (char)CurTok;
+ Kind = 1;
+ getNextToken();
+ break;
+ case tok_binary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected binary operator");
+ FnName = "binary";
+ FnName += (char)CurTok;
+ Kind = 2;
+ getNextToken();
+
+ // Read the precedence if present.
+ if (CurTok == tok_number) {
+ if (NumVal < 1 || NumVal > 100)
+ return ErrorP("Invalid precedecnce: must be 1..100");
+ BinaryPrecedence = (unsigned)NumVal;
+ getNextToken();
+ }
+ break;
+ }
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector<std::string> ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ // Verify right number of names for operator.
+ if (Kind && ArgNames.size() != Kind)
+ return ErrorP("Invalid number of operands for operator");
+
+ return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder<> Builder(getGlobalContext());
+static std::map<std::string, Value*> NamedValues;
+static FunctionPassManager *TheFPM;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ return V ? V : ErrorV("Unknown variable name");
+}
+
+Value *UnaryExprAST::Codegen() {
+ Value *OperandV = Operand->Codegen();
+ if (OperandV == 0) return 0;
+
+ Function *F = TheModule->getFunction(std::string("unary")+Opcode);
+ if (F == 0)
+ return ErrorV("Unknown unary operator");
+
+ return Builder.CreateCall(F, OperandV, "unop");
+}
+
+Value *BinaryExprAST::Codegen() {
+ Value *L = LHS->Codegen();
+ Value *R = RHS->Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '<':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: break;
+ }
+
+ // If it wasn't a builtin binary operator, it must be a user defined one. Emit
+ // a call to it.
+ Function *F = TheModule->getFunction(std::string("binary")+Op);
+ assert(F && "binary operator not found!");
+
+ Value *Ops[] = { L, R };
+ return Builder.CreateCall(F, Ops, "binop");
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule->getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF->arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector<Value*> ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]->Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Value *IfExprAST::Codegen() {
+ Value *CondV = Cond->Codegen();
+ if (CondV == 0) return 0;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ CondV = Builder.CreateFCmpONE(CondV,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "ifcond");
+
+ Function *TheFunction = Builder.GetInsertBlock()->getParent();
+
+ // Create blocks for the then and else cases. Insert the 'then' block at the
+ // end of the function.
+ BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
+ BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
+ BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+
+ Builder.CreateCondBr(CondV, ThenBB, ElseBB);
+
+ // Emit then value.
+ Builder.SetInsertPoint(ThenBB);
+
+ Value *ThenV = Then->Codegen();
+ if (ThenV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
+ ThenBB = Builder.GetInsertBlock();
+
+ // Emit else block.
+ TheFunction->getBasicBlockList().push_back(ElseBB);
+ Builder.SetInsertPoint(ElseBB);
+
+ Value *ElseV = Else->Codegen();
+ if (ElseV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
+ ElseBB = Builder.GetInsertBlock();
+
+ // Emit merge block.
+ TheFunction->getBasicBlockList().push_back(MergeBB);
+ Builder.SetInsertPoint(MergeBB);
+ PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+ "iftmp");
+
+ PN->addIncoming(ThenV, ThenBB);
+ PN->addIncoming(ElseV, ElseBB);
+ return PN;
+}
+
+Value *ForExprAST::Codegen() {
+ // Output this as:
+ // ...
+ // start = startexpr
+ // goto loop
+ // loop:
+ // variable = phi [start, loopheader], [nextvariable, loopend]
+ // ...
+ // bodyexpr
+ // ...
+ // loopend:
+ // step = stepexpr
+ // nextvariable = variable + step
+ // endcond = endexpr
+ // br endcond, loop, endloop
+ // outloop:
+
+ // Emit the start code first, without 'variable' in scope.
+ Value *StartVal = Start->Codegen();
+ if (StartVal == 0) return 0;
+
+ // Make the new basic block for the loop header, inserting after current
+ // block.
+ Function *TheFunction = Builder.GetInsertBlock()->getParent();
+ BasicBlock *PreheaderBB = Builder.GetInsertBlock();
+ BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+
+ // Insert an explicit fall through from the current block to the LoopBB.
+ Builder.CreateBr(LoopBB);
+
+ // Start insertion in LoopBB.
+ Builder.SetInsertPoint(LoopBB);
+
+ // Start the PHI node with an entry for Start.
+ PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
+ Variable->addIncoming(StartVal, PreheaderBB);
+
+ // Within the loop, the variable is defined equal to the PHI node. If it
+ // shadows an existing variable, we have to restore it, so save it now.
+ Value *OldVal = NamedValues[VarName];
+ NamedValues[VarName] = Variable;
+
+ // Emit the body of the loop. This, like any other expr, can change the
+ // current BB. Note that we ignore the value computed by the body, but don't
+ // allow an error.
+ if (Body->Codegen() == 0)
+ return 0;
+
+ // Emit the step value.
+ Value *StepVal;
+ if (Step) {
+ StepVal = Step->Codegen();
+ if (StepVal == 0) return 0;
+ } else {
+ // If not specified, use 1.0.
+ StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+ }
+
+ Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
+
+ // Compute the end condition.
+ Value *EndCond = End->Codegen();
+ if (EndCond == 0) return EndCond;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ EndCond = Builder.CreateFCmpONE(EndCond,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "loopcond");
+
+ // Create the "after loop" block and insert it.
+ BasicBlock *LoopEndBB = Builder.GetInsertBlock();
+ BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+
+ // Insert the conditional branch into the end of LoopEndBB.
+ Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
+
+ // Any new code will be inserted in AfterBB.
+ Builder.SetInsertPoint(AfterBB);
+
+ // Add a new entry to the PHI node for the backedge.
+ Variable->addIncoming(NextVar, LoopEndBB);
+
+ // Restore the unshadowed variable.
+ if (OldVal)
+ NamedValues[VarName] = OldVal;
+ else
+ NamedValues.erase(VarName);
+
+
+ // for expr always returns 0.0.
+ return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector<Type*> Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F->getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F->eraseFromParent();
+ F = TheModule->getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F->empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F->arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI->setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+
+ return F;
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto->Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // If this is an operator, install it.
+ if (Proto->isBinaryOp())
+ BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body->Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ // Optimize the function.
+ TheFPM->run(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction->eraseFromParent();
+
+ if (Proto->isBinaryOp())
+ BinopPrecedence.erase(Proto->getOperatorName());
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static ExecutionEngine *TheExecutionEngine;
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F->Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P->Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F->Codegen()) {
+ // JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready> ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+/// printd - printf that takes a double prints it as "%f\n", returning 0.
+extern "C"
+double printd(double X) {
+ printf("%f\n", X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext &Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['<'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready> ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Create the JIT. This takes ownership of the module.
+ std::string ErrStr;
+ TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
+ if (!TheExecutionEngine) {
+ fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+ exit(1);
+ }
+
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ TheFPM = 0;
+
+ // Print out all of the generated code.
+ TheModule->dump();
+
+ return 0;
+}
diff --git a/examples/Kaleidoscope/Chapter7/CMakeLists.txt b/examples/Kaleidoscope/Chapter7/CMakeLists.txt
new file mode 100644
index 00000000000..da3839843bd
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter7/CMakeLists.txt
@@ -0,0 +1,6 @@
+set(LLVM_LINK_COMPONENTS core jit interpreter native)
+set(LLVM_REQUIRES_RTTI 1)
+
+add_llvm_example(Kaleidoscope-Ch7
+ toy.cpp
+ )
diff --git a/examples/Kaleidoscope/Chapter7/Makefile b/examples/Kaleidoscope/Chapter7/Makefile
new file mode 100644
index 00000000000..6cec323efd4
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter7/Makefile
@@ -0,0 +1,16 @@
+##===- examples/Kaleidoscope/Chapter7/Makefile -------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../../..
+TOOLNAME = Kaleidoscope-Ch7
+EXAMPLE_TOOL = 1
+REQUIRES_RTTI := 1
+
+LINK_COMPONENTS := core jit native
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/Kaleidoscope/Chapter7/toy.cpp b/examples/Kaleidoscope/Chapter7/toy.cpp
new file mode 100644
index 00000000000..143b30bf476
--- /dev/null
+++ b/examples/Kaleidoscope/Chapter7/toy.cpp
@@ -0,0 +1,1142 @@
+#include "llvm/DerivedTypes.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/IRBuilder.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/PassManager.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Support/TargetSelect.h"
+#include <cstdio>
+#include <string>
+#include <map>
+#include <vector>
+using namespace llvm;
+
+//===----------------------------------------------------------------------===//
+// Lexer
+//===----------------------------------------------------------------------===//
+
+// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
+// of these for known things.
+enum Token {
+ tok_eof = -1,
+
+ // commands
+ tok_def = -2, tok_extern = -3,
+
+ // primary
+ tok_identifier = -4, tok_number = -5,
+
+ // control
+ tok_if = -6, tok_then = -7, tok_else = -8,
+ tok_for = -9, tok_in = -10,
+
+ // operators
+ tok_binary = -11, tok_unary = -12,
+
+ // var definition
+ tok_var = -13
+};
+
+static std::string IdentifierStr; // Filled in if tok_identifier
+static double NumVal; // Filled in if tok_number
+
+/// gettok - Return the next token from standard input.
+static int gettok() {
+ static int LastChar = ' ';
+
+ // Skip any whitespace.
+ while (isspace(LastChar))
+ LastChar = getchar();
+
+ if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
+ IdentifierStr = LastChar;
+ while (isalnum((LastChar = getchar())))
+ IdentifierStr += LastChar;
+
+ if (IdentifierStr == "def") return tok_def;
+ if (IdentifierStr == "extern") return tok_extern;
+ if (IdentifierStr == "if") return tok_if;
+ if (IdentifierStr == "then") return tok_then;
+ if (IdentifierStr == "else") return tok_else;
+ if (IdentifierStr == "for") return tok_for;
+ if (IdentifierStr == "in") return tok_in;
+ if (IdentifierStr == "binary") return tok_binary;
+ if (IdentifierStr == "unary") return tok_unary;
+ if (IdentifierStr == "var") return tok_var;
+ return tok_identifier;
+ }
+
+ if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
+ std::string NumStr;
+ do {
+ NumStr += LastChar;
+ LastChar = getchar();
+ } while (isdigit(LastChar) || LastChar == '.');
+
+ NumVal = strtod(NumStr.c_str(), 0);
+ return tok_number;
+ }
+
+ if (LastChar == '#') {
+ // Comment until end of line.
+ do LastChar = getchar();
+ while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
+
+ if (LastChar != EOF)
+ return gettok();
+ }
+
+ // Check for end of file. Don't eat the EOF.
+ if (LastChar == EOF)
+ return tok_eof;
+
+ // Otherwise, just return the character as its ascii value.
+ int ThisChar = LastChar;
+ LastChar = getchar();
+ return ThisChar;
+}
+
+//===----------------------------------------------------------------------===//
+// Abstract Syntax Tree (aka Parse Tree)
+//===----------------------------------------------------------------------===//
+
+/// ExprAST - Base class for all expression nodes.
+class ExprAST {
+public:
+ virtual ~ExprAST() {}
+ virtual Value *Codegen() = 0;
+};
+
+/// NumberExprAST - Expression class for numeric literals like "1.0".
+class NumberExprAST : public ExprAST {
+ double Val;
+public:
+ NumberExprAST(double val) : Val(val) {}
+ virtual Value *Codegen();
+};
+
+/// VariableExprAST - Expression class for referencing a variable, like "a".
+class VariableExprAST : public ExprAST {
+ std::string Name;
+public:
+ VariableExprAST(const std::string &name) : Name(name) {}
+ const std::string &getName() const { return Name; }
+ virtual Value *Codegen();
+};
+
+/// UnaryExprAST - Expression class for a unary operator.
+class UnaryExprAST : public ExprAST {
+ char Opcode;
+ ExprAST *Operand;
+public:
+ UnaryExprAST(char opcode, ExprAST *operand)
+ : Opcode(opcode), Operand(operand) {}
+ virtual Value *Codegen();
+};
+
+/// BinaryExprAST - Expression class for a binary operator.
+class BinaryExprAST : public ExprAST {
+ char Op;
+ ExprAST *LHS, *RHS;
+public:
+ BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
+ : Op(op), LHS(lhs), RHS(rhs) {}
+ virtual Value *Codegen();
+};
+
+/// CallExprAST - Expression class for function calls.
+class CallExprAST : public ExprAST {
+ std::string Callee;
+ std::vector<ExprAST*> Args;
+public:
+ CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
+ : Callee(callee), Args(args) {}
+ virtual Value *Codegen();
+};
+
+/// IfExprAST - Expression class for if/then/else.
+class IfExprAST : public ExprAST {
+ ExprAST *Cond, *Then, *Else;
+public:
+ IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
+ : Cond(cond), Then(then), Else(_else) {}
+ virtual Value *Codegen();
+};
+
+/// ForExprAST - Expression class for for/in.
+class ForExprAST : public ExprAST {
+ std::string VarName;
+ ExprAST *Start, *End, *Step, *Body;
+public:
+ ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
+ ExprAST *step, ExprAST *body)
+ : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
+ virtual Value *Codegen();
+};
+
+/// VarExprAST - Expression class for var/in
+class VarExprAST : public ExprAST {
+ std::vector<std::pair<std::string, ExprAST*> > VarNames;
+ ExprAST *Body;
+public:
+ VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
+ ExprAST *body)
+ : VarNames(varnames), Body(body) {}
+
+ virtual Value *Codegen();
+};
+
+/// PrototypeAST - This class represents the "prototype" for a function,
+/// which captures its argument names as well as if it is an operator.
+class PrototypeAST {
+ std::string Name;
+ std::vector<std::string> Args;
+ bool isOperator;
+ unsigned Precedence; // Precedence if a binary op.
+public:
+ PrototypeAST(const std::string &name, const std::vector<std::string> &args,
+ bool isoperator = false, unsigned prec = 0)
+ : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
+
+ bool isUnaryOp() const { return isOperator && Args.size() == 1; }
+ bool isBinaryOp() const { return isOperator && Args.size() == 2; }
+
+ char getOperatorName() const {
+ assert(isUnaryOp() || isBinaryOp());
+ return Name[Name.size()-1];
+ }
+
+ unsigned getBinaryPrecedence() const { return Precedence; }
+
+ Function *Codegen();
+
+ void CreateArgumentAllocas(Function *F);
+};
+
+/// FunctionAST - This class represents a function definition itself.
+class FunctionAST {
+ PrototypeAST *Proto;
+ ExprAST *Body;
+public:
+ FunctionAST(PrototypeAST *proto, ExprAST *body)
+ : Proto(proto), Body(body) {}
+
+ Function *Codegen();
+};
+
+//===----------------------------------------------------------------------===//
+// Parser
+//===----------------------------------------------------------------------===//
+
+/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
+/// token the parser is looking at. getNextToken reads another token from the
+/// lexer and updates CurTok with its results.
+static int CurTok;
+static int getNextToken() {
+ return CurTok = gettok();
+}
+
+/// BinopPrecedence - This holds the precedence for each binary operator that is
+/// defined.
+static std::map<char, int> BinopPrecedence;
+
+/// GetTokPrecedence - Get the precedence of the pending binary operator token.
+static int GetTokPrecedence() {
+ if (!isascii(CurTok))
+ return -1;
+
+ // Make sure it's a declared binop.
+ int TokPrec = BinopPrecedence[CurTok];
+ if (TokPrec <= 0) return -1;
+ return TokPrec;
+}
+
+/// Error* - These are little helper functions for error handling.
+ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
+PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
+FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
+
+static ExprAST *ParseExpression();
+
+/// identifierexpr
+/// ::= identifier
+/// ::= identifier '(' expression* ')'
+static ExprAST *ParseIdentifierExpr() {
+ std::string IdName = IdentifierStr;
+
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '(') // Simple variable ref.
+ return new VariableExprAST(IdName);
+
+ // Call.
+ getNextToken(); // eat (
+ std::vector<ExprAST*> Args;
+ if (CurTok != ')') {
+ while (1) {
+ ExprAST *Arg = ParseExpression();
+ if (!Arg) return 0;
+ Args.push_back(Arg);
+
+ if (CurTok == ')') break;
+
+ if (CurTok != ',')
+ return Error("Expected ')' or ',' in argument list");
+ getNextToken();
+ }
+ }
+
+ // Eat the ')'.
+ getNextToken();
+
+ return new CallExprAST(IdName, Args);
+}
+
+/// numberexpr ::= number
+static ExprAST *ParseNumberExpr() {
+ ExprAST *Result = new NumberExprAST(NumVal);
+ getNextToken(); // consume the number
+ return Result;
+}
+
+/// parenexpr ::= '(' expression ')'
+static ExprAST *ParseParenExpr() {
+ getNextToken(); // eat (.
+ ExprAST *V = ParseExpression();
+ if (!V) return 0;
+
+ if (CurTok != ')')
+ return Error("expected ')'");
+ getNextToken(); // eat ).
+ return V;
+}
+
+/// ifexpr ::= 'if' expression 'then' expression 'else' expression
+static ExprAST *ParseIfExpr() {
+ getNextToken(); // eat the if.
+
+ // condition.
+ ExprAST *Cond = ParseExpression();
+ if (!Cond) return 0;
+
+ if (CurTok != tok_then)
+ return Error("expected then");
+ getNextToken(); // eat the then
+
+ ExprAST *Then = ParseExpression();
+ if (Then == 0) return 0;
+
+ if (CurTok != tok_else)
+ return Error("expected else");
+
+ getNextToken();
+
+ ExprAST *Else = ParseExpression();
+ if (!Else) return 0;
+
+ return new IfExprAST(Cond, Then, Else);
+}
+
+/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
+static ExprAST *ParseForExpr() {
+ getNextToken(); // eat the for.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after for");
+
+ std::string IdName = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ if (CurTok != '=')
+ return Error("expected '=' after for");
+ getNextToken(); // eat '='.
+
+
+ ExprAST *Start = ParseExpression();
+ if (Start == 0) return 0;
+ if (CurTok != ',')
+ return Error("expected ',' after for start value");
+ getNextToken();
+
+ ExprAST *End = ParseExpression();
+ if (End == 0) return 0;
+
+ // The step value is optional.
+ ExprAST *Step = 0;
+ if (CurTok == ',') {
+ getNextToken();
+ Step = ParseExpression();
+ if (Step == 0) return 0;
+ }
+
+ if (CurTok != tok_in)
+ return Error("expected 'in' after for");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new ForExprAST(IdName, Start, End, Step, Body);
+}
+
+/// varexpr ::= 'var' identifier ('=' expression)?
+// (',' identifier ('=' expression)?)* 'in' expression
+static ExprAST *ParseVarExpr() {
+ getNextToken(); // eat the var.
+
+ std::vector<std::pair<std::string, ExprAST*> > VarNames;
+
+ // At least one variable name is required.
+ if (CurTok != tok_identifier)
+ return Error("expected identifier after var");
+
+ while (1) {
+ std::string Name = IdentifierStr;
+ getNextToken(); // eat identifier.
+
+ // Read the optional initializer.
+ ExprAST *Init = 0;
+ if (CurTok == '=') {
+ getNextToken(); // eat the '='.
+
+ Init = ParseExpression();
+ if (Init == 0) return 0;
+ }
+
+ VarNames.push_back(std::make_pair(Name, Init));
+
+ // End of var list, exit loop.
+ if (CurTok != ',') break;
+ getNextToken(); // eat the ','.
+
+ if (CurTok != tok_identifier)
+ return Error("expected identifier list after var");
+ }
+
+ // At this point, we have to have 'in'.
+ if (CurTok != tok_in)
+ return Error("expected 'in' keyword after 'var'");
+ getNextToken(); // eat 'in'.
+
+ ExprAST *Body = ParseExpression();
+ if (Body == 0) return 0;
+
+ return new VarExprAST(VarNames, Body);
+}
+
+/// primary
+/// ::= identifierexpr
+/// ::= numberexpr
+/// ::= parenexpr
+/// ::= ifexpr
+/// ::= forexpr
+/// ::= varexpr
+static ExprAST *ParsePrimary() {
+ switch (CurTok) {
+ default: return Error("unknown token when expecting an expression");
+ case tok_identifier: return ParseIdentifierExpr();
+ case tok_number: return ParseNumberExpr();
+ case '(': return ParseParenExpr();
+ case tok_if: return ParseIfExpr();
+ case tok_for: return ParseForExpr();
+ case tok_var: return ParseVarExpr();
+ }
+}
+
+/// unary
+/// ::= primary
+/// ::= '!' unary
+static ExprAST *ParseUnary() {
+ // If the current token is not an operator, it must be a primary expr.
+ if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
+ return ParsePrimary();
+
+ // If this is a unary operator, read it.
+ int Opc = CurTok;
+ getNextToken();
+ if (ExprAST *Operand = ParseUnary())
+ return new UnaryExprAST(Opc, Operand);
+ return 0;
+}
+
+/// binoprhs
+/// ::= ('+' unary)*
+static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
+ // If this is a binop, find its precedence.
+ while (1) {
+ int TokPrec = GetTokPrecedence();
+
+ // If this is a binop that binds at least as tightly as the current binop,
+ // consume it, otherwise we are done.
+ if (TokPrec < ExprPrec)
+ return LHS;
+
+ // Okay, we know this is a binop.
+ int BinOp = CurTok;
+ getNextToken(); // eat binop
+
+ // Parse the unary expression after the binary operator.
+ ExprAST *RHS = ParseUnary();
+ if (!RHS) return 0;
+
+ // If BinOp binds less tightly with RHS than the operator after RHS, let
+ // the pending operator take RHS as its LHS.
+ int NextPrec = GetTokPrecedence();
+ if (TokPrec < NextPrec) {
+ RHS = ParseBinOpRHS(TokPrec+1, RHS);
+ if (RHS == 0) return 0;
+ }
+
+ // Merge LHS/RHS.
+ LHS = new BinaryExprAST(BinOp, LHS, RHS);
+ }
+}
+
+/// expression
+/// ::= unary binoprhs
+///
+static ExprAST *ParseExpression() {
+ ExprAST *LHS = ParseUnary();
+ if (!LHS) return 0;
+
+ return ParseBinOpRHS(0, LHS);
+}
+
+/// prototype
+/// ::= id '(' id* ')'
+/// ::= binary LETTER number? (id, id)
+/// ::= unary LETTER (id)
+static PrototypeAST *ParsePrototype() {
+ std::string FnName;
+
+ unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
+ unsigned BinaryPrecedence = 30;
+
+ switch (CurTok) {
+ default:
+ return ErrorP("Expected function name in prototype");
+ case tok_identifier:
+ FnName = IdentifierStr;
+ Kind = 0;
+ getNextToken();
+ break;
+ case tok_unary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected unary operator");
+ FnName = "unary";
+ FnName += (char)CurTok;
+ Kind = 1;
+ getNextToken();
+ break;
+ case tok_binary:
+ getNextToken();
+ if (!isascii(CurTok))
+ return ErrorP("Expected binary operator");
+ FnName = "binary";
+ FnName += (char)CurTok;
+ Kind = 2;
+ getNextToken();
+
+ // Read the precedence if present.
+ if (CurTok == tok_number) {
+ if (NumVal < 1 || NumVal > 100)
+ return ErrorP("Invalid precedecnce: must be 1..100");
+ BinaryPrecedence = (unsigned)NumVal;
+ getNextToken();
+ }
+ break;
+ }
+
+ if (CurTok != '(')
+ return ErrorP("Expected '(' in prototype");
+
+ std::vector<std::string> ArgNames;
+ while (getNextToken() == tok_identifier)
+ ArgNames.push_back(IdentifierStr);
+ if (CurTok != ')')
+ return ErrorP("Expected ')' in prototype");
+
+ // success.
+ getNextToken(); // eat ')'.
+
+ // Verify right number of names for operator.
+ if (Kind && ArgNames.size() != Kind)
+ return ErrorP("Invalid number of operands for operator");
+
+ return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
+}
+
+/// definition ::= 'def' prototype expression
+static FunctionAST *ParseDefinition() {
+ getNextToken(); // eat def.
+ PrototypeAST *Proto = ParsePrototype();
+ if (Proto == 0) return 0;
+
+ if (ExprAST *E = ParseExpression())
+ return new FunctionAST(Proto, E);
+ return 0;
+}
+
+/// toplevelexpr ::= expression
+static FunctionAST *ParseTopLevelExpr() {
+ if (ExprAST *E = ParseExpression()) {
+ // Make an anonymous proto.
+ PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
+ return new FunctionAST(Proto, E);
+ }
+ return 0;
+}
+
+/// external ::= 'extern' prototype
+static PrototypeAST *ParseExtern() {
+ getNextToken(); // eat extern.
+ return ParsePrototype();
+}
+
+//===----------------------------------------------------------------------===//
+// Code Generation
+//===----------------------------------------------------------------------===//
+
+static Module *TheModule;
+static IRBuilder<> Builder(getGlobalContext());
+static std::map<std::string, AllocaInst*> NamedValues;
+static FunctionPassManager *TheFPM;
+
+Value *ErrorV(const char *Str) { Error(Str); return 0; }
+
+/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
+/// the function. This is used for mutable variables etc.
+static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
+ const std::string &VarName) {
+ IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
+ TheFunction->getEntryBlock().begin());
+ return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+ VarName.c_str());
+}
+
+Value *NumberExprAST::Codegen() {
+ return ConstantFP::get(getGlobalContext(), APFloat(Val));
+}
+
+Value *VariableExprAST::Codegen() {
+ // Look this variable up in the function.
+ Value *V = NamedValues[Name];
+ if (V == 0) return ErrorV("Unknown variable name");
+
+ // Load the value.
+ return Builder.CreateLoad(V, Name.c_str());
+}
+
+Value *UnaryExprAST::Codegen() {
+ Value *OperandV = Operand->Codegen();
+ if (OperandV == 0) return 0;
+
+ Function *F = TheModule->getFunction(std::string("unary")+Opcode);
+ if (F == 0)
+ return ErrorV("Unknown unary operator");
+
+ return Builder.CreateCall(F, OperandV, "unop");
+}
+
+Value *BinaryExprAST::Codegen() {
+ // Special case '=' because we don't want to emit the LHS as an expression.
+ if (Op == '=') {
+ // Assignment requires the LHS to be an identifier.
+ VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS);
+ if (!LHSE)
+ return ErrorV("destination of '=' must be a variable");
+ // Codegen the RHS.
+ Value *Val = RHS->Codegen();
+ if (Val == 0) return 0;
+
+ // Look up the name.
+ Value *Variable = NamedValues[LHSE->getName()];
+ if (Variable == 0) return ErrorV("Unknown variable name");
+
+ Builder.CreateStore(Val, Variable);
+ return Val;
+ }
+
+ Value *L = LHS->Codegen();
+ Value *R = RHS->Codegen();
+ if (L == 0 || R == 0) return 0;
+
+ switch (Op) {
+ case '+': return Builder.CreateFAdd(L, R, "addtmp");
+ case '-': return Builder.CreateFSub(L, R, "subtmp");
+ case '*': return Builder.CreateFMul(L, R, "multmp");
+ case '<':
+ L = Builder.CreateFCmpULT(L, R, "cmptmp");
+ // Convert bool 0/1 to double 0.0 or 1.0
+ return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+ "booltmp");
+ default: break;
+ }
+
+ // If it wasn't a builtin binary operator, it must be a user defined one. Emit
+ // a call to it.
+ Function *F = TheModule->getFunction(std::string("binary")+Op);
+ assert(F && "binary operator not found!");
+
+ Value *Ops[] = { L, R };
+ return Builder.CreateCall(F, Ops, "binop");
+}
+
+Value *CallExprAST::Codegen() {
+ // Look up the name in the global module table.
+ Function *CalleeF = TheModule->getFunction(Callee);
+ if (CalleeF == 0)
+ return ErrorV("Unknown function referenced");
+
+ // If argument mismatch error.
+ if (CalleeF->arg_size() != Args.size())
+ return ErrorV("Incorrect # arguments passed");
+
+ std::vector<Value*> ArgsV;
+ for (unsigned i = 0, e = Args.size(); i != e; ++i) {
+ ArgsV.push_back(Args[i]->Codegen());
+ if (ArgsV.back() == 0) return 0;
+ }
+
+ return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
+}
+
+Value *IfExprAST::Codegen() {
+ Value *CondV = Cond->Codegen();
+ if (CondV == 0) return 0;
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ CondV = Builder.CreateFCmpONE(CondV,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "ifcond");
+
+ Function *TheFunction = Builder.GetInsertBlock()->getParent();
+
+ // Create blocks for the then and else cases. Insert the 'then' block at the
+ // end of the function.
+ BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
+ BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
+ BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+
+ Builder.CreateCondBr(CondV, ThenBB, ElseBB);
+
+ // Emit then value.
+ Builder.SetInsertPoint(ThenBB);
+
+ Value *ThenV = Then->Codegen();
+ if (ThenV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
+ ThenBB = Builder.GetInsertBlock();
+
+ // Emit else block.
+ TheFunction->getBasicBlockList().push_back(ElseBB);
+ Builder.SetInsertPoint(ElseBB);
+
+ Value *ElseV = Else->Codegen();
+ if (ElseV == 0) return 0;
+
+ Builder.CreateBr(MergeBB);
+ // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
+ ElseBB = Builder.GetInsertBlock();
+
+ // Emit merge block.
+ TheFunction->getBasicBlockList().push_back(MergeBB);
+ Builder.SetInsertPoint(MergeBB);
+ PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+ "iftmp");
+
+ PN->addIncoming(ThenV, ThenBB);
+ PN->addIncoming(ElseV, ElseBB);
+ return PN;
+}
+
+Value *ForExprAST::Codegen() {
+ // Output this as:
+ // var = alloca double
+ // ...
+ // start = startexpr
+ // store start -> var
+ // goto loop
+ // loop:
+ // ...
+ // bodyexpr
+ // ...
+ // loopend:
+ // step = stepexpr
+ // endcond = endexpr
+ //
+ // curvar = load var
+ // nextvar = curvar + step
+ // store nextvar -> var
+ // br endcond, loop, endloop
+ // outloop:
+
+ Function *TheFunction = Builder.GetInsertBlock()->getParent();
+
+ // Create an alloca for the variable in the entry block.
+ AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
+
+ // Emit the start code first, without 'variable' in scope.
+ Value *StartVal = Start->Codegen();
+ if (StartVal == 0) return 0;
+
+ // Store the value into the alloca.
+ Builder.CreateStore(StartVal, Alloca);
+
+ // Make the new basic block for the loop header, inserting after current
+ // block.
+ BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+
+ // Insert an explicit fall through from the current block to the LoopBB.
+ Builder.CreateBr(LoopBB);
+
+ // Start insertion in LoopBB.
+ Builder.SetInsertPoint(LoopBB);
+
+ // Within the loop, the variable is defined equal to the PHI node. If it
+ // shadows an existing variable, we have to restore it, so save it now.
+ AllocaInst *OldVal = NamedValues[VarName];
+ NamedValues[VarName] = Alloca;
+
+ // Emit the body of the loop. This, like any other expr, can change the
+ // current BB. Note that we ignore the value computed by the body, but don't
+ // allow an error.
+ if (Body->Codegen() == 0)
+ return 0;
+
+ // Emit the step value.
+ Value *StepVal;
+ if (Step) {
+ StepVal = Step->Codegen();
+ if (StepVal == 0) return 0;
+ } else {
+ // If not specified, use 1.0.
+ StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+ }
+
+ // Compute the end condition.
+ Value *EndCond = End->Codegen();
+ if (EndCond == 0) return EndCond;
+
+ // Reload, increment, and restore the alloca. This handles the case where
+ // the body of the loop mutates the variable.
+ Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
+ Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
+ Builder.CreateStore(NextVar, Alloca);
+
+ // Convert condition to a bool by comparing equal to 0.0.
+ EndCond = Builder.CreateFCmpONE(EndCond,
+ ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+ "loopcond");
+
+ // Create the "after loop" block and insert it.
+ BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+
+ // Insert the conditional branch into the end of LoopEndBB.
+ Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
+
+ // Any new code will be inserted in AfterBB.
+ Builder.SetInsertPoint(AfterBB);
+
+ // Restore the unshadowed variable.
+ if (OldVal)
+ NamedValues[VarName] = OldVal;
+ else
+ NamedValues.erase(VarName);
+
+
+ // for expr always returns 0.0.
+ return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+}
+
+Value *VarExprAST::Codegen() {
+ std::vector<AllocaInst *> OldBindings;
+
+ Function *TheFunction = Builder.GetInsertBlock()->getParent();
+
+ // Register all variables and emit their initializer.
+ for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
+ const std::string &VarName = VarNames[i].first;
+ ExprAST *Init = VarNames[i].second;
+
+ // Emit the initializer before adding the variable to scope, this prevents
+ // the initializer from referencing the variable itself, and permits stuff
+ // like this:
+ // var a = 1 in
+ // var a = a in ... # refers to outer 'a'.
+ Value *InitVal;
+ if (Init) {
+ InitVal = Init->Codegen();
+ if (InitVal == 0) return 0;
+ } else { // If not specified, use 0.0.
+ InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+ }
+
+ AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
+ Builder.CreateStore(InitVal, Alloca);
+
+ // Remember the old variable binding so that we can restore the binding when
+ // we unrecurse.
+ OldBindings.push_back(NamedValues[VarName]);
+
+ // Remember this binding.
+ NamedValues[VarName] = Alloca;
+ }
+
+ // Codegen the body, now that all vars are in scope.
+ Value *BodyVal = Body->Codegen();
+ if (BodyVal == 0) return 0;
+
+ // Pop all our variables from scope.
+ for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
+ NamedValues[VarNames[i].first] = OldBindings[i];
+
+ // Return the body computation.
+ return BodyVal;
+}
+
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector<Type*> Doubles(Args.size(),
+ Type::getDoubleTy(getGlobalContext()));
+ FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+ Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F->getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F->eraseFromParent();
+ F = TheModule->getFunction(Name);
+
+ // If F already has a body, reject this.
+ if (!F->empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F->arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
+ ++AI, ++Idx)
+ AI->setName(Args[Idx]);
+
+ return F;
+}
+
+/// CreateArgumentAllocas - Create an alloca for each argument and register the
+/// argument in the symbol table so that references to it will succeed.
+void PrototypeAST::CreateArgumentAllocas(Function *F) {
+ Function::arg_iterator AI = F->arg_begin();
+ for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
+ // Create an alloca for this variable.
+ AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
+
+ // Store the initial value into the alloca.
+ Builder.CreateStore(AI, Alloca);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = Alloca;
+ }
+}
+
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto->Codegen();
+ if (TheFunction == 0)
+ return 0;
+
+ // If this is an operator, install it.
+ if (Proto->isBinaryOp())
+ BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
+
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ // Add all arguments to the symbol table and create their allocas.
+ Proto->CreateArgumentAllocas(TheFunction);
+
+ if (Value *RetVal = Body->Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+
+ // Optimize the function.
+ TheFPM->run(*TheFunction);
+
+ return TheFunction;
+ }
+
+ // Error reading body, remove function.
+ TheFunction->eraseFromParent();
+
+ if (Proto->isBinaryOp())
+ BinopPrecedence.erase(Proto->getOperatorName());
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Top-Level parsing and JIT Driver
+//===----------------------------------------------------------------------===//
+
+static ExecutionEngine *TheExecutionEngine;
+
+static void HandleDefinition() {
+ if (FunctionAST *F = ParseDefinition()) {
+ if (Function *LF = F->Codegen()) {
+ fprintf(stderr, "Read function definition:");
+ LF->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleExtern() {
+ if (PrototypeAST *P = ParseExtern()) {
+ if (Function *F = P->Codegen()) {
+ fprintf(stderr, "Read extern: ");
+ F->dump();
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (FunctionAST *F = ParseTopLevelExpr()) {
+ if (Function *LF = F->Codegen()) {
+ // JIT the function, returning a function pointer.
+ void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
+
+ // Cast it to the right type (takes no arguments, returns a double) so we
+ // can call it as a native function.
+ double (*FP)() = (double (*)())(intptr_t)FPtr;
+ fprintf(stderr, "Evaluated to %f\n", FP());
+ }
+ } else {
+ // Skip token for error recovery.
+ getNextToken();
+ }
+}
+
+/// top ::= definition | external | expression | ';'
+static void MainLoop() {
+ while (1) {
+ fprintf(stderr, "ready> ");
+ switch (CurTok) {
+ case tok_eof: return;
+ case ';': getNextToken(); break; // ignore top-level semicolons.
+ case tok_def: HandleDefinition(); break;
+ case tok_extern: HandleExtern(); break;
+ default: HandleTopLevelExpression(); break;
+ }
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// "Library" functions that can be "extern'd" from user code.
+//===----------------------------------------------------------------------===//
+
+/// putchard - putchar that takes a double and returns 0.
+extern "C"
+double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+/// printd - printf that takes a double prints it as "%f\n", returning 0.
+extern "C"
+double printd(double X) {
+ printf("%f\n", X);
+ return 0;
+}
+
+//===----------------------------------------------------------------------===//
+// Main driver code.
+//===----------------------------------------------------------------------===//
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext &Context = getGlobalContext();
+
+ // Install standard binary operators.
+ // 1 is lowest precedence.
+ BinopPrecedence['='] = 2;
+ BinopPrecedence['<'] = 10;
+ BinopPrecedence['+'] = 20;
+ BinopPrecedence['-'] = 20;
+ BinopPrecedence['*'] = 40; // highest.
+
+ // Prime the first token.
+ fprintf(stderr, "ready> ");
+ getNextToken();
+
+ // Make the module, which holds all the code.
+ TheModule = new Module("my cool jit", Context);
+
+ // Create the JIT. This takes ownership of the module.
+ std::string ErrStr;
+ TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
+ if (!TheExecutionEngine) {
+ fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+ exit(1);
+ }
+
+ FunctionPassManager OurFPM(TheModule);
+
+ // Set up the optimizer pipeline. Start with registering info about how the
+ // target lays out data structures.
+ OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
+ // Provide basic AliasAnalysis support for GVN.
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Promote allocas to registers.
+ OurFPM.add(createPromoteMemoryToRegisterPass());
+ // Do simple "peephole" optimizations and bit-twiddling optzns.
+ OurFPM.add(createInstructionCombiningPass());
+ // Reassociate expressions.
+ OurFPM.add(createReassociatePass());
+ // Eliminate Common SubExpressions.
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+
+ OurFPM.doInitialization();
+
+ // Set the global so the code gen can use this.
+ TheFPM = &OurFPM;
+
+ // Run the main "interpreter loop" now.
+ MainLoop();
+
+ TheFPM = 0;
+
+ // Print out all of the generated code.
+ TheModule->dump();
+
+ return 0;
+}
diff --git a/examples/Kaleidoscope/Makefile b/examples/Kaleidoscope/Makefile
new file mode 100644
index 00000000000..bd0c252c2c0
--- /dev/null
+++ b/examples/Kaleidoscope/Makefile
@@ -0,0 +1,15 @@
+##===- examples/Kaleidoscope/Makefile ----------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL=../..
+
+include $(LEVEL)/Makefile.config
+
+PARALLEL_DIRS:= Chapter2 Chapter3 Chapter4 Chapter5 Chapter6 Chapter7
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/LLVMBuild.txt b/examples/LLVMBuild.txt
new file mode 100644
index 00000000000..4d06ffb995f
--- /dev/null
+++ b/examples/LLVMBuild.txt
@@ -0,0 +1,21 @@
+;===- ./examples/LLVMBuild.txt ---------------------------------*- Conf -*--===;
+;
+; The LLVM Compiler Infrastructure
+;
+; This file is distributed under the University of Illinois Open Source
+; License. See LICENSE.TXT for details.
+;
+;===------------------------------------------------------------------------===;
+;
+; This is an LLVMBuild description file for the components in this subdirectory.
+;
+; For more information on the LLVMBuild system, please see:
+;
+; http://llvm.org/docs/LLVMBuild.html
+;
+;===------------------------------------------------------------------------===;
+
+[component_0]
+type = Group
+name = Examples
+parent = $ROOT
diff --git a/examples/Makefile b/examples/Makefile
new file mode 100644
index 00000000000..50a6db76aa2
--- /dev/null
+++ b/examples/Makefile
@@ -0,0 +1,32 @@
+##===- examples/Makefile -----------------------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL=..
+
+include $(LEVEL)/Makefile.config
+
+PARALLEL_DIRS:= BrainF Fibonacci HowToUseJIT Kaleidoscope ModuleMaker
+
+ifeq ($(HAVE_PTHREAD),1)
+PARALLEL_DIRS += ParallelJIT
+endif
+
+ifeq ($(LLVM_ON_UNIX),1)
+ ifeq ($(ARCH),x86)
+ PARALLEL_DIRS += ExceptionDemo
+ endif
+ ifeq ($(ARCH),x86_64)
+ PARALLEL_DIRS += ExceptionDemo
+ endif
+endif
+
+ifeq ($(filter $(BINDINGS_TO_BUILD),ocaml),ocaml)
+ PARALLEL_DIRS += OCaml-Kaleidoscope
+endif
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/ModuleMaker/CMakeLists.txt b/examples/ModuleMaker/CMakeLists.txt
new file mode 100644
index 00000000000..81e911560bd
--- /dev/null
+++ b/examples/ModuleMaker/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(LLVM_LINK_COMPONENTS bitwriter)
+
+add_llvm_example(ModuleMaker
+ ModuleMaker.cpp
+ )
diff --git a/examples/ModuleMaker/Makefile b/examples/ModuleMaker/Makefile
new file mode 100644
index 00000000000..9454cf514dc
--- /dev/null
+++ b/examples/ModuleMaker/Makefile
@@ -0,0 +1,14 @@
+##===- examples/ModuleMaker/Makefile -----------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL=../..
+TOOLNAME=ModuleMaker
+EXAMPLE_TOOL = 1
+LINK_COMPONENTS := bitwriter
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/ModuleMaker/ModuleMaker.cpp b/examples/ModuleMaker/ModuleMaker.cpp
new file mode 100644
index 00000000000..6bc52c12a03
--- /dev/null
+++ b/examples/ModuleMaker/ModuleMaker.cpp
@@ -0,0 +1,64 @@
+//===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This programs is a simple example that creates an LLVM module "from scratch",
+// emitting it as a bitcode file to standard out. This is just to show how
+// LLVM projects work and to demonstrate some of the LLVM APIs.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/Constants.h"
+#include "llvm/Instructions.h"
+#include "llvm/Bitcode/ReaderWriter.h"
+#include "llvm/Support/raw_ostream.h"
+using namespace llvm;
+
+int main() {
+ LLVMContext Context;
+
+ // Create the "module" or "program" or "translation unit" to hold the
+ // function
+ Module *M = new Module("test", Context);
+
+ // Create the main function: first create the type 'int ()'
+ FunctionType *FT =
+ FunctionType::get(Type::getInt32Ty(Context), /*not vararg*/false);
+
+ // By passing a module as the last parameter to the Function constructor,
+ // it automatically gets appended to the Module.
+ Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);
+
+ // Add a basic block to the function... again, it automatically inserts
+ // because of the last argument.
+ BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", F);
+
+ // Get pointers to the constant integers...
+ Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
+ Value *Three = ConstantInt::get(Type::getInt32Ty(Context), 3);
+
+ // Create the add instruction... does not insert...
+ Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,
+ "addresult");
+
+ // explicitly insert it into the basic block...
+ BB->getInstList().push_back(Add);
+
+ // Create the return instruction and add it to the basic block
+ BB->getInstList().push_back(ReturnInst::Create(Context, Add));
+
+ // Output the bitcode file to stdout
+ WriteBitcodeToFile(M, outs());
+
+ // Delete the module and all of its contents.
+ delete M;
+ return 0;
+}
diff --git a/examples/ModuleMaker/README.txt b/examples/ModuleMaker/README.txt
new file mode 100644
index 00000000000..66a5d3fe0b1
--- /dev/null
+++ b/examples/ModuleMaker/README.txt
@@ -0,0 +1,8 @@
+//===----------------------------------------------------------------------===//
+// ModuleMaker Sample project
+//===----------------------------------------------------------------------===//
+
+This project is an extremely simple example of using some simple pieces of the
+LLVM API. The actual executable generated by this project simply emits an
+LLVM bitcode file to standard output. It is designed to show some basic
+usage of LLVM APIs, and how to link to LLVM libraries.
diff --git a/examples/OCaml-Kaleidoscope/Chapter2/Makefile b/examples/OCaml-Kaleidoscope/Chapter2/Makefile
new file mode 100644
index 00000000000..8fc03da0fbd
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter2/Makefile
@@ -0,0 +1,22 @@
+##===- examples/OCaml-Kaleidoscope/Chapter2/Makefile -------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 2.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+TOOLNAME := OCaml-Kaleidoscope-Ch2
+EXAMPLE_TOOL := 1
+UsedComponents := core
+UsedOcamLibs := llvm
+
+OCAMLCFLAGS += -pp camlp4of
+
+include $(LEVEL)/bindings/ocaml/Makefile.ocaml
diff --git a/examples/OCaml-Kaleidoscope/Chapter2/_tags b/examples/OCaml-Kaleidoscope/Chapter2/_tags
new file mode 100644
index 00000000000..7b9b80b1e94
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter2/_tags
@@ -0,0 +1 @@
+<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
diff --git a/examples/OCaml-Kaleidoscope/Chapter2/ast.ml b/examples/OCaml-Kaleidoscope/Chapter2/ast.ml
new file mode 100644
index 00000000000..4cc2dea86b7
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter2/ast.ml
@@ -0,0 +1,25 @@
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
diff --git a/examples/OCaml-Kaleidoscope/Chapter2/lexer.ml b/examples/OCaml-Kaleidoscope/Chapter2/lexer.ml
new file mode 100644
index 00000000000..22a915552f0
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter2/lexer.ml
@@ -0,0 +1,52 @@
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [< ' ('0' .. '9' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [< ' ('#'); stream >] ->
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [< 'c; stream >] ->
+ [< 'Token.Kwd c; lex stream >]
+
+ (* end of stream. *)
+ | [< >] -> [< >]
+
+and lex_number buffer = parser
+ | [< ' ('0' .. '9' | '.' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [< stream=lex >] ->
+ [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
+
+and lex_ident buffer = parser
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [< stream=lex >] ->
+ match Buffer.contents buffer with
+ | "def" -> [< 'Token.Def; stream >]
+ | "extern" -> [< 'Token.Extern; stream >]
+ | id -> [< 'Token.Ident id; stream >]
+
+and lex_comment = parser
+ | [< ' ('\n'); stream=lex >] -> stream
+ | [< 'c; e=lex_comment >] -> e
+ | [< >] -> [< >]
diff --git a/examples/OCaml-Kaleidoscope/Chapter2/parser.ml b/examples/OCaml-Kaleidoscope/Chapter2/parser.ml
new file mode 100644
index 00000000000..83d9874a4ab
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter2/parser.ml
@@ -0,0 +1,122 @@
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [< 'Token.Number n >] -> Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [< 'Token.Ident id; stream >] ->
+ let rec parse_args accumulator = parser
+ | [< e=parse_expr; stream >] ->
+ begin parser
+ | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
+ | [< >] -> e :: accumulator
+ end stream
+ | [< >] -> accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [< 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'">] ->
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [< >] -> Ast.Variable id
+ in
+ parse_ident id stream
+
+ | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec < expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_primary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) ->
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec < next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -> rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -> lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
+ | [< >] -> accumulator
+ in
+
+ parser
+ | [< 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [< >] ->
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [< e=parse_expr >] ->
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [< 'Token.Extern; e=parse_prototype >] -> e
diff --git a/examples/OCaml-Kaleidoscope/Chapter2/token.ml b/examples/OCaml-Kaleidoscope/Chapter2/token.ml
new file mode 100644
index 00000000000..2ca782e1499
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter2/token.ml
@@ -0,0 +1,15 @@
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
diff --git a/examples/OCaml-Kaleidoscope/Chapter2/toplevel.ml b/examples/OCaml-Kaleidoscope/Chapter2/toplevel.ml
new file mode 100644
index 00000000000..01c85bd70d2
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter2/toplevel.ml
@@ -0,0 +1,34 @@
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop stream =
+ match Stream.peek stream with
+ | None -> ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') ->
+ Stream.junk stream;
+ main_loop stream
+
+ | Some token ->
+ begin
+ try match token with
+ | Token.Def ->
+ ignore(Parser.parse_definition stream);
+ print_endline "parsed a function definition.";
+ | Token.Extern ->
+ ignore(Parser.parse_extern stream);
+ print_endline "parsed an extern.";
+ | _ ->
+ (* Evaluate a top-level expression into an anonymous function. *)
+ ignore(Parser.parse_toplevel stream);
+ print_endline "parsed a top-level expr";
+ with Stream.Error s ->
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready> "; flush stdout;
+ main_loop stream
diff --git a/examples/OCaml-Kaleidoscope/Chapter2/toy.ml b/examples/OCaml-Kaleidoscope/Chapter2/toy.ml
new file mode 100644
index 00000000000..42b19fec001
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter2/toy.ml
@@ -0,0 +1,21 @@
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+let main () =
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '<' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready> "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop stream;
+;;
+
+main ()
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/Makefile b/examples/OCaml-Kaleidoscope/Chapter3/Makefile
new file mode 100644
index 00000000000..fdbcd5191f4
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/Makefile
@@ -0,0 +1,24 @@
+##===- examples/OCaml-Kaleidoscope/Chapter3/Makefile -------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 3.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+TOOLNAME := OCaml-Kaleidoscope-Ch3
+EXAMPLE_TOOL := 1
+UsedComponents := core
+UsedOcamLibs := llvm llvm_analysis
+
+OCAMLCFLAGS += -pp camlp4of
+
+ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
+
+include $(LEVEL)/bindings/ocaml/Makefile.ocaml
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/_tags b/examples/OCaml-Kaleidoscope/Chapter3/_tags
new file mode 100644
index 00000000000..990490a5db2
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/_tags
@@ -0,0 +1,2 @@
+<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
+<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/ast.ml b/examples/OCaml-Kaleidoscope/Chapter3/ast.ml
new file mode 100644
index 00000000000..4cc2dea86b7
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/ast.ml
@@ -0,0 +1,25 @@
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/codegen.ml b/examples/OCaml-Kaleidoscope/Chapter3/codegen.ml
new file mode 100644
index 00000000000..275cd0bee04
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/codegen.ml
@@ -0,0 +1,100 @@
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+let rec codegen_expr = function
+ | Ast.Number n -> const_float double_type n
+ | Ast.Variable name ->
+ (try Hashtbl.find named_values name with
+ | Not_found -> raise (Error "unknown variable name"))
+ | Ast.Binary (op, lhs, rhs) ->
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -> build_add lhs_val rhs_val "addtmp" builder
+ | '-' -> build_sub lhs_val rhs_val "subtmp" builder
+ | '*' -> build_mul lhs_val rhs_val "multmp" builder
+ | '<' ->
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -> raise (Error "invalid binary operator")
+ end
+ | Ast.Call (callee, args) ->
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) ->
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -> declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f ->
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f <> At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) <> ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a ->
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+let codegen_func = function
+ | Ast.Function (proto, body) ->
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ the_function
+ with e ->
+ delete_function the_function;
+ raise e
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/lexer.ml b/examples/OCaml-Kaleidoscope/Chapter3/lexer.ml
new file mode 100644
index 00000000000..22a915552f0
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/lexer.ml
@@ -0,0 +1,52 @@
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [< ' ('0' .. '9' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [< ' ('#'); stream >] ->
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [< 'c; stream >] ->
+ [< 'Token.Kwd c; lex stream >]
+
+ (* end of stream. *)
+ | [< >] -> [< >]
+
+and lex_number buffer = parser
+ | [< ' ('0' .. '9' | '.' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [< stream=lex >] ->
+ [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
+
+and lex_ident buffer = parser
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [< stream=lex >] ->
+ match Buffer.contents buffer with
+ | "def" -> [< 'Token.Def; stream >]
+ | "extern" -> [< 'Token.Extern; stream >]
+ | id -> [< 'Token.Ident id; stream >]
+
+and lex_comment = parser
+ | [< ' ('\n'); stream=lex >] -> stream
+ | [< 'c; e=lex_comment >] -> e
+ | [< >] -> [< >]
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/myocamlbuild.ml b/examples/OCaml-Kaleidoscope/Chapter3/myocamlbuild.ml
new file mode 100644
index 00000000000..b71f5d717ef
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/myocamlbuild.ml
@@ -0,0 +1,6 @@
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/parser.ml b/examples/OCaml-Kaleidoscope/Chapter3/parser.ml
new file mode 100644
index 00000000000..83d9874a4ab
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/parser.ml
@@ -0,0 +1,122 @@
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [< 'Token.Number n >] -> Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [< 'Token.Ident id; stream >] ->
+ let rec parse_args accumulator = parser
+ | [< e=parse_expr; stream >] ->
+ begin parser
+ | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
+ | [< >] -> e :: accumulator
+ end stream
+ | [< >] -> accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [< 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'">] ->
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [< >] -> Ast.Variable id
+ in
+ parse_ident id stream
+
+ | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec < expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_primary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) ->
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec < next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -> rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -> lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
+ | [< >] -> accumulator
+ in
+
+ parser
+ | [< 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [< >] ->
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [< e=parse_expr >] ->
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [< 'Token.Extern; e=parse_prototype >] -> e
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/token.ml b/examples/OCaml-Kaleidoscope/Chapter3/token.ml
new file mode 100644
index 00000000000..2ca782e1499
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/token.ml
@@ -0,0 +1,15 @@
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/toplevel.ml b/examples/OCaml-Kaleidoscope/Chapter3/toplevel.ml
new file mode 100644
index 00000000000..d1bf5d4c0c6
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/toplevel.ml
@@ -0,0 +1,39 @@
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop stream =
+ match Stream.peek stream with
+ | None -> ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') ->
+ Stream.junk stream;
+ main_loop stream
+
+ | Some token ->
+ begin
+ try match token with
+ | Token.Def ->
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func e);
+ | Token.Extern ->
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ ->
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ dump_value (Codegen.codegen_func e);
+ with Stream.Error s | Codegen.Error s ->
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready> "; flush stdout;
+ main_loop stream
diff --git a/examples/OCaml-Kaleidoscope/Chapter3/toy.ml b/examples/OCaml-Kaleidoscope/Chapter3/toy.ml
new file mode 100644
index 00000000000..73c1a1ec62a
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter3/toy.ml
@@ -0,0 +1,26 @@
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+let main () =
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '<' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready> "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/Makefile b/examples/OCaml-Kaleidoscope/Chapter4/Makefile
new file mode 100644
index 00000000000..d9c3f49bea6
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/Makefile
@@ -0,0 +1,25 @@
+##===- examples/OCaml-Kaleidoscope/Chapter4/Makefile -------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 4.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+TOOLNAME := OCaml-Kaleidoscope-Ch4
+EXAMPLE_TOOL := 1
+UsedComponents := core
+UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \
+ llvm_scalar_opts
+
+OCAMLCFLAGS += -pp camlp4of
+
+ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
+
+include $(LEVEL)/bindings/ocaml/Makefile.ocaml
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/_tags b/examples/OCaml-Kaleidoscope/Chapter4/_tags
new file mode 100644
index 00000000000..7a03dba6672
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/_tags
@@ -0,0 +1,4 @@
+<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
+<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
+<*.{byte,native}>: use_llvm_executionengine, use_llvm_target
+<*.{byte,native}>: use_llvm_scalar_opts, use_bindings
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/ast.ml b/examples/OCaml-Kaleidoscope/Chapter4/ast.ml
new file mode 100644
index 00000000000..4cc2dea86b7
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/ast.ml
@@ -0,0 +1,25 @@
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/bindings.c b/examples/OCaml-Kaleidoscope/Chapter4/bindings.c
new file mode 100644
index 00000000000..053513bf0c0
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/bindings.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+
+/* putchard - putchar that takes a double and returns 0. */
+extern double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/codegen.ml b/examples/OCaml-Kaleidoscope/Chapter4/codegen.ml
new file mode 100644
index 00000000000..8957f4c610f
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/codegen.ml
@@ -0,0 +1,103 @@
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+let rec codegen_expr = function
+ | Ast.Number n -> const_float double_type n
+ | Ast.Variable name ->
+ (try Hashtbl.find named_values name with
+ | Not_found -> raise (Error "unknown variable name"))
+ | Ast.Binary (op, lhs, rhs) ->
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -> build_fadd lhs_val rhs_val "addtmp" builder
+ | '-' -> build_fsub lhs_val rhs_val "subtmp" builder
+ | '*' -> build_fmul lhs_val rhs_val "multmp" builder
+ | '<' ->
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -> raise (Error "invalid binary operator")
+ end
+ | Ast.Call (callee, args) ->
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) ->
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -> declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f ->
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f <> At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) <> ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a ->
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) ->
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+ with e ->
+ delete_function the_function;
+ raise e
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/lexer.ml b/examples/OCaml-Kaleidoscope/Chapter4/lexer.ml
new file mode 100644
index 00000000000..22a915552f0
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/lexer.ml
@@ -0,0 +1,52 @@
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [< ' ('0' .. '9' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [< ' ('#'); stream >] ->
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [< 'c; stream >] ->
+ [< 'Token.Kwd c; lex stream >]
+
+ (* end of stream. *)
+ | [< >] -> [< >]
+
+and lex_number buffer = parser
+ | [< ' ('0' .. '9' | '.' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [< stream=lex >] ->
+ [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
+
+and lex_ident buffer = parser
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [< stream=lex >] ->
+ match Buffer.contents buffer with
+ | "def" -> [< 'Token.Def; stream >]
+ | "extern" -> [< 'Token.Extern; stream >]
+ | id -> [< 'Token.Ident id; stream >]
+
+and lex_comment = parser
+ | [< ' ('\n'); stream=lex >] -> stream
+ | [< 'c; e=lex_comment >] -> e
+ | [< >] -> [< >]
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/myocamlbuild.ml b/examples/OCaml-Kaleidoscope/Chapter4/myocamlbuild.ml
new file mode 100644
index 00000000000..ff42664c43b
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/myocamlbuild.ml
@@ -0,0 +1,10 @@
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+ocaml_lib ~extern:true "llvm_executionengine";;
+ocaml_lib ~extern:true "llvm_target";;
+ocaml_lib ~extern:true "llvm_scalar_opts";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
+dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/parser.ml b/examples/OCaml-Kaleidoscope/Chapter4/parser.ml
new file mode 100644
index 00000000000..83d9874a4ab
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/parser.ml
@@ -0,0 +1,122 @@
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [< 'Token.Number n >] -> Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [< 'Token.Ident id; stream >] ->
+ let rec parse_args accumulator = parser
+ | [< e=parse_expr; stream >] ->
+ begin parser
+ | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
+ | [< >] -> e :: accumulator
+ end stream
+ | [< >] -> accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [< 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'">] ->
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [< >] -> Ast.Variable id
+ in
+ parse_ident id stream
+
+ | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec < expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_primary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) ->
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec < next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -> rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -> lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
+ | [< >] -> accumulator
+ in
+
+ parser
+ | [< 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [< >] ->
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [< e=parse_expr >] ->
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [< 'Token.Extern; e=parse_prototype >] -> e
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/token.ml b/examples/OCaml-Kaleidoscope/Chapter4/token.ml
new file mode 100644
index 00000000000..2ca782e1499
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/token.ml
@@ -0,0 +1,15 @@
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/toplevel.ml b/examples/OCaml-Kaleidoscope/Chapter4/toplevel.ml
new file mode 100644
index 00000000000..01d24ede149
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/toplevel.ml
@@ -0,0 +1,49 @@
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop the_fpm the_execution_engine stream =
+ match Stream.peek stream with
+ | None -> ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') ->
+ Stream.junk stream;
+ main_loop the_fpm the_execution_engine stream
+
+ | Some token ->
+ begin
+ try match token with
+ | Token.Def ->
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func the_fpm e);
+ | Token.Extern ->
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ ->
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+ with Stream.Error s | Codegen.Error s ->
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready> "; flush stdout;
+ main_loop the_fpm the_execution_engine stream
diff --git a/examples/OCaml-Kaleidoscope/Chapter4/toy.ml b/examples/OCaml-Kaleidoscope/Chapter4/toy.ml
new file mode 100644
index 00000000000..5f9d912499c
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter4/toy.ml
@@ -0,0 +1,53 @@
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+open Llvm_target
+open Llvm_scalar_opts
+
+let main () =
+ ignore (initialize_native_target ());
+
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '<' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready> "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combination the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/Makefile b/examples/OCaml-Kaleidoscope/Chapter5/Makefile
new file mode 100644
index 00000000000..f31c10d3c2f
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/Makefile
@@ -0,0 +1,25 @@
+##===- examples/OCaml-Kaleidoscope/Chapter5/Makefile -------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 5.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+TOOLNAME := OCaml-Kaleidoscope-Ch5
+EXAMPLE_TOOL := 1
+UsedComponents := core
+UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \
+ llvm_scalar_opts
+
+OCAMLCFLAGS += -pp camlp4of
+
+ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
+
+include $(LEVEL)/bindings/ocaml/Makefile.ocaml
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/_tags b/examples/OCaml-Kaleidoscope/Chapter5/_tags
new file mode 100644
index 00000000000..7a03dba6672
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/_tags
@@ -0,0 +1,4 @@
+<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
+<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
+<*.{byte,native}>: use_llvm_executionengine, use_llvm_target
+<*.{byte,native}>: use_llvm_scalar_opts, use_bindings
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/ast.ml b/examples/OCaml-Kaleidoscope/Chapter5/ast.ml
new file mode 100644
index 00000000000..8a6703db837
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/ast.ml
@@ -0,0 +1,31 @@
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+ (* variant for if/then/else. *)
+ | If of expr * expr * expr
+
+ (* variant for for/in. *)
+ | For of string * expr * expr * expr option * expr
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto = Prototype of string * string array
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/bindings.c b/examples/OCaml-Kaleidoscope/Chapter5/bindings.c
new file mode 100644
index 00000000000..053513bf0c0
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/bindings.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+
+/* putchard - putchar that takes a double and returns 0. */
+extern double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/codegen.ml b/examples/OCaml-Kaleidoscope/Chapter5/codegen.ml
new file mode 100644
index 00000000000..e4570a65759
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/codegen.ml
@@ -0,0 +1,225 @@
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+let rec codegen_expr = function
+ | Ast.Number n -> const_float double_type n
+ | Ast.Variable name ->
+ (try Hashtbl.find named_values name with
+ | Not_found -> raise (Error "unknown variable name"))
+ | Ast.Binary (op, lhs, rhs) ->
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -> build_fadd lhs_val rhs_val "addtmp" builder
+ | '-' -> build_fsub lhs_val rhs_val "subtmp" builder
+ | '*' -> build_fmul lhs_val rhs_val "multmp" builder
+ | '<' ->
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ -> raise (Error "invalid binary operator")
+ end
+ | Ast.Call (callee, args) ->
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+ | Ast.If (cond, then_, else_) ->
+ let cond = codegen_expr cond in
+
+ (* Convert condition to a bool by comparing equal to 0.0 *)
+ let zero = const_float double_type 0.0 in
+ let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
+
+ (* Grab the first block so that we might later add the conditional branch
+ * to it at the end of the function. *)
+ let start_bb = insertion_block builder in
+ let the_function = block_parent start_bb in
+
+ let then_bb = append_block context "then" the_function in
+
+ (* Emit 'then' value. *)
+ position_at_end then_bb builder;
+ let then_val = codegen_expr then_ in
+
+ (* Codegen of 'then' can change the current block, update then_bb for the
+ * phi. We create a new name because one is used for the phi node, and the
+ * other is used for the conditional branch. *)
+ let new_then_bb = insertion_block builder in
+
+ (* Emit 'else' value. *)
+ let else_bb = append_block context "else" the_function in
+ position_at_end else_bb builder;
+ let else_val = codegen_expr else_ in
+
+ (* Codegen of 'else' can change the current block, update else_bb for the
+ * phi. *)
+ let new_else_bb = insertion_block builder in
+
+ (* Emit merge block. *)
+ let merge_bb = append_block context "ifcont" the_function in
+ position_at_end merge_bb builder;
+ let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
+ let phi = build_phi incoming "iftmp" builder in
+
+ (* Return to the start block to add the conditional branch. *)
+ position_at_end start_bb builder;
+ ignore (build_cond_br cond_val then_bb else_bb builder);
+
+ (* Set a unconditional branch at the end of the 'then' block and the
+ * 'else' block to the 'merge' block. *)
+ position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
+ position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
+
+ (* Finally, set the builder to the end of the merge block. *)
+ position_at_end merge_bb builder;
+
+ phi
+ | Ast.For (var_name, start, end_, step, body) ->
+ (* Emit the start code first, without 'variable' in scope. *)
+ let start_val = codegen_expr start in
+
+ (* Make the new basic block for the loop header, inserting after current
+ * block. *)
+ let preheader_bb = insertion_block builder in
+ let the_function = block_parent preheader_bb in
+ let loop_bb = append_block context "loop" the_function in
+
+ (* Insert an explicit fall through from the current block to the
+ * loop_bb. *)
+ ignore (build_br loop_bb builder);
+
+ (* Start insertion in loop_bb. *)
+ position_at_end loop_bb builder;
+
+ (* Start the PHI node with an entry for start. *)
+ let variable = build_phi [(start_val, preheader_bb)] var_name builder in
+
+ (* Within the loop, the variable is defined equal to the PHI node. If it
+ * shadows an existing variable, we have to restore it, so save it
+ * now. *)
+ let old_val =
+ try Some (Hashtbl.find named_values var_name) with Not_found -> None
+ in
+ Hashtbl.add named_values var_name variable;
+
+ (* Emit the body of the loop. This, like any other expr, can change the
+ * current BB. Note that we ignore the value computed by the body, but
+ * don't allow an error *)
+ ignore (codegen_expr body);
+
+ (* Emit the step value. *)
+ let step_val =
+ match step with
+ | Some step -> codegen_expr step
+ (* If not specified, use 1.0. *)
+ | None -> const_float double_type 1.0
+ in
+
+ let next_var = build_add variable step_val "nextvar" builder in
+
+ (* Compute the end condition. *)
+ let end_cond = codegen_expr end_ in
+
+ (* Convert condition to a bool by comparing equal to 0.0. *)
+ let zero = const_float double_type 0.0 in
+ let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
+
+ (* Create the "after loop" block and insert it. *)
+ let loop_end_bb = insertion_block builder in
+ let after_bb = append_block context "afterloop" the_function in
+
+ (* Insert the conditional branch into the end of loop_end_bb. *)
+ ignore (build_cond_br end_cond loop_bb after_bb builder);
+
+ (* Any new code will be inserted in after_bb. *)
+ position_at_end after_bb builder;
+
+ (* Add a new entry to the PHI node for the backedge. *)
+ add_incoming (next_var, loop_end_bb) variable;
+
+ (* Restore the unshadowed variable. *)
+ begin match old_val with
+ | Some old_val -> Hashtbl.add named_values var_name old_val
+ | None -> ()
+ end;
+
+ (* for expr always returns 0.0. *)
+ const_null double_type
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) ->
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -> declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f ->
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f <> At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) <> ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a ->
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) ->
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+ with e ->
+ delete_function the_function;
+ raise e
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/lexer.ml b/examples/OCaml-Kaleidoscope/Chapter5/lexer.ml
new file mode 100644
index 00000000000..d8c1d563010
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/lexer.ml
@@ -0,0 +1,57 @@
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [< ' ('0' .. '9' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [< ' ('#'); stream >] ->
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [< 'c; stream >] ->
+ [< 'Token.Kwd c; lex stream >]
+
+ (* end of stream. *)
+ | [< >] -> [< >]
+
+and lex_number buffer = parser
+ | [< ' ('0' .. '9' | '.' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [< stream=lex >] ->
+ [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
+
+and lex_ident buffer = parser
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [< stream=lex >] ->
+ match Buffer.contents buffer with
+ | "def" -> [< 'Token.Def; stream >]
+ | "extern" -> [< 'Token.Extern; stream >]
+ | "if" -> [< 'Token.If; stream >]
+ | "then" -> [< 'Token.Then; stream >]
+ | "else" -> [< 'Token.Else; stream >]
+ | "for" -> [< 'Token.For; stream >]
+ | "in" -> [< 'Token.In; stream >]
+ | id -> [< 'Token.Ident id; stream >]
+
+and lex_comment = parser
+ | [< ' ('\n'); stream=lex >] -> stream
+ | [< 'c; e=lex_comment >] -> e
+ | [< >] -> [< >]
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/myocamlbuild.ml b/examples/OCaml-Kaleidoscope/Chapter5/myocamlbuild.ml
new file mode 100644
index 00000000000..ff42664c43b
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/myocamlbuild.ml
@@ -0,0 +1,10 @@
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+ocaml_lib ~extern:true "llvm_executionengine";;
+ocaml_lib ~extern:true "llvm_target";;
+ocaml_lib ~extern:true "llvm_scalar_opts";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
+dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/parser.ml b/examples/OCaml-Kaleidoscope/Chapter5/parser.ml
new file mode 100644
index 00000000000..bfb4f168458
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/parser.ml
@@ -0,0 +1,158 @@
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr
+ * ::= ifexpr
+ * ::= forexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [< 'Token.Number n >] -> Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [< 'Token.Ident id; stream >] ->
+ let rec parse_args accumulator = parser
+ | [< e=parse_expr; stream >] ->
+ begin parser
+ | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
+ | [< >] -> e :: accumulator
+ end stream
+ | [< >] -> accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [< 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'">] ->
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [< >] -> Ast.Variable id
+ in
+ parse_ident id stream
+
+ (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
+ | [< 'Token.If; c=parse_expr;
+ 'Token.Then ?? "expected 'then'"; t=parse_expr;
+ 'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
+ Ast.If (c, t, e)
+
+ (* forexpr
+ ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
+ | [< 'Token.For;
+ 'Token.Ident id ?? "expected identifier after for";
+ 'Token.Kwd '=' ?? "expected '=' after for";
+ stream >] ->
+ begin parser
+ | [<
+ start=parse_expr;
+ 'Token.Kwd ',' ?? "expected ',' after for";
+ end_=parse_expr;
+ stream >] ->
+ let step =
+ begin parser
+ | [< 'Token.Kwd ','; step=parse_expr >] -> Some step
+ | [< >] -> None
+ end stream
+ in
+ begin parser
+ | [< 'Token.In; body=parse_expr >] ->
+ Ast.For (id, start, end_, step, body)
+ | [< >] ->
+ raise (Stream.Error "expected 'in' after for")
+ end stream
+ | [< >] ->
+ raise (Stream.Error "expected '=' after for")
+ end stream
+
+ | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec < expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_primary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) ->
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec < next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -> rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -> lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')' *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
+ | [< >] -> accumulator
+ in
+
+ parser
+ | [< 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+
+ | [< >] ->
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [< e=parse_expr >] ->
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [< 'Token.Extern; e=parse_prototype >] -> e
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/token.ml b/examples/OCaml-Kaleidoscope/Chapter5/token.ml
new file mode 100644
index 00000000000..5eb502fb894
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/token.ml
@@ -0,0 +1,19 @@
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+
+ (* control *)
+ | If | Then | Else
+ | For | In
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/toplevel.ml b/examples/OCaml-Kaleidoscope/Chapter5/toplevel.ml
new file mode 100644
index 00000000000..01d24ede149
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/toplevel.ml
@@ -0,0 +1,49 @@
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop the_fpm the_execution_engine stream =
+ match Stream.peek stream with
+ | None -> ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') ->
+ Stream.junk stream;
+ main_loop the_fpm the_execution_engine stream
+
+ | Some token ->
+ begin
+ try match token with
+ | Token.Def ->
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func the_fpm e);
+ | Token.Extern ->
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ ->
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+ with Stream.Error s | Codegen.Error s ->
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready> "; flush stdout;
+ main_loop the_fpm the_execution_engine stream
diff --git a/examples/OCaml-Kaleidoscope/Chapter5/toy.ml b/examples/OCaml-Kaleidoscope/Chapter5/toy.ml
new file mode 100644
index 00000000000..5f9d912499c
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter5/toy.ml
@@ -0,0 +1,53 @@
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+open Llvm_target
+open Llvm_scalar_opts
+
+let main () =
+ ignore (initialize_native_target ());
+
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '<' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready> "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combination the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/Makefile b/examples/OCaml-Kaleidoscope/Chapter6/Makefile
new file mode 100644
index 00000000000..21f0c53df4b
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/Makefile
@@ -0,0 +1,34 @@
+##===- examples/OCaml-Kaleidoscope/Chapter6/Makefile -------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 6.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+TOOLNAME := OCaml-Kaleidoscope-Ch6
+EXAMPLE_TOOL := 1
+UsedComponents := core
+UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \
+ llvm_scalar_opts
+
+OCAMLCFLAGS += -pp camlp4of
+
+OcamlSources1 = \
+ $(PROJ_SRC_DIR)/ast.ml \
+ $(PROJ_SRC_DIR)/parser.ml \
+ $(PROJ_SRC_DIR)/codegen.ml \
+ $(PROJ_SRC_DIR)/lexer.ml \
+ $(PROJ_SRC_DIR)/token.ml \
+ $(PROJ_SRC_DIR)/toplevel.ml \
+ $(PROJ_SRC_DIR)/toy.ml
+
+ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
+
+include $(LEVEL)/bindings/ocaml/Makefile.ocaml
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/_tags b/examples/OCaml-Kaleidoscope/Chapter6/_tags
new file mode 100644
index 00000000000..7a03dba6672
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/_tags
@@ -0,0 +1,4 @@
+<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
+<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
+<*.{byte,native}>: use_llvm_executionengine, use_llvm_target
+<*.{byte,native}>: use_llvm_scalar_opts, use_bindings
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/ast.ml b/examples/OCaml-Kaleidoscope/Chapter6/ast.ml
new file mode 100644
index 00000000000..99088cfd2f5
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/ast.ml
@@ -0,0 +1,36 @@
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a unary operator. *)
+ | Unary of char * expr
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+ (* variant for if/then/else. *)
+ | If of expr * expr * expr
+
+ (* variant for for/in. *)
+ | For of string * expr * expr * expr option * expr
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto =
+ | Prototype of string * string array
+ | BinOpPrototype of string * string array * int
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/bindings.c b/examples/OCaml-Kaleidoscope/Chapter6/bindings.c
new file mode 100644
index 00000000000..90faed15813
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/bindings.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+
+/* putchard - putchar that takes a double and returns 0. */
+extern double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+/* printd - printf that takes a double prints it as "%f\n", returning 0. */
+extern double printd(double X) {
+ printf("%f\n", X);
+ return 0;
+}
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/codegen.ml b/examples/OCaml-Kaleidoscope/Chapter6/codegen.ml
new file mode 100644
index 00000000000..96674359440
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/codegen.ml
@@ -0,0 +1,251 @@
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+let rec codegen_expr = function
+ | Ast.Number n -> const_float double_type n
+ | Ast.Variable name ->
+ (try Hashtbl.find named_values name with
+ | Not_found -> raise (Error "unknown variable name"))
+ | Ast.Unary (op, operand) ->
+ let operand = codegen_expr operand in
+ let callee = "unary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "unknown unary operator")
+ in
+ build_call callee [|operand|] "unop" builder
+ | Ast.Binary (op, lhs, rhs) ->
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -> build_fadd lhs_val rhs_val "addtmp" builder
+ | '-' -> build_fsub lhs_val rhs_val "subtmp" builder
+ | '*' -> build_fmul lhs_val rhs_val "multmp" builder
+ | '<' ->
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ ->
+ (* If it wasn't a builtin binary operator, it must be a user defined
+ * one. Emit a call to it. *)
+ let callee = "binary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "binary operator not found!")
+ in
+ build_call callee [|lhs_val; rhs_val|] "binop" builder
+ end
+ | Ast.Call (callee, args) ->
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+ | Ast.If (cond, then_, else_) ->
+ let cond = codegen_expr cond in
+
+ (* Convert condition to a bool by comparing equal to 0.0 *)
+ let zero = const_float double_type 0.0 in
+ let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
+
+ (* Grab the first block so that we might later add the conditional branch
+ * to it at the end of the function. *)
+ let start_bb = insertion_block builder in
+ let the_function = block_parent start_bb in
+
+ let then_bb = append_block context "then" the_function in
+
+ (* Emit 'then' value. *)
+ position_at_end then_bb builder;
+ let then_val = codegen_expr then_ in
+
+ (* Codegen of 'then' can change the current block, update then_bb for the
+ * phi. We create a new name because one is used for the phi node, and the
+ * other is used for the conditional branch. *)
+ let new_then_bb = insertion_block builder in
+
+ (* Emit 'else' value. *)
+ let else_bb = append_block context "else" the_function in
+ position_at_end else_bb builder;
+ let else_val = codegen_expr else_ in
+
+ (* Codegen of 'else' can change the current block, update else_bb for the
+ * phi. *)
+ let new_else_bb = insertion_block builder in
+
+ (* Emit merge block. *)
+ let merge_bb = append_block context "ifcont" the_function in
+ position_at_end merge_bb builder;
+ let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
+ let phi = build_phi incoming "iftmp" builder in
+
+ (* Return to the start block to add the conditional branch. *)
+ position_at_end start_bb builder;
+ ignore (build_cond_br cond_val then_bb else_bb builder);
+
+ (* Set a unconditional branch at the end of the 'then' block and the
+ * 'else' block to the 'merge' block. *)
+ position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
+ position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
+
+ (* Finally, set the builder to the end of the merge block. *)
+ position_at_end merge_bb builder;
+
+ phi
+ | Ast.For (var_name, start, end_, step, body) ->
+ (* Emit the start code first, without 'variable' in scope. *)
+ let start_val = codegen_expr start in
+
+ (* Make the new basic block for the loop header, inserting after current
+ * block. *)
+ let preheader_bb = insertion_block builder in
+ let the_function = block_parent preheader_bb in
+ let loop_bb = append_block context "loop" the_function in
+
+ (* Insert an explicit fall through from the current block to the
+ * loop_bb. *)
+ ignore (build_br loop_bb builder);
+
+ (* Start insertion in loop_bb. *)
+ position_at_end loop_bb builder;
+
+ (* Start the PHI node with an entry for start. *)
+ let variable = build_phi [(start_val, preheader_bb)] var_name builder in
+
+ (* Within the loop, the variable is defined equal to the PHI node. If it
+ * shadows an existing variable, we have to restore it, so save it
+ * now. *)
+ let old_val =
+ try Some (Hashtbl.find named_values var_name) with Not_found -> None
+ in
+ Hashtbl.add named_values var_name variable;
+
+ (* Emit the body of the loop. This, like any other expr, can change the
+ * current BB. Note that we ignore the value computed by the body, but
+ * don't allow an error *)
+ ignore (codegen_expr body);
+
+ (* Emit the step value. *)
+ let step_val =
+ match step with
+ | Some step -> codegen_expr step
+ (* If not specified, use 1.0. *)
+ | None -> const_float double_type 1.0
+ in
+
+ let next_var = build_add variable step_val "nextvar" builder in
+
+ (* Compute the end condition. *)
+ let end_cond = codegen_expr end_ in
+
+ (* Convert condition to a bool by comparing equal to 0.0. *)
+ let zero = const_float double_type 0.0 in
+ let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
+
+ (* Create the "after loop" block and insert it. *)
+ let loop_end_bb = insertion_block builder in
+ let after_bb = append_block context "afterloop" the_function in
+
+ (* Insert the conditional branch into the end of loop_end_bb. *)
+ ignore (build_cond_br end_cond loop_bb after_bb builder);
+
+ (* Any new code will be inserted in after_bb. *)
+ position_at_end after_bb builder;
+
+ (* Add a new entry to the PHI node for the backedge. *)
+ add_incoming (next_var, loop_end_bb) variable;
+
+ (* Restore the unshadowed variable. *)
+ begin match old_val with
+ | Some old_val -> Hashtbl.add named_values var_name old_val
+ | None -> ()
+ end;
+
+ (* for expr always returns 0.0. *)
+ const_null double_type
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) | Ast.BinOpPrototype (name, args, _) ->
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -> declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f ->
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f <> At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) <> ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a ->
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) ->
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* If this is an operator, install it. *)
+ begin match proto with
+ | Ast.BinOpPrototype (name, args, prec) ->
+ let op = name.[String.length name - 1] in
+ Hashtbl.add Parser.binop_precedence op prec;
+ | _ -> ()
+ end;
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+ with e ->
+ delete_function the_function;
+ raise e
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/lexer.ml b/examples/OCaml-Kaleidoscope/Chapter6/lexer.ml
new file mode 100644
index 00000000000..5fe9da4f16c
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/lexer.ml
@@ -0,0 +1,59 @@
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [< ' ('0' .. '9' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [< ' ('#'); stream >] ->
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [< 'c; stream >] ->
+ [< 'Token.Kwd c; lex stream >]
+
+ (* end of stream. *)
+ | [< >] -> [< >]
+
+and lex_number buffer = parser
+ | [< ' ('0' .. '9' | '.' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [< stream=lex >] ->
+ [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
+
+and lex_ident buffer = parser
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [< stream=lex >] ->
+ match Buffer.contents buffer with
+ | "def" -> [< 'Token.Def; stream >]
+ | "extern" -> [< 'Token.Extern; stream >]
+ | "if" -> [< 'Token.If; stream >]
+ | "then" -> [< 'Token.Then; stream >]
+ | "else" -> [< 'Token.Else; stream >]
+ | "for" -> [< 'Token.For; stream >]
+ | "in" -> [< 'Token.In; stream >]
+ | "binary" -> [< 'Token.Binary; stream >]
+ | "unary" -> [< 'Token.Unary; stream >]
+ | id -> [< 'Token.Ident id; stream >]
+
+and lex_comment = parser
+ | [< ' ('\n'); stream=lex >] -> stream
+ | [< 'c; e=lex_comment >] -> e
+ | [< >] -> [< >]
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/myocamlbuild.ml b/examples/OCaml-Kaleidoscope/Chapter6/myocamlbuild.ml
new file mode 100644
index 00000000000..54d3fd97709
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/myocamlbuild.ml
@@ -0,0 +1,10 @@
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+ocaml_lib ~extern:true "llvm_executionengine";;
+ocaml_lib ~extern:true "llvm_target";;
+ocaml_lib ~extern:true "llvm_scalar_opts";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"; A"-cclib"; A"-rdynamic"]);;
+dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/parser.ml b/examples/OCaml-Kaleidoscope/Chapter6/parser.ml
new file mode 100644
index 00000000000..da443c5bb68
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/parser.ml
@@ -0,0 +1,195 @@
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr
+ * ::= ifexpr
+ * ::= forexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [< 'Token.Number n >] -> Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [< 'Token.Ident id; stream >] ->
+ let rec parse_args accumulator = parser
+ | [< e=parse_expr; stream >] ->
+ begin parser
+ | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
+ | [< >] -> e :: accumulator
+ end stream
+ | [< >] -> accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [< 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'">] ->
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [< >] -> Ast.Variable id
+ in
+ parse_ident id stream
+
+ (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
+ | [< 'Token.If; c=parse_expr;
+ 'Token.Then ?? "expected 'then'"; t=parse_expr;
+ 'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
+ Ast.If (c, t, e)
+
+ (* forexpr
+ ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
+ | [< 'Token.For;
+ 'Token.Ident id ?? "expected identifier after for";
+ 'Token.Kwd '=' ?? "expected '=' after for";
+ stream >] ->
+ begin parser
+ | [<
+ start=parse_expr;
+ 'Token.Kwd ',' ?? "expected ',' after for";
+ end_=parse_expr;
+ stream >] ->
+ let step =
+ begin parser
+ | [< 'Token.Kwd ','; step=parse_expr >] -> Some step
+ | [< >] -> None
+ end stream
+ in
+ begin parser
+ | [< 'Token.In; body=parse_expr >] ->
+ Ast.For (id, start, end_, step, body)
+ | [< >] ->
+ raise (Stream.Error "expected 'in' after for")
+ end stream
+ | [< >] ->
+ raise (Stream.Error "expected '=' after for")
+ end stream
+
+ | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
+
+(* unary
+ * ::= primary
+ * ::= '!' unary *)
+and parse_unary = parser
+ (* If this is a unary operator, read it. *)
+ | [< 'Token.Kwd op when op != '(' && op != ')'; operand=parse_expr >] ->
+ Ast.Unary (op, operand)
+
+ (* If the current token is not an operator, it must be a primary expr. *)
+ | [< stream >] -> parse_primary stream
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec < expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the unary expression after the binary operator. *)
+ let rhs = parse_unary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) ->
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec < next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -> rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -> lhs
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [< lhs=parse_unary; stream >] -> parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')'
+ * ::= binary LETTER number? (id, id)
+ * ::= unary LETTER number? (id) *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
+ | [< >] -> accumulator
+ in
+ let parse_operator = parser
+ | [< 'Token.Unary >] -> "unary", 1
+ | [< 'Token.Binary >] -> "binary", 2
+ in
+ let parse_binary_precedence = parser
+ | [< 'Token.Number n >] -> int_of_float n
+ | [< >] -> 30
+ in
+ parser
+ | [< 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+ | [< (prefix, kind)=parse_operator;
+ 'Token.Kwd op ?? "expected an operator";
+ (* Read the precedence if present. *)
+ binary_precedence=parse_binary_precedence;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
+ let name = prefix ^ (String.make 1 op) in
+ let args = Array.of_list (List.rev args) in
+
+ (* Verify right number of arguments for operator. *)
+ if Array.length args != kind
+ then raise (Stream.Error "invalid number of operands for operator")
+ else
+ if kind == 1 then
+ Ast.Prototype (name, args)
+ else
+ Ast.BinOpPrototype (name, args, binary_precedence)
+ | [< >] ->
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [< e=parse_expr >] ->
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [< 'Token.Extern; e=parse_prototype >] -> e
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/token.ml b/examples/OCaml-Kaleidoscope/Chapter6/token.ml
new file mode 100644
index 00000000000..c7a5f95092d
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/token.ml
@@ -0,0 +1,22 @@
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+
+ (* control *)
+ | If | Then | Else
+ | For | In
+
+ (* operators *)
+ | Binary | Unary
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/toplevel.ml b/examples/OCaml-Kaleidoscope/Chapter6/toplevel.ml
new file mode 100644
index 00000000000..01d24ede149
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/toplevel.ml
@@ -0,0 +1,49 @@
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop the_fpm the_execution_engine stream =
+ match Stream.peek stream with
+ | None -> ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') ->
+ Stream.junk stream;
+ main_loop the_fpm the_execution_engine stream
+
+ | Some token ->
+ begin
+ try match token with
+ | Token.Def ->
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func the_fpm e);
+ | Token.Extern ->
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ ->
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+ with Stream.Error s | Codegen.Error s ->
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready> "; flush stdout;
+ main_loop the_fpm the_execution_engine stream
diff --git a/examples/OCaml-Kaleidoscope/Chapter6/toy.ml b/examples/OCaml-Kaleidoscope/Chapter6/toy.ml
new file mode 100644
index 00000000000..5f9d912499c
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter6/toy.ml
@@ -0,0 +1,53 @@
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+open Llvm_target
+open Llvm_scalar_opts
+
+let main () =
+ ignore (initialize_native_target ());
+
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '<' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready> "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combination the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/Makefile b/examples/OCaml-Kaleidoscope/Chapter7/Makefile
new file mode 100644
index 00000000000..99686e17ea8
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/Makefile
@@ -0,0 +1,34 @@
+##===- examples/OCaml-Kaleidoscope/Chapter7/Makefile -------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+#
+# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 7.
+#
+##===----------------------------------------------------------------------===##
+
+LEVEL := ../../..
+TOOLNAME := OCaml-Kaleidoscope-Ch7
+EXAMPLE_TOOL := 1
+UsedComponents := core
+UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \
+ llvm_scalar_opts
+
+OCAMLCFLAGS += -pp camlp4of
+
+OcamlSources1 = \
+ $(PROJ_SRC_DIR)/ast.ml \
+ $(PROJ_SRC_DIR)/parser.ml \
+ $(PROJ_SRC_DIR)/codegen.ml \
+ $(PROJ_SRC_DIR)/lexer.ml \
+ $(PROJ_SRC_DIR)/token.ml \
+ $(PROJ_SRC_DIR)/toplevel.ml \
+ $(PROJ_SRC_DIR)/toy.ml
+
+ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
+
+include $(LEVEL)/bindings/ocaml/Makefile.ocaml
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/_tags b/examples/OCaml-Kaleidoscope/Chapter7/_tags
new file mode 100644
index 00000000000..7a03dba6672
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/_tags
@@ -0,0 +1,4 @@
+<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
+<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
+<*.{byte,native}>: use_llvm_executionengine, use_llvm_target
+<*.{byte,native}>: use_llvm_scalar_opts, use_bindings
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/ast.ml b/examples/OCaml-Kaleidoscope/Chapter7/ast.ml
new file mode 100644
index 00000000000..c699e8074a4
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/ast.ml
@@ -0,0 +1,39 @@
+(*===----------------------------------------------------------------------===
+ * Abstract Syntax Tree (aka Parse Tree)
+ *===----------------------------------------------------------------------===*)
+
+(* expr - Base type for all expression nodes. *)
+type expr =
+ (* variant for numeric literals like "1.0". *)
+ | Number of float
+
+ (* variant for referencing a variable, like "a". *)
+ | Variable of string
+
+ (* variant for a unary operator. *)
+ | Unary of char * expr
+
+ (* variant for a binary operator. *)
+ | Binary of char * expr * expr
+
+ (* variant for function calls. *)
+ | Call of string * expr array
+
+ (* variant for if/then/else. *)
+ | If of expr * expr * expr
+
+ (* variant for for/in. *)
+ | For of string * expr * expr * expr option * expr
+
+ (* variant for var/in. *)
+ | Var of (string * expr option) array * expr
+
+(* proto - This type represents the "prototype" for a function, which captures
+ * its name, and its argument names (thus implicitly the number of arguments the
+ * function takes). *)
+type proto =
+ | Prototype of string * string array
+ | BinOpPrototype of string * string array * int
+
+(* func - This type represents a function definition itself. *)
+type func = Function of proto * expr
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/bindings.c b/examples/OCaml-Kaleidoscope/Chapter7/bindings.c
new file mode 100644
index 00000000000..90faed15813
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/bindings.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+
+/* putchard - putchar that takes a double and returns 0. */
+extern double putchard(double X) {
+ putchar((char)X);
+ return 0;
+}
+
+/* printd - printf that takes a double prints it as "%f\n", returning 0. */
+extern double printd(double X) {
+ printf("%f\n", X);
+ return 0;
+}
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/codegen.ml b/examples/OCaml-Kaleidoscope/Chapter7/codegen.ml
new file mode 100644
index 00000000000..e66396eb6ac
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/codegen.ml
@@ -0,0 +1,370 @@
+(*===----------------------------------------------------------------------===
+ * Code Generation
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+
+exception Error of string
+
+let context = global_context ()
+let the_module = create_module context "my cool jit"
+let builder = builder context
+let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
+let double_type = double_type context
+
+(* Create an alloca instruction in the entry block of the function. This
+ * is used for mutable variables etc. *)
+let create_entry_block_alloca the_function var_name =
+ let builder = builder_at context (instr_begin (entry_block the_function)) in
+ build_alloca double_type var_name builder
+
+let rec codegen_expr = function
+ | Ast.Number n -> const_float double_type n
+ | Ast.Variable name ->
+ let v = try Hashtbl.find named_values name with
+ | Not_found -> raise (Error "unknown variable name")
+ in
+ (* Load the value. *)
+ build_load v name builder
+ | Ast.Unary (op, operand) ->
+ let operand = codegen_expr operand in
+ let callee = "unary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "unknown unary operator")
+ in
+ build_call callee [|operand|] "unop" builder
+ | Ast.Binary (op, lhs, rhs) ->
+ begin match op with
+ | '=' ->
+ (* Special case '=' because we don't want to emit the LHS as an
+ * expression. *)
+ let name =
+ match lhs with
+ | Ast.Variable name -> name
+ | _ -> raise (Error "destination of '=' must be a variable")
+ in
+
+ (* Codegen the rhs. *)
+ let val_ = codegen_expr rhs in
+
+ (* Lookup the name. *)
+ let variable = try Hashtbl.find named_values name with
+ | Not_found -> raise (Error "unknown variable name")
+ in
+ ignore(build_store val_ variable builder);
+ val_
+ | _ ->
+ let lhs_val = codegen_expr lhs in
+ let rhs_val = codegen_expr rhs in
+ begin
+ match op with
+ | '+' -> build_fadd lhs_val rhs_val "addtmp" builder
+ | '-' -> build_fsub lhs_val rhs_val "subtmp" builder
+ | '*' -> build_fmul lhs_val rhs_val "multmp" builder
+ | '<' ->
+ (* Convert bool 0/1 to double 0.0 or 1.0 *)
+ let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
+ build_uitofp i double_type "booltmp" builder
+ | _ ->
+ (* If it wasn't a builtin binary operator, it must be a user defined
+ * one. Emit a call to it. *)
+ let callee = "binary" ^ (String.make 1 op) in
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "binary operator not found!")
+ in
+ build_call callee [|lhs_val; rhs_val|] "binop" builder
+ end
+ end
+ | Ast.Call (callee, args) ->
+ (* Look up the name in the module table. *)
+ let callee =
+ match lookup_function callee the_module with
+ | Some callee -> callee
+ | None -> raise (Error "unknown function referenced")
+ in
+ let params = params callee in
+
+ (* If argument mismatch error. *)
+ if Array.length params == Array.length args then () else
+ raise (Error "incorrect # arguments passed");
+ let args = Array.map codegen_expr args in
+ build_call callee args "calltmp" builder
+ | Ast.If (cond, then_, else_) ->
+ let cond = codegen_expr cond in
+
+ (* Convert condition to a bool by comparing equal to 0.0 *)
+ let zero = const_float double_type 0.0 in
+ let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
+
+ (* Grab the first block so that we might later add the conditional branch
+ * to it at the end of the function. *)
+ let start_bb = insertion_block builder in
+ let the_function = block_parent start_bb in
+
+ let then_bb = append_block context "then" the_function in
+
+ (* Emit 'then' value. *)
+ position_at_end then_bb builder;
+ let then_val = codegen_expr then_ in
+
+ (* Codegen of 'then' can change the current block, update then_bb for the
+ * phi. We create a new name because one is used for the phi node, and the
+ * other is used for the conditional branch. *)
+ let new_then_bb = insertion_block builder in
+
+ (* Emit 'else' value. *)
+ let else_bb = append_block context "else" the_function in
+ position_at_end else_bb builder;
+ let else_val = codegen_expr else_ in
+
+ (* Codegen of 'else' can change the current block, update else_bb for the
+ * phi. *)
+ let new_else_bb = insertion_block builder in
+
+ (* Emit merge block. *)
+ let merge_bb = append_block context "ifcont" the_function in
+ position_at_end merge_bb builder;
+ let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
+ let phi = build_phi incoming "iftmp" builder in
+
+ (* Return to the start block to add the conditional branch. *)
+ position_at_end start_bb builder;
+ ignore (build_cond_br cond_val then_bb else_bb builder);
+
+ (* Set a unconditional branch at the end of the 'then' block and the
+ * 'else' block to the 'merge' block. *)
+ position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
+ position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
+
+ (* Finally, set the builder to the end of the merge block. *)
+ position_at_end merge_bb builder;
+
+ phi
+ | Ast.For (var_name, start, end_, step, body) ->
+ (* Output this as:
+ * var = alloca double
+ * ...
+ * start = startexpr
+ * store start -> var
+ * goto loop
+ * loop:
+ * ...
+ * bodyexpr
+ * ...
+ * loopend:
+ * step = stepexpr
+ * endcond = endexpr
+ *
+ * curvar = load var
+ * nextvar = curvar + step
+ * store nextvar -> var
+ * br endcond, loop, endloop
+ * outloop: *)
+
+ let the_function = block_parent (insertion_block builder) in
+
+ (* Create an alloca for the variable in the entry block. *)
+ let alloca = create_entry_block_alloca the_function var_name in
+
+ (* Emit the start code first, without 'variable' in scope. *)
+ let start_val = codegen_expr start in
+
+ (* Store the value into the alloca. *)
+ ignore(build_store start_val alloca builder);
+
+ (* Make the new basic block for the loop header, inserting after current
+ * block. *)
+ let loop_bb = append_block context "loop" the_function in
+
+ (* Insert an explicit fall through from the current block to the
+ * loop_bb. *)
+ ignore (build_br loop_bb builder);
+
+ (* Start insertion in loop_bb. *)
+ position_at_end loop_bb builder;
+
+ (* Within the loop, the variable is defined equal to the PHI node. If it
+ * shadows an existing variable, we have to restore it, so save it
+ * now. *)
+ let old_val =
+ try Some (Hashtbl.find named_values var_name) with Not_found -> None
+ in
+ Hashtbl.add named_values var_name alloca;
+
+ (* Emit the body of the loop. This, like any other expr, can change the
+ * current BB. Note that we ignore the value computed by the body, but
+ * don't allow an error *)
+ ignore (codegen_expr body);
+
+ (* Emit the step value. *)
+ let step_val =
+ match step with
+ | Some step -> codegen_expr step
+ (* If not specified, use 1.0. *)
+ | None -> const_float double_type 1.0
+ in
+
+ (* Compute the end condition. *)
+ let end_cond = codegen_expr end_ in
+
+ (* Reload, increment, and restore the alloca. This handles the case where
+ * the body of the loop mutates the variable. *)
+ let cur_var = build_load alloca var_name builder in
+ let next_var = build_add cur_var step_val "nextvar" builder in
+ ignore(build_store next_var alloca builder);
+
+ (* Convert condition to a bool by comparing equal to 0.0. *)
+ let zero = const_float double_type 0.0 in
+ let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
+
+ (* Create the "after loop" block and insert it. *)
+ let after_bb = append_block context "afterloop" the_function in
+
+ (* Insert the conditional branch into the end of loop_end_bb. *)
+ ignore (build_cond_br end_cond loop_bb after_bb builder);
+
+ (* Any new code will be inserted in after_bb. *)
+ position_at_end after_bb builder;
+
+ (* Restore the unshadowed variable. *)
+ begin match old_val with
+ | Some old_val -> Hashtbl.add named_values var_name old_val
+ | None -> ()
+ end;
+
+ (* for expr always returns 0.0. *)
+ const_null double_type
+ | Ast.Var (var_names, body) ->
+ let old_bindings = ref [] in
+
+ let the_function = block_parent (insertion_block builder) in
+
+ (* Register all variables and emit their initializer. *)
+ Array.iter (fun (var_name, init) ->
+ (* Emit the initializer before adding the variable to scope, this
+ * prevents the initializer from referencing the variable itself, and
+ * permits stuff like this:
+ * var a = 1 in
+ * var a = a in ... # refers to outer 'a'. *)
+ let init_val =
+ match init with
+ | Some init -> codegen_expr init
+ (* If not specified, use 0.0. *)
+ | None -> const_float double_type 0.0
+ in
+
+ let alloca = create_entry_block_alloca the_function var_name in
+ ignore(build_store init_val alloca builder);
+
+ (* Remember the old variable binding so that we can restore the binding
+ * when we unrecurse. *)
+ begin
+ try
+ let old_value = Hashtbl.find named_values var_name in
+ old_bindings := (var_name, old_value) :: !old_bindings;
+ with Not_found -> ()
+ end;
+
+ (* Remember this binding. *)
+ Hashtbl.add named_values var_name alloca;
+ ) var_names;
+
+ (* Codegen the body, now that all vars are in scope. *)
+ let body_val = codegen_expr body in
+
+ (* Pop all our variables from scope. *)
+ List.iter (fun (var_name, old_value) ->
+ Hashtbl.add named_values var_name old_value
+ ) !old_bindings;
+
+ (* Return the body computation. *)
+ body_val
+
+let codegen_proto = function
+ | Ast.Prototype (name, args) | Ast.BinOpPrototype (name, args, _) ->
+ (* Make the function type: double(double,double) etc. *)
+ let doubles = Array.make (Array.length args) double_type in
+ let ft = function_type double_type doubles in
+ let f =
+ match lookup_function name the_module with
+ | None -> declare_function name ft the_module
+
+ (* If 'f' conflicted, there was already something named 'name'. If it
+ * has a body, don't allow redefinition or reextern. *)
+ | Some f ->
+ (* If 'f' already has a body, reject this. *)
+ if block_begin f <> At_end f then
+ raise (Error "redefinition of function");
+
+ (* If 'f' took a different number of arguments, reject. *)
+ if element_type (type_of f) <> ft then
+ raise (Error "redefinition of function with different # args");
+ f
+ in
+
+ (* Set names for all arguments. *)
+ Array.iteri (fun i a ->
+ let n = args.(i) in
+ set_value_name n a;
+ Hashtbl.add named_values n a;
+ ) (params f);
+ f
+
+(* Create an alloca for each argument and register the argument in the symbol
+ * table so that references to it will succeed. *)
+let create_argument_allocas the_function proto =
+ let args = match proto with
+ | Ast.Prototype (_, args) | Ast.BinOpPrototype (_, args, _) -> args
+ in
+ Array.iteri (fun i ai ->
+ let var_name = args.(i) in
+ (* Create an alloca for this variable. *)
+ let alloca = create_entry_block_alloca the_function var_name in
+
+ (* Store the initial value into the alloca. *)
+ ignore(build_store ai alloca builder);
+
+ (* Add arguments to variable symbol table. *)
+ Hashtbl.add named_values var_name alloca;
+ ) (params the_function)
+
+let codegen_func the_fpm = function
+ | Ast.Function (proto, body) ->
+ Hashtbl.clear named_values;
+ let the_function = codegen_proto proto in
+
+ (* If this is an operator, install it. *)
+ begin match proto with
+ | Ast.BinOpPrototype (name, args, prec) ->
+ let op = name.[String.length name - 1] in
+ Hashtbl.add Parser.binop_precedence op prec;
+ | _ -> ()
+ end;
+
+ (* Create a new basic block to start insertion into. *)
+ let bb = append_block context "entry" the_function in
+ position_at_end bb builder;
+
+ try
+ (* Add all arguments to the symbol table and create their allocas. *)
+ create_argument_allocas the_function proto;
+
+ let ret_val = codegen_expr body in
+
+ (* Finish off the function. *)
+ let _ = build_ret ret_val builder in
+
+ (* Validate the generated code, checking for consistency. *)
+ Llvm_analysis.assert_valid_function the_function;
+
+ (* Optimize the function. *)
+ let _ = PassManager.run_function the_function the_fpm in
+
+ the_function
+ with e ->
+ delete_function the_function;
+ raise e
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/lexer.ml b/examples/OCaml-Kaleidoscope/Chapter7/lexer.ml
new file mode 100644
index 00000000000..922cabf0428
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/lexer.ml
@@ -0,0 +1,60 @@
+(*===----------------------------------------------------------------------===
+ * Lexer
+ *===----------------------------------------------------------------------===*)
+
+let rec lex = parser
+ (* Skip any whitespace. *)
+ | [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
+
+ (* identifier: [a-zA-Z][a-zA-Z0-9] *)
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+
+ (* number: [0-9.]+ *)
+ | [< ' ('0' .. '9' as c); stream >] ->
+ let buffer = Buffer.create 1 in
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+
+ (* Comment until end of line. *)
+ | [< ' ('#'); stream >] ->
+ lex_comment stream
+
+ (* Otherwise, just return the character as its ascii value. *)
+ | [< 'c; stream >] ->
+ [< 'Token.Kwd c; lex stream >]
+
+ (* end of stream. *)
+ | [< >] -> [< >]
+
+and lex_number buffer = parser
+ | [< ' ('0' .. '9' | '.' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_number buffer stream
+ | [< stream=lex >] ->
+ [< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
+
+and lex_ident buffer = parser
+ | [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
+ Buffer.add_char buffer c;
+ lex_ident buffer stream
+ | [< stream=lex >] ->
+ match Buffer.contents buffer with
+ | "def" -> [< 'Token.Def; stream >]
+ | "extern" -> [< 'Token.Extern; stream >]
+ | "if" -> [< 'Token.If; stream >]
+ | "then" -> [< 'Token.Then; stream >]
+ | "else" -> [< 'Token.Else; stream >]
+ | "for" -> [< 'Token.For; stream >]
+ | "in" -> [< 'Token.In; stream >]
+ | "binary" -> [< 'Token.Binary; stream >]
+ | "unary" -> [< 'Token.Unary; stream >]
+ | "var" -> [< 'Token.Var; stream >]
+ | id -> [< 'Token.Ident id; stream >]
+
+and lex_comment = parser
+ | [< ' ('\n'); stream=lex >] -> stream
+ | [< 'c; e=lex_comment >] -> e
+ | [< >] -> [< >]
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/myocamlbuild.ml b/examples/OCaml-Kaleidoscope/Chapter7/myocamlbuild.ml
new file mode 100644
index 00000000000..54d3fd97709
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/myocamlbuild.ml
@@ -0,0 +1,10 @@
+open Ocamlbuild_plugin;;
+
+ocaml_lib ~extern:true "llvm";;
+ocaml_lib ~extern:true "llvm_analysis";;
+ocaml_lib ~extern:true "llvm_executionengine";;
+ocaml_lib ~extern:true "llvm_target";;
+ocaml_lib ~extern:true "llvm_scalar_opts";;
+
+flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"; A"-cclib"; A"-rdynamic"]);;
+dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/parser.ml b/examples/OCaml-Kaleidoscope/Chapter7/parser.ml
new file mode 100644
index 00000000000..c0e7db8349a
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/parser.ml
@@ -0,0 +1,221 @@
+(*===---------------------------------------------------------------------===
+ * Parser
+ *===---------------------------------------------------------------------===*)
+
+(* binop_precedence - This holds the precedence for each binary operator that is
+ * defined *)
+let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
+
+(* precedence - Get the precedence of the pending binary operator token. *)
+let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
+
+(* primary
+ * ::= identifier
+ * ::= numberexpr
+ * ::= parenexpr
+ * ::= ifexpr
+ * ::= forexpr
+ * ::= varexpr *)
+let rec parse_primary = parser
+ (* numberexpr ::= number *)
+ | [< 'Token.Number n >] -> Ast.Number n
+
+ (* parenexpr ::= '(' expression ')' *)
+ | [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
+
+ (* identifierexpr
+ * ::= identifier
+ * ::= identifier '(' argumentexpr ')' *)
+ | [< 'Token.Ident id; stream >] ->
+ let rec parse_args accumulator = parser
+ | [< e=parse_expr; stream >] ->
+ begin parser
+ | [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
+ | [< >] -> e :: accumulator
+ end stream
+ | [< >] -> accumulator
+ in
+ let rec parse_ident id = parser
+ (* Call. *)
+ | [< 'Token.Kwd '(';
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')'">] ->
+ Ast.Call (id, Array.of_list (List.rev args))
+
+ (* Simple variable ref. *)
+ | [< >] -> Ast.Variable id
+ in
+ parse_ident id stream
+
+ (* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
+ | [< 'Token.If; c=parse_expr;
+ 'Token.Then ?? "expected 'then'"; t=parse_expr;
+ 'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
+ Ast.If (c, t, e)
+
+ (* forexpr
+ ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
+ | [< 'Token.For;
+ 'Token.Ident id ?? "expected identifier after for";
+ 'Token.Kwd '=' ?? "expected '=' after for";
+ stream >] ->
+ begin parser
+ | [<
+ start=parse_expr;
+ 'Token.Kwd ',' ?? "expected ',' after for";
+ end_=parse_expr;
+ stream >] ->
+ let step =
+ begin parser
+ | [< 'Token.Kwd ','; step=parse_expr >] -> Some step
+ | [< >] -> None
+ end stream
+ in
+ begin parser
+ | [< 'Token.In; body=parse_expr >] ->
+ Ast.For (id, start, end_, step, body)
+ | [< >] ->
+ raise (Stream.Error "expected 'in' after for")
+ end stream
+ | [< >] ->
+ raise (Stream.Error "expected '=' after for")
+ end stream
+
+ (* varexpr
+ * ::= 'var' identifier ('=' expression?
+ * (',' identifier ('=' expression)?)* 'in' expression *)
+ | [< 'Token.Var;
+ (* At least one variable name is required. *)
+ 'Token.Ident id ?? "expected identifier after var";
+ init=parse_var_init;
+ var_names=parse_var_names [(id, init)];
+ (* At this point, we have to have 'in'. *)
+ 'Token.In ?? "expected 'in' keyword after 'var'";
+ body=parse_expr >] ->
+ Ast.Var (Array.of_list (List.rev var_names), body)
+
+ | [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
+
+(* unary
+ * ::= primary
+ * ::= '!' unary *)
+and parse_unary = parser
+ (* If this is a unary operator, read it. *)
+ | [< 'Token.Kwd op when op != '(' && op != ')'; operand=parse_expr >] ->
+ Ast.Unary (op, operand)
+
+ (* If the current token is not an operator, it must be a primary expr. *)
+ | [< stream >] -> parse_primary stream
+
+(* binoprhs
+ * ::= ('+' primary)* *)
+and parse_bin_rhs expr_prec lhs stream =
+ match Stream.peek stream with
+ (* If this is a binop, find its precedence. *)
+ | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
+ let token_prec = precedence c in
+
+ (* If this is a binop that binds at least as tightly as the current binop,
+ * consume it, otherwise we are done. *)
+ if token_prec < expr_prec then lhs else begin
+ (* Eat the binop. *)
+ Stream.junk stream;
+
+ (* Parse the primary expression after the binary operator. *)
+ let rhs = parse_unary stream in
+
+ (* Okay, we know this is a binop. *)
+ let rhs =
+ match Stream.peek stream with
+ | Some (Token.Kwd c2) ->
+ (* If BinOp binds less tightly with rhs than the operator after
+ * rhs, let the pending operator take rhs as its lhs. *)
+ let next_prec = precedence c2 in
+ if token_prec < next_prec
+ then parse_bin_rhs (token_prec + 1) rhs stream
+ else rhs
+ | _ -> rhs
+ in
+
+ (* Merge lhs/rhs. *)
+ let lhs = Ast.Binary (c, lhs, rhs) in
+ parse_bin_rhs expr_prec lhs stream
+ end
+ | _ -> lhs
+
+and parse_var_init = parser
+ (* read in the optional initializer. *)
+ | [< 'Token.Kwd '='; e=parse_expr >] -> Some e
+ | [< >] -> None
+
+and parse_var_names accumulator = parser
+ | [< 'Token.Kwd ',';
+ 'Token.Ident id ?? "expected identifier list after var";
+ init=parse_var_init;
+ e=parse_var_names ((id, init) :: accumulator) >] -> e
+ | [< >] -> accumulator
+
+(* expression
+ * ::= primary binoprhs *)
+and parse_expr = parser
+ | [< lhs=parse_unary; stream >] -> parse_bin_rhs 0 lhs stream
+
+(* prototype
+ * ::= id '(' id* ')'
+ * ::= binary LETTER number? (id, id)
+ * ::= unary LETTER number? (id) *)
+let parse_prototype =
+ let rec parse_args accumulator = parser
+ | [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
+ | [< >] -> accumulator
+ in
+ let parse_operator = parser
+ | [< 'Token.Unary >] -> "unary", 1
+ | [< 'Token.Binary >] -> "binary", 2
+ in
+ let parse_binary_precedence = parser
+ | [< 'Token.Number n >] -> int_of_float n
+ | [< >] -> 30
+ in
+ parser
+ | [< 'Token.Ident id;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
+ (* success. *)
+ Ast.Prototype (id, Array.of_list (List.rev args))
+ | [< (prefix, kind)=parse_operator;
+ 'Token.Kwd op ?? "expected an operator";
+ (* Read the precedence if present. *)
+ binary_precedence=parse_binary_precedence;
+ 'Token.Kwd '(' ?? "expected '(' in prototype";
+ args=parse_args [];
+ 'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
+ let name = prefix ^ (String.make 1 op) in
+ let args = Array.of_list (List.rev args) in
+
+ (* Verify right number of arguments for operator. *)
+ if Array.length args != kind
+ then raise (Stream.Error "invalid number of operands for operator")
+ else
+ if kind == 1 then
+ Ast.Prototype (name, args)
+ else
+ Ast.BinOpPrototype (name, args, binary_precedence)
+ | [< >] ->
+ raise (Stream.Error "expected function name in prototype")
+
+(* definition ::= 'def' prototype expression *)
+let parse_definition = parser
+ | [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
+ Ast.Function (p, e)
+
+(* toplevelexpr ::= expression *)
+let parse_toplevel = parser
+ | [< e=parse_expr >] ->
+ (* Make an anonymous proto. *)
+ Ast.Function (Ast.Prototype ("", [||]), e)
+
+(* external ::= 'extern' prototype *)
+let parse_extern = parser
+ | [< 'Token.Extern; e=parse_prototype >] -> e
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/token.ml b/examples/OCaml-Kaleidoscope/Chapter7/token.ml
new file mode 100644
index 00000000000..1489f0b9e79
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/token.ml
@@ -0,0 +1,25 @@
+(*===----------------------------------------------------------------------===
+ * Lexer Tokens
+ *===----------------------------------------------------------------------===*)
+
+(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
+ * these others for known things. *)
+type token =
+ (* commands *)
+ | Def | Extern
+
+ (* primary *)
+ | Ident of string | Number of float
+
+ (* unknown *)
+ | Kwd of char
+
+ (* control *)
+ | If | Then | Else
+ | For | In
+
+ (* operators *)
+ | Binary | Unary
+
+ (* var definition *)
+ | Var
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/toplevel.ml b/examples/OCaml-Kaleidoscope/Chapter7/toplevel.ml
new file mode 100644
index 00000000000..01d24ede149
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/toplevel.ml
@@ -0,0 +1,49 @@
+(*===----------------------------------------------------------------------===
+ * Top-Level parsing and JIT Driver
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+
+(* top ::= definition | external | expression | ';' *)
+let rec main_loop the_fpm the_execution_engine stream =
+ match Stream.peek stream with
+ | None -> ()
+
+ (* ignore top-level semicolons. *)
+ | Some (Token.Kwd ';') ->
+ Stream.junk stream;
+ main_loop the_fpm the_execution_engine stream
+
+ | Some token ->
+ begin
+ try match token with
+ | Token.Def ->
+ let e = Parser.parse_definition stream in
+ print_endline "parsed a function definition.";
+ dump_value (Codegen.codegen_func the_fpm e);
+ | Token.Extern ->
+ let e = Parser.parse_extern stream in
+ print_endline "parsed an extern.";
+ dump_value (Codegen.codegen_proto e);
+ | _ ->
+ (* Evaluate a top-level expression into an anonymous function. *)
+ let e = Parser.parse_toplevel stream in
+ print_endline "parsed a top-level expr";
+ let the_function = Codegen.codegen_func the_fpm e in
+ dump_value the_function;
+
+ (* JIT the function, returning a function pointer. *)
+ let result = ExecutionEngine.run_function the_function [||]
+ the_execution_engine in
+
+ print_string "Evaluated to ";
+ print_float (GenericValue.as_float Codegen.double_type result);
+ print_newline ();
+ with Stream.Error s | Codegen.Error s ->
+ (* Skip token for error recovery. *)
+ Stream.junk stream;
+ print_endline s;
+ end;
+ print_string "ready> "; flush stdout;
+ main_loop the_fpm the_execution_engine stream
diff --git a/examples/OCaml-Kaleidoscope/Chapter7/toy.ml b/examples/OCaml-Kaleidoscope/Chapter7/toy.ml
new file mode 100644
index 00000000000..babab28601d
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Chapter7/toy.ml
@@ -0,0 +1,57 @@
+(*===----------------------------------------------------------------------===
+ * Main driver code.
+ *===----------------------------------------------------------------------===*)
+
+open Llvm
+open Llvm_executionengine
+open Llvm_target
+open Llvm_scalar_opts
+
+let main () =
+ ignore (initialize_native_target ());
+
+ (* Install standard binary operators.
+ * 1 is the lowest precedence. *)
+ Hashtbl.add Parser.binop_precedence '=' 2;
+ Hashtbl.add Parser.binop_precedence '<' 10;
+ Hashtbl.add Parser.binop_precedence '+' 20;
+ Hashtbl.add Parser.binop_precedence '-' 20;
+ Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
+
+ (* Prime the first token. *)
+ print_string "ready> "; flush stdout;
+ let stream = Lexer.lex (Stream.of_channel stdin) in
+
+ (* Create the JIT. *)
+ let the_execution_engine = ExecutionEngine.create Codegen.the_module in
+ let the_fpm = PassManager.create_function Codegen.the_module in
+
+ (* Set up the optimizer pipeline. Start with registering info about how the
+ * target lays out data structures. *)
+ TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
+
+ (* Promote allocas to registers. *)
+ add_memory_to_register_promotion the_fpm;
+
+ (* Do simple "peephole" optimizations and bit-twiddling optzn. *)
+ add_instruction_combination the_fpm;
+
+ (* reassociate expressions. *)
+ add_reassociation the_fpm;
+
+ (* Eliminate Common SubExpressions. *)
+ add_gvn the_fpm;
+
+ (* Simplify the control flow graph (deleting unreachable blocks, etc). *)
+ add_cfg_simplification the_fpm;
+
+ ignore (PassManager.initialize the_fpm);
+
+ (* Run the main "interpreter loop" now. *)
+ Toplevel.main_loop the_fpm the_execution_engine stream;
+
+ (* Print out all the generated code. *)
+ dump_module Codegen.the_module
+;;
+
+main ()
diff --git a/examples/OCaml-Kaleidoscope/Makefile b/examples/OCaml-Kaleidoscope/Makefile
new file mode 100644
index 00000000000..5342b94022a
--- /dev/null
+++ b/examples/OCaml-Kaleidoscope/Makefile
@@ -0,0 +1,15 @@
+##===- examples/OCaml-Kaleidoscope/Makefile ----------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL=../..
+
+include $(LEVEL)/Makefile.config
+
+PARALLEL_DIRS:= Chapter2 Chapter3 Chapter4 Chapter5 Chapter6 Chapter7
+
+include $(LEVEL)/Makefile.common
diff --git a/examples/ParallelJIT/CMakeLists.txt b/examples/ParallelJIT/CMakeLists.txt
new file mode 100644
index 00000000000..fbdc6e5fc10
--- /dev/null
+++ b/examples/ParallelJIT/CMakeLists.txt
@@ -0,0 +1,9 @@
+set(LLVM_LINK_COMPONENTS jit interpreter nativecodegen)
+
+add_llvm_example(ParallelJIT
+ ParallelJIT.cpp
+ )
+
+if(HAVE_LIBPTHREAD)
+ target_link_libraries(ParallelJIT pthread)
+endif(HAVE_LIBPTHREAD)
diff --git a/examples/ParallelJIT/Makefile b/examples/ParallelJIT/Makefile
new file mode 100644
index 00000000000..8a49d427313
--- /dev/null
+++ b/examples/ParallelJIT/Makefile
@@ -0,0 +1,17 @@
+##===- examples/ParallelJIT/Makefile -----------------------*- Makefile -*-===##
+#
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+#
+##===----------------------------------------------------------------------===##
+LEVEL = ../..
+TOOLNAME = ParallelJIT
+EXAMPLE_TOOL = 1
+
+LINK_COMPONENTS := jit interpreter nativecodegen
+
+include $(LEVEL)/Makefile.common
+
+LIBS += -lpthread
diff --git a/examples/ParallelJIT/ParallelJIT.cpp b/examples/ParallelJIT/ParallelJIT.cpp
new file mode 100644
index 00000000000..305cf1dde06
--- /dev/null
+++ b/examples/ParallelJIT/ParallelJIT.cpp
@@ -0,0 +1,305 @@
+//===-- examples/ParallelJIT/ParallelJIT.cpp - Exercise threaded-safe JIT -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Parallel JIT
+//
+// This test program creates two LLVM functions then calls them from three
+// separate threads. It requires the pthreads library.
+// The three threads are created and then block waiting on a condition variable.
+// Once all threads are blocked on the conditional variable, the main thread
+// wakes them up. This complicated work is performed so that all three threads
+// call into the JIT at the same time (or the best possible approximation of the
+// same time). This test had assertion errors until I got the locking right.
+
+#include <pthread.h>
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/Constants.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/Instructions.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/ExecutionEngine/Interpreter.h"
+#include "llvm/ExecutionEngine/GenericValue.h"
+#include "llvm/Support/TargetSelect.h"
+#include <iostream>
+using namespace llvm;
+
+static Function* createAdd1(Module *M) {
+ // Create the add1 function entry and insert this entry into module M. The
+ // function will have a return type of "int" and take an argument of "int".
+ // The '0' terminates the list of argument types.
+ Function *Add1F =
+ cast<Function>(M->getOrInsertFunction("add1",
+ Type::getInt32Ty(M->getContext()),
+ Type::getInt32Ty(M->getContext()),
+ (Type *)0));
+
+ // Add a basic block to the function. As before, it automatically inserts
+ // because of the last argument.
+ BasicBlock *BB = BasicBlock::Create(M->getContext(), "EntryBlock", Add1F);
+
+ // Get pointers to the constant `1'.
+ Value *One = ConstantInt::get(Type::getInt32Ty(M->getContext()), 1);
+
+ // Get pointers to the integer argument of the add1 function...
+ assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
+ Argument *ArgX = Add1F->arg_begin(); // Get the arg
+ ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
+
+ // Create the add instruction, inserting it into the end of BB.
+ Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
+
+ // Create the return instruction and add it to the basic block
+ ReturnInst::Create(M->getContext(), Add, BB);
+
+ // Now, function add1 is ready.
+ return Add1F;
+}
+
+static Function *CreateFibFunction(Module *M) {
+ // Create the fib function and insert it into module M. This function is said
+ // to return an int and take an int parameter.
+ Function *FibF =
+ cast<Function>(M->getOrInsertFunction("fib",
+ Type::getInt32Ty(M->getContext()),
+ Type::getInt32Ty(M->getContext()),
+ (Type *)0));
+
+ // Add a basic block to the function.
+ BasicBlock *BB = BasicBlock::Create(M->getContext(), "EntryBlock", FibF);
+
+ // Get pointers to the constants.
+ Value *One = ConstantInt::get(Type::getInt32Ty(M->getContext()), 1);
+ Value *Two = ConstantInt::get(Type::getInt32Ty(M->getContext()), 2);
+
+ // Get pointer to the integer argument of the add1 function...
+ Argument *ArgX = FibF->arg_begin(); // Get the arg.
+ ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
+
+ // Create the true_block.
+ BasicBlock *RetBB = BasicBlock::Create(M->getContext(), "return", FibF);
+ // Create an exit block.
+ BasicBlock* RecurseBB = BasicBlock::Create(M->getContext(), "recurse", FibF);
+
+ // Create the "if (arg < 2) goto exitbb"
+ Value *CondInst = new ICmpInst(*BB, ICmpInst::ICMP_SLE, ArgX, Two, "cond");
+ BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
+
+ // Create: ret int 1
+ ReturnInst::Create(M->getContext(), One, RetBB);
+
+ // create fib(x-1)
+ Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
+ Value *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
+
+ // create fib(x-2)
+ Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
+ Value *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
+
+ // fib(x-1)+fib(x-2)
+ Value *Sum =
+ BinaryOperator::CreateAdd(CallFibX1, CallFibX2, "addresult", RecurseBB);
+
+ // Create the return instruction and add it to the basic block
+ ReturnInst::Create(M->getContext(), Sum, RecurseBB);
+
+ return FibF;
+}
+
+struct threadParams {
+ ExecutionEngine* EE;
+ Function* F;
+ int value;
+};
+
+// We block the subthreads just before they begin to execute:
+// we want all of them to call into the JIT at the same time,
+// to verify that the locking is working correctly.
+class WaitForThreads
+{
+public:
+ WaitForThreads()
+ {
+ n = 0;
+ waitFor = 0;
+
+ int result = pthread_cond_init( &condition, NULL );
+ assert( result == 0 );
+
+ result = pthread_mutex_init( &mutex, NULL );
+ assert( result == 0 );
+ }
+
+ ~WaitForThreads()
+ {
+ int result = pthread_cond_destroy( &condition );
+ assert( result == 0 );
+
+ result = pthread_mutex_destroy( &mutex );
+ assert( result == 0 );
+ }
+
+ // All threads will stop here until another thread calls releaseThreads
+ void block()
+ {
+ int result = pthread_mutex_lock( &mutex );
+ assert( result == 0 );
+ n ++;
+ //~ std::cout << "block() n " << n << " waitFor " << waitFor << std::endl;
+
+ assert( waitFor == 0 || n <= waitFor );
+ if ( waitFor > 0 && n == waitFor )
+ {
+ // There are enough threads blocked that we can release all of them
+ std::cout << "Unblocking threads from block()" << std::endl;
+ unblockThreads();
+ }
+ else
+ {
+ // We just need to wait until someone unblocks us
+ result = pthread_cond_wait( &condition, &mutex );
+ assert( result == 0 );
+ }
+
+ // unlock the mutex before returning
+ result = pthread_mutex_unlock( &mutex );
+ assert( result == 0 );
+ }
+
+ // If there are num or more threads blocked, it will signal them all
+ // Otherwise, this thread blocks until there are enough OTHER threads
+ // blocked
+ void releaseThreads( size_t num )
+ {
+ int result = pthread_mutex_lock( &mutex );
+ assert( result == 0 );
+
+ if ( n >= num ) {
+ std::cout << "Unblocking threads from releaseThreads()" << std::endl;
+ unblockThreads();
+ }
+ else
+ {
+ waitFor = num;
+ pthread_cond_wait( &condition, &mutex );
+ }
+
+ // unlock the mutex before returning
+ result = pthread_mutex_unlock( &mutex );
+ assert( result == 0 );
+ }
+
+private:
+ void unblockThreads()
+ {
+ // Reset the counters to zero: this way, if any new threads
+ // enter while threads are exiting, they will block instead
+ // of triggering a new release of threads
+ n = 0;
+
+ // Reset waitFor to zero: this way, if waitFor threads enter
+ // while threads are exiting, they will block instead of
+ // triggering a new release of threads
+ waitFor = 0;
+
+ int result = pthread_cond_broadcast( &condition );
+ (void)result;
+ assert(result == 0);
+ }
+
+ size_t n;
+ size_t waitFor;
+ pthread_cond_t condition;
+ pthread_mutex_t mutex;
+};
+
+static WaitForThreads synchronize;
+
+void* callFunc( void* param )
+{
+ struct threadParams* p = (struct threadParams*) param;
+
+ // Call the `foo' function with no arguments:
+ std::vector<GenericValue> Args(1);
+ Args[0].IntVal = APInt(32, p->value);
+
+ synchronize.block(); // wait until other threads are at this point
+ GenericValue gv = p->EE->runFunction(p->F, Args);
+
+ return (void*)(intptr_t)gv.IntVal.getZExtValue();
+}
+
+int main() {
+ InitializeNativeTarget();
+ LLVMContext Context;
+
+ // Create some module to put our function into it.
+ Module *M = new Module("test", Context);
+
+ Function* add1F = createAdd1( M );
+ Function* fibF = CreateFibFunction( M );
+
+ // Now we create the JIT.
+ ExecutionEngine* EE = EngineBuilder(M).create();
+
+ //~ std::cout << "We just constructed this LLVM module:\n\n" << *M;
+ //~ std::cout << "\n\nRunning foo: " << std::flush;
+
+ // Create one thread for add1 and two threads for fib
+ struct threadParams add1 = { EE, add1F, 1000 };
+ struct threadParams fib1 = { EE, fibF, 39 };
+ struct threadParams fib2 = { EE, fibF, 42 };
+
+ pthread_t add1Thread;
+ int result = pthread_create( &add1Thread, NULL, callFunc, &add1 );
+ if ( result != 0 ) {
+ std::cerr << "Could not create thread" << std::endl;
+ return 1;
+ }
+
+ pthread_t fibThread1;
+ result = pthread_create( &fibThread1, NULL, callFunc, &fib1 );
+ if ( result != 0 ) {
+ std::cerr << "Could not create thread" << std::endl;
+ return 1;
+ }
+
+ pthread_t fibThread2;
+ result = pthread_create( &fibThread2, NULL, callFunc, &fib2 );
+ if ( result != 0 ) {
+ std::cerr << "Could not create thread" << std::endl;
+ return 1;
+ }
+
+ synchronize.releaseThreads(3); // wait until other threads are at this point
+
+ void* returnValue;
+ result = pthread_join( add1Thread, &returnValue );
+ if ( result != 0 ) {
+ std::cerr << "Could not join thread" << std::endl;
+ return 1;
+ }
+ std::cout << "Add1 returned " << intptr_t(returnValue) << std::endl;
+
+ result = pthread_join( fibThread1, &returnValue );
+ if ( result != 0 ) {
+ std::cerr << "Could not join thread" << std::endl;
+ return 1;
+ }
+ std::cout << "Fib1 returned " << intptr_t(returnValue) << std::endl;
+
+ result = pthread_join( fibThread2, &returnValue );
+ if ( result != 0 ) {
+ std::cerr << "Could not join thread" << std::endl;
+ return 1;
+ }
+ std::cout << "Fib2 returned " << intptr_t(returnValue) << std::endl;
+
+ return 0;
+}
diff --git a/include/llvm-c/Analysis.h b/include/llvm-c/Analysis.h
new file mode 100644
index 00000000000..f0bdddc50ab
--- /dev/null
+++ b/include/llvm-c/Analysis.h
@@ -0,0 +1,65 @@
+/*===-- llvm-c/Analysis.h - Analysis Library C Interface --------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to libLLVMAnalysis.a, which *|
+|* implements various analyses of the LLVM IR. *|
+|* *|
+|* Many exotic languages can interoperate with C code but have a harder time *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_ANALYSIS_H
+#define LLVM_C_ANALYSIS_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCAnalysis Analysis
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+typedef enum {
+ LLVMAbortProcessAction, /* verifier will print to stderr and abort() */
+ LLVMPrintMessageAction, /* verifier will print to stderr and return 1 */
+ LLVMReturnStatusAction /* verifier will just return 1 */
+} LLVMVerifierFailureAction;
+
+
+/* Verifies that a module is valid, taking the specified action if not.
+ Optionally returns a human-readable description of any invalid constructs.
+ OutMessage must be disposed with LLVMDisposeMessage. */
+LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action,
+ char **OutMessage);
+
+/* Verifies that a single function is valid, taking the specified action. Useful
+ for debugging. */
+LLVMBool LLVMVerifyFunction(LLVMValueRef Fn, LLVMVerifierFailureAction Action);
+
+/* Open up a ghostview window that displays the CFG of the current function.
+ Useful for debugging. */
+void LLVMViewFunctionCFG(LLVMValueRef Fn);
+void LLVMViewFunctionCFGOnly(LLVMValueRef Fn);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/BitReader.h b/include/llvm-c/BitReader.h
new file mode 100644
index 00000000000..52280351839
--- /dev/null
+++ b/include/llvm-c/BitReader.h
@@ -0,0 +1,76 @@
+/*===-- llvm-c/BitReader.h - BitReader Library C Interface ------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to libLLVMBitReader.a, which *|
+|* implements input of the LLVM bitcode format. *|
+|* *|
+|* Many exotic languages can interoperate with C code but have a harder time *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_BITCODEREADER_H
+#define LLVM_C_BITCODEREADER_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCBitReader Bit Reader
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+/* Builds a module from the bitcode in the specified memory buffer, returning a
+ reference to the module via the OutModule parameter. Returns 0 on success.
+ Optionally returns a human-readable error message via OutMessage. */
+LLVMBool LLVMParseBitcode(LLVMMemoryBufferRef MemBuf,
+ LLVMModuleRef *OutModule, char **OutMessage);
+
+LLVMBool LLVMParseBitcodeInContext(LLVMContextRef ContextRef,
+ LLVMMemoryBufferRef MemBuf,
+ LLVMModuleRef *OutModule, char **OutMessage);
+
+/** Reads a module from the specified path, returning via the OutMP parameter
+ a module provider which performs lazy deserialization. Returns 0 on success.
+ Optionally returns a human-readable error message via OutMessage. */
+LLVMBool LLVMGetBitcodeModuleInContext(LLVMContextRef ContextRef,
+ LLVMMemoryBufferRef MemBuf,
+ LLVMModuleRef *OutM,
+ char **OutMessage);
+
+LLVMBool LLVMGetBitcodeModule(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
+ char **OutMessage);
+
+
+/** Deprecated: Use LLVMGetBitcodeModuleInContext instead. */
+LLVMBool LLVMGetBitcodeModuleProviderInContext(LLVMContextRef ContextRef,
+ LLVMMemoryBufferRef MemBuf,
+ LLVMModuleProviderRef *OutMP,
+ char **OutMessage);
+
+/** Deprecated: Use LLVMGetBitcodeModule instead. */
+LLVMBool LLVMGetBitcodeModuleProvider(LLVMMemoryBufferRef MemBuf,
+ LLVMModuleProviderRef *OutMP,
+ char **OutMessage);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/BitWriter.h b/include/llvm-c/BitWriter.h
new file mode 100644
index 00000000000..ba5a6778c94
--- /dev/null
+++ b/include/llvm-c/BitWriter.h
@@ -0,0 +1,56 @@
+/*===-- llvm-c/BitWriter.h - BitWriter Library C Interface ------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to libLLVMBitWriter.a, which *|
+|* implements output of the LLVM bitcode format. *|
+|* *|
+|* Many exotic languages can interoperate with C code but have a harder time *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_BITCODEWRITER_H
+#define LLVM_C_BITCODEWRITER_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCBitWriter Bit Writer
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+/*===-- Operations on modules ---------------------------------------------===*/
+
+/** Writes a module to the specified path. Returns 0 on success. */
+int LLVMWriteBitcodeToFile(LLVMModuleRef M, const char *Path);
+
+/** Writes a module to an open file descriptor. Returns 0 on success. */
+int LLVMWriteBitcodeToFD(LLVMModuleRef M, int FD, int ShouldClose,
+ int Unbuffered);
+
+/** Deprecated for LLVMWriteBitcodeToFD. Writes a module to an open file
+ descriptor. Returns 0 on success. Closes the Handle. */
+int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int Handle);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/Core.h b/include/llvm-c/Core.h
new file mode 100644
index 00000000000..6587e770800
--- /dev/null
+++ b/include/llvm-c/Core.h
@@ -0,0 +1,2706 @@
+/*===-- llvm-c/Core.h - Core Library C Interface ------------------*- C -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to libLLVMCore.a, which implements *|
+|* the LLVM intermediate representation. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_CORE_H
+#define LLVM_C_CORE_H
+
+#include "llvm/Support/DataTypes.h"
+
+#ifdef __cplusplus
+
+/* Need these includes to support the LLVM 'cast' template for the C++ 'wrap'
+ and 'unwrap' conversion functions. */
+#include "llvm/IRBuilder.h"
+#include "llvm/Module.h"
+#include "llvm/PassRegistry.h"
+
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMC LLVM-C: C interface to LLVM
+ *
+ * This module exposes parts of the LLVM library as a C API.
+ *
+ * @{
+ */
+
+/**
+ * @defgroup LLVMCTransforms Transforms
+ */
+
+/**
+ * @defgroup LLVMCCore Core
+ *
+ * This modules provide an interface to libLLVMCore, which implements
+ * the LLVM intermediate representation as well as other related types
+ * and utilities.
+ *
+ * LLVM uses a polymorphic type hierarchy which C cannot represent, therefore
+ * parameters must be passed as base types. Despite the declared types, most
+ * of the functions provided operate only on branches of the type hierarchy.
+ * The declared parameter names are descriptive and specify which type is
+ * required. Additionally, each type hierarchy is documented along with the
+ * functions that operate upon it. For more detail, refer to LLVM's C++ code.
+ * If in doubt, refer to Core.cpp, which performs parameter downcasts in the
+ * form unwrap<RequiredType>(Param).
+ *
+ * Many exotic languages can interoperate with C code but have a harder time
+ * with C++ due to name mangling. So in addition to C, this interface enables
+ * tools written in such languages.
+ *
+ * When included into a C++ source file, also declares 'wrap' and 'unwrap'
+ * helpers to perform opaque reference<-->pointer conversions. These helpers
+ * are shorter and more tightly typed than writing the casts by hand when
+ * authoring bindings. In assert builds, they will do runtime type checking.
+ *
+ * @{
+ */
+
+/**
+ * @defgroup LLVMCCoreTypes Types and Enumerations
+ *
+ * @{
+ */
+
+typedef int LLVMBool;
+
+/* Opaque types. */
+
+/**
+ * The top-level container for all LLVM global data. See the LLVMContext class.
+ */
+typedef struct LLVMOpaqueContext *LLVMContextRef;
+
+/**
+ * The top-level container for all other LLVM Intermediate Representation (IR)
+ * objects.
+ *
+ * @see llvm::Module
+ */
+typedef struct LLVMOpaqueModule *LLVMModuleRef;
+
+/**
+ * Each value in the LLVM IR has a type, an LLVMTypeRef.
+ *
+ * @see llvm::Type
+ */
+typedef struct LLVMOpaqueType *LLVMTypeRef;
+
+/**
+ * Represents an individual value in LLVM IR.
+ *
+ * This models llvm::Value.
+ */
+typedef struct LLVMOpaqueValue *LLVMValueRef;
+
+/**
+ * Represents a basic block of instructions in LLVM IR.
+ *
+ * This models llvm::BasicBlock.
+ */
+typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef;
+
+/**
+ * Represents an LLVM basic block builder.
+ *
+ * This models llvm::IRBuilder.
+ */
+typedef struct LLVMOpaqueBuilder *LLVMBuilderRef;
+
+/**
+ * Interface used to provide a module to JIT or interpreter.
+ * This is now just a synonym for llvm::Module, but we have to keep using the
+ * different type to keep binary compatibility.
+ */
+typedef struct LLVMOpaqueModuleProvider *LLVMModuleProviderRef;
+
+/**
+ * Used to provide a module to JIT or interpreter.
+ *
+ * @see llvm::MemoryBuffer
+ */
+typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef;
+
+/** @see llvm::PassManagerBase */
+typedef struct LLVMOpaquePassManager *LLVMPassManagerRef;
+
+/** @see llvm::PassRegistry */
+typedef struct LLVMOpaquePassRegistry *LLVMPassRegistryRef;
+
+/**
+ * Used to get the users and usees of a Value.
+ *
+ * @see llvm::Use */
+typedef struct LLVMOpaqueUse *LLVMUseRef;
+
+typedef enum {
+ LLVMZExtAttribute = 1<<0,
+ LLVMSExtAttribute = 1<<1,
+ LLVMNoReturnAttribute = 1<<2,
+ LLVMInRegAttribute = 1<<3,
+ LLVMStructRetAttribute = 1<<4,
+ LLVMNoUnwindAttribute = 1<<5,
+ LLVMNoAliasAttribute = 1<<6,
+ LLVMByValAttribute = 1<<7,
+ LLVMNestAttribute = 1<<8,
+ LLVMReadNoneAttribute = 1<<9,
+ LLVMReadOnlyAttribute = 1<<10,
+ LLVMNoInlineAttribute = 1<<11,
+ LLVMAlwaysInlineAttribute = 1<<12,
+ LLVMOptimizeForSizeAttribute = 1<<13,
+ LLVMStackProtectAttribute = 1<<14,
+ LLVMStackProtectReqAttribute = 1<<15,
+ LLVMAlignment = 31<<16,
+ LLVMNoCaptureAttribute = 1<<21,
+ LLVMNoRedZoneAttribute = 1<<22,
+ LLVMNoImplicitFloatAttribute = 1<<23,
+ LLVMNakedAttribute = 1<<24,
+ LLVMInlineHintAttribute = 1<<25,
+ LLVMStackAlignment = 7<<26,
+ LLVMReturnsTwice = 1 << 29,
+ LLVMUWTable = 1 << 30,
+ LLVMNonLazyBind = 1 << 31
+
+ /* FIXME: This attribute is currently not included in the C API as
+ a temporary measure until the API/ABI impact to the C API is understood
+ and the path forward agreed upon.
+ LLVMAddressSafety = 1ULL << 32
+ */
+} LLVMAttribute;
+
+typedef enum {
+ /* Terminator Instructions */
+ LLVMRet = 1,
+ LLVMBr = 2,
+ LLVMSwitch = 3,
+ LLVMIndirectBr = 4,
+ LLVMInvoke = 5,
+ /* removed 6 due to API changes */
+ LLVMUnreachable = 7,
+
+ /* Standard Binary Operators */
+ LLVMAdd = 8,
+ LLVMFAdd = 9,
+ LLVMSub = 10,
+ LLVMFSub = 11,
+ LLVMMul = 12,
+ LLVMFMul = 13,
+ LLVMUDiv = 14,
+ LLVMSDiv = 15,
+ LLVMFDiv = 16,
+ LLVMURem = 17,
+ LLVMSRem = 18,
+ LLVMFRem = 19,
+
+ /* Logical Operators */
+ LLVMShl = 20,
+ LLVMLShr = 21,
+ LLVMAShr = 22,
+ LLVMAnd = 23,
+ LLVMOr = 24,
+ LLVMXor = 25,
+
+ /* Memory Operators */
+ LLVMAlloca = 26,
+ LLVMLoad = 27,
+ LLVMStore = 28,
+ LLVMGetElementPtr = 29,
+
+ /* Cast Operators */
+ LLVMTrunc = 30,
+ LLVMZExt = 31,
+ LLVMSExt = 32,
+ LLVMFPToUI = 33,
+ LLVMFPToSI = 34,
+ LLVMUIToFP = 35,
+ LLVMSIToFP = 36,
+ LLVMFPTrunc = 37,
+ LLVMFPExt = 38,
+ LLVMPtrToInt = 39,
+ LLVMIntToPtr = 40,
+ LLVMBitCast = 41,
+
+ /* Other Operators */
+ LLVMICmp = 42,
+ LLVMFCmp = 43,
+ LLVMPHI = 44,
+ LLVMCall = 45,
+ LLVMSelect = 46,
+ LLVMUserOp1 = 47,
+ LLVMUserOp2 = 48,
+ LLVMVAArg = 49,
+ LLVMExtractElement = 50,
+ LLVMInsertElement = 51,
+ LLVMShuffleVector = 52,
+ LLVMExtractValue = 53,
+ LLVMInsertValue = 54,
+
+ /* Atomic operators */
+ LLVMFence = 55,
+ LLVMAtomicCmpXchg = 56,
+ LLVMAtomicRMW = 57,
+
+ /* Exception Handling Operators */
+ LLVMResume = 58,
+ LLVMLandingPad = 59
+
+} LLVMOpcode;
+
+typedef enum {
+ LLVMVoidTypeKind, /**< type with no size */
+ LLVMHalfTypeKind, /**< 16 bit floating point type */
+ LLVMFloatTypeKind, /**< 32 bit floating point type */
+ LLVMDoubleTypeKind, /**< 64 bit floating point type */
+ LLVMX86_FP80TypeKind, /**< 80 bit floating point type (X87) */
+ LLVMFP128TypeKind, /**< 128 bit floating point type (112-bit mantissa)*/
+ LLVMPPC_FP128TypeKind, /**< 128 bit floating point type (two 64-bits) */
+ LLVMLabelTypeKind, /**< Labels */
+ LLVMIntegerTypeKind, /**< Arbitrary bit width integers */
+ LLVMFunctionTypeKind, /**< Functions */
+ LLVMStructTypeKind, /**< Structures */
+ LLVMArrayTypeKind, /**< Arrays */
+ LLVMPointerTypeKind, /**< Pointers */
+ LLVMVectorTypeKind, /**< SIMD 'packed' format, or other vector type */
+ LLVMMetadataTypeKind, /**< Metadata */
+ LLVMX86_MMXTypeKind /**< X86 MMX */
+} LLVMTypeKind;
+
+typedef enum {
+ LLVMExternalLinkage, /**< Externally visible function */
+ LLVMAvailableExternallyLinkage,
+ LLVMLinkOnceAnyLinkage, /**< Keep one copy of function when linking (inline)*/
+ LLVMLinkOnceODRLinkage, /**< Same, but only replaced by something
+ equivalent. */
+ LLVMLinkOnceODRAutoHideLinkage, /**< Like LinkOnceODR, but possibly hidden. */
+ LLVMWeakAnyLinkage, /**< Keep one copy of function when linking (weak) */
+ LLVMWeakODRLinkage, /**< Same, but only replaced by something
+ equivalent. */
+ LLVMAppendingLinkage, /**< Special purpose, only applies to global arrays */
+ LLVMInternalLinkage, /**< Rename collisions when linking (static
+ functions) */
+ LLVMPrivateLinkage, /**< Like Internal, but omit from symbol table */
+ LLVMDLLImportLinkage, /**< Function to be imported from DLL */
+ LLVMDLLExportLinkage, /**< Function to be accessible from DLL */
+ LLVMExternalWeakLinkage,/**< ExternalWeak linkage description */
+ LLVMGhostLinkage, /**< Obsolete */
+ LLVMCommonLinkage, /**< Tentative definitions */
+ LLVMLinkerPrivateLinkage, /**< Like Private, but linker removes. */
+ LLVMLinkerPrivateWeakLinkage /**< Like LinkerPrivate, but is weak. */
+} LLVMLinkage;
+
+typedef enum {
+ LLVMDefaultVisibility, /**< The GV is visible */
+ LLVMHiddenVisibility, /**< The GV is hidden */
+ LLVMProtectedVisibility /**< The GV is protected */
+} LLVMVisibility;
+
+typedef enum {
+ LLVMCCallConv = 0,
+ LLVMFastCallConv = 8,
+ LLVMColdCallConv = 9,
+ LLVMX86StdcallCallConv = 64,
+ LLVMX86FastcallCallConv = 65
+} LLVMCallConv;
+
+typedef enum {
+ LLVMIntEQ = 32, /**< equal */
+ LLVMIntNE, /**< not equal */
+ LLVMIntUGT, /**< unsigned greater than */
+ LLVMIntUGE, /**< unsigned greater or equal */
+ LLVMIntULT, /**< unsigned less than */
+ LLVMIntULE, /**< unsigned less or equal */
+ LLVMIntSGT, /**< signed greater than */
+ LLVMIntSGE, /**< signed greater or equal */
+ LLVMIntSLT, /**< signed less than */
+ LLVMIntSLE /**< signed less or equal */
+} LLVMIntPredicate;
+
+typedef enum {
+ LLVMRealPredicateFalse, /**< Always false (always folded) */
+ LLVMRealOEQ, /**< True if ordered and equal */
+ LLVMRealOGT, /**< True if ordered and greater than */
+ LLVMRealOGE, /**< True if ordered and greater than or equal */
+ LLVMRealOLT, /**< True if ordered and less than */
+ LLVMRealOLE, /**< True if ordered and less than or equal */
+ LLVMRealONE, /**< True if ordered and operands are unequal */
+ LLVMRealORD, /**< True if ordered (no nans) */
+ LLVMRealUNO, /**< True if unordered: isnan(X) | isnan(Y) */
+ LLVMRealUEQ, /**< True if unordered or equal */
+ LLVMRealUGT, /**< True if unordered or greater than */
+ LLVMRealUGE, /**< True if unordered, greater than, or equal */
+ LLVMRealULT, /**< True if unordered or less than */
+ LLVMRealULE, /**< True if unordered, less than, or equal */
+ LLVMRealUNE, /**< True if unordered or not equal */
+ LLVMRealPredicateTrue /**< Always true (always folded) */
+} LLVMRealPredicate;
+
+typedef enum {
+ LLVMLandingPadCatch, /**< A catch clause */
+ LLVMLandingPadFilter /**< A filter clause */
+} LLVMLandingPadClauseTy;
+
+/**
+ * @}
+ */
+
+void LLVMInitializeCore(LLVMPassRegistryRef R);
+
+
+/*===-- Error handling ----------------------------------------------------===*/
+
+void LLVMDisposeMessage(char *Message);
+
+
+/**
+ * @defgroup LLVMCCoreContext Contexts
+ *
+ * Contexts are execution states for the core LLVM IR system.
+ *
+ * Most types are tied to a context instance. Multiple contexts can
+ * exist simultaneously. A single context is not thread safe. However,
+ * different contexts can execute on different threads simultaneously.
+ *
+ * @{
+ */
+
+/**
+ * Create a new context.
+ *
+ * Every call to this function should be paired with a call to
+ * LLVMContextDispose() or the context will leak memory.
+ */
+LLVMContextRef LLVMContextCreate(void);
+
+/**
+ * Obtain the global context instance.
+ */
+LLVMContextRef LLVMGetGlobalContext(void);
+
+/**
+ * Destroy a context instance.
+ *
+ * This should be called for every call to LLVMContextCreate() or memory
+ * will be leaked.
+ */
+void LLVMContextDispose(LLVMContextRef C);
+
+unsigned LLVMGetMDKindIDInContext(LLVMContextRef C, const char* Name,
+ unsigned SLen);
+unsigned LLVMGetMDKindID(const char* Name, unsigned SLen);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreModule Modules
+ *
+ * Modules represent the top-level structure in a LLVM program. An LLVM
+ * module is effectively a translation unit or a collection of
+ * translation units merged together.
+ *
+ * @{
+ */
+
+/**
+ * Create a new, empty module in the global context.
+ *
+ * This is equivalent to calling LLVMModuleCreateWithNameInContext with
+ * LLVMGetGlobalContext() as the context parameter.
+ *
+ * Every invocation should be paired with LLVMDisposeModule() or memory
+ * will be leaked.
+ */
+LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID);
+
+/**
+ * Create a new, empty module in a specific context.
+ *
+ * Every invocation should be paired with LLVMDisposeModule() or memory
+ * will be leaked.
+ */
+LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID,
+ LLVMContextRef C);
+
+/**
+ * Destroy a module instance.
+ *
+ * This must be called for every created module or memory will be
+ * leaked.
+ */
+void LLVMDisposeModule(LLVMModuleRef M);
+
+/**
+ * Obtain the data layout for a module.
+ *
+ * @see Module::getDataLayout()
+ */
+const char *LLVMGetDataLayout(LLVMModuleRef M);
+
+/**
+ * Set the data layout for a module.
+ *
+ * @see Module::setDataLayout()
+ */
+void LLVMSetDataLayout(LLVMModuleRef M, const char *Triple);
+
+/**
+ * Obtain the target triple for a module.
+ *
+ * @see Module::getTargetTriple()
+ */
+const char *LLVMGetTarget(LLVMModuleRef M);
+
+/**
+ * Set the target triple for a module.
+ *
+ * @see Module::setTargetTriple()
+ */
+void LLVMSetTarget(LLVMModuleRef M, const char *Triple);
+
+/**
+ * Dump a representation of a module to stderr.
+ *
+ * @see Module::dump()
+ */
+void LLVMDumpModule(LLVMModuleRef M);
+
+/**
+ * Print a representation of a module to a file. The ErrorMessage needs to be
+ * disposed with LLVMDisposeMessage. Returns 0 on success, 1 otherwise.
+ *
+ * @see Module::print()
+ */
+LLVMBool LLVMPrintModuleToFile(LLVMModuleRef M, const char *Filename,
+ char **ErrorMessage);
+
+/**
+ * Set inline assembly for a module.
+ *
+ * @see Module::setModuleInlineAsm()
+ */
+void LLVMSetModuleInlineAsm(LLVMModuleRef M, const char *Asm);
+
+/**
+ * Obtain the context to which this module is associated.
+ *
+ * @see Module::getContext()
+ */
+LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M);
+
+/**
+ * Obtain a Type from a module by its registered name.
+ */
+LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name);
+
+/**
+ * Obtain the number of operands for named metadata in a module.
+ *
+ * @see llvm::Module::getNamedMetadata()
+ */
+unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char* name);
+
+/**
+ * Obtain the named metadata operands for a module.
+ *
+ * The passed LLVMValueRef pointer should refer to an array of
+ * LLVMValueRef at least LLVMGetNamedMetadataNumOperands long. This
+ * array will be populated with the LLVMValueRef instances. Each
+ * instance corresponds to a llvm::MDNode.
+ *
+ * @see llvm::Module::getNamedMetadata()
+ * @see llvm::MDNode::getOperand()
+ */
+void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char* name, LLVMValueRef *Dest);
+
+/**
+ * Add an operand to named metadata.
+ *
+ * @see llvm::Module::getNamedMetadata()
+ * @see llvm::MDNode::addOperand()
+ */
+void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char* name,
+ LLVMValueRef Val);
+
+/**
+ * Add a function to a module under a specified name.
+ *
+ * @see llvm::Function::Create()
+ */
+LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name,
+ LLVMTypeRef FunctionTy);
+
+/**
+ * Obtain a Function value from a Module by its name.
+ *
+ * The returned value corresponds to a llvm::Function value.
+ *
+ * @see llvm::Module::getFunction()
+ */
+LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name);
+
+/**
+ * Obtain an iterator to the first Function in a Module.
+ *
+ * @see llvm::Module::begin()
+ */
+LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M);
+
+/**
+ * Obtain an iterator to the last Function in a Module.
+ *
+ * @see llvm::Module::end()
+ */
+LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M);
+
+/**
+ * Advance a Function iterator to the next Function.
+ *
+ * Returns NULL if the iterator was already at the end and there are no more
+ * functions.
+ */
+LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn);
+
+/**
+ * Decrement a Function iterator to the previous Function.
+ *
+ * Returns NULL if the iterator was already at the beginning and there are
+ * no previous functions.
+ */
+LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreType Types
+ *
+ * Types represent the type of a value.
+ *
+ * Types are associated with a context instance. The context internally
+ * deduplicates types so there is only 1 instance of a specific type
+ * alive at a time. In other words, a unique type is shared among all
+ * consumers within a context.
+ *
+ * A Type in the C API corresponds to llvm::Type.
+ *
+ * Types have the following hierarchy:
+ *
+ * types:
+ * integer type
+ * real type
+ * function type
+ * sequence types:
+ * array type
+ * pointer type
+ * vector type
+ * void type
+ * label type
+ * opaque type
+ *
+ * @{
+ */
+
+/**
+ * Obtain the enumerated type of a Type instance.
+ *
+ * @see llvm::Type:getTypeID()
+ */
+LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty);
+
+/**
+ * Whether the type has a known size.
+ *
+ * Things that don't have a size are abstract types, labels, and void.a
+ *
+ * @see llvm::Type::isSized()
+ */
+LLVMBool LLVMTypeIsSized(LLVMTypeRef Ty);
+
+/**
+ * Obtain the context to which this type instance is associated.
+ *
+ * @see llvm::Type::getContext()
+ */
+LLVMContextRef LLVMGetTypeContext(LLVMTypeRef Ty);
+
+/**
+ * @defgroup LLVMCCoreTypeInt Integer Types
+ *
+ * Functions in this section operate on integer types.
+ *
+ * @{
+ */
+
+/**
+ * Obtain an integer type from a context with specified bit width.
+ */
+LLVMTypeRef LLVMInt1TypeInContext(LLVMContextRef C);
+LLVMTypeRef LLVMInt8TypeInContext(LLVMContextRef C);
+LLVMTypeRef LLVMInt16TypeInContext(LLVMContextRef C);
+LLVMTypeRef LLVMInt32TypeInContext(LLVMContextRef C);
+LLVMTypeRef LLVMInt64TypeInContext(LLVMContextRef C);
+LLVMTypeRef LLVMIntTypeInContext(LLVMContextRef C, unsigned NumBits);
+
+/**
+ * Obtain an integer type from the global context with a specified bit
+ * width.
+ */
+LLVMTypeRef LLVMInt1Type(void);
+LLVMTypeRef LLVMInt8Type(void);
+LLVMTypeRef LLVMInt16Type(void);
+LLVMTypeRef LLVMInt32Type(void);
+LLVMTypeRef LLVMInt64Type(void);
+LLVMTypeRef LLVMIntType(unsigned NumBits);
+unsigned LLVMGetIntTypeWidth(LLVMTypeRef IntegerTy);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreTypeFloat Floating Point Types
+ *
+ * @{
+ */
+
+/**
+ * Obtain a 16-bit floating point type from a context.
+ */
+LLVMTypeRef LLVMHalfTypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 32-bit floating point type from a context.
+ */
+LLVMTypeRef LLVMFloatTypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 64-bit floating point type from a context.
+ */
+LLVMTypeRef LLVMDoubleTypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 80-bit floating point type (X87) from a context.
+ */
+LLVMTypeRef LLVMX86FP80TypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 128-bit floating point type (112-bit mantissa) from a
+ * context.
+ */
+LLVMTypeRef LLVMFP128TypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 128-bit floating point type (two 64-bits) from a context.
+ */
+LLVMTypeRef LLVMPPCFP128TypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a floating point type from the global context.
+ *
+ * These map to the functions in this group of the same name.
+ */
+LLVMTypeRef LLVMHalfType(void);
+LLVMTypeRef LLVMFloatType(void);
+LLVMTypeRef LLVMDoubleType(void);
+LLVMTypeRef LLVMX86FP80Type(void);
+LLVMTypeRef LLVMFP128Type(void);
+LLVMTypeRef LLVMPPCFP128Type(void);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreTypeFunction Function Types
+ *
+ * @{
+ */
+
+/**
+ * Obtain a function type consisting of a specified signature.
+ *
+ * The function is defined as a tuple of a return Type, a list of
+ * parameter types, and whether the function is variadic.
+ */
+LLVMTypeRef LLVMFunctionType(LLVMTypeRef ReturnType,
+ LLVMTypeRef *ParamTypes, unsigned ParamCount,
+ LLVMBool IsVarArg);
+
+/**
+ * Returns whether a function type is variadic.
+ */
+LLVMBool LLVMIsFunctionVarArg(LLVMTypeRef FunctionTy);
+
+/**
+ * Obtain the Type this function Type returns.
+ */
+LLVMTypeRef LLVMGetReturnType(LLVMTypeRef FunctionTy);
+
+/**
+ * Obtain the number of parameters this function accepts.
+ */
+unsigned LLVMCountParamTypes(LLVMTypeRef FunctionTy);
+
+/**
+ * Obtain the types of a function's parameters.
+ *
+ * The Dest parameter should point to a pre-allocated array of
+ * LLVMTypeRef at least LLVMCountParamTypes() large. On return, the
+ * first LLVMCountParamTypes() entries in the array will be populated
+ * with LLVMTypeRef instances.
+ *
+ * @param FunctionTy The function type to operate on.
+ * @param Dest Memory address of an array to be filled with result.
+ */
+void LLVMGetParamTypes(LLVMTypeRef FunctionTy, LLVMTypeRef *Dest);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreTypeStruct Structure Types
+ *
+ * These functions relate to LLVMTypeRef instances.
+ *
+ * @see llvm::StructType
+ *
+ * @{
+ */
+
+/**
+ * Create a new structure type in a context.
+ *
+ * A structure is specified by a list of inner elements/types and
+ * whether these can be packed together.
+ *
+ * @see llvm::StructType::create()
+ */
+LLVMTypeRef LLVMStructTypeInContext(LLVMContextRef C, LLVMTypeRef *ElementTypes,
+ unsigned ElementCount, LLVMBool Packed);
+
+/**
+ * Create a new structure type in the global context.
+ *
+ * @see llvm::StructType::create()
+ */
+LLVMTypeRef LLVMStructType(LLVMTypeRef *ElementTypes, unsigned ElementCount,
+ LLVMBool Packed);
+
+/**
+ * Create an empty structure in a context having a specified name.
+ *
+ * @see llvm::StructType::create()
+ */
+LLVMTypeRef LLVMStructCreateNamed(LLVMContextRef C, const char *Name);
+
+/**
+ * Obtain the name of a structure.
+ *
+ * @see llvm::StructType::getName()
+ */
+const char *LLVMGetStructName(LLVMTypeRef Ty);
+
+/**
+ * Set the contents of a structure type.
+ *
+ * @see llvm::StructType::setBody()
+ */
+void LLVMStructSetBody(LLVMTypeRef StructTy, LLVMTypeRef *ElementTypes,
+ unsigned ElementCount, LLVMBool Packed);
+
+/**
+ * Get the number of elements defined inside the structure.
+ *
+ * @see llvm::StructType::getNumElements()
+ */
+unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy);
+
+/**
+ * Get the elements within a structure.
+ *
+ * The function is passed the address of a pre-allocated array of
+ * LLVMTypeRef at least LLVMCountStructElementTypes() long. After
+ * invocation, this array will be populated with the structure's
+ * elements. The objects in the destination array will have a lifetime
+ * of the structure type itself, which is the lifetime of the context it
+ * is contained in.
+ */
+void LLVMGetStructElementTypes(LLVMTypeRef StructTy, LLVMTypeRef *Dest);
+
+/**
+ * Determine whether a structure is packed.
+ *
+ * @see llvm::StructType::isPacked()
+ */
+LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy);
+
+/**
+ * Determine whether a structure is opaque.
+ *
+ * @see llvm::StructType::isOpaque()
+ */
+LLVMBool LLVMIsOpaqueStruct(LLVMTypeRef StructTy);
+
+/**
+ * @}
+ */
+
+
+/**
+ * @defgroup LLVMCCoreTypeSequential Sequential Types
+ *
+ * Sequential types represents "arrays" of types. This is a super class
+ * for array, vector, and pointer types.
+ *
+ * @{
+ */
+
+/**
+ * Obtain the type of elements within a sequential type.
+ *
+ * This works on array, vector, and pointer types.
+ *
+ * @see llvm::SequentialType::getElementType()
+ */
+LLVMTypeRef LLVMGetElementType(LLVMTypeRef Ty);
+
+/**
+ * Create a fixed size array type that refers to a specific type.
+ *
+ * The created type will exist in the context that its element type
+ * exists in.
+ *
+ * @see llvm::ArrayType::get()
+ */
+LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount);
+
+/**
+ * Obtain the length of an array type.
+ *
+ * This only works on types that represent arrays.
+ *
+ * @see llvm::ArrayType::getNumElements()
+ */
+unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy);
+
+/**
+ * Create a pointer type that points to a defined type.
+ *
+ * The created type will exist in the context that its pointee type
+ * exists in.
+ *
+ * @see llvm::PointerType::get()
+ */
+LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace);
+
+/**
+ * Obtain the address space of a pointer type.
+ *
+ * This only works on types that represent pointers.
+ *
+ * @see llvm::PointerType::getAddressSpace()
+ */
+unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy);
+
+/**
+ * Create a vector type that contains a defined type and has a specific
+ * number of elements.
+ *
+ * The created type will exist in the context thats its element type
+ * exists in.
+ *
+ * @see llvm::VectorType::get()
+ */
+LLVMTypeRef LLVMVectorType(LLVMTypeRef ElementType, unsigned ElementCount);
+
+/**
+ * Obtain the number of elements in a vector type.
+ *
+ * This only works on types that represent vectors.
+ *
+ * @see llvm::VectorType::getNumElements()
+ */
+unsigned LLVMGetVectorSize(LLVMTypeRef VectorTy);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreTypeOther Other Types
+ *
+ * @{
+ */
+
+/**
+ * Create a void type in a context.
+ */
+LLVMTypeRef LLVMVoidTypeInContext(LLVMContextRef C);
+
+/**
+ * Create a label type in a context.
+ */
+LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C);
+
+/**
+ * Create a X86 MMX type in a context.
+ */
+LLVMTypeRef LLVMX86MMXTypeInContext(LLVMContextRef C);
+
+/**
+ * These are similar to the above functions except they operate on the
+ * global context.
+ */
+LLVMTypeRef LLVMVoidType(void);
+LLVMTypeRef LLVMLabelType(void);
+LLVMTypeRef LLVMX86MMXType(void);
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValues Values
+ *
+ * The bulk of LLVM's object model consists of values, which comprise a very
+ * rich type hierarchy.
+ *
+ * LLVMValueRef essentially represents llvm::Value. There is a rich
+ * hierarchy of classes within this type. Depending on the instance
+ * obtained, not all APIs are available.
+ *
+ * Callers can determine the type of a LLVMValueRef by calling the
+ * LLVMIsA* family of functions (e.g. LLVMIsAArgument()). These
+ * functions are defined by a macro, so it isn't obvious which are
+ * available by looking at the Doxygen source code. Instead, look at the
+ * source definition of LLVM_FOR_EACH_VALUE_SUBCLASS and note the list
+ * of value names given. These value names also correspond to classes in
+ * the llvm::Value hierarchy.
+ *
+ * @{
+ */
+
+#define LLVM_FOR_EACH_VALUE_SUBCLASS(macro) \
+ macro(Argument) \
+ macro(BasicBlock) \
+ macro(InlineAsm) \
+ macro(MDNode) \
+ macro(MDString) \
+ macro(User) \
+ macro(Constant) \
+ macro(BlockAddress) \
+ macro(ConstantAggregateZero) \
+ macro(ConstantArray) \
+ macro(ConstantExpr) \
+ macro(ConstantFP) \
+ macro(ConstantInt) \
+ macro(ConstantPointerNull) \
+ macro(ConstantStruct) \
+ macro(ConstantVector) \
+ macro(GlobalValue) \
+ macro(Function) \
+ macro(GlobalAlias) \
+ macro(GlobalVariable) \
+ macro(UndefValue) \
+ macro(Instruction) \
+ macro(BinaryOperator) \
+ macro(CallInst) \
+ macro(IntrinsicInst) \
+ macro(DbgInfoIntrinsic) \
+ macro(DbgDeclareInst) \
+ macro(MemIntrinsic) \
+ macro(MemCpyInst) \
+ macro(MemMoveInst) \
+ macro(MemSetInst) \
+ macro(CmpInst) \
+ macro(FCmpInst) \
+ macro(ICmpInst) \
+ macro(ExtractElementInst) \
+ macro(GetElementPtrInst) \
+ macro(InsertElementInst) \
+ macro(InsertValueInst) \
+ macro(LandingPadInst) \
+ macro(PHINode) \
+ macro(SelectInst) \
+ macro(ShuffleVectorInst) \
+ macro(StoreInst) \
+ macro(TerminatorInst) \
+ macro(BranchInst) \
+ macro(IndirectBrInst) \
+ macro(InvokeInst) \
+ macro(ReturnInst) \
+ macro(SwitchInst) \
+ macro(UnreachableInst) \
+ macro(ResumeInst) \
+ macro(UnaryInstruction) \
+ macro(AllocaInst) \
+ macro(CastInst) \
+ macro(BitCastInst) \
+ macro(FPExtInst) \
+ macro(FPToSIInst) \
+ macro(FPToUIInst) \
+ macro(FPTruncInst) \
+ macro(IntToPtrInst) \
+ macro(PtrToIntInst) \
+ macro(SExtInst) \
+ macro(SIToFPInst) \
+ macro(TruncInst) \
+ macro(UIToFPInst) \
+ macro(ZExtInst) \
+ macro(ExtractValueInst) \
+ macro(LoadInst) \
+ macro(VAArgInst)
+
+/**
+ * @defgroup LLVMCCoreValueGeneral General APIs
+ *
+ * Functions in this section work on all LLVMValueRef instances,
+ * regardless of their sub-type. They correspond to functions available
+ * on llvm::Value.
+ *
+ * @{
+ */
+
+/**
+ * Obtain the type of a value.
+ *
+ * @see llvm::Value::getType()
+ */
+LLVMTypeRef LLVMTypeOf(LLVMValueRef Val);
+
+/**
+ * Obtain the string name of a value.
+ *
+ * @see llvm::Value::getName()
+ */
+const char *LLVMGetValueName(LLVMValueRef Val);
+
+/**
+ * Set the string name of a value.
+ *
+ * @see llvm::Value::setName()
+ */
+void LLVMSetValueName(LLVMValueRef Val, const char *Name);
+
+/**
+ * Dump a representation of a value to stderr.
+ *
+ * @see llvm::Value::dump()
+ */
+void LLVMDumpValue(LLVMValueRef Val);
+
+/**
+ * Replace all uses of a value with another one.
+ *
+ * @see llvm::Value::replaceAllUsesWith()
+ */
+void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal);
+
+/**
+ * Determine whether the specified constant instance is constant.
+ */
+LLVMBool LLVMIsConstant(LLVMValueRef Val);
+
+/**
+ * Determine whether a value instance is undefined.
+ */
+LLVMBool LLVMIsUndef(LLVMValueRef Val);
+
+/**
+ * Convert value instances between types.
+ *
+ * Internally, a LLVMValueRef is "pinned" to a specific type. This
+ * series of functions allows you to cast an instance to a specific
+ * type.
+ *
+ * If the cast is not valid for the specified type, NULL is returned.
+ *
+ * @see llvm::dyn_cast_or_null<>
+ */
+#define LLVM_DECLARE_VALUE_CAST(name) \
+ LLVMValueRef LLVMIsA##name(LLVMValueRef Val);
+LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DECLARE_VALUE_CAST)
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueUses Usage
+ *
+ * This module defines functions that allow you to inspect the uses of a
+ * LLVMValueRef.
+ *
+ * It is possible to obtain a LLVMUseRef for any LLVMValueRef instance.
+ * Each LLVMUseRef (which corresponds to a llvm::Use instance) holds a
+ * llvm::User and llvm::Value.
+ *
+ * @{
+ */
+
+/**
+ * Obtain the first use of a value.
+ *
+ * Uses are obtained in an iterator fashion. First, call this function
+ * to obtain a reference to the first use. Then, call LLVMGetNextUse()
+ * on that instance and all subsequently obtained instances until
+ * LLVMGetNextUse() returns NULL.
+ *
+ * @see llvm::Value::use_begin()
+ */
+LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val);
+
+/**
+ * Obtain the next use of a value.
+ *
+ * This effectively advances the iterator. It returns NULL if you are on
+ * the final use and no more are available.
+ */
+LLVMUseRef LLVMGetNextUse(LLVMUseRef U);
+
+/**
+ * Obtain the user value for a user.
+ *
+ * The returned value corresponds to a llvm::User type.
+ *
+ * @see llvm::Use::getUser()
+ */
+LLVMValueRef LLVMGetUser(LLVMUseRef U);
+
+/**
+ * Obtain the value this use corresponds to.
+ *
+ * @see llvm::Use::get().
+ */
+LLVMValueRef LLVMGetUsedValue(LLVMUseRef U);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueUser User value
+ *
+ * Function in this group pertain to LLVMValueRef instances that descent
+ * from llvm::User. This includes constants, instructions, and
+ * operators.
+ *
+ * @{
+ */
+
+/**
+ * Obtain an operand at a specific index in a llvm::User value.
+ *
+ * @see llvm::User::getOperand()
+ */
+LLVMValueRef LLVMGetOperand(LLVMValueRef Val, unsigned Index);
+
+/**
+ * Set an operand at a specific index in a llvm::User value.
+ *
+ * @see llvm::User::setOperand()
+ */
+void LLVMSetOperand(LLVMValueRef User, unsigned Index, LLVMValueRef Val);
+
+/**
+ * Obtain the number of operands in a llvm::User value.
+ *
+ * @see llvm::User::getNumOperands()
+ */
+int LLVMGetNumOperands(LLVMValueRef Val);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueConstant Constants
+ *
+ * This section contains APIs for interacting with LLVMValueRef that
+ * correspond to llvm::Constant instances.
+ *
+ * These functions will work for any LLVMValueRef in the llvm::Constant
+ * class hierarchy.
+ *
+ * @{
+ */
+
+/**
+ * Obtain a constant value referring to the null instance of a type.
+ *
+ * @see llvm::Constant::getNullValue()
+ */
+LLVMValueRef LLVMConstNull(LLVMTypeRef Ty); /* all zeroes */
+
+/**
+ * Obtain a constant value referring to the instance of a type
+ * consisting of all ones.
+ *
+ * This is only valid for integer types.
+ *
+ * @see llvm::Constant::getAllOnesValue()
+ */
+LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty);
+
+/**
+ * Obtain a constant value referring to an undefined value of a type.
+ *
+ * @see llvm::UndefValue::get()
+ */
+LLVMValueRef LLVMGetUndef(LLVMTypeRef Ty);
+
+/**
+ * Determine whether a value instance is null.
+ *
+ * @see llvm::Constant::isNullValue()
+ */
+LLVMBool LLVMIsNull(LLVMValueRef Val);
+
+/**
+ * Obtain a constant that is a constant pointer pointing to NULL for a
+ * specified type.
+ */
+LLVMValueRef LLVMConstPointerNull(LLVMTypeRef Ty);
+
+/**
+ * @defgroup LLVMCCoreValueConstantScalar Scalar constants
+ *
+ * Functions in this group model LLVMValueRef instances that correspond
+ * to constants referring to scalar types.
+ *
+ * For integer types, the LLVMTypeRef parameter should correspond to a
+ * llvm::IntegerType instance and the returned LLVMValueRef will
+ * correspond to a llvm::ConstantInt.
+ *
+ * For floating point types, the LLVMTypeRef returned corresponds to a
+ * llvm::ConstantFP.
+ *
+ * @{
+ */
+
+/**
+ * Obtain a constant value for an integer type.
+ *
+ * The returned value corresponds to a llvm::ConstantInt.
+ *
+ * @see llvm::ConstantInt::get()
+ *
+ * @param IntTy Integer type to obtain value of.
+ * @param N The value the returned instance should refer to.
+ * @param SignExtend Whether to sign extend the produced value.
+ */
+LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N,
+ LLVMBool SignExtend);
+
+/**
+ * Obtain a constant value for an integer of arbitrary precision.
+ *
+ * @see llvm::ConstantInt::get()
+ */
+LLVMValueRef LLVMConstIntOfArbitraryPrecision(LLVMTypeRef IntTy,
+ unsigned NumWords,
+ const uint64_t Words[]);
+
+/**
+ * Obtain a constant value for an integer parsed from a string.
+ *
+ * A similar API, LLVMConstIntOfStringAndSize is also available. If the
+ * string's length is available, it is preferred to call that function
+ * instead.
+ *
+ * @see llvm::ConstantInt::get()
+ */
+LLVMValueRef LLVMConstIntOfString(LLVMTypeRef IntTy, const char *Text,
+ uint8_t Radix);
+
+/**
+ * Obtain a constant value for an integer parsed from a string with
+ * specified length.
+ *
+ * @see llvm::ConstantInt::get()
+ */
+LLVMValueRef LLVMConstIntOfStringAndSize(LLVMTypeRef IntTy, const char *Text,
+ unsigned SLen, uint8_t Radix);
+
+/**
+ * Obtain a constant value referring to a double floating point value.
+ */
+LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N);
+
+/**
+ * Obtain a constant for a floating point value parsed from a string.
+ *
+ * A similar API, LLVMConstRealOfStringAndSize is also available. It
+ * should be used if the input string's length is known.
+ */
+LLVMValueRef LLVMConstRealOfString(LLVMTypeRef RealTy, const char *Text);
+
+/**
+ * Obtain a constant for a floating point value parsed from a string.
+ */
+LLVMValueRef LLVMConstRealOfStringAndSize(LLVMTypeRef RealTy, const char *Text,
+ unsigned SLen);
+
+/**
+ * Obtain the zero extended value for an integer constant value.
+ *
+ * @see llvm::ConstantInt::getZExtValue()
+ */
+unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal);
+
+/**
+ * Obtain the sign extended value for an integer constant value.
+ *
+ * @see llvm::ConstantInt::getSExtValue()
+ */
+long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueConstantComposite Composite Constants
+ *
+ * Functions in this group operate on composite constants.
+ *
+ * @{
+ */
+
+/**
+ * Create a ConstantDataSequential and initialize it with a string.
+ *
+ * @see llvm::ConstantDataArray::getString()
+ */
+LLVMValueRef LLVMConstStringInContext(LLVMContextRef C, const char *Str,
+ unsigned Length, LLVMBool DontNullTerminate);
+
+/**
+ * Create a ConstantDataSequential with string content in the global context.
+ *
+ * This is the same as LLVMConstStringInContext except it operates on the
+ * global context.
+ *
+ * @see LLVMConstStringInContext()
+ * @see llvm::ConstantDataArray::getString()
+ */
+LLVMValueRef LLVMConstString(const char *Str, unsigned Length,
+ LLVMBool DontNullTerminate);
+
+/**
+ * Create an anonymous ConstantStruct with the specified values.
+ *
+ * @see llvm::ConstantStruct::getAnon()
+ */
+LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,
+ LLVMValueRef *ConstantVals,
+ unsigned Count, LLVMBool Packed);
+
+/**
+ * Create a ConstantStruct in the global Context.
+ *
+ * This is the same as LLVMConstStructInContext except it operates on the
+ * global Context.
+ *
+ * @see LLVMConstStructInContext()
+ */
+LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,
+ LLVMBool Packed);
+
+/**
+ * Create a ConstantArray from values.
+ *
+ * @see llvm::ConstantArray::get()
+ */
+LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,
+ LLVMValueRef *ConstantVals, unsigned Length);
+
+/**
+ * Create a non-anonymous ConstantStruct from values.
+ *
+ * @see llvm::ConstantStruct::get()
+ */
+LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy,
+ LLVMValueRef *ConstantVals,
+ unsigned Count);
+
+/**
+ * Create a ConstantVector from values.
+ *
+ * @see llvm::ConstantVector::get()
+ */
+LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Size);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueConstantExpressions Constant Expressions
+ *
+ * Functions in this group correspond to APIs on llvm::ConstantExpr.
+ *
+ * @see llvm::ConstantExpr.
+ *
+ * @{
+ */
+LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal);
+LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty);
+LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty);
+LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal);
+LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal);
+LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal);
+LLVMValueRef LLVMConstFNeg(LLVMValueRef ConstantVal);
+LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal);
+LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstFAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstFSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstFMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstExactSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstFDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstURem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstSRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstFRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstICmp(LLVMIntPredicate Predicate,
+ LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstFCmp(LLVMRealPredicate Predicate,
+ LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
+LLVMValueRef LLVMConstGEP(LLVMValueRef ConstantVal,
+ LLVMValueRef *ConstantIndices, unsigned NumIndices);
+LLVMValueRef LLVMConstInBoundsGEP(LLVMValueRef ConstantVal,
+ LLVMValueRef *ConstantIndices,
+ unsigned NumIndices);
+LLVMValueRef LLVMConstTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstSExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstZExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstFPTrunc(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstFPExt(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstUIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstSIToFP(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstFPToUI(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstFPToSI(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstPtrToInt(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstIntToPtr(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstBitCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstZExtOrBitCast(LLVMValueRef ConstantVal,
+ LLVMTypeRef ToType);
+LLVMValueRef LLVMConstSExtOrBitCast(LLVMValueRef ConstantVal,
+ LLVMTypeRef ToType);
+LLVMValueRef LLVMConstTruncOrBitCast(LLVMValueRef ConstantVal,
+ LLVMTypeRef ToType);
+LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal,
+ LLVMTypeRef ToType);
+LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType,
+ LLVMBool isSigned);
+LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
+LLVMValueRef LLVMConstSelect(LLVMValueRef ConstantCondition,
+ LLVMValueRef ConstantIfTrue,
+ LLVMValueRef ConstantIfFalse);
+LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant,
+ LLVMValueRef IndexConstant);
+LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,
+ LLVMValueRef ElementValueConstant,
+ LLVMValueRef IndexConstant);
+LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant,
+ LLVMValueRef VectorBConstant,
+ LLVMValueRef MaskConstant);
+LLVMValueRef LLVMConstExtractValue(LLVMValueRef AggConstant, unsigned *IdxList,
+ unsigned NumIdx);
+LLVMValueRef LLVMConstInsertValue(LLVMValueRef AggConstant,
+ LLVMValueRef ElementValueConstant,
+ unsigned *IdxList, unsigned NumIdx);
+LLVMValueRef LLVMConstInlineAsm(LLVMTypeRef Ty,
+ const char *AsmString, const char *Constraints,
+ LLVMBool HasSideEffects, LLVMBool IsAlignStack);
+LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueConstantGlobals Global Values
+ *
+ * This group contains functions that operate on global values. Functions in
+ * this group relate to functions in the llvm::GlobalValue class tree.
+ *
+ * @see llvm::GlobalValue
+ *
+ * @{
+ */
+
+LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global);
+LLVMBool LLVMIsDeclaration(LLVMValueRef Global);
+LLVMLinkage LLVMGetLinkage(LLVMValueRef Global);
+void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage);
+const char *LLVMGetSection(LLVMValueRef Global);
+void LLVMSetSection(LLVMValueRef Global, const char *Section);
+LLVMVisibility LLVMGetVisibility(LLVMValueRef Global);
+void LLVMSetVisibility(LLVMValueRef Global, LLVMVisibility Viz);
+unsigned LLVMGetAlignment(LLVMValueRef Global);
+void LLVMSetAlignment(LLVMValueRef Global, unsigned Bytes);
+
+/**
+ * @defgroup LLVMCoreValueConstantGlobalVariable Global Variables
+ *
+ * This group contains functions that operate on global variable values.
+ *
+ * @see llvm::GlobalVariable
+ *
+ * @{
+ */
+LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Name);
+LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty,
+ const char *Name,
+ unsigned AddressSpace);
+LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name);
+LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M);
+LLVMValueRef LLVMGetLastGlobal(LLVMModuleRef M);
+LLVMValueRef LLVMGetNextGlobal(LLVMValueRef GlobalVar);
+LLVMValueRef LLVMGetPreviousGlobal(LLVMValueRef GlobalVar);
+void LLVMDeleteGlobal(LLVMValueRef GlobalVar);
+LLVMValueRef LLVMGetInitializer(LLVMValueRef GlobalVar);
+void LLVMSetInitializer(LLVMValueRef GlobalVar, LLVMValueRef ConstantVal);
+LLVMBool LLVMIsThreadLocal(LLVMValueRef GlobalVar);
+void LLVMSetThreadLocal(LLVMValueRef GlobalVar, LLVMBool IsThreadLocal);
+LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar);
+void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCoreValueConstantGlobalAlias Global Aliases
+ *
+ * This group contains function that operate on global alias values.
+ *
+ * @see llvm::GlobalAlias
+ *
+ * @{
+ */
+LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Aliasee,
+ const char *Name);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueFunction Function values
+ *
+ * Functions in this group operate on LLVMValueRef instances that
+ * correspond to llvm::Function instances.
+ *
+ * @see llvm::Function
+ *
+ * @{
+ */
+
+/**
+ * Remove a function from its containing module and deletes it.
+ *
+ * @see llvm::Function::eraseFromParent()
+ */
+void LLVMDeleteFunction(LLVMValueRef Fn);
+
+/**
+ * Obtain the ID number from a function instance.
+ *
+ * @see llvm::Function::getIntrinsicID()
+ */
+unsigned LLVMGetIntrinsicID(LLVMValueRef Fn);
+
+/**
+ * Obtain the calling function of a function.
+ *
+ * The returned value corresponds to the LLVMCallConv enumeration.
+ *
+ * @see llvm::Function::getCallingConv()
+ */
+unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn);
+
+/**
+ * Set the calling convention of a function.
+ *
+ * @see llvm::Function::setCallingConv()
+ *
+ * @param Fn Function to operate on
+ * @param CC LLVMCallConv to set calling convention to
+ */
+void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC);
+
+/**
+ * Obtain the name of the garbage collector to use during code
+ * generation.
+ *
+ * @see llvm::Function::getGC()
+ */
+const char *LLVMGetGC(LLVMValueRef Fn);
+
+/**
+ * Define the garbage collector to use during code generation.
+ *
+ * @see llvm::Function::setGC()
+ */
+void LLVMSetGC(LLVMValueRef Fn, const char *Name);
+
+/**
+ * Add an attribute to a function.
+ *
+ * @see llvm::Function::addAttribute()
+ */
+void LLVMAddFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA);
+
+/**
+ * Obtain an attribute from a function.
+ *
+ * @see llvm::Function::getAttributes()
+ */
+LLVMAttribute LLVMGetFunctionAttr(LLVMValueRef Fn);
+
+/**
+ * Remove an attribute from a function.
+ */
+void LLVMRemoveFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA);
+
+/**
+ * @defgroup LLVMCCoreValueFunctionParameters Function Parameters
+ *
+ * Functions in this group relate to arguments/parameters on functions.
+ *
+ * Functions in this group expect LLVMValueRef instances that correspond
+ * to llvm::Function instances.
+ *
+ * @{
+ */
+
+/**
+ * Obtain the number of parameters in a function.
+ *
+ * @see llvm::Function::arg_size()
+ */
+unsigned LLVMCountParams(LLVMValueRef Fn);
+
+/**
+ * Obtain the parameters in a function.
+ *
+ * The takes a pointer to a pre-allocated array of LLVMValueRef that is
+ * at least LLVMCountParams() long. This array will be filled with
+ * LLVMValueRef instances which correspond to the parameters the
+ * function receives. Each LLVMValueRef corresponds to a llvm::Argument
+ * instance.
+ *
+ * @see llvm::Function::arg_begin()
+ */
+void LLVMGetParams(LLVMValueRef Fn, LLVMValueRef *Params);
+
+/**
+ * Obtain the parameter at the specified index.
+ *
+ * Parameters are indexed from 0.
+ *
+ * @see llvm::Function::arg_begin()
+ */
+LLVMValueRef LLVMGetParam(LLVMValueRef Fn, unsigned Index);
+
+/**
+ * Obtain the function to which this argument belongs.
+ *
+ * Unlike other functions in this group, this one takes a LLVMValueRef
+ * that corresponds to a llvm::Attribute.
+ *
+ * The returned LLVMValueRef is the llvm::Function to which this
+ * argument belongs.
+ */
+LLVMValueRef LLVMGetParamParent(LLVMValueRef Inst);
+
+/**
+ * Obtain the first parameter to a function.
+ *
+ * @see llvm::Function::arg_begin()
+ */
+LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn);
+
+/**
+ * Obtain the last parameter to a function.
+ *
+ * @see llvm::Function::arg_end()
+ */
+LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn);
+
+/**
+ * Obtain the next parameter to a function.
+ *
+ * This takes a LLVMValueRef obtained from LLVMGetFirstParam() (which is
+ * actually a wrapped iterator) and obtains the next parameter from the
+ * underlying iterator.
+ */
+LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg);
+
+/**
+ * Obtain the previous parameter to a function.
+ *
+ * This is the opposite of LLVMGetNextParam().
+ */
+LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg);
+
+/**
+ * Add an attribute to a function argument.
+ *
+ * @see llvm::Argument::addAttr()
+ */
+void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA);
+
+/**
+ * Remove an attribute from a function argument.
+ *
+ * @see llvm::Argument::removeAttr()
+ */
+void LLVMRemoveAttribute(LLVMValueRef Arg, LLVMAttribute PA);
+
+/**
+ * Get an attribute from a function argument.
+ */
+LLVMAttribute LLVMGetAttribute(LLVMValueRef Arg);
+
+/**
+ * Set the alignment for a function parameter.
+ *
+ * @see llvm::Argument::addAttr()
+ * @see llvm::Attribute::constructAlignmentFromInt()
+ */
+void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align);
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueMetadata Metadata
+ *
+ * @{
+ */
+
+/**
+ * Obtain a MDString value from a context.
+ *
+ * The returned instance corresponds to the llvm::MDString class.
+ *
+ * The instance is specified by string data of a specified length. The
+ * string content is copied, so the backing memory can be freed after
+ * this function returns.
+ */
+LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,
+ unsigned SLen);
+
+/**
+ * Obtain a MDString value from the global context.
+ */
+LLVMValueRef LLVMMDString(const char *Str, unsigned SLen);
+
+/**
+ * Obtain a MDNode value from a context.
+ *
+ * The returned value corresponds to the llvm::MDNode class.
+ */
+LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals,
+ unsigned Count);
+
+/**
+ * Obtain a MDNode value from the global context.
+ */
+LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count);
+
+/**
+ * Obtain the underlying string from a MDString value.
+ *
+ * @param V Instance to obtain string from.
+ * @param Len Memory address which will hold length of returned string.
+ * @return String data in MDString.
+ */
+const char *LLVMGetMDString(LLVMValueRef V, unsigned* Len);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueBasicBlock Basic Block
+ *
+ * A basic block represents a single entry single exit section of code.
+ * Basic blocks contain a list of instructions which form the body of
+ * the block.
+ *
+ * Basic blocks belong to functions. They have the type of label.
+ *
+ * Basic blocks are themselves values. However, the C API models them as
+ * LLVMBasicBlockRef.
+ *
+ * @see llvm::BasicBlock
+ *
+ * @{
+ */
+
+/**
+ * Convert a basic block instance to a value type.
+ */
+LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB);
+
+/**
+ * Determine whether a LLVMValueRef is itself a basic block.
+ */
+LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val);
+
+/**
+ * Convert a LLVMValueRef to a LLVMBasicBlockRef instance.
+ */
+LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val);
+
+/**
+ * Obtain the function to which a basic block belongs.
+ *
+ * @see llvm::BasicBlock::getParent()
+ */
+LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB);
+
+/**
+ * Obtain the terminator instruction for a basic block.
+ *
+ * If the basic block does not have a terminator (it is not well-formed
+ * if it doesn't), then NULL is returned.
+ *
+ * The returned LLVMValueRef corresponds to a llvm::TerminatorInst.
+ *
+ * @see llvm::BasicBlock::getTerminator()
+ */
+LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB);
+
+/**
+ * Obtain the number of basic blocks in a function.
+ *
+ * @param Fn Function value to operate on.
+ */
+unsigned LLVMCountBasicBlocks(LLVMValueRef Fn);
+
+/**
+ * Obtain all of the basic blocks in a function.
+ *
+ * This operates on a function value. The BasicBlocks parameter is a
+ * pointer to a pre-allocated array of LLVMBasicBlockRef of at least
+ * LLVMCountBasicBlocks() in length. This array is populated with
+ * LLVMBasicBlockRef instances.
+ */
+void LLVMGetBasicBlocks(LLVMValueRef Fn, LLVMBasicBlockRef *BasicBlocks);
+
+/**
+ * Obtain the first basic block in a function.
+ *
+ * The returned basic block can be used as an iterator. You will likely
+ * eventually call into LLVMGetNextBasicBlock() with it.
+ *
+ * @see llvm::Function::begin()
+ */
+LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn);
+
+/**
+ * Obtain the last basic block in a function.
+ *
+ * @see llvm::Function::end()
+ */
+LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn);
+
+/**
+ * Advance a basic block iterator.
+ */
+LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB);
+
+/**
+ * Go backwards in a basic block iterator.
+ */
+LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB);
+
+/**
+ * Obtain the basic block that corresponds to the entry point of a
+ * function.
+ *
+ * @see llvm::Function::getEntryBlock()
+ */
+LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn);
+
+/**
+ * Append a basic block to the end of a function.
+ *
+ * @see llvm::BasicBlock::Create()
+ */
+LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
+ LLVMValueRef Fn,
+ const char *Name);
+
+/**
+ * Append a basic block to the end of a function using the global
+ * context.
+ *
+ * @see llvm::BasicBlock::Create()
+ */
+LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef Fn, const char *Name);
+
+/**
+ * Insert a basic block in a function before another basic block.
+ *
+ * The function to add to is determined by the function of the
+ * passed basic block.
+ *
+ * @see llvm::BasicBlock::Create()
+ */
+LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C,
+ LLVMBasicBlockRef BB,
+ const char *Name);
+
+/**
+ * Insert a basic block in a function using the global context.
+ *
+ * @see llvm::BasicBlock::Create()
+ */
+LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef InsertBeforeBB,
+ const char *Name);
+
+/**
+ * Remove a basic block from a function and delete it.
+ *
+ * This deletes the basic block from its containing function and deletes
+ * the basic block itself.
+ *
+ * @see llvm::BasicBlock::eraseFromParent()
+ */
+void LLVMDeleteBasicBlock(LLVMBasicBlockRef BB);
+
+/**
+ * Remove a basic block from a function.
+ *
+ * This deletes the basic block from its containing function but keep
+ * the basic block alive.
+ *
+ * @see llvm::BasicBlock::removeFromParent()
+ */
+void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BB);
+
+/**
+ * Move a basic block to before another one.
+ *
+ * @see llvm::BasicBlock::moveBefore()
+ */
+void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos);
+
+/**
+ * Move a basic block to after another one.
+ *
+ * @see llvm::BasicBlock::moveAfter()
+ */
+void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MovePos);
+
+/**
+ * Obtain the first instruction in a basic block.
+ *
+ * The returned LLVMValueRef corresponds to a llvm::Instruction
+ * instance.
+ */
+LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB);
+
+/**
+ * Obtain the last instruction in a basic block.
+ *
+ * The returned LLVMValueRef corresponds to a LLVM:Instruction.
+ */
+LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueInstruction Instructions
+ *
+ * Functions in this group relate to the inspection and manipulation of
+ * individual instructions.
+ *
+ * In the C++ API, an instruction is modeled by llvm::Instruction. This
+ * class has a large number of descendents. llvm::Instruction is a
+ * llvm::Value and in the C API, instructions are modeled by
+ * LLVMValueRef.
+ *
+ * This group also contains sub-groups which operate on specific
+ * llvm::Instruction types, e.g. llvm::CallInst.
+ *
+ * @{
+ */
+
+/**
+ * Determine whether an instruction has any metadata attached.
+ */
+int LLVMHasMetadata(LLVMValueRef Val);
+
+/**
+ * Return metadata associated with an instruction value.
+ */
+LLVMValueRef LLVMGetMetadata(LLVMValueRef Val, unsigned KindID);
+
+/**
+ * Set metadata associated with an instruction value.
+ */
+void LLVMSetMetadata(LLVMValueRef Val, unsigned KindID, LLVMValueRef Node);
+
+/**
+ * Obtain the basic block to which an instruction belongs.
+ *
+ * @see llvm::Instruction::getParent()
+ */
+LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst);
+
+/**
+ * Obtain the instruction that occurs after the one specified.
+ *
+ * The next instruction will be from the same basic block.
+ *
+ * If this is the last instruction in a basic block, NULL will be
+ * returned.
+ */
+LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst);
+
+/**
+ * Obtain the instruction that occurred before this one.
+ *
+ * If the instruction is the first instruction in a basic block, NULL
+ * will be returned.
+ */
+LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst);
+
+/**
+ * Remove and delete an instruction.
+ *
+ * The instruction specified is removed from its containing building
+ * block and then deleted.
+ *
+ * @see llvm::Instruction::eraseFromParent()
+ */
+void LLVMInstructionEraseFromParent(LLVMValueRef Inst);
+
+/**
+ * Obtain the code opcode for an individual instruction.
+ *
+ * @see llvm::Instruction::getOpCode()
+ */
+LLVMOpcode LLVMGetInstructionOpcode(LLVMValueRef Inst);
+
+/**
+ * Obtain the predicate of an instruction.
+ *
+ * This is only valid for instructions that correspond to llvm::ICmpInst
+ * or llvm::ConstantExpr whose opcode is llvm::Instruction::ICmp.
+ *
+ * @see llvm::ICmpInst::getPredicate()
+ */
+LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst);
+
+/**
+ * @defgroup LLVMCCoreValueInstructionCall Call Sites and Invocations
+ *
+ * Functions in this group apply to instructions that refer to call
+ * sites and invocations. These correspond to C++ types in the
+ * llvm::CallInst class tree.
+ *
+ * @{
+ */
+
+/**
+ * Set the calling convention for a call instruction.
+ *
+ * This expects an LLVMValueRef that corresponds to a llvm::CallInst or
+ * llvm::InvokeInst.
+ *
+ * @see llvm::CallInst::setCallingConv()
+ * @see llvm::InvokeInst::setCallingConv()
+ */
+void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC);
+
+/**
+ * Obtain the calling convention for a call instruction.
+ *
+ * This is the opposite of LLVMSetInstructionCallConv(). Reads its
+ * usage.
+ *
+ * @see LLVMSetInstructionCallConv()
+ */
+unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr);
+
+
+void LLVMAddInstrAttribute(LLVMValueRef Instr, unsigned index, LLVMAttribute);
+void LLVMRemoveInstrAttribute(LLVMValueRef Instr, unsigned index,
+ LLVMAttribute);
+void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index,
+ unsigned align);
+
+/**
+ * Obtain whether a call instruction is a tail call.
+ *
+ * This only works on llvm::CallInst instructions.
+ *
+ * @see llvm::CallInst::isTailCall()
+ */
+LLVMBool LLVMIsTailCall(LLVMValueRef CallInst);
+
+/**
+ * Set whether a call instruction is a tail call.
+ *
+ * This only works on llvm::CallInst instructions.
+ *
+ * @see llvm::CallInst::setTailCall()
+ */
+void LLVMSetTailCall(LLVMValueRef CallInst, LLVMBool IsTailCall);
+
+/**
+ * @}
+ */
+
+/**
+ * Obtain the default destination basic block of a switch instruction.
+ *
+ * This only works on llvm::SwitchInst instructions.
+ *
+ * @see llvm::SwitchInst::getDefaultDest()
+ */
+LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef SwitchInstr);
+
+/**
+ * @defgroup LLVMCCoreValueInstructionPHINode PHI Nodes
+ *
+ * Functions in this group only apply to instructions that map to
+ * llvm::PHINode instances.
+ *
+ * @{
+ */
+
+/**
+ * Add an incoming value to the end of a PHI list.
+ */
+void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues,
+ LLVMBasicBlockRef *IncomingBlocks, unsigned Count);
+
+/**
+ * Obtain the number of incoming basic blocks to a PHI node.
+ */
+unsigned LLVMCountIncoming(LLVMValueRef PhiNode);
+
+/**
+ * Obtain an incoming value to a PHI node as a LLVMValueRef.
+ */
+LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index);
+
+/**
+ * Obtain an incoming value to a PHI node as a LLVMBasicBlockRef.
+ */
+LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index);
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreInstructionBuilder Instruction Builders
+ *
+ * An instruction builder represents a point within a basic block and is
+ * the exclusive means of building instructions using the C interface.
+ *
+ * @{
+ */
+
+LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C);
+LLVMBuilderRef LLVMCreateBuilder(void);
+void LLVMPositionBuilder(LLVMBuilderRef Builder, LLVMBasicBlockRef Block,
+ LLVMValueRef Instr);
+void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr);
+void LLVMPositionBuilderAtEnd(LLVMBuilderRef Builder, LLVMBasicBlockRef Block);
+LLVMBasicBlockRef LLVMGetInsertBlock(LLVMBuilderRef Builder);
+void LLVMClearInsertionPosition(LLVMBuilderRef Builder);
+void LLVMInsertIntoBuilder(LLVMBuilderRef Builder, LLVMValueRef Instr);
+void LLVMInsertIntoBuilderWithName(LLVMBuilderRef Builder, LLVMValueRef Instr,
+ const char *Name);
+void LLVMDisposeBuilder(LLVMBuilderRef Builder);
+
+/* Metadata */
+void LLVMSetCurrentDebugLocation(LLVMBuilderRef Builder, LLVMValueRef L);
+LLVMValueRef LLVMGetCurrentDebugLocation(LLVMBuilderRef Builder);
+void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst);
+
+/* Terminators */
+LLVMValueRef LLVMBuildRetVoid(LLVMBuilderRef);
+LLVMValueRef LLVMBuildRet(LLVMBuilderRef, LLVMValueRef V);
+LLVMValueRef LLVMBuildAggregateRet(LLVMBuilderRef, LLVMValueRef *RetVals,
+ unsigned N);
+LLVMValueRef LLVMBuildBr(LLVMBuilderRef, LLVMBasicBlockRef Dest);
+LLVMValueRef LLVMBuildCondBr(LLVMBuilderRef, LLVMValueRef If,
+ LLVMBasicBlockRef Then, LLVMBasicBlockRef Else);
+LLVMValueRef LLVMBuildSwitch(LLVMBuilderRef, LLVMValueRef V,
+ LLVMBasicBlockRef Else, unsigned NumCases);
+LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr,
+ unsigned NumDests);
+LLVMValueRef LLVMBuildInvoke(LLVMBuilderRef, LLVMValueRef Fn,
+ LLVMValueRef *Args, unsigned NumArgs,
+ LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
+ const char *Name);
+LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty,
+ LLVMValueRef PersFn, unsigned NumClauses,
+ const char *Name);
+LLVMValueRef LLVMBuildResume(LLVMBuilderRef B, LLVMValueRef Exn);
+LLVMValueRef LLVMBuildUnreachable(LLVMBuilderRef);
+
+/* Add a case to the switch instruction */
+void LLVMAddCase(LLVMValueRef Switch, LLVMValueRef OnVal,
+ LLVMBasicBlockRef Dest);
+
+/* Add a destination to the indirectbr instruction */
+void LLVMAddDestination(LLVMValueRef IndirectBr, LLVMBasicBlockRef Dest);
+
+/* Add a catch or filter clause to the landingpad instruction */
+void LLVMAddClause(LLVMValueRef LandingPad, LLVMValueRef ClauseVal);
+
+/* Set the 'cleanup' flag in the landingpad instruction */
+void LLVMSetCleanup(LLVMValueRef LandingPad, LLVMBool Val);
+
+/* Arithmetic */
+LLVMValueRef LLVMBuildAdd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildNSWAdd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildNUWAdd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildFAdd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildNSWSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildNUWSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildFSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildMul(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildNSWMul(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildNUWMul(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildFMul(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildUDiv(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildSDiv(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildExactSDiv(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildFDiv(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildURem(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildSRem(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildFRem(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildShl(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildLShr(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildAShr(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildAnd(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildOr(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildXor(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildBinOp(LLVMBuilderRef B, LLVMOpcode Op,
+ LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildNeg(LLVMBuilderRef, LLVMValueRef V, const char *Name);
+LLVMValueRef LLVMBuildNSWNeg(LLVMBuilderRef B, LLVMValueRef V,
+ const char *Name);
+LLVMValueRef LLVMBuildNUWNeg(LLVMBuilderRef B, LLVMValueRef V,
+ const char *Name);
+LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef, LLVMValueRef V, const char *Name);
+LLVMValueRef LLVMBuildNot(LLVMBuilderRef, LLVMValueRef V, const char *Name);
+
+/* Memory */
+LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name);
+LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef, LLVMTypeRef Ty,
+ LLVMValueRef Val, const char *Name);
+LLVMValueRef LLVMBuildAlloca(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name);
+LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef, LLVMTypeRef Ty,
+ LLVMValueRef Val, const char *Name);
+LLVMValueRef LLVMBuildFree(LLVMBuilderRef, LLVMValueRef PointerVal);
+LLVMValueRef LLVMBuildLoad(LLVMBuilderRef, LLVMValueRef PointerVal,
+ const char *Name);
+LLVMValueRef LLVMBuildStore(LLVMBuilderRef, LLVMValueRef Val, LLVMValueRef Ptr);
+LLVMValueRef LLVMBuildGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
+ LLVMValueRef *Indices, unsigned NumIndices,
+ const char *Name);
+LLVMValueRef LLVMBuildInBoundsGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
+ LLVMValueRef *Indices, unsigned NumIndices,
+ const char *Name);
+LLVMValueRef LLVMBuildStructGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
+ unsigned Idx, const char *Name);
+LLVMValueRef LLVMBuildGlobalString(LLVMBuilderRef B, const char *Str,
+ const char *Name);
+LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str,
+ const char *Name);
+LLVMBool LLVMGetVolatile(LLVMValueRef MemoryAccessInst);
+void LLVMSetVolatile(LLVMValueRef MemoryAccessInst, LLVMBool IsVolatile);
+
+/* Casts */
+LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildZExt(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildSExt(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildFPToUI(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildFPToSI(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildUIToFP(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildSIToFP(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildFPTrunc(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildFPExt(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildPtrToInt(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildIntToPtr(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildBitCast(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildZExtOrBitCast(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildSExtOrBitCast(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildTruncOrBitCast(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildCast(LLVMBuilderRef B, LLVMOpcode Op, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildPointerCast(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef, LLVMValueRef Val, /*Signed cast!*/
+ LLVMTypeRef DestTy, const char *Name);
+LLVMValueRef LLVMBuildFPCast(LLVMBuilderRef, LLVMValueRef Val,
+ LLVMTypeRef DestTy, const char *Name);
+
+/* Comparisons */
+LLVMValueRef LLVMBuildICmp(LLVMBuilderRef, LLVMIntPredicate Op,
+ LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef, LLVMRealPredicate Op,
+ LLVMValueRef LHS, LLVMValueRef RHS,
+ const char *Name);
+
+/* Miscellaneous instructions */
+LLVMValueRef LLVMBuildPhi(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name);
+LLVMValueRef LLVMBuildCall(LLVMBuilderRef, LLVMValueRef Fn,
+ LLVMValueRef *Args, unsigned NumArgs,
+ const char *Name);
+LLVMValueRef LLVMBuildSelect(LLVMBuilderRef, LLVMValueRef If,
+ LLVMValueRef Then, LLVMValueRef Else,
+ const char *Name);
+LLVMValueRef LLVMBuildVAArg(LLVMBuilderRef, LLVMValueRef List, LLVMTypeRef Ty,
+ const char *Name);
+LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef, LLVMValueRef VecVal,
+ LLVMValueRef Index, const char *Name);
+LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef, LLVMValueRef VecVal,
+ LLVMValueRef EltVal, LLVMValueRef Index,
+ const char *Name);
+LLVMValueRef LLVMBuildShuffleVector(LLVMBuilderRef, LLVMValueRef V1,
+ LLVMValueRef V2, LLVMValueRef Mask,
+ const char *Name);
+LLVMValueRef LLVMBuildExtractValue(LLVMBuilderRef, LLVMValueRef AggVal,
+ unsigned Index, const char *Name);
+LLVMValueRef LLVMBuildInsertValue(LLVMBuilderRef, LLVMValueRef AggVal,
+ LLVMValueRef EltVal, unsigned Index,
+ const char *Name);
+
+LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef, LLVMValueRef Val,
+ const char *Name);
+LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef, LLVMValueRef Val,
+ const char *Name);
+LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef, LLVMValueRef LHS,
+ LLVMValueRef RHS, const char *Name);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreModuleProvider Module Providers
+ *
+ * @{
+ */
+
+/**
+ * Changes the type of M so it can be passed to FunctionPassManagers and the
+ * JIT. They take ModuleProviders for historical reasons.
+ */
+LLVMModuleProviderRef
+LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M);
+
+/**
+ * Destroys the module M.
+ */
+void LLVMDisposeModuleProvider(LLVMModuleProviderRef M);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreMemoryBuffers Memory Buffers
+ *
+ * @{
+ */
+
+LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(const char *Path,
+ LLVMMemoryBufferRef *OutMemBuf,
+ char **OutMessage);
+LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf,
+ char **OutMessage);
+void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCorePassRegistry Pass Registry
+ *
+ * @{
+ */
+
+/** Return the global pass registry, for use with initialization functions.
+ @see llvm::PassRegistry::getPassRegistry */
+LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCorePassManagers Pass Managers
+ *
+ * @{
+ */
+
+/** Constructs a new whole-module pass pipeline. This type of pipeline is
+ suitable for link-time optimization and whole-module transformations.
+ @see llvm::PassManager::PassManager */
+LLVMPassManagerRef LLVMCreatePassManager(void);
+
+/** Constructs a new function-by-function pass pipeline over the module
+ provider. It does not take ownership of the module provider. This type of
+ pipeline is suitable for code generation and JIT compilation tasks.
+ @see llvm::FunctionPassManager::FunctionPassManager */
+LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M);
+
+/** Deprecated: Use LLVMCreateFunctionPassManagerForModule instead. */
+LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef MP);
+
+/** Initializes, executes on the provided module, and finalizes all of the
+ passes scheduled in the pass manager. Returns 1 if any of the passes
+ modified the module, 0 otherwise.
+ @see llvm::PassManager::run(Module&) */
+LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M);
+
+/** Initializes all of the function passes scheduled in the function pass
+ manager. Returns 1 if any of the passes modified the module, 0 otherwise.
+ @see llvm::FunctionPassManager::doInitialization */
+LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM);
+
+/** Executes all of the function passes scheduled in the function pass manager
+ on the provided function. Returns 1 if any of the passes modified the
+ function, false otherwise.
+ @see llvm::FunctionPassManager::run(Function&) */
+LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F);
+
+/** Finalizes all of the function passes scheduled in in the function pass
+ manager. Returns 1 if any of the passes modified the module, 0 otherwise.
+ @see llvm::FunctionPassManager::doFinalization */
+LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM);
+
+/** Frees the memory of a pass pipeline. For function pipelines, does not free
+ the module provider.
+ @see llvm::PassManagerBase::~PassManagerBase. */
+void LLVMDisposePassManager(LLVMPassManagerRef PM);
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+
+namespace llvm {
+ class MemoryBuffer;
+ class PassManagerBase;
+
+ #define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \
+ inline ty *unwrap(ref P) { \
+ return reinterpret_cast<ty*>(P); \
+ } \
+ \
+ inline ref wrap(const ty *P) { \
+ return reinterpret_cast<ref>(const_cast<ty*>(P)); \
+ }
+
+ #define DEFINE_ISA_CONVERSION_FUNCTIONS(ty, ref) \
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \
+ \
+ template<typename T> \
+ inline T *unwrap(ref P) { \
+ return cast<T>(unwrap(P)); \
+ }
+
+ #define DEFINE_STDCXX_CONVERSION_FUNCTIONS(ty, ref) \
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \
+ \
+ template<typename T> \
+ inline T *unwrap(ref P) { \
+ T *Q = (T*)unwrap(P); \
+ assert(Q && "Invalid cast!"); \
+ return Q; \
+ }
+
+ DEFINE_ISA_CONVERSION_FUNCTIONS (Type, LLVMTypeRef )
+ DEFINE_ISA_CONVERSION_FUNCTIONS (Value, LLVMValueRef )
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef )
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef )
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef )
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(MemoryBuffer, LLVMMemoryBufferRef )
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef )
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Use, LLVMUseRef )
+ DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBase, LLVMPassManagerRef )
+ DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassRegistry, LLVMPassRegistryRef )
+ /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
+ * Module.
+ */
+ inline Module *unwrap(LLVMModuleProviderRef MP) {
+ return reinterpret_cast<Module*>(MP);
+ }
+
+ #undef DEFINE_STDCXX_CONVERSION_FUNCTIONS
+ #undef DEFINE_ISA_CONVERSION_FUNCTIONS
+ #undef DEFINE_SIMPLE_CONVERSION_FUNCTIONS
+
+ /* Specialized opaque context conversions.
+ */
+ inline LLVMContext **unwrap(LLVMContextRef* Tys) {
+ return reinterpret_cast<LLVMContext**>(Tys);
+ }
+
+ inline LLVMContextRef *wrap(const LLVMContext **Tys) {
+ return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
+ }
+
+ /* Specialized opaque type conversions.
+ */
+ inline Type **unwrap(LLVMTypeRef* Tys) {
+ return reinterpret_cast<Type**>(Tys);
+ }
+
+ inline LLVMTypeRef *wrap(Type **Tys) {
+ return reinterpret_cast<LLVMTypeRef*>(const_cast<Type**>(Tys));
+ }
+
+ /* Specialized opaque value conversions.
+ */
+ inline Value **unwrap(LLVMValueRef *Vals) {
+ return reinterpret_cast<Value**>(Vals);
+ }
+
+ template<typename T>
+ inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
+ #ifdef DEBUG
+ for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
+ cast<T>(*I);
+ #endif
+ (void)Length;
+ return reinterpret_cast<T**>(Vals);
+ }
+
+ inline LLVMValueRef *wrap(const Value **Vals) {
+ return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
+ }
+}
+
+#endif /* !defined(__cplusplus) */
+
+#endif /* !defined(LLVM_C_CORE_H) */
diff --git a/include/llvm-c/Disassembler.h b/include/llvm-c/Disassembler.h
new file mode 100644
index 00000000000..69fdc645669
--- /dev/null
+++ b/include/llvm-c/Disassembler.h
@@ -0,0 +1,175 @@
+/*===-- llvm-c/Disassembler.h - Disassembler Public C Interface ---*- C -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header provides a public interface to a disassembler library. *|
+|* LLVM provides an implementation of this interface. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_DISASSEMBLER_H
+#define LLVM_C_DISASSEMBLER_H
+
+#include "llvm/Support/DataTypes.h"
+#include <stddef.h>
+
+/**
+ * @defgroup LLVMCDisassembler Disassembler
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+/**
+ * An opaque reference to a disassembler context.
+ */
+typedef void *LLVMDisasmContextRef;
+
+/**
+ * The type for the operand information call back function. This is called to
+ * get the symbolic information for an operand of an instruction. Typically
+ * this is from the relocation information, symbol table, etc. That block of
+ * information is saved when the disassembler context is created and passed to
+ * the call back in the DisInfo parameter. The instruction containing operand
+ * is at the PC parameter. For some instruction sets, there can be more than
+ * one operand with symbolic information. To determine the symbolic operand
+ * information for each operand, the bytes for the specific operand in the
+ * instruction are specified by the Offset parameter and its byte widith is the
+ * size parameter. For instructions sets with fixed widths and one symbolic
+ * operand per instruction, the Offset parameter will be zero and Size parameter
+ * will be the instruction width. The information is returned in TagBuf and is
+ * Triple specific with its specific information defined by the value of
+ * TagType for that Triple. If symbolic information is returned the function
+ * returns 1, otherwise it returns 0.
+ */
+typedef int (*LLVMOpInfoCallback)(void *DisInfo, uint64_t PC,
+ uint64_t Offset, uint64_t Size,
+ int TagType, void *TagBuf);
+
+/**
+ * The initial support in LLVM MC for the most general form of a relocatable
+ * expression is "AddSymbol - SubtractSymbol + Offset". For some Darwin targets
+ * this full form is encoded in the relocation information so that AddSymbol and
+ * SubtractSymbol can be link edited independent of each other. Many other
+ * platforms only allow a relocatable expression of the form AddSymbol + Offset
+ * to be encoded.
+ *
+ * The LLVMOpInfoCallback() for the TagType value of 1 uses the struct
+ * LLVMOpInfo1. The value of the relocatable expression for the operand,
+ * including any PC adjustment, is passed in to the call back in the Value
+ * field. The symbolic information about the operand is returned using all
+ * the fields of the structure with the Offset of the relocatable expression
+ * returned in the Value field. It is possible that some symbols in the
+ * relocatable expression were assembly temporary symbols, for example
+ * "Ldata - LpicBase + constant", and only the Values of the symbols without
+ * symbol names are present in the relocation information. The VariantKind
+ * type is one of the Target specific #defines below and is used to print
+ * operands like "_foo@GOT", ":lower16:_foo", etc.
+ */
+struct LLVMOpInfoSymbol1 {
+ uint64_t Present; /* 1 if this symbol is present */
+ const char *Name; /* symbol name if not NULL */
+ uint64_t Value; /* symbol value if name is NULL */
+};
+
+struct LLVMOpInfo1 {
+ struct LLVMOpInfoSymbol1 AddSymbol;
+ struct LLVMOpInfoSymbol1 SubtractSymbol;
+ uint64_t Value;
+ uint64_t VariantKind;
+};
+
+/**
+ * The operand VariantKinds for symbolic disassembly.
+ */
+#define LLVMDisassembler_VariantKind_None 0 /* all targets */
+
+/**
+ * The ARM target VariantKinds.
+ */
+#define LLVMDisassembler_VariantKind_ARM_HI16 1 /* :upper16: */
+#define LLVMDisassembler_VariantKind_ARM_LO16 2 /* :lower16: */
+
+/**
+ * The type for the symbol lookup function. This may be called by the
+ * disassembler for things like adding a comment for a PC plus a constant
+ * offset load instruction to use a symbol name instead of a load address value.
+ * It is passed the block information is saved when the disassembler context is
+ * created and the ReferenceValue to look up as a symbol. If no symbol is found
+ * for the ReferenceValue NULL is returned. The ReferenceType of the
+ * instruction is passed indirectly as is the PC of the instruction in
+ * ReferencePC. If the output reference can be determined its type is returned
+ * indirectly in ReferenceType along with ReferenceName if any, or that is set
+ * to NULL.
+ */
+typedef const char *(*LLVMSymbolLookupCallback)(void *DisInfo,
+ uint64_t ReferenceValue,
+ uint64_t *ReferenceType,
+ uint64_t ReferencePC,
+ const char **ReferenceName);
+/**
+ * The reference types on input and output.
+ */
+/* No input reference type or no output reference type. */
+#define LLVMDisassembler_ReferenceType_InOut_None 0
+
+/* The input reference is from a branch instruction. */
+#define LLVMDisassembler_ReferenceType_In_Branch 1
+/* The input reference is from a PC relative load instruction. */
+#define LLVMDisassembler_ReferenceType_In_PCrel_Load 2
+
+/* The output reference is to as symbol stub. */
+#define LLVMDisassembler_ReferenceType_Out_SymbolStub 1
+/* The output reference is to a symbol address in a literal pool. */
+#define LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr 2
+/* The output reference is to a cstring address in a literal pool. */
+#define LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr 3
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* !defined(__cplusplus) */
+
+/**
+ * Create a disassembler for the TripleName. Symbolic disassembly is supported
+ * by passing a block of information in the DisInfo parameter and specifying the
+ * TagType and callback functions as described above. These can all be passed
+ * as NULL. If successful, this returns a disassembler context. If not, it
+ * returns NULL.
+ */
+LLVMDisasmContextRef LLVMCreateDisasm(const char *TripleName, void *DisInfo,
+ int TagType, LLVMOpInfoCallback GetOpInfo,
+ LLVMSymbolLookupCallback SymbolLookUp);
+
+/**
+ * Dispose of a disassembler context.
+ */
+void LLVMDisasmDispose(LLVMDisasmContextRef DC);
+
+/**
+ * Disassemble a single instruction using the disassembler context specified in
+ * the parameter DC. The bytes of the instruction are specified in the
+ * parameter Bytes, and contains at least BytesSize number of bytes. The
+ * instruction is at the address specified by the PC parameter. If a valid
+ * instruction can be disassembled, its string is returned indirectly in
+ * OutString whose size is specified in the parameter OutStringSize. This
+ * function returns the number of bytes in the instruction or zero if there was
+ * no valid instruction.
+ */
+size_t LLVMDisasmInstruction(LLVMDisasmContextRef DC, uint8_t *Bytes,
+ uint64_t BytesSize, uint64_t PC,
+ char *OutString, size_t OutStringSize);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif /* !defined(__cplusplus) */
+
+#endif /* !defined(LLVM_C_DISASSEMBLER_H) */
diff --git a/include/llvm-c/EnhancedDisassembly.h b/include/llvm-c/EnhancedDisassembly.h
new file mode 100644
index 00000000000..71a0d496c02
--- /dev/null
+++ b/include/llvm-c/EnhancedDisassembly.h
@@ -0,0 +1,530 @@
+/*===-- llvm-c/EnhancedDisassembly.h - Disassembler C Interface ---*- C -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to EnhancedDisassembly.so, which *|
+|* implements a disassembler with the ability to extract operand values and *|
+|* individual tokens from assembly instructions. *|
+|* *|
+|* The header declares additional interfaces if the host compiler supports *|
+|* the blocks API. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_ENHANCEDDISASSEMBLY_H
+#define LLVM_C_ENHANCEDDISASSEMBLY_H
+
+#include "llvm/Support/DataTypes.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCEnhancedDisassembly Enhanced Disassembly
+ * @ingroup LLVMC
+ * @deprecated
+ *
+ * This module contains an interface to the Enhanced Disassembly (edis)
+ * library. The edis library is deprecated and will likely disappear in
+ * the near future. You should use the @ref LLVMCDisassembler interface
+ * instead.
+ *
+ * @{
+ */
+
+/*!
+ @typedef EDByteReaderCallback
+ Interface to memory from which instructions may be read.
+ @param byte A pointer whose target should be filled in with the data returned.
+ @param address The address of the byte to be read.
+ @param arg An anonymous argument for client use.
+ @result 0 on success; -1 otherwise.
+ */
+typedef int (*EDByteReaderCallback)(uint8_t *byte, uint64_t address, void *arg);
+
+/*!
+ @typedef EDRegisterReaderCallback
+ Interface to registers from which registers may be read.
+ @param value A pointer whose target should be filled in with the value of the
+ register.
+ @param regID The LLVM register identifier for the register to read.
+ @param arg An anonymous argument for client use.
+ @result 0 if the register could be read; -1 otherwise.
+ */
+typedef int (*EDRegisterReaderCallback)(uint64_t *value, unsigned regID,
+ void* arg);
+
+/*!
+ @typedef EDAssemblySyntax_t
+ An assembly syntax for use in tokenizing instructions.
+ */
+enum {
+/*! @constant kEDAssemblySyntaxX86Intel Intel syntax for i386 and x86_64. */
+ kEDAssemblySyntaxX86Intel = 0,
+/*! @constant kEDAssemblySyntaxX86ATT AT&T syntax for i386 and x86_64. */
+ kEDAssemblySyntaxX86ATT = 1,
+ kEDAssemblySyntaxARMUAL = 2
+};
+typedef unsigned EDAssemblySyntax_t;
+
+/*!
+ @typedef EDDisassemblerRef
+ Encapsulates a disassembler for a single CPU architecture.
+ */
+typedef void *EDDisassemblerRef;
+
+/*!
+ @typedef EDInstRef
+ Encapsulates a single disassembled instruction in one assembly syntax.
+ */
+typedef void *EDInstRef;
+
+/*!
+ @typedef EDTokenRef
+ Encapsulates a token from the disassembly of an instruction.
+ */
+typedef void *EDTokenRef;
+
+/*!
+ @typedef EDOperandRef
+ Encapsulates an operand of an instruction.
+ */
+typedef void *EDOperandRef;
+
+/*!
+ @functiongroup Getting a disassembler
+ */
+
+/*!
+ @function EDGetDisassembler
+ Gets the disassembler for a given target.
+ @param disassembler A pointer whose target will be filled in with the
+ disassembler.
+ @param triple Identifies the target. Example: "x86_64-apple-darwin10"
+ @param syntax The assembly syntax to use when decoding instructions.
+ @result 0 on success; -1 otherwise.
+ */
+int EDGetDisassembler(EDDisassemblerRef *disassembler,
+ const char *triple,
+ EDAssemblySyntax_t syntax);
+
+/*!
+ @functiongroup Generic architectural queries
+ */
+
+/*!
+ @function EDGetRegisterName
+ Gets the human-readable name for a given register.
+ @param regName A pointer whose target will be pointed at the name of the
+ register. The name does not need to be deallocated and will be
+ @param disassembler The disassembler to query for the name.
+ @param regID The register identifier, as returned by EDRegisterTokenValue.
+ @result 0 on success; -1 otherwise.
+ */
+int EDGetRegisterName(const char** regName,
+ EDDisassemblerRef disassembler,
+ unsigned regID);
+
+/*!
+ @function EDRegisterIsStackPointer
+ Determines if a register is one of the platform's stack-pointer registers.
+ @param disassembler The disassembler to query.
+ @param regID The register identifier, as returned by EDRegisterTokenValue.
+ @result 1 if true; 0 otherwise.
+ */
+int EDRegisterIsStackPointer(EDDisassemblerRef disassembler,
+ unsigned regID);
+
+/*!
+ @function EDRegisterIsProgramCounter
+ Determines if a register is one of the platform's stack-pointer registers.
+ @param disassembler The disassembler to query.
+ @param regID The register identifier, as returned by EDRegisterTokenValue.
+ @result 1 if true; 0 otherwise.
+ */
+int EDRegisterIsProgramCounter(EDDisassemblerRef disassembler,
+ unsigned regID);
+
+/*!
+ @functiongroup Creating and querying instructions
+ */
+
+/*!
+ @function EDCreateInst
+ Gets a set of contiguous instructions from a disassembler.
+ @param insts A pointer to an array that will be filled in with the
+ instructions. Must have at least count entries. Entries not filled in will
+ be set to NULL.
+ @param count The maximum number of instructions to fill in.
+ @param disassembler The disassembler to use when decoding the instructions.
+ @param byteReader The function to use when reading the instruction's machine
+ code.
+ @param address The address of the first byte of the instruction.
+ @param arg An anonymous argument to be passed to byteReader.
+ @result The number of instructions read on success; 0 otherwise.
+ */
+unsigned int EDCreateInsts(EDInstRef *insts,
+ unsigned int count,
+ EDDisassemblerRef disassembler,
+ EDByteReaderCallback byteReader,
+ uint64_t address,
+ void *arg);
+
+/*!
+ @function EDReleaseInst
+ Frees the memory for an instruction. The instruction can no longer be accessed
+ after this call.
+ @param inst The instruction to be freed.
+ */
+void EDReleaseInst(EDInstRef inst);
+
+/*!
+ @function EDInstByteSize
+ @param inst The instruction to be queried.
+ @result The number of bytes in the instruction's machine-code representation.
+ */
+int EDInstByteSize(EDInstRef inst);
+
+/*!
+ @function EDGetInstString
+ Gets the disassembled text equivalent of the instruction.
+ @param buf A pointer whose target will be filled in with a pointer to the
+ string. (The string becomes invalid when the instruction is released.)
+ @param inst The instruction to be queried.
+ @result 0 on success; -1 otherwise.
+ */
+int EDGetInstString(const char **buf,
+ EDInstRef inst);
+
+/*!
+ @function EDInstID
+ @param instID A pointer whose target will be filled in with the LLVM identifier
+ for the instruction.
+ @param inst The instruction to be queried.
+ @result 0 on success; -1 otherwise.
+ */
+int EDInstID(unsigned *instID, EDInstRef inst);
+
+/*!
+ @function EDInstIsBranch
+ @param inst The instruction to be queried.
+ @result 1 if the instruction is a branch instruction; 0 if it is some other
+ type of instruction; -1 if there was an error.
+ */
+int EDInstIsBranch(EDInstRef inst);
+
+/*!
+ @function EDInstIsMove
+ @param inst The instruction to be queried.
+ @result 1 if the instruction is a move instruction; 0 if it is some other
+ type of instruction; -1 if there was an error.
+ */
+int EDInstIsMove(EDInstRef inst);
+
+/*!
+ @function EDBranchTargetID
+ @param inst The instruction to be queried.
+ @result The ID of the branch target operand, suitable for use with
+ EDCopyOperand. -1 if no such operand exists.
+ */
+int EDBranchTargetID(EDInstRef inst);
+
+/*!
+ @function EDMoveSourceID
+ @param inst The instruction to be queried.
+ @result The ID of the move source operand, suitable for use with
+ EDCopyOperand. -1 if no such operand exists.
+ */
+int EDMoveSourceID(EDInstRef inst);
+
+/*!
+ @function EDMoveTargetID
+ @param inst The instruction to be queried.
+ @result The ID of the move source operand, suitable for use with
+ EDCopyOperand. -1 if no such operand exists.
+ */
+int EDMoveTargetID(EDInstRef inst);
+
+/*!
+ @functiongroup Creating and querying tokens
+ */
+
+/*!
+ @function EDNumTokens
+ @param inst The instruction to be queried.
+ @result The number of tokens in the instruction, or -1 on error.
+ */
+int EDNumTokens(EDInstRef inst);
+
+/*!
+ @function EDGetToken
+ Retrieves a token from an instruction. The token is valid until the
+ instruction is released.
+ @param token A pointer to be filled in with the token.
+ @param inst The instruction to be queried.
+ @param index The index of the token in the instruction.
+ @result 0 on success; -1 otherwise.
+ */
+int EDGetToken(EDTokenRef *token,
+ EDInstRef inst,
+ int index);
+
+/*!
+ @function EDGetTokenString
+ Gets the disassembled text for a token.
+ @param buf A pointer whose target will be filled in with a pointer to the
+ string. (The string becomes invalid when the token is released.)
+ @param token The token to be queried.
+ @result 0 on success; -1 otherwise.
+ */
+int EDGetTokenString(const char **buf,
+ EDTokenRef token);
+
+/*!
+ @function EDOperandIndexForToken
+ Returns the index of the operand to which a token belongs.
+ @param token The token to be queried.
+ @result The operand index on success; -1 otherwise
+ */
+int EDOperandIndexForToken(EDTokenRef token);
+
+/*!
+ @function EDTokenIsWhitespace
+ @param token The token to be queried.
+ @result 1 if the token is whitespace; 0 if not; -1 on error.
+ */
+int EDTokenIsWhitespace(EDTokenRef token);
+
+/*!
+ @function EDTokenIsPunctuation
+ @param token The token to be queried.
+ @result 1 if the token is punctuation; 0 if not; -1 on error.
+ */
+int EDTokenIsPunctuation(EDTokenRef token);
+
+/*!
+ @function EDTokenIsOpcode
+ @param token The token to be queried.
+ @result 1 if the token is opcode; 0 if not; -1 on error.
+ */
+int EDTokenIsOpcode(EDTokenRef token);
+
+/*!
+ @function EDTokenIsLiteral
+ @param token The token to be queried.
+ @result 1 if the token is a numeric literal; 0 if not; -1 on error.
+ */
+int EDTokenIsLiteral(EDTokenRef token);
+
+/*!
+ @function EDTokenIsRegister
+ @param token The token to be queried.
+ @result 1 if the token identifies a register; 0 if not; -1 on error.
+ */
+int EDTokenIsRegister(EDTokenRef token);
+
+/*!
+ @function EDTokenIsNegativeLiteral
+ @param token The token to be queried.
+ @result 1 if the token is a negative signed literal; 0 if not; -1 on error.
+ */
+int EDTokenIsNegativeLiteral(EDTokenRef token);
+
+/*!
+ @function EDLiteralTokenAbsoluteValue
+ @param value A pointer whose target will be filled in with the absolute value
+ of the literal.
+ @param token The token to be queried.
+ @result 0 on success; -1 otherwise.
+ */
+int EDLiteralTokenAbsoluteValue(uint64_t *value,
+ EDTokenRef token);
+
+/*!
+ @function EDRegisterTokenValue
+ @param registerID A pointer whose target will be filled in with the LLVM
+ register identifier for the token.
+ @param token The token to be queried.
+ @result 0 on success; -1 otherwise.
+ */
+int EDRegisterTokenValue(unsigned *registerID,
+ EDTokenRef token);
+
+/*!
+ @functiongroup Creating and querying operands
+ */
+
+/*!
+ @function EDNumOperands
+ @param inst The instruction to be queried.
+ @result The number of operands in the instruction, or -1 on error.
+ */
+int EDNumOperands(EDInstRef inst);
+
+/*!
+ @function EDGetOperand
+ Retrieves an operand from an instruction. The operand is valid until the
+ instruction is released.
+ @param operand A pointer to be filled in with the operand.
+ @param inst The instruction to be queried.
+ @param index The index of the operand in the instruction.
+ @result 0 on success; -1 otherwise.
+ */
+int EDGetOperand(EDOperandRef *operand,
+ EDInstRef inst,
+ int index);
+
+/*!
+ @function EDOperandIsRegister
+ @param operand The operand to be queried.
+ @result 1 if the operand names a register; 0 if not; -1 on error.
+ */
+int EDOperandIsRegister(EDOperandRef operand);
+
+/*!
+ @function EDOperandIsImmediate
+ @param operand The operand to be queried.
+ @result 1 if the operand specifies an immediate value; 0 if not; -1 on error.
+ */
+int EDOperandIsImmediate(EDOperandRef operand);
+
+/*!
+ @function EDOperandIsMemory
+ @param operand The operand to be queried.
+ @result 1 if the operand specifies a location in memory; 0 if not; -1 on error.
+ */
+int EDOperandIsMemory(EDOperandRef operand);
+
+/*!
+ @function EDRegisterOperandValue
+ @param value A pointer whose target will be filled in with the LLVM register ID
+ of the register named by the operand.
+ @param operand The operand to be queried.
+ @result 0 on success; -1 otherwise.
+ */
+int EDRegisterOperandValue(unsigned *value,
+ EDOperandRef operand);
+
+/*!
+ @function EDImmediateOperandValue
+ @param value A pointer whose target will be filled in with the value of the
+ immediate.
+ @param operand The operand to be queried.
+ @result 0 on success; -1 otherwise.
+ */
+int EDImmediateOperandValue(uint64_t *value,
+ EDOperandRef operand);
+
+/*!
+ @function EDEvaluateOperand
+ Evaluates an operand using a client-supplied register state accessor. Register
+ operands are evaluated by reading the value of the register; immediate operands
+ are evaluated by reporting the immediate value; memory operands are evaluated
+ by computing the target address (with only those relocations applied that were
+ already applied to the original bytes).
+ @param result A pointer whose target is to be filled with the result of
+ evaluating the operand.
+ @param operand The operand to be evaluated.
+ @param regReader The function to use when reading registers from the register
+ state.
+ @param arg An anonymous argument for client use.
+ @result 0 if the operand could be evaluated; -1 otherwise.
+ */
+int EDEvaluateOperand(uint64_t *result,
+ EDOperandRef operand,
+ EDRegisterReaderCallback regReader,
+ void *arg);
+
+#ifdef __BLOCKS__
+
+/*!
+ @typedef EDByteBlock_t
+ Block-based interface to memory from which instructions may be read.
+ @param byte A pointer whose target should be filled in with the data returned.
+ @param address The address of the byte to be read.
+ @result 0 on success; -1 otherwise.
+ */
+typedef int (^EDByteBlock_t)(uint8_t *byte, uint64_t address);
+
+/*!
+ @typedef EDRegisterBlock_t
+ Block-based interface to registers from which registers may be read.
+ @param value A pointer whose target should be filled in with the value of the
+ register.
+ @param regID The LLVM register identifier for the register to read.
+ @result 0 if the register could be read; -1 otherwise.
+ */
+typedef int (^EDRegisterBlock_t)(uint64_t *value, unsigned regID);
+
+/*!
+ @typedef EDTokenVisitor_t
+ Block-based handler for individual tokens.
+ @param token The current token being read.
+ @result 0 to continue; 1 to stop normally; -1 on error.
+ */
+typedef int (^EDTokenVisitor_t)(EDTokenRef token);
+
+/*! @functiongroup Block-based interfaces */
+
+/*!
+ @function EDBlockCreateInsts
+ Gets a set of contiguous instructions from a disassembler, using a block to
+ read memory.
+ @param insts A pointer to an array that will be filled in with the
+ instructions. Must have at least count entries. Entries not filled in will
+ be set to NULL.
+ @param count The maximum number of instructions to fill in.
+ @param disassembler The disassembler to use when decoding the instructions.
+ @param byteBlock The block to use when reading the instruction's machine
+ code.
+ @param address The address of the first byte of the instruction.
+ @result The number of instructions read on success; 0 otherwise.
+ */
+unsigned int EDBlockCreateInsts(EDInstRef *insts,
+ int count,
+ EDDisassemblerRef disassembler,
+ EDByteBlock_t byteBlock,
+ uint64_t address);
+
+/*!
+ @function EDBlockEvaluateOperand
+ Evaluates an operand using a block to read registers.
+ @param result A pointer whose target is to be filled with the result of
+ evaluating the operand.
+ @param operand The operand to be evaluated.
+ @param regBlock The block to use when reading registers from the register
+ state.
+ @result 0 if the operand could be evaluated; -1 otherwise.
+ */
+int EDBlockEvaluateOperand(uint64_t *result,
+ EDOperandRef operand,
+ EDRegisterBlock_t regBlock);
+
+/*!
+ @function EDBlockVisitTokens
+ Visits every token with a visitor.
+ @param inst The instruction with the tokens to be visited.
+ @param visitor The visitor.
+ @result 0 if the visit ended normally; -1 if the visitor encountered an error
+ or there was some other error.
+ */
+int EDBlockVisitTokens(EDInstRef inst,
+ EDTokenVisitor_t visitor);
+
+/**
+ * @}
+ */
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/ExecutionEngine.h b/include/llvm-c/ExecutionEngine.h
new file mode 100644
index 00000000000..cb77bb2e2e2
--- /dev/null
+++ b/include/llvm-c/ExecutionEngine.h
@@ -0,0 +1,163 @@
+/*===-- llvm-c/ExecutionEngine.h - ExecutionEngine Lib C Iface --*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to libLLVMExecutionEngine.o, which *|
+|* implements various analyses of the LLVM IR. *|
+|* *|
+|* Many exotic languages can interoperate with C code but have a harder time *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_EXECUTIONENGINE_H
+#define LLVM_C_EXECUTIONENGINE_H
+
+#include "llvm-c/Core.h"
+#include "llvm-c/Target.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCExecutionEngine Execution Engine
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+void LLVMLinkInJIT(void);
+void LLVMLinkInInterpreter(void);
+
+typedef struct LLVMOpaqueGenericValue *LLVMGenericValueRef;
+typedef struct LLVMOpaqueExecutionEngine *LLVMExecutionEngineRef;
+
+/*===-- Operations on generic values --------------------------------------===*/
+
+LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
+ unsigned long long N,
+ LLVMBool IsSigned);
+
+LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P);
+
+LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef Ty, double N);
+
+unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef);
+
+unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenVal,
+ LLVMBool IsSigned);
+
+void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal);
+
+double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal);
+
+void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal);
+
+/*===-- Operations on execution engines -----------------------------------===*/
+
+LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
+ LLVMModuleRef M,
+ char **OutError);
+
+LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
+ LLVMModuleRef M,
+ char **OutError);
+
+LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
+ LLVMModuleRef M,
+ unsigned OptLevel,
+ char **OutError);
+
+/** Deprecated: Use LLVMCreateExecutionEngineForModule instead. */
+LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
+ LLVMModuleProviderRef MP,
+ char **OutError);
+
+/** Deprecated: Use LLVMCreateInterpreterForModule instead. */
+LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
+ LLVMModuleProviderRef MP,
+ char **OutError);
+
+/** Deprecated: Use LLVMCreateJITCompilerForModule instead. */
+LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
+ LLVMModuleProviderRef MP,
+ unsigned OptLevel,
+ char **OutError);
+
+void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE);
+
+void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE);
+
+void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE);
+
+int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
+ unsigned ArgC, const char * const *ArgV,
+ const char * const *EnvP);
+
+LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
+ unsigned NumArgs,
+ LLVMGenericValueRef *Args);
+
+void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F);
+
+void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M);
+
+/** Deprecated: Use LLVMAddModule instead. */
+void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP);
+
+LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
+ LLVMModuleRef *OutMod, char **OutError);
+
+/** Deprecated: Use LLVMRemoveModule instead. */
+LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
+ LLVMModuleProviderRef MP,
+ LLVMModuleRef *OutMod, char **OutError);
+
+LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
+ LLVMValueRef *OutFn);
+
+void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE, LLVMValueRef Fn);
+
+LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE);
+
+void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
+ void* Addr);
+
+void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+
+namespace llvm {
+ struct GenericValue;
+ class ExecutionEngine;
+
+ #define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \
+ inline ty *unwrap(ref P) { \
+ return reinterpret_cast<ty*>(P); \
+ } \
+ \
+ inline ref wrap(const ty *P) { \
+ return reinterpret_cast<ref>(const_cast<ty*>(P)); \
+ }
+
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef )
+ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
+
+ #undef DEFINE_SIMPLE_CONVERSION_FUNCTIONS
+}
+
+#endif /* defined(__cplusplus) */
+
+#endif
diff --git a/include/llvm-c/Initialization.h b/include/llvm-c/Initialization.h
new file mode 100644
index 00000000000..cb3ab9e3f39
--- /dev/null
+++ b/include/llvm-c/Initialization.h
@@ -0,0 +1,54 @@
+/*===-- llvm-c/Initialization.h - Initialization C Interface ------*- C -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to LLVM initialization routines, *|
+|* which must be called before you can use the functionality provided by *|
+|* the corresponding LLVM library. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_INITIALIZEPASSES_H
+#define LLVM_C_INITIALIZEPASSES_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCInitialization Initialization Routines
+ * @ingroup LLVMC
+ *
+ * This module contains routines used to initialize the LLVM system.
+ *
+ * @{
+ */
+
+void LLVMInitializeCore(LLVMPassRegistryRef R);
+void LLVMInitializeTransformUtils(LLVMPassRegistryRef R);
+void LLVMInitializeScalarOpts(LLVMPassRegistryRef R);
+void LLVMInitializeVectorization(LLVMPassRegistryRef R);
+void LLVMInitializeInstCombine(LLVMPassRegistryRef R);
+void LLVMInitializeIPO(LLVMPassRegistryRef R);
+void LLVMInitializeInstrumentation(LLVMPassRegistryRef R);
+void LLVMInitializeAnalysis(LLVMPassRegistryRef R);
+void LLVMInitializeIPA(LLVMPassRegistryRef R);
+void LLVMInitializeCodeGen(LLVMPassRegistryRef R);
+void LLVMInitializeTarget(LLVMPassRegistryRef R);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/LinkTimeOptimizer.h b/include/llvm-c/LinkTimeOptimizer.h
new file mode 100644
index 00000000000..5338d3fc4c8
--- /dev/null
+++ b/include/llvm-c/LinkTimeOptimizer.h
@@ -0,0 +1,69 @@
+//===-- llvm/LinkTimeOptimizer.h - LTO Public C Interface -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header provides a C API to use the LLVM link time optimization
+// library. This is intended to be used by linkers which are C-only in
+// their implementation for performing LTO.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef __LTO_CAPI_H__
+#define __LTO_CAPI_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCLinkTimeOptimizer Link Time Optimization
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+ /// This provides a dummy type for pointers to the LTO object.
+ typedef void* llvm_lto_t;
+
+ /// This provides a C-visible enumerator to manage status codes.
+ /// This should map exactly onto the C++ enumerator LTOStatus.
+ typedef enum llvm_lto_status {
+ LLVM_LTO_UNKNOWN,
+ LLVM_LTO_OPT_SUCCESS,
+ LLVM_LTO_READ_SUCCESS,
+ LLVM_LTO_READ_FAILURE,
+ LLVM_LTO_WRITE_FAILURE,
+ LLVM_LTO_NO_TARGET,
+ LLVM_LTO_NO_WORK,
+ LLVM_LTO_MODULE_MERGE_FAILURE,
+ LLVM_LTO_ASM_FAILURE,
+
+ // Added C-specific error codes
+ LLVM_LTO_NULL_OBJECT
+ } llvm_lto_status_t;
+
+ /// This provides C interface to initialize link time optimizer. This allows
+ /// linker to use dlopen() interface to dynamically load LinkTimeOptimizer.
+ /// extern "C" helps, because dlopen() interface uses name to find the symbol.
+ extern llvm_lto_t llvm_create_optimizer(void);
+ extern void llvm_destroy_optimizer(llvm_lto_t lto);
+
+ extern llvm_lto_status_t llvm_read_object_file
+ (llvm_lto_t lto, const char* input_filename);
+ extern llvm_lto_status_t llvm_optimize_modules
+ (llvm_lto_t lto, const char* output_filename);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/Linker.h b/include/llvm-c/Linker.h
new file mode 100644
index 00000000000..9f337cfba47
--- /dev/null
+++ b/include/llvm-c/Linker.h
@@ -0,0 +1,42 @@
+/*===-- llvm-c/Linker.h - Module Linker C Interface -------------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file defines the C interface to the module/file/archive linker. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_LINKER_H
+#define LLVM_C_LINKER_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+typedef enum {
+ LLVMLinkerDestroySource = 0, /* Allow source module to be destroyed. */
+ LLVMLinkerPreserveSource = 1 /* Preserve the source module. */
+} LLVMLinkerMode;
+
+
+/* Links the source module into the destination module, taking ownership
+ * of the source module away from the caller. Optionally returns a
+ * human-readable description of any errors that occurred in linking.
+ * OutMessage must be disposed with LLVMDisposeMessage. The return value
+ * is true if an error occurred, false otherwise. */
+LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
+ LLVMLinkerMode Mode, char **OutMessage);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/Object.h b/include/llvm-c/Object.h
new file mode 100644
index 00000000000..e2dad62b4e0
--- /dev/null
+++ b/include/llvm-c/Object.h
@@ -0,0 +1,149 @@
+/*===-- llvm-c/Object.h - Object Lib C Iface --------------------*- C++ -*-===*/
+/* */
+/* The LLVM Compiler Infrastructure */
+/* */
+/* This file is distributed under the University of Illinois Open Source */
+/* License. See LICENSE.TXT for details. */
+/* */
+/*===----------------------------------------------------------------------===*/
+/* */
+/* This header declares the C interface to libLLVMObject.a, which */
+/* implements object file reading and writing. */
+/* */
+/* Many exotic languages can interoperate with C code but have a harder time */
+/* with C++ due to name mangling. So in addition to C, this interface enables */
+/* tools written in such languages. */
+/* */
+/*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_OBJECT_H
+#define LLVM_C_OBJECT_H
+
+#include "llvm-c/Core.h"
+#include "llvm/Config/llvm-config.h"
+
+#ifdef __cplusplus
+#include "llvm/Object/ObjectFile.h"
+
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCObject Object file reading and writing
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+// Opaque type wrappers
+typedef struct LLVMOpaqueObjectFile *LLVMObjectFileRef;
+typedef struct LLVMOpaqueSectionIterator *LLVMSectionIteratorRef;
+typedef struct LLVMOpaqueSymbolIterator *LLVMSymbolIteratorRef;
+typedef struct LLVMOpaqueRelocationIterator *LLVMRelocationIteratorRef;
+
+// ObjectFile creation
+LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf);
+void LLVMDisposeObjectFile(LLVMObjectFileRef ObjectFile);
+
+// ObjectFile Section iterators
+LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef ObjectFile);
+void LLVMDisposeSectionIterator(LLVMSectionIteratorRef SI);
+LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef ObjectFile,
+ LLVMSectionIteratorRef SI);
+void LLVMMoveToNextSection(LLVMSectionIteratorRef SI);
+void LLVMMoveToContainingSection(LLVMSectionIteratorRef Sect,
+ LLVMSymbolIteratorRef Sym);
+
+// ObjectFile Symbol iterators
+LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef ObjectFile);
+void LLVMDisposeSymbolIterator(LLVMSymbolIteratorRef SI);
+LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef ObjectFile,
+ LLVMSymbolIteratorRef SI);
+void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI);
+
+// SectionRef accessors
+const char *LLVMGetSectionName(LLVMSectionIteratorRef SI);
+uint64_t LLVMGetSectionSize(LLVMSectionIteratorRef SI);
+const char *LLVMGetSectionContents(LLVMSectionIteratorRef SI);
+uint64_t LLVMGetSectionAddress(LLVMSectionIteratorRef SI);
+LLVMBool LLVMGetSectionContainsSymbol(LLVMSectionIteratorRef SI,
+ LLVMSymbolIteratorRef Sym);
+
+// Section Relocation iterators
+LLVMRelocationIteratorRef LLVMGetRelocations(LLVMSectionIteratorRef Section);
+void LLVMDisposeRelocationIterator(LLVMRelocationIteratorRef RI);
+LLVMBool LLVMIsRelocationIteratorAtEnd(LLVMSectionIteratorRef Section,
+ LLVMRelocationIteratorRef RI);
+void LLVMMoveToNextRelocation(LLVMRelocationIteratorRef RI);
+
+
+// SymbolRef accessors
+const char *LLVMGetSymbolName(LLVMSymbolIteratorRef SI);
+uint64_t LLVMGetSymbolAddress(LLVMSymbolIteratorRef SI);
+uint64_t LLVMGetSymbolFileOffset(LLVMSymbolIteratorRef SI);
+uint64_t LLVMGetSymbolSize(LLVMSymbolIteratorRef SI);
+
+// RelocationRef accessors
+uint64_t LLVMGetRelocationAddress(LLVMRelocationIteratorRef RI);
+uint64_t LLVMGetRelocationOffset(LLVMRelocationIteratorRef RI);
+LLVMSymbolIteratorRef LLVMGetRelocationSymbol(LLVMRelocationIteratorRef RI);
+uint64_t LLVMGetRelocationType(LLVMRelocationIteratorRef RI);
+// NOTE: Caller takes ownership of returned string of the two
+// following functions.
+const char *LLVMGetRelocationTypeName(LLVMRelocationIteratorRef RI);
+const char *LLVMGetRelocationValueString(LLVMRelocationIteratorRef RI);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+
+namespace llvm {
+ namespace object {
+ inline ObjectFile *unwrap(LLVMObjectFileRef OF) {
+ return reinterpret_cast<ObjectFile*>(OF);
+ }
+
+ inline LLVMObjectFileRef wrap(const ObjectFile *OF) {
+ return reinterpret_cast<LLVMObjectFileRef>(const_cast<ObjectFile*>(OF));
+ }
+
+ inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
+ return reinterpret_cast<section_iterator*>(SI);
+ }
+
+ inline LLVMSectionIteratorRef
+ wrap(const section_iterator *SI) {
+ return reinterpret_cast<LLVMSectionIteratorRef>
+ (const_cast<section_iterator*>(SI));
+ }
+
+ inline symbol_iterator *unwrap(LLVMSymbolIteratorRef SI) {
+ return reinterpret_cast<symbol_iterator*>(SI);
+ }
+
+ inline LLVMSymbolIteratorRef
+ wrap(const symbol_iterator *SI) {
+ return reinterpret_cast<LLVMSymbolIteratorRef>
+ (const_cast<symbol_iterator*>(SI));
+ }
+
+ inline relocation_iterator *unwrap(LLVMRelocationIteratorRef SI) {
+ return reinterpret_cast<relocation_iterator*>(SI);
+ }
+
+ inline LLVMRelocationIteratorRef
+ wrap(const relocation_iterator *SI) {
+ return reinterpret_cast<LLVMRelocationIteratorRef>
+ (const_cast<relocation_iterator*>(SI));
+ }
+
+ }
+}
+
+#endif /* defined(__cplusplus) */
+
+#endif
+
diff --git a/include/llvm-c/Target.h b/include/llvm-c/Target.h
new file mode 100644
index 00000000000..89150401ffe
--- /dev/null
+++ b/include/llvm-c/Target.h
@@ -0,0 +1,253 @@
+/*===-- llvm-c/Target.h - Target Lib C Iface --------------------*- C++ -*-===*/
+/* */
+/* The LLVM Compiler Infrastructure */
+/* */
+/* This file is distributed under the University of Illinois Open Source */
+/* License. See LICENSE.TXT for details. */
+/* */
+/*===----------------------------------------------------------------------===*/
+/* */
+/* This header declares the C interface to libLLVMTarget.a, which */
+/* implements target information. */
+/* */
+/* Many exotic languages can interoperate with C code but have a harder time */
+/* with C++ due to name mangling. So in addition to C, this interface enables */
+/* tools written in such languages. */
+/* */
+/*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_TARGET_H
+#define LLVM_C_TARGET_H
+
+#include "llvm-c/Core.h"
+#include "llvm/Config/llvm-config.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCTarget Target information
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+enum LLVMByteOrdering { LLVMBigEndian, LLVMLittleEndian };
+
+typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
+typedef struct LLVMOpaqueTargetLibraryInfotData *LLVMTargetLibraryInfoRef;
+typedef struct LLVMStructLayout *LLVMStructLayoutRef;
+
+/* Declare all of the target-initialization functions that are available. */
+#define LLVM_TARGET(TargetName) \
+ void LLVMInitialize##TargetName##TargetInfo(void);
+#include "llvm/Config/Targets.def"
+#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
+
+#define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##Target(void);
+#include "llvm/Config/Targets.def"
+#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
+
+#define LLVM_TARGET(TargetName) \
+ void LLVMInitialize##TargetName##TargetMC(void);
+#include "llvm/Config/Targets.def"
+#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
+
+/* Declare all of the available assembly printer initialization functions. */
+#define LLVM_ASM_PRINTER(TargetName) \
+ void LLVMInitialize##TargetName##AsmPrinter(void);
+#include "llvm/Config/AsmPrinters.def"
+#undef LLVM_ASM_PRINTER /* Explicit undef to make SWIG happier */
+
+/* Declare all of the available assembly parser initialization functions. */
+#define LLVM_ASM_PARSER(TargetName) \
+ void LLVMInitialize##TargetName##AsmParser(void);
+#include "llvm/Config/AsmParsers.def"
+#undef LLVM_ASM_PARSER /* Explicit undef to make SWIG happier */
+
+/* Declare all of the available disassembler initialization functions. */
+#define LLVM_DISASSEMBLER(TargetName) \
+ void LLVMInitialize##TargetName##Disassembler(void);
+#include "llvm/Config/Disassemblers.def"
+#undef LLVM_DISASSEMBLER /* Explicit undef to make SWIG happier */
+
+/** LLVMInitializeAllTargetInfos - The main program should call this function if
+ it wants access to all available targets that LLVM is configured to
+ support. */
+static inline void LLVMInitializeAllTargetInfos(void) {
+#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo();
+#include "llvm/Config/Targets.def"
+#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
+}
+
+/** LLVMInitializeAllTargets - The main program should call this function if it
+ wants to link in all available targets that LLVM is configured to
+ support. */
+static inline void LLVMInitializeAllTargets(void) {
+#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target();
+#include "llvm/Config/Targets.def"
+#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
+}
+
+/** LLVMInitializeAllTargetMCs - The main program should call this function if
+ it wants access to all available target MC that LLVM is configured to
+ support. */
+static inline void LLVMInitializeAllTargetMCs(void) {
+#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC();
+#include "llvm/Config/Targets.def"
+#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
+}
+
+/** LLVMInitializeAllAsmPrinters - The main program should call this function if
+ it wants all asm printers that LLVM is configured to support, to make them
+ available via the TargetRegistry. */
+static inline void LLVMInitializeAllAsmPrinters(void) {
+#define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinter();
+#include "llvm/Config/AsmPrinters.def"
+#undef LLVM_ASM_PRINTER /* Explicit undef to make SWIG happier */
+}
+
+/** LLVMInitializeAllAsmParsers - The main program should call this function if
+ it wants all asm parsers that LLVM is configured to support, to make them
+ available via the TargetRegistry. */
+static inline void LLVMInitializeAllAsmParsers(void) {
+#define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser();
+#include "llvm/Config/AsmParsers.def"
+#undef LLVM_ASM_PARSER /* Explicit undef to make SWIG happier */
+}
+
+/** LLVMInitializeAllDisassemblers - The main program should call this function
+ if it wants all disassemblers that LLVM is configured to support, to make
+ them available via the TargetRegistry. */
+static inline void LLVMInitializeAllDisassemblers(void) {
+#define LLVM_DISASSEMBLER(TargetName) \
+ LLVMInitialize##TargetName##Disassembler();
+#include "llvm/Config/Disassemblers.def"
+#undef LLVM_DISASSEMBLER /* Explicit undef to make SWIG happier */
+}
+
+/** LLVMInitializeNativeTarget - The main program should call this function to
+ initialize the native target corresponding to the host. This is useful
+ for JIT applications to ensure that the target gets linked in correctly. */
+static inline LLVMBool LLVMInitializeNativeTarget(void) {
+ /* If we have a native target, initialize it to ensure it is linked in. */
+#ifdef LLVM_NATIVE_TARGET
+ LLVM_NATIVE_TARGETINFO();
+ LLVM_NATIVE_TARGET();
+ LLVM_NATIVE_TARGETMC();
+ return 0;
+#else
+ return 1;
+#endif
+}
+
+/*===-- Target Data -------------------------------------------------------===*/
+
+/** Creates target data from a target layout string.
+ See the constructor llvm::TargetData::TargetData. */
+LLVMTargetDataRef LLVMCreateTargetData(const char *StringRep);
+
+/** Adds target data information to a pass manager. This does not take ownership
+ of the target data.
+ See the method llvm::PassManagerBase::add. */
+void LLVMAddTargetData(LLVMTargetDataRef, LLVMPassManagerRef);
+
+/** Adds target library information to a pass manager. This does not take
+ ownership of the target library info.
+ See the method llvm::PassManagerBase::add. */
+void LLVMAddTargetLibraryInfo(LLVMTargetLibraryInfoRef, LLVMPassManagerRef);
+
+/** Converts target data to a target layout string. The string must be disposed
+ with LLVMDisposeMessage.
+ See the constructor llvm::TargetData::TargetData. */
+char *LLVMCopyStringRepOfTargetData(LLVMTargetDataRef);
+
+/** Returns the byte order of a target, either LLVMBigEndian or
+ LLVMLittleEndian.
+ See the method llvm::TargetData::isLittleEndian. */
+enum LLVMByteOrdering LLVMByteOrder(LLVMTargetDataRef);
+
+/** Returns the pointer size in bytes for a target.
+ See the method llvm::TargetData::getPointerSize. */
+unsigned LLVMPointerSize(LLVMTargetDataRef);
+
+/** Returns the integer type that is the same size as a pointer on a target.
+ See the method llvm::TargetData::getIntPtrType. */
+LLVMTypeRef LLVMIntPtrType(LLVMTargetDataRef);
+
+/** Computes the size of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeSizeInBits. */
+unsigned long long LLVMSizeOfTypeInBits(LLVMTargetDataRef, LLVMTypeRef);
+
+/** Computes the storage size of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeStoreSize. */
+unsigned long long LLVMStoreSizeOfType(LLVMTargetDataRef, LLVMTypeRef);
+
+/** Computes the ABI size of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeAllocSize. */
+unsigned long long LLVMABISizeOfType(LLVMTargetDataRef, LLVMTypeRef);
+
+/** Computes the ABI alignment of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeABISize. */
+unsigned LLVMABIAlignmentOfType(LLVMTargetDataRef, LLVMTypeRef);
+
+/** Computes the call frame alignment of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeABISize. */
+unsigned LLVMCallFrameAlignmentOfType(LLVMTargetDataRef, LLVMTypeRef);
+
+/** Computes the preferred alignment of a type in bytes for a target.
+ See the method llvm::TargetData::getTypeABISize. */
+unsigned LLVMPreferredAlignmentOfType(LLVMTargetDataRef, LLVMTypeRef);
+
+/** Computes the preferred alignment of a global variable in bytes for a target.
+ See the method llvm::TargetData::getPreferredAlignment. */
+unsigned LLVMPreferredAlignmentOfGlobal(LLVMTargetDataRef,
+ LLVMValueRef GlobalVar);
+
+/** Computes the structure element that contains the byte offset for a target.
+ See the method llvm::StructLayout::getElementContainingOffset. */
+unsigned LLVMElementAtOffset(LLVMTargetDataRef, LLVMTypeRef StructTy,
+ unsigned long long Offset);
+
+/** Computes the byte offset of the indexed struct element for a target.
+ See the method llvm::StructLayout::getElementContainingOffset. */
+unsigned long long LLVMOffsetOfElement(LLVMTargetDataRef, LLVMTypeRef StructTy,
+ unsigned Element);
+
+/** Deallocates a TargetData.
+ See the destructor llvm::TargetData::~TargetData. */
+void LLVMDisposeTargetData(LLVMTargetDataRef);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+
+namespace llvm {
+ class TargetData;
+ class TargetLibraryInfo;
+
+ inline TargetData *unwrap(LLVMTargetDataRef P) {
+ return reinterpret_cast<TargetData*>(P);
+ }
+
+ inline LLVMTargetDataRef wrap(const TargetData *P) {
+ return reinterpret_cast<LLVMTargetDataRef>(const_cast<TargetData*>(P));
+ }
+
+ inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
+ return reinterpret_cast<TargetLibraryInfo*>(P);
+ }
+
+ inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
+ TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
+ return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
+ }
+}
+
+#endif /* defined(__cplusplus) */
+
+#endif
diff --git a/include/llvm-c/TargetMachine.h b/include/llvm-c/TargetMachine.h
new file mode 100644
index 00000000000..0d35d73a11d
--- /dev/null
+++ b/include/llvm-c/TargetMachine.h
@@ -0,0 +1,142 @@
+/*===-- llvm-c/TargetMachine.h - Target Machine Library C Interface - C++ -*-=*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to the Target and TargetMachine *|
+|* classes, which can be used to generate assembly or object files. *|
+|* *|
+|* Many exotic languages can interoperate with C code but have a harder time *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_TARGETMACHINE_H
+#define LLVM_C_TARGETMACHINE_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+typedef struct LLVMTargetMachine *LLVMTargetMachineRef;
+typedef struct LLVMTarget *LLVMTargetRef;
+
+typedef enum {
+ LLVMCodeGenLevelNone,
+ LLVMCodeGenLevelLess,
+ LLVMCodeGenLevelDefault,
+ LLVMCodeGenLevelAggressive
+} LLVMCodeGenOptLevel;
+
+typedef enum {
+ LLVMRelocDefault,
+ LLVMRelocStatic,
+ LLVMRelocPIC,
+ LLVMRelocDynamicNoPic
+} LLVMRelocMode;
+
+typedef enum {
+ LLVMCodeModelDefault,
+ LLVMCodeModelJITDefault,
+ LLVMCodeModelSmall,
+ LLVMCodeModelKernel,
+ LLVMCodeModelMedium,
+ LLVMCodeModelLarge
+} LLVMCodeModel;
+
+typedef enum {
+ LLVMAssemblyFile,
+ LLVMObjectFile
+} LLVMCodeGenFileType;
+
+/** Returns the first llvm::Target in the registered targets list. */
+LLVMTargetRef LLVMGetFirstTarget();
+/** Returns the next llvm::Target given a previous one (or null if there's none) */
+LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T);
+
+/*===-- Target ------------------------------------------------------------===*/
+/** Returns the name of a target. See llvm::Target::getName */
+const char *LLVMGetTargetName(LLVMTargetRef T);
+
+/** Returns the description of a target. See llvm::Target::getDescription */
+const char *LLVMGetTargetDescription(LLVMTargetRef T);
+
+/** Returns if the target has a JIT */
+LLVMBool LLVMTargetHasJIT(LLVMTargetRef T);
+
+/** Returns if the target has a TargetMachine associated */
+LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T);
+
+/** Returns if the target as an ASM backend (required for emitting output) */
+LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T);
+
+/*===-- Target Machine ----------------------------------------------------===*/
+/** Creates a new llvm::TargetMachine. See llvm::Target::createTargetMachine */
+LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T, char *Triple,
+ char *CPU, char *Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc,
+ LLVMCodeModel CodeModel);
+
+/** Dispose the LLVMTargetMachineRef instance generated by
+ LLVMCreateTargetMachine. */
+void LLVMDisposeTargetMachine(LLVMTargetMachineRef T);
+
+/** Returns the Target used in a TargetMachine */
+LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T);
+
+/** Returns the triple used creating this target machine. See
+ llvm::TargetMachine::getTriple. The result needs to be disposed with
+ LLVMDisposeMessage. */
+char *LLVMGetTargetMachineTriple(LLVMTargetMachineRef T);
+
+/** Returns the cpu used creating this target machine. See
+ llvm::TargetMachine::getCPU. The result needs to be disposed with
+ LLVMDisposeMessage. */
+char *LLVMGetTargetMachineCPU(LLVMTargetMachineRef T);
+
+/** Returns the feature string used creating this target machine. See
+ llvm::TargetMachine::getFeatureString. The result needs to be disposed with
+ LLVMDisposeMessage. */
+char *LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T);
+
+/** Returns the llvm::TargetData used for this llvm:TargetMachine. */
+LLVMTargetDataRef LLVMGetTargetMachineData(LLVMTargetMachineRef T);
+
+/** Emits an asm or object file for the given module to the filename. This
+ wraps several c++ only classes (among them a file stream). Returns any
+ error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */
+LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
+ char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage);
+
+
+
+
+#ifdef __cplusplus
+}
+
+namespace llvm {
+ class TargetMachine;
+ class Target;
+
+ inline TargetMachine *unwrap(LLVMTargetMachineRef P) {
+ return reinterpret_cast<TargetMachine*>(P);
+ }
+ inline Target *unwrap(LLVMTargetRef P) {
+ return reinterpret_cast<Target*>(P);
+ }
+ inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
+ return reinterpret_cast<LLVMTargetMachineRef>(
+ const_cast<TargetMachine*>(P));
+ }
+ inline LLVMTargetRef wrap(const Target * P) {
+ return reinterpret_cast<LLVMTargetRef>(const_cast<Target*>(P));
+ }
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/Transforms/IPO.h b/include/llvm-c/Transforms/IPO.h
new file mode 100644
index 00000000000..448078012ea
--- /dev/null
+++ b/include/llvm-c/Transforms/IPO.h
@@ -0,0 +1,81 @@
+/*===-- IPO.h - Interprocedural Transformations C Interface -----*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to libLLVMIPO.a, which implements *|
+|* various interprocedural transformations of the LLVM IR. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_TRANSFORMS_IPO_H
+#define LLVM_C_TRANSFORMS_IPO_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCTransformsIPO Interprocedural transformations
+ * @ingroup LLVMCTransforms
+ *
+ * @{
+ */
+
+/** See llvm::createArgumentPromotionPass function. */
+void LLVMAddArgumentPromotionPass(LLVMPassManagerRef PM);
+
+/** See llvm::createConstantMergePass function. */
+void LLVMAddConstantMergePass(LLVMPassManagerRef PM);
+
+/** See llvm::createDeadArgEliminationPass function. */
+void LLVMAddDeadArgEliminationPass(LLVMPassManagerRef PM);
+
+/** See llvm::createFunctionAttrsPass function. */
+void LLVMAddFunctionAttrsPass(LLVMPassManagerRef PM);
+
+/** See llvm::createFunctionInliningPass function. */
+void LLVMAddFunctionInliningPass(LLVMPassManagerRef PM);
+
+/** See llvm::createAlwaysInlinerPass function. */
+void LLVMAddAlwaysInlinerPass(LLVMPassManagerRef PM);
+
+/** See llvm::createGlobalDCEPass function. */
+void LLVMAddGlobalDCEPass(LLVMPassManagerRef PM);
+
+/** See llvm::createGlobalOptimizerPass function. */
+void LLVMAddGlobalOptimizerPass(LLVMPassManagerRef PM);
+
+/** See llvm::createIPConstantPropagationPass function. */
+void LLVMAddIPConstantPropagationPass(LLVMPassManagerRef PM);
+
+/** See llvm::createPruneEHPass function. */
+void LLVMAddPruneEHPass(LLVMPassManagerRef PM);
+
+/** See llvm::createIPSCCPPass function. */
+void LLVMAddIPSCCPPass(LLVMPassManagerRef PM);
+
+/** See llvm::createInternalizePass function. */
+void LLVMAddInternalizePass(LLVMPassManagerRef, unsigned AllButMain);
+
+/** See llvm::createStripDeadPrototypesPass function. */
+void LLVMAddStripDeadPrototypesPass(LLVMPassManagerRef PM);
+
+/** See llvm::createStripSymbolsPass function. */
+void LLVMAddStripSymbolsPass(LLVMPassManagerRef PM);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif /* defined(__cplusplus) */
+
+#endif
diff --git a/include/llvm-c/Transforms/PassManagerBuilder.h b/include/llvm-c/Transforms/PassManagerBuilder.h
new file mode 100644
index 00000000000..cee6e5a0ee0
--- /dev/null
+++ b/include/llvm-c/Transforms/PassManagerBuilder.h
@@ -0,0 +1,101 @@
+/*===-- llvm-c/Transform/PassManagerBuilder.h - PMB C Interface ---*- C -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to the PassManagerBuilder class. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_PASSMANAGERBUILDER
+#define LLVM_C_PASSMANAGERBUILDER
+
+#include "llvm-c/Core.h"
+
+typedef struct LLVMOpaquePassManagerBuilder *LLVMPassManagerBuilderRef;
+
+#ifdef __cplusplus
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCTransformsPassManagerBuilder Pass manager builder
+ * @ingroup LLVMCTransforms
+ *
+ * @{
+ */
+
+/** See llvm::PassManagerBuilder. */
+LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void);
+void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB);
+
+/** See llvm::PassManagerBuilder::OptLevel. */
+void
+LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
+ unsigned OptLevel);
+
+/** See llvm::PassManagerBuilder::SizeLevel. */
+void
+LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
+ unsigned SizeLevel);
+
+/** See llvm::PassManagerBuilder::DisableUnitAtATime. */
+void
+LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
+ LLVMBool Value);
+
+/** See llvm::PassManagerBuilder::DisableUnrollLoops. */
+void
+LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
+ LLVMBool Value);
+
+/** See llvm::PassManagerBuilder::DisableSimplifyLibCalls */
+void
+LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
+ LLVMBool Value);
+
+/** See llvm::PassManagerBuilder::Inliner. */
+void
+LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
+ unsigned Threshold);
+
+/** See llvm::PassManagerBuilder::populateFunctionPassManager. */
+void
+LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
+ LLVMPassManagerRef PM);
+
+/** See llvm::PassManagerBuilder::populateModulePassManager. */
+void
+LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
+ LLVMPassManagerRef PM);
+
+/** See llvm::PassManagerBuilder::populateLTOPassManager. */
+void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
+ LLVMPassManagerRef PM,
+ bool Internalize,
+ bool RunInliner);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+
+namespace llvm {
+ inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
+ return reinterpret_cast<PassManagerBuilder*>(P);
+ }
+
+ inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
+ return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
+ }
+}
+#endif
+
+#endif
diff --git a/include/llvm-c/Transforms/Scalar.h b/include/llvm-c/Transforms/Scalar.h
new file mode 100644
index 00000000000..a2c4d6116f0
--- /dev/null
+++ b/include/llvm-c/Transforms/Scalar.h
@@ -0,0 +1,134 @@
+/*===-- Scalar.h - Scalar Transformation Library C Interface ----*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to libLLVMScalarOpts.a, which *|
+|* implements various scalar transformations of the LLVM IR. *|
+|* *|
+|* Many exotic languages can interoperate with C code but have a harder time *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_TRANSFORMS_SCALAR_H
+#define LLVM_C_TRANSFORMS_SCALAR_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCTransformsScalar Scalar transformations
+ * @ingroup LLVMCTransforms
+ *
+ * @{
+ */
+
+/** See llvm::createAggressiveDCEPass function. */
+void LLVMAddAggressiveDCEPass(LLVMPassManagerRef PM);
+
+/** See llvm::createCFGSimplificationPass function. */
+void LLVMAddCFGSimplificationPass(LLVMPassManagerRef PM);
+
+/** See llvm::createDeadStoreEliminationPass function. */
+void LLVMAddDeadStoreEliminationPass(LLVMPassManagerRef PM);
+
+/** See llvm::createGVNPass function. */
+void LLVMAddGVNPass(LLVMPassManagerRef PM);
+
+/** See llvm::createIndVarSimplifyPass function. */
+void LLVMAddIndVarSimplifyPass(LLVMPassManagerRef PM);
+
+/** See llvm::createInstructionCombiningPass function. */
+void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM);
+
+/** See llvm::createJumpThreadingPass function. */
+void LLVMAddJumpThreadingPass(LLVMPassManagerRef PM);
+
+/** See llvm::createLICMPass function. */
+void LLVMAddLICMPass(LLVMPassManagerRef PM);
+
+/** See llvm::createLoopDeletionPass function. */
+void LLVMAddLoopDeletionPass(LLVMPassManagerRef PM);
+
+/** See llvm::createLoopIdiomPass function */
+void LLVMAddLoopIdiomPass(LLVMPassManagerRef PM);
+
+/** See llvm::createLoopRotatePass function. */
+void LLVMAddLoopRotatePass(LLVMPassManagerRef PM);
+
+/** See llvm::createLoopUnrollPass function. */
+void LLVMAddLoopUnrollPass(LLVMPassManagerRef PM);
+
+/** See llvm::createLoopUnswitchPass function. */
+void LLVMAddLoopUnswitchPass(LLVMPassManagerRef PM);
+
+/** See llvm::createMemCpyOptPass function. */
+void LLVMAddMemCpyOptPass(LLVMPassManagerRef PM);
+
+/** See llvm::createPromoteMemoryToRegisterPass function. */
+void LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM);
+
+/** See llvm::createReassociatePass function. */
+void LLVMAddReassociatePass(LLVMPassManagerRef PM);
+
+/** See llvm::createSCCPPass function. */
+void LLVMAddSCCPPass(LLVMPassManagerRef PM);
+
+/** See llvm::createScalarReplAggregatesPass function. */
+void LLVMAddScalarReplAggregatesPass(LLVMPassManagerRef PM);
+
+/** See llvm::createScalarReplAggregatesPass function. */
+void LLVMAddScalarReplAggregatesPassSSA(LLVMPassManagerRef PM);
+
+/** See llvm::createScalarReplAggregatesPass function. */
+void LLVMAddScalarReplAggregatesPassWithThreshold(LLVMPassManagerRef PM,
+ int Threshold);
+
+/** See llvm::createSimplifyLibCallsPass function. */
+void LLVMAddSimplifyLibCallsPass(LLVMPassManagerRef PM);
+
+/** See llvm::createTailCallEliminationPass function. */
+void LLVMAddTailCallEliminationPass(LLVMPassManagerRef PM);
+
+/** See llvm::createConstantPropagationPass function. */
+void LLVMAddConstantPropagationPass(LLVMPassManagerRef PM);
+
+/** See llvm::demotePromoteMemoryToRegisterPass function. */
+void LLVMAddDemoteMemoryToRegisterPass(LLVMPassManagerRef PM);
+
+/** See llvm::createVerifierPass function. */
+void LLVMAddVerifierPass(LLVMPassManagerRef PM);
+
+/** See llvm::createCorrelatedValuePropagationPass function */
+void LLVMAddCorrelatedValuePropagationPass(LLVMPassManagerRef PM);
+
+/** See llvm::createEarlyCSEPass function */
+void LLVMAddEarlyCSEPass(LLVMPassManagerRef PM);
+
+/** See llvm::createLowerExpectIntrinsicPass function */
+void LLVMAddLowerExpectIntrinsicPass(LLVMPassManagerRef PM);
+
+/** See llvm::createTypeBasedAliasAnalysisPass function */
+void LLVMAddTypeBasedAliasAnalysisPass(LLVMPassManagerRef PM);
+
+/** See llvm::createBasicAliasAnalysisPass function */
+void LLVMAddBasicAliasAnalysisPass(LLVMPassManagerRef PM);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif /* defined(__cplusplus) */
+
+#endif
diff --git a/include/llvm-c/Transforms/Vectorize.h b/include/llvm-c/Transforms/Vectorize.h
new file mode 100644
index 00000000000..9e7c7540d76
--- /dev/null
+++ b/include/llvm-c/Transforms/Vectorize.h
@@ -0,0 +1,48 @@
+/*===---------------------------Vectorize.h --------------------- -*- C -*-===*\
+|*===----------- Vectorization Transformation Library C Interface ---------===*|
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header declares the C interface to libLLVMVectorize.a, which *|
+|* implements various vectorization transformations of the LLVM IR. *|
+|* *|
+|* Many exotic languages can interoperate with C code but have a harder time *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_TRANSFORMS_VECTORIZE_H
+#define LLVM_C_TRANSFORMS_VECTORIZE_H
+
+#include "llvm-c/Core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup LLVMCTransformsVectorize Vectorization transformations
+ * @ingroup LLVMCTransforms
+ *
+ * @{
+ */
+
+/** See llvm::createBBVectorizePass function. */
+void LLVMAddBBVectorizePass(LLVMPassManagerRef PM);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif /* defined(__cplusplus) */
+
+#endif
+
diff --git a/include/llvm-c/lto.h b/include/llvm-c/lto.h
new file mode 100644
index 00000000000..f43d365e3db
--- /dev/null
+++ b/include/llvm-c/lto.h
@@ -0,0 +1,302 @@
+/*===-- llvm-c/lto.h - LTO Public C Interface ---------------------*- C -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header provides public interface to an abstract link time optimization*|
+|* library. LLVM provides an implementation of this interface for use with *|
+|* llvm bitcode files. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LTO_H
+#define LTO_H 1
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <unistd.h>
+
+/**
+ * @defgroup LLVMCLTO LTO
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+#define LTO_API_VERSION 4
+
+typedef enum {
+ LTO_SYMBOL_ALIGNMENT_MASK = 0x0000001F, /* log2 of alignment */
+ LTO_SYMBOL_PERMISSIONS_MASK = 0x000000E0,
+ LTO_SYMBOL_PERMISSIONS_CODE = 0x000000A0,
+ LTO_SYMBOL_PERMISSIONS_DATA = 0x000000C0,
+ LTO_SYMBOL_PERMISSIONS_RODATA = 0x00000080,
+ LTO_SYMBOL_DEFINITION_MASK = 0x00000700,
+ LTO_SYMBOL_DEFINITION_REGULAR = 0x00000100,
+ LTO_SYMBOL_DEFINITION_TENTATIVE = 0x00000200,
+ LTO_SYMBOL_DEFINITION_WEAK = 0x00000300,
+ LTO_SYMBOL_DEFINITION_UNDEFINED = 0x00000400,
+ LTO_SYMBOL_DEFINITION_WEAKUNDEF = 0x00000500,
+ LTO_SYMBOL_SCOPE_MASK = 0x00003800,
+ LTO_SYMBOL_SCOPE_INTERNAL = 0x00000800,
+ LTO_SYMBOL_SCOPE_HIDDEN = 0x00001000,
+ LTO_SYMBOL_SCOPE_PROTECTED = 0x00002000,
+ LTO_SYMBOL_SCOPE_DEFAULT = 0x00001800,
+ LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN = 0x00002800
+} lto_symbol_attributes;
+
+typedef enum {
+ LTO_DEBUG_MODEL_NONE = 0,
+ LTO_DEBUG_MODEL_DWARF = 1
+} lto_debug_model;
+
+typedef enum {
+ LTO_CODEGEN_PIC_MODEL_STATIC = 0,
+ LTO_CODEGEN_PIC_MODEL_DYNAMIC = 1,
+ LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC = 2
+} lto_codegen_model;
+
+
+/** opaque reference to a loaded object module */
+typedef struct LTOModule* lto_module_t;
+
+/** opaque reference to a code generator */
+typedef struct LTOCodeGenerator* lto_code_gen_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Returns a printable string.
+ */
+extern const char*
+lto_get_version(void);
+
+
+/**
+ * Returns the last error string or NULL if last operation was successful.
+ */
+extern const char*
+lto_get_error_message(void);
+
+/**
+ * Checks if a file is a loadable object file.
+ */
+extern bool
+lto_module_is_object_file(const char* path);
+
+
+/**
+ * Checks if a file is a loadable object compiled for requested target.
+ */
+extern bool
+lto_module_is_object_file_for_target(const char* path,
+ const char* target_triple_prefix);
+
+
+/**
+ * Checks if a buffer is a loadable object file.
+ */
+extern bool
+lto_module_is_object_file_in_memory(const void* mem, size_t length);
+
+
+/**
+ * Checks if a buffer is a loadable object compiled for requested target.
+ */
+extern bool
+lto_module_is_object_file_in_memory_for_target(const void* mem, size_t length,
+ const char* target_triple_prefix);
+
+
+/**
+ * Loads an object file from disk.
+ * Returns NULL on error (check lto_get_error_message() for details).
+ */
+extern lto_module_t
+lto_module_create(const char* path);
+
+
+/**
+ * Loads an object file from memory.
+ * Returns NULL on error (check lto_get_error_message() for details).
+ */
+extern lto_module_t
+lto_module_create_from_memory(const void* mem, size_t length);
+
+/**
+ * Loads an object file from disk. The seek point of fd is not preserved.
+ * Returns NULL on error (check lto_get_error_message() for details).
+ */
+extern lto_module_t
+lto_module_create_from_fd(int fd, const char *path, size_t file_size);
+
+/**
+ * Loads an object file from disk. The seek point of fd is not preserved.
+ * Returns NULL on error (check lto_get_error_message() for details).
+ */
+extern lto_module_t
+lto_module_create_from_fd_at_offset(int fd, const char *path, size_t file_size,
+ size_t map_size, off_t offset);
+
+
+/**
+ * Frees all memory internally allocated by the module.
+ * Upon return the lto_module_t is no longer valid.
+ */
+extern void
+lto_module_dispose(lto_module_t mod);
+
+
+/**
+ * Returns triple string which the object module was compiled under.
+ */
+extern const char*
+lto_module_get_target_triple(lto_module_t mod);
+
+/**
+ * Sets triple string with which the object will be codegened.
+ */
+extern void
+lto_module_set_target_triple(lto_module_t mod, const char *triple);
+
+
+/**
+ * Returns the number of symbols in the object module.
+ */
+extern unsigned int
+lto_module_get_num_symbols(lto_module_t mod);
+
+
+/**
+ * Returns the name of the ith symbol in the object module.
+ */
+extern const char*
+lto_module_get_symbol_name(lto_module_t mod, unsigned int index);
+
+
+/**
+ * Returns the attributes of the ith symbol in the object module.
+ */
+extern lto_symbol_attributes
+lto_module_get_symbol_attribute(lto_module_t mod, unsigned int index);
+
+
+/**
+ * Instantiates a code generator.
+ * Returns NULL on error (check lto_get_error_message() for details).
+ */
+extern lto_code_gen_t
+lto_codegen_create(void);
+
+
+/**
+ * Frees all code generator and all memory it internally allocated.
+ * Upon return the lto_code_gen_t is no longer valid.
+ */
+extern void
+lto_codegen_dispose(lto_code_gen_t);
+
+
+
+/**
+ * Add an object module to the set of modules for which code will be generated.
+ * Returns true on error (check lto_get_error_message() for details).
+ */
+extern bool
+lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod);
+
+
+
+/**
+ * Sets if debug info should be generated.
+ * Returns true on error (check lto_get_error_message() for details).
+ */
+extern bool
+lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model);
+
+
+/**
+ * Sets which PIC code model to generated.
+ * Returns true on error (check lto_get_error_message() for details).
+ */
+extern bool
+lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model);
+
+
+/**
+ * Sets the cpu to generate code for.
+ */
+extern void
+lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu);
+
+
+/**
+ * Sets the location of the assembler tool to run. If not set, libLTO
+ * will use gcc to invoke the assembler.
+ */
+extern void
+lto_codegen_set_assembler_path(lto_code_gen_t cg, const char* path);
+
+/**
+ * Sets extra arguments that libLTO should pass to the assembler.
+ */
+extern void
+lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
+ int nargs);
+
+/**
+ * Adds to a list of all global symbols that must exist in the final
+ * generated code. If a function is not listed, it might be
+ * inlined into every usage and optimized away.
+ */
+extern void
+lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char* symbol);
+
+/**
+ * Writes a new object file at the specified path that contains the
+ * merged contents of all modules added so far.
+ * Returns true on error (check lto_get_error_message() for details).
+ */
+extern bool
+lto_codegen_write_merged_modules(lto_code_gen_t cg, const char* path);
+
+/**
+ * Generates code for all added modules into one native object file.
+ * On success returns a pointer to a generated mach-o/ELF buffer and
+ * length set to the buffer size. The buffer is owned by the
+ * lto_code_gen_t and will be freed when lto_codegen_dispose()
+ * is called, or lto_codegen_compile() is called again.
+ * On failure, returns NULL (check lto_get_error_message() for details).
+ */
+extern const void*
+lto_codegen_compile(lto_code_gen_t cg, size_t* length);
+
+/**
+ * Generates code for all added modules into one native object file.
+ * The name of the file is written to name. Returns true on error.
+ */
+extern bool
+lto_codegen_compile_to_file(lto_code_gen_t cg, const char** name);
+
+
+/**
+ * Sets options to help debug codegen bugs.
+ */
+extern void
+lto_codegen_debug_options(lto_code_gen_t cg, const char *);
+
+#ifdef __cplusplus
+}
+#endif
+
+/**
+ * @}
+ */
+
+#endif
diff --git a/include/llvm/ADT/APFloat.h b/include/llvm/ADT/APFloat.h
new file mode 100644
index 00000000000..5a625a4c832
--- /dev/null
+++ b/include/llvm/ADT/APFloat.h
@@ -0,0 +1,468 @@
+//== llvm/Support/APFloat.h - Arbitrary Precision Floating Point -*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares a class to represent arbitrary precision floating
+// point values and provide a variety of arithmetic operations on them.
+//
+//===----------------------------------------------------------------------===//
+
+/* A self-contained host- and target-independent arbitrary-precision
+ floating-point software implementation. It uses bignum integer
+ arithmetic as provided by static functions in the APInt class.
+ The library will work with bignum integers whose parts are any
+ unsigned type at least 16 bits wide, but 64 bits is recommended.
+
+ Written for clarity rather than speed, in particular with a view
+ to use in the front-end of a cross compiler so that target
+ arithmetic can be correctly performed on the host. Performance
+ should nonetheless be reasonable, particularly for its intended
+ use. It may be useful as a base implementation for a run-time
+ library during development of a faster target-specific one.
+
+ All 5 rounding modes in the IEEE-754R draft are handled correctly
+ for all implemented operations. Currently implemented operations
+ are add, subtract, multiply, divide, fused-multiply-add,
+ conversion-to-float, conversion-to-integer and
+ conversion-from-integer. New rounding modes (e.g. away from zero)
+ can be added with three or four lines of code.
+
+ Four formats are built-in: IEEE single precision, double
+ precision, quadruple precision, and x87 80-bit extended double
+ (when operating with full extended precision). Adding a new
+ format that obeys IEEE semantics only requires adding two lines of
+ code: a declaration and definition of the format.
+
+ All operations return the status of that operation as an exception
+ bit-mask, so multiple operations can be done consecutively with
+ their results or-ed together. The returned status can be useful
+ for compiler diagnostics; e.g., inexact, underflow and overflow
+ can be easily diagnosed on constant folding, and compiler
+ optimizers can determine what exceptions would be raised by
+ folding operations and optimize, or perhaps not optimize,
+ accordingly.
+
+ At present, underflow tininess is detected after rounding; it
+ should be straight forward to add support for the before-rounding
+ case too.
+
+ The library reads hexadecimal floating point numbers as per C99,
+ and correctly rounds if necessary according to the specified
+ rounding mode. Syntax is required to have been validated by the
+ caller. It also converts floating point numbers to hexadecimal
+ text as per the C99 %a and %A conversions. The output precision
+ (or alternatively the natural minimal precision) can be specified;
+ if the requested precision is less than the natural precision the
+ output is correctly rounded for the specified rounding mode.
+
+ It also reads decimal floating point numbers and correctly rounds
+ according to the specified rounding mode.
+
+ Conversion to decimal text is not currently implemented.
+
+ Non-zero finite numbers are represented internally as a sign bit,
+ a 16-bit signed exponent, and the significand as an array of
+ integer parts. After normalization of a number of precision P the
+ exponent is within the range of the format, and if the number is
+ not denormal the P-th bit of the significand is set as an explicit
+ integer bit. For denormals the most significant bit is shifted
+ right so that the exponent is maintained at the format's minimum,
+ so that the smallest denormal has just the least significant bit
+ of the significand set. The sign of zeroes and infinities is
+ significant; the exponent and significand of such numbers is not
+ stored, but has a known implicit (deterministic) value: 0 for the
+ significands, 0 for zero exponent, all 1 bits for infinity
+ exponent. For NaNs the sign and significand are deterministic,
+ although not really meaningful, and preserved in non-conversion
+ operations. The exponent is implicitly all 1 bits.
+
+ TODO
+ ====
+
+ Some features that may or may not be worth adding:
+
+ Binary to decimal conversion (hard).
+
+ Optional ability to detect underflow tininess before rounding.
+
+ New formats: x87 in single and double precision mode (IEEE apart
+ from extended exponent range) (hard).
+
+ New operations: sqrt, IEEE remainder, C90 fmod, nextafter,
+ nexttoward.
+*/
+
+#ifndef LLVM_FLOAT_H
+#define LLVM_FLOAT_H
+
+// APInt contains static functions implementing bignum arithmetic.
+#include "llvm/ADT/APInt.h"
+
+namespace llvm {
+
+ /* Exponents are stored as signed numbers. */
+ typedef signed short exponent_t;
+
+ struct fltSemantics;
+ class APSInt;
+ class StringRef;
+
+ /* When bits of a floating point number are truncated, this enum is
+ used to indicate what fraction of the LSB those bits represented.
+ It essentially combines the roles of guard and sticky bits. */
+ enum lostFraction { // Example of truncated bits:
+ lfExactlyZero, // 000000
+ lfLessThanHalf, // 0xxxxx x's not all zero
+ lfExactlyHalf, // 100000
+ lfMoreThanHalf // 1xxxxx x's not all zero
+ };
+
+ class APFloat {
+ public:
+
+ /* We support the following floating point semantics. */
+ static const fltSemantics IEEEhalf;
+ static const fltSemantics IEEEsingle;
+ static const fltSemantics IEEEdouble;
+ static const fltSemantics IEEEquad;
+ static const fltSemantics PPCDoubleDouble;
+ static const fltSemantics x87DoubleExtended;
+ /* And this pseudo, used to construct APFloats that cannot
+ conflict with anything real. */
+ static const fltSemantics Bogus;
+
+ static unsigned int semanticsPrecision(const fltSemantics &);
+
+ /* Floating point numbers have a four-state comparison relation. */
+ enum cmpResult {
+ cmpLessThan,
+ cmpEqual,
+ cmpGreaterThan,
+ cmpUnordered
+ };
+
+ /* IEEE-754R gives five rounding modes. */
+ enum roundingMode {
+ rmNearestTiesToEven,
+ rmTowardPositive,
+ rmTowardNegative,
+ rmTowardZero,
+ rmNearestTiesToAway
+ };
+
+ // Operation status. opUnderflow or opOverflow are always returned
+ // or-ed with opInexact.
+ enum opStatus {
+ opOK = 0x00,
+ opInvalidOp = 0x01,
+ opDivByZero = 0x02,
+ opOverflow = 0x04,
+ opUnderflow = 0x08,
+ opInexact = 0x10
+ };
+
+ // Category of internally-represented number.
+ enum fltCategory {
+ fcInfinity,
+ fcNaN,
+ fcNormal,
+ fcZero
+ };
+
+ enum uninitializedTag {
+ uninitialized
+ };
+
+ // Constructors.
+ APFloat(const fltSemantics &); // Default construct to 0.0
+ APFloat(const fltSemantics &, StringRef);
+ APFloat(const fltSemantics &, integerPart);
+ APFloat(const fltSemantics &, fltCategory, bool negative);
+ APFloat(const fltSemantics &, uninitializedTag);
+ explicit APFloat(double d);
+ explicit APFloat(float f);
+ explicit APFloat(const APInt &, bool isIEEE = false);
+ APFloat(const APFloat &);
+ ~APFloat();
+
+ // Convenience "constructors"
+ static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
+ return APFloat(Sem, fcZero, Negative);
+ }
+ static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
+ return APFloat(Sem, fcInfinity, Negative);
+ }
+
+ /// getNaN - Factory for QNaN values.
+ ///
+ /// \param Negative - True iff the NaN generated should be negative.
+ /// \param type - The unspecified fill bits for creating the NaN, 0 by
+ /// default. The value is truncated as necessary.
+ static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
+ unsigned type = 0) {
+ if (type) {
+ APInt fill(64, type);
+ return getQNaN(Sem, Negative, &fill);
+ } else {
+ return getQNaN(Sem, Negative, 0);
+ }
+ }
+
+ /// getQNan - Factory for QNaN values.
+ static APFloat getQNaN(const fltSemantics &Sem,
+ bool Negative = false,
+ const APInt *payload = 0) {
+ return makeNaN(Sem, false, Negative, payload);
+ }
+
+ /// getSNan - Factory for SNaN values.
+ static APFloat getSNaN(const fltSemantics &Sem,
+ bool Negative = false,
+ const APInt *payload = 0) {
+ return makeNaN(Sem, true, Negative, payload);
+ }
+
+ /// getLargest - Returns the largest finite number in the given
+ /// semantics.
+ ///
+ /// \param Negative - True iff the number should be negative
+ static APFloat getLargest(const fltSemantics &Sem, bool Negative = false);
+
+ /// getSmallest - Returns the smallest (by magnitude) finite number
+ /// in the given semantics. Might be denormalized, which implies a
+ /// relative loss of precision.
+ ///
+ /// \param Negative - True iff the number should be negative
+ static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false);
+
+ /// getSmallestNormalized - Returns the smallest (by magnitude)
+ /// normalized finite number in the given semantics.
+ ///
+ /// \param Negative - True iff the number should be negative
+ static APFloat getSmallestNormalized(const fltSemantics &Sem,
+ bool Negative = false);
+
+ /// getAllOnesValue - Returns a float which is bitcasted from
+ /// an all one value int.
+ ///
+ /// \param BitWidth - Select float type
+ /// \param isIEEE - If 128 bit number, select between PPC and IEEE
+ static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
+
+ /// Profile - Used to insert APFloat objects, or objects that contain
+ /// APFloat objects, into FoldingSets.
+ void Profile(FoldingSetNodeID& NID) const;
+
+ /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
+ void Emit(Serializer& S) const;
+
+ /// @brief Used by the Bitcode deserializer to deserialize APInts.
+ static APFloat ReadVal(Deserializer& D);
+
+ /* Arithmetic. */
+ opStatus add(const APFloat &, roundingMode);
+ opStatus subtract(const APFloat &, roundingMode);
+ opStatus multiply(const APFloat &, roundingMode);
+ opStatus divide(const APFloat &, roundingMode);
+ /* IEEE remainder. */
+ opStatus remainder(const APFloat &);
+ /* C fmod, or llvm frem. */
+ opStatus mod(const APFloat &, roundingMode);
+ opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
+ opStatus roundToIntegral(roundingMode);
+
+ /* Sign operations. */
+ void changeSign();
+ void clearSign();
+ void copySign(const APFloat &);
+
+ /* Conversions. */
+ opStatus convert(const fltSemantics &, roundingMode, bool *);
+ opStatus convertToInteger(integerPart *, unsigned int, bool,
+ roundingMode, bool *) const;
+ opStatus convertToInteger(APSInt&, roundingMode, bool *) const;
+ opStatus convertFromAPInt(const APInt &,
+ bool, roundingMode);
+ opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
+ bool, roundingMode);
+ opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
+ bool, roundingMode);
+ opStatus convertFromString(StringRef, roundingMode);
+ APInt bitcastToAPInt() const;
+ double convertToDouble() const;
+ float convertToFloat() const;
+
+ /* The definition of equality is not straightforward for floating point,
+ so we won't use operator==. Use one of the following, or write
+ whatever it is you really mean. */
+ // bool operator==(const APFloat &) const; // DO NOT IMPLEMENT
+
+ /* IEEE comparison with another floating point number (NaNs
+ compare unordered, 0==-0). */
+ cmpResult compare(const APFloat &) const;
+
+ /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */
+ bool bitwiseIsEqual(const APFloat &) const;
+
+ /* Write out a hexadecimal representation of the floating point
+ value to DST, which must be of sufficient size, in the C99 form
+ [-]0xh.hhhhp[+-]d. Return the number of characters written,
+ excluding the terminating NUL. */
+ unsigned int convertToHexString(char *dst, unsigned int hexDigits,
+ bool upperCase, roundingMode) const;
+
+ /* Simple queries. */
+ fltCategory getCategory() const { return category; }
+ const fltSemantics &getSemantics() const { return *semantics; }
+ bool isZero() const { return category == fcZero; }
+ bool isNonZero() const { return category != fcZero; }
+ bool isNormal() const { return category == fcNormal; }
+ bool isNaN() const { return category == fcNaN; }
+ bool isInfinity() const { return category == fcInfinity; }
+ bool isNegative() const { return sign; }
+ bool isPosZero() const { return isZero() && !isNegative(); }
+ bool isNegZero() const { return isZero() && isNegative(); }
+
+ APFloat& operator=(const APFloat &);
+
+ /// \brief Overload to compute a hash code for an APFloat value.
+ ///
+ /// Note that the use of hash codes for floating point values is in general
+ /// frought with peril. Equality is hard to define for these values. For
+ /// example, should negative and positive zero hash to different codes? Are
+ /// they equal or not? This hash value implementation specifically
+ /// emphasizes producing different codes for different inputs in order to
+ /// be used in canonicalization and memoization. As such, equality is
+ /// bitwiseIsEqual, and 0 != -0.
+ friend hash_code hash_value(const APFloat &Arg);
+
+ /// Converts this value into a decimal string.
+ ///
+ /// \param FormatPrecision The maximum number of digits of
+ /// precision to output. If there are fewer digits available,
+ /// zero padding will not be used unless the value is
+ /// integral and small enough to be expressed in
+ /// FormatPrecision digits. 0 means to use the natural
+ /// precision of the number.
+ /// \param FormatMaxPadding The maximum number of zeros to
+ /// consider inserting before falling back to scientific
+ /// notation. 0 means to always use scientific notation.
+ ///
+ /// Number Precision MaxPadding Result
+ /// ------ --------- ---------- ------
+ /// 1.01E+4 5 2 10100
+ /// 1.01E+4 4 2 1.01E+4
+ /// 1.01E+4 5 1 1.01E+4
+ /// 1.01E-2 5 2 0.0101
+ /// 1.01E-2 4 2 0.0101
+ /// 1.01E-2 4 1 1.01E-2
+ void toString(SmallVectorImpl<char> &Str,
+ unsigned FormatPrecision = 0,
+ unsigned FormatMaxPadding = 3) const;
+
+ /// getExactInverse - If this value has an exact multiplicative inverse,
+ /// store it in inv and return true.
+ bool getExactInverse(APFloat *inv) const;
+
+ private:
+
+ /* Trivial queries. */
+ integerPart *significandParts();
+ const integerPart *significandParts() const;
+ unsigned int partCount() const;
+
+ /* Significand operations. */
+ integerPart addSignificand(const APFloat &);
+ integerPart subtractSignificand(const APFloat &, integerPart);
+ lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
+ lostFraction multiplySignificand(const APFloat &, const APFloat *);
+ lostFraction divideSignificand(const APFloat &);
+ void incrementSignificand();
+ void initialize(const fltSemantics *);
+ void shiftSignificandLeft(unsigned int);
+ lostFraction shiftSignificandRight(unsigned int);
+ unsigned int significandLSB() const;
+ unsigned int significandMSB() const;
+ void zeroSignificand();
+
+ /* Arithmetic on special values. */
+ opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
+ opStatus divideSpecials(const APFloat &);
+ opStatus multiplySpecials(const APFloat &);
+ opStatus modSpecials(const APFloat &);
+
+ /* Miscellany. */
+ static APFloat makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
+ const APInt *fill);
+ void makeNaN(bool SNaN = false, bool Neg = false, const APInt *fill = 0);
+ opStatus normalize(roundingMode, lostFraction);
+ opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
+ cmpResult compareAbsoluteValue(const APFloat &) const;
+ opStatus handleOverflow(roundingMode);
+ bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
+ opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
+ roundingMode, bool *) const;
+ opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
+ roundingMode);
+ opStatus convertFromHexadecimalString(StringRef, roundingMode);
+ opStatus convertFromDecimalString(StringRef, roundingMode);
+ char *convertNormalToHexString(char *, unsigned int, bool,
+ roundingMode) const;
+ opStatus roundSignificandWithExponent(const integerPart *, unsigned int,
+ int, roundingMode);
+
+ APInt convertHalfAPFloatToAPInt() const;
+ APInt convertFloatAPFloatToAPInt() const;
+ APInt convertDoubleAPFloatToAPInt() const;
+ APInt convertQuadrupleAPFloatToAPInt() const;
+ APInt convertF80LongDoubleAPFloatToAPInt() const;
+ APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
+ void initFromAPInt(const APInt& api, bool isIEEE = false);
+ void initFromHalfAPInt(const APInt& api);
+ void initFromFloatAPInt(const APInt& api);
+ void initFromDoubleAPInt(const APInt& api);
+ void initFromQuadrupleAPInt(const APInt &api);
+ void initFromF80LongDoubleAPInt(const APInt& api);
+ void initFromPPCDoubleDoubleAPInt(const APInt& api);
+
+ void assign(const APFloat &);
+ void copySignificand(const APFloat &);
+ void freeSignificand();
+
+ /* What kind of semantics does this value obey? */
+ const fltSemantics *semantics;
+
+ /* Significand - the fraction with an explicit integer bit. Must be
+ at least one bit wider than the target precision. */
+ union Significand
+ {
+ integerPart part;
+ integerPart *parts;
+ } significand;
+
+ /* The exponent - a signed number. */
+ exponent_t exponent;
+
+ /* What kind of floating point number this is. */
+ /* Only 2 bits are required, but VisualStudio incorrectly sign extends
+ it. Using the extra bit keeps it from failing under VisualStudio */
+ fltCategory category: 3;
+
+ /* The sign bit of this number. */
+ unsigned int sign: 1;
+
+ /* For PPCDoubleDouble, we have a second exponent and sign (the second
+ significand is appended to the first one, although it would be wrong to
+ regard these as a single number for arithmetic purposes). These fields
+ are not meaningful for any other type. */
+ exponent_t exponent2 : 11;
+ unsigned int sign2: 1;
+ };
+} /* namespace llvm */
+
+#endif /* LLVM_FLOAT_H */
diff --git a/include/llvm/ADT/APInt.h b/include/llvm/ADT/APInt.h
new file mode 100644
index 00000000000..4470534e049
--- /dev/null
+++ b/include/llvm/ADT/APInt.h
@@ -0,0 +1,1785 @@
+//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements a class to represent arbitrary precision integral
+// constant values and operations on them.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_APINT_H
+#define LLVM_APINT_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/MathExtras.h"
+#include <cassert>
+#include <climits>
+#include <cstring>
+#include <string>
+
+namespace llvm {
+ class Deserializer;
+ class FoldingSetNodeID;
+ class Serializer;
+ class StringRef;
+ class hash_code;
+ class raw_ostream;
+
+ template<typename T>
+ class SmallVectorImpl;
+
+ // An unsigned host type used as a single part of a multi-part
+ // bignum.
+ typedef uint64_t integerPart;
+
+ const unsigned int host_char_bit = 8;
+ const unsigned int integerPartWidth = host_char_bit *
+ static_cast<unsigned int>(sizeof(integerPart));
+
+//===----------------------------------------------------------------------===//
+// APInt Class
+//===----------------------------------------------------------------------===//
+
+/// APInt - This class represents arbitrary precision constant integral values.
+/// It is a functional replacement for common case unsigned integer type like
+/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
+/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
+/// than 64-bits of precision. APInt provides a variety of arithmetic operators
+/// and methods to manipulate integer values of any bit-width. It supports both
+/// the typical integer arithmetic and comparison operations as well as bitwise
+/// manipulation.
+///
+/// The class has several invariants worth noting:
+/// * All bit, byte, and word positions are zero-based.
+/// * Once the bit width is set, it doesn't change except by the Truncate,
+/// SignExtend, or ZeroExtend operations.
+/// * All binary operators must be on APInt instances of the same bit width.
+/// Attempting to use these operators on instances with different bit
+/// widths will yield an assertion.
+/// * The value is stored canonically as an unsigned value. For operations
+/// where it makes a difference, there are both signed and unsigned variants
+/// of the operation. For example, sdiv and udiv. However, because the bit
+/// widths must be the same, operations such as Mul and Add produce the same
+/// results regardless of whether the values are interpreted as signed or
+/// not.
+/// * In general, the class tries to follow the style of computation that LLVM
+/// uses in its IR. This simplifies its use for LLVM.
+///
+/// @brief Class for arbitrary precision integers.
+class APInt {
+ unsigned BitWidth; ///< The number of bits in this APInt.
+
+ /// This union is used to store the integer value. When the
+ /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
+ union {
+ uint64_t VAL; ///< Used to store the <= 64 bits integer value.
+ uint64_t *pVal; ///< Used to store the >64 bits integer value.
+ };
+
+ /// This enum is used to hold the constants we needed for APInt.
+ enum {
+ /// Bits in a word
+ APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
+ CHAR_BIT,
+ /// Byte size of a word
+ APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
+ };
+
+ /// This constructor is used only internally for speed of construction of
+ /// temporaries. It is unsafe for general use so it is not public.
+ /// @brief Fast internal constructor
+ APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { }
+
+ /// @returns true if the number of bits <= 64, false otherwise.
+ /// @brief Determine if this APInt just has one word to store value.
+ bool isSingleWord() const {
+ return BitWidth <= APINT_BITS_PER_WORD;
+ }
+
+ /// @returns the word position for the specified bit position.
+ /// @brief Determine which word a bit is in.
+ static unsigned whichWord(unsigned bitPosition) {
+ return bitPosition / APINT_BITS_PER_WORD;
+ }
+
+ /// @returns the bit position in a word for the specified bit position
+ /// in the APInt.
+ /// @brief Determine which bit in a word a bit is in.
+ static unsigned whichBit(unsigned bitPosition) {
+ return bitPosition % APINT_BITS_PER_WORD;
+ }
+
+ /// This method generates and returns a uint64_t (word) mask for a single
+ /// bit at a specific bit position. This is used to mask the bit in the
+ /// corresponding word.
+ /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
+ /// @brief Get a single bit mask.
+ static uint64_t maskBit(unsigned bitPosition) {
+ return 1ULL << whichBit(bitPosition);
+ }
+
+ /// This method is used internally to clear the to "N" bits in the high order
+ /// word that are not used by the APInt. This is needed after the most
+ /// significant word is assigned a value to ensure that those bits are
+ /// zero'd out.
+ /// @brief Clear unused high order bits
+ APInt& clearUnusedBits() {
+ // Compute how many bits are used in the final word
+ unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
+ if (wordBits == 0)
+ // If all bits are used, we want to leave the value alone. This also
+ // avoids the undefined behavior of >> when the shift is the same size as
+ // the word size (64).
+ return *this;
+
+ // Mask out the high bits.
+ uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
+ if (isSingleWord())
+ VAL &= mask;
+ else
+ pVal[getNumWords() - 1] &= mask;
+ return *this;
+ }
+
+ /// @returns the corresponding word for the specified bit position.
+ /// @brief Get the word corresponding to a bit position
+ uint64_t getWord(unsigned bitPosition) const {
+ return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
+ }
+
+ /// Converts a string into a number. The string must be non-empty
+ /// and well-formed as a number of the given base. The bit-width
+ /// must be sufficient to hold the result.
+ ///
+ /// This is used by the constructors that take string arguments.
+ ///
+ /// StringRef::getAsInteger is superficially similar but (1) does
+ /// not assume that the string is well-formed and (2) grows the
+ /// result to hold the input.
+ ///
+ /// @param radix 2, 8, 10, 16, or 36
+ /// @brief Convert a char array into an APInt
+ void fromString(unsigned numBits, StringRef str, uint8_t radix);
+
+ /// This is used by the toString method to divide by the radix. It simply
+ /// provides a more convenient form of divide for internal use since KnuthDiv
+ /// has specific constraints on its inputs. If those constraints are not met
+ /// then it provides a simpler form of divide.
+ /// @brief An internal division function for dividing APInts.
+ static void divide(const APInt LHS, unsigned lhsWords,
+ const APInt &RHS, unsigned rhsWords,
+ APInt *Quotient, APInt *Remainder);
+
+ /// out-of-line slow case for inline constructor
+ void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
+
+ /// shared code between two array constructors
+ void initFromArray(ArrayRef<uint64_t> array);
+
+ /// out-of-line slow case for inline copy constructor
+ void initSlowCase(const APInt& that);
+
+ /// out-of-line slow case for shl
+ APInt shlSlowCase(unsigned shiftAmt) const;
+
+ /// out-of-line slow case for operator&
+ APInt AndSlowCase(const APInt& RHS) const;
+
+ /// out-of-line slow case for operator|
+ APInt OrSlowCase(const APInt& RHS) const;
+
+ /// out-of-line slow case for operator^
+ APInt XorSlowCase(const APInt& RHS) const;
+
+ /// out-of-line slow case for operator=
+ APInt& AssignSlowCase(const APInt& RHS);
+
+ /// out-of-line slow case for operator==
+ bool EqualSlowCase(const APInt& RHS) const;
+
+ /// out-of-line slow case for operator==
+ bool EqualSlowCase(uint64_t Val) const;
+
+ /// out-of-line slow case for countLeadingZeros
+ unsigned countLeadingZerosSlowCase() const;
+
+ /// out-of-line slow case for countTrailingOnes
+ unsigned countTrailingOnesSlowCase() const;
+
+ /// out-of-line slow case for countPopulation
+ unsigned countPopulationSlowCase() const;
+
+public:
+ /// @name Constructors
+ /// @{
+ /// If isSigned is true then val is treated as if it were a signed value
+ /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
+ /// will be done. Otherwise, no sign extension occurs (high order bits beyond
+ /// the range of val are zero filled).
+ /// @param numBits the bit width of the constructed APInt
+ /// @param val the initial value of the APInt
+ /// @param isSigned how to treat signedness of val
+ /// @brief Create a new APInt of numBits width, initialized as val.
+ APInt(unsigned numBits, uint64_t val, bool isSigned = false)
+ : BitWidth(numBits), VAL(0) {
+ assert(BitWidth && "bitwidth too small");
+ if (isSingleWord())
+ VAL = val;
+ else
+ initSlowCase(numBits, val, isSigned);
+ clearUnusedBits();
+ }
+
+ /// Note that bigVal.size() can be smaller or larger than the corresponding
+ /// bit width but any extraneous bits will be dropped.
+ /// @param numBits the bit width of the constructed APInt
+ /// @param bigVal a sequence of words to form the initial value of the APInt
+ /// @brief Construct an APInt of numBits width, initialized as bigVal[].
+ APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
+ /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
+ /// deprecated because this constructor is prone to ambiguity with the
+ /// APInt(unsigned, uint64_t, bool) constructor.
+ ///
+ /// If this overload is ever deleted, care should be taken to prevent calls
+ /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
+ /// constructor.
+ APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
+
+ /// This constructor interprets the string \p str in the given radix. The
+ /// interpretation stops when the first character that is not suitable for the
+ /// radix is encountered, or the end of the string. Acceptable radix values
+ /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
+ /// string to require more bits than numBits.
+ ///
+ /// @param numBits the bit width of the constructed APInt
+ /// @param str the string to be interpreted
+ /// @param radix the radix to use for the conversion
+ /// @brief Construct an APInt from a string representation.
+ APInt(unsigned numBits, StringRef str, uint8_t radix);
+
+ /// Simply makes *this a copy of that.
+ /// @brief Copy Constructor.
+ APInt(const APInt& that)
+ : BitWidth(that.BitWidth), VAL(0) {
+ assert(BitWidth && "bitwidth too small");
+ if (isSingleWord())
+ VAL = that.VAL;
+ else
+ initSlowCase(that);
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ /// @brief Move Constructor.
+ APInt(APInt&& that) : BitWidth(that.BitWidth), VAL(that.VAL) {
+ that.BitWidth = 0;
+ }
+#endif
+
+ /// @brief Destructor.
+ ~APInt() {
+ if (!isSingleWord())
+ delete [] pVal;
+ }
+
+ /// Default constructor that creates an uninitialized APInt. This is useful
+ /// for object deserialization (pair this with the static method Read).
+ explicit APInt() : BitWidth(1) {}
+
+ /// Profile - Used to insert APInt objects, or objects that contain APInt
+ /// objects, into FoldingSets.
+ void Profile(FoldingSetNodeID& id) const;
+
+ /// @}
+ /// @name Value Tests
+ /// @{
+ /// This tests the high bit of this APInt to determine if it is set.
+ /// @returns true if this APInt is negative, false otherwise
+ /// @brief Determine sign of this APInt.
+ bool isNegative() const {
+ return (*this)[BitWidth - 1];
+ }
+
+ /// This tests the high bit of the APInt to determine if it is unset.
+ /// @brief Determine if this APInt Value is non-negative (>= 0)
+ bool isNonNegative() const {
+ return !isNegative();
+ }
+
+ /// This tests if the value of this APInt is positive (> 0). Note
+ /// that 0 is not a positive value.
+ /// @returns true if this APInt is positive.
+ /// @brief Determine if this APInt Value is positive.
+ bool isStrictlyPositive() const {
+ return isNonNegative() && !!*this;
+ }
+
+ /// This checks to see if the value has all bits of the APInt are set or not.
+ /// @brief Determine if all bits are set
+ bool isAllOnesValue() const {
+ return countPopulation() == BitWidth;
+ }
+
+ /// This checks to see if the value of this APInt is the maximum unsigned
+ /// value for the APInt's bit width.
+ /// @brief Determine if this is the largest unsigned value.
+ bool isMaxValue() const {
+ return countPopulation() == BitWidth;
+ }
+
+ /// This checks to see if the value of this APInt is the maximum signed
+ /// value for the APInt's bit width.
+ /// @brief Determine if this is the largest signed value.
+ bool isMaxSignedValue() const {
+ return BitWidth == 1 ? VAL == 0 :
+ !isNegative() && countPopulation() == BitWidth - 1;
+ }
+
+ /// This checks to see if the value of this APInt is the minimum unsigned
+ /// value for the APInt's bit width.
+ /// @brief Determine if this is the smallest unsigned value.
+ bool isMinValue() const {
+ return !*this;
+ }
+
+ /// This checks to see if the value of this APInt is the minimum signed
+ /// value for the APInt's bit width.
+ /// @brief Determine if this is the smallest signed value.
+ bool isMinSignedValue() const {
+ return BitWidth == 1 ? VAL == 1 : isNegative() && isPowerOf2();
+ }
+
+ /// @brief Check if this APInt has an N-bits unsigned integer value.
+ bool isIntN(unsigned N) const {
+ assert(N && "N == 0 ???");
+ return getActiveBits() <= N;
+ }
+
+ /// @brief Check if this APInt has an N-bits signed integer value.
+ bool isSignedIntN(unsigned N) const {
+ assert(N && "N == 0 ???");
+ return getMinSignedBits() <= N;
+ }
+
+ /// @returns true if the argument APInt value is a power of two > 0.
+ bool isPowerOf2() const {
+ if (isSingleWord())
+ return isPowerOf2_64(VAL);
+ return countPopulationSlowCase() == 1;
+ }
+
+ /// isSignBit - Return true if this is the value returned by getSignBit.
+ bool isSignBit() const { return isMinSignedValue(); }
+
+ /// This converts the APInt to a boolean value as a test against zero.
+ /// @brief Boolean conversion function.
+ bool getBoolValue() const {
+ return !!*this;
+ }
+
+ /// getLimitedValue - If this value is smaller than the specified limit,
+ /// return it, otherwise return the limit value. This causes the value
+ /// to saturate to the limit.
+ uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
+ return (getActiveBits() > 64 || getZExtValue() > Limit) ?
+ Limit : getZExtValue();
+ }
+
+ /// @}
+ /// @name Value Generators
+ /// @{
+ /// @brief Gets maximum unsigned value of APInt for specific bit width.
+ static APInt getMaxValue(unsigned numBits) {
+ return getAllOnesValue(numBits);
+ }
+
+ /// @brief Gets maximum signed value of APInt for a specific bit width.
+ static APInt getSignedMaxValue(unsigned numBits) {
+ APInt API = getAllOnesValue(numBits);
+ API.clearBit(numBits - 1);
+ return API;
+ }
+
+ /// @brief Gets minimum unsigned value of APInt for a specific bit width.
+ static APInt getMinValue(unsigned numBits) {
+ return APInt(numBits, 0);
+ }
+
+ /// @brief Gets minimum signed value of APInt for a specific bit width.
+ static APInt getSignedMinValue(unsigned numBits) {
+ APInt API(numBits, 0);
+ API.setBit(numBits - 1);
+ return API;
+ }
+
+ /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
+ /// it helps code readability when we want to get a SignBit.
+ /// @brief Get the SignBit for a specific bit width.
+ static APInt getSignBit(unsigned BitWidth) {
+ return getSignedMinValue(BitWidth);
+ }
+
+ /// @returns the all-ones value for an APInt of the specified bit-width.
+ /// @brief Get the all-ones value.
+ static APInt getAllOnesValue(unsigned numBits) {
+ return APInt(numBits, -1ULL, true);
+ }
+
+ /// @returns the '0' value for an APInt of the specified bit-width.
+ /// @brief Get the '0' value.
+ static APInt getNullValue(unsigned numBits) {
+ return APInt(numBits, 0);
+ }
+
+ /// Get an APInt with the same BitWidth as this APInt, just zero mask
+ /// the low bits and right shift to the least significant bit.
+ /// @returns the high "numBits" bits of this APInt.
+ APInt getHiBits(unsigned numBits) const;
+
+ /// Get an APInt with the same BitWidth as this APInt, just zero mask
+ /// the high bits.
+ /// @returns the low "numBits" bits of this APInt.
+ APInt getLoBits(unsigned numBits) const;
+
+ /// getOneBitSet - Return an APInt with exactly one bit set in the result.
+ static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
+ APInt Res(numBits, 0);
+ Res.setBit(BitNo);
+ return Res;
+ }
+
+ /// Constructs an APInt value that has a contiguous range of bits set. The
+ /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
+ /// bits will be zero. For example, with parameters(32, 0, 16) you would get
+ /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
+ /// example, with parameters (32, 28, 4), you would get 0xF000000F.
+ /// @param numBits the intended bit width of the result
+ /// @param loBit the index of the lowest bit set.
+ /// @param hiBit the index of the highest bit set.
+ /// @returns An APInt value with the requested bits set.
+ /// @brief Get a value with a block of bits set.
+ static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
+ assert(hiBit <= numBits && "hiBit out of range");
+ assert(loBit < numBits && "loBit out of range");
+ if (hiBit < loBit)
+ return getLowBitsSet(numBits, hiBit) |
+ getHighBitsSet(numBits, numBits-loBit);
+ return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
+ }
+
+ /// Constructs an APInt value that has the top hiBitsSet bits set.
+ /// @param numBits the bitwidth of the result
+ /// @param hiBitsSet the number of high-order bits set in the result.
+ /// @brief Get a value with high bits set
+ static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
+ assert(hiBitsSet <= numBits && "Too many bits to set!");
+ // Handle a degenerate case, to avoid shifting by word size
+ if (hiBitsSet == 0)
+ return APInt(numBits, 0);
+ unsigned shiftAmt = numBits - hiBitsSet;
+ // For small values, return quickly
+ if (numBits <= APINT_BITS_PER_WORD)
+ return APInt(numBits, ~0ULL << shiftAmt);
+ return getAllOnesValue(numBits).shl(shiftAmt);
+ }
+
+ /// Constructs an APInt value that has the bottom loBitsSet bits set.
+ /// @param numBits the bitwidth of the result
+ /// @param loBitsSet the number of low-order bits set in the result.
+ /// @brief Get a value with low bits set
+ static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
+ assert(loBitsSet <= numBits && "Too many bits to set!");
+ // Handle a degenerate case, to avoid shifting by word size
+ if (loBitsSet == 0)
+ return APInt(numBits, 0);
+ if (loBitsSet == APINT_BITS_PER_WORD)
+ return APInt(numBits, -1ULL);
+ // For small values, return quickly.
+ if (loBitsSet <= APINT_BITS_PER_WORD)
+ return APInt(numBits, -1ULL >> (APINT_BITS_PER_WORD - loBitsSet));
+ return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
+ }
+
+ /// \brief Determine if two APInts have the same value, after zero-extending
+ /// one of them (if needed!) to ensure that the bit-widths match.
+ static bool isSameValue(const APInt &I1, const APInt &I2) {
+ if (I1.getBitWidth() == I2.getBitWidth())
+ return I1 == I2;
+
+ if (I1.getBitWidth() > I2.getBitWidth())
+ return I1 == I2.zext(I1.getBitWidth());
+
+ return I1.zext(I2.getBitWidth()) == I2;
+ }
+
+ /// \brief Overload to compute a hash_code for an APInt value.
+ friend hash_code hash_value(const APInt &Arg);
+
+ /// This function returns a pointer to the internal storage of the APInt.
+ /// This is useful for writing out the APInt in binary form without any
+ /// conversions.
+ const uint64_t* getRawData() const {
+ if (isSingleWord())
+ return &VAL;
+ return &pVal[0];
+ }
+
+ /// @}
+ /// @name Unary Operators
+ /// @{
+ /// @returns a new APInt value representing *this incremented by one
+ /// @brief Postfix increment operator.
+ const APInt operator++(int) {
+ APInt API(*this);
+ ++(*this);
+ return API;
+ }
+
+ /// @returns *this incremented by one
+ /// @brief Prefix increment operator.
+ APInt& operator++();
+
+ /// @returns a new APInt representing *this decremented by one.
+ /// @brief Postfix decrement operator.
+ const APInt operator--(int) {
+ APInt API(*this);
+ --(*this);
+ return API;
+ }
+
+ /// @returns *this decremented by one.
+ /// @brief Prefix decrement operator.
+ APInt& operator--();
+
+ /// Performs a bitwise complement operation on this APInt.
+ /// @returns an APInt that is the bitwise complement of *this
+ /// @brief Unary bitwise complement operator.
+ APInt operator~() const {
+ APInt Result(*this);
+ Result.flipAllBits();
+ return Result;
+ }
+
+ /// Negates *this using two's complement logic.
+ /// @returns An APInt value representing the negation of *this.
+ /// @brief Unary negation operator
+ APInt operator-() const {
+ return APInt(BitWidth, 0) - (*this);
+ }
+
+ /// Performs logical negation operation on this APInt.
+ /// @returns true if *this is zero, false otherwise.
+ /// @brief Logical negation operator.
+ bool operator!() const {
+ if (isSingleWord())
+ return !VAL;
+
+ for (unsigned i = 0; i != getNumWords(); ++i)
+ if (pVal[i])
+ return false;
+ return true;
+ }
+
+ /// @}
+ /// @name Assignment Operators
+ /// @{
+ /// @returns *this after assignment of RHS.
+ /// @brief Copy assignment operator.
+ APInt& operator=(const APInt& RHS) {
+ // If the bitwidths are the same, we can avoid mucking with memory
+ if (isSingleWord() && RHS.isSingleWord()) {
+ VAL = RHS.VAL;
+ BitWidth = RHS.BitWidth;
+ return clearUnusedBits();
+ }
+
+ return AssignSlowCase(RHS);
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ /// @brief Move assignment operator.
+ APInt& operator=(APInt&& that) {
+ if (!isSingleWord())
+ delete [] pVal;
+
+ BitWidth = that.BitWidth;
+ VAL = that.VAL;
+
+ that.BitWidth = 0;
+
+ return *this;
+ }
+#endif
+
+ /// The RHS value is assigned to *this. If the significant bits in RHS exceed
+ /// the bit width, the excess bits are truncated. If the bit width is larger
+ /// than 64, the value is zero filled in the unspecified high order bits.
+ /// @returns *this after assignment of RHS value.
+ /// @brief Assignment operator.
+ APInt& operator=(uint64_t RHS);
+
+ /// Performs a bitwise AND operation on this APInt and RHS. The result is
+ /// assigned to *this.
+ /// @returns *this after ANDing with RHS.
+ /// @brief Bitwise AND assignment operator.
+ APInt& operator&=(const APInt& RHS);
+
+ /// Performs a bitwise OR operation on this APInt and RHS. The result is
+ /// assigned *this;
+ /// @returns *this after ORing with RHS.
+ /// @brief Bitwise OR assignment operator.
+ APInt& operator|=(const APInt& RHS);
+
+ /// Performs a bitwise OR operation on this APInt and RHS. RHS is
+ /// logically zero-extended or truncated to match the bit-width of
+ /// the LHS.
+ ///
+ /// @brief Bitwise OR assignment operator.
+ APInt& operator|=(uint64_t RHS) {
+ if (isSingleWord()) {
+ VAL |= RHS;
+ clearUnusedBits();
+ } else {
+ pVal[0] |= RHS;
+ }
+ return *this;
+ }
+
+ /// Performs a bitwise XOR operation on this APInt and RHS. The result is
+ /// assigned to *this.
+ /// @returns *this after XORing with RHS.
+ /// @brief Bitwise XOR assignment operator.
+ APInt& operator^=(const APInt& RHS);
+
+ /// Multiplies this APInt by RHS and assigns the result to *this.
+ /// @returns *this
+ /// @brief Multiplication assignment operator.
+ APInt& operator*=(const APInt& RHS);
+
+ /// Adds RHS to *this and assigns the result to *this.
+ /// @returns *this
+ /// @brief Addition assignment operator.
+ APInt& operator+=(const APInt& RHS);
+
+ /// Subtracts RHS from *this and assigns the result to *this.
+ /// @returns *this
+ /// @brief Subtraction assignment operator.
+ APInt& operator-=(const APInt& RHS);
+
+ /// Shifts *this left by shiftAmt and assigns the result to *this.
+ /// @returns *this after shifting left by shiftAmt
+ /// @brief Left-shift assignment function.
+ APInt& operator<<=(unsigned shiftAmt) {
+ *this = shl(shiftAmt);
+ return *this;
+ }
+
+ /// @}
+ /// @name Binary Operators
+ /// @{
+ /// Performs a bitwise AND operation on *this and RHS.
+ /// @returns An APInt value representing the bitwise AND of *this and RHS.
+ /// @brief Bitwise AND operator.
+ APInt operator&(const APInt& RHS) const {
+ assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
+ if (isSingleWord())
+ return APInt(getBitWidth(), VAL & RHS.VAL);
+ return AndSlowCase(RHS);
+ }
+ APInt And(const APInt& RHS) const {
+ return this->operator&(RHS);
+ }
+
+ /// Performs a bitwise OR operation on *this and RHS.
+ /// @returns An APInt value representing the bitwise OR of *this and RHS.
+ /// @brief Bitwise OR operator.
+ APInt operator|(const APInt& RHS) const {
+ assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
+ if (isSingleWord())
+ return APInt(getBitWidth(), VAL | RHS.VAL);
+ return OrSlowCase(RHS);
+ }
+ APInt Or(const APInt& RHS) const {
+ return this->operator|(RHS);
+ }
+
+ /// Performs a bitwise XOR operation on *this and RHS.
+ /// @returns An APInt value representing the bitwise XOR of *this and RHS.
+ /// @brief Bitwise XOR operator.
+ APInt operator^(const APInt& RHS) const {
+ assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
+ if (isSingleWord())
+ return APInt(BitWidth, VAL ^ RHS.VAL);
+ return XorSlowCase(RHS);
+ }
+ APInt Xor(const APInt& RHS) const {
+ return this->operator^(RHS);
+ }
+
+ /// Multiplies this APInt by RHS and returns the result.
+ /// @brief Multiplication operator.
+ APInt operator*(const APInt& RHS) const;
+
+ /// Adds RHS to this APInt and returns the result.
+ /// @brief Addition operator.
+ APInt operator+(const APInt& RHS) const;
+ APInt operator+(uint64_t RHS) const {
+ return (*this) + APInt(BitWidth, RHS);
+ }
+
+ /// Subtracts RHS from this APInt and returns the result.
+ /// @brief Subtraction operator.
+ APInt operator-(const APInt& RHS) const;
+ APInt operator-(uint64_t RHS) const {
+ return (*this) - APInt(BitWidth, RHS);
+ }
+
+ APInt operator<<(unsigned Bits) const {
+ return shl(Bits);
+ }
+
+ APInt operator<<(const APInt &Bits) const {
+ return shl(Bits);
+ }
+
+ /// Arithmetic right-shift this APInt by shiftAmt.
+ /// @brief Arithmetic right-shift function.
+ APInt ashr(unsigned shiftAmt) const;
+
+ /// Logical right-shift this APInt by shiftAmt.
+ /// @brief Logical right-shift function.
+ APInt lshr(unsigned shiftAmt) const;
+
+ /// Left-shift this APInt by shiftAmt.
+ /// @brief Left-shift function.
+ APInt shl(unsigned shiftAmt) const {
+ assert(shiftAmt <= BitWidth && "Invalid shift amount");
+ if (isSingleWord()) {
+ if (shiftAmt == BitWidth)
+ return APInt(BitWidth, 0); // avoid undefined shift results
+ return APInt(BitWidth, VAL << shiftAmt);
+ }
+ return shlSlowCase(shiftAmt);
+ }
+
+ /// @brief Rotate left by rotateAmt.
+ APInt rotl(unsigned rotateAmt) const;
+
+ /// @brief Rotate right by rotateAmt.
+ APInt rotr(unsigned rotateAmt) const;
+
+ /// Arithmetic right-shift this APInt by shiftAmt.
+ /// @brief Arithmetic right-shift function.
+ APInt ashr(const APInt &shiftAmt) const;
+
+ /// Logical right-shift this APInt by shiftAmt.
+ /// @brief Logical right-shift function.
+ APInt lshr(const APInt &shiftAmt) const;
+
+ /// Left-shift this APInt by shiftAmt.
+ /// @brief Left-shift function.
+ APInt shl(const APInt &shiftAmt) const;
+
+ /// @brief Rotate left by rotateAmt.
+ APInt rotl(const APInt &rotateAmt) const;
+
+ /// @brief Rotate right by rotateAmt.
+ APInt rotr(const APInt &rotateAmt) const;
+
+ /// Perform an unsigned divide operation on this APInt by RHS. Both this and
+ /// RHS are treated as unsigned quantities for purposes of this division.
+ /// @returns a new APInt value containing the division result
+ /// @brief Unsigned division operation.
+ APInt udiv(const APInt &RHS) const;
+
+ /// Signed divide this APInt by APInt RHS.
+ /// @brief Signed division function for APInt.
+ APInt sdiv(const APInt &RHS) const {
+ if (isNegative())
+ if (RHS.isNegative())
+ return (-(*this)).udiv(-RHS);
+ else
+ return -((-(*this)).udiv(RHS));
+ else if (RHS.isNegative())
+ return -(this->udiv(-RHS));
+ return this->udiv(RHS);
+ }
+
+ /// Perform an unsigned remainder operation on this APInt with RHS being the
+ /// divisor. Both this and RHS are treated as unsigned quantities for purposes
+ /// of this operation. Note that this is a true remainder operation and not
+ /// a modulo operation because the sign follows the sign of the dividend
+ /// which is *this.
+ /// @returns a new APInt value containing the remainder result
+ /// @brief Unsigned remainder operation.
+ APInt urem(const APInt &RHS) const;
+
+ /// Signed remainder operation on APInt.
+ /// @brief Function for signed remainder operation.
+ APInt srem(const APInt &RHS) const {
+ if (isNegative())
+ if (RHS.isNegative())
+ return -((-(*this)).urem(-RHS));
+ else
+ return -((-(*this)).urem(RHS));
+ else if (RHS.isNegative())
+ return this->urem(-RHS);
+ return this->urem(RHS);
+ }
+
+ /// Sometimes it is convenient to divide two APInt values and obtain both the
+ /// quotient and remainder. This function does both operations in the same
+ /// computation making it a little more efficient. The pair of input arguments
+ /// may overlap with the pair of output arguments. It is safe to call
+ /// udivrem(X, Y, X, Y), for example.
+ /// @brief Dual division/remainder interface.
+ static void udivrem(const APInt &LHS, const APInt &RHS,
+ APInt &Quotient, APInt &Remainder);
+
+ static void sdivrem(const APInt &LHS, const APInt &RHS,
+ APInt &Quotient, APInt &Remainder) {
+ if (LHS.isNegative()) {
+ if (RHS.isNegative())
+ APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
+ else {
+ APInt::udivrem(-LHS, RHS, Quotient, Remainder);
+ Quotient = -Quotient;
+ }
+ Remainder = -Remainder;
+ } else if (RHS.isNegative()) {
+ APInt::udivrem(LHS, -RHS, Quotient, Remainder);
+ Quotient = -Quotient;
+ } else {
+ APInt::udivrem(LHS, RHS, Quotient, Remainder);
+ }
+ }
+
+
+ // Operations that return overflow indicators.
+ APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
+ APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
+ APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
+ APInt usub_ov(const APInt &RHS, bool &Overflow) const;
+ APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
+ APInt smul_ov(const APInt &RHS, bool &Overflow) const;
+ APInt umul_ov(const APInt &RHS, bool &Overflow) const;
+ APInt sshl_ov(unsigned Amt, bool &Overflow) const;
+
+ /// @returns the bit value at bitPosition
+ /// @brief Array-indexing support.
+ bool operator[](unsigned bitPosition) const {
+ assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
+ return (maskBit(bitPosition) &
+ (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
+ }
+
+ /// @}
+ /// @name Comparison Operators
+ /// @{
+ /// Compares this APInt with RHS for the validity of the equality
+ /// relationship.
+ /// @brief Equality operator.
+ bool operator==(const APInt& RHS) const {
+ assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
+ if (isSingleWord())
+ return VAL == RHS.VAL;
+ return EqualSlowCase(RHS);
+ }
+
+ /// Compares this APInt with a uint64_t for the validity of the equality
+ /// relationship.
+ /// @returns true if *this == Val
+ /// @brief Equality operator.
+ bool operator==(uint64_t Val) const {
+ if (isSingleWord())
+ return VAL == Val;
+ return EqualSlowCase(Val);
+ }
+
+ /// Compares this APInt with RHS for the validity of the equality
+ /// relationship.
+ /// @returns true if *this == Val
+ /// @brief Equality comparison.
+ bool eq(const APInt &RHS) const {
+ return (*this) == RHS;
+ }
+
+ /// Compares this APInt with RHS for the validity of the inequality
+ /// relationship.
+ /// @returns true if *this != Val
+ /// @brief Inequality operator.
+ bool operator!=(const APInt& RHS) const {
+ return !((*this) == RHS);
+ }
+
+ /// Compares this APInt with a uint64_t for the validity of the inequality
+ /// relationship.
+ /// @returns true if *this != Val
+ /// @brief Inequality operator.
+ bool operator!=(uint64_t Val) const {
+ return !((*this) == Val);
+ }
+
+ /// Compares this APInt with RHS for the validity of the inequality
+ /// relationship.
+ /// @returns true if *this != Val
+ /// @brief Inequality comparison
+ bool ne(const APInt &RHS) const {
+ return !((*this) == RHS);
+ }
+
+ /// Regards both *this and RHS as unsigned quantities and compares them for
+ /// the validity of the less-than relationship.
+ /// @returns true if *this < RHS when both are considered unsigned.
+ /// @brief Unsigned less than comparison
+ bool ult(const APInt &RHS) const;
+
+ /// Regards both *this as an unsigned quantity and compares it with RHS for
+ /// the validity of the less-than relationship.
+ /// @returns true if *this < RHS when considered unsigned.
+ /// @brief Unsigned less than comparison
+ bool ult(uint64_t RHS) const {
+ return ult(APInt(getBitWidth(), RHS));
+ }
+
+ /// Regards both *this and RHS as signed quantities and compares them for
+ /// validity of the less-than relationship.
+ /// @returns true if *this < RHS when both are considered signed.
+ /// @brief Signed less than comparison
+ bool slt(const APInt& RHS) const;
+
+ /// Regards both *this as a signed quantity and compares it with RHS for
+ /// the validity of the less-than relationship.
+ /// @returns true if *this < RHS when considered signed.
+ /// @brief Signed less than comparison
+ bool slt(uint64_t RHS) const {
+ return slt(APInt(getBitWidth(), RHS));
+ }
+
+ /// Regards both *this and RHS as unsigned quantities and compares them for
+ /// validity of the less-or-equal relationship.
+ /// @returns true if *this <= RHS when both are considered unsigned.
+ /// @brief Unsigned less or equal comparison
+ bool ule(const APInt& RHS) const {
+ return ult(RHS) || eq(RHS);
+ }
+
+ /// Regards both *this as an unsigned quantity and compares it with RHS for
+ /// the validity of the less-or-equal relationship.
+ /// @returns true if *this <= RHS when considered unsigned.
+ /// @brief Unsigned less or equal comparison
+ bool ule(uint64_t RHS) const {
+ return ule(APInt(getBitWidth(), RHS));
+ }
+
+ /// Regards both *this and RHS as signed quantities and compares them for
+ /// validity of the less-or-equal relationship.
+ /// @returns true if *this <= RHS when both are considered signed.
+ /// @brief Signed less or equal comparison
+ bool sle(const APInt& RHS) const {
+ return slt(RHS) || eq(RHS);
+ }
+
+ /// Regards both *this as a signed quantity and compares it with RHS for
+ /// the validity of the less-or-equal relationship.
+ /// @returns true if *this <= RHS when considered signed.
+ /// @brief Signed less or equal comparison
+ bool sle(uint64_t RHS) const {
+ return sle(APInt(getBitWidth(), RHS));
+ }
+
+ /// Regards both *this and RHS as unsigned quantities and compares them for
+ /// the validity of the greater-than relationship.
+ /// @returns true if *this > RHS when both are considered unsigned.
+ /// @brief Unsigned greather than comparison
+ bool ugt(const APInt& RHS) const {
+ return !ult(RHS) && !eq(RHS);
+ }
+
+ /// Regards both *this as an unsigned quantity and compares it with RHS for
+ /// the validity of the greater-than relationship.
+ /// @returns true if *this > RHS when considered unsigned.
+ /// @brief Unsigned greater than comparison
+ bool ugt(uint64_t RHS) const {
+ return ugt(APInt(getBitWidth(), RHS));
+ }
+
+ /// Regards both *this and RHS as signed quantities and compares them for
+ /// the validity of the greater-than relationship.
+ /// @returns true if *this > RHS when both are considered signed.
+ /// @brief Signed greather than comparison
+ bool sgt(const APInt& RHS) const {
+ return !slt(RHS) && !eq(RHS);
+ }
+
+ /// Regards both *this as a signed quantity and compares it with RHS for
+ /// the validity of the greater-than relationship.
+ /// @returns true if *this > RHS when considered signed.
+ /// @brief Signed greater than comparison
+ bool sgt(uint64_t RHS) const {
+ return sgt(APInt(getBitWidth(), RHS));
+ }
+
+ /// Regards both *this and RHS as unsigned quantities and compares them for
+ /// validity of the greater-or-equal relationship.
+ /// @returns true if *this >= RHS when both are considered unsigned.
+ /// @brief Unsigned greater or equal comparison
+ bool uge(const APInt& RHS) const {
+ return !ult(RHS);
+ }
+
+ /// Regards both *this as an unsigned quantity and compares it with RHS for
+ /// the validity of the greater-or-equal relationship.
+ /// @returns true if *this >= RHS when considered unsigned.
+ /// @brief Unsigned greater or equal comparison
+ bool uge(uint64_t RHS) const {
+ return uge(APInt(getBitWidth(), RHS));
+ }
+
+ /// Regards both *this and RHS as signed quantities and compares them for
+ /// validity of the greater-or-equal relationship.
+ /// @returns true if *this >= RHS when both are considered signed.
+ /// @brief Signed greather or equal comparison
+ bool sge(const APInt& RHS) const {
+ return !slt(RHS);
+ }
+
+ /// Regards both *this as a signed quantity and compares it with RHS for
+ /// the validity of the greater-or-equal relationship.
+ /// @returns true if *this >= RHS when considered signed.
+ /// @brief Signed greater or equal comparison
+ bool sge(uint64_t RHS) const {
+ return sge(APInt(getBitWidth(), RHS));
+ }
+
+
+
+
+ /// This operation tests if there are any pairs of corresponding bits
+ /// between this APInt and RHS that are both set.
+ bool intersects(const APInt &RHS) const {
+ return (*this & RHS) != 0;
+ }
+
+ /// @}
+ /// @name Resizing Operators
+ /// @{
+ /// Truncate the APInt to a specified width. It is an error to specify a width
+ /// that is greater than or equal to the current width.
+ /// @brief Truncate to new width.
+ APInt trunc(unsigned width) const;
+
+ /// This operation sign extends the APInt to a new width. If the high order
+ /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
+ /// It is an error to specify a width that is less than or equal to the
+ /// current width.
+ /// @brief Sign extend to a new width.
+ APInt sext(unsigned width) const;
+
+ /// This operation zero extends the APInt to a new width. The high order bits
+ /// are filled with 0 bits. It is an error to specify a width that is less
+ /// than or equal to the current width.
+ /// @brief Zero extend to a new width.
+ APInt zext(unsigned width) const;
+
+ /// Make this APInt have the bit width given by \p width. The value is sign
+ /// extended, truncated, or left alone to make it that width.
+ /// @brief Sign extend or truncate to width
+ APInt sextOrTrunc(unsigned width) const;
+
+ /// Make this APInt have the bit width given by \p width. The value is zero
+ /// extended, truncated, or left alone to make it that width.
+ /// @brief Zero extend or truncate to width
+ APInt zextOrTrunc(unsigned width) const;
+
+ /// Make this APInt have the bit width given by \p width. The value is sign
+ /// extended, or left alone to make it that width.
+ /// @brief Sign extend or truncate to width
+ APInt sextOrSelf(unsigned width) const;
+
+ /// Make this APInt have the bit width given by \p width. The value is zero
+ /// extended, or left alone to make it that width.
+ /// @brief Zero extend or truncate to width
+ APInt zextOrSelf(unsigned width) const;
+
+ /// @}
+ /// @name Bit Manipulation Operators
+ /// @{
+ /// @brief Set every bit to 1.
+ void setAllBits() {
+ if (isSingleWord())
+ VAL = -1ULL;
+ else {
+ // Set all the bits in all the words.
+ for (unsigned i = 0; i < getNumWords(); ++i)
+ pVal[i] = -1ULL;
+ }
+ // Clear the unused ones
+ clearUnusedBits();
+ }
+
+ /// Set the given bit to 1 whose position is given as "bitPosition".
+ /// @brief Set a given bit to 1.
+ void setBit(unsigned bitPosition);
+
+ /// @brief Set every bit to 0.
+ void clearAllBits() {
+ if (isSingleWord())
+ VAL = 0;
+ else
+ memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
+ }
+
+ /// Set the given bit to 0 whose position is given as "bitPosition".
+ /// @brief Set a given bit to 0.
+ void clearBit(unsigned bitPosition);
+
+ /// @brief Toggle every bit to its opposite value.
+ void flipAllBits() {
+ if (isSingleWord())
+ VAL ^= -1ULL;
+ else {
+ for (unsigned i = 0; i < getNumWords(); ++i)
+ pVal[i] ^= -1ULL;
+ }
+ clearUnusedBits();
+ }
+
+ /// Toggle a given bit to its opposite value whose position is given
+ /// as "bitPosition".
+ /// @brief Toggles a given bit to its opposite value.
+ void flipBit(unsigned bitPosition);
+
+ /// @}
+ /// @name Value Characterization Functions
+ /// @{
+
+ /// @returns the total number of bits.
+ unsigned getBitWidth() const {
+ return BitWidth;
+ }
+
+ /// Here one word's bitwidth equals to that of uint64_t.
+ /// @returns the number of words to hold the integer value of this APInt.
+ /// @brief Get the number of words.
+ unsigned getNumWords() const {
+ return getNumWords(BitWidth);
+ }
+
+ /// Here one word's bitwidth equals to that of uint64_t.
+ /// @returns the number of words to hold the integer value with a
+ /// given bit width.
+ /// @brief Get the number of words.
+ static unsigned getNumWords(unsigned BitWidth) {
+ return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
+ }
+
+ /// This function returns the number of active bits which is defined as the
+ /// bit width minus the number of leading zeros. This is used in several
+ /// computations to see how "wide" the value is.
+ /// @brief Compute the number of active bits in the value
+ unsigned getActiveBits() const {
+ return BitWidth - countLeadingZeros();
+ }
+
+ /// This function returns the number of active words in the value of this
+ /// APInt. This is used in conjunction with getActiveData to extract the raw
+ /// value of the APInt.
+ unsigned getActiveWords() const {
+ return whichWord(getActiveBits()-1) + 1;
+ }
+
+ /// Computes the minimum bit width for this APInt while considering it to be
+ /// a signed (and probably negative) value. If the value is not negative,
+ /// this function returns the same value as getActiveBits()+1. Otherwise, it
+ /// returns the smallest bit width that will retain the negative value. For
+ /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
+ /// for -1, this function will always return 1.
+ /// @brief Get the minimum bit size for this signed APInt
+ unsigned getMinSignedBits() const {
+ if (isNegative())
+ return BitWidth - countLeadingOnes() + 1;
+ return getActiveBits()+1;
+ }
+
+ /// This method attempts to return the value of this APInt as a zero extended
+ /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
+ /// uint64_t. Otherwise an assertion will result.
+ /// @brief Get zero extended value
+ uint64_t getZExtValue() const {
+ if (isSingleWord())
+ return VAL;
+ assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
+ return pVal[0];
+ }
+
+ /// This method attempts to return the value of this APInt as a sign extended
+ /// int64_t. The bit width must be <= 64 or the value must fit within an
+ /// int64_t. Otherwise an assertion will result.
+ /// @brief Get sign extended value
+ int64_t getSExtValue() const {
+ if (isSingleWord())
+ return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
+ (APINT_BITS_PER_WORD - BitWidth);
+ assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
+ return int64_t(pVal[0]);
+ }
+
+ /// This method determines how many bits are required to hold the APInt
+ /// equivalent of the string given by \p str.
+ /// @brief Get bits required for string value.
+ static unsigned getBitsNeeded(StringRef str, uint8_t radix);
+
+ /// countLeadingZeros - This function is an APInt version of the
+ /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
+ /// of zeros from the most significant bit to the first one bit.
+ /// @returns BitWidth if the value is zero, otherwise
+ /// returns the number of zeros from the most significant bit to the first
+ /// one bits.
+ unsigned countLeadingZeros() const {
+ if (isSingleWord()) {
+ unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
+ return CountLeadingZeros_64(VAL) - unusedBits;
+ }
+ return countLeadingZerosSlowCase();
+ }
+
+ /// countLeadingOnes - This function is an APInt version of the
+ /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
+ /// of ones from the most significant bit to the first zero bit.
+ /// @returns 0 if the high order bit is not set, otherwise
+ /// returns the number of 1 bits from the most significant to the least
+ /// @brief Count the number of leading one bits.
+ unsigned countLeadingOnes() const;
+
+ /// Computes the number of leading bits of this APInt that are equal to its
+ /// sign bit.
+ unsigned getNumSignBits() const {
+ return isNegative() ? countLeadingOnes() : countLeadingZeros();
+ }
+
+ /// countTrailingZeros - This function is an APInt version of the
+ /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
+ /// the number of zeros from the least significant bit to the first set bit.
+ /// @returns BitWidth if the value is zero, otherwise
+ /// returns the number of zeros from the least significant bit to the first
+ /// one bit.
+ /// @brief Count the number of trailing zero bits.
+ unsigned countTrailingZeros() const;
+
+ /// countTrailingOnes - This function is an APInt version of the
+ /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
+ /// the number of ones from the least significant bit to the first zero bit.
+ /// @returns BitWidth if the value is all ones, otherwise
+ /// returns the number of ones from the least significant bit to the first
+ /// zero bit.
+ /// @brief Count the number of trailing one bits.
+ unsigned countTrailingOnes() const {
+ if (isSingleWord())
+ return CountTrailingOnes_64(VAL);
+ return countTrailingOnesSlowCase();
+ }
+
+ /// countPopulation - This function is an APInt version of the
+ /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
+ /// of 1 bits in the APInt value.
+ /// @returns 0 if the value is zero, otherwise returns the number of set
+ /// bits.
+ /// @brief Count the number of bits set.
+ unsigned countPopulation() const {
+ if (isSingleWord())
+ return CountPopulation_64(VAL);
+ return countPopulationSlowCase();
+ }
+
+ /// @}
+ /// @name Conversion Functions
+ /// @{
+ void print(raw_ostream &OS, bool isSigned) const;
+
+ /// toString - Converts an APInt to a string and append it to Str. Str is
+ /// commonly a SmallString.
+ void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
+ bool formatAsCLiteral = false) const;
+
+ /// Considers the APInt to be unsigned and converts it into a string in the
+ /// radix given. The radix can be 2, 8, 10 16, or 36.
+ void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
+ toString(Str, Radix, false, false);
+ }
+
+ /// Considers the APInt to be signed and converts it into a string in the
+ /// radix given. The radix can be 2, 8, 10, 16, or 36.
+ void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
+ toString(Str, Radix, true, false);
+ }
+
+ /// toString - This returns the APInt as a std::string. Note that this is an
+ /// inefficient method. It is better to pass in a SmallVector/SmallString
+ /// to the methods above to avoid thrashing the heap for the string.
+ std::string toString(unsigned Radix, bool Signed) const;
+
+
+ /// @returns a byte-swapped representation of this APInt Value.
+ APInt byteSwap() const;
+
+ /// @brief Converts this APInt to a double value.
+ double roundToDouble(bool isSigned) const;
+
+ /// @brief Converts this unsigned APInt to a double value.
+ double roundToDouble() const {
+ return roundToDouble(false);
+ }
+
+ /// @brief Converts this signed APInt to a double value.
+ double signedRoundToDouble() const {
+ return roundToDouble(true);
+ }
+
+ /// The conversion does not do a translation from integer to double, it just
+ /// re-interprets the bits as a double. Note that it is valid to do this on
+ /// any bit width. Exactly 64 bits will be translated.
+ /// @brief Converts APInt bits to a double
+ double bitsToDouble() const {
+ union {
+ uint64_t I;
+ double D;
+ } T;
+ T.I = (isSingleWord() ? VAL : pVal[0]);
+ return T.D;
+ }
+
+ /// The conversion does not do a translation from integer to float, it just
+ /// re-interprets the bits as a float. Note that it is valid to do this on
+ /// any bit width. Exactly 32 bits will be translated.
+ /// @brief Converts APInt bits to a double
+ float bitsToFloat() const {
+ union {
+ unsigned I;
+ float F;
+ } T;
+ T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
+ return T.F;
+ }
+
+ /// The conversion does not do a translation from double to integer, it just
+ /// re-interprets the bits of the double.
+ /// @brief Converts a double to APInt bits.
+ static APInt doubleToBits(double V) {
+ union {
+ uint64_t I;
+ double D;
+ } T;
+ T.D = V;
+ return APInt(sizeof T * CHAR_BIT, T.I);
+ }
+
+ /// The conversion does not do a translation from float to integer, it just
+ /// re-interprets the bits of the float.
+ /// @brief Converts a float to APInt bits.
+ static APInt floatToBits(float V) {
+ union {
+ unsigned I;
+ float F;
+ } T;
+ T.F = V;
+ return APInt(sizeof T * CHAR_BIT, T.I);
+ }
+
+ /// @}
+ /// @name Mathematics Operations
+ /// @{
+
+ /// @returns the floor log base 2 of this APInt.
+ unsigned logBase2() const {
+ return BitWidth - 1 - countLeadingZeros();
+ }
+
+ /// @returns the ceil log base 2 of this APInt.
+ unsigned ceilLogBase2() const {
+ return BitWidth - (*this - 1).countLeadingZeros();
+ }
+
+ /// @returns the log base 2 of this APInt if its an exact power of two, -1
+ /// otherwise
+ int32_t exactLogBase2() const {
+ if (!isPowerOf2())
+ return -1;
+ return logBase2();
+ }
+
+ /// @brief Compute the square root
+ APInt sqrt() const;
+
+ /// If *this is < 0 then return -(*this), otherwise *this;
+ /// @brief Get the absolute value;
+ APInt abs() const {
+ if (isNegative())
+ return -(*this);
+ return *this;
+ }
+
+ /// @returns the multiplicative inverse for a given modulo.
+ APInt multiplicativeInverse(const APInt& modulo) const;
+
+ /// @}
+ /// @name Support for division by constant
+ /// @{
+
+ /// Calculate the magic number for signed division by a constant.
+ struct ms;
+ ms magic() const;
+
+ /// Calculate the magic number for unsigned division by a constant.
+ struct mu;
+ mu magicu(unsigned LeadingZeros = 0) const;
+
+ /// @}
+ /// @name Building-block Operations for APInt and APFloat
+ /// @{
+
+ // These building block operations operate on a representation of
+ // arbitrary precision, two's-complement, bignum integer values.
+ // They should be sufficient to implement APInt and APFloat bignum
+ // requirements. Inputs are generally a pointer to the base of an
+ // array of integer parts, representing an unsigned bignum, and a
+ // count of how many parts there are.
+
+ /// Sets the least significant part of a bignum to the input value,
+ /// and zeroes out higher parts. */
+ static void tcSet(integerPart *, integerPart, unsigned int);
+
+ /// Assign one bignum to another.
+ static void tcAssign(integerPart *, const integerPart *, unsigned int);
+
+ /// Returns true if a bignum is zero, false otherwise.
+ static bool tcIsZero(const integerPart *, unsigned int);
+
+ /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
+ static int tcExtractBit(const integerPart *, unsigned int bit);
+
+ /// Copy the bit vector of width srcBITS from SRC, starting at bit
+ /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
+ /// becomes the least significant bit of DST. All high bits above
+ /// srcBITS in DST are zero-filled.
+ static void tcExtract(integerPart *, unsigned int dstCount,
+ const integerPart *,
+ unsigned int srcBits, unsigned int srcLSB);
+
+ /// Set the given bit of a bignum. Zero-based.
+ static void tcSetBit(integerPart *, unsigned int bit);
+
+ /// Clear the given bit of a bignum. Zero-based.
+ static void tcClearBit(integerPart *, unsigned int bit);
+
+ /// Returns the bit number of the least or most significant set bit
+ /// of a number. If the input number has no bits set -1U is
+ /// returned.
+ static unsigned int tcLSB(const integerPart *, unsigned int);
+ static unsigned int tcMSB(const integerPart *parts, unsigned int n);
+
+ /// Negate a bignum in-place.
+ static void tcNegate(integerPart *, unsigned int);
+
+ /// DST += RHS + CARRY where CARRY is zero or one. Returns the
+ /// carry flag.
+ static integerPart tcAdd(integerPart *, const integerPart *,
+ integerPart carry, unsigned);
+
+ /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
+ /// carry flag.
+ static integerPart tcSubtract(integerPart *, const integerPart *,
+ integerPart carry, unsigned);
+
+ /// DST += SRC * MULTIPLIER + PART if add is true
+ /// DST = SRC * MULTIPLIER + PART if add is false
+ ///
+ /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
+ /// they must start at the same point, i.e. DST == SRC.
+ ///
+ /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
+ /// returned. Otherwise DST is filled with the least significant
+ /// DSTPARTS parts of the result, and if all of the omitted higher
+ /// parts were zero return zero, otherwise overflow occurred and
+ /// return one.
+ static int tcMultiplyPart(integerPart *dst, const integerPart *src,
+ integerPart multiplier, integerPart carry,
+ unsigned int srcParts, unsigned int dstParts,
+ bool add);
+
+ /// DST = LHS * RHS, where DST has the same width as the operands
+ /// and is filled with the least significant parts of the result.
+ /// Returns one if overflow occurred, otherwise zero. DST must be
+ /// disjoint from both operands.
+ static int tcMultiply(integerPart *, const integerPart *,
+ const integerPart *, unsigned);
+
+ /// DST = LHS * RHS, where DST has width the sum of the widths of
+ /// the operands. No overflow occurs. DST must be disjoint from
+ /// both operands. Returns the number of parts required to hold the
+ /// result.
+ static unsigned int tcFullMultiply(integerPart *, const integerPart *,
+ const integerPart *, unsigned, unsigned);
+
+ /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
+ /// Otherwise set LHS to LHS / RHS with the fractional part
+ /// discarded, set REMAINDER to the remainder, return zero. i.e.
+ ///
+ /// OLD_LHS = RHS * LHS + REMAINDER
+ ///
+ /// SCRATCH is a bignum of the same size as the operands and result
+ /// for use by the routine; its contents need not be initialized
+ /// and are destroyed. LHS, REMAINDER and SCRATCH must be
+ /// distinct.
+ static int tcDivide(integerPart *lhs, const integerPart *rhs,
+ integerPart *remainder, integerPart *scratch,
+ unsigned int parts);
+
+ /// Shift a bignum left COUNT bits. Shifted in bits are zero.
+ /// There are no restrictions on COUNT.
+ static void tcShiftLeft(integerPart *, unsigned int parts,
+ unsigned int count);
+
+ /// Shift a bignum right COUNT bits. Shifted in bits are zero.
+ /// There are no restrictions on COUNT.
+ static void tcShiftRight(integerPart *, unsigned int parts,
+ unsigned int count);
+
+ /// The obvious AND, OR and XOR and complement operations.
+ static void tcAnd(integerPart *, const integerPart *, unsigned int);
+ static void tcOr(integerPart *, const integerPart *, unsigned int);
+ static void tcXor(integerPart *, const integerPart *, unsigned int);
+ static void tcComplement(integerPart *, unsigned int);
+
+ /// Comparison (unsigned) of two bignums.
+ static int tcCompare(const integerPart *, const integerPart *,
+ unsigned int);
+
+ /// Increment a bignum in-place. Return the carry flag.
+ static integerPart tcIncrement(integerPart *, unsigned int);
+
+ /// Set the least significant BITS and clear the rest.
+ static void tcSetLeastSignificantBits(integerPart *, unsigned int,
+ unsigned int bits);
+
+ /// @brief debug method
+ void dump() const;
+
+ /// @}
+};
+
+/// Magic data for optimising signed division by a constant.
+struct APInt::ms {
+ APInt m; ///< magic number
+ unsigned s; ///< shift amount
+};
+
+/// Magic data for optimising unsigned division by a constant.
+struct APInt::mu {
+ APInt m; ///< magic number
+ bool a; ///< add indicator
+ unsigned s; ///< shift amount
+};
+
+inline bool operator==(uint64_t V1, const APInt& V2) {
+ return V2 == V1;
+}
+
+inline bool operator!=(uint64_t V1, const APInt& V2) {
+ return V2 != V1;
+}
+
+inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
+ I.print(OS, true);
+ return OS;
+}
+
+namespace APIntOps {
+
+/// @brief Determine the smaller of two APInts considered to be signed.
+inline APInt smin(const APInt &A, const APInt &B) {
+ return A.slt(B) ? A : B;
+}
+
+/// @brief Determine the larger of two APInts considered to be signed.
+inline APInt smax(const APInt &A, const APInt &B) {
+ return A.sgt(B) ? A : B;
+}
+
+/// @brief Determine the smaller of two APInts considered to be signed.
+inline APInt umin(const APInt &A, const APInt &B) {
+ return A.ult(B) ? A : B;
+}
+
+/// @brief Determine the larger of two APInts considered to be unsigned.
+inline APInt umax(const APInt &A, const APInt &B) {
+ return A.ugt(B) ? A : B;
+}
+
+/// @brief Check if the specified APInt has a N-bits unsigned integer value.
+inline bool isIntN(unsigned N, const APInt& APIVal) {
+ return APIVal.isIntN(N);
+}
+
+/// @brief Check if the specified APInt has a N-bits signed integer value.
+inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
+ return APIVal.isSignedIntN(N);
+}
+
+/// @returns true if the argument APInt value is a sequence of ones
+/// starting at the least significant bit with the remainder zero.
+inline bool isMask(unsigned numBits, const APInt& APIVal) {
+ return numBits <= APIVal.getBitWidth() &&
+ APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
+}
+
+/// @returns true if the argument APInt value contains a sequence of ones
+/// with the remainder zero.
+inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
+ return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
+}
+
+/// @returns a byte-swapped representation of the specified APInt Value.
+inline APInt byteSwap(const APInt& APIVal) {
+ return APIVal.byteSwap();
+}
+
+/// @returns the floor log base 2 of the specified APInt value.
+inline unsigned logBase2(const APInt& APIVal) {
+ return APIVal.logBase2();
+}
+
+/// GreatestCommonDivisor - This function returns the greatest common
+/// divisor of the two APInt values using Euclid's algorithm.
+/// @returns the greatest common divisor of Val1 and Val2
+/// @brief Compute GCD of two APInt values.
+APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
+
+/// Treats the APInt as an unsigned value for conversion purposes.
+/// @brief Converts the given APInt to a double value.
+inline double RoundAPIntToDouble(const APInt& APIVal) {
+ return APIVal.roundToDouble();
+}
+
+/// Treats the APInt as a signed value for conversion purposes.
+/// @brief Converts the given APInt to a double value.
+inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
+ return APIVal.signedRoundToDouble();
+}
+
+/// @brief Converts the given APInt to a float vlalue.
+inline float RoundAPIntToFloat(const APInt& APIVal) {
+ return float(RoundAPIntToDouble(APIVal));
+}
+
+/// Treast the APInt as a signed value for conversion purposes.
+/// @brief Converts the given APInt to a float value.
+inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
+ return float(APIVal.signedRoundToDouble());
+}
+
+/// RoundDoubleToAPInt - This function convert a double value to an APInt value.
+/// @brief Converts the given double value into a APInt.
+APInt RoundDoubleToAPInt(double Double, unsigned width);
+
+/// RoundFloatToAPInt - Converts a float value into an APInt value.
+/// @brief Converts a float value into a APInt.
+inline APInt RoundFloatToAPInt(float Float, unsigned width) {
+ return RoundDoubleToAPInt(double(Float), width);
+}
+
+/// Arithmetic right-shift the APInt by shiftAmt.
+/// @brief Arithmetic right-shift function.
+inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
+ return LHS.ashr(shiftAmt);
+}
+
+/// Logical right-shift the APInt by shiftAmt.
+/// @brief Logical right-shift function.
+inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
+ return LHS.lshr(shiftAmt);
+}
+
+/// Left-shift the APInt by shiftAmt.
+/// @brief Left-shift function.
+inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
+ return LHS.shl(shiftAmt);
+}
+
+/// Signed divide APInt LHS by APInt RHS.
+/// @brief Signed division function for APInt.
+inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
+ return LHS.sdiv(RHS);
+}
+
+/// Unsigned divide APInt LHS by APInt RHS.
+/// @brief Unsigned division function for APInt.
+inline APInt udiv(const APInt& LHS, const APInt& RHS) {
+ return LHS.udiv(RHS);
+}
+
+/// Signed remainder operation on APInt.
+/// @brief Function for signed remainder operation.
+inline APInt srem(const APInt& LHS, const APInt& RHS) {
+ return LHS.srem(RHS);
+}
+
+/// Unsigned remainder operation on APInt.
+/// @brief Function for unsigned remainder operation.
+inline APInt urem(const APInt& LHS, const APInt& RHS) {
+ return LHS.urem(RHS);
+}
+
+/// Performs multiplication on APInt values.
+/// @brief Function for multiplication operation.
+inline APInt mul(const APInt& LHS, const APInt& RHS) {
+ return LHS * RHS;
+}
+
+/// Performs addition on APInt values.
+/// @brief Function for addition operation.
+inline APInt add(const APInt& LHS, const APInt& RHS) {
+ return LHS + RHS;
+}
+
+/// Performs subtraction on APInt values.
+/// @brief Function for subtraction operation.
+inline APInt sub(const APInt& LHS, const APInt& RHS) {
+ return LHS - RHS;
+}
+
+/// Performs bitwise AND operation on APInt LHS and
+/// APInt RHS.
+/// @brief Bitwise AND function for APInt.
+inline APInt And(const APInt& LHS, const APInt& RHS) {
+ return LHS & RHS;
+}
+
+/// Performs bitwise OR operation on APInt LHS and APInt RHS.
+/// @brief Bitwise OR function for APInt.
+inline APInt Or(const APInt& LHS, const APInt& RHS) {
+ return LHS | RHS;
+}
+
+/// Performs bitwise XOR operation on APInt.
+/// @brief Bitwise XOR function for APInt.
+inline APInt Xor(const APInt& LHS, const APInt& RHS) {
+ return LHS ^ RHS;
+}
+
+/// Performs a bitwise complement operation on APInt.
+/// @brief Bitwise complement function.
+inline APInt Not(const APInt& APIVal) {
+ return ~APIVal;
+}
+
+} // End of APIntOps namespace
+
+} // End of llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/APSInt.h b/include/llvm/ADT/APSInt.h
new file mode 100644
index 00000000000..048c65ce2c7
--- /dev/null
+++ b/include/llvm/ADT/APSInt.h
@@ -0,0 +1,312 @@
+//===-- llvm/ADT/APSInt.h - Arbitrary Precision Signed Int -----*- C++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the APSInt class, which is a simple class that
+// represents an arbitrary sized integer that knows its signedness.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_APSINT_H
+#define LLVM_APSINT_H
+
+#include "llvm/ADT/APInt.h"
+
+namespace llvm {
+
+class APSInt : public APInt {
+ bool IsUnsigned;
+public:
+ /// Default constructor that creates an uninitialized APInt.
+ explicit APSInt() {}
+
+ /// APSInt ctor - Create an APSInt with the specified width, default to
+ /// unsigned.
+ explicit APSInt(uint32_t BitWidth, bool isUnsigned = true)
+ : APInt(BitWidth, 0), IsUnsigned(isUnsigned) {}
+
+ explicit APSInt(const APInt &I, bool isUnsigned = true)
+ : APInt(I), IsUnsigned(isUnsigned) {}
+
+ APSInt &operator=(const APSInt &RHS) {
+ APInt::operator=(RHS);
+ IsUnsigned = RHS.IsUnsigned;
+ return *this;
+ }
+
+ APSInt &operator=(const APInt &RHS) {
+ // Retain our current sign.
+ APInt::operator=(RHS);
+ return *this;
+ }
+
+ APSInt &operator=(uint64_t RHS) {
+ // Retain our current sign.
+ APInt::operator=(RHS);
+ return *this;
+ }
+
+ // Query sign information.
+ bool isSigned() const { return !IsUnsigned; }
+ bool isUnsigned() const { return IsUnsigned; }
+ void setIsUnsigned(bool Val) { IsUnsigned = Val; }
+ void setIsSigned(bool Val) { IsUnsigned = !Val; }
+
+ /// toString - Append this APSInt to the specified SmallString.
+ void toString(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
+ APInt::toString(Str, Radix, isSigned());
+ }
+ /// toString - Converts an APInt to a std::string. This is an inefficient
+ /// method, your should prefer passing in a SmallString instead.
+ std::string toString(unsigned Radix) const {
+ return APInt::toString(Radix, isSigned());
+ }
+ using APInt::toString;
+
+ APSInt trunc(uint32_t width) const {
+ return APSInt(APInt::trunc(width), IsUnsigned);
+ }
+
+ APSInt extend(uint32_t width) const {
+ if (IsUnsigned)
+ return APSInt(zext(width), IsUnsigned);
+ else
+ return APSInt(sext(width), IsUnsigned);
+ }
+
+ APSInt extOrTrunc(uint32_t width) const {
+ if (IsUnsigned)
+ return APSInt(zextOrTrunc(width), IsUnsigned);
+ else
+ return APSInt(sextOrTrunc(width), IsUnsigned);
+ }
+
+ const APSInt &operator%=(const APSInt &RHS) {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ if (IsUnsigned)
+ *this = urem(RHS);
+ else
+ *this = srem(RHS);
+ return *this;
+ }
+ const APSInt &operator/=(const APSInt &RHS) {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ if (IsUnsigned)
+ *this = udiv(RHS);
+ else
+ *this = sdiv(RHS);
+ return *this;
+ }
+ APSInt operator%(const APSInt &RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return IsUnsigned ? APSInt(urem(RHS), true) : APSInt(srem(RHS), false);
+ }
+ APSInt operator/(const APSInt &RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return IsUnsigned ? APSInt(udiv(RHS), true) : APSInt(sdiv(RHS), false);
+ }
+
+ APSInt operator>>(unsigned Amt) const {
+ return IsUnsigned ? APSInt(lshr(Amt), true) : APSInt(ashr(Amt), false);
+ }
+ APSInt& operator>>=(unsigned Amt) {
+ *this = *this >> Amt;
+ return *this;
+ }
+
+ inline bool operator<(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return IsUnsigned ? ult(RHS) : slt(RHS);
+ }
+ inline bool operator>(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return IsUnsigned ? ugt(RHS) : sgt(RHS);
+ }
+ inline bool operator<=(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return IsUnsigned ? ule(RHS) : sle(RHS);
+ }
+ inline bool operator>=(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return IsUnsigned ? uge(RHS) : sge(RHS);
+ }
+ inline bool operator==(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return eq(RHS);
+ }
+ inline bool operator==(int64_t RHS) const {
+ return isSameValue(*this, APSInt(APInt(64, RHS), true));
+ }
+ inline bool operator!=(const APSInt& RHS) const {
+ return !((*this) == RHS);
+ }
+ inline bool operator!=(int64_t RHS) const {
+ return !((*this) == RHS);
+ }
+
+ // The remaining operators just wrap the logic of APInt, but retain the
+ // signedness information.
+
+ APSInt operator<<(unsigned Bits) const {
+ return APSInt(static_cast<const APInt&>(*this) << Bits, IsUnsigned);
+ }
+ APSInt& operator<<=(unsigned Amt) {
+ *this = *this << Amt;
+ return *this;
+ }
+
+ APSInt& operator++() {
+ static_cast<APInt&>(*this)++;
+ return *this;
+ }
+ APSInt& operator--() {
+ static_cast<APInt&>(*this)--;
+ return *this;
+ }
+ APSInt operator++(int) {
+ return APSInt(++static_cast<APInt&>(*this), IsUnsigned);
+ }
+ APSInt operator--(int) {
+ return APSInt(--static_cast<APInt&>(*this), IsUnsigned);
+ }
+ APSInt operator-() const {
+ return APSInt(-static_cast<const APInt&>(*this), IsUnsigned);
+ }
+ APSInt& operator+=(const APSInt& RHS) {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ static_cast<APInt&>(*this) += RHS;
+ return *this;
+ }
+ APSInt& operator-=(const APSInt& RHS) {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ static_cast<APInt&>(*this) -= RHS;
+ return *this;
+ }
+ APSInt& operator*=(const APSInt& RHS) {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ static_cast<APInt&>(*this) *= RHS;
+ return *this;
+ }
+ APSInt& operator&=(const APSInt& RHS) {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ static_cast<APInt&>(*this) &= RHS;
+ return *this;
+ }
+ APSInt& operator|=(const APSInt& RHS) {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ static_cast<APInt&>(*this) |= RHS;
+ return *this;
+ }
+ APSInt& operator^=(const APSInt& RHS) {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ static_cast<APInt&>(*this) ^= RHS;
+ return *this;
+ }
+
+ APSInt operator&(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return APSInt(static_cast<const APInt&>(*this) & RHS, IsUnsigned);
+ }
+ APSInt And(const APSInt& RHS) const {
+ return this->operator&(RHS);
+ }
+
+ APSInt operator|(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return APSInt(static_cast<const APInt&>(*this) | RHS, IsUnsigned);
+ }
+ APSInt Or(const APSInt& RHS) const {
+ return this->operator|(RHS);
+ }
+
+
+ APSInt operator^(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return APSInt(static_cast<const APInt&>(*this) ^ RHS, IsUnsigned);
+ }
+ APSInt Xor(const APSInt& RHS) const {
+ return this->operator^(RHS);
+ }
+
+ APSInt operator*(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return APSInt(static_cast<const APInt&>(*this) * RHS, IsUnsigned);
+ }
+ APSInt operator+(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return APSInt(static_cast<const APInt&>(*this) + RHS, IsUnsigned);
+ }
+ APSInt operator-(const APSInt& RHS) const {
+ assert(IsUnsigned == RHS.IsUnsigned && "Signedness mismatch!");
+ return APSInt(static_cast<const APInt&>(*this) - RHS, IsUnsigned);
+ }
+ APSInt operator~() const {
+ return APSInt(~static_cast<const APInt&>(*this), IsUnsigned);
+ }
+
+ /// getMaxValue - Return the APSInt representing the maximum integer value
+ /// with the given bit width and signedness.
+ static APSInt getMaxValue(uint32_t numBits, bool Unsigned) {
+ return APSInt(Unsigned ? APInt::getMaxValue(numBits)
+ : APInt::getSignedMaxValue(numBits), Unsigned);
+ }
+
+ /// getMinValue - Return the APSInt representing the minimum integer value
+ /// with the given bit width and signedness.
+ static APSInt getMinValue(uint32_t numBits, bool Unsigned) {
+ return APSInt(Unsigned ? APInt::getMinValue(numBits)
+ : APInt::getSignedMinValue(numBits), Unsigned);
+ }
+
+ /// \brief Determine if two APSInts have the same value, zero- or
+ /// sign-extending as needed.
+ static bool isSameValue(const APSInt &I1, const APSInt &I2) {
+ if (I1.getBitWidth() == I2.getBitWidth() && I1.isSigned() == I2.isSigned())
+ return I1 == I2;
+
+ // Check for a bit-width mismatch.
+ if (I1.getBitWidth() > I2.getBitWidth())
+ return isSameValue(I1, I2.extend(I1.getBitWidth()));
+ else if (I2.getBitWidth() > I1.getBitWidth())
+ return isSameValue(I1.extend(I2.getBitWidth()), I2);
+
+ // We have a signedness mismatch. Turn the signed value into an unsigned
+ // value.
+ if (I1.isSigned()) {
+ if (I1.isNegative())
+ return false;
+
+ return APSInt(I1, true) == I2;
+ }
+
+ if (I2.isNegative())
+ return false;
+
+ return I1 == APSInt(I2, true);
+ }
+
+ /// Profile - Used to insert APSInt objects, or objects that contain APSInt
+ /// objects, into FoldingSets.
+ void Profile(FoldingSetNodeID& ID) const;
+};
+
+inline bool operator==(int64_t V1, const APSInt& V2) {
+ return V2 == V1;
+}
+inline bool operator!=(int64_t V1, const APSInt& V2) {
+ return V2 != V1;
+}
+
+inline raw_ostream &operator<<(raw_ostream &OS, const APSInt &I) {
+ I.print(OS, I.isSigned());
+ return OS;
+}
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/ArrayRef.h b/include/llvm/ADT/ArrayRef.h
new file mode 100644
index 00000000000..1e35d627921
--- /dev/null
+++ b/include/llvm/ADT/ArrayRef.h
@@ -0,0 +1,305 @@
+//===--- ArrayRef.h - Array Reference Wrapper -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_ARRAYREF_H
+#define LLVM_ADT_ARRAYREF_H
+
+#include "llvm/ADT/SmallVector.h"
+#include <vector>
+
+namespace llvm {
+
+ /// ArrayRef - Represent a constant reference to an array (0 or more elements
+ /// consecutively in memory), i.e. a start pointer and a length. It allows
+ /// various APIs to take consecutive elements easily and conveniently.
+ ///
+ /// This class does not own the underlying data, it is expected to be used in
+ /// situations where the data resides in some other buffer, whose lifetime
+ /// extends past that of the ArrayRef. For this reason, it is not in general
+ /// safe to store an ArrayRef.
+ ///
+ /// This is intended to be trivially copyable, so it should be passed by
+ /// value.
+ template<typename T>
+ class ArrayRef {
+ public:
+ typedef const T *iterator;
+ typedef const T *const_iterator;
+ typedef size_t size_type;
+
+ private:
+ /// The start of the array, in an external buffer.
+ const T *Data;
+
+ /// The number of elements.
+ size_type Length;
+
+ public:
+ /// @name Constructors
+ /// @{
+
+ /// Construct an empty ArrayRef.
+ /*implicit*/ ArrayRef() : Data(0), Length(0) {}
+
+ /// Construct an ArrayRef from a single element.
+ /*implicit*/ ArrayRef(const T &OneElt)
+ : Data(&OneElt), Length(1) {}
+
+ /// Construct an ArrayRef from a pointer and length.
+ /*implicit*/ ArrayRef(const T *data, size_t length)
+ : Data(data), Length(length) {}
+
+ /// Construct an ArrayRef from a range.
+ ArrayRef(const T *begin, const T *end)
+ : Data(begin), Length(end - begin) {}
+
+ /// Construct an ArrayRef from a SmallVector. This is templated in order to
+ /// avoid instantiating SmallVectorTemplateCommon<T> whenever we
+ /// copy-construct an ArrayRef.
+ template<typename U>
+ /*implicit*/ ArrayRef(const SmallVectorTemplateCommon<T, U> &Vec)
+ : Data(Vec.data()), Length(Vec.size()) {
+ }
+
+ /// Construct an ArrayRef from a std::vector.
+ template<typename A>
+ /*implicit*/ ArrayRef(const std::vector<T, A> &Vec)
+ : Data(Vec.empty() ? (T*)0 : &Vec[0]), Length(Vec.size()) {}
+
+ /// Construct an ArrayRef from a C array.
+ template <size_t N>
+ /*implicit*/ ArrayRef(const T (&Arr)[N])
+ : Data(Arr), Length(N) {}
+
+ /// @}
+ /// @name Simple Operations
+ /// @{
+
+ iterator begin() const { return Data; }
+ iterator end() const { return Data + Length; }
+
+ /// empty - Check if the array is empty.
+ bool empty() const { return Length == 0; }
+
+ const T *data() const { return Data; }
+
+ /// size - Get the array size.
+ size_t size() const { return Length; }
+
+ /// front - Get the first element.
+ const T &front() const {
+ assert(!empty());
+ return Data[0];
+ }
+
+ /// back - Get the last element.
+ const T &back() const {
+ assert(!empty());
+ return Data[Length-1];
+ }
+
+ /// equals - Check for element-wise equality.
+ bool equals(ArrayRef RHS) const {
+ if (Length != RHS.Length)
+ return false;
+ for (size_type i = 0; i != Length; i++)
+ if (Data[i] != RHS.Data[i])
+ return false;
+ return true;
+ }
+
+ /// slice(n) - Chop off the first N elements of the array.
+ ArrayRef<T> slice(unsigned N) const {
+ assert(N <= size() && "Invalid specifier");
+ return ArrayRef<T>(data()+N, size()-N);
+ }
+
+ /// slice(n, m) - Chop off the first N elements of the array, and keep M
+ /// elements in the array.
+ ArrayRef<T> slice(unsigned N, unsigned M) const {
+ assert(N+M <= size() && "Invalid specifier");
+ return ArrayRef<T>(data()+N, M);
+ }
+
+ /// @}
+ /// @name Operator Overloads
+ /// @{
+ const T &operator[](size_t Index) const {
+ assert(Index < Length && "Invalid index!");
+ return Data[Index];
+ }
+
+ /// @}
+ /// @name Expensive Operations
+ /// @{
+ std::vector<T> vec() const {
+ return std::vector<T>(Data, Data+Length);
+ }
+
+ /// @}
+ /// @name Conversion operators
+ /// @{
+ operator std::vector<T>() const {
+ return std::vector<T>(Data, Data+Length);
+ }
+
+ /// @}
+ };
+
+ /// MutableArrayRef - Represent a mutable reference to an array (0 or more
+ /// elements consecutively in memory), i.e. a start pointer and a length. It
+ /// allows various APIs to take and modify consecutive elements easily and
+ /// conveniently.
+ ///
+ /// This class does not own the underlying data, it is expected to be used in
+ /// situations where the data resides in some other buffer, whose lifetime
+ /// extends past that of the MutableArrayRef. For this reason, it is not in
+ /// general safe to store a MutableArrayRef.
+ ///
+ /// This is intended to be trivially copyable, so it should be passed by
+ /// value.
+ template<typename T>
+ class MutableArrayRef : public ArrayRef<T> {
+ public:
+ typedef T *iterator;
+
+ /// Construct an empty ArrayRef.
+ /*implicit*/ MutableArrayRef() : ArrayRef<T>() {}
+
+ /// Construct an MutableArrayRef from a single element.
+ /*implicit*/ MutableArrayRef(T &OneElt) : ArrayRef<T>(OneElt) {}
+
+ /// Construct an MutableArrayRef from a pointer and length.
+ /*implicit*/ MutableArrayRef(T *data, size_t length)
+ : ArrayRef<T>(data, length) {}
+
+ /// Construct an MutableArrayRef from a range.
+ MutableArrayRef(T *begin, T *end) : ArrayRef<T>(begin, end) {}
+
+ /// Construct an MutableArrayRef from a SmallVector.
+ /*implicit*/ MutableArrayRef(SmallVectorImpl<T> &Vec)
+ : ArrayRef<T>(Vec) {}
+
+ /// Construct a MutableArrayRef from a std::vector.
+ /*implicit*/ MutableArrayRef(std::vector<T> &Vec)
+ : ArrayRef<T>(Vec) {}
+
+ /// Construct an MutableArrayRef from a C array.
+ template <size_t N>
+ /*implicit*/ MutableArrayRef(T (&Arr)[N])
+ : ArrayRef<T>(Arr) {}
+
+ T *data() const { return const_cast<T*>(ArrayRef<T>::data()); }
+
+ iterator begin() const { return data(); }
+ iterator end() const { return data() + this->size(); }
+
+ /// front - Get the first element.
+ T &front() const {
+ assert(!this->empty());
+ return data()[0];
+ }
+
+ /// back - Get the last element.
+ T &back() const {
+ assert(!this->empty());
+ return data()[this->size()-1];
+ }
+
+ /// slice(n) - Chop off the first N elements of the array.
+ MutableArrayRef<T> slice(unsigned N) const {
+ assert(N <= this->size() && "Invalid specifier");
+ return MutableArrayRef<T>(data()+N, this->size()-N);
+ }
+
+ /// slice(n, m) - Chop off the first N elements of the array, and keep M
+ /// elements in the array.
+ MutableArrayRef<T> slice(unsigned N, unsigned M) const {
+ assert(N+M <= this->size() && "Invalid specifier");
+ return MutableArrayRef<T>(data()+N, M);
+ }
+
+ /// @}
+ /// @name Operator Overloads
+ /// @{
+ T &operator[](size_t Index) const {
+ assert(Index < this->size() && "Invalid index!");
+ return data()[Index];
+ }
+ };
+
+ /// @name ArrayRef Convenience constructors
+ /// @{
+
+ /// Construct an ArrayRef from a single element.
+ template<typename T>
+ ArrayRef<T> makeArrayRef(const T &OneElt) {
+ return OneElt;
+ }
+
+ /// Construct an ArrayRef from a pointer and length.
+ template<typename T>
+ ArrayRef<T> makeArrayRef(const T *data, size_t length) {
+ return ArrayRef<T>(data, length);
+ }
+
+ /// Construct an ArrayRef from a range.
+ template<typename T>
+ ArrayRef<T> makeArrayRef(const T *begin, const T *end) {
+ return ArrayRef<T>(begin, end);
+ }
+
+ /// Construct an ArrayRef from a SmallVector.
+ template <typename T>
+ ArrayRef<T> makeArrayRef(const SmallVectorImpl<T> &Vec) {
+ return Vec;
+ }
+
+ /// Construct an ArrayRef from a SmallVector.
+ template <typename T, unsigned N>
+ ArrayRef<T> makeArrayRef(const SmallVector<T, N> &Vec) {
+ return Vec;
+ }
+
+ /// Construct an ArrayRef from a std::vector.
+ template<typename T>
+ ArrayRef<T> makeArrayRef(const std::vector<T> &Vec) {
+ return Vec;
+ }
+
+ /// Construct an ArrayRef from a C array.
+ template<typename T, size_t N>
+ ArrayRef<T> makeArrayRef(const T (&Arr)[N]) {
+ return ArrayRef<T>(Arr);
+ }
+
+ /// @}
+ /// @name ArrayRef Comparison Operators
+ /// @{
+
+ template<typename T>
+ inline bool operator==(ArrayRef<T> LHS, ArrayRef<T> RHS) {
+ return LHS.equals(RHS);
+ }
+
+ template<typename T>
+ inline bool operator!=(ArrayRef<T> LHS, ArrayRef<T> RHS) {
+ return !(LHS == RHS);
+ }
+
+ /// @}
+
+ // ArrayRefs can be treated like a POD type.
+ template <typename T> struct isPodLike;
+ template <typename T> struct isPodLike<ArrayRef<T> > {
+ static const bool value = true;
+ };
+}
+
+#endif
diff --git a/include/llvm/ADT/BitVector.h b/include/llvm/ADT/BitVector.h
new file mode 100644
index 00000000000..26ec346b182
--- /dev/null
+++ b/include/llvm/ADT/BitVector.h
@@ -0,0 +1,533 @@
+//===- llvm/ADT/BitVector.h - Bit vectors -----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the BitVector class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_BITVECTOR_H
+#define LLVM_ADT_BITVECTOR_H
+
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
+#include <algorithm>
+#include <cassert>
+#include <climits>
+#include <cstdlib>
+
+namespace llvm {
+
+class BitVector {
+ typedef unsigned long BitWord;
+
+ enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
+
+ BitWord *Bits; // Actual bits.
+ unsigned Size; // Size of bitvector in bits.
+ unsigned Capacity; // Size of allocated memory in BitWord.
+
+public:
+ // Encapsulation of a single bit.
+ class reference {
+ friend class BitVector;
+
+ BitWord *WordRef;
+ unsigned BitPos;
+
+ reference(); // Undefined
+
+ public:
+ reference(BitVector &b, unsigned Idx) {
+ WordRef = &b.Bits[Idx / BITWORD_SIZE];
+ BitPos = Idx % BITWORD_SIZE;
+ }
+
+ ~reference() {}
+
+ reference &operator=(reference t) {
+ *this = bool(t);
+ return *this;
+ }
+
+ reference& operator=(bool t) {
+ if (t)
+ *WordRef |= 1L << BitPos;
+ else
+ *WordRef &= ~(1L << BitPos);
+ return *this;
+ }
+
+ operator bool() const {
+ return ((*WordRef) & (1L << BitPos)) ? true : false;
+ }
+ };
+
+
+ /// BitVector default ctor - Creates an empty bitvector.
+ BitVector() : Size(0), Capacity(0) {
+ Bits = 0;
+ }
+
+ /// BitVector ctor - Creates a bitvector of specified number of bits. All
+ /// bits are initialized to the specified value.
+ explicit BitVector(unsigned s, bool t = false) : Size(s) {
+ Capacity = NumBitWords(s);
+ Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
+ init_words(Bits, Capacity, t);
+ if (t)
+ clear_unused_bits();
+ }
+
+ /// BitVector copy ctor.
+ BitVector(const BitVector &RHS) : Size(RHS.size()) {
+ if (Size == 0) {
+ Bits = 0;
+ Capacity = 0;
+ return;
+ }
+
+ Capacity = NumBitWords(RHS.size());
+ Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
+ std::memcpy(Bits, RHS.Bits, Capacity * sizeof(BitWord));
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ BitVector(BitVector &&RHS)
+ : Bits(RHS.Bits), Size(RHS.Size), Capacity(RHS.Capacity) {
+ RHS.Bits = 0;
+ }
+#endif
+
+ ~BitVector() {
+ std::free(Bits);
+ }
+
+ /// empty - Tests whether there are no bits in this bitvector.
+ bool empty() const { return Size == 0; }
+
+ /// size - Returns the number of bits in this bitvector.
+ unsigned size() const { return Size; }
+
+ /// count - Returns the number of bits which are set.
+ unsigned count() const {
+ unsigned NumBits = 0;
+ for (unsigned i = 0; i < NumBitWords(size()); ++i)
+ if (sizeof(BitWord) == 4)
+ NumBits += CountPopulation_32((uint32_t)Bits[i]);
+ else if (sizeof(BitWord) == 8)
+ NumBits += CountPopulation_64(Bits[i]);
+ else
+ llvm_unreachable("Unsupported!");
+ return NumBits;
+ }
+
+ /// any - Returns true if any bit is set.
+ bool any() const {
+ for (unsigned i = 0; i < NumBitWords(size()); ++i)
+ if (Bits[i] != 0)
+ return true;
+ return false;
+ }
+
+ /// all - Returns true if all bits are set.
+ bool all() const {
+ // TODO: Optimize this.
+ return count() == size();
+ }
+
+ /// none - Returns true if none of the bits are set.
+ bool none() const {
+ return !any();
+ }
+
+ /// find_first - Returns the index of the first set bit, -1 if none
+ /// of the bits are set.
+ int find_first() const {
+ for (unsigned i = 0; i < NumBitWords(size()); ++i)
+ if (Bits[i] != 0) {
+ if (sizeof(BitWord) == 4)
+ return i * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Bits[i]);
+ if (sizeof(BitWord) == 8)
+ return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
+ llvm_unreachable("Unsupported!");
+ }
+ return -1;
+ }
+
+ /// find_next - Returns the index of the next set bit following the
+ /// "Prev" bit. Returns -1 if the next set bit is not found.
+ int find_next(unsigned Prev) const {
+ ++Prev;
+ if (Prev >= Size)
+ return -1;
+
+ unsigned WordPos = Prev / BITWORD_SIZE;
+ unsigned BitPos = Prev % BITWORD_SIZE;
+ BitWord Copy = Bits[WordPos];
+ // Mask off previous bits.
+ Copy &= ~0UL << BitPos;
+
+ if (Copy != 0) {
+ if (sizeof(BitWord) == 4)
+ return WordPos * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Copy);
+ if (sizeof(BitWord) == 8)
+ return WordPos * BITWORD_SIZE + CountTrailingZeros_64(Copy);
+ llvm_unreachable("Unsupported!");
+ }
+
+ // Check subsequent words.
+ for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
+ if (Bits[i] != 0) {
+ if (sizeof(BitWord) == 4)
+ return i * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Bits[i]);
+ if (sizeof(BitWord) == 8)
+ return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
+ llvm_unreachable("Unsupported!");
+ }
+ return -1;
+ }
+
+ /// clear - Clear all bits.
+ void clear() {
+ Size = 0;
+ }
+
+ /// resize - Grow or shrink the bitvector.
+ void resize(unsigned N, bool t = false) {
+ if (N > Capacity * BITWORD_SIZE) {
+ unsigned OldCapacity = Capacity;
+ grow(N);
+ init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
+ }
+
+ // Set any old unused bits that are now included in the BitVector. This
+ // may set bits that are not included in the new vector, but we will clear
+ // them back out below.
+ if (N > Size)
+ set_unused_bits(t);
+
+ // Update the size, and clear out any bits that are now unused
+ unsigned OldSize = Size;
+ Size = N;
+ if (t || N < OldSize)
+ clear_unused_bits();
+ }
+
+ void reserve(unsigned N) {
+ if (N > Capacity * BITWORD_SIZE)
+ grow(N);
+ }
+
+ // Set, reset, flip
+ BitVector &set() {
+ init_words(Bits, Capacity, true);
+ clear_unused_bits();
+ return *this;
+ }
+
+ BitVector &set(unsigned Idx) {
+ Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
+ return *this;
+ }
+
+ BitVector &reset() {
+ init_words(Bits, Capacity, false);
+ return *this;
+ }
+
+ BitVector &reset(unsigned Idx) {
+ Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
+ return *this;
+ }
+
+ BitVector &flip() {
+ for (unsigned i = 0; i < NumBitWords(size()); ++i)
+ Bits[i] = ~Bits[i];
+ clear_unused_bits();
+ return *this;
+ }
+
+ BitVector &flip(unsigned Idx) {
+ Bits[Idx / BITWORD_SIZE] ^= 1L << (Idx % BITWORD_SIZE);
+ return *this;
+ }
+
+ // Indexing.
+ reference operator[](unsigned Idx) {
+ assert (Idx < Size && "Out-of-bounds Bit access.");
+ return reference(*this, Idx);
+ }
+
+ bool operator[](unsigned Idx) const {
+ assert (Idx < Size && "Out-of-bounds Bit access.");
+ BitWord Mask = 1L << (Idx % BITWORD_SIZE);
+ return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
+ }
+
+ bool test(unsigned Idx) const {
+ return (*this)[Idx];
+ }
+
+ /// Test if any common bits are set.
+ bool anyCommon(const BitVector &RHS) const {
+ unsigned ThisWords = NumBitWords(size());
+ unsigned RHSWords = NumBitWords(RHS.size());
+ for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
+ if (Bits[i] & RHS.Bits[i])
+ return true;
+ return false;
+ }
+
+ // Comparison operators.
+ bool operator==(const BitVector &RHS) const {
+ unsigned ThisWords = NumBitWords(size());
+ unsigned RHSWords = NumBitWords(RHS.size());
+ unsigned i;
+ for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
+ if (Bits[i] != RHS.Bits[i])
+ return false;
+
+ // Verify that any extra words are all zeros.
+ if (i != ThisWords) {
+ for (; i != ThisWords; ++i)
+ if (Bits[i])
+ return false;
+ } else if (i != RHSWords) {
+ for (; i != RHSWords; ++i)
+ if (RHS.Bits[i])
+ return false;
+ }
+ return true;
+ }
+
+ bool operator!=(const BitVector &RHS) const {
+ return !(*this == RHS);
+ }
+
+ /// Intersection, union, disjoint union.
+ BitVector &operator&=(const BitVector &RHS) {
+ unsigned ThisWords = NumBitWords(size());
+ unsigned RHSWords = NumBitWords(RHS.size());
+ unsigned i;
+ for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
+ Bits[i] &= RHS.Bits[i];
+
+ // Any bits that are just in this bitvector become zero, because they aren't
+ // in the RHS bit vector. Any words only in RHS are ignored because they
+ // are already zero in the LHS.
+ for (; i != ThisWords; ++i)
+ Bits[i] = 0;
+
+ return *this;
+ }
+
+ /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
+ BitVector &reset(const BitVector &RHS) {
+ unsigned ThisWords = NumBitWords(size());
+ unsigned RHSWords = NumBitWords(RHS.size());
+ unsigned i;
+ for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
+ Bits[i] &= ~RHS.Bits[i];
+ return *this;
+ }
+
+ /// test - Check if (This - RHS) is zero.
+ /// This is the same as reset(RHS) and any().
+ bool test(const BitVector &RHS) const {
+ unsigned ThisWords = NumBitWords(size());
+ unsigned RHSWords = NumBitWords(RHS.size());
+ unsigned i;
+ for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
+ if ((Bits[i] & ~RHS.Bits[i]) != 0)
+ return true;
+
+ for (; i != ThisWords ; ++i)
+ if (Bits[i] != 0)
+ return true;
+
+ return false;
+ }
+
+ BitVector &operator|=(const BitVector &RHS) {
+ if (size() < RHS.size())
+ resize(RHS.size());
+ for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
+ Bits[i] |= RHS.Bits[i];
+ return *this;
+ }
+
+ BitVector &operator^=(const BitVector &RHS) {
+ if (size() < RHS.size())
+ resize(RHS.size());
+ for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
+ Bits[i] ^= RHS.Bits[i];
+ return *this;
+ }
+
+ // Assignment operator.
+ const BitVector &operator=(const BitVector &RHS) {
+ if (this == &RHS) return *this;
+
+ Size = RHS.size();
+ unsigned RHSWords = NumBitWords(Size);
+ if (Size <= Capacity * BITWORD_SIZE) {
+ if (Size)
+ std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord));
+ clear_unused_bits();
+ return *this;
+ }
+
+ // Grow the bitvector to have enough elements.
+ Capacity = RHSWords;
+ BitWord *NewBits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
+ std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord));
+
+ // Destroy the old bits.
+ std::free(Bits);
+ Bits = NewBits;
+
+ return *this;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ const BitVector &operator=(BitVector &&RHS) {
+ if (this == &RHS) return *this;
+
+ std::free(Bits);
+ Bits = RHS.Bits;
+ Size = RHS.Size;
+ Capacity = RHS.Capacity;
+
+ RHS.Bits = 0;
+
+ return *this;
+ }
+#endif
+
+ void swap(BitVector &RHS) {
+ std::swap(Bits, RHS.Bits);
+ std::swap(Size, RHS.Size);
+ std::swap(Capacity, RHS.Capacity);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Portable bit mask operations.
+ //===--------------------------------------------------------------------===//
+ //
+ // These methods all operate on arrays of uint32_t, each holding 32 bits. The
+ // fixed word size makes it easier to work with literal bit vector constants
+ // in portable code.
+ //
+ // The LSB in each word is the lowest numbered bit. The size of a portable
+ // bit mask is always a whole multiple of 32 bits. If no bit mask size is
+ // given, the bit mask is assumed to cover the entire BitVector.
+
+ /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
+ /// This computes "*this |= Mask".
+ void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
+ applyMask<true, false>(Mask, MaskWords);
+ }
+
+ /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
+ /// Don't resize. This computes "*this &= ~Mask".
+ void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
+ applyMask<false, false>(Mask, MaskWords);
+ }
+
+ /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
+ /// Don't resize. This computes "*this |= ~Mask".
+ void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
+ applyMask<true, true>(Mask, MaskWords);
+ }
+
+ /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
+ /// Don't resize. This computes "*this &= Mask".
+ void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
+ applyMask<false, true>(Mask, MaskWords);
+ }
+
+private:
+ unsigned NumBitWords(unsigned S) const {
+ return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
+ }
+
+ // Set the unused bits in the high words.
+ void set_unused_bits(bool t = true) {
+ // Set high words first.
+ unsigned UsedWords = NumBitWords(Size);
+ if (Capacity > UsedWords)
+ init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
+
+ // Then set any stray high bits of the last used word.
+ unsigned ExtraBits = Size % BITWORD_SIZE;
+ if (ExtraBits) {
+ BitWord ExtraBitMask = ~0UL << ExtraBits;
+ if (t)
+ Bits[UsedWords-1] |= ExtraBitMask;
+ else
+ Bits[UsedWords-1] &= ~ExtraBitMask;
+ }
+ }
+
+ // Clear the unused bits in the high words.
+ void clear_unused_bits() {
+ set_unused_bits(false);
+ }
+
+ void grow(unsigned NewSize) {
+ Capacity = std::max(NumBitWords(NewSize), Capacity * 2);
+ Bits = (BitWord *)std::realloc(Bits, Capacity * sizeof(BitWord));
+
+ clear_unused_bits();
+ }
+
+ void init_words(BitWord *B, unsigned NumWords, bool t) {
+ memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
+ }
+
+ template<bool AddBits, bool InvertMask>
+ void applyMask(const uint32_t *Mask, unsigned MaskWords) {
+ assert(BITWORD_SIZE % 32 == 0 && "Unsupported BitWord size.");
+ MaskWords = std::min(MaskWords, (size() + 31) / 32);
+ const unsigned Scale = BITWORD_SIZE / 32;
+ unsigned i;
+ for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
+ BitWord BW = Bits[i];
+ // This inner loop should unroll completely when BITWORD_SIZE > 32.
+ for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
+ uint32_t M = *Mask++;
+ if (InvertMask) M = ~M;
+ if (AddBits) BW |= BitWord(M) << b;
+ else BW &= ~(BitWord(M) << b);
+ }
+ Bits[i] = BW;
+ }
+ for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
+ uint32_t M = *Mask++;
+ if (InvertMask) M = ~M;
+ if (AddBits) Bits[i] |= BitWord(M) << b;
+ else Bits[i] &= ~(BitWord(M) << b);
+ }
+ if (AddBits)
+ clear_unused_bits();
+ }
+};
+
+} // End llvm namespace
+
+namespace std {
+ /// Implement std::swap in terms of BitVector swap.
+ inline void
+ swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {
+ LHS.swap(RHS);
+ }
+}
+
+#endif
diff --git a/include/llvm/ADT/DAGDeltaAlgorithm.h b/include/llvm/ADT/DAGDeltaAlgorithm.h
new file mode 100644
index 00000000000..2dfed075dea
--- /dev/null
+++ b/include/llvm/ADT/DAGDeltaAlgorithm.h
@@ -0,0 +1,77 @@
+//===--- DAGDeltaAlgorithm.h - A DAG Minimization Algorithm ----*- C++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_DAGDELTAALGORITHM_H
+#define LLVM_ADT_DAGDELTAALGORITHM_H
+
+#include <vector>
+#include <set>
+
+namespace llvm {
+
+/// DAGDeltaAlgorithm - Implements a "delta debugging" algorithm for minimizing
+/// directed acyclic graphs using a predicate function.
+///
+/// The result of the algorithm is a subset of the input change set which is
+/// guaranteed to satisfy the predicate, assuming that the input set did. For
+/// well formed predicates, the result set is guaranteed to be such that
+/// removing any single element not required by the dependencies on the other
+/// elements would falsify the predicate.
+///
+/// The DAG should be used to represent dependencies in the changes which are
+/// likely to hold across the predicate function. That is, for a particular
+/// changeset S and predicate P:
+///
+/// P(S) => P(S union pred(S))
+///
+/// The minization algorithm uses this dependency information to attempt to
+/// eagerly prune large subsets of changes. As with \see DeltaAlgorithm, the DAG
+/// is not required to satisfy this property, but the algorithm will run
+/// substantially fewer tests with appropriate dependencies. \see DeltaAlgorithm
+/// for more information on the properties which the predicate function itself
+/// should satisfy.
+class DAGDeltaAlgorithm {
+ virtual void anchor();
+public:
+ typedef unsigned change_ty;
+ typedef std::pair<change_ty, change_ty> edge_ty;
+
+ // FIXME: Use a decent data structure.
+ typedef std::set<change_ty> changeset_ty;
+ typedef std::vector<changeset_ty> changesetlist_ty;
+
+public:
+ virtual ~DAGDeltaAlgorithm() {}
+
+ /// Run - Minimize the DAG formed by the \p Changes vertices and the
+ /// \p Dependencies edges by executing \see ExecuteOneTest() on subsets of
+ /// changes and returning the smallest set which still satisfies the test
+ /// predicate and the input \p Dependencies.
+ ///
+ /// \param Changes The list of changes.
+ ///
+ /// \param Dependencies The list of dependencies amongst changes. For each
+ /// (x,y) in \p Dependencies, both x and y must be in \p Changes. The
+ /// minimization algorithm guarantees that for each tested changed set S,
+ /// \f$ x \in S \f$ implies \f$ y \in S \f$. It is an error to have cyclic
+ /// dependencies.
+ changeset_ty Run(const changeset_ty &Changes,
+ const std::vector<edge_ty> &Dependencies);
+
+ /// UpdatedSearchState - Callback used when the search state changes.
+ virtual void UpdatedSearchState(const changeset_ty &Changes,
+ const changesetlist_ty &Sets,
+ const changeset_ty &Required) {}
+
+ /// ExecuteOneTest - Execute a single test predicate on the change set \p S.
+ virtual bool ExecuteOneTest(const changeset_ty &S) = 0;
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/DeltaAlgorithm.h b/include/llvm/ADT/DeltaAlgorithm.h
new file mode 100644
index 00000000000..7bf7960c63a
--- /dev/null
+++ b/include/llvm/ADT/DeltaAlgorithm.h
@@ -0,0 +1,91 @@
+//===--- DeltaAlgorithm.h - A Set Minimization Algorithm -------*- C++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_DELTAALGORITHM_H
+#define LLVM_ADT_DELTAALGORITHM_H
+
+#include <vector>
+#include <set>
+
+namespace llvm {
+
+/// DeltaAlgorithm - Implements the delta debugging algorithm (A. Zeller '99)
+/// for minimizing arbitrary sets using a predicate function.
+///
+/// The result of the algorithm is a subset of the input change set which is
+/// guaranteed to satisfy the predicate, assuming that the input set did. For
+/// well formed predicates, the result set is guaranteed to be such that
+/// removing any single element would falsify the predicate.
+///
+/// For best results the predicate function *should* (but need not) satisfy
+/// certain properties, in particular:
+/// (1) The predicate should return false on an empty set and true on the full
+/// set.
+/// (2) If the predicate returns true for a set of changes, it should return
+/// true for all supersets of that set.
+///
+/// It is not an error to provide a predicate that does not satisfy these
+/// requirements, and the algorithm will generally produce reasonable
+/// results. However, it may run substantially more tests than with a good
+/// predicate.
+class DeltaAlgorithm {
+public:
+ typedef unsigned change_ty;
+ // FIXME: Use a decent data structure.
+ typedef std::set<change_ty> changeset_ty;
+ typedef std::vector<changeset_ty> changesetlist_ty;
+
+private:
+ /// Cache of failed test results. Successful test results are never cached
+ /// since we always reduce following a success.
+ std::set<changeset_ty> FailedTestsCache;
+
+ /// GetTestResult - Get the test result for the \p Changes from the
+ /// cache, executing the test if necessary.
+ ///
+ /// \param Changes - The change set to test.
+ /// \return - The test result.
+ bool GetTestResult(const changeset_ty &Changes);
+
+ /// Split - Partition a set of changes \p S into one or two subsets.
+ void Split(const changeset_ty &S, changesetlist_ty &Res);
+
+ /// Delta - Minimize a set of \p Changes which has been partioned into
+ /// smaller sets, by attempting to remove individual subsets.
+ changeset_ty Delta(const changeset_ty &Changes,
+ const changesetlist_ty &Sets);
+
+ /// Search - Search for a subset (or subsets) in \p Sets which can be
+ /// removed from \p Changes while still satisfying the predicate.
+ ///
+ /// \param Res - On success, a subset of Changes which satisfies the
+ /// predicate.
+ /// \return - True on success.
+ bool Search(const changeset_ty &Changes, const changesetlist_ty &Sets,
+ changeset_ty &Res);
+
+protected:
+ /// UpdatedSearchState - Callback used when the search state changes.
+ virtual void UpdatedSearchState(const changeset_ty &Changes,
+ const changesetlist_ty &Sets) {}
+
+ /// ExecuteOneTest - Execute a single test predicate on the change set \p S.
+ virtual bool ExecuteOneTest(const changeset_ty &S) = 0;
+
+public:
+ virtual ~DeltaAlgorithm();
+
+ /// Run - Minimize the set \p Changes by executing \see ExecuteOneTest() on
+ /// subsets of changes and returning the smallest set which still satisfies
+ /// the test predicate.
+ changeset_ty Run(const changeset_ty &Changes);
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/DenseMap.h b/include/llvm/ADT/DenseMap.h
new file mode 100644
index 00000000000..f60d688c0dc
--- /dev/null
+++ b/include/llvm/ADT/DenseMap.h
@@ -0,0 +1,1038 @@
+//===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the DenseMap class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_DENSEMAP_H
+#define LLVM_ADT_DENSEMAP_H
+
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/AlignOf.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/PointerLikeTypeTraits.h"
+#include "llvm/Support/type_traits.h"
+#include "llvm/ADT/DenseMapInfo.h"
+#include <algorithm>
+#include <iterator>
+#include <new>
+#include <utility>
+#include <cassert>
+#include <climits>
+#include <cstddef>
+#include <cstring>
+
+namespace llvm {
+
+template<typename KeyT, typename ValueT,
+ typename KeyInfoT = DenseMapInfo<KeyT>,
+ bool IsConst = false>
+class DenseMapIterator;
+
+template<typename DerivedT,
+ typename KeyT, typename ValueT, typename KeyInfoT>
+class DenseMapBase {
+protected:
+ typedef std::pair<KeyT, ValueT> BucketT;
+
+public:
+ typedef KeyT key_type;
+ typedef ValueT mapped_type;
+ typedef BucketT value_type;
+
+ typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
+ typedef DenseMapIterator<KeyT, ValueT,
+ KeyInfoT, true> const_iterator;
+ inline iterator begin() {
+ // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
+ return empty() ? end() : iterator(getBuckets(), getBucketsEnd());
+ }
+ inline iterator end() {
+ return iterator(getBucketsEnd(), getBucketsEnd(), true);
+ }
+ inline const_iterator begin() const {
+ return empty() ? end() : const_iterator(getBuckets(), getBucketsEnd());
+ }
+ inline const_iterator end() const {
+ return const_iterator(getBucketsEnd(), getBucketsEnd(), true);
+ }
+
+ bool empty() const { return getNumEntries() == 0; }
+ unsigned size() const { return getNumEntries(); }
+
+ /// Grow the densemap so that it has at least Size buckets. Does not shrink
+ void resize(size_t Size) {
+ if (Size > getNumBuckets())
+ grow(Size);
+ }
+
+ void clear() {
+ if (getNumEntries() == 0 && getNumTombstones() == 0) return;
+
+ // If the capacity of the array is huge, and the # elements used is small,
+ // shrink the array.
+ if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
+ shrink_and_clear();
+ return;
+ }
+
+ const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
+ for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
+ if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
+ if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
+ P->second.~ValueT();
+ decrementNumEntries();
+ }
+ P->first = EmptyKey;
+ }
+ }
+ assert(getNumEntries() == 0 && "Node count imbalance!");
+ setNumTombstones(0);
+ }
+
+ /// count - Return true if the specified key is in the map.
+ bool count(const KeyT &Val) const {
+ const BucketT *TheBucket;
+ return LookupBucketFor(Val, TheBucket);
+ }
+
+ iterator find(const KeyT &Val) {
+ BucketT *TheBucket;
+ if (LookupBucketFor(Val, TheBucket))
+ return iterator(TheBucket, getBucketsEnd(), true);
+ return end();
+ }
+ const_iterator find(const KeyT &Val) const {
+ const BucketT *TheBucket;
+ if (LookupBucketFor(Val, TheBucket))
+ return const_iterator(TheBucket, getBucketsEnd(), true);
+ return end();
+ }
+
+ /// Alternate version of find() which allows a different, and possibly
+ /// less expensive, key type.
+ /// The DenseMapInfo is responsible for supplying methods
+ /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
+ /// type used.
+ template<class LookupKeyT>
+ iterator find_as(const LookupKeyT &Val) {
+ BucketT *TheBucket;
+ if (LookupBucketFor(Val, TheBucket))
+ return iterator(TheBucket, getBucketsEnd(), true);
+ return end();
+ }
+ template<class LookupKeyT>
+ const_iterator find_as(const LookupKeyT &Val) const {
+ const BucketT *TheBucket;
+ if (LookupBucketFor(Val, TheBucket))
+ return const_iterator(TheBucket, getBucketsEnd(), true);
+ return end();
+ }
+
+ /// lookup - Return the entry for the specified key, or a default
+ /// constructed value if no such entry exists.
+ ValueT lookup(const KeyT &Val) const {
+ const BucketT *TheBucket;
+ if (LookupBucketFor(Val, TheBucket))
+ return TheBucket->second;
+ return ValueT();
+ }
+
+ // Inserts key,value pair into the map if the key isn't already in the map.
+ // If the key is already in the map, it returns false and doesn't update the
+ // value.
+ std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
+ BucketT *TheBucket;
+ if (LookupBucketFor(KV.first, TheBucket))
+ return std::make_pair(iterator(TheBucket, getBucketsEnd(), true),
+ false); // Already in map.
+
+ // Otherwise, insert the new element.
+ TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
+ return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true);
+ }
+
+ /// insert - Range insertion of pairs.
+ template<typename InputIt>
+ void insert(InputIt I, InputIt E) {
+ for (; I != E; ++I)
+ insert(*I);
+ }
+
+
+ bool erase(const KeyT &Val) {
+ BucketT *TheBucket;
+ if (!LookupBucketFor(Val, TheBucket))
+ return false; // not in map.
+
+ TheBucket->second.~ValueT();
+ TheBucket->first = getTombstoneKey();
+ decrementNumEntries();
+ incrementNumTombstones();
+ return true;
+ }
+ void erase(iterator I) {
+ BucketT *TheBucket = &*I;
+ TheBucket->second.~ValueT();
+ TheBucket->first = getTombstoneKey();
+ decrementNumEntries();
+ incrementNumTombstones();
+ }
+
+ value_type& FindAndConstruct(const KeyT &Key) {
+ BucketT *TheBucket;
+ if (LookupBucketFor(Key, TheBucket))
+ return *TheBucket;
+
+ return *InsertIntoBucket(Key, ValueT(), TheBucket);
+ }
+
+ ValueT &operator[](const KeyT &Key) {
+ return FindAndConstruct(Key).second;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ value_type& FindAndConstruct(KeyT &&Key) {
+ BucketT *TheBucket;
+ if (LookupBucketFor(Key, TheBucket))
+ return *TheBucket;
+
+ return *InsertIntoBucket(Key, ValueT(), TheBucket);
+ }
+
+ ValueT &operator[](KeyT &&Key) {
+ return FindAndConstruct(Key).second;
+ }
+#endif
+
+ /// isPointerIntoBucketsArray - Return true if the specified pointer points
+ /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
+ /// value in the DenseMap).
+ bool isPointerIntoBucketsArray(const void *Ptr) const {
+ return Ptr >= getBuckets() && Ptr < getBucketsEnd();
+ }
+
+ /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
+ /// array. In conjunction with the previous method, this can be used to
+ /// determine whether an insertion caused the DenseMap to reallocate.
+ const void *getPointerIntoBucketsArray() const { return getBuckets(); }
+
+protected:
+ DenseMapBase() {}
+
+ void destroyAll() {
+ if (getNumBuckets() == 0) // Nothing to do.
+ return;
+
+ const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
+ for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
+ if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
+ !KeyInfoT::isEqual(P->first, TombstoneKey))
+ P->second.~ValueT();
+ P->first.~KeyT();
+ }
+
+#ifndef NDEBUG
+ memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
+#endif
+ }
+
+ void initEmpty() {
+ setNumEntries(0);
+ setNumTombstones(0);
+
+ assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
+ "# initial buckets must be a power of two!");
+ const KeyT EmptyKey = getEmptyKey();
+ for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
+ new (&B->first) KeyT(EmptyKey);
+ }
+
+ void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
+ initEmpty();
+
+ // Insert all the old elements.
+ const KeyT EmptyKey = getEmptyKey();
+ const KeyT TombstoneKey = getTombstoneKey();
+ for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
+ if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
+ !KeyInfoT::isEqual(B->first, TombstoneKey)) {
+ // Insert the key/value into the new table.
+ BucketT *DestBucket;
+ bool FoundVal = LookupBucketFor(B->first, DestBucket);
+ (void)FoundVal; // silence warning.
+ assert(!FoundVal && "Key already in new map?");
+ DestBucket->first = llvm_move(B->first);
+ new (&DestBucket->second) ValueT(llvm_move(B->second));
+ incrementNumEntries();
+
+ // Free the value.
+ B->second.~ValueT();
+ }
+ B->first.~KeyT();
+ }
+
+#ifndef NDEBUG
+ if (OldBucketsBegin != OldBucketsEnd)
+ memset((void*)OldBucketsBegin, 0x5a,
+ sizeof(BucketT) * (OldBucketsEnd - OldBucketsBegin));
+#endif
+ }
+
+ template <typename OtherBaseT>
+ void copyFrom(const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT>& other) {
+ assert(getNumBuckets() == other.getNumBuckets());
+
+ setNumEntries(other.getNumEntries());
+ setNumTombstones(other.getNumTombstones());
+
+ if (isPodLike<KeyT>::value && isPodLike<ValueT>::value)
+ memcpy(getBuckets(), other.getBuckets(),
+ getNumBuckets() * sizeof(BucketT));
+ else
+ for (size_t i = 0; i < getNumBuckets(); ++i) {
+ new (&getBuckets()[i].first) KeyT(other.getBuckets()[i].first);
+ if (!KeyInfoT::isEqual(getBuckets()[i].first, getEmptyKey()) &&
+ !KeyInfoT::isEqual(getBuckets()[i].first, getTombstoneKey()))
+ new (&getBuckets()[i].second) ValueT(other.getBuckets()[i].second);
+ }
+ }
+
+ void swap(DenseMapBase& RHS) {
+ std::swap(getNumEntries(), RHS.getNumEntries());
+ std::swap(getNumTombstones(), RHS.getNumTombstones());
+ }
+
+ static unsigned getHashValue(const KeyT &Val) {
+ return KeyInfoT::getHashValue(Val);
+ }
+ template<typename LookupKeyT>
+ static unsigned getHashValue(const LookupKeyT &Val) {
+ return KeyInfoT::getHashValue(Val);
+ }
+ static const KeyT getEmptyKey() {
+ return KeyInfoT::getEmptyKey();
+ }
+ static const KeyT getTombstoneKey() {
+ return KeyInfoT::getTombstoneKey();
+ }
+
+private:
+ unsigned getNumEntries() const {
+ return static_cast<const DerivedT *>(this)->getNumEntries();
+ }
+ void setNumEntries(unsigned Num) {
+ static_cast<DerivedT *>(this)->setNumEntries(Num);
+ }
+ void incrementNumEntries() {
+ setNumEntries(getNumEntries() + 1);
+ }
+ void decrementNumEntries() {
+ setNumEntries(getNumEntries() - 1);
+ }
+ unsigned getNumTombstones() const {
+ return static_cast<const DerivedT *>(this)->getNumTombstones();
+ }
+ void setNumTombstones(unsigned Num) {
+ static_cast<DerivedT *>(this)->setNumTombstones(Num);
+ }
+ void incrementNumTombstones() {
+ setNumTombstones(getNumTombstones() + 1);
+ }
+ void decrementNumTombstones() {
+ setNumTombstones(getNumTombstones() - 1);
+ }
+ const BucketT *getBuckets() const {
+ return static_cast<const DerivedT *>(this)->getBuckets();
+ }
+ BucketT *getBuckets() {
+ return static_cast<DerivedT *>(this)->getBuckets();
+ }
+ unsigned getNumBuckets() const {
+ return static_cast<const DerivedT *>(this)->getNumBuckets();
+ }
+ BucketT *getBucketsEnd() {
+ return getBuckets() + getNumBuckets();
+ }
+ const BucketT *getBucketsEnd() const {
+ return getBuckets() + getNumBuckets();
+ }
+
+ void grow(unsigned AtLeast) {
+ static_cast<DerivedT *>(this)->grow(AtLeast);
+ }
+
+ void shrink_and_clear() {
+ static_cast<DerivedT *>(this)->shrink_and_clear();
+ }
+
+
+ BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
+ BucketT *TheBucket) {
+ TheBucket = InsertIntoBucketImpl(Key, TheBucket);
+
+ TheBucket->first = Key;
+ new (&TheBucket->second) ValueT(Value);
+ return TheBucket;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ BucketT *InsertIntoBucket(const KeyT &Key, ValueT &&Value,
+ BucketT *TheBucket) {
+ TheBucket = InsertIntoBucketImpl(Key, TheBucket);
+
+ TheBucket->first = Key;
+ new (&TheBucket->second) ValueT(std::move(Value));
+ return TheBucket;
+ }
+
+ BucketT *InsertIntoBucket(KeyT &&Key, ValueT &&Value, BucketT *TheBucket) {
+ TheBucket = InsertIntoBucketImpl(Key, TheBucket);
+
+ TheBucket->first = std::move(Key);
+ new (&TheBucket->second) ValueT(std::move(Value));
+ return TheBucket;
+ }
+#endif
+
+ BucketT *InsertIntoBucketImpl(const KeyT &Key, BucketT *TheBucket) {
+ // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
+ // the buckets are empty (meaning that many are filled with tombstones),
+ // grow the table.
+ //
+ // The later case is tricky. For example, if we had one empty bucket with
+ // tons of tombstones, failing lookups (e.g. for insertion) would have to
+ // probe almost the entire table until it found the empty bucket. If the
+ // table completely filled with tombstones, no lookup would ever succeed,
+ // causing infinite loops in lookup.
+ unsigned NewNumEntries = getNumEntries() + 1;
+ unsigned NumBuckets = getNumBuckets();
+ if (NewNumEntries*4 >= NumBuckets*3) {
+ this->grow(NumBuckets * 2);
+ LookupBucketFor(Key, TheBucket);
+ NumBuckets = getNumBuckets();
+ }
+ if (NumBuckets-(NewNumEntries+getNumTombstones()) <= NumBuckets/8) {
+ this->grow(NumBuckets);
+ LookupBucketFor(Key, TheBucket);
+ }
+
+ // Only update the state after we've grown our bucket space appropriately
+ // so that when growing buckets we have self-consistent entry count.
+ incrementNumEntries();
+
+ // If we are writing over a tombstone, remember this.
+ if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
+ decrementNumTombstones();
+
+ return TheBucket;
+ }
+
+ /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
+ /// FoundBucket. If the bucket contains the key and a value, this returns
+ /// true, otherwise it returns a bucket with an empty marker or tombstone and
+ /// returns false.
+ template<typename LookupKeyT>
+ bool LookupBucketFor(const LookupKeyT &Val,
+ const BucketT *&FoundBucket) const {
+ const BucketT *BucketsPtr = getBuckets();
+ const unsigned NumBuckets = getNumBuckets();
+
+ if (NumBuckets == 0) {
+ FoundBucket = 0;
+ return false;
+ }
+
+ // FoundTombstone - Keep track of whether we find a tombstone while probing.
+ const BucketT *FoundTombstone = 0;
+ const KeyT EmptyKey = getEmptyKey();
+ const KeyT TombstoneKey = getTombstoneKey();
+ assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
+ !KeyInfoT::isEqual(Val, TombstoneKey) &&
+ "Empty/Tombstone value shouldn't be inserted into map!");
+
+ unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
+ unsigned ProbeAmt = 1;
+ while (1) {
+ const BucketT *ThisBucket = BucketsPtr + BucketNo;
+ // Found Val's bucket? If so, return it.
+ if (KeyInfoT::isEqual(Val, ThisBucket->first)) {
+ FoundBucket = ThisBucket;
+ return true;
+ }
+
+ // If we found an empty bucket, the key doesn't exist in the set.
+ // Insert it and return the default value.
+ if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
+ // If we've already seen a tombstone while probing, fill it in instead
+ // of the empty bucket we eventually probed to.
+ if (FoundTombstone) ThisBucket = FoundTombstone;
+ FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
+ return false;
+ }
+
+ // If this is a tombstone, remember it. If Val ends up not in the map, we
+ // prefer to return it than something that would require more probing.
+ if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
+ FoundTombstone = ThisBucket; // Remember the first tombstone found.
+
+ // Otherwise, it's a hash collision or a tombstone, continue quadratic
+ // probing.
+ BucketNo += ProbeAmt++;
+ BucketNo &= (NumBuckets-1);
+ }
+ }
+
+ template <typename LookupKeyT>
+ bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
+ const BucketT *ConstFoundBucket;
+ bool Result = const_cast<const DenseMapBase *>(this)
+ ->LookupBucketFor(Val, ConstFoundBucket);
+ FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
+ return Result;
+ }
+
+public:
+ /// Return the approximate size (in bytes) of the actual map.
+ /// This is just the raw memory used by DenseMap.
+ /// If entries are pointers to objects, the size of the referenced objects
+ /// are not included.
+ size_t getMemorySize() const {
+ return getNumBuckets() * sizeof(BucketT);
+ }
+};
+
+template<typename KeyT, typename ValueT,
+ typename KeyInfoT = DenseMapInfo<KeyT> >
+class DenseMap
+ : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT>,
+ KeyT, ValueT, KeyInfoT> {
+ // Lift some types from the dependent base class into this class for
+ // simplicity of referring to them.
+ typedef DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT> BaseT;
+ typedef typename BaseT::BucketT BucketT;
+ friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT>;
+
+ BucketT *Buckets;
+ unsigned NumEntries;
+ unsigned NumTombstones;
+ unsigned NumBuckets;
+
+public:
+ explicit DenseMap(unsigned NumInitBuckets = 0) {
+ init(NumInitBuckets);
+ }
+
+ DenseMap(const DenseMap &other) {
+ init(0);
+ copyFrom(other);
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ DenseMap(DenseMap &&other) {
+ init(0);
+ swap(other);
+ }
+#endif
+
+ template<typename InputIt>
+ DenseMap(const InputIt &I, const InputIt &E) {
+ init(NextPowerOf2(std::distance(I, E)));
+ this->insert(I, E);
+ }
+
+ ~DenseMap() {
+ this->destroyAll();
+ operator delete(Buckets);
+ }
+
+ void swap(DenseMap& RHS) {
+ std::swap(Buckets, RHS.Buckets);
+ std::swap(NumEntries, RHS.NumEntries);
+ std::swap(NumTombstones, RHS.NumTombstones);
+ std::swap(NumBuckets, RHS.NumBuckets);
+ }
+
+ DenseMap& operator=(const DenseMap& other) {
+ copyFrom(other);
+ return *this;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ DenseMap& operator=(DenseMap &&other) {
+ this->destroyAll();
+ operator delete(Buckets);
+ init(0);
+ swap(other);
+ return *this;
+ }
+#endif
+
+ void copyFrom(const DenseMap& other) {
+ this->destroyAll();
+ operator delete(Buckets);
+ if (allocateBuckets(other.NumBuckets)) {
+ this->BaseT::copyFrom(other);
+ } else {
+ NumEntries = 0;
+ NumTombstones = 0;
+ }
+ }
+
+ void init(unsigned InitBuckets) {
+ if (allocateBuckets(InitBuckets)) {
+ this->BaseT::initEmpty();
+ } else {
+ NumEntries = 0;
+ NumTombstones = 0;
+ }
+ }
+
+ void grow(unsigned AtLeast) {
+ unsigned OldNumBuckets = NumBuckets;
+ BucketT *OldBuckets = Buckets;
+
+ allocateBuckets(std::max<unsigned>(64, NextPowerOf2(AtLeast)));
+ assert(Buckets);
+ if (!OldBuckets) {
+ this->BaseT::initEmpty();
+ return;
+ }
+
+ this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
+
+ // Free the old table.
+ operator delete(OldBuckets);
+ }
+
+ void shrink_and_clear() {
+ unsigned OldNumEntries = NumEntries;
+ this->destroyAll();
+
+ // Reduce the number of buckets.
+ unsigned NewNumBuckets = 0;
+ if (OldNumEntries)
+ NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
+ if (NewNumBuckets == NumBuckets) {
+ this->BaseT::initEmpty();
+ return;
+ }
+
+ operator delete(Buckets);
+ init(NewNumBuckets);
+ }
+
+private:
+ unsigned getNumEntries() const {
+ return NumEntries;
+ }
+ void setNumEntries(unsigned Num) {
+ NumEntries = Num;
+ }
+
+ unsigned getNumTombstones() const {
+ return NumTombstones;
+ }
+ void setNumTombstones(unsigned Num) {
+ NumTombstones = Num;
+ }
+
+ BucketT *getBuckets() const {
+ return Buckets;
+ }
+
+ unsigned getNumBuckets() const {
+ return NumBuckets;
+ }
+
+ bool allocateBuckets(unsigned Num) {
+ NumBuckets = Num;
+ if (NumBuckets == 0) {
+ Buckets = 0;
+ return false;
+ }
+
+ Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
+ return true;
+ }
+};
+
+template<typename KeyT, typename ValueT,
+ unsigned InlineBuckets = 4,
+ typename KeyInfoT = DenseMapInfo<KeyT> >
+class SmallDenseMap
+ : public DenseMapBase<SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT>,
+ KeyT, ValueT, KeyInfoT> {
+ // Lift some types from the dependent base class into this class for
+ // simplicity of referring to them.
+ typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT> BaseT;
+ typedef typename BaseT::BucketT BucketT;
+ friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT>;
+
+ unsigned Small : 1;
+ unsigned NumEntries : 31;
+ unsigned NumTombstones;
+
+ struct LargeRep {
+ BucketT *Buckets;
+ unsigned NumBuckets;
+ };
+
+ /// A "union" of an inline bucket array and the struct representing
+ /// a large bucket. This union will be discriminated by the 'Small' bit.
+ AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
+
+public:
+ explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
+ init(NumInitBuckets);
+ }
+
+ SmallDenseMap(const SmallDenseMap &other) {
+ init(0);
+ copyFrom(other);
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ SmallDenseMap(SmallDenseMap &&other) {
+ init(0);
+ swap(other);
+ }
+#endif
+
+ template<typename InputIt>
+ SmallDenseMap(const InputIt &I, const InputIt &E) {
+ init(NextPowerOf2(std::distance(I, E)));
+ this->insert(I, E);
+ }
+
+ ~SmallDenseMap() {
+ this->destroyAll();
+ deallocateBuckets();
+ }
+
+ void swap(SmallDenseMap& RHS) {
+ unsigned TmpNumEntries = RHS.NumEntries;
+ RHS.NumEntries = NumEntries;
+ NumEntries = TmpNumEntries;
+ std::swap(NumTombstones, RHS.NumTombstones);
+
+ const KeyT EmptyKey = this->getEmptyKey();
+ const KeyT TombstoneKey = this->getTombstoneKey();
+ if (Small && RHS.Small) {
+ // If we're swapping inline bucket arrays, we have to cope with some of
+ // the tricky bits of DenseMap's storage system: the buckets are not
+ // fully initialized. Thus we swap every key, but we may have
+ // a one-directional move of the value.
+ for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
+ BucketT *LHSB = &getInlineBuckets()[i],
+ *RHSB = &RHS.getInlineBuckets()[i];
+ bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->first, EmptyKey) &&
+ !KeyInfoT::isEqual(LHSB->first, TombstoneKey));
+ bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->first, EmptyKey) &&
+ !KeyInfoT::isEqual(RHSB->first, TombstoneKey));
+ if (hasLHSValue && hasRHSValue) {
+ // Swap together if we can...
+ std::swap(*LHSB, *RHSB);
+ continue;
+ }
+ // Swap separately and handle any assymetry.
+ std::swap(LHSB->first, RHSB->first);
+ if (hasLHSValue) {
+ new (&RHSB->second) ValueT(llvm_move(LHSB->second));
+ LHSB->second.~ValueT();
+ } else if (hasRHSValue) {
+ new (&LHSB->second) ValueT(llvm_move(RHSB->second));
+ RHSB->second.~ValueT();
+ }
+ }
+ return;
+ }
+ if (!Small && !RHS.Small) {
+ std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
+ std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
+ return;
+ }
+
+ SmallDenseMap &SmallSide = Small ? *this : RHS;
+ SmallDenseMap &LargeSide = Small ? RHS : *this;
+
+ // First stash the large side's rep and move the small side across.
+ LargeRep TmpRep = llvm_move(*LargeSide.getLargeRep());
+ LargeSide.getLargeRep()->~LargeRep();
+ LargeSide.Small = true;
+ // This is similar to the standard move-from-old-buckets, but the bucket
+ // count hasn't actually rotated in this case. So we have to carefully
+ // move construct the keys and values into their new locations, but there
+ // is no need to re-hash things.
+ for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
+ BucketT *NewB = &LargeSide.getInlineBuckets()[i],
+ *OldB = &SmallSide.getInlineBuckets()[i];
+ new (&NewB->first) KeyT(llvm_move(OldB->first));
+ OldB->first.~KeyT();
+ if (!KeyInfoT::isEqual(NewB->first, EmptyKey) &&
+ !KeyInfoT::isEqual(NewB->first, TombstoneKey)) {
+ new (&NewB->second) ValueT(llvm_move(OldB->second));
+ OldB->second.~ValueT();
+ }
+ }
+
+ // The hard part of moving the small buckets across is done, just move
+ // the TmpRep into its new home.
+ SmallSide.Small = false;
+ new (SmallSide.getLargeRep()) LargeRep(llvm_move(TmpRep));
+ }
+
+ SmallDenseMap& operator=(const SmallDenseMap& other) {
+ copyFrom(other);
+ return *this;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ SmallDenseMap& operator=(SmallDenseMap &&other) {
+ this->destroyAll();
+ deallocateBuckets();
+ init(0);
+ swap(other);
+ return *this;
+ }
+#endif
+
+ void copyFrom(const SmallDenseMap& other) {
+ this->destroyAll();
+ deallocateBuckets();
+ Small = true;
+ if (other.getNumBuckets() > InlineBuckets) {
+ Small = false;
+ allocateBuckets(other.getNumBuckets());
+ }
+ this->BaseT::copyFrom(other);
+ }
+
+ void init(unsigned InitBuckets) {
+ Small = true;
+ if (InitBuckets > InlineBuckets) {
+ Small = false;
+ new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
+ }
+ this->BaseT::initEmpty();
+ }
+
+ void grow(unsigned AtLeast) {
+ if (AtLeast > InlineBuckets)
+ AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast));
+
+ if (Small) {
+ if (AtLeast <= InlineBuckets)
+ return; // Nothing to do.
+
+ // First move the inline buckets into a temporary storage.
+ AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
+ BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
+ BucketT *TmpEnd = TmpBegin;
+
+ // Loop over the buckets, moving non-empty, non-tombstones into the
+ // temporary storage. Have the loop move the TmpEnd forward as it goes.
+ const KeyT EmptyKey = this->getEmptyKey();
+ const KeyT TombstoneKey = this->getTombstoneKey();
+ for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
+ if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
+ !KeyInfoT::isEqual(P->first, TombstoneKey)) {
+ assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
+ "Too many inline buckets!");
+ new (&TmpEnd->first) KeyT(llvm_move(P->first));
+ new (&TmpEnd->second) ValueT(llvm_move(P->second));
+ ++TmpEnd;
+ P->second.~ValueT();
+ }
+ P->first.~KeyT();
+ }
+
+ // Now make this map use the large rep, and move all the entries back
+ // into it.
+ Small = false;
+ new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
+ this->moveFromOldBuckets(TmpBegin, TmpEnd);
+ return;
+ }
+
+ LargeRep OldRep = llvm_move(*getLargeRep());
+ getLargeRep()->~LargeRep();
+ if (AtLeast <= InlineBuckets) {
+ Small = true;
+ } else {
+ new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
+ }
+
+ this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
+
+ // Free the old table.
+ operator delete(OldRep.Buckets);
+ }
+
+ void shrink_and_clear() {
+ unsigned OldSize = this->size();
+ this->destroyAll();
+
+ // Reduce the number of buckets.
+ unsigned NewNumBuckets = 0;
+ if (OldSize) {
+ NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
+ if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
+ NewNumBuckets = 64;
+ }
+ if ((Small && NewNumBuckets <= InlineBuckets) ||
+ (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
+ this->BaseT::initEmpty();
+ return;
+ }
+
+ deallocateBuckets();
+ init(NewNumBuckets);
+ }
+
+private:
+ unsigned getNumEntries() const {
+ return NumEntries;
+ }
+ void setNumEntries(unsigned Num) {
+ assert(Num < INT_MAX && "Cannot support more than INT_MAX entries");
+ NumEntries = Num;
+ }
+
+ unsigned getNumTombstones() const {
+ return NumTombstones;
+ }
+ void setNumTombstones(unsigned Num) {
+ NumTombstones = Num;
+ }
+
+ const BucketT *getInlineBuckets() const {
+ assert(Small);
+ // Note that this cast does not violate aliasing rules as we assert that
+ // the memory's dynamic type is the small, inline bucket buffer, and the
+ // 'storage.buffer' static type is 'char *'.
+ return reinterpret_cast<const BucketT *>(storage.buffer);
+ }
+ BucketT *getInlineBuckets() {
+ return const_cast<BucketT *>(
+ const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
+ }
+ const LargeRep *getLargeRep() const {
+ assert(!Small);
+ // Note, same rule about aliasing as with getInlineBuckets.
+ return reinterpret_cast<const LargeRep *>(storage.buffer);
+ }
+ LargeRep *getLargeRep() {
+ return const_cast<LargeRep *>(
+ const_cast<const SmallDenseMap *>(this)->getLargeRep());
+ }
+
+ const BucketT *getBuckets() const {
+ return Small ? getInlineBuckets() : getLargeRep()->Buckets;
+ }
+ BucketT *getBuckets() {
+ return const_cast<BucketT *>(
+ const_cast<const SmallDenseMap *>(this)->getBuckets());
+ }
+ unsigned getNumBuckets() const {
+ return Small ? InlineBuckets : getLargeRep()->NumBuckets;
+ }
+
+ void deallocateBuckets() {
+ if (Small)
+ return;
+
+ operator delete(getLargeRep()->Buckets);
+ getLargeRep()->~LargeRep();
+ }
+
+ LargeRep allocateBuckets(unsigned Num) {
+ assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
+ LargeRep Rep = {
+ static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
+ };
+ return Rep;
+ }
+};
+
+template<typename KeyT, typename ValueT,
+ typename KeyInfoT, bool IsConst>
+class DenseMapIterator {
+ typedef std::pair<KeyT, ValueT> Bucket;
+ typedef DenseMapIterator<KeyT, ValueT,
+ KeyInfoT, true> ConstIterator;
+ friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, true>;
+public:
+ typedef ptrdiff_t difference_type;
+ typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
+ typedef value_type *pointer;
+ typedef value_type &reference;
+ typedef std::forward_iterator_tag iterator_category;
+private:
+ pointer Ptr, End;
+public:
+ DenseMapIterator() : Ptr(0), End(0) {}
+
+ DenseMapIterator(pointer Pos, pointer E, bool NoAdvance = false)
+ : Ptr(Pos), End(E) {
+ if (!NoAdvance) AdvancePastEmptyBuckets();
+ }
+
+ // If IsConst is true this is a converting constructor from iterator to
+ // const_iterator and the default copy constructor is used.
+ // Otherwise this is a copy constructor for iterator.
+ DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
+ KeyInfoT, false>& I)
+ : Ptr(I.Ptr), End(I.End) {}
+
+ reference operator*() const {
+ return *Ptr;
+ }
+ pointer operator->() const {
+ return Ptr;
+ }
+
+ bool operator==(const ConstIterator &RHS) const {
+ return Ptr == RHS.operator->();
+ }
+ bool operator!=(const ConstIterator &RHS) const {
+ return Ptr != RHS.operator->();
+ }
+
+ inline DenseMapIterator& operator++() { // Preincrement
+ ++Ptr;
+ AdvancePastEmptyBuckets();
+ return *this;
+ }
+ DenseMapIterator operator++(int) { // Postincrement
+ DenseMapIterator tmp = *this; ++*this; return tmp;
+ }
+
+private:
+ void AdvancePastEmptyBuckets() {
+ const KeyT Empty = KeyInfoT::getEmptyKey();
+ const KeyT Tombstone = KeyInfoT::getTombstoneKey();
+
+ while (Ptr != End &&
+ (KeyInfoT::isEqual(Ptr->first, Empty) ||
+ KeyInfoT::isEqual(Ptr->first, Tombstone)))
+ ++Ptr;
+ }
+};
+
+template<typename KeyT, typename ValueT, typename KeyInfoT>
+static inline size_t
+capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
+ return X.getMemorySize();
+}
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/DenseMapInfo.h b/include/llvm/ADT/DenseMapInfo.h
new file mode 100644
index 00000000000..6f17a647b63
--- /dev/null
+++ b/include/llvm/ADT/DenseMapInfo.h
@@ -0,0 +1,168 @@
+//===- llvm/ADT/DenseMapInfo.h - Type traits for DenseMap -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines DenseMapInfo traits for DenseMap.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_DENSEMAPINFO_H
+#define LLVM_ADT_DENSEMAPINFO_H
+
+#include "llvm/Support/PointerLikeTypeTraits.h"
+#include "llvm/Support/type_traits.h"
+
+namespace llvm {
+
+template<typename T>
+struct DenseMapInfo {
+ //static inline T getEmptyKey();
+ //static inline T getTombstoneKey();
+ //static unsigned getHashValue(const T &Val);
+ //static bool isEqual(const T &LHS, const T &RHS);
+};
+
+// Provide DenseMapInfo for all pointers.
+template<typename T>
+struct DenseMapInfo<T*> {
+ static inline T* getEmptyKey() {
+ uintptr_t Val = static_cast<uintptr_t>(-1);
+ Val <<= PointerLikeTypeTraits<T*>::NumLowBitsAvailable;
+ return reinterpret_cast<T*>(Val);
+ }
+ static inline T* getTombstoneKey() {
+ uintptr_t Val = static_cast<uintptr_t>(-2);
+ Val <<= PointerLikeTypeTraits<T*>::NumLowBitsAvailable;
+ return reinterpret_cast<T*>(Val);
+ }
+ static unsigned getHashValue(const T *PtrVal) {
+ return (unsigned((uintptr_t)PtrVal) >> 4) ^
+ (unsigned((uintptr_t)PtrVal) >> 9);
+ }
+ static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
+};
+
+// Provide DenseMapInfo for chars.
+template<> struct DenseMapInfo<char> {
+ static inline char getEmptyKey() { return ~0; }
+ static inline char getTombstoneKey() { return ~0 - 1; }
+ static unsigned getHashValue(const char& Val) { return Val * 37U; }
+ static bool isEqual(const char &LHS, const char &RHS) {
+ return LHS == RHS;
+ }
+};
+
+// Provide DenseMapInfo for unsigned ints.
+template<> struct DenseMapInfo<unsigned> {
+ static inline unsigned getEmptyKey() { return ~0U; }
+ static inline unsigned getTombstoneKey() { return ~0U - 1; }
+ static unsigned getHashValue(const unsigned& Val) { return Val * 37U; }
+ static bool isEqual(const unsigned& LHS, const unsigned& RHS) {
+ return LHS == RHS;
+ }
+};
+
+// Provide DenseMapInfo for unsigned longs.
+template<> struct DenseMapInfo<unsigned long> {
+ static inline unsigned long getEmptyKey() { return ~0UL; }
+ static inline unsigned long getTombstoneKey() { return ~0UL - 1L; }
+ static unsigned getHashValue(const unsigned long& Val) {
+ return (unsigned)(Val * 37UL);
+ }
+ static bool isEqual(const unsigned long& LHS, const unsigned long& RHS) {
+ return LHS == RHS;
+ }
+};
+
+// Provide DenseMapInfo for unsigned long longs.
+template<> struct DenseMapInfo<unsigned long long> {
+ static inline unsigned long long getEmptyKey() { return ~0ULL; }
+ static inline unsigned long long getTombstoneKey() { return ~0ULL - 1ULL; }
+ static unsigned getHashValue(const unsigned long long& Val) {
+ return (unsigned)(Val * 37ULL);
+ }
+ static bool isEqual(const unsigned long long& LHS,
+ const unsigned long long& RHS) {
+ return LHS == RHS;
+ }
+};
+
+// Provide DenseMapInfo for ints.
+template<> struct DenseMapInfo<int> {
+ static inline int getEmptyKey() { return 0x7fffffff; }
+ static inline int getTombstoneKey() { return -0x7fffffff - 1; }
+ static unsigned getHashValue(const int& Val) { return (unsigned)(Val * 37U); }
+ static bool isEqual(const int& LHS, const int& RHS) {
+ return LHS == RHS;
+ }
+};
+
+// Provide DenseMapInfo for longs.
+template<> struct DenseMapInfo<long> {
+ static inline long getEmptyKey() {
+ return (1UL << (sizeof(long) * 8 - 1)) - 1UL;
+ }
+ static inline long getTombstoneKey() { return getEmptyKey() - 1L; }
+ static unsigned getHashValue(const long& Val) {
+ return (unsigned)(Val * 37UL);
+ }
+ static bool isEqual(const long& LHS, const long& RHS) {
+ return LHS == RHS;
+ }
+};
+
+// Provide DenseMapInfo for long longs.
+template<> struct DenseMapInfo<long long> {
+ static inline long long getEmptyKey() { return 0x7fffffffffffffffLL; }
+ static inline long long getTombstoneKey() { return -0x7fffffffffffffffLL-1; }
+ static unsigned getHashValue(const long long& Val) {
+ return (unsigned)(Val * 37ULL);
+ }
+ static bool isEqual(const long long& LHS,
+ const long long& RHS) {
+ return LHS == RHS;
+ }
+};
+
+// Provide DenseMapInfo for all pairs whose members have info.
+template<typename T, typename U>
+struct DenseMapInfo<std::pair<T, U> > {
+ typedef std::pair<T, U> Pair;
+ typedef DenseMapInfo<T> FirstInfo;
+ typedef DenseMapInfo<U> SecondInfo;
+
+ static inline Pair getEmptyKey() {
+ return std::make_pair(FirstInfo::getEmptyKey(),
+ SecondInfo::getEmptyKey());
+ }
+ static inline Pair getTombstoneKey() {
+ return std::make_pair(FirstInfo::getTombstoneKey(),
+ SecondInfo::getTombstoneKey());
+ }
+ static unsigned getHashValue(const Pair& PairVal) {
+ uint64_t key = (uint64_t)FirstInfo::getHashValue(PairVal.first) << 32
+ | (uint64_t)SecondInfo::getHashValue(PairVal.second);
+ key += ~(key << 32);
+ key ^= (key >> 22);
+ key += ~(key << 13);
+ key ^= (key >> 8);
+ key += (key << 3);
+ key ^= (key >> 15);
+ key += ~(key << 27);
+ key ^= (key >> 31);
+ return (unsigned)key;
+ }
+ static bool isEqual(const Pair &LHS, const Pair &RHS) {
+ return FirstInfo::isEqual(LHS.first, RHS.first) &&
+ SecondInfo::isEqual(LHS.second, RHS.second);
+ }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/DenseSet.h b/include/llvm/ADT/DenseSet.h
new file mode 100644
index 00000000000..8ab9a33200c
--- /dev/null
+++ b/include/llvm/ADT/DenseSet.h
@@ -0,0 +1,129 @@
+//===- llvm/ADT/DenseSet.h - Dense probed hash table ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the DenseSet class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_DENSESET_H
+#define LLVM_ADT_DENSESET_H
+
+#include "llvm/ADT/DenseMap.h"
+
+namespace llvm {
+
+/// DenseSet - This implements a dense probed hash-table based set.
+///
+/// FIXME: This is currently implemented directly in terms of DenseMap, this
+/// should be optimized later if there is a need.
+template<typename ValueT, typename ValueInfoT = DenseMapInfo<ValueT> >
+class DenseSet {
+ typedef DenseMap<ValueT, char, ValueInfoT> MapTy;
+ MapTy TheMap;
+public:
+ DenseSet(const DenseSet &Other) : TheMap(Other.TheMap) {}
+ explicit DenseSet(unsigned NumInitBuckets = 0) : TheMap(NumInitBuckets) {}
+
+ bool empty() const { return TheMap.empty(); }
+ unsigned size() const { return TheMap.size(); }
+
+ /// Grow the denseset so that it has at least Size buckets. Does not shrink
+ void resize(size_t Size) { TheMap.resize(Size); }
+
+ void clear() {
+ TheMap.clear();
+ }
+
+ bool count(const ValueT &V) const {
+ return TheMap.count(V);
+ }
+
+ bool erase(const ValueT &V) {
+ return TheMap.erase(V);
+ }
+
+ void swap(DenseSet& RHS) {
+ TheMap.swap(RHS.TheMap);
+ }
+
+ DenseSet &operator=(const DenseSet &RHS) {
+ TheMap = RHS.TheMap;
+ return *this;
+ }
+
+ // Iterators.
+
+ class Iterator {
+ typename MapTy::iterator I;
+ friend class DenseSet;
+ public:
+ typedef typename MapTy::iterator::difference_type difference_type;
+ typedef ValueT value_type;
+ typedef value_type *pointer;
+ typedef value_type &reference;
+ typedef std::forward_iterator_tag iterator_category;
+
+ Iterator(const typename MapTy::iterator &i) : I(i) {}
+
+ ValueT& operator*() { return I->first; }
+ ValueT* operator->() { return &I->first; }
+
+ Iterator& operator++() { ++I; return *this; }
+ bool operator==(const Iterator& X) const { return I == X.I; }
+ bool operator!=(const Iterator& X) const { return I != X.I; }
+ };
+
+ class ConstIterator {
+ typename MapTy::const_iterator I;
+ friend class DenseSet;
+ public:
+ typedef typename MapTy::const_iterator::difference_type difference_type;
+ typedef ValueT value_type;
+ typedef value_type *pointer;
+ typedef value_type &reference;
+ typedef std::forward_iterator_tag iterator_category;
+
+ ConstIterator(const typename MapTy::const_iterator &i) : I(i) {}
+
+ const ValueT& operator*() { return I->first; }
+ const ValueT* operator->() { return &I->first; }
+
+ ConstIterator& operator++() { ++I; return *this; }
+ bool operator==(const ConstIterator& X) const { return I == X.I; }
+ bool operator!=(const ConstIterator& X) const { return I != X.I; }
+ };
+
+ typedef Iterator iterator;
+ typedef ConstIterator const_iterator;
+
+ iterator begin() { return Iterator(TheMap.begin()); }
+ iterator end() { return Iterator(TheMap.end()); }
+
+ const_iterator begin() const { return ConstIterator(TheMap.begin()); }
+ const_iterator end() const { return ConstIterator(TheMap.end()); }
+
+ iterator find(const ValueT &V) { return Iterator(TheMap.find(V)); }
+ void erase(Iterator I) { return TheMap.erase(I.I); }
+ void erase(ConstIterator CI) { return TheMap.erase(CI.I); }
+
+ std::pair<iterator, bool> insert(const ValueT &V) {
+ return TheMap.insert(std::make_pair(V, 0));
+ }
+
+ // Range insertion of values.
+ template<typename InputIt>
+ void insert(InputIt I, InputIt E) {
+ for (; I != E; ++I)
+ insert(*I);
+ }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/DepthFirstIterator.h b/include/llvm/ADT/DepthFirstIterator.h
new file mode 100644
index 00000000000..519b18052b6
--- /dev/null
+++ b/include/llvm/ADT/DepthFirstIterator.h
@@ -0,0 +1,268 @@
+//===- llvm/ADT/DepthFirstIterator.h - Depth First iterator -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file builds on the ADT/GraphTraits.h file to build generic depth
+// first graph iterator. This file exposes the following functions/types:
+//
+// df_begin/df_end/df_iterator
+// * Normal depth-first iteration - visit a node and then all of its children.
+//
+// idf_begin/idf_end/idf_iterator
+// * Depth-first iteration on the 'inverse' graph.
+//
+// df_ext_begin/df_ext_end/df_ext_iterator
+// * Normal depth-first iteration - visit a node and then all of its children.
+// This iterator stores the 'visited' set in an external set, which allows
+// it to be more efficient, and allows external clients to use the set for
+// other purposes.
+//
+// idf_ext_begin/idf_ext_end/idf_ext_iterator
+// * Depth-first iteration on the 'inverse' graph.
+// This iterator stores the 'visited' set in an external set, which allows
+// it to be more efficient, and allows external clients to use the set for
+// other purposes.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_DEPTHFIRSTITERATOR_H
+#define LLVM_ADT_DEPTHFIRSTITERATOR_H
+
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include <set>
+#include <vector>
+
+namespace llvm {
+
+// df_iterator_storage - A private class which is used to figure out where to
+// store the visited set.
+template<class SetType, bool External> // Non-external set
+class df_iterator_storage {
+public:
+ SetType Visited;
+};
+
+template<class SetType>
+class df_iterator_storage<SetType, true> {
+public:
+ df_iterator_storage(SetType &VSet) : Visited(VSet) {}
+ df_iterator_storage(const df_iterator_storage &S) : Visited(S.Visited) {}
+ SetType &Visited;
+};
+
+
+// Generic Depth First Iterator
+template<class GraphT,
+class SetType = llvm::SmallPtrSet<typename GraphTraits<GraphT>::NodeType*, 8>,
+ bool ExtStorage = false, class GT = GraphTraits<GraphT> >
+class df_iterator : public std::iterator<std::forward_iterator_tag,
+ typename GT::NodeType, ptrdiff_t>,
+ public df_iterator_storage<SetType, ExtStorage> {
+ typedef std::iterator<std::forward_iterator_tag,
+ typename GT::NodeType, ptrdiff_t> super;
+
+ typedef typename GT::NodeType NodeType;
+ typedef typename GT::ChildIteratorType ChildItTy;
+ typedef PointerIntPair<NodeType*, 1> PointerIntTy;
+
+ // VisitStack - Used to maintain the ordering. Top = current block
+ // First element is node pointer, second is the 'next child' to visit
+ // if the int in PointerIntTy is 0, the 'next child' to visit is invalid
+ std::vector<std::pair<PointerIntTy, ChildItTy> > VisitStack;
+private:
+ inline df_iterator(NodeType *Node) {
+ this->Visited.insert(Node);
+ VisitStack.push_back(std::make_pair(PointerIntTy(Node, 0),
+ GT::child_begin(Node)));
+ }
+ inline df_iterator() {
+ // End is when stack is empty
+ }
+ inline df_iterator(NodeType *Node, SetType &S)
+ : df_iterator_storage<SetType, ExtStorage>(S) {
+ if (!S.count(Node)) {
+ VisitStack.push_back(std::make_pair(PointerIntTy(Node, 0),
+ GT::child_begin(Node)));
+ this->Visited.insert(Node);
+ }
+ }
+ inline df_iterator(SetType &S)
+ : df_iterator_storage<SetType, ExtStorage>(S) {
+ // End is when stack is empty
+ }
+
+ inline void toNext() {
+ do {
+ std::pair<PointerIntTy, ChildItTy> &Top = VisitStack.back();
+ NodeType *Node = Top.first.getPointer();
+ ChildItTy &It = Top.second;
+ if (!Top.first.getInt()) {
+ // now retrieve the real begin of the children before we dive in
+ It = GT::child_begin(Node);
+ Top.first.setInt(1);
+ }
+
+ while (It != GT::child_end(Node)) {
+ NodeType *Next = *It++;
+ // Has our next sibling been visited?
+ if (Next && !this->Visited.count(Next)) {
+ // No, do it now.
+ this->Visited.insert(Next);
+ VisitStack.push_back(std::make_pair(PointerIntTy(Next, 0),
+ GT::child_begin(Next)));
+ return;
+ }
+ }
+
+ // Oops, ran out of successors... go up a level on the stack.
+ VisitStack.pop_back();
+ } while (!VisitStack.empty());
+ }
+
+public:
+ typedef typename super::pointer pointer;
+ typedef df_iterator<GraphT, SetType, ExtStorage, GT> _Self;
+
+ // Provide static begin and end methods as our public "constructors"
+ static inline _Self begin(const GraphT& G) {
+ return _Self(GT::getEntryNode(G));
+ }
+ static inline _Self end(const GraphT& G) { return _Self(); }
+
+ // Static begin and end methods as our public ctors for external iterators
+ static inline _Self begin(const GraphT& G, SetType &S) {
+ return _Self(GT::getEntryNode(G), S);
+ }
+ static inline _Self end(const GraphT& G, SetType &S) { return _Self(S); }
+
+ inline bool operator==(const _Self& x) const {
+ return VisitStack == x.VisitStack;
+ }
+ inline bool operator!=(const _Self& x) const { return !operator==(x); }
+
+ inline pointer operator*() const {
+ return VisitStack.back().first.getPointer();
+ }
+
+ // This is a nonstandard operator-> that dereferences the pointer an extra
+ // time... so that you can actually call methods ON the Node, because
+ // the contained type is a pointer. This allows BBIt->getTerminator() f.e.
+ //
+ inline NodeType *operator->() const { return operator*(); }
+
+ inline _Self& operator++() { // Preincrement
+ toNext();
+ return *this;
+ }
+
+ // skips all children of the current node and traverses to next node
+ //
+ inline _Self& skipChildren() {
+ VisitStack.pop_back();
+ if (!VisitStack.empty())
+ toNext();
+ return *this;
+ }
+
+ inline _Self operator++(int) { // Postincrement
+ _Self tmp = *this; ++*this; return tmp;
+ }
+
+ // nodeVisited - return true if this iterator has already visited the
+ // specified node. This is public, and will probably be used to iterate over
+ // nodes that a depth first iteration did not find: ie unreachable nodes.
+ //
+ inline bool nodeVisited(NodeType *Node) const {
+ return this->Visited.count(Node) != 0;
+ }
+
+ /// getPathLength - Return the length of the path from the entry node to the
+ /// current node, counting both nodes.
+ unsigned getPathLength() const { return VisitStack.size(); }
+
+ /// getPath - Return the n'th node in the path from the entry node to the
+ /// current node.
+ NodeType *getPath(unsigned n) const {
+ return VisitStack[n].first.getPointer();
+ }
+};
+
+
+// Provide global constructors that automatically figure out correct types...
+//
+template <class T>
+df_iterator<T> df_begin(const T& G) {
+ return df_iterator<T>::begin(G);
+}
+
+template <class T>
+df_iterator<T> df_end(const T& G) {
+ return df_iterator<T>::end(G);
+}
+
+// Provide global definitions of external depth first iterators...
+template <class T, class SetTy = std::set<typename GraphTraits<T>::NodeType*> >
+struct df_ext_iterator : public df_iterator<T, SetTy, true> {
+ df_ext_iterator(const df_iterator<T, SetTy, true> &V)
+ : df_iterator<T, SetTy, true>(V) {}
+};
+
+template <class T, class SetTy>
+df_ext_iterator<T, SetTy> df_ext_begin(const T& G, SetTy &S) {
+ return df_ext_iterator<T, SetTy>::begin(G, S);
+}
+
+template <class T, class SetTy>
+df_ext_iterator<T, SetTy> df_ext_end(const T& G, SetTy &S) {
+ return df_ext_iterator<T, SetTy>::end(G, S);
+}
+
+
+// Provide global definitions of inverse depth first iterators...
+template <class T,
+ class SetTy = llvm::SmallPtrSet<typename GraphTraits<T>::NodeType*, 8>,
+ bool External = false>
+struct idf_iterator : public df_iterator<Inverse<T>, SetTy, External> {
+ idf_iterator(const df_iterator<Inverse<T>, SetTy, External> &V)
+ : df_iterator<Inverse<T>, SetTy, External>(V) {}
+};
+
+template <class T>
+idf_iterator<T> idf_begin(const T& G) {
+ return idf_iterator<T>::begin(Inverse<T>(G));
+}
+
+template <class T>
+idf_iterator<T> idf_end(const T& G){
+ return idf_iterator<T>::end(Inverse<T>(G));
+}
+
+// Provide global definitions of external inverse depth first iterators...
+template <class T, class SetTy = std::set<typename GraphTraits<T>::NodeType*> >
+struct idf_ext_iterator : public idf_iterator<T, SetTy, true> {
+ idf_ext_iterator(const idf_iterator<T, SetTy, true> &V)
+ : idf_iterator<T, SetTy, true>(V) {}
+ idf_ext_iterator(const df_iterator<Inverse<T>, SetTy, true> &V)
+ : idf_iterator<T, SetTy, true>(V) {}
+};
+
+template <class T, class SetTy>
+idf_ext_iterator<T, SetTy> idf_ext_begin(const T& G, SetTy &S) {
+ return idf_ext_iterator<T, SetTy>::begin(Inverse<T>(G), S);
+}
+
+template <class T, class SetTy>
+idf_ext_iterator<T, SetTy> idf_ext_end(const T& G, SetTy &S) {
+ return idf_ext_iterator<T, SetTy>::end(Inverse<T>(G), S);
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/EquivalenceClasses.h b/include/llvm/ADT/EquivalenceClasses.h
new file mode 100644
index 00000000000..1d81772ee8a
--- /dev/null
+++ b/include/llvm/ADT/EquivalenceClasses.h
@@ -0,0 +1,283 @@
+//===-- llvm/ADT/EquivalenceClasses.h - Generic Equiv. Classes --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Generic implementation of equivalence classes through the use Tarjan's
+// efficient union-find algorithm.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_EQUIVALENCECLASSES_H
+#define LLVM_ADT_EQUIVALENCECLASSES_H
+
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+#include <set>
+
+namespace llvm {
+
+/// EquivalenceClasses - This represents a collection of equivalence classes and
+/// supports three efficient operations: insert an element into a class of its
+/// own, union two classes, and find the class for a given element. In
+/// addition to these modification methods, it is possible to iterate over all
+/// of the equivalence classes and all of the elements in a class.
+///
+/// This implementation is an efficient implementation that only stores one copy
+/// of the element being indexed per entry in the set, and allows any arbitrary
+/// type to be indexed (as long as it can be ordered with operator<).
+///
+/// Here is a simple example using integers:
+///
+/// \code
+/// EquivalenceClasses<int> EC;
+/// EC.unionSets(1, 2); // insert 1, 2 into the same set
+/// EC.insert(4); EC.insert(5); // insert 4, 5 into own sets
+/// EC.unionSets(5, 1); // merge the set for 1 with 5's set.
+///
+/// for (EquivalenceClasses<int>::iterator I = EC.begin(), E = EC.end();
+/// I != E; ++I) { // Iterate over all of the equivalence sets.
+/// if (!I->isLeader()) continue; // Ignore non-leader sets.
+/// for (EquivalenceClasses<int>::member_iterator MI = EC.member_begin(I);
+/// MI != EC.member_end(); ++MI) // Loop over members in this set.
+/// cerr << *MI << " "; // Print member.
+/// cerr << "\n"; // Finish set.
+/// }
+/// \endcode
+///
+/// This example prints:
+/// 4
+/// 5 1 2
+///
+template <class ElemTy>
+class EquivalenceClasses {
+ /// ECValue - The EquivalenceClasses data structure is just a set of these.
+ /// Each of these represents a relation for a value. First it stores the
+ /// value itself, which provides the ordering that the set queries. Next, it
+ /// provides a "next pointer", which is used to enumerate all of the elements
+ /// in the unioned set. Finally, it defines either a "end of list pointer" or
+ /// "leader pointer" depending on whether the value itself is a leader. A
+ /// "leader pointer" points to the node that is the leader for this element,
+ /// if the node is not a leader. A "end of list pointer" points to the last
+ /// node in the list of members of this list. Whether or not a node is a
+ /// leader is determined by a bit stolen from one of the pointers.
+ class ECValue {
+ friend class EquivalenceClasses;
+ mutable const ECValue *Leader, *Next;
+ ElemTy Data;
+ // ECValue ctor - Start out with EndOfList pointing to this node, Next is
+ // Null, isLeader = true.
+ ECValue(const ElemTy &Elt)
+ : Leader(this), Next((ECValue*)(intptr_t)1), Data(Elt) {}
+
+ const ECValue *getLeader() const {
+ if (isLeader()) return this;
+ if (Leader->isLeader()) return Leader;
+ // Path compression.
+ return Leader = Leader->getLeader();
+ }
+ const ECValue *getEndOfList() const {
+ assert(isLeader() && "Cannot get the end of a list for a non-leader!");
+ return Leader;
+ }
+
+ void setNext(const ECValue *NewNext) const {
+ assert(getNext() == 0 && "Already has a next pointer!");
+ Next = (const ECValue*)((intptr_t)NewNext | (intptr_t)isLeader());
+ }
+ public:
+ ECValue(const ECValue &RHS) : Leader(this), Next((ECValue*)(intptr_t)1),
+ Data(RHS.Data) {
+ // Only support copying of singleton nodes.
+ assert(RHS.isLeader() && RHS.getNext() == 0 && "Not a singleton!");
+ }
+
+ bool operator<(const ECValue &UFN) const { return Data < UFN.Data; }
+
+ bool isLeader() const { return (intptr_t)Next & 1; }
+ const ElemTy &getData() const { return Data; }
+
+ const ECValue *getNext() const {
+ return (ECValue*)((intptr_t)Next & ~(intptr_t)1);
+ }
+
+ template<typename T>
+ bool operator<(const T &Val) const { return Data < Val; }
+ };
+
+ /// TheMapping - This implicitly provides a mapping from ElemTy values to the
+ /// ECValues, it just keeps the key as part of the value.
+ std::set<ECValue> TheMapping;
+
+public:
+ EquivalenceClasses() {}
+ EquivalenceClasses(const EquivalenceClasses &RHS) {
+ operator=(RHS);
+ }
+
+ const EquivalenceClasses &operator=(const EquivalenceClasses &RHS) {
+ TheMapping.clear();
+ for (iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
+ if (I->isLeader()) {
+ member_iterator MI = RHS.member_begin(I);
+ member_iterator LeaderIt = member_begin(insert(*MI));
+ for (++MI; MI != member_end(); ++MI)
+ unionSets(LeaderIt, member_begin(insert(*MI)));
+ }
+ return *this;
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Inspection methods
+ //
+
+ /// iterator* - Provides a way to iterate over all values in the set.
+ typedef typename std::set<ECValue>::const_iterator iterator;
+ iterator begin() const { return TheMapping.begin(); }
+ iterator end() const { return TheMapping.end(); }
+
+ bool empty() const { return TheMapping.empty(); }
+
+ /// member_* Iterate over the members of an equivalence class.
+ ///
+ class member_iterator;
+ member_iterator member_begin(iterator I) const {
+ // Only leaders provide anything to iterate over.
+ return member_iterator(I->isLeader() ? &*I : 0);
+ }
+ member_iterator member_end() const {
+ return member_iterator(0);
+ }
+
+ /// findValue - Return an iterator to the specified value. If it does not
+ /// exist, end() is returned.
+ iterator findValue(const ElemTy &V) const {
+ return TheMapping.find(V);
+ }
+
+ /// getLeaderValue - Return the leader for the specified value that is in the
+ /// set. It is an error to call this method for a value that is not yet in
+ /// the set. For that, call getOrInsertLeaderValue(V).
+ const ElemTy &getLeaderValue(const ElemTy &V) const {
+ member_iterator MI = findLeader(V);
+ assert(MI != member_end() && "Value is not in the set!");
+ return *MI;
+ }
+
+ /// getOrInsertLeaderValue - Return the leader for the specified value that is
+ /// in the set. If the member is not in the set, it is inserted, then
+ /// returned.
+ const ElemTy &getOrInsertLeaderValue(const ElemTy &V) {
+ member_iterator MI = findLeader(insert(V));
+ assert(MI != member_end() && "Value is not in the set!");
+ return *MI;
+ }
+
+ /// getNumClasses - Return the number of equivalence classes in this set.
+ /// Note that this is a linear time operation.
+ unsigned getNumClasses() const {
+ unsigned NC = 0;
+ for (iterator I = begin(), E = end(); I != E; ++I)
+ if (I->isLeader()) ++NC;
+ return NC;
+ }
+
+
+ //===--------------------------------------------------------------------===//
+ // Mutation methods
+
+ /// insert - Insert a new value into the union/find set, ignoring the request
+ /// if the value already exists.
+ iterator insert(const ElemTy &Data) {
+ return TheMapping.insert(ECValue(Data)).first;
+ }
+
+ /// findLeader - Given a value in the set, return a member iterator for the
+ /// equivalence class it is in. This does the path-compression part that
+ /// makes union-find "union findy". This returns an end iterator if the value
+ /// is not in the equivalence class.
+ ///
+ member_iterator findLeader(iterator I) const {
+ if (I == TheMapping.end()) return member_end();
+ return member_iterator(I->getLeader());
+ }
+ member_iterator findLeader(const ElemTy &V) const {
+ return findLeader(TheMapping.find(V));
+ }
+
+
+ /// union - Merge the two equivalence sets for the specified values, inserting
+ /// them if they do not already exist in the equivalence set.
+ member_iterator unionSets(const ElemTy &V1, const ElemTy &V2) {
+ iterator V1I = insert(V1), V2I = insert(V2);
+ return unionSets(findLeader(V1I), findLeader(V2I));
+ }
+ member_iterator unionSets(member_iterator L1, member_iterator L2) {
+ assert(L1 != member_end() && L2 != member_end() && "Illegal inputs!");
+ if (L1 == L2) return L1; // Unifying the same two sets, noop.
+
+ // Otherwise, this is a real union operation. Set the end of the L1 list to
+ // point to the L2 leader node.
+ const ECValue &L1LV = *L1.Node, &L2LV = *L2.Node;
+ L1LV.getEndOfList()->setNext(&L2LV);
+
+ // Update L1LV's end of list pointer.
+ L1LV.Leader = L2LV.getEndOfList();
+
+ // Clear L2's leader flag:
+ L2LV.Next = L2LV.getNext();
+
+ // L2's leader is now L1.
+ L2LV.Leader = &L1LV;
+ return L1;
+ }
+
+ class member_iterator : public std::iterator<std::forward_iterator_tag,
+ const ElemTy, ptrdiff_t> {
+ typedef std::iterator<std::forward_iterator_tag,
+ const ElemTy, ptrdiff_t> super;
+ const ECValue *Node;
+ friend class EquivalenceClasses;
+ public:
+ typedef size_t size_type;
+ typedef typename super::pointer pointer;
+ typedef typename super::reference reference;
+
+ explicit member_iterator() {}
+ explicit member_iterator(const ECValue *N) : Node(N) {}
+ member_iterator(const member_iterator &I) : Node(I.Node) {}
+
+ reference operator*() const {
+ assert(Node != 0 && "Dereferencing end()!");
+ return Node->getData();
+ }
+ reference operator->() const { return operator*(); }
+
+ member_iterator &operator++() {
+ assert(Node != 0 && "++'d off the end of the list!");
+ Node = Node->getNext();
+ return *this;
+ }
+
+ member_iterator operator++(int) { // postincrement operators.
+ member_iterator tmp = *this;
+ ++*this;
+ return tmp;
+ }
+
+ bool operator==(const member_iterator &RHS) const {
+ return Node == RHS.Node;
+ }
+ bool operator!=(const member_iterator &RHS) const {
+ return Node != RHS.Node;
+ }
+ };
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/FoldingSet.h b/include/llvm/ADT/FoldingSet.h
new file mode 100644
index 00000000000..375d84abebd
--- /dev/null
+++ b/include/llvm/ADT/FoldingSet.h
@@ -0,0 +1,794 @@
+//===-- llvm/ADT/FoldingSet.h - Uniquing Hash Set ---------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a hash set that can be used to remove duplication of nodes
+// in a graph. This code was originally created by Chris Lattner for use with
+// SelectionDAGCSEMap, but was isolated to provide use across the llvm code set.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_FOLDINGSET_H
+#define LLVM_ADT_FOLDINGSET_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+ class APFloat;
+ class APInt;
+ class BumpPtrAllocator;
+
+/// This folding set used for two purposes:
+/// 1. Given information about a node we want to create, look up the unique
+/// instance of the node in the set. If the node already exists, return
+/// it, otherwise return the bucket it should be inserted into.
+/// 2. Given a node that has already been created, remove it from the set.
+///
+/// This class is implemented as a single-link chained hash table, where the
+/// "buckets" are actually the nodes themselves (the next pointer is in the
+/// node). The last node points back to the bucket to simplify node removal.
+///
+/// Any node that is to be included in the folding set must be a subclass of
+/// FoldingSetNode. The node class must also define a Profile method used to
+/// establish the unique bits of data for the node. The Profile method is
+/// passed a FoldingSetNodeID object which is used to gather the bits. Just
+/// call one of the Add* functions defined in the FoldingSetImpl::NodeID class.
+/// NOTE: That the folding set does not own the nodes and it is the
+/// responsibility of the user to dispose of the nodes.
+///
+/// Eg.
+/// class MyNode : public FoldingSetNode {
+/// private:
+/// std::string Name;
+/// unsigned Value;
+/// public:
+/// MyNode(const char *N, unsigned V) : Name(N), Value(V) {}
+/// ...
+/// void Profile(FoldingSetNodeID &ID) const {
+/// ID.AddString(Name);
+/// ID.AddInteger(Value);
+/// }
+/// ...
+/// };
+///
+/// To define the folding set itself use the FoldingSet template;
+///
+/// Eg.
+/// FoldingSet<MyNode> MyFoldingSet;
+///
+/// Four public methods are available to manipulate the folding set;
+///
+/// 1) If you have an existing node that you want add to the set but unsure
+/// that the node might already exist then call;
+///
+/// MyNode *M = MyFoldingSet.GetOrInsertNode(N);
+///
+/// If The result is equal to the input then the node has been inserted.
+/// Otherwise, the result is the node existing in the folding set, and the
+/// input can be discarded (use the result instead.)
+///
+/// 2) If you are ready to construct a node but want to check if it already
+/// exists, then call FindNodeOrInsertPos with a FoldingSetNodeID of the bits to
+/// check;
+///
+/// FoldingSetNodeID ID;
+/// ID.AddString(Name);
+/// ID.AddInteger(Value);
+/// void *InsertPoint;
+///
+/// MyNode *M = MyFoldingSet.FindNodeOrInsertPos(ID, InsertPoint);
+///
+/// If found then M with be non-NULL, else InsertPoint will point to where it
+/// should be inserted using InsertNode.
+///
+/// 3) If you get a NULL result from FindNodeOrInsertPos then you can as a new
+/// node with FindNodeOrInsertPos;
+///
+/// InsertNode(N, InsertPoint);
+///
+/// 4) Finally, if you want to remove a node from the folding set call;
+///
+/// bool WasRemoved = RemoveNode(N);
+///
+/// The result indicates whether the node existed in the folding set.
+
+class FoldingSetNodeID;
+
+//===----------------------------------------------------------------------===//
+/// FoldingSetImpl - Implements the folding set functionality. The main
+/// structure is an array of buckets. Each bucket is indexed by the hash of
+/// the nodes it contains. The bucket itself points to the nodes contained
+/// in the bucket via a singly linked list. The last node in the list points
+/// back to the bucket to facilitate node removal.
+///
+class FoldingSetImpl {
+protected:
+ /// Buckets - Array of bucket chains.
+ ///
+ void **Buckets;
+
+ /// NumBuckets - Length of the Buckets array. Always a power of 2.
+ ///
+ unsigned NumBuckets;
+
+ /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
+ /// is greater than twice the number of buckets.
+ unsigned NumNodes;
+
+public:
+ explicit FoldingSetImpl(unsigned Log2InitSize = 6);
+ virtual ~FoldingSetImpl();
+
+ //===--------------------------------------------------------------------===//
+ /// Node - This class is used to maintain the singly linked bucket list in
+ /// a folding set.
+ ///
+ class Node {
+ private:
+ // NextInFoldingSetBucket - next link in the bucket list.
+ void *NextInFoldingSetBucket;
+
+ public:
+
+ Node() : NextInFoldingSetBucket(0) {}
+
+ // Accessors
+ void *getNextInBucket() const { return NextInFoldingSetBucket; }
+ void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
+ };
+
+ /// clear - Remove all nodes from the folding set.
+ void clear();
+
+ /// RemoveNode - Remove a node from the folding set, returning true if one
+ /// was removed or false if the node was not in the folding set.
+ bool RemoveNode(Node *N);
+
+ /// GetOrInsertNode - If there is an existing simple Node exactly
+ /// equal to the specified node, return it. Otherwise, insert 'N' and return
+ /// it instead.
+ Node *GetOrInsertNode(Node *N);
+
+ /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
+ /// return it. If not, return the insertion token that will make insertion
+ /// faster.
+ Node *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
+
+ /// InsertNode - Insert the specified node into the folding set, knowing that
+ /// it is not already in the folding set. InsertPos must be obtained from
+ /// FindNodeOrInsertPos.
+ void InsertNode(Node *N, void *InsertPos);
+
+ /// InsertNode - Insert the specified node into the folding set, knowing that
+ /// it is not already in the folding set.
+ void InsertNode(Node *N) {
+ Node *Inserted = GetOrInsertNode(N);
+ (void)Inserted;
+ assert(Inserted == N && "Node already inserted!");
+ }
+
+ /// size - Returns the number of nodes in the folding set.
+ unsigned size() const { return NumNodes; }
+
+ /// empty - Returns true if there are no nodes in the folding set.
+ bool empty() const { return NumNodes == 0; }
+
+private:
+
+ /// GrowHashTable - Double the size of the hash table and rehash everything.
+ ///
+ void GrowHashTable();
+
+protected:
+
+ /// GetNodeProfile - Instantiations of the FoldingSet template implement
+ /// this function to gather data bits for the given node.
+ virtual void GetNodeProfile(Node *N, FoldingSetNodeID &ID) const = 0;
+ /// NodeEquals - Instantiations of the FoldingSet template implement
+ /// this function to compare the given node with the given ID.
+ virtual bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned IDHash,
+ FoldingSetNodeID &TempID) const=0;
+ /// ComputeNodeHash - Instantiations of the FoldingSet template implement
+ /// this function to compute a hash value for the given node.
+ virtual unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) const = 0;
+};
+
+//===----------------------------------------------------------------------===//
+
+template<typename T> struct FoldingSetTrait;
+
+/// DefaultFoldingSetTrait - This class provides default implementations
+/// for FoldingSetTrait implementations.
+///
+template<typename T> struct DefaultFoldingSetTrait {
+ static void Profile(const T &X, FoldingSetNodeID &ID) {
+ X.Profile(ID);
+ }
+ static void Profile(T &X, FoldingSetNodeID &ID) {
+ X.Profile(ID);
+ }
+
+ // Equals - Test if the profile for X would match ID, using TempID
+ // to compute a temporary ID if necessary. The default implementation
+ // just calls Profile and does a regular comparison. Implementations
+ // can override this to provide more efficient implementations.
+ static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
+ FoldingSetNodeID &TempID);
+
+ // ComputeHash - Compute a hash value for X, using TempID to
+ // compute a temporary ID if necessary. The default implementation
+ // just calls Profile and does a regular hash computation.
+ // Implementations can override this to provide more efficient
+ // implementations.
+ static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID);
+};
+
+/// FoldingSetTrait - This trait class is used to define behavior of how
+/// to "profile" (in the FoldingSet parlance) an object of a given type.
+/// The default behavior is to invoke a 'Profile' method on an object, but
+/// through template specialization the behavior can be tailored for specific
+/// types. Combined with the FoldingSetNodeWrapper class, one can add objects
+/// to FoldingSets that were not originally designed to have that behavior.
+template<typename T> struct FoldingSetTrait
+ : public DefaultFoldingSetTrait<T> {};
+
+template<typename T, typename Ctx> struct ContextualFoldingSetTrait;
+
+/// DefaultContextualFoldingSetTrait - Like DefaultFoldingSetTrait, but
+/// for ContextualFoldingSets.
+template<typename T, typename Ctx>
+struct DefaultContextualFoldingSetTrait {
+ static void Profile(T &X, FoldingSetNodeID &ID, Ctx Context) {
+ X.Profile(ID, Context);
+ }
+ static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
+ FoldingSetNodeID &TempID, Ctx Context);
+ static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID,
+ Ctx Context);
+};
+
+/// ContextualFoldingSetTrait - Like FoldingSetTrait, but for
+/// ContextualFoldingSets.
+template<typename T, typename Ctx> struct ContextualFoldingSetTrait
+ : public DefaultContextualFoldingSetTrait<T, Ctx> {};
+
+//===--------------------------------------------------------------------===//
+/// FoldingSetNodeIDRef - This class describes a reference to an interned
+/// FoldingSetNodeID, which can be a useful to store node id data rather
+/// than using plain FoldingSetNodeIDs, since the 32-element SmallVector
+/// is often much larger than necessary, and the possibility of heap
+/// allocation means it requires a non-trivial destructor call.
+class FoldingSetNodeIDRef {
+ const unsigned *Data;
+ size_t Size;
+public:
+ FoldingSetNodeIDRef() : Data(0), Size(0) {}
+ FoldingSetNodeIDRef(const unsigned *D, size_t S) : Data(D), Size(S) {}
+
+ /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
+ /// used to lookup the node in the FoldingSetImpl.
+ unsigned ComputeHash() const;
+
+ bool operator==(FoldingSetNodeIDRef) const;
+
+ /// Used to compare the "ordering" of two nodes as defined by the
+ /// profiled bits and their ordering defined by memcmp().
+ bool operator<(FoldingSetNodeIDRef) const;
+
+ const unsigned *getData() const { return Data; }
+ size_t getSize() const { return Size; }
+};
+
+//===--------------------------------------------------------------------===//
+/// FoldingSetNodeID - This class is used to gather all the unique data bits of
+/// a node. When all the bits are gathered this class is used to produce a
+/// hash value for the node.
+///
+class FoldingSetNodeID {
+ /// Bits - Vector of all the data bits that make the node unique.
+ /// Use a SmallVector to avoid a heap allocation in the common case.
+ SmallVector<unsigned, 32> Bits;
+
+public:
+ FoldingSetNodeID() {}
+
+ FoldingSetNodeID(FoldingSetNodeIDRef Ref)
+ : Bits(Ref.getData(), Ref.getData() + Ref.getSize()) {}
+
+ /// Add* - Add various data types to Bit data.
+ ///
+ void AddPointer(const void *Ptr);
+ void AddInteger(signed I);
+ void AddInteger(unsigned I);
+ void AddInteger(long I);
+ void AddInteger(unsigned long I);
+ void AddInteger(long long I);
+ void AddInteger(unsigned long long I);
+ void AddBoolean(bool B) { AddInteger(B ? 1U : 0U); }
+ void AddString(StringRef String);
+ void AddNodeID(const FoldingSetNodeID &ID);
+
+ template <typename T>
+ inline void Add(const T &x) { FoldingSetTrait<T>::Profile(x, *this); }
+
+ /// clear - Clear the accumulated profile, allowing this FoldingSetNodeID
+ /// object to be used to compute a new profile.
+ inline void clear() { Bits.clear(); }
+
+ /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used
+ /// to lookup the node in the FoldingSetImpl.
+ unsigned ComputeHash() const;
+
+ /// operator== - Used to compare two nodes to each other.
+ ///
+ bool operator==(const FoldingSetNodeID &RHS) const;
+ bool operator==(const FoldingSetNodeIDRef RHS) const;
+
+ /// Used to compare the "ordering" of two nodes as defined by the
+ /// profiled bits and their ordering defined by memcmp().
+ bool operator<(const FoldingSetNodeID &RHS) const;
+ bool operator<(const FoldingSetNodeIDRef RHS) const;
+
+ /// Intern - Copy this node's data to a memory region allocated from the
+ /// given allocator and return a FoldingSetNodeIDRef describing the
+ /// interned data.
+ FoldingSetNodeIDRef Intern(BumpPtrAllocator &Allocator) const;
+};
+
+// Convenience type to hide the implementation of the folding set.
+typedef FoldingSetImpl::Node FoldingSetNode;
+template<class T> class FoldingSetIterator;
+template<class T> class FoldingSetBucketIterator;
+
+// Definitions of FoldingSetTrait and ContextualFoldingSetTrait functions, which
+// require the definition of FoldingSetNodeID.
+template<typename T>
+inline bool
+DefaultFoldingSetTrait<T>::Equals(T &X, const FoldingSetNodeID &ID,
+ unsigned IDHash, FoldingSetNodeID &TempID) {
+ FoldingSetTrait<T>::Profile(X, TempID);
+ return TempID == ID;
+}
+template<typename T>
+inline unsigned
+DefaultFoldingSetTrait<T>::ComputeHash(T &X, FoldingSetNodeID &TempID) {
+ FoldingSetTrait<T>::Profile(X, TempID);
+ return TempID.ComputeHash();
+}
+template<typename T, typename Ctx>
+inline bool
+DefaultContextualFoldingSetTrait<T, Ctx>::Equals(T &X,
+ const FoldingSetNodeID &ID,
+ unsigned IDHash,
+ FoldingSetNodeID &TempID,
+ Ctx Context) {
+ ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
+ return TempID == ID;
+}
+template<typename T, typename Ctx>
+inline unsigned
+DefaultContextualFoldingSetTrait<T, Ctx>::ComputeHash(T &X,
+ FoldingSetNodeID &TempID,
+ Ctx Context) {
+ ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
+ return TempID.ComputeHash();
+}
+
+//===----------------------------------------------------------------------===//
+/// FoldingSet - This template class is used to instantiate a specialized
+/// implementation of the folding set to the node class T. T must be a
+/// subclass of FoldingSetNode and implement a Profile function.
+///
+template<class T> class FoldingSet : public FoldingSetImpl {
+private:
+ /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
+ /// way to convert nodes into a unique specifier.
+ virtual void GetNodeProfile(Node *N, FoldingSetNodeID &ID) const {
+ T *TN = static_cast<T *>(N);
+ FoldingSetTrait<T>::Profile(*TN, ID);
+ }
+ /// NodeEquals - Instantiations may optionally provide a way to compare a
+ /// node with a specified ID.
+ virtual bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned IDHash,
+ FoldingSetNodeID &TempID) const {
+ T *TN = static_cast<T *>(N);
+ return FoldingSetTrait<T>::Equals(*TN, ID, IDHash, TempID);
+ }
+ /// ComputeNodeHash - Instantiations may optionally provide a way to compute a
+ /// hash value directly from a node.
+ virtual unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) const {
+ T *TN = static_cast<T *>(N);
+ return FoldingSetTrait<T>::ComputeHash(*TN, TempID);
+ }
+
+public:
+ explicit FoldingSet(unsigned Log2InitSize = 6)
+ : FoldingSetImpl(Log2InitSize)
+ {}
+
+ typedef FoldingSetIterator<T> iterator;
+ iterator begin() { return iterator(Buckets); }
+ iterator end() { return iterator(Buckets+NumBuckets); }
+
+ typedef FoldingSetIterator<const T> const_iterator;
+ const_iterator begin() const { return const_iterator(Buckets); }
+ const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
+
+ typedef FoldingSetBucketIterator<T> bucket_iterator;
+
+ bucket_iterator bucket_begin(unsigned hash) {
+ return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
+ }
+
+ bucket_iterator bucket_end(unsigned hash) {
+ return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
+ }
+
+ /// GetOrInsertNode - If there is an existing simple Node exactly
+ /// equal to the specified node, return it. Otherwise, insert 'N' and
+ /// return it instead.
+ T *GetOrInsertNode(Node *N) {
+ return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
+ }
+
+ /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
+ /// return it. If not, return the insertion token that will make insertion
+ /// faster.
+ T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
+ return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// ContextualFoldingSet - This template class is a further refinement
+/// of FoldingSet which provides a context argument when calling
+/// Profile on its nodes. Currently, that argument is fixed at
+/// initialization time.
+///
+/// T must be a subclass of FoldingSetNode and implement a Profile
+/// function with signature
+/// void Profile(llvm::FoldingSetNodeID &, Ctx);
+template <class T, class Ctx>
+class ContextualFoldingSet : public FoldingSetImpl {
+ // Unfortunately, this can't derive from FoldingSet<T> because the
+ // construction vtable for FoldingSet<T> requires
+ // FoldingSet<T>::GetNodeProfile to be instantiated, which in turn
+ // requires a single-argument T::Profile().
+
+private:
+ Ctx Context;
+
+ /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
+ /// way to convert nodes into a unique specifier.
+ virtual void GetNodeProfile(FoldingSetImpl::Node *N,
+ FoldingSetNodeID &ID) const {
+ T *TN = static_cast<T *>(N);
+ ContextualFoldingSetTrait<T, Ctx>::Profile(*TN, ID, Context);
+ }
+ virtual bool NodeEquals(FoldingSetImpl::Node *N,
+ const FoldingSetNodeID &ID, unsigned IDHash,
+ FoldingSetNodeID &TempID) const {
+ T *TN = static_cast<T *>(N);
+ return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, IDHash, TempID,
+ Context);
+ }
+ virtual unsigned ComputeNodeHash(FoldingSetImpl::Node *N,
+ FoldingSetNodeID &TempID) const {
+ T *TN = static_cast<T *>(N);
+ return ContextualFoldingSetTrait<T, Ctx>::ComputeHash(*TN, TempID, Context);
+ }
+
+public:
+ explicit ContextualFoldingSet(Ctx Context, unsigned Log2InitSize = 6)
+ : FoldingSetImpl(Log2InitSize), Context(Context)
+ {}
+
+ Ctx getContext() const { return Context; }
+
+
+ typedef FoldingSetIterator<T> iterator;
+ iterator begin() { return iterator(Buckets); }
+ iterator end() { return iterator(Buckets+NumBuckets); }
+
+ typedef FoldingSetIterator<const T> const_iterator;
+ const_iterator begin() const { return const_iterator(Buckets); }
+ const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
+
+ typedef FoldingSetBucketIterator<T> bucket_iterator;
+
+ bucket_iterator bucket_begin(unsigned hash) {
+ return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
+ }
+
+ bucket_iterator bucket_end(unsigned hash) {
+ return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
+ }
+
+ /// GetOrInsertNode - If there is an existing simple Node exactly
+ /// equal to the specified node, return it. Otherwise, insert 'N'
+ /// and return it instead.
+ T *GetOrInsertNode(Node *N) {
+ return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
+ }
+
+ /// FindNodeOrInsertPos - Look up the node specified by ID. If it
+ /// exists, return it. If not, return the insertion token that will
+ /// make insertion faster.
+ T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
+ return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// FoldingSetVectorIterator - This implements an iterator for
+/// FoldingSetVector. It is only necessary because FoldingSetIterator provides
+/// a value_type of T, while the vector in FoldingSetVector exposes
+/// a value_type of T*. Fortunately, FoldingSetIterator doesn't expose very
+/// much besides operator* and operator->, so we just wrap the inner vector
+/// iterator and perform the extra dereference.
+template <class T, class VectorIteratorT>
+class FoldingSetVectorIterator {
+ // Provide a typedef to workaround the lack of correct injected class name
+ // support in older GCCs.
+ typedef FoldingSetVectorIterator<T, VectorIteratorT> SelfT;
+
+ VectorIteratorT Iterator;
+
+public:
+ FoldingSetVectorIterator(VectorIteratorT I) : Iterator(I) {}
+
+ bool operator==(const SelfT &RHS) const {
+ return Iterator == RHS.Iterator;
+ }
+ bool operator!=(const SelfT &RHS) const {
+ return Iterator != RHS.Iterator;
+ }
+
+ T &operator*() const { return **Iterator; }
+
+ T *operator->() const { return *Iterator; }
+
+ inline SelfT &operator++() {
+ ++Iterator;
+ return *this;
+ }
+ SelfT operator++(int) {
+ SelfT tmp = *this;
+ ++*this;
+ return tmp;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// FoldingSetVector - This template class combines a FoldingSet and a vector
+/// to provide the interface of FoldingSet but with deterministic iteration
+/// order based on the insertion order. T must be a subclass of FoldingSetNode
+/// and implement a Profile function.
+template <class T, class VectorT = SmallVector<T*, 8> >
+class FoldingSetVector {
+ FoldingSet<T> Set;
+ VectorT Vector;
+
+public:
+ explicit FoldingSetVector(unsigned Log2InitSize = 6)
+ : Set(Log2InitSize) {
+ }
+
+ typedef FoldingSetVectorIterator<T, typename VectorT::iterator> iterator;
+ iterator begin() { return Vector.begin(); }
+ iterator end() { return Vector.end(); }
+
+ typedef FoldingSetVectorIterator<const T, typename VectorT::const_iterator>
+ const_iterator;
+ const_iterator begin() const { return Vector.begin(); }
+ const_iterator end() const { return Vector.end(); }
+
+ /// clear - Remove all nodes from the folding set.
+ void clear() { Set.clear(); Vector.clear(); }
+
+ /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
+ /// return it. If not, return the insertion token that will make insertion
+ /// faster.
+ T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
+ return Set.FindNodeOrInsertPos(ID, InsertPos);
+ }
+
+ /// GetOrInsertNode - If there is an existing simple Node exactly
+ /// equal to the specified node, return it. Otherwise, insert 'N' and
+ /// return it instead.
+ T *GetOrInsertNode(T *N) {
+ T *Result = Set.GetOrInsertNode(N);
+ if (Result == N) Vector.push_back(N);
+ return Result;
+ }
+
+ /// InsertNode - Insert the specified node into the folding set, knowing that
+ /// it is not already in the folding set. InsertPos must be obtained from
+ /// FindNodeOrInsertPos.
+ void InsertNode(T *N, void *InsertPos) {
+ Set.InsertNode(N, InsertPos);
+ Vector.push_back(N);
+ }
+
+ /// InsertNode - Insert the specified node into the folding set, knowing that
+ /// it is not already in the folding set.
+ void InsertNode(T *N) {
+ Set.InsertNode(N);
+ Vector.push_back(N);
+ }
+
+ /// size - Returns the number of nodes in the folding set.
+ unsigned size() const { return Set.size(); }
+
+ /// empty - Returns true if there are no nodes in the folding set.
+ bool empty() const { return Set.empty(); }
+};
+
+//===----------------------------------------------------------------------===//
+/// FoldingSetIteratorImpl - This is the common iterator support shared by all
+/// folding sets, which knows how to walk the folding set hash table.
+class FoldingSetIteratorImpl {
+protected:
+ FoldingSetNode *NodePtr;
+ FoldingSetIteratorImpl(void **Bucket);
+ void advance();
+
+public:
+ bool operator==(const FoldingSetIteratorImpl &RHS) const {
+ return NodePtr == RHS.NodePtr;
+ }
+ bool operator!=(const FoldingSetIteratorImpl &RHS) const {
+ return NodePtr != RHS.NodePtr;
+ }
+};
+
+
+template<class T>
+class FoldingSetIterator : public FoldingSetIteratorImpl {
+public:
+ explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
+
+ T &operator*() const {
+ return *static_cast<T*>(NodePtr);
+ }
+
+ T *operator->() const {
+ return static_cast<T*>(NodePtr);
+ }
+
+ inline FoldingSetIterator &operator++() { // Preincrement
+ advance();
+ return *this;
+ }
+ FoldingSetIterator operator++(int) { // Postincrement
+ FoldingSetIterator tmp = *this; ++*this; return tmp;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
+/// shared by all folding sets, which knows how to walk a particular bucket
+/// of a folding set hash table.
+
+class FoldingSetBucketIteratorImpl {
+protected:
+ void *Ptr;
+
+ explicit FoldingSetBucketIteratorImpl(void **Bucket);
+
+ FoldingSetBucketIteratorImpl(void **Bucket, bool)
+ : Ptr(Bucket) {}
+
+ void advance() {
+ void *Probe = static_cast<FoldingSetNode*>(Ptr)->getNextInBucket();
+ uintptr_t x = reinterpret_cast<uintptr_t>(Probe) & ~0x1;
+ Ptr = reinterpret_cast<void*>(x);
+ }
+
+public:
+ bool operator==(const FoldingSetBucketIteratorImpl &RHS) const {
+ return Ptr == RHS.Ptr;
+ }
+ bool operator!=(const FoldingSetBucketIteratorImpl &RHS) const {
+ return Ptr != RHS.Ptr;
+ }
+};
+
+
+template<class T>
+class FoldingSetBucketIterator : public FoldingSetBucketIteratorImpl {
+public:
+ explicit FoldingSetBucketIterator(void **Bucket) :
+ FoldingSetBucketIteratorImpl(Bucket) {}
+
+ FoldingSetBucketIterator(void **Bucket, bool) :
+ FoldingSetBucketIteratorImpl(Bucket, true) {}
+
+ T &operator*() const { return *static_cast<T*>(Ptr); }
+ T *operator->() const { return static_cast<T*>(Ptr); }
+
+ inline FoldingSetBucketIterator &operator++() { // Preincrement
+ advance();
+ return *this;
+ }
+ FoldingSetBucketIterator operator++(int) { // Postincrement
+ FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
+/// types in an enclosing object so that they can be inserted into FoldingSets.
+template <typename T>
+class FoldingSetNodeWrapper : public FoldingSetNode {
+ T data;
+public:
+ explicit FoldingSetNodeWrapper(const T &x) : data(x) {}
+ virtual ~FoldingSetNodeWrapper() {}
+
+ template<typename A1>
+ explicit FoldingSetNodeWrapper(const A1 &a1)
+ : data(a1) {}
+
+ template <typename A1, typename A2>
+ explicit FoldingSetNodeWrapper(const A1 &a1, const A2 &a2)
+ : data(a1,a2) {}
+
+ template <typename A1, typename A2, typename A3>
+ explicit FoldingSetNodeWrapper(const A1 &a1, const A2 &a2, const A3 &a3)
+ : data(a1,a2,a3) {}
+
+ template <typename A1, typename A2, typename A3, typename A4>
+ explicit FoldingSetNodeWrapper(const A1 &a1, const A2 &a2, const A3 &a3,
+ const A4 &a4)
+ : data(a1,a2,a3,a4) {}
+
+ template <typename A1, typename A2, typename A3, typename A4, typename A5>
+ explicit FoldingSetNodeWrapper(const A1 &a1, const A2 &a2, const A3 &a3,
+ const A4 &a4, const A5 &a5)
+ : data(a1,a2,a3,a4,a5) {}
+
+
+ void Profile(FoldingSetNodeID &ID) { FoldingSetTrait<T>::Profile(data, ID); }
+
+ T &getValue() { return data; }
+ const T &getValue() const { return data; }
+
+ operator T&() { return data; }
+ operator const T&() const { return data; }
+};
+
+//===----------------------------------------------------------------------===//
+/// FastFoldingSetNode - This is a subclass of FoldingSetNode which stores
+/// a FoldingSetNodeID value rather than requiring the node to recompute it
+/// each time it is needed. This trades space for speed (which can be
+/// significant if the ID is long), and it also permits nodes to drop
+/// information that would otherwise only be required for recomputing an ID.
+class FastFoldingSetNode : public FoldingSetNode {
+ FoldingSetNodeID FastID;
+protected:
+ explicit FastFoldingSetNode(const FoldingSetNodeID &ID) : FastID(ID) {}
+public:
+ void Profile(FoldingSetNodeID &ID) const {
+ ID.AddNodeID(FastID);
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// Partial specializations of FoldingSetTrait.
+
+template<typename T> struct FoldingSetTrait<T*> {
+ static inline void Profile(T *X, FoldingSetNodeID &ID) {
+ ID.AddPointer(X);
+ }
+};
+} // End of namespace llvm.
+
+#endif
diff --git a/include/llvm/ADT/GraphTraits.h b/include/llvm/ADT/GraphTraits.h
new file mode 100644
index 00000000000..823caef7647
--- /dev/null
+++ b/include/llvm/ADT/GraphTraits.h
@@ -0,0 +1,106 @@
+//===-- llvm/ADT/GraphTraits.h - Graph traits template ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the little GraphTraits<X> template class that should be
+// specialized by classes that want to be iteratable by generic graph iterators.
+//
+// This file also defines the marker class Inverse that is used to iterate over
+// graphs in a graph defined, inverse ordering...
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_GRAPHTRAITS_H
+#define LLVM_ADT_GRAPHTRAITS_H
+
+namespace llvm {
+
+// GraphTraits - This class should be specialized by different graph types...
+// which is why the default version is empty.
+//
+template<class GraphType>
+struct GraphTraits {
+ // Elements to provide:
+
+ // typedef NodeType - Type of Node in the graph
+ // typedef ChildIteratorType - Type used to iterate over children in graph
+
+ // static NodeType *getEntryNode(const GraphType &)
+ // Return the entry node of the graph
+
+ // static ChildIteratorType child_begin(NodeType *)
+ // static ChildIteratorType child_end (NodeType *)
+ // Return iterators that point to the beginning and ending of the child
+ // node list for the specified node.
+ //
+
+
+ // typedef ...iterator nodes_iterator;
+ // static nodes_iterator nodes_begin(GraphType *G)
+ // static nodes_iterator nodes_end (GraphType *G)
+ // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
+
+ // static unsigned size (GraphType *G)
+ // Return total number of nodes in the graph
+ //
+
+
+ // If anyone tries to use this class without having an appropriate
+ // specialization, make an error. If you get this error, it's because you
+ // need to include the appropriate specialization of GraphTraits<> for your
+ // graph, or you need to define it for a new graph type. Either that or
+ // your argument to XXX_begin(...) is unknown or needs to have the proper .h
+ // file #include'd.
+ //
+ typedef typename GraphType::UnknownGraphTypeError NodeType;
+};
+
+
+// Inverse - This class is used as a little marker class to tell the graph
+// iterator to iterate over the graph in a graph defined "Inverse" ordering.
+// Not all graphs define an inverse ordering, and if they do, it depends on
+// the graph exactly what that is. Here's an example of usage with the
+// df_iterator:
+//
+// idf_iterator<Method*> I = idf_begin(M), E = idf_end(M);
+// for (; I != E; ++I) { ... }
+//
+// Which is equivalent to:
+// df_iterator<Inverse<Method*> > I = idf_begin(M), E = idf_end(M);
+// for (; I != E; ++I) { ... }
+//
+template <class GraphType>
+struct Inverse {
+ const GraphType &Graph;
+
+ inline Inverse(const GraphType &G) : Graph(G) {}
+};
+
+// Provide a partial specialization of GraphTraits so that the inverse of an
+// inverse falls back to the original graph.
+template<class T>
+struct GraphTraits<Inverse<Inverse<T> > > {
+ typedef typename GraphTraits<T>::NodeType NodeType;
+ typedef typename GraphTraits<T>::ChildIteratorType ChildIteratorType;
+
+ static NodeType *getEntryNode(Inverse<Inverse<T> > *G) {
+ return GraphTraits<T>::getEntryNode(G->Graph.Graph);
+ }
+
+ static ChildIteratorType child_begin(NodeType* N) {
+ return GraphTraits<T>::child_begin(N);
+ }
+
+ static ChildIteratorType child_end(NodeType* N) {
+ return GraphTraits<T>::child_end(N);
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/Hashing.h b/include/llvm/ADT/Hashing.h
new file mode 100644
index 00000000000..cda31a261df
--- /dev/null
+++ b/include/llvm/ADT/Hashing.h
@@ -0,0 +1,765 @@
+//===-- llvm/ADT/Hashing.h - Utilities for hashing --------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the newly proposed standard C++ interfaces for hashing
+// arbitrary data and building hash functions for user-defined types. This
+// interface was originally proposed in N3333[1] and is currently under review
+// for inclusion in a future TR and/or standard.
+//
+// The primary interfaces provide are comprised of one type and three functions:
+//
+// -- 'hash_code' class is an opaque type representing the hash code for some
+// data. It is the intended product of hashing, and can be used to implement
+// hash tables, checksumming, and other common uses of hashes. It is not an
+// integer type (although it can be converted to one) because it is risky
+// to assume much about the internals of a hash_code. In particular, each
+// execution of the program has a high probability of producing a different
+// hash_code for a given input. Thus their values are not stable to save or
+// persist, and should only be used during the execution for the
+// construction of hashing datastructures.
+//
+// -- 'hash_value' is a function designed to be overloaded for each
+// user-defined type which wishes to be used within a hashing context. It
+// should be overloaded within the user-defined type's namespace and found
+// via ADL. Overloads for primitive types are provided by this library.
+//
+// -- 'hash_combine' and 'hash_combine_range' are functions designed to aid
+// programmers in easily and intuitively combining a set of data into
+// a single hash_code for their object. They should only logically be used
+// within the implementation of a 'hash_value' routine or similar context.
+//
+// Note that 'hash_combine_range' contains very special logic for hashing
+// a contiguous array of integers or pointers. This logic is *extremely* fast,
+// on a modern Intel "Gainestown" Xeon (Nehalem uarch) @2.2 GHz, these were
+// benchmarked at over 6.5 GiB/s for large keys, and <20 cycles/hash for keys
+// under 32-bytes.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_HASHING_H
+#define LLVM_ADT_HASHING_H
+
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/Host.h"
+#include "llvm/Support/SwapByteOrder.h"
+#include "llvm/Support/type_traits.h"
+#include <algorithm>
+#include <cassert>
+#include <cstring>
+#include <iterator>
+#include <utility>
+
+// Allow detecting C++11 feature availability when building with Clang without
+// breaking other compilers.
+#ifndef __has_feature
+# define __has_feature(x) 0
+#endif
+
+namespace llvm {
+
+/// \brief An opaque object representing a hash code.
+///
+/// This object represents the result of hashing some entity. It is intended to
+/// be used to implement hashtables or other hashing-based data structures.
+/// While it wraps and exposes a numeric value, this value should not be
+/// trusted to be stable or predictable across processes or executions.
+///
+/// In order to obtain the hash_code for an object 'x':
+/// \code
+/// using llvm::hash_value;
+/// llvm::hash_code code = hash_value(x);
+/// \endcode
+class hash_code {
+ size_t value;
+
+public:
+ /// \brief Default construct a hash_code.
+ /// Note that this leaves the value uninitialized.
+ hash_code() {}
+
+ /// \brief Form a hash code directly from a numerical value.
+ hash_code(size_t value) : value(value) {}
+
+ /// \brief Convert the hash code to its numerical value for use.
+ /*explicit*/ operator size_t() const { return value; }
+
+ friend bool operator==(const hash_code &lhs, const hash_code &rhs) {
+ return lhs.value == rhs.value;
+ }
+ friend bool operator!=(const hash_code &lhs, const hash_code &rhs) {
+ return lhs.value != rhs.value;
+ }
+
+ /// \brief Allow a hash_code to be directly run through hash_value.
+ friend size_t hash_value(const hash_code &code) { return code.value; }
+};
+
+/// \brief Compute a hash_code for any integer value.
+///
+/// Note that this function is intended to compute the same hash_code for
+/// a particular value without regard to the pre-promotion type. This is in
+/// contrast to hash_combine which may produce different hash_codes for
+/// differing argument types even if they would implicit promote to a common
+/// type without changing the value.
+template <typename T>
+typename enable_if<is_integral_or_enum<T>, hash_code>::type hash_value(T value);
+
+/// \brief Compute a hash_code for a pointer's address.
+///
+/// N.B.: This hashes the *address*. Not the value and not the type.
+template <typename T> hash_code hash_value(const T *ptr);
+
+/// \brief Compute a hash_code for a pair of objects.
+template <typename T, typename U>
+hash_code hash_value(const std::pair<T, U> &arg);
+
+/// \brief Compute a hash_code for a standard string.
+template <typename T>
+hash_code hash_value(const std::basic_string<T> &arg);
+
+
+/// \brief Override the execution seed with a fixed value.
+///
+/// This hashing library uses a per-execution seed designed to change on each
+/// run with high probability in order to ensure that the hash codes are not
+/// attackable and to ensure that output which is intended to be stable does
+/// not rely on the particulars of the hash codes produced.
+///
+/// That said, there are use cases where it is important to be able to
+/// reproduce *exactly* a specific behavior. To that end, we provide a function
+/// which will forcibly set the seed to a fixed value. This must be done at the
+/// start of the program, before any hashes are computed. Also, it cannot be
+/// undone. This makes it thread-hostile and very hard to use outside of
+/// immediately on start of a simple program designed for reproducible
+/// behavior.
+void set_fixed_execution_hash_seed(size_t fixed_value);
+
+
+// All of the implementation details of actually computing the various hash
+// code values are held within this namespace. These routines are included in
+// the header file mainly to allow inlining and constant propagation.
+namespace hashing {
+namespace detail {
+
+inline uint64_t fetch64(const char *p) {
+ uint64_t result;
+ memcpy(&result, p, sizeof(result));
+ if (sys::isBigEndianHost())
+ return sys::SwapByteOrder(result);
+ return result;
+}
+
+inline uint32_t fetch32(const char *p) {
+ uint32_t result;
+ memcpy(&result, p, sizeof(result));
+ if (sys::isBigEndianHost())
+ return sys::SwapByteOrder(result);
+ return result;
+}
+
+/// Some primes between 2^63 and 2^64 for various uses.
+static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
+static const uint64_t k1 = 0xb492b66fbe98f273ULL;
+static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
+static const uint64_t k3 = 0xc949d7c7509e6557ULL;
+
+/// \brief Bitwise right rotate.
+/// Normally this will compile to a single instruction, especially if the
+/// shift is a manifest constant.
+inline uint64_t rotate(uint64_t val, size_t shift) {
+ // Avoid shifting by 64: doing so yields an undefined result.
+ return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
+}
+
+inline uint64_t shift_mix(uint64_t val) {
+ return val ^ (val >> 47);
+}
+
+inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) {
+ // Murmur-inspired hashing.
+ const uint64_t kMul = 0x9ddfea08eb382d69ULL;
+ uint64_t a = (low ^ high) * kMul;
+ a ^= (a >> 47);
+ uint64_t b = (high ^ a) * kMul;
+ b ^= (b >> 47);
+ b *= kMul;
+ return b;
+}
+
+inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) {
+ uint8_t a = s[0];
+ uint8_t b = s[len >> 1];
+ uint8_t c = s[len - 1];
+ uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
+ uint32_t z = len + (static_cast<uint32_t>(c) << 2);
+ return shift_mix(y * k2 ^ z * k3 ^ seed) * k2;
+}
+
+inline uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed) {
+ uint64_t a = fetch32(s);
+ return hash_16_bytes(len + (a << 3), seed ^ fetch32(s + len - 4));
+}
+
+inline uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed) {
+ uint64_t a = fetch64(s);
+ uint64_t b = fetch64(s + len - 8);
+ return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b;
+}
+
+inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) {
+ uint64_t a = fetch64(s) * k1;
+ uint64_t b = fetch64(s + 8);
+ uint64_t c = fetch64(s + len - 8) * k2;
+ uint64_t d = fetch64(s + len - 16) * k0;
+ return hash_16_bytes(rotate(a - b, 43) + rotate(c ^ seed, 30) + d,
+ a + rotate(b ^ k3, 20) - c + len + seed);
+}
+
+inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) {
+ uint64_t z = fetch64(s + 24);
+ uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0;
+ uint64_t b = rotate(a + z, 52);
+ uint64_t c = rotate(a, 37);
+ a += fetch64(s + 8);
+ c += rotate(a, 7);
+ a += fetch64(s + 16);
+ uint64_t vf = a + z;
+ uint64_t vs = b + rotate(a, 31) + c;
+ a = fetch64(s + 16) + fetch64(s + len - 32);
+ z = fetch64(s + len - 8);
+ b = rotate(a + z, 52);
+ c = rotate(a, 37);
+ a += fetch64(s + len - 24);
+ c += rotate(a, 7);
+ a += fetch64(s + len - 16);
+ uint64_t wf = a + z;
+ uint64_t ws = b + rotate(a, 31) + c;
+ uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0);
+ return shift_mix((seed ^ (r * k0)) + vs) * k2;
+}
+
+inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) {
+ if (length >= 4 && length <= 8)
+ return hash_4to8_bytes(s, length, seed);
+ if (length > 8 && length <= 16)
+ return hash_9to16_bytes(s, length, seed);
+ if (length > 16 && length <= 32)
+ return hash_17to32_bytes(s, length, seed);
+ if (length > 32)
+ return hash_33to64_bytes(s, length, seed);
+ if (length != 0)
+ return hash_1to3_bytes(s, length, seed);
+
+ return k2 ^ seed;
+}
+
+/// \brief The intermediate state used during hashing.
+/// Currently, the algorithm for computing hash codes is based on CityHash and
+/// keeps 56 bytes of arbitrary state.
+struct hash_state {
+ uint64_t h0, h1, h2, h3, h4, h5, h6;
+ uint64_t seed;
+
+ /// \brief Create a new hash_state structure and initialize it based on the
+ /// seed and the first 64-byte chunk.
+ /// This effectively performs the initial mix.
+ static hash_state create(const char *s, uint64_t seed) {
+ hash_state state = {
+ 0, seed, hash_16_bytes(seed, k1), rotate(seed ^ k1, 49),
+ seed * k1, shift_mix(seed), 0, seed };
+ state.h6 = hash_16_bytes(state.h4, state.h5);
+ state.mix(s);
+ return state;
+ }
+
+ /// \brief Mix 32-bytes from the input sequence into the 16-bytes of 'a'
+ /// and 'b', including whatever is already in 'a' and 'b'.
+ static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) {
+ a += fetch64(s);
+ uint64_t c = fetch64(s + 24);
+ b = rotate(b + a + c, 21);
+ uint64_t d = a;
+ a += fetch64(s + 8) + fetch64(s + 16);
+ b += rotate(a, 44) + d;
+ a += c;
+ }
+
+ /// \brief Mix in a 64-byte buffer of data.
+ /// We mix all 64 bytes even when the chunk length is smaller, but we
+ /// record the actual length.
+ void mix(const char *s) {
+ h0 = rotate(h0 + h1 + h3 + fetch64(s + 8), 37) * k1;
+ h1 = rotate(h1 + h4 + fetch64(s + 48), 42) * k1;
+ h0 ^= h6;
+ h1 += h3 + fetch64(s + 40);
+ h2 = rotate(h2 + h5, 33) * k1;
+ h3 = h4 * k1;
+ h4 = h0 + h5;
+ mix_32_bytes(s, h3, h4);
+ h5 = h2 + h6;
+ h6 = h1 + fetch64(s + 16);
+ mix_32_bytes(s + 32, h5, h6);
+ std::swap(h2, h0);
+ }
+
+ /// \brief Compute the final 64-bit hash code value based on the current
+ /// state and the length of bytes hashed.
+ uint64_t finalize(size_t length) {
+ return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2,
+ hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0);
+ }
+};
+
+
+/// \brief A global, fixed seed-override variable.
+///
+/// This variable can be set using the \see llvm::set_fixed_execution_seed
+/// function. See that function for details. Do not, under any circumstances,
+/// set or read this variable.
+extern size_t fixed_seed_override;
+
+inline size_t get_execution_seed() {
+ // FIXME: This needs to be a per-execution seed. This is just a placeholder
+ // implementation. Switching to a per-execution seed is likely to flush out
+ // instability bugs and so will happen as its own commit.
+ //
+ // However, if there is a fixed seed override set the first time this is
+ // called, return that instead of the per-execution seed.
+ const uint64_t seed_prime = 0xff51afd7ed558ccdULL;
+ static size_t seed = fixed_seed_override ? fixed_seed_override
+ : (size_t)seed_prime;
+ return seed;
+}
+
+
+/// \brief Trait to indicate whether a type's bits can be hashed directly.
+///
+/// A type trait which is true if we want to combine values for hashing by
+/// reading the underlying data. It is false if values of this type must
+/// first be passed to hash_value, and the resulting hash_codes combined.
+//
+// FIXME: We want to replace is_integral_or_enum and is_pointer here with
+// a predicate which asserts that comparing the underlying storage of two
+// values of the type for equality is equivalent to comparing the two values
+// for equality. For all the platforms we care about, this holds for integers
+// and pointers, but there are platforms where it doesn't and we would like to
+// support user-defined types which happen to satisfy this property.
+template <typename T> struct is_hashable_data
+ : integral_constant<bool, ((is_integral_or_enum<T>::value ||
+ is_pointer<T>::value) &&
+ 64 % sizeof(T) == 0)> {};
+
+// Special case std::pair to detect when both types are viable and when there
+// is no alignment-derived padding in the pair. This is a bit of a lie because
+// std::pair isn't truly POD, but it's close enough in all reasonable
+// implementations for our use case of hashing the underlying data.
+template <typename T, typename U> struct is_hashable_data<std::pair<T, U> >
+ : integral_constant<bool, (is_hashable_data<T>::value &&
+ is_hashable_data<U>::value &&
+ (sizeof(T) + sizeof(U)) ==
+ sizeof(std::pair<T, U>))> {};
+
+/// \brief Helper to get the hashable data representation for a type.
+/// This variant is enabled when the type itself can be used.
+template <typename T>
+typename enable_if<is_hashable_data<T>, T>::type
+get_hashable_data(const T &value) {
+ return value;
+}
+/// \brief Helper to get the hashable data representation for a type.
+/// This variant is enabled when we must first call hash_value and use the
+/// result as our data.
+template <typename T>
+typename enable_if_c<!is_hashable_data<T>::value, size_t>::type
+get_hashable_data(const T &value) {
+ using ::llvm::hash_value;
+ return hash_value(value);
+}
+
+/// \brief Helper to store data from a value into a buffer and advance the
+/// pointer into that buffer.
+///
+/// This routine first checks whether there is enough space in the provided
+/// buffer, and if not immediately returns false. If there is space, it
+/// copies the underlying bytes of value into the buffer, advances the
+/// buffer_ptr past the copied bytes, and returns true.
+template <typename T>
+bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value,
+ size_t offset = 0) {
+ size_t store_size = sizeof(value) - offset;
+ if (buffer_ptr + store_size > buffer_end)
+ return false;
+ const char *value_data = reinterpret_cast<const char *>(&value);
+ memcpy(buffer_ptr, value_data + offset, store_size);
+ buffer_ptr += store_size;
+ return true;
+}
+
+/// \brief Implement the combining of integral values into a hash_code.
+///
+/// This overload is selected when the value type of the iterator is
+/// integral. Rather than computing a hash_code for each object and then
+/// combining them, this (as an optimization) directly combines the integers.
+template <typename InputIteratorT>
+hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) {
+ const size_t seed = get_execution_seed();
+ char buffer[64], *buffer_ptr = buffer;
+ char *const buffer_end = buffer_ptr + array_lengthof(buffer);
+ while (first != last && store_and_advance(buffer_ptr, buffer_end,
+ get_hashable_data(*first)))
+ ++first;
+ if (first == last)
+ return hash_short(buffer, buffer_ptr - buffer, seed);
+ assert(buffer_ptr == buffer_end);
+
+ hash_state state = state.create(buffer, seed);
+ size_t length = 64;
+ while (first != last) {
+ // Fill up the buffer. We don't clear it, which re-mixes the last round
+ // when only a partial 64-byte chunk is left.
+ buffer_ptr = buffer;
+ while (first != last && store_and_advance(buffer_ptr, buffer_end,
+ get_hashable_data(*first)))
+ ++first;
+
+ // Rotate the buffer if we did a partial fill in order to simulate doing
+ // a mix of the last 64-bytes. That is how the algorithm works when we
+ // have a contiguous byte sequence, and we want to emulate that here.
+ std::rotate(buffer, buffer_ptr, buffer_end);
+
+ // Mix this chunk into the current state.
+ state.mix(buffer);
+ length += buffer_ptr - buffer;
+ };
+
+ return state.finalize(length);
+}
+
+/// \brief Implement the combining of integral values into a hash_code.
+///
+/// This overload is selected when the value type of the iterator is integral
+/// and when the input iterator is actually a pointer. Rather than computing
+/// a hash_code for each object and then combining them, this (as an
+/// optimization) directly combines the integers. Also, because the integers
+/// are stored in contiguous memory, this routine avoids copying each value
+/// and directly reads from the underlying memory.
+template <typename ValueT>
+typename enable_if<is_hashable_data<ValueT>, hash_code>::type
+hash_combine_range_impl(ValueT *first, ValueT *last) {
+ const size_t seed = get_execution_seed();
+ const char *s_begin = reinterpret_cast<const char *>(first);
+ const char *s_end = reinterpret_cast<const char *>(last);
+ const size_t length = std::distance(s_begin, s_end);
+ if (length <= 64)
+ return hash_short(s_begin, length, seed);
+
+ const char *s_aligned_end = s_begin + (length & ~63);
+ hash_state state = state.create(s_begin, seed);
+ s_begin += 64;
+ while (s_begin != s_aligned_end) {
+ state.mix(s_begin);
+ s_begin += 64;
+ }
+ if (length & 63)
+ state.mix(s_end - 64);
+
+ return state.finalize(length);
+}
+
+} // namespace detail
+} // namespace hashing
+
+
+/// \brief Compute a hash_code for a sequence of values.
+///
+/// This hashes a sequence of values. It produces the same hash_code as
+/// 'hash_combine(a, b, c, ...)', but can run over arbitrary sized sequences
+/// and is significantly faster given pointers and types which can be hashed as
+/// a sequence of bytes.
+template <typename InputIteratorT>
+hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) {
+ return ::llvm::hashing::detail::hash_combine_range_impl(first, last);
+}
+
+
+// Implementation details for hash_combine.
+namespace hashing {
+namespace detail {
+
+/// \brief Helper class to manage the recursive combining of hash_combine
+/// arguments.
+///
+/// This class exists to manage the state and various calls involved in the
+/// recursive combining of arguments used in hash_combine. It is particularly
+/// useful at minimizing the code in the recursive calls to ease the pain
+/// caused by a lack of variadic functions.
+struct hash_combine_recursive_helper {
+ char buffer[64];
+ hash_state state;
+ const size_t seed;
+
+public:
+ /// \brief Construct a recursive hash combining helper.
+ ///
+ /// This sets up the state for a recursive hash combine, including getting
+ /// the seed and buffer setup.
+ hash_combine_recursive_helper()
+ : seed(get_execution_seed()) {}
+
+ /// \brief Combine one chunk of data into the current in-flight hash.
+ ///
+ /// This merges one chunk of data into the hash. First it tries to buffer
+ /// the data. If the buffer is full, it hashes the buffer into its
+ /// hash_state, empties it, and then merges the new chunk in. This also
+ /// handles cases where the data straddles the end of the buffer.
+ template <typename T>
+ char *combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data) {
+ if (!store_and_advance(buffer_ptr, buffer_end, data)) {
+ // Check for skew which prevents the buffer from being packed, and do
+ // a partial store into the buffer to fill it. This is only a concern
+ // with the variadic combine because that formation can have varying
+ // argument types.
+ size_t partial_store_size = buffer_end - buffer_ptr;
+ memcpy(buffer_ptr, &data, partial_store_size);
+
+ // If the store fails, our buffer is full and ready to hash. We have to
+ // either initialize the hash state (on the first full buffer) or mix
+ // this buffer into the existing hash state. Length tracks the *hashed*
+ // length, not the buffered length.
+ if (length == 0) {
+ state = state.create(buffer, seed);
+ length = 64;
+ } else {
+ // Mix this chunk into the current state and bump length up by 64.
+ state.mix(buffer);
+ length += 64;
+ }
+ // Reset the buffer_ptr to the head of the buffer for the next chunk of
+ // data.
+ buffer_ptr = buffer;
+
+ // Try again to store into the buffer -- this cannot fail as we only
+ // store types smaller than the buffer.
+ if (!store_and_advance(buffer_ptr, buffer_end, data,
+ partial_store_size))
+ abort();
+ }
+ return buffer_ptr;
+ }
+
+#if defined(__has_feature) && __has_feature(__cxx_variadic_templates__)
+
+ /// \brief Recursive, variadic combining method.
+ ///
+ /// This function recurses through each argument, combining that argument
+ /// into a single hash.
+ template <typename T, typename ...Ts>
+ hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
+ const T &arg, const Ts &...args) {
+ buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg));
+
+ // Recurse to the next argument.
+ return combine(length, buffer_ptr, buffer_end, args...);
+ }
+
+#else
+ // Manually expanded recursive combining methods. See variadic above for
+ // documentation.
+
+ template <typename T1, typename T2, typename T3, typename T4, typename T5,
+ typename T6>
+ hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
+ const T1 &arg1, const T2 &arg2, const T3 &arg3,
+ const T4 &arg4, const T5 &arg5, const T6 &arg6) {
+ buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg1));
+ return combine(length, buffer_ptr, buffer_end, arg2, arg3, arg4, arg5, arg6);
+ }
+ template <typename T1, typename T2, typename T3, typename T4, typename T5>
+ hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
+ const T1 &arg1, const T2 &arg2, const T3 &arg3,
+ const T4 &arg4, const T5 &arg5) {
+ buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg1));
+ return combine(length, buffer_ptr, buffer_end, arg2, arg3, arg4, arg5);
+ }
+ template <typename T1, typename T2, typename T3, typename T4>
+ hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
+ const T1 &arg1, const T2 &arg2, const T3 &arg3,
+ const T4 &arg4) {
+ buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg1));
+ return combine(length, buffer_ptr, buffer_end, arg2, arg3, arg4);
+ }
+ template <typename T1, typename T2, typename T3>
+ hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
+ const T1 &arg1, const T2 &arg2, const T3 &arg3) {
+ buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg1));
+ return combine(length, buffer_ptr, buffer_end, arg2, arg3);
+ }
+ template <typename T1, typename T2>
+ hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
+ const T1 &arg1, const T2 &arg2) {
+ buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg1));
+ return combine(length, buffer_ptr, buffer_end, arg2);
+ }
+ template <typename T1>
+ hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
+ const T1 &arg1) {
+ buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg1));
+ return combine(length, buffer_ptr, buffer_end);
+ }
+
+#endif
+
+ /// \brief Base case for recursive, variadic combining.
+ ///
+ /// The base case when combining arguments recursively is reached when all
+ /// arguments have been handled. It flushes the remaining buffer and
+ /// constructs a hash_code.
+ hash_code combine(size_t length, char *buffer_ptr, char *buffer_end) {
+ // Check whether the entire set of values fit in the buffer. If so, we'll
+ // use the optimized short hashing routine and skip state entirely.
+ if (length == 0)
+ return hash_short(buffer, buffer_ptr - buffer, seed);
+
+ // Mix the final buffer, rotating it if we did a partial fill in order to
+ // simulate doing a mix of the last 64-bytes. That is how the algorithm
+ // works when we have a contiguous byte sequence, and we want to emulate
+ // that here.
+ std::rotate(buffer, buffer_ptr, buffer_end);
+
+ // Mix this chunk into the current state.
+ state.mix(buffer);
+ length += buffer_ptr - buffer;
+
+ return state.finalize(length);
+ }
+};
+
+} // namespace detail
+} // namespace hashing
+
+
+#if __has_feature(__cxx_variadic_templates__)
+
+/// \brief Combine values into a single hash_code.
+///
+/// This routine accepts a varying number of arguments of any type. It will
+/// attempt to combine them into a single hash_code. For user-defined types it
+/// attempts to call a \see hash_value overload (via ADL) for the type. For
+/// integer and pointer types it directly combines their data into the
+/// resulting hash_code.
+///
+/// The result is suitable for returning from a user's hash_value
+/// *implementation* for their user-defined type. Consumers of a type should
+/// *not* call this routine, they should instead call 'hash_value'.
+template <typename ...Ts> hash_code hash_combine(const Ts &...args) {
+ // Recursively hash each argument using a helper class.
+ ::llvm::hashing::detail::hash_combine_recursive_helper helper;
+ return helper.combine(0, helper.buffer, helper.buffer + 64, args...);
+}
+
+#else
+
+// What follows are manually exploded overloads for each argument width. See
+// the above variadic definition for documentation and specification.
+
+template <typename T1, typename T2, typename T3, typename T4, typename T5,
+ typename T6>
+hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
+ const T4 &arg4, const T5 &arg5, const T6 &arg6) {
+ ::llvm::hashing::detail::hash_combine_recursive_helper helper;
+ return helper.combine(0, helper.buffer, helper.buffer + 64,
+ arg1, arg2, arg3, arg4, arg5, arg6);
+}
+template <typename T1, typename T2, typename T3, typename T4, typename T5>
+hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
+ const T4 &arg4, const T5 &arg5) {
+ ::llvm::hashing::detail::hash_combine_recursive_helper helper;
+ return helper.combine(0, helper.buffer, helper.buffer + 64,
+ arg1, arg2, arg3, arg4, arg5);
+}
+template <typename T1, typename T2, typename T3, typename T4>
+hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
+ const T4 &arg4) {
+ ::llvm::hashing::detail::hash_combine_recursive_helper helper;
+ return helper.combine(0, helper.buffer, helper.buffer + 64,
+ arg1, arg2, arg3, arg4);
+}
+template <typename T1, typename T2, typename T3>
+hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3) {
+ ::llvm::hashing::detail::hash_combine_recursive_helper helper;
+ return helper.combine(0, helper.buffer, helper.buffer + 64, arg1, arg2, arg3);
+}
+template <typename T1, typename T2>
+hash_code hash_combine(const T1 &arg1, const T2 &arg2) {
+ ::llvm::hashing::detail::hash_combine_recursive_helper helper;
+ return helper.combine(0, helper.buffer, helper.buffer + 64, arg1, arg2);
+}
+template <typename T1>
+hash_code hash_combine(const T1 &arg1) {
+ ::llvm::hashing::detail::hash_combine_recursive_helper helper;
+ return helper.combine(0, helper.buffer, helper.buffer + 64, arg1);
+}
+
+#endif
+
+
+// Implementation details for implementations of hash_value overloads provided
+// here.
+namespace hashing {
+namespace detail {
+
+/// \brief Helper to hash the value of a single integer.
+///
+/// Overloads for smaller integer types are not provided to ensure consistent
+/// behavior in the presence of integral promotions. Essentially,
+/// "hash_value('4')" and "hash_value('0' + 4)" should be the same.
+inline hash_code hash_integer_value(uint64_t value) {
+ // Similar to hash_4to8_bytes but using a seed instead of length.
+ const uint64_t seed = get_execution_seed();
+ const char *s = reinterpret_cast<const char *>(&value);
+ const uint64_t a = fetch32(s);
+ return hash_16_bytes(seed + (a << 3), fetch32(s + 4));
+}
+
+} // namespace detail
+} // namespace hashing
+
+// Declared and documented above, but defined here so that any of the hashing
+// infrastructure is available.
+template <typename T>
+typename enable_if<is_integral_or_enum<T>, hash_code>::type
+hash_value(T value) {
+ return ::llvm::hashing::detail::hash_integer_value(value);
+}
+
+// Declared and documented above, but defined here so that any of the hashing
+// infrastructure is available.
+template <typename T> hash_code hash_value(const T *ptr) {
+ return ::llvm::hashing::detail::hash_integer_value(
+ reinterpret_cast<uintptr_t>(ptr));
+}
+
+// Declared and documented above, but defined here so that any of the hashing
+// infrastructure is available.
+template <typename T, typename U>
+hash_code hash_value(const std::pair<T, U> &arg) {
+ return hash_combine(arg.first, arg.second);
+}
+
+// Declared and documented above, but defined here so that any of the hashing
+// infrastructure is available.
+template <typename T>
+hash_code hash_value(const std::basic_string<T> &arg) {
+ return hash_combine_range(arg.begin(), arg.end());
+}
+
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/ImmutableIntervalMap.h b/include/llvm/ADT/ImmutableIntervalMap.h
new file mode 100644
index 00000000000..fa7ccb975e5
--- /dev/null
+++ b/include/llvm/ADT/ImmutableIntervalMap.h
@@ -0,0 +1,248 @@
+//===--- ImmutableIntervalMap.h - Immutable (functional) map ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the ImmutableIntervalMap class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_IMMUTABLE_INTERVAL_MAP_H
+#define LLVM_ADT_IMMUTABLE_INTERVAL_MAP_H
+
+#include "llvm/ADT/ImmutableMap.h"
+
+namespace llvm {
+
+class Interval {
+private:
+ int64_t Start;
+ int64_t End;
+
+public:
+ Interval(int64_t S, int64_t E) : Start(S), End(E) {}
+
+ int64_t getStart() const { return Start; }
+ int64_t getEnd() const { return End; }
+};
+
+template <typename T>
+struct ImutIntervalInfo {
+ typedef const std::pair<Interval, T> value_type;
+ typedef const value_type &value_type_ref;
+ typedef const Interval key_type;
+ typedef const Interval &key_type_ref;
+ typedef const T data_type;
+ typedef const T &data_type_ref;
+
+ static key_type_ref KeyOfValue(value_type_ref V) {
+ return V.first;
+ }
+
+ static data_type_ref DataOfValue(value_type_ref V) {
+ return V.second;
+ }
+
+ static bool isEqual(key_type_ref L, key_type_ref R) {
+ return L.getStart() == R.getStart() && L.getEnd() == R.getEnd();
+ }
+
+ static bool isDataEqual(data_type_ref L, data_type_ref R) {
+ return ImutContainerInfo<T>::isEqual(L,R);
+ }
+
+ static bool isLess(key_type_ref L, key_type_ref R) {
+ // Assume L and R does not overlap.
+ if (L.getStart() < R.getStart()) {
+ assert(L.getEnd() < R.getStart());
+ return true;
+ } else if (L.getStart() == R.getStart()) {
+ assert(L.getEnd() == R.getEnd());
+ return false;
+ } else {
+ assert(L.getStart() > R.getEnd());
+ return false;
+ }
+ }
+
+ static bool isContainedIn(key_type_ref K, key_type_ref L) {
+ if (K.getStart() >= L.getStart() && K.getEnd() <= L.getEnd())
+ return true;
+ else
+ return false;
+ }
+
+ static void Profile(FoldingSetNodeID &ID, value_type_ref V) {
+ ID.AddInteger(V.first.getStart());
+ ID.AddInteger(V.first.getEnd());
+ ImutProfileInfo<T>::Profile(ID, V.second);
+ }
+};
+
+template <typename ImutInfo>
+class ImutIntervalAVLFactory : public ImutAVLFactory<ImutInfo> {
+ typedef ImutAVLTree<ImutInfo> TreeTy;
+ typedef typename ImutInfo::value_type value_type;
+ typedef typename ImutInfo::value_type_ref value_type_ref;
+ typedef typename ImutInfo::key_type key_type;
+ typedef typename ImutInfo::key_type_ref key_type_ref;
+ typedef typename ImutInfo::data_type data_type;
+ typedef typename ImutInfo::data_type_ref data_type_ref;
+
+public:
+ ImutIntervalAVLFactory(BumpPtrAllocator &Alloc)
+ : ImutAVLFactory<ImutInfo>(Alloc) {}
+
+ TreeTy *Add(TreeTy *T, value_type_ref V) {
+ T = add_internal(V,T);
+ this->MarkImmutable(T);
+ return T;
+ }
+
+ TreeTy *Find(TreeTy *T, key_type_ref K) {
+ if (!T)
+ return NULL;
+
+ key_type_ref CurrentKey = ImutInfo::KeyOfValue(this->getValue(T));
+
+ if (ImutInfo::isContainedIn(K, CurrentKey))
+ return T;
+ else if (ImutInfo::isLess(K, CurrentKey))
+ return Find(this->getLeft(T), K);
+ else
+ return Find(this->getRight(T), K);
+ }
+
+private:
+ TreeTy *add_internal(value_type_ref V, TreeTy *T) {
+ key_type_ref K = ImutInfo::KeyOfValue(V);
+ T = removeAllOverlaps(T, K);
+ if (this->isEmpty(T))
+ return this->CreateNode(NULL, V, NULL);
+
+ assert(!T->isMutable());
+
+ key_type_ref KCurrent = ImutInfo::KeyOfValue(this->Value(T));
+
+ if (ImutInfo::isLess(K, KCurrent))
+ return this->Balance(add_internal(V, this->Left(T)), this->Value(T),
+ this->Right(T));
+ else
+ return this->Balance(this->Left(T), this->Value(T),
+ add_internal(V, this->Right(T)));
+ }
+
+ // Remove all overlaps from T.
+ TreeTy *removeAllOverlaps(TreeTy *T, key_type_ref K) {
+ bool Changed;
+ do {
+ Changed = false;
+ T = removeOverlap(T, K, Changed);
+ this->markImmutable(T);
+ } while (Changed);
+
+ return T;
+ }
+
+ // Remove one overlap from T.
+ TreeTy *removeOverlap(TreeTy *T, key_type_ref K, bool &Changed) {
+ if (!T)
+ return NULL;
+ Interval CurrentK = ImutInfo::KeyOfValue(this->Value(T));
+
+ // If current key does not overlap the inserted key.
+ if (CurrentK.getStart() > K.getEnd())
+ return this->Balance(removeOverlap(this->Left(T), K, Changed),
+ this->Value(T), this->Right(T));
+ else if (CurrentK.getEnd() < K.getStart())
+ return this->Balance(this->Left(T), this->Value(T),
+ removeOverlap(this->Right(T), K, Changed));
+
+ // Current key overlaps with the inserted key.
+ // Remove the current key.
+ Changed = true;
+ data_type_ref OldData = ImutInfo::DataOfValue(this->Value(T));
+ T = this->Remove_internal(CurrentK, T);
+ // Add back the unoverlapped part of the current key.
+ if (CurrentK.getStart() < K.getStart()) {
+ if (CurrentK.getEnd() <= K.getEnd()) {
+ Interval NewK(CurrentK.getStart(), K.getStart()-1);
+ return add_internal(std::make_pair(NewK, OldData), T);
+ } else {
+ Interval NewK1(CurrentK.getStart(), K.getStart()-1);
+ T = add_internal(std::make_pair(NewK1, OldData), T);
+
+ Interval NewK2(K.getEnd()+1, CurrentK.getEnd());
+ return add_internal(std::make_pair(NewK2, OldData), T);
+ }
+ } else {
+ if (CurrentK.getEnd() > K.getEnd()) {
+ Interval NewK(K.getEnd()+1, CurrentK.getEnd());
+ return add_internal(std::make_pair(NewK, OldData), T);
+ } else
+ return T;
+ }
+ }
+};
+
+/// ImmutableIntervalMap maps an interval [start, end] to a value. The intervals
+/// in the map are guaranteed to be disjoint.
+template <typename ValT>
+class ImmutableIntervalMap
+ : public ImmutableMap<Interval, ValT, ImutIntervalInfo<ValT> > {
+
+ typedef typename ImutIntervalInfo<ValT>::value_type value_type;
+ typedef typename ImutIntervalInfo<ValT>::value_type_ref value_type_ref;
+ typedef typename ImutIntervalInfo<ValT>::key_type key_type;
+ typedef typename ImutIntervalInfo<ValT>::key_type_ref key_type_ref;
+ typedef typename ImutIntervalInfo<ValT>::data_type data_type;
+ typedef typename ImutIntervalInfo<ValT>::data_type_ref data_type_ref;
+ typedef ImutAVLTree<ImutIntervalInfo<ValT> > TreeTy;
+
+public:
+ explicit ImmutableIntervalMap(TreeTy *R)
+ : ImmutableMap<Interval, ValT, ImutIntervalInfo<ValT> >(R) {}
+
+ class Factory {
+ ImutIntervalAVLFactory<ImutIntervalInfo<ValT> > F;
+
+ public:
+ Factory(BumpPtrAllocator& Alloc) : F(Alloc) {}
+
+ ImmutableIntervalMap getEmptyMap() {
+ return ImmutableIntervalMap(F.getEmptyTree());
+ }
+
+ ImmutableIntervalMap add(ImmutableIntervalMap Old,
+ key_type_ref K, data_type_ref D) {
+ TreeTy *T = F.add(Old.Root, std::pair<key_type, data_type>(K, D));
+ return ImmutableIntervalMap(F.getCanonicalTree(T));
+ }
+
+ ImmutableIntervalMap remove(ImmutableIntervalMap Old, key_type_ref K) {
+ TreeTy *T = F.remove(Old.Root, K);
+ return ImmutableIntervalMap(F.getCanonicalTree(T));
+ }
+
+ data_type *lookup(ImmutableIntervalMap M, key_type_ref K) {
+ TreeTy *T = F.Find(M.getRoot(), K);
+ if (T)
+ return &T->getValue().second;
+ else
+ return 0;
+ }
+ };
+
+private:
+ // For ImmutableIntervalMap, the lookup operation has to be done by the
+ // factory.
+ data_type* lookup(key_type_ref K) const;
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/ImmutableList.h b/include/llvm/ADT/ImmutableList.h
new file mode 100644
index 00000000000..20bdd903f7a
--- /dev/null
+++ b/include/llvm/ADT/ImmutableList.h
@@ -0,0 +1,229 @@
+//==--- ImmutableList.h - Immutable (functional) list interface --*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the ImmutableList class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_IMLIST_H
+#define LLVM_ADT_IMLIST_H
+
+#include "llvm/Support/Allocator.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+
+namespace llvm {
+
+template <typename T> class ImmutableListFactory;
+
+template <typename T>
+class ImmutableListImpl : public FoldingSetNode {
+ T Head;
+ const ImmutableListImpl* Tail;
+
+ ImmutableListImpl(const T& head, const ImmutableListImpl* tail = 0)
+ : Head(head), Tail(tail) {}
+
+ friend class ImmutableListFactory<T>;
+
+ void operator=(const ImmutableListImpl&) LLVM_DELETED_FUNCTION;
+ ImmutableListImpl(const ImmutableListImpl&) LLVM_DELETED_FUNCTION;
+
+public:
+ const T& getHead() const { return Head; }
+ const ImmutableListImpl* getTail() const { return Tail; }
+
+ static inline void Profile(FoldingSetNodeID& ID, const T& H,
+ const ImmutableListImpl* L){
+ ID.AddPointer(L);
+ ID.Add(H);
+ }
+
+ void Profile(FoldingSetNodeID& ID) {
+ Profile(ID, Head, Tail);
+ }
+};
+
+/// ImmutableList - This class represents an immutable (functional) list.
+/// It is implemented as a smart pointer (wraps ImmutableListImpl), so it
+/// it is intended to always be copied by value as if it were a pointer.
+/// This interface matches ImmutableSet and ImmutableMap. ImmutableList
+/// objects should almost never be created directly, and instead should
+/// be created by ImmutableListFactory objects that manage the lifetime
+/// of a group of lists. When the factory object is reclaimed, all lists
+/// created by that factory are released as well.
+template <typename T>
+class ImmutableList {
+public:
+ typedef T value_type;
+ typedef ImmutableListFactory<T> Factory;
+
+private:
+ const ImmutableListImpl<T>* X;
+
+public:
+ // This constructor should normally only be called by ImmutableListFactory<T>.
+ // There may be cases, however, when one needs to extract the internal pointer
+ // and reconstruct a list object from that pointer.
+ ImmutableList(const ImmutableListImpl<T>* x = 0) : X(x) {}
+
+ const ImmutableListImpl<T>* getInternalPointer() const {
+ return X;
+ }
+
+ class iterator {
+ const ImmutableListImpl<T>* L;
+ public:
+ iterator() : L(0) {}
+ iterator(ImmutableList l) : L(l.getInternalPointer()) {}
+
+ iterator& operator++() { L = L->getTail(); return *this; }
+ bool operator==(const iterator& I) const { return L == I.L; }
+ bool operator!=(const iterator& I) const { return L != I.L; }
+ const value_type& operator*() const { return L->getHead(); }
+ ImmutableList getList() const { return L; }
+ };
+
+ /// begin - Returns an iterator referring to the head of the list, or
+ /// an iterator denoting the end of the list if the list is empty.
+ iterator begin() const { return iterator(X); }
+
+ /// end - Returns an iterator denoting the end of the list. This iterator
+ /// does not refer to a valid list element.
+ iterator end() const { return iterator(); }
+
+ /// isEmpty - Returns true if the list is empty.
+ bool isEmpty() const { return !X; }
+
+ bool contains(const T& V) const {
+ for (iterator I = begin(), E = end(); I != E; ++I) {
+ if (*I == V)
+ return true;
+ }
+ return false;
+ }
+
+ /// isEqual - Returns true if two lists are equal. Because all lists created
+ /// from the same ImmutableListFactory are uniqued, this has O(1) complexity
+ /// because it the contents of the list do not need to be compared. Note
+ /// that you should only compare two lists created from the same
+ /// ImmutableListFactory.
+ bool isEqual(const ImmutableList& L) const { return X == L.X; }
+
+ bool operator==(const ImmutableList& L) const { return isEqual(L); }
+
+ /// getHead - Returns the head of the list.
+ const T& getHead() {
+ assert (!isEmpty() && "Cannot get the head of an empty list.");
+ return X->getHead();
+ }
+
+ /// getTail - Returns the tail of the list, which is another (possibly empty)
+ /// ImmutableList.
+ ImmutableList getTail() {
+ return X ? X->getTail() : 0;
+ }
+
+ void Profile(FoldingSetNodeID& ID) const {
+ ID.AddPointer(X);
+ }
+};
+
+template <typename T>
+class ImmutableListFactory {
+ typedef ImmutableListImpl<T> ListTy;
+ typedef FoldingSet<ListTy> CacheTy;
+
+ CacheTy Cache;
+ uintptr_t Allocator;
+
+ bool ownsAllocator() const {
+ return Allocator & 0x1 ? false : true;
+ }
+
+ BumpPtrAllocator& getAllocator() const {
+ return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
+ }
+
+public:
+ ImmutableListFactory()
+ : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
+
+ ImmutableListFactory(BumpPtrAllocator& Alloc)
+ : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
+
+ ~ImmutableListFactory() {
+ if (ownsAllocator()) delete &getAllocator();
+ }
+
+ ImmutableList<T> concat(const T& Head, ImmutableList<T> Tail) {
+ // Profile the new list to see if it already exists in our cache.
+ FoldingSetNodeID ID;
+ void* InsertPos;
+
+ const ListTy* TailImpl = Tail.getInternalPointer();
+ ListTy::Profile(ID, Head, TailImpl);
+ ListTy* L = Cache.FindNodeOrInsertPos(ID, InsertPos);
+
+ if (!L) {
+ // The list does not exist in our cache. Create it.
+ BumpPtrAllocator& A = getAllocator();
+ L = (ListTy*) A.Allocate<ListTy>();
+ new (L) ListTy(Head, TailImpl);
+
+ // Insert the new list into the cache.
+ Cache.InsertNode(L, InsertPos);
+ }
+
+ return L;
+ }
+
+ ImmutableList<T> add(const T& D, ImmutableList<T> L) {
+ return concat(D, L);
+ }
+
+ ImmutableList<T> getEmptyList() const {
+ return ImmutableList<T>(0);
+ }
+
+ ImmutableList<T> create(const T& X) {
+ return Concat(X, getEmptyList());
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// Partially-specialized Traits.
+//===----------------------------------------------------------------------===//
+
+template<typename T> struct DenseMapInfo;
+template<typename T> struct DenseMapInfo<ImmutableList<T> > {
+ static inline ImmutableList<T> getEmptyKey() {
+ return reinterpret_cast<ImmutableListImpl<T>*>(-1);
+ }
+ static inline ImmutableList<T> getTombstoneKey() {
+ return reinterpret_cast<ImmutableListImpl<T>*>(-2);
+ }
+ static unsigned getHashValue(ImmutableList<T> X) {
+ uintptr_t PtrVal = reinterpret_cast<uintptr_t>(X.getInternalPointer());
+ return (unsigned((uintptr_t)PtrVal) >> 4) ^
+ (unsigned((uintptr_t)PtrVal) >> 9);
+ }
+ static bool isEqual(ImmutableList<T> X1, ImmutableList<T> X2) {
+ return X1 == X2;
+ }
+};
+
+template <typename T> struct isPodLike;
+template <typename T>
+struct isPodLike<ImmutableList<T> > { static const bool value = true; };
+
+} // end llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/ImmutableMap.h b/include/llvm/ADT/ImmutableMap.h
new file mode 100644
index 00000000000..4883c5ba0a6
--- /dev/null
+++ b/include/llvm/ADT/ImmutableMap.h
@@ -0,0 +1,418 @@
+//===--- ImmutableMap.h - Immutable (functional) map interface --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the ImmutableMap class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_IMMAP_H
+#define LLVM_ADT_IMMAP_H
+
+#include "llvm/ADT/ImmutableSet.h"
+
+namespace llvm {
+
+/// ImutKeyValueInfo -Traits class used by ImmutableMap. While both the first
+/// and second elements in a pair are used to generate profile information,
+/// only the first element (the key) is used by isEqual and isLess.
+template <typename T, typename S>
+struct ImutKeyValueInfo {
+ typedef const std::pair<T,S> value_type;
+ typedef const value_type& value_type_ref;
+ typedef const T key_type;
+ typedef const T& key_type_ref;
+ typedef const S data_type;
+ typedef const S& data_type_ref;
+
+ static inline key_type_ref KeyOfValue(value_type_ref V) {
+ return V.first;
+ }
+
+ static inline data_type_ref DataOfValue(value_type_ref V) {
+ return V.second;
+ }
+
+ static inline bool isEqual(key_type_ref L, key_type_ref R) {
+ return ImutContainerInfo<T>::isEqual(L,R);
+ }
+ static inline bool isLess(key_type_ref L, key_type_ref R) {
+ return ImutContainerInfo<T>::isLess(L,R);
+ }
+
+ static inline bool isDataEqual(data_type_ref L, data_type_ref R) {
+ return ImutContainerInfo<S>::isEqual(L,R);
+ }
+
+ static inline void Profile(FoldingSetNodeID& ID, value_type_ref V) {
+ ImutContainerInfo<T>::Profile(ID, V.first);
+ ImutContainerInfo<S>::Profile(ID, V.second);
+ }
+};
+
+
+template <typename KeyT, typename ValT,
+ typename ValInfo = ImutKeyValueInfo<KeyT,ValT> >
+class ImmutableMap {
+public:
+ typedef typename ValInfo::value_type value_type;
+ typedef typename ValInfo::value_type_ref value_type_ref;
+ typedef typename ValInfo::key_type key_type;
+ typedef typename ValInfo::key_type_ref key_type_ref;
+ typedef typename ValInfo::data_type data_type;
+ typedef typename ValInfo::data_type_ref data_type_ref;
+ typedef ImutAVLTree<ValInfo> TreeTy;
+
+protected:
+ TreeTy* Root;
+
+public:
+ /// Constructs a map from a pointer to a tree root. In general one
+ /// should use a Factory object to create maps instead of directly
+ /// invoking the constructor, but there are cases where make this
+ /// constructor public is useful.
+ explicit ImmutableMap(const TreeTy* R) : Root(const_cast<TreeTy*>(R)) {
+ if (Root) { Root->retain(); }
+ }
+ ImmutableMap(const ImmutableMap &X) : Root(X.Root) {
+ if (Root) { Root->retain(); }
+ }
+ ImmutableMap &operator=(const ImmutableMap &X) {
+ if (Root != X.Root) {
+ if (X.Root) { X.Root->retain(); }
+ if (Root) { Root->release(); }
+ Root = X.Root;
+ }
+ return *this;
+ }
+ ~ImmutableMap() {
+ if (Root) { Root->release(); }
+ }
+
+ class Factory {
+ typename TreeTy::Factory F;
+ const bool Canonicalize;
+
+ public:
+ Factory(bool canonicalize = true)
+ : Canonicalize(canonicalize) {}
+
+ Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
+ : F(Alloc), Canonicalize(canonicalize) {}
+
+ ImmutableMap getEmptyMap() { return ImmutableMap(F.getEmptyTree()); }
+
+ ImmutableMap add(ImmutableMap Old, key_type_ref K, data_type_ref D) {
+ TreeTy *T = F.add(Old.Root, std::pair<key_type,data_type>(K,D));
+ return ImmutableMap(Canonicalize ? F.getCanonicalTree(T): T);
+ }
+
+ ImmutableMap remove(ImmutableMap Old, key_type_ref K) {
+ TreeTy *T = F.remove(Old.Root,K);
+ return ImmutableMap(Canonicalize ? F.getCanonicalTree(T): T);
+ }
+
+ typename TreeTy::Factory *getTreeFactory() const {
+ return const_cast<typename TreeTy::Factory *>(&F);
+ }
+
+ private:
+ Factory(const Factory& RHS) LLVM_DELETED_FUNCTION;
+ void operator=(const Factory& RHS) LLVM_DELETED_FUNCTION;
+ };
+
+ bool contains(key_type_ref K) const {
+ return Root ? Root->contains(K) : false;
+ }
+
+ bool operator==(const ImmutableMap &RHS) const {
+ return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
+ }
+
+ bool operator!=(const ImmutableMap &RHS) const {
+ return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
+ }
+
+ TreeTy *getRoot() const {
+ if (Root) { Root->retain(); }
+ return Root;
+ }
+
+ TreeTy *getRootWithoutRetain() const {
+ return Root;
+ }
+
+ void manualRetain() {
+ if (Root) Root->retain();
+ }
+
+ void manualRelease() {
+ if (Root) Root->release();
+ }
+
+ bool isEmpty() const { return !Root; }
+
+ //===--------------------------------------------------===//
+ // Foreach - A limited form of map iteration.
+ //===--------------------------------------------------===//
+
+private:
+ template <typename Callback>
+ struct CBWrapper {
+ Callback C;
+ void operator()(value_type_ref V) { C(V.first,V.second); }
+ };
+
+ template <typename Callback>
+ struct CBWrapperRef {
+ Callback &C;
+ CBWrapperRef(Callback& c) : C(c) {}
+
+ void operator()(value_type_ref V) { C(V.first,V.second); }
+ };
+
+public:
+ template <typename Callback>
+ void foreach(Callback& C) {
+ if (Root) {
+ CBWrapperRef<Callback> CB(C);
+ Root->foreach(CB);
+ }
+ }
+
+ template <typename Callback>
+ void foreach() {
+ if (Root) {
+ CBWrapper<Callback> CB;
+ Root->foreach(CB);
+ }
+ }
+
+ //===--------------------------------------------------===//
+ // For testing.
+ //===--------------------------------------------------===//
+
+ void verify() const { if (Root) Root->verify(); }
+
+ //===--------------------------------------------------===//
+ // Iterators.
+ //===--------------------------------------------------===//
+
+ class iterator {
+ typename TreeTy::iterator itr;
+
+ iterator() {}
+ iterator(TreeTy* t) : itr(t) {}
+ friend class ImmutableMap;
+
+ public:
+ value_type_ref operator*() const { return itr->getValue(); }
+ value_type* operator->() const { return &itr->getValue(); }
+
+ key_type_ref getKey() const { return itr->getValue().first; }
+ data_type_ref getData() const { return itr->getValue().second; }
+
+
+ iterator& operator++() { ++itr; return *this; }
+ iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
+ iterator& operator--() { --itr; return *this; }
+ iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
+ bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
+ bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
+ };
+
+ iterator begin() const { return iterator(Root); }
+ iterator end() const { return iterator(); }
+
+ data_type* lookup(key_type_ref K) const {
+ if (Root) {
+ TreeTy* T = Root->find(K);
+ if (T) return &T->getValue().second;
+ }
+
+ return 0;
+ }
+
+ /// getMaxElement - Returns the <key,value> pair in the ImmutableMap for
+ /// which key is the highest in the ordering of keys in the map. This
+ /// method returns NULL if the map is empty.
+ value_type* getMaxElement() const {
+ return Root ? &(Root->getMaxElement()->getValue()) : 0;
+ }
+
+ //===--------------------------------------------------===//
+ // Utility methods.
+ //===--------------------------------------------------===//
+
+ unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
+
+ static inline void Profile(FoldingSetNodeID& ID, const ImmutableMap& M) {
+ ID.AddPointer(M.Root);
+ }
+
+ inline void Profile(FoldingSetNodeID& ID) const {
+ return Profile(ID,*this);
+ }
+};
+
+// NOTE: This will possibly become the new implementation of ImmutableMap some day.
+template <typename KeyT, typename ValT,
+typename ValInfo = ImutKeyValueInfo<KeyT,ValT> >
+class ImmutableMapRef {
+public:
+ typedef typename ValInfo::value_type value_type;
+ typedef typename ValInfo::value_type_ref value_type_ref;
+ typedef typename ValInfo::key_type key_type;
+ typedef typename ValInfo::key_type_ref key_type_ref;
+ typedef typename ValInfo::data_type data_type;
+ typedef typename ValInfo::data_type_ref data_type_ref;
+ typedef ImutAVLTree<ValInfo> TreeTy;
+ typedef typename TreeTy::Factory FactoryTy;
+
+protected:
+ TreeTy *Root;
+ FactoryTy *Factory;
+
+public:
+ /// Constructs a map from a pointer to a tree root. In general one
+ /// should use a Factory object to create maps instead of directly
+ /// invoking the constructor, but there are cases where make this
+ /// constructor public is useful.
+ explicit ImmutableMapRef(const TreeTy* R, FactoryTy *F)
+ : Root(const_cast<TreeTy*>(R)),
+ Factory(F) {
+ if (Root) { Root->retain(); }
+ }
+
+ ImmutableMapRef(const ImmutableMapRef &X)
+ : Root(X.Root),
+ Factory(X.Factory) {
+ if (Root) { Root->retain(); }
+ }
+
+ ImmutableMapRef &operator=(const ImmutableMapRef &X) {
+ if (Root != X.Root) {
+ if (X.Root)
+ X.Root->retain();
+
+ if (Root)
+ Root->release();
+
+ Root = X.Root;
+ Factory = X.Factory;
+ }
+ return *this;
+ }
+
+ ~ImmutableMapRef() {
+ if (Root)
+ Root->release();
+ }
+
+ static inline ImmutableMapRef getEmptyMap(FactoryTy *F) {
+ return ImmutableMapRef(0, F);
+ }
+
+ ImmutableMapRef add(key_type_ref K, data_type_ref D) {
+ TreeTy *NewT = Factory->add(Root, std::pair<key_type, data_type>(K, D));
+ return ImmutableMapRef(NewT, Factory);
+ }
+
+ ImmutableMapRef remove(key_type_ref K) {
+ TreeTy *NewT = Factory->remove(Root, K);
+ return ImmutableMapRef(NewT, Factory);
+ }
+
+ bool contains(key_type_ref K) const {
+ return Root ? Root->contains(K) : false;
+ }
+
+ ImmutableMap<KeyT, ValT> asImmutableMap() const {
+ return ImmutableMap<KeyT, ValT>(Factory->getCanonicalTree(Root));
+ }
+
+ bool operator==(const ImmutableMapRef &RHS) const {
+ return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
+ }
+
+ bool operator!=(const ImmutableMapRef &RHS) const {
+ return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
+ }
+
+ bool isEmpty() const { return !Root; }
+
+ //===--------------------------------------------------===//
+ // For testing.
+ //===--------------------------------------------------===//
+
+ void verify() const { if (Root) Root->verify(); }
+
+ //===--------------------------------------------------===//
+ // Iterators.
+ //===--------------------------------------------------===//
+
+ class iterator {
+ typename TreeTy::iterator itr;
+
+ iterator() {}
+ iterator(TreeTy* t) : itr(t) {}
+ friend class ImmutableMapRef;
+
+ public:
+ value_type_ref operator*() const { return itr->getValue(); }
+ value_type* operator->() const { return &itr->getValue(); }
+
+ key_type_ref getKey() const { return itr->getValue().first; }
+ data_type_ref getData() const { return itr->getValue().second; }
+
+
+ iterator& operator++() { ++itr; return *this; }
+ iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
+ iterator& operator--() { --itr; return *this; }
+ iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
+ bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
+ bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
+ };
+
+ iterator begin() const { return iterator(Root); }
+ iterator end() const { return iterator(); }
+
+ data_type* lookup(key_type_ref K) const {
+ if (Root) {
+ TreeTy* T = Root->find(K);
+ if (T) return &T->getValue().second;
+ }
+
+ return 0;
+ }
+
+ /// getMaxElement - Returns the <key,value> pair in the ImmutableMap for
+ /// which key is the highest in the ordering of keys in the map. This
+ /// method returns NULL if the map is empty.
+ value_type* getMaxElement() const {
+ return Root ? &(Root->getMaxElement()->getValue()) : 0;
+ }
+
+ //===--------------------------------------------------===//
+ // Utility methods.
+ //===--------------------------------------------------===//
+
+ unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
+
+ static inline void Profile(FoldingSetNodeID& ID, const ImmutableMapRef &M) {
+ ID.AddPointer(M.Root);
+ }
+
+ inline void Profile(FoldingSetNodeID& ID) const {
+ return Profile(ID, *this);
+ }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/ImmutableSet.h b/include/llvm/ADT/ImmutableSet.h
new file mode 100644
index 00000000000..261d0494e2d
--- /dev/null
+++ b/include/llvm/ADT/ImmutableSet.h
@@ -0,0 +1,1223 @@
+//===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the ImutAVLTree and ImmutableSet classes.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_IMSET_H
+#define LLVM_ADT_IMSET_H
+
+#include "llvm/Support/Allocator.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include <cassert>
+#include <functional>
+#include <vector>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// Immutable AVL-Tree Definition.
+//===----------------------------------------------------------------------===//
+
+template <typename ImutInfo> class ImutAVLFactory;
+template <typename ImutInfo> class ImutIntervalAVLFactory;
+template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
+template <typename ImutInfo> class ImutAVLTreeGenericIterator;
+
+template <typename ImutInfo >
+class ImutAVLTree {
+public:
+ typedef typename ImutInfo::key_type_ref key_type_ref;
+ typedef typename ImutInfo::value_type value_type;
+ typedef typename ImutInfo::value_type_ref value_type_ref;
+
+ typedef ImutAVLFactory<ImutInfo> Factory;
+ friend class ImutAVLFactory<ImutInfo>;
+ friend class ImutIntervalAVLFactory<ImutInfo>;
+
+ friend class ImutAVLTreeGenericIterator<ImutInfo>;
+
+ typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
+
+ //===----------------------------------------------------===//
+ // Public Interface.
+ //===----------------------------------------------------===//
+
+ /// Return a pointer to the left subtree. This value
+ /// is NULL if there is no left subtree.
+ ImutAVLTree *getLeft() const { return left; }
+
+ /// Return a pointer to the right subtree. This value is
+ /// NULL if there is no right subtree.
+ ImutAVLTree *getRight() const { return right; }
+
+ /// getHeight - Returns the height of the tree. A tree with no subtrees
+ /// has a height of 1.
+ unsigned getHeight() const { return height; }
+
+ /// getValue - Returns the data value associated with the tree node.
+ const value_type& getValue() const { return value; }
+
+ /// find - Finds the subtree associated with the specified key value.
+ /// This method returns NULL if no matching subtree is found.
+ ImutAVLTree* find(key_type_ref K) {
+ ImutAVLTree *T = this;
+ while (T) {
+ key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
+ if (ImutInfo::isEqual(K,CurrentKey))
+ return T;
+ else if (ImutInfo::isLess(K,CurrentKey))
+ T = T->getLeft();
+ else
+ T = T->getRight();
+ }
+ return NULL;
+ }
+
+ /// getMaxElement - Find the subtree associated with the highest ranged
+ /// key value.
+ ImutAVLTree* getMaxElement() {
+ ImutAVLTree *T = this;
+ ImutAVLTree *Right = T->getRight();
+ while (Right) { T = right; right = T->getRight(); }
+ return T;
+ }
+
+ /// size - Returns the number of nodes in the tree, which includes
+ /// both leaves and non-leaf nodes.
+ unsigned size() const {
+ unsigned n = 1;
+ if (const ImutAVLTree* L = getLeft())
+ n += L->size();
+ if (const ImutAVLTree* R = getRight())
+ n += R->size();
+ return n;
+ }
+
+ /// begin - Returns an iterator that iterates over the nodes of the tree
+ /// in an inorder traversal. The returned iterator thus refers to the
+ /// the tree node with the minimum data element.
+ iterator begin() const { return iterator(this); }
+
+ /// end - Returns an iterator for the tree that denotes the end of an
+ /// inorder traversal.
+ iterator end() const { return iterator(); }
+
+ bool isElementEqual(value_type_ref V) const {
+ // Compare the keys.
+ if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
+ ImutInfo::KeyOfValue(V)))
+ return false;
+
+ // Also compare the data values.
+ if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
+ ImutInfo::DataOfValue(V)))
+ return false;
+
+ return true;
+ }
+
+ bool isElementEqual(const ImutAVLTree* RHS) const {
+ return isElementEqual(RHS->getValue());
+ }
+
+ /// isEqual - Compares two trees for structural equality and returns true
+ /// if they are equal. This worst case performance of this operation is
+ // linear in the sizes of the trees.
+ bool isEqual(const ImutAVLTree& RHS) const {
+ if (&RHS == this)
+ return true;
+
+ iterator LItr = begin(), LEnd = end();
+ iterator RItr = RHS.begin(), REnd = RHS.end();
+
+ while (LItr != LEnd && RItr != REnd) {
+ if (*LItr == *RItr) {
+ LItr.skipSubTree();
+ RItr.skipSubTree();
+ continue;
+ }
+
+ if (!LItr->isElementEqual(*RItr))
+ return false;
+
+ ++LItr;
+ ++RItr;
+ }
+
+ return LItr == LEnd && RItr == REnd;
+ }
+
+ /// isNotEqual - Compares two trees for structural inequality. Performance
+ /// is the same is isEqual.
+ bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
+
+ /// contains - Returns true if this tree contains a subtree (node) that
+ /// has an data element that matches the specified key. Complexity
+ /// is logarithmic in the size of the tree.
+ bool contains(key_type_ref K) { return (bool) find(K); }
+
+ /// foreach - A member template the accepts invokes operator() on a functor
+ /// object (specifed by Callback) for every node/subtree in the tree.
+ /// Nodes are visited using an inorder traversal.
+ template <typename Callback>
+ void foreach(Callback& C) {
+ if (ImutAVLTree* L = getLeft())
+ L->foreach(C);
+
+ C(value);
+
+ if (ImutAVLTree* R = getRight())
+ R->foreach(C);
+ }
+
+ /// validateTree - A utility method that checks that the balancing and
+ /// ordering invariants of the tree are satisifed. It is a recursive
+ /// method that returns the height of the tree, which is then consumed
+ /// by the enclosing validateTree call. External callers should ignore the
+ /// return value. An invalid tree will cause an assertion to fire in
+ /// a debug build.
+ unsigned validateTree() const {
+ unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
+ unsigned HR = getRight() ? getRight()->validateTree() : 0;
+ (void) HL;
+ (void) HR;
+
+ assert(getHeight() == ( HL > HR ? HL : HR ) + 1
+ && "Height calculation wrong");
+
+ assert((HL > HR ? HL-HR : HR-HL) <= 2
+ && "Balancing invariant violated");
+
+ assert((!getLeft() ||
+ ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
+ ImutInfo::KeyOfValue(getValue()))) &&
+ "Value in left child is not less that current value");
+
+
+ assert(!(getRight() ||
+ ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
+ ImutInfo::KeyOfValue(getRight()->getValue()))) &&
+ "Current value is not less that value of right child");
+
+ return getHeight();
+ }
+
+ //===----------------------------------------------------===//
+ // Internal values.
+ //===----------------------------------------------------===//
+
+private:
+ Factory *factory;
+ ImutAVLTree *left;
+ ImutAVLTree *right;
+ ImutAVLTree *prev;
+ ImutAVLTree *next;
+
+ unsigned height : 28;
+ unsigned IsMutable : 1;
+ unsigned IsDigestCached : 1;
+ unsigned IsCanonicalized : 1;
+
+ value_type value;
+ uint32_t digest;
+ uint32_t refCount;
+
+ //===----------------------------------------------------===//
+ // Internal methods (node manipulation; used by Factory).
+ //===----------------------------------------------------===//
+
+private:
+ /// ImutAVLTree - Internal constructor that is only called by
+ /// ImutAVLFactory.
+ ImutAVLTree(Factory *f, ImutAVLTree* l, ImutAVLTree* r, value_type_ref v,
+ unsigned height)
+ : factory(f), left(l), right(r), prev(0), next(0), height(height),
+ IsMutable(true), IsDigestCached(false), IsCanonicalized(0),
+ value(v), digest(0), refCount(0)
+ {
+ if (left) left->retain();
+ if (right) right->retain();
+ }
+
+ /// isMutable - Returns true if the left and right subtree references
+ /// (as well as height) can be changed. If this method returns false,
+ /// the tree is truly immutable. Trees returned from an ImutAVLFactory
+ /// object should always have this method return true. Further, if this
+ /// method returns false for an instance of ImutAVLTree, all subtrees
+ /// will also have this method return false. The converse is not true.
+ bool isMutable() const { return IsMutable; }
+
+ /// hasCachedDigest - Returns true if the digest for this tree is cached.
+ /// This can only be true if the tree is immutable.
+ bool hasCachedDigest() const { return IsDigestCached; }
+
+ //===----------------------------------------------------===//
+ // Mutating operations. A tree root can be manipulated as
+ // long as its reference has not "escaped" from internal
+ // methods of a factory object (see below). When a tree
+ // pointer is externally viewable by client code, the
+ // internal "mutable bit" is cleared to mark the tree
+ // immutable. Note that a tree that still has its mutable
+ // bit set may have children (subtrees) that are themselves
+ // immutable.
+ //===----------------------------------------------------===//
+
+ /// markImmutable - Clears the mutable flag for a tree. After this happens,
+ /// it is an error to call setLeft(), setRight(), and setHeight().
+ void markImmutable() {
+ assert(isMutable() && "Mutable flag already removed.");
+ IsMutable = false;
+ }
+
+ /// markedCachedDigest - Clears the NoCachedDigest flag for a tree.
+ void markedCachedDigest() {
+ assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
+ IsDigestCached = true;
+ }
+
+ /// setHeight - Changes the height of the tree. Used internally by
+ /// ImutAVLFactory.
+ void setHeight(unsigned h) {
+ assert(isMutable() && "Only a mutable tree can have its height changed.");
+ height = h;
+ }
+
+ static inline
+ uint32_t computeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
+ uint32_t digest = 0;
+
+ if (L)
+ digest += L->computeDigest();
+
+ // Compute digest of stored data.
+ FoldingSetNodeID ID;
+ ImutInfo::Profile(ID,V);
+ digest += ID.ComputeHash();
+
+ if (R)
+ digest += R->computeDigest();
+
+ return digest;
+ }
+
+ inline uint32_t computeDigest() {
+ // Check the lowest bit to determine if digest has actually been
+ // pre-computed.
+ if (hasCachedDigest())
+ return digest;
+
+ uint32_t X = computeDigest(getLeft(), getRight(), getValue());
+ digest = X;
+ markedCachedDigest();
+ return X;
+ }
+
+ //===----------------------------------------------------===//
+ // Reference count operations.
+ //===----------------------------------------------------===//
+
+public:
+ void retain() { ++refCount; }
+ void release() {
+ assert(refCount > 0);
+ if (--refCount == 0)
+ destroy();
+ }
+ void destroy() {
+ if (left)
+ left->release();
+ if (right)
+ right->release();
+ if (IsCanonicalized) {
+ if (next)
+ next->prev = prev;
+
+ if (prev)
+ prev->next = next;
+ else
+ factory->Cache[factory->maskCacheIndex(computeDigest())] = next;
+ }
+
+ // We need to clear the mutability bit in case we are
+ // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
+ IsMutable = false;
+ factory->freeNodes.push_back(this);
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// Immutable AVL-Tree Factory class.
+//===----------------------------------------------------------------------===//
+
+template <typename ImutInfo >
+class ImutAVLFactory {
+ friend class ImutAVLTree<ImutInfo>;
+ typedef ImutAVLTree<ImutInfo> TreeTy;
+ typedef typename TreeTy::value_type_ref value_type_ref;
+ typedef typename TreeTy::key_type_ref key_type_ref;
+
+ typedef DenseMap<unsigned, TreeTy*> CacheTy;
+
+ CacheTy Cache;
+ uintptr_t Allocator;
+ std::vector<TreeTy*> createdNodes;
+ std::vector<TreeTy*> freeNodes;
+
+ bool ownsAllocator() const {
+ return Allocator & 0x1 ? false : true;
+ }
+
+ BumpPtrAllocator& getAllocator() const {
+ return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
+ }
+
+ //===--------------------------------------------------===//
+ // Public interface.
+ //===--------------------------------------------------===//
+
+public:
+ ImutAVLFactory()
+ : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
+
+ ImutAVLFactory(BumpPtrAllocator& Alloc)
+ : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
+
+ ~ImutAVLFactory() {
+ if (ownsAllocator()) delete &getAllocator();
+ }
+
+ TreeTy* add(TreeTy* T, value_type_ref V) {
+ T = add_internal(V,T);
+ markImmutable(T);
+ recoverNodes();
+ return T;
+ }
+
+ TreeTy* remove(TreeTy* T, key_type_ref V) {
+ T = remove_internal(V,T);
+ markImmutable(T);
+ recoverNodes();
+ return T;
+ }
+
+ TreeTy* getEmptyTree() const { return NULL; }
+
+protected:
+
+ //===--------------------------------------------------===//
+ // A bunch of quick helper functions used for reasoning
+ // about the properties of trees and their children.
+ // These have succinct names so that the balancing code
+ // is as terse (and readable) as possible.
+ //===--------------------------------------------------===//
+
+ bool isEmpty(TreeTy* T) const { return !T; }
+ unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
+ TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
+ TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
+ value_type_ref getValue(TreeTy* T) const { return T->value; }
+
+ // Make sure the index is not the Tombstone or Entry key of the DenseMap.
+ static inline unsigned maskCacheIndex(unsigned I) {
+ return (I & ~0x02);
+ }
+
+ unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
+ unsigned hl = getHeight(L);
+ unsigned hr = getHeight(R);
+ return (hl > hr ? hl : hr) + 1;
+ }
+
+ static bool compareTreeWithSection(TreeTy* T,
+ typename TreeTy::iterator& TI,
+ typename TreeTy::iterator& TE) {
+ typename TreeTy::iterator I = T->begin(), E = T->end();
+ for ( ; I!=E ; ++I, ++TI) {
+ if (TI == TE || !I->isElementEqual(*TI))
+ return false;
+ }
+ return true;
+ }
+
+ //===--------------------------------------------------===//
+ // "createNode" is used to generate new tree roots that link
+ // to other trees. The functon may also simply move links
+ // in an existing root if that root is still marked mutable.
+ // This is necessary because otherwise our balancing code
+ // would leak memory as it would create nodes that are
+ // then discarded later before the finished tree is
+ // returned to the caller.
+ //===--------------------------------------------------===//
+
+ TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
+ BumpPtrAllocator& A = getAllocator();
+ TreeTy* T;
+ if (!freeNodes.empty()) {
+ T = freeNodes.back();
+ freeNodes.pop_back();
+ assert(T != L);
+ assert(T != R);
+ } else {
+ T = (TreeTy*) A.Allocate<TreeTy>();
+ }
+ new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
+ createdNodes.push_back(T);
+ return T;
+ }
+
+ TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
+ return createNode(newLeft, getValue(oldTree), newRight);
+ }
+
+ void recoverNodes() {
+ for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
+ TreeTy *N = createdNodes[i];
+ if (N->isMutable() && N->refCount == 0)
+ N->destroy();
+ }
+ createdNodes.clear();
+ }
+
+ /// balanceTree - Used by add_internal and remove_internal to
+ /// balance a newly created tree.
+ TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
+ unsigned hl = getHeight(L);
+ unsigned hr = getHeight(R);
+
+ if (hl > hr + 2) {
+ assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
+
+ TreeTy *LL = getLeft(L);
+ TreeTy *LR = getRight(L);
+
+ if (getHeight(LL) >= getHeight(LR))
+ return createNode(LL, L, createNode(LR,V,R));
+
+ assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
+
+ TreeTy *LRL = getLeft(LR);
+ TreeTy *LRR = getRight(LR);
+
+ return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
+ }
+
+ if (hr > hl + 2) {
+ assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
+
+ TreeTy *RL = getLeft(R);
+ TreeTy *RR = getRight(R);
+
+ if (getHeight(RR) >= getHeight(RL))
+ return createNode(createNode(L,V,RL), R, RR);
+
+ assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
+
+ TreeTy *RLL = getLeft(RL);
+ TreeTy *RLR = getRight(RL);
+
+ return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
+ }
+
+ return createNode(L,V,R);
+ }
+
+ /// add_internal - Creates a new tree that includes the specified
+ /// data and the data from the original tree. If the original tree
+ /// already contained the data item, the original tree is returned.
+ TreeTy* add_internal(value_type_ref V, TreeTy* T) {
+ if (isEmpty(T))
+ return createNode(T, V, T);
+ assert(!T->isMutable());
+
+ key_type_ref K = ImutInfo::KeyOfValue(V);
+ key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
+
+ if (ImutInfo::isEqual(K,KCurrent))
+ return createNode(getLeft(T), V, getRight(T));
+ else if (ImutInfo::isLess(K,KCurrent))
+ return balanceTree(add_internal(V, getLeft(T)), getValue(T), getRight(T));
+ else
+ return balanceTree(getLeft(T), getValue(T), add_internal(V, getRight(T)));
+ }
+
+ /// remove_internal - Creates a new tree that includes all the data
+ /// from the original tree except the specified data. If the
+ /// specified data did not exist in the original tree, the original
+ /// tree is returned.
+ TreeTy* remove_internal(key_type_ref K, TreeTy* T) {
+ if (isEmpty(T))
+ return T;
+
+ assert(!T->isMutable());
+
+ key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
+
+ if (ImutInfo::isEqual(K,KCurrent)) {
+ return combineTrees(getLeft(T), getRight(T));
+ } else if (ImutInfo::isLess(K,KCurrent)) {
+ return balanceTree(remove_internal(K, getLeft(T)),
+ getValue(T), getRight(T));
+ } else {
+ return balanceTree(getLeft(T), getValue(T),
+ remove_internal(K, getRight(T)));
+ }
+ }
+
+ TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
+ if (isEmpty(L))
+ return R;
+ if (isEmpty(R))
+ return L;
+ TreeTy* OldNode;
+ TreeTy* newRight = removeMinBinding(R,OldNode);
+ return balanceTree(L, getValue(OldNode), newRight);
+ }
+
+ TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
+ assert(!isEmpty(T));
+ if (isEmpty(getLeft(T))) {
+ Noderemoved = T;
+ return getRight(T);
+ }
+ return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
+ getValue(T), getRight(T));
+ }
+
+ /// markImmutable - Clears the mutable bits of a root and all of its
+ /// descendants.
+ void markImmutable(TreeTy* T) {
+ if (!T || !T->isMutable())
+ return;
+ T->markImmutable();
+ markImmutable(getLeft(T));
+ markImmutable(getRight(T));
+ }
+
+public:
+ TreeTy *getCanonicalTree(TreeTy *TNew) {
+ if (!TNew)
+ return 0;
+
+ if (TNew->IsCanonicalized)
+ return TNew;
+
+ // Search the hashtable for another tree with the same digest, and
+ // if find a collision compare those trees by their contents.
+ unsigned digest = TNew->computeDigest();
+ TreeTy *&entry = Cache[maskCacheIndex(digest)];
+ do {
+ if (!entry)
+ break;
+ for (TreeTy *T = entry ; T != 0; T = T->next) {
+ // Compare the Contents('T') with Contents('TNew')
+ typename TreeTy::iterator TI = T->begin(), TE = T->end();
+ if (!compareTreeWithSection(TNew, TI, TE))
+ continue;
+ if (TI != TE)
+ continue; // T has more contents than TNew.
+ // Trees did match! Return 'T'.
+ if (TNew->refCount == 0)
+ TNew->destroy();
+ return T;
+ }
+ entry->prev = TNew;
+ TNew->next = entry;
+ }
+ while (false);
+
+ entry = TNew;
+ TNew->IsCanonicalized = true;
+ return TNew;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// Immutable AVL-Tree Iterators.
+//===----------------------------------------------------------------------===//
+
+template <typename ImutInfo>
+class ImutAVLTreeGenericIterator {
+ SmallVector<uintptr_t,20> stack;
+public:
+ enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
+ Flags=0x3 };
+
+ typedef ImutAVLTree<ImutInfo> TreeTy;
+ typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
+
+ inline ImutAVLTreeGenericIterator() {}
+ inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
+ if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
+ }
+
+ TreeTy* operator*() const {
+ assert(!stack.empty());
+ return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
+ }
+
+ uintptr_t getVisitState() const {
+ assert(!stack.empty());
+ return stack.back() & Flags;
+ }
+
+
+ bool atEnd() const { return stack.empty(); }
+
+ bool atBeginning() const {
+ return stack.size() == 1 && getVisitState() == VisitedNone;
+ }
+
+ void skipToParent() {
+ assert(!stack.empty());
+ stack.pop_back();
+ if (stack.empty())
+ return;
+ switch (getVisitState()) {
+ case VisitedNone:
+ stack.back() |= VisitedLeft;
+ break;
+ case VisitedLeft:
+ stack.back() |= VisitedRight;
+ break;
+ default:
+ llvm_unreachable("Unreachable.");
+ }
+ }
+
+ inline bool operator==(const _Self& x) const {
+ if (stack.size() != x.stack.size())
+ return false;
+ for (unsigned i = 0 ; i < stack.size(); i++)
+ if (stack[i] != x.stack[i])
+ return false;
+ return true;
+ }
+
+ inline bool operator!=(const _Self& x) const { return !operator==(x); }
+
+ _Self& operator++() {
+ assert(!stack.empty());
+ TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
+ assert(Current);
+ switch (getVisitState()) {
+ case VisitedNone:
+ if (TreeTy* L = Current->getLeft())
+ stack.push_back(reinterpret_cast<uintptr_t>(L));
+ else
+ stack.back() |= VisitedLeft;
+ break;
+ case VisitedLeft:
+ if (TreeTy* R = Current->getRight())
+ stack.push_back(reinterpret_cast<uintptr_t>(R));
+ else
+ stack.back() |= VisitedRight;
+ break;
+ case VisitedRight:
+ skipToParent();
+ break;
+ default:
+ llvm_unreachable("Unreachable.");
+ }
+ return *this;
+ }
+
+ _Self& operator--() {
+ assert(!stack.empty());
+ TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
+ assert(Current);
+ switch (getVisitState()) {
+ case VisitedNone:
+ stack.pop_back();
+ break;
+ case VisitedLeft:
+ stack.back() &= ~Flags; // Set state to "VisitedNone."
+ if (TreeTy* L = Current->getLeft())
+ stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
+ break;
+ case VisitedRight:
+ stack.back() &= ~Flags;
+ stack.back() |= VisitedLeft;
+ if (TreeTy* R = Current->getRight())
+ stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
+ break;
+ default:
+ llvm_unreachable("Unreachable.");
+ }
+ return *this;
+ }
+};
+
+template <typename ImutInfo>
+class ImutAVLTreeInOrderIterator {
+ typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
+ InternalIteratorTy InternalItr;
+
+public:
+ typedef ImutAVLTree<ImutInfo> TreeTy;
+ typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
+
+ ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
+ if (Root) operator++(); // Advance to first element.
+ }
+
+ ImutAVLTreeInOrderIterator() : InternalItr() {}
+
+ inline bool operator==(const _Self& x) const {
+ return InternalItr == x.InternalItr;
+ }
+
+ inline bool operator!=(const _Self& x) const { return !operator==(x); }
+
+ inline TreeTy* operator*() const { return *InternalItr; }
+ inline TreeTy* operator->() const { return *InternalItr; }
+
+ inline _Self& operator++() {
+ do ++InternalItr;
+ while (!InternalItr.atEnd() &&
+ InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
+
+ return *this;
+ }
+
+ inline _Self& operator--() {
+ do --InternalItr;
+ while (!InternalItr.atBeginning() &&
+ InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
+
+ return *this;
+ }
+
+ inline void skipSubTree() {
+ InternalItr.skipToParent();
+
+ while (!InternalItr.atEnd() &&
+ InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
+ ++InternalItr;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// Trait classes for Profile information.
+//===----------------------------------------------------------------------===//
+
+/// Generic profile template. The default behavior is to invoke the
+/// profile method of an object. Specializations for primitive integers
+/// and generic handling of pointers is done below.
+template <typename T>
+struct ImutProfileInfo {
+ typedef const T value_type;
+ typedef const T& value_type_ref;
+
+ static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
+ FoldingSetTrait<T>::Profile(X,ID);
+ }
+};
+
+/// Profile traits for integers.
+template <typename T>
+struct ImutProfileInteger {
+ typedef const T value_type;
+ typedef const T& value_type_ref;
+
+ static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
+ ID.AddInteger(X);
+ }
+};
+
+#define PROFILE_INTEGER_INFO(X)\
+template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
+
+PROFILE_INTEGER_INFO(char)
+PROFILE_INTEGER_INFO(unsigned char)
+PROFILE_INTEGER_INFO(short)
+PROFILE_INTEGER_INFO(unsigned short)
+PROFILE_INTEGER_INFO(unsigned)
+PROFILE_INTEGER_INFO(signed)
+PROFILE_INTEGER_INFO(long)
+PROFILE_INTEGER_INFO(unsigned long)
+PROFILE_INTEGER_INFO(long long)
+PROFILE_INTEGER_INFO(unsigned long long)
+
+#undef PROFILE_INTEGER_INFO
+
+/// Generic profile trait for pointer types. We treat pointers as
+/// references to unique objects.
+template <typename T>
+struct ImutProfileInfo<T*> {
+ typedef const T* value_type;
+ typedef value_type value_type_ref;
+
+ static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
+ ID.AddPointer(X);
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// Trait classes that contain element comparison operators and type
+// definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
+// inherit from the profile traits (ImutProfileInfo) to include operations
+// for element profiling.
+//===----------------------------------------------------------------------===//
+
+
+/// ImutContainerInfo - Generic definition of comparison operations for
+/// elements of immutable containers that defaults to using
+/// std::equal_to<> and std::less<> to perform comparison of elements.
+template <typename T>
+struct ImutContainerInfo : public ImutProfileInfo<T> {
+ typedef typename ImutProfileInfo<T>::value_type value_type;
+ typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
+ typedef value_type key_type;
+ typedef value_type_ref key_type_ref;
+ typedef bool data_type;
+ typedef bool data_type_ref;
+
+ static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
+ static inline data_type_ref DataOfValue(value_type_ref) { return true; }
+
+ static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
+ return std::equal_to<key_type>()(LHS,RHS);
+ }
+
+ static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
+ return std::less<key_type>()(LHS,RHS);
+ }
+
+ static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
+};
+
+/// ImutContainerInfo - Specialization for pointer values to treat pointers
+/// as references to unique objects. Pointers are thus compared by
+/// their addresses.
+template <typename T>
+struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
+ typedef typename ImutProfileInfo<T*>::value_type value_type;
+ typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
+ typedef value_type key_type;
+ typedef value_type_ref key_type_ref;
+ typedef bool data_type;
+ typedef bool data_type_ref;
+
+ static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
+ static inline data_type_ref DataOfValue(value_type_ref) { return true; }
+
+ static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
+ return LHS == RHS;
+ }
+
+ static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
+ return LHS < RHS;
+ }
+
+ static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
+};
+
+//===----------------------------------------------------------------------===//
+// Immutable Set
+//===----------------------------------------------------------------------===//
+
+template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
+class ImmutableSet {
+public:
+ typedef typename ValInfo::value_type value_type;
+ typedef typename ValInfo::value_type_ref value_type_ref;
+ typedef ImutAVLTree<ValInfo> TreeTy;
+
+private:
+ TreeTy *Root;
+
+public:
+ /// Constructs a set from a pointer to a tree root. In general one
+ /// should use a Factory object to create sets instead of directly
+ /// invoking the constructor, but there are cases where make this
+ /// constructor public is useful.
+ explicit ImmutableSet(TreeTy* R) : Root(R) {
+ if (Root) { Root->retain(); }
+ }
+ ImmutableSet(const ImmutableSet &X) : Root(X.Root) {
+ if (Root) { Root->retain(); }
+ }
+ ImmutableSet &operator=(const ImmutableSet &X) {
+ if (Root != X.Root) {
+ if (X.Root) { X.Root->retain(); }
+ if (Root) { Root->release(); }
+ Root = X.Root;
+ }
+ return *this;
+ }
+ ~ImmutableSet() {
+ if (Root) { Root->release(); }
+ }
+
+ class Factory {
+ typename TreeTy::Factory F;
+ const bool Canonicalize;
+
+ public:
+ Factory(bool canonicalize = true)
+ : Canonicalize(canonicalize) {}
+
+ Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
+ : F(Alloc), Canonicalize(canonicalize) {}
+
+ /// getEmptySet - Returns an immutable set that contains no elements.
+ ImmutableSet getEmptySet() {
+ return ImmutableSet(F.getEmptyTree());
+ }
+
+ /// add - Creates a new immutable set that contains all of the values
+ /// of the original set with the addition of the specified value. If
+ /// the original set already included the value, then the original set is
+ /// returned and no memory is allocated. The time and space complexity
+ /// of this operation is logarithmic in the size of the original set.
+ /// The memory allocated to represent the set is released when the
+ /// factory object that created the set is destroyed.
+ ImmutableSet add(ImmutableSet Old, value_type_ref V) {
+ TreeTy *NewT = F.add(Old.Root, V);
+ return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
+ }
+
+ /// remove - Creates a new immutable set that contains all of the values
+ /// of the original set with the exception of the specified value. If
+ /// the original set did not contain the value, the original set is
+ /// returned and no memory is allocated. The time and space complexity
+ /// of this operation is logarithmic in the size of the original set.
+ /// The memory allocated to represent the set is released when the
+ /// factory object that created the set is destroyed.
+ ImmutableSet remove(ImmutableSet Old, value_type_ref V) {
+ TreeTy *NewT = F.remove(Old.Root, V);
+ return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
+ }
+
+ BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
+
+ typename TreeTy::Factory *getTreeFactory() const {
+ return const_cast<typename TreeTy::Factory *>(&F);
+ }
+
+ private:
+ Factory(const Factory& RHS) LLVM_DELETED_FUNCTION;
+ void operator=(const Factory& RHS) LLVM_DELETED_FUNCTION;
+ };
+
+ friend class Factory;
+
+ /// Returns true if the set contains the specified value.
+ bool contains(value_type_ref V) const {
+ return Root ? Root->contains(V) : false;
+ }
+
+ bool operator==(const ImmutableSet &RHS) const {
+ return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
+ }
+
+ bool operator!=(const ImmutableSet &RHS) const {
+ return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
+ }
+
+ TreeTy *getRoot() {
+ if (Root) { Root->retain(); }
+ return Root;
+ }
+
+ TreeTy *getRootWithoutRetain() const {
+ return Root;
+ }
+
+ /// isEmpty - Return true if the set contains no elements.
+ bool isEmpty() const { return !Root; }
+
+ /// isSingleton - Return true if the set contains exactly one element.
+ /// This method runs in constant time.
+ bool isSingleton() const { return getHeight() == 1; }
+
+ template <typename Callback>
+ void foreach(Callback& C) { if (Root) Root->foreach(C); }
+
+ template <typename Callback>
+ void foreach() { if (Root) { Callback C; Root->foreach(C); } }
+
+ //===--------------------------------------------------===//
+ // Iterators.
+ //===--------------------------------------------------===//
+
+ class iterator {
+ typename TreeTy::iterator itr;
+ iterator(TreeTy* t) : itr(t) {}
+ friend class ImmutableSet<ValT,ValInfo>;
+ public:
+ iterator() {}
+ inline value_type_ref operator*() const { return itr->getValue(); }
+ inline iterator& operator++() { ++itr; return *this; }
+ inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
+ inline iterator& operator--() { --itr; return *this; }
+ inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
+ inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
+ inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
+ inline value_type *operator->() const { return &(operator*()); }
+ };
+
+ iterator begin() const { return iterator(Root); }
+ iterator end() const { return iterator(); }
+
+ //===--------------------------------------------------===//
+ // Utility methods.
+ //===--------------------------------------------------===//
+
+ unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
+
+ static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
+ ID.AddPointer(S.Root);
+ }
+
+ inline void Profile(FoldingSetNodeID& ID) const {
+ return Profile(ID,*this);
+ }
+
+ //===--------------------------------------------------===//
+ // For testing.
+ //===--------------------------------------------------===//
+
+ void validateTree() const { if (Root) Root->validateTree(); }
+};
+
+// NOTE: This may some day replace the current ImmutableSet.
+template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
+class ImmutableSetRef {
+public:
+ typedef typename ValInfo::value_type value_type;
+ typedef typename ValInfo::value_type_ref value_type_ref;
+ typedef ImutAVLTree<ValInfo> TreeTy;
+ typedef typename TreeTy::Factory FactoryTy;
+
+private:
+ TreeTy *Root;
+ FactoryTy *Factory;
+
+public:
+ /// Constructs a set from a pointer to a tree root. In general one
+ /// should use a Factory object to create sets instead of directly
+ /// invoking the constructor, but there are cases where make this
+ /// constructor public is useful.
+ explicit ImmutableSetRef(TreeTy* R, FactoryTy *F)
+ : Root(R),
+ Factory(F) {
+ if (Root) { Root->retain(); }
+ }
+ ImmutableSetRef(const ImmutableSetRef &X)
+ : Root(X.Root),
+ Factory(X.Factory) {
+ if (Root) { Root->retain(); }
+ }
+ ImmutableSetRef &operator=(const ImmutableSetRef &X) {
+ if (Root != X.Root) {
+ if (X.Root) { X.Root->retain(); }
+ if (Root) { Root->release(); }
+ Root = X.Root;
+ Factory = X.Factory;
+ }
+ return *this;
+ }
+ ~ImmutableSetRef() {
+ if (Root) { Root->release(); }
+ }
+
+ static inline ImmutableSetRef getEmptySet(FactoryTy *F) {
+ return ImmutableSetRef(0, F);
+ }
+
+ ImmutableSetRef add(value_type_ref V) {
+ return ImmutableSetRef(Factory->add(Root, V), Factory);
+ }
+
+ ImmutableSetRef remove(value_type_ref V) {
+ return ImmutableSetRef(Factory->remove(Root, V), Factory);
+ }
+
+ /// Returns true if the set contains the specified value.
+ bool contains(value_type_ref V) const {
+ return Root ? Root->contains(V) : false;
+ }
+
+ ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
+ return ImmutableSet<ValT>(canonicalize ?
+ Factory->getCanonicalTree(Root) : Root);
+ }
+
+ TreeTy *getRootWithoutRetain() const {
+ return Root;
+ }
+
+ bool operator==(const ImmutableSetRef &RHS) const {
+ return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
+ }
+
+ bool operator!=(const ImmutableSetRef &RHS) const {
+ return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
+ }
+
+ /// isEmpty - Return true if the set contains no elements.
+ bool isEmpty() const { return !Root; }
+
+ /// isSingleton - Return true if the set contains exactly one element.
+ /// This method runs in constant time.
+ bool isSingleton() const { return getHeight() == 1; }
+
+ //===--------------------------------------------------===//
+ // Iterators.
+ //===--------------------------------------------------===//
+
+ class iterator {
+ typename TreeTy::iterator itr;
+ iterator(TreeTy* t) : itr(t) {}
+ friend class ImmutableSetRef<ValT,ValInfo>;
+ public:
+ iterator() {}
+ inline value_type_ref operator*() const { return itr->getValue(); }
+ inline iterator& operator++() { ++itr; return *this; }
+ inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
+ inline iterator& operator--() { --itr; return *this; }
+ inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
+ inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
+ inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
+ inline value_type *operator->() const { return &(operator*()); }
+ };
+
+ iterator begin() const { return iterator(Root); }
+ iterator end() const { return iterator(); }
+
+ //===--------------------------------------------------===//
+ // Utility methods.
+ //===--------------------------------------------------===//
+
+ unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
+
+ static inline void Profile(FoldingSetNodeID& ID, const ImmutableSetRef& S) {
+ ID.AddPointer(S.Root);
+ }
+
+ inline void Profile(FoldingSetNodeID& ID) const {
+ return Profile(ID,*this);
+ }
+
+ //===--------------------------------------------------===//
+ // For testing.
+ //===--------------------------------------------------===//
+
+ void validateTree() const { if (Root) Root->validateTree(); }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/InMemoryStruct.h b/include/llvm/ADT/InMemoryStruct.h
new file mode 100644
index 00000000000..a56084501a6
--- /dev/null
+++ b/include/llvm/ADT/InMemoryStruct.h
@@ -0,0 +1,77 @@
+//===- InMemoryStruct.h - Indirect Struct Access Smart Pointer --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_INMEMORYSTRUCT_H
+#define LLVM_ADT_INMEMORYSTRUCT_H
+
+#include <cassert>
+
+namespace llvm {
+
+/// \brief Helper object for abstracting access to an in-memory structure which
+/// may require some kind of temporary storage.
+///
+/// This class is designed to be used for accessing file data structures which
+/// in the common case can be accessed from a direct pointer to a memory mapped
+/// object, but which in some cases may require indirect access to a temporary
+/// structure (which, for example, may have undergone endianness translation).
+template<typename T>
+class InMemoryStruct {
+ typedef T value_type;
+ typedef value_type &reference;
+ typedef value_type *pointer;
+ typedef const value_type &const_reference;
+ typedef const value_type *const_pointer;
+
+ /// \brief The smart pointer target.
+ value_type *Target;
+
+ /// \brief A temporary object which can be used as a target of the smart
+ /// pointer.
+ value_type Contents;
+
+private:
+
+public:
+ InMemoryStruct() : Target(0) {}
+ InMemoryStruct(reference Value) : Target(&Contents), Contents(Value) {}
+ InMemoryStruct(pointer Value) : Target(Value) {}
+ InMemoryStruct(const InMemoryStruct<T> &Value) { *this = Value; }
+
+ void operator=(const InMemoryStruct<T> &Value) {
+ if (Value.Target != &Value.Contents) {
+ Target = Value.Target;
+ } else {
+ Target = &Contents;
+ Contents = Value.Contents;
+ }
+ }
+
+ const_reference operator*() const {
+ assert(Target && "Cannot dereference null pointer");
+ return *Target;
+ }
+ reference operator*() {
+ assert(Target && "Cannot dereference null pointer");
+ return *Target;
+ }
+
+ const_pointer operator->() const {
+ return Target;
+ }
+ pointer operator->() {
+ return Target;
+ }
+
+ operator bool() const { return Target != 0; }
+};
+
+}
+
+#endif
diff --git a/include/llvm/ADT/IndexedMap.h b/include/llvm/ADT/IndexedMap.h
new file mode 100644
index 00000000000..2ffb5058e5b
--- /dev/null
+++ b/include/llvm/ADT/IndexedMap.h
@@ -0,0 +1,82 @@
+//===- llvm/ADT/IndexedMap.h - An index map implementation ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements an indexed map. The index map template takes two
+// types. The first is the mapped type and the second is a functor
+// that maps its argument to a size_t. On instantiation a "null" value
+// can be provided to be used as a "does not exist" indicator in the
+// map. A member function grow() is provided that given the value of
+// the maximally indexed key (the argument of the functor) makes sure
+// the map has enough space for it.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_INDEXEDMAP_H
+#define LLVM_ADT_INDEXEDMAP_H
+
+#include "llvm/ADT/STLExtras.h"
+#include <cassert>
+#include <functional>
+#include <vector>
+
+namespace llvm {
+
+template <typename T, typename ToIndexT = llvm::identity<unsigned> >
+ class IndexedMap {
+ typedef typename ToIndexT::argument_type IndexT;
+ typedef std::vector<T> StorageT;
+ StorageT storage_;
+ T nullVal_;
+ ToIndexT toIndex_;
+
+ public:
+ IndexedMap() : nullVal_(T()) { }
+
+ explicit IndexedMap(const T& val) : nullVal_(val) { }
+
+ typename StorageT::reference operator[](IndexT n) {
+ assert(toIndex_(n) < storage_.size() && "index out of bounds!");
+ return storage_[toIndex_(n)];
+ }
+
+ typename StorageT::const_reference operator[](IndexT n) const {
+ assert(toIndex_(n) < storage_.size() && "index out of bounds!");
+ return storage_[toIndex_(n)];
+ }
+
+ void reserve(typename StorageT::size_type s) {
+ storage_.reserve(s);
+ }
+
+ void resize(typename StorageT::size_type s) {
+ storage_.resize(s, nullVal_);
+ }
+
+ void clear() {
+ storage_.clear();
+ }
+
+ void grow(IndexT n) {
+ unsigned NewSize = toIndex_(n) + 1;
+ if (NewSize > storage_.size())
+ resize(NewSize);
+ }
+
+ bool inBounds(IndexT n) const {
+ return toIndex_(n) < storage_.size();
+ }
+
+ typename StorageT::size_type size() const {
+ return storage_.size();
+ }
+ };
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/IntEqClasses.h b/include/llvm/ADT/IntEqClasses.h
new file mode 100644
index 00000000000..8e75c48e376
--- /dev/null
+++ b/include/llvm/ADT/IntEqClasses.h
@@ -0,0 +1,88 @@
+//===-- llvm/ADT/IntEqClasses.h - Equiv. Classes of Integers ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Equivalence classes for small integers. This is a mapping of the integers
+// 0 .. N-1 into M equivalence classes numbered 0 .. M-1.
+//
+// Initially each integer has its own equivalence class. Classes are joined by
+// passing a representative member of each class to join().
+//
+// Once the classes are built, compress() will number them 0 .. M-1 and prevent
+// further changes.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_INTEQCLASSES_H
+#define LLVM_ADT_INTEQCLASSES_H
+
+#include "llvm/ADT/SmallVector.h"
+
+namespace llvm {
+
+class IntEqClasses {
+ /// EC - When uncompressed, map each integer to a smaller member of its
+ /// equivalence class. The class leader is the smallest member and maps to
+ /// itself.
+ ///
+ /// When compressed, EC[i] is the equivalence class of i.
+ SmallVector<unsigned, 8> EC;
+
+ /// NumClasses - The number of equivalence classes when compressed, or 0 when
+ /// uncompressed.
+ unsigned NumClasses;
+
+public:
+ /// IntEqClasses - Create an equivalence class mapping for 0 .. N-1.
+ IntEqClasses(unsigned N = 0) : NumClasses(0) { grow(N); }
+
+ /// grow - Increase capacity to hold 0 .. N-1, putting new integers in unique
+ /// equivalence classes.
+ /// This requires an uncompressed map.
+ void grow(unsigned N);
+
+ /// clear - Clear all classes so that grow() will assign a unique class to
+ /// every integer.
+ void clear() {
+ EC.clear();
+ NumClasses = 0;
+ }
+
+ /// join - Join the equivalence classes of a and b. After joining classes,
+ /// findLeader(a) == findLeader(b).
+ /// This requires an uncompressed map.
+ void join(unsigned a, unsigned b);
+
+ /// findLeader - Compute the leader of a's equivalence class. This is the
+ /// smallest member of the class.
+ /// This requires an uncompressed map.
+ unsigned findLeader(unsigned a) const;
+
+ /// compress - Compress equivalence classes by numbering them 0 .. M.
+ /// This makes the equivalence class map immutable.
+ void compress();
+
+ /// getNumClasses - Return the number of equivalence classes after compress()
+ /// was called.
+ unsigned getNumClasses() const { return NumClasses; }
+
+ /// operator[] - Return a's equivalence class number, 0 .. getNumClasses()-1.
+ /// This requires a compressed map.
+ unsigned operator[](unsigned a) const {
+ assert(NumClasses && "operator[] called before compress()");
+ return EC[a];
+ }
+
+ /// uncompress - Change back to the uncompressed representation that allows
+ /// editing.
+ void uncompress();
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/IntervalMap.h b/include/llvm/ADT/IntervalMap.h
new file mode 100644
index 00000000000..931b67e4091
--- /dev/null
+++ b/include/llvm/ADT/IntervalMap.h
@@ -0,0 +1,2146 @@
+//===- llvm/ADT/IntervalMap.h - A sorted interval map -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements a coalescing interval map for small objects.
+//
+// KeyT objects are mapped to ValT objects. Intervals of keys that map to the
+// same value are represented in a compressed form.
+//
+// Iterators provide ordered access to the compressed intervals rather than the
+// individual keys, and insert and erase operations use key intervals as well.
+//
+// Like SmallVector, IntervalMap will store the first N intervals in the map
+// object itself without any allocations. When space is exhausted it switches to
+// a B+-tree representation with very small overhead for small key and value
+// objects.
+//
+// A Traits class specifies how keys are compared. It also allows IntervalMap to
+// work with both closed and half-open intervals.
+//
+// Keys and values are not stored next to each other in a std::pair, so we don't
+// provide such a value_type. Dereferencing iterators only returns the mapped
+// value. The interval bounds are accessible through the start() and stop()
+// iterator methods.
+//
+// IntervalMap is optimized for small key and value objects, 4 or 8 bytes each
+// is the optimal size. For large objects use std::map instead.
+//
+//===----------------------------------------------------------------------===//
+//
+// Synopsis:
+//
+// template <typename KeyT, typename ValT, unsigned N, typename Traits>
+// class IntervalMap {
+// public:
+// typedef KeyT key_type;
+// typedef ValT mapped_type;
+// typedef RecyclingAllocator<...> Allocator;
+// class iterator;
+// class const_iterator;
+//
+// explicit IntervalMap(Allocator&);
+// ~IntervalMap():
+//
+// bool empty() const;
+// KeyT start() const;
+// KeyT stop() const;
+// ValT lookup(KeyT x, Value NotFound = Value()) const;
+//
+// const_iterator begin() const;
+// const_iterator end() const;
+// iterator begin();
+// iterator end();
+// const_iterator find(KeyT x) const;
+// iterator find(KeyT x);
+//
+// void insert(KeyT a, KeyT b, ValT y);
+// void clear();
+// };
+//
+// template <typename KeyT, typename ValT, unsigned N, typename Traits>
+// class IntervalMap::const_iterator :
+// public std::iterator<std::bidirectional_iterator_tag, ValT> {
+// public:
+// bool operator==(const const_iterator &) const;
+// bool operator!=(const const_iterator &) const;
+// bool valid() const;
+//
+// const KeyT &start() const;
+// const KeyT &stop() const;
+// const ValT &value() const;
+// const ValT &operator*() const;
+// const ValT *operator->() const;
+//
+// const_iterator &operator++();
+// const_iterator &operator++(int);
+// const_iterator &operator--();
+// const_iterator &operator--(int);
+// void goToBegin();
+// void goToEnd();
+// void find(KeyT x);
+// void advanceTo(KeyT x);
+// };
+//
+// template <typename KeyT, typename ValT, unsigned N, typename Traits>
+// class IntervalMap::iterator : public const_iterator {
+// public:
+// void insert(KeyT a, KeyT b, Value y);
+// void erase();
+// };
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_INTERVALMAP_H
+#define LLVM_ADT_INTERVALMAP_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/Support/Allocator.h"
+#include "llvm/Support/RecyclingAllocator.h"
+#include <iterator>
+
+namespace llvm {
+
+
+//===----------------------------------------------------------------------===//
+//--- Key traits ---//
+//===----------------------------------------------------------------------===//
+//
+// The IntervalMap works with closed or half-open intervals.
+// Adjacent intervals that map to the same value are coalesced.
+//
+// The IntervalMapInfo traits class is used to determine if a key is contained
+// in an interval, and if two intervals are adjacent so they can be coalesced.
+// The provided implementation works for closed integer intervals, other keys
+// probably need a specialized version.
+//
+// The point x is contained in [a;b] when !startLess(x, a) && !stopLess(b, x).
+//
+// It is assumed that (a;b] half-open intervals are not used, only [a;b) is
+// allowed. This is so that stopLess(a, b) can be used to determine if two
+// intervals overlap.
+//
+//===----------------------------------------------------------------------===//
+
+template <typename T>
+struct IntervalMapInfo {
+
+ /// startLess - Return true if x is not in [a;b].
+ /// This is x < a both for closed intervals and for [a;b) half-open intervals.
+ static inline bool startLess(const T &x, const T &a) {
+ return x < a;
+ }
+
+ /// stopLess - Return true if x is not in [a;b].
+ /// This is b < x for a closed interval, b <= x for [a;b) half-open intervals.
+ static inline bool stopLess(const T &b, const T &x) {
+ return b < x;
+ }
+
+ /// adjacent - Return true when the intervals [x;a] and [b;y] can coalesce.
+ /// This is a+1 == b for closed intervals, a == b for half-open intervals.
+ static inline bool adjacent(const T &a, const T &b) {
+ return a+1 == b;
+ }
+
+};
+
+/// IntervalMapImpl - Namespace used for IntervalMap implementation details.
+/// It should be considered private to the implementation.
+namespace IntervalMapImpl {
+
+// Forward declarations.
+template <typename, typename, unsigned, typename> class LeafNode;
+template <typename, typename, unsigned, typename> class BranchNode;
+
+typedef std::pair<unsigned,unsigned> IdxPair;
+
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMapImpl::NodeBase ---//
+//===----------------------------------------------------------------------===//
+//
+// Both leaf and branch nodes store vectors of pairs.
+// Leaves store ((KeyT, KeyT), ValT) pairs, branches use (NodeRef, KeyT).
+//
+// Keys and values are stored in separate arrays to avoid padding caused by
+// different object alignments. This also helps improve locality of reference
+// when searching the keys.
+//
+// The nodes don't know how many elements they contain - that information is
+// stored elsewhere. Omitting the size field prevents padding and allows a node
+// to fill the allocated cache lines completely.
+//
+// These are typical key and value sizes, the node branching factor (N), and
+// wasted space when nodes are sized to fit in three cache lines (192 bytes):
+//
+// T1 T2 N Waste Used by
+// 4 4 24 0 Branch<4> (32-bit pointers)
+// 8 4 16 0 Leaf<4,4>, Branch<4>
+// 8 8 12 0 Leaf<4,8>, Branch<8>
+// 16 4 9 12 Leaf<8,4>
+// 16 8 8 0 Leaf<8,8>
+//
+//===----------------------------------------------------------------------===//
+
+template <typename T1, typename T2, unsigned N>
+class NodeBase {
+public:
+ enum { Capacity = N };
+
+ T1 first[N];
+ T2 second[N];
+
+ /// copy - Copy elements from another node.
+ /// @param Other Node elements are copied from.
+ /// @param i Beginning of the source range in other.
+ /// @param j Beginning of the destination range in this.
+ /// @param Count Number of elements to copy.
+ template <unsigned M>
+ void copy(const NodeBase<T1, T2, M> &Other, unsigned i,
+ unsigned j, unsigned Count) {
+ assert(i + Count <= M && "Invalid source range");
+ assert(j + Count <= N && "Invalid dest range");
+ for (unsigned e = i + Count; i != e; ++i, ++j) {
+ first[j] = Other.first[i];
+ second[j] = Other.second[i];
+ }
+ }
+
+ /// moveLeft - Move elements to the left.
+ /// @param i Beginning of the source range.
+ /// @param j Beginning of the destination range.
+ /// @param Count Number of elements to copy.
+ void moveLeft(unsigned i, unsigned j, unsigned Count) {
+ assert(j <= i && "Use moveRight shift elements right");
+ copy(*this, i, j, Count);
+ }
+
+ /// moveRight - Move elements to the right.
+ /// @param i Beginning of the source range.
+ /// @param j Beginning of the destination range.
+ /// @param Count Number of elements to copy.
+ void moveRight(unsigned i, unsigned j, unsigned Count) {
+ assert(i <= j && "Use moveLeft shift elements left");
+ assert(j + Count <= N && "Invalid range");
+ while (Count--) {
+ first[j + Count] = first[i + Count];
+ second[j + Count] = second[i + Count];
+ }
+ }
+
+ /// erase - Erase elements [i;j).
+ /// @param i Beginning of the range to erase.
+ /// @param j End of the range. (Exclusive).
+ /// @param Size Number of elements in node.
+ void erase(unsigned i, unsigned j, unsigned Size) {
+ moveLeft(j, i, Size - j);
+ }
+
+ /// erase - Erase element at i.
+ /// @param i Index of element to erase.
+ /// @param Size Number of elements in node.
+ void erase(unsigned i, unsigned Size) {
+ erase(i, i+1, Size);
+ }
+
+ /// shift - Shift elements [i;size) 1 position to the right.
+ /// @param i Beginning of the range to move.
+ /// @param Size Number of elements in node.
+ void shift(unsigned i, unsigned Size) {
+ moveRight(i, i + 1, Size - i);
+ }
+
+ /// transferToLeftSib - Transfer elements to a left sibling node.
+ /// @param Size Number of elements in this.
+ /// @param Sib Left sibling node.
+ /// @param SSize Number of elements in sib.
+ /// @param Count Number of elements to transfer.
+ void transferToLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize,
+ unsigned Count) {
+ Sib.copy(*this, 0, SSize, Count);
+ erase(0, Count, Size);
+ }
+
+ /// transferToRightSib - Transfer elements to a right sibling node.
+ /// @param Size Number of elements in this.
+ /// @param Sib Right sibling node.
+ /// @param SSize Number of elements in sib.
+ /// @param Count Number of elements to transfer.
+ void transferToRightSib(unsigned Size, NodeBase &Sib, unsigned SSize,
+ unsigned Count) {
+ Sib.moveRight(0, Count, SSize);
+ Sib.copy(*this, Size-Count, 0, Count);
+ }
+
+ /// adjustFromLeftSib - Adjust the number if elements in this node by moving
+ /// elements to or from a left sibling node.
+ /// @param Size Number of elements in this.
+ /// @param Sib Right sibling node.
+ /// @param SSize Number of elements in sib.
+ /// @param Add The number of elements to add to this node, possibly < 0.
+ /// @return Number of elements added to this node, possibly negative.
+ int adjustFromLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, int Add) {
+ if (Add > 0) {
+ // We want to grow, copy from sib.
+ unsigned Count = std::min(std::min(unsigned(Add), SSize), N - Size);
+ Sib.transferToRightSib(SSize, *this, Size, Count);
+ return Count;
+ } else {
+ // We want to shrink, copy to sib.
+ unsigned Count = std::min(std::min(unsigned(-Add), Size), N - SSize);
+ transferToLeftSib(Size, Sib, SSize, Count);
+ return -Count;
+ }
+ }
+};
+
+/// IntervalMapImpl::adjustSiblingSizes - Move elements between sibling nodes.
+/// @param Node Array of pointers to sibling nodes.
+/// @param Nodes Number of nodes.
+/// @param CurSize Array of current node sizes, will be overwritten.
+/// @param NewSize Array of desired node sizes.
+template <typename NodeT>
+void adjustSiblingSizes(NodeT *Node[], unsigned Nodes,
+ unsigned CurSize[], const unsigned NewSize[]) {
+ // Move elements right.
+ for (int n = Nodes - 1; n; --n) {
+ if (CurSize[n] == NewSize[n])
+ continue;
+ for (int m = n - 1; m != -1; --m) {
+ int d = Node[n]->adjustFromLeftSib(CurSize[n], *Node[m], CurSize[m],
+ NewSize[n] - CurSize[n]);
+ CurSize[m] -= d;
+ CurSize[n] += d;
+ // Keep going if the current node was exhausted.
+ if (CurSize[n] >= NewSize[n])
+ break;
+ }
+ }
+
+ if (Nodes == 0)
+ return;
+
+ // Move elements left.
+ for (unsigned n = 0; n != Nodes - 1; ++n) {
+ if (CurSize[n] == NewSize[n])
+ continue;
+ for (unsigned m = n + 1; m != Nodes; ++m) {
+ int d = Node[m]->adjustFromLeftSib(CurSize[m], *Node[n], CurSize[n],
+ CurSize[n] - NewSize[n]);
+ CurSize[m] += d;
+ CurSize[n] -= d;
+ // Keep going if the current node was exhausted.
+ if (CurSize[n] >= NewSize[n])
+ break;
+ }
+ }
+
+#ifndef NDEBUG
+ for (unsigned n = 0; n != Nodes; n++)
+ assert(CurSize[n] == NewSize[n] && "Insufficient element shuffle");
+#endif
+}
+
+/// IntervalMapImpl::distribute - Compute a new distribution of node elements
+/// after an overflow or underflow. Reserve space for a new element at Position,
+/// and compute the node that will hold Position after redistributing node
+/// elements.
+///
+/// It is required that
+///
+/// Elements == sum(CurSize), and
+/// Elements + Grow <= Nodes * Capacity.
+///
+/// NewSize[] will be filled in such that:
+///
+/// sum(NewSize) == Elements, and
+/// NewSize[i] <= Capacity.
+///
+/// The returned index is the node where Position will go, so:
+///
+/// sum(NewSize[0..idx-1]) <= Position
+/// sum(NewSize[0..idx]) >= Position
+///
+/// The last equality, sum(NewSize[0..idx]) == Position, can only happen when
+/// Grow is set and NewSize[idx] == Capacity-1. The index points to the node
+/// before the one holding the Position'th element where there is room for an
+/// insertion.
+///
+/// @param Nodes The number of nodes.
+/// @param Elements Total elements in all nodes.
+/// @param Capacity The capacity of each node.
+/// @param CurSize Array[Nodes] of current node sizes, or NULL.
+/// @param NewSize Array[Nodes] to receive the new node sizes.
+/// @param Position Insert position.
+/// @param Grow Reserve space for a new element at Position.
+/// @return (node, offset) for Position.
+IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity,
+ const unsigned *CurSize, unsigned NewSize[],
+ unsigned Position, bool Grow);
+
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMapImpl::NodeSizer ---//
+//===----------------------------------------------------------------------===//
+//
+// Compute node sizes from key and value types.
+//
+// The branching factors are chosen to make nodes fit in three cache lines.
+// This may not be possible if keys or values are very large. Such large objects
+// are handled correctly, but a std::map would probably give better performance.
+//
+//===----------------------------------------------------------------------===//
+
+enum {
+ // Cache line size. Most architectures have 32 or 64 byte cache lines.
+ // We use 64 bytes here because it provides good branching factors.
+ Log2CacheLine = 6,
+ CacheLineBytes = 1 << Log2CacheLine,
+ DesiredNodeBytes = 3 * CacheLineBytes
+};
+
+template <typename KeyT, typename ValT>
+struct NodeSizer {
+ enum {
+ // Compute the leaf node branching factor that makes a node fit in three
+ // cache lines. The branching factor must be at least 3, or some B+-tree
+ // balancing algorithms won't work.
+ // LeafSize can't be larger than CacheLineBytes. This is required by the
+ // PointerIntPair used by NodeRef.
+ DesiredLeafSize = DesiredNodeBytes /
+ static_cast<unsigned>(2*sizeof(KeyT)+sizeof(ValT)),
+ MinLeafSize = 3,
+ LeafSize = DesiredLeafSize > MinLeafSize ? DesiredLeafSize : MinLeafSize
+ };
+
+ typedef NodeBase<std::pair<KeyT, KeyT>, ValT, LeafSize> LeafBase;
+
+ enum {
+ // Now that we have the leaf branching factor, compute the actual allocation
+ // unit size by rounding up to a whole number of cache lines.
+ AllocBytes = (sizeof(LeafBase) + CacheLineBytes-1) & ~(CacheLineBytes-1),
+
+ // Determine the branching factor for branch nodes.
+ BranchSize = AllocBytes /
+ static_cast<unsigned>(sizeof(KeyT) + sizeof(void*))
+ };
+
+ /// Allocator - The recycling allocator used for both branch and leaf nodes.
+ /// This typedef is very likely to be identical for all IntervalMaps with
+ /// reasonably sized entries, so the same allocator can be shared among
+ /// different kinds of maps.
+ typedef RecyclingAllocator<BumpPtrAllocator, char,
+ AllocBytes, CacheLineBytes> Allocator;
+
+};
+
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMapImpl::NodeRef ---//
+//===----------------------------------------------------------------------===//
+//
+// B+-tree nodes can be leaves or branches, so we need a polymorphic node
+// pointer that can point to both kinds.
+//
+// All nodes are cache line aligned and the low 6 bits of a node pointer are
+// always 0. These bits are used to store the number of elements in the
+// referenced node. Besides saving space, placing node sizes in the parents
+// allow tree balancing algorithms to run without faulting cache lines for nodes
+// that may not need to be modified.
+//
+// A NodeRef doesn't know whether it references a leaf node or a branch node.
+// It is the responsibility of the caller to use the correct types.
+//
+// Nodes are never supposed to be empty, and it is invalid to store a node size
+// of 0 in a NodeRef. The valid range of sizes is 1-64.
+//
+//===----------------------------------------------------------------------===//
+
+class NodeRef {
+ struct CacheAlignedPointerTraits {
+ static inline void *getAsVoidPointer(void *P) { return P; }
+ static inline void *getFromVoidPointer(void *P) { return P; }
+ enum { NumLowBitsAvailable = Log2CacheLine };
+ };
+ PointerIntPair<void*, Log2CacheLine, unsigned, CacheAlignedPointerTraits> pip;
+
+public:
+ /// NodeRef - Create a null ref.
+ NodeRef() {}
+
+ /// operator bool - Detect a null ref.
+ operator bool() const { return pip.getOpaqueValue(); }
+
+ /// NodeRef - Create a reference to the node p with n elements.
+ template <typename NodeT>
+ NodeRef(NodeT *p, unsigned n) : pip(p, n - 1) {
+ assert(n <= NodeT::Capacity && "Size too big for node");
+ }
+
+ /// size - Return the number of elements in the referenced node.
+ unsigned size() const { return pip.getInt() + 1; }
+
+ /// setSize - Update the node size.
+ void setSize(unsigned n) { pip.setInt(n - 1); }
+
+ /// subtree - Access the i'th subtree reference in a branch node.
+ /// This depends on branch nodes storing the NodeRef array as their first
+ /// member.
+ NodeRef &subtree(unsigned i) const {
+ return reinterpret_cast<NodeRef*>(pip.getPointer())[i];
+ }
+
+ /// get - Dereference as a NodeT reference.
+ template <typename NodeT>
+ NodeT &get() const {
+ return *reinterpret_cast<NodeT*>(pip.getPointer());
+ }
+
+ bool operator==(const NodeRef &RHS) const {
+ if (pip == RHS.pip)
+ return true;
+ assert(pip.getPointer() != RHS.pip.getPointer() && "Inconsistent NodeRefs");
+ return false;
+ }
+
+ bool operator!=(const NodeRef &RHS) const {
+ return !operator==(RHS);
+ }
+};
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMapImpl::LeafNode ---//
+//===----------------------------------------------------------------------===//
+//
+// Leaf nodes store up to N disjoint intervals with corresponding values.
+//
+// The intervals are kept sorted and fully coalesced so there are no adjacent
+// intervals mapping to the same value.
+//
+// These constraints are always satisfied:
+//
+// - Traits::stopLess(start(i), stop(i)) - Non-empty, sane intervals.
+//
+// - Traits::stopLess(stop(i), start(i + 1) - Sorted.
+//
+// - value(i) != value(i + 1) || !Traits::adjacent(stop(i), start(i + 1))
+// - Fully coalesced.
+//
+//===----------------------------------------------------------------------===//
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+class LeafNode : public NodeBase<std::pair<KeyT, KeyT>, ValT, N> {
+public:
+ const KeyT &start(unsigned i) const { return this->first[i].first; }
+ const KeyT &stop(unsigned i) const { return this->first[i].second; }
+ const ValT &value(unsigned i) const { return this->second[i]; }
+
+ KeyT &start(unsigned i) { return this->first[i].first; }
+ KeyT &stop(unsigned i) { return this->first[i].second; }
+ ValT &value(unsigned i) { return this->second[i]; }
+
+ /// findFrom - Find the first interval after i that may contain x.
+ /// @param i Starting index for the search.
+ /// @param Size Number of elements in node.
+ /// @param x Key to search for.
+ /// @return First index with !stopLess(key[i].stop, x), or size.
+ /// This is the first interval that can possibly contain x.
+ unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
+ assert(i <= Size && Size <= N && "Bad indices");
+ assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
+ "Index is past the needed point");
+ while (i != Size && Traits::stopLess(stop(i), x)) ++i;
+ return i;
+ }
+
+ /// safeFind - Find an interval that is known to exist. This is the same as
+ /// findFrom except is it assumed that x is at least within range of the last
+ /// interval.
+ /// @param i Starting index for the search.
+ /// @param x Key to search for.
+ /// @return First index with !stopLess(key[i].stop, x), never size.
+ /// This is the first interval that can possibly contain x.
+ unsigned safeFind(unsigned i, KeyT x) const {
+ assert(i < N && "Bad index");
+ assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
+ "Index is past the needed point");
+ while (Traits::stopLess(stop(i), x)) ++i;
+ assert(i < N && "Unsafe intervals");
+ return i;
+ }
+
+ /// safeLookup - Lookup mapped value for a safe key.
+ /// It is assumed that x is within range of the last entry.
+ /// @param x Key to search for.
+ /// @param NotFound Value to return if x is not in any interval.
+ /// @return The mapped value at x or NotFound.
+ ValT safeLookup(KeyT x, ValT NotFound) const {
+ unsigned i = safeFind(0, x);
+ return Traits::startLess(x, start(i)) ? NotFound : value(i);
+ }
+
+ unsigned insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y);
+};
+
+/// insertFrom - Add mapping of [a;b] to y if possible, coalescing as much as
+/// possible. This may cause the node to grow by 1, or it may cause the node
+/// to shrink because of coalescing.
+/// @param i Starting index = insertFrom(0, size, a)
+/// @param Size Number of elements in node.
+/// @param a Interval start.
+/// @param b Interval stop.
+/// @param y Value be mapped.
+/// @return (insert position, new size), or (i, Capacity+1) on overflow.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+unsigned LeafNode<KeyT, ValT, N, Traits>::
+insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y) {
+ unsigned i = Pos;
+ assert(i <= Size && Size <= N && "Invalid index");
+ assert(!Traits::stopLess(b, a) && "Invalid interval");
+
+ // Verify the findFrom invariant.
+ assert((i == 0 || Traits::stopLess(stop(i - 1), a)));
+ assert((i == Size || !Traits::stopLess(stop(i), a)));
+ assert((i == Size || Traits::stopLess(b, start(i))) && "Overlapping insert");
+
+ // Coalesce with previous interval.
+ if (i && value(i - 1) == y && Traits::adjacent(stop(i - 1), a)) {
+ Pos = i - 1;
+ // Also coalesce with next interval?
+ if (i != Size && value(i) == y && Traits::adjacent(b, start(i))) {
+ stop(i - 1) = stop(i);
+ this->erase(i, Size);
+ return Size - 1;
+ }
+ stop(i - 1) = b;
+ return Size;
+ }
+
+ // Detect overflow.
+ if (i == N)
+ return N + 1;
+
+ // Add new interval at end.
+ if (i == Size) {
+ start(i) = a;
+ stop(i) = b;
+ value(i) = y;
+ return Size + 1;
+ }
+
+ // Try to coalesce with following interval.
+ if (value(i) == y && Traits::adjacent(b, start(i))) {
+ start(i) = a;
+ return Size;
+ }
+
+ // We must insert before i. Detect overflow.
+ if (Size == N)
+ return N + 1;
+
+ // Insert before i.
+ this->shift(i, Size);
+ start(i) = a;
+ stop(i) = b;
+ value(i) = y;
+ return Size + 1;
+}
+
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMapImpl::BranchNode ---//
+//===----------------------------------------------------------------------===//
+//
+// A branch node stores references to 1--N subtrees all of the same height.
+//
+// The key array in a branch node holds the rightmost stop key of each subtree.
+// It is redundant to store the last stop key since it can be found in the
+// parent node, but doing so makes tree balancing a lot simpler.
+//
+// It is unusual for a branch node to only have one subtree, but it can happen
+// in the root node if it is smaller than the normal nodes.
+//
+// When all of the leaf nodes from all the subtrees are concatenated, they must
+// satisfy the same constraints as a single leaf node. They must be sorted,
+// sane, and fully coalesced.
+//
+//===----------------------------------------------------------------------===//
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+class BranchNode : public NodeBase<NodeRef, KeyT, N> {
+public:
+ const KeyT &stop(unsigned i) const { return this->second[i]; }
+ const NodeRef &subtree(unsigned i) const { return this->first[i]; }
+
+ KeyT &stop(unsigned i) { return this->second[i]; }
+ NodeRef &subtree(unsigned i) { return this->first[i]; }
+
+ /// findFrom - Find the first subtree after i that may contain x.
+ /// @param i Starting index for the search.
+ /// @param Size Number of elements in node.
+ /// @param x Key to search for.
+ /// @return First index with !stopLess(key[i], x), or size.
+ /// This is the first subtree that can possibly contain x.
+ unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
+ assert(i <= Size && Size <= N && "Bad indices");
+ assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
+ "Index to findFrom is past the needed point");
+ while (i != Size && Traits::stopLess(stop(i), x)) ++i;
+ return i;
+ }
+
+ /// safeFind - Find a subtree that is known to exist. This is the same as
+ /// findFrom except is it assumed that x is in range.
+ /// @param i Starting index for the search.
+ /// @param x Key to search for.
+ /// @return First index with !stopLess(key[i], x), never size.
+ /// This is the first subtree that can possibly contain x.
+ unsigned safeFind(unsigned i, KeyT x) const {
+ assert(i < N && "Bad index");
+ assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
+ "Index is past the needed point");
+ while (Traits::stopLess(stop(i), x)) ++i;
+ assert(i < N && "Unsafe intervals");
+ return i;
+ }
+
+ /// safeLookup - Get the subtree containing x, Assuming that x is in range.
+ /// @param x Key to search for.
+ /// @return Subtree containing x
+ NodeRef safeLookup(KeyT x) const {
+ return subtree(safeFind(0, x));
+ }
+
+ /// insert - Insert a new (subtree, stop) pair.
+ /// @param i Insert position, following entries will be shifted.
+ /// @param Size Number of elements in node.
+ /// @param Node Subtree to insert.
+ /// @param Stop Last key in subtree.
+ void insert(unsigned i, unsigned Size, NodeRef Node, KeyT Stop) {
+ assert(Size < N && "branch node overflow");
+ assert(i <= Size && "Bad insert position");
+ this->shift(i, Size);
+ subtree(i) = Node;
+ stop(i) = Stop;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMapImpl::Path ---//
+//===----------------------------------------------------------------------===//
+//
+// A Path is used by iterators to represent a position in a B+-tree, and the
+// path to get there from the root.
+//
+// The Path class also contains the tree navigation code that doesn't have to
+// be templatized.
+//
+//===----------------------------------------------------------------------===//
+
+class Path {
+ /// Entry - Each step in the path is a node pointer and an offset into that
+ /// node.
+ struct Entry {
+ void *node;
+ unsigned size;
+ unsigned offset;
+
+ Entry(void *Node, unsigned Size, unsigned Offset)
+ : node(Node), size(Size), offset(Offset) {}
+
+ Entry(NodeRef Node, unsigned Offset)
+ : node(&Node.subtree(0)), size(Node.size()), offset(Offset) {}
+
+ NodeRef &subtree(unsigned i) const {
+ return reinterpret_cast<NodeRef*>(node)[i];
+ }
+ };
+
+ /// path - The path entries, path[0] is the root node, path.back() is a leaf.
+ SmallVector<Entry, 4> path;
+
+public:
+ // Node accessors.
+ template <typename NodeT> NodeT &node(unsigned Level) const {
+ return *reinterpret_cast<NodeT*>(path[Level].node);
+ }
+ unsigned size(unsigned Level) const { return path[Level].size; }
+ unsigned offset(unsigned Level) const { return path[Level].offset; }
+ unsigned &offset(unsigned Level) { return path[Level].offset; }
+
+ // Leaf accessors.
+ template <typename NodeT> NodeT &leaf() const {
+ return *reinterpret_cast<NodeT*>(path.back().node);
+ }
+ unsigned leafSize() const { return path.back().size; }
+ unsigned leafOffset() const { return path.back().offset; }
+ unsigned &leafOffset() { return path.back().offset; }
+
+ /// valid - Return true if path is at a valid node, not at end().
+ bool valid() const {
+ return !path.empty() && path.front().offset < path.front().size;
+ }
+
+ /// height - Return the height of the tree corresponding to this path.
+ /// This matches map->height in a full path.
+ unsigned height() const { return path.size() - 1; }
+
+ /// subtree - Get the subtree referenced from Level. When the path is
+ /// consistent, node(Level + 1) == subtree(Level).
+ /// @param Level 0..height-1. The leaves have no subtrees.
+ NodeRef &subtree(unsigned Level) const {
+ return path[Level].subtree(path[Level].offset);
+ }
+
+ /// reset - Reset cached information about node(Level) from subtree(Level -1).
+ /// @param Level 1..height. THe node to update after parent node changed.
+ void reset(unsigned Level) {
+ path[Level] = Entry(subtree(Level - 1), offset(Level));
+ }
+
+ /// push - Add entry to path.
+ /// @param Node Node to add, should be subtree(path.size()-1).
+ /// @param Offset Offset into Node.
+ void push(NodeRef Node, unsigned Offset) {
+ path.push_back(Entry(Node, Offset));
+ }
+
+ /// pop - Remove the last path entry.
+ void pop() {
+ path.pop_back();
+ }
+
+ /// setSize - Set the size of a node both in the path and in the tree.
+ /// @param Level 0..height. Note that setting the root size won't change
+ /// map->rootSize.
+ /// @param Size New node size.
+ void setSize(unsigned Level, unsigned Size) {
+ path[Level].size = Size;
+ if (Level)
+ subtree(Level - 1).setSize(Size);
+ }
+
+ /// setRoot - Clear the path and set a new root node.
+ /// @param Node New root node.
+ /// @param Size New root size.
+ /// @param Offset Offset into root node.
+ void setRoot(void *Node, unsigned Size, unsigned Offset) {
+ path.clear();
+ path.push_back(Entry(Node, Size, Offset));
+ }
+
+ /// replaceRoot - Replace the current root node with two new entries after the
+ /// tree height has increased.
+ /// @param Root The new root node.
+ /// @param Size Number of entries in the new root.
+ /// @param Offsets Offsets into the root and first branch nodes.
+ void replaceRoot(void *Root, unsigned Size, IdxPair Offsets);
+
+ /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
+ /// @param Level Get the sibling to node(Level).
+ /// @return Left sibling, or NodeRef().
+ NodeRef getLeftSibling(unsigned Level) const;
+
+ /// moveLeft - Move path to the left sibling at Level. Leave nodes below Level
+ /// unaltered.
+ /// @param Level Move node(Level).
+ void moveLeft(unsigned Level);
+
+ /// fillLeft - Grow path to Height by taking leftmost branches.
+ /// @param Height The target height.
+ void fillLeft(unsigned Height) {
+ while (height() < Height)
+ push(subtree(height()), 0);
+ }
+
+ /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
+ /// @param Level Get the sinbling to node(Level).
+ /// @return Left sibling, or NodeRef().
+ NodeRef getRightSibling(unsigned Level) const;
+
+ /// moveRight - Move path to the left sibling at Level. Leave nodes below
+ /// Level unaltered.
+ /// @param Level Move node(Level).
+ void moveRight(unsigned Level);
+
+ /// atBegin - Return true if path is at begin().
+ bool atBegin() const {
+ for (unsigned i = 0, e = path.size(); i != e; ++i)
+ if (path[i].offset != 0)
+ return false;
+ return true;
+ }
+
+ /// atLastEntry - Return true if the path is at the last entry of the node at
+ /// Level.
+ /// @param Level Node to examine.
+ bool atLastEntry(unsigned Level) const {
+ return path[Level].offset == path[Level].size - 1;
+ }
+
+ /// legalizeForInsert - Prepare the path for an insertion at Level. When the
+ /// path is at end(), node(Level) may not be a legal node. legalizeForInsert
+ /// ensures that node(Level) is real by moving back to the last node at Level,
+ /// and setting offset(Level) to size(Level) if required.
+ /// @param Level The level where an insertion is about to take place.
+ void legalizeForInsert(unsigned Level) {
+ if (valid())
+ return;
+ moveLeft(Level);
+ ++path[Level].offset;
+ }
+};
+
+} // namespace IntervalMapImpl
+
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMap ----//
+//===----------------------------------------------------------------------===//
+
+template <typename KeyT, typename ValT,
+ unsigned N = IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
+ typename Traits = IntervalMapInfo<KeyT> >
+class IntervalMap {
+ typedef IntervalMapImpl::NodeSizer<KeyT, ValT> Sizer;
+ typedef IntervalMapImpl::LeafNode<KeyT, ValT, Sizer::LeafSize, Traits> Leaf;
+ typedef IntervalMapImpl::BranchNode<KeyT, ValT, Sizer::BranchSize, Traits>
+ Branch;
+ typedef IntervalMapImpl::LeafNode<KeyT, ValT, N, Traits> RootLeaf;
+ typedef IntervalMapImpl::IdxPair IdxPair;
+
+ // The RootLeaf capacity is given as a template parameter. We must compute the
+ // corresponding RootBranch capacity.
+ enum {
+ DesiredRootBranchCap = (sizeof(RootLeaf) - sizeof(KeyT)) /
+ (sizeof(KeyT) + sizeof(IntervalMapImpl::NodeRef)),
+ RootBranchCap = DesiredRootBranchCap ? DesiredRootBranchCap : 1
+ };
+
+ typedef IntervalMapImpl::BranchNode<KeyT, ValT, RootBranchCap, Traits>
+ RootBranch;
+
+ // When branched, we store a global start key as well as the branch node.
+ struct RootBranchData {
+ KeyT start;
+ RootBranch node;
+ };
+
+ enum {
+ RootDataSize = sizeof(RootBranchData) > sizeof(RootLeaf) ?
+ sizeof(RootBranchData) : sizeof(RootLeaf)
+ };
+
+public:
+ typedef typename Sizer::Allocator Allocator;
+ typedef KeyT KeyType;
+ typedef ValT ValueType;
+ typedef Traits KeyTraits;
+
+private:
+ // The root data is either a RootLeaf or a RootBranchData instance.
+ // We can't put them in a union since C++03 doesn't allow non-trivial
+ // constructors in unions.
+ // Instead, we use a char array with pointer alignment. The alignment is
+ // ensured by the allocator member in the class, but still verified in the
+ // constructor. We don't support keys or values that are more aligned than a
+ // pointer.
+ char data[RootDataSize];
+
+ // Tree height.
+ // 0: Leaves in root.
+ // 1: Root points to leaf.
+ // 2: root->branch->leaf ...
+ unsigned height;
+
+ // Number of entries in the root node.
+ unsigned rootSize;
+
+ // Allocator used for creating external nodes.
+ Allocator &allocator;
+
+ /// dataAs - Represent data as a node type without breaking aliasing rules.
+ template <typename T>
+ T &dataAs() const {
+ union {
+ const char *d;
+ T *t;
+ } u;
+ u.d = data;
+ return *u.t;
+ }
+
+ const RootLeaf &rootLeaf() const {
+ assert(!branched() && "Cannot acces leaf data in branched root");
+ return dataAs<RootLeaf>();
+ }
+ RootLeaf &rootLeaf() {
+ assert(!branched() && "Cannot acces leaf data in branched root");
+ return dataAs<RootLeaf>();
+ }
+ RootBranchData &rootBranchData() const {
+ assert(branched() && "Cannot access branch data in non-branched root");
+ return dataAs<RootBranchData>();
+ }
+ RootBranchData &rootBranchData() {
+ assert(branched() && "Cannot access branch data in non-branched root");
+ return dataAs<RootBranchData>();
+ }
+ const RootBranch &rootBranch() const { return rootBranchData().node; }
+ RootBranch &rootBranch() { return rootBranchData().node; }
+ KeyT rootBranchStart() const { return rootBranchData().start; }
+ KeyT &rootBranchStart() { return rootBranchData().start; }
+
+ template <typename NodeT> NodeT *newNode() {
+ return new(allocator.template Allocate<NodeT>()) NodeT();
+ }
+
+ template <typename NodeT> void deleteNode(NodeT *P) {
+ P->~NodeT();
+ allocator.Deallocate(P);
+ }
+
+ IdxPair branchRoot(unsigned Position);
+ IdxPair splitRoot(unsigned Position);
+
+ void switchRootToBranch() {
+ rootLeaf().~RootLeaf();
+ height = 1;
+ new (&rootBranchData()) RootBranchData();
+ }
+
+ void switchRootToLeaf() {
+ rootBranchData().~RootBranchData();
+ height = 0;
+ new(&rootLeaf()) RootLeaf();
+ }
+
+ bool branched() const { return height > 0; }
+
+ ValT treeSafeLookup(KeyT x, ValT NotFound) const;
+ void visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef,
+ unsigned Level));
+ void deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level);
+
+public:
+ explicit IntervalMap(Allocator &a) : height(0), rootSize(0), allocator(a) {
+ assert((uintptr_t(data) & (alignOf<RootLeaf>() - 1)) == 0 &&
+ "Insufficient alignment");
+ new(&rootLeaf()) RootLeaf();
+ }
+
+ ~IntervalMap() {
+ clear();
+ rootLeaf().~RootLeaf();
+ }
+
+ /// empty - Return true when no intervals are mapped.
+ bool empty() const {
+ return rootSize == 0;
+ }
+
+ /// start - Return the smallest mapped key in a non-empty map.
+ KeyT start() const {
+ assert(!empty() && "Empty IntervalMap has no start");
+ return !branched() ? rootLeaf().start(0) : rootBranchStart();
+ }
+
+ /// stop - Return the largest mapped key in a non-empty map.
+ KeyT stop() const {
+ assert(!empty() && "Empty IntervalMap has no stop");
+ return !branched() ? rootLeaf().stop(rootSize - 1) :
+ rootBranch().stop(rootSize - 1);
+ }
+
+ /// lookup - Return the mapped value at x or NotFound.
+ ValT lookup(KeyT x, ValT NotFound = ValT()) const {
+ if (empty() || Traits::startLess(x, start()) || Traits::stopLess(stop(), x))
+ return NotFound;
+ return branched() ? treeSafeLookup(x, NotFound) :
+ rootLeaf().safeLookup(x, NotFound);
+ }
+
+ /// insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
+ /// It is assumed that no key in the interval is mapped to another value, but
+ /// overlapping intervals already mapped to y will be coalesced.
+ void insert(KeyT a, KeyT b, ValT y) {
+ if (branched() || rootSize == RootLeaf::Capacity)
+ return find(a).insert(a, b, y);
+
+ // Easy insert into root leaf.
+ unsigned p = rootLeaf().findFrom(0, rootSize, a);
+ rootSize = rootLeaf().insertFrom(p, rootSize, a, b, y);
+ }
+
+ /// clear - Remove all entries.
+ void clear();
+
+ class const_iterator;
+ class iterator;
+ friend class const_iterator;
+ friend class iterator;
+
+ const_iterator begin() const {
+ const_iterator I(*this);
+ I.goToBegin();
+ return I;
+ }
+
+ iterator begin() {
+ iterator I(*this);
+ I.goToBegin();
+ return I;
+ }
+
+ const_iterator end() const {
+ const_iterator I(*this);
+ I.goToEnd();
+ return I;
+ }
+
+ iterator end() {
+ iterator I(*this);
+ I.goToEnd();
+ return I;
+ }
+
+ /// find - Return an iterator pointing to the first interval ending at or
+ /// after x, or end().
+ const_iterator find(KeyT x) const {
+ const_iterator I(*this);
+ I.find(x);
+ return I;
+ }
+
+ iterator find(KeyT x) {
+ iterator I(*this);
+ I.find(x);
+ return I;
+ }
+};
+
+/// treeSafeLookup - Return the mapped value at x or NotFound, assuming a
+/// branched root.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+ValT IntervalMap<KeyT, ValT, N, Traits>::
+treeSafeLookup(KeyT x, ValT NotFound) const {
+ assert(branched() && "treeLookup assumes a branched root");
+
+ IntervalMapImpl::NodeRef NR = rootBranch().safeLookup(x);
+ for (unsigned h = height-1; h; --h)
+ NR = NR.get<Branch>().safeLookup(x);
+ return NR.get<Leaf>().safeLookup(x, NotFound);
+}
+
+
+// branchRoot - Switch from a leaf root to a branched root.
+// Return the new (root offset, node offset) corresponding to Position.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
+branchRoot(unsigned Position) {
+ using namespace IntervalMapImpl;
+ // How many external leaf nodes to hold RootLeaf+1?
+ const unsigned Nodes = RootLeaf::Capacity / Leaf::Capacity + 1;
+
+ // Compute element distribution among new nodes.
+ unsigned size[Nodes];
+ IdxPair NewOffset(0, Position);
+
+ // Is is very common for the root node to be smaller than external nodes.
+ if (Nodes == 1)
+ size[0] = rootSize;
+ else
+ NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, NULL, size,
+ Position, true);
+
+ // Allocate new nodes.
+ unsigned pos = 0;
+ NodeRef node[Nodes];
+ for (unsigned n = 0; n != Nodes; ++n) {
+ Leaf *L = newNode<Leaf>();
+ L->copy(rootLeaf(), pos, 0, size[n]);
+ node[n] = NodeRef(L, size[n]);
+ pos += size[n];
+ }
+
+ // Destroy the old leaf node, construct branch node instead.
+ switchRootToBranch();
+ for (unsigned n = 0; n != Nodes; ++n) {
+ rootBranch().stop(n) = node[n].template get<Leaf>().stop(size[n]-1);
+ rootBranch().subtree(n) = node[n];
+ }
+ rootBranchStart() = node[0].template get<Leaf>().start(0);
+ rootSize = Nodes;
+ return NewOffset;
+}
+
+// splitRoot - Split the current BranchRoot into multiple Branch nodes.
+// Return the new (root offset, node offset) corresponding to Position.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
+splitRoot(unsigned Position) {
+ using namespace IntervalMapImpl;
+ // How many external leaf nodes to hold RootBranch+1?
+ const unsigned Nodes = RootBranch::Capacity / Branch::Capacity + 1;
+
+ // Compute element distribution among new nodes.
+ unsigned Size[Nodes];
+ IdxPair NewOffset(0, Position);
+
+ // Is is very common for the root node to be smaller than external nodes.
+ if (Nodes == 1)
+ Size[0] = rootSize;
+ else
+ NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, NULL, Size,
+ Position, true);
+
+ // Allocate new nodes.
+ unsigned Pos = 0;
+ NodeRef Node[Nodes];
+ for (unsigned n = 0; n != Nodes; ++n) {
+ Branch *B = newNode<Branch>();
+ B->copy(rootBranch(), Pos, 0, Size[n]);
+ Node[n] = NodeRef(B, Size[n]);
+ Pos += Size[n];
+ }
+
+ for (unsigned n = 0; n != Nodes; ++n) {
+ rootBranch().stop(n) = Node[n].template get<Branch>().stop(Size[n]-1);
+ rootBranch().subtree(n) = Node[n];
+ }
+ rootSize = Nodes;
+ ++height;
+ return NewOffset;
+}
+
+/// visitNodes - Visit each external node.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef, unsigned Height)) {
+ if (!branched())
+ return;
+ SmallVector<IntervalMapImpl::NodeRef, 4> Refs, NextRefs;
+
+ // Collect level 0 nodes from the root.
+ for (unsigned i = 0; i != rootSize; ++i)
+ Refs.push_back(rootBranch().subtree(i));
+
+ // Visit all branch nodes.
+ for (unsigned h = height - 1; h; --h) {
+ for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
+ for (unsigned j = 0, s = Refs[i].size(); j != s; ++j)
+ NextRefs.push_back(Refs[i].subtree(j));
+ (this->*f)(Refs[i], h);
+ }
+ Refs.clear();
+ Refs.swap(NextRefs);
+ }
+
+ // Visit all leaf nodes.
+ for (unsigned i = 0, e = Refs.size(); i != e; ++i)
+ (this->*f)(Refs[i], 0);
+}
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level) {
+ if (Level)
+ deleteNode(&Node.get<Branch>());
+ else
+ deleteNode(&Node.get<Leaf>());
+}
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+clear() {
+ if (branched()) {
+ visitNodes(&IntervalMap::deleteNode);
+ switchRootToLeaf();
+ }
+ rootSize = 0;
+}
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMap::const_iterator ----//
+//===----------------------------------------------------------------------===//
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+class IntervalMap<KeyT, ValT, N, Traits>::const_iterator :
+ public std::iterator<std::bidirectional_iterator_tag, ValT> {
+protected:
+ friend class IntervalMap;
+
+ // The map referred to.
+ IntervalMap *map;
+
+ // We store a full path from the root to the current position.
+ // The path may be partially filled, but never between iterator calls.
+ IntervalMapImpl::Path path;
+
+ explicit const_iterator(const IntervalMap &map) :
+ map(const_cast<IntervalMap*>(&map)) {}
+
+ bool branched() const {
+ assert(map && "Invalid iterator");
+ return map->branched();
+ }
+
+ void setRoot(unsigned Offset) {
+ if (branched())
+ path.setRoot(&map->rootBranch(), map->rootSize, Offset);
+ else
+ path.setRoot(&map->rootLeaf(), map->rootSize, Offset);
+ }
+
+ void pathFillFind(KeyT x);
+ void treeFind(KeyT x);
+ void treeAdvanceTo(KeyT x);
+
+ /// unsafeStart - Writable access to start() for iterator.
+ KeyT &unsafeStart() const {
+ assert(valid() && "Cannot access invalid iterator");
+ return branched() ? path.leaf<Leaf>().start(path.leafOffset()) :
+ path.leaf<RootLeaf>().start(path.leafOffset());
+ }
+
+ /// unsafeStop - Writable access to stop() for iterator.
+ KeyT &unsafeStop() const {
+ assert(valid() && "Cannot access invalid iterator");
+ return branched() ? path.leaf<Leaf>().stop(path.leafOffset()) :
+ path.leaf<RootLeaf>().stop(path.leafOffset());
+ }
+
+ /// unsafeValue - Writable access to value() for iterator.
+ ValT &unsafeValue() const {
+ assert(valid() && "Cannot access invalid iterator");
+ return branched() ? path.leaf<Leaf>().value(path.leafOffset()) :
+ path.leaf<RootLeaf>().value(path.leafOffset());
+ }
+
+public:
+ /// const_iterator - Create an iterator that isn't pointing anywhere.
+ const_iterator() : map(0) {}
+
+ /// setMap - Change the map iterated over. This call must be followed by a
+ /// call to goToBegin(), goToEnd(), or find()
+ void setMap(const IntervalMap &m) { map = const_cast<IntervalMap*>(&m); }
+
+ /// valid - Return true if the current position is valid, false for end().
+ bool valid() const { return path.valid(); }
+
+ /// atBegin - Return true if the current position is the first map entry.
+ bool atBegin() const { return path.atBegin(); }
+
+ /// start - Return the beginning of the current interval.
+ const KeyT &start() const { return unsafeStart(); }
+
+ /// stop - Return the end of the current interval.
+ const KeyT &stop() const { return unsafeStop(); }
+
+ /// value - Return the mapped value at the current interval.
+ const ValT &value() const { return unsafeValue(); }
+
+ const ValT &operator*() const { return value(); }
+
+ bool operator==(const const_iterator &RHS) const {
+ assert(map == RHS.map && "Cannot compare iterators from different maps");
+ if (!valid())
+ return !RHS.valid();
+ if (path.leafOffset() != RHS.path.leafOffset())
+ return false;
+ return &path.template leaf<Leaf>() == &RHS.path.template leaf<Leaf>();
+ }
+
+ bool operator!=(const const_iterator &RHS) const {
+ return !operator==(RHS);
+ }
+
+ /// goToBegin - Move to the first interval in map.
+ void goToBegin() {
+ setRoot(0);
+ if (branched())
+ path.fillLeft(map->height);
+ }
+
+ /// goToEnd - Move beyond the last interval in map.
+ void goToEnd() {
+ setRoot(map->rootSize);
+ }
+
+ /// preincrement - move to the next interval.
+ const_iterator &operator++() {
+ assert(valid() && "Cannot increment end()");
+ if (++path.leafOffset() == path.leafSize() && branched())
+ path.moveRight(map->height);
+ return *this;
+ }
+
+ /// postincrement - Dont do that!
+ const_iterator operator++(int) {
+ const_iterator tmp = *this;
+ operator++();
+ return tmp;
+ }
+
+ /// predecrement - move to the previous interval.
+ const_iterator &operator--() {
+ if (path.leafOffset() && (valid() || !branched()))
+ --path.leafOffset();
+ else
+ path.moveLeft(map->height);
+ return *this;
+ }
+
+ /// postdecrement - Dont do that!
+ const_iterator operator--(int) {
+ const_iterator tmp = *this;
+ operator--();
+ return tmp;
+ }
+
+ /// find - Move to the first interval with stop >= x, or end().
+ /// This is a full search from the root, the current position is ignored.
+ void find(KeyT x) {
+ if (branched())
+ treeFind(x);
+ else
+ setRoot(map->rootLeaf().findFrom(0, map->rootSize, x));
+ }
+
+ /// advanceTo - Move to the first interval with stop >= x, or end().
+ /// The search is started from the current position, and no earlier positions
+ /// can be found. This is much faster than find() for small moves.
+ void advanceTo(KeyT x) {
+ if (!valid())
+ return;
+ if (branched())
+ treeAdvanceTo(x);
+ else
+ path.leafOffset() =
+ map->rootLeaf().findFrom(path.leafOffset(), map->rootSize, x);
+ }
+
+};
+
+/// pathFillFind - Complete path by searching for x.
+/// @param x Key to search for.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+const_iterator::pathFillFind(KeyT x) {
+ IntervalMapImpl::NodeRef NR = path.subtree(path.height());
+ for (unsigned i = map->height - path.height() - 1; i; --i) {
+ unsigned p = NR.get<Branch>().safeFind(0, x);
+ path.push(NR, p);
+ NR = NR.subtree(p);
+ }
+ path.push(NR, NR.get<Leaf>().safeFind(0, x));
+}
+
+/// treeFind - Find in a branched tree.
+/// @param x Key to search for.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+const_iterator::treeFind(KeyT x) {
+ setRoot(map->rootBranch().findFrom(0, map->rootSize, x));
+ if (valid())
+ pathFillFind(x);
+}
+
+/// treeAdvanceTo - Find position after the current one.
+/// @param x Key to search for.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+const_iterator::treeAdvanceTo(KeyT x) {
+ // Can we stay on the same leaf node?
+ if (!Traits::stopLess(path.leaf<Leaf>().stop(path.leafSize() - 1), x)) {
+ path.leafOffset() = path.leaf<Leaf>().safeFind(path.leafOffset(), x);
+ return;
+ }
+
+ // Drop the current leaf.
+ path.pop();
+
+ // Search towards the root for a usable subtree.
+ if (path.height()) {
+ for (unsigned l = path.height() - 1; l; --l) {
+ if (!Traits::stopLess(path.node<Branch>(l).stop(path.offset(l)), x)) {
+ // The branch node at l+1 is usable
+ path.offset(l + 1) =
+ path.node<Branch>(l + 1).safeFind(path.offset(l + 1), x);
+ return pathFillFind(x);
+ }
+ path.pop();
+ }
+ // Is the level-1 Branch usable?
+ if (!Traits::stopLess(map->rootBranch().stop(path.offset(0)), x)) {
+ path.offset(1) = path.node<Branch>(1).safeFind(path.offset(1), x);
+ return pathFillFind(x);
+ }
+ }
+
+ // We reached the root.
+ setRoot(map->rootBranch().findFrom(path.offset(0), map->rootSize, x));
+ if (valid())
+ pathFillFind(x);
+}
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMap::iterator ----//
+//===----------------------------------------------------------------------===//
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+class IntervalMap<KeyT, ValT, N, Traits>::iterator : public const_iterator {
+ friend class IntervalMap;
+ typedef IntervalMapImpl::IdxPair IdxPair;
+
+ explicit iterator(IntervalMap &map) : const_iterator(map) {}
+
+ void setNodeStop(unsigned Level, KeyT Stop);
+ bool insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop);
+ template <typename NodeT> bool overflow(unsigned Level);
+ void treeInsert(KeyT a, KeyT b, ValT y);
+ void eraseNode(unsigned Level);
+ void treeErase(bool UpdateRoot = true);
+ bool canCoalesceLeft(KeyT Start, ValT x);
+ bool canCoalesceRight(KeyT Stop, ValT x);
+
+public:
+ /// iterator - Create null iterator.
+ iterator() {}
+
+ /// setStart - Move the start of the current interval.
+ /// This may cause coalescing with the previous interval.
+ /// @param a New start key, must not overlap the previous interval.
+ void setStart(KeyT a);
+
+ /// setStop - Move the end of the current interval.
+ /// This may cause coalescing with the following interval.
+ /// @param b New stop key, must not overlap the following interval.
+ void setStop(KeyT b);
+
+ /// setValue - Change the mapped value of the current interval.
+ /// This may cause coalescing with the previous and following intervals.
+ /// @param x New value.
+ void setValue(ValT x);
+
+ /// setStartUnchecked - Move the start of the current interval without
+ /// checking for coalescing or overlaps.
+ /// This should only be used when it is known that coalescing is not required.
+ /// @param a New start key.
+ void setStartUnchecked(KeyT a) { this->unsafeStart() = a; }
+
+ /// setStopUnchecked - Move the end of the current interval without checking
+ /// for coalescing or overlaps.
+ /// This should only be used when it is known that coalescing is not required.
+ /// @param b New stop key.
+ void setStopUnchecked(KeyT b) {
+ this->unsafeStop() = b;
+ // Update keys in branch nodes as well.
+ if (this->path.atLastEntry(this->path.height()))
+ setNodeStop(this->path.height(), b);
+ }
+
+ /// setValueUnchecked - Change the mapped value of the current interval
+ /// without checking for coalescing.
+ /// @param x New value.
+ void setValueUnchecked(ValT x) { this->unsafeValue() = x; }
+
+ /// insert - Insert mapping [a;b] -> y before the current position.
+ void insert(KeyT a, KeyT b, ValT y);
+
+ /// erase - Erase the current interval.
+ void erase();
+
+ iterator &operator++() {
+ const_iterator::operator++();
+ return *this;
+ }
+
+ iterator operator++(int) {
+ iterator tmp = *this;
+ operator++();
+ return tmp;
+ }
+
+ iterator &operator--() {
+ const_iterator::operator--();
+ return *this;
+ }
+
+ iterator operator--(int) {
+ iterator tmp = *this;
+ operator--();
+ return tmp;
+ }
+
+};
+
+/// canCoalesceLeft - Can the current interval coalesce to the left after
+/// changing start or value?
+/// @param Start New start of current interval.
+/// @param Value New value for current interval.
+/// @return True when updating the current interval would enable coalescing.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+bool IntervalMap<KeyT, ValT, N, Traits>::
+iterator::canCoalesceLeft(KeyT Start, ValT Value) {
+ using namespace IntervalMapImpl;
+ Path &P = this->path;
+ if (!this->branched()) {
+ unsigned i = P.leafOffset();
+ RootLeaf &Node = P.leaf<RootLeaf>();
+ return i && Node.value(i-1) == Value &&
+ Traits::adjacent(Node.stop(i-1), Start);
+ }
+ // Branched.
+ if (unsigned i = P.leafOffset()) {
+ Leaf &Node = P.leaf<Leaf>();
+ return Node.value(i-1) == Value && Traits::adjacent(Node.stop(i-1), Start);
+ } else if (NodeRef NR = P.getLeftSibling(P.height())) {
+ unsigned i = NR.size() - 1;
+ Leaf &Node = NR.get<Leaf>();
+ return Node.value(i) == Value && Traits::adjacent(Node.stop(i), Start);
+ }
+ return false;
+}
+
+/// canCoalesceRight - Can the current interval coalesce to the right after
+/// changing stop or value?
+/// @param Stop New stop of current interval.
+/// @param Value New value for current interval.
+/// @return True when updating the current interval would enable coalescing.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+bool IntervalMap<KeyT, ValT, N, Traits>::
+iterator::canCoalesceRight(KeyT Stop, ValT Value) {
+ using namespace IntervalMapImpl;
+ Path &P = this->path;
+ unsigned i = P.leafOffset() + 1;
+ if (!this->branched()) {
+ if (i >= P.leafSize())
+ return false;
+ RootLeaf &Node = P.leaf<RootLeaf>();
+ return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i));
+ }
+ // Branched.
+ if (i < P.leafSize()) {
+ Leaf &Node = P.leaf<Leaf>();
+ return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i));
+ } else if (NodeRef NR = P.getRightSibling(P.height())) {
+ Leaf &Node = NR.get<Leaf>();
+ return Node.value(0) == Value && Traits::adjacent(Stop, Node.start(0));
+ }
+ return false;
+}
+
+/// setNodeStop - Update the stop key of the current node at level and above.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::setNodeStop(unsigned Level, KeyT Stop) {
+ // There are no references to the root node, so nothing to update.
+ if (!Level)
+ return;
+ IntervalMapImpl::Path &P = this->path;
+ // Update nodes pointing to the current node.
+ while (--Level) {
+ P.node<Branch>(Level).stop(P.offset(Level)) = Stop;
+ if (!P.atLastEntry(Level))
+ return;
+ }
+ // Update root separately since it has a different layout.
+ P.node<RootBranch>(Level).stop(P.offset(Level)) = Stop;
+}
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::setStart(KeyT a) {
+ assert(Traits::stopLess(a, this->stop()) && "Cannot move start beyond stop");
+ KeyT &CurStart = this->unsafeStart();
+ if (!Traits::startLess(a, CurStart) || !canCoalesceLeft(a, this->value())) {
+ CurStart = a;
+ return;
+ }
+ // Coalesce with the interval to the left.
+ --*this;
+ a = this->start();
+ erase();
+ setStartUnchecked(a);
+}
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::setStop(KeyT b) {
+ assert(Traits::stopLess(this->start(), b) && "Cannot move stop beyond start");
+ if (Traits::startLess(b, this->stop()) ||
+ !canCoalesceRight(b, this->value())) {
+ setStopUnchecked(b);
+ return;
+ }
+ // Coalesce with interval to the right.
+ KeyT a = this->start();
+ erase();
+ setStartUnchecked(a);
+}
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::setValue(ValT x) {
+ setValueUnchecked(x);
+ if (canCoalesceRight(this->stop(), x)) {
+ KeyT a = this->start();
+ erase();
+ setStartUnchecked(a);
+ }
+ if (canCoalesceLeft(this->start(), x)) {
+ --*this;
+ KeyT a = this->start();
+ erase();
+ setStartUnchecked(a);
+ }
+}
+
+/// insertNode - insert a node before the current path at level.
+/// Leave the current path pointing at the new node.
+/// @param Level path index of the node to be inserted.
+/// @param Node The node to be inserted.
+/// @param Stop The last index in the new node.
+/// @return True if the tree height was increased.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+bool IntervalMap<KeyT, ValT, N, Traits>::
+iterator::insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop) {
+ assert(Level && "Cannot insert next to the root");
+ bool SplitRoot = false;
+ IntervalMap &IM = *this->map;
+ IntervalMapImpl::Path &P = this->path;
+
+ if (Level == 1) {
+ // Insert into the root branch node.
+ if (IM.rootSize < RootBranch::Capacity) {
+ IM.rootBranch().insert(P.offset(0), IM.rootSize, Node, Stop);
+ P.setSize(0, ++IM.rootSize);
+ P.reset(Level);
+ return SplitRoot;
+ }
+
+ // We need to split the root while keeping our position.
+ SplitRoot = true;
+ IdxPair Offset = IM.splitRoot(P.offset(0));
+ P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
+
+ // Fall through to insert at the new higher level.
+ ++Level;
+ }
+
+ // When inserting before end(), make sure we have a valid path.
+ P.legalizeForInsert(--Level);
+
+ // Insert into the branch node at Level-1.
+ if (P.size(Level) == Branch::Capacity) {
+ // Branch node is full, handle handle the overflow.
+ assert(!SplitRoot && "Cannot overflow after splitting the root");
+ SplitRoot = overflow<Branch>(Level);
+ Level += SplitRoot;
+ }
+ P.node<Branch>(Level).insert(P.offset(Level), P.size(Level), Node, Stop);
+ P.setSize(Level, P.size(Level) + 1);
+ if (P.atLastEntry(Level))
+ setNodeStop(Level, Stop);
+ P.reset(Level + 1);
+ return SplitRoot;
+}
+
+// insert
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::insert(KeyT a, KeyT b, ValT y) {
+ if (this->branched())
+ return treeInsert(a, b, y);
+ IntervalMap &IM = *this->map;
+ IntervalMapImpl::Path &P = this->path;
+
+ // Try simple root leaf insert.
+ unsigned Size = IM.rootLeaf().insertFrom(P.leafOffset(), IM.rootSize, a, b, y);
+
+ // Was the root node insert successful?
+ if (Size <= RootLeaf::Capacity) {
+ P.setSize(0, IM.rootSize = Size);
+ return;
+ }
+
+ // Root leaf node is full, we must branch.
+ IdxPair Offset = IM.branchRoot(P.leafOffset());
+ P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
+
+ // Now it fits in the new leaf.
+ treeInsert(a, b, y);
+}
+
+
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::treeInsert(KeyT a, KeyT b, ValT y) {
+ using namespace IntervalMapImpl;
+ Path &P = this->path;
+
+ if (!P.valid())
+ P.legalizeForInsert(this->map->height);
+
+ // Check if this insertion will extend the node to the left.
+ if (P.leafOffset() == 0 && Traits::startLess(a, P.leaf<Leaf>().start(0))) {
+ // Node is growing to the left, will it affect a left sibling node?
+ if (NodeRef Sib = P.getLeftSibling(P.height())) {
+ Leaf &SibLeaf = Sib.get<Leaf>();
+ unsigned SibOfs = Sib.size() - 1;
+ if (SibLeaf.value(SibOfs) == y &&
+ Traits::adjacent(SibLeaf.stop(SibOfs), a)) {
+ // This insertion will coalesce with the last entry in SibLeaf. We can
+ // handle it in two ways:
+ // 1. Extend SibLeaf.stop to b and be done, or
+ // 2. Extend a to SibLeaf, erase the SibLeaf entry and continue.
+ // We prefer 1., but need 2 when coalescing to the right as well.
+ Leaf &CurLeaf = P.leaf<Leaf>();
+ P.moveLeft(P.height());
+ if (Traits::stopLess(b, CurLeaf.start(0)) &&
+ (y != CurLeaf.value(0) || !Traits::adjacent(b, CurLeaf.start(0)))) {
+ // Easy, just extend SibLeaf and we're done.
+ setNodeStop(P.height(), SibLeaf.stop(SibOfs) = b);
+ return;
+ } else {
+ // We have both left and right coalescing. Erase the old SibLeaf entry
+ // and continue inserting the larger interval.
+ a = SibLeaf.start(SibOfs);
+ treeErase(/* UpdateRoot= */false);
+ }
+ }
+ } else {
+ // No left sibling means we are at begin(). Update cached bound.
+ this->map->rootBranchStart() = a;
+ }
+ }
+
+ // When we are inserting at the end of a leaf node, we must update stops.
+ unsigned Size = P.leafSize();
+ bool Grow = P.leafOffset() == Size;
+ Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), Size, a, b, y);
+
+ // Leaf insertion unsuccessful? Overflow and try again.
+ if (Size > Leaf::Capacity) {
+ overflow<Leaf>(P.height());
+ Grow = P.leafOffset() == P.leafSize();
+ Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), P.leafSize(), a, b, y);
+ assert(Size <= Leaf::Capacity && "overflow() didn't make room");
+ }
+
+ // Inserted, update offset and leaf size.
+ P.setSize(P.height(), Size);
+
+ // Insert was the last node entry, update stops.
+ if (Grow)
+ setNodeStop(P.height(), b);
+}
+
+/// erase - erase the current interval and move to the next position.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::erase() {
+ IntervalMap &IM = *this->map;
+ IntervalMapImpl::Path &P = this->path;
+ assert(P.valid() && "Cannot erase end()");
+ if (this->branched())
+ return treeErase();
+ IM.rootLeaf().erase(P.leafOffset(), IM.rootSize);
+ P.setSize(0, --IM.rootSize);
+}
+
+/// treeErase - erase() for a branched tree.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::treeErase(bool UpdateRoot) {
+ IntervalMap &IM = *this->map;
+ IntervalMapImpl::Path &P = this->path;
+ Leaf &Node = P.leaf<Leaf>();
+
+ // Nodes are not allowed to become empty.
+ if (P.leafSize() == 1) {
+ IM.deleteNode(&Node);
+ eraseNode(IM.height);
+ // Update rootBranchStart if we erased begin().
+ if (UpdateRoot && IM.branched() && P.valid() && P.atBegin())
+ IM.rootBranchStart() = P.leaf<Leaf>().start(0);
+ return;
+ }
+
+ // Erase current entry.
+ Node.erase(P.leafOffset(), P.leafSize());
+ unsigned NewSize = P.leafSize() - 1;
+ P.setSize(IM.height, NewSize);
+ // When we erase the last entry, update stop and move to a legal position.
+ if (P.leafOffset() == NewSize) {
+ setNodeStop(IM.height, Node.stop(NewSize - 1));
+ P.moveRight(IM.height);
+ } else if (UpdateRoot && P.atBegin())
+ IM.rootBranchStart() = P.leaf<Leaf>().start(0);
+}
+
+/// eraseNode - Erase the current node at Level from its parent and move path to
+/// the first entry of the next sibling node.
+/// The node must be deallocated by the caller.
+/// @param Level 1..height, the root node cannot be erased.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+void IntervalMap<KeyT, ValT, N, Traits>::
+iterator::eraseNode(unsigned Level) {
+ assert(Level && "Cannot erase root node");
+ IntervalMap &IM = *this->map;
+ IntervalMapImpl::Path &P = this->path;
+
+ if (--Level == 0) {
+ IM.rootBranch().erase(P.offset(0), IM.rootSize);
+ P.setSize(0, --IM.rootSize);
+ // If this cleared the root, switch to height=0.
+ if (IM.empty()) {
+ IM.switchRootToLeaf();
+ this->setRoot(0);
+ return;
+ }
+ } else {
+ // Remove node ref from branch node at Level.
+ Branch &Parent = P.node<Branch>(Level);
+ if (P.size(Level) == 1) {
+ // Branch node became empty, remove it recursively.
+ IM.deleteNode(&Parent);
+ eraseNode(Level);
+ } else {
+ // Branch node won't become empty.
+ Parent.erase(P.offset(Level), P.size(Level));
+ unsigned NewSize = P.size(Level) - 1;
+ P.setSize(Level, NewSize);
+ // If we removed the last branch, update stop and move to a legal pos.
+ if (P.offset(Level) == NewSize) {
+ setNodeStop(Level, Parent.stop(NewSize - 1));
+ P.moveRight(Level);
+ }
+ }
+ }
+ // Update path cache for the new right sibling position.
+ if (P.valid()) {
+ P.reset(Level + 1);
+ P.offset(Level + 1) = 0;
+ }
+}
+
+/// overflow - Distribute entries of the current node evenly among
+/// its siblings and ensure that the current node is not full.
+/// This may require allocating a new node.
+/// @param NodeT The type of node at Level (Leaf or Branch).
+/// @param Level path index of the overflowing node.
+/// @return True when the tree height was changed.
+template <typename KeyT, typename ValT, unsigned N, typename Traits>
+template <typename NodeT>
+bool IntervalMap<KeyT, ValT, N, Traits>::
+iterator::overflow(unsigned Level) {
+ using namespace IntervalMapImpl;
+ Path &P = this->path;
+ unsigned CurSize[4];
+ NodeT *Node[4];
+ unsigned Nodes = 0;
+ unsigned Elements = 0;
+ unsigned Offset = P.offset(Level);
+
+ // Do we have a left sibling?
+ NodeRef LeftSib = P.getLeftSibling(Level);
+ if (LeftSib) {
+ Offset += Elements = CurSize[Nodes] = LeftSib.size();
+ Node[Nodes++] = &LeftSib.get<NodeT>();
+ }
+
+ // Current node.
+ Elements += CurSize[Nodes] = P.size(Level);
+ Node[Nodes++] = &P.node<NodeT>(Level);
+
+ // Do we have a right sibling?
+ NodeRef RightSib = P.getRightSibling(Level);
+ if (RightSib) {
+ Elements += CurSize[Nodes] = RightSib.size();
+ Node[Nodes++] = &RightSib.get<NodeT>();
+ }
+
+ // Do we need to allocate a new node?
+ unsigned NewNode = 0;
+ if (Elements + 1 > Nodes * NodeT::Capacity) {
+ // Insert NewNode at the penultimate position, or after a single node.
+ NewNode = Nodes == 1 ? 1 : Nodes - 1;
+ CurSize[Nodes] = CurSize[NewNode];
+ Node[Nodes] = Node[NewNode];
+ CurSize[NewNode] = 0;
+ Node[NewNode] = this->map->template newNode<NodeT>();
+ ++Nodes;
+ }
+
+ // Compute the new element distribution.
+ unsigned NewSize[4];
+ IdxPair NewOffset = distribute(Nodes, Elements, NodeT::Capacity,
+ CurSize, NewSize, Offset, true);
+ adjustSiblingSizes(Node, Nodes, CurSize, NewSize);
+
+ // Move current location to the leftmost node.
+ if (LeftSib)
+ P.moveLeft(Level);
+
+ // Elements have been rearranged, now update node sizes and stops.
+ bool SplitRoot = false;
+ unsigned Pos = 0;
+ for (;;) {
+ KeyT Stop = Node[Pos]->stop(NewSize[Pos]-1);
+ if (NewNode && Pos == NewNode) {
+ SplitRoot = insertNode(Level, NodeRef(Node[Pos], NewSize[Pos]), Stop);
+ Level += SplitRoot;
+ } else {
+ P.setSize(Level, NewSize[Pos]);
+ setNodeStop(Level, Stop);
+ }
+ if (Pos + 1 == Nodes)
+ break;
+ P.moveRight(Level);
+ ++Pos;
+ }
+
+ // Where was I? Find NewOffset.
+ while(Pos != NewOffset.first) {
+ P.moveLeft(Level);
+ --Pos;
+ }
+ P.offset(Level) = NewOffset.second;
+ return SplitRoot;
+}
+
+//===----------------------------------------------------------------------===//
+//--- IntervalMapOverlaps ----//
+//===----------------------------------------------------------------------===//
+
+/// IntervalMapOverlaps - Iterate over the overlaps of mapped intervals in two
+/// IntervalMaps. The maps may be different, but the KeyT and Traits types
+/// should be the same.
+///
+/// Typical uses:
+///
+/// 1. Test for overlap:
+/// bool overlap = IntervalMapOverlaps(a, b).valid();
+///
+/// 2. Enumerate overlaps:
+/// for (IntervalMapOverlaps I(a, b); I.valid() ; ++I) { ... }
+///
+template <typename MapA, typename MapB>
+class IntervalMapOverlaps {
+ typedef typename MapA::KeyType KeyType;
+ typedef typename MapA::KeyTraits Traits;
+ typename MapA::const_iterator posA;
+ typename MapB::const_iterator posB;
+
+ /// advance - Move posA and posB forward until reaching an overlap, or until
+ /// either meets end.
+ /// Don't move the iterators if they are already overlapping.
+ void advance() {
+ if (!valid())
+ return;
+
+ if (Traits::stopLess(posA.stop(), posB.start())) {
+ // A ends before B begins. Catch up.
+ posA.advanceTo(posB.start());
+ if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start()))
+ return;
+ } else if (Traits::stopLess(posB.stop(), posA.start())) {
+ // B ends before A begins. Catch up.
+ posB.advanceTo(posA.start());
+ if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start()))
+ return;
+ } else
+ // Already overlapping.
+ return;
+
+ for (;;) {
+ // Make a.end > b.start.
+ posA.advanceTo(posB.start());
+ if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start()))
+ return;
+ // Make b.end > a.start.
+ posB.advanceTo(posA.start());
+ if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start()))
+ return;
+ }
+ }
+
+public:
+ /// IntervalMapOverlaps - Create an iterator for the overlaps of a and b.
+ IntervalMapOverlaps(const MapA &a, const MapB &b)
+ : posA(b.empty() ? a.end() : a.find(b.start())),
+ posB(posA.valid() ? b.find(posA.start()) : b.end()) { advance(); }
+
+ /// valid - Return true if iterator is at an overlap.
+ bool valid() const {
+ return posA.valid() && posB.valid();
+ }
+
+ /// a - access the left hand side in the overlap.
+ const typename MapA::const_iterator &a() const { return posA; }
+
+ /// b - access the right hand side in the overlap.
+ const typename MapB::const_iterator &b() const { return posB; }
+
+ /// start - Beginning of the overlapping interval.
+ KeyType start() const {
+ KeyType ak = a().start();
+ KeyType bk = b().start();
+ return Traits::startLess(ak, bk) ? bk : ak;
+ }
+
+ /// stop - End of the overlapping interval.
+ KeyType stop() const {
+ KeyType ak = a().stop();
+ KeyType bk = b().stop();
+ return Traits::startLess(ak, bk) ? ak : bk;
+ }
+
+ /// skipA - Move to the next overlap that doesn't involve a().
+ void skipA() {
+ ++posA;
+ advance();
+ }
+
+ /// skipB - Move to the next overlap that doesn't involve b().
+ void skipB() {
+ ++posB;
+ advance();
+ }
+
+ /// Preincrement - Move to the next overlap.
+ IntervalMapOverlaps &operator++() {
+ // Bump the iterator that ends first. The other one may have more overlaps.
+ if (Traits::startLess(posB.stop(), posA.stop()))
+ skipB();
+ else
+ skipA();
+ return *this;
+ }
+
+ /// advanceTo - Move to the first overlapping interval with
+ /// stopLess(x, stop()).
+ void advanceTo(KeyType x) {
+ if (!valid())
+ return;
+ // Make sure advanceTo sees monotonic keys.
+ if (Traits::stopLess(posA.stop(), x))
+ posA.advanceTo(x);
+ if (Traits::stopLess(posB.stop(), x))
+ posB.advanceTo(x);
+ advance();
+ }
+};
+
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/IntrusiveRefCntPtr.h b/include/llvm/ADT/IntrusiveRefCntPtr.h
new file mode 100644
index 00000000000..a9724ee1544
--- /dev/null
+++ b/include/llvm/ADT/IntrusiveRefCntPtr.h
@@ -0,0 +1,243 @@
+//== llvm/ADT/IntrusiveRefCntPtr.h - Smart Refcounting Pointer ---*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines IntrusiveRefCntPtr, a template class that
+// implements a "smart" pointer for objects that maintain their own
+// internal reference count, and RefCountedBase/RefCountedBaseVPTR, two
+// generic base classes for objects that wish to have their lifetimes
+// managed using reference counting.
+//
+// IntrusiveRefCntPtr is similar to Boost's intrusive_ptr with added
+// LLVM-style casting.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_INTRUSIVE_REF_CNT_PTR
+#define LLVM_ADT_INTRUSIVE_REF_CNT_PTR
+
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Compiler.h"
+#include <memory>
+
+namespace llvm {
+
+ template <class T>
+ class IntrusiveRefCntPtr;
+
+//===----------------------------------------------------------------------===//
+/// RefCountedBase - A generic base class for objects that wish to
+/// have their lifetimes managed using reference counts. Classes
+/// subclass RefCountedBase to obtain such functionality, and are
+/// typically handled with IntrusiveRefCntPtr "smart pointers" (see below)
+/// which automatically handle the management of reference counts.
+/// Objects that subclass RefCountedBase should not be allocated on
+/// the stack, as invoking "delete" (which is called when the
+/// reference count hits 0) on such objects is an error.
+//===----------------------------------------------------------------------===//
+ template <class Derived>
+ class RefCountedBase {
+ mutable unsigned ref_cnt;
+
+ public:
+ RefCountedBase() : ref_cnt(0) {}
+ RefCountedBase(const RefCountedBase &) : ref_cnt(0) {}
+
+ void Retain() const { ++ref_cnt; }
+ void Release() const {
+ assert (ref_cnt > 0 && "Reference count is already zero.");
+ if (--ref_cnt == 0) delete static_cast<const Derived*>(this);
+ }
+ };
+
+//===----------------------------------------------------------------------===//
+/// RefCountedBaseVPTR - A class that has the same function as
+/// RefCountedBase, but with a virtual destructor. Should be used
+/// instead of RefCountedBase for classes that already have virtual
+/// methods to enforce dynamic allocation via 'new'. Classes that
+/// inherit from RefCountedBaseVPTR can't be allocated on stack -
+/// attempting to do this will produce a compile error.
+//===----------------------------------------------------------------------===//
+ class RefCountedBaseVPTR {
+ mutable unsigned ref_cnt;
+ virtual void anchor();
+
+ protected:
+ RefCountedBaseVPTR() : ref_cnt(0) {}
+ RefCountedBaseVPTR(const RefCountedBaseVPTR &) : ref_cnt(0) {}
+
+ virtual ~RefCountedBaseVPTR() {}
+
+ void Retain() const { ++ref_cnt; }
+ void Release() const {
+ assert (ref_cnt > 0 && "Reference count is already zero.");
+ if (--ref_cnt == 0) delete this;
+ }
+
+ template <typename T>
+ friend struct IntrusiveRefCntPtrInfo;
+ };
+
+
+ template <typename T> struct IntrusiveRefCntPtrInfo {
+ static void retain(T *obj) { obj->Retain(); }
+ static void release(T *obj) { obj->Release(); }
+ };
+
+//===----------------------------------------------------------------------===//
+/// IntrusiveRefCntPtr - A template class that implements a "smart pointer"
+/// that assumes the wrapped object has a reference count associated
+/// with it that can be managed via calls to
+/// IntrusivePtrAddRef/IntrusivePtrRelease. The smart pointers
+/// manage reference counts via the RAII idiom: upon creation of
+/// smart pointer the reference count of the wrapped object is
+/// incremented and upon destruction of the smart pointer the
+/// reference count is decremented. This class also safely handles
+/// wrapping NULL pointers.
+///
+/// Reference counting is implemented via calls to
+/// Obj->Retain()/Obj->Release(). Release() is required to destroy
+/// the object when the reference count reaches zero. Inheriting from
+/// RefCountedBase/RefCountedBaseVPTR takes care of this
+/// automatically.
+//===----------------------------------------------------------------------===//
+ template <typename T>
+ class IntrusiveRefCntPtr {
+ T* Obj;
+ typedef IntrusiveRefCntPtr this_type;
+ public:
+ typedef T element_type;
+
+ explicit IntrusiveRefCntPtr() : Obj(0) {}
+
+ IntrusiveRefCntPtr(T* obj) : Obj(obj) {
+ retain();
+ }
+
+ IntrusiveRefCntPtr(const IntrusiveRefCntPtr& S) : Obj(S.Obj) {
+ retain();
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ IntrusiveRefCntPtr(IntrusiveRefCntPtr&& S) : Obj(S.Obj) {
+ S.Obj = 0;
+ }
+
+ template <class X>
+ IntrusiveRefCntPtr(IntrusiveRefCntPtr<X>&& S) : Obj(S.getPtr()) {
+ S.Obj = 0;
+ }
+#endif
+
+ template <class X>
+ IntrusiveRefCntPtr(const IntrusiveRefCntPtr<X>& S)
+ : Obj(S.getPtr()) {
+ retain();
+ }
+
+ IntrusiveRefCntPtr& operator=(IntrusiveRefCntPtr S) {
+ swap(S);
+ return *this;
+ }
+
+ ~IntrusiveRefCntPtr() { release(); }
+
+ T& operator*() const { return *Obj; }
+
+ T* operator->() const { return Obj; }
+
+ T* getPtr() const { return Obj; }
+
+ typedef T* (IntrusiveRefCntPtr::*unspecified_bool_type) () const;
+ operator unspecified_bool_type() const {
+ return Obj == 0 ? 0 : &IntrusiveRefCntPtr::getPtr;
+ }
+
+ void swap(IntrusiveRefCntPtr& other) {
+ T* tmp = other.Obj;
+ other.Obj = Obj;
+ Obj = tmp;
+ }
+
+ void reset() {
+ release();
+ Obj = 0;
+ }
+
+ void resetWithoutRelease() {
+ Obj = 0;
+ }
+
+ private:
+ void retain() { if (Obj) IntrusiveRefCntPtrInfo<T>::retain(Obj); }
+ void release() { if (Obj) IntrusiveRefCntPtrInfo<T>::release(Obj); }
+ };
+
+ template<class T, class U>
+ inline bool operator==(const IntrusiveRefCntPtr<T>& A,
+ const IntrusiveRefCntPtr<U>& B)
+ {
+ return A.getPtr() == B.getPtr();
+ }
+
+ template<class T, class U>
+ inline bool operator!=(const IntrusiveRefCntPtr<T>& A,
+ const IntrusiveRefCntPtr<U>& B)
+ {
+ return A.getPtr() != B.getPtr();
+ }
+
+ template<class T, class U>
+ inline bool operator==(const IntrusiveRefCntPtr<T>& A,
+ U* B)
+ {
+ return A.getPtr() == B;
+ }
+
+ template<class T, class U>
+ inline bool operator!=(const IntrusiveRefCntPtr<T>& A,
+ U* B)
+ {
+ return A.getPtr() != B;
+ }
+
+ template<class T, class U>
+ inline bool operator==(T* A,
+ const IntrusiveRefCntPtr<U>& B)
+ {
+ return A == B.getPtr();
+ }
+
+ template<class T, class U>
+ inline bool operator!=(T* A,
+ const IntrusiveRefCntPtr<U>& B)
+ {
+ return A != B.getPtr();
+ }
+
+//===----------------------------------------------------------------------===//
+// LLVM-style downcasting support for IntrusiveRefCntPtr objects
+//===----------------------------------------------------------------------===//
+
+ template<class T> struct simplify_type<IntrusiveRefCntPtr<T> > {
+ typedef T* SimpleType;
+ static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T>& Val) {
+ return Val.getPtr();
+ }
+ };
+
+ template<class T> struct simplify_type<const IntrusiveRefCntPtr<T> > {
+ typedef T* SimpleType;
+ static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T>& Val) {
+ return Val.getPtr();
+ }
+ };
+
+} // end namespace llvm
+
+#endif // LLVM_ADT_INTRUSIVE_REF_CNT_PTR
diff --git a/include/llvm/ADT/MapVector.h b/include/llvm/ADT/MapVector.h
new file mode 100644
index 00000000000..be3845f1d27
--- /dev/null
+++ b/include/llvm/ADT/MapVector.h
@@ -0,0 +1,153 @@
+//===- llvm/ADT/MapVector.h - Map with deterministic value order *- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements a map that also provides access to all stored values
+// in a deterministic order via the getValues method. Note that the iteration
+// order itself is just the DenseMap order and not deterministic. The interface
+// is purposefully minimal.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_MAPVECTOR_H
+#define LLVM_ADT_MAPVECTOR_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include <vector>
+
+namespace llvm {
+
+/// This class implements a map that also provides access to all stored values
+/// in a deterministic order. The values are kept in a std::vector and the
+/// mapping is done with DenseMap from Keys to indexes in that vector.
+template<typename KeyT, typename ValueT>
+class MapVector {
+ typedef llvm::DenseMap<KeyT, unsigned> MapType;
+ typedef std::vector<ValueT> VectorType;
+ typedef typename VectorType::size_type SizeType;
+
+ MapType Map;
+ VectorType Vector;
+
+public:
+ // The keys and values are not stored close to each other, so the iterator
+ // operator->() cannot return a pointer to a std::pair like a DenseMap does.
+ // Instead it returns a FakePair that contains references to Key and Value.
+ // This lets code using this to look the same as if using a regular DenseMap.
+ template<bool IsConst>
+ struct FakePair {
+ typedef typename conditional<IsConst, const ValueT, ValueT>::type VT;
+ const KeyT &first;
+ VT &second;
+ FakePair(const KeyT &K, VT &V) : first(K), second(V) {
+ }
+ FakePair *operator->() {
+ return this;
+ }
+ };
+
+ template<bool IsConst>
+ class IteratorTemplate {
+ typedef typename MapType::const_iterator WrappedIteratorType;
+ WrappedIteratorType WrappedI;
+ typedef
+ typename conditional<IsConst, const VectorType, VectorType>::type VT;
+ VT &VecRef;
+ typedef FakePair<IsConst> PairType;
+ friend class IteratorTemplate<true>;
+
+ public:
+ IteratorTemplate(WrappedIteratorType I, VT &V) :
+ WrappedI(I), VecRef(V) {
+ }
+
+ // If IsConst is true this is a converting constructor from iterator to
+ // const_iterator and the default copy constructor is used.
+ // Otherwise this is a copy constructor for iterator.
+ IteratorTemplate(const IteratorTemplate<false>& I) :
+ WrappedI(I.WrappedI), VecRef(I.VecRef) {
+ }
+
+ bool operator!=(const IteratorTemplate &RHS) const {
+ return WrappedI != RHS.WrappedI;
+ }
+
+ IteratorTemplate &operator++() { // Preincrement
+ ++WrappedI;
+ return *this;
+ }
+
+ PairType operator->() {
+ unsigned Pos = WrappedI->second;
+ PairType Ret(WrappedI->first, VecRef[Pos]);
+ return Ret;
+ }
+ };
+
+ typedef IteratorTemplate<false> iterator;
+ typedef IteratorTemplate<true> const_iterator;
+
+ SizeType size() const {
+ return Vector.size();
+ }
+
+ iterator begin() {
+ return iterator(Map.begin(), this->Vector);
+ }
+
+ const_iterator begin() const {
+ return const_iterator(Map.begin(), this->Vector);
+ }
+
+ iterator end() {
+ return iterator(Map.end(), this->Vector);
+ }
+
+ const_iterator end() const {
+ return const_iterator(Map.end(), this->Vector);
+ }
+
+ bool empty() const {
+ return Map.empty();
+ }
+
+ typedef typename VectorType::iterator value_iterator;
+ typedef typename VectorType::const_iterator const_value_iterator;
+
+ value_iterator value_begin() {
+ return Vector.begin();
+ }
+
+ const_value_iterator value_begin() const {
+ return Vector.begin();
+ }
+
+ value_iterator value_end() {
+ return Vector.end();
+ }
+
+ const_value_iterator value_end() const {
+ return Vector.end();
+ }
+
+ ValueT &operator[](const KeyT &Key) {
+ std::pair<KeyT, unsigned> Pair = std::make_pair(Key, 0);
+ std::pair<typename MapType::iterator, bool> Result = Map.insert(Pair);
+ unsigned &I = Result.first->second;
+ if (Result.second) {
+ Vector.push_back(ValueT());
+ I = Vector.size() - 1;
+ }
+ return Vector[I];
+ }
+};
+
+}
+
+#endif
diff --git a/include/llvm/ADT/NullablePtr.h b/include/llvm/ADT/NullablePtr.h
new file mode 100644
index 00000000000..a9c47a138ec
--- /dev/null
+++ b/include/llvm/ADT/NullablePtr.h
@@ -0,0 +1,52 @@
+//===- llvm/ADT/NullablePtr.h - A pointer that allows null ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines and implements the NullablePtr class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_NULLABLE_PTR_H
+#define LLVM_ADT_NULLABLE_PTR_H
+
+#include <cassert>
+#include <cstddef>
+
+namespace llvm {
+/// NullablePtr pointer wrapper - NullablePtr is used for APIs where a
+/// potentially-null pointer gets passed around that must be explicitly handled
+/// in lots of places. By putting a wrapper around the null pointer, it makes
+/// it more likely that the null pointer case will be handled correctly.
+template<class T>
+class NullablePtr {
+ T *Ptr;
+public:
+ NullablePtr(T *P = 0) : Ptr(P) {}
+
+ bool isNull() const { return Ptr == 0; }
+ bool isNonNull() const { return Ptr != 0; }
+
+ /// get - Return the pointer if it is non-null.
+ const T *get() const {
+ assert(Ptr && "Pointer wasn't checked for null!");
+ return Ptr;
+ }
+
+ /// get - Return the pointer if it is non-null.
+ T *get() {
+ assert(Ptr && "Pointer wasn't checked for null!");
+ return Ptr;
+ }
+
+ T *getPtrOrNull() { return Ptr; }
+ const T *getPtrOrNull() const { return Ptr; }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/Optional.h b/include/llvm/ADT/Optional.h
new file mode 100644
index 00000000000..ee8b69f3d12
--- /dev/null
+++ b/include/llvm/ADT/Optional.h
@@ -0,0 +1,120 @@
+//===-- Optional.h - Simple variant for passing optional values ---*- C++ -*-=//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file provides Optional, a template class modeled in the spirit of
+// OCaml's 'opt' variant. The idea is to strongly type whether or not
+// a value can be optional.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_OPTIONAL
+#define LLVM_ADT_OPTIONAL
+
+#include <cassert>
+
+namespace llvm {
+
+template<typename T>
+class Optional {
+ T x;
+ unsigned hasVal : 1;
+public:
+ explicit Optional() : x(), hasVal(false) {}
+ Optional(const T &y) : x(y), hasVal(true) {}
+
+ static inline Optional create(const T* y) {
+ return y ? Optional(*y) : Optional();
+ }
+
+ Optional &operator=(const T &y) {
+ x = y;
+ hasVal = true;
+ return *this;
+ }
+
+ const T* getPointer() const { assert(hasVal); return &x; }
+ const T& getValue() const { assert(hasVal); return x; }
+
+ operator bool() const { return hasVal; }
+ bool hasValue() const { return hasVal; }
+ const T* operator->() const { return getPointer(); }
+ const T& operator*() const { assert(hasVal); return x; }
+};
+
+template<typename T> struct simplify_type;
+
+template <typename T>
+struct simplify_type<const Optional<T> > {
+ typedef const T* SimpleType;
+ static SimpleType getSimplifiedValue(const Optional<T> &Val) {
+ return Val.getPointer();
+ }
+};
+
+template <typename T>
+struct simplify_type<Optional<T> >
+ : public simplify_type<const Optional<T> > {};
+
+/// \brief Poison comparison between two \c Optional objects. Clients needs to
+/// explicitly compare the underlying values and account for empty \c Optional
+/// objects.
+///
+/// This routine will never be defined. It returns \c void to help diagnose
+/// errors at compile time.
+template<typename T, typename U>
+void operator==(const Optional<T> &X, const Optional<U> &Y);
+
+/// \brief Poison comparison between two \c Optional objects. Clients needs to
+/// explicitly compare the underlying values and account for empty \c Optional
+/// objects.
+///
+/// This routine will never be defined. It returns \c void to help diagnose
+/// errors at compile time.
+template<typename T, typename U>
+void operator!=(const Optional<T> &X, const Optional<U> &Y);
+
+/// \brief Poison comparison between two \c Optional objects. Clients needs to
+/// explicitly compare the underlying values and account for empty \c Optional
+/// objects.
+///
+/// This routine will never be defined. It returns \c void to help diagnose
+/// errors at compile time.
+template<typename T, typename U>
+void operator<(const Optional<T> &X, const Optional<U> &Y);
+
+/// \brief Poison comparison between two \c Optional objects. Clients needs to
+/// explicitly compare the underlying values and account for empty \c Optional
+/// objects.
+///
+/// This routine will never be defined. It returns \c void to help diagnose
+/// errors at compile time.
+template<typename T, typename U>
+void operator<=(const Optional<T> &X, const Optional<U> &Y);
+
+/// \brief Poison comparison between two \c Optional objects. Clients needs to
+/// explicitly compare the underlying values and account for empty \c Optional
+/// objects.
+///
+/// This routine will never be defined. It returns \c void to help diagnose
+/// errors at compile time.
+template<typename T, typename U>
+void operator>=(const Optional<T> &X, const Optional<U> &Y);
+
+/// \brief Poison comparison between two \c Optional objects. Clients needs to
+/// explicitly compare the underlying values and account for empty \c Optional
+/// objects.
+///
+/// This routine will never be defined. It returns \c void to help diagnose
+/// errors at compile time.
+template<typename T, typename U>
+void operator>(const Optional<T> &X, const Optional<U> &Y);
+
+} // end llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/OwningPtr.h b/include/llvm/ADT/OwningPtr.h
new file mode 100644
index 00000000000..ea9495d3869
--- /dev/null
+++ b/include/llvm/ADT/OwningPtr.h
@@ -0,0 +1,134 @@
+//===- llvm/ADT/OwningPtr.h - Smart ptr that owns the pointee ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines and implements the OwningPtr class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_OWNING_PTR_H
+#define LLVM_ADT_OWNING_PTR_H
+
+#include "llvm/Support/Compiler.h"
+#include <cassert>
+#include <cstddef>
+
+namespace llvm {
+
+/// OwningPtr smart pointer - OwningPtr mimics a built-in pointer except that it
+/// guarantees deletion of the object pointed to, either on destruction of the
+/// OwningPtr or via an explicit reset(). Once created, ownership of the
+/// pointee object can be taken away from OwningPtr by using the take method.
+template<class T>
+class OwningPtr {
+ OwningPtr(OwningPtr const &) LLVM_DELETED_FUNCTION;
+ OwningPtr &operator=(OwningPtr const &) LLVM_DELETED_FUNCTION;
+ T *Ptr;
+public:
+ explicit OwningPtr(T *P = 0) : Ptr(P) {}
+
+ ~OwningPtr() {
+ delete Ptr;
+ }
+
+ /// reset - Change the current pointee to the specified pointer. Note that
+ /// calling this with any pointer (including a null pointer) deletes the
+ /// current pointer.
+ void reset(T *P = 0) {
+ if (P == Ptr) return;
+ T *Tmp = Ptr;
+ Ptr = P;
+ delete Tmp;
+ }
+
+ /// take - Reset the owning pointer to null and return its pointer. This does
+ /// not delete the pointer before returning it.
+ T *take() {
+ T *Tmp = Ptr;
+ Ptr = 0;
+ return Tmp;
+ }
+
+ T &operator*() const {
+ assert(Ptr && "Cannot dereference null pointer");
+ return *Ptr;
+ }
+
+ T *operator->() const { return Ptr; }
+ T *get() const { return Ptr; }
+ operator bool() const { return Ptr != 0; }
+ bool operator!() const { return Ptr == 0; }
+
+ void swap(OwningPtr &RHS) {
+ T *Tmp = RHS.Ptr;
+ RHS.Ptr = Ptr;
+ Ptr = Tmp;
+ }
+};
+
+template<class T>
+inline void swap(OwningPtr<T> &a, OwningPtr<T> &b) {
+ a.swap(b);
+}
+
+/// OwningArrayPtr smart pointer - OwningArrayPtr provides the same
+/// functionality as OwningPtr, except that it works for array types.
+template<class T>
+class OwningArrayPtr {
+ OwningArrayPtr(OwningArrayPtr const &) LLVM_DELETED_FUNCTION;
+ OwningArrayPtr &operator=(OwningArrayPtr const &) LLVM_DELETED_FUNCTION;
+ T *Ptr;
+public:
+ explicit OwningArrayPtr(T *P = 0) : Ptr(P) {}
+
+ ~OwningArrayPtr() {
+ delete [] Ptr;
+ }
+
+ /// reset - Change the current pointee to the specified pointer. Note that
+ /// calling this with any pointer (including a null pointer) deletes the
+ /// current pointer.
+ void reset(T *P = 0) {
+ if (P == Ptr) return;
+ T *Tmp = Ptr;
+ Ptr = P;
+ delete [] Tmp;
+ }
+
+ /// take - Reset the owning pointer to null and return its pointer. This does
+ /// not delete the pointer before returning it.
+ T *take() {
+ T *Tmp = Ptr;
+ Ptr = 0;
+ return Tmp;
+ }
+
+ T &operator[](std::ptrdiff_t i) const {
+ assert(Ptr && "Cannot dereference null pointer");
+ return Ptr[i];
+ }
+
+ T *get() const { return Ptr; }
+ operator bool() const { return Ptr != 0; }
+ bool operator!() const { return Ptr == 0; }
+
+ void swap(OwningArrayPtr &RHS) {
+ T *Tmp = RHS.Ptr;
+ RHS.Ptr = Ptr;
+ Ptr = Tmp;
+ }
+};
+
+template<class T>
+inline void swap(OwningArrayPtr<T> &a, OwningArrayPtr<T> &b) {
+ a.swap(b);
+}
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/PackedVector.h b/include/llvm/ADT/PackedVector.h
new file mode 100644
index 00000000000..2eaddc2b4ee
--- /dev/null
+++ b/include/llvm/ADT/PackedVector.h
@@ -0,0 +1,158 @@
+//===- llvm/ADT/PackedVector.h - Packed values vector -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the PackedVector class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_PACKEDVECTOR_H
+#define LLVM_ADT_PACKEDVECTOR_H
+
+#include "llvm/ADT/BitVector.h"
+#include <limits>
+
+namespace llvm {
+
+template <typename T, unsigned BitNum, bool isSigned>
+class PackedVectorBase;
+
+// This won't be necessary if we can specialize members without specializing
+// the parent template.
+template <typename T, unsigned BitNum>
+class PackedVectorBase<T, BitNum, false> {
+protected:
+ static T getValue(const llvm::BitVector &Bits, unsigned Idx) {
+ T val = T();
+ for (unsigned i = 0; i != BitNum; ++i)
+ val = T(val | ((Bits[(Idx << (BitNum-1)) + i] ? 1UL : 0UL) << i));
+ return val;
+ }
+
+ static void setValue(llvm::BitVector &Bits, unsigned Idx, T val) {
+ assert((val >> BitNum) == 0 && "value is too big");
+ for (unsigned i = 0; i != BitNum; ++i)
+ Bits[(Idx << (BitNum-1)) + i] = val & (T(1) << i);
+ }
+};
+
+template <typename T, unsigned BitNum>
+class PackedVectorBase<T, BitNum, true> {
+protected:
+ static T getValue(const llvm::BitVector &Bits, unsigned Idx) {
+ T val = T();
+ for (unsigned i = 0; i != BitNum-1; ++i)
+ val = T(val | ((Bits[(Idx << (BitNum-1)) + i] ? 1UL : 0UL) << i));
+ if (Bits[(Idx << (BitNum-1)) + BitNum-1])
+ val = ~val;
+ return val;
+ }
+
+ static void setValue(llvm::BitVector &Bits, unsigned Idx, T val) {
+ if (val < 0) {
+ val = ~val;
+ Bits.set((Idx << (BitNum-1)) + BitNum-1);
+ }
+ assert((val >> (BitNum-1)) == 0 && "value is too big");
+ for (unsigned i = 0; i != BitNum-1; ++i)
+ Bits[(Idx << (BitNum-1)) + i] = val & (T(1) << i);
+ }
+};
+
+/// \brief Store a vector of values using a specific number of bits for each
+/// value. Both signed and unsigned types can be used, e.g
+/// @code
+/// PackedVector<signed, 2> vec;
+/// @endcode
+/// will create a vector accepting values -2, -1, 0, 1. Any other value will hit
+/// an assertion.
+template <typename T, unsigned BitNum>
+class PackedVector : public PackedVectorBase<T, BitNum,
+ std::numeric_limits<T>::is_signed> {
+ llvm::BitVector Bits;
+ typedef PackedVectorBase<T, BitNum, std::numeric_limits<T>::is_signed> base;
+
+public:
+ class reference {
+ PackedVector &Vec;
+ const unsigned Idx;
+
+ reference(); // Undefined
+ public:
+ reference(PackedVector &vec, unsigned idx) : Vec(vec), Idx(idx) { }
+
+ reference &operator=(T val) {
+ Vec.setValue(Vec.Bits, Idx, val);
+ return *this;
+ }
+ operator T() const {
+ return Vec.getValue(Vec.Bits, Idx);
+ }
+ };
+
+ PackedVector() { }
+ explicit PackedVector(unsigned size) : Bits(size << (BitNum-1)) { }
+
+ bool empty() const { return Bits.empty(); }
+
+ unsigned size() const { return Bits.size() >> (BitNum-1); }
+
+ void clear() { Bits.clear(); }
+
+ void resize(unsigned N) { Bits.resize(N << (BitNum-1)); }
+
+ void reserve(unsigned N) { Bits.reserve(N << (BitNum-1)); }
+
+ PackedVector &reset() {
+ Bits.reset();
+ return *this;
+ }
+
+ void push_back(T val) {
+ resize(size()+1);
+ (*this)[size()-1] = val;
+ }
+
+ reference operator[](unsigned Idx) {
+ return reference(*this, Idx);
+ }
+
+ T operator[](unsigned Idx) const {
+ return base::getValue(Bits, Idx);
+ }
+
+ bool operator==(const PackedVector &RHS) const {
+ return Bits == RHS.Bits;
+ }
+
+ bool operator!=(const PackedVector &RHS) const {
+ return Bits != RHS.Bits;
+ }
+
+ const PackedVector &operator=(const PackedVector &RHS) {
+ Bits = RHS.Bits;
+ return *this;
+ }
+
+ PackedVector &operator|=(const PackedVector &RHS) {
+ Bits |= RHS.Bits;
+ return *this;
+ }
+
+ void swap(PackedVector &RHS) {
+ Bits.swap(RHS.Bits);
+ }
+};
+
+// Leave BitNum=0 undefined.
+template <typename T>
+class PackedVector<T, 0>;
+
+} // end llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/PointerIntPair.h b/include/llvm/ADT/PointerIntPair.h
new file mode 100644
index 00000000000..71c379bad5a
--- /dev/null
+++ b/include/llvm/ADT/PointerIntPair.h
@@ -0,0 +1,178 @@
+//===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the PointerIntPair class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_POINTERINTPAIR_H
+#define LLVM_ADT_POINTERINTPAIR_H
+
+#include "llvm/Support/PointerLikeTypeTraits.h"
+#include <cassert>
+
+namespace llvm {
+
+template<typename T>
+struct DenseMapInfo;
+
+/// PointerIntPair - This class implements a pair of a pointer and small
+/// integer. It is designed to represent this in the space required by one
+/// pointer by bitmangling the integer into the low part of the pointer. This
+/// can only be done for small integers: typically up to 3 bits, but it depends
+/// on the number of bits available according to PointerLikeTypeTraits for the
+/// type.
+///
+/// Note that PointerIntPair always puts the Int part in the highest bits
+/// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for
+/// the bool into bit #2, not bit #0, which allows the low two bits to be used
+/// for something else. For example, this allows:
+/// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool>
+/// ... and the two bools will land in different bits.
+///
+template <typename PointerTy, unsigned IntBits, typename IntType=unsigned,
+ typename PtrTraits = PointerLikeTypeTraits<PointerTy> >
+class PointerIntPair {
+ intptr_t Value;
+ enum {
+ /// PointerBitMask - The bits that come from the pointer.
+ PointerBitMask =
+ ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable)-1),
+
+ /// IntShift - The number of low bits that we reserve for other uses, and
+ /// keep zero.
+ IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable-IntBits,
+
+ /// IntMask - This is the unshifted mask for valid bits of the int type.
+ IntMask = (uintptr_t)(((intptr_t)1 << IntBits)-1),
+
+ // ShiftedIntMask - This is the bits for the integer shifted in place.
+ ShiftedIntMask = (uintptr_t)(IntMask << IntShift)
+ };
+public:
+ PointerIntPair() : Value(0) {}
+ PointerIntPair(PointerTy Ptr, IntType Int) : Value(0) {
+ assert(IntBits <= PtrTraits::NumLowBitsAvailable &&
+ "PointerIntPair formed with integer size too large for pointer");
+ setPointer(Ptr);
+ setInt(Int);
+ }
+
+ PointerTy getPointer() const {
+ return PtrTraits::getFromVoidPointer(
+ reinterpret_cast<void*>(Value & PointerBitMask));
+ }
+
+ IntType getInt() const {
+ return (IntType)((Value >> IntShift) & IntMask);
+ }
+
+ void setPointer(PointerTy Ptr) {
+ intptr_t PtrVal
+ = reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr));
+ assert((PtrVal & ((1 << PtrTraits::NumLowBitsAvailable)-1)) == 0 &&
+ "Pointer is not sufficiently aligned");
+ // Preserve all low bits, just update the pointer.
+ Value = PtrVal | (Value & ~PointerBitMask);
+ }
+
+ void setInt(IntType Int) {
+ intptr_t IntVal = Int;
+ assert(IntVal < (1 << IntBits) && "Integer too large for field");
+
+ // Preserve all bits other than the ones we are updating.
+ Value &= ~ShiftedIntMask; // Remove integer field.
+ Value |= IntVal << IntShift; // Set new integer.
+ }
+
+ PointerTy const *getAddrOfPointer() const {
+ return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
+ }
+
+ PointerTy *getAddrOfPointer() {
+ assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&
+ "Can only return the address if IntBits is cleared and "
+ "PtrTraits doesn't change the pointer");
+ return reinterpret_cast<PointerTy *>(&Value);
+ }
+
+ void *getOpaqueValue() const { return reinterpret_cast<void*>(Value); }
+ void setFromOpaqueValue(void *Val) { Value = reinterpret_cast<intptr_t>(Val);}
+
+ static PointerIntPair getFromOpaqueValue(void *V) {
+ PointerIntPair P; P.setFromOpaqueValue(V); return P;
+ }
+
+ // Allow PointerIntPairs to be created from const void * if and only if the
+ // pointer type could be created from a const void *.
+ static PointerIntPair getFromOpaqueValue(const void *V) {
+ (void)PtrTraits::getFromVoidPointer(V);
+ return getFromOpaqueValue(const_cast<void *>(V));
+ }
+
+ bool operator==(const PointerIntPair &RHS) const {return Value == RHS.Value;}
+ bool operator!=(const PointerIntPair &RHS) const {return Value != RHS.Value;}
+ bool operator<(const PointerIntPair &RHS) const {return Value < RHS.Value;}
+ bool operator>(const PointerIntPair &RHS) const {return Value > RHS.Value;}
+ bool operator<=(const PointerIntPair &RHS) const {return Value <= RHS.Value;}
+ bool operator>=(const PointerIntPair &RHS) const {return Value >= RHS.Value;}
+};
+
+template <typename T> struct isPodLike;
+template<typename PointerTy, unsigned IntBits, typename IntType>
+struct isPodLike<PointerIntPair<PointerTy, IntBits, IntType> > {
+ static const bool value = true;
+};
+
+// Provide specialization of DenseMapInfo for PointerIntPair.
+template<typename PointerTy, unsigned IntBits, typename IntType>
+struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType> > {
+ typedef PointerIntPair<PointerTy, IntBits, IntType> Ty;
+ static Ty getEmptyKey() {
+ uintptr_t Val = static_cast<uintptr_t>(-1);
+ Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable;
+ return Ty(reinterpret_cast<PointerTy>(Val), IntType((1 << IntBits)-1));
+ }
+ static Ty getTombstoneKey() {
+ uintptr_t Val = static_cast<uintptr_t>(-2);
+ Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable;
+ return Ty(reinterpret_cast<PointerTy>(Val), IntType(0));
+ }
+ static unsigned getHashValue(Ty V) {
+ uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue());
+ return unsigned(IV) ^ unsigned(IV >> 9);
+ }
+ static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; }
+};
+
+// Teach SmallPtrSet that PointerIntPair is "basically a pointer".
+template<typename PointerTy, unsigned IntBits, typename IntType,
+ typename PtrTraits>
+class PointerLikeTypeTraits<PointerIntPair<PointerTy, IntBits, IntType,
+ PtrTraits> > {
+public:
+ static inline void *
+ getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) {
+ return P.getOpaqueValue();
+ }
+ static inline PointerIntPair<PointerTy, IntBits, IntType>
+ getFromVoidPointer(void *P) {
+ return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
+ }
+ static inline PointerIntPair<PointerTy, IntBits, IntType>
+ getFromVoidPointer(const void *P) {
+ return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
+ }
+ enum {
+ NumLowBitsAvailable = PtrTraits::NumLowBitsAvailable - IntBits
+ };
+};
+
+} // end namespace llvm
+#endif
diff --git a/include/llvm/ADT/PointerUnion.h b/include/llvm/ADT/PointerUnion.h
new file mode 100644
index 00000000000..a9e86d22002
--- /dev/null
+++ b/include/llvm/ADT/PointerUnion.h
@@ -0,0 +1,452 @@
+//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the PointerUnion class, which is a discriminated union of
+// pointer types.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_POINTERUNION_H
+#define LLVM_ADT_POINTERUNION_H
+
+#include "llvm/ADT/PointerIntPair.h"
+
+namespace llvm {
+
+ template <typename T>
+ struct PointerUnionTypeSelectorReturn {
+ typedef T Return;
+ };
+
+ /// \brief Get a type based on whether two types are the same or not. For:
+ /// @code
+ /// typedef typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return Ret;
+ /// @endcode
+ /// Ret will be EQ type if T1 is same as T2 or NE type otherwise.
+ template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
+ struct PointerUnionTypeSelector {
+ typedef typename PointerUnionTypeSelectorReturn<RET_NE>::Return Return;
+ };
+
+ template <typename T, typename RET_EQ, typename RET_NE>
+ struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> {
+ typedef typename PointerUnionTypeSelectorReturn<RET_EQ>::Return Return;
+ };
+
+ template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
+ struct PointerUnionTypeSelectorReturn<
+ PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE> > {
+ typedef typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return
+ Return;
+ };
+
+ /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
+ /// for the two template arguments.
+ template <typename PT1, typename PT2>
+ class PointerUnionUIntTraits {
+ public:
+ static inline void *getAsVoidPointer(void *P) { return P; }
+ static inline void *getFromVoidPointer(void *P) { return P; }
+ enum {
+ PT1BitsAv = (int)(PointerLikeTypeTraits<PT1>::NumLowBitsAvailable),
+ PT2BitsAv = (int)(PointerLikeTypeTraits<PT2>::NumLowBitsAvailable),
+ NumLowBitsAvailable = PT1BitsAv < PT2BitsAv ? PT1BitsAv : PT2BitsAv
+ };
+ };
+
+ /// PointerUnion - This implements a discriminated union of two pointer types,
+ /// and keeps the discriminator bit-mangled into the low bits of the pointer.
+ /// This allows the implementation to be extremely efficient in space, but
+ /// permits a very natural and type-safe API.
+ ///
+ /// Common use patterns would be something like this:
+ /// PointerUnion<int*, float*> P;
+ /// P = (int*)0;
+ /// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
+ /// X = P.get<int*>(); // ok.
+ /// Y = P.get<float*>(); // runtime assertion failure.
+ /// Z = P.get<double*>(); // runtime assertion failure (regardless of tag)
+ /// P = (float*)0;
+ /// Y = P.get<float*>(); // ok.
+ /// X = P.get<int*>(); // runtime assertion failure.
+ template <typename PT1, typename PT2>
+ class PointerUnion {
+ public:
+ typedef PointerIntPair<void*, 1, bool,
+ PointerUnionUIntTraits<PT1,PT2> > ValTy;
+ private:
+ ValTy Val;
+
+ struct IsPT1 {
+ static const int Num = 0;
+ };
+ struct IsPT2 {
+ static const int Num = 1;
+ };
+ template <typename T>
+ struct UNION_DOESNT_CONTAIN_TYPE { };
+
+ public:
+ PointerUnion() {}
+
+ PointerUnion(PT1 V) {
+ Val.setPointer(
+ const_cast<void *>(PointerLikeTypeTraits<PT1>::getAsVoidPointer(V)));
+ Val.setInt(0);
+ }
+ PointerUnion(PT2 V) {
+ Val.setPointer(
+ const_cast<void *>(PointerLikeTypeTraits<PT2>::getAsVoidPointer(V)));
+ Val.setInt(1);
+ }
+
+ /// isNull - Return true if the pointer held in the union is null,
+ /// regardless of which type it is.
+ bool isNull() const {
+ // Convert from the void* to one of the pointer types, to make sure that
+ // we recursively strip off low bits if we have a nested PointerUnion.
+ return !PointerLikeTypeTraits<PT1>::getFromVoidPointer(Val.getPointer());
+ }
+ operator bool() const { return !isNull(); }
+
+ /// is<T>() return true if the Union currently holds the type matching T.
+ template<typename T>
+ int is() const {
+ typedef typename
+ ::llvm::PointerUnionTypeSelector<PT1, T, IsPT1,
+ ::llvm::PointerUnionTypeSelector<PT2, T, IsPT2,
+ UNION_DOESNT_CONTAIN_TYPE<T> > >::Return Ty;
+ int TyNo = Ty::Num;
+ return static_cast<int>(Val.getInt()) == TyNo;
+ }
+
+ /// get<T>() - Return the value of the specified pointer type. If the
+ /// specified pointer type is incorrect, assert.
+ template<typename T>
+ T get() const {
+ assert(is<T>() && "Invalid accessor called");
+ return PointerLikeTypeTraits<T>::getFromVoidPointer(Val.getPointer());
+ }
+
+ /// dyn_cast<T>() - If the current value is of the specified pointer type,
+ /// return it, otherwise return null.
+ template<typename T>
+ T dyn_cast() const {
+ if (is<T>()) return get<T>();
+ return T();
+ }
+
+ /// \brief If the union is set to the first pointer type get an address
+ /// pointing to it.
+ PT1 const *getAddrOfPtr1() const {
+ return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
+ }
+
+ /// \brief If the union is set to the first pointer type get an address
+ /// pointing to it.
+ PT1 *getAddrOfPtr1() {
+ assert(is<PT1>() && "Val is not the first pointer");
+ assert(get<PT1>() == Val.getPointer() &&
+ "Can't get the address because PointerLikeTypeTraits changes the ptr");
+ return (PT1 *)Val.getAddrOfPointer();
+ }
+
+ /// Assignment operators - Allow assigning into this union from either
+ /// pointer type, setting the discriminator to remember what it came from.
+ const PointerUnion &operator=(const PT1 &RHS) {
+ Val.setPointer(
+ const_cast<void *>(PointerLikeTypeTraits<PT1>::getAsVoidPointer(RHS)));
+ Val.setInt(0);
+ return *this;
+ }
+ const PointerUnion &operator=(const PT2 &RHS) {
+ Val.setPointer(
+ const_cast<void *>(PointerLikeTypeTraits<PT2>::getAsVoidPointer(RHS)));
+ Val.setInt(1);
+ return *this;
+ }
+
+ void *getOpaqueValue() const { return Val.getOpaqueValue(); }
+ static inline PointerUnion getFromOpaqueValue(void *VP) {
+ PointerUnion V;
+ V.Val = ValTy::getFromOpaqueValue(VP);
+ return V;
+ }
+ };
+
+ // Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
+ // # low bits available = min(PT1bits,PT2bits)-1.
+ template<typename PT1, typename PT2>
+ class PointerLikeTypeTraits<PointerUnion<PT1, PT2> > {
+ public:
+ static inline void *
+ getAsVoidPointer(const PointerUnion<PT1, PT2> &P) {
+ return P.getOpaqueValue();
+ }
+ static inline PointerUnion<PT1, PT2>
+ getFromVoidPointer(void *P) {
+ return PointerUnion<PT1, PT2>::getFromOpaqueValue(P);
+ }
+
+ // The number of bits available are the min of the two pointer types.
+ enum {
+ NumLowBitsAvailable =
+ PointerLikeTypeTraits<typename PointerUnion<PT1,PT2>::ValTy>
+ ::NumLowBitsAvailable
+ };
+ };
+
+
+ /// PointerUnion3 - This is a pointer union of three pointer types. See
+ /// documentation for PointerUnion for usage.
+ template <typename PT1, typename PT2, typename PT3>
+ class PointerUnion3 {
+ public:
+ typedef PointerUnion<PT1, PT2> InnerUnion;
+ typedef PointerUnion<InnerUnion, PT3> ValTy;
+ private:
+ ValTy Val;
+
+ struct IsInnerUnion {
+ ValTy Val;
+ IsInnerUnion(ValTy val) : Val(val) { }
+ template<typename T>
+ int is() const {
+ return Val.template is<InnerUnion>() &&
+ Val.template get<InnerUnion>().template is<T>();
+ }
+ template<typename T>
+ T get() const {
+ return Val.template get<InnerUnion>().template get<T>();
+ }
+ };
+
+ struct IsPT3 {
+ ValTy Val;
+ IsPT3(ValTy val) : Val(val) { }
+ template<typename T>
+ int is() const {
+ return Val.template is<T>();
+ }
+ template<typename T>
+ T get() const {
+ return Val.template get<T>();
+ }
+ };
+
+ public:
+ PointerUnion3() {}
+
+ PointerUnion3(PT1 V) {
+ Val = InnerUnion(V);
+ }
+ PointerUnion3(PT2 V) {
+ Val = InnerUnion(V);
+ }
+ PointerUnion3(PT3 V) {
+ Val = V;
+ }
+
+ /// isNull - Return true if the pointer held in the union is null,
+ /// regardless of which type it is.
+ bool isNull() const { return Val.isNull(); }
+ operator bool() const { return !isNull(); }
+
+ /// is<T>() return true if the Union currently holds the type matching T.
+ template<typename T>
+ int is() const {
+ // If T is PT1/PT2 choose IsInnerUnion otherwise choose IsPT3.
+ typedef typename
+ ::llvm::PointerUnionTypeSelector<PT1, T, IsInnerUnion,
+ ::llvm::PointerUnionTypeSelector<PT2, T, IsInnerUnion, IsPT3 >
+ >::Return Ty;
+ return Ty(Val).template is<T>();
+ }
+
+ /// get<T>() - Return the value of the specified pointer type. If the
+ /// specified pointer type is incorrect, assert.
+ template<typename T>
+ T get() const {
+ assert(is<T>() && "Invalid accessor called");
+ // If T is PT1/PT2 choose IsInnerUnion otherwise choose IsPT3.
+ typedef typename
+ ::llvm::PointerUnionTypeSelector<PT1, T, IsInnerUnion,
+ ::llvm::PointerUnionTypeSelector<PT2, T, IsInnerUnion, IsPT3 >
+ >::Return Ty;
+ return Ty(Val).template get<T>();
+ }
+
+ /// dyn_cast<T>() - If the current value is of the specified pointer type,
+ /// return it, otherwise return null.
+ template<typename T>
+ T dyn_cast() const {
+ if (is<T>()) return get<T>();
+ return T();
+ }
+
+ /// Assignment operators - Allow assigning into this union from either
+ /// pointer type, setting the discriminator to remember what it came from.
+ const PointerUnion3 &operator=(const PT1 &RHS) {
+ Val = InnerUnion(RHS);
+ return *this;
+ }
+ const PointerUnion3 &operator=(const PT2 &RHS) {
+ Val = InnerUnion(RHS);
+ return *this;
+ }
+ const PointerUnion3 &operator=(const PT3 &RHS) {
+ Val = RHS;
+ return *this;
+ }
+
+ void *getOpaqueValue() const { return Val.getOpaqueValue(); }
+ static inline PointerUnion3 getFromOpaqueValue(void *VP) {
+ PointerUnion3 V;
+ V.Val = ValTy::getFromOpaqueValue(VP);
+ return V;
+ }
+ };
+
+ // Teach SmallPtrSet that PointerUnion3 is "basically a pointer", that has
+ // # low bits available = min(PT1bits,PT2bits,PT2bits)-2.
+ template<typename PT1, typename PT2, typename PT3>
+ class PointerLikeTypeTraits<PointerUnion3<PT1, PT2, PT3> > {
+ public:
+ static inline void *
+ getAsVoidPointer(const PointerUnion3<PT1, PT2, PT3> &P) {
+ return P.getOpaqueValue();
+ }
+ static inline PointerUnion3<PT1, PT2, PT3>
+ getFromVoidPointer(void *P) {
+ return PointerUnion3<PT1, PT2, PT3>::getFromOpaqueValue(P);
+ }
+
+ // The number of bits available are the min of the two pointer types.
+ enum {
+ NumLowBitsAvailable =
+ PointerLikeTypeTraits<typename PointerUnion3<PT1, PT2, PT3>::ValTy>
+ ::NumLowBitsAvailable
+ };
+ };
+
+ /// PointerUnion4 - This is a pointer union of four pointer types. See
+ /// documentation for PointerUnion for usage.
+ template <typename PT1, typename PT2, typename PT3, typename PT4>
+ class PointerUnion4 {
+ public:
+ typedef PointerUnion<PT1, PT2> InnerUnion1;
+ typedef PointerUnion<PT3, PT4> InnerUnion2;
+ typedef PointerUnion<InnerUnion1, InnerUnion2> ValTy;
+ private:
+ ValTy Val;
+ public:
+ PointerUnion4() {}
+
+ PointerUnion4(PT1 V) {
+ Val = InnerUnion1(V);
+ }
+ PointerUnion4(PT2 V) {
+ Val = InnerUnion1(V);
+ }
+ PointerUnion4(PT3 V) {
+ Val = InnerUnion2(V);
+ }
+ PointerUnion4(PT4 V) {
+ Val = InnerUnion2(V);
+ }
+
+ /// isNull - Return true if the pointer held in the union is null,
+ /// regardless of which type it is.
+ bool isNull() const { return Val.isNull(); }
+ operator bool() const { return !isNull(); }
+
+ /// is<T>() return true if the Union currently holds the type matching T.
+ template<typename T>
+ int is() const {
+ // If T is PT1/PT2 choose InnerUnion1 otherwise choose InnerUnion2.
+ typedef typename
+ ::llvm::PointerUnionTypeSelector<PT1, T, InnerUnion1,
+ ::llvm::PointerUnionTypeSelector<PT2, T, InnerUnion1, InnerUnion2 >
+ >::Return Ty;
+ return Val.template is<Ty>() &&
+ Val.template get<Ty>().template is<T>();
+ }
+
+ /// get<T>() - Return the value of the specified pointer type. If the
+ /// specified pointer type is incorrect, assert.
+ template<typename T>
+ T get() const {
+ assert(is<T>() && "Invalid accessor called");
+ // If T is PT1/PT2 choose InnerUnion1 otherwise choose InnerUnion2.
+ typedef typename
+ ::llvm::PointerUnionTypeSelector<PT1, T, InnerUnion1,
+ ::llvm::PointerUnionTypeSelector<PT2, T, InnerUnion1, InnerUnion2 >
+ >::Return Ty;
+ return Val.template get<Ty>().template get<T>();
+ }
+
+ /// dyn_cast<T>() - If the current value is of the specified pointer type,
+ /// return it, otherwise return null.
+ template<typename T>
+ T dyn_cast() const {
+ if (is<T>()) return get<T>();
+ return T();
+ }
+
+ /// Assignment operators - Allow assigning into this union from either
+ /// pointer type, setting the discriminator to remember what it came from.
+ const PointerUnion4 &operator=(const PT1 &RHS) {
+ Val = InnerUnion1(RHS);
+ return *this;
+ }
+ const PointerUnion4 &operator=(const PT2 &RHS) {
+ Val = InnerUnion1(RHS);
+ return *this;
+ }
+ const PointerUnion4 &operator=(const PT3 &RHS) {
+ Val = InnerUnion2(RHS);
+ return *this;
+ }
+ const PointerUnion4 &operator=(const PT4 &RHS) {
+ Val = InnerUnion2(RHS);
+ return *this;
+ }
+
+ void *getOpaqueValue() const { return Val.getOpaqueValue(); }
+ static inline PointerUnion4 getFromOpaqueValue(void *VP) {
+ PointerUnion4 V;
+ V.Val = ValTy::getFromOpaqueValue(VP);
+ return V;
+ }
+ };
+
+ // Teach SmallPtrSet that PointerUnion4 is "basically a pointer", that has
+ // # low bits available = min(PT1bits,PT2bits,PT2bits)-2.
+ template<typename PT1, typename PT2, typename PT3, typename PT4>
+ class PointerLikeTypeTraits<PointerUnion4<PT1, PT2, PT3, PT4> > {
+ public:
+ static inline void *
+ getAsVoidPointer(const PointerUnion4<PT1, PT2, PT3, PT4> &P) {
+ return P.getOpaqueValue();
+ }
+ static inline PointerUnion4<PT1, PT2, PT3, PT4>
+ getFromVoidPointer(void *P) {
+ return PointerUnion4<PT1, PT2, PT3, PT4>::getFromOpaqueValue(P);
+ }
+
+ // The number of bits available are the min of the two pointer types.
+ enum {
+ NumLowBitsAvailable =
+ PointerLikeTypeTraits<typename PointerUnion4<PT1, PT2, PT3, PT4>::ValTy>
+ ::NumLowBitsAvailable
+ };
+ };
+}
+
+#endif
diff --git a/include/llvm/ADT/PostOrderIterator.h b/include/llvm/ADT/PostOrderIterator.h
new file mode 100644
index 00000000000..7f6350e4443
--- /dev/null
+++ b/include/llvm/ADT/PostOrderIterator.h
@@ -0,0 +1,279 @@
+//===- llvm/ADT/PostOrderIterator.h - PostOrder iterator --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file builds on the ADT/GraphTraits.h file to build a generic graph
+// post order iterator. This should work over any graph type that has a
+// GraphTraits specialization.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_POSTORDERITERATOR_H
+#define LLVM_ADT_POSTORDERITERATOR_H
+
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include <set>
+#include <vector>
+
+namespace llvm {
+
+// The po_iterator_storage template provides access to the set of already
+// visited nodes during the po_iterator's depth-first traversal.
+//
+// The default implementation simply contains a set of visited nodes, while
+// the Extended=true version uses a reference to an external set.
+//
+// It is possible to prune the depth-first traversal in several ways:
+//
+// - When providing an external set that already contains some graph nodes,
+// those nodes won't be visited again. This is useful for restarting a
+// post-order traversal on a graph with nodes that aren't dominated by a
+// single node.
+//
+// - By providing a custom SetType class, unwanted graph nodes can be excluded
+// by having the insert() function return false. This could for example
+// confine a CFG traversal to blocks in a specific loop.
+//
+// - Finally, by specializing the po_iterator_storage template itself, graph
+// edges can be pruned by returning false in the insertEdge() function. This
+// could be used to remove loop back-edges from the CFG seen by po_iterator.
+//
+// A specialized po_iterator_storage class can observe both the pre-order and
+// the post-order. The insertEdge() function is called in a pre-order, while
+// the finishPostorder() function is called just before the po_iterator moves
+// on to the next node.
+
+/// Default po_iterator_storage implementation with an internal set object.
+template<class SetType, bool External>
+class po_iterator_storage {
+ SetType Visited;
+public:
+ // Return true if edge destination should be visited.
+ template<typename NodeType>
+ bool insertEdge(NodeType *From, NodeType *To) {
+ return Visited.insert(To);
+ }
+
+ // Called after all children of BB have been visited.
+ template<typename NodeType>
+ void finishPostorder(NodeType *BB) {}
+};
+
+/// Specialization of po_iterator_storage that references an external set.
+template<class SetType>
+class po_iterator_storage<SetType, true> {
+ SetType &Visited;
+public:
+ po_iterator_storage(SetType &VSet) : Visited(VSet) {}
+ po_iterator_storage(const po_iterator_storage &S) : Visited(S.Visited) {}
+
+ // Return true if edge destination should be visited, called with From = 0 for
+ // the root node.
+ // Graph edges can be pruned by specializing this function.
+ template<class NodeType>
+ bool insertEdge(NodeType *From, NodeType *To) { return Visited.insert(To); }
+
+ // Called after all children of BB have been visited.
+ template<class NodeType>
+ void finishPostorder(NodeType *BB) {}
+};
+
+template<class GraphT,
+ class SetType = llvm::SmallPtrSet<typename GraphTraits<GraphT>::NodeType*, 8>,
+ bool ExtStorage = false,
+ class GT = GraphTraits<GraphT> >
+class po_iterator : public std::iterator<std::forward_iterator_tag,
+ typename GT::NodeType, ptrdiff_t>,
+ public po_iterator_storage<SetType, ExtStorage> {
+ typedef std::iterator<std::forward_iterator_tag,
+ typename GT::NodeType, ptrdiff_t> super;
+ typedef typename GT::NodeType NodeType;
+ typedef typename GT::ChildIteratorType ChildItTy;
+
+ // VisitStack - Used to maintain the ordering. Top = current block
+ // First element is basic block pointer, second is the 'next child' to visit
+ std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
+
+ void traverseChild() {
+ while (VisitStack.back().second != GT::child_end(VisitStack.back().first)) {
+ NodeType *BB = *VisitStack.back().second++;
+ if (this->insertEdge(VisitStack.back().first, BB)) {
+ // If the block is not visited...
+ VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
+ }
+ }
+ }
+
+ inline po_iterator(NodeType *BB) {
+ this->insertEdge((NodeType*)0, BB);
+ VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
+ traverseChild();
+ }
+ inline po_iterator() {} // End is when stack is empty.
+
+ inline po_iterator(NodeType *BB, SetType &S) :
+ po_iterator_storage<SetType, ExtStorage>(S) {
+ if (this->insertEdge((NodeType*)0, BB)) {
+ VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
+ traverseChild();
+ }
+ }
+
+ inline po_iterator(SetType &S) :
+ po_iterator_storage<SetType, ExtStorage>(S) {
+ } // End is when stack is empty.
+public:
+ typedef typename super::pointer pointer;
+ typedef po_iterator<GraphT, SetType, ExtStorage, GT> _Self;
+
+ // Provide static "constructors"...
+ static inline _Self begin(GraphT G) { return _Self(GT::getEntryNode(G)); }
+ static inline _Self end (GraphT G) { return _Self(); }
+
+ static inline _Self begin(GraphT G, SetType &S) {
+ return _Self(GT::getEntryNode(G), S);
+ }
+ static inline _Self end (GraphT G, SetType &S) { return _Self(S); }
+
+ inline bool operator==(const _Self& x) const {
+ return VisitStack == x.VisitStack;
+ }
+ inline bool operator!=(const _Self& x) const { return !operator==(x); }
+
+ inline pointer operator*() const {
+ return VisitStack.back().first;
+ }
+
+ // This is a nonstandard operator-> that dereferences the pointer an extra
+ // time... so that you can actually call methods ON the BasicBlock, because
+ // the contained type is a pointer. This allows BBIt->getTerminator() f.e.
+ //
+ inline NodeType *operator->() const { return operator*(); }
+
+ inline _Self& operator++() { // Preincrement
+ this->finishPostorder(VisitStack.back().first);
+ VisitStack.pop_back();
+ if (!VisitStack.empty())
+ traverseChild();
+ return *this;
+ }
+
+ inline _Self operator++(int) { // Postincrement
+ _Self tmp = *this; ++*this; return tmp;
+ }
+};
+
+// Provide global constructors that automatically figure out correct types...
+//
+template <class T>
+po_iterator<T> po_begin(T G) { return po_iterator<T>::begin(G); }
+template <class T>
+po_iterator<T> po_end (T G) { return po_iterator<T>::end(G); }
+
+// Provide global definitions of external postorder iterators...
+template<class T, class SetType=std::set<typename GraphTraits<T>::NodeType*> >
+struct po_ext_iterator : public po_iterator<T, SetType, true> {
+ po_ext_iterator(const po_iterator<T, SetType, true> &V) :
+ po_iterator<T, SetType, true>(V) {}
+};
+
+template<class T, class SetType>
+po_ext_iterator<T, SetType> po_ext_begin(T G, SetType &S) {
+ return po_ext_iterator<T, SetType>::begin(G, S);
+}
+
+template<class T, class SetType>
+po_ext_iterator<T, SetType> po_ext_end(T G, SetType &S) {
+ return po_ext_iterator<T, SetType>::end(G, S);
+}
+
+// Provide global definitions of inverse post order iterators...
+template <class T,
+ class SetType = std::set<typename GraphTraits<T>::NodeType*>,
+ bool External = false>
+struct ipo_iterator : public po_iterator<Inverse<T>, SetType, External > {
+ ipo_iterator(const po_iterator<Inverse<T>, SetType, External> &V) :
+ po_iterator<Inverse<T>, SetType, External> (V) {}
+};
+
+template <class T>
+ipo_iterator<T> ipo_begin(T G, bool Reverse = false) {
+ return ipo_iterator<T>::begin(G, Reverse);
+}
+
+template <class T>
+ipo_iterator<T> ipo_end(T G){
+ return ipo_iterator<T>::end(G);
+}
+
+// Provide global definitions of external inverse postorder iterators...
+template <class T,
+ class SetType = std::set<typename GraphTraits<T>::NodeType*> >
+struct ipo_ext_iterator : public ipo_iterator<T, SetType, true> {
+ ipo_ext_iterator(const ipo_iterator<T, SetType, true> &V) :
+ ipo_iterator<T, SetType, true>(V) {}
+ ipo_ext_iterator(const po_iterator<Inverse<T>, SetType, true> &V) :
+ ipo_iterator<T, SetType, true>(V) {}
+};
+
+template <class T, class SetType>
+ipo_ext_iterator<T, SetType> ipo_ext_begin(T G, SetType &S) {
+ return ipo_ext_iterator<T, SetType>::begin(G, S);
+}
+
+template <class T, class SetType>
+ipo_ext_iterator<T, SetType> ipo_ext_end(T G, SetType &S) {
+ return ipo_ext_iterator<T, SetType>::end(G, S);
+}
+
+//===--------------------------------------------------------------------===//
+// Reverse Post Order CFG iterator code
+//===--------------------------------------------------------------------===//
+//
+// This is used to visit basic blocks in a method in reverse post order. This
+// class is awkward to use because I don't know a good incremental algorithm to
+// computer RPO from a graph. Because of this, the construction of the
+// ReversePostOrderTraversal object is expensive (it must walk the entire graph
+// with a postorder iterator to build the data structures). The moral of this
+// story is: Don't create more ReversePostOrderTraversal classes than necessary.
+//
+// This class should be used like this:
+// {
+// ReversePostOrderTraversal<Function*> RPOT(FuncPtr); // Expensive to create
+// for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
+// ...
+// }
+// for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
+// ...
+// }
+// }
+//
+
+template<class GraphT, class GT = GraphTraits<GraphT> >
+class ReversePostOrderTraversal {
+ typedef typename GT::NodeType NodeType;
+ std::vector<NodeType*> Blocks; // Block list in normal PO order
+ inline void Initialize(NodeType *BB) {
+ copy(po_begin(BB), po_end(BB), back_inserter(Blocks));
+ }
+public:
+ typedef typename std::vector<NodeType*>::reverse_iterator rpo_iterator;
+
+ inline ReversePostOrderTraversal(GraphT G) {
+ Initialize(GT::getEntryNode(G));
+ }
+
+ // Because we want a reverse post order, use reverse iterators from the vector
+ inline rpo_iterator begin() { return Blocks.rbegin(); }
+ inline rpo_iterator end() { return Blocks.rend(); }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/PriorityQueue.h b/include/llvm/ADT/PriorityQueue.h
new file mode 100644
index 00000000000..bf8a6870816
--- /dev/null
+++ b/include/llvm/ADT/PriorityQueue.h
@@ -0,0 +1,84 @@
+//===- llvm/ADT/PriorityQueue.h - Priority queues ---------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the PriorityQueue class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_PRIORITY_QUEUE_H
+#define LLVM_ADT_PRIORITY_QUEUE_H
+
+#include <algorithm>
+#include <queue>
+
+namespace llvm {
+
+/// PriorityQueue - This class behaves like std::priority_queue and
+/// provides a few additional convenience functions.
+///
+template<class T,
+ class Sequence = std::vector<T>,
+ class Compare = std::less<typename Sequence::value_type> >
+class PriorityQueue : public std::priority_queue<T, Sequence, Compare> {
+public:
+ explicit PriorityQueue(const Compare &compare = Compare(),
+ const Sequence &sequence = Sequence())
+ : std::priority_queue<T, Sequence, Compare>(compare, sequence)
+ {}
+
+ template<class Iterator>
+ PriorityQueue(Iterator begin, Iterator end,
+ const Compare &compare = Compare(),
+ const Sequence &sequence = Sequence())
+ : std::priority_queue<T, Sequence, Compare>(begin, end, compare, sequence)
+ {}
+
+ /// erase_one - Erase one element from the queue, regardless of its
+ /// position. This operation performs a linear search to find an element
+ /// equal to t, but then uses all logarithmic-time algorithms to do
+ /// the erase operation.
+ ///
+ void erase_one(const T &t) {
+ // Linear-search to find the element.
+ typename Sequence::size_type i =
+ std::find(this->c.begin(), this->c.end(), t) - this->c.begin();
+
+ // Logarithmic-time heap bubble-up.
+ while (i != 0) {
+ typename Sequence::size_type parent = (i - 1) / 2;
+ this->c[i] = this->c[parent];
+ i = parent;
+ }
+
+ // The element we want to remove is now at the root, so we can use
+ // priority_queue's plain pop to remove it.
+ this->pop();
+ }
+
+ /// reheapify - If an element in the queue has changed in a way that
+ /// affects its standing in the comparison function, the queue's
+ /// internal state becomes invalid. Calling reheapify() resets the
+ /// queue's state, making it valid again. This operation has time
+ /// complexity proportional to the number of elements in the queue,
+ /// so don't plan to use it a lot.
+ ///
+ void reheapify() {
+ std::make_heap(this->c.begin(), this->c.end(), this->comp);
+ }
+
+ /// clear - Erase all elements from the queue.
+ ///
+ void clear() {
+ this->c.clear();
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/SCCIterator.h b/include/llvm/ADT/SCCIterator.h
new file mode 100644
index 00000000000..48436c66747
--- /dev/null
+++ b/include/llvm/ADT/SCCIterator.h
@@ -0,0 +1,220 @@
+//===---- ADT/SCCIterator.h - Strongly Connected Comp. Iter. ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected
+// components (SCCs) of a graph in O(N+E) time using Tarjan's DFS algorithm.
+//
+// The SCC iterator has the important property that if a node in SCC S1 has an
+// edge to a node in SCC S2, then it visits S1 *after* S2.
+//
+// To visit S1 *before* S2, use the scc_iterator on the Inverse graph.
+// (NOTE: This requires some simple wrappers and is not supported yet.)
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SCCITERATOR_H
+#define LLVM_ADT_SCCITERATOR_H
+
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/DenseMap.h"
+#include <vector>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+///
+/// scc_iterator - Enumerate the SCCs of a directed graph, in
+/// reverse topological order of the SCC DAG.
+///
+template<class GraphT, class GT = GraphTraits<GraphT> >
+class scc_iterator
+ : public std::iterator<std::forward_iterator_tag,
+ std::vector<typename GT::NodeType>, ptrdiff_t> {
+ typedef typename GT::NodeType NodeType;
+ typedef typename GT::ChildIteratorType ChildItTy;
+ typedef std::vector<NodeType*> SccTy;
+ typedef std::iterator<std::forward_iterator_tag,
+ std::vector<typename GT::NodeType>, ptrdiff_t> super;
+ typedef typename super::reference reference;
+ typedef typename super::pointer pointer;
+
+ // The visit counters used to detect when a complete SCC is on the stack.
+ // visitNum is the global counter.
+ // nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
+ unsigned visitNum;
+ DenseMap<NodeType *, unsigned> nodeVisitNumbers;
+
+ // SCCNodeStack - Stack holding nodes of the SCC.
+ std::vector<NodeType *> SCCNodeStack;
+
+ // CurrentSCC - The current SCC, retrieved using operator*().
+ SccTy CurrentSCC;
+
+ // VisitStack - Used to maintain the ordering. Top = current block
+ // First element is basic block pointer, second is the 'next child' to visit
+ std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
+
+ // MinVisitNumStack - Stack holding the "min" values for each node in the DFS.
+ // This is used to track the minimum uplink values for all children of
+ // the corresponding node on the VisitStack.
+ std::vector<unsigned> MinVisitNumStack;
+
+ // A single "visit" within the non-recursive DFS traversal.
+ void DFSVisitOne(NodeType *N) {
+ ++visitNum; // Global counter for the visit order
+ nodeVisitNumbers[N] = visitNum;
+ SCCNodeStack.push_back(N);
+ MinVisitNumStack.push_back(visitNum);
+ VisitStack.push_back(std::make_pair(N, GT::child_begin(N)));
+ //dbgs() << "TarjanSCC: Node " << N <<
+ // " : visitNum = " << visitNum << "\n";
+ }
+
+ // The stack-based DFS traversal; defined below.
+ void DFSVisitChildren() {
+ assert(!VisitStack.empty());
+ while (VisitStack.back().second != GT::child_end(VisitStack.back().first)) {
+ // TOS has at least one more child so continue DFS
+ NodeType *childN = *VisitStack.back().second++;
+ if (!nodeVisitNumbers.count(childN)) {
+ // this node has never been seen.
+ DFSVisitOne(childN);
+ continue;
+ }
+
+ unsigned childNum = nodeVisitNumbers[childN];
+ if (MinVisitNumStack.back() > childNum)
+ MinVisitNumStack.back() = childNum;
+ }
+ }
+
+ // Compute the next SCC using the DFS traversal.
+ void GetNextSCC() {
+ assert(VisitStack.size() == MinVisitNumStack.size());
+ CurrentSCC.clear(); // Prepare to compute the next SCC
+ while (!VisitStack.empty()) {
+ DFSVisitChildren();
+ assert(VisitStack.back().second ==GT::child_end(VisitStack.back().first));
+ NodeType *visitingN = VisitStack.back().first;
+ unsigned minVisitNum = MinVisitNumStack.back();
+ VisitStack.pop_back();
+ MinVisitNumStack.pop_back();
+ if (!MinVisitNumStack.empty() && MinVisitNumStack.back() > minVisitNum)
+ MinVisitNumStack.back() = minVisitNum;
+
+ //dbgs() << "TarjanSCC: Popped node " << visitingN <<
+ // " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
+ // nodeVisitNumbers[visitingN] << "\n";
+
+ if (minVisitNum != nodeVisitNumbers[visitingN])
+ continue;
+
+ // A full SCC is on the SCCNodeStack! It includes all nodes below
+ // visitingN on the stack. Copy those nodes to CurrentSCC,
+ // reset their minVisit values, and return (this suspends
+ // the DFS traversal till the next ++).
+ do {
+ CurrentSCC.push_back(SCCNodeStack.back());
+ SCCNodeStack.pop_back();
+ nodeVisitNumbers[CurrentSCC.back()] = ~0U;
+ } while (CurrentSCC.back() != visitingN);
+ return;
+ }
+ }
+
+ inline scc_iterator(NodeType *entryN) : visitNum(0) {
+ DFSVisitOne(entryN);
+ GetNextSCC();
+ }
+ inline scc_iterator() { /* End is when DFS stack is empty */ }
+
+public:
+ typedef scc_iterator<GraphT, GT> _Self;
+
+ // Provide static "constructors"...
+ static inline _Self begin(const GraphT &G){return _Self(GT::getEntryNode(G));}
+ static inline _Self end (const GraphT &) { return _Self(); }
+
+ // Direct loop termination test: I.isAtEnd() is more efficient than I == end()
+ inline bool isAtEnd() const {
+ assert(!CurrentSCC.empty() || VisitStack.empty());
+ return CurrentSCC.empty();
+ }
+
+ inline bool operator==(const _Self& x) const {
+ return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
+ }
+ inline bool operator!=(const _Self& x) const { return !operator==(x); }
+
+ // Iterator traversal: forward iteration only
+ inline _Self& operator++() { // Preincrement
+ GetNextSCC();
+ return *this;
+ }
+ inline _Self operator++(int) { // Postincrement
+ _Self tmp = *this; ++*this; return tmp;
+ }
+
+ // Retrieve a reference to the current SCC
+ inline const SccTy &operator*() const {
+ assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
+ return CurrentSCC;
+ }
+ inline SccTy &operator*() {
+ assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
+ return CurrentSCC;
+ }
+
+ // hasLoop() -- Test if the current SCC has a loop. If it has more than one
+ // node, this is trivially true. If not, it may still contain a loop if the
+ // node has an edge back to itself.
+ bool hasLoop() const {
+ assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
+ if (CurrentSCC.size() > 1) return true;
+ NodeType *N = CurrentSCC.front();
+ for (ChildItTy CI = GT::child_begin(N), CE=GT::child_end(N); CI != CE; ++CI)
+ if (*CI == N)
+ return true;
+ return false;
+ }
+
+ /// ReplaceNode - This informs the scc_iterator that the specified Old node
+ /// has been deleted, and New is to be used in its place.
+ void ReplaceNode(NodeType *Old, NodeType *New) {
+ assert(nodeVisitNumbers.count(Old) && "Old not in scc_iterator?");
+ nodeVisitNumbers[New] = nodeVisitNumbers[Old];
+ nodeVisitNumbers.erase(Old);
+ }
+};
+
+
+// Global constructor for the SCC iterator.
+template <class T>
+scc_iterator<T> scc_begin(const T &G) {
+ return scc_iterator<T>::begin(G);
+}
+
+template <class T>
+scc_iterator<T> scc_end(const T &G) {
+ return scc_iterator<T>::end(G);
+}
+
+template <class T>
+scc_iterator<Inverse<T> > scc_begin(const Inverse<T> &G) {
+ return scc_iterator<Inverse<T> >::begin(G);
+}
+
+template <class T>
+scc_iterator<Inverse<T> > scc_end(const Inverse<T> &G) {
+ return scc_iterator<Inverse<T> >::end(G);
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/STLExtras.h b/include/llvm/ADT/STLExtras.h
new file mode 100644
index 00000000000..aee500d4fb6
--- /dev/null
+++ b/include/llvm/ADT/STLExtras.h
@@ -0,0 +1,312 @@
+//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains some templates that are useful if you are working with the
+// STL at all.
+//
+// No library is required when using these functions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_STLEXTRAS_H
+#define LLVM_ADT_STLEXTRAS_H
+
+#include <cstddef> // for std::size_t
+#include <cstdlib> // for qsort
+#include <functional>
+#include <iterator>
+#include <utility> // for std::pair
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// Extra additions to <functional>
+//===----------------------------------------------------------------------===//
+
+template<class Ty>
+struct identity : public std::unary_function<Ty, Ty> {
+ Ty &operator()(Ty &self) const {
+ return self;
+ }
+ const Ty &operator()(const Ty &self) const {
+ return self;
+ }
+};
+
+template<class Ty>
+struct less_ptr : public std::binary_function<Ty, Ty, bool> {
+ bool operator()(const Ty* left, const Ty* right) const {
+ return *left < *right;
+ }
+};
+
+template<class Ty>
+struct greater_ptr : public std::binary_function<Ty, Ty, bool> {
+ bool operator()(const Ty* left, const Ty* right) const {
+ return *right < *left;
+ }
+};
+
+// deleter - Very very very simple method that is used to invoke operator
+// delete on something. It is used like this:
+//
+// for_each(V.begin(), B.end(), deleter<Interval>);
+//
+template <class T>
+inline void deleter(T *Ptr) {
+ delete Ptr;
+}
+
+
+
+//===----------------------------------------------------------------------===//
+// Extra additions to <iterator>
+//===----------------------------------------------------------------------===//
+
+// mapped_iterator - This is a simple iterator adapter that causes a function to
+// be dereferenced whenever operator* is invoked on the iterator.
+//
+template <class RootIt, class UnaryFunc>
+class mapped_iterator {
+ RootIt current;
+ UnaryFunc Fn;
+public:
+ typedef typename std::iterator_traits<RootIt>::iterator_category
+ iterator_category;
+ typedef typename std::iterator_traits<RootIt>::difference_type
+ difference_type;
+ typedef typename UnaryFunc::result_type value_type;
+
+ typedef void pointer;
+ //typedef typename UnaryFunc::result_type *pointer;
+ typedef void reference; // Can't modify value returned by fn
+
+ typedef RootIt iterator_type;
+ typedef mapped_iterator<RootIt, UnaryFunc> _Self;
+
+ inline const RootIt &getCurrent() const { return current; }
+ inline const UnaryFunc &getFunc() const { return Fn; }
+
+ inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
+ : current(I), Fn(F) {}
+ inline mapped_iterator(const mapped_iterator &It)
+ : current(It.current), Fn(It.Fn) {}
+
+ inline value_type operator*() const { // All this work to do this
+ return Fn(*current); // little change
+ }
+
+ _Self& operator++() { ++current; return *this; }
+ _Self& operator--() { --current; return *this; }
+ _Self operator++(int) { _Self __tmp = *this; ++current; return __tmp; }
+ _Self operator--(int) { _Self __tmp = *this; --current; return __tmp; }
+ _Self operator+ (difference_type n) const {
+ return _Self(current + n, Fn);
+ }
+ _Self& operator+= (difference_type n) { current += n; return *this; }
+ _Self operator- (difference_type n) const {
+ return _Self(current - n, Fn);
+ }
+ _Self& operator-= (difference_type n) { current -= n; return *this; }
+ reference operator[](difference_type n) const { return *(*this + n); }
+
+ inline bool operator!=(const _Self &X) const { return !operator==(X); }
+ inline bool operator==(const _Self &X) const { return current == X.current; }
+ inline bool operator< (const _Self &X) const { return current < X.current; }
+
+ inline difference_type operator-(const _Self &X) const {
+ return current - X.current;
+ }
+};
+
+template <class _Iterator, class Func>
+inline mapped_iterator<_Iterator, Func>
+operator+(typename mapped_iterator<_Iterator, Func>::difference_type N,
+ const mapped_iterator<_Iterator, Func>& X) {
+ return mapped_iterator<_Iterator, Func>(X.getCurrent() - N, X.getFunc());
+}
+
+
+// map_iterator - Provide a convenient way to create mapped_iterators, just like
+// make_pair is useful for creating pairs...
+//
+template <class ItTy, class FuncTy>
+inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
+ return mapped_iterator<ItTy, FuncTy>(I, F);
+}
+
+
+// next/prior - These functions unlike std::advance do not modify the
+// passed iterator but return a copy.
+//
+// next(myIt) returns copy of myIt incremented once
+// next(myIt, n) returns copy of myIt incremented n times
+// prior(myIt) returns copy of myIt decremented once
+// prior(myIt, n) returns copy of myIt decremented n times
+
+template <typename ItTy, typename Dist>
+inline ItTy next(ItTy it, Dist n)
+{
+ std::advance(it, n);
+ return it;
+}
+
+template <typename ItTy>
+inline ItTy next(ItTy it)
+{
+ return ++it;
+}
+
+template <typename ItTy, typename Dist>
+inline ItTy prior(ItTy it, Dist n)
+{
+ std::advance(it, -n);
+ return it;
+}
+
+template <typename ItTy>
+inline ItTy prior(ItTy it)
+{
+ return --it;
+}
+
+//===----------------------------------------------------------------------===//
+// Extra additions to <utility>
+//===----------------------------------------------------------------------===//
+
+// tie - this function ties two objects and returns a temporary object
+// that is assignable from a std::pair. This can be used to make code
+// more readable when using values returned from functions bundled in
+// a std::pair. Since an example is worth 1000 words:
+//
+// typedef std::map<int, int> Int2IntMap;
+//
+// Int2IntMap myMap;
+// Int2IntMap::iterator where;
+// bool inserted;
+// tie(where, inserted) = myMap.insert(std::make_pair(123,456));
+//
+// if (inserted)
+// // do stuff
+// else
+// // do other stuff
+template <typename T1, typename T2>
+struct tier {
+ typedef T1 &first_type;
+ typedef T2 &second_type;
+
+ first_type first;
+ second_type second;
+
+ tier(first_type f, second_type s) : first(f), second(s) { }
+ tier& operator=(const std::pair<T1, T2>& p) {
+ first = p.first;
+ second = p.second;
+ return *this;
+ }
+};
+
+template <typename T1, typename T2>
+inline tier<T1, T2> tie(T1& f, T2& s) {
+ return tier<T1, T2>(f, s);
+}
+
+//===----------------------------------------------------------------------===//
+// Extra additions for arrays
+//===----------------------------------------------------------------------===//
+
+/// Find where an array ends (for ending iterators)
+/// This returns a pointer to the byte immediately
+/// after the end of an array.
+template<class T, std::size_t N>
+inline T *array_endof(T (&x)[N]) {
+ return x+N;
+}
+
+/// Find the length of an array.
+template<class T, std::size_t N>
+inline size_t array_lengthof(T (&)[N]) {
+ return N;
+}
+
+/// array_pod_sort_comparator - This is helper function for array_pod_sort,
+/// which just uses operator< on T.
+template<typename T>
+inline int array_pod_sort_comparator(const void *P1, const void *P2) {
+ if (*reinterpret_cast<const T*>(P1) < *reinterpret_cast<const T*>(P2))
+ return -1;
+ if (*reinterpret_cast<const T*>(P2) < *reinterpret_cast<const T*>(P1))
+ return 1;
+ return 0;
+}
+
+/// get_array_pad_sort_comparator - This is an internal helper function used to
+/// get type deduction of T right.
+template<typename T>
+inline int (*get_array_pad_sort_comparator(const T &))
+ (const void*, const void*) {
+ return array_pod_sort_comparator<T>;
+}
+
+
+/// array_pod_sort - This sorts an array with the specified start and end
+/// extent. This is just like std::sort, except that it calls qsort instead of
+/// using an inlined template. qsort is slightly slower than std::sort, but
+/// most sorts are not performance critical in LLVM and std::sort has to be
+/// template instantiated for each type, leading to significant measured code
+/// bloat. This function should generally be used instead of std::sort where
+/// possible.
+///
+/// This function assumes that you have simple POD-like types that can be
+/// compared with operator< and can be moved with memcpy. If this isn't true,
+/// you should use std::sort.
+///
+/// NOTE: If qsort_r were portable, we could allow a custom comparator and
+/// default to std::less.
+template<class IteratorTy>
+inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
+ // Don't dereference start iterator of empty sequence.
+ if (Start == End) return;
+ qsort(&*Start, End-Start, sizeof(*Start),
+ get_array_pad_sort_comparator(*Start));
+}
+
+template<class IteratorTy>
+inline void array_pod_sort(IteratorTy Start, IteratorTy End,
+ int (*Compare)(const void*, const void*)) {
+ // Don't dereference start iterator of empty sequence.
+ if (Start == End) return;
+ qsort(&*Start, End-Start, sizeof(*Start), Compare);
+}
+
+//===----------------------------------------------------------------------===//
+// Extra additions to <algorithm>
+//===----------------------------------------------------------------------===//
+
+/// For a container of pointers, deletes the pointers and then clears the
+/// container.
+template<typename Container>
+void DeleteContainerPointers(Container &C) {
+ for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
+ delete *I;
+ C.clear();
+}
+
+/// In a container of pairs (usually a map) whose second element is a pointer,
+/// deletes the second elements and then clears the container.
+template<typename Container>
+void DeleteContainerSeconds(Container &C) {
+ for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
+ delete I->second;
+ C.clear();
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/ScopedHashTable.h b/include/llvm/ADT/ScopedHashTable.h
new file mode 100644
index 00000000000..efddd9f9b85
--- /dev/null
+++ b/include/llvm/ADT/ScopedHashTable.h
@@ -0,0 +1,256 @@
+//===- ScopedHashTable.h - A simple scoped hash table ---------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements an efficient scoped hash table, which is useful for
+// things like dominator-based optimizations. This allows clients to do things
+// like this:
+//
+// ScopedHashTable<int, int> HT;
+// {
+// ScopedHashTableScope<int, int> Scope1(HT);
+// HT.insert(0, 0);
+// HT.insert(1, 1);
+// {
+// ScopedHashTableScope<int, int> Scope2(HT);
+// HT.insert(0, 42);
+// }
+// }
+//
+// Looking up the value for "0" in the Scope2 block will return 42. Looking
+// up the value for 0 before 42 is inserted or after Scope2 is popped will
+// return 0.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SCOPEDHASHTABLE_H
+#define LLVM_ADT_SCOPEDHASHTABLE_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/Allocator.h"
+
+namespace llvm {
+
+template <typename K, typename V, typename KInfo = DenseMapInfo<K>,
+ typename AllocatorTy = MallocAllocator>
+class ScopedHashTable;
+
+template <typename K, typename V>
+class ScopedHashTableVal {
+ ScopedHashTableVal *NextInScope;
+ ScopedHashTableVal *NextForKey;
+ K Key;
+ V Val;
+ ScopedHashTableVal(const K &key, const V &val) : Key(key), Val(val) {}
+public:
+
+ const K &getKey() const { return Key; }
+ const V &getValue() const { return Val; }
+ V &getValue() { return Val; }
+
+ ScopedHashTableVal *getNextForKey() { return NextForKey; }
+ const ScopedHashTableVal *getNextForKey() const { return NextForKey; }
+ ScopedHashTableVal *getNextInScope() { return NextInScope; }
+
+ template <typename AllocatorTy>
+ static ScopedHashTableVal *Create(ScopedHashTableVal *nextInScope,
+ ScopedHashTableVal *nextForKey,
+ const K &key, const V &val,
+ AllocatorTy &Allocator) {
+ ScopedHashTableVal *New = Allocator.template Allocate<ScopedHashTableVal>();
+ // Set up the value.
+ new (New) ScopedHashTableVal(key, val);
+ New->NextInScope = nextInScope;
+ New->NextForKey = nextForKey;
+ return New;
+ }
+
+ template <typename AllocatorTy>
+ void Destroy(AllocatorTy &Allocator) {
+ // Free memory referenced by the item.
+ this->~ScopedHashTableVal();
+ Allocator.Deallocate(this);
+ }
+};
+
+template <typename K, typename V, typename KInfo = DenseMapInfo<K>,
+ typename AllocatorTy = MallocAllocator>
+class ScopedHashTableScope {
+ /// HT - The hashtable that we are active for.
+ ScopedHashTable<K, V, KInfo, AllocatorTy> &HT;
+
+ /// PrevScope - This is the scope that we are shadowing in HT.
+ ScopedHashTableScope *PrevScope;
+
+ /// LastValInScope - This is the last value that was inserted for this scope
+ /// or null if none have been inserted yet.
+ ScopedHashTableVal<K, V> *LastValInScope;
+ void operator=(ScopedHashTableScope&) LLVM_DELETED_FUNCTION;
+ ScopedHashTableScope(ScopedHashTableScope&) LLVM_DELETED_FUNCTION;
+public:
+ ScopedHashTableScope(ScopedHashTable<K, V, KInfo, AllocatorTy> &HT);
+ ~ScopedHashTableScope();
+
+ ScopedHashTableScope *getParentScope() { return PrevScope; }
+ const ScopedHashTableScope *getParentScope() const { return PrevScope; }
+
+private:
+ friend class ScopedHashTable<K, V, KInfo, AllocatorTy>;
+ ScopedHashTableVal<K, V> *getLastValInScope() {
+ return LastValInScope;
+ }
+ void setLastValInScope(ScopedHashTableVal<K, V> *Val) {
+ LastValInScope = Val;
+ }
+};
+
+
+template <typename K, typename V, typename KInfo = DenseMapInfo<K> >
+class ScopedHashTableIterator {
+ ScopedHashTableVal<K, V> *Node;
+public:
+ ScopedHashTableIterator(ScopedHashTableVal<K, V> *node) : Node(node) {}
+
+ V &operator*() const {
+ assert(Node && "Dereference end()");
+ return Node->getValue();
+ }
+ V *operator->() const {
+ return &Node->getValue();
+ }
+
+ bool operator==(const ScopedHashTableIterator &RHS) const {
+ return Node == RHS.Node;
+ }
+ bool operator!=(const ScopedHashTableIterator &RHS) const {
+ return Node != RHS.Node;
+ }
+
+ inline ScopedHashTableIterator& operator++() { // Preincrement
+ assert(Node && "incrementing past end()");
+ Node = Node->getNextForKey();
+ return *this;
+ }
+ ScopedHashTableIterator operator++(int) { // Postincrement
+ ScopedHashTableIterator tmp = *this; ++*this; return tmp;
+ }
+};
+
+
+template <typename K, typename V, typename KInfo, typename AllocatorTy>
+class ScopedHashTable {
+public:
+ /// ScopeTy - This is a helpful typedef that allows clients to get easy access
+ /// to the name of the scope for this hash table.
+ typedef ScopedHashTableScope<K, V, KInfo, AllocatorTy> ScopeTy;
+private:
+ typedef ScopedHashTableVal<K, V> ValTy;
+ DenseMap<K, ValTy*, KInfo> TopLevelMap;
+ ScopeTy *CurScope;
+
+ AllocatorTy Allocator;
+
+ ScopedHashTable(const ScopedHashTable&); // NOT YET IMPLEMENTED
+ void operator=(const ScopedHashTable&); // NOT YET IMPLEMENTED
+ friend class ScopedHashTableScope<K, V, KInfo, AllocatorTy>;
+public:
+ ScopedHashTable() : CurScope(0) {}
+ ScopedHashTable(AllocatorTy A) : CurScope(0), Allocator(A) {}
+ ~ScopedHashTable() {
+ assert(CurScope == 0 && TopLevelMap.empty() && "Scope imbalance!");
+ }
+
+
+ /// Access to the allocator.
+ typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
+ typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
+ AllocatorRefTy getAllocator() { return Allocator; }
+ AllocatorCRefTy getAllocator() const { return Allocator; }
+
+ bool count(const K &Key) const {
+ return TopLevelMap.count(Key);
+ }
+
+ V lookup(const K &Key) {
+ typename DenseMap<K, ValTy*, KInfo>::iterator I = TopLevelMap.find(Key);
+ if (I != TopLevelMap.end())
+ return I->second->getValue();
+
+ return V();
+ }
+
+ void insert(const K &Key, const V &Val) {
+ insertIntoScope(CurScope, Key, Val);
+ }
+
+ typedef ScopedHashTableIterator<K, V, KInfo> iterator;
+
+ iterator end() { return iterator(0); }
+
+ iterator begin(const K &Key) {
+ typename DenseMap<K, ValTy*, KInfo>::iterator I =
+ TopLevelMap.find(Key);
+ if (I == TopLevelMap.end()) return end();
+ return iterator(I->second);
+ }
+
+ ScopeTy *getCurScope() { return CurScope; }
+ const ScopeTy *getCurScope() const { return CurScope; }
+
+ /// insertIntoScope - This inserts the specified key/value at the specified
+ /// (possibly not the current) scope. While it is ok to insert into a scope
+ /// that isn't the current one, it isn't ok to insert *underneath* an existing
+ /// value of the specified key.
+ void insertIntoScope(ScopeTy *S, const K &Key, const V &Val) {
+ assert(S && "No scope active!");
+ ScopedHashTableVal<K, V> *&KeyEntry = TopLevelMap[Key];
+ KeyEntry = ValTy::Create(S->getLastValInScope(), KeyEntry, Key, Val,
+ Allocator);
+ S->setLastValInScope(KeyEntry);
+ }
+};
+
+/// ScopedHashTableScope ctor - Install this as the current scope for the hash
+/// table.
+template <typename K, typename V, typename KInfo, typename Allocator>
+ScopedHashTableScope<K, V, KInfo, Allocator>::
+ ScopedHashTableScope(ScopedHashTable<K, V, KInfo, Allocator> &ht) : HT(ht) {
+ PrevScope = HT.CurScope;
+ HT.CurScope = this;
+ LastValInScope = 0;
+}
+
+template <typename K, typename V, typename KInfo, typename Allocator>
+ScopedHashTableScope<K, V, KInfo, Allocator>::~ScopedHashTableScope() {
+ assert(HT.CurScope == this && "Scope imbalance!");
+ HT.CurScope = PrevScope;
+
+ // Pop and delete all values corresponding to this scope.
+ while (ScopedHashTableVal<K, V> *ThisEntry = LastValInScope) {
+ // Pop this value out of the TopLevelMap.
+ if (ThisEntry->getNextForKey() == 0) {
+ assert(HT.TopLevelMap[ThisEntry->getKey()] == ThisEntry &&
+ "Scope imbalance!");
+ HT.TopLevelMap.erase(ThisEntry->getKey());
+ } else {
+ ScopedHashTableVal<K, V> *&KeyEntry = HT.TopLevelMap[ThisEntry->getKey()];
+ assert(KeyEntry == ThisEntry && "Scope imbalance!");
+ KeyEntry = ThisEntry->getNextForKey();
+ }
+
+ // Pop this value out of the scope.
+ LastValInScope = ThisEntry->getNextInScope();
+
+ // Delete this entry.
+ ThisEntry->Destroy(HT.getAllocator());
+ }
+}
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/SetOperations.h b/include/llvm/ADT/SetOperations.h
new file mode 100644
index 00000000000..71f5db380f6
--- /dev/null
+++ b/include/llvm/ADT/SetOperations.h
@@ -0,0 +1,71 @@
+//===-- llvm/ADT/SetOperations.h - Generic Set Operations -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines generic set operations that may be used on set's of
+// different types, and different element types.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SETOPERATIONS_H
+#define LLVM_ADT_SETOPERATIONS_H
+
+namespace llvm {
+
+/// set_union(A, B) - Compute A := A u B, return whether A changed.
+///
+template <class S1Ty, class S2Ty>
+bool set_union(S1Ty &S1, const S2Ty &S2) {
+ bool Changed = false;
+
+ for (typename S2Ty::const_iterator SI = S2.begin(), SE = S2.end();
+ SI != SE; ++SI)
+ if (S1.insert(*SI).second)
+ Changed = true;
+
+ return Changed;
+}
+
+/// set_intersect(A, B) - Compute A := A ^ B
+/// Identical to set_intersection, except that it works on set<>'s and
+/// is nicer to use. Functionally, this iterates through S1, removing
+/// elements that are not contained in S2.
+///
+template <class S1Ty, class S2Ty>
+void set_intersect(S1Ty &S1, const S2Ty &S2) {
+ for (typename S1Ty::iterator I = S1.begin(); I != S1.end();) {
+ const typename S1Ty::key_type &E = *I;
+ ++I;
+ if (!S2.count(E)) S1.erase(E); // Erase element if not in S2
+ }
+}
+
+/// set_difference(A, B) - Return A - B
+///
+template <class S1Ty, class S2Ty>
+S1Ty set_difference(const S1Ty &S1, const S2Ty &S2) {
+ S1Ty Result;
+ for (typename S1Ty::const_iterator SI = S1.begin(), SE = S1.end();
+ SI != SE; ++SI)
+ if (!S2.count(*SI)) // if the element is not in set2
+ Result.insert(*SI);
+ return Result;
+}
+
+/// set_subtract(A, B) - Compute A := A - B
+///
+template <class S1Ty, class S2Ty>
+void set_subtract(S1Ty &S1, const S2Ty &S2) {
+ for (typename S2Ty::const_iterator SI = S2.begin(), SE = S2.end();
+ SI != SE; ++SI)
+ S1.erase(*SI);
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/SetVector.h b/include/llvm/ADT/SetVector.h
new file mode 100644
index 00000000000..965f0deacaa
--- /dev/null
+++ b/include/llvm/ADT/SetVector.h
@@ -0,0 +1,184 @@
+//===- llvm/ADT/SetVector.h - Set with insert order iteration ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements a set that has insertion order iteration
+// characteristics. This is useful for keeping a set of things that need to be
+// visited later but in a deterministic order (insertion order). The interface
+// is purposefully minimal.
+//
+// This file defines SetVector and SmallSetVector, which performs no allocations
+// if the SetVector has less than a certain number of elements.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SETVECTOR_H
+#define LLVM_ADT_SETVECTOR_H
+
+#include "llvm/ADT/SmallSet.h"
+#include <algorithm>
+#include <cassert>
+#include <vector>
+
+namespace llvm {
+
+/// This adapter class provides a way to keep a set of things that also has the
+/// property of a deterministic iteration order. The order of iteration is the
+/// order of insertion.
+/// @brief A vector that has set insertion semantics.
+template <typename T, typename Vector = std::vector<T>,
+ typename Set = SmallSet<T, 16> >
+class SetVector {
+public:
+ typedef T value_type;
+ typedef T key_type;
+ typedef T& reference;
+ typedef const T& const_reference;
+ typedef Set set_type;
+ typedef Vector vector_type;
+ typedef typename vector_type::const_iterator iterator;
+ typedef typename vector_type::const_iterator const_iterator;
+ typedef typename vector_type::size_type size_type;
+
+ /// @brief Construct an empty SetVector
+ SetVector() {}
+
+ /// @brief Initialize a SetVector with a range of elements
+ template<typename It>
+ SetVector(It Start, It End) {
+ insert(Start, End);
+ }
+
+ /// @brief Determine if the SetVector is empty or not.
+ bool empty() const {
+ return vector_.empty();
+ }
+
+ /// @brief Determine the number of elements in the SetVector.
+ size_type size() const {
+ return vector_.size();
+ }
+
+ /// @brief Get an iterator to the beginning of the SetVector.
+ iterator begin() {
+ return vector_.begin();
+ }
+
+ /// @brief Get a const_iterator to the beginning of the SetVector.
+ const_iterator begin() const {
+ return vector_.begin();
+ }
+
+ /// @brief Get an iterator to the end of the SetVector.
+ iterator end() {
+ return vector_.end();
+ }
+
+ /// @brief Get a const_iterator to the end of the SetVector.
+ const_iterator end() const {
+ return vector_.end();
+ }
+
+ /// @brief Return the last element of the SetVector.
+ const T &back() const {
+ assert(!empty() && "Cannot call back() on empty SetVector!");
+ return vector_.back();
+ }
+
+ /// @brief Index into the SetVector.
+ const_reference operator[](size_type n) const {
+ assert(n < vector_.size() && "SetVector access out of range!");
+ return vector_[n];
+ }
+
+ /// @returns true iff the element was inserted into the SetVector.
+ /// @brief Insert a new element into the SetVector.
+ bool insert(const value_type &X) {
+ bool result = set_.insert(X);
+ if (result)
+ vector_.push_back(X);
+ return result;
+ }
+
+ /// @brief Insert a range of elements into the SetVector.
+ template<typename It>
+ void insert(It Start, It End) {
+ for (; Start != End; ++Start)
+ if (set_.insert(*Start))
+ vector_.push_back(*Start);
+ }
+
+ /// @brief Remove an item from the set vector.
+ bool remove(const value_type& X) {
+ if (set_.erase(X)) {
+ typename vector_type::iterator I =
+ std::find(vector_.begin(), vector_.end(), X);
+ assert(I != vector_.end() && "Corrupted SetVector instances!");
+ vector_.erase(I);
+ return true;
+ }
+ return false;
+ }
+
+
+ /// @returns 0 if the element is not in the SetVector, 1 if it is.
+ /// @brief Count the number of elements of a given key in the SetVector.
+ size_type count(const key_type &key) const {
+ return set_.count(key);
+ }
+
+ /// @brief Completely clear the SetVector
+ void clear() {
+ set_.clear();
+ vector_.clear();
+ }
+
+ /// @brief Remove the last element of the SetVector.
+ void pop_back() {
+ assert(!empty() && "Cannot remove an element from an empty SetVector!");
+ set_.erase(back());
+ vector_.pop_back();
+ }
+
+ T pop_back_val() {
+ T Ret = back();
+ pop_back();
+ return Ret;
+ }
+
+ bool operator==(const SetVector &that) const {
+ return vector_ == that.vector_;
+ }
+
+ bool operator!=(const SetVector &that) const {
+ return vector_ != that.vector_;
+ }
+
+private:
+ set_type set_; ///< The set.
+ vector_type vector_; ///< The vector.
+};
+
+/// SmallSetVector - A SetVector that performs no allocations if smaller than
+/// a certain size.
+template <typename T, unsigned N>
+class SmallSetVector : public SetVector<T, SmallVector<T, N>, SmallSet<T, N> > {
+public:
+ SmallSetVector() {}
+
+ /// @brief Initialize a SmallSetVector with a range of elements
+ template<typename It>
+ SmallSetVector(It Start, It End) {
+ this->insert(Start, End);
+ }
+};
+
+} // End llvm namespace
+
+// vim: sw=2 ai
+#endif
diff --git a/include/llvm/ADT/SmallBitVector.h b/include/llvm/ADT/SmallBitVector.h
new file mode 100644
index 00000000000..7a645e0c724
--- /dev/null
+++ b/include/llvm/ADT/SmallBitVector.h
@@ -0,0 +1,544 @@
+//===- llvm/ADT/SmallBitVector.h - 'Normally small' bit vectors -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the SmallBitVector class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SMALLBITVECTOR_H
+#define LLVM_ADT_SMALLBITVECTOR_H
+
+#include "llvm/ADT/BitVector.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/MathExtras.h"
+#include <cassert>
+
+namespace llvm {
+
+/// SmallBitVector - This is a 'bitvector' (really, a variable-sized bit array),
+/// optimized for the case when the array is small. It contains one
+/// pointer-sized field, which is directly used as a plain collection of bits
+/// when possible, or as a pointer to a larger heap-allocated array when
+/// necessary. This allows normal "small" cases to be fast without losing
+/// generality for large inputs.
+///
+class SmallBitVector {
+ // TODO: In "large" mode, a pointer to a BitVector is used, leading to an
+ // unnecessary level of indirection. It would be more efficient to use a
+ // pointer to memory containing size, allocation size, and the array of bits.
+ uintptr_t X;
+
+ enum {
+ // The number of bits in this class.
+ NumBaseBits = sizeof(uintptr_t) * CHAR_BIT,
+
+ // One bit is used to discriminate between small and large mode. The
+ // remaining bits are used for the small-mode representation.
+ SmallNumRawBits = NumBaseBits - 1,
+
+ // A few more bits are used to store the size of the bit set in small mode.
+ // Theoretically this is a ceil-log2. These bits are encoded in the most
+ // significant bits of the raw bits.
+ SmallNumSizeBits = (NumBaseBits == 32 ? 5 :
+ NumBaseBits == 64 ? 6 :
+ SmallNumRawBits),
+
+ // The remaining bits are used to store the actual set in small mode.
+ SmallNumDataBits = SmallNumRawBits - SmallNumSizeBits
+ };
+
+public:
+ // Encapsulation of a single bit.
+ class reference {
+ SmallBitVector &TheVector;
+ unsigned BitPos;
+
+ public:
+ reference(SmallBitVector &b, unsigned Idx) : TheVector(b), BitPos(Idx) {}
+
+ reference& operator=(reference t) {
+ *this = bool(t);
+ return *this;
+ }
+
+ reference& operator=(bool t) {
+ if (t)
+ TheVector.set(BitPos);
+ else
+ TheVector.reset(BitPos);
+ return *this;
+ }
+
+ operator bool() const {
+ return const_cast<const SmallBitVector &>(TheVector).operator[](BitPos);
+ }
+ };
+
+private:
+ bool isSmall() const {
+ return X & uintptr_t(1);
+ }
+
+ BitVector *getPointer() const {
+ assert(!isSmall());
+ return reinterpret_cast<BitVector *>(X);
+ }
+
+ void switchToSmall(uintptr_t NewSmallBits, size_t NewSize) {
+ X = 1;
+ setSmallSize(NewSize);
+ setSmallBits(NewSmallBits);
+ }
+
+ void switchToLarge(BitVector *BV) {
+ X = reinterpret_cast<uintptr_t>(BV);
+ assert(!isSmall() && "Tried to use an unaligned pointer");
+ }
+
+ // Return all the bits used for the "small" representation; this includes
+ // bits for the size as well as the element bits.
+ uintptr_t getSmallRawBits() const {
+ assert(isSmall());
+ return X >> 1;
+ }
+
+ void setSmallRawBits(uintptr_t NewRawBits) {
+ assert(isSmall());
+ X = (NewRawBits << 1) | uintptr_t(1);
+ }
+
+ // Return the size.
+ size_t getSmallSize() const {
+ return getSmallRawBits() >> SmallNumDataBits;
+ }
+
+ void setSmallSize(size_t Size) {
+ setSmallRawBits(getSmallBits() | (Size << SmallNumDataBits));
+ }
+
+ // Return the element bits.
+ uintptr_t getSmallBits() const {
+ return getSmallRawBits() & ~(~uintptr_t(0) << getSmallSize());
+ }
+
+ void setSmallBits(uintptr_t NewBits) {
+ setSmallRawBits((NewBits & ~(~uintptr_t(0) << getSmallSize())) |
+ (getSmallSize() << SmallNumDataBits));
+ }
+
+public:
+ /// SmallBitVector default ctor - Creates an empty bitvector.
+ SmallBitVector() : X(1) {}
+
+ /// SmallBitVector ctor - Creates a bitvector of specified number of bits. All
+ /// bits are initialized to the specified value.
+ explicit SmallBitVector(unsigned s, bool t = false) {
+ if (s <= SmallNumDataBits)
+ switchToSmall(t ? ~uintptr_t(0) : 0, s);
+ else
+ switchToLarge(new BitVector(s, t));
+ }
+
+ /// SmallBitVector copy ctor.
+ SmallBitVector(const SmallBitVector &RHS) {
+ if (RHS.isSmall())
+ X = RHS.X;
+ else
+ switchToLarge(new BitVector(*RHS.getPointer()));
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ SmallBitVector(SmallBitVector &&RHS) : X(RHS.X) {
+ RHS.X = 1;
+ }
+#endif
+
+ ~SmallBitVector() {
+ if (!isSmall())
+ delete getPointer();
+ }
+
+ /// empty - Tests whether there are no bits in this bitvector.
+ bool empty() const {
+ return isSmall() ? getSmallSize() == 0 : getPointer()->empty();
+ }
+
+ /// size - Returns the number of bits in this bitvector.
+ size_t size() const {
+ return isSmall() ? getSmallSize() : getPointer()->size();
+ }
+
+ /// count - Returns the number of bits which are set.
+ unsigned count() const {
+ if (isSmall()) {
+ uintptr_t Bits = getSmallBits();
+ if (sizeof(uintptr_t) * CHAR_BIT == 32)
+ return CountPopulation_32(Bits);
+ if (sizeof(uintptr_t) * CHAR_BIT == 64)
+ return CountPopulation_64(Bits);
+ llvm_unreachable("Unsupported!");
+ }
+ return getPointer()->count();
+ }
+
+ /// any - Returns true if any bit is set.
+ bool any() const {
+ if (isSmall())
+ return getSmallBits() != 0;
+ return getPointer()->any();
+ }
+
+ /// all - Returns true if all bits are set.
+ bool all() const {
+ if (isSmall())
+ return getSmallBits() == (uintptr_t(1) << getSmallSize()) - 1;
+ return getPointer()->all();
+ }
+
+ /// none - Returns true if none of the bits are set.
+ bool none() const {
+ if (isSmall())
+ return getSmallBits() == 0;
+ return getPointer()->none();
+ }
+
+ /// find_first - Returns the index of the first set bit, -1 if none
+ /// of the bits are set.
+ int find_first() const {
+ if (isSmall()) {
+ uintptr_t Bits = getSmallBits();
+ if (Bits == 0)
+ return -1;
+ if (sizeof(uintptr_t) * CHAR_BIT == 32)
+ return CountTrailingZeros_32(Bits);
+ if (sizeof(uintptr_t) * CHAR_BIT == 64)
+ return CountTrailingZeros_64(Bits);
+ llvm_unreachable("Unsupported!");
+ }
+ return getPointer()->find_first();
+ }
+
+ /// find_next - Returns the index of the next set bit following the
+ /// "Prev" bit. Returns -1 if the next set bit is not found.
+ int find_next(unsigned Prev) const {
+ if (isSmall()) {
+ uintptr_t Bits = getSmallBits();
+ // Mask off previous bits.
+ Bits &= ~uintptr_t(0) << (Prev + 1);
+ if (Bits == 0 || Prev + 1 >= getSmallSize())
+ return -1;
+ if (sizeof(uintptr_t) * CHAR_BIT == 32)
+ return CountTrailingZeros_32(Bits);
+ if (sizeof(uintptr_t) * CHAR_BIT == 64)
+ return CountTrailingZeros_64(Bits);
+ llvm_unreachable("Unsupported!");
+ }
+ return getPointer()->find_next(Prev);
+ }
+
+ /// clear - Clear all bits.
+ void clear() {
+ if (!isSmall())
+ delete getPointer();
+ switchToSmall(0, 0);
+ }
+
+ /// resize - Grow or shrink the bitvector.
+ void resize(unsigned N, bool t = false) {
+ if (!isSmall()) {
+ getPointer()->resize(N, t);
+ } else if (SmallNumDataBits >= N) {
+ uintptr_t NewBits = t ? ~uintptr_t(0) << getSmallSize() : 0;
+ setSmallSize(N);
+ setSmallBits(NewBits | getSmallBits());
+ } else {
+ BitVector *BV = new BitVector(N, t);
+ uintptr_t OldBits = getSmallBits();
+ for (size_t i = 0, e = getSmallSize(); i != e; ++i)
+ (*BV)[i] = (OldBits >> i) & 1;
+ switchToLarge(BV);
+ }
+ }
+
+ void reserve(unsigned N) {
+ if (isSmall()) {
+ if (N > SmallNumDataBits) {
+ uintptr_t OldBits = getSmallRawBits();
+ size_t SmallSize = getSmallSize();
+ BitVector *BV = new BitVector(SmallSize);
+ for (size_t i = 0; i < SmallSize; ++i)
+ if ((OldBits >> i) & 1)
+ BV->set(i);
+ BV->reserve(N);
+ switchToLarge(BV);
+ }
+ } else {
+ getPointer()->reserve(N);
+ }
+ }
+
+ // Set, reset, flip
+ SmallBitVector &set() {
+ if (isSmall())
+ setSmallBits(~uintptr_t(0));
+ else
+ getPointer()->set();
+ return *this;
+ }
+
+ SmallBitVector &set(unsigned Idx) {
+ if (isSmall())
+ setSmallBits(getSmallBits() | (uintptr_t(1) << Idx));
+ else
+ getPointer()->set(Idx);
+ return *this;
+ }
+
+ SmallBitVector &reset() {
+ if (isSmall())
+ setSmallBits(0);
+ else
+ getPointer()->reset();
+ return *this;
+ }
+
+ SmallBitVector &reset(unsigned Idx) {
+ if (isSmall())
+ setSmallBits(getSmallBits() & ~(uintptr_t(1) << Idx));
+ else
+ getPointer()->reset(Idx);
+ return *this;
+ }
+
+ SmallBitVector &flip() {
+ if (isSmall())
+ setSmallBits(~getSmallBits());
+ else
+ getPointer()->flip();
+ return *this;
+ }
+
+ SmallBitVector &flip(unsigned Idx) {
+ if (isSmall())
+ setSmallBits(getSmallBits() ^ (uintptr_t(1) << Idx));
+ else
+ getPointer()->flip(Idx);
+ return *this;
+ }
+
+ // No argument flip.
+ SmallBitVector operator~() const {
+ return SmallBitVector(*this).flip();
+ }
+
+ // Indexing.
+ reference operator[](unsigned Idx) {
+ assert(Idx < size() && "Out-of-bounds Bit access.");
+ return reference(*this, Idx);
+ }
+
+ bool operator[](unsigned Idx) const {
+ assert(Idx < size() && "Out-of-bounds Bit access.");
+ if (isSmall())
+ return ((getSmallBits() >> Idx) & 1) != 0;
+ return getPointer()->operator[](Idx);
+ }
+
+ bool test(unsigned Idx) const {
+ return (*this)[Idx];
+ }
+
+ /// Test if any common bits are set.
+ bool anyCommon(const SmallBitVector &RHS) const {
+ if (isSmall() && RHS.isSmall())
+ return (getSmallBits() & RHS.getSmallBits()) != 0;
+ if (!isSmall() && !RHS.isSmall())
+ return getPointer()->anyCommon(*RHS.getPointer());
+
+ for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
+ if (test(i) && RHS.test(i))
+ return true;
+ return false;
+ }
+
+ // Comparison operators.
+ bool operator==(const SmallBitVector &RHS) const {
+ if (size() != RHS.size())
+ return false;
+ if (isSmall())
+ return getSmallBits() == RHS.getSmallBits();
+ else
+ return *getPointer() == *RHS.getPointer();
+ }
+
+ bool operator!=(const SmallBitVector &RHS) const {
+ return !(*this == RHS);
+ }
+
+ // Intersection, union, disjoint union.
+ SmallBitVector &operator&=(const SmallBitVector &RHS) {
+ resize(std::max(size(), RHS.size()));
+ if (isSmall())
+ setSmallBits(getSmallBits() & RHS.getSmallBits());
+ else if (!RHS.isSmall())
+ getPointer()->operator&=(*RHS.getPointer());
+ else {
+ SmallBitVector Copy = RHS;
+ Copy.resize(size());
+ getPointer()->operator&=(*Copy.getPointer());
+ }
+ return *this;
+ }
+
+ SmallBitVector &operator|=(const SmallBitVector &RHS) {
+ resize(std::max(size(), RHS.size()));
+ if (isSmall())
+ setSmallBits(getSmallBits() | RHS.getSmallBits());
+ else if (!RHS.isSmall())
+ getPointer()->operator|=(*RHS.getPointer());
+ else {
+ SmallBitVector Copy = RHS;
+ Copy.resize(size());
+ getPointer()->operator|=(*Copy.getPointer());
+ }
+ return *this;
+ }
+
+ SmallBitVector &operator^=(const SmallBitVector &RHS) {
+ resize(std::max(size(), RHS.size()));
+ if (isSmall())
+ setSmallBits(getSmallBits() ^ RHS.getSmallBits());
+ else if (!RHS.isSmall())
+ getPointer()->operator^=(*RHS.getPointer());
+ else {
+ SmallBitVector Copy = RHS;
+ Copy.resize(size());
+ getPointer()->operator^=(*Copy.getPointer());
+ }
+ return *this;
+ }
+
+ // Assignment operator.
+ const SmallBitVector &operator=(const SmallBitVector &RHS) {
+ if (isSmall()) {
+ if (RHS.isSmall())
+ X = RHS.X;
+ else
+ switchToLarge(new BitVector(*RHS.getPointer()));
+ } else {
+ if (!RHS.isSmall())
+ *getPointer() = *RHS.getPointer();
+ else {
+ delete getPointer();
+ X = RHS.X;
+ }
+ }
+ return *this;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ const SmallBitVector &operator=(SmallBitVector &&RHS) {
+ if (this != &RHS) {
+ clear();
+ swap(RHS);
+ }
+ return *this;
+ }
+#endif
+
+ void swap(SmallBitVector &RHS) {
+ std::swap(X, RHS.X);
+ }
+
+ /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
+ /// This computes "*this |= Mask".
+ void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
+ if (isSmall())
+ applyMask<true, false>(Mask, MaskWords);
+ else
+ getPointer()->setBitsInMask(Mask, MaskWords);
+ }
+
+ /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
+ /// Don't resize. This computes "*this &= ~Mask".
+ void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
+ if (isSmall())
+ applyMask<false, false>(Mask, MaskWords);
+ else
+ getPointer()->clearBitsInMask(Mask, MaskWords);
+ }
+
+ /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
+ /// Don't resize. This computes "*this |= ~Mask".
+ void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
+ if (isSmall())
+ applyMask<true, true>(Mask, MaskWords);
+ else
+ getPointer()->setBitsNotInMask(Mask, MaskWords);
+ }
+
+ /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
+ /// Don't resize. This computes "*this &= Mask".
+ void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
+ if (isSmall())
+ applyMask<false, true>(Mask, MaskWords);
+ else
+ getPointer()->clearBitsNotInMask(Mask, MaskWords);
+ }
+
+private:
+ template<bool AddBits, bool InvertMask>
+ void applyMask(const uint32_t *Mask, unsigned MaskWords) {
+ assert((NumBaseBits == 64 || NumBaseBits == 32) && "Unsupported word size");
+ if (NumBaseBits == 64 && MaskWords >= 2) {
+ uint64_t M = Mask[0] | (uint64_t(Mask[1]) << 32);
+ if (InvertMask) M = ~M;
+ if (AddBits) setSmallBits(getSmallBits() | M);
+ else setSmallBits(getSmallBits() & ~M);
+ } else {
+ uint32_t M = Mask[0];
+ if (InvertMask) M = ~M;
+ if (AddBits) setSmallBits(getSmallBits() | M);
+ else setSmallBits(getSmallBits() & ~M);
+ }
+ }
+};
+
+inline SmallBitVector
+operator&(const SmallBitVector &LHS, const SmallBitVector &RHS) {
+ SmallBitVector Result(LHS);
+ Result &= RHS;
+ return Result;
+}
+
+inline SmallBitVector
+operator|(const SmallBitVector &LHS, const SmallBitVector &RHS) {
+ SmallBitVector Result(LHS);
+ Result |= RHS;
+ return Result;
+}
+
+inline SmallBitVector
+operator^(const SmallBitVector &LHS, const SmallBitVector &RHS) {
+ SmallBitVector Result(LHS);
+ Result ^= RHS;
+ return Result;
+}
+
+} // End llvm namespace
+
+namespace std {
+ /// Implement std::swap in terms of BitVector swap.
+ inline void
+ swap(llvm::SmallBitVector &LHS, llvm::SmallBitVector &RHS) {
+ LHS.swap(RHS);
+ }
+}
+
+#endif
diff --git a/include/llvm/ADT/SmallPtrSet.h b/include/llvm/ADT/SmallPtrSet.h
new file mode 100644
index 00000000000..3bb883088c5
--- /dev/null
+++ b/include/llvm/ADT/SmallPtrSet.h
@@ -0,0 +1,308 @@
+//===- llvm/ADT/SmallPtrSet.h - 'Normally small' pointer set ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the SmallPtrSet class. See the doxygen comment for
+// SmallPtrSetImpl for more details on the algorithm used.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SMALLPTRSET_H
+#define LLVM_ADT_SMALLPTRSET_H
+
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/PointerLikeTypeTraits.h"
+#include <cassert>
+#include <cstddef>
+#include <cstring>
+#include <iterator>
+
+namespace llvm {
+
+class SmallPtrSetIteratorImpl;
+
+/// SmallPtrSetImpl - This is the common code shared among all the
+/// SmallPtrSet<>'s, which is almost everything. SmallPtrSet has two modes, one
+/// for small and one for large sets.
+///
+/// Small sets use an array of pointers allocated in the SmallPtrSet object,
+/// which is treated as a simple array of pointers. When a pointer is added to
+/// the set, the array is scanned to see if the element already exists, if not
+/// the element is 'pushed back' onto the array. If we run out of space in the
+/// array, we grow into the 'large set' case. SmallSet should be used when the
+/// sets are often small. In this case, no memory allocation is used, and only
+/// light-weight and cache-efficient scanning is used.
+///
+/// Large sets use a classic exponentially-probed hash table. Empty buckets are
+/// represented with an illegal pointer value (-1) to allow null pointers to be
+/// inserted. Tombstones are represented with another illegal pointer value
+/// (-2), to allow deletion. The hash table is resized when the table is 3/4 or
+/// more. When this happens, the table is doubled in size.
+///
+class SmallPtrSetImpl {
+ friend class SmallPtrSetIteratorImpl;
+protected:
+ /// SmallArray - Points to a fixed size set of buckets, used in 'small mode'.
+ const void **SmallArray;
+ /// CurArray - This is the current set of buckets. If equal to SmallArray,
+ /// then the set is in 'small mode'.
+ const void **CurArray;
+ /// CurArraySize - The allocated size of CurArray, always a power of two.
+ /// Note that CurArray points to an array that has CurArraySize+1 elements in
+ /// it, so that the end iterator actually points to valid memory.
+ unsigned CurArraySize;
+
+ // If small, this is # elts allocated consecutively
+ unsigned NumElements;
+ unsigned NumTombstones;
+
+ // Helper to copy construct a SmallPtrSet.
+ SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl& that);
+ explicit SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize) :
+ SmallArray(SmallStorage), CurArray(SmallStorage), CurArraySize(SmallSize) {
+ assert(SmallSize && (SmallSize & (SmallSize-1)) == 0 &&
+ "Initial size must be a power of two!");
+ // The end pointer, always valid, is set to a valid element to help the
+ // iterator.
+ CurArray[SmallSize] = 0;
+ clear();
+ }
+ ~SmallPtrSetImpl();
+
+public:
+ bool empty() const { return size() == 0; }
+ unsigned size() const { return NumElements; }
+
+ void clear() {
+ // If the capacity of the array is huge, and the # elements used is small,
+ // shrink the array.
+ if (!isSmall() && NumElements*4 < CurArraySize && CurArraySize > 32)
+ return shrink_and_clear();
+
+ // Fill the array with empty markers.
+ memset(CurArray, -1, CurArraySize*sizeof(void*));
+ NumElements = 0;
+ NumTombstones = 0;
+ }
+
+protected:
+ static void *getTombstoneMarker() { return reinterpret_cast<void*>(-2); }
+ static void *getEmptyMarker() {
+ // Note that -1 is chosen to make clear() efficiently implementable with
+ // memset and because it's not a valid pointer value.
+ return reinterpret_cast<void*>(-1);
+ }
+
+ /// insert_imp - This returns true if the pointer was new to the set, false if
+ /// it was already in the set. This is hidden from the client so that the
+ /// derived class can check that the right type of pointer is passed in.
+ bool insert_imp(const void * Ptr);
+
+ /// erase_imp - If the set contains the specified pointer, remove it and
+ /// return true, otherwise return false. This is hidden from the client so
+ /// that the derived class can check that the right type of pointer is passed
+ /// in.
+ bool erase_imp(const void * Ptr);
+
+ bool count_imp(const void * Ptr) const {
+ if (isSmall()) {
+ // Linear search for the item.
+ for (const void *const *APtr = SmallArray,
+ *const *E = SmallArray+NumElements; APtr != E; ++APtr)
+ if (*APtr == Ptr)
+ return true;
+ return false;
+ }
+
+ // Big set case.
+ return *FindBucketFor(Ptr) == Ptr;
+ }
+
+private:
+ bool isSmall() const { return CurArray == SmallArray; }
+
+ const void * const *FindBucketFor(const void *Ptr) const;
+ void shrink_and_clear();
+
+ /// Grow - Allocate a larger backing store for the buckets and move it over.
+ void Grow(unsigned NewSize);
+
+ void operator=(const SmallPtrSetImpl &RHS) LLVM_DELETED_FUNCTION;
+protected:
+ /// swap - Swaps the elements of two sets.
+ /// Note: This method assumes that both sets have the same small size.
+ void swap(SmallPtrSetImpl &RHS);
+
+ void CopyFrom(const SmallPtrSetImpl &RHS);
+};
+
+/// SmallPtrSetIteratorImpl - This is the common base class shared between all
+/// instances of SmallPtrSetIterator.
+class SmallPtrSetIteratorImpl {
+protected:
+ const void *const *Bucket;
+public:
+ explicit SmallPtrSetIteratorImpl(const void *const *BP) : Bucket(BP) {
+ AdvanceIfNotValid();
+ }
+
+ bool operator==(const SmallPtrSetIteratorImpl &RHS) const {
+ return Bucket == RHS.Bucket;
+ }
+ bool operator!=(const SmallPtrSetIteratorImpl &RHS) const {
+ return Bucket != RHS.Bucket;
+ }
+
+protected:
+ /// AdvanceIfNotValid - If the current bucket isn't valid, advance to a bucket
+ /// that is. This is guaranteed to stop because the end() bucket is marked
+ /// valid.
+ void AdvanceIfNotValid() {
+ while (*Bucket == SmallPtrSetImpl::getEmptyMarker() ||
+ *Bucket == SmallPtrSetImpl::getTombstoneMarker())
+ ++Bucket;
+ }
+};
+
+/// SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
+template<typename PtrTy>
+class SmallPtrSetIterator : public SmallPtrSetIteratorImpl {
+ typedef PointerLikeTypeTraits<PtrTy> PtrTraits;
+
+public:
+ typedef PtrTy value_type;
+ typedef PtrTy reference;
+ typedef PtrTy pointer;
+ typedef std::ptrdiff_t difference_type;
+ typedef std::forward_iterator_tag iterator_category;
+
+ explicit SmallPtrSetIterator(const void *const *BP)
+ : SmallPtrSetIteratorImpl(BP) {}
+
+ // Most methods provided by baseclass.
+
+ const PtrTy operator*() const {
+ return PtrTraits::getFromVoidPointer(const_cast<void*>(*Bucket));
+ }
+
+ inline SmallPtrSetIterator& operator++() { // Preincrement
+ ++Bucket;
+ AdvanceIfNotValid();
+ return *this;
+ }
+
+ SmallPtrSetIterator operator++(int) { // Postincrement
+ SmallPtrSetIterator tmp = *this; ++*this; return tmp;
+ }
+};
+
+/// RoundUpToPowerOfTwo - This is a helper template that rounds N up to the next
+/// power of two (which means N itself if N is already a power of two).
+template<unsigned N>
+struct RoundUpToPowerOfTwo;
+
+/// RoundUpToPowerOfTwoH - If N is not a power of two, increase it. This is a
+/// helper template used to implement RoundUpToPowerOfTwo.
+template<unsigned N, bool isPowerTwo>
+struct RoundUpToPowerOfTwoH {
+ enum { Val = N };
+};
+template<unsigned N>
+struct RoundUpToPowerOfTwoH<N, false> {
+ enum {
+ // We could just use NextVal = N+1, but this converges faster. N|(N-1) sets
+ // the right-most zero bits to one all at once, e.g. 0b0011000 -> 0b0011111.
+ Val = RoundUpToPowerOfTwo<(N|(N-1)) + 1>::Val
+ };
+};
+
+template<unsigned N>
+struct RoundUpToPowerOfTwo {
+ enum { Val = RoundUpToPowerOfTwoH<N, (N&(N-1)) == 0>::Val };
+};
+
+
+/// SmallPtrSet - This class implements a set which is optimized for holding
+/// SmallSize or less elements. This internally rounds up SmallSize to the next
+/// power of two if it is not already a power of two. See the comments above
+/// SmallPtrSetImpl for details of the algorithm.
+template<class PtrType, unsigned SmallSize>
+class SmallPtrSet : public SmallPtrSetImpl {
+ // Make sure that SmallSize is a power of two, round up if not.
+ enum { SmallSizePowTwo = RoundUpToPowerOfTwo<SmallSize>::Val };
+ /// SmallStorage - Fixed size storage used in 'small mode'. The extra element
+ /// ensures that the end iterator actually points to valid memory.
+ const void *SmallStorage[SmallSizePowTwo+1];
+ typedef PointerLikeTypeTraits<PtrType> PtrTraits;
+public:
+ SmallPtrSet() : SmallPtrSetImpl(SmallStorage, SmallSizePowTwo) {}
+ SmallPtrSet(const SmallPtrSet &that) : SmallPtrSetImpl(SmallStorage, that) {}
+
+ template<typename It>
+ SmallPtrSet(It I, It E) : SmallPtrSetImpl(SmallStorage, SmallSizePowTwo) {
+ insert(I, E);
+ }
+
+ /// insert - This returns true if the pointer was new to the set, false if it
+ /// was already in the set.
+ bool insert(PtrType Ptr) {
+ return insert_imp(PtrTraits::getAsVoidPointer(Ptr));
+ }
+
+ /// erase - If the set contains the specified pointer, remove it and return
+ /// true, otherwise return false.
+ bool erase(PtrType Ptr) {
+ return erase_imp(PtrTraits::getAsVoidPointer(Ptr));
+ }
+
+ /// count - Return true if the specified pointer is in the set.
+ bool count(PtrType Ptr) const {
+ return count_imp(PtrTraits::getAsVoidPointer(Ptr));
+ }
+
+ template <typename IterT>
+ void insert(IterT I, IterT E) {
+ for (; I != E; ++I)
+ insert(*I);
+ }
+
+ typedef SmallPtrSetIterator<PtrType> iterator;
+ typedef SmallPtrSetIterator<PtrType> const_iterator;
+ inline iterator begin() const {
+ return iterator(CurArray);
+ }
+ inline iterator end() const {
+ return iterator(CurArray+CurArraySize);
+ }
+
+ // Allow assignment from any smallptrset with the same element type even if it
+ // doesn't have the same smallsize.
+ const SmallPtrSet<PtrType, SmallSize>&
+ operator=(const SmallPtrSet<PtrType, SmallSize> &RHS) {
+ CopyFrom(RHS);
+ return *this;
+ }
+
+ /// swap - Swaps the elements of two sets.
+ void swap(SmallPtrSet<PtrType, SmallSize> &RHS) {
+ SmallPtrSetImpl::swap(RHS);
+ }
+};
+
+}
+
+namespace std {
+ /// Implement std::swap in terms of SmallPtrSet swap.
+ template<class T, unsigned N>
+ inline void swap(llvm::SmallPtrSet<T, N> &LHS, llvm::SmallPtrSet<T, N> &RHS) {
+ LHS.swap(RHS);
+ }
+}
+
+#endif
diff --git a/include/llvm/ADT/SmallSet.h b/include/llvm/ADT/SmallSet.h
new file mode 100644
index 00000000000..cd117f59ba7
--- /dev/null
+++ b/include/llvm/ADT/SmallSet.h
@@ -0,0 +1,118 @@
+//===- llvm/ADT/SmallSet.h - 'Normally small' sets --------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the SmallSet class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SMALLSET_H
+#define LLVM_ADT_SMALLSET_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include <set>
+
+namespace llvm {
+
+/// SmallSet - This maintains a set of unique values, optimizing for the case
+/// when the set is small (less than N). In this case, the set can be
+/// maintained with no mallocs. If the set gets large, we expand to using an
+/// std::set to maintain reasonable lookup times.
+///
+/// Note that this set does not provide a way to iterate over members in the
+/// set.
+template <typename T, unsigned N, typename C = std::less<T> >
+class SmallSet {
+ /// Use a SmallVector to hold the elements here (even though it will never
+ /// reach its 'large' stage) to avoid calling the default ctors of elements
+ /// we will never use.
+ SmallVector<T, N> Vector;
+ std::set<T, C> Set;
+ typedef typename SmallVector<T, N>::const_iterator VIterator;
+ typedef typename SmallVector<T, N>::iterator mutable_iterator;
+public:
+ SmallSet() {}
+
+ bool empty() const { return Vector.empty() && Set.empty(); }
+ unsigned size() const {
+ return isSmall() ? Vector.size() : Set.size();
+ }
+
+ /// count - Return true if the element is in the set.
+ bool count(const T &V) const {
+ if (isSmall()) {
+ // Since the collection is small, just do a linear search.
+ return vfind(V) != Vector.end();
+ } else {
+ return Set.count(V);
+ }
+ }
+
+ /// insert - Insert an element into the set if it isn't already there.
+ bool insert(const T &V) {
+ if (!isSmall())
+ return Set.insert(V).second;
+
+ VIterator I = vfind(V);
+ if (I != Vector.end()) // Don't reinsert if it already exists.
+ return false;
+ if (Vector.size() < N) {
+ Vector.push_back(V);
+ return true;
+ }
+
+ // Otherwise, grow from vector to set.
+ while (!Vector.empty()) {
+ Set.insert(Vector.back());
+ Vector.pop_back();
+ }
+ Set.insert(V);
+ return true;
+ }
+
+ template <typename IterT>
+ void insert(IterT I, IterT E) {
+ for (; I != E; ++I)
+ insert(*I);
+ }
+
+ bool erase(const T &V) {
+ if (!isSmall())
+ return Set.erase(V);
+ for (mutable_iterator I = Vector.begin(), E = Vector.end(); I != E; ++I)
+ if (*I == V) {
+ Vector.erase(I);
+ return true;
+ }
+ return false;
+ }
+
+ void clear() {
+ Vector.clear();
+ Set.clear();
+ }
+private:
+ bool isSmall() const { return Set.empty(); }
+
+ VIterator vfind(const T &V) const {
+ for (VIterator I = Vector.begin(), E = Vector.end(); I != E; ++I)
+ if (*I == V)
+ return I;
+ return Vector.end();
+ }
+};
+
+/// If this set is of pointer values, transparently switch over to using
+/// SmallPtrSet for performance.
+template <typename PointeeType, unsigned N>
+class SmallSet<PointeeType*, N> : public SmallPtrSet<PointeeType*, N> {};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/SmallString.h b/include/llvm/ADT/SmallString.h
new file mode 100644
index 00000000000..8da99d1c125
--- /dev/null
+++ b/include/llvm/ADT/SmallString.h
@@ -0,0 +1,300 @@
+//===- llvm/ADT/SmallString.h - 'Normally small' strings --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the SmallString class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SMALLSTRING_H
+#define LLVM_ADT_SMALLSTRING_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+
+/// SmallString - A SmallString is just a SmallVector with methods and accessors
+/// that make it work better as a string (e.g. operator+ etc).
+template<unsigned InternalLen>
+class SmallString : public SmallVector<char, InternalLen> {
+public:
+ /// Default ctor - Initialize to empty.
+ SmallString() {}
+
+ /// Initialize from a StringRef.
+ SmallString(StringRef S) : SmallVector<char, InternalLen>(S.begin(), S.end()) {}
+
+ /// Initialize with a range.
+ template<typename ItTy>
+ SmallString(ItTy S, ItTy E) : SmallVector<char, InternalLen>(S, E) {}
+
+ /// Copy ctor.
+ SmallString(const SmallString &RHS) : SmallVector<char, InternalLen>(RHS) {}
+
+ // Note that in order to add new overloads for append & assign, we have to
+ // duplicate the inherited versions so as not to inadvertently hide them.
+
+ /// @}
+ /// @name String Assignment
+ /// @{
+
+ /// Assign from a repeated element.
+ void assign(size_t NumElts, char Elt) {
+ this->SmallVectorImpl<char>::assign(NumElts, Elt);
+ }
+
+ /// Assign from an iterator pair.
+ template<typename in_iter>
+ void assign(in_iter S, in_iter E) {
+ this->clear();
+ SmallVectorImpl<char>::append(S, E);
+ }
+
+ /// Assign from a StringRef.
+ void assign(StringRef RHS) {
+ this->clear();
+ SmallVectorImpl<char>::append(RHS.begin(), RHS.end());
+ }
+
+ /// Assign from a SmallVector.
+ void assign(const SmallVectorImpl<char> &RHS) {
+ this->clear();
+ SmallVectorImpl<char>::append(RHS.begin(), RHS.end());
+ }
+
+ /// @}
+ /// @name String Concatenation
+ /// @{
+
+ /// Append from an iterator pair.
+ template<typename in_iter>
+ void append(in_iter S, in_iter E) {
+ SmallVectorImpl<char>::append(S, E);
+ }
+
+ void append(size_t NumInputs, char Elt) {
+ SmallVectorImpl<char>::append(NumInputs, Elt);
+ }
+
+
+ /// Append from a StringRef.
+ void append(StringRef RHS) {
+ SmallVectorImpl<char>::append(RHS.begin(), RHS.end());
+ }
+
+ /// Append from a SmallVector.
+ void append(const SmallVectorImpl<char> &RHS) {
+ SmallVectorImpl<char>::append(RHS.begin(), RHS.end());
+ }
+
+ /// @}
+ /// @name String Comparison
+ /// @{
+
+ /// Check for string equality. This is more efficient than compare() when
+ /// the relative ordering of inequal strings isn't needed.
+ bool equals(StringRef RHS) const {
+ return str().equals(RHS);
+ }
+
+ /// Check for string equality, ignoring case.
+ bool equals_lower(StringRef RHS) const {
+ return str().equals_lower(RHS);
+ }
+
+ /// Compare two strings; the result is -1, 0, or 1 if this string is
+ /// lexicographically less than, equal to, or greater than the \p RHS.
+ int compare(StringRef RHS) const {
+ return str().compare(RHS);
+ }
+
+ /// compare_lower - Compare two strings, ignoring case.
+ int compare_lower(StringRef RHS) const {
+ return str().compare_lower(RHS);
+ }
+
+ /// compare_numeric - Compare two strings, treating sequences of digits as
+ /// numbers.
+ int compare_numeric(StringRef RHS) const {
+ return str().compare_numeric(RHS);
+ }
+
+ /// @}
+ /// @name String Predicates
+ /// @{
+
+ /// startswith - Check if this string starts with the given \p Prefix.
+ bool startswith(StringRef Prefix) const {
+ return str().startswith(Prefix);
+ }
+
+ /// endswith - Check if this string ends with the given \p Suffix.
+ bool endswith(StringRef Suffix) const {
+ return str().endswith(Suffix);
+ }
+
+ /// @}
+ /// @name String Searching
+ /// @{
+
+ /// find - Search for the first character \p C in the string.
+ ///
+ /// \return - The index of the first occurrence of \p C, or npos if not
+ /// found.
+ size_t find(char C, size_t From = 0) const {
+ return str().find(C, From);
+ }
+
+ /// Search for the first string \p Str in the string.
+ ///
+ /// \returns The index of the first occurrence of \p Str, or npos if not
+ /// found.
+ size_t find(StringRef Str, size_t From = 0) const {
+ return str().find(Str, From);
+ }
+
+ /// Search for the last character \p C in the string.
+ ///
+ /// \returns The index of the last occurrence of \p C, or npos if not
+ /// found.
+ size_t rfind(char C, size_t From = StringRef::npos) const {
+ return str().rfind(C, From);
+ }
+
+ /// Search for the last string \p Str in the string.
+ ///
+ /// \returns The index of the last occurrence of \p Str, or npos if not
+ /// found.
+ size_t rfind(StringRef Str) const {
+ return str().rfind(Str);
+ }
+
+ /// Find the first character in the string that is \p C, or npos if not
+ /// found. Same as find.
+ size_t find_first_of(char C, size_t From = 0) const {
+ return str().find_first_of(C, From);
+ }
+
+ /// Find the first character in the string that is in \p Chars, or npos if
+ /// not found.
+ ///
+ /// Complexity: O(size() + Chars.size())
+ size_t find_first_of(StringRef Chars, size_t From = 0) const {
+ return str().find_first_of(Chars, From);
+ }
+
+ /// Find the first character in the string that is not \p C or npos if not
+ /// found.
+ size_t find_first_not_of(char C, size_t From = 0) const {
+ return str().find_first_not_of(C, From);
+ }
+
+ /// Find the first character in the string that is not in the string
+ /// \p Chars, or npos if not found.
+ ///
+ /// Complexity: O(size() + Chars.size())
+ size_t find_first_not_of(StringRef Chars, size_t From = 0) const {
+ return str().find_first_not_of(Chars, From);
+ }
+
+ /// Find the last character in the string that is \p C, or npos if not
+ /// found.
+ size_t find_last_of(char C, size_t From = StringRef::npos) const {
+ return str().find_last_of(C, From);
+ }
+
+ /// Find the last character in the string that is in \p C, or npos if not
+ /// found.
+ ///
+ /// Complexity: O(size() + Chars.size())
+ size_t find_last_of(
+ StringRef Chars, size_t From = StringRef::npos) const {
+ return str().find_last_of(Chars, From);
+ }
+
+ /// @}
+ /// @name Helpful Algorithms
+ /// @{
+
+ /// Return the number of occurrences of \p C in the string.
+ size_t count(char C) const {
+ return str().count(C);
+ }
+
+ /// Return the number of non-overlapped occurrences of \p Str in the
+ /// string.
+ size_t count(StringRef Str) const {
+ return str().count(Str);
+ }
+
+ /// @}
+ /// @name Substring Operations
+ /// @{
+
+ /// Return a reference to the substring from [Start, Start + N).
+ ///
+ /// \param Start The index of the starting character in the substring; if
+ /// the index is npos or greater than the length of the string then the
+ /// empty substring will be returned.
+ ///
+ /// \param N The number of characters to included in the substring. If \p N
+ /// exceeds the number of characters remaining in the string, the string
+ /// suffix (starting with \p Start) will be returned.
+ StringRef substr(size_t Start, size_t N = StringRef::npos) const {
+ return str().substr(Start, N);
+ }
+
+ /// Return a reference to the substring from [Start, End).
+ ///
+ /// \param Start The index of the starting character in the substring; if
+ /// the index is npos or greater than the length of the string then the
+ /// empty substring will be returned.
+ ///
+ /// \param End The index following the last character to include in the
+ /// substring. If this is npos, or less than \p Start, or exceeds the
+ /// number of characters remaining in the string, the string suffix
+ /// (starting with \p Start) will be returned.
+ StringRef slice(size_t Start, size_t End) const {
+ return str().slice(Start, End);
+ }
+
+ // Extra methods.
+
+ /// Explicit conversion to StringRef.
+ StringRef str() const { return StringRef(this->begin(), this->size()); }
+
+ // TODO: Make this const, if it's safe...
+ const char* c_str() {
+ this->push_back(0);
+ this->pop_back();
+ return this->data();
+ }
+
+ /// Implicit conversion to StringRef.
+ operator StringRef() const { return str(); }
+
+ // Extra operators.
+ const SmallString &operator=(StringRef RHS) {
+ this->clear();
+ return *this += RHS;
+ }
+
+ SmallString &operator+=(StringRef RHS) {
+ this->append(RHS.begin(), RHS.end());
+ return *this;
+ }
+ SmallString &operator+=(char C) {
+ this->push_back(C);
+ return *this;
+ }
+};
+
+}
+
+#endif
diff --git a/include/llvm/ADT/SmallVector.h b/include/llvm/ADT/SmallVector.h
new file mode 100644
index 00000000000..6e0fd94dfe6
--- /dev/null
+++ b/include/llvm/ADT/SmallVector.h
@@ -0,0 +1,938 @@
+//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the SmallVector class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SMALLVECTOR_H
+#define LLVM_ADT_SMALLVECTOR_H
+
+#include "llvm/Support/AlignOf.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/type_traits.h"
+#include <algorithm>
+#include <cassert>
+#include <cstddef>
+#include <cstdlib>
+#include <cstring>
+#include <iterator>
+#include <memory>
+
+namespace llvm {
+
+/// SmallVectorBase - This is all the non-templated stuff common to all
+/// SmallVectors.
+class SmallVectorBase {
+protected:
+ void *BeginX, *EndX, *CapacityX;
+
+protected:
+ SmallVectorBase(void *FirstEl, size_t Size)
+ : BeginX(FirstEl), EndX(FirstEl), CapacityX((char*)FirstEl+Size) {}
+
+ /// grow_pod - This is an implementation of the grow() method which only works
+ /// on POD-like data types and is out of line to reduce code duplication.
+ void grow_pod(void *FirstEl, size_t MinSizeInBytes, size_t TSize);
+
+public:
+ /// size_in_bytes - This returns size()*sizeof(T).
+ size_t size_in_bytes() const {
+ return size_t((char*)EndX - (char*)BeginX);
+ }
+
+ /// capacity_in_bytes - This returns capacity()*sizeof(T).
+ size_t capacity_in_bytes() const {
+ return size_t((char*)CapacityX - (char*)BeginX);
+ }
+
+ bool empty() const { return BeginX == EndX; }
+};
+
+template <typename T, unsigned N> struct SmallVectorStorage;
+
+/// SmallVectorTemplateCommon - This is the part of SmallVectorTemplateBase
+/// which does not depend on whether the type T is a POD. The extra dummy
+/// template argument is used by ArrayRef to avoid unnecessarily requiring T
+/// to be complete.
+template <typename T, typename = void>
+class SmallVectorTemplateCommon : public SmallVectorBase {
+private:
+ template <typename, unsigned> friend struct SmallVectorStorage;
+
+ // Allocate raw space for N elements of type T. If T has a ctor or dtor, we
+ // don't want it to be automatically run, so we need to represent the space as
+ // something else. Use an array of char of sufficient alignment.
+ typedef llvm::AlignedCharArrayUnion<T> U;
+ U FirstEl;
+ // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
+
+protected:
+ SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(&FirstEl, Size) {}
+
+ void grow_pod(size_t MinSizeInBytes, size_t TSize) {
+ SmallVectorBase::grow_pod(&FirstEl, MinSizeInBytes, TSize);
+ }
+
+ /// isSmall - Return true if this is a smallvector which has not had dynamic
+ /// memory allocated for it.
+ bool isSmall() const {
+ return BeginX == static_cast<const void*>(&FirstEl);
+ }
+
+ /// resetToSmall - Put this vector in a state of being small.
+ void resetToSmall() {
+ BeginX = EndX = CapacityX = &FirstEl;
+ }
+
+ void setEnd(T *P) { this->EndX = P; }
+public:
+ typedef size_t size_type;
+ typedef ptrdiff_t difference_type;
+ typedef T value_type;
+ typedef T *iterator;
+ typedef const T *const_iterator;
+
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+
+ typedef T &reference;
+ typedef const T &const_reference;
+ typedef T *pointer;
+ typedef const T *const_pointer;
+
+ // forward iterator creation methods.
+ iterator begin() { return (iterator)this->BeginX; }
+ const_iterator begin() const { return (const_iterator)this->BeginX; }
+ iterator end() { return (iterator)this->EndX; }
+ const_iterator end() const { return (const_iterator)this->EndX; }
+protected:
+ iterator capacity_ptr() { return (iterator)this->CapacityX; }
+ const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
+public:
+
+ // reverse iterator creation methods.
+ reverse_iterator rbegin() { return reverse_iterator(end()); }
+ const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
+ reverse_iterator rend() { return reverse_iterator(begin()); }
+ const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
+
+ size_type size() const { return end()-begin(); }
+ size_type max_size() const { return size_type(-1) / sizeof(T); }
+
+ /// capacity - Return the total number of elements in the currently allocated
+ /// buffer.
+ size_t capacity() const { return capacity_ptr() - begin(); }
+
+ /// data - Return a pointer to the vector's buffer, even if empty().
+ pointer data() { return pointer(begin()); }
+ /// data - Return a pointer to the vector's buffer, even if empty().
+ const_pointer data() const { return const_pointer(begin()); }
+
+ reference operator[](unsigned idx) {
+ assert(begin() + idx < end());
+ return begin()[idx];
+ }
+ const_reference operator[](unsigned idx) const {
+ assert(begin() + idx < end());
+ return begin()[idx];
+ }
+
+ reference front() {
+ return begin()[0];
+ }
+ const_reference front() const {
+ return begin()[0];
+ }
+
+ reference back() {
+ return end()[-1];
+ }
+ const_reference back() const {
+ return end()[-1];
+ }
+};
+
+/// SmallVectorTemplateBase<isPodLike = false> - This is where we put method
+/// implementations that are designed to work with non-POD-like T's.
+template <typename T, bool isPodLike>
+class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
+protected:
+ SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
+
+ static void destroy_range(T *S, T *E) {
+ while (S != E) {
+ --E;
+ E->~T();
+ }
+ }
+
+ /// move - Use move-assignment to move the range [I, E) onto the
+ /// objects starting with "Dest". This is just <memory>'s
+ /// std::move, but not all stdlibs actually provide that.
+ template<typename It1, typename It2>
+ static It2 move(It1 I, It1 E, It2 Dest) {
+#if LLVM_USE_RVALUE_REFERENCES
+ for (; I != E; ++I, ++Dest)
+ *Dest = ::std::move(*I);
+ return Dest;
+#else
+ return ::std::copy(I, E, Dest);
+#endif
+ }
+
+ /// move_backward - Use move-assignment to move the range
+ /// [I, E) onto the objects ending at "Dest", moving objects
+ /// in reverse order. This is just <algorithm>'s
+ /// std::move_backward, but not all stdlibs actually provide that.
+ template<typename It1, typename It2>
+ static It2 move_backward(It1 I, It1 E, It2 Dest) {
+#if LLVM_USE_RVALUE_REFERENCES
+ while (I != E)
+ *--Dest = ::std::move(*--E);
+ return Dest;
+#else
+ return ::std::copy_backward(I, E, Dest);
+#endif
+ }
+
+ /// uninitialized_move - Move the range [I, E) into the uninitialized
+ /// memory starting with "Dest", constructing elements as needed.
+ template<typename It1, typename It2>
+ static void uninitialized_move(It1 I, It1 E, It2 Dest) {
+#if LLVM_USE_RVALUE_REFERENCES
+ for (; I != E; ++I, ++Dest)
+ ::new ((void*) &*Dest) T(::std::move(*I));
+#else
+ ::std::uninitialized_copy(I, E, Dest);
+#endif
+ }
+
+ /// uninitialized_copy - Copy the range [I, E) onto the uninitialized
+ /// memory starting with "Dest", constructing elements as needed.
+ template<typename It1, typename It2>
+ static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
+ std::uninitialized_copy(I, E, Dest);
+ }
+
+ /// grow - Grow the allocated memory (without initializing new
+ /// elements), doubling the size of the allocated memory.
+ /// Guarantees space for at least one more element, or MinSize more
+ /// elements if specified.
+ void grow(size_t MinSize = 0);
+
+public:
+ void push_back(const T &Elt) {
+ if (this->EndX < this->CapacityX) {
+ Retry:
+ ::new ((void*) this->end()) T(Elt);
+ this->setEnd(this->end()+1);
+ return;
+ }
+ this->grow();
+ goto Retry;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ void push_back(T &&Elt) {
+ if (this->EndX < this->CapacityX) {
+ Retry:
+ ::new ((void*) this->end()) T(::std::move(Elt));
+ this->setEnd(this->end()+1);
+ return;
+ }
+ this->grow();
+ goto Retry;
+ }
+#endif
+
+ void pop_back() {
+ this->setEnd(this->end()-1);
+ this->end()->~T();
+ }
+};
+
+// Define this out-of-line to dissuade the C++ compiler from inlining it.
+template <typename T, bool isPodLike>
+void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
+ size_t CurCapacity = this->capacity();
+ size_t CurSize = this->size();
+ size_t NewCapacity = 2*CurCapacity + 1; // Always grow, even from zero.
+ if (NewCapacity < MinSize)
+ NewCapacity = MinSize;
+ T *NewElts = static_cast<T*>(malloc(NewCapacity*sizeof(T)));
+
+ // Move the elements over.
+ this->uninitialized_move(this->begin(), this->end(), NewElts);
+
+ // Destroy the original elements.
+ destroy_range(this->begin(), this->end());
+
+ // If this wasn't grown from the inline copy, deallocate the old space.
+ if (!this->isSmall())
+ free(this->begin());
+
+ this->setEnd(NewElts+CurSize);
+ this->BeginX = NewElts;
+ this->CapacityX = this->begin()+NewCapacity;
+}
+
+
+/// SmallVectorTemplateBase<isPodLike = true> - This is where we put method
+/// implementations that are designed to work with POD-like T's.
+template <typename T>
+class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
+protected:
+ SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
+
+ // No need to do a destroy loop for POD's.
+ static void destroy_range(T *, T *) {}
+
+ /// move - Use move-assignment to move the range [I, E) onto the
+ /// objects starting with "Dest". For PODs, this is just memcpy.
+ template<typename It1, typename It2>
+ static It2 move(It1 I, It1 E, It2 Dest) {
+ return ::std::copy(I, E, Dest);
+ }
+
+ /// move_backward - Use move-assignment to move the range
+ /// [I, E) onto the objects ending at "Dest", moving objects
+ /// in reverse order.
+ template<typename It1, typename It2>
+ static It2 move_backward(It1 I, It1 E, It2 Dest) {
+ return ::std::copy_backward(I, E, Dest);
+ }
+
+ /// uninitialized_move - Move the range [I, E) onto the uninitialized memory
+ /// starting with "Dest", constructing elements into it as needed.
+ template<typename It1, typename It2>
+ static void uninitialized_move(It1 I, It1 E, It2 Dest) {
+ // Just do a copy.
+ uninitialized_copy(I, E, Dest);
+ }
+
+ /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
+ /// starting with "Dest", constructing elements into it as needed.
+ template<typename It1, typename It2>
+ static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
+ // Arbitrary iterator types; just use the basic implementation.
+ std::uninitialized_copy(I, E, Dest);
+ }
+
+ /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
+ /// starting with "Dest", constructing elements into it as needed.
+ template<typename T1, typename T2>
+ static void uninitialized_copy(T1 *I, T1 *E, T2 *Dest) {
+ // Use memcpy for PODs iterated by pointers (which includes SmallVector
+ // iterators): std::uninitialized_copy optimizes to memmove, but we can
+ // use memcpy here.
+ memcpy(Dest, I, (E-I)*sizeof(T));
+ }
+
+ /// grow - double the size of the allocated memory, guaranteeing space for at
+ /// least one more element or MinSize if specified.
+ void grow(size_t MinSize = 0) {
+ this->grow_pod(MinSize*sizeof(T), sizeof(T));
+ }
+public:
+ void push_back(const T &Elt) {
+ if (this->EndX < this->CapacityX) {
+ Retry:
+ memcpy(this->end(), &Elt, sizeof(T));
+ this->setEnd(this->end()+1);
+ return;
+ }
+ this->grow();
+ goto Retry;
+ }
+
+ void pop_back() {
+ this->setEnd(this->end()-1);
+ }
+};
+
+
+/// SmallVectorImpl - This class consists of common code factored out of the
+/// SmallVector class to reduce code duplication based on the SmallVector 'N'
+/// template parameter.
+template <typename T>
+class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
+ typedef SmallVectorTemplateBase<T, isPodLike<T>::value > SuperClass;
+
+ SmallVectorImpl(const SmallVectorImpl&); // DISABLED.
+public:
+ typedef typename SuperClass::iterator iterator;
+ typedef typename SuperClass::size_type size_type;
+
+protected:
+ // Default ctor - Initialize to empty.
+ explicit SmallVectorImpl(unsigned N)
+ : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
+ }
+
+public:
+ ~SmallVectorImpl() {
+ // Destroy the constructed elements in the vector.
+ this->destroy_range(this->begin(), this->end());
+
+ // If this wasn't grown from the inline copy, deallocate the old space.
+ if (!this->isSmall())
+ free(this->begin());
+ }
+
+
+ void clear() {
+ this->destroy_range(this->begin(), this->end());
+ this->EndX = this->BeginX;
+ }
+
+ void resize(unsigned N) {
+ if (N < this->size()) {
+ this->destroy_range(this->begin()+N, this->end());
+ this->setEnd(this->begin()+N);
+ } else if (N > this->size()) {
+ if (this->capacity() < N)
+ this->grow(N);
+ std::uninitialized_fill(this->end(), this->begin()+N, T());
+ this->setEnd(this->begin()+N);
+ }
+ }
+
+ void resize(unsigned N, const T &NV) {
+ if (N < this->size()) {
+ this->destroy_range(this->begin()+N, this->end());
+ this->setEnd(this->begin()+N);
+ } else if (N > this->size()) {
+ if (this->capacity() < N)
+ this->grow(N);
+ std::uninitialized_fill(this->end(), this->begin()+N, NV);
+ this->setEnd(this->begin()+N);
+ }
+ }
+
+ void reserve(unsigned N) {
+ if (this->capacity() < N)
+ this->grow(N);
+ }
+
+ T pop_back_val() {
+#if LLVM_USE_RVALUE_REFERENCES
+ T Result = ::std::move(this->back());
+#else
+ T Result = this->back();
+#endif
+ this->pop_back();
+ return Result;
+ }
+
+ void swap(SmallVectorImpl &RHS);
+
+ /// append - Add the specified range to the end of the SmallVector.
+ ///
+ template<typename in_iter>
+ void append(in_iter in_start, in_iter in_end) {
+ size_type NumInputs = std::distance(in_start, in_end);
+ // Grow allocated space if needed.
+ if (NumInputs > size_type(this->capacity_ptr()-this->end()))
+ this->grow(this->size()+NumInputs);
+
+ // Copy the new elements over.
+ // TODO: NEED To compile time dispatch on whether in_iter is a random access
+ // iterator to use the fast uninitialized_copy.
+ std::uninitialized_copy(in_start, in_end, this->end());
+ this->setEnd(this->end() + NumInputs);
+ }
+
+ /// append - Add the specified range to the end of the SmallVector.
+ ///
+ void append(size_type NumInputs, const T &Elt) {
+ // Grow allocated space if needed.
+ if (NumInputs > size_type(this->capacity_ptr()-this->end()))
+ this->grow(this->size()+NumInputs);
+
+ // Copy the new elements over.
+ std::uninitialized_fill_n(this->end(), NumInputs, Elt);
+ this->setEnd(this->end() + NumInputs);
+ }
+
+ void assign(unsigned NumElts, const T &Elt) {
+ clear();
+ if (this->capacity() < NumElts)
+ this->grow(NumElts);
+ this->setEnd(this->begin()+NumElts);
+ std::uninitialized_fill(this->begin(), this->end(), Elt);
+ }
+
+ iterator erase(iterator I) {
+ assert(I >= this->begin() && "Iterator to erase is out of bounds.");
+ assert(I < this->end() && "Erasing at past-the-end iterator.");
+
+ iterator N = I;
+ // Shift all elts down one.
+ this->move(I+1, this->end(), I);
+ // Drop the last elt.
+ this->pop_back();
+ return(N);
+ }
+
+ iterator erase(iterator S, iterator E) {
+ assert(S >= this->begin() && "Range to erase is out of bounds.");
+ assert(S <= E && "Trying to erase invalid range.");
+ assert(E <= this->end() && "Trying to erase past the end.");
+
+ iterator N = S;
+ // Shift all elts down.
+ iterator I = this->move(E, this->end(), S);
+ // Drop the last elts.
+ this->destroy_range(I, this->end());
+ this->setEnd(I);
+ return(N);
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ iterator insert(iterator I, T &&Elt) {
+ if (I == this->end()) { // Important special case for empty vector.
+ this->push_back(::std::move(Elt));
+ return this->end()-1;
+ }
+
+ assert(I >= this->begin() && "Insertion iterator is out of bounds.");
+ assert(I <= this->end() && "Inserting past the end of the vector.");
+
+ if (this->EndX < this->CapacityX) {
+ Retry:
+ ::new ((void*) this->end()) T(::std::move(this->back()));
+ this->setEnd(this->end()+1);
+ // Push everything else over.
+ this->move_backward(I, this->end()-1, this->end());
+
+ // If we just moved the element we're inserting, be sure to update
+ // the reference.
+ T *EltPtr = &Elt;
+ if (I <= EltPtr && EltPtr < this->EndX)
+ ++EltPtr;
+
+ *I = ::std::move(*EltPtr);
+ return I;
+ }
+ size_t EltNo = I-this->begin();
+ this->grow();
+ I = this->begin()+EltNo;
+ goto Retry;
+ }
+#endif
+
+ iterator insert(iterator I, const T &Elt) {
+ if (I == this->end()) { // Important special case for empty vector.
+ this->push_back(Elt);
+ return this->end()-1;
+ }
+
+ assert(I >= this->begin() && "Insertion iterator is out of bounds.");
+ assert(I <= this->end() && "Inserting past the end of the vector.");
+
+ if (this->EndX < this->CapacityX) {
+ Retry:
+ ::new ((void*) this->end()) T(this->back());
+ this->setEnd(this->end()+1);
+ // Push everything else over.
+ this->move_backward(I, this->end()-1, this->end());
+
+ // If we just moved the element we're inserting, be sure to update
+ // the reference.
+ const T *EltPtr = &Elt;
+ if (I <= EltPtr && EltPtr < this->EndX)
+ ++EltPtr;
+
+ *I = *EltPtr;
+ return I;
+ }
+ size_t EltNo = I-this->begin();
+ this->grow();
+ I = this->begin()+EltNo;
+ goto Retry;
+ }
+
+ iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
+ // Convert iterator to elt# to avoid invalidating iterator when we reserve()
+ size_t InsertElt = I - this->begin();
+
+ if (I == this->end()) { // Important special case for empty vector.
+ append(NumToInsert, Elt);
+ return this->begin()+InsertElt;
+ }
+
+ assert(I >= this->begin() && "Insertion iterator is out of bounds.");
+ assert(I <= this->end() && "Inserting past the end of the vector.");
+
+ // Ensure there is enough space.
+ reserve(static_cast<unsigned>(this->size() + NumToInsert));
+
+ // Uninvalidate the iterator.
+ I = this->begin()+InsertElt;
+
+ // If there are more elements between the insertion point and the end of the
+ // range than there are being inserted, we can use a simple approach to
+ // insertion. Since we already reserved space, we know that this won't
+ // reallocate the vector.
+ if (size_t(this->end()-I) >= NumToInsert) {
+ T *OldEnd = this->end();
+ append(this->end()-NumToInsert, this->end());
+
+ // Copy the existing elements that get replaced.
+ this->move_backward(I, OldEnd-NumToInsert, OldEnd);
+
+ std::fill_n(I, NumToInsert, Elt);
+ return I;
+ }
+
+ // Otherwise, we're inserting more elements than exist already, and we're
+ // not inserting at the end.
+
+ // Move over the elements that we're about to overwrite.
+ T *OldEnd = this->end();
+ this->setEnd(this->end() + NumToInsert);
+ size_t NumOverwritten = OldEnd-I;
+ this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
+
+ // Replace the overwritten part.
+ std::fill_n(I, NumOverwritten, Elt);
+
+ // Insert the non-overwritten middle part.
+ std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
+ return I;
+ }
+
+ template<typename ItTy>
+ iterator insert(iterator I, ItTy From, ItTy To) {
+ // Convert iterator to elt# to avoid invalidating iterator when we reserve()
+ size_t InsertElt = I - this->begin();
+
+ if (I == this->end()) { // Important special case for empty vector.
+ append(From, To);
+ return this->begin()+InsertElt;
+ }
+
+ assert(I >= this->begin() && "Insertion iterator is out of bounds.");
+ assert(I <= this->end() && "Inserting past the end of the vector.");
+
+ size_t NumToInsert = std::distance(From, To);
+
+ // Ensure there is enough space.
+ reserve(static_cast<unsigned>(this->size() + NumToInsert));
+
+ // Uninvalidate the iterator.
+ I = this->begin()+InsertElt;
+
+ // If there are more elements between the insertion point and the end of the
+ // range than there are being inserted, we can use a simple approach to
+ // insertion. Since we already reserved space, we know that this won't
+ // reallocate the vector.
+ if (size_t(this->end()-I) >= NumToInsert) {
+ T *OldEnd = this->end();
+ append(this->end()-NumToInsert, this->end());
+
+ // Copy the existing elements that get replaced.
+ this->move_backward(I, OldEnd-NumToInsert, OldEnd);
+
+ std::copy(From, To, I);
+ return I;
+ }
+
+ // Otherwise, we're inserting more elements than exist already, and we're
+ // not inserting at the end.
+
+ // Move over the elements that we're about to overwrite.
+ T *OldEnd = this->end();
+ this->setEnd(this->end() + NumToInsert);
+ size_t NumOverwritten = OldEnd-I;
+ this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
+
+ // Replace the overwritten part.
+ for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
+ *J = *From;
+ ++J; ++From;
+ }
+
+ // Insert the non-overwritten middle part.
+ this->uninitialized_copy(From, To, OldEnd);
+ return I;
+ }
+
+ SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
+
+#if LLVM_USE_RVALUE_REFERENCES
+ SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
+#endif
+
+ bool operator==(const SmallVectorImpl &RHS) const {
+ if (this->size() != RHS.size()) return false;
+ return std::equal(this->begin(), this->end(), RHS.begin());
+ }
+ bool operator!=(const SmallVectorImpl &RHS) const {
+ return !(*this == RHS);
+ }
+
+ bool operator<(const SmallVectorImpl &RHS) const {
+ return std::lexicographical_compare(this->begin(), this->end(),
+ RHS.begin(), RHS.end());
+ }
+
+ /// Set the array size to \p N, which the current array must have enough
+ /// capacity for.
+ ///
+ /// This does not construct or destroy any elements in the vector.
+ ///
+ /// Clients can use this in conjunction with capacity() to write past the end
+ /// of the buffer when they know that more elements are available, and only
+ /// update the size later. This avoids the cost of value initializing elements
+ /// which will only be overwritten.
+ void set_size(unsigned N) {
+ assert(N <= this->capacity());
+ this->setEnd(this->begin() + N);
+ }
+};
+
+
+template <typename T>
+void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
+ if (this == &RHS) return;
+
+ // We can only avoid copying elements if neither vector is small.
+ if (!this->isSmall() && !RHS.isSmall()) {
+ std::swap(this->BeginX, RHS.BeginX);
+ std::swap(this->EndX, RHS.EndX);
+ std::swap(this->CapacityX, RHS.CapacityX);
+ return;
+ }
+ if (RHS.size() > this->capacity())
+ this->grow(RHS.size());
+ if (this->size() > RHS.capacity())
+ RHS.grow(this->size());
+
+ // Swap the shared elements.
+ size_t NumShared = this->size();
+ if (NumShared > RHS.size()) NumShared = RHS.size();
+ for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
+ std::swap((*this)[i], RHS[i]);
+
+ // Copy over the extra elts.
+ if (this->size() > RHS.size()) {
+ size_t EltDiff = this->size() - RHS.size();
+ this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
+ RHS.setEnd(RHS.end()+EltDiff);
+ this->destroy_range(this->begin()+NumShared, this->end());
+ this->setEnd(this->begin()+NumShared);
+ } else if (RHS.size() > this->size()) {
+ size_t EltDiff = RHS.size() - this->size();
+ this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
+ this->setEnd(this->end() + EltDiff);
+ this->destroy_range(RHS.begin()+NumShared, RHS.end());
+ RHS.setEnd(RHS.begin()+NumShared);
+ }
+}
+
+template <typename T>
+SmallVectorImpl<T> &SmallVectorImpl<T>::
+ operator=(const SmallVectorImpl<T> &RHS) {
+ // Avoid self-assignment.
+ if (this == &RHS) return *this;
+
+ // If we already have sufficient space, assign the common elements, then
+ // destroy any excess.
+ size_t RHSSize = RHS.size();
+ size_t CurSize = this->size();
+ if (CurSize >= RHSSize) {
+ // Assign common elements.
+ iterator NewEnd;
+ if (RHSSize)
+ NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
+ else
+ NewEnd = this->begin();
+
+ // Destroy excess elements.
+ this->destroy_range(NewEnd, this->end());
+
+ // Trim.
+ this->setEnd(NewEnd);
+ return *this;
+ }
+
+ // If we have to grow to have enough elements, destroy the current elements.
+ // This allows us to avoid copying them during the grow.
+ // FIXME: don't do this if they're efficiently moveable.
+ if (this->capacity() < RHSSize) {
+ // Destroy current elements.
+ this->destroy_range(this->begin(), this->end());
+ this->setEnd(this->begin());
+ CurSize = 0;
+ this->grow(RHSSize);
+ } else if (CurSize) {
+ // Otherwise, use assignment for the already-constructed elements.
+ std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
+ }
+
+ // Copy construct the new elements in place.
+ this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
+ this->begin()+CurSize);
+
+ // Set end.
+ this->setEnd(this->begin()+RHSSize);
+ return *this;
+}
+
+#if LLVM_USE_RVALUE_REFERENCES
+template <typename T>
+SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
+ // Avoid self-assignment.
+ if (this == &RHS) return *this;
+
+ // If the RHS isn't small, clear this vector and then steal its buffer.
+ if (!RHS.isSmall()) {
+ this->destroy_range(this->begin(), this->end());
+ if (!this->isSmall()) free(this->begin());
+ this->BeginX = RHS.BeginX;
+ this->EndX = RHS.EndX;
+ this->CapacityX = RHS.CapacityX;
+ RHS.resetToSmall();
+ return *this;
+ }
+
+ // If we already have sufficient space, assign the common elements, then
+ // destroy any excess.
+ size_t RHSSize = RHS.size();
+ size_t CurSize = this->size();
+ if (CurSize >= RHSSize) {
+ // Assign common elements.
+ iterator NewEnd = this->begin();
+ if (RHSSize)
+ NewEnd = this->move(RHS.begin(), RHS.end(), NewEnd);
+
+ // Destroy excess elements and trim the bounds.
+ this->destroy_range(NewEnd, this->end());
+ this->setEnd(NewEnd);
+
+ // Clear the RHS.
+ RHS.clear();
+
+ return *this;
+ }
+
+ // If we have to grow to have enough elements, destroy the current elements.
+ // This allows us to avoid copying them during the grow.
+ // FIXME: this may not actually make any sense if we can efficiently move
+ // elements.
+ if (this->capacity() < RHSSize) {
+ // Destroy current elements.
+ this->destroy_range(this->begin(), this->end());
+ this->setEnd(this->begin());
+ CurSize = 0;
+ this->grow(RHSSize);
+ } else if (CurSize) {
+ // Otherwise, use assignment for the already-constructed elements.
+ this->move(RHS.begin(), RHS.end(), this->begin());
+ }
+
+ // Move-construct the new elements in place.
+ this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
+ this->begin()+CurSize);
+
+ // Set end.
+ this->setEnd(this->begin()+RHSSize);
+
+ RHS.clear();
+ return *this;
+}
+#endif
+
+/// Storage for the SmallVector elements which aren't contained in
+/// SmallVectorTemplateCommon. There are 'N-1' elements here. The remaining '1'
+/// element is in the base class. This is specialized for the N=1 and N=0 cases
+/// to avoid allocating unnecessary storage.
+template <typename T, unsigned N>
+struct SmallVectorStorage {
+ typename SmallVectorTemplateCommon<T>::U InlineElts[N - 1];
+};
+template <typename T> struct SmallVectorStorage<T, 1> {};
+template <typename T> struct SmallVectorStorage<T, 0> {};
+
+/// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
+/// for the case when the array is small. It contains some number of elements
+/// in-place, which allows it to avoid heap allocation when the actual number of
+/// elements is below that threshold. This allows normal "small" cases to be
+/// fast without losing generality for large inputs.
+///
+/// Note that this does not attempt to be exception safe.
+///
+template <typename T, unsigned N>
+class SmallVector : public SmallVectorImpl<T> {
+ /// Storage - Inline space for elements which aren't stored in the base class.
+ SmallVectorStorage<T, N> Storage;
+public:
+ SmallVector() : SmallVectorImpl<T>(N) {
+ }
+
+ explicit SmallVector(unsigned Size, const T &Value = T())
+ : SmallVectorImpl<T>(N) {
+ this->assign(Size, Value);
+ }
+
+ template<typename ItTy>
+ SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
+ this->append(S, E);
+ }
+
+ SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
+ if (!RHS.empty())
+ SmallVectorImpl<T>::operator=(RHS);
+ }
+
+ const SmallVector &operator=(const SmallVector &RHS) {
+ SmallVectorImpl<T>::operator=(RHS);
+ return *this;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
+ if (!RHS.empty())
+ SmallVectorImpl<T>::operator=(::std::move(RHS));
+ }
+
+ const SmallVector &operator=(SmallVector &&RHS) {
+ SmallVectorImpl<T>::operator=(::std::move(RHS));
+ return *this;
+ }
+#endif
+
+};
+
+template<typename T, unsigned N>
+static inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
+ return X.capacity_in_bytes();
+}
+
+} // End llvm namespace
+
+namespace std {
+ /// Implement std::swap in terms of SmallVector swap.
+ template<typename T>
+ inline void
+ swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
+ LHS.swap(RHS);
+ }
+
+ /// Implement std::swap in terms of SmallVector swap.
+ template<typename T, unsigned N>
+ inline void
+ swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
+ LHS.swap(RHS);
+ }
+}
+
+#endif
diff --git a/include/llvm/ADT/SparseBitVector.h b/include/llvm/ADT/SparseBitVector.h
new file mode 100644
index 00000000000..791f1082c28
--- /dev/null
+++ b/include/llvm/ADT/SparseBitVector.h
@@ -0,0 +1,881 @@
+//===- llvm/ADT/SparseBitVector.h - Efficient Sparse BitVector -*- C++ -*- ===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the SparseBitVector class. See the doxygen comment for
+// SparseBitVector for more details on the algorithm used.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SPARSEBITVECTOR_H
+#define LLVM_ADT_SPARSEBITVECTOR_H
+
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/raw_ostream.h"
+#include <cassert>
+#include <climits>
+
+namespace llvm {
+
+/// SparseBitVector is an implementation of a bitvector that is sparse by only
+/// storing the elements that have non-zero bits set. In order to make this
+/// fast for the most common cases, SparseBitVector is implemented as a linked
+/// list of SparseBitVectorElements. We maintain a pointer to the last
+/// SparseBitVectorElement accessed (in the form of a list iterator), in order
+/// to make multiple in-order test/set constant time after the first one is
+/// executed. Note that using vectors to store SparseBitVectorElement's does
+/// not work out very well because it causes insertion in the middle to take
+/// enormous amounts of time with a large amount of bits. Other structures that
+/// have better worst cases for insertion in the middle (various balanced trees,
+/// etc) do not perform as well in practice as a linked list with this iterator
+/// kept up to date. They are also significantly more memory intensive.
+
+
+template <unsigned ElementSize = 128>
+struct SparseBitVectorElement
+ : public ilist_node<SparseBitVectorElement<ElementSize> > {
+public:
+ typedef unsigned long BitWord;
+ enum {
+ BITWORD_SIZE = sizeof(BitWord) * CHAR_BIT,
+ BITWORDS_PER_ELEMENT = (ElementSize + BITWORD_SIZE - 1) / BITWORD_SIZE,
+ BITS_PER_ELEMENT = ElementSize
+ };
+
+private:
+ // Index of Element in terms of where first bit starts.
+ unsigned ElementIndex;
+ BitWord Bits[BITWORDS_PER_ELEMENT];
+ // Needed for sentinels
+ friend struct ilist_sentinel_traits<SparseBitVectorElement>;
+ SparseBitVectorElement() {
+ ElementIndex = ~0U;
+ memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
+ }
+
+public:
+ explicit SparseBitVectorElement(unsigned Idx) {
+ ElementIndex = Idx;
+ memset(&Bits[0], 0, sizeof (BitWord) * BITWORDS_PER_ELEMENT);
+ }
+
+ // Comparison.
+ bool operator==(const SparseBitVectorElement &RHS) const {
+ if (ElementIndex != RHS.ElementIndex)
+ return false;
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
+ if (Bits[i] != RHS.Bits[i])
+ return false;
+ return true;
+ }
+
+ bool operator!=(const SparseBitVectorElement &RHS) const {
+ return !(*this == RHS);
+ }
+
+ // Return the bits that make up word Idx in our element.
+ BitWord word(unsigned Idx) const {
+ assert (Idx < BITWORDS_PER_ELEMENT);
+ return Bits[Idx];
+ }
+
+ unsigned index() const {
+ return ElementIndex;
+ }
+
+ bool empty() const {
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
+ if (Bits[i])
+ return false;
+ return true;
+ }
+
+ void set(unsigned Idx) {
+ Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
+ }
+
+ bool test_and_set (unsigned Idx) {
+ bool old = test(Idx);
+ if (!old) {
+ set(Idx);
+ return true;
+ }
+ return false;
+ }
+
+ void reset(unsigned Idx) {
+ Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
+ }
+
+ bool test(unsigned Idx) const {
+ return Bits[Idx / BITWORD_SIZE] & (1L << (Idx % BITWORD_SIZE));
+ }
+
+ unsigned count() const {
+ unsigned NumBits = 0;
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
+ if (sizeof(BitWord) == 4)
+ NumBits += CountPopulation_32(Bits[i]);
+ else if (sizeof(BitWord) == 8)
+ NumBits += CountPopulation_64(Bits[i]);
+ else
+ llvm_unreachable("Unsupported!");
+ return NumBits;
+ }
+
+ /// find_first - Returns the index of the first set bit.
+ int find_first() const {
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i)
+ if (Bits[i] != 0) {
+ if (sizeof(BitWord) == 4)
+ return i * BITWORD_SIZE + CountTrailingZeros_32(Bits[i]);
+ if (sizeof(BitWord) == 8)
+ return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
+ llvm_unreachable("Unsupported!");
+ }
+ llvm_unreachable("Illegal empty element");
+ }
+
+ /// find_next - Returns the index of the next set bit starting from the
+ /// "Curr" bit. Returns -1 if the next set bit is not found.
+ int find_next(unsigned Curr) const {
+ if (Curr >= BITS_PER_ELEMENT)
+ return -1;
+
+ unsigned WordPos = Curr / BITWORD_SIZE;
+ unsigned BitPos = Curr % BITWORD_SIZE;
+ BitWord Copy = Bits[WordPos];
+ assert (WordPos <= BITWORDS_PER_ELEMENT
+ && "Word Position outside of element");
+
+ // Mask off previous bits.
+ Copy &= ~0UL << BitPos;
+
+ if (Copy != 0) {
+ if (sizeof(BitWord) == 4)
+ return WordPos * BITWORD_SIZE + CountTrailingZeros_32(Copy);
+ if (sizeof(BitWord) == 8)
+ return WordPos * BITWORD_SIZE + CountTrailingZeros_64(Copy);
+ llvm_unreachable("Unsupported!");
+ }
+
+ // Check subsequent words.
+ for (unsigned i = WordPos+1; i < BITWORDS_PER_ELEMENT; ++i)
+ if (Bits[i] != 0) {
+ if (sizeof(BitWord) == 4)
+ return i * BITWORD_SIZE + CountTrailingZeros_32(Bits[i]);
+ if (sizeof(BitWord) == 8)
+ return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
+ llvm_unreachable("Unsupported!");
+ }
+ return -1;
+ }
+
+ // Union this element with RHS and return true if this one changed.
+ bool unionWith(const SparseBitVectorElement &RHS) {
+ bool changed = false;
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
+ BitWord old = changed ? 0 : Bits[i];
+
+ Bits[i] |= RHS.Bits[i];
+ if (!changed && old != Bits[i])
+ changed = true;
+ }
+ return changed;
+ }
+
+ // Return true if we have any bits in common with RHS
+ bool intersects(const SparseBitVectorElement &RHS) const {
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
+ if (RHS.Bits[i] & Bits[i])
+ return true;
+ }
+ return false;
+ }
+
+ // Intersect this Element with RHS and return true if this one changed.
+ // BecameZero is set to true if this element became all-zero bits.
+ bool intersectWith(const SparseBitVectorElement &RHS,
+ bool &BecameZero) {
+ bool changed = false;
+ bool allzero = true;
+
+ BecameZero = false;
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
+ BitWord old = changed ? 0 : Bits[i];
+
+ Bits[i] &= RHS.Bits[i];
+ if (Bits[i] != 0)
+ allzero = false;
+
+ if (!changed && old != Bits[i])
+ changed = true;
+ }
+ BecameZero = allzero;
+ return changed;
+ }
+ // Intersect this Element with the complement of RHS and return true if this
+ // one changed. BecameZero is set to true if this element became all-zero
+ // bits.
+ bool intersectWithComplement(const SparseBitVectorElement &RHS,
+ bool &BecameZero) {
+ bool changed = false;
+ bool allzero = true;
+
+ BecameZero = false;
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
+ BitWord old = changed ? 0 : Bits[i];
+
+ Bits[i] &= ~RHS.Bits[i];
+ if (Bits[i] != 0)
+ allzero = false;
+
+ if (!changed && old != Bits[i])
+ changed = true;
+ }
+ BecameZero = allzero;
+ return changed;
+ }
+ // Three argument version of intersectWithComplement that intersects
+ // RHS1 & ~RHS2 into this element
+ void intersectWithComplement(const SparseBitVectorElement &RHS1,
+ const SparseBitVectorElement &RHS2,
+ bool &BecameZero) {
+ bool allzero = true;
+
+ BecameZero = false;
+ for (unsigned i = 0; i < BITWORDS_PER_ELEMENT; ++i) {
+ Bits[i] = RHS1.Bits[i] & ~RHS2.Bits[i];
+ if (Bits[i] != 0)
+ allzero = false;
+ }
+ BecameZero = allzero;
+ }
+};
+
+template <unsigned ElementSize = 128>
+class SparseBitVector {
+ typedef ilist<SparseBitVectorElement<ElementSize> > ElementList;
+ typedef typename ElementList::iterator ElementListIter;
+ typedef typename ElementList::const_iterator ElementListConstIter;
+ enum {
+ BITWORD_SIZE = SparseBitVectorElement<ElementSize>::BITWORD_SIZE
+ };
+
+ // Pointer to our current Element.
+ ElementListIter CurrElementIter;
+ ElementList Elements;
+
+ // This is like std::lower_bound, except we do linear searching from the
+ // current position.
+ ElementListIter FindLowerBound(unsigned ElementIndex) {
+
+ if (Elements.empty()) {
+ CurrElementIter = Elements.begin();
+ return Elements.begin();
+ }
+
+ // Make sure our current iterator is valid.
+ if (CurrElementIter == Elements.end())
+ --CurrElementIter;
+
+ // Search from our current iterator, either backwards or forwards,
+ // depending on what element we are looking for.
+ ElementListIter ElementIter = CurrElementIter;
+ if (CurrElementIter->index() == ElementIndex) {
+ return ElementIter;
+ } else if (CurrElementIter->index() > ElementIndex) {
+ while (ElementIter != Elements.begin()
+ && ElementIter->index() > ElementIndex)
+ --ElementIter;
+ } else {
+ while (ElementIter != Elements.end() &&
+ ElementIter->index() < ElementIndex)
+ ++ElementIter;
+ }
+ CurrElementIter = ElementIter;
+ return ElementIter;
+ }
+
+ // Iterator to walk set bits in the bitmap. This iterator is a lot uglier
+ // than it would be, in order to be efficient.
+ class SparseBitVectorIterator {
+ private:
+ bool AtEnd;
+
+ const SparseBitVector<ElementSize> *BitVector;
+
+ // Current element inside of bitmap.
+ ElementListConstIter Iter;
+
+ // Current bit number inside of our bitmap.
+ unsigned BitNumber;
+
+ // Current word number inside of our element.
+ unsigned WordNumber;
+
+ // Current bits from the element.
+ typename SparseBitVectorElement<ElementSize>::BitWord Bits;
+
+ // Move our iterator to the first non-zero bit in the bitmap.
+ void AdvanceToFirstNonZero() {
+ if (AtEnd)
+ return;
+ if (BitVector->Elements.empty()) {
+ AtEnd = true;
+ return;
+ }
+ Iter = BitVector->Elements.begin();
+ BitNumber = Iter->index() * ElementSize;
+ unsigned BitPos = Iter->find_first();
+ BitNumber += BitPos;
+ WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
+ Bits = Iter->word(WordNumber);
+ Bits >>= BitPos % BITWORD_SIZE;
+ }
+
+ // Move our iterator to the next non-zero bit.
+ void AdvanceToNextNonZero() {
+ if (AtEnd)
+ return;
+
+ while (Bits && !(Bits & 1)) {
+ Bits >>= 1;
+ BitNumber += 1;
+ }
+
+ // See if we ran out of Bits in this word.
+ if (!Bits) {
+ int NextSetBitNumber = Iter->find_next(BitNumber % ElementSize) ;
+ // If we ran out of set bits in this element, move to next element.
+ if (NextSetBitNumber == -1 || (BitNumber % ElementSize == 0)) {
+ ++Iter;
+ WordNumber = 0;
+
+ // We may run out of elements in the bitmap.
+ if (Iter == BitVector->Elements.end()) {
+ AtEnd = true;
+ return;
+ }
+ // Set up for next non zero word in bitmap.
+ BitNumber = Iter->index() * ElementSize;
+ NextSetBitNumber = Iter->find_first();
+ BitNumber += NextSetBitNumber;
+ WordNumber = (BitNumber % ElementSize) / BITWORD_SIZE;
+ Bits = Iter->word(WordNumber);
+ Bits >>= NextSetBitNumber % BITWORD_SIZE;
+ } else {
+ WordNumber = (NextSetBitNumber % ElementSize) / BITWORD_SIZE;
+ Bits = Iter->word(WordNumber);
+ Bits >>= NextSetBitNumber % BITWORD_SIZE;
+ BitNumber = Iter->index() * ElementSize;
+ BitNumber += NextSetBitNumber;
+ }
+ }
+ }
+ public:
+ // Preincrement.
+ inline SparseBitVectorIterator& operator++() {
+ ++BitNumber;
+ Bits >>= 1;
+ AdvanceToNextNonZero();
+ return *this;
+ }
+
+ // Postincrement.
+ inline SparseBitVectorIterator operator++(int) {
+ SparseBitVectorIterator tmp = *this;
+ ++*this;
+ return tmp;
+ }
+
+ // Return the current set bit number.
+ unsigned operator*() const {
+ return BitNumber;
+ }
+
+ bool operator==(const SparseBitVectorIterator &RHS) const {
+ // If they are both at the end, ignore the rest of the fields.
+ if (AtEnd && RHS.AtEnd)
+ return true;
+ // Otherwise they are the same if they have the same bit number and
+ // bitmap.
+ return AtEnd == RHS.AtEnd && RHS.BitNumber == BitNumber;
+ }
+ bool operator!=(const SparseBitVectorIterator &RHS) const {
+ return !(*this == RHS);
+ }
+ SparseBitVectorIterator(): BitVector(NULL) {
+ }
+
+
+ SparseBitVectorIterator(const SparseBitVector<ElementSize> *RHS,
+ bool end = false):BitVector(RHS) {
+ Iter = BitVector->Elements.begin();
+ BitNumber = 0;
+ Bits = 0;
+ WordNumber = ~0;
+ AtEnd = end;
+ AdvanceToFirstNonZero();
+ }
+ };
+public:
+ typedef SparseBitVectorIterator iterator;
+
+ SparseBitVector () {
+ CurrElementIter = Elements.begin ();
+ }
+
+ ~SparseBitVector() {
+ }
+
+ // SparseBitVector copy ctor.
+ SparseBitVector(const SparseBitVector &RHS) {
+ ElementListConstIter ElementIter = RHS.Elements.begin();
+ while (ElementIter != RHS.Elements.end()) {
+ Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
+ ++ElementIter;
+ }
+
+ CurrElementIter = Elements.begin ();
+ }
+
+ // Clear.
+ void clear() {
+ Elements.clear();
+ }
+
+ // Assignment
+ SparseBitVector& operator=(const SparseBitVector& RHS) {
+ Elements.clear();
+
+ ElementListConstIter ElementIter = RHS.Elements.begin();
+ while (ElementIter != RHS.Elements.end()) {
+ Elements.push_back(SparseBitVectorElement<ElementSize>(*ElementIter));
+ ++ElementIter;
+ }
+
+ CurrElementIter = Elements.begin ();
+
+ return *this;
+ }
+
+ // Test, Reset, and Set a bit in the bitmap.
+ bool test(unsigned Idx) {
+ if (Elements.empty())
+ return false;
+
+ unsigned ElementIndex = Idx / ElementSize;
+ ElementListIter ElementIter = FindLowerBound(ElementIndex);
+
+ // If we can't find an element that is supposed to contain this bit, there
+ // is nothing more to do.
+ if (ElementIter == Elements.end() ||
+ ElementIter->index() != ElementIndex)
+ return false;
+ return ElementIter->test(Idx % ElementSize);
+ }
+
+ void reset(unsigned Idx) {
+ if (Elements.empty())
+ return;
+
+ unsigned ElementIndex = Idx / ElementSize;
+ ElementListIter ElementIter = FindLowerBound(ElementIndex);
+
+ // If we can't find an element that is supposed to contain this bit, there
+ // is nothing more to do.
+ if (ElementIter == Elements.end() ||
+ ElementIter->index() != ElementIndex)
+ return;
+ ElementIter->reset(Idx % ElementSize);
+
+ // When the element is zeroed out, delete it.
+ if (ElementIter->empty()) {
+ ++CurrElementIter;
+ Elements.erase(ElementIter);
+ }
+ }
+
+ void set(unsigned Idx) {
+ unsigned ElementIndex = Idx / ElementSize;
+ SparseBitVectorElement<ElementSize> *Element;
+ ElementListIter ElementIter;
+ if (Elements.empty()) {
+ Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
+ ElementIter = Elements.insert(Elements.end(), Element);
+
+ } else {
+ ElementIter = FindLowerBound(ElementIndex);
+
+ if (ElementIter == Elements.end() ||
+ ElementIter->index() != ElementIndex) {
+ Element = new SparseBitVectorElement<ElementSize>(ElementIndex);
+ // We may have hit the beginning of our SparseBitVector, in which case,
+ // we may need to insert right after this element, which requires moving
+ // the current iterator forward one, because insert does insert before.
+ if (ElementIter != Elements.end() &&
+ ElementIter->index() < ElementIndex)
+ ElementIter = Elements.insert(++ElementIter, Element);
+ else
+ ElementIter = Elements.insert(ElementIter, Element);
+ }
+ }
+ CurrElementIter = ElementIter;
+
+ ElementIter->set(Idx % ElementSize);
+ }
+
+ bool test_and_set (unsigned Idx) {
+ bool old = test(Idx);
+ if (!old) {
+ set(Idx);
+ return true;
+ }
+ return false;
+ }
+
+ bool operator!=(const SparseBitVector &RHS) const {
+ return !(*this == RHS);
+ }
+
+ bool operator==(const SparseBitVector &RHS) const {
+ ElementListConstIter Iter1 = Elements.begin();
+ ElementListConstIter Iter2 = RHS.Elements.begin();
+
+ for (; Iter1 != Elements.end() && Iter2 != RHS.Elements.end();
+ ++Iter1, ++Iter2) {
+ if (*Iter1 != *Iter2)
+ return false;
+ }
+ return Iter1 == Elements.end() && Iter2 == RHS.Elements.end();
+ }
+
+ // Union our bitmap with the RHS and return true if we changed.
+ bool operator|=(const SparseBitVector &RHS) {
+ bool changed = false;
+ ElementListIter Iter1 = Elements.begin();
+ ElementListConstIter Iter2 = RHS.Elements.begin();
+
+ // If RHS is empty, we are done
+ if (RHS.Elements.empty())
+ return false;
+
+ while (Iter2 != RHS.Elements.end()) {
+ if (Iter1 == Elements.end() || Iter1->index() > Iter2->index()) {
+ Elements.insert(Iter1,
+ new SparseBitVectorElement<ElementSize>(*Iter2));
+ ++Iter2;
+ changed = true;
+ } else if (Iter1->index() == Iter2->index()) {
+ changed |= Iter1->unionWith(*Iter2);
+ ++Iter1;
+ ++Iter2;
+ } else {
+ ++Iter1;
+ }
+ }
+ CurrElementIter = Elements.begin();
+ return changed;
+ }
+
+ // Intersect our bitmap with the RHS and return true if ours changed.
+ bool operator&=(const SparseBitVector &RHS) {
+ bool changed = false;
+ ElementListIter Iter1 = Elements.begin();
+ ElementListConstIter Iter2 = RHS.Elements.begin();
+
+ // Check if both bitmaps are empty.
+ if (Elements.empty() && RHS.Elements.empty())
+ return false;
+
+ // Loop through, intersecting as we go, erasing elements when necessary.
+ while (Iter2 != RHS.Elements.end()) {
+ if (Iter1 == Elements.end()) {
+ CurrElementIter = Elements.begin();
+ return changed;
+ }
+
+ if (Iter1->index() > Iter2->index()) {
+ ++Iter2;
+ } else if (Iter1->index() == Iter2->index()) {
+ bool BecameZero;
+ changed |= Iter1->intersectWith(*Iter2, BecameZero);
+ if (BecameZero) {
+ ElementListIter IterTmp = Iter1;
+ ++Iter1;
+ Elements.erase(IterTmp);
+ } else {
+ ++Iter1;
+ }
+ ++Iter2;
+ } else {
+ ElementListIter IterTmp = Iter1;
+ ++Iter1;
+ Elements.erase(IterTmp);
+ }
+ }
+ Elements.erase(Iter1, Elements.end());
+ CurrElementIter = Elements.begin();
+ return changed;
+ }
+
+ // Intersect our bitmap with the complement of the RHS and return true
+ // if ours changed.
+ bool intersectWithComplement(const SparseBitVector &RHS) {
+ bool changed = false;
+ ElementListIter Iter1 = Elements.begin();
+ ElementListConstIter Iter2 = RHS.Elements.begin();
+
+ // If either our bitmap or RHS is empty, we are done
+ if (Elements.empty() || RHS.Elements.empty())
+ return false;
+
+ // Loop through, intersecting as we go, erasing elements when necessary.
+ while (Iter2 != RHS.Elements.end()) {
+ if (Iter1 == Elements.end()) {
+ CurrElementIter = Elements.begin();
+ return changed;
+ }
+
+ if (Iter1->index() > Iter2->index()) {
+ ++Iter2;
+ } else if (Iter1->index() == Iter2->index()) {
+ bool BecameZero;
+ changed |= Iter1->intersectWithComplement(*Iter2, BecameZero);
+ if (BecameZero) {
+ ElementListIter IterTmp = Iter1;
+ ++Iter1;
+ Elements.erase(IterTmp);
+ } else {
+ ++Iter1;
+ }
+ ++Iter2;
+ } else {
+ ++Iter1;
+ }
+ }
+ CurrElementIter = Elements.begin();
+ return changed;
+ }
+
+ bool intersectWithComplement(const SparseBitVector<ElementSize> *RHS) const {
+ return intersectWithComplement(*RHS);
+ }
+
+
+ // Three argument version of intersectWithComplement.
+ // Result of RHS1 & ~RHS2 is stored into this bitmap.
+ void intersectWithComplement(const SparseBitVector<ElementSize> &RHS1,
+ const SparseBitVector<ElementSize> &RHS2)
+ {
+ Elements.clear();
+ CurrElementIter = Elements.begin();
+ ElementListConstIter Iter1 = RHS1.Elements.begin();
+ ElementListConstIter Iter2 = RHS2.Elements.begin();
+
+ // If RHS1 is empty, we are done
+ // If RHS2 is empty, we still have to copy RHS1
+ if (RHS1.Elements.empty())
+ return;
+
+ // Loop through, intersecting as we go, erasing elements when necessary.
+ while (Iter2 != RHS2.Elements.end()) {
+ if (Iter1 == RHS1.Elements.end())
+ return;
+
+ if (Iter1->index() > Iter2->index()) {
+ ++Iter2;
+ } else if (Iter1->index() == Iter2->index()) {
+ bool BecameZero = false;
+ SparseBitVectorElement<ElementSize> *NewElement =
+ new SparseBitVectorElement<ElementSize>(Iter1->index());
+ NewElement->intersectWithComplement(*Iter1, *Iter2, BecameZero);
+ if (!BecameZero) {
+ Elements.push_back(NewElement);
+ }
+ else
+ delete NewElement;
+ ++Iter1;
+ ++Iter2;
+ } else {
+ SparseBitVectorElement<ElementSize> *NewElement =
+ new SparseBitVectorElement<ElementSize>(*Iter1);
+ Elements.push_back(NewElement);
+ ++Iter1;
+ }
+ }
+
+ // copy the remaining elements
+ while (Iter1 != RHS1.Elements.end()) {
+ SparseBitVectorElement<ElementSize> *NewElement =
+ new SparseBitVectorElement<ElementSize>(*Iter1);
+ Elements.push_back(NewElement);
+ ++Iter1;
+ }
+
+ return;
+ }
+
+ void intersectWithComplement(const SparseBitVector<ElementSize> *RHS1,
+ const SparseBitVector<ElementSize> *RHS2) {
+ intersectWithComplement(*RHS1, *RHS2);
+ }
+
+ bool intersects(const SparseBitVector<ElementSize> *RHS) const {
+ return intersects(*RHS);
+ }
+
+ // Return true if we share any bits in common with RHS
+ bool intersects(const SparseBitVector<ElementSize> &RHS) const {
+ ElementListConstIter Iter1 = Elements.begin();
+ ElementListConstIter Iter2 = RHS.Elements.begin();
+
+ // Check if both bitmaps are empty.
+ if (Elements.empty() && RHS.Elements.empty())
+ return false;
+
+ // Loop through, intersecting stopping when we hit bits in common.
+ while (Iter2 != RHS.Elements.end()) {
+ if (Iter1 == Elements.end())
+ return false;
+
+ if (Iter1->index() > Iter2->index()) {
+ ++Iter2;
+ } else if (Iter1->index() == Iter2->index()) {
+ if (Iter1->intersects(*Iter2))
+ return true;
+ ++Iter1;
+ ++Iter2;
+ } else {
+ ++Iter1;
+ }
+ }
+ return false;
+ }
+
+ // Return true iff all bits set in this SparseBitVector are
+ // also set in RHS.
+ bool contains(const SparseBitVector<ElementSize> &RHS) const {
+ SparseBitVector<ElementSize> Result(*this);
+ Result &= RHS;
+ return (Result == RHS);
+ }
+
+ // Return the first set bit in the bitmap. Return -1 if no bits are set.
+ int find_first() const {
+ if (Elements.empty())
+ return -1;
+ const SparseBitVectorElement<ElementSize> &First = *(Elements.begin());
+ return (First.index() * ElementSize) + First.find_first();
+ }
+
+ // Return true if the SparseBitVector is empty
+ bool empty() const {
+ return Elements.empty();
+ }
+
+ unsigned count() const {
+ unsigned BitCount = 0;
+ for (ElementListConstIter Iter = Elements.begin();
+ Iter != Elements.end();
+ ++Iter)
+ BitCount += Iter->count();
+
+ return BitCount;
+ }
+ iterator begin() const {
+ return iterator(this);
+ }
+
+ iterator end() const {
+ return iterator(this, true);
+ }
+};
+
+// Convenience functions to allow Or and And without dereferencing in the user
+// code.
+
+template <unsigned ElementSize>
+inline bool operator |=(SparseBitVector<ElementSize> &LHS,
+ const SparseBitVector<ElementSize> *RHS) {
+ return LHS |= *RHS;
+}
+
+template <unsigned ElementSize>
+inline bool operator |=(SparseBitVector<ElementSize> *LHS,
+ const SparseBitVector<ElementSize> &RHS) {
+ return LHS->operator|=(RHS);
+}
+
+template <unsigned ElementSize>
+inline bool operator &=(SparseBitVector<ElementSize> *LHS,
+ const SparseBitVector<ElementSize> &RHS) {
+ return LHS->operator&=(RHS);
+}
+
+template <unsigned ElementSize>
+inline bool operator &=(SparseBitVector<ElementSize> &LHS,
+ const SparseBitVector<ElementSize> *RHS) {
+ return LHS &= *RHS;
+}
+
+// Convenience functions for infix union, intersection, difference operators.
+
+template <unsigned ElementSize>
+inline SparseBitVector<ElementSize>
+operator|(const SparseBitVector<ElementSize> &LHS,
+ const SparseBitVector<ElementSize> &RHS) {
+ SparseBitVector<ElementSize> Result(LHS);
+ Result |= RHS;
+ return Result;
+}
+
+template <unsigned ElementSize>
+inline SparseBitVector<ElementSize>
+operator&(const SparseBitVector<ElementSize> &LHS,
+ const SparseBitVector<ElementSize> &RHS) {
+ SparseBitVector<ElementSize> Result(LHS);
+ Result &= RHS;
+ return Result;
+}
+
+template <unsigned ElementSize>
+inline SparseBitVector<ElementSize>
+operator-(const SparseBitVector<ElementSize> &LHS,
+ const SparseBitVector<ElementSize> &RHS) {
+ SparseBitVector<ElementSize> Result;
+ Result.intersectWithComplement(LHS, RHS);
+ return Result;
+}
+
+
+
+
+// Dump a SparseBitVector to a stream
+template <unsigned ElementSize>
+void dump(const SparseBitVector<ElementSize> &LHS, raw_ostream &out) {
+ out << "[";
+
+ typename SparseBitVector<ElementSize>::iterator bi = LHS.begin(),
+ be = LHS.end();
+ if (bi != be) {
+ out << *bi;
+ for (++bi; bi != be; ++bi) {
+ out << " " << *bi;
+ }
+ }
+ out << "]\n";
+}
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/SparseSet.h b/include/llvm/ADT/SparseSet.h
new file mode 100644
index 00000000000..063c6755c68
--- /dev/null
+++ b/include/llvm/ADT/SparseSet.h
@@ -0,0 +1,308 @@
+//===--- llvm/ADT/SparseSet.h - Sparse set ----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the SparseSet class derived from the version described in
+// Briggs, Torczon, "An efficient representation for sparse sets", ACM Letters
+// on Programming Languages and Systems, Volume 2 Issue 1-4, March-Dec. 1993.
+//
+// A sparse set holds a small number of objects identified by integer keys from
+// a moderately sized universe. The sparse set uses more memory than other
+// containers in order to provide faster operations.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_SPARSESET_H
+#define LLVM_ADT_SPARSESET_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/DataTypes.h"
+#include <limits>
+
+namespace llvm {
+
+/// SparseSetValTraits - Objects in a SparseSet are identified by keys that can
+/// be uniquely converted to a small integer less than the set's universe. This
+/// class allows the set to hold values that differ from the set's key type as
+/// long as an index can still be derived from the value. SparseSet never
+/// directly compares ValueT, only their indices, so it can map keys to
+/// arbitrary values. SparseSetValTraits computes the index from the value
+/// object. To compute the index from a key, SparseSet uses a separate
+/// KeyFunctorT template argument.
+///
+/// A simple type declaration, SparseSet<Type>, handles these cases:
+/// - unsigned key, identity index, identity value
+/// - unsigned key, identity index, fat value providing getSparseSetIndex()
+///
+/// The type declaration SparseSet<Type, UnaryFunction> handles:
+/// - unsigned key, remapped index, identity value (virtual registers)
+/// - pointer key, pointer-derived index, identity value (node+ID)
+/// - pointer key, pointer-derived index, fat value with getSparseSetIndex()
+///
+/// Only other, unexpected cases require specializing SparseSetValTraits.
+///
+/// For best results, ValueT should not require a destructor.
+///
+template<typename ValueT>
+struct SparseSetValTraits {
+ static unsigned getValIndex(const ValueT &Val) {
+ return Val.getSparseSetIndex();
+ }
+};
+
+/// SparseSetValFunctor - Helper class for selecting SparseSetValTraits. The
+/// generic implementation handles ValueT classes which either provide
+/// getSparseSetIndex() or specialize SparseSetValTraits<>.
+///
+template<typename KeyT, typename ValueT, typename KeyFunctorT>
+struct SparseSetValFunctor {
+ unsigned operator()(const ValueT &Val) const {
+ return SparseSetValTraits<ValueT>::getValIndex(Val);
+ }
+};
+
+/// SparseSetValFunctor<KeyT, KeyT> - Helper class for the common case of
+/// identity key/value sets.
+template<typename KeyT, typename KeyFunctorT>
+struct SparseSetValFunctor<KeyT, KeyT, KeyFunctorT> {
+ unsigned operator()(const KeyT &Key) const {
+ return KeyFunctorT()(Key);
+ }
+};
+
+/// SparseSet - Fast set implmentation for objects that can be identified by
+/// small unsigned keys.
+///
+/// SparseSet allocates memory proportional to the size of the key universe, so
+/// it is not recommended for building composite data structures. It is useful
+/// for algorithms that require a single set with fast operations.
+///
+/// Compared to DenseSet and DenseMap, SparseSet provides constant-time fast
+/// clear() and iteration as fast as a vector. The find(), insert(), and
+/// erase() operations are all constant time, and typically faster than a hash
+/// table. The iteration order doesn't depend on numerical key values, it only
+/// depends on the order of insert() and erase() operations. When no elements
+/// have been erased, the iteration order is the insertion order.
+///
+/// Compared to BitVector, SparseSet<unsigned> uses 8x-40x more memory, but
+/// offers constant-time clear() and size() operations as well as fast
+/// iteration independent on the size of the universe.
+///
+/// SparseSet contains a dense vector holding all the objects and a sparse
+/// array holding indexes into the dense vector. Most of the memory is used by
+/// the sparse array which is the size of the key universe. The SparseT
+/// template parameter provides a space/speed tradeoff for sets holding many
+/// elements.
+///
+/// When SparseT is uint32_t, find() only touches 2 cache lines, but the sparse
+/// array uses 4 x Universe bytes.
+///
+/// When SparseT is uint8_t (the default), find() touches up to 2+[N/256] cache
+/// lines, but the sparse array is 4x smaller. N is the number of elements in
+/// the set.
+///
+/// For sets that may grow to thousands of elements, SparseT should be set to
+/// uint16_t or uint32_t.
+///
+/// @tparam ValueT The type of objects in the set.
+/// @tparam KeyFunctorT A functor that computes an unsigned index from KeyT.
+/// @tparam SparseT An unsigned integer type. See above.
+///
+template<typename ValueT,
+ typename KeyFunctorT = llvm::identity<unsigned>,
+ typename SparseT = uint8_t>
+class SparseSet {
+ typedef typename KeyFunctorT::argument_type KeyT;
+ typedef SmallVector<ValueT, 8> DenseT;
+ DenseT Dense;
+ SparseT *Sparse;
+ unsigned Universe;
+ KeyFunctorT KeyIndexOf;
+ SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
+
+ // Disable copy construction and assignment.
+ // This data structure is not meant to be used that way.
+ SparseSet(const SparseSet&) LLVM_DELETED_FUNCTION;
+ SparseSet &operator=(const SparseSet&) LLVM_DELETED_FUNCTION;
+
+public:
+ typedef ValueT value_type;
+ typedef ValueT &reference;
+ typedef const ValueT &const_reference;
+ typedef ValueT *pointer;
+ typedef const ValueT *const_pointer;
+
+ SparseSet() : Sparse(0), Universe(0) {}
+ ~SparseSet() { free(Sparse); }
+
+ /// setUniverse - Set the universe size which determines the largest key the
+ /// set can hold. The universe must be sized before any elements can be
+ /// added.
+ ///
+ /// @param U Universe size. All object keys must be less than U.
+ ///
+ void setUniverse(unsigned U) {
+ // It's not hard to resize the universe on a non-empty set, but it doesn't
+ // seem like a likely use case, so we can add that code when we need it.
+ assert(empty() && "Can only resize universe on an empty map");
+ // Hysteresis prevents needless reallocations.
+ if (U >= Universe/4 && U <= Universe)
+ return;
+ free(Sparse);
+ // The Sparse array doesn't actually need to be initialized, so malloc
+ // would be enough here, but that will cause tools like valgrind to
+ // complain about branching on uninitialized data.
+ Sparse = reinterpret_cast<SparseT*>(calloc(U, sizeof(SparseT)));
+ Universe = U;
+ }
+
+ // Import trivial vector stuff from DenseT.
+ typedef typename DenseT::iterator iterator;
+ typedef typename DenseT::const_iterator const_iterator;
+
+ const_iterator begin() const { return Dense.begin(); }
+ const_iterator end() const { return Dense.end(); }
+ iterator begin() { return Dense.begin(); }
+ iterator end() { return Dense.end(); }
+
+ /// empty - Returns true if the set is empty.
+ ///
+ /// This is not the same as BitVector::empty().
+ ///
+ bool empty() const { return Dense.empty(); }
+
+ /// size - Returns the number of elements in the set.
+ ///
+ /// This is not the same as BitVector::size() which returns the size of the
+ /// universe.
+ ///
+ unsigned size() const { return Dense.size(); }
+
+ /// clear - Clears the set. This is a very fast constant time operation.
+ ///
+ void clear() {
+ // Sparse does not need to be cleared, see find().
+ Dense.clear();
+ }
+
+ /// findIndex - Find an element by its index.
+ ///
+ /// @param Idx A valid index to find.
+ /// @returns An iterator to the element identified by key, or end().
+ ///
+ iterator findIndex(unsigned Idx) {
+ assert(Idx < Universe && "Key out of range");
+ assert(std::numeric_limits<SparseT>::is_integer &&
+ !std::numeric_limits<SparseT>::is_signed &&
+ "SparseT must be an unsigned integer type");
+ const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
+ for (unsigned i = Sparse[Idx], e = size(); i < e; i += Stride) {
+ const unsigned FoundIdx = ValIndexOf(Dense[i]);
+ assert(FoundIdx < Universe && "Invalid key in set. Did object mutate?");
+ if (Idx == FoundIdx)
+ return begin() + i;
+ // Stride is 0 when SparseT >= unsigned. We don't need to loop.
+ if (!Stride)
+ break;
+ }
+ return end();
+ }
+
+ /// find - Find an element by its key.
+ ///
+ /// @param Key A valid key to find.
+ /// @returns An iterator to the element identified by key, or end().
+ ///
+ iterator find(const KeyT &Key) {
+ return findIndex(KeyIndexOf(Key));
+ }
+
+ const_iterator find(const KeyT &Key) const {
+ return const_cast<SparseSet*>(this)->findIndex(KeyIndexOf(Key));
+ }
+
+ /// count - Returns true if this set contains an element identified by Key.
+ ///
+ bool count(const KeyT &Key) const {
+ return find(Key) != end();
+ }
+
+ /// insert - Attempts to insert a new element.
+ ///
+ /// If Val is successfully inserted, return (I, true), where I is an iterator
+ /// pointing to the newly inserted element.
+ ///
+ /// If the set already contains an element with the same key as Val, return
+ /// (I, false), where I is an iterator pointing to the existing element.
+ ///
+ /// Insertion invalidates all iterators.
+ ///
+ std::pair<iterator, bool> insert(const ValueT &Val) {
+ unsigned Idx = ValIndexOf(Val);
+ iterator I = findIndex(Idx);
+ if (I != end())
+ return std::make_pair(I, false);
+ Sparse[Idx] = size();
+ Dense.push_back(Val);
+ return std::make_pair(end() - 1, true);
+ }
+
+ /// array subscript - If an element already exists with this key, return it.
+ /// Otherwise, automatically construct a new value from Key, insert it,
+ /// and return the newly inserted element.
+ ValueT &operator[](const KeyT &Key) {
+ return *insert(ValueT(Key)).first;
+ }
+
+ /// erase - Erases an existing element identified by a valid iterator.
+ ///
+ /// This invalidates all iterators, but erase() returns an iterator pointing
+ /// to the next element. This makes it possible to erase selected elements
+ /// while iterating over the set:
+ ///
+ /// for (SparseSet::iterator I = Set.begin(); I != Set.end();)
+ /// if (test(*I))
+ /// I = Set.erase(I);
+ /// else
+ /// ++I;
+ ///
+ /// Note that end() changes when elements are erased, unlike std::list.
+ ///
+ iterator erase(iterator I) {
+ assert(unsigned(I - begin()) < size() && "Invalid iterator");
+ if (I != end() - 1) {
+ *I = Dense.back();
+ unsigned BackIdx = ValIndexOf(Dense.back());
+ assert(BackIdx < Universe && "Invalid key in set. Did object mutate?");
+ Sparse[BackIdx] = I - begin();
+ }
+ // This depends on SmallVector::pop_back() not invalidating iterators.
+ // std::vector::pop_back() doesn't give that guarantee.
+ Dense.pop_back();
+ return I;
+ }
+
+ /// erase - Erases an element identified by Key, if it exists.
+ ///
+ /// @param Key The key identifying the element to erase.
+ /// @returns True when an element was erased, false if no element was found.
+ ///
+ bool erase(const KeyT &Key) {
+ iterator I = find(Key);
+ if (I == end())
+ return false;
+ erase(I);
+ return true;
+ }
+
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/Statistic.h b/include/llvm/ADT/Statistic.h
new file mode 100644
index 00000000000..b54d10b9dd3
--- /dev/null
+++ b/include/llvm/ADT/Statistic.h
@@ -0,0 +1,139 @@
+//===-- llvm/ADT/Statistic.h - Easy way to expose stats ---------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the 'Statistic' class, which is designed to be an easy way
+// to expose various metrics from passes. These statistics are printed at the
+// end of a run (from llvm_shutdown), when the -stats command line option is
+// passed on the command line.
+//
+// This is useful for reporting information like the number of instructions
+// simplified, optimized or removed by various transformations, like this:
+//
+// static Statistic NumInstsKilled("gcse", "Number of instructions killed");
+//
+// Later, in the code: ++NumInstsKilled;
+//
+// NOTE: Statistics *must* be declared as global variables.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_STATISTIC_H
+#define LLVM_ADT_STATISTIC_H
+
+#include "llvm/Support/Atomic.h"
+#include "llvm/Support/Valgrind.h"
+
+namespace llvm {
+class raw_ostream;
+
+class Statistic {
+public:
+ const char *Name;
+ const char *Desc;
+ volatile llvm::sys::cas_flag Value;
+ bool Initialized;
+
+ llvm::sys::cas_flag getValue() const { return Value; }
+ const char *getName() const { return Name; }
+ const char *getDesc() const { return Desc; }
+
+ /// construct - This should only be called for non-global statistics.
+ void construct(const char *name, const char *desc) {
+ Name = name; Desc = desc;
+ Value = 0; Initialized = 0;
+ }
+
+ // Allow use of this class as the value itself.
+ operator unsigned() const { return Value; }
+ const Statistic &operator=(unsigned Val) {
+ Value = Val;
+ return init();
+ }
+
+ const Statistic &operator++() {
+ // FIXME: This function and all those that follow carefully use an
+ // atomic operation to update the value safely in the presence of
+ // concurrent accesses, but not to read the return value, so the
+ // return value is not thread safe.
+ sys::AtomicIncrement(&Value);
+ return init();
+ }
+
+ unsigned operator++(int) {
+ init();
+ unsigned OldValue = Value;
+ sys::AtomicIncrement(&Value);
+ return OldValue;
+ }
+
+ const Statistic &operator--() {
+ sys::AtomicDecrement(&Value);
+ return init();
+ }
+
+ unsigned operator--(int) {
+ init();
+ unsigned OldValue = Value;
+ sys::AtomicDecrement(&Value);
+ return OldValue;
+ }
+
+ const Statistic &operator+=(const unsigned &V) {
+ if (!V) return *this;
+ sys::AtomicAdd(&Value, V);
+ return init();
+ }
+
+ const Statistic &operator-=(const unsigned &V) {
+ if (!V) return *this;
+ sys::AtomicAdd(&Value, -V);
+ return init();
+ }
+
+ const Statistic &operator*=(const unsigned &V) {
+ sys::AtomicMul(&Value, V);
+ return init();
+ }
+
+ const Statistic &operator/=(const unsigned &V) {
+ sys::AtomicDiv(&Value, V);
+ return init();
+ }
+
+protected:
+ Statistic &init() {
+ bool tmp = Initialized;
+ sys::MemoryFence();
+ if (!tmp) RegisterStatistic();
+ TsanHappensAfter(this);
+ return *this;
+ }
+ void RegisterStatistic();
+};
+
+// STATISTIC - A macro to make definition of statistics really simple. This
+// automatically passes the DEBUG_TYPE of the file into the statistic.
+#define STATISTIC(VARNAME, DESC) \
+ static llvm::Statistic VARNAME = { DEBUG_TYPE, DESC, 0, 0 }
+
+/// \brief Enable the collection and printing of statistics.
+void EnableStatistics();
+
+/// \brief Check if statistics are enabled.
+bool AreStatisticsEnabled();
+
+/// \brief Print statistics to the file returned by CreateInfoOutputFile().
+void PrintStatistics();
+
+/// \brief Print statistics to the given output stream.
+void PrintStatistics(raw_ostream &OS);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/StringExtras.h b/include/llvm/ADT/StringExtras.h
new file mode 100644
index 00000000000..1ba60ed114f
--- /dev/null
+++ b/include/llvm/ADT/StringExtras.h
@@ -0,0 +1,134 @@
+//===-- llvm/ADT/StringExtras.h - Useful string functions -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains some functions that are useful when dealing with strings.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_STRINGEXTRAS_H
+#define LLVM_ADT_STRINGEXTRAS_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+template<typename T> class SmallVectorImpl;
+
+/// hexdigit - Return the hexadecimal character for the
+/// given number \p X (which should be less than 16).
+static inline char hexdigit(unsigned X, bool LowerCase = false) {
+ const char HexChar = LowerCase ? 'a' : 'A';
+ return X < 10 ? '0' + X : HexChar + X - 10;
+}
+
+/// utohex_buffer - Emit the specified number into the buffer specified by
+/// BufferEnd, returning a pointer to the start of the string. This can be used
+/// like this: (note that the buffer must be large enough to handle any number):
+/// char Buffer[40];
+/// printf("0x%s", utohex_buffer(X, Buffer+40));
+///
+/// This should only be used with unsigned types.
+///
+template<typename IntTy>
+static inline char *utohex_buffer(IntTy X, char *BufferEnd) {
+ char *BufPtr = BufferEnd;
+ *--BufPtr = 0; // Null terminate buffer.
+ if (X == 0) {
+ *--BufPtr = '0'; // Handle special case.
+ return BufPtr;
+ }
+
+ while (X) {
+ unsigned char Mod = static_cast<unsigned char>(X) & 15;
+ *--BufPtr = hexdigit(Mod);
+ X >>= 4;
+ }
+ return BufPtr;
+}
+
+static inline std::string utohexstr(uint64_t X) {
+ char Buffer[17];
+ return utohex_buffer(X, Buffer+17);
+}
+
+static inline std::string utostr_32(uint32_t X, bool isNeg = false) {
+ char Buffer[11];
+ char *BufPtr = Buffer+11;
+
+ if (X == 0) *--BufPtr = '0'; // Handle special case...
+
+ while (X) {
+ *--BufPtr = '0' + char(X % 10);
+ X /= 10;
+ }
+
+ if (isNeg) *--BufPtr = '-'; // Add negative sign...
+
+ return std::string(BufPtr, Buffer+11);
+}
+
+static inline std::string utostr(uint64_t X, bool isNeg = false) {
+ char Buffer[21];
+ char *BufPtr = Buffer+21;
+
+ if (X == 0) *--BufPtr = '0'; // Handle special case...
+
+ while (X) {
+ *--BufPtr = '0' + char(X % 10);
+ X /= 10;
+ }
+
+ if (isNeg) *--BufPtr = '-'; // Add negative sign...
+ return std::string(BufPtr, Buffer+21);
+}
+
+
+static inline std::string itostr(int64_t X) {
+ if (X < 0)
+ return utostr(static_cast<uint64_t>(-X), true);
+ else
+ return utostr(static_cast<uint64_t>(X));
+}
+
+/// StrInStrNoCase - Portable version of strcasestr. Locates the first
+/// occurrence of string 's1' in string 's2', ignoring case. Returns
+/// the offset of s2 in s1 or npos if s2 cannot be found.
+StringRef::size_type StrInStrNoCase(StringRef s1, StringRef s2);
+
+/// getToken - This function extracts one token from source, ignoring any
+/// leading characters that appear in the Delimiters string, and ending the
+/// token at any of the characters that appear in the Delimiters string. If
+/// there are no tokens in the source string, an empty string is returned.
+/// The function returns a pair containing the extracted token and the
+/// remaining tail string.
+std::pair<StringRef, StringRef> getToken(StringRef Source,
+ StringRef Delimiters = " \t\n\v\f\r");
+
+/// SplitString - Split up the specified string according to the specified
+/// delimiters, appending the result fragments to the output list.
+void SplitString(StringRef Source,
+ SmallVectorImpl<StringRef> &OutFragments,
+ StringRef Delimiters = " \t\n\v\f\r");
+
+/// HashString - Hash function for strings.
+///
+/// This is the Bernstein hash function.
+//
+// FIXME: Investigate whether a modified bernstein hash function performs
+// better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
+// X*33+c -> X*33^c
+static inline unsigned HashString(StringRef Str, unsigned Result = 0) {
+ for (unsigned i = 0, e = Str.size(); i != e; ++i)
+ Result = Result * 33 + (unsigned char)Str[i];
+ return Result;
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/StringMap.h b/include/llvm/ADT/StringMap.h
new file mode 100644
index 00000000000..b4497a276d0
--- /dev/null
+++ b/include/llvm/ADT/StringMap.h
@@ -0,0 +1,463 @@
+//===--- StringMap.h - String Hash table map interface ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the StringMap class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_STRINGMAP_H
+#define LLVM_ADT_STRINGMAP_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Allocator.h"
+#include <cstring>
+
+namespace llvm {
+ template<typename ValueT>
+ class StringMapConstIterator;
+ template<typename ValueT>
+ class StringMapIterator;
+ template<typename ValueTy>
+ class StringMapEntry;
+
+/// StringMapEntryInitializer - This datatype can be partially specialized for
+/// various datatypes in a stringmap to allow them to be initialized when an
+/// entry is default constructed for the map.
+template<typename ValueTy>
+class StringMapEntryInitializer {
+public:
+ template <typename InitTy>
+ static void Initialize(StringMapEntry<ValueTy> &T, InitTy InitVal) {
+ T.second = InitVal;
+ }
+};
+
+
+/// StringMapEntryBase - Shared base class of StringMapEntry instances.
+class StringMapEntryBase {
+ unsigned StrLen;
+public:
+ explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
+
+ unsigned getKeyLength() const { return StrLen; }
+};
+
+/// StringMapImpl - This is the base class of StringMap that is shared among
+/// all of its instantiations.
+class StringMapImpl {
+protected:
+ // Array of NumBuckets pointers to entries, null pointers are holes.
+ // TheTable[NumBuckets] contains a sentinel value for easy iteration. Follwed
+ // by an array of the actual hash values as unsigned integers.
+ StringMapEntryBase **TheTable;
+ unsigned NumBuckets;
+ unsigned NumItems;
+ unsigned NumTombstones;
+ unsigned ItemSize;
+protected:
+ explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
+ // Initialize the map with zero buckets to allocation.
+ TheTable = 0;
+ NumBuckets = 0;
+ NumItems = 0;
+ NumTombstones = 0;
+ }
+ StringMapImpl(unsigned InitSize, unsigned ItemSize);
+ void RehashTable();
+
+ /// LookupBucketFor - Look up the bucket that the specified string should end
+ /// up in. If it already exists as a key in the map, the Item pointer for the
+ /// specified bucket will be non-null. Otherwise, it will be null. In either
+ /// case, the FullHashValue field of the bucket will be set to the hash value
+ /// of the string.
+ unsigned LookupBucketFor(StringRef Key);
+
+ /// FindKey - Look up the bucket that contains the specified key. If it exists
+ /// in the map, return the bucket number of the key. Otherwise return -1.
+ /// This does not modify the map.
+ int FindKey(StringRef Key) const;
+
+ /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
+ /// delete it. This aborts if the value isn't in the table.
+ void RemoveKey(StringMapEntryBase *V);
+
+ /// RemoveKey - Remove the StringMapEntry for the specified key from the
+ /// table, returning it. If the key is not in the table, this returns null.
+ StringMapEntryBase *RemoveKey(StringRef Key);
+private:
+ void init(unsigned Size);
+public:
+ static StringMapEntryBase *getTombstoneVal() {
+ return (StringMapEntryBase*)-1;
+ }
+
+ unsigned getNumBuckets() const { return NumBuckets; }
+ unsigned getNumItems() const { return NumItems; }
+
+ bool empty() const { return NumItems == 0; }
+ unsigned size() const { return NumItems; }
+};
+
+/// StringMapEntry - This is used to represent one value that is inserted into
+/// a StringMap. It contains the Value itself and the key: the string length
+/// and data.
+template<typename ValueTy>
+class StringMapEntry : public StringMapEntryBase {
+public:
+ ValueTy second;
+
+ explicit StringMapEntry(unsigned strLen)
+ : StringMapEntryBase(strLen), second() {}
+ StringMapEntry(unsigned strLen, const ValueTy &V)
+ : StringMapEntryBase(strLen), second(V) {}
+
+ StringRef getKey() const {
+ return StringRef(getKeyData(), getKeyLength());
+ }
+
+ const ValueTy &getValue() const { return second; }
+ ValueTy &getValue() { return second; }
+
+ void setValue(const ValueTy &V) { second = V; }
+
+ /// getKeyData - Return the start of the string data that is the key for this
+ /// value. The string data is always stored immediately after the
+ /// StringMapEntry object.
+ const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
+
+ StringRef first() const { return StringRef(getKeyData(), getKeyLength()); }
+
+ /// Create - Create a StringMapEntry for the specified key and default
+ /// construct the value.
+ template<typename AllocatorTy, typename InitType>
+ static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
+ AllocatorTy &Allocator,
+ InitType InitVal) {
+ unsigned KeyLength = static_cast<unsigned>(KeyEnd-KeyStart);
+
+ // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
+ // in. Allocate a new item with space for the string at the end and a null
+ // terminator.
+
+ unsigned AllocSize = static_cast<unsigned>(sizeof(StringMapEntry))+
+ KeyLength+1;
+ unsigned Alignment = alignOf<StringMapEntry>();
+
+ StringMapEntry *NewItem =
+ static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
+
+ // Default construct the value.
+ new (NewItem) StringMapEntry(KeyLength);
+
+ // Copy the string information.
+ char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
+ memcpy(StrBuffer, KeyStart, KeyLength);
+ StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
+
+ // Initialize the value if the client wants to.
+ StringMapEntryInitializer<ValueTy>::Initialize(*NewItem, InitVal);
+ return NewItem;
+ }
+
+ template<typename AllocatorTy>
+ static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
+ AllocatorTy &Allocator) {
+ return Create(KeyStart, KeyEnd, Allocator, 0);
+ }
+
+
+ /// Create - Create a StringMapEntry with normal malloc/free.
+ template<typename InitType>
+ static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
+ InitType InitVal) {
+ MallocAllocator A;
+ return Create(KeyStart, KeyEnd, A, InitVal);
+ }
+
+ static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
+ return Create(KeyStart, KeyEnd, ValueTy());
+ }
+
+ /// GetStringMapEntryFromValue - Given a value that is known to be embedded
+ /// into a StringMapEntry, return the StringMapEntry itself.
+ static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
+ StringMapEntry *EPtr = 0;
+ char *Ptr = reinterpret_cast<char*>(&V) -
+ (reinterpret_cast<char*>(&EPtr->second) -
+ reinterpret_cast<char*>(EPtr));
+ return *reinterpret_cast<StringMapEntry*>(Ptr);
+ }
+ static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
+ return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
+ }
+
+ /// GetStringMapEntryFromKeyData - Given key data that is known to be embedded
+ /// into a StringMapEntry, return the StringMapEntry itself.
+ static StringMapEntry &GetStringMapEntryFromKeyData(const char *KeyData) {
+ char *Ptr = const_cast<char*>(KeyData) - sizeof(StringMapEntry<ValueTy>);
+ return *reinterpret_cast<StringMapEntry*>(Ptr);
+ }
+
+
+ /// Destroy - Destroy this StringMapEntry, releasing memory back to the
+ /// specified allocator.
+ template<typename AllocatorTy>
+ void Destroy(AllocatorTy &Allocator) {
+ // Free memory referenced by the item.
+ this->~StringMapEntry();
+ Allocator.Deallocate(this);
+ }
+
+ /// Destroy this object, releasing memory back to the malloc allocator.
+ void Destroy() {
+ MallocAllocator A;
+ Destroy(A);
+ }
+};
+
+
+/// StringMap - This is an unconventional map that is specialized for handling
+/// keys that are "strings", which are basically ranges of bytes. This does some
+/// funky memory allocation and hashing things to make it extremely efficient,
+/// storing the string data *after* the value in the map.
+template<typename ValueTy, typename AllocatorTy = MallocAllocator>
+class StringMap : public StringMapImpl {
+ AllocatorTy Allocator;
+public:
+ typedef StringMapEntry<ValueTy> MapEntryTy;
+
+ StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
+ explicit StringMap(unsigned InitialSize)
+ : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
+
+ explicit StringMap(AllocatorTy A)
+ : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), Allocator(A) {}
+
+ StringMap(const StringMap &RHS)
+ : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
+ assert(RHS.empty() &&
+ "Copy ctor from non-empty stringmap not implemented yet!");
+ (void)RHS;
+ }
+ void operator=(const StringMap &RHS) {
+ assert(RHS.empty() &&
+ "assignment from non-empty stringmap not implemented yet!");
+ (void)RHS;
+ clear();
+ }
+
+ typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
+ typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
+ AllocatorRefTy getAllocator() { return Allocator; }
+ AllocatorCRefTy getAllocator() const { return Allocator; }
+
+ typedef const char* key_type;
+ typedef ValueTy mapped_type;
+ typedef StringMapEntry<ValueTy> value_type;
+ typedef size_t size_type;
+
+ typedef StringMapConstIterator<ValueTy> const_iterator;
+ typedef StringMapIterator<ValueTy> iterator;
+
+ iterator begin() {
+ return iterator(TheTable, NumBuckets == 0);
+ }
+ iterator end() {
+ return iterator(TheTable+NumBuckets, true);
+ }
+ const_iterator begin() const {
+ return const_iterator(TheTable, NumBuckets == 0);
+ }
+ const_iterator end() const {
+ return const_iterator(TheTable+NumBuckets, true);
+ }
+
+ iterator find(StringRef Key) {
+ int Bucket = FindKey(Key);
+ if (Bucket == -1) return end();
+ return iterator(TheTable+Bucket, true);
+ }
+
+ const_iterator find(StringRef Key) const {
+ int Bucket = FindKey(Key);
+ if (Bucket == -1) return end();
+ return const_iterator(TheTable+Bucket, true);
+ }
+
+ /// lookup - Return the entry for the specified key, or a default
+ /// constructed value if no such entry exists.
+ ValueTy lookup(StringRef Key) const {
+ const_iterator it = find(Key);
+ if (it != end())
+ return it->second;
+ return ValueTy();
+ }
+
+ ValueTy &operator[](StringRef Key) {
+ return GetOrCreateValue(Key).getValue();
+ }
+
+ size_type count(StringRef Key) const {
+ return find(Key) == end() ? 0 : 1;
+ }
+
+ /// insert - Insert the specified key/value pair into the map. If the key
+ /// already exists in the map, return false and ignore the request, otherwise
+ /// insert it and return true.
+ bool insert(MapEntryTy *KeyValue) {
+ unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
+ StringMapEntryBase *&Bucket = TheTable[BucketNo];
+ if (Bucket && Bucket != getTombstoneVal())
+ return false; // Already exists in map.
+
+ if (Bucket == getTombstoneVal())
+ --NumTombstones;
+ Bucket = KeyValue;
+ ++NumItems;
+ assert(NumItems + NumTombstones <= NumBuckets);
+
+ RehashTable();
+ return true;
+ }
+
+ // clear - Empties out the StringMap
+ void clear() {
+ if (empty()) return;
+
+ // Zap all values, resetting the keys back to non-present (not tombstone),
+ // which is safe because we're removing all elements.
+ for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
+ StringMapEntryBase *&Bucket = TheTable[I];
+ if (Bucket && Bucket != getTombstoneVal()) {
+ static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
+ Bucket = 0;
+ }
+ }
+
+ NumItems = 0;
+ NumTombstones = 0;
+ }
+
+ /// GetOrCreateValue - Look up the specified key in the table. If a value
+ /// exists, return it. Otherwise, default construct a value, insert it, and
+ /// return.
+ template <typename InitTy>
+ MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
+ unsigned BucketNo = LookupBucketFor(Key);
+ StringMapEntryBase *&Bucket = TheTable[BucketNo];
+ if (Bucket && Bucket != getTombstoneVal())
+ return *static_cast<MapEntryTy*>(Bucket);
+
+ MapEntryTy *NewItem =
+ MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
+
+ if (Bucket == getTombstoneVal())
+ --NumTombstones;
+ ++NumItems;
+ assert(NumItems + NumTombstones <= NumBuckets);
+
+ // Fill in the bucket for the hash table. The FullHashValue was already
+ // filled in by LookupBucketFor.
+ Bucket = NewItem;
+
+ RehashTable();
+ return *NewItem;
+ }
+
+ MapEntryTy &GetOrCreateValue(StringRef Key) {
+ return GetOrCreateValue(Key, ValueTy());
+ }
+
+ /// remove - Remove the specified key/value pair from the map, but do not
+ /// erase it. This aborts if the key is not in the map.
+ void remove(MapEntryTy *KeyValue) {
+ RemoveKey(KeyValue);
+ }
+
+ void erase(iterator I) {
+ MapEntryTy &V = *I;
+ remove(&V);
+ V.Destroy(Allocator);
+ }
+
+ bool erase(StringRef Key) {
+ iterator I = find(Key);
+ if (I == end()) return false;
+ erase(I);
+ return true;
+ }
+
+ ~StringMap() {
+ clear();
+ free(TheTable);
+ }
+};
+
+
+template<typename ValueTy>
+class StringMapConstIterator {
+protected:
+ StringMapEntryBase **Ptr;
+public:
+ typedef StringMapEntry<ValueTy> value_type;
+
+ explicit StringMapConstIterator(StringMapEntryBase **Bucket,
+ bool NoAdvance = false)
+ : Ptr(Bucket) {
+ if (!NoAdvance) AdvancePastEmptyBuckets();
+ }
+
+ const value_type &operator*() const {
+ return *static_cast<StringMapEntry<ValueTy>*>(*Ptr);
+ }
+ const value_type *operator->() const {
+ return static_cast<StringMapEntry<ValueTy>*>(*Ptr);
+ }
+
+ bool operator==(const StringMapConstIterator &RHS) const {
+ return Ptr == RHS.Ptr;
+ }
+ bool operator!=(const StringMapConstIterator &RHS) const {
+ return Ptr != RHS.Ptr;
+ }
+
+ inline StringMapConstIterator& operator++() { // Preincrement
+ ++Ptr;
+ AdvancePastEmptyBuckets();
+ return *this;
+ }
+ StringMapConstIterator operator++(int) { // Postincrement
+ StringMapConstIterator tmp = *this; ++*this; return tmp;
+ }
+
+private:
+ void AdvancePastEmptyBuckets() {
+ while (*Ptr == 0 || *Ptr == StringMapImpl::getTombstoneVal())
+ ++Ptr;
+ }
+};
+
+template<typename ValueTy>
+class StringMapIterator : public StringMapConstIterator<ValueTy> {
+public:
+ explicit StringMapIterator(StringMapEntryBase **Bucket,
+ bool NoAdvance = false)
+ : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
+ }
+ StringMapEntry<ValueTy> &operator*() const {
+ return *static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
+ }
+ StringMapEntry<ValueTy> *operator->() const {
+ return static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
+ }
+};
+
+}
+
+#endif
diff --git a/include/llvm/ADT/StringRef.h b/include/llvm/ADT/StringRef.h
new file mode 100644
index 00000000000..292bde0cd90
--- /dev/null
+++ b/include/llvm/ADT/StringRef.h
@@ -0,0 +1,554 @@
+//===--- StringRef.h - Constant String Reference Wrapper --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_STRINGREF_H
+#define LLVM_ADT_STRINGREF_H
+
+#include "llvm/Support/type_traits.h"
+
+#include <algorithm>
+#include <cassert>
+#include <cstring>
+#include <limits>
+#include <string>
+#include <utility>
+
+namespace llvm {
+ template<typename T>
+ class SmallVectorImpl;
+ class APInt;
+ class hash_code;
+ class StringRef;
+
+ /// Helper functions for StringRef::getAsInteger.
+ bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
+ unsigned long long &Result);
+
+ bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
+
+ /// StringRef - Represent a constant reference to a string, i.e. a character
+ /// array and a length, which need not be null terminated.
+ ///
+ /// This class does not own the string data, it is expected to be used in
+ /// situations where the character data resides in some other buffer, whose
+ /// lifetime extends past that of the StringRef. For this reason, it is not in
+ /// general safe to store a StringRef.
+ class StringRef {
+ public:
+ typedef const char *iterator;
+ typedef const char *const_iterator;
+ static const size_t npos = ~size_t(0);
+ typedef size_t size_type;
+
+ private:
+ /// The start of the string, in an external buffer.
+ const char *Data;
+
+ /// The length of the string.
+ size_t Length;
+
+ // Workaround PR5482: nearly all gcc 4.x miscompile StringRef and std::min()
+ // Changing the arg of min to be an integer, instead of a reference to an
+ // integer works around this bug.
+ static size_t min(size_t a, size_t b) { return a < b ? a : b; }
+ static size_t max(size_t a, size_t b) { return a > b ? a : b; }
+
+ // Workaround memcmp issue with null pointers (undefined behavior)
+ // by providing a specialized version
+ static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
+ if (Length == 0) { return 0; }
+ return ::memcmp(Lhs,Rhs,Length);
+ }
+
+ public:
+ /// @name Constructors
+ /// @{
+
+ /// Construct an empty string ref.
+ /*implicit*/ StringRef() : Data(0), Length(0) {}
+
+ /// Construct a string ref from a cstring.
+ /*implicit*/ StringRef(const char *Str)
+ : Data(Str) {
+ assert(Str && "StringRef cannot be built from a NULL argument");
+ Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
+ }
+
+ /// Construct a string ref from a pointer and length.
+ /*implicit*/ StringRef(const char *data, size_t length)
+ : Data(data), Length(length) {
+ assert((data || length == 0) &&
+ "StringRef cannot be built from a NULL argument with non-null length");
+ }
+
+ /// Construct a string ref from an std::string.
+ /*implicit*/ StringRef(const std::string &Str)
+ : Data(Str.data()), Length(Str.length()) {}
+
+ /// @}
+ /// @name Iterators
+ /// @{
+
+ iterator begin() const { return Data; }
+
+ iterator end() const { return Data + Length; }
+
+ /// @}
+ /// @name String Operations
+ /// @{
+
+ /// data - Get a pointer to the start of the string (which may not be null
+ /// terminated).
+ const char *data() const { return Data; }
+
+ /// empty - Check if the string is empty.
+ bool empty() const { return Length == 0; }
+
+ /// size - Get the string size.
+ size_t size() const { return Length; }
+
+ /// front - Get the first character in the string.
+ char front() const {
+ assert(!empty());
+ return Data[0];
+ }
+
+ /// back - Get the last character in the string.
+ char back() const {
+ assert(!empty());
+ return Data[Length-1];
+ }
+
+ /// equals - Check for string equality, this is more efficient than
+ /// compare() when the relative ordering of inequal strings isn't needed.
+ bool equals(StringRef RHS) const {
+ return (Length == RHS.Length &&
+ compareMemory(Data, RHS.Data, RHS.Length) == 0);
+ }
+
+ /// equals_lower - Check for string equality, ignoring case.
+ bool equals_lower(StringRef RHS) const {
+ return Length == RHS.Length && compare_lower(RHS) == 0;
+ }
+
+ /// compare - Compare two strings; the result is -1, 0, or 1 if this string
+ /// is lexicographically less than, equal to, or greater than the \p RHS.
+ int compare(StringRef RHS) const {
+ // Check the prefix for a mismatch.
+ if (int Res = compareMemory(Data, RHS.Data, min(Length, RHS.Length)))
+ return Res < 0 ? -1 : 1;
+
+ // Otherwise the prefixes match, so we only need to check the lengths.
+ if (Length == RHS.Length)
+ return 0;
+ return Length < RHS.Length ? -1 : 1;
+ }
+
+ /// compare_lower - Compare two strings, ignoring case.
+ int compare_lower(StringRef RHS) const;
+
+ /// compare_numeric - Compare two strings, treating sequences of digits as
+ /// numbers.
+ int compare_numeric(StringRef RHS) const;
+
+ /// \brief Determine the edit distance between this string and another
+ /// string.
+ ///
+ /// \param Other the string to compare this string against.
+ ///
+ /// \param AllowReplacements whether to allow character
+ /// replacements (change one character into another) as a single
+ /// operation, rather than as two operations (an insertion and a
+ /// removal).
+ ///
+ /// \param MaxEditDistance If non-zero, the maximum edit distance that
+ /// this routine is allowed to compute. If the edit distance will exceed
+ /// that maximum, returns \c MaxEditDistance+1.
+ ///
+ /// \returns the minimum number of character insertions, removals,
+ /// or (if \p AllowReplacements is \c true) replacements needed to
+ /// transform one of the given strings into the other. If zero,
+ /// the strings are identical.
+ unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
+ unsigned MaxEditDistance = 0);
+
+ /// str - Get the contents as an std::string.
+ std::string str() const {
+ if (Data == 0) return std::string();
+ return std::string(Data, Length);
+ }
+
+ /// @}
+ /// @name Operator Overloads
+ /// @{
+
+ char operator[](size_t Index) const {
+ assert(Index < Length && "Invalid index!");
+ return Data[Index];
+ }
+
+ /// @}
+ /// @name Type Conversions
+ /// @{
+
+ operator std::string() const {
+ return str();
+ }
+
+ /// @}
+ /// @name String Predicates
+ /// @{
+
+ /// Check if this string starts with the given \p Prefix.
+ bool startswith(StringRef Prefix) const {
+ return Length >= Prefix.Length &&
+ compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
+ }
+
+ /// Check if this string ends with the given \p Suffix.
+ bool endswith(StringRef Suffix) const {
+ return Length >= Suffix.Length &&
+ compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
+ }
+
+ /// @}
+ /// @name String Searching
+ /// @{
+
+ /// Search for the first character \p C in the string.
+ ///
+ /// \returns The index of the first occurrence of \p C, or npos if not
+ /// found.
+ size_t find(char C, size_t From = 0) const {
+ for (size_t i = min(From, Length), e = Length; i != e; ++i)
+ if (Data[i] == C)
+ return i;
+ return npos;
+ }
+
+ /// Search for the first string \p Str in the string.
+ ///
+ /// \returns The index of the first occurrence of \p Str, or npos if not
+ /// found.
+ size_t find(StringRef Str, size_t From = 0) const;
+
+ /// Search for the last character \p C in the string.
+ ///
+ /// \returns The index of the last occurrence of \p C, or npos if not
+ /// found.
+ size_t rfind(char C, size_t From = npos) const {
+ From = min(From, Length);
+ size_t i = From;
+ while (i != 0) {
+ --i;
+ if (Data[i] == C)
+ return i;
+ }
+ return npos;
+ }
+
+ /// Search for the last string \p Str in the string.
+ ///
+ /// \returns The index of the last occurrence of \p Str, or npos if not
+ /// found.
+ size_t rfind(StringRef Str) const;
+
+ /// Find the first character in the string that is \p C, or npos if not
+ /// found. Same as find.
+ size_type find_first_of(char C, size_t From = 0) const {
+ return find(C, From);
+ }
+
+ /// Find the first character in the string that is in \p Chars, or npos if
+ /// not found.
+ ///
+ /// Complexity: O(size() + Chars.size())
+ size_type find_first_of(StringRef Chars, size_t From = 0) const;
+
+ /// Find the first character in the string that is not \p C or npos if not
+ /// found.
+ size_type find_first_not_of(char C, size_t From = 0) const;
+
+ /// Find the first character in the string that is not in the string
+ /// \p Chars, or npos if not found.
+ ///
+ /// Complexity: O(size() + Chars.size())
+ size_type find_first_not_of(StringRef Chars, size_t From = 0) const;
+
+ /// Find the last character in the string that is \p C, or npos if not
+ /// found.
+ size_type find_last_of(char C, size_t From = npos) const {
+ return rfind(C, From);
+ }
+
+ /// Find the last character in the string that is in \p C, or npos if not
+ /// found.
+ ///
+ /// Complexity: O(size() + Chars.size())
+ size_type find_last_of(StringRef Chars, size_t From = npos) const;
+
+ /// Find the last character in the string that is not \p C, or npos if not
+ /// found.
+ size_type find_last_not_of(char C, size_t From = npos) const;
+
+ /// Find the last character in the string that is not in \p Chars, or
+ /// npos if not found.
+ ///
+ /// Complexity: O(size() + Chars.size())
+ size_type find_last_not_of(StringRef Chars, size_t From = npos) const;
+
+ /// @}
+ /// @name Helpful Algorithms
+ /// @{
+
+ /// Return the number of occurrences of \p C in the string.
+ size_t count(char C) const {
+ size_t Count = 0;
+ for (size_t i = 0, e = Length; i != e; ++i)
+ if (Data[i] == C)
+ ++Count;
+ return Count;
+ }
+
+ /// Return the number of non-overlapped occurrences of \p Str in
+ /// the string.
+ size_t count(StringRef Str) const;
+
+ /// Parse the current string as an integer of the specified radix. If
+ /// \p Radix is specified as zero, this does radix autosensing using
+ /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
+ ///
+ /// If the string is invalid or if only a subset of the string is valid,
+ /// this returns true to signify the error. The string is considered
+ /// erroneous if empty or if it overflows T.
+ template <typename T>
+ typename enable_if_c<std::numeric_limits<T>::is_signed, bool>::type
+ getAsInteger(unsigned Radix, T &Result) const {
+ long long LLVal;
+ if (getAsSignedInteger(*this, Radix, LLVal) ||
+ static_cast<T>(LLVal) != LLVal)
+ return true;
+ Result = LLVal;
+ return false;
+ }
+
+ template <typename T>
+ typename enable_if_c<!std::numeric_limits<T>::is_signed, bool>::type
+ getAsInteger(unsigned Radix, T &Result) const {
+ unsigned long long ULLVal;
+ if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
+ static_cast<T>(ULLVal) != ULLVal)
+ return true;
+ Result = ULLVal;
+ return false;
+ }
+
+ /// Parse the current string as an integer of the specified \p Radix, or of
+ /// an autosensed radix if the \p Radix given is 0. The current value in
+ /// \p Result is discarded, and the storage is changed to be wide enough to
+ /// store the parsed integer.
+ ///
+ /// \returns true if the string does not solely consist of a valid
+ /// non-empty number in the appropriate base.
+ ///
+ /// APInt::fromString is superficially similar but assumes the
+ /// string is well-formed in the given radix.
+ bool getAsInteger(unsigned Radix, APInt &Result) const;
+
+ /// @}
+ /// @name String Operations
+ /// @{
+
+ // Convert the given ASCII string to lowercase.
+ std::string lower() const;
+
+ /// Convert the given ASCII string to uppercase.
+ std::string upper() const;
+
+ /// @}
+ /// @name Substring Operations
+ /// @{
+
+ /// Return a reference to the substring from [Start, Start + N).
+ ///
+ /// \param Start The index of the starting character in the substring; if
+ /// the index is npos or greater than the length of the string then the
+ /// empty substring will be returned.
+ ///
+ /// \param N The number of characters to included in the substring. If N
+ /// exceeds the number of characters remaining in the string, the string
+ /// suffix (starting with \p Start) will be returned.
+ StringRef substr(size_t Start, size_t N = npos) const {
+ Start = min(Start, Length);
+ return StringRef(Data + Start, min(N, Length - Start));
+ }
+
+ /// Return a StringRef equal to 'this' but with the first \p N elements
+ /// dropped.
+ StringRef drop_front(unsigned N = 1) const {
+ assert(size() >= N && "Dropping more elements than exist");
+ return substr(N);
+ }
+
+ /// Return a StringRef equal to 'this' but with the last \p N elements
+ /// dropped.
+ StringRef drop_back(unsigned N = 1) const {
+ assert(size() >= N && "Dropping more elements than exist");
+ return substr(0, size()-N);
+ }
+
+ /// Return a reference to the substring from [Start, End).
+ ///
+ /// \param Start The index of the starting character in the substring; if
+ /// the index is npos or greater than the length of the string then the
+ /// empty substring will be returned.
+ ///
+ /// \param End The index following the last character to include in the
+ /// substring. If this is npos, or less than \p Start, or exceeds the
+ /// number of characters remaining in the string, the string suffix
+ /// (starting with \p Start) will be returned.
+ StringRef slice(size_t Start, size_t End) const {
+ Start = min(Start, Length);
+ End = min(max(Start, End), Length);
+ return StringRef(Data + Start, End - Start);
+ }
+
+ /// Split into two substrings around the first occurrence of a separator
+ /// character.
+ ///
+ /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
+ /// such that (*this == LHS + Separator + RHS) is true and RHS is
+ /// maximal. If \p Separator is not in the string, then the result is a
+ /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
+ ///
+ /// \param Separator The character to split on.
+ /// \returns The split substrings.
+ std::pair<StringRef, StringRef> split(char Separator) const {
+ size_t Idx = find(Separator);
+ if (Idx == npos)
+ return std::make_pair(*this, StringRef());
+ return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
+ }
+
+ /// Split into two substrings around the first occurrence of a separator
+ /// string.
+ ///
+ /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
+ /// such that (*this == LHS + Separator + RHS) is true and RHS is
+ /// maximal. If \p Separator is not in the string, then the result is a
+ /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
+ ///
+ /// \param Separator - The string to split on.
+ /// \return - The split substrings.
+ std::pair<StringRef, StringRef> split(StringRef Separator) const {
+ size_t Idx = find(Separator);
+ if (Idx == npos)
+ return std::make_pair(*this, StringRef());
+ return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
+ }
+
+ /// Split into substrings around the occurrences of a separator string.
+ ///
+ /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
+ /// \p MaxSplit splits are done and consequently <= \p MaxSplit
+ /// elements are added to A.
+ /// If \p KeepEmpty is false, empty strings are not added to \p A. They
+ /// still count when considering \p MaxSplit
+ /// An useful invariant is that
+ /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
+ ///
+ /// \param A - Where to put the substrings.
+ /// \param Separator - The string to split on.
+ /// \param MaxSplit - The maximum number of times the string is split.
+ /// \param KeepEmpty - True if empty substring should be added.
+ void split(SmallVectorImpl<StringRef> &A,
+ StringRef Separator, int MaxSplit = -1,
+ bool KeepEmpty = true) const;
+
+ /// Split into two substrings around the last occurrence of a separator
+ /// character.
+ ///
+ /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
+ /// such that (*this == LHS + Separator + RHS) is true and RHS is
+ /// minimal. If \p Separator is not in the string, then the result is a
+ /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
+ ///
+ /// \param Separator - The character to split on.
+ /// \return - The split substrings.
+ std::pair<StringRef, StringRef> rsplit(char Separator) const {
+ size_t Idx = rfind(Separator);
+ if (Idx == npos)
+ return std::make_pair(*this, StringRef());
+ return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
+ }
+
+ /// Return string with consecutive characters in \p Chars starting from
+ /// the left removed.
+ StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
+ return drop_front(std::min(Length, find_first_not_of(Chars)));
+ }
+
+ /// Return string with consecutive characters in \p Chars starting from
+ /// the right removed.
+ StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
+ return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
+ }
+
+ /// Return string with consecutive characters in \p Chars starting from
+ /// the left and right removed.
+ StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
+ return ltrim(Chars).rtrim(Chars);
+ }
+
+ /// @}
+ };
+
+ /// @name StringRef Comparison Operators
+ /// @{
+
+ inline bool operator==(StringRef LHS, StringRef RHS) {
+ return LHS.equals(RHS);
+ }
+
+ inline bool operator!=(StringRef LHS, StringRef RHS) {
+ return !(LHS == RHS);
+ }
+
+ inline bool operator<(StringRef LHS, StringRef RHS) {
+ return LHS.compare(RHS) == -1;
+ }
+
+ inline bool operator<=(StringRef LHS, StringRef RHS) {
+ return LHS.compare(RHS) != 1;
+ }
+
+ inline bool operator>(StringRef LHS, StringRef RHS) {
+ return LHS.compare(RHS) == 1;
+ }
+
+ inline bool operator>=(StringRef LHS, StringRef RHS) {
+ return LHS.compare(RHS) != -1;
+ }
+
+ inline std::string &operator+=(std::string &buffer, llvm::StringRef string) {
+ return buffer.append(string.data(), string.size());
+ }
+
+ /// @}
+
+ /// \brief Compute a hash_code for a StringRef.
+ hash_code hash_value(StringRef S);
+
+ // StringRefs can be treated like a POD type.
+ template <typename T> struct isPodLike;
+ template <> struct isPodLike<StringRef> { static const bool value = true; };
+
+}
+
+#endif
diff --git a/include/llvm/ADT/StringSet.h b/include/llvm/ADT/StringSet.h
new file mode 100644
index 00000000000..9c55f6b70e3
--- /dev/null
+++ b/include/llvm/ADT/StringSet.h
@@ -0,0 +1,38 @@
+//===--- StringSet.h - The LLVM Compiler Driver -----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open
+// Source License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// StringSet - A set-like wrapper for the StringMap.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_STRINGSET_H
+#define LLVM_ADT_STRINGSET_H
+
+#include "llvm/ADT/StringMap.h"
+
+namespace llvm {
+
+ /// StringSet - A wrapper for StringMap that provides set-like
+ /// functionality. Only insert() and count() methods are used by my
+ /// code.
+ template <class AllocatorTy = llvm::MallocAllocator>
+ class StringSet : public llvm::StringMap<char, AllocatorTy> {
+ typedef llvm::StringMap<char, AllocatorTy> base;
+ public:
+ bool insert(StringRef InLang) {
+ assert(!InLang.empty());
+ const char *KeyStart = InLang.data();
+ const char *KeyEnd = KeyStart + InLang.size();
+ return base::insert(llvm::StringMapEntry<char>::
+ Create(KeyStart, KeyEnd, base::getAllocator(), '+'));
+ }
+ };
+}
+
+#endif // LLVM_ADT_STRINGSET_H
diff --git a/include/llvm/ADT/StringSwitch.h b/include/llvm/ADT/StringSwitch.h
new file mode 100644
index 00000000000..7fd6e279603
--- /dev/null
+++ b/include/llvm/ADT/StringSwitch.h
@@ -0,0 +1,126 @@
+//===--- StringSwitch.h - Switch-on-literal-string Construct --------------===/
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//===----------------------------------------------------------------------===/
+//
+// This file implements the StringSwitch template, which mimics a switch()
+// statement whose cases are string literals.
+//
+//===----------------------------------------------------------------------===/
+#ifndef LLVM_ADT_STRINGSWITCH_H
+#define LLVM_ADT_STRINGSWITCH_H
+
+#include "llvm/ADT/StringRef.h"
+#include <cassert>
+#include <cstring>
+
+namespace llvm {
+
+/// \brief A switch()-like statement whose cases are string literals.
+///
+/// The StringSwitch class is a simple form of a switch() statement that
+/// determines whether the given string matches one of the given string
+/// literals. The template type parameter \p T is the type of the value that
+/// will be returned from the string-switch expression. For example,
+/// the following code switches on the name of a color in \c argv[i]:
+///
+/// \code
+/// Color color = StringSwitch<Color>(argv[i])
+/// .Case("red", Red)
+/// .Case("orange", Orange)
+/// .Case("yellow", Yellow)
+/// .Case("green", Green)
+/// .Case("blue", Blue)
+/// .Case("indigo", Indigo)
+/// .Cases("violet", "purple", Violet)
+/// .Default(UnknownColor);
+/// \endcode
+template<typename T, typename R = T>
+class StringSwitch {
+ /// \brief The string we are matching.
+ StringRef Str;
+
+ /// \brief The pointer to the result of this switch statement, once known,
+ /// null before that.
+ const T *Result;
+
+public:
+ explicit StringSwitch(StringRef S)
+ : Str(S), Result(0) { }
+
+ template<unsigned N>
+ StringSwitch& Case(const char (&S)[N], const T& Value) {
+ if (!Result && N-1 == Str.size() &&
+ (std::memcmp(S, Str.data(), N-1) == 0)) {
+ Result = &Value;
+ }
+
+ return *this;
+ }
+
+ template<unsigned N>
+ StringSwitch& EndsWith(const char (&S)[N], const T &Value) {
+ if (!Result && Str.size() >= N-1 &&
+ std::memcmp(S, Str.data() + Str.size() + 1 - N, N-1) == 0) {
+ Result = &Value;
+ }
+
+ return *this;
+ }
+
+ template<unsigned N>
+ StringSwitch& StartsWith(const char (&S)[N], const T &Value) {
+ if (!Result && Str.size() >= N-1 &&
+ std::memcmp(S, Str.data(), N-1) == 0) {
+ Result = &Value;
+ }
+
+ return *this;
+ }
+
+ template<unsigned N0, unsigned N1>
+ StringSwitch& Cases(const char (&S0)[N0], const char (&S1)[N1],
+ const T& Value) {
+ return Case(S0, Value).Case(S1, Value);
+ }
+
+ template<unsigned N0, unsigned N1, unsigned N2>
+ StringSwitch& Cases(const char (&S0)[N0], const char (&S1)[N1],
+ const char (&S2)[N2], const T& Value) {
+ return Case(S0, Value).Case(S1, Value).Case(S2, Value);
+ }
+
+ template<unsigned N0, unsigned N1, unsigned N2, unsigned N3>
+ StringSwitch& Cases(const char (&S0)[N0], const char (&S1)[N1],
+ const char (&S2)[N2], const char (&S3)[N3],
+ const T& Value) {
+ return Case(S0, Value).Case(S1, Value).Case(S2, Value).Case(S3, Value);
+ }
+
+ template<unsigned N0, unsigned N1, unsigned N2, unsigned N3, unsigned N4>
+ StringSwitch& Cases(const char (&S0)[N0], const char (&S1)[N1],
+ const char (&S2)[N2], const char (&S3)[N3],
+ const char (&S4)[N4], const T& Value) {
+ return Case(S0, Value).Case(S1, Value).Case(S2, Value).Case(S3, Value)
+ .Case(S4, Value);
+ }
+
+ R Default(const T& Value) const {
+ if (Result)
+ return *Result;
+
+ return Value;
+ }
+
+ operator R() const {
+ assert(Result && "Fell off the end of a string-switch");
+ return *Result;
+ }
+};
+
+} // end namespace llvm
+
+#endif // LLVM_ADT_STRINGSWITCH_H
diff --git a/include/llvm/ADT/TinyPtrVector.h b/include/llvm/ADT/TinyPtrVector.h
new file mode 100644
index 00000000000..d3d33b8adde
--- /dev/null
+++ b/include/llvm/ADT/TinyPtrVector.h
@@ -0,0 +1,291 @@
+//===- llvm/ADT/TinyPtrVector.h - 'Normally tiny' vectors -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_TINYPTRVECTOR_H
+#define LLVM_ADT_TINYPTRVECTOR_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Compiler.h"
+
+namespace llvm {
+
+/// TinyPtrVector - This class is specialized for cases where there are
+/// normally 0 or 1 element in a vector, but is general enough to go beyond that
+/// when required.
+///
+/// NOTE: This container doesn't allow you to store a null pointer into it.
+///
+template <typename EltTy>
+class TinyPtrVector {
+public:
+ typedef llvm::SmallVector<EltTy, 4> VecTy;
+ typedef typename VecTy::value_type value_type;
+
+ llvm::PointerUnion<EltTy, VecTy*> Val;
+
+ TinyPtrVector() {}
+ ~TinyPtrVector() {
+ if (VecTy *V = Val.template dyn_cast<VecTy*>())
+ delete V;
+ }
+
+ TinyPtrVector(const TinyPtrVector &RHS) : Val(RHS.Val) {
+ if (VecTy *V = Val.template dyn_cast<VecTy*>())
+ Val = new VecTy(*V);
+ }
+ TinyPtrVector &operator=(const TinyPtrVector &RHS) {
+ if (this == &RHS)
+ return *this;
+ if (RHS.empty()) {
+ this->clear();
+ return *this;
+ }
+
+ // Try to squeeze into the single slot. If it won't fit, allocate a copied
+ // vector.
+ if (Val.template is<EltTy>()) {
+ if (RHS.size() == 1)
+ Val = RHS.front();
+ else
+ Val = new VecTy(*RHS.Val.template get<VecTy*>());
+ return *this;
+ }
+
+ // If we have a full vector allocated, try to re-use it.
+ if (RHS.Val.template is<EltTy>()) {
+ Val.template get<VecTy*>()->clear();
+ Val.template get<VecTy*>()->push_back(RHS.front());
+ } else {
+ *Val.template get<VecTy*>() = *RHS.Val.template get<VecTy*>();
+ }
+ return *this;
+ }
+
+#if LLVM_USE_RVALUE_REFERENCES
+ TinyPtrVector(TinyPtrVector &&RHS) : Val(RHS.Val) {
+ RHS.Val = (EltTy)0;
+ }
+ TinyPtrVector &operator=(TinyPtrVector &&RHS) {
+ if (this == &RHS)
+ return *this;
+ if (RHS.empty()) {
+ this->clear();
+ return *this;
+ }
+
+ // If this vector has been allocated on the heap, re-use it if cheap. If it
+ // would require more copying, just delete it and we'll steal the other
+ // side.
+ if (VecTy *V = Val.template dyn_cast<VecTy*>()) {
+ if (RHS.Val.template is<EltTy>()) {
+ V->clear();
+ V->push_back(RHS.front());
+ return *this;
+ }
+ delete V;
+ }
+
+ Val = RHS.Val;
+ RHS.Val = (EltTy)0;
+ return *this;
+ }
+#endif
+
+ // implicit conversion operator to ArrayRef.
+ operator ArrayRef<EltTy>() const {
+ if (Val.isNull())
+ return ArrayRef<EltTy>();
+ if (Val.template is<EltTy>())
+ return *Val.getAddrOfPtr1();
+ return *Val.template get<VecTy*>();
+ }
+
+ bool empty() const {
+ // This vector can be empty if it contains no element, or if it
+ // contains a pointer to an empty vector.
+ if (Val.isNull()) return true;
+ if (VecTy *Vec = Val.template dyn_cast<VecTy*>())
+ return Vec->empty();
+ return false;
+ }
+
+ unsigned size() const {
+ if (empty())
+ return 0;
+ if (Val.template is<EltTy>())
+ return 1;
+ return Val.template get<VecTy*>()->size();
+ }
+
+ typedef const EltTy *const_iterator;
+ typedef EltTy *iterator;
+
+ iterator begin() {
+ if (Val.template is<EltTy>())
+ return Val.getAddrOfPtr1();
+
+ return Val.template get<VecTy *>()->begin();
+
+ }
+ iterator end() {
+ if (Val.template is<EltTy>())
+ return begin() + (Val.isNull() ? 0 : 1);
+
+ return Val.template get<VecTy *>()->end();
+ }
+
+ const_iterator begin() const {
+ return (const_iterator)const_cast<TinyPtrVector*>(this)->begin();
+ }
+
+ const_iterator end() const {
+ return (const_iterator)const_cast<TinyPtrVector*>(this)->end();
+ }
+
+ EltTy operator[](unsigned i) const {
+ assert(!Val.isNull() && "can't index into an empty vector");
+ if (EltTy V = Val.template dyn_cast<EltTy>()) {
+ assert(i == 0 && "tinyvector index out of range");
+ return V;
+ }
+
+ assert(i < Val.template get<VecTy*>()->size() &&
+ "tinyvector index out of range");
+ return (*Val.template get<VecTy*>())[i];
+ }
+
+ EltTy front() const {
+ assert(!empty() && "vector empty");
+ if (EltTy V = Val.template dyn_cast<EltTy>())
+ return V;
+ return Val.template get<VecTy*>()->front();
+ }
+
+ EltTy back() const {
+ assert(!empty() && "vector empty");
+ if (EltTy V = Val.template dyn_cast<EltTy>())
+ return V;
+ return Val.template get<VecTy*>()->back();
+ }
+
+ void push_back(EltTy NewVal) {
+ assert(NewVal != 0 && "Can't add a null value");
+
+ // If we have nothing, add something.
+ if (Val.isNull()) {
+ Val = NewVal;
+ return;
+ }
+
+ // If we have a single value, convert to a vector.
+ if (EltTy V = Val.template dyn_cast<EltTy>()) {
+ Val = new VecTy();
+ Val.template get<VecTy*>()->push_back(V);
+ }
+
+ // Add the new value, we know we have a vector.
+ Val.template get<VecTy*>()->push_back(NewVal);
+ }
+
+ void pop_back() {
+ // If we have a single value, convert to empty.
+ if (Val.template is<EltTy>())
+ Val = (EltTy)0;
+ else if (VecTy *Vec = Val.template get<VecTy*>())
+ Vec->pop_back();
+ }
+
+ void clear() {
+ // If we have a single value, convert to empty.
+ if (Val.template is<EltTy>()) {
+ Val = (EltTy)0;
+ } else if (VecTy *Vec = Val.template dyn_cast<VecTy*>()) {
+ // If we have a vector form, just clear it.
+ Vec->clear();
+ }
+ // Otherwise, we're already empty.
+ }
+
+ iterator erase(iterator I) {
+ assert(I >= begin() && "Iterator to erase is out of bounds.");
+ assert(I < end() && "Erasing at past-the-end iterator.");
+
+ // If we have a single value, convert to empty.
+ if (Val.template is<EltTy>()) {
+ if (I == begin())
+ Val = (EltTy)0;
+ } else if (VecTy *Vec = Val.template dyn_cast<VecTy*>()) {
+ // multiple items in a vector; just do the erase, there is no
+ // benefit to collapsing back to a pointer
+ return Vec->erase(I);
+ }
+ return end();
+ }
+
+ iterator erase(iterator S, iterator E) {
+ assert(S >= begin() && "Range to erase is out of bounds.");
+ assert(S <= E && "Trying to erase invalid range.");
+ assert(E <= end() && "Trying to erase past the end.");
+
+ if (Val.template is<EltTy>()) {
+ if (S == begin() && S != E)
+ Val = (EltTy)0;
+ } else if (VecTy *Vec = Val.template dyn_cast<VecTy*>()) {
+ return Vec->erase(S, E);
+ }
+ return end();
+ }
+
+ iterator insert(iterator I, const EltTy &Elt) {
+ assert(I >= this->begin() && "Insertion iterator is out of bounds.");
+ assert(I <= this->end() && "Inserting past the end of the vector.");
+ if (I == end()) {
+ push_back(Elt);
+ return llvm::prior(end());
+ }
+ assert(!Val.isNull() && "Null value with non-end insert iterator.");
+ if (EltTy V = Val.template dyn_cast<EltTy>()) {
+ assert(I == begin());
+ Val = Elt;
+ push_back(V);
+ return begin();
+ }
+
+ return Val.template get<VecTy*>()->insert(I, Elt);
+ }
+
+ template<typename ItTy>
+ iterator insert(iterator I, ItTy From, ItTy To) {
+ assert(I >= this->begin() && "Insertion iterator is out of bounds.");
+ assert(I <= this->end() && "Inserting past the end of the vector.");
+ if (From == To)
+ return I;
+
+ // If we have a single value, convert to a vector.
+ ptrdiff_t Offset = I - begin();
+ if (Val.isNull()) {
+ if (llvm::next(From) == To) {
+ Val = *From;
+ return begin();
+ }
+
+ Val = new VecTy();
+ } else if (EltTy V = Val.template dyn_cast<EltTy>()) {
+ Val = new VecTy();
+ Val.template get<VecTy*>()->push_back(V);
+ }
+ return Val.template get<VecTy*>()->insert(begin() + Offset, From, To);
+ }
+};
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/Triple.h b/include/llvm/ADT/Triple.h
new file mode 100644
index 00000000000..f701a793afd
--- /dev/null
+++ b/include/llvm/ADT/Triple.h
@@ -0,0 +1,436 @@
+//===-- llvm/ADT/Triple.h - Target triple helper class ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_TRIPLE_H
+#define LLVM_ADT_TRIPLE_H
+
+#include "llvm/ADT/Twine.h"
+
+// Some system headers or GCC predefined macros conflict with identifiers in
+// this file. Undefine them here.
+#undef mips
+#undef sparc
+
+namespace llvm {
+
+/// Triple - Helper class for working with target triples.
+///
+/// Target triples are strings in the canonical form:
+/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM
+/// or
+/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM-ENVIRONMENT
+///
+/// This class is used for clients which want to support arbitrary
+/// target triples, but also want to implement certain special
+/// behavior for particular targets. This class isolates the mapping
+/// from the components of the target triple to well known IDs.
+///
+/// At its core the Triple class is designed to be a wrapper for a triple
+/// string; the constructor does not change or normalize the triple string.
+/// Clients that need to handle the non-canonical triples that users often
+/// specify should use the normalize method.
+///
+/// See autoconf/config.guess for a glimpse into what triples look like in
+/// practice.
+class Triple {
+public:
+ enum ArchType {
+ UnknownArch,
+
+ arm, // ARM; arm, armv.*, xscale
+ cellspu, // CellSPU: spu, cellspu
+ hexagon, // Hexagon: hexagon
+ mips, // MIPS: mips, mipsallegrex
+ mipsel, // MIPSEL: mipsel, mipsallegrexel
+ mips64, // MIPS64: mips64
+ mips64el,// MIPS64EL: mips64el
+ msp430, // MSP430: msp430
+ ppc, // PPC: powerpc
+ ppc64, // PPC64: powerpc64, ppu
+ r600, // R600: AMD GPUs HD2XXX - HD6XXX
+ sparc, // Sparc: sparc
+ sparcv9, // Sparcv9: Sparcv9
+ tce, // TCE (http://tce.cs.tut.fi/): tce
+ thumb, // Thumb: thumb, thumbv.*
+ x86, // X86: i[3-9]86
+ x86_64, // X86-64: amd64, x86_64
+ xcore, // XCore: xcore
+ mblaze, // MBlaze: mblaze
+ nvptx, // NVPTX: 32-bit
+ nvptx64, // NVPTX: 64-bit
+ le32, // le32: generic little-endian 32-bit CPU (PNaCl / Emscripten)
+ amdil // amdil: amd IL
+ };
+ enum VendorType {
+ UnknownVendor,
+
+ Apple,
+ PC,
+ SCEI,
+ BGP,
+ BGQ,
+ Freescale
+ };
+ enum OSType {
+ UnknownOS,
+
+ AuroraUX,
+ Cygwin,
+ Darwin,
+ DragonFly,
+ FreeBSD,
+ IOS,
+ KFreeBSD,
+ Linux,
+ Lv2, // PS3
+ MacOSX,
+ MinGW32, // i*86-pc-mingw32, *-w64-mingw32
+ NetBSD,
+ OpenBSD,
+ Solaris,
+ Win32,
+ Haiku,
+ Minix,
+ RTEMS,
+ NativeClient,
+ CNK, // BG/P Compute-Node Kernel
+ Bitrig
+ };
+ enum EnvironmentType {
+ UnknownEnvironment,
+
+ GNU,
+ GNUEABI,
+ GNUEABIHF,
+ EABI,
+ MachO,
+ Android
+ };
+
+private:
+ std::string Data;
+
+ /// The parsed arch type.
+ ArchType Arch;
+
+ /// The parsed vendor type.
+ VendorType Vendor;
+
+ /// The parsed OS type.
+ OSType OS;
+
+ /// The parsed Environment type.
+ EnvironmentType Environment;
+
+public:
+ /// @name Constructors
+ /// @{
+
+ /// \brief Default constructor is the same as an empty string and leaves all
+ /// triple fields unknown.
+ Triple() : Data(), Arch(), Vendor(), OS(), Environment() {}
+
+ explicit Triple(const Twine &Str);
+ Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr);
+ Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr,
+ const Twine &EnvironmentStr);
+
+ /// @}
+ /// @name Normalization
+ /// @{
+
+ /// normalize - Turn an arbitrary machine specification into the canonical
+ /// triple form (or something sensible that the Triple class understands if
+ /// nothing better can reasonably be done). In particular, it handles the
+ /// common case in which otherwise valid components are in the wrong order.
+ static std::string normalize(StringRef Str);
+
+ /// @}
+ /// @name Typed Component Access
+ /// @{
+
+ /// getArch - Get the parsed architecture type of this triple.
+ ArchType getArch() const { return Arch; }
+
+ /// getVendor - Get the parsed vendor type of this triple.
+ VendorType getVendor() const { return Vendor; }
+
+ /// getOS - Get the parsed operating system type of this triple.
+ OSType getOS() const { return OS; }
+
+ /// hasEnvironment - Does this triple have the optional environment
+ /// (fourth) component?
+ bool hasEnvironment() const {
+ return getEnvironmentName() != "";
+ }
+
+ /// getEnvironment - Get the parsed environment type of this triple.
+ EnvironmentType getEnvironment() const { return Environment; }
+
+ /// getOSVersion - Parse the version number from the OS name component of the
+ /// triple, if present.
+ ///
+ /// For example, "fooos1.2.3" would return (1, 2, 3).
+ ///
+ /// If an entry is not defined, it will be returned as 0.
+ void getOSVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) const;
+
+ /// getOSMajorVersion - Return just the major version number, this is
+ /// specialized because it is a common query.
+ unsigned getOSMajorVersion() const {
+ unsigned Maj, Min, Micro;
+ getOSVersion(Maj, Min, Micro);
+ return Maj;
+ }
+
+ /// getMacOSXVersion - Parse the version number as with getOSVersion and then
+ /// translate generic "darwin" versions to the corresponding OS X versions.
+ /// This may also be called with IOS triples but the OS X version number is
+ /// just set to a constant 10.4.0 in that case. Returns true if successful.
+ bool getMacOSXVersion(unsigned &Major, unsigned &Minor,
+ unsigned &Micro) const;
+
+ /// getiOSVersion - Parse the version number as with getOSVersion. This should
+ /// only be called with IOS triples.
+ void getiOSVersion(unsigned &Major, unsigned &Minor,
+ unsigned &Micro) const;
+
+ /// @}
+ /// @name Direct Component Access
+ /// @{
+
+ const std::string &str() const { return Data; }
+
+ const std::string &getTriple() const { return Data; }
+
+ /// getArchName - Get the architecture (first) component of the
+ /// triple.
+ StringRef getArchName() const;
+
+ /// getVendorName - Get the vendor (second) component of the triple.
+ StringRef getVendorName() const;
+
+ /// getOSName - Get the operating system (third) component of the
+ /// triple.
+ StringRef getOSName() const;
+
+ /// getEnvironmentName - Get the optional environment (fourth)
+ /// component of the triple, or "" if empty.
+ StringRef getEnvironmentName() const;
+
+ /// getOSAndEnvironmentName - Get the operating system and optional
+ /// environment components as a single string (separated by a '-'
+ /// if the environment component is present).
+ StringRef getOSAndEnvironmentName() const;
+
+ /// @}
+ /// @name Convenience Predicates
+ /// @{
+
+ /// \brief Test whether the architecture is 64-bit
+ ///
+ /// Note that this tests for 64-bit pointer width, and nothing else. Note
+ /// that we intentionally expose only three predicates, 64-bit, 32-bit, and
+ /// 16-bit. The inner details of pointer width for particular architectures
+ /// is not summed up in the triple, and so only a coarse grained predicate
+ /// system is provided.
+ bool isArch64Bit() const;
+
+ /// \brief Test whether the architecture is 32-bit
+ ///
+ /// Note that this tests for 32-bit pointer width, and nothing else.
+ bool isArch32Bit() const;
+
+ /// \brief Test whether the architecture is 16-bit
+ ///
+ /// Note that this tests for 16-bit pointer width, and nothing else.
+ bool isArch16Bit() const;
+
+ /// isOSVersionLT - Helper function for doing comparisons against version
+ /// numbers included in the target triple.
+ bool isOSVersionLT(unsigned Major, unsigned Minor = 0,
+ unsigned Micro = 0) const {
+ unsigned LHS[3];
+ getOSVersion(LHS[0], LHS[1], LHS[2]);
+
+ if (LHS[0] != Major)
+ return LHS[0] < Major;
+ if (LHS[1] != Minor)
+ return LHS[1] < Minor;
+ if (LHS[2] != Micro)
+ return LHS[1] < Micro;
+
+ return false;
+ }
+
+ /// isMacOSXVersionLT - Comparison function for checking OS X version
+ /// compatibility, which handles supporting skewed version numbering schemes
+ /// used by the "darwin" triples.
+ unsigned isMacOSXVersionLT(unsigned Major, unsigned Minor = 0,
+ unsigned Micro = 0) const {
+ assert(isMacOSX() && "Not an OS X triple!");
+
+ // If this is OS X, expect a sane version number.
+ if (getOS() == Triple::MacOSX)
+ return isOSVersionLT(Major, Minor, Micro);
+
+ // Otherwise, compare to the "Darwin" number.
+ assert(Major == 10 && "Unexpected major version");
+ return isOSVersionLT(Minor + 4, Micro, 0);
+ }
+
+ /// isMacOSX - Is this a Mac OS X triple. For legacy reasons, we support both
+ /// "darwin" and "osx" as OS X triples.
+ bool isMacOSX() const {
+ return getOS() == Triple::Darwin || getOS() == Triple::MacOSX;
+ }
+
+ /// isOSDarwin - Is this a "Darwin" OS (OS X or iOS).
+ bool isOSDarwin() const {
+ return isMacOSX() || getOS() == Triple::IOS;
+ }
+
+ /// \brief Tests for either Cygwin or MinGW OS
+ bool isOSCygMing() const {
+ return getOS() == Triple::Cygwin || getOS() == Triple::MinGW32;
+ }
+
+ /// isOSWindows - Is this a "Windows" OS.
+ bool isOSWindows() const {
+ return getOS() == Triple::Win32 || isOSCygMing();
+ }
+
+ /// \brief Tests whether the OS uses the ELF binary format.
+ bool isOSBinFormatELF() const {
+ return !isOSDarwin() && !isOSWindows();
+ }
+
+ /// \brief Tests whether the OS uses the COFF binary format.
+ bool isOSBinFormatCOFF() const {
+ return isOSWindows();
+ }
+
+ /// \brief Tests whether the environment is MachO.
+ // FIXME: Should this be an OSBinFormat predicate?
+ bool isEnvironmentMachO() const {
+ return getEnvironment() == Triple::MachO || isOSDarwin();
+ }
+
+ /// @}
+ /// @name Mutators
+ /// @{
+
+ /// setArch - Set the architecture (first) component of the triple
+ /// to a known type.
+ void setArch(ArchType Kind);
+
+ /// setVendor - Set the vendor (second) component of the triple to a
+ /// known type.
+ void setVendor(VendorType Kind);
+
+ /// setOS - Set the operating system (third) component of the triple
+ /// to a known type.
+ void setOS(OSType Kind);
+
+ /// setEnvironment - Set the environment (fourth) component of the triple
+ /// to a known type.
+ void setEnvironment(EnvironmentType Kind);
+
+ /// setTriple - Set all components to the new triple \p Str.
+ void setTriple(const Twine &Str);
+
+ /// setArchName - Set the architecture (first) component of the
+ /// triple by name.
+ void setArchName(StringRef Str);
+
+ /// setVendorName - Set the vendor (second) component of the triple
+ /// by name.
+ void setVendorName(StringRef Str);
+
+ /// setOSName - Set the operating system (third) component of the
+ /// triple by name.
+ void setOSName(StringRef Str);
+
+ /// setEnvironmentName - Set the optional environment (fourth)
+ /// component of the triple by name.
+ void setEnvironmentName(StringRef Str);
+
+ /// setOSAndEnvironmentName - Set the operating system and optional
+ /// environment components with a single string.
+ void setOSAndEnvironmentName(StringRef Str);
+
+ /// getArchNameForAssembler - Get an architecture name that is understood by
+ /// the target assembler.
+ const char *getArchNameForAssembler();
+
+ /// @}
+ /// @name Helpers to build variants of a particular triple.
+ /// @{
+
+ /// \brief Form a triple with a 32-bit variant of the current architecture.
+ ///
+ /// This can be used to move across "families" of architectures where useful.
+ ///
+ /// \returns A new triple with a 32-bit architecture or an unknown
+ /// architecture if no such variant can be found.
+ llvm::Triple get32BitArchVariant() const;
+
+ /// \brief Form a triple with a 64-bit variant of the current architecture.
+ ///
+ /// This can be used to move across "families" of architectures where useful.
+ ///
+ /// \returns A new triple with a 64-bit architecture or an unknown
+ /// architecture if no such variant can be found.
+ llvm::Triple get64BitArchVariant() const;
+
+ /// @}
+ /// @name Static helpers for IDs.
+ /// @{
+
+ /// getArchTypeName - Get the canonical name for the \p Kind architecture.
+ static const char *getArchTypeName(ArchType Kind);
+
+ /// getArchTypePrefix - Get the "prefix" canonical name for the \p Kind
+ /// architecture. This is the prefix used by the architecture specific
+ /// builtins, and is suitable for passing to \see
+ /// Intrinsic::getIntrinsicForGCCBuiltin().
+ ///
+ /// \return - The architecture prefix, or 0 if none is defined.
+ static const char *getArchTypePrefix(ArchType Kind);
+
+ /// getVendorTypeName - Get the canonical name for the \p Kind vendor.
+ static const char *getVendorTypeName(VendorType Kind);
+
+ /// getOSTypeName - Get the canonical name for the \p Kind operating system.
+ static const char *getOSTypeName(OSType Kind);
+
+ /// getEnvironmentTypeName - Get the canonical name for the \p Kind
+ /// environment.
+ static const char *getEnvironmentTypeName(EnvironmentType Kind);
+
+ /// @}
+ /// @name Static helpers for converting alternate architecture names.
+ /// @{
+
+ /// getArchTypeForLLVMName - The canonical type for the given LLVM
+ /// architecture name (e.g., "x86").
+ static ArchType getArchTypeForLLVMName(StringRef Str);
+
+ /// getArchTypeForDarwinArchName - Get the architecture type for a "Darwin"
+ /// architecture name, for example as accepted by "gcc -arch" (see also
+ /// arch(3)).
+ static ArchType getArchTypeForDarwinArchName(StringRef Str);
+
+ /// @}
+};
+
+} // End llvm namespace
+
+
+#endif
diff --git a/include/llvm/ADT/Twine.h b/include/llvm/ADT/Twine.h
new file mode 100644
index 00000000000..cc290d51d27
--- /dev/null
+++ b/include/llvm/ADT/Twine.h
@@ -0,0 +1,524 @@
+//===-- Twine.h - Fast Temporary String Concatenation -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_TWINE_H
+#define LLVM_ADT_TWINE_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include <cassert>
+#include <string>
+
+namespace llvm {
+ template <typename T>
+ class SmallVectorImpl;
+ class StringRef;
+ class raw_ostream;
+
+ /// Twine - A lightweight data structure for efficiently representing the
+ /// concatenation of temporary values as strings.
+ ///
+ /// A Twine is a kind of rope, it represents a concatenated string using a
+ /// binary-tree, where the string is the preorder of the nodes. Since the
+ /// Twine can be efficiently rendered into a buffer when its result is used,
+ /// it avoids the cost of generating temporary values for intermediate string
+ /// results -- particularly in cases when the Twine result is never
+ /// required. By explicitly tracking the type of leaf nodes, we can also avoid
+ /// the creation of temporary strings for conversions operations (such as
+ /// appending an integer to a string).
+ ///
+ /// A Twine is not intended for use directly and should not be stored, its
+ /// implementation relies on the ability to store pointers to temporary stack
+ /// objects which may be deallocated at the end of a statement. Twines should
+ /// only be used accepted as const references in arguments, when an API wishes
+ /// to accept possibly-concatenated strings.
+ ///
+ /// Twines support a special 'null' value, which always concatenates to form
+ /// itself, and renders as an empty string. This can be returned from APIs to
+ /// effectively nullify any concatenations performed on the result.
+ ///
+ /// \b Implementation
+ ///
+ /// Given the nature of a Twine, it is not possible for the Twine's
+ /// concatenation method to construct interior nodes; the result must be
+ /// represented inside the returned value. For this reason a Twine object
+ /// actually holds two values, the left- and right-hand sides of a
+ /// concatenation. We also have nullary Twine objects, which are effectively
+ /// sentinel values that represent empty strings.
+ ///
+ /// Thus, a Twine can effectively have zero, one, or two children. The \see
+ /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
+ /// testing the number of children.
+ ///
+ /// We maintain a number of invariants on Twine objects (FIXME: Why):
+ /// - Nullary twines are always represented with their Kind on the left-hand
+ /// side, and the Empty kind on the right-hand side.
+ /// - Unary twines are always represented with the value on the left-hand
+ /// side, and the Empty kind on the right-hand side.
+ /// - If a Twine has another Twine as a child, that child should always be
+ /// binary (otherwise it could have been folded into the parent).
+ ///
+ /// These invariants are check by \see isValid().
+ ///
+ /// \b Efficiency Considerations
+ ///
+ /// The Twine is designed to yield efficient and small code for common
+ /// situations. For this reason, the concat() method is inlined so that
+ /// concatenations of leaf nodes can be optimized into stores directly into a
+ /// single stack allocated object.
+ ///
+ /// In practice, not all compilers can be trusted to optimize concat() fully,
+ /// so we provide two additional methods (and accompanying operator+
+ /// overloads) to guarantee that particularly important cases (cstring plus
+ /// StringRef) codegen as desired.
+ class Twine {
+ /// NodeKind - Represent the type of an argument.
+ enum NodeKind {
+ /// An empty string; the result of concatenating anything with it is also
+ /// empty.
+ NullKind,
+
+ /// The empty string.
+ EmptyKind,
+
+ /// A pointer to a Twine instance.
+ TwineKind,
+
+ /// A pointer to a C string instance.
+ CStringKind,
+
+ /// A pointer to an std::string instance.
+ StdStringKind,
+
+ /// A pointer to a StringRef instance.
+ StringRefKind,
+
+ /// A char value reinterpreted as a pointer, to render as a character.
+ CharKind,
+
+ /// An unsigned int value reinterpreted as a pointer, to render as an
+ /// unsigned decimal integer.
+ DecUIKind,
+
+ /// An int value reinterpreted as a pointer, to render as a signed
+ /// decimal integer.
+ DecIKind,
+
+ /// A pointer to an unsigned long value, to render as an unsigned decimal
+ /// integer.
+ DecULKind,
+
+ /// A pointer to a long value, to render as a signed decimal integer.
+ DecLKind,
+
+ /// A pointer to an unsigned long long value, to render as an unsigned
+ /// decimal integer.
+ DecULLKind,
+
+ /// A pointer to a long long value, to render as a signed decimal integer.
+ DecLLKind,
+
+ /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
+ /// integer.
+ UHexKind
+ };
+
+ union Child
+ {
+ const Twine *twine;
+ const char *cString;
+ const std::string *stdString;
+ const StringRef *stringRef;
+ char character;
+ unsigned int decUI;
+ int decI;
+ const unsigned long *decUL;
+ const long *decL;
+ const unsigned long long *decULL;
+ const long long *decLL;
+ const uint64_t *uHex;
+ };
+
+ private:
+ /// LHS - The prefix in the concatenation, which may be uninitialized for
+ /// Null or Empty kinds.
+ Child LHS;
+ /// RHS - The suffix in the concatenation, which may be uninitialized for
+ /// Null or Empty kinds.
+ Child RHS;
+ // enums stored as unsigned chars to save on space while some compilers
+ // don't support specifying the backing type for an enum
+ /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
+ unsigned char LHSKind;
+ /// RHSKind - The NodeKind of the left hand side, \see getLHSKind().
+ unsigned char RHSKind;
+
+ private:
+ /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
+ explicit Twine(NodeKind Kind)
+ : LHSKind(Kind), RHSKind(EmptyKind) {
+ assert(isNullary() && "Invalid kind!");
+ }
+
+ /// Construct a binary twine.
+ explicit Twine(const Twine &_LHS, const Twine &_RHS)
+ : LHSKind(TwineKind), RHSKind(TwineKind) {
+ LHS.twine = &_LHS;
+ RHS.twine = &_RHS;
+ assert(isValid() && "Invalid twine!");
+ }
+
+ /// Construct a twine from explicit values.
+ explicit Twine(Child _LHS, NodeKind _LHSKind,
+ Child _RHS, NodeKind _RHSKind)
+ : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
+ assert(isValid() && "Invalid twine!");
+ }
+
+ /// isNull - Check for the null twine.
+ bool isNull() const {
+ return getLHSKind() == NullKind;
+ }
+
+ /// isEmpty - Check for the empty twine.
+ bool isEmpty() const {
+ return getLHSKind() == EmptyKind;
+ }
+
+ /// isNullary - Check if this is a nullary twine (null or empty).
+ bool isNullary() const {
+ return isNull() || isEmpty();
+ }
+
+ /// isUnary - Check if this is a unary twine.
+ bool isUnary() const {
+ return getRHSKind() == EmptyKind && !isNullary();
+ }
+
+ /// isBinary - Check if this is a binary twine.
+ bool isBinary() const {
+ return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
+ }
+
+ /// isValid - Check if this is a valid twine (satisfying the invariants on
+ /// order and number of arguments).
+ bool isValid() const {
+ // Nullary twines always have Empty on the RHS.
+ if (isNullary() && getRHSKind() != EmptyKind)
+ return false;
+
+ // Null should never appear on the RHS.
+ if (getRHSKind() == NullKind)
+ return false;
+
+ // The RHS cannot be non-empty if the LHS is empty.
+ if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
+ return false;
+
+ // A twine child should always be binary.
+ if (getLHSKind() == TwineKind &&
+ !LHS.twine->isBinary())
+ return false;
+ if (getRHSKind() == TwineKind &&
+ !RHS.twine->isBinary())
+ return false;
+
+ return true;
+ }
+
+ /// getLHSKind - Get the NodeKind of the left-hand side.
+ NodeKind getLHSKind() const { return (NodeKind) LHSKind; }
+
+ /// getRHSKind - Get the NodeKind of the left-hand side.
+ NodeKind getRHSKind() const { return (NodeKind) RHSKind; }
+
+ /// printOneChild - Print one child from a twine.
+ void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
+
+ /// printOneChildRepr - Print the representation of one child from a twine.
+ void printOneChildRepr(raw_ostream &OS, Child Ptr,
+ NodeKind Kind) const;
+
+ public:
+ /// @name Constructors
+ /// @{
+
+ /// Construct from an empty string.
+ /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
+ assert(isValid() && "Invalid twine!");
+ }
+
+ /// Construct from a C string.
+ ///
+ /// We take care here to optimize "" into the empty twine -- this will be
+ /// optimized out for string constants. This allows Twine arguments have
+ /// default "" values, without introducing unnecessary string constants.
+ /*implicit*/ Twine(const char *Str)
+ : RHSKind(EmptyKind) {
+ if (Str[0] != '\0') {
+ LHS.cString = Str;
+ LHSKind = CStringKind;
+ } else
+ LHSKind = EmptyKind;
+
+ assert(isValid() && "Invalid twine!");
+ }
+
+ /// Construct from an std::string.
+ /*implicit*/ Twine(const std::string &Str)
+ : LHSKind(StdStringKind), RHSKind(EmptyKind) {
+ LHS.stdString = &Str;
+ assert(isValid() && "Invalid twine!");
+ }
+
+ /// Construct from a StringRef.
+ /*implicit*/ Twine(const StringRef &Str)
+ : LHSKind(StringRefKind), RHSKind(EmptyKind) {
+ LHS.stringRef = &Str;
+ assert(isValid() && "Invalid twine!");
+ }
+
+ /// Construct from a char.
+ explicit Twine(char Val)
+ : LHSKind(CharKind), RHSKind(EmptyKind) {
+ LHS.character = Val;
+ }
+
+ /// Construct from a signed char.
+ explicit Twine(signed char Val)
+ : LHSKind(CharKind), RHSKind(EmptyKind) {
+ LHS.character = static_cast<char>(Val);
+ }
+
+ /// Construct from an unsigned char.
+ explicit Twine(unsigned char Val)
+ : LHSKind(CharKind), RHSKind(EmptyKind) {
+ LHS.character = static_cast<char>(Val);
+ }
+
+ /// Construct a twine to print \p Val as an unsigned decimal integer.
+ explicit Twine(unsigned Val)
+ : LHSKind(DecUIKind), RHSKind(EmptyKind) {
+ LHS.decUI = Val;
+ }
+
+ /// Construct a twine to print \p Val as a signed decimal integer.
+ explicit Twine(int Val)
+ : LHSKind(DecIKind), RHSKind(EmptyKind) {
+ LHS.decI = Val;
+ }
+
+ /// Construct a twine to print \p Val as an unsigned decimal integer.
+ explicit Twine(const unsigned long &Val)
+ : LHSKind(DecULKind), RHSKind(EmptyKind) {
+ LHS.decUL = &Val;
+ }
+
+ /// Construct a twine to print \p Val as a signed decimal integer.
+ explicit Twine(const long &Val)
+ : LHSKind(DecLKind), RHSKind(EmptyKind) {
+ LHS.decL = &Val;
+ }
+
+ /// Construct a twine to print \p Val as an unsigned decimal integer.
+ explicit Twine(const unsigned long long &Val)
+ : LHSKind(DecULLKind), RHSKind(EmptyKind) {
+ LHS.decULL = &Val;
+ }
+
+ /// Construct a twine to print \p Val as a signed decimal integer.
+ explicit Twine(const long long &Val)
+ : LHSKind(DecLLKind), RHSKind(EmptyKind) {
+ LHS.decLL = &Val;
+ }
+
+ // FIXME: Unfortunately, to make sure this is as efficient as possible we
+ // need extra binary constructors from particular types. We can't rely on
+ // the compiler to be smart enough to fold operator+()/concat() down to the
+ // right thing. Yet.
+
+ /// Construct as the concatenation of a C string and a StringRef.
+ /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
+ : LHSKind(CStringKind), RHSKind(StringRefKind) {
+ LHS.cString = _LHS;
+ RHS.stringRef = &_RHS;
+ assert(isValid() && "Invalid twine!");
+ }
+
+ /// Construct as the concatenation of a StringRef and a C string.
+ /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
+ : LHSKind(StringRefKind), RHSKind(CStringKind) {
+ LHS.stringRef = &_LHS;
+ RHS.cString = _RHS;
+ assert(isValid() && "Invalid twine!");
+ }
+
+ /// Create a 'null' string, which is an empty string that always
+ /// concatenates to form another empty string.
+ static Twine createNull() {
+ return Twine(NullKind);
+ }
+
+ /// @}
+ /// @name Numeric Conversions
+ /// @{
+
+ // Construct a twine to print \p Val as an unsigned hexadecimal integer.
+ static Twine utohexstr(const uint64_t &Val) {
+ Child LHS, RHS;
+ LHS.uHex = &Val;
+ RHS.twine = 0;
+ return Twine(LHS, UHexKind, RHS, EmptyKind);
+ }
+
+ /// @}
+ /// @name Predicate Operations
+ /// @{
+
+ /// isTriviallyEmpty - Check if this twine is trivially empty; a false
+ /// return value does not necessarily mean the twine is empty.
+ bool isTriviallyEmpty() const {
+ return isNullary();
+ }
+
+ /// isSingleStringRef - Return true if this twine can be dynamically
+ /// accessed as a single StringRef value with getSingleStringRef().
+ bool isSingleStringRef() const {
+ if (getRHSKind() != EmptyKind) return false;
+
+ switch (getLHSKind()) {
+ case EmptyKind:
+ case CStringKind:
+ case StdStringKind:
+ case StringRefKind:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /// @}
+ /// @name String Operations
+ /// @{
+
+ Twine concat(const Twine &Suffix) const;
+
+ /// @}
+ /// @name Output & Conversion.
+ /// @{
+
+ /// str - Return the twine contents as a std::string.
+ std::string str() const;
+
+ /// toVector - Write the concatenated string into the given SmallString or
+ /// SmallVector.
+ void toVector(SmallVectorImpl<char> &Out) const;
+
+ /// getSingleStringRef - This returns the twine as a single StringRef. This
+ /// method is only valid if isSingleStringRef() is true.
+ StringRef getSingleStringRef() const {
+ assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
+ switch (getLHSKind()) {
+ default: llvm_unreachable("Out of sync with isSingleStringRef");
+ case EmptyKind: return StringRef();
+ case CStringKind: return StringRef(LHS.cString);
+ case StdStringKind: return StringRef(*LHS.stdString);
+ case StringRefKind: return *LHS.stringRef;
+ }
+ }
+
+ /// toStringRef - This returns the twine as a single StringRef if it can be
+ /// represented as such. Otherwise the twine is written into the given
+ /// SmallVector and a StringRef to the SmallVector's data is returned.
+ StringRef toStringRef(SmallVectorImpl<char> &Out) const;
+
+ /// toNullTerminatedStringRef - This returns the twine as a single null
+ /// terminated StringRef if it can be represented as such. Otherwise the
+ /// twine is written into the given SmallVector and a StringRef to the
+ /// SmallVector's data is returned.
+ ///
+ /// The returned StringRef's size does not include the null terminator.
+ StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
+
+ /// Write the concatenated string represented by this twine to the
+ /// stream \p OS.
+ void print(raw_ostream &OS) const;
+
+ /// Dump the concatenated string represented by this twine to stderr.
+ void dump() const;
+
+ /// Write the representation of this twine to the stream \p OS.
+ void printRepr(raw_ostream &OS) const;
+
+ /// Dump the representation of this twine to stderr.
+ void dumpRepr() const;
+
+ /// @}
+ };
+
+ /// @name Twine Inline Implementations
+ /// @{
+
+ inline Twine Twine::concat(const Twine &Suffix) const {
+ // Concatenation with null is null.
+ if (isNull() || Suffix.isNull())
+ return Twine(NullKind);
+
+ // Concatenation with empty yields the other side.
+ if (isEmpty())
+ return Suffix;
+ if (Suffix.isEmpty())
+ return *this;
+
+ // Otherwise we need to create a new node, taking care to fold in unary
+ // twines.
+ Child NewLHS, NewRHS;
+ NewLHS.twine = this;
+ NewRHS.twine = &Suffix;
+ NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
+ if (isUnary()) {
+ NewLHS = LHS;
+ NewLHSKind = getLHSKind();
+ }
+ if (Suffix.isUnary()) {
+ NewRHS = Suffix.LHS;
+ NewRHSKind = Suffix.getLHSKind();
+ }
+
+ return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
+ }
+
+ inline Twine operator+(const Twine &LHS, const Twine &RHS) {
+ return LHS.concat(RHS);
+ }
+
+ /// Additional overload to guarantee simplified codegen; this is equivalent to
+ /// concat().
+
+ inline Twine operator+(const char *LHS, const StringRef &RHS) {
+ return Twine(LHS, RHS);
+ }
+
+ /// Additional overload to guarantee simplified codegen; this is equivalent to
+ /// concat().
+
+ inline Twine operator+(const StringRef &LHS, const char *RHS) {
+ return Twine(LHS, RHS);
+ }
+
+ inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
+ RHS.print(OS);
+ return OS;
+ }
+
+ /// @}
+}
+
+#endif
diff --git a/include/llvm/ADT/UniqueVector.h b/include/llvm/ADT/UniqueVector.h
new file mode 100644
index 00000000000..2d02d1ce166
--- /dev/null
+++ b/include/llvm/ADT/UniqueVector.h
@@ -0,0 +1,89 @@
+//===-- llvm/ADT/UniqueVector.h ---------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_UNIQUEVECTOR_H
+#define LLVM_ADT_UNIQUEVECTOR_H
+
+#include <cassert>
+#include <map>
+#include <vector>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+/// UniqueVector - This class produces a sequential ID number (base 1) for each
+/// unique entry that is added. T is the type of entries in the vector. This
+/// class should have an implementation of operator== and of operator<.
+/// Entries can be fetched using operator[] with the entry ID.
+template<class T> class UniqueVector {
+private:
+ // Map - Used to handle the correspondence of entry to ID.
+ std::map<T, unsigned> Map;
+
+ // Vector - ID ordered vector of entries. Entries can be indexed by ID - 1.
+ //
+ std::vector<T> Vector;
+
+public:
+ /// insert - Append entry to the vector if it doesn't already exist. Returns
+ /// the entry's index + 1 to be used as a unique ID.
+ unsigned insert(const T &Entry) {
+ // Check if the entry is already in the map.
+ unsigned &Val = Map[Entry];
+
+ // See if entry exists, if so return prior ID.
+ if (Val) return Val;
+
+ // Compute ID for entry.
+ Val = static_cast<unsigned>(Vector.size()) + 1;
+
+ // Insert in vector.
+ Vector.push_back(Entry);
+ return Val;
+ }
+
+ /// idFor - return the ID for an existing entry. Returns 0 if the entry is
+ /// not found.
+ unsigned idFor(const T &Entry) const {
+ // Search for entry in the map.
+ typename std::map<T, unsigned>::const_iterator MI = Map.find(Entry);
+
+ // See if entry exists, if so return ID.
+ if (MI != Map.end()) return MI->second;
+
+ // No luck.
+ return 0;
+ }
+
+ /// operator[] - Returns a reference to the entry with the specified ID.
+ ///
+ const T &operator[](unsigned ID) const {
+ assert(ID-1 < size() && "ID is 0 or out of range!");
+ return Vector[ID - 1];
+ }
+
+ /// size - Returns the number of entries in the vector.
+ ///
+ size_t size() const { return Vector.size(); }
+
+ /// empty - Returns true if the vector is empty.
+ ///
+ bool empty() const { return Vector.empty(); }
+
+ /// reset - Clears all the entries.
+ ///
+ void reset() {
+ Map.clear();
+ Vector.resize(0, 0);
+ }
+};
+
+} // End of namespace llvm
+
+#endif // LLVM_ADT_UNIQUEVECTOR_H
diff --git a/include/llvm/ADT/ValueMap.h b/include/llvm/ADT/ValueMap.h
new file mode 100644
index 00000000000..d23fccf3e8c
--- /dev/null
+++ b/include/llvm/ADT/ValueMap.h
@@ -0,0 +1,378 @@
+//===- llvm/ADT/ValueMap.h - Safe map from Values to data -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the ValueMap class. ValueMap maps Value* or any subclass
+// to an arbitrary other type. It provides the DenseMap interface but updates
+// itself to remain safe when keys are RAUWed or deleted. By default, when a
+// key is RAUWed from V1 to V2, the old mapping V1->target is removed, and a new
+// mapping V2->target is added. If V2 already existed, its old target is
+// overwritten. When a key is deleted, its mapping is removed.
+//
+// You can override a ValueMap's Config parameter to control exactly what
+// happens on RAUW and destruction and to get called back on each event. It's
+// legal to call back into the ValueMap from a Config's callbacks. Config
+// parameters should inherit from ValueMapConfig<KeyT> to get default
+// implementations of all the methods ValueMap uses. See ValueMapConfig for
+// documentation of the functions you can override.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_VALUEMAP_H
+#define LLVM_ADT_VALUEMAP_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/ValueHandle.h"
+#include "llvm/Support/type_traits.h"
+#include "llvm/Support/Mutex.h"
+
+#include <iterator>
+
+namespace llvm {
+
+template<typename KeyT, typename ValueT, typename Config>
+class ValueMapCallbackVH;
+
+template<typename DenseMapT, typename KeyT>
+class ValueMapIterator;
+template<typename DenseMapT, typename KeyT>
+class ValueMapConstIterator;
+
+/// This class defines the default behavior for configurable aspects of
+/// ValueMap<>. User Configs should inherit from this class to be as compatible
+/// as possible with future versions of ValueMap.
+template<typename KeyT>
+struct ValueMapConfig {
+ /// If FollowRAUW is true, the ValueMap will update mappings on RAUW. If it's
+ /// false, the ValueMap will leave the original mapping in place.
+ enum { FollowRAUW = true };
+
+ // All methods will be called with a first argument of type ExtraData. The
+ // default implementations in this class take a templated first argument so
+ // that users' subclasses can use any type they want without having to
+ // override all the defaults.
+ struct ExtraData {};
+
+ template<typename ExtraDataT>
+ static void onRAUW(const ExtraDataT & /*Data*/, KeyT /*Old*/, KeyT /*New*/) {}
+ template<typename ExtraDataT>
+ static void onDelete(const ExtraDataT &/*Data*/, KeyT /*Old*/) {}
+
+ /// Returns a mutex that should be acquired around any changes to the map.
+ /// This is only acquired from the CallbackVH (and held around calls to onRAUW
+ /// and onDelete) and not inside other ValueMap methods. NULL means that no
+ /// mutex is necessary.
+ template<typename ExtraDataT>
+ static sys::Mutex *getMutex(const ExtraDataT &/*Data*/) { return NULL; }
+};
+
+/// See the file comment.
+template<typename KeyT, typename ValueT, typename Config =ValueMapConfig<KeyT> >
+class ValueMap {
+ friend class ValueMapCallbackVH<KeyT, ValueT, Config>;
+ typedef ValueMapCallbackVH<KeyT, ValueT, Config> ValueMapCVH;
+ typedef DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH> > MapT;
+ typedef typename Config::ExtraData ExtraData;
+ MapT Map;
+ ExtraData Data;
+ ValueMap(const ValueMap&) LLVM_DELETED_FUNCTION;
+ ValueMap& operator=(const ValueMap&) LLVM_DELETED_FUNCTION;
+public:
+ typedef KeyT key_type;
+ typedef ValueT mapped_type;
+ typedef std::pair<KeyT, ValueT> value_type;
+
+ explicit ValueMap(unsigned NumInitBuckets = 64)
+ : Map(NumInitBuckets), Data() {}
+ explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64)
+ : Map(NumInitBuckets), Data(Data) {}
+
+ ~ValueMap() {}
+
+ typedef ValueMapIterator<MapT, KeyT> iterator;
+ typedef ValueMapConstIterator<MapT, KeyT> const_iterator;
+ inline iterator begin() { return iterator(Map.begin()); }
+ inline iterator end() { return iterator(Map.end()); }
+ inline const_iterator begin() const { return const_iterator(Map.begin()); }
+ inline const_iterator end() const { return const_iterator(Map.end()); }
+
+ bool empty() const { return Map.empty(); }
+ unsigned size() const { return Map.size(); }
+
+ /// Grow the map so that it has at least Size buckets. Does not shrink
+ void resize(size_t Size) { Map.resize(Size); }
+
+ void clear() { Map.clear(); }
+
+ /// count - Return true if the specified key is in the map.
+ bool count(const KeyT &Val) const {
+ return Map.find_as(Val) != Map.end();
+ }
+
+ iterator find(const KeyT &Val) {
+ return iterator(Map.find_as(Val));
+ }
+ const_iterator find(const KeyT &Val) const {
+ return const_iterator(Map.find_as(Val));
+ }
+
+ /// lookup - Return the entry for the specified key, or a default
+ /// constructed value if no such entry exists.
+ ValueT lookup(const KeyT &Val) const {
+ typename MapT::const_iterator I = Map.find_as(Val);
+ return I != Map.end() ? I->second : ValueT();
+ }
+
+ // Inserts key,value pair into the map if the key isn't already in the map.
+ // If the key is already in the map, it returns false and doesn't update the
+ // value.
+ std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
+ std::pair<typename MapT::iterator, bool> map_result=
+ Map.insert(std::make_pair(Wrap(KV.first), KV.second));
+ return std::make_pair(iterator(map_result.first), map_result.second);
+ }
+
+ /// insert - Range insertion of pairs.
+ template<typename InputIt>
+ void insert(InputIt I, InputIt E) {
+ for (; I != E; ++I)
+ insert(*I);
+ }
+
+
+ bool erase(const KeyT &Val) {
+ typename MapT::iterator I = Map.find_as(Val);
+ if (I == Map.end())
+ return false;
+
+ Map.erase(I);
+ return true;
+ }
+ void erase(iterator I) {
+ return Map.erase(I.base());
+ }
+
+ value_type& FindAndConstruct(const KeyT &Key) {
+ return Map.FindAndConstruct(Wrap(Key));
+ }
+
+ ValueT &operator[](const KeyT &Key) {
+ return Map[Wrap(Key)];
+ }
+
+ /// isPointerIntoBucketsArray - Return true if the specified pointer points
+ /// somewhere into the ValueMap's array of buckets (i.e. either to a key or
+ /// value in the ValueMap).
+ bool isPointerIntoBucketsArray(const void *Ptr) const {
+ return Map.isPointerIntoBucketsArray(Ptr);
+ }
+
+ /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
+ /// array. In conjunction with the previous method, this can be used to
+ /// determine whether an insertion caused the ValueMap to reallocate.
+ const void *getPointerIntoBucketsArray() const {
+ return Map.getPointerIntoBucketsArray();
+ }
+
+private:
+ // Takes a key being looked up in the map and wraps it into a
+ // ValueMapCallbackVH, the actual key type of the map. We use a helper
+ // function because ValueMapCVH is constructed with a second parameter.
+ ValueMapCVH Wrap(KeyT key) const {
+ // The only way the resulting CallbackVH could try to modify *this (making
+ // the const_cast incorrect) is if it gets inserted into the map. But then
+ // this function must have been called from a non-const method, making the
+ // const_cast ok.
+ return ValueMapCVH(key, const_cast<ValueMap*>(this));
+ }
+};
+
+// This CallbackVH updates its ValueMap when the contained Value changes,
+// according to the user's preferences expressed through the Config object.
+template<typename KeyT, typename ValueT, typename Config>
+class ValueMapCallbackVH : public CallbackVH {
+ friend class ValueMap<KeyT, ValueT, Config>;
+ friend struct DenseMapInfo<ValueMapCallbackVH>;
+ typedef ValueMap<KeyT, ValueT, Config> ValueMapT;
+ typedef typename llvm::remove_pointer<KeyT>::type KeySansPointerT;
+
+ ValueMapT *Map;
+
+ ValueMapCallbackVH(KeyT Key, ValueMapT *Map)
+ : CallbackVH(const_cast<Value*>(static_cast<const Value*>(Key))),
+ Map(Map) {}
+
+public:
+ KeyT Unwrap() const { return cast_or_null<KeySansPointerT>(getValPtr()); }
+
+ virtual void deleted() {
+ // Make a copy that won't get changed even when *this is destroyed.
+ ValueMapCallbackVH Copy(*this);
+ sys::Mutex *M = Config::getMutex(Copy.Map->Data);
+ if (M)
+ M->acquire();
+ Config::onDelete(Copy.Map->Data, Copy.Unwrap()); // May destroy *this.
+ Copy.Map->Map.erase(Copy); // Definitely destroys *this.
+ if (M)
+ M->release();
+ }
+ virtual void allUsesReplacedWith(Value *new_key) {
+ assert(isa<KeySansPointerT>(new_key) &&
+ "Invalid RAUW on key of ValueMap<>");
+ // Make a copy that won't get changed even when *this is destroyed.
+ ValueMapCallbackVH Copy(*this);
+ sys::Mutex *M = Config::getMutex(Copy.Map->Data);
+ if (M)
+ M->acquire();
+
+ KeyT typed_new_key = cast<KeySansPointerT>(new_key);
+ // Can destroy *this:
+ Config::onRAUW(Copy.Map->Data, Copy.Unwrap(), typed_new_key);
+ if (Config::FollowRAUW) {
+ typename ValueMapT::MapT::iterator I = Copy.Map->Map.find(Copy);
+ // I could == Copy.Map->Map.end() if the onRAUW callback already
+ // removed the old mapping.
+ if (I != Copy.Map->Map.end()) {
+ ValueT Target(I->second);
+ Copy.Map->Map.erase(I); // Definitely destroys *this.
+ Copy.Map->insert(std::make_pair(typed_new_key, Target));
+ }
+ }
+ if (M)
+ M->release();
+ }
+};
+
+template<typename KeyT, typename ValueT, typename Config>
+struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config> > {
+ typedef ValueMapCallbackVH<KeyT, ValueT, Config> VH;
+ typedef DenseMapInfo<KeyT> PointerInfo;
+
+ static inline VH getEmptyKey() {
+ return VH(PointerInfo::getEmptyKey(), NULL);
+ }
+ static inline VH getTombstoneKey() {
+ return VH(PointerInfo::getTombstoneKey(), NULL);
+ }
+ static unsigned getHashValue(const VH &Val) {
+ return PointerInfo::getHashValue(Val.Unwrap());
+ }
+ static unsigned getHashValue(const KeyT &Val) {
+ return PointerInfo::getHashValue(Val);
+ }
+ static bool isEqual(const VH &LHS, const VH &RHS) {
+ return LHS == RHS;
+ }
+ static bool isEqual(const KeyT &LHS, const VH &RHS) {
+ return LHS == RHS.getValPtr();
+ }
+};
+
+
+template<typename DenseMapT, typename KeyT>
+class ValueMapIterator :
+ public std::iterator<std::forward_iterator_tag,
+ std::pair<KeyT, typename DenseMapT::mapped_type>,
+ ptrdiff_t> {
+ typedef typename DenseMapT::iterator BaseT;
+ typedef typename DenseMapT::mapped_type ValueT;
+ BaseT I;
+public:
+ ValueMapIterator() : I() {}
+
+ ValueMapIterator(BaseT I) : I(I) {}
+
+ BaseT base() const { return I; }
+
+ struct ValueTypeProxy {
+ const KeyT first;
+ ValueT& second;
+ ValueTypeProxy *operator->() { return this; }
+ operator std::pair<KeyT, ValueT>() const {
+ return std::make_pair(first, second);
+ }
+ };
+
+ ValueTypeProxy operator*() const {
+ ValueTypeProxy Result = {I->first.Unwrap(), I->second};
+ return Result;
+ }
+
+ ValueTypeProxy operator->() const {
+ return operator*();
+ }
+
+ bool operator==(const ValueMapIterator &RHS) const {
+ return I == RHS.I;
+ }
+ bool operator!=(const ValueMapIterator &RHS) const {
+ return I != RHS.I;
+ }
+
+ inline ValueMapIterator& operator++() { // Preincrement
+ ++I;
+ return *this;
+ }
+ ValueMapIterator operator++(int) { // Postincrement
+ ValueMapIterator tmp = *this; ++*this; return tmp;
+ }
+};
+
+template<typename DenseMapT, typename KeyT>
+class ValueMapConstIterator :
+ public std::iterator<std::forward_iterator_tag,
+ std::pair<KeyT, typename DenseMapT::mapped_type>,
+ ptrdiff_t> {
+ typedef typename DenseMapT::const_iterator BaseT;
+ typedef typename DenseMapT::mapped_type ValueT;
+ BaseT I;
+public:
+ ValueMapConstIterator() : I() {}
+ ValueMapConstIterator(BaseT I) : I(I) {}
+ ValueMapConstIterator(ValueMapIterator<DenseMapT, KeyT> Other)
+ : I(Other.base()) {}
+
+ BaseT base() const { return I; }
+
+ struct ValueTypeProxy {
+ const KeyT first;
+ const ValueT& second;
+ ValueTypeProxy *operator->() { return this; }
+ operator std::pair<KeyT, ValueT>() const {
+ return std::make_pair(first, second);
+ }
+ };
+
+ ValueTypeProxy operator*() const {
+ ValueTypeProxy Result = {I->first.Unwrap(), I->second};
+ return Result;
+ }
+
+ ValueTypeProxy operator->() const {
+ return operator*();
+ }
+
+ bool operator==(const ValueMapConstIterator &RHS) const {
+ return I == RHS.I;
+ }
+ bool operator!=(const ValueMapConstIterator &RHS) const {
+ return I != RHS.I;
+ }
+
+ inline ValueMapConstIterator& operator++() { // Preincrement
+ ++I;
+ return *this;
+ }
+ ValueMapConstIterator operator++(int) { // Postincrement
+ ValueMapConstIterator tmp = *this; ++*this; return tmp;
+ }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/ADT/VariadicFunction.h b/include/llvm/ADT/VariadicFunction.h
new file mode 100644
index 00000000000..a7f83a6bca9
--- /dev/null
+++ b/include/llvm/ADT/VariadicFunction.h
@@ -0,0 +1,331 @@
+//===--- VariadicFunctions.h - Variadic Functions ---------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements compile-time type-safe variadic functions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_VARIADIC_FUNCTION_H
+#define LLVM_ADT_VARIADIC_FUNCTION_H
+
+#include "llvm/ADT/ArrayRef.h"
+
+namespace llvm {
+
+// Define macros to aid in expanding a comma separated series with the index of
+// the series pasted onto the last token.
+#define LLVM_COMMA_JOIN1(x) x ## 0
+#define LLVM_COMMA_JOIN2(x) LLVM_COMMA_JOIN1(x), x ## 1
+#define LLVM_COMMA_JOIN3(x) LLVM_COMMA_JOIN2(x), x ## 2
+#define LLVM_COMMA_JOIN4(x) LLVM_COMMA_JOIN3(x), x ## 3
+#define LLVM_COMMA_JOIN5(x) LLVM_COMMA_JOIN4(x), x ## 4
+#define LLVM_COMMA_JOIN6(x) LLVM_COMMA_JOIN5(x), x ## 5
+#define LLVM_COMMA_JOIN7(x) LLVM_COMMA_JOIN6(x), x ## 6
+#define LLVM_COMMA_JOIN8(x) LLVM_COMMA_JOIN7(x), x ## 7
+#define LLVM_COMMA_JOIN9(x) LLVM_COMMA_JOIN8(x), x ## 8
+#define LLVM_COMMA_JOIN10(x) LLVM_COMMA_JOIN9(x), x ## 9
+#define LLVM_COMMA_JOIN11(x) LLVM_COMMA_JOIN10(x), x ## 10
+#define LLVM_COMMA_JOIN12(x) LLVM_COMMA_JOIN11(x), x ## 11
+#define LLVM_COMMA_JOIN13(x) LLVM_COMMA_JOIN12(x), x ## 12
+#define LLVM_COMMA_JOIN14(x) LLVM_COMMA_JOIN13(x), x ## 13
+#define LLVM_COMMA_JOIN15(x) LLVM_COMMA_JOIN14(x), x ## 14
+#define LLVM_COMMA_JOIN16(x) LLVM_COMMA_JOIN15(x), x ## 15
+#define LLVM_COMMA_JOIN17(x) LLVM_COMMA_JOIN16(x), x ## 16
+#define LLVM_COMMA_JOIN18(x) LLVM_COMMA_JOIN17(x), x ## 17
+#define LLVM_COMMA_JOIN19(x) LLVM_COMMA_JOIN18(x), x ## 18
+#define LLVM_COMMA_JOIN20(x) LLVM_COMMA_JOIN19(x), x ## 19
+#define LLVM_COMMA_JOIN21(x) LLVM_COMMA_JOIN20(x), x ## 20
+#define LLVM_COMMA_JOIN22(x) LLVM_COMMA_JOIN21(x), x ## 21
+#define LLVM_COMMA_JOIN23(x) LLVM_COMMA_JOIN22(x), x ## 22
+#define LLVM_COMMA_JOIN24(x) LLVM_COMMA_JOIN23(x), x ## 23
+#define LLVM_COMMA_JOIN25(x) LLVM_COMMA_JOIN24(x), x ## 24
+#define LLVM_COMMA_JOIN26(x) LLVM_COMMA_JOIN25(x), x ## 25
+#define LLVM_COMMA_JOIN27(x) LLVM_COMMA_JOIN26(x), x ## 26
+#define LLVM_COMMA_JOIN28(x) LLVM_COMMA_JOIN27(x), x ## 27
+#define LLVM_COMMA_JOIN29(x) LLVM_COMMA_JOIN28(x), x ## 28
+#define LLVM_COMMA_JOIN30(x) LLVM_COMMA_JOIN29(x), x ## 29
+#define LLVM_COMMA_JOIN31(x) LLVM_COMMA_JOIN30(x), x ## 30
+#define LLVM_COMMA_JOIN32(x) LLVM_COMMA_JOIN31(x), x ## 31
+
+/// \brief Class which can simulate a type-safe variadic function.
+///
+/// The VariadicFunction class template makes it easy to define
+/// type-safe variadic functions where all arguments have the same
+/// type.
+///
+/// Suppose we need a variadic function like this:
+///
+/// ResultT Foo(const ArgT &A_0, const ArgT &A_1, ..., const ArgT &A_N);
+///
+/// Instead of many overloads of Foo(), we only need to define a helper
+/// function that takes an array of arguments:
+///
+/// ResultT FooImpl(ArrayRef<const ArgT *> Args) {
+/// // 'Args[i]' is a pointer to the i-th argument passed to Foo().
+/// ...
+/// }
+///
+/// and then define Foo() like this:
+///
+/// const VariadicFunction<ResultT, ArgT, FooImpl> Foo;
+///
+/// VariadicFunction takes care of defining the overloads of Foo().
+///
+/// Actually, Foo is a function object (i.e. functor) instead of a plain
+/// function. This object is stateless and its constructor/destructor
+/// does nothing, so it's safe to create global objects and call Foo(...) at
+/// any time.
+///
+/// Sometimes we need a variadic function to have some fixed leading
+/// arguments whose types may be different from that of the optional
+/// arguments. For example:
+///
+/// bool FullMatch(const StringRef &S, const RE &Regex,
+/// const ArgT &A_0, ..., const ArgT &A_N);
+///
+/// VariadicFunctionN is for such cases, where N is the number of fixed
+/// arguments. It is like VariadicFunction, except that it takes N more
+/// template arguments for the types of the fixed arguments:
+///
+/// bool FullMatchImpl(const StringRef &S, const RE &Regex,
+/// ArrayRef<const ArgT *> Args) { ... }
+/// const VariadicFunction2<bool, const StringRef&,
+/// const RE&, ArgT, FullMatchImpl>
+/// FullMatch;
+///
+/// Currently VariadicFunction and friends support up-to 3
+/// fixed leading arguments and up-to 32 optional arguments.
+template <typename ResultT, typename ArgT,
+ ResultT (*Func)(ArrayRef<const ArgT *>)>
+struct VariadicFunction {
+ ResultT operator()() const {
+ return Func(ArrayRef<const ArgT *>());
+ }
+
+#define LLVM_DEFINE_OVERLOAD(N) \
+ ResultT operator()(LLVM_COMMA_JOIN ## N(const ArgT &A)) const { \
+ const ArgT *const Args[] = { LLVM_COMMA_JOIN ## N(&A) }; \
+ return Func(makeArrayRef(Args)); \
+ }
+ LLVM_DEFINE_OVERLOAD(1)
+ LLVM_DEFINE_OVERLOAD(2)
+ LLVM_DEFINE_OVERLOAD(3)
+ LLVM_DEFINE_OVERLOAD(4)
+ LLVM_DEFINE_OVERLOAD(5)
+ LLVM_DEFINE_OVERLOAD(6)
+ LLVM_DEFINE_OVERLOAD(7)
+ LLVM_DEFINE_OVERLOAD(8)
+ LLVM_DEFINE_OVERLOAD(9)
+ LLVM_DEFINE_OVERLOAD(10)
+ LLVM_DEFINE_OVERLOAD(11)
+ LLVM_DEFINE_OVERLOAD(12)
+ LLVM_DEFINE_OVERLOAD(13)
+ LLVM_DEFINE_OVERLOAD(14)
+ LLVM_DEFINE_OVERLOAD(15)
+ LLVM_DEFINE_OVERLOAD(16)
+ LLVM_DEFINE_OVERLOAD(17)
+ LLVM_DEFINE_OVERLOAD(18)
+ LLVM_DEFINE_OVERLOAD(19)
+ LLVM_DEFINE_OVERLOAD(20)
+ LLVM_DEFINE_OVERLOAD(21)
+ LLVM_DEFINE_OVERLOAD(22)
+ LLVM_DEFINE_OVERLOAD(23)
+ LLVM_DEFINE_OVERLOAD(24)
+ LLVM_DEFINE_OVERLOAD(25)
+ LLVM_DEFINE_OVERLOAD(26)
+ LLVM_DEFINE_OVERLOAD(27)
+ LLVM_DEFINE_OVERLOAD(28)
+ LLVM_DEFINE_OVERLOAD(29)
+ LLVM_DEFINE_OVERLOAD(30)
+ LLVM_DEFINE_OVERLOAD(31)
+ LLVM_DEFINE_OVERLOAD(32)
+#undef LLVM_DEFINE_OVERLOAD
+};
+
+template <typename ResultT, typename Param0T, typename ArgT,
+ ResultT (*Func)(Param0T, ArrayRef<const ArgT *>)>
+struct VariadicFunction1 {
+ ResultT operator()(Param0T P0) const {
+ return Func(P0, ArrayRef<const ArgT *>());
+ }
+
+#define LLVM_DEFINE_OVERLOAD(N) \
+ ResultT operator()(Param0T P0, LLVM_COMMA_JOIN ## N(const ArgT &A)) const { \
+ const ArgT *const Args[] = { LLVM_COMMA_JOIN ## N(&A) }; \
+ return Func(P0, makeArrayRef(Args)); \
+ }
+ LLVM_DEFINE_OVERLOAD(1)
+ LLVM_DEFINE_OVERLOAD(2)
+ LLVM_DEFINE_OVERLOAD(3)
+ LLVM_DEFINE_OVERLOAD(4)
+ LLVM_DEFINE_OVERLOAD(5)
+ LLVM_DEFINE_OVERLOAD(6)
+ LLVM_DEFINE_OVERLOAD(7)
+ LLVM_DEFINE_OVERLOAD(8)
+ LLVM_DEFINE_OVERLOAD(9)
+ LLVM_DEFINE_OVERLOAD(10)
+ LLVM_DEFINE_OVERLOAD(11)
+ LLVM_DEFINE_OVERLOAD(12)
+ LLVM_DEFINE_OVERLOAD(13)
+ LLVM_DEFINE_OVERLOAD(14)
+ LLVM_DEFINE_OVERLOAD(15)
+ LLVM_DEFINE_OVERLOAD(16)
+ LLVM_DEFINE_OVERLOAD(17)
+ LLVM_DEFINE_OVERLOAD(18)
+ LLVM_DEFINE_OVERLOAD(19)
+ LLVM_DEFINE_OVERLOAD(20)
+ LLVM_DEFINE_OVERLOAD(21)
+ LLVM_DEFINE_OVERLOAD(22)
+ LLVM_DEFINE_OVERLOAD(23)
+ LLVM_DEFINE_OVERLOAD(24)
+ LLVM_DEFINE_OVERLOAD(25)
+ LLVM_DEFINE_OVERLOAD(26)
+ LLVM_DEFINE_OVERLOAD(27)
+ LLVM_DEFINE_OVERLOAD(28)
+ LLVM_DEFINE_OVERLOAD(29)
+ LLVM_DEFINE_OVERLOAD(30)
+ LLVM_DEFINE_OVERLOAD(31)
+ LLVM_DEFINE_OVERLOAD(32)
+#undef LLVM_DEFINE_OVERLOAD
+};
+
+template <typename ResultT, typename Param0T, typename Param1T, typename ArgT,
+ ResultT (*Func)(Param0T, Param1T, ArrayRef<const ArgT *>)>
+struct VariadicFunction2 {
+ ResultT operator()(Param0T P0, Param1T P1) const {
+ return Func(P0, P1, ArrayRef<const ArgT *>());
+ }
+
+#define LLVM_DEFINE_OVERLOAD(N) \
+ ResultT operator()(Param0T P0, Param1T P1, \
+ LLVM_COMMA_JOIN ## N(const ArgT &A)) const { \
+ const ArgT *const Args[] = { LLVM_COMMA_JOIN ## N(&A) }; \
+ return Func(P0, P1, makeArrayRef(Args)); \
+ }
+ LLVM_DEFINE_OVERLOAD(1)
+ LLVM_DEFINE_OVERLOAD(2)
+ LLVM_DEFINE_OVERLOAD(3)
+ LLVM_DEFINE_OVERLOAD(4)
+ LLVM_DEFINE_OVERLOAD(5)
+ LLVM_DEFINE_OVERLOAD(6)
+ LLVM_DEFINE_OVERLOAD(7)
+ LLVM_DEFINE_OVERLOAD(8)
+ LLVM_DEFINE_OVERLOAD(9)
+ LLVM_DEFINE_OVERLOAD(10)
+ LLVM_DEFINE_OVERLOAD(11)
+ LLVM_DEFINE_OVERLOAD(12)
+ LLVM_DEFINE_OVERLOAD(13)
+ LLVM_DEFINE_OVERLOAD(14)
+ LLVM_DEFINE_OVERLOAD(15)
+ LLVM_DEFINE_OVERLOAD(16)
+ LLVM_DEFINE_OVERLOAD(17)
+ LLVM_DEFINE_OVERLOAD(18)
+ LLVM_DEFINE_OVERLOAD(19)
+ LLVM_DEFINE_OVERLOAD(20)
+ LLVM_DEFINE_OVERLOAD(21)
+ LLVM_DEFINE_OVERLOAD(22)
+ LLVM_DEFINE_OVERLOAD(23)
+ LLVM_DEFINE_OVERLOAD(24)
+ LLVM_DEFINE_OVERLOAD(25)
+ LLVM_DEFINE_OVERLOAD(26)
+ LLVM_DEFINE_OVERLOAD(27)
+ LLVM_DEFINE_OVERLOAD(28)
+ LLVM_DEFINE_OVERLOAD(29)
+ LLVM_DEFINE_OVERLOAD(30)
+ LLVM_DEFINE_OVERLOAD(31)
+ LLVM_DEFINE_OVERLOAD(32)
+#undef LLVM_DEFINE_OVERLOAD
+};
+
+template <typename ResultT, typename Param0T, typename Param1T,
+ typename Param2T, typename ArgT,
+ ResultT (*Func)(Param0T, Param1T, Param2T, ArrayRef<const ArgT *>)>
+struct VariadicFunction3 {
+ ResultT operator()(Param0T P0, Param1T P1, Param2T P2) const {
+ return Func(P0, P1, P2, ArrayRef<const ArgT *>());
+ }
+
+#define LLVM_DEFINE_OVERLOAD(N) \
+ ResultT operator()(Param0T P0, Param1T P1, Param2T P2, \
+ LLVM_COMMA_JOIN ## N(const ArgT &A)) const { \
+ const ArgT *const Args[] = { LLVM_COMMA_JOIN ## N(&A) }; \
+ return Func(P0, P1, P2, makeArrayRef(Args)); \
+ }
+ LLVM_DEFINE_OVERLOAD(1)
+ LLVM_DEFINE_OVERLOAD(2)
+ LLVM_DEFINE_OVERLOAD(3)
+ LLVM_DEFINE_OVERLOAD(4)
+ LLVM_DEFINE_OVERLOAD(5)
+ LLVM_DEFINE_OVERLOAD(6)
+ LLVM_DEFINE_OVERLOAD(7)
+ LLVM_DEFINE_OVERLOAD(8)
+ LLVM_DEFINE_OVERLOAD(9)
+ LLVM_DEFINE_OVERLOAD(10)
+ LLVM_DEFINE_OVERLOAD(11)
+ LLVM_DEFINE_OVERLOAD(12)
+ LLVM_DEFINE_OVERLOAD(13)
+ LLVM_DEFINE_OVERLOAD(14)
+ LLVM_DEFINE_OVERLOAD(15)
+ LLVM_DEFINE_OVERLOAD(16)
+ LLVM_DEFINE_OVERLOAD(17)
+ LLVM_DEFINE_OVERLOAD(18)
+ LLVM_DEFINE_OVERLOAD(19)
+ LLVM_DEFINE_OVERLOAD(20)
+ LLVM_DEFINE_OVERLOAD(21)
+ LLVM_DEFINE_OVERLOAD(22)
+ LLVM_DEFINE_OVERLOAD(23)
+ LLVM_DEFINE_OVERLOAD(24)
+ LLVM_DEFINE_OVERLOAD(25)
+ LLVM_DEFINE_OVERLOAD(26)
+ LLVM_DEFINE_OVERLOAD(27)
+ LLVM_DEFINE_OVERLOAD(28)
+ LLVM_DEFINE_OVERLOAD(29)
+ LLVM_DEFINE_OVERLOAD(30)
+ LLVM_DEFINE_OVERLOAD(31)
+ LLVM_DEFINE_OVERLOAD(32)
+#undef LLVM_DEFINE_OVERLOAD
+};
+
+// Cleanup the macro namespace.
+#undef LLVM_COMMA_JOIN1
+#undef LLVM_COMMA_JOIN2
+#undef LLVM_COMMA_JOIN3
+#undef LLVM_COMMA_JOIN4
+#undef LLVM_COMMA_JOIN5
+#undef LLVM_COMMA_JOIN6
+#undef LLVM_COMMA_JOIN7
+#undef LLVM_COMMA_JOIN8
+#undef LLVM_COMMA_JOIN9
+#undef LLVM_COMMA_JOIN10
+#undef LLVM_COMMA_JOIN11
+#undef LLVM_COMMA_JOIN12
+#undef LLVM_COMMA_JOIN13
+#undef LLVM_COMMA_JOIN14
+#undef LLVM_COMMA_JOIN15
+#undef LLVM_COMMA_JOIN16
+#undef LLVM_COMMA_JOIN17
+#undef LLVM_COMMA_JOIN18
+#undef LLVM_COMMA_JOIN19
+#undef LLVM_COMMA_JOIN20
+#undef LLVM_COMMA_JOIN21
+#undef LLVM_COMMA_JOIN22
+#undef LLVM_COMMA_JOIN23
+#undef LLVM_COMMA_JOIN24
+#undef LLVM_COMMA_JOIN25
+#undef LLVM_COMMA_JOIN26
+#undef LLVM_COMMA_JOIN27
+#undef LLVM_COMMA_JOIN28
+#undef LLVM_COMMA_JOIN29
+#undef LLVM_COMMA_JOIN30
+#undef LLVM_COMMA_JOIN31
+#undef LLVM_COMMA_JOIN32
+
+} // end namespace llvm
+
+#endif // LLVM_ADT_VARIADIC_FUNCTION_H
diff --git a/include/llvm/ADT/edit_distance.h b/include/llvm/ADT/edit_distance.h
new file mode 100644
index 00000000000..f77ef13fef2
--- /dev/null
+++ b/include/llvm/ADT/edit_distance.h
@@ -0,0 +1,102 @@
+//===-- llvm/ADT/edit_distance.h - Array edit distance function --- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a Levenshtein distance function that works for any two
+// sequences, with each element of each sequence being analogous to a character
+// in a string.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_EDIT_DISTANCE_H
+#define LLVM_ADT_EDIT_DISTANCE_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/OwningPtr.h"
+#include <algorithm>
+
+namespace llvm {
+
+/// \brief Determine the edit distance between two sequences.
+///
+/// \param FromArray the first sequence to compare.
+///
+/// \param ToArray the second sequence to compare.
+///
+/// \param AllowReplacements whether to allow element replacements (change one
+/// element into another) as a single operation, rather than as two operations
+/// (an insertion and a removal).
+///
+/// \param MaxEditDistance If non-zero, the maximum edit distance that this
+/// routine is allowed to compute. If the edit distance will exceed that
+/// maximum, returns \c MaxEditDistance+1.
+///
+/// \returns the minimum number of element insertions, removals, or (if
+/// \p AllowReplacements is \c true) replacements needed to transform one of
+/// the given sequences into the other. If zero, the sequences are identical.
+template<typename T>
+unsigned ComputeEditDistance(ArrayRef<T> FromArray, ArrayRef<T> ToArray,
+ bool AllowReplacements = true,
+ unsigned MaxEditDistance = 0) {
+ // The algorithm implemented below is the "classic"
+ // dynamic-programming algorithm for computing the Levenshtein
+ // distance, which is described here:
+ //
+ // http://en.wikipedia.org/wiki/Levenshtein_distance
+ //
+ // Although the algorithm is typically described using an m x n
+ // array, only two rows are used at a time, so this implemenation
+ // just keeps two separate vectors for those two rows.
+ typename ArrayRef<T>::size_type m = FromArray.size();
+ typename ArrayRef<T>::size_type n = ToArray.size();
+
+ const unsigned SmallBufferSize = 64;
+ unsigned SmallBuffer[SmallBufferSize];
+ llvm::OwningArrayPtr<unsigned> Allocated;
+ unsigned *Previous = SmallBuffer;
+ if (2*(n + 1) > SmallBufferSize) {
+ Previous = new unsigned [2*(n+1)];
+ Allocated.reset(Previous);
+ }
+ unsigned *Current = Previous + (n + 1);
+
+ for (unsigned i = 0; i <= n; ++i)
+ Previous[i] = i;
+
+ for (typename ArrayRef<T>::size_type y = 1; y <= m; ++y) {
+ Current[0] = y;
+ unsigned BestThisRow = Current[0];
+
+ for (typename ArrayRef<T>::size_type x = 1; x <= n; ++x) {
+ if (AllowReplacements) {
+ Current[x] = std::min(
+ Previous[x-1] + (FromArray[y-1] == ToArray[x-1] ? 0u : 1u),
+ std::min(Current[x-1], Previous[x])+1);
+ }
+ else {
+ if (FromArray[y-1] == ToArray[x-1]) Current[x] = Previous[x-1];
+ else Current[x] = std::min(Current[x-1], Previous[x]) + 1;
+ }
+ BestThisRow = std::min(BestThisRow, Current[x]);
+ }
+
+ if (MaxEditDistance && BestThisRow > MaxEditDistance)
+ return MaxEditDistance + 1;
+
+ unsigned *tmp = Current;
+ Current = Previous;
+ Previous = tmp;
+ }
+
+ unsigned Result = Previous[n];
+ return Result;
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ADT/ilist.h b/include/llvm/ADT/ilist.h
new file mode 100644
index 00000000000..7f5cd171814
--- /dev/null
+++ b/include/llvm/ADT/ilist.h
@@ -0,0 +1,705 @@
+//==-- llvm/ADT/ilist.h - Intrusive Linked List Template ---------*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines classes to implement an intrusive doubly linked list class
+// (i.e. each node of the list must contain a next and previous field for the
+// list.
+//
+// The ilist_traits trait class is used to gain access to the next and previous
+// fields of the node type that the list is instantiated with. If it is not
+// specialized, the list defaults to using the getPrev(), getNext() method calls
+// to get the next and previous pointers.
+//
+// The ilist class itself, should be a plug in replacement for list, assuming
+// that the nodes contain next/prev pointers. This list replacement does not
+// provide a constant time size() method, so be careful to use empty() when you
+// really want to know if it's empty.
+//
+// The ilist class is implemented by allocating a 'tail' node when the list is
+// created (using ilist_traits<>::createSentinel()). This tail node is
+// absolutely required because the user must be able to compute end()-1. Because
+// of this, users of the direct next/prev links will see an extra link on the
+// end of the list, which should be ignored.
+//
+// Requirements for a user of this list:
+//
+// 1. The user must provide {g|s}et{Next|Prev} methods, or specialize
+// ilist_traits to provide an alternate way of getting and setting next and
+// prev links.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_ILIST_H
+#define LLVM_ADT_ILIST_H
+
+#include "llvm/Support/Compiler.h"
+#include <algorithm>
+#include <cassert>
+#include <cstddef>
+#include <iterator>
+
+namespace llvm {
+
+template<typename NodeTy, typename Traits> class iplist;
+template<typename NodeTy> class ilist_iterator;
+
+/// ilist_nextprev_traits - A fragment for template traits for intrusive list
+/// that provides default next/prev implementations for common operations.
+///
+template<typename NodeTy>
+struct ilist_nextprev_traits {
+ static NodeTy *getPrev(NodeTy *N) { return N->getPrev(); }
+ static NodeTy *getNext(NodeTy *N) { return N->getNext(); }
+ static const NodeTy *getPrev(const NodeTy *N) { return N->getPrev(); }
+ static const NodeTy *getNext(const NodeTy *N) { return N->getNext(); }
+
+ static void setPrev(NodeTy *N, NodeTy *Prev) { N->setPrev(Prev); }
+ static void setNext(NodeTy *N, NodeTy *Next) { N->setNext(Next); }
+};
+
+template<typename NodeTy>
+struct ilist_traits;
+
+/// ilist_sentinel_traits - A fragment for template traits for intrusive list
+/// that provides default sentinel implementations for common operations.
+///
+/// ilist_sentinel_traits implements a lazy dynamic sentinel allocation
+/// strategy. The sentinel is stored in the prev field of ilist's Head.
+///
+template<typename NodeTy>
+struct ilist_sentinel_traits {
+ /// createSentinel - create the dynamic sentinel
+ static NodeTy *createSentinel() { return new NodeTy(); }
+
+ /// destroySentinel - deallocate the dynamic sentinel
+ static void destroySentinel(NodeTy *N) { delete N; }
+
+ /// provideInitialHead - when constructing an ilist, provide a starting
+ /// value for its Head
+ /// @return null node to indicate that it needs to be allocated later
+ static NodeTy *provideInitialHead() { return 0; }
+
+ /// ensureHead - make sure that Head is either already
+ /// initialized or assigned a fresh sentinel
+ /// @return the sentinel
+ static NodeTy *ensureHead(NodeTy *&Head) {
+ if (!Head) {
+ Head = ilist_traits<NodeTy>::createSentinel();
+ ilist_traits<NodeTy>::noteHead(Head, Head);
+ ilist_traits<NodeTy>::setNext(Head, 0);
+ return Head;
+ }
+ return ilist_traits<NodeTy>::getPrev(Head);
+ }
+
+ /// noteHead - stash the sentinel into its default location
+ static void noteHead(NodeTy *NewHead, NodeTy *Sentinel) {
+ ilist_traits<NodeTy>::setPrev(NewHead, Sentinel);
+ }
+};
+
+/// ilist_node_traits - A fragment for template traits for intrusive list
+/// that provides default node related operations.
+///
+template<typename NodeTy>
+struct ilist_node_traits {
+ static NodeTy *createNode(const NodeTy &V) { return new NodeTy(V); }
+ static void deleteNode(NodeTy *V) { delete V; }
+
+ void addNodeToList(NodeTy *) {}
+ void removeNodeFromList(NodeTy *) {}
+ void transferNodesFromList(ilist_node_traits & /*SrcTraits*/,
+ ilist_iterator<NodeTy> /*first*/,
+ ilist_iterator<NodeTy> /*last*/) {}
+};
+
+/// ilist_default_traits - Default template traits for intrusive list.
+/// By inheriting from this, you can easily use default implementations
+/// for all common operations.
+///
+template<typename NodeTy>
+struct ilist_default_traits : public ilist_nextprev_traits<NodeTy>,
+ public ilist_sentinel_traits<NodeTy>,
+ public ilist_node_traits<NodeTy> {
+};
+
+// Template traits for intrusive list. By specializing this template class, you
+// can change what next/prev fields are used to store the links...
+template<typename NodeTy>
+struct ilist_traits : public ilist_default_traits<NodeTy> {};
+
+// Const traits are the same as nonconst traits...
+template<typename Ty>
+struct ilist_traits<const Ty> : public ilist_traits<Ty> {};
+
+//===----------------------------------------------------------------------===//
+// ilist_iterator<Node> - Iterator for intrusive list.
+//
+template<typename NodeTy>
+class ilist_iterator
+ : public std::iterator<std::bidirectional_iterator_tag, NodeTy, ptrdiff_t> {
+
+public:
+ typedef ilist_traits<NodeTy> Traits;
+ typedef std::iterator<std::bidirectional_iterator_tag,
+ NodeTy, ptrdiff_t> super;
+
+ typedef typename super::value_type value_type;
+ typedef typename super::difference_type difference_type;
+ typedef typename super::pointer pointer;
+ typedef typename super::reference reference;
+private:
+ pointer NodePtr;
+
+ // ilist_iterator is not a random-access iterator, but it has an
+ // implicit conversion to pointer-type, which is. Declare (but
+ // don't define) these functions as private to help catch
+ // accidental misuse.
+ void operator[](difference_type) const;
+ void operator+(difference_type) const;
+ void operator-(difference_type) const;
+ void operator+=(difference_type) const;
+ void operator-=(difference_type) const;
+ template<class T> void operator<(T) const;
+ template<class T> void operator<=(T) const;
+ template<class T> void operator>(T) const;
+ template<class T> void operator>=(T) const;
+ template<class T> void operator-(T) const;
+public:
+
+ ilist_iterator(pointer NP) : NodePtr(NP) {}
+ ilist_iterator(reference NR) : NodePtr(&NR) {}
+ ilist_iterator() : NodePtr(0) {}
+
+ // This is templated so that we can allow constructing a const iterator from
+ // a nonconst iterator...
+ template<class node_ty>
+ ilist_iterator(const ilist_iterator<node_ty> &RHS)
+ : NodePtr(RHS.getNodePtrUnchecked()) {}
+
+ // This is templated so that we can allow assigning to a const iterator from
+ // a nonconst iterator...
+ template<class node_ty>
+ const ilist_iterator &operator=(const ilist_iterator<node_ty> &RHS) {
+ NodePtr = RHS.getNodePtrUnchecked();
+ return *this;
+ }
+
+ // Accessors...
+ operator pointer() const {
+ return NodePtr;
+ }
+
+ reference operator*() const {
+ return *NodePtr;
+ }
+ pointer operator->() const { return &operator*(); }
+
+ // Comparison operators
+ bool operator==(const ilist_iterator &RHS) const {
+ return NodePtr == RHS.NodePtr;
+ }
+ bool operator!=(const ilist_iterator &RHS) const {
+ return NodePtr != RHS.NodePtr;
+ }
+
+ // Increment and decrement operators...
+ ilist_iterator &operator--() { // predecrement - Back up
+ NodePtr = Traits::getPrev(NodePtr);
+ assert(NodePtr && "--'d off the beginning of an ilist!");
+ return *this;
+ }
+ ilist_iterator &operator++() { // preincrement - Advance
+ NodePtr = Traits::getNext(NodePtr);
+ return *this;
+ }
+ ilist_iterator operator--(int) { // postdecrement operators...
+ ilist_iterator tmp = *this;
+ --*this;
+ return tmp;
+ }
+ ilist_iterator operator++(int) { // postincrement operators...
+ ilist_iterator tmp = *this;
+ ++*this;
+ return tmp;
+ }
+
+ // Internal interface, do not use...
+ pointer getNodePtrUnchecked() const { return NodePtr; }
+};
+
+// do not implement. this is to catch errors when people try to use
+// them as random access iterators
+template<typename T>
+void operator-(int, ilist_iterator<T>);
+template<typename T>
+void operator-(ilist_iterator<T>,int);
+
+template<typename T>
+void operator+(int, ilist_iterator<T>);
+template<typename T>
+void operator+(ilist_iterator<T>,int);
+
+// operator!=/operator== - Allow mixed comparisons without dereferencing
+// the iterator, which could very likely be pointing to end().
+template<typename T>
+bool operator!=(const T* LHS, const ilist_iterator<const T> &RHS) {
+ return LHS != RHS.getNodePtrUnchecked();
+}
+template<typename T>
+bool operator==(const T* LHS, const ilist_iterator<const T> &RHS) {
+ return LHS == RHS.getNodePtrUnchecked();
+}
+template<typename T>
+bool operator!=(T* LHS, const ilist_iterator<T> &RHS) {
+ return LHS != RHS.getNodePtrUnchecked();
+}
+template<typename T>
+bool operator==(T* LHS, const ilist_iterator<T> &RHS) {
+ return LHS == RHS.getNodePtrUnchecked();
+}
+
+
+// Allow ilist_iterators to convert into pointers to a node automatically when
+// used by the dyn_cast, cast, isa mechanisms...
+
+template<typename From> struct simplify_type;
+
+template<typename NodeTy> struct simplify_type<ilist_iterator<NodeTy> > {
+ typedef NodeTy* SimpleType;
+
+ static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
+ return &*Node;
+ }
+};
+template<typename NodeTy> struct simplify_type<const ilist_iterator<NodeTy> > {
+ typedef NodeTy* SimpleType;
+
+ static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
+ return &*Node;
+ }
+};
+
+
+//===----------------------------------------------------------------------===//
+//
+/// iplist - The subset of list functionality that can safely be used on nodes
+/// of polymorphic types, i.e. a heterogeneous list with a common base class that
+/// holds the next/prev pointers. The only state of the list itself is a single
+/// pointer to the head of the list.
+///
+/// This list can be in one of three interesting states:
+/// 1. The list may be completely unconstructed. In this case, the head
+/// pointer is null. When in this form, any query for an iterator (e.g.
+/// begin() or end()) causes the list to transparently change to state #2.
+/// 2. The list may be empty, but contain a sentinel for the end iterator. This
+/// sentinel is created by the Traits::createSentinel method and is a link
+/// in the list. When the list is empty, the pointer in the iplist points
+/// to the sentinel. Once the sentinel is constructed, it
+/// is not destroyed until the list is.
+/// 3. The list may contain actual objects in it, which are stored as a doubly
+/// linked list of nodes. One invariant of the list is that the predecessor
+/// of the first node in the list always points to the last node in the list,
+/// and the successor pointer for the sentinel (which always stays at the
+/// end of the list) is always null.
+///
+template<typename NodeTy, typename Traits=ilist_traits<NodeTy> >
+class iplist : public Traits {
+ mutable NodeTy *Head;
+
+ // Use the prev node pointer of 'head' as the tail pointer. This is really a
+ // circularly linked list where we snip the 'next' link from the sentinel node
+ // back to the first node in the list (to preserve assertions about going off
+ // the end of the list).
+ NodeTy *getTail() { return this->ensureHead(Head); }
+ const NodeTy *getTail() const { return this->ensureHead(Head); }
+ void setTail(NodeTy *N) const { this->noteHead(Head, N); }
+
+ /// CreateLazySentinel - This method verifies whether the sentinel for the
+ /// list has been created and lazily makes it if not.
+ void CreateLazySentinel() const {
+ this->ensureHead(Head);
+ }
+
+ static bool op_less(NodeTy &L, NodeTy &R) { return L < R; }
+ static bool op_equal(NodeTy &L, NodeTy &R) { return L == R; }
+
+ // No fundamental reason why iplist can't be copyable, but the default
+ // copy/copy-assign won't do.
+ iplist(const iplist &) LLVM_DELETED_FUNCTION;
+ void operator=(const iplist &) LLVM_DELETED_FUNCTION;
+
+public:
+ typedef NodeTy *pointer;
+ typedef const NodeTy *const_pointer;
+ typedef NodeTy &reference;
+ typedef const NodeTy &const_reference;
+ typedef NodeTy value_type;
+ typedef ilist_iterator<NodeTy> iterator;
+ typedef ilist_iterator<const NodeTy> const_iterator;
+ typedef size_t size_type;
+ typedef ptrdiff_t difference_type;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+
+ iplist() : Head(this->provideInitialHead()) {}
+ ~iplist() {
+ if (!Head) return;
+ clear();
+ Traits::destroySentinel(getTail());
+ }
+
+ // Iterator creation methods.
+ iterator begin() {
+ CreateLazySentinel();
+ return iterator(Head);
+ }
+ const_iterator begin() const {
+ CreateLazySentinel();
+ return const_iterator(Head);
+ }
+ iterator end() {
+ CreateLazySentinel();
+ return iterator(getTail());
+ }
+ const_iterator end() const {
+ CreateLazySentinel();
+ return const_iterator(getTail());
+ }
+
+ // reverse iterator creation methods.
+ reverse_iterator rbegin() { return reverse_iterator(end()); }
+ const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
+ reverse_iterator rend() { return reverse_iterator(begin()); }
+ const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
+
+
+ // Miscellaneous inspection routines.
+ size_type max_size() const { return size_type(-1); }
+ bool empty() const { return Head == 0 || Head == getTail(); }
+
+ // Front and back accessor functions...
+ reference front() {
+ assert(!empty() && "Called front() on empty list!");
+ return *Head;
+ }
+ const_reference front() const {
+ assert(!empty() && "Called front() on empty list!");
+ return *Head;
+ }
+ reference back() {
+ assert(!empty() && "Called back() on empty list!");
+ return *this->getPrev(getTail());
+ }
+ const_reference back() const {
+ assert(!empty() && "Called back() on empty list!");
+ return *this->getPrev(getTail());
+ }
+
+ void swap(iplist &RHS) {
+ assert(0 && "Swap does not use list traits callback correctly yet!");
+ std::swap(Head, RHS.Head);
+ }
+
+ iterator insert(iterator where, NodeTy *New) {
+ NodeTy *CurNode = where.getNodePtrUnchecked();
+ NodeTy *PrevNode = this->getPrev(CurNode);
+ this->setNext(New, CurNode);
+ this->setPrev(New, PrevNode);
+
+ if (CurNode != Head) // Is PrevNode off the beginning of the list?
+ this->setNext(PrevNode, New);
+ else
+ Head = New;
+ this->setPrev(CurNode, New);
+
+ this->addNodeToList(New); // Notify traits that we added a node...
+ return New;
+ }
+
+ iterator insertAfter(iterator where, NodeTy *New) {
+ if (empty())
+ return insert(begin(), New);
+ else
+ return insert(++where, New);
+ }
+
+ NodeTy *remove(iterator &IT) {
+ assert(IT != end() && "Cannot remove end of list!");
+ NodeTy *Node = &*IT;
+ NodeTy *NextNode = this->getNext(Node);
+ NodeTy *PrevNode = this->getPrev(Node);
+
+ if (Node != Head) // Is PrevNode off the beginning of the list?
+ this->setNext(PrevNode, NextNode);
+ else
+ Head = NextNode;
+ this->setPrev(NextNode, PrevNode);
+ IT = NextNode;
+ this->removeNodeFromList(Node); // Notify traits that we removed a node...
+
+ // Set the next/prev pointers of the current node to null. This isn't
+ // strictly required, but this catches errors where a node is removed from
+ // an ilist (and potentially deleted) with iterators still pointing at it.
+ // When those iterators are incremented or decremented, they will assert on
+ // the null next/prev pointer instead of "usually working".
+ this->setNext(Node, 0);
+ this->setPrev(Node, 0);
+ return Node;
+ }
+
+ NodeTy *remove(const iterator &IT) {
+ iterator MutIt = IT;
+ return remove(MutIt);
+ }
+
+ // erase - remove a node from the controlled sequence... and delete it.
+ iterator erase(iterator where) {
+ this->deleteNode(remove(where));
+ return where;
+ }
+
+
+private:
+ // transfer - The heart of the splice function. Move linked list nodes from
+ // [first, last) into position.
+ //
+ void transfer(iterator position, iplist &L2, iterator first, iterator last) {
+ assert(first != last && "Should be checked by callers");
+
+ if (position != last) {
+ // Note: we have to be careful about the case when we move the first node
+ // in the list. This node is the list sentinel node and we can't move it.
+ NodeTy *ThisSentinel = getTail();
+ setTail(0);
+ NodeTy *L2Sentinel = L2.getTail();
+ L2.setTail(0);
+
+ // Remove [first, last) from its old position.
+ NodeTy *First = &*first, *Prev = this->getPrev(First);
+ NodeTy *Next = last.getNodePtrUnchecked(), *Last = this->getPrev(Next);
+ if (Prev)
+ this->setNext(Prev, Next);
+ else
+ L2.Head = Next;
+ this->setPrev(Next, Prev);
+
+ // Splice [first, last) into its new position.
+ NodeTy *PosNext = position.getNodePtrUnchecked();
+ NodeTy *PosPrev = this->getPrev(PosNext);
+
+ // Fix head of list...
+ if (PosPrev)
+ this->setNext(PosPrev, First);
+ else
+ Head = First;
+ this->setPrev(First, PosPrev);
+
+ // Fix end of list...
+ this->setNext(Last, PosNext);
+ this->setPrev(PosNext, Last);
+
+ this->transferNodesFromList(L2, First, PosNext);
+
+ // Now that everything is set, restore the pointers to the list sentinels.
+ L2.setTail(L2Sentinel);
+ setTail(ThisSentinel);
+ }
+ }
+
+public:
+
+ //===----------------------------------------------------------------------===
+ // Functionality derived from other functions defined above...
+ //
+
+ size_type size() const {
+ if (Head == 0) return 0; // Don't require construction of sentinel if empty.
+ return std::distance(begin(), end());
+ }
+
+ iterator erase(iterator first, iterator last) {
+ while (first != last)
+ first = erase(first);
+ return last;
+ }
+
+ void clear() { if (Head) erase(begin(), end()); }
+
+ // Front and back inserters...
+ void push_front(NodeTy *val) { insert(begin(), val); }
+ void push_back(NodeTy *val) { insert(end(), val); }
+ void pop_front() {
+ assert(!empty() && "pop_front() on empty list!");
+ erase(begin());
+ }
+ void pop_back() {
+ assert(!empty() && "pop_back() on empty list!");
+ iterator t = end(); erase(--t);
+ }
+
+ // Special forms of insert...
+ template<class InIt> void insert(iterator where, InIt first, InIt last) {
+ for (; first != last; ++first) insert(where, *first);
+ }
+
+ // Splice members - defined in terms of transfer...
+ void splice(iterator where, iplist &L2) {
+ if (!L2.empty())
+ transfer(where, L2, L2.begin(), L2.end());
+ }
+ void splice(iterator where, iplist &L2, iterator first) {
+ iterator last = first; ++last;
+ if (where == first || where == last) return; // No change
+ transfer(where, L2, first, last);
+ }
+ void splice(iterator where, iplist &L2, iterator first, iterator last) {
+ if (first != last) transfer(where, L2, first, last);
+ }
+
+
+
+ //===----------------------------------------------------------------------===
+ // High-Level Functionality that shouldn't really be here, but is part of list
+ //
+
+ // These two functions are actually called remove/remove_if in list<>, but
+ // they actually do the job of erase, rename them accordingly.
+ //
+ void erase(const NodeTy &val) {
+ for (iterator I = begin(), E = end(); I != E; ) {
+ iterator next = I; ++next;
+ if (*I == val) erase(I);
+ I = next;
+ }
+ }
+ template<class Pr1> void erase_if(Pr1 pred) {
+ for (iterator I = begin(), E = end(); I != E; ) {
+ iterator next = I; ++next;
+ if (pred(*I)) erase(I);
+ I = next;
+ }
+ }
+
+ template<class Pr2> void unique(Pr2 pred) {
+ if (empty()) return;
+ for (iterator I = begin(), E = end(), Next = begin(); ++Next != E;) {
+ if (pred(*I))
+ erase(Next);
+ else
+ I = Next;
+ Next = I;
+ }
+ }
+ void unique() { unique(op_equal); }
+
+ template<class Pr3> void merge(iplist &right, Pr3 pred) {
+ iterator first1 = begin(), last1 = end();
+ iterator first2 = right.begin(), last2 = right.end();
+ while (first1 != last1 && first2 != last2)
+ if (pred(*first2, *first1)) {
+ iterator next = first2;
+ transfer(first1, right, first2, ++next);
+ first2 = next;
+ } else {
+ ++first1;
+ }
+ if (first2 != last2) transfer(last1, right, first2, last2);
+ }
+ void merge(iplist &right) { return merge(right, op_less); }
+
+ template<class Pr3> void sort(Pr3 pred);
+ void sort() { sort(op_less); }
+};
+
+
+template<typename NodeTy>
+struct ilist : public iplist<NodeTy> {
+ typedef typename iplist<NodeTy>::size_type size_type;
+ typedef typename iplist<NodeTy>::iterator iterator;
+
+ ilist() {}
+ ilist(const ilist &right) {
+ insert(this->begin(), right.begin(), right.end());
+ }
+ explicit ilist(size_type count) {
+ insert(this->begin(), count, NodeTy());
+ }
+ ilist(size_type count, const NodeTy &val) {
+ insert(this->begin(), count, val);
+ }
+ template<class InIt> ilist(InIt first, InIt last) {
+ insert(this->begin(), first, last);
+ }
+
+ // bring hidden functions into scope
+ using iplist<NodeTy>::insert;
+ using iplist<NodeTy>::push_front;
+ using iplist<NodeTy>::push_back;
+
+ // Main implementation here - Insert for a node passed by value...
+ iterator insert(iterator where, const NodeTy &val) {
+ return insert(where, this->createNode(val));
+ }
+
+
+ // Front and back inserters...
+ void push_front(const NodeTy &val) { insert(this->begin(), val); }
+ void push_back(const NodeTy &val) { insert(this->end(), val); }
+
+ void insert(iterator where, size_type count, const NodeTy &val) {
+ for (; count != 0; --count) insert(where, val);
+ }
+
+ // Assign special forms...
+ void assign(size_type count, const NodeTy &val) {
+ iterator I = this->begin();
+ for (; I != this->end() && count != 0; ++I, --count)
+ *I = val;
+ if (count != 0)
+ insert(this->end(), val, val);
+ else
+ erase(I, this->end());
+ }
+ template<class InIt> void assign(InIt first1, InIt last1) {
+ iterator first2 = this->begin(), last2 = this->end();
+ for ( ; first1 != last1 && first2 != last2; ++first1, ++first2)
+ *first1 = *first2;
+ if (first2 == last2)
+ erase(first1, last1);
+ else
+ insert(last1, first2, last2);
+ }
+
+
+ // Resize members...
+ void resize(size_type newsize, NodeTy val) {
+ iterator i = this->begin();
+ size_type len = 0;
+ for ( ; i != this->end() && len < newsize; ++i, ++len) /* empty*/ ;
+
+ if (len == newsize)
+ erase(i, this->end());
+ else // i == end()
+ insert(this->end(), newsize - len, val);
+ }
+ void resize(size_type newsize) { resize(newsize, NodeTy()); }
+};
+
+} // End llvm namespace
+
+namespace std {
+ // Ensure that swap uses the fast list swap...
+ template<class Ty>
+ void swap(llvm::iplist<Ty> &Left, llvm::iplist<Ty> &Right) {
+ Left.swap(Right);
+ }
+} // End 'std' extensions...
+
+#endif // LLVM_ADT_ILIST_H
diff --git a/include/llvm/ADT/ilist_node.h b/include/llvm/ADT/ilist_node.h
new file mode 100644
index 00000000000..f0080035cb8
--- /dev/null
+++ b/include/llvm/ADT/ilist_node.h
@@ -0,0 +1,106 @@
+//==-- llvm/ADT/ilist_node.h - Intrusive Linked List Helper ------*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the ilist_node class template, which is a convenient
+// base class for creating classes that can be used with ilists.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ADT_ILIST_NODE_H
+#define LLVM_ADT_ILIST_NODE_H
+
+namespace llvm {
+
+template<typename NodeTy>
+struct ilist_traits;
+
+/// ilist_half_node - Base class that provides prev services for sentinels.
+///
+template<typename NodeTy>
+class ilist_half_node {
+ friend struct ilist_traits<NodeTy>;
+ NodeTy *Prev;
+protected:
+ NodeTy *getPrev() { return Prev; }
+ const NodeTy *getPrev() const { return Prev; }
+ void setPrev(NodeTy *P) { Prev = P; }
+ ilist_half_node() : Prev(0) {}
+};
+
+template<typename NodeTy>
+struct ilist_nextprev_traits;
+
+/// ilist_node - Base class that provides next/prev services for nodes
+/// that use ilist_nextprev_traits or ilist_default_traits.
+///
+template<typename NodeTy>
+class ilist_node : private ilist_half_node<NodeTy> {
+ friend struct ilist_nextprev_traits<NodeTy>;
+ friend struct ilist_traits<NodeTy>;
+ NodeTy *Next;
+ NodeTy *getNext() { return Next; }
+ const NodeTy *getNext() const { return Next; }
+ void setNext(NodeTy *N) { Next = N; }
+protected:
+ ilist_node() : Next(0) {}
+
+public:
+ /// @name Adjacent Node Accessors
+ /// @{
+
+ /// \brief Get the previous node, or 0 for the list head.
+ NodeTy *getPrevNode() {
+ NodeTy *Prev = this->getPrev();
+
+ // Check for sentinel.
+ if (!Prev->getNext())
+ return 0;
+
+ return Prev;
+ }
+
+ /// \brief Get the previous node, or 0 for the list head.
+ const NodeTy *getPrevNode() const {
+ const NodeTy *Prev = this->getPrev();
+
+ // Check for sentinel.
+ if (!Prev->getNext())
+ return 0;
+
+ return Prev;
+ }
+
+ /// \brief Get the next node, or 0 for the list tail.
+ NodeTy *getNextNode() {
+ NodeTy *Next = getNext();
+
+ // Check for sentinel.
+ if (!Next->getNext())
+ return 0;
+
+ return Next;
+ }
+
+ /// \brief Get the next node, or 0 for the list tail.
+ const NodeTy *getNextNode() const {
+ const NodeTy *Next = getNext();
+
+ // Check for sentinel.
+ if (!Next->getNext())
+ return 0;
+
+ return Next;
+ }
+
+ /// @}
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/AliasAnalysis.h b/include/llvm/Analysis/AliasAnalysis.h
new file mode 100644
index 00000000000..f5872201ad2
--- /dev/null
+++ b/include/llvm/Analysis/AliasAnalysis.h
@@ -0,0 +1,603 @@
+//===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the generic AliasAnalysis interface, which is used as the
+// common interface used by all clients of alias analysis information, and
+// implemented by all alias analysis implementations. Mod/Ref information is
+// also captured by this interface.
+//
+// Implementations of this interface must implement the various virtual methods,
+// which automatically provides functionality for the entire suite of client
+// APIs.
+//
+// This API identifies memory regions with the Location class. The pointer
+// component specifies the base memory address of the region. The Size specifies
+// the maximum size (in address units) of the memory region, or UnknownSize if
+// the size is not known. The TBAA tag identifies the "type" of the memory
+// reference; see the TypeBasedAliasAnalysis class for details.
+//
+// Some non-obvious details include:
+// - Pointers that point to two completely different objects in memory never
+// alias, regardless of the value of the Size component.
+// - NoAlias doesn't imply inequal pointers. The most obvious example of this
+// is two pointers to constant memory. Even if they are equal, constant
+// memory is never stored to, so there will never be any dependencies.
+// In this and other situations, the pointers may be both NoAlias and
+// MustAlias at the same time. The current API can only return one result,
+// though this is rarely a problem in practice.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_ALIAS_ANALYSIS_H
+#define LLVM_ANALYSIS_ALIAS_ANALYSIS_H
+
+#include "llvm/Support/CallSite.h"
+#include "llvm/ADT/DenseMap.h"
+
+namespace llvm {
+
+class LoadInst;
+class StoreInst;
+class VAArgInst;
+class TargetData;
+class TargetLibraryInfo;
+class Pass;
+class AnalysisUsage;
+class MemTransferInst;
+class MemIntrinsic;
+class DominatorTree;
+
+class AliasAnalysis {
+protected:
+ const TargetData *TD;
+ const TargetLibraryInfo *TLI;
+
+private:
+ AliasAnalysis *AA; // Previous Alias Analysis to chain to.
+
+protected:
+ /// InitializeAliasAnalysis - Subclasses must call this method to initialize
+ /// the AliasAnalysis interface before any other methods are called. This is
+ /// typically called by the run* methods of these subclasses. This may be
+ /// called multiple times.
+ ///
+ void InitializeAliasAnalysis(Pass *P);
+
+ /// getAnalysisUsage - All alias analysis implementations should invoke this
+ /// directly (using AliasAnalysis::getAnalysisUsage(AU)).
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+public:
+ static char ID; // Class identification, replacement for typeinfo
+ AliasAnalysis() : TD(0), TLI(0), AA(0) {}
+ virtual ~AliasAnalysis(); // We want to be subclassed
+
+ /// UnknownSize - This is a special value which can be used with the
+ /// size arguments in alias queries to indicate that the caller does not
+ /// know the sizes of the potential memory references.
+ static uint64_t const UnknownSize = ~UINT64_C(0);
+
+ /// getTargetData - Return a pointer to the current TargetData object, or
+ /// null if no TargetData object is available.
+ ///
+ const TargetData *getTargetData() const { return TD; }
+
+ /// getTargetLibraryInfo - Return a pointer to the current TargetLibraryInfo
+ /// object, or null if no TargetLibraryInfo object is available.
+ ///
+ const TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
+
+ /// getTypeStoreSize - Return the TargetData store size for the given type,
+ /// if known, or a conservative value otherwise.
+ ///
+ uint64_t getTypeStoreSize(Type *Ty);
+
+ //===--------------------------------------------------------------------===//
+ /// Alias Queries...
+ ///
+
+ /// Location - A description of a memory location.
+ struct Location {
+ /// Ptr - The address of the start of the location.
+ const Value *Ptr;
+ /// Size - The maximum size of the location, in address-units, or
+ /// UnknownSize if the size is not known. Note that an unknown size does
+ /// not mean the pointer aliases the entire virtual address space, because
+ /// there are restrictions on stepping out of one object and into another.
+ /// See http://llvm.org/docs/LangRef.html#pointeraliasing
+ uint64_t Size;
+ /// TBAATag - The metadata node which describes the TBAA type of
+ /// the location, or null if there is no known unique tag.
+ const MDNode *TBAATag;
+
+ explicit Location(const Value *P = 0, uint64_t S = UnknownSize,
+ const MDNode *N = 0)
+ : Ptr(P), Size(S), TBAATag(N) {}
+
+ Location getWithNewPtr(const Value *NewPtr) const {
+ Location Copy(*this);
+ Copy.Ptr = NewPtr;
+ return Copy;
+ }
+
+ Location getWithNewSize(uint64_t NewSize) const {
+ Location Copy(*this);
+ Copy.Size = NewSize;
+ return Copy;
+ }
+
+ Location getWithoutTBAATag() const {
+ Location Copy(*this);
+ Copy.TBAATag = 0;
+ return Copy;
+ }
+ };
+
+ /// getLocation - Fill in Loc with information about the memory reference by
+ /// the given instruction.
+ Location getLocation(const LoadInst *LI);
+ Location getLocation(const StoreInst *SI);
+ Location getLocation(const VAArgInst *VI);
+ Location getLocation(const AtomicCmpXchgInst *CXI);
+ Location getLocation(const AtomicRMWInst *RMWI);
+ static Location getLocationForSource(const MemTransferInst *MTI);
+ static Location getLocationForDest(const MemIntrinsic *MI);
+
+ /// Alias analysis result - Either we know for sure that it does not alias, we
+ /// know for sure it must alias, or we don't know anything: The two pointers
+ /// _might_ alias. This enum is designed so you can do things like:
+ /// if (AA.alias(P1, P2)) { ... }
+ /// to check to see if two pointers might alias.
+ ///
+ /// See docs/AliasAnalysis.html for more information on the specific meanings
+ /// of these values.
+ ///
+ enum AliasResult {
+ NoAlias = 0, ///< No dependencies.
+ MayAlias, ///< Anything goes.
+ PartialAlias, ///< Pointers differ, but pointees overlap.
+ MustAlias ///< Pointers are equal.
+ };
+
+ /// alias - The main low level interface to the alias analysis implementation.
+ /// Returns an AliasResult indicating whether the two pointers are aliased to
+ /// each other. This is the interface that must be implemented by specific
+ /// alias analysis implementations.
+ virtual AliasResult alias(const Location &LocA, const Location &LocB);
+
+ /// alias - A convenience wrapper.
+ AliasResult alias(const Value *V1, uint64_t V1Size,
+ const Value *V2, uint64_t V2Size) {
+ return alias(Location(V1, V1Size), Location(V2, V2Size));
+ }
+
+ /// alias - A convenience wrapper.
+ AliasResult alias(const Value *V1, const Value *V2) {
+ return alias(V1, UnknownSize, V2, UnknownSize);
+ }
+
+ /// isNoAlias - A trivial helper function to check to see if the specified
+ /// pointers are no-alias.
+ bool isNoAlias(const Location &LocA, const Location &LocB) {
+ return alias(LocA, LocB) == NoAlias;
+ }
+
+ /// isNoAlias - A convenience wrapper.
+ bool isNoAlias(const Value *V1, uint64_t V1Size,
+ const Value *V2, uint64_t V2Size) {
+ return isNoAlias(Location(V1, V1Size), Location(V2, V2Size));
+ }
+
+ /// isNoAlias - A convenience wrapper.
+ bool isNoAlias(const Value *V1, const Value *V2) {
+ return isNoAlias(Location(V1), Location(V2));
+ }
+
+ /// isMustAlias - A convenience wrapper.
+ bool isMustAlias(const Location &LocA, const Location &LocB) {
+ return alias(LocA, LocB) == MustAlias;
+ }
+
+ /// isMustAlias - A convenience wrapper.
+ bool isMustAlias(const Value *V1, const Value *V2) {
+ return alias(V1, 1, V2, 1) == MustAlias;
+ }
+
+ /// pointsToConstantMemory - If the specified memory location is
+ /// known to be constant, return true. If OrLocal is true and the
+ /// specified memory location is known to be "local" (derived from
+ /// an alloca), return true. Otherwise return false.
+ virtual bool pointsToConstantMemory(const Location &Loc,
+ bool OrLocal = false);
+
+ /// pointsToConstantMemory - A convenient wrapper.
+ bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
+ return pointsToConstantMemory(Location(P), OrLocal);
+ }
+
+ //===--------------------------------------------------------------------===//
+ /// Simple mod/ref information...
+ ///
+
+ /// ModRefResult - Represent the result of a mod/ref query. Mod and Ref are
+ /// bits which may be or'd together.
+ ///
+ enum ModRefResult { NoModRef = 0, Ref = 1, Mod = 2, ModRef = 3 };
+
+ /// These values define additional bits used to define the
+ /// ModRefBehavior values.
+ enum { Nowhere = 0, ArgumentPointees = 4, Anywhere = 8 | ArgumentPointees };
+
+ /// ModRefBehavior - Summary of how a function affects memory in the program.
+ /// Loads from constant globals are not considered memory accesses for this
+ /// interface. Also, functions may freely modify stack space local to their
+ /// invocation without having to report it through these interfaces.
+ enum ModRefBehavior {
+ /// DoesNotAccessMemory - This function does not perform any non-local loads
+ /// or stores to memory.
+ ///
+ /// This property corresponds to the GCC 'const' attribute.
+ /// This property corresponds to the LLVM IR 'readnone' attribute.
+ /// This property corresponds to the IntrNoMem LLVM intrinsic flag.
+ DoesNotAccessMemory = Nowhere | NoModRef,
+
+ /// OnlyReadsArgumentPointees - The only memory references in this function
+ /// (if it has any) are non-volatile loads from objects pointed to by its
+ /// pointer-typed arguments, with arbitrary offsets.
+ ///
+ /// This property corresponds to the IntrReadArgMem LLVM intrinsic flag.
+ OnlyReadsArgumentPointees = ArgumentPointees | Ref,
+
+ /// OnlyAccessesArgumentPointees - The only memory references in this
+ /// function (if it has any) are non-volatile loads and stores from objects
+ /// pointed to by its pointer-typed arguments, with arbitrary offsets.
+ ///
+ /// This property corresponds to the IntrReadWriteArgMem LLVM intrinsic flag.
+ OnlyAccessesArgumentPointees = ArgumentPointees | ModRef,
+
+ /// OnlyReadsMemory - This function does not perform any non-local stores or
+ /// volatile loads, but may read from any memory location.
+ ///
+ /// This property corresponds to the GCC 'pure' attribute.
+ /// This property corresponds to the LLVM IR 'readonly' attribute.
+ /// This property corresponds to the IntrReadMem LLVM intrinsic flag.
+ OnlyReadsMemory = Anywhere | Ref,
+
+ /// UnknownModRefBehavior - This indicates that the function could not be
+ /// classified into one of the behaviors above.
+ UnknownModRefBehavior = Anywhere | ModRef
+ };
+
+ /// getModRefBehavior - Return the behavior when calling the given call site.
+ virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
+
+ /// getModRefBehavior - Return the behavior when calling the given function.
+ /// For use when the call site is not known.
+ virtual ModRefBehavior getModRefBehavior(const Function *F);
+
+ /// doesNotAccessMemory - If the specified call is known to never read or
+ /// write memory, return true. If the call only reads from known-constant
+ /// memory, it is also legal to return true. Calls that unwind the stack
+ /// are legal for this predicate.
+ ///
+ /// Many optimizations (such as CSE and LICM) can be performed on such calls
+ /// without worrying about aliasing properties, and many calls have this
+ /// property (e.g. calls to 'sin' and 'cos').
+ ///
+ /// This property corresponds to the GCC 'const' attribute.
+ ///
+ bool doesNotAccessMemory(ImmutableCallSite CS) {
+ return getModRefBehavior(CS) == DoesNotAccessMemory;
+ }
+
+ /// doesNotAccessMemory - If the specified function is known to never read or
+ /// write memory, return true. For use when the call site is not known.
+ ///
+ bool doesNotAccessMemory(const Function *F) {
+ return getModRefBehavior(F) == DoesNotAccessMemory;
+ }
+
+ /// onlyReadsMemory - If the specified call is known to only read from
+ /// non-volatile memory (or not access memory at all), return true. Calls
+ /// that unwind the stack are legal for this predicate.
+ ///
+ /// This property allows many common optimizations to be performed in the
+ /// absence of interfering store instructions, such as CSE of strlen calls.
+ ///
+ /// This property corresponds to the GCC 'pure' attribute.
+ ///
+ bool onlyReadsMemory(ImmutableCallSite CS) {
+ return onlyReadsMemory(getModRefBehavior(CS));
+ }
+
+ /// onlyReadsMemory - If the specified function is known to only read from
+ /// non-volatile memory (or not access memory at all), return true. For use
+ /// when the call site is not known.
+ ///
+ bool onlyReadsMemory(const Function *F) {
+ return onlyReadsMemory(getModRefBehavior(F));
+ }
+
+ /// onlyReadsMemory - Return true if functions with the specified behavior are
+ /// known to only read from non-volatile memory (or not access memory at all).
+ ///
+ static bool onlyReadsMemory(ModRefBehavior MRB) {
+ return !(MRB & Mod);
+ }
+
+ /// onlyAccessesArgPointees - Return true if functions with the specified
+ /// behavior are known to read and write at most from objects pointed to by
+ /// their pointer-typed arguments (with arbitrary offsets).
+ ///
+ static bool onlyAccessesArgPointees(ModRefBehavior MRB) {
+ return !(MRB & Anywhere & ~ArgumentPointees);
+ }
+
+ /// doesAccessArgPointees - Return true if functions with the specified
+ /// behavior are known to potentially read or write from objects pointed
+ /// to be their pointer-typed arguments (with arbitrary offsets).
+ ///
+ static bool doesAccessArgPointees(ModRefBehavior MRB) {
+ return (MRB & ModRef) && (MRB & ArgumentPointees);
+ }
+
+ /// getModRefInfo - Return information about whether or not an instruction may
+ /// read or write the specified memory location. An instruction
+ /// that doesn't read or write memory may be trivially LICM'd for example.
+ ModRefResult getModRefInfo(const Instruction *I,
+ const Location &Loc) {
+ switch (I->getOpcode()) {
+ case Instruction::VAArg: return getModRefInfo((const VAArgInst*)I, Loc);
+ case Instruction::Load: return getModRefInfo((const LoadInst*)I, Loc);
+ case Instruction::Store: return getModRefInfo((const StoreInst*)I, Loc);
+ case Instruction::Fence: return getModRefInfo((const FenceInst*)I, Loc);
+ case Instruction::AtomicCmpXchg:
+ return getModRefInfo((const AtomicCmpXchgInst*)I, Loc);
+ case Instruction::AtomicRMW:
+ return getModRefInfo((const AtomicRMWInst*)I, Loc);
+ case Instruction::Call: return getModRefInfo((const CallInst*)I, Loc);
+ case Instruction::Invoke: return getModRefInfo((const InvokeInst*)I,Loc);
+ default: return NoModRef;
+ }
+ }
+
+ /// getModRefInfo - A convenience wrapper.
+ ModRefResult getModRefInfo(const Instruction *I,
+ const Value *P, uint64_t Size) {
+ return getModRefInfo(I, Location(P, Size));
+ }
+
+ /// getModRefInfo (for call sites) - Return whether information about whether
+ /// a particular call site modifies or reads the specified memory location.
+ virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
+ const Location &Loc);
+
+ /// getModRefInfo (for call sites) - A convenience wrapper.
+ ModRefResult getModRefInfo(ImmutableCallSite CS,
+ const Value *P, uint64_t Size) {
+ return getModRefInfo(CS, Location(P, Size));
+ }
+
+ /// getModRefInfo (for calls) - Return whether information about whether
+ /// a particular call modifies or reads the specified memory location.
+ ModRefResult getModRefInfo(const CallInst *C, const Location &Loc) {
+ return getModRefInfo(ImmutableCallSite(C), Loc);
+ }
+
+ /// getModRefInfo (for calls) - A convenience wrapper.
+ ModRefResult getModRefInfo(const CallInst *C, const Value *P, uint64_t Size) {
+ return getModRefInfo(C, Location(P, Size));
+ }
+
+ /// getModRefInfo (for invokes) - Return whether information about whether
+ /// a particular invoke modifies or reads the specified memory location.
+ ModRefResult getModRefInfo(const InvokeInst *I,
+ const Location &Loc) {
+ return getModRefInfo(ImmutableCallSite(I), Loc);
+ }
+
+ /// getModRefInfo (for invokes) - A convenience wrapper.
+ ModRefResult getModRefInfo(const InvokeInst *I,
+ const Value *P, uint64_t Size) {
+ return getModRefInfo(I, Location(P, Size));
+ }
+
+ /// getModRefInfo (for loads) - Return whether information about whether
+ /// a particular load modifies or reads the specified memory location.
+ ModRefResult getModRefInfo(const LoadInst *L, const Location &Loc);
+
+ /// getModRefInfo (for loads) - A convenience wrapper.
+ ModRefResult getModRefInfo(const LoadInst *L, const Value *P, uint64_t Size) {
+ return getModRefInfo(L, Location(P, Size));
+ }
+
+ /// getModRefInfo (for stores) - Return whether information about whether
+ /// a particular store modifies or reads the specified memory location.
+ ModRefResult getModRefInfo(const StoreInst *S, const Location &Loc);
+
+ /// getModRefInfo (for stores) - A convenience wrapper.
+ ModRefResult getModRefInfo(const StoreInst *S, const Value *P, uint64_t Size){
+ return getModRefInfo(S, Location(P, Size));
+ }
+
+ /// getModRefInfo (for fences) - Return whether information about whether
+ /// a particular store modifies or reads the specified memory location.
+ ModRefResult getModRefInfo(const FenceInst *S, const Location &Loc) {
+ // Conservatively correct. (We could possibly be a bit smarter if
+ // Loc is a alloca that doesn't escape.)
+ return ModRef;
+ }
+
+ /// getModRefInfo (for fences) - A convenience wrapper.
+ ModRefResult getModRefInfo(const FenceInst *S, const Value *P, uint64_t Size){
+ return getModRefInfo(S, Location(P, Size));
+ }
+
+ /// getModRefInfo (for cmpxchges) - Return whether information about whether
+ /// a particular cmpxchg modifies or reads the specified memory location.
+ ModRefResult getModRefInfo(const AtomicCmpXchgInst *CX, const Location &Loc);
+
+ /// getModRefInfo (for cmpxchges) - A convenience wrapper.
+ ModRefResult getModRefInfo(const AtomicCmpXchgInst *CX,
+ const Value *P, unsigned Size) {
+ return getModRefInfo(CX, Location(P, Size));
+ }
+
+ /// getModRefInfo (for atomicrmws) - Return whether information about whether
+ /// a particular atomicrmw modifies or reads the specified memory location.
+ ModRefResult getModRefInfo(const AtomicRMWInst *RMW, const Location &Loc);
+
+ /// getModRefInfo (for atomicrmws) - A convenience wrapper.
+ ModRefResult getModRefInfo(const AtomicRMWInst *RMW,
+ const Value *P, unsigned Size) {
+ return getModRefInfo(RMW, Location(P, Size));
+ }
+
+ /// getModRefInfo (for va_args) - Return whether information about whether
+ /// a particular va_arg modifies or reads the specified memory location.
+ ModRefResult getModRefInfo(const VAArgInst* I, const Location &Loc);
+
+ /// getModRefInfo (for va_args) - A convenience wrapper.
+ ModRefResult getModRefInfo(const VAArgInst* I, const Value* P, uint64_t Size){
+ return getModRefInfo(I, Location(P, Size));
+ }
+
+ /// getModRefInfo - Return information about whether two call sites may refer
+ /// to the same set of memory locations. See
+ /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
+ /// for details.
+ virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
+ ImmutableCallSite CS2);
+
+ /// callCapturesBefore - Return information about whether a particular call
+ /// site modifies or reads the specified memory location.
+ ModRefResult callCapturesBefore(const Instruction *I,
+ const AliasAnalysis::Location &MemLoc,
+ DominatorTree *DT);
+
+ /// callCapturesBefore - A convenience wrapper.
+ ModRefResult callCapturesBefore(const Instruction *I, const Value *P,
+ uint64_t Size, DominatorTree *DT) {
+ return callCapturesBefore(I, Location(P, Size), DT);
+ }
+
+ //===--------------------------------------------------------------------===//
+ /// Higher level methods for querying mod/ref information.
+ ///
+
+ /// canBasicBlockModify - Return true if it is possible for execution of the
+ /// specified basic block to modify the value pointed to by Ptr.
+ bool canBasicBlockModify(const BasicBlock &BB, const Location &Loc);
+
+ /// canBasicBlockModify - A convenience wrapper.
+ bool canBasicBlockModify(const BasicBlock &BB, const Value *P, uint64_t Size){
+ return canBasicBlockModify(BB, Location(P, Size));
+ }
+
+ /// canInstructionRangeModify - Return true if it is possible for the
+ /// execution of the specified instructions to modify the value pointed to by
+ /// Ptr. The instructions to consider are all of the instructions in the
+ /// range of [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
+ bool canInstructionRangeModify(const Instruction &I1, const Instruction &I2,
+ const Location &Loc);
+
+ /// canInstructionRangeModify - A convenience wrapper.
+ bool canInstructionRangeModify(const Instruction &I1, const Instruction &I2,
+ const Value *Ptr, uint64_t Size) {
+ return canInstructionRangeModify(I1, I2, Location(Ptr, Size));
+ }
+
+ //===--------------------------------------------------------------------===//
+ /// Methods that clients should call when they transform the program to allow
+ /// alias analyses to update their internal data structures. Note that these
+ /// methods may be called on any instruction, regardless of whether or not
+ /// they have pointer-analysis implications.
+ ///
+
+ /// deleteValue - This method should be called whenever an LLVM Value is
+ /// deleted from the program, for example when an instruction is found to be
+ /// redundant and is eliminated.
+ ///
+ virtual void deleteValue(Value *V);
+
+ /// copyValue - This method should be used whenever a preexisting value in the
+ /// program is copied or cloned, introducing a new value. Note that analysis
+ /// implementations should tolerate clients that use this method to introduce
+ /// the same value multiple times: if the analysis already knows about a
+ /// value, it should ignore the request.
+ ///
+ virtual void copyValue(Value *From, Value *To);
+
+ /// addEscapingUse - This method should be used whenever an escaping use is
+ /// added to a pointer value. Analysis implementations may either return
+ /// conservative responses for that value in the future, or may recompute
+ /// some or all internal state to continue providing precise responses.
+ ///
+ /// Escaping uses are considered by anything _except_ the following:
+ /// - GEPs or bitcasts of the pointer
+ /// - Loads through the pointer
+ /// - Stores through (but not of) the pointer
+ virtual void addEscapingUse(Use &U);
+
+ /// replaceWithNewValue - This method is the obvious combination of the two
+ /// above, and it provided as a helper to simplify client code.
+ ///
+ void replaceWithNewValue(Value *Old, Value *New) {
+ copyValue(Old, New);
+ deleteValue(Old);
+ }
+};
+
+// Specialize DenseMapInfo for Location.
+template<>
+struct DenseMapInfo<AliasAnalysis::Location> {
+ static inline AliasAnalysis::Location getEmptyKey() {
+ return
+ AliasAnalysis::Location(DenseMapInfo<const Value *>::getEmptyKey(),
+ 0, 0);
+ }
+ static inline AliasAnalysis::Location getTombstoneKey() {
+ return
+ AliasAnalysis::Location(DenseMapInfo<const Value *>::getTombstoneKey(),
+ 0, 0);
+ }
+ static unsigned getHashValue(const AliasAnalysis::Location &Val) {
+ return DenseMapInfo<const Value *>::getHashValue(Val.Ptr) ^
+ DenseMapInfo<uint64_t>::getHashValue(Val.Size) ^
+ DenseMapInfo<const MDNode *>::getHashValue(Val.TBAATag);
+ }
+ static bool isEqual(const AliasAnalysis::Location &LHS,
+ const AliasAnalysis::Location &RHS) {
+ return LHS.Ptr == RHS.Ptr &&
+ LHS.Size == RHS.Size &&
+ LHS.TBAATag == RHS.TBAATag;
+ }
+};
+
+/// isNoAliasCall - Return true if this pointer is returned by a noalias
+/// function.
+bool isNoAliasCall(const Value *V);
+
+/// isIdentifiedObject - Return true if this pointer refers to a distinct and
+/// identifiable object. This returns true for:
+/// Global Variables and Functions (but not Global Aliases)
+/// Allocas and Mallocs
+/// ByVal and NoAlias Arguments
+/// NoAlias returns
+///
+bool isIdentifiedObject(const Value *V);
+
+/// isKnownNonNull - Return true if this pointer couldn't possibly be null by
+/// its definition. This returns true for allocas, non-extern-weak globals and
+/// byval arguments.
+bool isKnownNonNull(const Value *V);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/AliasSetTracker.h b/include/llvm/Analysis/AliasSetTracker.h
new file mode 100644
index 00000000000..1e606c81d9c
--- /dev/null
+++ b/include/llvm/Analysis/AliasSetTracker.h
@@ -0,0 +1,438 @@
+//===- llvm/Analysis/AliasSetTracker.h - Build Alias Sets -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines two classes: AliasSetTracker and AliasSet. These interface
+// are used to classify a collection of pointer references into a maximal number
+// of disjoint sets. Each AliasSet object constructed by the AliasSetTracker
+// object refers to memory disjoint from the other sets.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_ALIASSETTRACKER_H
+#define LLVM_ANALYSIS_ALIASSETTRACKER_H
+
+#include "llvm/Support/CallSite.h"
+#include "llvm/Support/ValueHandle.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/ilist_node.h"
+#include <vector>
+
+namespace llvm {
+
+class AliasAnalysis;
+class LoadInst;
+class StoreInst;
+class VAArgInst;
+class AliasSetTracker;
+class AliasSet;
+
+class AliasSet : public ilist_node<AliasSet> {
+ friend class AliasSetTracker;
+
+ class PointerRec {
+ Value *Val; // The pointer this record corresponds to.
+ PointerRec **PrevInList, *NextInList;
+ AliasSet *AS;
+ uint64_t Size;
+ const MDNode *TBAAInfo;
+ public:
+ PointerRec(Value *V)
+ : Val(V), PrevInList(0), NextInList(0), AS(0), Size(0),
+ TBAAInfo(DenseMapInfo<const MDNode *>::getEmptyKey()) {}
+
+ Value *getValue() const { return Val; }
+
+ PointerRec *getNext() const { return NextInList; }
+ bool hasAliasSet() const { return AS != 0; }
+
+ PointerRec** setPrevInList(PointerRec **PIL) {
+ PrevInList = PIL;
+ return &NextInList;
+ }
+
+ void updateSizeAndTBAAInfo(uint64_t NewSize, const MDNode *NewTBAAInfo) {
+ if (NewSize > Size) Size = NewSize;
+
+ if (TBAAInfo == DenseMapInfo<const MDNode *>::getEmptyKey())
+ // We don't have a TBAAInfo yet. Set it to NewTBAAInfo.
+ TBAAInfo = NewTBAAInfo;
+ else if (TBAAInfo != NewTBAAInfo)
+ // NewTBAAInfo conflicts with TBAAInfo.
+ TBAAInfo = DenseMapInfo<const MDNode *>::getTombstoneKey();
+ }
+
+ uint64_t getSize() const { return Size; }
+
+ /// getTBAAInfo - Return the TBAAInfo, or null if there is no
+ /// information or conflicting information.
+ const MDNode *getTBAAInfo() const {
+ // If we have missing or conflicting TBAAInfo, return null.
+ if (TBAAInfo == DenseMapInfo<const MDNode *>::getEmptyKey() ||
+ TBAAInfo == DenseMapInfo<const MDNode *>::getTombstoneKey())
+ return 0;
+ return TBAAInfo;
+ }
+
+ AliasSet *getAliasSet(AliasSetTracker &AST) {
+ assert(AS && "No AliasSet yet!");
+ if (AS->Forward) {
+ AliasSet *OldAS = AS;
+ AS = OldAS->getForwardedTarget(AST);
+ AS->addRef();
+ OldAS->dropRef(AST);
+ }
+ return AS;
+ }
+
+ void setAliasSet(AliasSet *as) {
+ assert(AS == 0 && "Already have an alias set!");
+ AS = as;
+ }
+
+ void eraseFromList() {
+ if (NextInList) NextInList->PrevInList = PrevInList;
+ *PrevInList = NextInList;
+ if (AS->PtrListEnd == &NextInList) {
+ AS->PtrListEnd = PrevInList;
+ assert(*AS->PtrListEnd == 0 && "List not terminated right!");
+ }
+ delete this;
+ }
+ };
+
+ PointerRec *PtrList, **PtrListEnd; // Doubly linked list of nodes.
+ AliasSet *Forward; // Forwarding pointer.
+
+ // All instructions without a specific address in this alias set.
+ std::vector<AssertingVH<Instruction> > UnknownInsts;
+
+ // RefCount - Number of nodes pointing to this AliasSet plus the number of
+ // AliasSets forwarding to it.
+ unsigned RefCount : 28;
+
+ /// AccessType - Keep track of whether this alias set merely refers to the
+ /// locations of memory, whether it modifies the memory, or whether it does
+ /// both. The lattice goes from "NoModRef" to either Refs or Mods, then to
+ /// ModRef as necessary.
+ ///
+ enum AccessType {
+ NoModRef = 0, Refs = 1, // Ref = bit 1
+ Mods = 2, ModRef = 3 // Mod = bit 2
+ };
+ unsigned AccessTy : 2;
+
+ /// AliasType - Keep track the relationships between the pointers in the set.
+ /// Lattice goes from MustAlias to MayAlias.
+ ///
+ enum AliasType {
+ MustAlias = 0, MayAlias = 1
+ };
+ unsigned AliasTy : 1;
+
+ // Volatile - True if this alias set contains volatile loads or stores.
+ bool Volatile : 1;
+
+ void addRef() { ++RefCount; }
+ void dropRef(AliasSetTracker &AST) {
+ assert(RefCount >= 1 && "Invalid reference count detected!");
+ if (--RefCount == 0)
+ removeFromTracker(AST);
+ }
+
+ Instruction *getUnknownInst(unsigned i) const {
+ assert(i < UnknownInsts.size());
+ return UnknownInsts[i];
+ }
+
+public:
+ /// Accessors...
+ bool isRef() const { return AccessTy & Refs; }
+ bool isMod() const { return AccessTy & Mods; }
+ bool isMustAlias() const { return AliasTy == MustAlias; }
+ bool isMayAlias() const { return AliasTy == MayAlias; }
+
+ // isVolatile - Return true if this alias set contains volatile loads or
+ // stores.
+ bool isVolatile() const { return Volatile; }
+
+ /// isForwardingAliasSet - Return true if this alias set should be ignored as
+ /// part of the AliasSetTracker object.
+ bool isForwardingAliasSet() const { return Forward; }
+
+ /// mergeSetIn - Merge the specified alias set into this alias set...
+ ///
+ void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
+
+ // Alias Set iteration - Allow access to all of the pointer which are part of
+ // this alias set...
+ class iterator;
+ iterator begin() const { return iterator(PtrList); }
+ iterator end() const { return iterator(); }
+ bool empty() const { return PtrList == 0; }
+
+ void print(raw_ostream &OS) const;
+ void dump() const;
+
+ /// Define an iterator for alias sets... this is just a forward iterator.
+ class iterator : public std::iterator<std::forward_iterator_tag,
+ PointerRec, ptrdiff_t> {
+ PointerRec *CurNode;
+ public:
+ explicit iterator(PointerRec *CN = 0) : CurNode(CN) {}
+
+ bool operator==(const iterator& x) const {
+ return CurNode == x.CurNode;
+ }
+ bool operator!=(const iterator& x) const { return !operator==(x); }
+
+ const iterator &operator=(const iterator &I) {
+ CurNode = I.CurNode;
+ return *this;
+ }
+
+ value_type &operator*() const {
+ assert(CurNode && "Dereferencing AliasSet.end()!");
+ return *CurNode;
+ }
+ value_type *operator->() const { return &operator*(); }
+
+ Value *getPointer() const { return CurNode->getValue(); }
+ uint64_t getSize() const { return CurNode->getSize(); }
+ const MDNode *getTBAAInfo() const { return CurNode->getTBAAInfo(); }
+
+ iterator& operator++() { // Preincrement
+ assert(CurNode && "Advancing past AliasSet.end()!");
+ CurNode = CurNode->getNext();
+ return *this;
+ }
+ iterator operator++(int) { // Postincrement
+ iterator tmp = *this; ++*this; return tmp;
+ }
+ };
+
+private:
+ // Can only be created by AliasSetTracker. Also, ilist creates one
+ // to serve as a sentinel.
+ friend struct ilist_sentinel_traits<AliasSet>;
+ AliasSet() : PtrList(0), PtrListEnd(&PtrList), Forward(0), RefCount(0),
+ AccessTy(NoModRef), AliasTy(MustAlias), Volatile(false) {
+ }
+
+ AliasSet(const AliasSet &AS) LLVM_DELETED_FUNCTION;
+ void operator=(const AliasSet &AS) LLVM_DELETED_FUNCTION;
+
+ PointerRec *getSomePointer() const {
+ return PtrList;
+ }
+
+ /// getForwardedTarget - Return the real alias set this represents. If this
+ /// has been merged with another set and is forwarding, return the ultimate
+ /// destination set. This also implements the union-find collapsing as well.
+ AliasSet *getForwardedTarget(AliasSetTracker &AST) {
+ if (!Forward) return this;
+
+ AliasSet *Dest = Forward->getForwardedTarget(AST);
+ if (Dest != Forward) {
+ Dest->addRef();
+ Forward->dropRef(AST);
+ Forward = Dest;
+ }
+ return Dest;
+ }
+
+ void removeFromTracker(AliasSetTracker &AST);
+
+ void addPointer(AliasSetTracker &AST, PointerRec &Entry, uint64_t Size,
+ const MDNode *TBAAInfo,
+ bool KnownMustAlias = false);
+ void addUnknownInst(Instruction *I, AliasAnalysis &AA);
+ void removeUnknownInst(Instruction *I) {
+ for (size_t i = 0, e = UnknownInsts.size(); i != e; ++i)
+ if (UnknownInsts[i] == I) {
+ UnknownInsts[i] = UnknownInsts.back();
+ UnknownInsts.pop_back();
+ --i; --e; // Revisit the moved entry.
+ }
+ }
+ void setVolatile() { Volatile = true; }
+
+public:
+ /// aliasesPointer - Return true if the specified pointer "may" (or must)
+ /// alias one of the members in the set.
+ ///
+ bool aliasesPointer(const Value *Ptr, uint64_t Size, const MDNode *TBAAInfo,
+ AliasAnalysis &AA) const;
+ bool aliasesUnknownInst(Instruction *Inst, AliasAnalysis &AA) const;
+};
+
+inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
+ AS.print(OS);
+ return OS;
+}
+
+
+class AliasSetTracker {
+ /// CallbackVH - A CallbackVH to arrange for AliasSetTracker to be
+ /// notified whenever a Value is deleted.
+ class ASTCallbackVH : public CallbackVH {
+ AliasSetTracker *AST;
+ virtual void deleted();
+ virtual void allUsesReplacedWith(Value *);
+ public:
+ ASTCallbackVH(Value *V, AliasSetTracker *AST = 0);
+ ASTCallbackVH &operator=(Value *V);
+ };
+ /// ASTCallbackVHDenseMapInfo - Traits to tell DenseMap that tell us how to
+ /// compare and hash the value handle.
+ struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {};
+
+ AliasAnalysis &AA;
+ ilist<AliasSet> AliasSets;
+
+ typedef DenseMap<ASTCallbackVH, AliasSet::PointerRec*,
+ ASTCallbackVHDenseMapInfo>
+ PointerMapType;
+
+ // Map from pointers to their node
+ PointerMapType PointerMap;
+
+public:
+ /// AliasSetTracker ctor - Create an empty collection of AliasSets, and use
+ /// the specified alias analysis object to disambiguate load and store
+ /// addresses.
+ explicit AliasSetTracker(AliasAnalysis &aa) : AA(aa) {}
+ ~AliasSetTracker() { clear(); }
+
+ /// add methods - These methods are used to add different types of
+ /// instructions to the alias sets. Adding a new instruction can result in
+ /// one of three actions happening:
+ ///
+ /// 1. If the instruction doesn't alias any other sets, create a new set.
+ /// 2. If the instruction aliases exactly one set, add it to the set
+ /// 3. If the instruction aliases multiple sets, merge the sets, and add
+ /// the instruction to the result.
+ ///
+ /// These methods return true if inserting the instruction resulted in the
+ /// addition of a new alias set (i.e., the pointer did not alias anything).
+ ///
+ bool add(Value *Ptr, uint64_t Size, const MDNode *TBAAInfo); // Add a location
+ bool add(LoadInst *LI);
+ bool add(StoreInst *SI);
+ bool add(VAArgInst *VAAI);
+ bool add(Instruction *I); // Dispatch to one of the other add methods...
+ void add(BasicBlock &BB); // Add all instructions in basic block
+ void add(const AliasSetTracker &AST); // Add alias relations from another AST
+ bool addUnknown(Instruction *I);
+
+ /// remove methods - These methods are used to remove all entries that might
+ /// be aliased by the specified instruction. These methods return true if any
+ /// alias sets were eliminated.
+ // Remove a location
+ bool remove(Value *Ptr, uint64_t Size, const MDNode *TBAAInfo);
+ bool remove(LoadInst *LI);
+ bool remove(StoreInst *SI);
+ bool remove(VAArgInst *VAAI);
+ bool remove(Instruction *I);
+ void remove(AliasSet &AS);
+ bool removeUnknown(Instruction *I);
+
+ void clear();
+
+ /// getAliasSets - Return the alias sets that are active.
+ ///
+ const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
+
+ /// getAliasSetForPointer - Return the alias set that the specified pointer
+ /// lives in. If the New argument is non-null, this method sets the value to
+ /// true if a new alias set is created to contain the pointer (because the
+ /// pointer didn't alias anything).
+ AliasSet &getAliasSetForPointer(Value *P, uint64_t Size,
+ const MDNode *TBAAInfo,
+ bool *New = 0);
+
+ /// getAliasSetForPointerIfExists - Return the alias set containing the
+ /// location specified if one exists, otherwise return null.
+ AliasSet *getAliasSetForPointerIfExists(Value *P, uint64_t Size,
+ const MDNode *TBAAInfo) {
+ return findAliasSetForPointer(P, Size, TBAAInfo);
+ }
+
+ /// containsPointer - Return true if the specified location is represented by
+ /// this alias set, false otherwise. This does not modify the AST object or
+ /// alias sets.
+ bool containsPointer(Value *P, uint64_t Size, const MDNode *TBAAInfo) const;
+
+ /// getAliasAnalysis - Return the underlying alias analysis object used by
+ /// this tracker.
+ AliasAnalysis &getAliasAnalysis() const { return AA; }
+
+ /// deleteValue method - This method is used to remove a pointer value from
+ /// the AliasSetTracker entirely. It should be used when an instruction is
+ /// deleted from the program to update the AST. If you don't use this, you
+ /// would have dangling pointers to deleted instructions.
+ ///
+ void deleteValue(Value *PtrVal);
+
+ /// copyValue - This method should be used whenever a preexisting value in the
+ /// program is copied or cloned, introducing a new value. Note that it is ok
+ /// for clients that use this method to introduce the same value multiple
+ /// times: if the tracker already knows about a value, it will ignore the
+ /// request.
+ ///
+ void copyValue(Value *From, Value *To);
+
+
+ typedef ilist<AliasSet>::iterator iterator;
+ typedef ilist<AliasSet>::const_iterator const_iterator;
+
+ const_iterator begin() const { return AliasSets.begin(); }
+ const_iterator end() const { return AliasSets.end(); }
+
+ iterator begin() { return AliasSets.begin(); }
+ iterator end() { return AliasSets.end(); }
+
+ void print(raw_ostream &OS) const;
+ void dump() const;
+
+private:
+ friend class AliasSet;
+ void removeAliasSet(AliasSet *AS);
+
+ // getEntryFor - Just like operator[] on the map, except that it creates an
+ // entry for the pointer if it doesn't already exist.
+ AliasSet::PointerRec &getEntryFor(Value *V) {
+ AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
+ if (Entry == 0)
+ Entry = new AliasSet::PointerRec(V);
+ return *Entry;
+ }
+
+ AliasSet &addPointer(Value *P, uint64_t Size, const MDNode *TBAAInfo,
+ AliasSet::AccessType E,
+ bool &NewSet) {
+ NewSet = false;
+ AliasSet &AS = getAliasSetForPointer(P, Size, TBAAInfo, &NewSet);
+ AS.AccessTy |= E;
+ return AS;
+ }
+ AliasSet *findAliasSetForPointer(const Value *Ptr, uint64_t Size,
+ const MDNode *TBAAInfo);
+
+ AliasSet *findAliasSetForUnknownInst(Instruction *Inst);
+};
+
+inline raw_ostream& operator<<(raw_ostream &OS, const AliasSetTracker &AST) {
+ AST.print(OS);
+ return OS;
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/BlockFrequencyImpl.h b/include/llvm/Analysis/BlockFrequencyImpl.h
new file mode 100644
index 00000000000..5168ab78729
--- /dev/null
+++ b/include/llvm/Analysis/BlockFrequencyImpl.h
@@ -0,0 +1,342 @@
+//===---- BlockFrequencyImpl.h - Machine Block Frequency Implementation ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Shared implementation of BlockFrequency for IR and Machine Instructions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYIMPL_H
+#define LLVM_ANALYSIS_BLOCKFREQUENCYIMPL_H
+
+#include "llvm/BasicBlock.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/Support/BlockFrequency.h"
+#include "llvm/Support/BranchProbability.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+#include <vector>
+#include <string>
+
+namespace llvm {
+
+
+class BlockFrequencyInfo;
+class MachineBlockFrequencyInfo;
+
+/// BlockFrequencyImpl implements block frequency algorithm for IR and
+/// Machine Instructions. Algorithm starts with value 1024 (START_FREQ)
+/// for the entry block and then propagates frequencies using branch weights
+/// from (Machine)BranchProbabilityInfo. LoopInfo is not required because
+/// algorithm can find "backedges" by itself.
+template<class BlockT, class FunctionT, class BlockProbInfoT>
+class BlockFrequencyImpl {
+
+ DenseMap<const BlockT *, BlockFrequency> Freqs;
+
+ BlockProbInfoT *BPI;
+
+ FunctionT *Fn;
+
+ typedef GraphTraits< Inverse<BlockT *> > GT;
+
+ const uint32_t EntryFreq;
+
+ std::string getBlockName(BasicBlock *BB) const {
+ return BB->getName().str();
+ }
+
+ std::string getBlockName(MachineBasicBlock *MBB) const {
+ std::string str;
+ raw_string_ostream ss(str);
+ ss << "BB#" << MBB->getNumber();
+
+ if (const BasicBlock *BB = MBB->getBasicBlock())
+ ss << " derived from LLVM BB " << BB->getName();
+
+ return ss.str();
+ }
+
+ void setBlockFreq(BlockT *BB, BlockFrequency Freq) {
+ Freqs[BB] = Freq;
+ DEBUG(dbgs() << "Frequency(" << getBlockName(BB) << ") = " << Freq << "\n");
+ }
+
+ /// getEdgeFreq - Return edge frequency based on SRC frequency and Src -> Dst
+ /// edge probability.
+ BlockFrequency getEdgeFreq(BlockT *Src, BlockT *Dst) const {
+ BranchProbability Prob = BPI->getEdgeProbability(Src, Dst);
+ return getBlockFreq(Src) * Prob;
+ }
+
+ /// incBlockFreq - Increase BB block frequency by FREQ.
+ ///
+ void incBlockFreq(BlockT *BB, BlockFrequency Freq) {
+ Freqs[BB] += Freq;
+ DEBUG(dbgs() << "Frequency(" << getBlockName(BB) << ") += " << Freq
+ << " --> " << Freqs[BB] << "\n");
+ }
+
+ /// divBlockFreq - Divide BB block frequency by PROB. If Prob = 0 do nothing.
+ ///
+ void divBlockFreq(BlockT *BB, BranchProbability Prob) {
+ uint64_t N = Prob.getNumerator();
+ assert(N && "Illegal division by zero!");
+ uint64_t D = Prob.getDenominator();
+ uint64_t Freq = (Freqs[BB].getFrequency() * D) / N;
+
+ // Should we assert it?
+ if (Freq > UINT32_MAX)
+ Freq = UINT32_MAX;
+
+ Freqs[BB] = BlockFrequency(Freq);
+ DEBUG(dbgs() << "Frequency(" << getBlockName(BB) << ") /= (" << Prob
+ << ") --> " << Freqs[BB] << "\n");
+ }
+
+ // All blocks in postorder.
+ std::vector<BlockT *> POT;
+
+ // Map Block -> Position in reverse-postorder list.
+ DenseMap<BlockT *, unsigned> RPO;
+
+ // Cycle Probability for each bloch.
+ DenseMap<BlockT *, uint32_t> CycleProb;
+
+ // (reverse-)postorder traversal iterators.
+ typedef typename std::vector<BlockT *>::iterator pot_iterator;
+ typedef typename std::vector<BlockT *>::reverse_iterator rpot_iterator;
+
+ pot_iterator pot_begin() { return POT.begin(); }
+ pot_iterator pot_end() { return POT.end(); }
+
+ rpot_iterator rpot_begin() { return POT.rbegin(); }
+ rpot_iterator rpot_end() { return POT.rend(); }
+
+ rpot_iterator rpot_at(BlockT *BB) {
+ rpot_iterator I = rpot_begin();
+ unsigned idx = RPO[BB];
+ assert(idx);
+ std::advance(I, idx - 1);
+
+ assert(*I == BB);
+ return I;
+ }
+
+
+ /// isReachable - Returns if BB block is reachable from the entry.
+ ///
+ bool isReachable(BlockT *BB) {
+ return RPO.count(BB);
+ }
+
+ /// isBackedge - Return if edge Src -> Dst is a backedge.
+ ///
+ bool isBackedge(BlockT *Src, BlockT *Dst) {
+ assert(isReachable(Src));
+ assert(isReachable(Dst));
+
+ unsigned a = RPO[Src];
+ unsigned b = RPO[Dst];
+
+ return a >= b;
+ }
+
+ /// getSingleBlockPred - return single BB block predecessor or NULL if
+ /// BB has none or more predecessors.
+ BlockT *getSingleBlockPred(BlockT *BB) {
+ typename GT::ChildIteratorType
+ PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
+ PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);
+
+ if (PI == PE)
+ return 0;
+
+ BlockT *Pred = *PI;
+
+ ++PI;
+ if (PI != PE)
+ return 0;
+
+ return Pred;
+ }
+
+ void doBlock(BlockT *BB, BlockT *LoopHead,
+ SmallPtrSet<BlockT *, 8> &BlocksInLoop) {
+
+ DEBUG(dbgs() << "doBlock(" << getBlockName(BB) << ")\n");
+ setBlockFreq(BB, 0);
+
+ if (BB == LoopHead) {
+ setBlockFreq(BB, EntryFreq);
+ return;
+ }
+
+ if(BlockT *Pred = getSingleBlockPred(BB)) {
+ if (BlocksInLoop.count(Pred))
+ setBlockFreq(BB, getEdgeFreq(Pred, BB));
+ // TODO: else? irreducible, ignore it for now.
+ return;
+ }
+
+ bool isInLoop = false;
+ bool isLoopHead = false;
+
+ for (typename GT::ChildIteratorType
+ PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
+ PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);
+ PI != PE; ++PI) {
+ BlockT *Pred = *PI;
+
+ if (isReachable(Pred) && isBackedge(Pred, BB)) {
+ isLoopHead = true;
+ } else if (BlocksInLoop.count(Pred)) {
+ incBlockFreq(BB, getEdgeFreq(Pred, BB));
+ isInLoop = true;
+ }
+ // TODO: else? irreducible.
+ }
+
+ if (!isInLoop)
+ return;
+
+ if (!isLoopHead)
+ return;
+
+ assert(EntryFreq >= CycleProb[BB]);
+ uint32_t CProb = CycleProb[BB];
+ uint32_t Numerator = EntryFreq - CProb ? EntryFreq - CProb : 1;
+ divBlockFreq(BB, BranchProbability(Numerator, EntryFreq));
+ }
+
+ /// doLoop - Propagate block frequency down through the loop.
+ void doLoop(BlockT *Head, BlockT *Tail) {
+ DEBUG(dbgs() << "doLoop(" << getBlockName(Head) << ", "
+ << getBlockName(Tail) << ")\n");
+
+ SmallPtrSet<BlockT *, 8> BlocksInLoop;
+
+ for (rpot_iterator I = rpot_at(Head), E = rpot_at(Tail); ; ++I) {
+ BlockT *BB = *I;
+ doBlock(BB, Head, BlocksInLoop);
+
+ BlocksInLoop.insert(BB);
+ if (I == E)
+ break;
+ }
+
+ // Compute loop's cyclic probability using backedges probabilities.
+ for (typename GT::ChildIteratorType
+ PI = GraphTraits< Inverse<BlockT *> >::child_begin(Head),
+ PE = GraphTraits< Inverse<BlockT *> >::child_end(Head);
+ PI != PE; ++PI) {
+ BlockT *Pred = *PI;
+ assert(Pred);
+ if (isReachable(Pred) && isBackedge(Pred, Head)) {
+ uint64_t N = getEdgeFreq(Pred, Head).getFrequency();
+ uint64_t D = getBlockFreq(Head).getFrequency();
+ assert(N <= EntryFreq && "Backedge frequency must be <= EntryFreq!");
+ uint64_t Res = (N * EntryFreq) / D;
+
+ assert(Res <= UINT32_MAX);
+ CycleProb[Head] += (uint32_t) Res;
+ DEBUG(dbgs() << " CycleProb[" << getBlockName(Head) << "] += " << Res
+ << " --> " << CycleProb[Head] << "\n");
+ }
+ }
+ }
+
+ friend class BlockFrequencyInfo;
+ friend class MachineBlockFrequencyInfo;
+
+ BlockFrequencyImpl() : EntryFreq(BlockFrequency::getEntryFrequency()) { }
+
+ void doFunction(FunctionT *fn, BlockProbInfoT *bpi) {
+ Fn = fn;
+ BPI = bpi;
+
+ // Clear everything.
+ RPO.clear();
+ POT.clear();
+ CycleProb.clear();
+ Freqs.clear();
+
+ BlockT *EntryBlock = fn->begin();
+
+ copy(po_begin(EntryBlock), po_end(EntryBlock), back_inserter(POT));
+
+ unsigned RPOidx = 0;
+ for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
+ BlockT *BB = *I;
+ RPO[BB] = ++RPOidx;
+ DEBUG(dbgs() << "RPO[" << getBlockName(BB) << "] = " << RPO[BB] << "\n");
+ }
+
+ // Travel over all blocks in postorder.
+ for (pot_iterator I = pot_begin(), E = pot_end(); I != E; ++I) {
+ BlockT *BB = *I;
+ BlockT *LastTail = 0;
+ DEBUG(dbgs() << "POT: " << getBlockName(BB) << "\n");
+
+ for (typename GT::ChildIteratorType
+ PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
+ PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);
+ PI != PE; ++PI) {
+
+ BlockT *Pred = *PI;
+ if (isReachable(Pred) && isBackedge(Pred, BB)
+ && (!LastTail || RPO[Pred] > RPO[LastTail]))
+ LastTail = Pred;
+ }
+
+ if (LastTail)
+ doLoop(BB, LastTail);
+ }
+
+ // At the end assume the whole function as a loop, and travel over it once
+ // again.
+ doLoop(*(rpot_begin()), *(pot_begin()));
+ }
+
+public:
+ /// getBlockFreq - Return block frequency. Return 0 if we don't have it.
+ BlockFrequency getBlockFreq(const BlockT *BB) const {
+ typename DenseMap<const BlockT *, BlockFrequency>::const_iterator
+ I = Freqs.find(BB);
+ if (I != Freqs.end())
+ return I->second;
+ return 0;
+ }
+
+ void print(raw_ostream &OS) const {
+ OS << "\n\n---- Block Freqs ----\n";
+ for (typename FunctionT::iterator I = Fn->begin(), E = Fn->end(); I != E;) {
+ BlockT *BB = I++;
+ OS << " " << getBlockName(BB) << " = " << getBlockFreq(BB) << "\n";
+
+ for (typename GraphTraits<BlockT *>::ChildIteratorType
+ SI = GraphTraits<BlockT *>::child_begin(BB),
+ SE = GraphTraits<BlockT *>::child_end(BB); SI != SE; ++SI) {
+ BlockT *Succ = *SI;
+ OS << " " << getBlockName(BB) << " -> " << getBlockName(Succ)
+ << " = " << getEdgeFreq(BB, Succ) << "\n";
+ }
+ }
+ }
+
+ void dump() const {
+ print(dbgs());
+ }
+};
+
+}
+
+#endif
diff --git a/include/llvm/Analysis/BlockFrequencyInfo.h b/include/llvm/Analysis/BlockFrequencyInfo.h
new file mode 100644
index 00000000000..fcab90677a4
--- /dev/null
+++ b/include/llvm/Analysis/BlockFrequencyInfo.h
@@ -0,0 +1,55 @@
+//========-------- BlockFrequencyInfo.h - Block Frequency Analysis -------========//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Loops should be simplified before this analysis.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFO_H
+#define LLVM_ANALYSIS_BLOCKFREQUENCYINFO_H
+
+#include "llvm/Pass.h"
+#include "llvm/Support/BlockFrequency.h"
+#include <climits>
+
+namespace llvm {
+
+class BranchProbabilityInfo;
+template<class BlockT, class FunctionT, class BranchProbInfoT>
+class BlockFrequencyImpl;
+
+/// BlockFrequencyInfo pass uses BlockFrequencyImpl implementation to estimate
+/// IR basic block frequencies.
+class BlockFrequencyInfo : public FunctionPass {
+
+ BlockFrequencyImpl<BasicBlock, Function, BranchProbabilityInfo> *BFI;
+
+public:
+ static char ID;
+
+ BlockFrequencyInfo();
+
+ ~BlockFrequencyInfo();
+
+ void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ bool runOnFunction(Function &F);
+ void print(raw_ostream &O, const Module *M) const;
+
+ /// getblockFreq - Return block frequency. Return 0 if we don't have the
+ /// information. Please note that initial frequency is equal to 1024. It means
+ /// that we should not rely on the value itself, but only on the comparison to
+ /// the other block frequencies. We do this to avoid using of floating points.
+ ///
+ BlockFrequency getBlockFreq(const BasicBlock *BB) const;
+};
+
+}
+
+#endif
diff --git a/include/llvm/Analysis/BranchProbabilityInfo.h b/include/llvm/Analysis/BranchProbabilityInfo.h
new file mode 100644
index 00000000000..c0567daa3a5
--- /dev/null
+++ b/include/llvm/Analysis/BranchProbabilityInfo.h
@@ -0,0 +1,148 @@
+//===--- BranchProbabilityInfo.h - Branch Probability Analysis --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This pass is used to evaluate branch probabilties.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
+#define LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
+
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/BranchProbability.h"
+
+namespace llvm {
+class LoopInfo;
+class raw_ostream;
+
+/// \brief Analysis pass providing branch probability information.
+///
+/// This is a function analysis pass which provides information on the relative
+/// probabilities of each "edge" in the function's CFG where such an edge is
+/// defined by a pair (PredBlock and an index in the successors). The
+/// probability of an edge from one block is always relative to the
+/// probabilities of other edges from the block. The probabilites of all edges
+/// from a block sum to exactly one (100%).
+/// We use a pair (PredBlock and an index in the successors) to uniquely
+/// identify an edge, since we can have multiple edges from Src to Dst.
+/// As an example, we can have a switch which jumps to Dst with value 0 and
+/// value 10.
+class BranchProbabilityInfo : public FunctionPass {
+public:
+ static char ID;
+
+ BranchProbabilityInfo() : FunctionPass(ID) {
+ initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
+ }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const;
+ bool runOnFunction(Function &F);
+ void print(raw_ostream &OS, const Module *M = 0) const;
+
+ /// \brief Get an edge's probability, relative to other out-edges of the Src.
+ ///
+ /// This routine provides access to the fractional probability between zero
+ /// (0%) and one (100%) of this edge executing, relative to other edges
+ /// leaving the 'Src' block. The returned probability is never zero, and can
+ /// only be one if the source block has only one successor.
+ BranchProbability getEdgeProbability(const BasicBlock *Src,
+ unsigned IndexInSuccessors) const;
+
+ /// \brief Get the probability of going from Src to Dst.
+ ///
+ /// It returns the sum of all probabilities for edges from Src to Dst.
+ BranchProbability getEdgeProbability(const BasicBlock *Src,
+ const BasicBlock *Dst) const;
+
+ /// \brief Test if an edge is hot relative to other out-edges of the Src.
+ ///
+ /// Check whether this edge out of the source block is 'hot'. We define hot
+ /// as having a relative probability >= 80%.
+ bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
+
+ /// \brief Retrieve the hot successor of a block if one exists.
+ ///
+ /// Given a basic block, look through its successors and if one exists for
+ /// which \see isEdgeHot would return true, return that successor block.
+ BasicBlock *getHotSucc(BasicBlock *BB) const;
+
+ /// \brief Print an edge's probability.
+ ///
+ /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
+ /// then prints that probability to the provided stream. That stream is then
+ /// returned.
+ raw_ostream &printEdgeProbability(raw_ostream &OS, const BasicBlock *Src,
+ const BasicBlock *Dst) const;
+
+ /// \brief Get the raw edge weight calculated for the edge.
+ ///
+ /// This returns the raw edge weight. It is guaranteed to fall between 1 and
+ /// UINT32_MAX. Note that the raw edge weight is not meaningful in isolation.
+ /// This interface should be very carefully, and primarily by routines that
+ /// are updating the analysis by later calling setEdgeWeight.
+ uint32_t getEdgeWeight(const BasicBlock *Src,
+ unsigned IndexInSuccessors) const;
+
+ /// \brief Get the raw edge weight calculated for the block pair.
+ ///
+ /// This returns the sum of all raw edge weights from Src to Dst.
+ /// It is guaranteed to fall between 1 and UINT32_MAX.
+ uint32_t getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const;
+
+ /// \brief Set the raw edge weight for a given edge.
+ ///
+ /// This allows a pass to explicitly set the edge weight for an edge. It can
+ /// be used when updating the CFG to update and preserve the branch
+ /// probability information. Read the implementation of how these edge
+ /// weights are calculated carefully before using!
+ void setEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors,
+ uint32_t Weight);
+
+private:
+ // Since we allow duplicate edges from one basic block to another, we use
+ // a pair (PredBlock and an index in the successors) to specify an edge.
+ typedef std::pair<const BasicBlock *, unsigned> Edge;
+
+ // Default weight value. Used when we don't have information about the edge.
+ // TODO: DEFAULT_WEIGHT makes sense during static predication, when none of
+ // the successors have a weight yet. But it doesn't make sense when providing
+ // weight to an edge that may have siblings with non-zero weights. This can
+ // be handled various ways, but it's probably fine for an edge with unknown
+ // weight to just "inherit" the non-zero weight of an adjacent successor.
+ static const uint32_t DEFAULT_WEIGHT = 16;
+
+ DenseMap<Edge, uint32_t> Weights;
+
+ /// \brief Handle to the LoopInfo analysis.
+ LoopInfo *LI;
+
+ /// \brief Track the last function we run over for printing.
+ Function *LastF;
+
+ /// \brief Track the set of blocks directly succeeded by a returning block.
+ SmallPtrSet<BasicBlock *, 16> PostDominatedByUnreachable;
+
+ /// \brief Get sum of the block successors' weights.
+ uint32_t getSumForBlock(const BasicBlock *BB) const;
+
+ bool calcUnreachableHeuristics(BasicBlock *BB);
+ bool calcMetadataWeights(BasicBlock *BB);
+ bool calcPointerHeuristics(BasicBlock *BB);
+ bool calcLoopBranchHeuristics(BasicBlock *BB);
+ bool calcZeroHeuristics(BasicBlock *BB);
+ bool calcFloatingPointHeuristics(BasicBlock *BB);
+ bool calcInvokeHeuristics(BasicBlock *BB);
+};
+
+}
+
+#endif
diff --git a/include/llvm/Analysis/CFGPrinter.h b/include/llvm/Analysis/CFGPrinter.h
new file mode 100644
index 00000000000..4704a929acf
--- /dev/null
+++ b/include/llvm/Analysis/CFGPrinter.h
@@ -0,0 +1,114 @@
+//===-- CFGPrinter.h - CFG printer external interface -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines external functions that can be called to explicitly
+// instantiate the CFG printer.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_CFGPRINTER_H
+#define LLVM_ANALYSIS_CFGPRINTER_H
+
+#include "llvm/Constants.h"
+#include "llvm/Function.h"
+#include "llvm/Instructions.h"
+#include "llvm/Assembly/Writer.h"
+#include "llvm/Support/CFG.h"
+#include "llvm/Support/GraphWriter.h"
+
+namespace llvm {
+template<>
+struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
+
+ DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
+
+ static std::string getGraphName(const Function *F) {
+ return "CFG for '" + F->getName().str() + "' function";
+ }
+
+ static std::string getSimpleNodeLabel(const BasicBlock *Node,
+ const Function *) {
+ if (!Node->getName().empty())
+ return Node->getName().str();
+
+ std::string Str;
+ raw_string_ostream OS(Str);
+
+ WriteAsOperand(OS, Node, false);
+ return OS.str();
+ }
+
+ static std::string getCompleteNodeLabel(const BasicBlock *Node,
+ const Function *) {
+ std::string Str;
+ raw_string_ostream OS(Str);
+
+ if (Node->getName().empty()) {
+ WriteAsOperand(OS, Node, false);
+ OS << ":";
+ }
+
+ OS << *Node;
+ std::string OutStr = OS.str();
+ if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
+
+ // Process string output to make it nicer...
+ for (unsigned i = 0; i != OutStr.length(); ++i)
+ if (OutStr[i] == '\n') { // Left justify
+ OutStr[i] = '\\';
+ OutStr.insert(OutStr.begin()+i+1, 'l');
+ } else if (OutStr[i] == ';') { // Delete comments!
+ unsigned Idx = OutStr.find('\n', i+1); // Find end of line
+ OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
+ --i;
+ }
+
+ return OutStr;
+ }
+
+ std::string getNodeLabel(const BasicBlock *Node,
+ const Function *Graph) {
+ if (isSimple())
+ return getSimpleNodeLabel(Node, Graph);
+ else
+ return getCompleteNodeLabel(Node, Graph);
+ }
+
+ static std::string getEdgeSourceLabel(const BasicBlock *Node,
+ succ_const_iterator I) {
+ // Label source of conditional branches with "T" or "F"
+ if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
+ if (BI->isConditional())
+ return (I == succ_begin(Node)) ? "T" : "F";
+
+ // Label source of switch edges with the associated value.
+ if (const SwitchInst *SI = dyn_cast<SwitchInst>(Node->getTerminator())) {
+ unsigned SuccNo = I.getSuccessorIndex();
+
+ if (SuccNo == 0) return "def";
+
+ std::string Str;
+ raw_string_ostream OS(Str);
+ SwitchInst::ConstCaseIt Case =
+ SwitchInst::ConstCaseIt::fromSuccessorIndex(SI, SuccNo);
+ OS << Case.getCaseValue()->getValue();
+ return OS.str();
+ }
+ return "";
+ }
+};
+} // End llvm namespace
+
+namespace llvm {
+ class FunctionPass;
+ FunctionPass *createCFGPrinterPass ();
+ FunctionPass *createCFGOnlyPrinterPass ();
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/CallGraph.h b/include/llvm/Analysis/CallGraph.h
new file mode 100644
index 00000000000..6a9ed310375
--- /dev/null
+++ b/include/llvm/Analysis/CallGraph.h
@@ -0,0 +1,378 @@
+//===- CallGraph.h - Build a Module's call graph ----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This interface is used to build and manipulate a call graph, which is a very
+// useful tool for interprocedural optimization.
+//
+// Every function in a module is represented as a node in the call graph. The
+// callgraph node keeps track of which functions the are called by the function
+// corresponding to the node.
+//
+// A call graph may contain nodes where the function that they correspond to is
+// null. These 'external' nodes are used to represent control flow that is not
+// represented (or analyzable) in the module. In particular, this analysis
+// builds one external node such that:
+// 1. All functions in the module without internal linkage will have edges
+// from this external node, indicating that they could be called by
+// functions outside of the module.
+// 2. All functions whose address is used for something more than a direct
+// call, for example being stored into a memory location will also have an
+// edge from this external node. Since they may be called by an unknown
+// caller later, they must be tracked as such.
+//
+// There is a second external node added for calls that leave this module.
+// Functions have a call edge to the external node iff:
+// 1. The function is external, reflecting the fact that they could call
+// anything without internal linkage or that has its address taken.
+// 2. The function contains an indirect function call.
+//
+// As an extension in the future, there may be multiple nodes with a null
+// function. These will be used when we can prove (through pointer analysis)
+// that an indirect call site can call only a specific set of functions.
+//
+// Because of these properties, the CallGraph captures a conservative superset
+// of all of the caller-callee relationships, which is useful for
+// transformations.
+//
+// The CallGraph class also attempts to figure out what the root of the
+// CallGraph is, which it currently does by looking for a function named 'main'.
+// If no function named 'main' is found, the external node is used as the entry
+// node, reflecting the fact that any function without internal linkage could
+// be called into (which is common for libraries).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_CALLGRAPH_H
+#define LLVM_ANALYSIS_CALLGRAPH_H
+
+#include "llvm/Function.h"
+#include "llvm/Pass.h"
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/CallSite.h"
+#include "llvm/Support/ValueHandle.h"
+#include "llvm/Support/IncludeFile.h"
+#include <map>
+
+namespace llvm {
+
+class Function;
+class Module;
+class CallGraphNode;
+
+//===----------------------------------------------------------------------===//
+// CallGraph class definition
+//
+class CallGraph {
+protected:
+ Module *Mod; // The module this call graph represents
+
+ typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
+ FunctionMapTy FunctionMap; // Map from a function to its node
+
+public:
+ static char ID; // Class identification, replacement for typeinfo
+ //===---------------------------------------------------------------------
+ // Accessors.
+ //
+ typedef FunctionMapTy::iterator iterator;
+ typedef FunctionMapTy::const_iterator const_iterator;
+
+ /// getModule - Return the module the call graph corresponds to.
+ ///
+ Module &getModule() const { return *Mod; }
+
+ inline iterator begin() { return FunctionMap.begin(); }
+ inline iterator end() { return FunctionMap.end(); }
+ inline const_iterator begin() const { return FunctionMap.begin(); }
+ inline const_iterator end() const { return FunctionMap.end(); }
+
+ // Subscripting operators, return the call graph node for the provided
+ // function
+ inline const CallGraphNode *operator[](const Function *F) const {
+ const_iterator I = FunctionMap.find(F);
+ assert(I != FunctionMap.end() && "Function not in callgraph!");
+ return I->second;
+ }
+ inline CallGraphNode *operator[](const Function *F) {
+ const_iterator I = FunctionMap.find(F);
+ assert(I != FunctionMap.end() && "Function not in callgraph!");
+ return I->second;
+ }
+
+ /// Returns the CallGraphNode which is used to represent undetermined calls
+ /// into the callgraph. Override this if you want behavioral inheritance.
+ virtual CallGraphNode* getExternalCallingNode() const { return 0; }
+ virtual CallGraphNode* getCallsExternalNode() const { return 0; }
+
+ /// Return the root/main method in the module, or some other root node, such
+ /// as the externalcallingnode. Overload these if you behavioral
+ /// inheritance.
+ virtual CallGraphNode* getRoot() { return 0; }
+ virtual const CallGraphNode* getRoot() const { return 0; }
+
+ //===---------------------------------------------------------------------
+ // Functions to keep a call graph up to date with a function that has been
+ // modified.
+ //
+
+ /// removeFunctionFromModule - Unlink the function from this module, returning
+ /// it. Because this removes the function from the module, the call graph
+ /// node is destroyed. This is only valid if the function does not call any
+ /// other functions (ie, there are no edges in it's CGN). The easiest way to
+ /// do this is to dropAllReferences before calling this.
+ ///
+ Function *removeFunctionFromModule(CallGraphNode *CGN);
+ Function *removeFunctionFromModule(Function *F) {
+ return removeFunctionFromModule((*this)[F]);
+ }
+
+ /// getOrInsertFunction - This method is identical to calling operator[], but
+ /// it will insert a new CallGraphNode for the specified function if one does
+ /// not already exist.
+ CallGraphNode *getOrInsertFunction(const Function *F);
+
+ /// spliceFunction - Replace the function represented by this node by another.
+ /// This does not rescan the body of the function, so it is suitable when
+ /// splicing the body of one function to another while also updating all
+ /// callers from the old function to the new.
+ ///
+ void spliceFunction(const Function *From, const Function *To);
+
+ //===---------------------------------------------------------------------
+ // Pass infrastructure interface glue code.
+ //
+protected:
+ CallGraph() {}
+
+public:
+ virtual ~CallGraph() { destroy(); }
+
+ /// initialize - Call this method before calling other methods,
+ /// re/initializes the state of the CallGraph.
+ ///
+ void initialize(Module &M);
+
+ void print(raw_ostream &o, Module *) const;
+ void dump() const;
+protected:
+ // destroy - Release memory for the call graph
+ virtual void destroy();
+};
+
+//===----------------------------------------------------------------------===//
+// CallGraphNode class definition.
+//
+class CallGraphNode {
+ friend class CallGraph;
+
+ AssertingVH<Function> F;
+
+ // CallRecord - This is a pair of the calling instruction (a call or invoke)
+ // and the callgraph node being called.
+public:
+ typedef std::pair<WeakVH, CallGraphNode*> CallRecord;
+private:
+ std::vector<CallRecord> CalledFunctions;
+
+ /// NumReferences - This is the number of times that this CallGraphNode occurs
+ /// in the CalledFunctions array of this or other CallGraphNodes.
+ unsigned NumReferences;
+
+ CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
+ void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
+
+ void DropRef() { --NumReferences; }
+ void AddRef() { ++NumReferences; }
+public:
+ typedef std::vector<CallRecord> CalledFunctionsVector;
+
+
+ // CallGraphNode ctor - Create a node for the specified function.
+ inline CallGraphNode(Function *f) : F(f), NumReferences(0) {}
+ ~CallGraphNode() {
+ assert(NumReferences == 0 && "Node deleted while references remain");
+ }
+
+ //===---------------------------------------------------------------------
+ // Accessor methods.
+ //
+
+ typedef std::vector<CallRecord>::iterator iterator;
+ typedef std::vector<CallRecord>::const_iterator const_iterator;
+
+ // getFunction - Return the function that this call graph node represents.
+ Function *getFunction() const { return F; }
+
+ inline iterator begin() { return CalledFunctions.begin(); }
+ inline iterator end() { return CalledFunctions.end(); }
+ inline const_iterator begin() const { return CalledFunctions.begin(); }
+ inline const_iterator end() const { return CalledFunctions.end(); }
+ inline bool empty() const { return CalledFunctions.empty(); }
+ inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
+
+ /// getNumReferences - Return the number of other CallGraphNodes in this
+ /// CallGraph that reference this node in their callee list.
+ unsigned getNumReferences() const { return NumReferences; }
+
+ // Subscripting operator - Return the i'th called function.
+ //
+ CallGraphNode *operator[](unsigned i) const {
+ assert(i < CalledFunctions.size() && "Invalid index");
+ return CalledFunctions[i].second;
+ }
+
+ /// dump - Print out this call graph node.
+ ///
+ void dump() const;
+ void print(raw_ostream &OS) const;
+
+ //===---------------------------------------------------------------------
+ // Methods to keep a call graph up to date with a function that has been
+ // modified
+ //
+
+ /// removeAllCalledFunctions - As the name implies, this removes all edges
+ /// from this CallGraphNode to any functions it calls.
+ void removeAllCalledFunctions() {
+ while (!CalledFunctions.empty()) {
+ CalledFunctions.back().second->DropRef();
+ CalledFunctions.pop_back();
+ }
+ }
+
+ /// stealCalledFunctionsFrom - Move all the callee information from N to this
+ /// node.
+ void stealCalledFunctionsFrom(CallGraphNode *N) {
+ assert(CalledFunctions.empty() &&
+ "Cannot steal callsite information if I already have some");
+ std::swap(CalledFunctions, N->CalledFunctions);
+ }
+
+
+ /// addCalledFunction - Add a function to the list of functions called by this
+ /// one.
+ void addCalledFunction(CallSite CS, CallGraphNode *M) {
+ assert(!CS.getInstruction() ||
+ !CS.getCalledFunction() ||
+ !CS.getCalledFunction()->isIntrinsic());
+ CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
+ M->AddRef();
+ }
+
+ void removeCallEdge(iterator I) {
+ I->second->DropRef();
+ *I = CalledFunctions.back();
+ CalledFunctions.pop_back();
+ }
+
+
+ /// removeCallEdgeFor - This method removes the edge in the node for the
+ /// specified call site. Note that this method takes linear time, so it
+ /// should be used sparingly.
+ void removeCallEdgeFor(CallSite CS);
+
+ /// removeAnyCallEdgeTo - This method removes all call edges from this node
+ /// to the specified callee function. This takes more time to execute than
+ /// removeCallEdgeTo, so it should not be used unless necessary.
+ void removeAnyCallEdgeTo(CallGraphNode *Callee);
+
+ /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
+ /// from this node to the specified callee function.
+ void removeOneAbstractEdgeTo(CallGraphNode *Callee);
+
+ /// replaceCallEdge - This method replaces the edge in the node for the
+ /// specified call site with a new one. Note that this method takes linear
+ /// time, so it should be used sparingly.
+ void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
+
+ /// allReferencesDropped - This is a special function that should only be
+ /// used by the CallGraph class.
+ void allReferencesDropped() {
+ NumReferences = 0;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// GraphTraits specializations for call graphs so that they can be treated as
+// graphs by the generic graph algorithms.
+//
+
+// Provide graph traits for tranversing call graphs using standard graph
+// traversals.
+template <> struct GraphTraits<CallGraphNode*> {
+ typedef CallGraphNode NodeType;
+
+ typedef CallGraphNode::CallRecord CGNPairTy;
+ typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode*> CGNDerefFun;
+
+ static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
+
+ typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
+
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
+ }
+ static inline ChildIteratorType child_end (NodeType *N) {
+ return map_iterator(N->end(), CGNDerefFun(CGNDeref));
+ }
+
+ static CallGraphNode *CGNDeref(CGNPairTy P) {
+ return P.second;
+ }
+
+};
+
+template <> struct GraphTraits<const CallGraphNode*> {
+ typedef const CallGraphNode NodeType;
+ typedef NodeType::const_iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
+ static inline ChildIteratorType child_begin(NodeType *N) { return N->begin();}
+ static inline ChildIteratorType child_end (NodeType *N) { return N->end(); }
+};
+
+template<> struct GraphTraits<CallGraph*> : public GraphTraits<CallGraphNode*> {
+ static NodeType *getEntryNode(CallGraph *CGN) {
+ return CGN->getExternalCallingNode(); // Start at the external node!
+ }
+ typedef std::pair<const Function*, CallGraphNode*> PairTy;
+ typedef std::pointer_to_unary_function<PairTy, CallGraphNode&> DerefFun;
+
+ // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
+ typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
+ static nodes_iterator nodes_begin(CallGraph *CG) {
+ return map_iterator(CG->begin(), DerefFun(CGdereference));
+ }
+ static nodes_iterator nodes_end (CallGraph *CG) {
+ return map_iterator(CG->end(), DerefFun(CGdereference));
+ }
+
+ static CallGraphNode &CGdereference(PairTy P) {
+ return *P.second;
+ }
+};
+
+template<> struct GraphTraits<const CallGraph*> :
+ public GraphTraits<const CallGraphNode*> {
+ static NodeType *getEntryNode(const CallGraph *CGN) {
+ return CGN->getExternalCallingNode();
+ }
+ // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
+ typedef CallGraph::const_iterator nodes_iterator;
+ static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
+ static nodes_iterator nodes_end (const CallGraph *CG) { return CG->end(); }
+};
+
+} // End llvm namespace
+
+// Make sure that any clients of this file link in CallGraph.cpp
+FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)
+
+#endif
diff --git a/include/llvm/Analysis/CaptureTracking.h b/include/llvm/Analysis/CaptureTracking.h
new file mode 100644
index 00000000000..9b5e8425ad2
--- /dev/null
+++ b/include/llvm/Analysis/CaptureTracking.h
@@ -0,0 +1,63 @@
+//===----- llvm/Analysis/CaptureTracking.h - Pointer capture ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains routines that help determine which pointers are captured.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_CAPTURETRACKING_H
+#define LLVM_ANALYSIS_CAPTURETRACKING_H
+
+#include "llvm/Constants.h"
+#include "llvm/Instructions.h"
+#include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/Support/CallSite.h"
+
+namespace llvm {
+ /// PointerMayBeCaptured - Return true if this pointer value may be captured
+ /// by the enclosing function (which is required to exist). This routine can
+ /// be expensive, so consider caching the results. The boolean ReturnCaptures
+ /// specifies whether returning the value (or part of it) from the function
+ /// counts as capturing it or not. The boolean StoreCaptures specified
+ /// whether storing the value (or part of it) into memory anywhere
+ /// automatically counts as capturing it or not.
+ bool PointerMayBeCaptured(const Value *V,
+ bool ReturnCaptures,
+ bool StoreCaptures);
+
+ /// This callback is used in conjunction with PointerMayBeCaptured. In
+ /// addition to the interface here, you'll need to provide your own getters
+ /// to see whether anything was captured.
+ struct CaptureTracker {
+ virtual ~CaptureTracker();
+
+ /// tooManyUses - The depth of traversal has breached a limit. There may be
+ /// capturing instructions that will not be passed into captured().
+ virtual void tooManyUses() = 0;
+
+ /// shouldExplore - This is the use of a value derived from the pointer.
+ /// To prune the search (ie., assume that none of its users could possibly
+ /// capture) return false. To search it, return true.
+ ///
+ /// U->getUser() is always an Instruction.
+ virtual bool shouldExplore(Use *U) = 0;
+
+ /// captured - Information about the pointer was captured by the user of
+ /// use U. Return true to stop the traversal or false to continue looking
+ /// for more capturing instructions.
+ virtual bool captured(Use *U) = 0;
+ };
+
+ /// PointerMayBeCaptured - Visit the value and the values derived from it and
+ /// find values which appear to be capturing the pointer value. This feeds
+ /// results into and is controlled by the CaptureTracker object.
+ void PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker);
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Analysis/CodeMetrics.h b/include/llvm/Analysis/CodeMetrics.h
new file mode 100644
index 00000000000..03c807cf832
--- /dev/null
+++ b/include/llvm/Analysis/CodeMetrics.h
@@ -0,0 +1,95 @@
+//===- CodeMetrics.h - Code cost measurements -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements various weight measurements for code, helping
+// the Inliner and other passes decide whether to duplicate its contents.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_CODEMETRICS_H
+#define LLVM_ANALYSIS_CODEMETRICS_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/CallSite.h"
+
+namespace llvm {
+ class BasicBlock;
+ class Function;
+ class Instruction;
+ class TargetData;
+ class Value;
+
+ /// \brief Check whether an instruction is likely to be "free" when lowered.
+ bool isInstructionFree(const Instruction *I, const TargetData *TD = 0);
+
+ /// \brief Check whether a call will lower to something small.
+ ///
+ /// This tests checks whether this callsite will lower to something
+ /// significantly cheaper than a traditional call, often a single
+ /// instruction. Note that if isInstructionFree(CS.getInstruction()) would
+ /// return true, so will this function.
+ bool callIsSmall(ImmutableCallSite CS);
+
+ /// \brief Utility to calculate the size and a few similar metrics for a set
+ /// of basic blocks.
+ struct CodeMetrics {
+ /// \brief True if this function contains a call to setjmp or other functions
+ /// with attribute "returns twice" without having the attribute itself.
+ bool exposesReturnsTwice;
+
+ /// \brief True if this function calls itself.
+ bool isRecursive;
+
+ /// \brief True if this function contains one or more indirect branches.
+ bool containsIndirectBr;
+
+ /// \brief True if this function calls alloca (in the C sense).
+ bool usesDynamicAlloca;
+
+ /// \brief Number of instructions in the analyzed blocks.
+ unsigned NumInsts;
+
+ /// \brief Number of analyzed blocks.
+ unsigned NumBlocks;
+
+ /// \brief Keeps track of basic block code size estimates.
+ DenseMap<const BasicBlock *, unsigned> NumBBInsts;
+
+ /// \brief Keep track of the number of calls to 'big' functions.
+ unsigned NumCalls;
+
+ /// \brief The number of calls to internal functions with a single caller.
+ ///
+ /// These are likely targets for future inlining, likely exposed by
+ /// interleaved devirtualization.
+ unsigned NumInlineCandidates;
+
+ /// \brief How many instructions produce vector values.
+ ///
+ /// The inliner is more aggressive with inlining vector kernels.
+ unsigned NumVectorInsts;
+
+ /// \brief How many 'ret' instructions the blocks contain.
+ unsigned NumRets;
+
+ CodeMetrics() : exposesReturnsTwice(false), isRecursive(false),
+ containsIndirectBr(false), usesDynamicAlloca(false),
+ NumInsts(0), NumBlocks(0), NumCalls(0),
+ NumInlineCandidates(0), NumVectorInsts(0),
+ NumRets(0) {}
+
+ /// \brief Add information about a block to the current state.
+ void analyzeBasicBlock(const BasicBlock *BB, const TargetData *TD = 0);
+
+ /// \brief Add information about a function to the current state.
+ void analyzeFunction(Function *F, const TargetData *TD = 0);
+ };
+}
+
+#endif
diff --git a/include/llvm/Analysis/ConstantFolding.h b/include/llvm/Analysis/ConstantFolding.h
new file mode 100644
index 00000000000..2fdef5f0836
--- /dev/null
+++ b/include/llvm/Analysis/ConstantFolding.h
@@ -0,0 +1,102 @@
+//===-- ConstantFolding.h - Fold instructions into constants --------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares routines for folding instructions into constants when all
+// operands are constants, for example "sub i32 1, 0" -> "1".
+//
+// Also, to supplement the basic VMCore ConstantExpr simplifications,
+// this file declares some additional folding routines that can make use of
+// TargetData information. These functions cannot go in VMCore due to library
+// dependency issues.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_CONSTANTFOLDING_H
+#define LLVM_ANALYSIS_CONSTANTFOLDING_H
+
+namespace llvm {
+ class Constant;
+ class ConstantExpr;
+ class Instruction;
+ class TargetData;
+ class TargetLibraryInfo;
+ class Function;
+ class Type;
+ template<typename T>
+ class ArrayRef;
+
+/// ConstantFoldInstruction - Try to constant fold the specified instruction.
+/// If successful, the constant result is returned, if not, null is returned.
+/// Note that this fails if not all of the operands are constant. Otherwise,
+/// this function can only fail when attempting to fold instructions like loads
+/// and stores, which have no constant expression form.
+Constant *ConstantFoldInstruction(Instruction *I, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0);
+
+/// ConstantFoldConstantExpression - Attempt to fold the constant expression
+/// using the specified TargetData. If successful, the constant result is
+/// result is returned, if not, null is returned.
+Constant *ConstantFoldConstantExpression(const ConstantExpr *CE,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0);
+
+/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
+/// specified operands. If successful, the constant result is returned, if not,
+/// null is returned. Note that this function can fail when attempting to
+/// fold instructions like loads and stores, which have no constant expression
+/// form.
+///
+Constant *ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
+ ArrayRef<Constant *> Ops,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0);
+
+/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
+/// instruction (icmp/fcmp) with the specified operands. If it fails, it
+/// returns a constant expression of the specified operands.
+///
+Constant *ConstantFoldCompareInstOperands(unsigned Predicate,
+ Constant *LHS, Constant *RHS,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0);
+
+/// ConstantFoldInsertValueInstruction - Attempt to constant fold an insertvalue
+/// instruction with the specified operands and indices. The constant result is
+/// returned if successful; if not, null is returned.
+Constant *ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val,
+ ArrayRef<unsigned> Idxs);
+
+/// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
+/// produce if it is constant and determinable. If this is not determinable,
+/// return null.
+Constant *ConstantFoldLoadFromConstPtr(Constant *C, const TargetData *TD = 0);
+
+/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
+/// getelementptr constantexpr, return the constant value being addressed by the
+/// constant expression, or null if something is funny and we can't decide.
+Constant *ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE);
+
+/// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
+/// indices (with an *implied* zero pointer index that is not in the list),
+/// return the constant value being addressed by a virtual load, or null if
+/// something is funny and we can't decide.
+Constant *ConstantFoldLoadThroughGEPIndices(Constant *C,
+ ArrayRef<Constant*> Indices);
+
+/// canConstantFoldCallTo - Return true if its even possible to fold a call to
+/// the specified function.
+bool canConstantFoldCallTo(const Function *F);
+
+/// ConstantFoldCall - Attempt to constant fold a call to the specified function
+/// with the specified arguments, returning null if unsuccessful.
+Constant *ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
+ const TargetLibraryInfo *TLI = 0);
+}
+
+#endif
diff --git a/include/llvm/Analysis/ConstantsScanner.h b/include/llvm/Analysis/ConstantsScanner.h
new file mode 100644
index 00000000000..cdaf68d75a6
--- /dev/null
+++ b/include/llvm/Analysis/ConstantsScanner.h
@@ -0,0 +1,93 @@
+//==- llvm/Analysis/ConstantsScanner.h - Iterate over constants -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This class implements an iterator to walk through the constants referenced by
+// a method. This is used by the Bitcode & Assembly writers to build constant
+// pools.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_CONSTANTSSCANNER_H
+#define LLVM_ANALYSIS_CONSTANTSSCANNER_H
+
+#include "llvm/Support/InstIterator.h"
+
+namespace llvm {
+
+class Constant;
+
+class constant_iterator : public std::iterator<std::forward_iterator_tag,
+ const Constant, ptrdiff_t> {
+ const_inst_iterator InstI; // Method instruction iterator
+ unsigned OpIdx; // Operand index
+
+ typedef constant_iterator _Self;
+
+ inline bool isAtConstant() const {
+ assert(!InstI.atEnd() && OpIdx < InstI->getNumOperands() &&
+ "isAtConstant called with invalid arguments!");
+ return isa<Constant>(InstI->getOperand(OpIdx));
+ }
+
+public:
+ inline constant_iterator(const Function *F) : InstI(inst_begin(F)), OpIdx(0) {
+ // Advance to first constant... if we are not already at constant or end
+ if (InstI != inst_end(F) && // InstI is valid?
+ (InstI->getNumOperands() == 0 || !isAtConstant())) // Not at constant?
+ operator++();
+ }
+
+ inline constant_iterator(const Function *F, bool) // end ctor
+ : InstI(inst_end(F)), OpIdx(0) {
+ }
+
+ inline bool operator==(const _Self& x) const { return OpIdx == x.OpIdx &&
+ InstI == x.InstI; }
+ inline bool operator!=(const _Self& x) const { return !operator==(x); }
+
+ inline pointer operator*() const {
+ assert(isAtConstant() && "Dereferenced an iterator at the end!");
+ return cast<Constant>(InstI->getOperand(OpIdx));
+ }
+ inline pointer operator->() const { return operator*(); }
+
+ inline _Self& operator++() { // Preincrement implementation
+ ++OpIdx;
+ do {
+ unsigned NumOperands = InstI->getNumOperands();
+ while (OpIdx < NumOperands && !isAtConstant()) {
+ ++OpIdx;
+ }
+
+ if (OpIdx < NumOperands) return *this; // Found a constant!
+ ++InstI;
+ OpIdx = 0;
+ } while (!InstI.atEnd());
+
+ return *this; // At the end of the method
+ }
+
+ inline _Self operator++(int) { // Postincrement
+ _Self tmp = *this; ++*this; return tmp;
+ }
+
+ inline bool atEnd() const { return InstI.atEnd(); }
+};
+
+inline constant_iterator constant_begin(const Function *F) {
+ return constant_iterator(F);
+}
+
+inline constant_iterator constant_end(const Function *F) {
+ return constant_iterator(F, true);
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/DOTGraphTraitsPass.h b/include/llvm/Analysis/DOTGraphTraitsPass.h
new file mode 100644
index 00000000000..b701b8fca5d
--- /dev/null
+++ b/include/llvm/Analysis/DOTGraphTraitsPass.h
@@ -0,0 +1,83 @@
+//===-- DOTGraphTraitsPass.h - Print/View dotty graphs-----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Templates to create dotty viewer and printer passes for GraphTraits graphs.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_DOT_GRAPHTRAITS_PASS_H
+#define LLVM_ANALYSIS_DOT_GRAPHTRAITS_PASS_H
+
+#include "llvm/Pass.h"
+#include "llvm/Analysis/CFGPrinter.h"
+
+namespace llvm {
+template <class Analysis, bool Simple>
+struct DOTGraphTraitsViewer : public FunctionPass {
+ std::string Name;
+
+ DOTGraphTraitsViewer(std::string GraphName, char &ID) : FunctionPass(ID) {
+ Name = GraphName;
+ }
+
+ virtual bool runOnFunction(Function &F) {
+ Analysis *Graph;
+ std::string Title, GraphName;
+ Graph = &getAnalysis<Analysis>();
+ GraphName = DOTGraphTraits<Analysis*>::getGraphName(Graph);
+ Title = GraphName + " for '" + F.getName().str() + "' function";
+ ViewGraph(Graph, Name, Simple, Title);
+
+ return false;
+ }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ AU.addRequired<Analysis>();
+ }
+};
+
+template <class Analysis, bool Simple>
+struct DOTGraphTraitsPrinter : public FunctionPass {
+
+ std::string Name;
+
+ DOTGraphTraitsPrinter(std::string GraphName, char &ID)
+ : FunctionPass(ID) {
+ Name = GraphName;
+ }
+
+ virtual bool runOnFunction(Function &F) {
+ Analysis *Graph;
+ std::string Filename = Name + "." + F.getName().str() + ".dot";
+ errs() << "Writing '" << Filename << "'...";
+
+ std::string ErrorInfo;
+ raw_fd_ostream File(Filename.c_str(), ErrorInfo);
+ Graph = &getAnalysis<Analysis>();
+
+ std::string Title, GraphName;
+ GraphName = DOTGraphTraits<Analysis*>::getGraphName(Graph);
+ Title = GraphName + " for '" + F.getName().str() + "' function";
+
+ if (ErrorInfo.empty())
+ WriteGraph(File, Graph, Simple, Title);
+ else
+ errs() << " error opening file for writing!";
+ errs() << "\n";
+ return false;
+ }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ AU.addRequired<Analysis>();
+ }
+};
+}
+#endif
diff --git a/include/llvm/Analysis/DomPrinter.h b/include/llvm/Analysis/DomPrinter.h
new file mode 100644
index 00000000000..0ed28994995
--- /dev/null
+++ b/include/llvm/Analysis/DomPrinter.h
@@ -0,0 +1,30 @@
+//===-- DomPrinter.h - Dom printer external interface ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines external functions that can be called to explicitly
+// instantiate the dominance tree printer.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_DOMPRINTER_H
+#define LLVM_ANALYSIS_DOMPRINTER_H
+
+namespace llvm {
+ class FunctionPass;
+ FunctionPass *createDomPrinterPass();
+ FunctionPass *createDomOnlyPrinterPass();
+ FunctionPass *createDomViewerPass();
+ FunctionPass *createDomOnlyViewerPass();
+ FunctionPass *createPostDomPrinterPass();
+ FunctionPass *createPostDomOnlyPrinterPass();
+ FunctionPass *createPostDomViewerPass();
+ FunctionPass *createPostDomOnlyViewerPass();
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/DominanceFrontier.h b/include/llvm/Analysis/DominanceFrontier.h
new file mode 100644
index 00000000000..a2e0675e92b
--- /dev/null
+++ b/include/llvm/Analysis/DominanceFrontier.h
@@ -0,0 +1,190 @@
+//===- llvm/Analysis/DominanceFrontier.h - Dominator Frontiers --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the DominanceFrontier class, which calculate and holds the
+// dominance frontier for a function.
+//
+// This should be considered deprecated, don't add any more uses of this data
+// structure.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_DOMINANCEFRONTIER_H
+#define LLVM_ANALYSIS_DOMINANCEFRONTIER_H
+
+#include "llvm/Analysis/Dominators.h"
+#include <map>
+#include <set>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+/// DominanceFrontierBase - Common base class for computing forward and inverse
+/// dominance frontiers for a function.
+///
+class DominanceFrontierBase : public FunctionPass {
+public:
+ typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
+ typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
+protected:
+ DomSetMapType Frontiers;
+ std::vector<BasicBlock*> Roots;
+ const bool IsPostDominators;
+
+public:
+ DominanceFrontierBase(char &ID, bool isPostDom)
+ : FunctionPass(ID), IsPostDominators(isPostDom) {}
+
+ /// getRoots - Return the root blocks of the current CFG. This may include
+ /// multiple blocks if we are computing post dominators. For forward
+ /// dominators, this will always be a single block (the entry node).
+ ///
+ inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
+
+ /// isPostDominator - Returns true if analysis based of postdoms
+ ///
+ bool isPostDominator() const { return IsPostDominators; }
+
+ virtual void releaseMemory() { Frontiers.clear(); }
+
+ // Accessor interface:
+ typedef DomSetMapType::iterator iterator;
+ typedef DomSetMapType::const_iterator const_iterator;
+ iterator begin() { return Frontiers.begin(); }
+ const_iterator begin() const { return Frontiers.begin(); }
+ iterator end() { return Frontiers.end(); }
+ const_iterator end() const { return Frontiers.end(); }
+ iterator find(BasicBlock *B) { return Frontiers.find(B); }
+ const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
+
+ iterator addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
+ assert(find(BB) == end() && "Block already in DominanceFrontier!");
+ return Frontiers.insert(std::make_pair(BB, frontier)).first;
+ }
+
+ /// removeBlock - Remove basic block BB's frontier.
+ void removeBlock(BasicBlock *BB) {
+ assert(find(BB) != end() && "Block is not in DominanceFrontier!");
+ for (iterator I = begin(), E = end(); I != E; ++I)
+ I->second.erase(BB);
+ Frontiers.erase(BB);
+ }
+
+ void addToFrontier(iterator I, BasicBlock *Node) {
+ assert(I != end() && "BB is not in DominanceFrontier!");
+ I->second.insert(Node);
+ }
+
+ void removeFromFrontier(iterator I, BasicBlock *Node) {
+ assert(I != end() && "BB is not in DominanceFrontier!");
+ assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
+ I->second.erase(Node);
+ }
+
+ /// compareDomSet - Return false if two domsets match. Otherwise
+ /// return true;
+ bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
+ std::set<BasicBlock *> tmpSet;
+ for (DomSetType::const_iterator I = DS2.begin(),
+ E = DS2.end(); I != E; ++I)
+ tmpSet.insert(*I);
+
+ for (DomSetType::const_iterator I = DS1.begin(),
+ E = DS1.end(); I != E; ) {
+ BasicBlock *Node = *I++;
+
+ if (tmpSet.erase(Node) == 0)
+ // Node is in DS1 but not in DS2.
+ return true;
+ }
+
+ if (!tmpSet.empty())
+ // There are nodes that are in DS2 but not in DS1.
+ return true;
+
+ // DS1 and DS2 matches.
+ return false;
+ }
+
+ /// compare - Return true if the other dominance frontier base matches
+ /// this dominance frontier base. Otherwise return false.
+ bool compare(DominanceFrontierBase &Other) const {
+ DomSetMapType tmpFrontiers;
+ for (DomSetMapType::const_iterator I = Other.begin(),
+ E = Other.end(); I != E; ++I)
+ tmpFrontiers.insert(std::make_pair(I->first, I->second));
+
+ for (DomSetMapType::iterator I = tmpFrontiers.begin(),
+ E = tmpFrontiers.end(); I != E; ) {
+ BasicBlock *Node = I->first;
+ const_iterator DFI = find(Node);
+ if (DFI == end())
+ return true;
+
+ if (compareDomSet(I->second, DFI->second))
+ return true;
+
+ ++I;
+ tmpFrontiers.erase(Node);
+ }
+
+ if (!tmpFrontiers.empty())
+ return true;
+
+ return false;
+ }
+
+ /// print - Convert to human readable form
+ ///
+ virtual void print(raw_ostream &OS, const Module* = 0) const;
+
+ /// dump - Dump the dominance frontier to dbgs().
+ void dump() const;
+};
+
+
+//===-------------------------------------
+/// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
+/// used to compute a forward dominator frontiers.
+///
+class DominanceFrontier : public DominanceFrontierBase {
+ virtual void anchor();
+public:
+ static char ID; // Pass ID, replacement for typeid
+ DominanceFrontier() :
+ DominanceFrontierBase(ID, false) {
+ initializeDominanceFrontierPass(*PassRegistry::getPassRegistry());
+ }
+
+ BasicBlock *getRoot() const {
+ assert(Roots.size() == 1 && "Should always have entry node!");
+ return Roots[0];
+ }
+
+ virtual bool runOnFunction(Function &) {
+ Frontiers.clear();
+ DominatorTree &DT = getAnalysis<DominatorTree>();
+ Roots = DT.getRoots();
+ assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
+ calculate(DT, DT[Roots[0]]);
+ return false;
+ }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ AU.addRequired<DominatorTree>();
+ }
+
+ const DomSetType &calculate(const DominatorTree &DT,
+ const DomTreeNode *Node);
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/DominatorInternals.h b/include/llvm/Analysis/DominatorInternals.h
new file mode 100644
index 00000000000..0c29236dde9
--- /dev/null
+++ b/include/llvm/Analysis/DominatorInternals.h
@@ -0,0 +1,289 @@
+//=== llvm/Analysis/DominatorInternals.h - Dominator Calculation -*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_DOMINATOR_INTERNALS_H
+#define LLVM_ANALYSIS_DOMINATOR_INTERNALS_H
+
+#include "llvm/Analysis/Dominators.h"
+#include "llvm/ADT/SmallPtrSet.h"
+
+//===----------------------------------------------------------------------===//
+//
+// DominatorTree construction - This pass constructs immediate dominator
+// information for a flow-graph based on the algorithm described in this
+// document:
+//
+// A Fast Algorithm for Finding Dominators in a Flowgraph
+// T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
+//
+// This implements the O(n*log(n)) versions of EVAL and LINK, because it turns
+// out that the theoretically slower O(n*log(n)) implementation is actually
+// faster than the almost-linear O(n*alpha(n)) version, even for large CFGs.
+//
+//===----------------------------------------------------------------------===//
+
+namespace llvm {
+
+template<class GraphT>
+unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
+ typename GraphT::NodeType* V, unsigned N) {
+ // This is more understandable as a recursive algorithm, but we can't use the
+ // recursive algorithm due to stack depth issues. Keep it here for
+ // documentation purposes.
+#if 0
+ InfoRec &VInfo = DT.Info[DT.Roots[i]];
+ VInfo.DFSNum = VInfo.Semi = ++N;
+ VInfo.Label = V;
+
+ Vertex.push_back(V); // Vertex[n] = V;
+
+ for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
+ InfoRec &SuccVInfo = DT.Info[*SI];
+ if (SuccVInfo.Semi == 0) {
+ SuccVInfo.Parent = V;
+ N = DTDFSPass(DT, *SI, N);
+ }
+ }
+#else
+ bool IsChildOfArtificialExit = (N != 0);
+
+ SmallVector<std::pair<typename GraphT::NodeType*,
+ typename GraphT::ChildIteratorType>, 32> Worklist;
+ Worklist.push_back(std::make_pair(V, GraphT::child_begin(V)));
+ while (!Worklist.empty()) {
+ typename GraphT::NodeType* BB = Worklist.back().first;
+ typename GraphT::ChildIteratorType NextSucc = Worklist.back().second;
+
+ typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
+ DT.Info[BB];
+
+ // First time we visited this BB?
+ if (NextSucc == GraphT::child_begin(BB)) {
+ BBInfo.DFSNum = BBInfo.Semi = ++N;
+ BBInfo.Label = BB;
+
+ DT.Vertex.push_back(BB); // Vertex[n] = V;
+
+ if (IsChildOfArtificialExit)
+ BBInfo.Parent = 1;
+
+ IsChildOfArtificialExit = false;
+ }
+
+ // store the DFS number of the current BB - the reference to BBInfo might
+ // get invalidated when processing the successors.
+ unsigned BBDFSNum = BBInfo.DFSNum;
+
+ // If we are done with this block, remove it from the worklist.
+ if (NextSucc == GraphT::child_end(BB)) {
+ Worklist.pop_back();
+ continue;
+ }
+
+ // Increment the successor number for the next time we get to it.
+ ++Worklist.back().second;
+
+ // Visit the successor next, if it isn't already visited.
+ typename GraphT::NodeType* Succ = *NextSucc;
+
+ typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &SuccVInfo =
+ DT.Info[Succ];
+ if (SuccVInfo.Semi == 0) {
+ SuccVInfo.Parent = BBDFSNum;
+ Worklist.push_back(std::make_pair(Succ, GraphT::child_begin(Succ)));
+ }
+ }
+#endif
+ return N;
+}
+
+template<class GraphT>
+typename GraphT::NodeType*
+Eval(DominatorTreeBase<typename GraphT::NodeType>& DT,
+ typename GraphT::NodeType *VIn, unsigned LastLinked) {
+ typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInInfo =
+ DT.Info[VIn];
+ if (VInInfo.DFSNum < LastLinked)
+ return VIn;
+
+ SmallVector<typename GraphT::NodeType*, 32> Work;
+ SmallPtrSet<typename GraphT::NodeType*, 32> Visited;
+
+ if (VInInfo.Parent >= LastLinked)
+ Work.push_back(VIn);
+
+ while (!Work.empty()) {
+ typename GraphT::NodeType* V = Work.back();
+ typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInfo =
+ DT.Info[V];
+ typename GraphT::NodeType* VAncestor = DT.Vertex[VInfo.Parent];
+
+ // Process Ancestor first
+ if (Visited.insert(VAncestor) && VInfo.Parent >= LastLinked) {
+ Work.push_back(VAncestor);
+ continue;
+ }
+ Work.pop_back();
+
+ // Update VInfo based on Ancestor info
+ if (VInfo.Parent < LastLinked)
+ continue;
+
+ typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VAInfo =
+ DT.Info[VAncestor];
+ typename GraphT::NodeType* VAncestorLabel = VAInfo.Label;
+ typename GraphT::NodeType* VLabel = VInfo.Label;
+ if (DT.Info[VAncestorLabel].Semi < DT.Info[VLabel].Semi)
+ VInfo.Label = VAncestorLabel;
+ VInfo.Parent = VAInfo.Parent;
+ }
+
+ return VInInfo.Label;
+}
+
+template<class FuncT, class NodeT>
+void Calculate(DominatorTreeBase<typename GraphTraits<NodeT>::NodeType>& DT,
+ FuncT& F) {
+ typedef GraphTraits<NodeT> GraphT;
+
+ unsigned N = 0;
+ bool MultipleRoots = (DT.Roots.size() > 1);
+ if (MultipleRoots) {
+ typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
+ DT.Info[NULL];
+ BBInfo.DFSNum = BBInfo.Semi = ++N;
+ BBInfo.Label = NULL;
+
+ DT.Vertex.push_back(NULL); // Vertex[n] = V;
+ }
+
+ // Step #1: Number blocks in depth-first order and initialize variables used
+ // in later stages of the algorithm.
+ for (unsigned i = 0, e = static_cast<unsigned>(DT.Roots.size());
+ i != e; ++i)
+ N = DFSPass<GraphT>(DT, DT.Roots[i], N);
+
+ // it might be that some blocks did not get a DFS number (e.g., blocks of
+ // infinite loops). In these cases an artificial exit node is required.
+ MultipleRoots |= (DT.isPostDominator() && N != GraphTraits<FuncT*>::size(&F));
+
+ // When naively implemented, the Lengauer-Tarjan algorithm requires a separate
+ // bucket for each vertex. However, this is unnecessary, because each vertex
+ // is only placed into a single bucket (that of its semidominator), and each
+ // vertex's bucket is processed before it is added to any bucket itself.
+ //
+ // Instead of using a bucket per vertex, we use a single array Buckets that
+ // has two purposes. Before the vertex V with preorder number i is processed,
+ // Buckets[i] stores the index of the first element in V's bucket. After V's
+ // bucket is processed, Buckets[i] stores the index of the next element in the
+ // bucket containing V, if any.
+ SmallVector<unsigned, 32> Buckets;
+ Buckets.resize(N + 1);
+ for (unsigned i = 1; i <= N; ++i)
+ Buckets[i] = i;
+
+ for (unsigned i = N; i >= 2; --i) {
+ typename GraphT::NodeType* W = DT.Vertex[i];
+ typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo =
+ DT.Info[W];
+
+ // Step #2: Implicitly define the immediate dominator of vertices
+ for (unsigned j = i; Buckets[j] != i; j = Buckets[j]) {
+ typename GraphT::NodeType* V = DT.Vertex[Buckets[j]];
+ typename GraphT::NodeType* U = Eval<GraphT>(DT, V, i + 1);
+ DT.IDoms[V] = DT.Info[U].Semi < i ? U : W;
+ }
+
+ // Step #3: Calculate the semidominators of all vertices
+
+ // initialize the semi dominator to point to the parent node
+ WInfo.Semi = WInfo.Parent;
+ typedef GraphTraits<Inverse<NodeT> > InvTraits;
+ for (typename InvTraits::ChildIteratorType CI =
+ InvTraits::child_begin(W),
+ E = InvTraits::child_end(W); CI != E; ++CI) {
+ typename InvTraits::NodeType *N = *CI;
+ if (DT.Info.count(N)) { // Only if this predecessor is reachable!
+ unsigned SemiU = DT.Info[Eval<GraphT>(DT, N, i + 1)].Semi;
+ if (SemiU < WInfo.Semi)
+ WInfo.Semi = SemiU;
+ }
+ }
+
+ // If V is a non-root vertex and sdom(V) = parent(V), then idom(V) is
+ // necessarily parent(V). In this case, set idom(V) here and avoid placing
+ // V into a bucket.
+ if (WInfo.Semi == WInfo.Parent) {
+ DT.IDoms[W] = DT.Vertex[WInfo.Parent];
+ } else {
+ Buckets[i] = Buckets[WInfo.Semi];
+ Buckets[WInfo.Semi] = i;
+ }
+ }
+
+ if (N >= 1) {
+ typename GraphT::NodeType* Root = DT.Vertex[1];
+ for (unsigned j = 1; Buckets[j] != 1; j = Buckets[j]) {
+ typename GraphT::NodeType* V = DT.Vertex[Buckets[j]];
+ DT.IDoms[V] = Root;
+ }
+ }
+
+ // Step #4: Explicitly define the immediate dominator of each vertex
+ for (unsigned i = 2; i <= N; ++i) {
+ typename GraphT::NodeType* W = DT.Vertex[i];
+ typename GraphT::NodeType*& WIDom = DT.IDoms[W];
+ if (WIDom != DT.Vertex[DT.Info[W].Semi])
+ WIDom = DT.IDoms[WIDom];
+ }
+
+ if (DT.Roots.empty()) return;
+
+ // Add a node for the root. This node might be the actual root, if there is
+ // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
+ // which postdominates all real exits if there are multiple exit blocks, or
+ // an infinite loop.
+ typename GraphT::NodeType* Root = !MultipleRoots ? DT.Roots[0] : 0;
+
+ DT.DomTreeNodes[Root] = DT.RootNode =
+ new DomTreeNodeBase<typename GraphT::NodeType>(Root, 0);
+
+ // Loop over all of the reachable blocks in the function...
+ for (unsigned i = 2; i <= N; ++i) {
+ typename GraphT::NodeType* W = DT.Vertex[i];
+
+ DomTreeNodeBase<typename GraphT::NodeType> *BBNode = DT.DomTreeNodes[W];
+ if (BBNode) continue; // Haven't calculated this node yet?
+
+ typename GraphT::NodeType* ImmDom = DT.getIDom(W);
+
+ assert(ImmDom || DT.DomTreeNodes[NULL]);
+
+ // Get or calculate the node for the immediate dominator
+ DomTreeNodeBase<typename GraphT::NodeType> *IDomNode =
+ DT.getNodeForBlock(ImmDom);
+
+ // Add a new tree node for this BasicBlock, and link it as a child of
+ // IDomNode
+ DomTreeNodeBase<typename GraphT::NodeType> *C =
+ new DomTreeNodeBase<typename GraphT::NodeType>(W, IDomNode);
+ DT.DomTreeNodes[W] = IDomNode->addChild(C);
+ }
+
+ // Free temporary memory used to construct idom's
+ DT.IDoms.clear();
+ DT.Info.clear();
+ std::vector<typename GraphT::NodeType*>().swap(DT.Vertex);
+
+ DT.updateDFSNumbers();
+}
+
+}
+
+#endif
diff --git a/include/llvm/Analysis/Dominators.h b/include/llvm/Analysis/Dominators.h
new file mode 100644
index 00000000000..a1cc196eae3
--- /dev/null
+++ b/include/llvm/Analysis/Dominators.h
@@ -0,0 +1,921 @@
+//===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the DominatorTree class, which provides fast and efficient
+// dominance queries.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_DOMINATORS_H
+#define LLVM_ANALYSIS_DOMINATORS_H
+
+#include "llvm/Pass.h"
+#include "llvm/Function.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DepthFirstIterator.h"
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/CFG.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/raw_ostream.h"
+#include <algorithm>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+/// DominatorBase - Base class that other, more interesting dominator analyses
+/// inherit from.
+///
+template <class NodeT>
+class DominatorBase {
+protected:
+ std::vector<NodeT*> Roots;
+ const bool IsPostDominators;
+ inline explicit DominatorBase(bool isPostDom) :
+ Roots(), IsPostDominators(isPostDom) {}
+public:
+
+ /// getRoots - Return the root blocks of the current CFG. This may include
+ /// multiple blocks if we are computing post dominators. For forward
+ /// dominators, this will always be a single block (the entry node).
+ ///
+ inline const std::vector<NodeT*> &getRoots() const { return Roots; }
+
+ /// isPostDominator - Returns true if analysis based of postdoms
+ ///
+ bool isPostDominator() const { return IsPostDominators; }
+};
+
+
+//===----------------------------------------------------------------------===//
+// DomTreeNode - Dominator Tree Node
+template<class NodeT> class DominatorTreeBase;
+struct PostDominatorTree;
+class MachineBasicBlock;
+
+template <class NodeT>
+class DomTreeNodeBase {
+ NodeT *TheBB;
+ DomTreeNodeBase<NodeT> *IDom;
+ std::vector<DomTreeNodeBase<NodeT> *> Children;
+ int DFSNumIn, DFSNumOut;
+
+ template<class N> friend class DominatorTreeBase;
+ friend struct PostDominatorTree;
+public:
+ typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
+ typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
+ const_iterator;
+
+ iterator begin() { return Children.begin(); }
+ iterator end() { return Children.end(); }
+ const_iterator begin() const { return Children.begin(); }
+ const_iterator end() const { return Children.end(); }
+
+ NodeT *getBlock() const { return TheBB; }
+ DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
+ const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
+ return Children;
+ }
+
+ DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
+ : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
+
+ DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
+ Children.push_back(C);
+ return C;
+ }
+
+ size_t getNumChildren() const {
+ return Children.size();
+ }
+
+ void clearAllChildren() {
+ Children.clear();
+ }
+
+ bool compare(DomTreeNodeBase<NodeT> *Other) {
+ if (getNumChildren() != Other->getNumChildren())
+ return true;
+
+ SmallPtrSet<NodeT *, 4> OtherChildren;
+ for (iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
+ NodeT *Nd = (*I)->getBlock();
+ OtherChildren.insert(Nd);
+ }
+
+ for (iterator I = begin(), E = end(); I != E; ++I) {
+ NodeT *N = (*I)->getBlock();
+ if (OtherChildren.count(N) == 0)
+ return true;
+ }
+ return false;
+ }
+
+ void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
+ assert(IDom && "No immediate dominator?");
+ if (IDom != NewIDom) {
+ typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
+ std::find(IDom->Children.begin(), IDom->Children.end(), this);
+ assert(I != IDom->Children.end() &&
+ "Not in immediate dominator children set!");
+ // I am no longer your child...
+ IDom->Children.erase(I);
+
+ // Switch to new dominator
+ IDom = NewIDom;
+ IDom->Children.push_back(this);
+ }
+ }
+
+ /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
+ /// not call them.
+ unsigned getDFSNumIn() const { return DFSNumIn; }
+ unsigned getDFSNumOut() const { return DFSNumOut; }
+private:
+ // Return true if this node is dominated by other. Use this only if DFS info
+ // is valid.
+ bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
+ return this->DFSNumIn >= other->DFSNumIn &&
+ this->DFSNumOut <= other->DFSNumOut;
+ }
+};
+
+EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
+EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
+
+template<class NodeT>
+inline raw_ostream &operator<<(raw_ostream &o,
+ const DomTreeNodeBase<NodeT> *Node) {
+ if (Node->getBlock())
+ WriteAsOperand(o, Node->getBlock(), false);
+ else
+ o << " <<exit node>>";
+
+ o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
+
+ return o << "\n";
+}
+
+template<class NodeT>
+inline void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
+ unsigned Lev) {
+ o.indent(2*Lev) << "[" << Lev << "] " << N;
+ for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
+ E = N->end(); I != E; ++I)
+ PrintDomTree<NodeT>(*I, o, Lev+1);
+}
+
+typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
+
+//===----------------------------------------------------------------------===//
+/// DominatorTree - Calculate the immediate dominator tree for a function.
+///
+
+template<class FuncT, class N>
+void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
+ FuncT& F);
+
+template<class NodeT>
+class DominatorTreeBase : public DominatorBase<NodeT> {
+ bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
+ const DomTreeNodeBase<NodeT> *B) const {
+ assert(A != B);
+ assert(isReachableFromEntry(B));
+ assert(isReachableFromEntry(A));
+
+ const DomTreeNodeBase<NodeT> *IDom;
+ while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
+ B = IDom; // Walk up the tree
+ return IDom != 0;
+ }
+
+protected:
+ typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
+ DomTreeNodeMapType DomTreeNodes;
+ DomTreeNodeBase<NodeT> *RootNode;
+
+ bool DFSInfoValid;
+ unsigned int SlowQueries;
+ // Information record used during immediate dominators computation.
+ struct InfoRec {
+ unsigned DFSNum;
+ unsigned Parent;
+ unsigned Semi;
+ NodeT *Label;
+
+ InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(0) {}
+ };
+
+ DenseMap<NodeT*, NodeT*> IDoms;
+
+ // Vertex - Map the DFS number to the BasicBlock*
+ std::vector<NodeT*> Vertex;
+
+ // Info - Collection of information used during the computation of idoms.
+ DenseMap<NodeT*, InfoRec> Info;
+
+ void reset() {
+ for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
+ E = DomTreeNodes.end(); I != E; ++I)
+ delete I->second;
+ DomTreeNodes.clear();
+ IDoms.clear();
+ this->Roots.clear();
+ Vertex.clear();
+ RootNode = 0;
+ }
+
+ // NewBB is split and now it has one successor. Update dominator tree to
+ // reflect this change.
+ template<class N, class GraphT>
+ void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
+ typename GraphT::NodeType* NewBB) {
+ assert(std::distance(GraphT::child_begin(NewBB),
+ GraphT::child_end(NewBB)) == 1 &&
+ "NewBB should have a single successor!");
+ typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
+
+ std::vector<typename GraphT::NodeType*> PredBlocks;
+ typedef GraphTraits<Inverse<N> > InvTraits;
+ for (typename InvTraits::ChildIteratorType PI =
+ InvTraits::child_begin(NewBB),
+ PE = InvTraits::child_end(NewBB); PI != PE; ++PI)
+ PredBlocks.push_back(*PI);
+
+ assert(!PredBlocks.empty() && "No predblocks?");
+
+ bool NewBBDominatesNewBBSucc = true;
+ for (typename InvTraits::ChildIteratorType PI =
+ InvTraits::child_begin(NewBBSucc),
+ E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
+ typename InvTraits::NodeType *ND = *PI;
+ if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
+ DT.isReachableFromEntry(ND)) {
+ NewBBDominatesNewBBSucc = false;
+ break;
+ }
+ }
+
+ // Find NewBB's immediate dominator and create new dominator tree node for
+ // NewBB.
+ NodeT *NewBBIDom = 0;
+ unsigned i = 0;
+ for (i = 0; i < PredBlocks.size(); ++i)
+ if (DT.isReachableFromEntry(PredBlocks[i])) {
+ NewBBIDom = PredBlocks[i];
+ break;
+ }
+
+ // It's possible that none of the predecessors of NewBB are reachable;
+ // in that case, NewBB itself is unreachable, so nothing needs to be
+ // changed.
+ if (!NewBBIDom)
+ return;
+
+ for (i = i + 1; i < PredBlocks.size(); ++i) {
+ if (DT.isReachableFromEntry(PredBlocks[i]))
+ NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
+ }
+
+ // Create the new dominator tree node... and set the idom of NewBB.
+ DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
+
+ // If NewBB strictly dominates other blocks, then it is now the immediate
+ // dominator of NewBBSucc. Update the dominator tree as appropriate.
+ if (NewBBDominatesNewBBSucc) {
+ DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
+ DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
+ }
+ }
+
+public:
+ explicit DominatorTreeBase(bool isPostDom)
+ : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
+ virtual ~DominatorTreeBase() { reset(); }
+
+ /// compare - Return false if the other dominator tree base matches this
+ /// dominator tree base. Otherwise return true.
+ bool compare(DominatorTreeBase &Other) const {
+
+ const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
+ if (DomTreeNodes.size() != OtherDomTreeNodes.size())
+ return true;
+
+ for (typename DomTreeNodeMapType::const_iterator
+ I = this->DomTreeNodes.begin(),
+ E = this->DomTreeNodes.end(); I != E; ++I) {
+ NodeT *BB = I->first;
+ typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
+ if (OI == OtherDomTreeNodes.end())
+ return true;
+
+ DomTreeNodeBase<NodeT>* MyNd = I->second;
+ DomTreeNodeBase<NodeT>* OtherNd = OI->second;
+
+ if (MyNd->compare(OtherNd))
+ return true;
+ }
+
+ return false;
+ }
+
+ virtual void releaseMemory() { reset(); }
+
+ /// getNode - return the (Post)DominatorTree node for the specified basic
+ /// block. This is the same as using operator[] on this class.
+ ///
+ inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
+ return DomTreeNodes.lookup(BB);
+ }
+
+ /// getRootNode - This returns the entry node for the CFG of the function. If
+ /// this tree represents the post-dominance relations for a function, however,
+ /// this root may be a node with the block == NULL. This is the case when
+ /// there are multiple exit nodes from a particular function. Consumers of
+ /// post-dominance information must be capable of dealing with this
+ /// possibility.
+ ///
+ DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
+ const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
+
+ /// properlyDominates - Returns true iff this dominates N and this != N.
+ /// Note that this is not a constant time operation!
+ ///
+ bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
+ const DomTreeNodeBase<NodeT> *B) {
+ if (A == 0 || B == 0)
+ return false;
+ if (A == B)
+ return false;
+ return dominates(A, B);
+ }
+
+ bool properlyDominates(const NodeT *A, const NodeT *B);
+
+ /// isReachableFromEntry - Return true if A is dominated by the entry
+ /// block of the function containing it.
+ bool isReachableFromEntry(const NodeT* A) const {
+ assert(!this->isPostDominator() &&
+ "This is not implemented for post dominators");
+ return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
+ }
+
+ inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
+ return A;
+ }
+
+ /// dominates - Returns true iff A dominates B. Note that this is not a
+ /// constant time operation!
+ ///
+ inline bool dominates(const DomTreeNodeBase<NodeT> *A,
+ const DomTreeNodeBase<NodeT> *B) {
+ // A node trivially dominates itself.
+ if (B == A)
+ return true;
+
+ // An unreachable node is dominated by anything.
+ if (!isReachableFromEntry(B))
+ return true;
+
+ // And dominates nothing.
+ if (!isReachableFromEntry(A))
+ return false;
+
+ // Compare the result of the tree walk and the dfs numbers, if expensive
+ // checks are enabled.
+#ifdef XDEBUG
+ assert((!DFSInfoValid ||
+ (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
+ "Tree walk disagrees with dfs numbers!");
+#endif
+
+ if (DFSInfoValid)
+ return B->DominatedBy(A);
+
+ // If we end up with too many slow queries, just update the
+ // DFS numbers on the theory that we are going to keep querying.
+ SlowQueries++;
+ if (SlowQueries > 32) {
+ updateDFSNumbers();
+ return B->DominatedBy(A);
+ }
+
+ return dominatedBySlowTreeWalk(A, B);
+ }
+
+ bool dominates(const NodeT *A, const NodeT *B);
+
+ NodeT *getRoot() const {
+ assert(this->Roots.size() == 1 && "Should always have entry node!");
+ return this->Roots[0];
+ }
+
+ /// findNearestCommonDominator - Find nearest common dominator basic block
+ /// for basic block A and B. If there is no such block then return NULL.
+ NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
+ assert(A->getParent() == B->getParent() &&
+ "Two blocks are not in same function");
+
+ // If either A or B is a entry block then it is nearest common dominator
+ // (for forward-dominators).
+ if (!this->isPostDominator()) {
+ NodeT &Entry = A->getParent()->front();
+ if (A == &Entry || B == &Entry)
+ return &Entry;
+ }
+
+ // If B dominates A then B is nearest common dominator.
+ if (dominates(B, A))
+ return B;
+
+ // If A dominates B then A is nearest common dominator.
+ if (dominates(A, B))
+ return A;
+
+ DomTreeNodeBase<NodeT> *NodeA = getNode(A);
+ DomTreeNodeBase<NodeT> *NodeB = getNode(B);
+
+ // Collect NodeA dominators set.
+ SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
+ NodeADoms.insert(NodeA);
+ DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
+ while (IDomA) {
+ NodeADoms.insert(IDomA);
+ IDomA = IDomA->getIDom();
+ }
+
+ // Walk NodeB immediate dominators chain and find common dominator node.
+ DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
+ while (IDomB) {
+ if (NodeADoms.count(IDomB) != 0)
+ return IDomB->getBlock();
+
+ IDomB = IDomB->getIDom();
+ }
+
+ return NULL;
+ }
+
+ const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
+ // Cast away the const qualifiers here. This is ok since
+ // const is re-introduced on the return type.
+ return findNearestCommonDominator(const_cast<NodeT *>(A),
+ const_cast<NodeT *>(B));
+ }
+
+ //===--------------------------------------------------------------------===//
+ // API to update (Post)DominatorTree information based on modifications to
+ // the CFG...
+
+ /// addNewBlock - Add a new node to the dominator tree information. This
+ /// creates a new node as a child of DomBB dominator node,linking it into
+ /// the children list of the immediate dominator.
+ DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
+ assert(getNode(BB) == 0 && "Block already in dominator tree!");
+ DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
+ assert(IDomNode && "Not immediate dominator specified for block!");
+ DFSInfoValid = false;
+ return DomTreeNodes[BB] =
+ IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
+ }
+
+ /// changeImmediateDominator - This method is used to update the dominator
+ /// tree information when a node's immediate dominator changes.
+ ///
+ void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
+ DomTreeNodeBase<NodeT> *NewIDom) {
+ assert(N && NewIDom && "Cannot change null node pointers!");
+ DFSInfoValid = false;
+ N->setIDom(NewIDom);
+ }
+
+ void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
+ changeImmediateDominator(getNode(BB), getNode(NewBB));
+ }
+
+ /// eraseNode - Removes a node from the dominator tree. Block must not
+ /// dominate any other blocks. Removes node from its immediate dominator's
+ /// children list. Deletes dominator node associated with basic block BB.
+ void eraseNode(NodeT *BB) {
+ DomTreeNodeBase<NodeT> *Node = getNode(BB);
+ assert(Node && "Removing node that isn't in dominator tree.");
+ assert(Node->getChildren().empty() && "Node is not a leaf node.");
+
+ // Remove node from immediate dominator's children list.
+ DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
+ if (IDom) {
+ typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
+ std::find(IDom->Children.begin(), IDom->Children.end(), Node);
+ assert(I != IDom->Children.end() &&
+ "Not in immediate dominator children set!");
+ // I am no longer your child...
+ IDom->Children.erase(I);
+ }
+
+ DomTreeNodes.erase(BB);
+ delete Node;
+ }
+
+ /// removeNode - Removes a node from the dominator tree. Block must not
+ /// dominate any other blocks. Invalidates any node pointing to removed
+ /// block.
+ void removeNode(NodeT *BB) {
+ assert(getNode(BB) && "Removing node that isn't in dominator tree.");
+ DomTreeNodes.erase(BB);
+ }
+
+ /// splitBlock - BB is split and now it has one successor. Update dominator
+ /// tree to reflect this change.
+ void splitBlock(NodeT* NewBB) {
+ if (this->IsPostDominators)
+ this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
+ else
+ this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
+ }
+
+ /// print - Convert to human readable form
+ ///
+ void print(raw_ostream &o) const {
+ o << "=============================--------------------------------\n";
+ if (this->isPostDominator())
+ o << "Inorder PostDominator Tree: ";
+ else
+ o << "Inorder Dominator Tree: ";
+ if (!this->DFSInfoValid)
+ o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
+ o << "\n";
+
+ // The postdom tree can have a null root if there are no returns.
+ if (getRootNode())
+ PrintDomTree<NodeT>(getRootNode(), o, 1);
+ }
+
+protected:
+ template<class GraphT>
+ friend typename GraphT::NodeType* Eval(
+ DominatorTreeBase<typename GraphT::NodeType>& DT,
+ typename GraphT::NodeType* V,
+ unsigned LastLinked);
+
+ template<class GraphT>
+ friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
+ typename GraphT::NodeType* V,
+ unsigned N);
+
+ template<class FuncT, class N>
+ friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
+ FuncT& F);
+
+ /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
+ /// dominator tree in dfs order.
+ void updateDFSNumbers() {
+ unsigned DFSNum = 0;
+
+ SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
+ typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
+
+ DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
+
+ if (!ThisRoot)
+ return;
+
+ // Even in the case of multiple exits that form the post dominator root
+ // nodes, do not iterate over all exits, but start from the virtual root
+ // node. Otherwise bbs, that are not post dominated by any exit but by the
+ // virtual root node, will never be assigned a DFS number.
+ WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
+ ThisRoot->DFSNumIn = DFSNum++;
+
+ while (!WorkStack.empty()) {
+ DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
+ typename DomTreeNodeBase<NodeT>::iterator ChildIt =
+ WorkStack.back().second;
+
+ // If we visited all of the children of this node, "recurse" back up the
+ // stack setting the DFOutNum.
+ if (ChildIt == Node->end()) {
+ Node->DFSNumOut = DFSNum++;
+ WorkStack.pop_back();
+ } else {
+ // Otherwise, recursively visit this child.
+ DomTreeNodeBase<NodeT> *Child = *ChildIt;
+ ++WorkStack.back().second;
+
+ WorkStack.push_back(std::make_pair(Child, Child->begin()));
+ Child->DFSNumIn = DFSNum++;
+ }
+ }
+
+ SlowQueries = 0;
+ DFSInfoValid = true;
+ }
+
+ DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
+ if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
+ return Node;
+
+ // Haven't calculated this node yet? Get or calculate the node for the
+ // immediate dominator.
+ NodeT *IDom = getIDom(BB);
+
+ assert(IDom || this->DomTreeNodes[NULL]);
+ DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
+
+ // Add a new tree node for this BasicBlock, and link it as a child of
+ // IDomNode
+ DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
+ return this->DomTreeNodes[BB] = IDomNode->addChild(C);
+ }
+
+ inline NodeT *getIDom(NodeT *BB) const {
+ return IDoms.lookup(BB);
+ }
+
+ inline void addRoot(NodeT* BB) {
+ this->Roots.push_back(BB);
+ }
+
+public:
+ /// recalculate - compute a dominator tree for the given function
+ template<class FT>
+ void recalculate(FT& F) {
+ typedef GraphTraits<FT*> TraitsTy;
+ reset();
+ this->Vertex.push_back(0);
+
+ if (!this->IsPostDominators) {
+ // Initialize root
+ NodeT *entry = TraitsTy::getEntryNode(&F);
+ this->Roots.push_back(entry);
+ this->IDoms[entry] = 0;
+ this->DomTreeNodes[entry] = 0;
+
+ Calculate<FT, NodeT*>(*this, F);
+ } else {
+ // Initialize the roots list
+ for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
+ E = TraitsTy::nodes_end(&F); I != E; ++I) {
+ if (std::distance(TraitsTy::child_begin(I),
+ TraitsTy::child_end(I)) == 0)
+ addRoot(I);
+
+ // Prepopulate maps so that we don't get iterator invalidation issues later.
+ this->IDoms[I] = 0;
+ this->DomTreeNodes[I] = 0;
+ }
+
+ Calculate<FT, Inverse<NodeT*> >(*this, F);
+ }
+ }
+};
+
+// These two functions are declared out of line as a workaround for building
+// with old (< r147295) versions of clang because of pr11642.
+template<class NodeT>
+bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) {
+ if (A == B)
+ return true;
+
+ // Cast away the const qualifiers here. This is ok since
+ // this function doesn't actually return the values returned
+ // from getNode.
+ return dominates(getNode(const_cast<NodeT *>(A)),
+ getNode(const_cast<NodeT *>(B)));
+}
+template<class NodeT>
+bool
+DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A, const NodeT *B) {
+ if (A == B)
+ return false;
+
+ // Cast away the const qualifiers here. This is ok since
+ // this function doesn't actually return the values returned
+ // from getNode.
+ return dominates(getNode(const_cast<NodeT *>(A)),
+ getNode(const_cast<NodeT *>(B)));
+}
+
+EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
+
+class BasicBlockEdge {
+ const BasicBlock *Start;
+ const BasicBlock *End;
+public:
+ BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_) :
+ Start(Start_), End(End_) { }
+ const BasicBlock *getStart() const {
+ return Start;
+ }
+ const BasicBlock *getEnd() const {
+ return End;
+ }
+ bool isSingleEdge() const;
+};
+
+//===-------------------------------------
+/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
+/// compute a normal dominator tree.
+///
+class DominatorTree : public FunctionPass {
+public:
+ static char ID; // Pass ID, replacement for typeid
+ DominatorTreeBase<BasicBlock>* DT;
+
+ DominatorTree() : FunctionPass(ID) {
+ initializeDominatorTreePass(*PassRegistry::getPassRegistry());
+ DT = new DominatorTreeBase<BasicBlock>(false);
+ }
+
+ ~DominatorTree() {
+ delete DT;
+ }
+
+ DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
+
+ /// getRoots - Return the root blocks of the current CFG. This may include
+ /// multiple blocks if we are computing post dominators. For forward
+ /// dominators, this will always be a single block (the entry node).
+ ///
+ inline const std::vector<BasicBlock*> &getRoots() const {
+ return DT->getRoots();
+ }
+
+ inline BasicBlock *getRoot() const {
+ return DT->getRoot();
+ }
+
+ inline DomTreeNode *getRootNode() const {
+ return DT->getRootNode();
+ }
+
+ /// compare - Return false if the other dominator tree matches this
+ /// dominator tree. Otherwise return true.
+ inline bool compare(DominatorTree &Other) const {
+ DomTreeNode *R = getRootNode();
+ DomTreeNode *OtherR = Other.getRootNode();
+
+ if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
+ return true;
+
+ if (DT->compare(Other.getBase()))
+ return true;
+
+ return false;
+ }
+
+ virtual bool runOnFunction(Function &F);
+
+ virtual void verifyAnalysis() const;
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ }
+
+ inline bool dominates(const DomTreeNode* A, const DomTreeNode* B) const {
+ return DT->dominates(A, B);
+ }
+
+ inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
+ return DT->dominates(A, B);
+ }
+
+ // dominates - Return true if Def dominates a use in User. This performs
+ // the special checks necessary if Def and User are in the same basic block.
+ // Note that Def doesn't dominate a use in Def itself!
+ bool dominates(const Instruction *Def, const Use &U) const;
+ bool dominates(const Instruction *Def, const Instruction *User) const;
+ bool dominates(const Instruction *Def, const BasicBlock *BB) const;
+ bool dominates(const BasicBlockEdge &BBE, const Use &U) const;
+ bool dominates(const BasicBlockEdge &BBE, const BasicBlock *BB) const;
+
+ bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
+ return DT->properlyDominates(A, B);
+ }
+
+ bool properlyDominates(const BasicBlock *A, const BasicBlock *B) const {
+ return DT->properlyDominates(A, B);
+ }
+
+ /// findNearestCommonDominator - Find nearest common dominator basic block
+ /// for basic block A and B. If there is no such block then return NULL.
+ inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
+ return DT->findNearestCommonDominator(A, B);
+ }
+
+ inline const BasicBlock *findNearestCommonDominator(const BasicBlock *A,
+ const BasicBlock *B) {
+ return DT->findNearestCommonDominator(A, B);
+ }
+
+ inline DomTreeNode *operator[](BasicBlock *BB) const {
+ return DT->getNode(BB);
+ }
+
+ /// getNode - return the (Post)DominatorTree node for the specified basic
+ /// block. This is the same as using operator[] on this class.
+ ///
+ inline DomTreeNode *getNode(BasicBlock *BB) const {
+ return DT->getNode(BB);
+ }
+
+ /// addNewBlock - Add a new node to the dominator tree information. This
+ /// creates a new node as a child of DomBB dominator node,linking it into
+ /// the children list of the immediate dominator.
+ inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
+ return DT->addNewBlock(BB, DomBB);
+ }
+
+ /// changeImmediateDominator - This method is used to update the dominator
+ /// tree information when a node's immediate dominator changes.
+ ///
+ inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
+ DT->changeImmediateDominator(N, NewIDom);
+ }
+
+ inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
+ DT->changeImmediateDominator(N, NewIDom);
+ }
+
+ /// eraseNode - Removes a node from the dominator tree. Block must not
+ /// dominate any other blocks. Removes node from its immediate dominator's
+ /// children list. Deletes dominator node associated with basic block BB.
+ inline void eraseNode(BasicBlock *BB) {
+ DT->eraseNode(BB);
+ }
+
+ /// splitBlock - BB is split and now it has one successor. Update dominator
+ /// tree to reflect this change.
+ inline void splitBlock(BasicBlock* NewBB) {
+ DT->splitBlock(NewBB);
+ }
+
+ bool isReachableFromEntry(const BasicBlock* A) const {
+ return DT->isReachableFromEntry(A);
+ }
+
+ bool isReachableFromEntry(const Use &U) const;
+
+
+ virtual void releaseMemory() {
+ DT->releaseMemory();
+ }
+
+ virtual void print(raw_ostream &OS, const Module* M= 0) const;
+};
+
+//===-------------------------------------
+/// DominatorTree GraphTraits specialization so the DominatorTree can be
+/// iterable by generic graph iterators.
+///
+template <> struct GraphTraits<DomTreeNode*> {
+ typedef DomTreeNode NodeType;
+ typedef NodeType::iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(NodeType *N) {
+ return N;
+ }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->end();
+ }
+
+ typedef df_iterator<DomTreeNode*> nodes_iterator;
+
+ static nodes_iterator nodes_begin(DomTreeNode *N) {
+ return df_begin(getEntryNode(N));
+ }
+
+ static nodes_iterator nodes_end(DomTreeNode *N) {
+ return df_end(getEntryNode(N));
+ }
+};
+
+template <> struct GraphTraits<DominatorTree*>
+ : public GraphTraits<DomTreeNode*> {
+ static NodeType *getEntryNode(DominatorTree *DT) {
+ return DT->getRootNode();
+ }
+
+ static nodes_iterator nodes_begin(DominatorTree *N) {
+ return df_begin(getEntryNode(N));
+ }
+
+ static nodes_iterator nodes_end(DominatorTree *N) {
+ return df_end(getEntryNode(N));
+ }
+};
+
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/FindUsedTypes.h b/include/llvm/Analysis/FindUsedTypes.h
new file mode 100644
index 00000000000..b22cb881351
--- /dev/null
+++ b/include/llvm/Analysis/FindUsedTypes.h
@@ -0,0 +1,66 @@
+//===- llvm/Analysis/FindUsedTypes.h - Find all Types in use ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This pass is used to seek out all of the types in use by the program.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_FINDUSEDTYPES_H
+#define LLVM_ANALYSIS_FINDUSEDTYPES_H
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/Pass.h"
+
+namespace llvm {
+
+class Type;
+class Value;
+
+class FindUsedTypes : public ModulePass {
+ SetVector<Type *> UsedTypes;
+public:
+ static char ID; // Pass identification, replacement for typeid
+ FindUsedTypes() : ModulePass(ID) {
+ initializeFindUsedTypesPass(*PassRegistry::getPassRegistry());
+ }
+
+ /// getTypes - After the pass has been run, return the set containing all of
+ /// the types used in the module.
+ ///
+ const SetVector<Type *> &getTypes() const { return UsedTypes; }
+
+ /// Print the types found in the module. If the optional Module parameter is
+ /// passed in, then the types are printed symbolically if possible, using the
+ /// symbol table from the module.
+ ///
+ void print(raw_ostream &o, const Module *M) const;
+
+private:
+ /// IncorporateType - Incorporate one type and all of its subtypes into the
+ /// collection of used types.
+ ///
+ void IncorporateType(Type *Ty);
+
+ /// IncorporateValue - Incorporate all of the types used by this value.
+ ///
+ void IncorporateValue(const Value *V);
+
+public:
+ /// run - This incorporates all types used by the specified module
+ bool runOnModule(Module &M);
+
+ /// getAnalysisUsage - We do not modify anything.
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/IVUsers.h b/include/llvm/Analysis/IVUsers.h
new file mode 100644
index 00000000000..2bf79b9c932
--- /dev/null
+++ b/include/llvm/Analysis/IVUsers.h
@@ -0,0 +1,185 @@
+//===- llvm/Analysis/IVUsers.h - Induction Variable Users -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements bookkeeping for "interesting" users of expressions
+// computed from induction variables.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_IVUSERS_H
+#define LLVM_ANALYSIS_IVUSERS_H
+
+#include "llvm/Analysis/LoopPass.h"
+#include "llvm/Analysis/ScalarEvolutionNormalization.h"
+#include "llvm/Support/ValueHandle.h"
+
+namespace llvm {
+
+class DominatorTree;
+class Instruction;
+class Value;
+class IVUsers;
+class ScalarEvolution;
+class SCEV;
+class IVUsers;
+class TargetData;
+
+/// IVStrideUse - Keep track of one use of a strided induction variable.
+/// The Expr member keeps track of the expression, User is the actual user
+/// instruction of the operand, and 'OperandValToReplace' is the operand of
+/// the User that is the use.
+class IVStrideUse : public CallbackVH, public ilist_node<IVStrideUse> {
+ friend class IVUsers;
+public:
+ IVStrideUse(IVUsers *P, Instruction* U, Value *O)
+ : CallbackVH(U), Parent(P), OperandValToReplace(O) {
+ }
+
+ /// getUser - Return the user instruction for this use.
+ Instruction *getUser() const {
+ return cast<Instruction>(getValPtr());
+ }
+
+ /// setUser - Assign a new user instruction for this use.
+ void setUser(Instruction *NewUser) {
+ setValPtr(NewUser);
+ }
+
+ /// getOperandValToReplace - Return the Value of the operand in the user
+ /// instruction that this IVStrideUse is representing.
+ Value *getOperandValToReplace() const {
+ return OperandValToReplace;
+ }
+
+ /// setOperandValToReplace - Assign a new Value as the operand value
+ /// to replace.
+ void setOperandValToReplace(Value *Op) {
+ OperandValToReplace = Op;
+ }
+
+ /// getPostIncLoops - Return the set of loops for which the expression has
+ /// been adjusted to use post-inc mode.
+ const PostIncLoopSet &getPostIncLoops() const {
+ return PostIncLoops;
+ }
+
+ /// transformToPostInc - Transform the expression to post-inc form for the
+ /// given loop.
+ void transformToPostInc(const Loop *L);
+
+private:
+ /// Parent - a pointer to the IVUsers that owns this IVStrideUse.
+ IVUsers *Parent;
+
+ /// OperandValToReplace - The Value of the operand in the user instruction
+ /// that this IVStrideUse is representing.
+ WeakVH OperandValToReplace;
+
+ /// PostIncLoops - The set of loops for which Expr has been adjusted to
+ /// use post-inc mode. This corresponds with SCEVExpander's post-inc concept.
+ PostIncLoopSet PostIncLoops;
+
+ /// Deleted - Implementation of CallbackVH virtual function to
+ /// receive notification when the User is deleted.
+ virtual void deleted();
+};
+
+template<> struct ilist_traits<IVStrideUse>
+ : public ilist_default_traits<IVStrideUse> {
+ // createSentinel is used to get hold of a node that marks the end of
+ // the list...
+ // The sentinel is relative to this instance, so we use a non-static
+ // method.
+ IVStrideUse *createSentinel() const {
+ // since i(p)lists always publicly derive from the corresponding
+ // traits, placing a data member in this class will augment i(p)list.
+ // But since the NodeTy is expected to publicly derive from
+ // ilist_node<NodeTy>, there is a legal viable downcast from it
+ // to NodeTy. We use this trick to superpose i(p)list with a "ghostly"
+ // NodeTy, which becomes the sentinel. Dereferencing the sentinel is
+ // forbidden (save the ilist_node<NodeTy>) so no one will ever notice
+ // the superposition.
+ return static_cast<IVStrideUse*>(&Sentinel);
+ }
+ static void destroySentinel(IVStrideUse*) {}
+
+ IVStrideUse *provideInitialHead() const { return createSentinel(); }
+ IVStrideUse *ensureHead(IVStrideUse*) const { return createSentinel(); }
+ static void noteHead(IVStrideUse*, IVStrideUse*) {}
+
+private:
+ mutable ilist_node<IVStrideUse> Sentinel;
+};
+
+class IVUsers : public LoopPass {
+ friend class IVStrideUse;
+ Loop *L;
+ LoopInfo *LI;
+ DominatorTree *DT;
+ ScalarEvolution *SE;
+ TargetData *TD;
+ SmallPtrSet<Instruction*,16> Processed;
+
+ /// IVUses - A list of all tracked IV uses of induction variable expressions
+ /// we are interested in.
+ ilist<IVStrideUse> IVUses;
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
+
+ virtual void releaseMemory();
+
+public:
+ static char ID; // Pass ID, replacement for typeid
+ IVUsers();
+
+ Loop *getLoop() const { return L; }
+
+ /// AddUsersIfInteresting - Inspect the specified Instruction. If it is a
+ /// reducible SCEV, recursively add its users to the IVUsesByStride set and
+ /// return true. Otherwise, return false.
+ bool AddUsersIfInteresting(Instruction *I);
+
+ IVStrideUse &AddUser(Instruction *User, Value *Operand);
+
+ /// getReplacementExpr - Return a SCEV expression which computes the
+ /// value of the OperandValToReplace of the given IVStrideUse.
+ const SCEV *getReplacementExpr(const IVStrideUse &IU) const;
+
+ /// getExpr - Return the expression for the use.
+ const SCEV *getExpr(const IVStrideUse &IU) const;
+
+ const SCEV *getStride(const IVStrideUse &IU, const Loop *L) const;
+
+ typedef ilist<IVStrideUse>::iterator iterator;
+ typedef ilist<IVStrideUse>::const_iterator const_iterator;
+ iterator begin() { return IVUses.begin(); }
+ iterator end() { return IVUses.end(); }
+ const_iterator begin() const { return IVUses.begin(); }
+ const_iterator end() const { return IVUses.end(); }
+ bool empty() const { return IVUses.empty(); }
+
+ bool isIVUserOrOperand(Instruction *Inst) const {
+ return Processed.count(Inst);
+ }
+
+ void print(raw_ostream &OS, const Module* = 0) const;
+
+ /// dump - This method is used for debugging.
+ void dump() const;
+protected:
+ bool AddUsersImpl(Instruction *I, SmallPtrSet<Loop*,16> &SimpleLoopNests);
+};
+
+Pass *createIVUsersPass();
+
+}
+
+#endif
diff --git a/include/llvm/Analysis/InlineCost.h b/include/llvm/Analysis/InlineCost.h
new file mode 100644
index 00000000000..0cba135222b
--- /dev/null
+++ b/include/llvm/Analysis/InlineCost.h
@@ -0,0 +1,132 @@
+//===- InlineCost.h - Cost analysis for inliner -----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements heuristics for inlining decisions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_INLINECOST_H
+#define LLVM_ANALYSIS_INLINECOST_H
+
+#include "llvm/Function.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/ValueMap.h"
+#include "llvm/Analysis/CodeMetrics.h"
+#include <cassert>
+#include <climits>
+#include <vector>
+
+namespace llvm {
+
+ class CallSite;
+ class TargetData;
+
+ namespace InlineConstants {
+ // Various magic constants used to adjust heuristics.
+ const int InstrCost = 5;
+ const int IndirectCallThreshold = 100;
+ const int CallPenalty = 25;
+ const int LastCallToStaticBonus = -15000;
+ const int ColdccPenalty = 2000;
+ const int NoreturnPenalty = 10000;
+ }
+
+ /// \brief Represents the cost of inlining a function.
+ ///
+ /// This supports special values for functions which should "always" or
+ /// "never" be inlined. Otherwise, the cost represents a unitless amount;
+ /// smaller values increase the likelihood of the function being inlined.
+ ///
+ /// Objects of this type also provide the adjusted threshold for inlining
+ /// based on the information available for a particular callsite. They can be
+ /// directly tested to determine if inlining should occur given the cost and
+ /// threshold for this cost metric.
+ class InlineCost {
+ enum SentinelValues {
+ AlwaysInlineCost = INT_MIN,
+ NeverInlineCost = INT_MAX
+ };
+
+ /// \brief The estimated cost of inlining this callsite.
+ const int Cost;
+
+ /// \brief The adjusted threshold against which this cost was computed.
+ const int Threshold;
+
+ // Trivial constructor, interesting logic in the factory functions below.
+ InlineCost(int Cost, int Threshold)
+ : Cost(Cost), Threshold(Threshold) {}
+
+ public:
+ static InlineCost get(int Cost, int Threshold) {
+ assert(Cost > AlwaysInlineCost && "Cost crosses sentinel value");
+ assert(Cost < NeverInlineCost && "Cost crosses sentinel value");
+ return InlineCost(Cost, Threshold);
+ }
+ static InlineCost getAlways() {
+ return InlineCost(AlwaysInlineCost, 0);
+ }
+ static InlineCost getNever() {
+ return InlineCost(NeverInlineCost, 0);
+ }
+
+ /// \brief Test whether the inline cost is low enough for inlining.
+ operator bool() const {
+ return Cost < Threshold;
+ }
+
+ bool isAlways() const { return Cost == AlwaysInlineCost; }
+ bool isNever() const { return Cost == NeverInlineCost; }
+ bool isVariable() const { return !isAlways() && !isNever(); }
+
+ /// \brief Get the inline cost estimate.
+ /// It is an error to call this on an "always" or "never" InlineCost.
+ int getCost() const {
+ assert(isVariable() && "Invalid access of InlineCost");
+ return Cost;
+ }
+
+ /// \brief Get the cost delta from the threshold for inlining.
+ /// Only valid if the cost is of the variable kind. Returns a negative
+ /// value if the cost is too high to inline.
+ int getCostDelta() const { return Threshold - getCost(); }
+ };
+
+ /// InlineCostAnalyzer - Cost analyzer used by inliner.
+ class InlineCostAnalyzer {
+ // TargetData if available, or null.
+ const TargetData *TD;
+
+ public:
+ InlineCostAnalyzer(): TD(0) {}
+
+ void setTargetData(const TargetData *TData) { TD = TData; }
+
+ /// \brief Get an InlineCost object representing the cost of inlining this
+ /// callsite.
+ ///
+ /// Note that threshold is passed into this function. Only costs below the
+ /// threshold are computed with any accuracy. The threshold can be used to
+ /// bound the computation necessary to determine whether the cost is
+ /// sufficiently low to warrant inlining.
+ InlineCost getInlineCost(CallSite CS, int Threshold);
+ /// getCalledFunction - The heuristic used to determine if we should inline
+ /// the function call or not. The callee is explicitly specified, to allow
+ /// you to calculate the cost of inlining a function via a pointer. This
+ /// behaves exactly as the version with no explicit callee parameter in all
+ /// other respects.
+ //
+ // Note: This is used by out-of-tree passes, please do not remove without
+ // adding a replacement API.
+ InlineCost getInlineCost(CallSite CS, Function *Callee, int Threshold);
+ };
+}
+
+#endif
diff --git a/include/llvm/Analysis/InstructionSimplify.h b/include/llvm/Analysis/InstructionSimplify.h
new file mode 100644
index 00000000000..152e885bf66
--- /dev/null
+++ b/include/llvm/Analysis/InstructionSimplify.h
@@ -0,0 +1,218 @@
+//===-- InstructionSimplify.h - Fold instructions into simpler forms ------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares routines for folding instructions into simpler forms
+// that do not require creating new instructions. This does constant folding
+// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
+// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
+// ("and i32 %x, %x" -> "%x"). If the simplification is also an instruction
+// then it dominates the original instruction.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
+#define LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
+
+namespace llvm {
+ template<typename T>
+ class ArrayRef;
+ class DominatorTree;
+ class Instruction;
+ class TargetData;
+ class TargetLibraryInfo;
+ class Type;
+ class Value;
+
+ /// SimplifyAddInst - Given operands for an Add, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifySubInst - Given operands for a Sub, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifySubInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyMulInst - Given operands for a Mul, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyMulInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifySDivInst - Given operands for an SDiv, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifySDivInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyUDivInst - Given operands for a UDiv, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyUDivInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyFDivInst - Given operands for an FDiv, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyFDivInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifySRemInst - Given operands for an SRem, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifySRemInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyURemInst - Given operands for a URem, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyURemInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyFRemInst - Given operands for an FRem, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyFRemInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyShlInst - Given operands for a Shl, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyLShrInst - Given operands for a LShr, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyAShrInst - Given operands for a AShr, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyAndInst - Given operands for an And, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyAndInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyOrInst - Given operands for an Or, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyOrInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyXorInst - Given operands for a Xor, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyXorInst(Value *LHS, Value *RHS, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
+ /// the result. If not, this returns null.
+ Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
+ /// can fold the result. If not, this returns null.
+ Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
+ ArrayRef<unsigned> Idxs,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyTruncInst - Given operands for an TruncInst, see if we can fold
+ /// the result. If not, this returns null.
+ Value *SimplifyTruncInst(Value *Op, Type *Ty, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ //=== Helper functions for higher up the class hierarchy.
+
+
+ /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
+ /// fold the result. If not, this returns null.
+ Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// SimplifyInstruction - See if we can compute a simplified version of this
+ /// instruction. If not, this returns null.
+ Value *SimplifyInstruction(Instruction *I, const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+
+ /// \brief Replace all uses of 'I' with 'SimpleV' and simplify the uses
+ /// recursively.
+ ///
+ /// This first performs a normal RAUW of I with SimpleV. It then recursively
+ /// attempts to simplify those users updated by the operation. The 'I'
+ /// instruction must not be equal to the simplified value 'SimpleV'.
+ ///
+ /// The function returns true if any simplifications were performed.
+ bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+
+ /// \brief Recursively attempt to simplify an instruction.
+ ///
+ /// This routine uses SimplifyInstruction to simplify 'I', and if successful
+ /// replaces uses of 'I' with the simplified value. It then recurses on each
+ /// of the users impacted. It returns true if any simplifications were
+ /// performed.
+ bool recursivelySimplifyInstruction(Instruction *I,
+ const TargetData *TD = 0,
+ const TargetLibraryInfo *TLI = 0,
+ const DominatorTree *DT = 0);
+} // end namespace llvm
+
+#endif
+
diff --git a/include/llvm/Analysis/Interval.h b/include/llvm/Analysis/Interval.h
new file mode 100644
index 00000000000..ca8ad73131a
--- /dev/null
+++ b/include/llvm/Analysis/Interval.h
@@ -0,0 +1,153 @@
+//===- llvm/Analysis/Interval.h - Interval Class Declaration ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the Interval class, which
+// represents a set of CFG nodes and is a portion of an interval partition.
+//
+// Intervals have some interesting and useful properties, including the
+// following:
+// 1. The header node of an interval dominates all of the elements of the
+// interval
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INTERVAL_H
+#define LLVM_INTERVAL_H
+
+#include "llvm/ADT/GraphTraits.h"
+#include <vector>
+
+namespace llvm {
+
+class BasicBlock;
+class raw_ostream;
+
+//===----------------------------------------------------------------------===//
+//
+/// Interval Class - An Interval is a set of nodes defined such that every node
+/// in the interval has all of its predecessors in the interval (except for the
+/// header)
+///
+class Interval {
+ /// HeaderNode - The header BasicBlock, which dominates all BasicBlocks in this
+ /// interval. Also, any loops in this interval must go through the HeaderNode.
+ ///
+ BasicBlock *HeaderNode;
+public:
+ typedef std::vector<BasicBlock*>::iterator succ_iterator;
+ typedef std::vector<BasicBlock*>::iterator pred_iterator;
+ typedef std::vector<BasicBlock*>::iterator node_iterator;
+
+ inline Interval(BasicBlock *Header) : HeaderNode(Header) {
+ Nodes.push_back(Header);
+ }
+
+ inline Interval(const Interval &I) // copy ctor
+ : HeaderNode(I.HeaderNode), Nodes(I.Nodes), Successors(I.Successors) {}
+
+ inline BasicBlock *getHeaderNode() const { return HeaderNode; }
+
+ /// Nodes - The basic blocks in this interval.
+ ///
+ std::vector<BasicBlock*> Nodes;
+
+ /// Successors - List of BasicBlocks that are reachable directly from nodes in
+ /// this interval, but are not in the interval themselves.
+ /// These nodes necessarily must be header nodes for other intervals.
+ ///
+ std::vector<BasicBlock*> Successors;
+
+ /// Predecessors - List of BasicBlocks that have this Interval's header block
+ /// as one of their successors.
+ ///
+ std::vector<BasicBlock*> Predecessors;
+
+ /// contains - Find out if a basic block is in this interval
+ inline bool contains(BasicBlock *BB) const {
+ for (unsigned i = 0; i < Nodes.size(); ++i)
+ if (Nodes[i] == BB) return true;
+ return false;
+ // I don't want the dependency on <algorithm>
+ //return find(Nodes.begin(), Nodes.end(), BB) != Nodes.end();
+ }
+
+ /// isSuccessor - find out if a basic block is a successor of this Interval
+ inline bool isSuccessor(BasicBlock *BB) const {
+ for (unsigned i = 0; i < Successors.size(); ++i)
+ if (Successors[i] == BB) return true;
+ return false;
+ // I don't want the dependency on <algorithm>
+ //return find(Successors.begin(), Successors.end(), BB) != Successors.end();
+ }
+
+ /// Equality operator. It is only valid to compare two intervals from the
+ /// same partition, because of this, all we have to check is the header node
+ /// for equality.
+ ///
+ inline bool operator==(const Interval &I) const {
+ return HeaderNode == I.HeaderNode;
+ }
+
+ /// isLoop - Find out if there is a back edge in this interval...
+ bool isLoop() const;
+
+ /// print - Show contents in human readable format...
+ void print(raw_ostream &O) const;
+};
+
+/// succ_begin/succ_end - define methods so that Intervals may be used
+/// just like BasicBlocks can with the succ_* functions, and *::succ_iterator.
+///
+inline Interval::succ_iterator succ_begin(Interval *I) {
+ return I->Successors.begin();
+}
+inline Interval::succ_iterator succ_end(Interval *I) {
+ return I->Successors.end();
+}
+
+/// pred_begin/pred_end - define methods so that Intervals may be used
+/// just like BasicBlocks can with the pred_* functions, and *::pred_iterator.
+///
+inline Interval::pred_iterator pred_begin(Interval *I) {
+ return I->Predecessors.begin();
+}
+inline Interval::pred_iterator pred_end(Interval *I) {
+ return I->Predecessors.end();
+}
+
+template <> struct GraphTraits<Interval*> {
+ typedef Interval NodeType;
+ typedef Interval::succ_iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(Interval *I) { return I; }
+
+ /// nodes_iterator/begin/end - Allow iteration over all nodes in the graph
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return succ_begin(N);
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return succ_end(N);
+ }
+};
+
+template <> struct GraphTraits<Inverse<Interval*> > {
+ typedef Interval NodeType;
+ typedef Interval::pred_iterator ChildIteratorType;
+ static NodeType *getEntryNode(Inverse<Interval *> G) { return G.Graph; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return pred_begin(N);
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return pred_end(N);
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/IntervalIterator.h b/include/llvm/Analysis/IntervalIterator.h
new file mode 100644
index 00000000000..0968c7468e6
--- /dev/null
+++ b/include/llvm/Analysis/IntervalIterator.h
@@ -0,0 +1,259 @@
+//===- IntervalIterator.h - Interval Iterator Declaration -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines an iterator that enumerates the intervals in a control flow
+// graph of some sort. This iterator is parametric, allowing iterator over the
+// following types of graphs:
+//
+// 1. A Function* object, composed of BasicBlock nodes.
+// 2. An IntervalPartition& object, composed of Interval nodes.
+//
+// This iterator is defined to walk the control flow graph, returning intervals
+// in depth first order. These intervals are completely filled in except for
+// the predecessor fields (the successor information is filled in however).
+//
+// By default, the intervals created by this iterator are deleted after they
+// are no longer any use to the iterator. This behavior can be changed by
+// passing a false value into the intervals_begin() function. This causes the
+// IOwnMem member to be set, and the intervals to not be deleted.
+//
+// It is only safe to use this if all of the intervals are deleted by the caller
+// and all of the intervals are processed. However, the user of the iterator is
+// not allowed to modify or delete the intervals until after the iterator has
+// been used completely. The IntervalPartition class uses this functionality.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INTERVAL_ITERATOR_H
+#define LLVM_INTERVAL_ITERATOR_H
+
+#include "llvm/Analysis/IntervalPartition.h"
+#include "llvm/Function.h"
+#include "llvm/Support/CFG.h"
+#include <algorithm>
+#include <set>
+#include <vector>
+
+namespace llvm {
+
+// getNodeHeader - Given a source graph node and the source graph, return the
+// BasicBlock that is the header node. This is the opposite of
+// getSourceGraphNode.
+//
+inline BasicBlock *getNodeHeader(BasicBlock *BB) { return BB; }
+inline BasicBlock *getNodeHeader(Interval *I) { return I->getHeaderNode(); }
+
+// getSourceGraphNode - Given a BasicBlock and the source graph, return the
+// source graph node that corresponds to the BasicBlock. This is the opposite
+// of getNodeHeader.
+//
+inline BasicBlock *getSourceGraphNode(Function *, BasicBlock *BB) {
+ return BB;
+}
+inline Interval *getSourceGraphNode(IntervalPartition *IP, BasicBlock *BB) {
+ return IP->getBlockInterval(BB);
+}
+
+// addNodeToInterval - This method exists to assist the generic ProcessNode
+// with the task of adding a node to the new interval, depending on the
+// type of the source node. In the case of a CFG source graph (BasicBlock
+// case), the BasicBlock itself is added to the interval.
+//
+inline void addNodeToInterval(Interval *Int, BasicBlock *BB) {
+ Int->Nodes.push_back(BB);
+}
+
+// addNodeToInterval - This method exists to assist the generic ProcessNode
+// with the task of adding a node to the new interval, depending on the
+// type of the source node. In the case of a CFG source graph (BasicBlock
+// case), the BasicBlock itself is added to the interval. In the case of
+// an IntervalPartition source graph (Interval case), all of the member
+// BasicBlocks are added to the interval.
+//
+inline void addNodeToInterval(Interval *Int, Interval *I) {
+ // Add all of the nodes in I as new nodes in Int.
+ copy(I->Nodes.begin(), I->Nodes.end(), back_inserter(Int->Nodes));
+}
+
+
+
+
+
+template<class NodeTy, class OrigContainer_t, class GT = GraphTraits<NodeTy*>,
+ class IGT = GraphTraits<Inverse<NodeTy*> > >
+class IntervalIterator {
+ std::vector<std::pair<Interval*, typename Interval::succ_iterator> > IntStack;
+ std::set<BasicBlock*> Visited;
+ OrigContainer_t *OrigContainer;
+ bool IOwnMem; // If True, delete intervals when done with them
+ // See file header for conditions of use
+public:
+ typedef IntervalIterator<NodeTy, OrigContainer_t> _Self;
+ typedef std::forward_iterator_tag iterator_category;
+
+ IntervalIterator() {} // End iterator, empty stack
+ IntervalIterator(Function *M, bool OwnMemory) : IOwnMem(OwnMemory) {
+ OrigContainer = M;
+ if (!ProcessInterval(&M->front())) {
+ llvm_unreachable("ProcessInterval should never fail for first interval!");
+ }
+ }
+
+ IntervalIterator(IntervalPartition &IP, bool OwnMemory) : IOwnMem(OwnMemory) {
+ OrigContainer = &IP;
+ if (!ProcessInterval(IP.getRootInterval())) {
+ llvm_unreachable("ProcessInterval should never fail for first interval!");
+ }
+ }
+
+ inline ~IntervalIterator() {
+ if (IOwnMem)
+ while (!IntStack.empty()) {
+ delete operator*();
+ IntStack.pop_back();
+ }
+ }
+
+ inline bool operator==(const _Self& x) const { return IntStack == x.IntStack;}
+ inline bool operator!=(const _Self& x) const { return !operator==(x); }
+
+ inline const Interval *operator*() const { return IntStack.back().first; }
+ inline Interval *operator*() { return IntStack.back().first; }
+ inline const Interval *operator->() const { return operator*(); }
+ inline Interval *operator->() { return operator*(); }
+
+ _Self& operator++() { // Preincrement
+ assert(!IntStack.empty() && "Attempting to use interval iterator at end!");
+ do {
+ // All of the intervals on the stack have been visited. Try visiting
+ // their successors now.
+ Interval::succ_iterator &SuccIt = IntStack.back().second,
+ EndIt = succ_end(IntStack.back().first);
+ while (SuccIt != EndIt) { // Loop over all interval succs
+ bool Done = ProcessInterval(getSourceGraphNode(OrigContainer, *SuccIt));
+ ++SuccIt; // Increment iterator
+ if (Done) return *this; // Found a new interval! Use it!
+ }
+
+ // Free interval memory... if necessary
+ if (IOwnMem) delete IntStack.back().first;
+
+ // We ran out of successors for this interval... pop off the stack
+ IntStack.pop_back();
+ } while (!IntStack.empty());
+
+ return *this;
+ }
+ inline _Self operator++(int) { // Postincrement
+ _Self tmp = *this; ++*this; return tmp;
+ }
+
+private:
+ // ProcessInterval - This method is used during the construction of the
+ // interval graph. It walks through the source graph, recursively creating
+ // an interval per invokation until the entire graph is covered. This uses
+ // the ProcessNode method to add all of the nodes to the interval.
+ //
+ // This method is templated because it may operate on two different source
+ // graphs: a basic block graph, or a preexisting interval graph.
+ //
+ bool ProcessInterval(NodeTy *Node) {
+ BasicBlock *Header = getNodeHeader(Node);
+ if (Visited.count(Header)) return false;
+
+ Interval *Int = new Interval(Header);
+ Visited.insert(Header); // The header has now been visited!
+
+ // Check all of our successors to see if they are in the interval...
+ for (typename GT::ChildIteratorType I = GT::child_begin(Node),
+ E = GT::child_end(Node); I != E; ++I)
+ ProcessNode(Int, getSourceGraphNode(OrigContainer, *I));
+
+ IntStack.push_back(std::make_pair(Int, succ_begin(Int)));
+ return true;
+ }
+
+ // ProcessNode - This method is called by ProcessInterval to add nodes to the
+ // interval being constructed, and it is also called recursively as it walks
+ // the source graph. A node is added to the current interval only if all of
+ // its predecessors are already in the graph. This also takes care of keeping
+ // the successor set of an interval up to date.
+ //
+ // This method is templated because it may operate on two different source
+ // graphs: a basic block graph, or a preexisting interval graph.
+ //
+ void ProcessNode(Interval *Int, NodeTy *Node) {
+ assert(Int && "Null interval == bad!");
+ assert(Node && "Null Node == bad!");
+
+ BasicBlock *NodeHeader = getNodeHeader(Node);
+
+ if (Visited.count(NodeHeader)) { // Node already been visited?
+ if (Int->contains(NodeHeader)) { // Already in this interval...
+ return;
+ } else { // In other interval, add as successor
+ if (!Int->isSuccessor(NodeHeader)) // Add only if not already in set
+ Int->Successors.push_back(NodeHeader);
+ }
+ } else { // Otherwise, not in interval yet
+ for (typename IGT::ChildIteratorType I = IGT::child_begin(Node),
+ E = IGT::child_end(Node); I != E; ++I) {
+ if (!Int->contains(*I)) { // If pred not in interval, we can't be
+ if (!Int->isSuccessor(NodeHeader)) // Add only if not already in set
+ Int->Successors.push_back(NodeHeader);
+ return; // See you later
+ }
+ }
+
+ // If we get here, then all of the predecessors of BB are in the interval
+ // already. In this case, we must add BB to the interval!
+ addNodeToInterval(Int, Node);
+ Visited.insert(NodeHeader); // The node has now been visited!
+
+ if (Int->isSuccessor(NodeHeader)) {
+ // If we were in the successor list from before... remove from succ list
+ Int->Successors.erase(std::remove(Int->Successors.begin(),
+ Int->Successors.end(), NodeHeader),
+ Int->Successors.end());
+ }
+
+ // Now that we have discovered that Node is in the interval, perhaps some
+ // of its successors are as well?
+ for (typename GT::ChildIteratorType It = GT::child_begin(Node),
+ End = GT::child_end(Node); It != End; ++It)
+ ProcessNode(Int, getSourceGraphNode(OrigContainer, *It));
+ }
+ }
+};
+
+typedef IntervalIterator<BasicBlock, Function> function_interval_iterator;
+typedef IntervalIterator<Interval, IntervalPartition>
+ interval_part_interval_iterator;
+
+
+inline function_interval_iterator intervals_begin(Function *F,
+ bool DeleteInts = true) {
+ return function_interval_iterator(F, DeleteInts);
+}
+inline function_interval_iterator intervals_end(Function *) {
+ return function_interval_iterator();
+}
+
+inline interval_part_interval_iterator
+ intervals_begin(IntervalPartition &IP, bool DeleteIntervals = true) {
+ return interval_part_interval_iterator(IP, DeleteIntervals);
+}
+
+inline interval_part_interval_iterator intervals_end(IntervalPartition &IP) {
+ return interval_part_interval_iterator();
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/IntervalPartition.h b/include/llvm/Analysis/IntervalPartition.h
new file mode 100644
index 00000000000..df7313f18f3
--- /dev/null
+++ b/include/llvm/Analysis/IntervalPartition.h
@@ -0,0 +1,111 @@
+//===- IntervalPartition.h - Interval partition Calculation -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the IntervalPartition class, which
+// calculates and represents the interval partition of a function, or a
+// preexisting interval partition.
+//
+// In this way, the interval partition may be used to reduce a flow graph down
+// to its degenerate single node interval partition (unless it is irreducible).
+//
+// TODO: The IntervalPartition class should take a bool parameter that tells
+// whether it should add the "tails" of an interval to an interval itself or if
+// they should be represented as distinct intervals.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INTERVAL_PARTITION_H
+#define LLVM_INTERVAL_PARTITION_H
+
+#include "llvm/Analysis/Interval.h"
+#include "llvm/Pass.h"
+#include <map>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+//
+// IntervalPartition - This class builds and holds an "interval partition" for
+// a function. This partition divides the control flow graph into a set of
+// maximal intervals, as defined with the properties above. Intuitively, a
+// BasicBlock is a (possibly nonexistent) loop with a "tail" of non looping
+// nodes following it.
+//
+class IntervalPartition : public FunctionPass {
+ typedef std::map<BasicBlock*, Interval*> IntervalMapTy;
+ IntervalMapTy IntervalMap;
+
+ typedef std::vector<Interval*> IntervalListTy;
+ Interval *RootInterval;
+ std::vector<Interval*> Intervals;
+
+public:
+ static char ID; // Pass identification, replacement for typeid
+
+ IntervalPartition() : FunctionPass(ID), RootInterval(0) {
+ initializeIntervalPartitionPass(*PassRegistry::getPassRegistry());
+ }
+
+ // run - Calculate the interval partition for this function
+ virtual bool runOnFunction(Function &F);
+
+ // IntervalPartition ctor - Build a reduced interval partition from an
+ // existing interval graph. This takes an additional boolean parameter to
+ // distinguish it from a copy constructor. Always pass in false for now.
+ //
+ IntervalPartition(IntervalPartition &I, bool);
+
+ // print - Show contents in human readable format...
+ virtual void print(raw_ostream &O, const Module* = 0) const;
+
+ // getRootInterval() - Return the root interval that contains the starting
+ // block of the function.
+ inline Interval *getRootInterval() { return RootInterval; }
+
+ // isDegeneratePartition() - Returns true if the interval partition contains
+ // a single interval, and thus cannot be simplified anymore.
+ bool isDegeneratePartition() { return Intervals.size() == 1; }
+
+ // TODO: isIrreducible - look for triangle graph.
+
+ // getBlockInterval - Return the interval that a basic block exists in.
+ inline Interval *getBlockInterval(BasicBlock *BB) {
+ IntervalMapTy::iterator I = IntervalMap.find(BB);
+ return I != IntervalMap.end() ? I->second : 0;
+ }
+
+ // getAnalysisUsage - Implement the Pass API
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ }
+
+ // Interface to Intervals vector...
+ const std::vector<Interval*> &getIntervals() const { return Intervals; }
+
+ // releaseMemory - Reset state back to before function was analyzed
+ void releaseMemory();
+
+private:
+ // addIntervalToPartition - Add an interval to the internal list of intervals,
+ // and then add mappings from all of the basic blocks in the interval to the
+ // interval itself (in the IntervalMap).
+ //
+ void addIntervalToPartition(Interval *I);
+
+ // updatePredecessors - Interval generation only sets the successor fields of
+ // the interval data structures. After interval generation is complete,
+ // run through all of the intervals and propagate successor info as
+ // predecessor info.
+ //
+ void updatePredecessors(Interval *Int);
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/LazyValueInfo.h b/include/llvm/Analysis/LazyValueInfo.h
new file mode 100644
index 00000000000..7b887d5a9ad
--- /dev/null
+++ b/include/llvm/Analysis/LazyValueInfo.h
@@ -0,0 +1,81 @@
+//===- LazyValueInfo.h - Value constraint analysis --------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the interface for lazy computation of value constraint
+// information.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LAZYVALUEINFO_H
+#define LLVM_ANALYSIS_LAZYVALUEINFO_H
+
+#include "llvm/Pass.h"
+
+namespace llvm {
+ class Constant;
+ class TargetData;
+ class TargetLibraryInfo;
+ class Value;
+
+/// LazyValueInfo - This pass computes, caches, and vends lazy value constraint
+/// information.
+class LazyValueInfo : public FunctionPass {
+ class TargetData *TD;
+ class TargetLibraryInfo *TLI;
+ void *PImpl;
+ LazyValueInfo(const LazyValueInfo&) LLVM_DELETED_FUNCTION;
+ void operator=(const LazyValueInfo&) LLVM_DELETED_FUNCTION;
+public:
+ static char ID;
+ LazyValueInfo() : FunctionPass(ID), PImpl(0) {
+ initializeLazyValueInfoPass(*PassRegistry::getPassRegistry());
+ }
+ ~LazyValueInfo() { assert(PImpl == 0 && "releaseMemory not called"); }
+
+ /// Tristate - This is used to return true/false/dunno results.
+ enum Tristate {
+ Unknown = -1, False = 0, True = 1
+ };
+
+
+ // Public query interface.
+
+ /// getPredicateOnEdge - Determine whether the specified value comparison
+ /// with a constant is known to be true or false on the specified CFG edge.
+ /// Pred is a CmpInst predicate.
+ Tristate getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
+ BasicBlock *FromBB, BasicBlock *ToBB);
+
+
+ /// getConstant - Determine whether the specified value is known to be a
+ /// constant at the end of the specified block. Return null if not.
+ Constant *getConstant(Value *V, BasicBlock *BB);
+
+ /// getConstantOnEdge - Determine whether the specified value is known to be a
+ /// constant on the specified edge. Return null if not.
+ Constant *getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB);
+
+ /// threadEdge - Inform the analysis cache that we have threaded an edge from
+ /// PredBB to OldSucc to be from PredBB to NewSucc instead.
+ void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc);
+
+ /// eraseBlock - Inform the analysis cache that we have erased a block.
+ void eraseBlock(BasicBlock *BB);
+
+ // Implementation boilerplate.
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+ virtual void releaseMemory();
+ virtual bool runOnFunction(Function &F);
+};
+
+} // end namespace llvm
+
+#endif
+
diff --git a/include/llvm/Analysis/LibCallAliasAnalysis.h b/include/llvm/Analysis/LibCallAliasAnalysis.h
new file mode 100644
index 00000000000..243234b7563
--- /dev/null
+++ b/include/llvm/Analysis/LibCallAliasAnalysis.h
@@ -0,0 +1,73 @@
+//===- LibCallAliasAnalysis.h - Implement AliasAnalysis for libcalls ------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the LibCallAliasAnalysis class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LIBCALL_AA_H
+#define LLVM_ANALYSIS_LIBCALL_AA_H
+
+#include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/Pass.h"
+
+namespace llvm {
+ class LibCallInfo;
+ struct LibCallFunctionInfo;
+
+ /// LibCallAliasAnalysis - Alias analysis driven from LibCallInfo.
+ struct LibCallAliasAnalysis : public FunctionPass, public AliasAnalysis {
+ static char ID; // Class identification
+
+ LibCallInfo *LCI;
+
+ explicit LibCallAliasAnalysis(LibCallInfo *LC = 0)
+ : FunctionPass(ID), LCI(LC) {
+ initializeLibCallAliasAnalysisPass(*PassRegistry::getPassRegistry());
+ }
+ explicit LibCallAliasAnalysis(char &ID, LibCallInfo *LC)
+ : FunctionPass(ID), LCI(LC) {
+ initializeLibCallAliasAnalysisPass(*PassRegistry::getPassRegistry());
+ }
+ ~LibCallAliasAnalysis();
+
+ ModRefResult getModRefInfo(ImmutableCallSite CS,
+ const Location &Loc);
+
+ ModRefResult getModRefInfo(ImmutableCallSite CS1,
+ ImmutableCallSite CS2) {
+ // TODO: Could compare two direct calls against each other if we cared to.
+ return AliasAnalysis::getModRefInfo(CS1, CS2);
+ }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ virtual bool runOnFunction(Function &F) {
+ InitializeAliasAnalysis(this); // set up super class
+ return false;
+ }
+
+ /// getAdjustedAnalysisPointer - This method is used when a pass implements
+ /// an analysis interface through multiple inheritance. If needed, it
+ /// should override this to adjust the this pointer as needed for the
+ /// specified pass info.
+ virtual void *getAdjustedAnalysisPointer(const void *PI) {
+ if (PI == &AliasAnalysis::ID)
+ return (AliasAnalysis*)this;
+ return this;
+ }
+
+ private:
+ ModRefResult AnalyzeLibCallDetails(const LibCallFunctionInfo *FI,
+ ImmutableCallSite CS,
+ const Location &Loc);
+ };
+} // End of llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/LibCallSemantics.h b/include/llvm/Analysis/LibCallSemantics.h
new file mode 100644
index 00000000000..f5a9e96cbdd
--- /dev/null
+++ b/include/llvm/Analysis/LibCallSemantics.h
@@ -0,0 +1,167 @@
+//===- LibCallSemantics.h - Describe library semantics --------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines interfaces that can be used to describe language specific
+// runtime library interfaces (e.g. libc, libm, etc) to LLVM optimizers.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LIBCALLSEMANTICS_H
+#define LLVM_ANALYSIS_LIBCALLSEMANTICS_H
+
+#include "llvm/Analysis/AliasAnalysis.h"
+
+namespace llvm {
+
+ /// LibCallLocationInfo - This struct describes a set of memory locations that
+ /// are accessed by libcalls. Identification of a location is doing with a
+ /// simple callback function.
+ ///
+ /// For example, the LibCallInfo may be set up to model the behavior of
+ /// standard libm functions. The location that they may be interested in is
+ /// an abstract location that represents errno for the current target. In
+ /// this case, a location for errno is anything such that the predicate
+ /// returns true. On Mac OS/X, this predicate would return true if the
+ /// pointer is the result of a call to "__error()".
+ ///
+ /// Locations can also be defined in a constant-sensitive way. For example,
+ /// it is possible to define a location that returns true iff it is passed
+ /// into the call as a specific argument. This is useful for modeling things
+ /// like "printf", which can store to memory, but only through pointers passed
+ /// with a '%n' constraint.
+ ///
+ struct LibCallLocationInfo {
+ // TODO: Flags: isContextSensitive etc.
+
+ /// isLocation - Return a LocResult if the specified pointer refers to this
+ /// location for the specified call site. This returns "Yes" if we can tell
+ /// that the pointer *does definitely* refer to the location, "No" if we can
+ /// tell that the location *definitely does not* refer to the location, and
+ /// returns "Unknown" if we cannot tell for certain.
+ enum LocResult {
+ Yes, No, Unknown
+ };
+ LocResult (*isLocation)(ImmutableCallSite CS,
+ const AliasAnalysis::Location &Loc);
+ };
+
+ /// LibCallFunctionInfo - Each record in the array of FunctionInfo structs
+ /// records the behavior of one libcall that is known by the optimizer. This
+ /// captures things like the side effects of the call. Side effects are
+ /// modeled both universally (in the readnone/readonly) sense, but also
+ /// potentially against a set of abstract locations defined by the optimizer.
+ /// This allows an optimizer to define that some libcall (e.g. sqrt) is
+ /// side-effect free except that it might modify errno (thus, the call is
+ /// *not* universally readonly). Or it might say that the side effects
+ /// are unknown other than to say that errno is not modified.
+ ///
+ struct LibCallFunctionInfo {
+ /// Name - This is the name of the libcall this describes.
+ const char *Name;
+
+ /// TODO: Constant folding function: Constant* vector -> Constant*.
+
+ /// UniversalBehavior - This captures the absolute mod/ref behavior without
+ /// any specific context knowledge. For example, if the function is known
+ /// to be readonly, this would be set to 'ref'. If known to be readnone,
+ /// this is set to NoModRef.
+ AliasAnalysis::ModRefResult UniversalBehavior;
+
+ /// LocationMRInfo - This pair captures info about whether a specific
+ /// location is modified or referenced by a libcall.
+ struct LocationMRInfo {
+ /// LocationID - ID # of the accessed location or ~0U for array end.
+ unsigned LocationID;
+ /// MRInfo - Mod/Ref info for this location.
+ AliasAnalysis::ModRefResult MRInfo;
+ };
+
+ /// DetailsType - Indicate the sense of the LocationDetails array. This
+ /// controls how the LocationDetails array is interpreted.
+ enum {
+ /// DoesOnly - If DetailsType is set to DoesOnly, then we know that the
+ /// *only* mod/ref behavior of this function is captured by the
+ /// LocationDetails array. If we are trying to say that 'sqrt' can only
+ /// modify errno, we'd have the {errnoloc,mod} in the LocationDetails
+ /// array and have DetailsType set to DoesOnly.
+ DoesOnly,
+
+ /// DoesNot - If DetailsType is set to DoesNot, then the sense of the
+ /// LocationDetails array is completely inverted. This means that we *do
+ /// not* know everything about the side effects of this libcall, but we do
+ /// know things that the libcall cannot do. This is useful for complex
+ /// functions like 'ctime' which have crazy mod/ref behavior, but are
+ /// known to never read or write errno. In this case, we'd have
+ /// {errnoloc,modref} in the LocationDetails array and DetailsType would
+ /// be set to DoesNot, indicating that ctime does not read or write the
+ /// errno location.
+ DoesNot
+ } DetailsType;
+
+ /// LocationDetails - This is a pointer to an array of LocationMRInfo
+ /// structs which indicates the behavior of the libcall w.r.t. specific
+ /// locations. For example, if this libcall is known to only modify
+ /// 'errno', it would have a LocationDetails array with the errno ID and
+ /// 'mod' in it. See the DetailsType field for how this is interpreted.
+ ///
+ /// In the "DoesOnly" case, this information is 'may' information for: there
+ /// is no guarantee that the specified side effect actually does happen,
+ /// just that it could. In the "DoesNot" case, this is 'must not' info.
+ ///
+ /// If this pointer is null, no details are known.
+ ///
+ const LocationMRInfo *LocationDetails;
+ };
+
+
+ /// LibCallInfo - Abstract interface to query about library call information.
+ /// Instances of this class return known information about some set of
+ /// libcalls.
+ ///
+ class LibCallInfo {
+ // Implementation details of this object, private.
+ mutable void *Impl;
+ mutable const LibCallLocationInfo *Locations;
+ mutable unsigned NumLocations;
+ public:
+ LibCallInfo() : Impl(0), Locations(0), NumLocations(0) {}
+ virtual ~LibCallInfo();
+
+ //===------------------------------------------------------------------===//
+ // Accessor Methods: Efficient access to contained data.
+ //===------------------------------------------------------------------===//
+
+ /// getLocationInfo - Return information about the specified LocationID.
+ const LibCallLocationInfo &getLocationInfo(unsigned LocID) const;
+
+
+ /// getFunctionInfo - Return the LibCallFunctionInfo object corresponding to
+ /// the specified function if we have it. If not, return null.
+ const LibCallFunctionInfo *getFunctionInfo(const Function *F) const;
+
+
+ //===------------------------------------------------------------------===//
+ // Implementation Methods: Subclasses should implement these.
+ //===------------------------------------------------------------------===//
+
+ /// getLocationInfo - Return descriptors for the locations referenced by
+ /// this set of libcalls.
+ virtual unsigned getLocationInfo(const LibCallLocationInfo *&Array) const {
+ return 0;
+ }
+
+ /// getFunctionInfoArray - Return an array of descriptors that describe the
+ /// set of libcalls represented by this LibCallInfo object. This array is
+ /// terminated by an entry with a NULL name.
+ virtual const LibCallFunctionInfo *getFunctionInfoArray() const = 0;
+ };
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Analysis/Lint.h b/include/llvm/Analysis/Lint.h
new file mode 100644
index 00000000000..7c88b137ec3
--- /dev/null
+++ b/include/llvm/Analysis/Lint.h
@@ -0,0 +1,49 @@
+//===-- llvm/Analysis/Lint.h - LLVM IR Lint ---------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines lint interfaces that can be used for some sanity checking
+// of input to the system, and for checking that transformations
+// haven't done something bad. In contrast to the Verifier, the Lint checker
+// checks for undefined behavior or constructions with likely unintended
+// behavior.
+//
+// To see what specifically is checked, look at Lint.cpp
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LINT_H
+#define LLVM_ANALYSIS_LINT_H
+
+namespace llvm {
+
+class FunctionPass;
+class Module;
+class Function;
+
+/// @brief Create a lint pass.
+///
+/// Check a module or function.
+FunctionPass *createLintPass();
+
+/// @brief Check a module.
+///
+/// This should only be used for debugging, because it plays games with
+/// PassManagers and stuff.
+void lintModule(
+ const Module &M ///< The module to be checked
+);
+
+// lintFunction - Check a function.
+void lintFunction(
+ const Function &F ///< The function to be checked
+);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/Loads.h b/include/llvm/Analysis/Loads.h
new file mode 100644
index 00000000000..5f0aefbeb01
--- /dev/null
+++ b/include/llvm/Analysis/Loads.h
@@ -0,0 +1,57 @@
+//===- Loads.h - Local load analysis --------------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares simple local analyses for load instructions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LOADS_H
+#define LLVM_ANALYSIS_LOADS_H
+
+#include "llvm/BasicBlock.h"
+
+namespace llvm {
+
+class AliasAnalysis;
+class TargetData;
+class MDNode;
+
+/// isSafeToLoadUnconditionally - Return true if we know that executing a load
+/// from this value cannot trap. If it is not obviously safe to load from the
+/// specified pointer, we do a quick local scan of the basic block containing
+/// ScanFrom, to determine if the address is already accessed.
+bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
+ unsigned Align, const TargetData *TD = 0);
+
+/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at
+/// the instruction before ScanFrom) checking to see if we have the value at
+/// the memory address *Ptr locally available within a small number of
+/// instructions. If the value is available, return it.
+///
+/// If not, return the iterator for the last validated instruction that the
+/// value would be live through. If we scanned the entire block and didn't
+/// find something that invalidates *Ptr or provides it, ScanFrom would be
+/// left at begin() and this returns null. ScanFrom could also be left
+///
+/// MaxInstsToScan specifies the maximum instructions to scan in the block.
+/// If it is set to 0, it will scan the whole block. You can also optionally
+/// specify an alias analysis implementation, which makes this more precise.
+///
+/// If TBAATag is non-null and a load or store is found, the TBAA tag from the
+/// load or store is recorded there. If there is no TBAA tag or if no access
+/// is found, it is left unmodified.
+Value *FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
+ BasicBlock::iterator &ScanFrom,
+ unsigned MaxInstsToScan = 6,
+ AliasAnalysis *AA = 0,
+ MDNode **TBAATag = 0);
+
+}
+
+#endif
diff --git a/include/llvm/Analysis/LoopDependenceAnalysis.h b/include/llvm/Analysis/LoopDependenceAnalysis.h
new file mode 100644
index 00000000000..f195d278241
--- /dev/null
+++ b/include/llvm/Analysis/LoopDependenceAnalysis.h
@@ -0,0 +1,124 @@
+//===- llvm/Analysis/LoopDependenceAnalysis.h --------------- -*- C++ -*---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// LoopDependenceAnalysis is an LLVM pass that analyses dependences in memory
+// accesses in loops.
+//
+// Please note that this is work in progress and the interface is subject to
+// change.
+//
+// TODO: adapt as interface progresses
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LOOP_DEPENDENCE_ANALYSIS_H
+#define LLVM_ANALYSIS_LOOP_DEPENDENCE_ANALYSIS_H
+
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Analysis/LoopPass.h"
+#include "llvm/Support/Allocator.h"
+
+namespace llvm {
+
+class AliasAnalysis;
+class AnalysisUsage;
+class ScalarEvolution;
+class SCEV;
+class Value;
+class raw_ostream;
+
+class LoopDependenceAnalysis : public LoopPass {
+ AliasAnalysis *AA;
+ ScalarEvolution *SE;
+
+ /// L - The loop we are currently analysing.
+ Loop *L;
+
+ /// TODO: doc
+ enum DependenceResult { Independent = 0, Dependent = 1, Unknown = 2 };
+
+ /// TODO: doc
+ struct Subscript {
+ /// TODO: Add distance, direction, breaking conditions, ...
+ };
+
+ /// DependencePair - Represents a data dependence relation between to memory
+ /// reference instructions.
+ struct DependencePair : public FastFoldingSetNode {
+ Value *A;
+ Value *B;
+ DependenceResult Result;
+ SmallVector<Subscript, 4> Subscripts;
+
+ DependencePair(const FoldingSetNodeID &ID, Value *a, Value *b) :
+ FastFoldingSetNode(ID), A(a), B(b), Result(Unknown), Subscripts() {}
+ };
+
+ /// findOrInsertDependencePair - Return true if a DependencePair for the
+ /// given Values already exists, false if a new DependencePair had to be
+ /// created. The third argument is set to the pair found or created.
+ bool findOrInsertDependencePair(Value*, Value*, DependencePair*&);
+
+ /// getLoops - Collect all loops of the loop nest L in which
+ /// a given SCEV is variant.
+ void getLoops(const SCEV*, DenseSet<const Loop*>*) const;
+
+ /// isLoopInvariant - True if a given SCEV is invariant in all loops of the
+ /// loop nest starting at the innermost loop L.
+ bool isLoopInvariant(const SCEV*) const;
+
+ /// isAffine - An SCEV is affine with respect to the loop nest starting at
+ /// the innermost loop L if it is of the form A+B*X where A, B are invariant
+ /// in the loop nest and X is a induction variable in the loop nest.
+ bool isAffine(const SCEV*) const;
+
+ /// TODO: doc
+ bool isZIVPair(const SCEV*, const SCEV*) const;
+ bool isSIVPair(const SCEV*, const SCEV*) const;
+ DependenceResult analyseZIV(const SCEV*, const SCEV*, Subscript*) const;
+ DependenceResult analyseSIV(const SCEV*, const SCEV*, Subscript*) const;
+ DependenceResult analyseMIV(const SCEV*, const SCEV*, Subscript*) const;
+ DependenceResult analyseSubscript(const SCEV*, const SCEV*, Subscript*) const;
+ DependenceResult analysePair(DependencePair*) const;
+
+public:
+ static char ID; // Class identification, replacement for typeinfo
+ LoopDependenceAnalysis() : LoopPass(ID) {
+ initializeLoopDependenceAnalysisPass(*PassRegistry::getPassRegistry());
+ }
+
+ /// isDependencePair - Check whether two values can possibly give rise to
+ /// a data dependence: that is the case if both are instructions accessing
+ /// memory and at least one of those accesses is a write.
+ bool isDependencePair(const Value*, const Value*) const;
+
+ /// depends - Return a boolean indicating if there is a data dependence
+ /// between two instructions.
+ bool depends(Value*, Value*);
+
+ bool runOnLoop(Loop*, LPPassManager&);
+ virtual void releaseMemory();
+ virtual void getAnalysisUsage(AnalysisUsage&) const;
+ void print(raw_ostream&, const Module* = 0) const;
+
+private:
+ FoldingSet<DependencePair> Pairs;
+ BumpPtrAllocator PairAllocator;
+}; // class LoopDependenceAnalysis
+
+// createLoopDependenceAnalysisPass - This creates an instance of the
+// LoopDependenceAnalysis pass.
+//
+LoopPass *createLoopDependenceAnalysisPass();
+
+} // namespace llvm
+
+#endif /* LLVM_ANALYSIS_LOOP_DEPENDENCE_ANALYSIS_H */
diff --git a/include/llvm/Analysis/LoopInfo.h b/include/llvm/Analysis/LoopInfo.h
new file mode 100644
index 00000000000..c5d7b0128e7
--- /dev/null
+++ b/include/llvm/Analysis/LoopInfo.h
@@ -0,0 +1,700 @@
+//===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the LoopInfo class that is used to identify natural loops
+// and determine the loop depth of various nodes of the CFG. A natural loop
+// has exactly one entry-point, which is called the header. Note that natural
+// loops may actually be several loops that share the same header node.
+//
+// This analysis calculates the nesting structure of loops in a function. For
+// each natural loop identified, this analysis identifies natural loops
+// contained entirely within the loop and the basic blocks the make up the loop.
+//
+// It can calculate on the fly various bits of information, for example:
+//
+// * whether there is a preheader for the loop
+// * the number of back edges to the header
+// * whether or not a particular block branches out of the loop
+// * the successor blocks of the loop
+// * the loop depth
+// * etc...
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LOOP_INFO_H
+#define LLVM_ANALYSIS_LOOP_INFO_H
+
+#include "llvm/Pass.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/DepthFirstIterator.h"
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Analysis/Dominators.h"
+#include "llvm/Support/CFG.h"
+#include "llvm/Support/raw_ostream.h"
+#include <algorithm>
+#include <map>
+
+namespace llvm {
+
+template<typename T>
+inline void RemoveFromVector(std::vector<T*> &V, T *N) {
+ typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
+ assert(I != V.end() && "N is not in this list!");
+ V.erase(I);
+}
+
+class DominatorTree;
+class LoopInfo;
+class Loop;
+class PHINode;
+template<class N, class M> class LoopInfoBase;
+template<class N, class M> class LoopBase;
+
+//===----------------------------------------------------------------------===//
+/// LoopBase class - Instances of this class are used to represent loops that
+/// are detected in the flow graph
+///
+template<class BlockT, class LoopT>
+class LoopBase {
+ LoopT *ParentLoop;
+ // SubLoops - Loops contained entirely within this one.
+ std::vector<LoopT *> SubLoops;
+
+ // Blocks - The list of blocks in this loop. First entry is the header node.
+ std::vector<BlockT*> Blocks;
+
+ LoopBase(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
+ const LoopBase<BlockT, LoopT>&
+ operator=(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
+public:
+ /// Loop ctor - This creates an empty loop.
+ LoopBase() : ParentLoop(0) {}
+ ~LoopBase() {
+ for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
+ delete SubLoops[i];
+ }
+
+ /// getLoopDepth - Return the nesting level of this loop. An outer-most
+ /// loop has depth 1, for consistency with loop depth values used for basic
+ /// blocks, where depth 0 is used for blocks not inside any loops.
+ unsigned getLoopDepth() const {
+ unsigned D = 1;
+ for (const LoopT *CurLoop = ParentLoop; CurLoop;
+ CurLoop = CurLoop->ParentLoop)
+ ++D;
+ return D;
+ }
+ BlockT *getHeader() const { return Blocks.front(); }
+ LoopT *getParentLoop() const { return ParentLoop; }
+
+ /// setParentLoop is a raw interface for bypassing addChildLoop.
+ void setParentLoop(LoopT *L) { ParentLoop = L; }
+
+ /// contains - Return true if the specified loop is contained within in
+ /// this loop.
+ ///
+ bool contains(const LoopT *L) const {
+ if (L == this) return true;
+ if (L == 0) return false;
+ return contains(L->getParentLoop());
+ }
+
+ /// contains - Return true if the specified basic block is in this loop.
+ ///
+ bool contains(const BlockT *BB) const {
+ return std::find(block_begin(), block_end(), BB) != block_end();
+ }
+
+ /// contains - Return true if the specified instruction is in this loop.
+ ///
+ template<class InstT>
+ bool contains(const InstT *Inst) const {
+ return contains(Inst->getParent());
+ }
+
+ /// iterator/begin/end - Return the loops contained entirely within this loop.
+ ///
+ const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
+ std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
+ typedef typename std::vector<LoopT *>::const_iterator iterator;
+ typedef typename std::vector<LoopT *>::const_reverse_iterator
+ reverse_iterator;
+ iterator begin() const { return SubLoops.begin(); }
+ iterator end() const { return SubLoops.end(); }
+ reverse_iterator rbegin() const { return SubLoops.rbegin(); }
+ reverse_iterator rend() const { return SubLoops.rend(); }
+ bool empty() const { return SubLoops.empty(); }
+
+ /// getBlocks - Get a list of the basic blocks which make up this loop.
+ ///
+ const std::vector<BlockT*> &getBlocks() const { return Blocks; }
+ std::vector<BlockT*> &getBlocksVector() { return Blocks; }
+ typedef typename std::vector<BlockT*>::const_iterator block_iterator;
+ block_iterator block_begin() const { return Blocks.begin(); }
+ block_iterator block_end() const { return Blocks.end(); }
+
+ /// getNumBlocks - Get the number of blocks in this loop in constant time.
+ unsigned getNumBlocks() const {
+ return Blocks.size();
+ }
+
+ /// isLoopExiting - True if terminator in the block can branch to another
+ /// block that is outside of the current loop.
+ ///
+ bool isLoopExiting(const BlockT *BB) const {
+ typedef GraphTraits<BlockT*> BlockTraits;
+ for (typename BlockTraits::ChildIteratorType SI =
+ BlockTraits::child_begin(const_cast<BlockT*>(BB)),
+ SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
+ if (!contains(*SI))
+ return true;
+ }
+ return false;
+ }
+
+ /// getNumBackEdges - Calculate the number of back edges to the loop header
+ ///
+ unsigned getNumBackEdges() const {
+ unsigned NumBackEdges = 0;
+ BlockT *H = getHeader();
+
+ typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
+ for (typename InvBlockTraits::ChildIteratorType I =
+ InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
+ E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
+ if (contains(*I))
+ ++NumBackEdges;
+
+ return NumBackEdges;
+ }
+
+ //===--------------------------------------------------------------------===//
+ // APIs for simple analysis of the loop.
+ //
+ // Note that all of these methods can fail on general loops (ie, there may not
+ // be a preheader, etc). For best success, the loop simplification and
+ // induction variable canonicalization pass should be used to normalize loops
+ // for easy analysis. These methods assume canonical loops.
+
+ /// getExitingBlocks - Return all blocks inside the loop that have successors
+ /// outside of the loop. These are the blocks _inside of the current loop_
+ /// which branch out. The returned list is always unique.
+ ///
+ void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
+
+ /// getExitingBlock - If getExitingBlocks would return exactly one block,
+ /// return that block. Otherwise return null.
+ BlockT *getExitingBlock() const;
+
+ /// getExitBlocks - Return all of the successor blocks of this loop. These
+ /// are the blocks _outside of the current loop_ which are branched to.
+ ///
+ void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
+
+ /// getExitBlock - If getExitBlocks would return exactly one block,
+ /// return that block. Otherwise return null.
+ BlockT *getExitBlock() const;
+
+ /// Edge type.
+ typedef std::pair<const BlockT*, const BlockT*> Edge;
+
+ /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
+ void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
+
+ /// getLoopPreheader - If there is a preheader for this loop, return it. A
+ /// loop has a preheader if there is only one edge to the header of the loop
+ /// from outside of the loop. If this is the case, the block branching to the
+ /// header of the loop is the preheader node.
+ ///
+ /// This method returns null if there is no preheader for the loop.
+ ///
+ BlockT *getLoopPreheader() const;
+
+ /// getLoopPredecessor - If the given loop's header has exactly one unique
+ /// predecessor outside the loop, return it. Otherwise return null.
+ /// This is less strict that the loop "preheader" concept, which requires
+ /// the predecessor to have exactly one successor.
+ ///
+ BlockT *getLoopPredecessor() const;
+
+ /// getLoopLatch - If there is a single latch block for this loop, return it.
+ /// A latch block is a block that contains a branch back to the header.
+ BlockT *getLoopLatch() const;
+
+ //===--------------------------------------------------------------------===//
+ // APIs for updating loop information after changing the CFG
+ //
+
+ /// addBasicBlockToLoop - This method is used by other analyses to update loop
+ /// information. NewBB is set to be a new member of the current loop.
+ /// Because of this, it is added as a member of all parent loops, and is added
+ /// to the specified LoopInfo object as being in the current basic block. It
+ /// is not valid to replace the loop header with this method.
+ ///
+ void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
+
+ /// replaceChildLoopWith - This is used when splitting loops up. It replaces
+ /// the OldChild entry in our children list with NewChild, and updates the
+ /// parent pointer of OldChild to be null and the NewChild to be this loop.
+ /// This updates the loop depth of the new child.
+ void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
+
+ /// addChildLoop - Add the specified loop to be a child of this loop. This
+ /// updates the loop depth of the new child.
+ ///
+ void addChildLoop(LoopT *NewChild) {
+ assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
+ NewChild->ParentLoop = static_cast<LoopT *>(this);
+ SubLoops.push_back(NewChild);
+ }
+
+ /// removeChildLoop - This removes the specified child from being a subloop of
+ /// this loop. The loop is not deleted, as it will presumably be inserted
+ /// into another loop.
+ LoopT *removeChildLoop(iterator I) {
+ assert(I != SubLoops.end() && "Cannot remove end iterator!");
+ LoopT *Child = *I;
+ assert(Child->ParentLoop == this && "Child is not a child of this loop!");
+ SubLoops.erase(SubLoops.begin()+(I-begin()));
+ Child->ParentLoop = 0;
+ return Child;
+ }
+
+ /// addBlockEntry - This adds a basic block directly to the basic block list.
+ /// This should only be used by transformations that create new loops. Other
+ /// transformations should use addBasicBlockToLoop.
+ void addBlockEntry(BlockT *BB) {
+ Blocks.push_back(BB);
+ }
+
+ /// moveToHeader - This method is used to move BB (which must be part of this
+ /// loop) to be the loop header of the loop (the block that dominates all
+ /// others).
+ void moveToHeader(BlockT *BB) {
+ if (Blocks[0] == BB) return;
+ for (unsigned i = 0; ; ++i) {
+ assert(i != Blocks.size() && "Loop does not contain BB!");
+ if (Blocks[i] == BB) {
+ Blocks[i] = Blocks[0];
+ Blocks[0] = BB;
+ return;
+ }
+ }
+ }
+
+ /// removeBlockFromLoop - This removes the specified basic block from the
+ /// current loop, updating the Blocks as appropriate. This does not update
+ /// the mapping in the LoopInfo class.
+ void removeBlockFromLoop(BlockT *BB) {
+ RemoveFromVector(Blocks, BB);
+ }
+
+ /// verifyLoop - Verify loop structure
+ void verifyLoop() const;
+
+ /// verifyLoop - Verify loop structure of this loop and all nested loops.
+ void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
+
+ void print(raw_ostream &OS, unsigned Depth = 0) const;
+
+protected:
+ friend class LoopInfoBase<BlockT, LoopT>;
+ explicit LoopBase(BlockT *BB) : ParentLoop(0) {
+ Blocks.push_back(BB);
+ }
+};
+
+template<class BlockT, class LoopT>
+raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
+ Loop.print(OS);
+ return OS;
+}
+
+// Implementation in LoopInfoImpl.h
+#ifdef __GNUC__
+__extension__ extern template class LoopBase<BasicBlock, Loop>;
+#endif
+
+class Loop : public LoopBase<BasicBlock, Loop> {
+public:
+ Loop() {}
+
+ /// isLoopInvariant - Return true if the specified value is loop invariant
+ ///
+ bool isLoopInvariant(Value *V) const;
+
+ /// hasLoopInvariantOperands - Return true if all the operands of the
+ /// specified instruction are loop invariant.
+ bool hasLoopInvariantOperands(Instruction *I) const;
+
+ /// makeLoopInvariant - If the given value is an instruction inside of the
+ /// loop and it can be hoisted, do so to make it trivially loop-invariant.
+ /// Return true if the value after any hoisting is loop invariant. This
+ /// function can be used as a slightly more aggressive replacement for
+ /// isLoopInvariant.
+ ///
+ /// If InsertPt is specified, it is the point to hoist instructions to.
+ /// If null, the terminator of the loop preheader is used.
+ ///
+ bool makeLoopInvariant(Value *V, bool &Changed,
+ Instruction *InsertPt = 0) const;
+
+ /// makeLoopInvariant - If the given instruction is inside of the
+ /// loop and it can be hoisted, do so to make it trivially loop-invariant.
+ /// Return true if the instruction after any hoisting is loop invariant. This
+ /// function can be used as a slightly more aggressive replacement for
+ /// isLoopInvariant.
+ ///
+ /// If InsertPt is specified, it is the point to hoist instructions to.
+ /// If null, the terminator of the loop preheader is used.
+ ///
+ bool makeLoopInvariant(Instruction *I, bool &Changed,
+ Instruction *InsertPt = 0) const;
+
+ /// getCanonicalInductionVariable - Check to see if the loop has a canonical
+ /// induction variable: an integer recurrence that starts at 0 and increments
+ /// by one each time through the loop. If so, return the phi node that
+ /// corresponds to it.
+ ///
+ /// The IndVarSimplify pass transforms loops to have a canonical induction
+ /// variable.
+ ///
+ PHINode *getCanonicalInductionVariable() const;
+
+ /// isLCSSAForm - Return true if the Loop is in LCSSA form
+ bool isLCSSAForm(DominatorTree &DT) const;
+
+ /// isLoopSimplifyForm - Return true if the Loop is in the form that
+ /// the LoopSimplify form transforms loops to, which is sometimes called
+ /// normal form.
+ bool isLoopSimplifyForm() const;
+
+ /// isSafeToClone - Return true if the loop body is safe to clone in practice.
+ bool isSafeToClone() const;
+
+ /// hasDedicatedExits - Return true if no exit block for the loop
+ /// has a predecessor that is outside the loop.
+ bool hasDedicatedExits() const;
+
+ /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
+ /// These are the blocks _outside of the current loop_ which are branched to.
+ /// This assumes that loop exits are in canonical form.
+ ///
+ void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
+
+ /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
+ /// block, return that block. Otherwise return null.
+ BasicBlock *getUniqueExitBlock() const;
+
+ void dump() const;
+
+private:
+ friend class LoopInfoBase<BasicBlock, Loop>;
+ explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
+};
+
+//===----------------------------------------------------------------------===//
+/// LoopInfo - This class builds and contains all of the top level loop
+/// structures in the specified function.
+///
+
+template<class BlockT, class LoopT>
+class LoopInfoBase {
+ // BBMap - Mapping of basic blocks to the inner most loop they occur in
+ DenseMap<BlockT *, LoopT *> BBMap;
+ std::vector<LoopT *> TopLevelLoops;
+ friend class LoopBase<BlockT, LoopT>;
+ friend class LoopInfo;
+
+ void operator=(const LoopInfoBase &) LLVM_DELETED_FUNCTION;
+ LoopInfoBase(const LoopInfo &) LLVM_DELETED_FUNCTION;
+public:
+ LoopInfoBase() { }
+ ~LoopInfoBase() { releaseMemory(); }
+
+ void releaseMemory() {
+ for (typename std::vector<LoopT *>::iterator I =
+ TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
+ delete *I; // Delete all of the loops...
+
+ BBMap.clear(); // Reset internal state of analysis
+ TopLevelLoops.clear();
+ }
+
+ /// iterator/begin/end - The interface to the top-level loops in the current
+ /// function.
+ ///
+ typedef typename std::vector<LoopT *>::const_iterator iterator;
+ typedef typename std::vector<LoopT *>::const_reverse_iterator
+ reverse_iterator;
+ iterator begin() const { return TopLevelLoops.begin(); }
+ iterator end() const { return TopLevelLoops.end(); }
+ reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
+ reverse_iterator rend() const { return TopLevelLoops.rend(); }
+ bool empty() const { return TopLevelLoops.empty(); }
+
+ /// getLoopFor - Return the inner most loop that BB lives in. If a basic
+ /// block is in no loop (for example the entry node), null is returned.
+ ///
+ LoopT *getLoopFor(const BlockT *BB) const {
+ return BBMap.lookup(const_cast<BlockT*>(BB));
+ }
+
+ /// operator[] - same as getLoopFor...
+ ///
+ const LoopT *operator[](const BlockT *BB) const {
+ return getLoopFor(BB);
+ }
+
+ /// getLoopDepth - Return the loop nesting level of the specified block. A
+ /// depth of 0 means the block is not inside any loop.
+ ///
+ unsigned getLoopDepth(const BlockT *BB) const {
+ const LoopT *L = getLoopFor(BB);
+ return L ? L->getLoopDepth() : 0;
+ }
+
+ // isLoopHeader - True if the block is a loop header node
+ bool isLoopHeader(BlockT *BB) const {
+ const LoopT *L = getLoopFor(BB);
+ return L && L->getHeader() == BB;
+ }
+
+ /// removeLoop - This removes the specified top-level loop from this loop info
+ /// object. The loop is not deleted, as it will presumably be inserted into
+ /// another loop.
+ LoopT *removeLoop(iterator I) {
+ assert(I != end() && "Cannot remove end iterator!");
+ LoopT *L = *I;
+ assert(L->getParentLoop() == 0 && "Not a top-level loop!");
+ TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
+ return L;
+ }
+
+ /// changeLoopFor - Change the top-level loop that contains BB to the
+ /// specified loop. This should be used by transformations that restructure
+ /// the loop hierarchy tree.
+ void changeLoopFor(BlockT *BB, LoopT *L) {
+ if (!L) {
+ BBMap.erase(BB);
+ return;
+ }
+ BBMap[BB] = L;
+ }
+
+ /// changeTopLevelLoop - Replace the specified loop in the top-level loops
+ /// list with the indicated loop.
+ void changeTopLevelLoop(LoopT *OldLoop,
+ LoopT *NewLoop) {
+ typename std::vector<LoopT *>::iterator I =
+ std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
+ assert(I != TopLevelLoops.end() && "Old loop not at top level!");
+ *I = NewLoop;
+ assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
+ "Loops already embedded into a subloop!");
+ }
+
+ /// addTopLevelLoop - This adds the specified loop to the collection of
+ /// top-level loops.
+ void addTopLevelLoop(LoopT *New) {
+ assert(New->getParentLoop() == 0 && "Loop already in subloop!");
+ TopLevelLoops.push_back(New);
+ }
+
+ /// removeBlock - This method completely removes BB from all data structures,
+ /// including all of the Loop objects it is nested in and our mapping from
+ /// BasicBlocks to loops.
+ void removeBlock(BlockT *BB) {
+ typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
+ if (I != BBMap.end()) {
+ for (LoopT *L = I->second; L; L = L->getParentLoop())
+ L->removeBlockFromLoop(BB);
+
+ BBMap.erase(I);
+ }
+ }
+
+ // Internals
+
+ static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
+ const LoopT *ParentLoop) {
+ if (SubLoop == 0) return true;
+ if (SubLoop == ParentLoop) return false;
+ return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
+ }
+
+ /// Create the loop forest using a stable algorithm.
+ void Analyze(DominatorTreeBase<BlockT> &DomTree);
+
+ // Debugging
+
+ void print(raw_ostream &OS) const;
+};
+
+// Implementation in LoopInfoImpl.h
+#ifdef __GNUC__
+__extension__ extern template class LoopInfoBase<BasicBlock, Loop>;
+#endif
+
+class LoopInfo : public FunctionPass {
+ LoopInfoBase<BasicBlock, Loop> LI;
+ friend class LoopBase<BasicBlock, Loop>;
+
+ void operator=(const LoopInfo &) LLVM_DELETED_FUNCTION;
+ LoopInfo(const LoopInfo &) LLVM_DELETED_FUNCTION;
+public:
+ static char ID; // Pass identification, replacement for typeid
+
+ LoopInfo() : FunctionPass(ID) {
+ initializeLoopInfoPass(*PassRegistry::getPassRegistry());
+ }
+
+ LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
+
+ /// iterator/begin/end - The interface to the top-level loops in the current
+ /// function.
+ ///
+ typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
+ typedef LoopInfoBase<BasicBlock, Loop>::reverse_iterator reverse_iterator;
+ inline iterator begin() const { return LI.begin(); }
+ inline iterator end() const { return LI.end(); }
+ inline reverse_iterator rbegin() const { return LI.rbegin(); }
+ inline reverse_iterator rend() const { return LI.rend(); }
+ bool empty() const { return LI.empty(); }
+
+ /// getLoopFor - Return the inner most loop that BB lives in. If a basic
+ /// block is in no loop (for example the entry node), null is returned.
+ ///
+ inline Loop *getLoopFor(const BasicBlock *BB) const {
+ return LI.getLoopFor(BB);
+ }
+
+ /// operator[] - same as getLoopFor...
+ ///
+ inline const Loop *operator[](const BasicBlock *BB) const {
+ return LI.getLoopFor(BB);
+ }
+
+ /// getLoopDepth - Return the loop nesting level of the specified block. A
+ /// depth of 0 means the block is not inside any loop.
+ ///
+ inline unsigned getLoopDepth(const BasicBlock *BB) const {
+ return LI.getLoopDepth(BB);
+ }
+
+ // isLoopHeader - True if the block is a loop header node
+ inline bool isLoopHeader(BasicBlock *BB) const {
+ return LI.isLoopHeader(BB);
+ }
+
+ /// runOnFunction - Calculate the natural loop information.
+ ///
+ virtual bool runOnFunction(Function &F);
+
+ virtual void verifyAnalysis() const;
+
+ virtual void releaseMemory() { LI.releaseMemory(); }
+
+ virtual void print(raw_ostream &O, const Module* M = 0) const;
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ /// removeLoop - This removes the specified top-level loop from this loop info
+ /// object. The loop is not deleted, as it will presumably be inserted into
+ /// another loop.
+ inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
+
+ /// changeLoopFor - Change the top-level loop that contains BB to the
+ /// specified loop. This should be used by transformations that restructure
+ /// the loop hierarchy tree.
+ inline void changeLoopFor(BasicBlock *BB, Loop *L) {
+ LI.changeLoopFor(BB, L);
+ }
+
+ /// changeTopLevelLoop - Replace the specified loop in the top-level loops
+ /// list with the indicated loop.
+ inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
+ LI.changeTopLevelLoop(OldLoop, NewLoop);
+ }
+
+ /// addTopLevelLoop - This adds the specified loop to the collection of
+ /// top-level loops.
+ inline void addTopLevelLoop(Loop *New) {
+ LI.addTopLevelLoop(New);
+ }
+
+ /// removeBlock - This method completely removes BB from all data structures,
+ /// including all of the Loop objects it is nested in and our mapping from
+ /// BasicBlocks to loops.
+ void removeBlock(BasicBlock *BB) {
+ LI.removeBlock(BB);
+ }
+
+ /// updateUnloop - Update LoopInfo after removing the last backedge from a
+ /// loop--now the "unloop". This updates the loop forest and parent loops for
+ /// each block so that Unloop is no longer referenced, but the caller must
+ /// actually delete the Unloop object.
+ void updateUnloop(Loop *Unloop);
+
+ /// replacementPreservesLCSSAForm - Returns true if replacing From with To
+ /// everywhere is guaranteed to preserve LCSSA form.
+ bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
+ // Preserving LCSSA form is only problematic if the replacing value is an
+ // instruction.
+ Instruction *I = dyn_cast<Instruction>(To);
+ if (!I) return true;
+ // If both instructions are defined in the same basic block then replacement
+ // cannot break LCSSA form.
+ if (I->getParent() == From->getParent())
+ return true;
+ // If the instruction is not defined in a loop then it can safely replace
+ // anything.
+ Loop *ToLoop = getLoopFor(I->getParent());
+ if (!ToLoop) return true;
+ // If the replacing instruction is defined in the same loop as the original
+ // instruction, or in a loop that contains it as an inner loop, then using
+ // it as a replacement will not break LCSSA form.
+ return ToLoop->contains(getLoopFor(From->getParent()));
+ }
+};
+
+
+// Allow clients to walk the list of nested loops...
+template <> struct GraphTraits<const Loop*> {
+ typedef const Loop NodeType;
+ typedef LoopInfo::iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(const Loop *L) { return L; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->end();
+ }
+};
+
+template <> struct GraphTraits<Loop*> {
+ typedef Loop NodeType;
+ typedef LoopInfo::iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(Loop *L) { return L; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->end();
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/LoopInfoImpl.h b/include/llvm/Analysis/LoopInfoImpl.h
new file mode 100644
index 00000000000..3bb96f96bf5
--- /dev/null
+++ b/include/llvm/Analysis/LoopInfoImpl.h
@@ -0,0 +1,569 @@
+//===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This is the generic implementation of LoopInfo used for both Loops and
+// MachineLoops.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LOOP_INFO_IMPL_H
+#define LLVM_ANALYSIS_LOOP_INFO_IMPL_H
+
+#include "llvm/Analysis/LoopInfo.h"
+#include "llvm/ADT/PostOrderIterator.h"
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// APIs for simple analysis of the loop. See header notes.
+
+/// getExitingBlocks - Return all blocks inside the loop that have successors
+/// outside of the loop. These are the blocks _inside of the current loop_
+/// which branch out. The returned list is always unique.
+///
+template<class BlockT, class LoopT>
+void LoopBase<BlockT, LoopT>::
+getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
+ // Sort the blocks vector so that we can use binary search to do quick
+ // lookups.
+ SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
+ std::sort(LoopBBs.begin(), LoopBBs.end());
+
+ typedef GraphTraits<BlockT*> BlockTraits;
+ for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
+ for (typename BlockTraits::ChildIteratorType I =
+ BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
+ I != E; ++I)
+ if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
+ // Not in current loop? It must be an exit block.
+ ExitingBlocks.push_back(*BI);
+ break;
+ }
+}
+
+/// getExitingBlock - If getExitingBlocks would return exactly one block,
+/// return that block. Otherwise return null.
+template<class BlockT, class LoopT>
+BlockT *LoopBase<BlockT, LoopT>::getExitingBlock() const {
+ SmallVector<BlockT*, 8> ExitingBlocks;
+ getExitingBlocks(ExitingBlocks);
+ if (ExitingBlocks.size() == 1)
+ return ExitingBlocks[0];
+ return 0;
+}
+
+/// getExitBlocks - Return all of the successor blocks of this loop. These
+/// are the blocks _outside of the current loop_ which are branched to.
+///
+template<class BlockT, class LoopT>
+void LoopBase<BlockT, LoopT>::
+getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
+ // Sort the blocks vector so that we can use binary search to do quick
+ // lookups.
+ SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
+ std::sort(LoopBBs.begin(), LoopBBs.end());
+
+ typedef GraphTraits<BlockT*> BlockTraits;
+ for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
+ for (typename BlockTraits::ChildIteratorType I =
+ BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
+ I != E; ++I)
+ if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
+ // Not in current loop? It must be an exit block.
+ ExitBlocks.push_back(*I);
+}
+
+/// getExitBlock - If getExitBlocks would return exactly one block,
+/// return that block. Otherwise return null.
+template<class BlockT, class LoopT>
+BlockT *LoopBase<BlockT, LoopT>::getExitBlock() const {
+ SmallVector<BlockT*, 8> ExitBlocks;
+ getExitBlocks(ExitBlocks);
+ if (ExitBlocks.size() == 1)
+ return ExitBlocks[0];
+ return 0;
+}
+
+/// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
+template<class BlockT, class LoopT>
+void LoopBase<BlockT, LoopT>::
+getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
+ // Sort the blocks vector so that we can use binary search to do quick
+ // lookups.
+ SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
+ array_pod_sort(LoopBBs.begin(), LoopBBs.end());
+
+ typedef GraphTraits<BlockT*> BlockTraits;
+ for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
+ for (typename BlockTraits::ChildIteratorType I =
+ BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
+ I != E; ++I)
+ if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
+ // Not in current loop? It must be an exit block.
+ ExitEdges.push_back(Edge(*BI, *I));
+}
+
+/// getLoopPreheader - If there is a preheader for this loop, return it. A
+/// loop has a preheader if there is only one edge to the header of the loop
+/// from outside of the loop. If this is the case, the block branching to the
+/// header of the loop is the preheader node.
+///
+/// This method returns null if there is no preheader for the loop.
+///
+template<class BlockT, class LoopT>
+BlockT *LoopBase<BlockT, LoopT>::getLoopPreheader() const {
+ // Keep track of nodes outside the loop branching to the header...
+ BlockT *Out = getLoopPredecessor();
+ if (!Out) return 0;
+
+ // Make sure there is only one exit out of the preheader.
+ typedef GraphTraits<BlockT*> BlockTraits;
+ typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
+ ++SI;
+ if (SI != BlockTraits::child_end(Out))
+ return 0; // Multiple exits from the block, must not be a preheader.
+
+ // The predecessor has exactly one successor, so it is a preheader.
+ return Out;
+}
+
+/// getLoopPredecessor - If the given loop's header has exactly one unique
+/// predecessor outside the loop, return it. Otherwise return null.
+/// This is less strict that the loop "preheader" concept, which requires
+/// the predecessor to have exactly one successor.
+///
+template<class BlockT, class LoopT>
+BlockT *LoopBase<BlockT, LoopT>::getLoopPredecessor() const {
+ // Keep track of nodes outside the loop branching to the header...
+ BlockT *Out = 0;
+
+ // Loop over the predecessors of the header node...
+ BlockT *Header = getHeader();
+ typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
+ for (typename InvBlockTraits::ChildIteratorType PI =
+ InvBlockTraits::child_begin(Header),
+ PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
+ typename InvBlockTraits::NodeType *N = *PI;
+ if (!contains(N)) { // If the block is not in the loop...
+ if (Out && Out != N)
+ return 0; // Multiple predecessors outside the loop
+ Out = N;
+ }
+ }
+
+ // Make sure there is only one exit out of the preheader.
+ assert(Out && "Header of loop has no predecessors from outside loop?");
+ return Out;
+}
+
+/// getLoopLatch - If there is a single latch block for this loop, return it.
+/// A latch block is a block that contains a branch back to the header.
+template<class BlockT, class LoopT>
+BlockT *LoopBase<BlockT, LoopT>::getLoopLatch() const {
+ BlockT *Header = getHeader();
+ typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
+ typename InvBlockTraits::ChildIteratorType PI =
+ InvBlockTraits::child_begin(Header);
+ typename InvBlockTraits::ChildIteratorType PE =
+ InvBlockTraits::child_end(Header);
+ BlockT *Latch = 0;
+ for (; PI != PE; ++PI) {
+ typename InvBlockTraits::NodeType *N = *PI;
+ if (contains(N)) {
+ if (Latch) return 0;
+ Latch = N;
+ }
+ }
+
+ return Latch;
+}
+
+//===----------------------------------------------------------------------===//
+// APIs for updating loop information after changing the CFG
+//
+
+/// addBasicBlockToLoop - This method is used by other analyses to update loop
+/// information. NewBB is set to be a new member of the current loop.
+/// Because of this, it is added as a member of all parent loops, and is added
+/// to the specified LoopInfo object as being in the current basic block. It
+/// is not valid to replace the loop header with this method.
+///
+template<class BlockT, class LoopT>
+void LoopBase<BlockT, LoopT>::
+addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
+ assert((Blocks.empty() || LIB[getHeader()] == this) &&
+ "Incorrect LI specified for this loop!");
+ assert(NewBB && "Cannot add a null basic block to the loop!");
+ assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
+
+ LoopT *L = static_cast<LoopT *>(this);
+
+ // Add the loop mapping to the LoopInfo object...
+ LIB.BBMap[NewBB] = L;
+
+ // Add the basic block to this loop and all parent loops...
+ while (L) {
+ L->Blocks.push_back(NewBB);
+ L = L->getParentLoop();
+ }
+}
+
+/// replaceChildLoopWith - This is used when splitting loops up. It replaces
+/// the OldChild entry in our children list with NewChild, and updates the
+/// parent pointer of OldChild to be null and the NewChild to be this loop.
+/// This updates the loop depth of the new child.
+template<class BlockT, class LoopT>
+void LoopBase<BlockT, LoopT>::
+replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild) {
+ assert(OldChild->ParentLoop == this && "This loop is already broken!");
+ assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
+ typename std::vector<LoopT *>::iterator I =
+ std::find(SubLoops.begin(), SubLoops.end(), OldChild);
+ assert(I != SubLoops.end() && "OldChild not in loop!");
+ *I = NewChild;
+ OldChild->ParentLoop = 0;
+ NewChild->ParentLoop = static_cast<LoopT *>(this);
+}
+
+/// verifyLoop - Verify loop structure
+template<class BlockT, class LoopT>
+void LoopBase<BlockT, LoopT>::verifyLoop() const {
+#ifndef NDEBUG
+ assert(!Blocks.empty() && "Loop header is missing");
+
+ // Setup for using a depth-first iterator to visit every block in the loop.
+ SmallVector<BlockT*, 8> ExitBBs;
+ getExitBlocks(ExitBBs);
+ llvm::SmallPtrSet<BlockT*, 8> VisitSet;
+ VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
+ df_ext_iterator<BlockT*, llvm::SmallPtrSet<BlockT*, 8> >
+ BI = df_ext_begin(getHeader(), VisitSet),
+ BE = df_ext_end(getHeader(), VisitSet);
+
+ // Keep track of the number of BBs visited.
+ unsigned NumVisited = 0;
+
+ // Sort the blocks vector so that we can use binary search to do quick
+ // lookups.
+ SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
+ std::sort(LoopBBs.begin(), LoopBBs.end());
+
+ // Check the individual blocks.
+ for ( ; BI != BE; ++BI) {
+ BlockT *BB = *BI;
+ bool HasInsideLoopSuccs = false;
+ bool HasInsideLoopPreds = false;
+ SmallVector<BlockT *, 2> OutsideLoopPreds;
+
+ typedef GraphTraits<BlockT*> BlockTraits;
+ for (typename BlockTraits::ChildIteratorType SI =
+ BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
+ SI != SE; ++SI)
+ if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
+ HasInsideLoopSuccs = true;
+ break;
+ }
+ typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
+ for (typename InvBlockTraits::ChildIteratorType PI =
+ InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
+ PI != PE; ++PI) {
+ BlockT *N = *PI;
+ if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), N))
+ HasInsideLoopPreds = true;
+ else
+ OutsideLoopPreds.push_back(N);
+ }
+
+ if (BB == getHeader()) {
+ assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
+ } else if (!OutsideLoopPreds.empty()) {
+ // A non-header loop shouldn't be reachable from outside the loop,
+ // though it is permitted if the predecessor is not itself actually
+ // reachable.
+ BlockT *EntryBB = BB->getParent()->begin();
+ for (df_iterator<BlockT *> NI = df_begin(EntryBB),
+ NE = df_end(EntryBB); NI != NE; ++NI)
+ for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
+ assert(*NI != OutsideLoopPreds[i] &&
+ "Loop has multiple entry points!");
+ }
+ assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
+ assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
+ assert(BB != getHeader()->getParent()->begin() &&
+ "Loop contains function entry block!");
+
+ NumVisited++;
+ }
+
+ assert(NumVisited == getNumBlocks() && "Unreachable block in loop");
+
+ // Check the subloops.
+ for (iterator I = begin(), E = end(); I != E; ++I)
+ // Each block in each subloop should be contained within this loop.
+ for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
+ BI != BE; ++BI) {
+ assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
+ "Loop does not contain all the blocks of a subloop!");
+ }
+
+ // Check the parent loop pointer.
+ if (ParentLoop) {
+ assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
+ ParentLoop->end() &&
+ "Loop is not a subloop of its parent!");
+ }
+#endif
+}
+
+/// verifyLoop - Verify loop structure of this loop and all nested loops.
+template<class BlockT, class LoopT>
+void LoopBase<BlockT, LoopT>::verifyLoopNest(
+ DenseSet<const LoopT*> *Loops) const {
+ Loops->insert(static_cast<const LoopT *>(this));
+ // Verify this loop.
+ verifyLoop();
+ // Verify the subloops.
+ for (iterator I = begin(), E = end(); I != E; ++I)
+ (*I)->verifyLoopNest(Loops);
+}
+
+template<class BlockT, class LoopT>
+void LoopBase<BlockT, LoopT>::print(raw_ostream &OS, unsigned Depth) const {
+ OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
+ << " containing: ";
+
+ for (unsigned i = 0; i < getBlocks().size(); ++i) {
+ if (i) OS << ",";
+ BlockT *BB = getBlocks()[i];
+ WriteAsOperand(OS, BB, false);
+ if (BB == getHeader()) OS << "<header>";
+ if (BB == getLoopLatch()) OS << "<latch>";
+ if (isLoopExiting(BB)) OS << "<exiting>";
+ }
+ OS << "\n";
+
+ for (iterator I = begin(), E = end(); I != E; ++I)
+ (*I)->print(OS, Depth+2);
+}
+
+//===----------------------------------------------------------------------===//
+/// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
+/// result does / not depend on use list (block predecessor) order.
+///
+
+/// Discover a subloop with the specified backedges such that: All blocks within
+/// this loop are mapped to this loop or a subloop. And all subloops within this
+/// loop have their parent loop set to this loop or a subloop.
+template<class BlockT, class LoopT>
+static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT*> Backedges,
+ LoopInfoBase<BlockT, LoopT> *LI,
+ DominatorTreeBase<BlockT> &DomTree) {
+ typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
+
+ unsigned NumBlocks = 0;
+ unsigned NumSubloops = 0;
+
+ // Perform a backward CFG traversal using a worklist.
+ std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
+ while (!ReverseCFGWorklist.empty()) {
+ BlockT *PredBB = ReverseCFGWorklist.back();
+ ReverseCFGWorklist.pop_back();
+
+ LoopT *Subloop = LI->getLoopFor(PredBB);
+ if (!Subloop) {
+ if (!DomTree.isReachableFromEntry(PredBB))
+ continue;
+
+ // This is an undiscovered block. Map it to the current loop.
+ LI->changeLoopFor(PredBB, L);
+ ++NumBlocks;
+ if (PredBB == L->getHeader())
+ continue;
+ // Push all block predecessors on the worklist.
+ ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
+ InvBlockTraits::child_begin(PredBB),
+ InvBlockTraits::child_end(PredBB));
+ }
+ else {
+ // This is a discovered block. Find its outermost discovered loop.
+ while (LoopT *Parent = Subloop->getParentLoop())
+ Subloop = Parent;
+
+ // If it is already discovered to be a subloop of this loop, continue.
+ if (Subloop == L)
+ continue;
+
+ // Discover a subloop of this loop.
+ Subloop->setParentLoop(L);
+ ++NumSubloops;
+ NumBlocks += Subloop->getBlocks().capacity();
+ PredBB = Subloop->getHeader();
+ // Continue traversal along predecessors that are not loop-back edges from
+ // within this subloop tree itself. Note that a predecessor may directly
+ // reach another subloop that is not yet discovered to be a subloop of
+ // this loop, which we must traverse.
+ for (typename InvBlockTraits::ChildIteratorType PI =
+ InvBlockTraits::child_begin(PredBB),
+ PE = InvBlockTraits::child_end(PredBB); PI != PE; ++PI) {
+ if (LI->getLoopFor(*PI) != Subloop)
+ ReverseCFGWorklist.push_back(*PI);
+ }
+ }
+ }
+ L->getSubLoopsVector().reserve(NumSubloops);
+ L->getBlocksVector().reserve(NumBlocks);
+}
+
+namespace {
+/// Populate all loop data in a stable order during a single forward DFS.
+template<class BlockT, class LoopT>
+class PopulateLoopsDFS {
+ typedef GraphTraits<BlockT*> BlockTraits;
+ typedef typename BlockTraits::ChildIteratorType SuccIterTy;
+
+ LoopInfoBase<BlockT, LoopT> *LI;
+ DenseSet<const BlockT *> VisitedBlocks;
+ std::vector<std::pair<BlockT*, SuccIterTy> > DFSStack;
+
+public:
+ PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li):
+ LI(li) {}
+
+ void traverse(BlockT *EntryBlock);
+
+protected:
+ void insertIntoLoop(BlockT *Block);
+
+ BlockT *dfsSource() { return DFSStack.back().first; }
+ SuccIterTy &dfsSucc() { return DFSStack.back().second; }
+ SuccIterTy dfsSuccEnd() { return BlockTraits::child_end(dfsSource()); }
+
+ void pushBlock(BlockT *Block) {
+ DFSStack.push_back(std::make_pair(Block, BlockTraits::child_begin(Block)));
+ }
+};
+} // anonymous
+
+/// Top-level driver for the forward DFS within the loop.
+template<class BlockT, class LoopT>
+void PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
+ pushBlock(EntryBlock);
+ VisitedBlocks.insert(EntryBlock);
+ while (!DFSStack.empty()) {
+ // Traverse the leftmost path as far as possible.
+ while (dfsSucc() != dfsSuccEnd()) {
+ BlockT *BB = *dfsSucc();
+ ++dfsSucc();
+ if (!VisitedBlocks.insert(BB).second)
+ continue;
+
+ // Push the next DFS successor onto the stack.
+ pushBlock(BB);
+ }
+ // Visit the top of the stack in postorder and backtrack.
+ insertIntoLoop(dfsSource());
+ DFSStack.pop_back();
+ }
+}
+
+/// Add a single Block to its ancestor loops in PostOrder. If the block is a
+/// subloop header, add the subloop to its parent in PostOrder, then reverse the
+/// Block and Subloop vectors of the now complete subloop to achieve RPO.
+template<class BlockT, class LoopT>
+void PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
+ LoopT *Subloop = LI->getLoopFor(Block);
+ if (Subloop && Block == Subloop->getHeader()) {
+ // We reach this point once per subloop after processing all the blocks in
+ // the subloop.
+ if (Subloop->getParentLoop())
+ Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
+ else
+ LI->addTopLevelLoop(Subloop);
+
+ // For convenience, Blocks and Subloops are inserted in postorder. Reverse
+ // the lists, except for the loop header, which is always at the beginning.
+ std::reverse(Subloop->getBlocksVector().begin()+1,
+ Subloop->getBlocksVector().end());
+ std::reverse(Subloop->getSubLoopsVector().begin(),
+ Subloop->getSubLoopsVector().end());
+
+ Subloop = Subloop->getParentLoop();
+ }
+ for (; Subloop; Subloop = Subloop->getParentLoop())
+ Subloop->getBlocksVector().push_back(Block);
+}
+
+/// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
+/// interleaved with backward CFG traversals within each subloop
+/// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
+/// this part of the algorithm is linear in the number of CFG edges. Subloop and
+/// Block vectors are then populated during a single forward CFG traversal
+/// (PopulateLoopDFS).
+///
+/// During the two CFG traversals each block is seen three times:
+/// 1) Discovered and mapped by a reverse CFG traversal.
+/// 2) Visited during a forward DFS CFG traversal.
+/// 3) Reverse-inserted in the loop in postorder following forward DFS.
+///
+/// The Block vectors are inclusive, so step 3 requires loop-depth number of
+/// insertions per block.
+template<class BlockT, class LoopT>
+void LoopInfoBase<BlockT, LoopT>::
+Analyze(DominatorTreeBase<BlockT> &DomTree) {
+
+ // Postorder traversal of the dominator tree.
+ DomTreeNodeBase<BlockT>* DomRoot = DomTree.getRootNode();
+ for (po_iterator<DomTreeNodeBase<BlockT>*> DomIter = po_begin(DomRoot),
+ DomEnd = po_end(DomRoot); DomIter != DomEnd; ++DomIter) {
+
+ BlockT *Header = DomIter->getBlock();
+ SmallVector<BlockT *, 4> Backedges;
+
+ // Check each predecessor of the potential loop header.
+ typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
+ for (typename InvBlockTraits::ChildIteratorType PI =
+ InvBlockTraits::child_begin(Header),
+ PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
+
+ BlockT *Backedge = *PI;
+
+ // If Header dominates predBB, this is a new loop. Collect the backedges.
+ if (DomTree.dominates(Header, Backedge)
+ && DomTree.isReachableFromEntry(Backedge)) {
+ Backedges.push_back(Backedge);
+ }
+ }
+ // Perform a backward CFG traversal to discover and map blocks in this loop.
+ if (!Backedges.empty()) {
+ LoopT *L = new LoopT(Header);
+ discoverAndMapSubloop(L, ArrayRef<BlockT*>(Backedges), this, DomTree);
+ }
+ }
+ // Perform a single forward CFG traversal to populate block and subloop
+ // vectors for all loops.
+ PopulateLoopsDFS<BlockT, LoopT> DFS(this);
+ DFS.traverse(DomRoot->getBlock());
+}
+
+// Debugging
+template<class BlockT, class LoopT>
+void LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
+ for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
+ TopLevelLoops[i]->print(OS);
+#if 0
+ for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
+ E = BBMap.end(); I != E; ++I)
+ OS << "BB '" << I->first->getName() << "' level = "
+ << I->second->getLoopDepth() << "\n";
+#endif
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/LoopIterator.h b/include/llvm/Analysis/LoopIterator.h
new file mode 100644
index 00000000000..68f25f74bc2
--- /dev/null
+++ b/include/llvm/Analysis/LoopIterator.h
@@ -0,0 +1,182 @@
+//===--------- LoopIterator.h - Iterate over loop blocks --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+// This file defines iterators to visit the basic blocks within a loop.
+//
+// These iterators currently visit blocks within subloops as well.
+// Unfortunately we have no efficient way of summarizing loop exits which would
+// allow skipping subloops during traversal.
+//
+// If you want to visit all blocks in a loop and don't need an ordered traveral,
+// use Loop::block_begin() instead.
+//
+// This is intentionally designed to work with ill-formed loops in which the
+// backedge has been deleted. The only prerequisite is that all blocks
+// contained within the loop according to the most recent LoopInfo analysis are
+// reachable from the loop header.
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_LOOP_ITERATOR_H
+#define LLVM_ANALYSIS_LOOP_ITERATOR_H
+
+#include "llvm/ADT/DepthFirstIterator.h"
+#include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/Analysis/LoopInfo.h"
+
+namespace llvm {
+
+class LoopBlocksTraversal;
+
+/// Store the result of a depth first search within basic blocks contained by a
+/// single loop.
+///
+/// TODO: This could be generalized for any CFG region, or the entire CFG.
+class LoopBlocksDFS {
+public:
+ /// Postorder list iterators.
+ typedef std::vector<BasicBlock*>::const_iterator POIterator;
+ typedef std::vector<BasicBlock*>::const_reverse_iterator RPOIterator;
+
+ friend class LoopBlocksTraversal;
+
+private:
+ Loop *L;
+
+ /// Map each block to its postorder number. A block is only mapped after it is
+ /// preorder visited by DFS. It's postorder number is initially zero and set
+ /// to nonzero after it is finished by postorder traversal.
+ DenseMap<BasicBlock*, unsigned> PostNumbers;
+ std::vector<BasicBlock*> PostBlocks;
+
+public:
+ LoopBlocksDFS(Loop *Container) :
+ L(Container), PostNumbers(NextPowerOf2(Container->getNumBlocks())) {
+ PostBlocks.reserve(Container->getNumBlocks());
+ }
+
+ Loop *getLoop() const { return L; }
+
+ /// Traverse the loop blocks and store the DFS result.
+ void perform(LoopInfo *LI);
+
+ /// Return true if postorder numbers are assigned to all loop blocks.
+ bool isComplete() const { return PostBlocks.size() == L->getNumBlocks(); }
+
+ /// Iterate over the cached postorder blocks.
+ POIterator beginPostorder() const {
+ assert(isComplete() && "bad loop DFS");
+ return PostBlocks.begin();
+ }
+ POIterator endPostorder() const { return PostBlocks.end(); }
+
+ /// Reverse iterate over the cached postorder blocks.
+ RPOIterator beginRPO() const {
+ assert(isComplete() && "bad loop DFS");
+ return PostBlocks.rbegin();
+ }
+ RPOIterator endRPO() const { return PostBlocks.rend(); }
+
+ /// Return true if this block has been preorder visited.
+ bool hasPreorder(BasicBlock *BB) const { return PostNumbers.count(BB); }
+
+ /// Return true if this block has a postorder number.
+ bool hasPostorder(BasicBlock *BB) const {
+ DenseMap<BasicBlock*, unsigned>::const_iterator I = PostNumbers.find(BB);
+ return I != PostNumbers.end() && I->second;
+ }
+
+ /// Get a block's postorder number.
+ unsigned getPostorder(BasicBlock *BB) const {
+ DenseMap<BasicBlock*, unsigned>::const_iterator I = PostNumbers.find(BB);
+ assert(I != PostNumbers.end() && "block not visited by DFS");
+ assert(I->second && "block not finished by DFS");
+ return I->second;
+ }
+
+ /// Get a block's reverse postorder number.
+ unsigned getRPO(BasicBlock *BB) const {
+ return 1 + PostBlocks.size() - getPostorder(BB);
+ }
+
+ void clear() {
+ PostNumbers.clear();
+ PostBlocks.clear();
+ }
+};
+
+/// Specialize po_iterator_storage to record postorder numbers.
+template<> class po_iterator_storage<LoopBlocksTraversal, true> {
+ LoopBlocksTraversal &LBT;
+public:
+ po_iterator_storage(LoopBlocksTraversal &lbs) : LBT(lbs) {}
+ // These functions are defined below.
+ bool insertEdge(BasicBlock *From, BasicBlock *To);
+ void finishPostorder(BasicBlock *BB);
+};
+
+/// Traverse the blocks in a loop using a depth-first search.
+class LoopBlocksTraversal {
+public:
+ /// Graph traversal iterator.
+ typedef po_iterator<BasicBlock*, LoopBlocksTraversal, true> POTIterator;
+
+private:
+ LoopBlocksDFS &DFS;
+ LoopInfo *LI;
+
+public:
+ LoopBlocksTraversal(LoopBlocksDFS &Storage, LoopInfo *LInfo) :
+ DFS(Storage), LI(LInfo) {}
+
+ /// Postorder traversal over the graph. This only needs to be done once.
+ /// po_iterator "automatically" calls back to visitPreorder and
+ /// finishPostorder to record the DFS result.
+ POTIterator begin() {
+ assert(DFS.PostBlocks.empty() && "Need clear DFS result before traversing");
+ assert(DFS.L->getNumBlocks() && "po_iterator cannot handle an empty graph");
+ return po_ext_begin(DFS.L->getHeader(), *this);
+ }
+ POTIterator end() {
+ // po_ext_end interface requires a basic block, but ignores its value.
+ return po_ext_end(DFS.L->getHeader(), *this);
+ }
+
+ /// Called by po_iterator upon reaching a block via a CFG edge. If this block
+ /// is contained in the loop and has not been visited, then mark it preorder
+ /// visited and return true.
+ ///
+ /// TODO: If anyone is interested, we could record preorder numbers here.
+ bool visitPreorder(BasicBlock *BB) {
+ if (!DFS.L->contains(LI->getLoopFor(BB)))
+ return false;
+
+ return DFS.PostNumbers.insert(std::make_pair(BB, 0)).second;
+ }
+
+ /// Called by po_iterator each time it advances, indicating a block's
+ /// postorder.
+ void finishPostorder(BasicBlock *BB) {
+ assert(DFS.PostNumbers.count(BB) && "Loop DFS skipped preorder");
+ DFS.PostBlocks.push_back(BB);
+ DFS.PostNumbers[BB] = DFS.PostBlocks.size();
+ }
+};
+
+inline bool po_iterator_storage<LoopBlocksTraversal, true>::
+insertEdge(BasicBlock *From, BasicBlock *To) {
+ return LBT.visitPreorder(To);
+}
+
+inline void po_iterator_storage<LoopBlocksTraversal, true>::
+finishPostorder(BasicBlock *BB) {
+ LBT.finishPostorder(BB);
+}
+
+} // End namespace llvm
+
+#endif
diff --git a/include/llvm/Analysis/LoopPass.h b/include/llvm/Analysis/LoopPass.h
new file mode 100644
index 00000000000..e6ed9bccee3
--- /dev/null
+++ b/include/llvm/Analysis/LoopPass.h
@@ -0,0 +1,158 @@
+//===- LoopPass.h - LoopPass class ----------------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines LoopPass class. All loop optimization
+// and transformation passes are derived from LoopPass.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LOOP_PASS_H
+#define LLVM_LOOP_PASS_H
+
+#include "llvm/Analysis/LoopInfo.h"
+#include "llvm/Pass.h"
+#include "llvm/PassManagers.h"
+#include "llvm/Function.h"
+#include <deque>
+
+namespace llvm {
+
+class LPPassManager;
+class Function;
+class PMStack;
+
+class LoopPass : public Pass {
+public:
+ explicit LoopPass(char &pid) : Pass(PT_Loop, pid) {}
+
+ /// getPrinterPass - Get a pass to print the function corresponding
+ /// to a Loop.
+ Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
+
+ // runOnLoop - This method should be implemented by the subclass to perform
+ // whatever action is necessary for the specified Loop.
+ virtual bool runOnLoop(Loop *L, LPPassManager &LPM) = 0;
+
+ // Initialization and finalization hooks.
+ virtual bool doInitialization(Loop *L, LPPassManager &LPM) {
+ return false;
+ }
+
+ // Finalization hook does not supply Loop because at this time
+ // loop nest is completely different.
+ virtual bool doFinalization() { return false; }
+
+ // Check if this pass is suitable for the current LPPassManager, if
+ // available. This pass P is not suitable for a LPPassManager if P
+ // is not preserving higher level analysis info used by other
+ // LPPassManager passes. In such case, pop LPPassManager from the
+ // stack. This will force assignPassManager() to create new
+ // LPPassManger as expected.
+ void preparePassManager(PMStack &PMS);
+
+ /// Assign pass manager to manage this pass
+ virtual void assignPassManager(PMStack &PMS,
+ PassManagerType PMT);
+
+ /// Return what kind of Pass Manager can manage this pass.
+ virtual PassManagerType getPotentialPassManagerType() const {
+ return PMT_LoopPassManager;
+ }
+
+ //===--------------------------------------------------------------------===//
+ /// SimpleAnalysis - Provides simple interface to update analysis info
+ /// maintained by various passes. Note, if required this interface can
+ /// be extracted into a separate abstract class but it would require
+ /// additional use of multiple inheritance in Pass class hierarchy, something
+ /// we are trying to avoid.
+
+ /// Each loop pass can override these simple analysis hooks to update
+ /// desired analysis information.
+ /// cloneBasicBlockAnalysis - Clone analysis info associated with basic block.
+ virtual void cloneBasicBlockAnalysis(BasicBlock *F, BasicBlock *T, Loop *L) {}
+
+ /// deleteAnalysisValue - Delete analysis info associated with value V.
+ virtual void deleteAnalysisValue(Value *V, Loop *L) {}
+};
+
+class LPPassManager : public FunctionPass, public PMDataManager {
+public:
+ static char ID;
+ explicit LPPassManager();
+
+ /// run - Execute all of the passes scheduled for execution. Keep track of
+ /// whether any of the passes modifies the module, and if so, return true.
+ bool runOnFunction(Function &F);
+
+ /// Pass Manager itself does not invalidate any analysis info.
+ // LPPassManager needs LoopInfo.
+ void getAnalysisUsage(AnalysisUsage &Info) const;
+
+ virtual const char *getPassName() const {
+ return "Loop Pass Manager";
+ }
+
+ virtual PMDataManager *getAsPMDataManager() { return this; }
+ virtual Pass *getAsPass() { return this; }
+
+ /// Print passes managed by this manager
+ void dumpPassStructure(unsigned Offset);
+
+ LoopPass *getContainedPass(unsigned N) {
+ assert(N < PassVector.size() && "Pass number out of range!");
+ LoopPass *LP = static_cast<LoopPass *>(PassVector[N]);
+ return LP;
+ }
+
+ virtual PassManagerType getPassManagerType() const {
+ return PMT_LoopPassManager;
+ }
+
+public:
+ // Delete loop from the loop queue and loop nest (LoopInfo).
+ void deleteLoopFromQueue(Loop *L);
+
+ // Insert loop into the loop queue and add it as a child of the
+ // given parent.
+ void insertLoop(Loop *L, Loop *ParentLoop);
+
+ // Insert a loop into the loop queue.
+ void insertLoopIntoQueue(Loop *L);
+
+ // Reoptimize this loop. LPPassManager will re-insert this loop into the
+ // queue. This allows LoopPass to change loop nest for the loop. This
+ // utility may send LPPassManager into infinite loops so use caution.
+ void redoLoop(Loop *L);
+
+ //===--------------------------------------------------------------------===//
+ /// SimpleAnalysis - Provides simple interface to update analysis info
+ /// maintained by various passes. Note, if required this interface can
+ /// be extracted into a separate abstract class but it would require
+ /// additional use of multiple inheritance in Pass class hierarchy, something
+ /// we are trying to avoid.
+
+ /// cloneBasicBlockSimpleAnalysis - Invoke cloneBasicBlockAnalysis hook for
+ /// all passes that implement simple analysis interface.
+ void cloneBasicBlockSimpleAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
+
+ /// deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes
+ /// that implement simple analysis interface.
+ void deleteSimpleAnalysisValue(Value *V, Loop *L);
+
+private:
+ std::deque<Loop *> LQ;
+ bool skipThisLoop;
+ bool redoThisLoop;
+ LoopInfo *LI;
+ Loop *CurrentLoop;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/MemoryBuiltins.h b/include/llvm/Analysis/MemoryBuiltins.h
new file mode 100644
index 00000000000..c3ae603b704
--- /dev/null
+++ b/include/llvm/Analysis/MemoryBuiltins.h
@@ -0,0 +1,265 @@
+//===- llvm/Analysis/MemoryBuiltins.h- Calls to memory builtins -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This family of functions identifies calls to builtin functions that allocate
+// or free memory.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_MEMORYBUILTINS_H
+#define LLVM_ANALYSIS_MEMORYBUILTINS_H
+
+#include "llvm/IRBuilder.h"
+#include "llvm/Operator.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/InstVisitor.h"
+#include "llvm/Support/TargetFolder.h"
+#include "llvm/Support/ValueHandle.h"
+
+namespace llvm {
+class CallInst;
+class PointerType;
+class TargetData;
+class TargetLibraryInfo;
+class Type;
+class Value;
+
+
+/// \brief Tests if a value is a call or invoke to a library function that
+/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
+/// like).
+bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
+ bool LookThroughBitCast = false);
+
+/// \brief Tests if a value is a call or invoke to a function that returns a
+/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
+bool isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
+ bool LookThroughBitCast = false);
+
+/// \brief Tests if a value is a call or invoke to a library function that
+/// allocates uninitialized memory (such as malloc).
+bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
+ bool LookThroughBitCast = false);
+
+/// \brief Tests if a value is a call or invoke to a library function that
+/// allocates zero-filled memory (such as calloc).
+bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
+ bool LookThroughBitCast = false);
+
+/// \brief Tests if a value is a call or invoke to a library function that
+/// allocates memory (either malloc, calloc, or strdup like).
+bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
+ bool LookThroughBitCast = false);
+
+/// \brief Tests if a value is a call or invoke to a library function that
+/// reallocates memory (such as realloc).
+bool isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
+ bool LookThroughBitCast = false);
+
+
+//===----------------------------------------------------------------------===//
+// malloc Call Utility Functions.
+//
+
+/// extractMallocCall - Returns the corresponding CallInst if the instruction
+/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
+/// ignore InvokeInst here.
+const CallInst *extractMallocCall(const Value *I, const TargetLibraryInfo *TLI);
+static inline CallInst *extractMallocCall(Value *I,
+ const TargetLibraryInfo *TLI) {
+ return const_cast<CallInst*>(extractMallocCall((const Value*)I, TLI));
+}
+
+/// isArrayMalloc - Returns the corresponding CallInst if the instruction
+/// is a call to malloc whose array size can be determined and the array size
+/// is not constant 1. Otherwise, return NULL.
+const CallInst *isArrayMalloc(const Value *I, const TargetData *TD,
+ const TargetLibraryInfo *TLI);
+
+/// getMallocType - Returns the PointerType resulting from the malloc call.
+/// The PointerType depends on the number of bitcast uses of the malloc call:
+/// 0: PointerType is the malloc calls' return type.
+/// 1: PointerType is the bitcast's result type.
+/// >1: Unique PointerType cannot be determined, return NULL.
+PointerType *getMallocType(const CallInst *CI, const TargetLibraryInfo *TLI);
+
+/// getMallocAllocatedType - Returns the Type allocated by malloc call.
+/// The Type depends on the number of bitcast uses of the malloc call:
+/// 0: PointerType is the malloc calls' return type.
+/// 1: PointerType is the bitcast's result type.
+/// >1: Unique PointerType cannot be determined, return NULL.
+Type *getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI);
+
+/// getMallocArraySize - Returns the array size of a malloc call. If the
+/// argument passed to malloc is a multiple of the size of the malloced type,
+/// then return that multiple. For non-array mallocs, the multiple is
+/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
+/// determined.
+Value *getMallocArraySize(CallInst *CI, const TargetData *TD,
+ const TargetLibraryInfo *TLI,
+ bool LookThroughSExt = false);
+
+
+//===----------------------------------------------------------------------===//
+// calloc Call Utility Functions.
+//
+
+/// extractCallocCall - Returns the corresponding CallInst if the instruction
+/// is a calloc call.
+const CallInst *extractCallocCall(const Value *I, const TargetLibraryInfo *TLI);
+static inline CallInst *extractCallocCall(Value *I,
+ const TargetLibraryInfo *TLI) {
+ return const_cast<CallInst*>(extractCallocCall((const Value*)I, TLI));
+}
+
+
+//===----------------------------------------------------------------------===//
+// free Call Utility Functions.
+//
+
+/// isFreeCall - Returns non-null if the value is a call to the builtin free()
+const CallInst *isFreeCall(const Value *I, const TargetLibraryInfo *TLI);
+
+static inline CallInst *isFreeCall(Value *I, const TargetLibraryInfo *TLI) {
+ return const_cast<CallInst*>(isFreeCall((const Value*)I, TLI));
+}
+
+
+//===----------------------------------------------------------------------===//
+// Utility functions to compute size of objects.
+//
+
+/// \brief Compute the size of the object pointed by Ptr. Returns true and the
+/// object size in Size if successful, and false otherwise.
+/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
+/// byval arguments, and global variables.
+bool getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
+ const TargetLibraryInfo *TLI, bool RoundToAlign = false);
+
+
+
+typedef std::pair<APInt, APInt> SizeOffsetType;
+
+/// \brief Evaluate the size and offset of an object ponted by a Value*
+/// statically. Fails if size or offset are not known at compile time.
+class ObjectSizeOffsetVisitor
+ : public InstVisitor<ObjectSizeOffsetVisitor, SizeOffsetType> {
+
+ const TargetData *TD;
+ const TargetLibraryInfo *TLI;
+ bool RoundToAlign;
+ unsigned IntTyBits;
+ APInt Zero;
+ SmallPtrSet<Instruction *, 8> SeenInsts;
+
+ APInt align(APInt Size, uint64_t Align);
+
+ SizeOffsetType unknown() {
+ return std::make_pair(APInt(), APInt());
+ }
+
+public:
+ ObjectSizeOffsetVisitor(const TargetData *TD, const TargetLibraryInfo *TLI,
+ LLVMContext &Context, bool RoundToAlign = false);
+
+ SizeOffsetType compute(Value *V);
+
+ bool knownSize(SizeOffsetType &SizeOffset) {
+ return SizeOffset.first.getBitWidth() > 1;
+ }
+
+ bool knownOffset(SizeOffsetType &SizeOffset) {
+ return SizeOffset.second.getBitWidth() > 1;
+ }
+
+ bool bothKnown(SizeOffsetType &SizeOffset) {
+ return knownSize(SizeOffset) && knownOffset(SizeOffset);
+ }
+
+ SizeOffsetType visitAllocaInst(AllocaInst &I);
+ SizeOffsetType visitArgument(Argument &A);
+ SizeOffsetType visitCallSite(CallSite CS);
+ SizeOffsetType visitConstantPointerNull(ConstantPointerNull&);
+ SizeOffsetType visitExtractElementInst(ExtractElementInst &I);
+ SizeOffsetType visitExtractValueInst(ExtractValueInst &I);
+ SizeOffsetType visitGEPOperator(GEPOperator &GEP);
+ SizeOffsetType visitGlobalVariable(GlobalVariable &GV);
+ SizeOffsetType visitIntToPtrInst(IntToPtrInst&);
+ SizeOffsetType visitLoadInst(LoadInst &I);
+ SizeOffsetType visitPHINode(PHINode&);
+ SizeOffsetType visitSelectInst(SelectInst &I);
+ SizeOffsetType visitUndefValue(UndefValue&);
+ SizeOffsetType visitInstruction(Instruction &I);
+};
+
+typedef std::pair<Value*, Value*> SizeOffsetEvalType;
+
+
+/// \brief Evaluate the size and offset of an object ponted by a Value*.
+/// May create code to compute the result at run-time.
+class ObjectSizeOffsetEvaluator
+ : public InstVisitor<ObjectSizeOffsetEvaluator, SizeOffsetEvalType> {
+
+ typedef IRBuilder<true, TargetFolder> BuilderTy;
+ typedef std::pair<WeakVH, WeakVH> WeakEvalType;
+ typedef DenseMap<const Value*, WeakEvalType> CacheMapTy;
+ typedef SmallPtrSet<const Value*, 8> PtrSetTy;
+
+ const TargetData *TD;
+ const TargetLibraryInfo *TLI;
+ LLVMContext &Context;
+ BuilderTy Builder;
+ IntegerType *IntTy;
+ Value *Zero;
+ CacheMapTy CacheMap;
+ PtrSetTy SeenVals;
+
+ SizeOffsetEvalType unknown() {
+ return std::make_pair((Value*)0, (Value*)0);
+ }
+ SizeOffsetEvalType compute_(Value *V);
+
+public:
+ ObjectSizeOffsetEvaluator(const TargetData *TD, const TargetLibraryInfo *TLI,
+ LLVMContext &Context);
+ SizeOffsetEvalType compute(Value *V);
+
+ bool knownSize(SizeOffsetEvalType SizeOffset) {
+ return SizeOffset.first;
+ }
+
+ bool knownOffset(SizeOffsetEvalType SizeOffset) {
+ return SizeOffset.second;
+ }
+
+ bool anyKnown(SizeOffsetEvalType SizeOffset) {
+ return knownSize(SizeOffset) || knownOffset(SizeOffset);
+ }
+
+ bool bothKnown(SizeOffsetEvalType SizeOffset) {
+ return knownSize(SizeOffset) && knownOffset(SizeOffset);
+ }
+
+ SizeOffsetEvalType visitAllocaInst(AllocaInst &I);
+ SizeOffsetEvalType visitCallSite(CallSite CS);
+ SizeOffsetEvalType visitExtractElementInst(ExtractElementInst &I);
+ SizeOffsetEvalType visitExtractValueInst(ExtractValueInst &I);
+ SizeOffsetEvalType visitGEPOperator(GEPOperator &GEP);
+ SizeOffsetEvalType visitIntToPtrInst(IntToPtrInst&);
+ SizeOffsetEvalType visitLoadInst(LoadInst &I);
+ SizeOffsetEvalType visitPHINode(PHINode &PHI);
+ SizeOffsetEvalType visitSelectInst(SelectInst &I);
+ SizeOffsetEvalType visitInstruction(Instruction &I);
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/MemoryDependenceAnalysis.h b/include/llvm/Analysis/MemoryDependenceAnalysis.h
new file mode 100644
index 00000000000..7e049d633b4
--- /dev/null
+++ b/include/llvm/Analysis/MemoryDependenceAnalysis.h
@@ -0,0 +1,442 @@
+//===- llvm/Analysis/MemoryDependenceAnalysis.h - Memory Deps --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MemoryDependenceAnalysis analysis pass.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_MEMORY_DEPENDENCE_H
+#define LLVM_ANALYSIS_MEMORY_DEPENDENCE_H
+
+#include "llvm/BasicBlock.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/ValueHandle.h"
+#include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/PointerIntPair.h"
+
+namespace llvm {
+ class Function;
+ class FunctionPass;
+ class Instruction;
+ class CallSite;
+ class AliasAnalysis;
+ class TargetData;
+ class MemoryDependenceAnalysis;
+ class PredIteratorCache;
+ class DominatorTree;
+ class PHITransAddr;
+
+ /// MemDepResult - A memory dependence query can return one of three different
+ /// answers, described below.
+ class MemDepResult {
+ enum DepType {
+ /// Invalid - Clients of MemDep never see this.
+ Invalid = 0,
+
+ /// Clobber - This is a dependence on the specified instruction which
+ /// clobbers the desired value. The pointer member of the MemDepResult
+ /// pair holds the instruction that clobbers the memory. For example,
+ /// this occurs when we see a may-aliased store to the memory location we
+ /// care about.
+ ///
+ /// There are several cases that may be interesting here:
+ /// 1. Loads are clobbered by may-alias stores.
+ /// 2. Loads are considered clobbered by partially-aliased loads. The
+ /// client may choose to analyze deeper into these cases.
+ Clobber,
+
+ /// Def - This is a dependence on the specified instruction which
+ /// defines/produces the desired memory location. The pointer member of
+ /// the MemDepResult pair holds the instruction that defines the memory.
+ /// Cases of interest:
+ /// 1. This could be a load or store for dependence queries on
+ /// load/store. The value loaded or stored is the produced value.
+ /// Note that the pointer operand may be different than that of the
+ /// queried pointer due to must aliases and phi translation. Note
+ /// that the def may not be the same type as the query, the pointers
+ /// may just be must aliases.
+ /// 2. For loads and stores, this could be an allocation instruction. In
+ /// this case, the load is loading an undef value or a store is the
+ /// first store to (that part of) the allocation.
+ /// 3. Dependence queries on calls return Def only when they are
+ /// readonly calls or memory use intrinsics with identical callees
+ /// and no intervening clobbers. No validation is done that the
+ /// operands to the calls are the same.
+ Def,
+
+ /// Other - This marker indicates that the query has no known dependency
+ /// in the specified block. More detailed state info is encoded in the
+ /// upper part of the pair (i.e. the Instruction*)
+ Other
+ };
+ /// If DepType is "Other", the upper part of the pair
+ /// (i.e. the Instruction* part) is instead used to encode more detailed
+ /// type information as follows
+ enum OtherType {
+ /// NonLocal - This marker indicates that the query has no dependency in
+ /// the specified block. To find out more, the client should query other
+ /// predecessor blocks.
+ NonLocal = 0x4,
+ /// NonFuncLocal - This marker indicates that the query has no
+ /// dependency in the specified function.
+ NonFuncLocal = 0x8,
+ /// Unknown - This marker indicates that the query dependency
+ /// is unknown.
+ Unknown = 0xc
+ };
+
+ typedef PointerIntPair<Instruction*, 2, DepType> PairTy;
+ PairTy Value;
+ explicit MemDepResult(PairTy V) : Value(V) {}
+ public:
+ MemDepResult() : Value(0, Invalid) {}
+
+ /// get methods: These are static ctor methods for creating various
+ /// MemDepResult kinds.
+ static MemDepResult getDef(Instruction *Inst) {
+ assert(Inst && "Def requires inst");
+ return MemDepResult(PairTy(Inst, Def));
+ }
+ static MemDepResult getClobber(Instruction *Inst) {
+ assert(Inst && "Clobber requires inst");
+ return MemDepResult(PairTy(Inst, Clobber));
+ }
+ static MemDepResult getNonLocal() {
+ return MemDepResult(
+ PairTy(reinterpret_cast<Instruction*>(NonLocal), Other));
+ }
+ static MemDepResult getNonFuncLocal() {
+ return MemDepResult(
+ PairTy(reinterpret_cast<Instruction*>(NonFuncLocal), Other));
+ }
+ static MemDepResult getUnknown() {
+ return MemDepResult(
+ PairTy(reinterpret_cast<Instruction*>(Unknown), Other));
+ }
+
+ /// isClobber - Return true if this MemDepResult represents a query that is
+ /// an instruction clobber dependency.
+ bool isClobber() const { return Value.getInt() == Clobber; }
+
+ /// isDef - Return true if this MemDepResult represents a query that is
+ /// an instruction definition dependency.
+ bool isDef() const { return Value.getInt() == Def; }
+
+ /// isNonLocal - Return true if this MemDepResult represents a query that
+ /// is transparent to the start of the block, but where a non-local hasn't
+ /// been done.
+ bool isNonLocal() const {
+ return Value.getInt() == Other
+ && Value.getPointer() == reinterpret_cast<Instruction*>(NonLocal);
+ }
+
+ /// isNonFuncLocal - Return true if this MemDepResult represents a query
+ /// that is transparent to the start of the function.
+ bool isNonFuncLocal() const {
+ return Value.getInt() == Other
+ && Value.getPointer() == reinterpret_cast<Instruction*>(NonFuncLocal);
+ }
+
+ /// isUnknown - Return true if this MemDepResult represents a query which
+ /// cannot and/or will not be computed.
+ bool isUnknown() const {
+ return Value.getInt() == Other
+ && Value.getPointer() == reinterpret_cast<Instruction*>(Unknown);
+ }
+
+ /// getInst() - If this is a normal dependency, return the instruction that
+ /// is depended on. Otherwise, return null.
+ Instruction *getInst() const {
+ if (Value.getInt() == Other) return NULL;
+ return Value.getPointer();
+ }
+
+ bool operator==(const MemDepResult &M) const { return Value == M.Value; }
+ bool operator!=(const MemDepResult &M) const { return Value != M.Value; }
+ bool operator<(const MemDepResult &M) const { return Value < M.Value; }
+ bool operator>(const MemDepResult &M) const { return Value > M.Value; }
+ private:
+ friend class MemoryDependenceAnalysis;
+ /// Dirty - Entries with this marker occur in a LocalDeps map or
+ /// NonLocalDeps map when the instruction they previously referenced was
+ /// removed from MemDep. In either case, the entry may include an
+ /// instruction pointer. If so, the pointer is an instruction in the
+ /// block where scanning can start from, saving some work.
+ ///
+ /// In a default-constructed MemDepResult object, the type will be Dirty
+ /// and the instruction pointer will be null.
+ ///
+
+ /// isDirty - Return true if this is a MemDepResult in its dirty/invalid.
+ /// state.
+ bool isDirty() const { return Value.getInt() == Invalid; }
+
+ static MemDepResult getDirty(Instruction *Inst) {
+ return MemDepResult(PairTy(Inst, Invalid));
+ }
+ };
+
+ /// NonLocalDepEntry - This is an entry in the NonLocalDepInfo cache. For
+ /// each BasicBlock (the BB entry) it keeps a MemDepResult.
+ class NonLocalDepEntry {
+ BasicBlock *BB;
+ MemDepResult Result;
+ public:
+ NonLocalDepEntry(BasicBlock *bb, MemDepResult result)
+ : BB(bb), Result(result) {}
+
+ // This is used for searches.
+ NonLocalDepEntry(BasicBlock *bb) : BB(bb) {}
+
+ // BB is the sort key, it can't be changed.
+ BasicBlock *getBB() const { return BB; }
+
+ void setResult(const MemDepResult &R) { Result = R; }
+
+ const MemDepResult &getResult() const { return Result; }
+
+ bool operator<(const NonLocalDepEntry &RHS) const {
+ return BB < RHS.BB;
+ }
+ };
+
+ /// NonLocalDepResult - This is a result from a NonLocal dependence query.
+ /// For each BasicBlock (the BB entry) it keeps a MemDepResult and the
+ /// (potentially phi translated) address that was live in the block.
+ class NonLocalDepResult {
+ NonLocalDepEntry Entry;
+ Value *Address;
+ public:
+ NonLocalDepResult(BasicBlock *bb, MemDepResult result, Value *address)
+ : Entry(bb, result), Address(address) {}
+
+ // BB is the sort key, it can't be changed.
+ BasicBlock *getBB() const { return Entry.getBB(); }
+
+ void setResult(const MemDepResult &R, Value *Addr) {
+ Entry.setResult(R);
+ Address = Addr;
+ }
+
+ const MemDepResult &getResult() const { return Entry.getResult(); }
+
+ /// getAddress - Return the address of this pointer in this block. This can
+ /// be different than the address queried for the non-local result because
+ /// of phi translation. This returns null if the address was not available
+ /// in a block (i.e. because phi translation failed) or if this is a cached
+ /// result and that address was deleted.
+ ///
+ /// The address is always null for a non-local 'call' dependence.
+ Value *getAddress() const { return Address; }
+ };
+
+ /// MemoryDependenceAnalysis - This is an analysis that determines, for a
+ /// given memory operation, what preceding memory operations it depends on.
+ /// It builds on alias analysis information, and tries to provide a lazy,
+ /// caching interface to a common kind of alias information query.
+ ///
+ /// The dependency information returned is somewhat unusual, but is pragmatic.
+ /// If queried about a store or call that might modify memory, the analysis
+ /// will return the instruction[s] that may either load from that memory or
+ /// store to it. If queried with a load or call that can never modify memory,
+ /// the analysis will return calls and stores that might modify the pointer,
+ /// but generally does not return loads unless a) they are volatile, or
+ /// b) they load from *must-aliased* pointers. Returning a dependence on
+ /// must-alias'd pointers instead of all pointers interacts well with the
+ /// internal caching mechanism.
+ ///
+ class MemoryDependenceAnalysis : public FunctionPass {
+ // A map from instructions to their dependency.
+ typedef DenseMap<Instruction*, MemDepResult> LocalDepMapType;
+ LocalDepMapType LocalDeps;
+
+ public:
+ typedef std::vector<NonLocalDepEntry> NonLocalDepInfo;
+ private:
+ /// ValueIsLoadPair - This is a pair<Value*, bool> where the bool is true if
+ /// the dependence is a read only dependence, false if read/write.
+ typedef PointerIntPair<const Value*, 1, bool> ValueIsLoadPair;
+
+ /// BBSkipFirstBlockPair - This pair is used when caching information for a
+ /// block. If the pointer is null, the cache value is not a full query that
+ /// starts at the specified block. If non-null, the bool indicates whether
+ /// or not the contents of the block was skipped.
+ typedef PointerIntPair<BasicBlock*, 1, bool> BBSkipFirstBlockPair;
+
+ /// NonLocalPointerInfo - This record is the information kept for each
+ /// (value, is load) pair.
+ struct NonLocalPointerInfo {
+ /// Pair - The pair of the block and the skip-first-block flag.
+ BBSkipFirstBlockPair Pair;
+ /// NonLocalDeps - The results of the query for each relevant block.
+ NonLocalDepInfo NonLocalDeps;
+ /// Size - The maximum size of the dereferences of the
+ /// pointer. May be UnknownSize if the sizes are unknown.
+ uint64_t Size;
+ /// TBAATag - The TBAA tag associated with dereferences of the
+ /// pointer. May be null if there are no tags or conflicting tags.
+ const MDNode *TBAATag;
+
+ NonLocalPointerInfo() : Size(AliasAnalysis::UnknownSize), TBAATag(0) {}
+ };
+
+ /// CachedNonLocalPointerInfo - This map stores the cached results of doing
+ /// a pointer lookup at the bottom of a block. The key of this map is the
+ /// pointer+isload bit, the value is a list of <bb->result> mappings.
+ typedef DenseMap<ValueIsLoadPair,
+ NonLocalPointerInfo> CachedNonLocalPointerInfo;
+ CachedNonLocalPointerInfo NonLocalPointerDeps;
+
+ // A map from instructions to their non-local pointer dependencies.
+ typedef DenseMap<Instruction*,
+ SmallPtrSet<ValueIsLoadPair, 4> > ReverseNonLocalPtrDepTy;
+ ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
+
+
+ /// PerInstNLInfo - This is the instruction we keep for each cached access
+ /// that we have for an instruction. The pointer is an owning pointer and
+ /// the bool indicates whether we have any dirty bits in the set.
+ typedef std::pair<NonLocalDepInfo, bool> PerInstNLInfo;
+
+ // A map from instructions to their non-local dependencies.
+ typedef DenseMap<Instruction*, PerInstNLInfo> NonLocalDepMapType;
+
+ NonLocalDepMapType NonLocalDeps;
+
+ // A reverse mapping from dependencies to the dependees. This is
+ // used when removing instructions to keep the cache coherent.
+ typedef DenseMap<Instruction*,
+ SmallPtrSet<Instruction*, 4> > ReverseDepMapType;
+ ReverseDepMapType ReverseLocalDeps;
+
+ // A reverse mapping from dependencies to the non-local dependees.
+ ReverseDepMapType ReverseNonLocalDeps;
+
+ /// Current AA implementation, just a cache.
+ AliasAnalysis *AA;
+ TargetData *TD;
+ DominatorTree *DT;
+ OwningPtr<PredIteratorCache> PredCache;
+ public:
+ MemoryDependenceAnalysis();
+ ~MemoryDependenceAnalysis();
+ static char ID;
+
+ /// Pass Implementation stuff. This doesn't do any analysis eagerly.
+ bool runOnFunction(Function &);
+
+ /// Clean up memory in between runs
+ void releaseMemory();
+
+ /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
+ /// and Alias Analysis.
+ ///
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ /// getDependency - Return the instruction on which a memory operation
+ /// depends. See the class comment for more details. It is illegal to call
+ /// this on non-memory instructions.
+ MemDepResult getDependency(Instruction *QueryInst);
+
+ /// getNonLocalCallDependency - Perform a full dependency query for the
+ /// specified call, returning the set of blocks that the value is
+ /// potentially live across. The returned set of results will include a
+ /// "NonLocal" result for all blocks where the value is live across.
+ ///
+ /// This method assumes the instruction returns a "NonLocal" dependency
+ /// within its own block.
+ ///
+ /// This returns a reference to an internal data structure that may be
+ /// invalidated on the next non-local query or when an instruction is
+ /// removed. Clients must copy this data if they want it around longer than
+ /// that.
+ const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
+
+
+ /// getNonLocalPointerDependency - Perform a full dependency query for an
+ /// access to the specified (non-volatile) memory location, returning the
+ /// set of instructions that either define or clobber the value.
+ ///
+ /// This method assumes the pointer has a "NonLocal" dependency within BB.
+ void getNonLocalPointerDependency(const AliasAnalysis::Location &Loc,
+ bool isLoad, BasicBlock *BB,
+ SmallVectorImpl<NonLocalDepResult> &Result);
+
+ /// removeInstruction - Remove an instruction from the dependence analysis,
+ /// updating the dependence of instructions that previously depended on it.
+ void removeInstruction(Instruction *InstToRemove);
+
+ /// invalidateCachedPointerInfo - This method is used to invalidate cached
+ /// information about the specified pointer, because it may be too
+ /// conservative in memdep. This is an optional call that can be used when
+ /// the client detects an equivalence between the pointer and some other
+ /// value and replaces the other value with ptr. This can make Ptr available
+ /// in more places that cached info does not necessarily keep.
+ void invalidateCachedPointerInfo(Value *Ptr);
+
+ /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
+ /// This needs to be done when the CFG changes, e.g., due to splitting
+ /// critical edges.
+ void invalidateCachedPredecessors();
+
+ /// getPointerDependencyFrom - Return the instruction on which a memory
+ /// location depends. If isLoad is true, this routine ignores may-aliases
+ /// with read-only operations. If isLoad is false, this routine ignores
+ /// may-aliases with reads from read-only locations.
+ ///
+ /// Note that this is an uncached query, and thus may be inefficient.
+ ///
+ MemDepResult getPointerDependencyFrom(const AliasAnalysis::Location &Loc,
+ bool isLoad,
+ BasicBlock::iterator ScanIt,
+ BasicBlock *BB);
+
+
+ /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
+ /// looks at a memory location for a load (specified by MemLocBase, Offs,
+ /// and Size) and compares it against a load. If the specified load could
+ /// be safely widened to a larger integer load that is 1) still efficient,
+ /// 2) safe for the target, and 3) would provide the specified memory
+ /// location value, then this function returns the size in bytes of the
+ /// load width to use. If not, this returns zero.
+ static unsigned getLoadLoadClobberFullWidthSize(const Value *MemLocBase,
+ int64_t MemLocOffs,
+ unsigned MemLocSize,
+ const LoadInst *LI,
+ const TargetData &TD);
+
+ private:
+ MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
+ BasicBlock::iterator ScanIt,
+ BasicBlock *BB);
+ bool getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
+ const AliasAnalysis::Location &Loc,
+ bool isLoad, BasicBlock *BB,
+ SmallVectorImpl<NonLocalDepResult> &Result,
+ DenseMap<BasicBlock*, Value*> &Visited,
+ bool SkipFirstBlock = false);
+ MemDepResult GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
+ bool isLoad, BasicBlock *BB,
+ NonLocalDepInfo *Cache,
+ unsigned NumSortedEntries);
+
+ void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
+
+ /// verifyRemoved - Verify that the specified instruction does not occur
+ /// in our internal data structures.
+ void verifyRemoved(Instruction *Inst) const;
+
+ };
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/PHITransAddr.h b/include/llvm/Analysis/PHITransAddr.h
new file mode 100644
index 00000000000..ff9a24790a9
--- /dev/null
+++ b/include/llvm/Analysis/PHITransAddr.h
@@ -0,0 +1,121 @@
+//===- PHITransAddr.h - PHI Translation for Addresses -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the PHITransAddr class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_PHITRANSADDR_H
+#define LLVM_ANALYSIS_PHITRANSADDR_H
+
+#include "llvm/Instruction.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace llvm {
+ class DominatorTree;
+ class TargetData;
+ class TargetLibraryInfo;
+
+/// PHITransAddr - An address value which tracks and handles phi translation.
+/// As we walk "up" the CFG through predecessors, we need to ensure that the
+/// address we're tracking is kept up to date. For example, if we're analyzing
+/// an address of "&A[i]" and walk through the definition of 'i' which is a PHI
+/// node, we *must* phi translate i to get "&A[j]" or else we will analyze an
+/// incorrect pointer in the predecessor block.
+///
+/// This is designed to be a relatively small object that lives on the stack and
+/// is copyable.
+///
+class PHITransAddr {
+ /// Addr - The actual address we're analyzing.
+ Value *Addr;
+
+ /// TD - The target data we are playing with if known, otherwise null.
+ const TargetData *TD;
+
+ /// TLI - The target library info if known, otherwise null.
+ const TargetLibraryInfo *TLI;
+
+ /// InstInputs - The inputs for our symbolic address.
+ SmallVector<Instruction*, 4> InstInputs;
+public:
+ PHITransAddr(Value *addr, const TargetData *td) : Addr(addr), TD(td), TLI(0) {
+ // If the address is an instruction, the whole thing is considered an input.
+ if (Instruction *I = dyn_cast<Instruction>(Addr))
+ InstInputs.push_back(I);
+ }
+
+ Value *getAddr() const { return Addr; }
+
+ /// NeedsPHITranslationFromBlock - Return true if moving from the specified
+ /// BasicBlock to its predecessors requires PHI translation.
+ bool NeedsPHITranslationFromBlock(BasicBlock *BB) const {
+ // We do need translation if one of our input instructions is defined in
+ // this block.
+ for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
+ if (InstInputs[i]->getParent() == BB)
+ return true;
+ return false;
+ }
+
+ /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
+ /// if we have some hope of doing it. This should be used as a filter to
+ /// avoid calling PHITranslateValue in hopeless situations.
+ bool IsPotentiallyPHITranslatable() const;
+
+ /// PHITranslateValue - PHI translate the current address up the CFG from
+ /// CurBB to Pred, updating our state to reflect any needed changes. If the
+ /// dominator tree DT is non-null, the translated value must dominate
+ /// PredBB. This returns true on failure and sets Addr to null.
+ bool PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
+ const DominatorTree *DT);
+
+ /// PHITranslateWithInsertion - PHI translate this value into the specified
+ /// predecessor block, inserting a computation of the value if it is
+ /// unavailable.
+ ///
+ /// All newly created instructions are added to the NewInsts list. This
+ /// returns null on failure.
+ ///
+ Value *PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
+ const DominatorTree &DT,
+ SmallVectorImpl<Instruction*> &NewInsts);
+
+ void dump() const;
+
+ /// Verify - Check internal consistency of this data structure. If the
+ /// structure is valid, it returns true. If invalid, it prints errors and
+ /// returns false.
+ bool Verify() const;
+private:
+ Value *PHITranslateSubExpr(Value *V, BasicBlock *CurBB, BasicBlock *PredBB,
+ const DominatorTree *DT);
+
+ /// InsertPHITranslatedSubExpr - Insert a computation of the PHI translated
+ /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
+ /// block. All newly created instructions are added to the NewInsts list.
+ /// This returns null on failure.
+ ///
+ Value *InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
+ BasicBlock *PredBB, const DominatorTree &DT,
+ SmallVectorImpl<Instruction*> &NewInsts);
+
+ /// AddAsInput - If the specified value is an instruction, add it as an input.
+ Value *AddAsInput(Value *V) {
+ // If V is an instruction, it is now an input.
+ if (Instruction *VI = dyn_cast<Instruction>(V))
+ InstInputs.push_back(VI);
+ return V;
+ }
+
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Analysis/Passes.h b/include/llvm/Analysis/Passes.h
new file mode 100644
index 00000000000..c52f846b5ca
--- /dev/null
+++ b/include/llvm/Analysis/Passes.h
@@ -0,0 +1,213 @@
+//===-- llvm/Analysis/Passes.h - Constructors for analyses ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header file defines prototypes for accessor functions that expose passes
+// in the analysis libraries.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_PASSES_H
+#define LLVM_ANALYSIS_PASSES_H
+
+namespace llvm {
+ class FunctionPass;
+ class ImmutablePass;
+ class LoopPass;
+ class ModulePass;
+ class Pass;
+ class PassInfo;
+ class LibCallInfo;
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createGlobalsModRefPass - This pass provides alias and mod/ref info for
+ // global values that do not have their addresses taken.
+ //
+ Pass *createGlobalsModRefPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createAliasDebugger - This pass helps debug clients of AA
+ //
+ Pass *createAliasDebugger();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createAliasAnalysisCounterPass - This pass counts alias queries and how the
+ // alias analysis implementation responds.
+ //
+ ModulePass *createAliasAnalysisCounterPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createAAEvalPass - This pass implements a simple N^2 alias analysis
+ // accuracy evaluator.
+ //
+ FunctionPass *createAAEvalPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createNoAAPass - This pass implements a "I don't know" alias analysis.
+ //
+ ImmutablePass *createNoAAPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createBasicAliasAnalysisPass - This pass implements the stateless alias
+ // analysis.
+ //
+ ImmutablePass *createBasicAliasAnalysisPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ /// createLibCallAliasAnalysisPass - Create an alias analysis pass that knows
+ /// about the semantics of a set of libcalls specified by LCI. The newly
+ /// constructed pass takes ownership of the pointer that is provided.
+ ///
+ FunctionPass *createLibCallAliasAnalysisPass(LibCallInfo *LCI);
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createScalarEvolutionAliasAnalysisPass - This pass implements a simple
+ // alias analysis using ScalarEvolution queries.
+ //
+ FunctionPass *createScalarEvolutionAliasAnalysisPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createTypeBasedAliasAnalysisPass - This pass implements metadata-based
+ // type-based alias analysis.
+ //
+ ImmutablePass *createTypeBasedAliasAnalysisPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createObjCARCAliasAnalysisPass - This pass implements ObjC-ARC-based
+ // alias analysis.
+ //
+ ImmutablePass *createObjCARCAliasAnalysisPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createProfileLoaderPass - This pass loads information from a profile dump
+ // file.
+ //
+ ModulePass *createProfileLoaderPass();
+ extern char &ProfileLoaderPassID;
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createProfileMetadataLoaderPass - This pass loads information from a
+ // profile dump file and sets branch weight metadata.
+ //
+ ModulePass *createProfileMetadataLoaderPass();
+ extern char &ProfileMetadataLoaderPassID;
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createNoProfileInfoPass - This pass implements the default "no profile".
+ //
+ ImmutablePass *createNoProfileInfoPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createProfileEstimatorPass - This pass estimates profiling information
+ // instead of loading it from a previous run.
+ //
+ FunctionPass *createProfileEstimatorPass();
+ extern char &ProfileEstimatorPassID;
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createProfileVerifierPass - This pass verifies profiling information.
+ //
+ FunctionPass *createProfileVerifierPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createPathProfileLoaderPass - This pass loads information from a path
+ // profile dump file.
+ //
+ ModulePass *createPathProfileLoaderPass();
+ extern char &PathProfileLoaderPassID;
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createNoPathProfileInfoPass - This pass implements the default
+ // "no path profile".
+ //
+ ImmutablePass *createNoPathProfileInfoPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createPathProfileVerifierPass - This pass verifies path profiling
+ // information.
+ //
+ ModulePass *createPathProfileVerifierPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createDSAAPass - This pass implements simple context sensitive alias
+ // analysis.
+ //
+ ModulePass *createDSAAPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createDSOptPass - This pass uses DSA to do a series of simple
+ // optimizations.
+ //
+ ModulePass *createDSOptPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createSteensgaardPass - This pass uses the data structure graphs to do a
+ // simple context insensitive alias analysis.
+ //
+ ModulePass *createSteensgaardPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ /// createLazyValueInfoPass - This creates an instance of the LazyValueInfo
+ /// pass.
+ FunctionPass *createLazyValueInfoPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createLoopDependenceAnalysisPass - This creates an instance of the
+ // LoopDependenceAnalysis pass.
+ //
+ LoopPass *createLoopDependenceAnalysisPass();
+
+ // Minor pass prototypes, allowing us to expose them through bugpoint and
+ // analyze.
+ FunctionPass *createInstCountPass();
+
+ // print debug info intrinsics in human readable form
+ FunctionPass *createDbgInfoPrinterPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createRegionInfoPass - This pass finds all single entry single exit regions
+ // in a function and builds the region hierarchy.
+ //
+ FunctionPass *createRegionInfoPass();
+
+ // Print module-level debug info metadata in human-readable form.
+ ModulePass *createModuleDebugInfoPrinterPass();
+
+ //===--------------------------------------------------------------------===//
+ //
+ // createMemDepPrinter - This pass exhaustively collects all memdep
+ // information and prints it with -analyze.
+ //
+ FunctionPass *createMemDepPrinter();
+}
+
+#endif
diff --git a/include/llvm/Analysis/PathNumbering.h b/include/llvm/Analysis/PathNumbering.h
new file mode 100644
index 00000000000..7025e28484c
--- /dev/null
+++ b/include/llvm/Analysis/PathNumbering.h
@@ -0,0 +1,304 @@
+//===- PathNumbering.h ----------------------------------------*- C++ -*---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Ball-Larus path numbers uniquely identify paths through a directed acyclic
+// graph (DAG) [Ball96]. For a CFG backedges are removed and replaced by phony
+// edges to obtain a DAG, and thus the unique path numbers [Ball96].
+//
+// The purpose of this analysis is to enumerate the edges in a CFG in order
+// to obtain paths from path numbers in a convenient manner. As described in
+// [Ball96] edges can be enumerated such that given a path number by following
+// the CFG and updating the path number, the path is obtained.
+//
+// [Ball96]
+// T. Ball and J. R. Larus. "Efficient Path Profiling."
+// International Symposium on Microarchitecture, pages 46-57, 1996.
+// http://portal.acm.org/citation.cfm?id=243857
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_PATH_NUMBERING_H
+#define LLVM_PATH_NUMBERING_H
+
+#include "llvm/BasicBlock.h"
+#include "llvm/Instructions.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/CFG.h"
+#include "llvm/Analysis/ProfileInfoTypes.h"
+#include <map>
+#include <stack>
+#include <vector>
+
+namespace llvm {
+class BallLarusNode;
+class BallLarusEdge;
+class BallLarusDag;
+
+// typedefs for storage/ interators of various DAG components
+typedef std::vector<BallLarusNode*> BLNodeVector;
+typedef std::vector<BallLarusNode*>::iterator BLNodeIterator;
+typedef std::vector<BallLarusEdge*> BLEdgeVector;
+typedef std::vector<BallLarusEdge*>::iterator BLEdgeIterator;
+typedef std::map<BasicBlock*, BallLarusNode*> BLBlockNodeMap;
+typedef std::stack<BallLarusNode*> BLNodeStack;
+
+// Represents a basic block with information necessary for the BallLarus
+// algorithms.
+class BallLarusNode {
+public:
+ enum NodeColor { WHITE, GRAY, BLACK };
+
+ // Constructor: Initializes a new Node for the given BasicBlock
+ BallLarusNode(BasicBlock* BB) :
+ _basicBlock(BB), _numberPaths(0), _color(WHITE) {
+ static unsigned nextUID = 0;
+ _uid = nextUID++;
+ }
+
+ // Returns the basic block for the BallLarusNode
+ BasicBlock* getBlock();
+
+ // Get/set the number of paths to the exit starting at the node.
+ unsigned getNumberPaths();
+ void setNumberPaths(unsigned numberPaths);
+
+ // Get/set the NodeColor used in graph algorithms.
+ NodeColor getColor();
+ void setColor(NodeColor color);
+
+ // Iterator information for predecessor edges. Includes phony and
+ // backedges.
+ BLEdgeIterator predBegin();
+ BLEdgeIterator predEnd();
+ unsigned getNumberPredEdges();
+
+ // Iterator information for successor edges. Includes phony and
+ // backedges.
+ BLEdgeIterator succBegin();
+ BLEdgeIterator succEnd();
+ unsigned getNumberSuccEdges();
+
+ // Add an edge to the predecessor list.
+ void addPredEdge(BallLarusEdge* edge);
+
+ // Remove an edge from the predecessor list.
+ void removePredEdge(BallLarusEdge* edge);
+
+ // Add an edge to the successor list.
+ void addSuccEdge(BallLarusEdge* edge);
+
+ // Remove an edge from the successor list.
+ void removeSuccEdge(BallLarusEdge* edge);
+
+ // Returns the name of the BasicBlock being represented. If BasicBlock
+ // is null then returns "<null>". If BasicBlock has no name, then
+ // "<unnamed>" is returned. Intended for use with debug output.
+ std::string getName();
+
+private:
+ // The corresponding underlying BB.
+ BasicBlock* _basicBlock;
+
+ // Holds the predecessor edges of this node.
+ BLEdgeVector _predEdges;
+
+ // Holds the successor edges of this node.
+ BLEdgeVector _succEdges;
+
+ // The number of paths from the node to the exit.
+ unsigned _numberPaths;
+
+ // 'Color' used by graph algorithms to mark the node.
+ NodeColor _color;
+
+ // Unique ID to ensure naming difference with dotgraphs
+ unsigned _uid;
+
+ // Removes an edge from an edgeVector. Used by removePredEdge and
+ // removeSuccEdge.
+ void removeEdge(BLEdgeVector& v, BallLarusEdge* e);
+};
+
+// Represents an edge in the Dag. For an edge, v -> w, v is the source, and
+// w is the target.
+class BallLarusEdge {
+public:
+ enum EdgeType { NORMAL, BACKEDGE, SPLITEDGE,
+ BACKEDGE_PHONY, SPLITEDGE_PHONY, CALLEDGE_PHONY };
+
+ // Constructor: Initializes an BallLarusEdge with a source and target.
+ BallLarusEdge(BallLarusNode* source, BallLarusNode* target,
+ unsigned duplicateNumber)
+ : _source(source), _target(target), _weight(0), _edgeType(NORMAL),
+ _realEdge(NULL), _duplicateNumber(duplicateNumber) {}
+
+ // Returns the source/ target node of this edge.
+ BallLarusNode* getSource() const;
+ BallLarusNode* getTarget() const;
+
+ // Sets the type of the edge.
+ EdgeType getType() const;
+
+ // Gets the type of the edge.
+ void setType(EdgeType type);
+
+ // Returns the weight of this edge. Used to decode path numbers to
+ // sequences of basic blocks.
+ unsigned getWeight();
+
+ // Sets the weight of the edge. Used during path numbering.
+ void setWeight(unsigned weight);
+
+ // Gets/sets the phony edge originating at the root.
+ BallLarusEdge* getPhonyRoot();
+ void setPhonyRoot(BallLarusEdge* phonyRoot);
+
+ // Gets/sets the phony edge terminating at the exit.
+ BallLarusEdge* getPhonyExit();
+ void setPhonyExit(BallLarusEdge* phonyExit);
+
+ // Gets/sets the associated real edge if this is a phony edge.
+ BallLarusEdge* getRealEdge();
+ void setRealEdge(BallLarusEdge* realEdge);
+
+ // Returns the duplicate number of the edge.
+ unsigned getDuplicateNumber();
+
+protected:
+ // Source node for this edge.
+ BallLarusNode* _source;
+
+ // Target node for this edge.
+ BallLarusNode* _target;
+
+private:
+ // Edge weight cooresponding to path number increments before removing
+ // increments along a spanning tree. The sum over the edge weights gives
+ // the path number.
+ unsigned _weight;
+
+ // Type to represent for what this edge is intended
+ EdgeType _edgeType;
+
+ // For backedges and split-edges, the phony edge which is linked to the
+ // root node of the DAG. This contains a path number initialization.
+ BallLarusEdge* _phonyRoot;
+
+ // For backedges and split-edges, the phony edge which is linked to the
+ // exit node of the DAG. This contains a path counter increment, and
+ // potentially a path number increment.
+ BallLarusEdge* _phonyExit;
+
+ // If this is a phony edge, _realEdge is a link to the back or split
+ // edge. Otherwise, this is null.
+ BallLarusEdge* _realEdge;
+
+ // An ID to differentiate between those edges which have the same source
+ // and destination blocks.
+ unsigned _duplicateNumber;
+};
+
+// Represents the Ball Larus DAG for a given Function. Can calculate
+// various properties required for instrumentation or analysis. E.g. the
+// edge weights that determine the path number.
+class BallLarusDag {
+public:
+ // Initializes a BallLarusDag from the CFG of a given function. Must
+ // call init() after creation, since some initialization requires
+ // virtual functions.
+ BallLarusDag(Function &F)
+ : _root(NULL), _exit(NULL), _function(F) {}
+
+ // Initialization that requires virtual functions which are not fully
+ // functional in the constructor.
+ void init();
+
+ // Frees all memory associated with the DAG.
+ virtual ~BallLarusDag();
+
+ // Calculate the path numbers by assigning edge increments as prescribed
+ // in Ball-Larus path profiling.
+ void calculatePathNumbers();
+
+ // Returns the number of paths for the DAG.
+ unsigned getNumberOfPaths();
+
+ // Returns the root (i.e. entry) node for the DAG.
+ BallLarusNode* getRoot();
+
+ // Returns the exit node for the DAG.
+ BallLarusNode* getExit();
+
+ // Returns the function for the DAG.
+ Function& getFunction();
+
+ // Clears the node colors.
+ void clearColors(BallLarusNode::NodeColor color);
+
+protected:
+ // All nodes in the DAG.
+ BLNodeVector _nodes;
+
+ // All edges in the DAG.
+ BLEdgeVector _edges;
+
+ // All backedges in the DAG.
+ BLEdgeVector _backEdges;
+
+ // Allows subclasses to determine which type of Node is created.
+ // Override this method to produce subclasses of BallLarusNode if
+ // necessary. The destructor of BallLarusDag will call free on each pointer
+ // created.
+ virtual BallLarusNode* createNode(BasicBlock* BB);
+
+ // Allows subclasses to determine which type of Edge is created.
+ // Override this method to produce subclasses of BallLarusEdge if
+ // necessary. Parameters source and target will have been created by
+ // createNode and can be cast to the subclass of BallLarusNode*
+ // returned by createNode. The destructor of BallLarusDag will call free
+ // on each pointer created.
+ virtual BallLarusEdge* createEdge(BallLarusNode* source, BallLarusNode*
+ target, unsigned duplicateNumber);
+
+ // Proxy to node's constructor. Updates the DAG state.
+ BallLarusNode* addNode(BasicBlock* BB);
+
+ // Proxy to edge's constructor. Updates the DAG state.
+ BallLarusEdge* addEdge(BallLarusNode* source, BallLarusNode* target,
+ unsigned duplicateNumber);
+
+private:
+ // The root (i.e. entry) node for this DAG.
+ BallLarusNode* _root;
+
+ // The exit node for this DAG.
+ BallLarusNode* _exit;
+
+ // The function represented by this DAG.
+ Function& _function;
+
+ // Processes one node and its imediate edges for building the DAG.
+ void buildNode(BLBlockNodeMap& inDag, std::stack<BallLarusNode*>& dfsStack);
+
+ // Process an edge in the CFG for DAG building.
+ void buildEdge(BLBlockNodeMap& inDag, std::stack<BallLarusNode*>& dfsStack,
+ BallLarusNode* currentNode, BasicBlock* succBB,
+ unsigned duplicateNumber);
+
+ // The weight on each edge is the increment required along any path that
+ // contains that edge.
+ void calculatePathNumbersFrom(BallLarusNode* node);
+
+ // Adds a backedge with its phony edges. Updates the DAG state.
+ void addBackedge(BallLarusNode* source, BallLarusNode* target,
+ unsigned duplicateCount);
+};
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Analysis/PathProfileInfo.h b/include/llvm/Analysis/PathProfileInfo.h
new file mode 100644
index 00000000000..cef6d2d2a6c
--- /dev/null
+++ b/include/llvm/Analysis/PathProfileInfo.h
@@ -0,0 +1,112 @@
+//===- PathProfileInfo.h --------------------------------------*- C++ -*---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file outlines the interface used by optimizers to load path profiles.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_PATHPROFILEINFO_H
+#define LLVM_PATHPROFILEINFO_H
+
+#include "llvm/BasicBlock.h"
+#include "llvm/Analysis/PathNumbering.h"
+
+namespace llvm {
+
+class ProfilePath;
+class ProfilePathEdge;
+class PathProfileInfo;
+
+typedef std::vector<ProfilePathEdge> ProfilePathEdgeVector;
+typedef std::vector<ProfilePathEdge>::iterator ProfilePathEdgeIterator;
+
+typedef std::vector<BasicBlock*> ProfilePathBlockVector;
+typedef std::vector<BasicBlock*>::iterator ProfilePathBlockIterator;
+
+typedef std::map<unsigned int,ProfilePath*> ProfilePathMap;
+typedef std::map<unsigned int,ProfilePath*>::iterator ProfilePathIterator;
+
+typedef std::map<Function*,unsigned int> FunctionPathCountMap;
+typedef std::map<Function*,ProfilePathMap> FunctionPathMap;
+typedef std::map<Function*,ProfilePathMap>::iterator FunctionPathIterator;
+
+class ProfilePathEdge {
+public:
+ ProfilePathEdge(BasicBlock* source, BasicBlock* target,
+ unsigned duplicateNumber);
+
+ inline unsigned getDuplicateNumber() { return _duplicateNumber; }
+ inline BasicBlock* getSource() { return _source; }
+ inline BasicBlock* getTarget() { return _target; }
+
+protected:
+ BasicBlock* _source;
+ BasicBlock* _target;
+ unsigned _duplicateNumber;
+};
+
+class ProfilePath {
+public:
+ ProfilePath(unsigned int number, unsigned int count,
+ double countStdDev, PathProfileInfo* ppi);
+
+ double getFrequency() const;
+
+ inline unsigned int getNumber() const { return _number; }
+ inline unsigned int getCount() const { return _count; }
+ inline double getCountStdDev() const { return _countStdDev; }
+
+ ProfilePathEdgeVector* getPathEdges() const;
+ ProfilePathBlockVector* getPathBlocks() const;
+
+ BasicBlock* getFirstBlockInPath() const;
+
+private:
+ unsigned int _number;
+ unsigned int _count;
+ double _countStdDev;
+
+ // double pointer back to the profiling info
+ PathProfileInfo* _ppi;
+};
+
+// TODO: overload [] operator for getting path
+// Add: getFunctionCallCount()
+class PathProfileInfo {
+ public:
+ PathProfileInfo();
+ ~PathProfileInfo();
+
+ void setCurrentFunction(Function* F);
+ Function* getCurrentFunction() const;
+ BasicBlock* getCurrentFunctionEntry();
+
+ ProfilePath* getPath(unsigned int number);
+ unsigned int getPotentialPathCount();
+
+ ProfilePathIterator pathBegin();
+ ProfilePathIterator pathEnd();
+ unsigned int pathsRun();
+
+ static char ID; // Pass identification
+ std::string argList;
+
+protected:
+ FunctionPathMap _functionPaths;
+ FunctionPathCountMap _functionPathCounts;
+
+private:
+ BallLarusDag* _currentDag;
+ Function* _currentFunction;
+
+ friend class ProfilePath;
+};
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Analysis/PostDominators.h b/include/llvm/Analysis/PostDominators.h
new file mode 100644
index 00000000000..0eddb9105e6
--- /dev/null
+++ b/include/llvm/Analysis/PostDominators.h
@@ -0,0 +1,106 @@
+//=- llvm/Analysis/PostDominators.h - Post Dominator Calculation-*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file exposes interfaces to post dominance information.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_POST_DOMINATORS_H
+#define LLVM_ANALYSIS_POST_DOMINATORS_H
+
+#include "llvm/Analysis/Dominators.h"
+
+namespace llvm {
+
+/// PostDominatorTree Class - Concrete subclass of DominatorTree that is used to
+/// compute the a post-dominator tree.
+///
+struct PostDominatorTree : public FunctionPass {
+ static char ID; // Pass identification, replacement for typeid
+ DominatorTreeBase<BasicBlock>* DT;
+
+ PostDominatorTree() : FunctionPass(ID) {
+ initializePostDominatorTreePass(*PassRegistry::getPassRegistry());
+ DT = new DominatorTreeBase<BasicBlock>(true);
+ }
+
+ ~PostDominatorTree();
+
+ virtual bool runOnFunction(Function &F);
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ }
+
+ inline const std::vector<BasicBlock*> &getRoots() const {
+ return DT->getRoots();
+ }
+
+ inline DomTreeNode *getRootNode() const {
+ return DT->getRootNode();
+ }
+
+ inline DomTreeNode *operator[](BasicBlock *BB) const {
+ return DT->getNode(BB);
+ }
+
+ inline DomTreeNode *getNode(BasicBlock *BB) const {
+ return DT->getNode(BB);
+ }
+
+ inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
+ return DT->dominates(A, B);
+ }
+
+ inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
+ return DT->dominates(A, B);
+ }
+
+ inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
+ return DT->properlyDominates(A, B);
+ }
+
+ inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
+ return DT->properlyDominates(A, B);
+ }
+
+ inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
+ return DT->findNearestCommonDominator(A, B);
+ }
+
+ virtual void releaseMemory() {
+ DT->releaseMemory();
+ }
+
+ virtual void print(raw_ostream &OS, const Module*) const;
+};
+
+FunctionPass* createPostDomTree();
+
+template <> struct GraphTraits<PostDominatorTree*>
+ : public GraphTraits<DomTreeNode*> {
+ static NodeType *getEntryNode(PostDominatorTree *DT) {
+ return DT->getRootNode();
+ }
+
+ static nodes_iterator nodes_begin(PostDominatorTree *N) {
+ if (getEntryNode(N))
+ return df_begin(getEntryNode(N));
+ else
+ return df_end(getEntryNode(N));
+ }
+
+ static nodes_iterator nodes_end(PostDominatorTree *N) {
+ return df_end(getEntryNode(N));
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/ProfileDataLoader.h b/include/llvm/Analysis/ProfileDataLoader.h
new file mode 100644
index 00000000000..bec9fac770c
--- /dev/null
+++ b/include/llvm/Analysis/ProfileDataLoader.h
@@ -0,0 +1,142 @@
+//===- ProfileDataLoader.h - Load & convert profile info ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The ProfileDataLoader class is used to load profiling data from a dump file.
+// The ProfileDataT<FType, BType> class is used to store the mapping of this
+// data to control flow edges.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_PROFILEDATALOADER_H
+#define LLVM_ANALYSIS_PROFILEDATALOADER_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
+#include <string>
+
+namespace llvm {
+
+class ModulePass;
+class Function;
+class BasicBlock;
+
+// Helper for dumping edges to dbgs().
+raw_ostream& operator<<(raw_ostream &O, std::pair<const BasicBlock *,
+ const BasicBlock *> E);
+
+/// \brief The ProfileDataT<FType, BType> class is used to store the mapping of
+/// profiling data to control flow edges.
+///
+/// An edge is defined by its source and sink basic blocks.
+template<class FType, class BType>
+class ProfileDataT {
+public:
+ // The profiling information defines an Edge by its source and sink basic
+ // blocks.
+ typedef std::pair<const BType*, const BType*> Edge;
+
+private:
+ typedef DenseMap<Edge, unsigned> EdgeWeights;
+
+ /// \brief Count the number of times a transition between two blocks is
+ /// executed.
+ ///
+ /// As a special case, we also hold an edge from the null BasicBlock to the
+ /// entry block to indicate how many times the function was entered.
+ DenseMap<const FType*, EdgeWeights> EdgeInformation;
+
+public:
+ /// getFunction() - Returns the Function for an Edge.
+ static const FType *getFunction(Edge e) {
+ // e.first may be NULL
+ assert(((!e.first) || (e.first->getParent() == e.second->getParent()))
+ && "A ProfileData::Edge can not be between two functions");
+ assert(e.second && "A ProfileData::Edge must have a real sink");
+ return e.second->getParent();
+ }
+
+ /// getEdge() - Creates an Edge between two BasicBlocks.
+ static Edge getEdge(const BType *Src, const BType *Dest) {
+ return Edge(Src, Dest);
+ }
+
+ /// getEdgeWeight - Return the number of times that a given edge was
+ /// executed.
+ unsigned getEdgeWeight(Edge e) const {
+ const FType *f = getFunction(e);
+ assert((EdgeInformation.find(f) != EdgeInformation.end())
+ && "No profiling information for function");
+ EdgeWeights weights = EdgeInformation.find(f)->second;
+
+ assert((weights.find(e) != weights.end())
+ && "No profiling information for edge");
+ return weights.find(e)->second;
+ }
+
+ /// addEdgeWeight - Add 'weight' to the already stored execution count for
+ /// this edge.
+ void addEdgeWeight(Edge e, unsigned weight) {
+ EdgeInformation[getFunction(e)][e] += weight;
+ }
+};
+
+typedef ProfileDataT<Function, BasicBlock> ProfileData;
+//typedef ProfileDataT<MachineFunction, MachineBasicBlock> MachineProfileData;
+
+/// The ProfileDataLoader class is used to load raw profiling data from the
+/// dump file.
+class ProfileDataLoader {
+private:
+ /// The name of the file where the raw profiling data is stored.
+ const std::string &Filename;
+
+ /// A vector of the command line arguments used when the target program was
+ /// run to generate profiling data. One entry per program run.
+ SmallVector<std::string, 1> CommandLines;
+
+ /// The raw values for how many times each edge was traversed, values from
+ /// multiple program runs are accumulated.
+ SmallVector<unsigned, 32> EdgeCounts;
+
+public:
+ /// ProfileDataLoader ctor - Read the specified profiling data file, exiting
+ /// the program if the file is invalid or broken.
+ ProfileDataLoader(const char *ToolName, const std::string &Filename);
+
+ /// A special value used to represent the weight of an edge which has not
+ /// been counted yet.
+ static const unsigned Uncounted;
+
+ /// The maximum value that can be stored in a profiling counter.
+ static const unsigned MaxCount;
+
+ /// getNumExecutions - Return the number of times the target program was run
+ /// to generate this profiling data.
+ unsigned getNumExecutions() const { return CommandLines.size(); }
+
+ /// getExecution - Return the command line parameters used to generate the
+ /// i'th set of profiling data.
+ const std::string &getExecution(unsigned i) const { return CommandLines[i]; }
+
+ const std::string &getFileName() const { return Filename; }
+
+ /// getRawEdgeCounts - Return the raw profiling data, this is just a list of
+ /// numbers with no mappings to edges.
+ ArrayRef<unsigned> getRawEdgeCounts() const { return EdgeCounts; }
+};
+
+/// createProfileMetadataLoaderPass - This function returns a Pass that loads
+/// the profiling information for the module from the specified filename.
+ModulePass *createProfileMetadataLoaderPass(const std::string &Filename);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/ProfileDataTypes.h b/include/llvm/Analysis/ProfileDataTypes.h
new file mode 100644
index 00000000000..1be15e025da
--- /dev/null
+++ b/include/llvm/Analysis/ProfileDataTypes.h
@@ -0,0 +1,39 @@
+/*===-- ProfileDataTypes.h - Profiling info shared constants --------------===*\
+|*
+|* The LLVM Compiler Infrastructure
+|*
+|* This file is distributed under the University of Illinois Open Source
+|* License. See LICENSE.TXT for details.
+|*
+|*===----------------------------------------------------------------------===*|
+|*
+|* This file defines constants shared by the various different profiling
+|* runtime libraries and the LLVM C++ profile metadata loader. It must be a
+|* C header because, at present, the profiling runtimes are written in C.
+|*
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_ANALYSIS_PROFILEDATATYPES_H
+#define LLVM_ANALYSIS_PROFILEDATATYPES_H
+
+/* Included by libprofile. */
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+/* TODO: Strip out unused entries once ProfileInfo etc has been removed. */
+enum ProfilingType {
+ ArgumentInfo = 1, /* The command line argument block */
+ FunctionInfo = 2, /* Function profiling information */
+ BlockInfo = 3, /* Block profiling information */
+ EdgeInfo = 4, /* Edge profiling information */
+ PathInfo = 5, /* Path profiling information */
+ BBTraceInfo = 6, /* Basic block trace information */
+ OptEdgeInfo = 7 /* Edge profiling information, optimal version */
+};
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* LLVM_ANALYSIS_PROFILEDATATYPES_H */
diff --git a/include/llvm/Analysis/ProfileInfo.h b/include/llvm/Analysis/ProfileInfo.h
new file mode 100644
index 00000000000..6c2e2732d34
--- /dev/null
+++ b/include/llvm/Analysis/ProfileInfo.h
@@ -0,0 +1,247 @@
+//===- llvm/Analysis/ProfileInfo.h - Profile Info Interface -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the generic ProfileInfo interface, which is used as the
+// common interface used by all clients of profiling information, and
+// implemented either by making static guestimations, or by actually reading in
+// profiling information gathered by running the program.
+//
+// Note that to be useful, all profile-based optimizations should preserve
+// ProfileInfo, which requires that they notify it when changes to the CFG are
+// made. (This is not implemented yet.)
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_PROFILEINFO_H
+#define LLVM_ANALYSIS_PROFILEINFO_H
+
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/Format.h"
+#include "llvm/Support/raw_ostream.h"
+#include <cassert>
+#include <string>
+#include <map>
+#include <set>
+
+namespace llvm {
+ class Pass;
+ class raw_ostream;
+
+ class BasicBlock;
+ class Function;
+ class MachineBasicBlock;
+ class MachineFunction;
+
+ // Helper for dumping edges to dbgs().
+ raw_ostream& operator<<(raw_ostream &O, std::pair<const BasicBlock *, const BasicBlock *> E);
+ raw_ostream& operator<<(raw_ostream &O, std::pair<const MachineBasicBlock *, const MachineBasicBlock *> E);
+
+ raw_ostream& operator<<(raw_ostream &O, const BasicBlock *BB);
+ raw_ostream& operator<<(raw_ostream &O, const MachineBasicBlock *MBB);
+
+ raw_ostream& operator<<(raw_ostream &O, const Function *F);
+ raw_ostream& operator<<(raw_ostream &O, const MachineFunction *MF);
+
+ /// ProfileInfo Class - This class holds and maintains profiling
+ /// information for some unit of code.
+ template<class FType, class BType>
+ class ProfileInfoT {
+ public:
+ // Types for handling profiling information.
+ typedef std::pair<const BType*, const BType*> Edge;
+ typedef std::pair<Edge, double> EdgeWeight;
+ typedef std::map<Edge, double> EdgeWeights;
+ typedef std::map<const BType*, double> BlockCounts;
+ typedef std::map<const BType*, const BType*> Path;
+
+ protected:
+ // EdgeInformation - Count the number of times a transition between two
+ // blocks is executed. As a special case, we also hold an edge from the
+ // null BasicBlock to the entry block to indicate how many times the
+ // function was entered.
+ std::map<const FType*, EdgeWeights> EdgeInformation;
+
+ // BlockInformation - Count the number of times a block is executed.
+ std::map<const FType*, BlockCounts> BlockInformation;
+
+ // FunctionInformation - Count the number of times a function is executed.
+ std::map<const FType*, double> FunctionInformation;
+
+ ProfileInfoT<MachineFunction, MachineBasicBlock> *MachineProfile;
+ public:
+ static char ID; // Class identification, replacement for typeinfo
+ ProfileInfoT();
+ ~ProfileInfoT(); // We want to be subclassed
+
+ // MissingValue - The value that is returned for execution counts in case
+ // no value is available.
+ static const double MissingValue;
+
+ // getFunction() - Returns the Function for an Edge, checking for validity.
+ static const FType* getFunction(Edge e) {
+ if (e.first)
+ return e.first->getParent();
+ if (e.second)
+ return e.second->getParent();
+ llvm_unreachable("Invalid ProfileInfo::Edge");
+ }
+
+ // getEdge() - Creates an Edge from two BasicBlocks.
+ static Edge getEdge(const BType *Src, const BType *Dest) {
+ return std::make_pair(Src, Dest);
+ }
+
+ //===------------------------------------------------------------------===//
+ /// Profile Information Queries
+ ///
+ double getExecutionCount(const FType *F);
+
+ double getExecutionCount(const BType *BB);
+
+ void setExecutionCount(const BType *BB, double w);
+
+ void addExecutionCount(const BType *BB, double w);
+
+ double getEdgeWeight(Edge e) const {
+ typename std::map<const FType*, EdgeWeights>::const_iterator J =
+ EdgeInformation.find(getFunction(e));
+ if (J == EdgeInformation.end()) return MissingValue;
+
+ typename EdgeWeights::const_iterator I = J->second.find(e);
+ if (I == J->second.end()) return MissingValue;
+
+ return I->second;
+ }
+
+ void setEdgeWeight(Edge e, double w) {
+ DEBUG_WITH_TYPE("profile-info",
+ dbgs() << "Creating Edge " << e
+ << " (weight: " << format("%.20g",w) << ")\n");
+ EdgeInformation[getFunction(e)][e] = w;
+ }
+
+ void addEdgeWeight(Edge e, double w);
+
+ EdgeWeights &getEdgeWeights (const FType *F) {
+ return EdgeInformation[F];
+ }
+
+ //===------------------------------------------------------------------===//
+ /// Analysis Update Methods
+ ///
+ void removeBlock(const BType *BB);
+
+ void removeEdge(Edge e);
+
+ void replaceEdge(const Edge &, const Edge &);
+
+ enum GetPathMode {
+ GetPathToExit = 1,
+ GetPathToValue = 2,
+ GetPathToDest = 4,
+ GetPathWithNewEdges = 8
+ };
+
+ const BType *GetPath(const BType *Src, const BType *Dest,
+ Path &P, unsigned Mode);
+
+ void divertFlow(const Edge &, const Edge &);
+
+ void splitEdge(const BType *FirstBB, const BType *SecondBB,
+ const BType *NewBB, bool MergeIdenticalEdges = false);
+
+ void splitBlock(const BType *Old, const BType* New);
+
+ void splitBlock(const BType *BB, const BType* NewBB,
+ BType *const *Preds, unsigned NumPreds);
+
+ void replaceAllUses(const BType *RmBB, const BType *DestBB);
+
+ void transfer(const FType *Old, const FType *New);
+
+ void repair(const FType *F);
+
+ void dump(FType *F = 0, bool real = true) {
+ dbgs() << "**** This is ProfileInfo " << this << " speaking:\n";
+ if (!real) {
+ typename std::set<const FType*> Functions;
+
+ dbgs() << "Functions: \n";
+ if (F) {
+ dbgs() << F << "@" << format("%p", F) << ": " << format("%.20g",getExecutionCount(F)) << "\n";
+ Functions.insert(F);
+ } else {
+ for (typename std::map<const FType*, double>::iterator fi = FunctionInformation.begin(),
+ fe = FunctionInformation.end(); fi != fe; ++fi) {
+ dbgs() << fi->first << "@" << format("%p",fi->first) << ": " << format("%.20g",fi->second) << "\n";
+ Functions.insert(fi->first);
+ }
+ }
+
+ for (typename std::set<const FType*>::iterator FI = Functions.begin(), FE = Functions.end();
+ FI != FE; ++FI) {
+ const FType *F = *FI;
+ typename std::map<const FType*, BlockCounts>::iterator bwi = BlockInformation.find(F);
+ dbgs() << "BasicBlocks for Function " << F << ":\n";
+ for (typename BlockCounts::const_iterator bi = bwi->second.begin(), be = bwi->second.end(); bi != be; ++bi) {
+ dbgs() << bi->first << "@" << format("%p", bi->first) << ": " << format("%.20g",bi->second) << "\n";
+ }
+ }
+
+ for (typename std::set<const FType*>::iterator FI = Functions.begin(), FE = Functions.end();
+ FI != FE; ++FI) {
+ typename std::map<const FType*, EdgeWeights>::iterator ei = EdgeInformation.find(*FI);
+ dbgs() << "Edges for Function " << ei->first << ":\n";
+ for (typename EdgeWeights::iterator ewi = ei->second.begin(), ewe = ei->second.end();
+ ewi != ewe; ++ewi) {
+ dbgs() << ewi->first << ": " << format("%.20g",ewi->second) << "\n";
+ }
+ }
+ } else {
+ assert(F && "No function given, this is not supported!");
+ dbgs() << "Functions: \n";
+ dbgs() << F << "@" << format("%p", F) << ": " << format("%.20g",getExecutionCount(F)) << "\n";
+
+ dbgs() << "BasicBlocks for Function " << F << ":\n";
+ for (typename FType::const_iterator BI = F->begin(), BE = F->end();
+ BI != BE; ++BI) {
+ const BType *BB = &(*BI);
+ dbgs() << BB << "@" << format("%p", BB) << ": " << format("%.20g",getExecutionCount(BB)) << "\n";
+ }
+ }
+ dbgs() << "**** ProfileInfo " << this << ", over and out.\n";
+ }
+
+ bool CalculateMissingEdge(const BType *BB, Edge &removed, bool assumeEmptyExit = false);
+
+ bool EstimateMissingEdges(const BType *BB);
+
+ ProfileInfoT<MachineFunction, MachineBasicBlock> *MI() {
+ if (MachineProfile == 0)
+ MachineProfile = new ProfileInfoT<MachineFunction, MachineBasicBlock>();
+ return MachineProfile;
+ }
+
+ bool hasMI() const {
+ return (MachineProfile != 0);
+ }
+ };
+
+ typedef ProfileInfoT<Function, BasicBlock> ProfileInfo;
+ typedef ProfileInfoT<MachineFunction, MachineBasicBlock> MachineProfileInfo;
+
+ /// createProfileLoaderPass - This function returns a Pass that loads the
+ /// profiling information for the module from the specified filename, making
+ /// it available to the optimizers.
+ Pass *createProfileLoaderPass(const std::string &Filename);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/ProfileInfoLoader.h b/include/llvm/Analysis/ProfileInfoLoader.h
new file mode 100644
index 00000000000..dcf3b38ddcd
--- /dev/null
+++ b/include/llvm/Analysis/ProfileInfoLoader.h
@@ -0,0 +1,81 @@
+//===- ProfileInfoLoader.h - Load & convert profile information -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The ProfileInfoLoader class is used to load and represent profiling
+// information read in from the dump file. If conversions between formats are
+// needed, it can also do this.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_PROFILEINFOLOADER_H
+#define LLVM_ANALYSIS_PROFILEINFOLOADER_H
+
+#include <vector>
+#include <string>
+#include <utility>
+
+namespace llvm {
+
+class Module;
+class Function;
+class BasicBlock;
+
+class ProfileInfoLoader {
+ const std::string &Filename;
+ std::vector<std::string> CommandLines;
+ std::vector<unsigned> FunctionCounts;
+ std::vector<unsigned> BlockCounts;
+ std::vector<unsigned> EdgeCounts;
+ std::vector<unsigned> OptimalEdgeCounts;
+ std::vector<unsigned> BBTrace;
+public:
+ // ProfileInfoLoader ctor - Read the specified profiling data file, exiting
+ // the program if the file is invalid or broken.
+ ProfileInfoLoader(const char *ToolName, const std::string &Filename);
+
+ static const unsigned Uncounted;
+
+ unsigned getNumExecutions() const { return CommandLines.size(); }
+ const std::string &getExecution(unsigned i) const { return CommandLines[i]; }
+
+ const std::string &getFileName() const { return Filename; }
+
+ // getRawFunctionCounts - This method is used by consumers of function
+ // counting information.
+ //
+ const std::vector<unsigned> &getRawFunctionCounts() const {
+ return FunctionCounts;
+ }
+
+ // getRawBlockCounts - This method is used by consumers of block counting
+ // information.
+ //
+ const std::vector<unsigned> &getRawBlockCounts() const {
+ return BlockCounts;
+ }
+
+ // getEdgeCounts - This method is used by consumers of edge counting
+ // information.
+ //
+ const std::vector<unsigned> &getRawEdgeCounts() const {
+ return EdgeCounts;
+ }
+
+ // getEdgeOptimalCounts - This method is used by consumers of optimal edge
+ // counting information.
+ //
+ const std::vector<unsigned> &getRawOptimalEdgeCounts() const {
+ return OptimalEdgeCounts;
+ }
+
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/ProfileInfoTypes.h b/include/llvm/Analysis/ProfileInfoTypes.h
new file mode 100644
index 00000000000..45aab5b70d2
--- /dev/null
+++ b/include/llvm/Analysis/ProfileInfoTypes.h
@@ -0,0 +1,52 @@
+/*===-- ProfileInfoTypes.h - Profiling info shared constants --------------===*\
+|*
+|* The LLVM Compiler Infrastructure
+|*
+|* This file is distributed under the University of Illinois Open Source
+|* License. See LICENSE.TXT for details.
+|*
+|*===----------------------------------------------------------------------===*|
+|*
+|* This file defines constants shared by the various different profiling
+|* runtime libraries and the LLVM C++ profile info loader. It must be a
+|* C header because, at present, the profiling runtimes are written in C.
+|*
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_ANALYSIS_PROFILEINFOTYPES_H
+#define LLVM_ANALYSIS_PROFILEINFOTYPES_H
+
+/* Included by libprofile. */
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+/* IDs to distinguish between those path counters stored in hashses vs arrays */
+enum ProfilingStorageType {
+ ProfilingArray = 1,
+ ProfilingHash = 2
+};
+
+#include "llvm/Analysis/ProfileDataTypes.h"
+
+/*
+ * The header for tables that map path numbers to path counters.
+ */
+typedef struct {
+ unsigned fnNumber; /* function number for these counters */
+ unsigned numEntries; /* number of entries stored */
+} PathProfileHeader;
+
+/*
+ * Describes an entry in a tagged table for path counters.
+ */
+typedef struct {
+ unsigned pathNumber;
+ unsigned pathCounter;
+} PathProfileTableEntry;
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* LLVM_ANALYSIS_PROFILEINFOTYPES_H */
diff --git a/include/llvm/Analysis/RegionInfo.h b/include/llvm/Analysis/RegionInfo.h
new file mode 100644
index 00000000000..48d7ee6b547
--- /dev/null
+++ b/include/llvm/Analysis/RegionInfo.h
@@ -0,0 +1,721 @@
+//===- RegionInfo.h - SESE region analysis ----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Calculate a program structure tree built out of single entry single exit
+// regions.
+// The basic ideas are taken from "The Program Structure Tree - Richard Johnson,
+// David Pearson, Keshav Pingali - 1994", however enriched with ideas from "The
+// Refined Process Structure Tree - Jussi Vanhatalo, Hagen Voelyer, Jana
+// Koehler - 2009".
+// The algorithm to calculate these data structures however is completely
+// different, as it takes advantage of existing information already available
+// in (Post)dominace tree and dominance frontier passes. This leads to a simpler
+// and in practice hopefully better performing algorithm. The runtime of the
+// algorithms described in the papers above are both linear in graph size,
+// O(V+E), whereas this algorithm is not, as the dominance frontier information
+// itself is not, but in practice runtime seems to be in the order of magnitude
+// of dominance tree calculation.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_REGION_INFO_H
+#define LLVM_ANALYSIS_REGION_INFO_H
+
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/Analysis/DominanceFrontier.h"
+#include "llvm/Analysis/PostDominators.h"
+#include "llvm/Support/Allocator.h"
+#include <map>
+
+namespace llvm {
+
+class Region;
+class RegionInfo;
+class raw_ostream;
+class Loop;
+class LoopInfo;
+
+/// @brief Marker class to iterate over the elements of a Region in flat mode.
+///
+/// The class is used to either iterate in Flat mode or by not using it to not
+/// iterate in Flat mode. During a Flat mode iteration all Regions are entered
+/// and the iteration returns every BasicBlock. If the Flat mode is not
+/// selected for SubRegions just one RegionNode containing the subregion is
+/// returned.
+template <class GraphType>
+class FlatIt {};
+
+/// @brief A RegionNode represents a subregion or a BasicBlock that is part of a
+/// Region.
+class RegionNode {
+ RegionNode(const RegionNode &) LLVM_DELETED_FUNCTION;
+ const RegionNode &operator=(const RegionNode &) LLVM_DELETED_FUNCTION;
+
+protected:
+ /// This is the entry basic block that starts this region node. If this is a
+ /// BasicBlock RegionNode, then entry is just the basic block, that this
+ /// RegionNode represents. Otherwise it is the entry of this (Sub)RegionNode.
+ ///
+ /// In the BBtoRegionNode map of the parent of this node, BB will always map
+ /// to this node no matter which kind of node this one is.
+ ///
+ /// The node can hold either a Region or a BasicBlock.
+ /// Use one bit to save, if this RegionNode is a subregion or BasicBlock
+ /// RegionNode.
+ PointerIntPair<BasicBlock*, 1, bool> entry;
+
+ /// @brief The parent Region of this RegionNode.
+ /// @see getParent()
+ Region* parent;
+
+public:
+ /// @brief Create a RegionNode.
+ ///
+ /// @param Parent The parent of this RegionNode.
+ /// @param Entry The entry BasicBlock of the RegionNode. If this
+ /// RegionNode represents a BasicBlock, this is the
+ /// BasicBlock itself. If it represents a subregion, this
+ /// is the entry BasicBlock of the subregion.
+ /// @param isSubRegion If this RegionNode represents a SubRegion.
+ inline RegionNode(Region* Parent, BasicBlock* Entry, bool isSubRegion = 0)
+ : entry(Entry, isSubRegion), parent(Parent) {}
+
+ /// @brief Get the parent Region of this RegionNode.
+ ///
+ /// The parent Region is the Region this RegionNode belongs to. If for
+ /// example a BasicBlock is element of two Regions, there exist two
+ /// RegionNodes for this BasicBlock. Each with the getParent() function
+ /// pointing to the Region this RegionNode belongs to.
+ ///
+ /// @return Get the parent Region of this RegionNode.
+ inline Region* getParent() const { return parent; }
+
+ /// @brief Get the entry BasicBlock of this RegionNode.
+ ///
+ /// If this RegionNode represents a BasicBlock this is just the BasicBlock
+ /// itself, otherwise we return the entry BasicBlock of the Subregion
+ ///
+ /// @return The entry BasicBlock of this RegionNode.
+ inline BasicBlock* getEntry() const { return entry.getPointer(); }
+
+ /// @brief Get the content of this RegionNode.
+ ///
+ /// This can be either a BasicBlock or a subregion. Before calling getNodeAs()
+ /// check the type of the content with the isSubRegion() function call.
+ ///
+ /// @return The content of this RegionNode.
+ template<class T>
+ inline T* getNodeAs() const;
+
+ /// @brief Is this RegionNode a subregion?
+ ///
+ /// @return True if it contains a subregion. False if it contains a
+ /// BasicBlock.
+ inline bool isSubRegion() const {
+ return entry.getInt();
+ }
+};
+
+/// Print a RegionNode.
+inline raw_ostream &operator<<(raw_ostream &OS, const RegionNode &Node);
+
+template<>
+inline BasicBlock* RegionNode::getNodeAs<BasicBlock>() const {
+ assert(!isSubRegion() && "This is not a BasicBlock RegionNode!");
+ return getEntry();
+}
+
+template<>
+inline Region* RegionNode::getNodeAs<Region>() const {
+ assert(isSubRegion() && "This is not a subregion RegionNode!");
+ return reinterpret_cast<Region*>(const_cast<RegionNode*>(this));
+}
+
+//===----------------------------------------------------------------------===//
+/// @brief A single entry single exit Region.
+///
+/// A Region is a connected subgraph of a control flow graph that has exactly
+/// two connections to the remaining graph. It can be used to analyze or
+/// optimize parts of the control flow graph.
+///
+/// A <em> simple Region </em> is connected to the remaining graph by just two
+/// edges. One edge entering the Region and another one leaving the Region.
+///
+/// An <em> extended Region </em> (or just Region) is a subgraph that can be
+/// transform into a simple Region. The transformation is done by adding
+/// BasicBlocks that merge several entry or exit edges so that after the merge
+/// just one entry and one exit edge exists.
+///
+/// The \e Entry of a Region is the first BasicBlock that is passed after
+/// entering the Region. It is an element of the Region. The entry BasicBlock
+/// dominates all BasicBlocks in the Region.
+///
+/// The \e Exit of a Region is the first BasicBlock that is passed after
+/// leaving the Region. It is not an element of the Region. The exit BasicBlock,
+/// postdominates all BasicBlocks in the Region.
+///
+/// A <em> canonical Region </em> cannot be constructed by combining smaller
+/// Regions.
+///
+/// Region A is the \e parent of Region B, if B is completely contained in A.
+///
+/// Two canonical Regions either do not intersect at all or one is
+/// the parent of the other.
+///
+/// The <em> Program Structure Tree</em> is a graph (V, E) where V is the set of
+/// Regions in the control flow graph and E is the \e parent relation of these
+/// Regions.
+///
+/// Example:
+///
+/// \verbatim
+/// A simple control flow graph, that contains two regions.
+///
+/// 1
+/// / |
+/// 2 |
+/// / \ 3
+/// 4 5 |
+/// | | |
+/// 6 7 8
+/// \ | /
+/// \ |/ Region A: 1 -> 9 {1,2,3,4,5,6,7,8}
+/// 9 Region B: 2 -> 9 {2,4,5,6,7}
+/// \endverbatim
+///
+/// You can obtain more examples by either calling
+///
+/// <tt> "opt -regions -analyze anyprogram.ll" </tt>
+/// or
+/// <tt> "opt -view-regions-only anyprogram.ll" </tt>
+///
+/// on any LLVM file you are interested in.
+///
+/// The first call returns a textual representation of the program structure
+/// tree, the second one creates a graphical representation using graphviz.
+class Region : public RegionNode {
+ friend class RegionInfo;
+ Region(const Region &) LLVM_DELETED_FUNCTION;
+ const Region &operator=(const Region &) LLVM_DELETED_FUNCTION;
+
+ // Information necessary to manage this Region.
+ RegionInfo* RI;
+ DominatorTree *DT;
+
+ // The exit BasicBlock of this region.
+ // (The entry BasicBlock is part of RegionNode)
+ BasicBlock *exit;
+
+ typedef std::vector<Region*> RegionSet;
+
+ // The subregions of this region.
+ RegionSet children;
+
+ typedef std::map<BasicBlock*, RegionNode*> BBNodeMapT;
+
+ // Save the BasicBlock RegionNodes that are element of this Region.
+ mutable BBNodeMapT BBNodeMap;
+
+ /// verifyBBInRegion - Check if a BB is in this Region. This check also works
+ /// if the region is incorrectly built. (EXPENSIVE!)
+ void verifyBBInRegion(BasicBlock* BB) const;
+
+ /// verifyWalk - Walk over all the BBs of the region starting from BB and
+ /// verify that all reachable basic blocks are elements of the region.
+ /// (EXPENSIVE!)
+ void verifyWalk(BasicBlock* BB, std::set<BasicBlock*>* visitedBB) const;
+
+ /// verifyRegionNest - Verify if the region and its children are valid
+ /// regions (EXPENSIVE!)
+ void verifyRegionNest() const;
+
+public:
+ /// @brief Create a new region.
+ ///
+ /// @param Entry The entry basic block of the region.
+ /// @param Exit The exit basic block of the region.
+ /// @param RI The region info object that is managing this region.
+ /// @param DT The dominator tree of the current function.
+ /// @param Parent The surrounding region or NULL if this is a top level
+ /// region.
+ Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RI,
+ DominatorTree *DT, Region *Parent = 0);
+
+ /// Delete the Region and all its subregions.
+ ~Region();
+
+ /// @brief Get the entry BasicBlock of the Region.
+ /// @return The entry BasicBlock of the region.
+ BasicBlock *getEntry() const { return RegionNode::getEntry(); }
+
+ /// @brief Replace the entry basic block of the region with the new basic
+ /// block.
+ ///
+ /// @param BB The new entry basic block of the region.
+ void replaceEntry(BasicBlock *BB);
+
+ /// @brief Replace the exit basic block of the region with the new basic
+ /// block.
+ ///
+ /// @param BB The new exit basic block of the region.
+ void replaceExit(BasicBlock *BB);
+
+ /// @brief Get the exit BasicBlock of the Region.
+ /// @return The exit BasicBlock of the Region, NULL if this is the TopLevel
+ /// Region.
+ BasicBlock *getExit() const { return exit; }
+
+ /// @brief Get the parent of the Region.
+ /// @return The parent of the Region or NULL if this is a top level
+ /// Region.
+ Region *getParent() const { return RegionNode::getParent(); }
+
+ /// @brief Get the RegionNode representing the current Region.
+ /// @return The RegionNode representing the current Region.
+ RegionNode* getNode() const {
+ return const_cast<RegionNode*>(reinterpret_cast<const RegionNode*>(this));
+ }
+
+ /// @brief Get the nesting level of this Region.
+ ///
+ /// An toplevel Region has depth 0.
+ ///
+ /// @return The depth of the region.
+ unsigned getDepth() const;
+
+ /// @brief Check if a Region is the TopLevel region.
+ ///
+ /// The toplevel region represents the whole function.
+ bool isTopLevelRegion() const { return exit == NULL; }
+
+ /// @brief Return a new (non canonical) region, that is obtained by joining
+ /// this region with its predecessors.
+ ///
+ /// @return A region also starting at getEntry(), but reaching to the next
+ /// basic block that forms with getEntry() a (non canonical) region.
+ /// NULL if such a basic block does not exist.
+ Region *getExpandedRegion() const;
+
+ /// @brief Return the first block of this region's single entry edge,
+ /// if existing.
+ ///
+ /// @return The BasicBlock starting this region's single entry edge,
+ /// else NULL.
+ BasicBlock *getEnteringBlock() const;
+
+ /// @brief Return the first block of this region's single exit edge,
+ /// if existing.
+ ///
+ /// @return The BasicBlock starting this region's single exit edge,
+ /// else NULL.
+ BasicBlock *getExitingBlock() const;
+
+ /// @brief Is this a simple region?
+ ///
+ /// A region is simple if it has exactly one exit and one entry edge.
+ ///
+ /// @return True if the Region is simple.
+ bool isSimple() const;
+
+ /// @brief Returns the name of the Region.
+ /// @return The Name of the Region.
+ std::string getNameStr() const;
+
+ /// @brief Return the RegionInfo object, that belongs to this Region.
+ RegionInfo *getRegionInfo() const {
+ return RI;
+ }
+
+ /// PrintStyle - Print region in difference ways.
+ enum PrintStyle { PrintNone, PrintBB, PrintRN };
+
+ /// @brief Print the region.
+ ///
+ /// @param OS The output stream the Region is printed to.
+ /// @param printTree Print also the tree of subregions.
+ /// @param level The indentation level used for printing.
+ void print(raw_ostream& OS, bool printTree = true, unsigned level = 0,
+ enum PrintStyle Style = PrintNone) const;
+
+ /// @brief Print the region to stderr.
+ void dump() const;
+
+ /// @brief Check if the region contains a BasicBlock.
+ ///
+ /// @param BB The BasicBlock that might be contained in this Region.
+ /// @return True if the block is contained in the region otherwise false.
+ bool contains(const BasicBlock *BB) const;
+
+ /// @brief Check if the region contains another region.
+ ///
+ /// @param SubRegion The region that might be contained in this Region.
+ /// @return True if SubRegion is contained in the region otherwise false.
+ bool contains(const Region *SubRegion) const {
+ // Toplevel Region.
+ if (!getExit())
+ return true;
+
+ return contains(SubRegion->getEntry())
+ && (contains(SubRegion->getExit()) || SubRegion->getExit() == getExit());
+ }
+
+ /// @brief Check if the region contains an Instruction.
+ ///
+ /// @param Inst The Instruction that might be contained in this region.
+ /// @return True if the Instruction is contained in the region otherwise false.
+ bool contains(const Instruction *Inst) const {
+ return contains(Inst->getParent());
+ }
+
+ /// @brief Check if the region contains a loop.
+ ///
+ /// @param L The loop that might be contained in this region.
+ /// @return True if the loop is contained in the region otherwise false.
+ /// In case a NULL pointer is passed to this function the result
+ /// is false, except for the region that describes the whole function.
+ /// In that case true is returned.
+ bool contains(const Loop *L) const;
+
+ /// @brief Get the outermost loop in the region that contains a loop.
+ ///
+ /// Find for a Loop L the outermost loop OuterL that is a parent loop of L
+ /// and is itself contained in the region.
+ ///
+ /// @param L The loop the lookup is started.
+ /// @return The outermost loop in the region, NULL if such a loop does not
+ /// exist or if the region describes the whole function.
+ Loop *outermostLoopInRegion(Loop *L) const;
+
+ /// @brief Get the outermost loop in the region that contains a basic block.
+ ///
+ /// Find for a basic block BB the outermost loop L that contains BB and is
+ /// itself contained in the region.
+ ///
+ /// @param LI A pointer to a LoopInfo analysis.
+ /// @param BB The basic block surrounded by the loop.
+ /// @return The outermost loop in the region, NULL if such a loop does not
+ /// exist or if the region describes the whole function.
+ Loop *outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const;
+
+ /// @brief Get the subregion that starts at a BasicBlock
+ ///
+ /// @param BB The BasicBlock the subregion should start.
+ /// @return The Subregion if available, otherwise NULL.
+ Region* getSubRegionNode(BasicBlock *BB) const;
+
+ /// @brief Get the RegionNode for a BasicBlock
+ ///
+ /// @param BB The BasicBlock at which the RegionNode should start.
+ /// @return If available, the RegionNode that represents the subregion
+ /// starting at BB. If no subregion starts at BB, the RegionNode
+ /// representing BB.
+ RegionNode* getNode(BasicBlock *BB) const;
+
+ /// @brief Get the BasicBlock RegionNode for a BasicBlock
+ ///
+ /// @param BB The BasicBlock for which the RegionNode is requested.
+ /// @return The RegionNode representing the BB.
+ RegionNode* getBBNode(BasicBlock *BB) const;
+
+ /// @brief Add a new subregion to this Region.
+ ///
+ /// @param SubRegion The new subregion that will be added.
+ /// @param moveChildren Move the children of this region, that are also
+ /// contained in SubRegion into SubRegion.
+ void addSubRegion(Region *SubRegion, bool moveChildren = false);
+
+ /// @brief Remove a subregion from this Region.
+ ///
+ /// The subregion is not deleted, as it will probably be inserted into another
+ /// region.
+ /// @param SubRegion The SubRegion that will be removed.
+ Region *removeSubRegion(Region *SubRegion);
+
+ /// @brief Move all direct child nodes of this Region to another Region.
+ ///
+ /// @param To The Region the child nodes will be transferred to.
+ void transferChildrenTo(Region *To);
+
+ /// @brief Verify if the region is a correct region.
+ ///
+ /// Check if this is a correctly build Region. This is an expensive check, as
+ /// the complete CFG of the Region will be walked.
+ void verifyRegion() const;
+
+ /// @brief Clear the cache for BB RegionNodes.
+ ///
+ /// After calling this function the BasicBlock RegionNodes will be stored at
+ /// different memory locations. RegionNodes obtained before this function is
+ /// called are therefore not comparable to RegionNodes abtained afterwords.
+ void clearNodeCache();
+
+ /// @name Subregion Iterators
+ ///
+ /// These iterators iterator over all subregions of this Region.
+ //@{
+ typedef RegionSet::iterator iterator;
+ typedef RegionSet::const_iterator const_iterator;
+
+ iterator begin() { return children.begin(); }
+ iterator end() { return children.end(); }
+
+ const_iterator begin() const { return children.begin(); }
+ const_iterator end() const { return children.end(); }
+ //@}
+
+ /// @name BasicBlock Iterators
+ ///
+ /// These iterators iterate over all BasicBlocks that are contained in this
+ /// Region. The iterator also iterates over BasicBlocks that are elements of
+ /// a subregion of this Region. It is therefore called a flat iterator.
+ //@{
+ template <bool IsConst>
+ class block_iterator_wrapper
+ : public df_iterator<typename conditional<IsConst,
+ const BasicBlock,
+ BasicBlock>::type*> {
+ typedef df_iterator<typename conditional<IsConst,
+ const BasicBlock,
+ BasicBlock>::type*>
+ super;
+ public:
+ typedef block_iterator_wrapper<IsConst> Self;
+ typedef typename super::pointer pointer;
+
+ // Construct the begin iterator.
+ block_iterator_wrapper(pointer Entry, pointer Exit) : super(df_begin(Entry))
+ {
+ // Mark the exit of the region as visited, so that the children of the
+ // exit and the exit itself, i.e. the block outside the region will never
+ // be visited.
+ super::Visited.insert(Exit);
+ }
+
+ // Construct the end iterator.
+ block_iterator_wrapper() : super(df_end<pointer>((BasicBlock *)0)) {}
+
+ /*implicit*/ block_iterator_wrapper(super I) : super(I) {}
+
+ // FIXME: Even a const_iterator returns a non-const BasicBlock pointer.
+ // This was introduced for backwards compatibility, but should
+ // be removed as soon as all users are fixed.
+ BasicBlock *operator*() const {
+ return const_cast<BasicBlock*>(super::operator*());
+ }
+ };
+
+ typedef block_iterator_wrapper<false> block_iterator;
+ typedef block_iterator_wrapper<true> const_block_iterator;
+
+ block_iterator block_begin() {
+ return block_iterator(getEntry(), getExit());
+ }
+
+ block_iterator block_end() {
+ return block_iterator();
+ }
+
+ const_block_iterator block_begin() const {
+ return const_block_iterator(getEntry(), getExit());
+ }
+ const_block_iterator block_end() const {
+ return const_block_iterator();
+ }
+ //@}
+
+ /// @name Element Iterators
+ ///
+ /// These iterators iterate over all BasicBlock and subregion RegionNodes that
+ /// are direct children of this Region. It does not iterate over any
+ /// RegionNodes that are also element of a subregion of this Region.
+ //@{
+ typedef df_iterator<RegionNode*, SmallPtrSet<RegionNode*, 8>, false,
+ GraphTraits<RegionNode*> > element_iterator;
+
+ typedef df_iterator<const RegionNode*, SmallPtrSet<const RegionNode*, 8>,
+ false, GraphTraits<const RegionNode*> >
+ const_element_iterator;
+
+ element_iterator element_begin();
+ element_iterator element_end();
+
+ const_element_iterator element_begin() const;
+ const_element_iterator element_end() const;
+ //@}
+};
+
+//===----------------------------------------------------------------------===//
+/// @brief Analysis that detects all canonical Regions.
+///
+/// The RegionInfo pass detects all canonical regions in a function. The Regions
+/// are connected using the parent relation. This builds a Program Structure
+/// Tree.
+class RegionInfo : public FunctionPass {
+ typedef DenseMap<BasicBlock*,BasicBlock*> BBtoBBMap;
+ typedef DenseMap<BasicBlock*, Region*> BBtoRegionMap;
+ typedef SmallPtrSet<Region*, 4> RegionSet;
+
+ RegionInfo(const RegionInfo &) LLVM_DELETED_FUNCTION;
+ const RegionInfo &operator=(const RegionInfo &) LLVM_DELETED_FUNCTION;
+
+ DominatorTree *DT;
+ PostDominatorTree *PDT;
+ DominanceFrontier *DF;
+
+ /// The top level region.
+ Region *TopLevelRegion;
+
+ /// Map every BB to the smallest region, that contains BB.
+ BBtoRegionMap BBtoRegion;
+
+ // isCommonDomFrontier - Returns true if BB is in the dominance frontier of
+ // entry, because it was inherited from exit. In the other case there is an
+ // edge going from entry to BB without passing exit.
+ bool isCommonDomFrontier(BasicBlock* BB, BasicBlock* entry,
+ BasicBlock* exit) const;
+
+ // isRegion - Check if entry and exit surround a valid region, based on
+ // dominance tree and dominance frontier.
+ bool isRegion(BasicBlock* entry, BasicBlock* exit) const;
+
+ // insertShortCut - Saves a shortcut pointing from entry to exit.
+ // This function may extend this shortcut if possible.
+ void insertShortCut(BasicBlock* entry, BasicBlock* exit,
+ BBtoBBMap* ShortCut) const;
+
+ // getNextPostDom - Returns the next BB that postdominates N, while skipping
+ // all post dominators that cannot finish a canonical region.
+ DomTreeNode *getNextPostDom(DomTreeNode* N, BBtoBBMap *ShortCut) const;
+
+ // isTrivialRegion - A region is trivial, if it contains only one BB.
+ bool isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const;
+
+ // createRegion - Creates a single entry single exit region.
+ Region *createRegion(BasicBlock *entry, BasicBlock *exit);
+
+ // findRegionsWithEntry - Detect all regions starting with bb 'entry'.
+ void findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut);
+
+ // scanForRegions - Detects regions in F.
+ void scanForRegions(Function &F, BBtoBBMap *ShortCut);
+
+ // getTopMostParent - Get the top most parent with the same entry block.
+ Region *getTopMostParent(Region *region);
+
+ // buildRegionsTree - build the region hierarchy after all region detected.
+ void buildRegionsTree(DomTreeNode *N, Region *region);
+
+ // Calculate - detecte all regions in function and build the region tree.
+ void Calculate(Function& F);
+
+ void releaseMemory();
+
+ // updateStatistics - Update statistic about created regions.
+ void updateStatistics(Region *R);
+
+ // isSimple - Check if a region is a simple region with exactly one entry
+ // edge and exactly one exit edge.
+ bool isSimple(Region* R) const;
+
+public:
+ static char ID;
+ explicit RegionInfo();
+
+ ~RegionInfo();
+
+ /// @name FunctionPass interface
+ //@{
+ virtual bool runOnFunction(Function &F);
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+ virtual void print(raw_ostream &OS, const Module *) const;
+ virtual void verifyAnalysis() const;
+ //@}
+
+ /// @brief Get the smallest region that contains a BasicBlock.
+ ///
+ /// @param BB The basic block.
+ /// @return The smallest region, that contains BB or NULL, if there is no
+ /// region containing BB.
+ Region *getRegionFor(BasicBlock *BB) const;
+
+ /// @brief Set the smallest region that surrounds a basic block.
+ ///
+ /// @param BB The basic block surrounded by a region.
+ /// @param R The smallest region that surrounds BB.
+ void setRegionFor(BasicBlock *BB, Region *R);
+
+ /// @brief A shortcut for getRegionFor().
+ ///
+ /// @param BB The basic block.
+ /// @return The smallest region, that contains BB or NULL, if there is no
+ /// region containing BB.
+ Region *operator[](BasicBlock *BB) const;
+
+ /// @brief Return the exit of the maximal refined region, that starts at a
+ /// BasicBlock.
+ ///
+ /// @param BB The BasicBlock the refined region starts.
+ BasicBlock *getMaxRegionExit(BasicBlock *BB) const;
+
+ /// @brief Find the smallest region that contains two regions.
+ ///
+ /// @param A The first region.
+ /// @param B The second region.
+ /// @return The smallest region containing A and B.
+ Region *getCommonRegion(Region* A, Region *B) const;
+
+ /// @brief Find the smallest region that contains two basic blocks.
+ ///
+ /// @param A The first basic block.
+ /// @param B The second basic block.
+ /// @return The smallest region that contains A and B.
+ Region* getCommonRegion(BasicBlock* A, BasicBlock *B) const {
+ return getCommonRegion(getRegionFor(A), getRegionFor(B));
+ }
+
+ /// @brief Find the smallest region that contains a set of regions.
+ ///
+ /// @param Regions A vector of regions.
+ /// @return The smallest region that contains all regions in Regions.
+ Region* getCommonRegion(SmallVectorImpl<Region*> &Regions) const;
+
+ /// @brief Find the smallest region that contains a set of basic blocks.
+ ///
+ /// @param BBs A vector of basic blocks.
+ /// @return The smallest region that contains all basic blocks in BBS.
+ Region* getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const;
+
+ Region *getTopLevelRegion() const {
+ return TopLevelRegion;
+ }
+
+ /// @brief Update RegionInfo after a basic block was split.
+ ///
+ /// @param NewBB The basic block that was created before OldBB.
+ /// @param OldBB The old basic block.
+ void splitBlock(BasicBlock* NewBB, BasicBlock *OldBB);
+
+ /// @brief Clear the Node Cache for all Regions.
+ ///
+ /// @see Region::clearNodeCache()
+ void clearNodeCache() {
+ if (TopLevelRegion)
+ TopLevelRegion->clearNodeCache();
+ }
+};
+
+inline raw_ostream &operator<<(raw_ostream &OS, const RegionNode &Node) {
+ if (Node.isSubRegion())
+ return OS << Node.getNodeAs<Region>()->getNameStr();
+ else
+ return OS << Node.getNodeAs<BasicBlock>()->getName();
+}
+} // End llvm namespace
+#endif
+
diff --git a/include/llvm/Analysis/RegionIterator.h b/include/llvm/Analysis/RegionIterator.h
new file mode 100644
index 00000000000..7adc71ca82a
--- /dev/null
+++ b/include/llvm/Analysis/RegionIterator.h
@@ -0,0 +1,342 @@
+//===- RegionIterator.h - Iterators to iteratate over Regions ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+// This file defines the iterators to iterate over the elements of a Region.
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_ANALYSIS_REGION_ITERATOR_H
+#define LLVM_ANALYSIS_REGION_ITERATOR_H
+
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/Analysis/RegionInfo.h"
+#include "llvm/Support/CFG.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace llvm {
+//===----------------------------------------------------------------------===//
+/// @brief Hierarchical RegionNode successor iterator.
+///
+/// This iterator iterates over all successors of a RegionNode.
+///
+/// For a BasicBlock RegionNode it skips all BasicBlocks that are not part of
+/// the parent Region. Furthermore for BasicBlocks that start a subregion, a
+/// RegionNode representing the subregion is returned.
+///
+/// For a subregion RegionNode there is just one successor. The RegionNode
+/// representing the exit of the subregion.
+template<class NodeType>
+class RNSuccIterator : public std::iterator<std::forward_iterator_tag,
+ NodeType, ptrdiff_t>
+{
+ typedef std::iterator<std::forward_iterator_tag, NodeType, ptrdiff_t> super;
+ // The iterator works in two modes, bb mode or region mode.
+ enum ItMode{
+ // In BB mode it returns all successors of this BasicBlock as its
+ // successors.
+ ItBB,
+ // In region mode there is only one successor, thats the regionnode mapping
+ // to the exit block of the regionnode
+ ItRgBegin, // At the beginning of the regionnode successor.
+ ItRgEnd // At the end of the regionnode successor.
+ };
+
+ // Use two bit to represent the mode iterator.
+ PointerIntPair<NodeType*, 2, enum ItMode> Node;
+
+ // The block successor iterator.
+ succ_iterator BItor;
+
+ // advanceRegionSucc - A region node has only one successor. It reaches end
+ // once we advance it.
+ void advanceRegionSucc() {
+ assert(Node.getInt() == ItRgBegin && "Cannot advance region successor!");
+ Node.setInt(ItRgEnd);
+ }
+
+ NodeType* getNode() const{ return Node.getPointer(); }
+
+ // isRegionMode - Is the current iterator in region mode?
+ bool isRegionMode() const { return Node.getInt() != ItBB; }
+
+ // Get the immediate successor. This function may return a Basic Block
+ // RegionNode or a subregion RegionNode.
+ RegionNode* getISucc(BasicBlock* BB) const {
+ RegionNode *succ;
+ succ = getNode()->getParent()->getNode(BB);
+ assert(succ && "BB not in Region or entered subregion!");
+ return succ;
+ }
+
+ // getRegionSucc - Return the successor basic block of a SubRegion RegionNode.
+ inline BasicBlock* getRegionSucc() const {
+ assert(Node.getInt() == ItRgBegin && "Cannot get the region successor!");
+ return getNode()->template getNodeAs<Region>()->getExit();
+ }
+
+ // isExit - Is this the exit BB of the Region?
+ inline bool isExit(BasicBlock* BB) const {
+ return getNode()->getParent()->getExit() == BB;
+ }
+public:
+ typedef RNSuccIterator<NodeType> Self;
+
+ typedef typename super::pointer pointer;
+
+ /// @brief Create begin iterator of a RegionNode.
+ inline RNSuccIterator(NodeType* node)
+ : Node(node, node->isSubRegion() ? ItRgBegin : ItBB),
+ BItor(succ_begin(node->getEntry())) {
+
+
+ // Skip the exit block
+ if (!isRegionMode())
+ while (succ_end(node->getEntry()) != BItor && isExit(*BItor))
+ ++BItor;
+
+ if (isRegionMode() && isExit(getRegionSucc()))
+ advanceRegionSucc();
+ }
+
+ /// @brief Create an end iterator.
+ inline RNSuccIterator(NodeType* node, bool)
+ : Node(node, node->isSubRegion() ? ItRgEnd : ItBB),
+ BItor(succ_end(node->getEntry())) {}
+
+ inline bool operator==(const Self& x) const {
+ assert(isRegionMode() == x.isRegionMode() && "Broken iterator!");
+ if (isRegionMode())
+ return Node.getInt() == x.Node.getInt();
+ else
+ return BItor == x.BItor;
+ }
+
+ inline bool operator!=(const Self& x) const { return !operator==(x); }
+
+ inline pointer operator*() const {
+ BasicBlock* BB = isRegionMode() ? getRegionSucc() : *BItor;
+ assert(!isExit(BB) && "Iterator out of range!");
+ return getISucc(BB);
+ }
+
+ inline Self& operator++() {
+ if(isRegionMode()) {
+ // The Region only has 1 successor.
+ advanceRegionSucc();
+ } else {
+ // Skip the exit.
+ do
+ ++BItor;
+ while (BItor != succ_end(getNode()->getEntry())
+ && isExit(*BItor));
+ }
+ return *this;
+ }
+
+ inline Self operator++(int) {
+ Self tmp = *this;
+ ++*this;
+ return tmp;
+ }
+
+ inline const Self &operator=(const Self &I) {
+ if (this != &I) {
+ assert(getNode()->getParent() == I.getNode()->getParent()
+ && "Cannot assign iterators of two different regions!");
+ Node = I.Node;
+ BItor = I.BItor;
+ }
+ return *this;
+ }
+};
+
+
+//===----------------------------------------------------------------------===//
+/// @brief Flat RegionNode iterator.
+///
+/// The Flat Region iterator will iterate over all BasicBlock RegionNodes that
+/// are contained in the Region and its subregions. This is close to a virtual
+/// control flow graph of the Region.
+template<class NodeType>
+class RNSuccIterator<FlatIt<NodeType> >
+ : public std::iterator<std::forward_iterator_tag, NodeType, ptrdiff_t>
+{
+ typedef std::iterator<std::forward_iterator_tag, NodeType, ptrdiff_t> super;
+ NodeType* Node;
+ succ_iterator Itor;
+
+public:
+ typedef RNSuccIterator<FlatIt<NodeType> > Self;
+ typedef typename super::pointer pointer;
+
+ /// @brief Create the iterator from a RegionNode.
+ ///
+ /// Note that the incoming node must be a bb node, otherwise it will trigger
+ /// an assertion when we try to get a BasicBlock.
+ inline RNSuccIterator(NodeType* node) : Node(node),
+ Itor(succ_begin(node->getEntry())) {
+ assert(!Node->isSubRegion()
+ && "Subregion node not allowed in flat iterating mode!");
+ assert(Node->getParent() && "A BB node must have a parent!");
+
+ // Skip the exit block of the iterating region.
+ while (succ_end(Node->getEntry()) != Itor
+ && Node->getParent()->getExit() == *Itor)
+ ++Itor;
+ }
+ /// @brief Create an end iterator
+ inline RNSuccIterator(NodeType* node, bool) : Node(node),
+ Itor(succ_end(node->getEntry())) {
+ assert(!Node->isSubRegion()
+ && "Subregion node not allowed in flat iterating mode!");
+ }
+
+ inline bool operator==(const Self& x) const {
+ assert(Node->getParent() == x.Node->getParent()
+ && "Cannot compare iterators of different regions!");
+
+ return Itor == x.Itor && Node == x.Node;
+ }
+
+ inline bool operator!=(const Self& x) const { return !operator==(x); }
+
+ inline pointer operator*() const {
+ BasicBlock* BB = *Itor;
+
+ // Get the iterating region.
+ Region* Parent = Node->getParent();
+
+ // The only case that the successor reaches out of the region is it reaches
+ // the exit of the region.
+ assert(Parent->getExit() != BB && "iterator out of range!");
+
+ return Parent->getBBNode(BB);
+ }
+
+ inline Self& operator++() {
+ // Skip the exit block of the iterating region.
+ do
+ ++Itor;
+ while (Itor != succ_end(Node->getEntry())
+ && Node->getParent()->getExit() == *Itor);
+
+ return *this;
+ }
+
+ inline Self operator++(int) {
+ Self tmp = *this;
+ ++*this;
+ return tmp;
+ }
+
+ inline const Self &operator=(const Self &I) {
+ if (this != &I) {
+ assert(Node->getParent() == I.Node->getParent()
+ && "Cannot assign iterators to two different regions!");
+ Node = I.Node;
+ Itor = I.Itor;
+ }
+ return *this;
+ }
+};
+
+template<class NodeType>
+inline RNSuccIterator<NodeType> succ_begin(NodeType* Node) {
+ return RNSuccIterator<NodeType>(Node);
+}
+
+template<class NodeType>
+inline RNSuccIterator<NodeType> succ_end(NodeType* Node) {
+ return RNSuccIterator<NodeType>(Node, true);
+}
+
+//===--------------------------------------------------------------------===//
+// RegionNode GraphTraits specialization so the bbs in the region can be
+// iterate by generic graph iterators.
+//
+// NodeT can either be region node or const region node, otherwise child_begin
+// and child_end fail.
+
+#define RegionNodeGraphTraits(NodeT) \
+ template<> struct GraphTraits<NodeT*> { \
+ typedef NodeT NodeType; \
+ typedef RNSuccIterator<NodeType> ChildIteratorType; \
+ static NodeType *getEntryNode(NodeType* N) { return N; } \
+ static inline ChildIteratorType child_begin(NodeType *N) { \
+ return RNSuccIterator<NodeType>(N); \
+ } \
+ static inline ChildIteratorType child_end(NodeType *N) { \
+ return RNSuccIterator<NodeType>(N, true); \
+ } \
+}; \
+template<> struct GraphTraits<FlatIt<NodeT*> > { \
+ typedef NodeT NodeType; \
+ typedef RNSuccIterator<FlatIt<NodeT> > ChildIteratorType; \
+ static NodeType *getEntryNode(NodeType* N) { return N; } \
+ static inline ChildIteratorType child_begin(NodeType *N) { \
+ return RNSuccIterator<FlatIt<NodeType> >(N); \
+ } \
+ static inline ChildIteratorType child_end(NodeType *N) { \
+ return RNSuccIterator<FlatIt<NodeType> >(N, true); \
+ } \
+}
+
+#define RegionGraphTraits(RegionT, NodeT) \
+template<> struct GraphTraits<RegionT*> \
+ : public GraphTraits<NodeT*> { \
+ typedef df_iterator<NodeType*> nodes_iterator; \
+ static NodeType *getEntryNode(RegionT* R) { \
+ return R->getNode(R->getEntry()); \
+ } \
+ static nodes_iterator nodes_begin(RegionT* R) { \
+ return nodes_iterator::begin(getEntryNode(R)); \
+ } \
+ static nodes_iterator nodes_end(RegionT* R) { \
+ return nodes_iterator::end(getEntryNode(R)); \
+ } \
+}; \
+template<> struct GraphTraits<FlatIt<RegionT*> > \
+ : public GraphTraits<FlatIt<NodeT*> > { \
+ typedef df_iterator<NodeType*, SmallPtrSet<NodeType*, 8>, false, \
+ GraphTraits<FlatIt<NodeType*> > > nodes_iterator; \
+ static NodeType *getEntryNode(RegionT* R) { \
+ return R->getBBNode(R->getEntry()); \
+ } \
+ static nodes_iterator nodes_begin(RegionT* R) { \
+ return nodes_iterator::begin(getEntryNode(R)); \
+ } \
+ static nodes_iterator nodes_end(RegionT* R) { \
+ return nodes_iterator::end(getEntryNode(R)); \
+ } \
+}
+
+RegionNodeGraphTraits(RegionNode);
+RegionNodeGraphTraits(const RegionNode);
+
+RegionGraphTraits(Region, RegionNode);
+RegionGraphTraits(const Region, const RegionNode);
+
+template <> struct GraphTraits<RegionInfo*>
+ : public GraphTraits<FlatIt<RegionNode*> > {
+ typedef df_iterator<NodeType*, SmallPtrSet<NodeType*, 8>, false,
+ GraphTraits<FlatIt<NodeType*> > > nodes_iterator;
+
+ static NodeType *getEntryNode(RegionInfo *RI) {
+ return GraphTraits<FlatIt<Region*> >::getEntryNode(RI->getTopLevelRegion());
+ }
+ static nodes_iterator nodes_begin(RegionInfo* RI) {
+ return nodes_iterator::begin(getEntryNode(RI));
+ }
+ static nodes_iterator nodes_end(RegionInfo *RI) {
+ return nodes_iterator::end(getEntryNode(RI));
+ }
+};
+
+} // End namespace llvm
+
+#endif
diff --git a/include/llvm/Analysis/RegionPass.h b/include/llvm/Analysis/RegionPass.h
new file mode 100644
index 00000000000..68f12012bcd
--- /dev/null
+++ b/include/llvm/Analysis/RegionPass.h
@@ -0,0 +1,126 @@
+//===- RegionPass.h - RegionPass class ------------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the RegionPass class. All region based analysis,
+// optimization and transformation passes are derived from RegionPass.
+// This class is implemented following the some ideas of the LoopPass.h class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_REGION_PASS_H
+#define LLVM_REGION_PASS_H
+
+#include "llvm/Analysis/RegionInfo.h"
+
+#include "llvm/Pass.h"
+#include "llvm/PassManagers.h"
+#include "llvm/Function.h"
+
+#include <deque>
+
+namespace llvm {
+
+class RGPassManager;
+class Function;
+
+//===----------------------------------------------------------------------===//
+/// @brief A pass that runs on each Region in a function.
+///
+/// RegionPass is managed by RGPassManager.
+class RegionPass : public Pass {
+public:
+ explicit RegionPass(char &pid) : Pass(PT_Region, pid) {}
+
+ //===--------------------------------------------------------------------===//
+ /// @name To be implemented by every RegionPass
+ ///
+ //@{
+ /// @brief Run the pass on a specific Region
+ ///
+ /// Accessing regions not contained in the current region is not allowed.
+ ///
+ /// @param R The region this pass is run on.
+ /// @param RGM The RegionPassManager that manages this Pass.
+ ///
+ /// @return True if the pass modifies this Region.
+ virtual bool runOnRegion(Region *R, RGPassManager &RGM) = 0;
+
+ /// @brief Get a pass to print the LLVM IR in the region.
+ ///
+ /// @param O The ouput stream to print the Region.
+ /// @param Banner The banner to separate different printed passes.
+ ///
+ /// @return The pass to print the LLVM IR in the region.
+ Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
+
+ virtual bool doInitialization(Region *R, RGPassManager &RGM) { return false; }
+ virtual bool doFinalization() { return false; }
+ //@}
+
+ //===--------------------------------------------------------------------===//
+ /// @name PassManager API
+ ///
+ //@{
+ void preparePassManager(PMStack &PMS);
+
+ virtual void assignPassManager(PMStack &PMS,
+ PassManagerType PMT = PMT_RegionPassManager);
+
+ virtual PassManagerType getPotentialPassManagerType() const {
+ return PMT_RegionPassManager;
+ }
+ //@}
+};
+
+/// @brief The pass manager to schedule RegionPasses.
+class RGPassManager : public FunctionPass, public PMDataManager {
+ std::deque<Region*> RQ;
+ bool skipThisRegion;
+ bool redoThisRegion;
+ RegionInfo *RI;
+ Region *CurrentRegion;
+
+public:
+ static char ID;
+ explicit RGPassManager();
+
+ /// @brief Execute all of the passes scheduled for execution.
+ ///
+ /// @return True if any of the passes modifies the function.
+ bool runOnFunction(Function &F);
+
+ /// Pass Manager itself does not invalidate any analysis info.
+ /// RGPassManager needs RegionInfo.
+ void getAnalysisUsage(AnalysisUsage &Info) const;
+
+ virtual const char *getPassName() const {
+ return "Region Pass Manager";
+ }
+
+ virtual PMDataManager *getAsPMDataManager() { return this; }
+ virtual Pass *getAsPass() { return this; }
+
+ /// @brief Print passes managed by this manager.
+ void dumpPassStructure(unsigned Offset);
+
+ /// @brief Get passes contained by this manager.
+ Pass *getContainedPass(unsigned N) {
+ assert(N < PassVector.size() && "Pass number out of range!");
+ Pass *FP = static_cast<Pass *>(PassVector[N]);
+ return FP;
+ }
+
+ virtual PassManagerType getPassManagerType() const {
+ return PMT_RegionPassManager;
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/RegionPrinter.h b/include/llvm/Analysis/RegionPrinter.h
new file mode 100644
index 00000000000..758748aad9e
--- /dev/null
+++ b/include/llvm/Analysis/RegionPrinter.h
@@ -0,0 +1,26 @@
+//===-- RegionPrinter.h - Region printer external interface -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines external functions that can be called to explicitly
+// instantiate the region printer.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_REGIONPRINTER_H
+#define LLVM_ANALYSIS_REGIONPRINTER_H
+
+namespace llvm {
+ class FunctionPass;
+ FunctionPass *createRegionViewerPass();
+ FunctionPass *createRegionOnlyViewerPass();
+ FunctionPass *createRegionPrinterPass();
+ FunctionPass *createRegionOnlyPrinterPass();
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Analysis/ScalarEvolution.h b/include/llvm/Analysis/ScalarEvolution.h
new file mode 100644
index 00000000000..c8c249a1b16
--- /dev/null
+++ b/include/llvm/Analysis/ScalarEvolution.h
@@ -0,0 +1,889 @@
+//===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The ScalarEvolution class is an LLVM pass which can be used to analyze and
+// categorize scalar expressions in loops. It specializes in recognizing
+// general induction variables, representing them with the abstract and opaque
+// SCEV class. Given this analysis, trip counts of loops and other important
+// properties can be obtained.
+//
+// This analysis is primarily useful for induction variable substitution and
+// strength reduction.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
+#define LLVM_ANALYSIS_SCALAREVOLUTION_H
+
+#include "llvm/Pass.h"
+#include "llvm/Instructions.h"
+#include "llvm/Function.h"
+#include "llvm/Operator.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ValueHandle.h"
+#include "llvm/Support/Allocator.h"
+#include "llvm/Support/ConstantRange.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/DenseSet.h"
+#include <map>
+
+namespace llvm {
+ class APInt;
+ class Constant;
+ class ConstantInt;
+ class DominatorTree;
+ class Type;
+ class ScalarEvolution;
+ class TargetData;
+ class TargetLibraryInfo;
+ class LLVMContext;
+ class Loop;
+ class LoopInfo;
+ class Operator;
+ class SCEVUnknown;
+ class SCEV;
+ template<> struct FoldingSetTrait<SCEV>;
+
+ /// SCEV - This class represents an analyzed expression in the program. These
+ /// are opaque objects that the client is not allowed to do much with
+ /// directly.
+ ///
+ class SCEV : public FoldingSetNode {
+ friend struct FoldingSetTrait<SCEV>;
+
+ /// FastID - A reference to an Interned FoldingSetNodeID for this node.
+ /// The ScalarEvolution's BumpPtrAllocator holds the data.
+ FoldingSetNodeIDRef FastID;
+
+ // The SCEV baseclass this node corresponds to
+ const unsigned short SCEVType;
+
+ protected:
+ /// SubclassData - This field is initialized to zero and may be used in
+ /// subclasses to store miscellaneous information.
+ unsigned short SubclassData;
+
+ private:
+ SCEV(const SCEV &) LLVM_DELETED_FUNCTION;
+ void operator=(const SCEV &) LLVM_DELETED_FUNCTION;
+
+ public:
+ /// NoWrapFlags are bitfield indices into SubclassData.
+ ///
+ /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
+ /// no-signed-wrap <NSW> properties, which are derived from the IR
+ /// operator. NSW is a misnomer that we use to mean no signed overflow or
+ /// underflow.
+ ///
+ /// AddRec expression may have a no-self-wraparound <NW> property if the
+ /// result can never reach the start value. This property is independent of
+ /// the actual start value and step direction. Self-wraparound is defined
+ /// purely in terms of the recurrence's loop, step size, and
+ /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
+ /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
+ ///
+ /// Note that NUW and NSW are also valid properties of a recurrence, and
+ /// either implies NW. For convenience, NW will be set for a recurrence
+ /// whenever either NUW or NSW are set.
+ enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee.
+ FlagNW = (1 << 0), // No self-wrap.
+ FlagNUW = (1 << 1), // No unsigned wrap.
+ FlagNSW = (1 << 2), // No signed wrap.
+ NoWrapMask = (1 << 3) -1 };
+
+ explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
+ FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
+
+ unsigned getSCEVType() const { return SCEVType; }
+
+ /// getType - Return the LLVM type of this SCEV expression.
+ ///
+ Type *getType() const;
+
+ /// isZero - Return true if the expression is a constant zero.
+ ///
+ bool isZero() const;
+
+ /// isOne - Return true if the expression is a constant one.
+ ///
+ bool isOne() const;
+
+ /// isAllOnesValue - Return true if the expression is a constant
+ /// all-ones value.
+ ///
+ bool isAllOnesValue() const;
+
+ /// isNonConstantNegative - Return true if the specified scev is negated,
+ /// but not a constant.
+ bool isNonConstantNegative() const;
+
+ /// print - Print out the internal representation of this scalar to the
+ /// specified stream. This should really only be used for debugging
+ /// purposes.
+ void print(raw_ostream &OS) const;
+
+ /// dump - This method is used for debugging.
+ ///
+ void dump() const;
+ };
+
+ // Specialize FoldingSetTrait for SCEV to avoid needing to compute
+ // temporary FoldingSetNodeID values.
+ template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
+ static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
+ ID = X.FastID;
+ }
+ static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
+ unsigned IDHash, FoldingSetNodeID &TempID) {
+ return ID == X.FastID;
+ }
+ static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
+ return X.FastID.ComputeHash();
+ }
+ };
+
+ inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
+ S.print(OS);
+ return OS;
+ }
+
+ /// SCEVCouldNotCompute - An object of this class is returned by queries that
+ /// could not be answered. For example, if you ask for the number of
+ /// iterations of a linked-list traversal loop, you will get one of these.
+ /// None of the standard SCEV operations are valid on this class, it is just a
+ /// marker.
+ struct SCEVCouldNotCompute : public SCEV {
+ SCEVCouldNotCompute();
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
+ static bool classof(const SCEV *S);
+ };
+
+ /// ScalarEvolution - This class is the main scalar evolution driver. Because
+ /// client code (intentionally) can't do much with the SCEV objects directly,
+ /// they must ask this class for services.
+ ///
+ class ScalarEvolution : public FunctionPass {
+ public:
+ /// LoopDisposition - An enum describing the relationship between a
+ /// SCEV and a loop.
+ enum LoopDisposition {
+ LoopVariant, ///< The SCEV is loop-variant (unknown).
+ LoopInvariant, ///< The SCEV is loop-invariant.
+ LoopComputable ///< The SCEV varies predictably with the loop.
+ };
+
+ /// BlockDisposition - An enum describing the relationship between a
+ /// SCEV and a basic block.
+ enum BlockDisposition {
+ DoesNotDominateBlock, ///< The SCEV does not dominate the block.
+ DominatesBlock, ///< The SCEV dominates the block.
+ ProperlyDominatesBlock ///< The SCEV properly dominates the block.
+ };
+
+ /// Convenient NoWrapFlags manipulation that hides enum casts and is
+ /// visible in the ScalarEvolution name space.
+ static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
+ return (SCEV::NoWrapFlags)(Flags & Mask);
+ }
+ static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
+ SCEV::NoWrapFlags OnFlags) {
+ return (SCEV::NoWrapFlags)(Flags | OnFlags);
+ }
+ static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags,
+ SCEV::NoWrapFlags OffFlags) {
+ return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
+ }
+
+ private:
+ /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
+ /// notified whenever a Value is deleted.
+ class SCEVCallbackVH : public CallbackVH {
+ ScalarEvolution *SE;
+ virtual void deleted();
+ virtual void allUsesReplacedWith(Value *New);
+ public:
+ SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
+ };
+
+ friend class SCEVCallbackVH;
+ friend class SCEVExpander;
+ friend class SCEVUnknown;
+
+ /// F - The function we are analyzing.
+ ///
+ Function *F;
+
+ /// LI - The loop information for the function we are currently analyzing.
+ ///
+ LoopInfo *LI;
+
+ /// TD - The target data information for the target we are targeting.
+ ///
+ TargetData *TD;
+
+ /// TLI - The target library information for the target we are targeting.
+ ///
+ TargetLibraryInfo *TLI;
+
+ /// DT - The dominator tree.
+ ///
+ DominatorTree *DT;
+
+ /// CouldNotCompute - This SCEV is used to represent unknown trip
+ /// counts and things.
+ SCEVCouldNotCompute CouldNotCompute;
+
+ /// ValueExprMapType - The typedef for ValueExprMap.
+ ///
+ typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
+ ValueExprMapType;
+
+ /// ValueExprMap - This is a cache of the values we have analyzed so far.
+ ///
+ ValueExprMapType ValueExprMap;
+
+ /// Mark predicate values currently being processed by isImpliedCond.
+ DenseSet<Value*> PendingLoopPredicates;
+
+ /// ExitLimit - Information about the number of loop iterations for
+ /// which a loop exit's branch condition evaluates to the not-taken path.
+ /// This is a temporary pair of exact and max expressions that are
+ /// eventually summarized in ExitNotTakenInfo and BackedgeTakenInfo.
+ struct ExitLimit {
+ const SCEV *Exact;
+ const SCEV *Max;
+
+ /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
+
+ ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
+
+ /// hasAnyInfo - Test whether this ExitLimit contains any computed
+ /// information, or whether it's all SCEVCouldNotCompute values.
+ bool hasAnyInfo() const {
+ return !isa<SCEVCouldNotCompute>(Exact) ||
+ !isa<SCEVCouldNotCompute>(Max);
+ }
+ };
+
+ /// ExitNotTakenInfo - Information about the number of times a particular
+ /// loop exit may be reached before exiting the loop.
+ struct ExitNotTakenInfo {
+ AssertingVH<BasicBlock> ExitingBlock;
+ const SCEV *ExactNotTaken;
+ PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
+
+ ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {}
+
+ /// isCompleteList - Return true if all loop exits are computable.
+ bool isCompleteList() const {
+ return NextExit.getInt() == 0;
+ }
+
+ void setIncomplete() { NextExit.setInt(1); }
+
+ /// getNextExit - Return a pointer to the next exit's not-taken info.
+ ExitNotTakenInfo *getNextExit() const {
+ return NextExit.getPointer();
+ }
+
+ void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
+ };
+
+ /// BackedgeTakenInfo - Information about the backedge-taken count
+ /// of a loop. This currently includes an exact count and a maximum count.
+ ///
+ class BackedgeTakenInfo {
+ /// ExitNotTaken - A list of computable exits and their not-taken counts.
+ /// Loops almost never have more than one computable exit.
+ ExitNotTakenInfo ExitNotTaken;
+
+ /// Max - An expression indicating the least maximum backedge-taken
+ /// count of the loop that is known, or a SCEVCouldNotCompute.
+ const SCEV *Max;
+
+ public:
+ BackedgeTakenInfo() : Max(0) {}
+
+ /// Initialize BackedgeTakenInfo from a list of exact exit counts.
+ BackedgeTakenInfo(
+ SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
+ bool Complete, const SCEV *MaxCount);
+
+ /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
+ /// computed information, or whether it's all SCEVCouldNotCompute
+ /// values.
+ bool hasAnyInfo() const {
+ return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
+ }
+
+ /// getExact - Return an expression indicating the exact backedge-taken
+ /// count of the loop if it is known, or SCEVCouldNotCompute
+ /// otherwise. This is the number of times the loop header can be
+ /// guaranteed to execute, minus one.
+ const SCEV *getExact(ScalarEvolution *SE) const;
+
+ /// getExact - Return the number of times this loop exit may fall through
+ /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
+ /// to exit via this block before this number of iterations, but may exit
+ /// via another block.
+ const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
+
+ /// getMax - Get the max backedge taken count for the loop.
+ const SCEV *getMax(ScalarEvolution *SE) const;
+
+ /// clear - Invalidate this result and free associated memory.
+ void clear();
+ };
+
+ /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
+ /// this function as they are computed.
+ DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
+
+ /// ConstantEvolutionLoopExitValue - This map contains entries for all of
+ /// the PHI instructions that we attempt to compute constant evolutions for.
+ /// This allows us to avoid potentially expensive recomputation of these
+ /// properties. An instruction maps to null if we are unable to compute its
+ /// exit value.
+ DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
+
+ /// ValuesAtScopes - This map contains entries for all the expressions
+ /// that we attempt to compute getSCEVAtScope information for, which can
+ /// be expensive in extreme cases.
+ DenseMap<const SCEV *,
+ std::map<const Loop *, const SCEV *> > ValuesAtScopes;
+
+ /// LoopDispositions - Memoized computeLoopDisposition results.
+ DenseMap<const SCEV *,
+ std::map<const Loop *, LoopDisposition> > LoopDispositions;
+
+ /// computeLoopDisposition - Compute a LoopDisposition value.
+ LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
+
+ /// BlockDispositions - Memoized computeBlockDisposition results.
+ DenseMap<const SCEV *,
+ std::map<const BasicBlock *, BlockDisposition> > BlockDispositions;
+
+ /// computeBlockDisposition - Compute a BlockDisposition value.
+ BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
+
+ /// UnsignedRanges - Memoized results from getUnsignedRange
+ DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
+
+ /// SignedRanges - Memoized results from getSignedRange
+ DenseMap<const SCEV *, ConstantRange> SignedRanges;
+
+ /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
+ const ConstantRange &setUnsignedRange(const SCEV *S,
+ const ConstantRange &CR) {
+ std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
+ UnsignedRanges.insert(std::make_pair(S, CR));
+ if (!Pair.second)
+ Pair.first->second = CR;
+ return Pair.first->second;
+ }
+
+ /// setUnsignedRange - Set the memoized signed range for the given SCEV.
+ const ConstantRange &setSignedRange(const SCEV *S,
+ const ConstantRange &CR) {
+ std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
+ SignedRanges.insert(std::make_pair(S, CR));
+ if (!Pair.second)
+ Pair.first->second = CR;
+ return Pair.first->second;
+ }
+
+ /// createSCEV - We know that there is no SCEV for the specified value.
+ /// Analyze the expression.
+ const SCEV *createSCEV(Value *V);
+
+ /// createNodeForPHI - Provide the special handling we need to analyze PHI
+ /// SCEVs.
+ const SCEV *createNodeForPHI(PHINode *PN);
+
+ /// createNodeForGEP - Provide the special handling we need to analyze GEP
+ /// SCEVs.
+ const SCEV *createNodeForGEP(GEPOperator *GEP);
+
+ /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
+ /// at most once for each SCEV+Loop pair.
+ ///
+ const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
+
+ /// ForgetSymbolicValue - This looks up computed SCEV values for all
+ /// instructions that depend on the given instruction and removes them from
+ /// the ValueExprMap map if they reference SymName. This is used during PHI
+ /// resolution.
+ void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
+
+ /// getBECount - Subtract the end and start values and divide by the step,
+ /// rounding up, to get the number of times the backedge is executed. Return
+ /// CouldNotCompute if an intermediate computation overflows.
+ const SCEV *getBECount(const SCEV *Start,
+ const SCEV *End,
+ const SCEV *Step,
+ bool NoWrap);
+
+ /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
+ /// loop, lazily computing new values if the loop hasn't been analyzed
+ /// yet.
+ const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
+
+ /// ComputeBackedgeTakenCount - Compute the number of times the specified
+ /// loop will iterate.
+ BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
+
+ /// ComputeExitLimit - Compute the number of times the backedge of the
+ /// specified loop will execute if it exits via the specified block.
+ ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
+
+ /// ComputeExitLimitFromCond - Compute the number of times the backedge of
+ /// the specified loop will execute if its exit condition were a conditional
+ /// branch of ExitCond, TBB, and FBB.
+ ExitLimit ComputeExitLimitFromCond(const Loop *L,
+ Value *ExitCond,
+ BasicBlock *TBB,
+ BasicBlock *FBB);
+
+ /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
+ /// the specified loop will execute if its exit condition were a conditional
+ /// branch of the ICmpInst ExitCond, TBB, and FBB.
+ ExitLimit ComputeExitLimitFromICmp(const Loop *L,
+ ICmpInst *ExitCond,
+ BasicBlock *TBB,
+ BasicBlock *FBB);
+
+ /// ComputeLoadConstantCompareExitLimit - Given an exit condition
+ /// of 'icmp op load X, cst', try to see if we can compute the
+ /// backedge-taken count.
+ ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
+ Constant *RHS,
+ const Loop *L,
+ ICmpInst::Predicate p);
+
+ /// ComputeExitCountExhaustively - If the loop is known to execute a
+ /// constant number of times (the condition evolves only from constants),
+ /// try to evaluate a few iterations of the loop until we get the exit
+ /// condition gets a value of ExitWhen (true or false). If we cannot
+ /// evaluate the exit count of the loop, return CouldNotCompute.
+ const SCEV *ComputeExitCountExhaustively(const Loop *L,
+ Value *Cond,
+ bool ExitWhen);
+
+ /// HowFarToZero - Return the number of times an exit condition comparing
+ /// the specified value to zero will execute. If not computable, return
+ /// CouldNotCompute.
+ ExitLimit HowFarToZero(const SCEV *V, const Loop *L);
+
+ /// HowFarToNonZero - Return the number of times an exit condition checking
+ /// the specified value for nonzero will execute. If not computable, return
+ /// CouldNotCompute.
+ ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
+
+ /// HowManyLessThans - Return the number of times an exit condition
+ /// containing the specified less-than comparison will execute. If not
+ /// computable, return CouldNotCompute. isSigned specifies whether the
+ /// less-than is signed.
+ ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
+ const Loop *L, bool isSigned);
+
+ /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
+ /// (which may not be an immediate predecessor) which has exactly one
+ /// successor from which BB is reachable, or null if no such block is
+ /// found.
+ std::pair<BasicBlock *, BasicBlock *>
+ getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
+
+ /// isImpliedCond - Test whether the condition described by Pred, LHS, and
+ /// RHS is true whenever the given FoundCondValue value evaluates to true.
+ bool isImpliedCond(ICmpInst::Predicate Pred,
+ const SCEV *LHS, const SCEV *RHS,
+ Value *FoundCondValue,
+ bool Inverse);
+
+ /// isImpliedCondOperands - Test whether the condition described by Pred,
+ /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
+ /// and FoundRHS is true.
+ bool isImpliedCondOperands(ICmpInst::Predicate Pred,
+ const SCEV *LHS, const SCEV *RHS,
+ const SCEV *FoundLHS, const SCEV *FoundRHS);
+
+ /// isImpliedCondOperandsHelper - Test whether the condition described by
+ /// Pred, LHS, and RHS is true whenever the condition described by Pred,
+ /// FoundLHS, and FoundRHS is true.
+ bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
+ const SCEV *LHS, const SCEV *RHS,
+ const SCEV *FoundLHS,
+ const SCEV *FoundRHS);
+
+ /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
+ /// in the header of its containing loop, we know the loop executes a
+ /// constant number of times, and the PHI node is just a recurrence
+ /// involving constants, fold it.
+ Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
+ const Loop *L);
+
+ /// isKnownPredicateWithRanges - Test if the given expression is known to
+ /// satisfy the condition described by Pred and the known constant ranges
+ /// of LHS and RHS.
+ ///
+ bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
+ const SCEV *LHS, const SCEV *RHS);
+
+ /// forgetMemoizedResults - Drop memoized information computed for S.
+ void forgetMemoizedResults(const SCEV *S);
+
+ public:
+ static char ID; // Pass identification, replacement for typeid
+ ScalarEvolution();
+
+ LLVMContext &getContext() const { return F->getContext(); }
+
+ /// isSCEVable - Test if values of the given type are analyzable within
+ /// the SCEV framework. This primarily includes integer types, and it
+ /// can optionally include pointer types if the ScalarEvolution class
+ /// has access to target-specific information.
+ bool isSCEVable(Type *Ty) const;
+
+ /// getTypeSizeInBits - Return the size in bits of the specified type,
+ /// for which isSCEVable must return true.
+ uint64_t getTypeSizeInBits(Type *Ty) const;
+
+ /// getEffectiveSCEVType - Return a type with the same bitwidth as
+ /// the given type and which represents how SCEV will treat the given
+ /// type, for which isSCEVable must return true. For pointer types,
+ /// this is the pointer-sized integer type.
+ Type *getEffectiveSCEVType(Type *Ty) const;
+
+ /// getSCEV - Return a SCEV expression for the full generality of the
+ /// specified expression.
+ const SCEV *getSCEV(Value *V);
+
+ const SCEV *getConstant(ConstantInt *V);
+ const SCEV *getConstant(const APInt& Val);
+ const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
+ const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
+ const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
+ const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
+ const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
+ const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
+ SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
+ const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
+ SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
+ SmallVector<const SCEV *, 2> Ops;
+ Ops.push_back(LHS);
+ Ops.push_back(RHS);
+ return getAddExpr(Ops, Flags);
+ }
+ const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
+ SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
+ SmallVector<const SCEV *, 3> Ops;
+ Ops.push_back(Op0);
+ Ops.push_back(Op1);
+ Ops.push_back(Op2);
+ return getAddExpr(Ops, Flags);
+ }
+ const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
+ SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
+ const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
+ SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
+ {
+ SmallVector<const SCEV *, 2> Ops;
+ Ops.push_back(LHS);
+ Ops.push_back(RHS);
+ return getMulExpr(Ops, Flags);
+ }
+ const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
+ SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
+ SmallVector<const SCEV *, 3> Ops;
+ Ops.push_back(Op0);
+ Ops.push_back(Op1);
+ Ops.push_back(Op2);
+ return getMulExpr(Ops, Flags);
+ }
+ const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
+ const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
+ const Loop *L, SCEV::NoWrapFlags Flags);
+ const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
+ const Loop *L, SCEV::NoWrapFlags Flags);
+ const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
+ const Loop *L, SCEV::NoWrapFlags Flags) {
+ SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
+ return getAddRecExpr(NewOp, L, Flags);
+ }
+ const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
+ const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
+ const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
+ const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
+ const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
+ const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
+ const SCEV *getUnknown(Value *V);
+ const SCEV *getCouldNotCompute();
+
+ /// getSizeOfExpr - Return an expression for sizeof on the given type.
+ ///
+ const SCEV *getSizeOfExpr(Type *AllocTy);
+
+ /// getAlignOfExpr - Return an expression for alignof on the given type.
+ ///
+ const SCEV *getAlignOfExpr(Type *AllocTy);
+
+ /// getOffsetOfExpr - Return an expression for offsetof on the given field.
+ ///
+ const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
+
+ /// getOffsetOfExpr - Return an expression for offsetof on the given field.
+ ///
+ const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
+
+ /// getNegativeSCEV - Return the SCEV object corresponding to -V.
+ ///
+ const SCEV *getNegativeSCEV(const SCEV *V);
+
+ /// getNotSCEV - Return the SCEV object corresponding to ~V.
+ ///
+ const SCEV *getNotSCEV(const SCEV *V);
+
+ /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
+ const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
+ SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
+
+ /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
+ /// of the input value to the specified type. If the type must be
+ /// extended, it is zero extended.
+ const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
+
+ /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
+ /// of the input value to the specified type. If the type must be
+ /// extended, it is sign extended.
+ const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
+
+ /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
+ /// the input value to the specified type. If the type must be extended,
+ /// it is zero extended. The conversion must not be narrowing.
+ const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
+
+ /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
+ /// the input value to the specified type. If the type must be extended,
+ /// it is sign extended. The conversion must not be narrowing.
+ const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
+
+ /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
+ /// the input value to the specified type. If the type must be extended,
+ /// it is extended with unspecified bits. The conversion must not be
+ /// narrowing.
+ const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
+
+ /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
+ /// input value to the specified type. The conversion must not be
+ /// widening.
+ const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
+
+ /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
+ /// the types using zero-extension, and then perform a umax operation
+ /// with them.
+ const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
+ const SCEV *RHS);
+
+ /// getUMinFromMismatchedTypes - Promote the operands to the wider of
+ /// the types using zero-extension, and then perform a umin operation
+ /// with them.
+ const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
+ const SCEV *RHS);
+
+ /// getPointerBase - Transitively follow the chain of pointer-type operands
+ /// until reaching a SCEV that does not have a single pointer operand. This
+ /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
+ /// but corner cases do exist.
+ const SCEV *getPointerBase(const SCEV *V);
+
+ /// getSCEVAtScope - Return a SCEV expression for the specified value
+ /// at the specified scope in the program. The L value specifies a loop
+ /// nest to evaluate the expression at, where null is the top-level or a
+ /// specified loop is immediately inside of the loop.
+ ///
+ /// This method can be used to compute the exit value for a variable defined
+ /// in a loop by querying what the value will hold in the parent loop.
+ ///
+ /// In the case that a relevant loop exit value cannot be computed, the
+ /// original value V is returned.
+ const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
+
+ /// getSCEVAtScope - This is a convenience function which does
+ /// getSCEVAtScope(getSCEV(V), L).
+ const SCEV *getSCEVAtScope(Value *V, const Loop *L);
+
+ /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
+ /// by a conditional between LHS and RHS. This is used to help avoid max
+ /// expressions in loop trip counts, and to eliminate casts.
+ bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
+ const SCEV *LHS, const SCEV *RHS);
+
+ /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
+ /// protected by a conditional between LHS and RHS. This is used to
+ /// to eliminate casts.
+ bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
+ const SCEV *LHS, const SCEV *RHS);
+
+ /// getSmallConstantTripCount - Returns the maximum trip count of this loop
+ /// as a normal unsigned value. Returns 0 if the trip count is unknown or
+ /// not constant. This "trip count" assumes that control exits via
+ /// ExitingBlock. More precisely, it is the number of times that control may
+ /// reach ExitingBlock before taking the branch. For loops with multiple
+ /// exits, it may not be the number times that the loop header executes if
+ /// the loop exits prematurely via another branch.
+ unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
+
+ /// getSmallConstantTripMultiple - Returns the largest constant divisor of
+ /// the trip count of this loop as a normal unsigned value, if
+ /// possible. This means that the actual trip count is always a multiple of
+ /// the returned value (don't forget the trip count could very well be zero
+ /// as well!). As explained in the comments for getSmallConstantTripCount,
+ /// this assumes that control exits the loop via ExitingBlock.
+ unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
+
+ // getExitCount - Get the expression for the number of loop iterations for
+ // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
+ // return SCEVCouldNotCompute.
+ const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
+
+ /// getBackedgeTakenCount - If the specified loop has a predictable
+ /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
+ /// object. The backedge-taken count is the number of times the loop header
+ /// will be branched to from within the loop. This is one less than the
+ /// trip count of the loop, since it doesn't count the first iteration,
+ /// when the header is branched to from outside the loop.
+ ///
+ /// Note that it is not valid to call this method on a loop without a
+ /// loop-invariant backedge-taken count (see
+ /// hasLoopInvariantBackedgeTakenCount).
+ ///
+ const SCEV *getBackedgeTakenCount(const Loop *L);
+
+ /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
+ /// return the least SCEV value that is known never to be less than the
+ /// actual backedge taken count.
+ const SCEV *getMaxBackedgeTakenCount(const Loop *L);
+
+ /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
+ /// has an analyzable loop-invariant backedge-taken count.
+ bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
+
+ /// forgetLoop - This method should be called by the client when it has
+ /// changed a loop in a way that may effect ScalarEvolution's ability to
+ /// compute a trip count, or if the loop is deleted.
+ void forgetLoop(const Loop *L);
+
+ /// forgetValue - This method should be called by the client when it has
+ /// changed a value in a way that may effect its value, or which may
+ /// disconnect it from a def-use chain linking it to a loop.
+ void forgetValue(Value *V);
+
+ /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
+ /// is guaranteed to end in (at every loop iteration). It is, at the same
+ /// time, the minimum number of times S is divisible by 2. For example,
+ /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
+ /// bitwidth of S.
+ uint32_t GetMinTrailingZeros(const SCEV *S);
+
+ /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
+ ///
+ ConstantRange getUnsignedRange(const SCEV *S);
+
+ /// getSignedRange - Determine the signed range for a particular SCEV.
+ ///
+ ConstantRange getSignedRange(const SCEV *S);
+
+ /// isKnownNegative - Test if the given expression is known to be negative.
+ ///
+ bool isKnownNegative(const SCEV *S);
+
+ /// isKnownPositive - Test if the given expression is known to be positive.
+ ///
+ bool isKnownPositive(const SCEV *S);
+
+ /// isKnownNonNegative - Test if the given expression is known to be
+ /// non-negative.
+ ///
+ bool isKnownNonNegative(const SCEV *S);
+
+ /// isKnownNonPositive - Test if the given expression is known to be
+ /// non-positive.
+ ///
+ bool isKnownNonPositive(const SCEV *S);
+
+ /// isKnownNonZero - Test if the given expression is known to be
+ /// non-zero.
+ ///
+ bool isKnownNonZero(const SCEV *S);
+
+ /// isKnownPredicate - Test if the given expression is known to satisfy
+ /// the condition described by Pred, LHS, and RHS.
+ ///
+ bool isKnownPredicate(ICmpInst::Predicate Pred,
+ const SCEV *LHS, const SCEV *RHS);
+
+ /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
+ /// predicate Pred. Return true iff any changes were made. If the
+ /// operands are provably equal or inequal, LHS and RHS are set to
+ /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
+ ///
+ bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
+ const SCEV *&LHS,
+ const SCEV *&RHS,
+ unsigned Depth = 0);
+
+ /// getLoopDisposition - Return the "disposition" of the given SCEV with
+ /// respect to the given loop.
+ LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
+
+ /// isLoopInvariant - Return true if the value of the given SCEV is
+ /// unchanging in the specified loop.
+ bool isLoopInvariant(const SCEV *S, const Loop *L);
+
+ /// hasComputableLoopEvolution - Return true if the given SCEV changes value
+ /// in a known way in the specified loop. This property being true implies
+ /// that the value is variant in the loop AND that we can emit an expression
+ /// to compute the value of the expression at any particular loop iteration.
+ bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
+
+ /// getLoopDisposition - Return the "disposition" of the given SCEV with
+ /// respect to the given block.
+ BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
+
+ /// dominates - Return true if elements that makes up the given SCEV
+ /// dominate the specified basic block.
+ bool dominates(const SCEV *S, const BasicBlock *BB);
+
+ /// properlyDominates - Return true if elements that makes up the given SCEV
+ /// properly dominate the specified basic block.
+ bool properlyDominates(const SCEV *S, const BasicBlock *BB);
+
+ /// hasOperand - Test whether the given SCEV has Op as a direct or
+ /// indirect operand.
+ bool hasOperand(const SCEV *S, const SCEV *Op) const;
+
+ virtual bool runOnFunction(Function &F);
+ virtual void releaseMemory();
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+ virtual void print(raw_ostream &OS, const Module* = 0) const;
+
+ private:
+ FoldingSet<SCEV> UniqueSCEVs;
+ BumpPtrAllocator SCEVAllocator;
+
+ /// FirstUnknown - The head of a linked list of all SCEVUnknown
+ /// values that have been allocated. This is used by releaseMemory
+ /// to locate them all and call their destructors.
+ SCEVUnknown *FirstUnknown;
+ };
+}
+
+#endif
diff --git a/include/llvm/Analysis/ScalarEvolutionExpander.h b/include/llvm/Analysis/ScalarEvolutionExpander.h
new file mode 100644
index 00000000000..3f8f149cb42
--- /dev/null
+++ b/include/llvm/Analysis/ScalarEvolutionExpander.h
@@ -0,0 +1,269 @@
+//===---- llvm/Analysis/ScalarEvolutionExpander.h - SCEV Exprs --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the classes used to generate code from scalar expressions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_SCALAREVOLUTION_EXPANDER_H
+#define LLVM_ANALYSIS_SCALAREVOLUTION_EXPANDER_H
+
+#include "llvm/IRBuilder.h"
+#include "llvm/Analysis/ScalarEvolutionExpressions.h"
+#include "llvm/Analysis/ScalarEvolutionNormalization.h"
+#include "llvm/Support/TargetFolder.h"
+#include "llvm/Support/ValueHandle.h"
+#include <set>
+
+namespace llvm {
+ class TargetLowering;
+
+ /// Return true if the given expression is safe to expand in the sense that
+ /// all materialized values are safe to speculate.
+ bool isSafeToExpand(const SCEV *S);
+
+ /// SCEVExpander - This class uses information about analyze scalars to
+ /// rewrite expressions in canonical form.
+ ///
+ /// Clients should create an instance of this class when rewriting is needed,
+ /// and destroy it when finished to allow the release of the associated
+ /// memory.
+ class SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
+ ScalarEvolution &SE;
+
+ // New instructions receive a name to identifies them with the current pass.
+ const char* IVName;
+
+ std::map<std::pair<const SCEV *, Instruction *>, AssertingVH<Value> >
+ InsertedExpressions;
+ std::set<AssertingVH<Value> > InsertedValues;
+ std::set<AssertingVH<Value> > InsertedPostIncValues;
+
+ /// RelevantLoops - A memoization of the "relevant" loop for a given SCEV.
+ DenseMap<const SCEV *, const Loop *> RelevantLoops;
+
+ /// PostIncLoops - Addrecs referring to any of the given loops are expanded
+ /// in post-inc mode. For example, expanding {1,+,1}<L> in post-inc mode
+ /// returns the add instruction that adds one to the phi for {0,+,1}<L>,
+ /// as opposed to a new phi starting at 1. This is only supported in
+ /// non-canonical mode.
+ PostIncLoopSet PostIncLoops;
+
+ /// IVIncInsertPos - When this is non-null, addrecs expanded in the
+ /// loop it indicates should be inserted with increments at
+ /// IVIncInsertPos.
+ const Loop *IVIncInsertLoop;
+
+ /// IVIncInsertPos - When expanding addrecs in the IVIncInsertLoop loop,
+ /// insert the IV increment at this position.
+ Instruction *IVIncInsertPos;
+
+ /// Phis that complete an IV chain. Reuse
+ std::set<AssertingVH<PHINode> > ChainedPhis;
+
+ /// CanonicalMode - When true, expressions are expanded in "canonical"
+ /// form. In particular, addrecs are expanded as arithmetic based on
+ /// a canonical induction variable. When false, expression are expanded
+ /// in a more literal form.
+ bool CanonicalMode;
+
+ /// When invoked from LSR, the expander is in "strength reduction" mode. The
+ /// only difference is that phi's are only reused if they are already in
+ /// "expanded" form.
+ bool LSRMode;
+
+ typedef IRBuilder<true, TargetFolder> BuilderType;
+ BuilderType Builder;
+
+#ifndef NDEBUG
+ const char *DebugType;
+#endif
+
+ friend struct SCEVVisitor<SCEVExpander, Value*>;
+
+ public:
+ /// SCEVExpander - Construct a SCEVExpander in "canonical" mode.
+ explicit SCEVExpander(ScalarEvolution &se, const char *name)
+ : SE(se), IVName(name), IVIncInsertLoop(0), IVIncInsertPos(0),
+ CanonicalMode(true), LSRMode(false),
+ Builder(se.getContext(), TargetFolder(se.TD)) {
+#ifndef NDEBUG
+ DebugType = "";
+#endif
+ }
+
+#ifndef NDEBUG
+ void setDebugType(const char* s) { DebugType = s; }
+#endif
+
+ /// clear - Erase the contents of the InsertedExpressions map so that users
+ /// trying to expand the same expression into multiple BasicBlocks or
+ /// different places within the same BasicBlock can do so.
+ void clear() {
+ InsertedExpressions.clear();
+ InsertedValues.clear();
+ InsertedPostIncValues.clear();
+ ChainedPhis.clear();
+ }
+
+ /// getOrInsertCanonicalInductionVariable - This method returns the
+ /// canonical induction variable of the specified type for the specified
+ /// loop (inserting one if there is none). A canonical induction variable
+ /// starts at zero and steps by one on each iteration.
+ PHINode *getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty);
+
+ /// getIVIncOperand - Return the induction variable increment's IV operand.
+ Instruction *getIVIncOperand(Instruction *IncV, Instruction *InsertPos,
+ bool allowScale);
+
+ /// hoistIVInc - Utility for hoisting an IV increment.
+ bool hoistIVInc(Instruction *IncV, Instruction *InsertPos);
+
+ /// replaceCongruentIVs - replace congruent phis with their most canonical
+ /// representative. Return the number of phis eliminated.
+ unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT,
+ SmallVectorImpl<WeakVH> &DeadInsts,
+ const TargetLowering *TLI = NULL);
+
+ /// expandCodeFor - Insert code to directly compute the specified SCEV
+ /// expression into the program. The inserted code is inserted into the
+ /// specified block.
+ Value *expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I);
+
+ /// setIVIncInsertPos - Set the current IV increment loop and position.
+ void setIVIncInsertPos(const Loop *L, Instruction *Pos) {
+ assert(!CanonicalMode &&
+ "IV increment positions are not supported in CanonicalMode");
+ IVIncInsertLoop = L;
+ IVIncInsertPos = Pos;
+ }
+
+ /// setPostInc - Enable post-inc expansion for addrecs referring to the
+ /// given loops. Post-inc expansion is only supported in non-canonical
+ /// mode.
+ void setPostInc(const PostIncLoopSet &L) {
+ assert(!CanonicalMode &&
+ "Post-inc expansion is not supported in CanonicalMode");
+ PostIncLoops = L;
+ }
+
+ /// clearPostInc - Disable all post-inc expansion.
+ void clearPostInc() {
+ PostIncLoops.clear();
+
+ // When we change the post-inc loop set, cached expansions may no
+ // longer be valid.
+ InsertedPostIncValues.clear();
+ }
+
+ /// disableCanonicalMode - Disable the behavior of expanding expressions in
+ /// canonical form rather than in a more literal form. Non-canonical mode
+ /// is useful for late optimization passes.
+ void disableCanonicalMode() { CanonicalMode = false; }
+
+ void enableLSRMode() { LSRMode = true; }
+
+ /// clearInsertPoint - Clear the current insertion point. This is useful
+ /// if the instruction that had been serving as the insertion point may
+ /// have been deleted.
+ void clearInsertPoint() {
+ Builder.ClearInsertionPoint();
+ }
+
+ /// isInsertedInstruction - Return true if the specified instruction was
+ /// inserted by the code rewriter. If so, the client should not modify the
+ /// instruction.
+ bool isInsertedInstruction(Instruction *I) const {
+ return InsertedValues.count(I) || InsertedPostIncValues.count(I);
+ }
+
+ void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
+
+ private:
+ LLVMContext &getContext() const { return SE.getContext(); }
+
+ /// InsertBinop - Insert the specified binary operator, doing a small amount
+ /// of work to avoid inserting an obviously redundant operation.
+ Value *InsertBinop(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS);
+
+ /// ReuseOrCreateCast - Arange for there to be a cast of V to Ty at IP,
+ /// reusing an existing cast if a suitable one exists, moving an existing
+ /// cast if a suitable one exists but isn't in the right place, or
+ /// or creating a new one.
+ Value *ReuseOrCreateCast(Value *V, Type *Ty,
+ Instruction::CastOps Op,
+ BasicBlock::iterator IP);
+
+ /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
+ /// which must be possible with a noop cast, doing what we can to
+ /// share the casts.
+ Value *InsertNoopCastOfTo(Value *V, Type *Ty);
+
+ /// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
+ /// instead of using ptrtoint+arithmetic+inttoptr.
+ Value *expandAddToGEP(const SCEV *const *op_begin,
+ const SCEV *const *op_end,
+ PointerType *PTy, Type *Ty, Value *V);
+
+ Value *expand(const SCEV *S);
+
+ /// expandCodeFor - Insert code to directly compute the specified SCEV
+ /// expression into the program. The inserted code is inserted into the
+ /// SCEVExpander's current insertion point. If a type is specified, the
+ /// result will be expanded to have that type, with a cast if necessary.
+ Value *expandCodeFor(const SCEV *SH, Type *Ty = 0);
+
+ /// getRelevantLoop - Determine the most "relevant" loop for the given SCEV.
+ const Loop *getRelevantLoop(const SCEV *);
+
+ Value *visitConstant(const SCEVConstant *S) {
+ return S->getValue();
+ }
+
+ Value *visitTruncateExpr(const SCEVTruncateExpr *S);
+
+ Value *visitZeroExtendExpr(const SCEVZeroExtendExpr *S);
+
+ Value *visitSignExtendExpr(const SCEVSignExtendExpr *S);
+
+ Value *visitAddExpr(const SCEVAddExpr *S);
+
+ Value *visitMulExpr(const SCEVMulExpr *S);
+
+ Value *visitUDivExpr(const SCEVUDivExpr *S);
+
+ Value *visitAddRecExpr(const SCEVAddRecExpr *S);
+
+ Value *visitSMaxExpr(const SCEVSMaxExpr *S);
+
+ Value *visitUMaxExpr(const SCEVUMaxExpr *S);
+
+ Value *visitUnknown(const SCEVUnknown *S) {
+ return S->getValue();
+ }
+
+ void rememberInstruction(Value *I);
+
+ void restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I);
+
+ bool isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
+
+ bool isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
+
+ Value *expandAddRecExprLiterally(const SCEVAddRecExpr *);
+ PHINode *getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
+ const Loop *L,
+ Type *ExpandTy,
+ Type *IntTy);
+ Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
+ Type *ExpandTy, Type *IntTy, bool useSubtract);
+ };
+}
+
+#endif
diff --git a/include/llvm/Analysis/ScalarEvolutionExpressions.h b/include/llvm/Analysis/ScalarEvolutionExpressions.h
new file mode 100644
index 00000000000..ded12974fac
--- /dev/null
+++ b/include/llvm/Analysis/ScalarEvolutionExpressions.h
@@ -0,0 +1,567 @@
+//===- llvm/Analysis/ScalarEvolutionExpressions.h - SCEV Exprs --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the classes used to represent and build scalar expressions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_SCALAREVOLUTION_EXPRESSIONS_H
+#define LLVM_ANALYSIS_SCALAREVOLUTION_EXPRESSIONS_H
+
+#include "llvm/Analysis/ScalarEvolution.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/ErrorHandling.h"
+
+namespace llvm {
+ class ConstantInt;
+ class ConstantRange;
+ class DominatorTree;
+
+ enum SCEVTypes {
+ // These should be ordered in terms of increasing complexity to make the
+ // folders simpler.
+ scConstant, scTruncate, scZeroExtend, scSignExtend, scAddExpr, scMulExpr,
+ scUDivExpr, scAddRecExpr, scUMaxExpr, scSMaxExpr,
+ scUnknown, scCouldNotCompute
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVConstant - This class represents a constant integer value.
+ ///
+ class SCEVConstant : public SCEV {
+ friend class ScalarEvolution;
+
+ ConstantInt *V;
+ SCEVConstant(const FoldingSetNodeIDRef ID, ConstantInt *v) :
+ SCEV(ID, scConstant), V(v) {}
+ public:
+ ConstantInt *getValue() const { return V; }
+
+ Type *getType() const { return V->getType(); }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVConstant *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scConstant;
+ }
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVCastExpr - This is the base class for unary cast operator classes.
+ ///
+ class SCEVCastExpr : public SCEV {
+ protected:
+ const SCEV *Op;
+ Type *Ty;
+
+ SCEVCastExpr(const FoldingSetNodeIDRef ID,
+ unsigned SCEVTy, const SCEV *op, Type *ty);
+
+ public:
+ const SCEV *getOperand() const { return Op; }
+ Type *getType() const { return Ty; }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVCastExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scTruncate ||
+ S->getSCEVType() == scZeroExtend ||
+ S->getSCEVType() == scSignExtend;
+ }
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVTruncateExpr - This class represents a truncation of an integer value
+ /// to a smaller integer value.
+ ///
+ class SCEVTruncateExpr : public SCEVCastExpr {
+ friend class ScalarEvolution;
+
+ SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
+ const SCEV *op, Type *ty);
+
+ public:
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVTruncateExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scTruncate;
+ }
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVZeroExtendExpr - This class represents a zero extension of a small
+ /// integer value to a larger integer value.
+ ///
+ class SCEVZeroExtendExpr : public SCEVCastExpr {
+ friend class ScalarEvolution;
+
+ SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
+ const SCEV *op, Type *ty);
+
+ public:
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVZeroExtendExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scZeroExtend;
+ }
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVSignExtendExpr - This class represents a sign extension of a small
+ /// integer value to a larger integer value.
+ ///
+ class SCEVSignExtendExpr : public SCEVCastExpr {
+ friend class ScalarEvolution;
+
+ SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
+ const SCEV *op, Type *ty);
+
+ public:
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVSignExtendExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scSignExtend;
+ }
+ };
+
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVNAryExpr - This node is a base class providing common
+ /// functionality for n'ary operators.
+ ///
+ class SCEVNAryExpr : public SCEV {
+ protected:
+ // Since SCEVs are immutable, ScalarEvolution allocates operand
+ // arrays with its SCEVAllocator, so this class just needs a simple
+ // pointer rather than a more elaborate vector-like data structure.
+ // This also avoids the need for a non-trivial destructor.
+ const SCEV *const *Operands;
+ size_t NumOperands;
+
+ SCEVNAryExpr(const FoldingSetNodeIDRef ID,
+ enum SCEVTypes T, const SCEV *const *O, size_t N)
+ : SCEV(ID, T), Operands(O), NumOperands(N) {}
+
+ public:
+ size_t getNumOperands() const { return NumOperands; }
+ const SCEV *getOperand(unsigned i) const {
+ assert(i < NumOperands && "Operand index out of range!");
+ return Operands[i];
+ }
+
+ typedef const SCEV *const *op_iterator;
+ op_iterator op_begin() const { return Operands; }
+ op_iterator op_end() const { return Operands + NumOperands; }
+
+ Type *getType() const { return getOperand(0)->getType(); }
+
+ NoWrapFlags getNoWrapFlags(NoWrapFlags Mask = NoWrapMask) const {
+ return (NoWrapFlags)(SubclassData & Mask);
+ }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVNAryExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scAddExpr ||
+ S->getSCEVType() == scMulExpr ||
+ S->getSCEVType() == scSMaxExpr ||
+ S->getSCEVType() == scUMaxExpr ||
+ S->getSCEVType() == scAddRecExpr;
+ }
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVCommutativeExpr - This node is the base class for n'ary commutative
+ /// operators.
+ ///
+ class SCEVCommutativeExpr : public SCEVNAryExpr {
+ protected:
+ SCEVCommutativeExpr(const FoldingSetNodeIDRef ID,
+ enum SCEVTypes T, const SCEV *const *O, size_t N)
+ : SCEVNAryExpr(ID, T, O, N) {}
+
+ public:
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVCommutativeExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scAddExpr ||
+ S->getSCEVType() == scMulExpr ||
+ S->getSCEVType() == scSMaxExpr ||
+ S->getSCEVType() == scUMaxExpr;
+ }
+
+ /// Set flags for a non-recurrence without clearing previously set flags.
+ void setNoWrapFlags(NoWrapFlags Flags) {
+ SubclassData |= Flags;
+ }
+ };
+
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVAddExpr - This node represents an addition of some number of SCEVs.
+ ///
+ class SCEVAddExpr : public SCEVCommutativeExpr {
+ friend class ScalarEvolution;
+
+ SCEVAddExpr(const FoldingSetNodeIDRef ID,
+ const SCEV *const *O, size_t N)
+ : SCEVCommutativeExpr(ID, scAddExpr, O, N) {
+ }
+
+ public:
+ Type *getType() const {
+ // Use the type of the last operand, which is likely to be a pointer
+ // type, if there is one. This doesn't usually matter, but it can help
+ // reduce casts when the expressions are expanded.
+ return getOperand(getNumOperands() - 1)->getType();
+ }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVAddExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scAddExpr;
+ }
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVMulExpr - This node represents multiplication of some number of SCEVs.
+ ///
+ class SCEVMulExpr : public SCEVCommutativeExpr {
+ friend class ScalarEvolution;
+
+ SCEVMulExpr(const FoldingSetNodeIDRef ID,
+ const SCEV *const *O, size_t N)
+ : SCEVCommutativeExpr(ID, scMulExpr, O, N) {
+ }
+
+ public:
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVMulExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scMulExpr;
+ }
+ };
+
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVUDivExpr - This class represents a binary unsigned division operation.
+ ///
+ class SCEVUDivExpr : public SCEV {
+ friend class ScalarEvolution;
+
+ const SCEV *LHS;
+ const SCEV *RHS;
+ SCEVUDivExpr(const FoldingSetNodeIDRef ID, const SCEV *lhs, const SCEV *rhs)
+ : SCEV(ID, scUDivExpr), LHS(lhs), RHS(rhs) {}
+
+ public:
+ const SCEV *getLHS() const { return LHS; }
+ const SCEV *getRHS() const { return RHS; }
+
+ Type *getType() const {
+ // In most cases the types of LHS and RHS will be the same, but in some
+ // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
+ // depend on the type for correctness, but handling types carefully can
+ // avoid extra casts in the SCEVExpander. The LHS is more likely to be
+ // a pointer type than the RHS, so use the RHS' type here.
+ return getRHS()->getType();
+ }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVUDivExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scUDivExpr;
+ }
+ };
+
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVAddRecExpr - This node represents a polynomial recurrence on the trip
+ /// count of the specified loop. This is the primary focus of the
+ /// ScalarEvolution framework; all the other SCEV subclasses are mostly just
+ /// supporting infrastructure to allow SCEVAddRecExpr expressions to be
+ /// created and analyzed.
+ ///
+ /// All operands of an AddRec are required to be loop invariant.
+ ///
+ class SCEVAddRecExpr : public SCEVNAryExpr {
+ friend class ScalarEvolution;
+
+ const Loop *L;
+
+ SCEVAddRecExpr(const FoldingSetNodeIDRef ID,
+ const SCEV *const *O, size_t N, const Loop *l)
+ : SCEVNAryExpr(ID, scAddRecExpr, O, N), L(l) {}
+
+ public:
+ const SCEV *getStart() const { return Operands[0]; }
+ const Loop *getLoop() const { return L; }
+
+ /// getStepRecurrence - This method constructs and returns the recurrence
+ /// indicating how much this expression steps by. If this is a polynomial
+ /// of degree N, it returns a chrec of degree N-1.
+ /// We cannot determine whether the step recurrence has self-wraparound.
+ const SCEV *getStepRecurrence(ScalarEvolution &SE) const {
+ if (isAffine()) return getOperand(1);
+ return SE.getAddRecExpr(SmallVector<const SCEV *, 3>(op_begin()+1,
+ op_end()),
+ getLoop(), FlagAnyWrap);
+ }
+
+ /// isAffine - Return true if this is an affine AddRec (i.e., it represents
+ /// an expressions A+B*x where A and B are loop invariant values.
+ bool isAffine() const {
+ // We know that the start value is invariant. This expression is thus
+ // affine iff the step is also invariant.
+ return getNumOperands() == 2;
+ }
+
+ /// isQuadratic - Return true if this is an quadratic AddRec (i.e., it
+ /// represents an expressions A+B*x+C*x^2 where A, B and C are loop
+ /// invariant values. This corresponds to an addrec of the form {L,+,M,+,N}
+ bool isQuadratic() const {
+ return getNumOperands() == 3;
+ }
+
+ /// Set flags for a recurrence without clearing any previously set flags.
+ /// For AddRec, either NUW or NSW implies NW. Keep track of this fact here
+ /// to make it easier to propagate flags.
+ void setNoWrapFlags(NoWrapFlags Flags) {
+ if (Flags & (FlagNUW | FlagNSW))
+ Flags = ScalarEvolution::setFlags(Flags, FlagNW);
+ SubclassData |= Flags;
+ }
+
+ /// evaluateAtIteration - Return the value of this chain of recurrences at
+ /// the specified iteration number.
+ const SCEV *evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const;
+
+ /// getNumIterationsInRange - Return the number of iterations of this loop
+ /// that produce values in the specified constant range. Another way of
+ /// looking at this is that it returns the first iteration number where the
+ /// value is not in the condition, thus computing the exit count. If the
+ /// iteration count can't be computed, an instance of SCEVCouldNotCompute is
+ /// returned.
+ const SCEV *getNumIterationsInRange(ConstantRange Range,
+ ScalarEvolution &SE) const;
+
+ /// getPostIncExpr - Return an expression representing the value of
+ /// this expression one iteration of the loop ahead.
+ const SCEVAddRecExpr *getPostIncExpr(ScalarEvolution &SE) const {
+ return cast<SCEVAddRecExpr>(SE.getAddExpr(this, getStepRecurrence(SE)));
+ }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVAddRecExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scAddRecExpr;
+ }
+ };
+
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVSMaxExpr - This class represents a signed maximum selection.
+ ///
+ class SCEVSMaxExpr : public SCEVCommutativeExpr {
+ friend class ScalarEvolution;
+
+ SCEVSMaxExpr(const FoldingSetNodeIDRef ID,
+ const SCEV *const *O, size_t N)
+ : SCEVCommutativeExpr(ID, scSMaxExpr, O, N) {
+ // Max never overflows.
+ setNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW));
+ }
+
+ public:
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVSMaxExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scSMaxExpr;
+ }
+ };
+
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVUMaxExpr - This class represents an unsigned maximum selection.
+ ///
+ class SCEVUMaxExpr : public SCEVCommutativeExpr {
+ friend class ScalarEvolution;
+
+ SCEVUMaxExpr(const FoldingSetNodeIDRef ID,
+ const SCEV *const *O, size_t N)
+ : SCEVCommutativeExpr(ID, scUMaxExpr, O, N) {
+ // Max never overflows.
+ setNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW));
+ }
+
+ public:
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVUMaxExpr *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scUMaxExpr;
+ }
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SCEVUnknown - This means that we are dealing with an entirely unknown SCEV
+ /// value, and only represent it as its LLVM Value. This is the "bottom"
+ /// value for the analysis.
+ ///
+ class SCEVUnknown : public SCEV, private CallbackVH {
+ friend class ScalarEvolution;
+
+ // Implement CallbackVH.
+ virtual void deleted();
+ virtual void allUsesReplacedWith(Value *New);
+
+ /// SE - The parent ScalarEvolution value. This is used to update
+ /// the parent's maps when the value associated with a SCEVUnknown
+ /// is deleted or RAUW'd.
+ ScalarEvolution *SE;
+
+ /// Next - The next pointer in the linked list of all
+ /// SCEVUnknown instances owned by a ScalarEvolution.
+ SCEVUnknown *Next;
+
+ SCEVUnknown(const FoldingSetNodeIDRef ID, Value *V,
+ ScalarEvolution *se, SCEVUnknown *next) :
+ SCEV(ID, scUnknown), CallbackVH(V), SE(se), Next(next) {}
+
+ public:
+ Value *getValue() const { return getValPtr(); }
+
+ /// isSizeOf, isAlignOf, isOffsetOf - Test whether this is a special
+ /// constant representing a type size, alignment, or field offset in
+ /// a target-independent manner, and hasn't happened to have been
+ /// folded with other operations into something unrecognizable. This
+ /// is mainly only useful for pretty-printing and other situations
+ /// where it isn't absolutely required for these to succeed.
+ bool isSizeOf(Type *&AllocTy) const;
+ bool isAlignOf(Type *&AllocTy) const;
+ bool isOffsetOf(Type *&STy, Constant *&FieldNo) const;
+
+ Type *getType() const { return getValPtr()->getType(); }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SCEVUnknown *S) { return true; }
+ static inline bool classof(const SCEV *S) {
+ return S->getSCEVType() == scUnknown;
+ }
+ };
+
+ /// SCEVVisitor - This class defines a simple visitor class that may be used
+ /// for various SCEV analysis purposes.
+ template<typename SC, typename RetVal=void>
+ struct SCEVVisitor {
+ RetVal visit(const SCEV *S) {
+ switch (S->getSCEVType()) {
+ case scConstant:
+ return ((SC*)this)->visitConstant((const SCEVConstant*)S);
+ case scTruncate:
+ return ((SC*)this)->visitTruncateExpr((const SCEVTruncateExpr*)S);
+ case scZeroExtend:
+ return ((SC*)this)->visitZeroExtendExpr((const SCEVZeroExtendExpr*)S);
+ case scSignExtend:
+ return ((SC*)this)->visitSignExtendExpr((const SCEVSignExtendExpr*)S);
+ case scAddExpr:
+ return ((SC*)this)->visitAddExpr((const SCEVAddExpr*)S);
+ case scMulExpr:
+ return ((SC*)this)->visitMulExpr((const SCEVMulExpr*)S);
+ case scUDivExpr:
+ return ((SC*)this)->visitUDivExpr((const SCEVUDivExpr*)S);
+ case scAddRecExpr:
+ return ((SC*)this)->visitAddRecExpr((const SCEVAddRecExpr*)S);
+ case scSMaxExpr:
+ return ((SC*)this)->visitSMaxExpr((const SCEVSMaxExpr*)S);
+ case scUMaxExpr:
+ return ((SC*)this)->visitUMaxExpr((const SCEVUMaxExpr*)S);
+ case scUnknown:
+ return ((SC*)this)->visitUnknown((const SCEVUnknown*)S);
+ case scCouldNotCompute:
+ return ((SC*)this)->visitCouldNotCompute((const SCEVCouldNotCompute*)S);
+ default:
+ llvm_unreachable("Unknown SCEV type!");
+ }
+ }
+
+ RetVal visitCouldNotCompute(const SCEVCouldNotCompute *S) {
+ llvm_unreachable("Invalid use of SCEVCouldNotCompute!");
+ }
+ };
+
+ /// Visit all nodes in the expression tree using worklist traversal.
+ ///
+ /// Visitor implements:
+ /// // return true to follow this node.
+ /// bool follow(const SCEV *S);
+ /// // return true to terminate the search.
+ /// bool isDone();
+ template<typename SV>
+ class SCEVTraversal {
+ SV &Visitor;
+ SmallVector<const SCEV *, 8> Worklist;
+ SmallPtrSet<const SCEV *, 8> Visited;
+
+ void push(const SCEV *S) {
+ if (Visited.insert(S) && Visitor.follow(S))
+ Worklist.push_back(S);
+ }
+ public:
+ SCEVTraversal(SV& V): Visitor(V) {}
+
+ void visitAll(const SCEV *Root) {
+ push(Root);
+ while (!Worklist.empty() && !Visitor.isDone()) {
+ const SCEV *S = Worklist.pop_back_val();
+
+ switch (S->getSCEVType()) {
+ case scConstant:
+ case scUnknown:
+ break;
+ case scTruncate:
+ case scZeroExtend:
+ case scSignExtend:
+ push(cast<SCEVCastExpr>(S)->getOperand());
+ break;
+ case scAddExpr:
+ case scMulExpr:
+ case scSMaxExpr:
+ case scUMaxExpr:
+ case scAddRecExpr: {
+ const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
+ for (SCEVNAryExpr::op_iterator I = NAry->op_begin(),
+ E = NAry->op_end(); I != E; ++I) {
+ push(*I);
+ }
+ break;
+ }
+ case scUDivExpr: {
+ const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
+ push(UDiv->getLHS());
+ push(UDiv->getRHS());
+ break;
+ }
+ case scCouldNotCompute:
+ llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
+ default:
+ llvm_unreachable("Unknown SCEV kind!");
+ }
+ }
+ }
+ };
+
+ /// Use SCEVTraversal to visit all nodes in the givien expression tree.
+ template<typename SV>
+ void visitAll(const SCEV *Root, SV& Visitor) {
+ SCEVTraversal<SV> T(Visitor);
+ T.visitAll(Root);
+ }
+}
+
+#endif
diff --git a/include/llvm/Analysis/ScalarEvolutionNormalization.h b/include/llvm/Analysis/ScalarEvolutionNormalization.h
new file mode 100644
index 00000000000..342e5937891
--- /dev/null
+++ b/include/llvm/Analysis/ScalarEvolutionNormalization.h
@@ -0,0 +1,78 @@
+//===- llvm/Analysis/ScalarEvolutionNormalization.h - See below -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines utilities for working with "normalized" ScalarEvolution
+// expressions.
+//
+// The following example illustrates post-increment uses and how normalized
+// expressions help.
+//
+// for (i=0; i!=n; ++i) {
+// ...
+// }
+// use(i);
+//
+// While the expression for most uses of i inside the loop is {0,+,1}<%L>, the
+// expression for the use of i outside the loop is {1,+,1}<%L>, since i is
+// incremented at the end of the loop body. This is inconveient, since it
+// suggests that we need two different induction variables, one that starts
+// at 0 and one that starts at 1. We'd prefer to be able to think of these as
+// the same induction variable, with uses inside the loop using the
+// "pre-incremented" value, and uses after the loop using the
+// "post-incremented" value.
+//
+// Expressions for post-incremented uses are represented as an expression
+// paired with a set of loops for which the expression is in "post-increment"
+// mode (there may be multiple loops).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_SCALAREVOLUTION_NORMALIZATION_H
+#define LLVM_ANALYSIS_SCALAREVOLUTION_NORMALIZATION_H
+
+#include "llvm/ADT/SmallPtrSet.h"
+
+namespace llvm {
+
+class Instruction;
+class DominatorTree;
+class Loop;
+class ScalarEvolution;
+class SCEV;
+class Value;
+
+/// TransformKind - Different types of transformations that
+/// TransformForPostIncUse can do.
+enum TransformKind {
+ /// Normalize - Normalize according to the given loops.
+ Normalize,
+ /// NormalizeAutodetect - Detect post-inc opportunities on new expressions,
+ /// update the given loop set, and normalize.
+ NormalizeAutodetect,
+ /// Denormalize - Perform the inverse transform on the expression with the
+ /// given loop set.
+ Denormalize
+};
+
+/// PostIncLoopSet - A set of loops.
+typedef SmallPtrSet<const Loop *, 2> PostIncLoopSet;
+
+/// TransformForPostIncUse - Transform the given expression according to the
+/// given transformation kind.
+const SCEV *TransformForPostIncUse(TransformKind Kind,
+ const SCEV *S,
+ Instruction *User,
+ Value *OperandValToReplace,
+ PostIncLoopSet &Loops,
+ ScalarEvolution &SE,
+ DominatorTree &DT);
+
+}
+
+#endif
diff --git a/include/llvm/Analysis/SparsePropagation.h b/include/llvm/Analysis/SparsePropagation.h
new file mode 100644
index 00000000000..b758eca42e7
--- /dev/null
+++ b/include/llvm/Analysis/SparsePropagation.h
@@ -0,0 +1,206 @@
+//===- SparsePropagation.h - Sparse Conditional Property Propagation ------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements an abstract sparse conditional propagation algorithm,
+// modeled after SCCP, but with a customizable lattice function.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_SPARSE_PROPAGATION_H
+#define LLVM_ANALYSIS_SPARSE_PROPAGATION_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include <vector>
+#include <set>
+
+namespace llvm {
+ class Value;
+ class Constant;
+ class Argument;
+ class Instruction;
+ class PHINode;
+ class TerminatorInst;
+ class BasicBlock;
+ class Function;
+ class SparseSolver;
+ class raw_ostream;
+
+ template<typename T> class SmallVectorImpl;
+
+/// AbstractLatticeFunction - This class is implemented by the dataflow instance
+/// to specify what the lattice values are and how they handle merges etc.
+/// This gives the client the power to compute lattice values from instructions,
+/// constants, etc. The requirement is that lattice values must all fit into
+/// a void*. If a void* is not sufficient, the implementation should use this
+/// pointer to be a pointer into a uniquing set or something.
+///
+class AbstractLatticeFunction {
+public:
+ typedef void *LatticeVal;
+private:
+ LatticeVal UndefVal, OverdefinedVal, UntrackedVal;
+public:
+ AbstractLatticeFunction(LatticeVal undefVal, LatticeVal overdefinedVal,
+ LatticeVal untrackedVal) {
+ UndefVal = undefVal;
+ OverdefinedVal = overdefinedVal;
+ UntrackedVal = untrackedVal;
+ }
+ virtual ~AbstractLatticeFunction();
+
+ LatticeVal getUndefVal() const { return UndefVal; }
+ LatticeVal getOverdefinedVal() const { return OverdefinedVal; }
+ LatticeVal getUntrackedVal() const { return UntrackedVal; }
+
+ /// IsUntrackedValue - If the specified Value is something that is obviously
+ /// uninteresting to the analysis (and would always return UntrackedVal),
+ /// this function can return true to avoid pointless work.
+ virtual bool IsUntrackedValue(Value *V) {
+ return false;
+ }
+
+ /// ComputeConstant - Given a constant value, compute and return a lattice
+ /// value corresponding to the specified constant.
+ virtual LatticeVal ComputeConstant(Constant *C) {
+ return getOverdefinedVal(); // always safe
+ }
+
+ /// IsSpecialCasedPHI - Given a PHI node, determine whether this PHI node is
+ /// one that the we want to handle through ComputeInstructionState.
+ virtual bool IsSpecialCasedPHI(PHINode *PN) {
+ return false;
+ }
+
+ /// GetConstant - If the specified lattice value is representable as an LLVM
+ /// constant value, return it. Otherwise return null. The returned value
+ /// must be in the same LLVM type as Val.
+ virtual Constant *GetConstant(LatticeVal LV, Value *Val, SparseSolver &SS) {
+ return 0;
+ }
+
+ /// ComputeArgument - Given a formal argument value, compute and return a
+ /// lattice value corresponding to the specified argument.
+ virtual LatticeVal ComputeArgument(Argument *I) {
+ return getOverdefinedVal(); // always safe
+ }
+
+ /// MergeValues - Compute and return the merge of the two specified lattice
+ /// values. Merging should only move one direction down the lattice to
+ /// guarantee convergence (toward overdefined).
+ virtual LatticeVal MergeValues(LatticeVal X, LatticeVal Y) {
+ return getOverdefinedVal(); // always safe, never useful.
+ }
+
+ /// ComputeInstructionState - Given an instruction and a vector of its operand
+ /// values, compute the result value of the instruction.
+ virtual LatticeVal ComputeInstructionState(Instruction &I, SparseSolver &SS) {
+ return getOverdefinedVal(); // always safe, never useful.
+ }
+
+ /// PrintValue - Render the specified lattice value to the specified stream.
+ virtual void PrintValue(LatticeVal V, raw_ostream &OS);
+};
+
+
+/// SparseSolver - This class is a general purpose solver for Sparse Conditional
+/// Propagation with a programmable lattice function.
+///
+class SparseSolver {
+ typedef AbstractLatticeFunction::LatticeVal LatticeVal;
+
+ /// LatticeFunc - This is the object that knows the lattice and how to do
+ /// compute transfer functions.
+ AbstractLatticeFunction *LatticeFunc;
+
+ DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
+ SmallPtrSet<BasicBlock*, 16> BBExecutable; // The bbs that are executable.
+
+ std::vector<Instruction*> InstWorkList; // Worklist of insts to process.
+
+ std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
+
+ /// KnownFeasibleEdges - Entries in this set are edges which have already had
+ /// PHI nodes retriggered.
+ typedef std::pair<BasicBlock*,BasicBlock*> Edge;
+ std::set<Edge> KnownFeasibleEdges;
+
+ SparseSolver(const SparseSolver&) LLVM_DELETED_FUNCTION;
+ void operator=(const SparseSolver&) LLVM_DELETED_FUNCTION;
+public:
+ explicit SparseSolver(AbstractLatticeFunction *Lattice)
+ : LatticeFunc(Lattice) {}
+ ~SparseSolver() {
+ delete LatticeFunc;
+ }
+
+ /// Solve - Solve for constants and executable blocks.
+ ///
+ void Solve(Function &F);
+
+ void Print(Function &F, raw_ostream &OS) const;
+
+ /// getLatticeState - Return the LatticeVal object that corresponds to the
+ /// value. If an value is not in the map, it is returned as untracked,
+ /// unlike the getOrInitValueState method.
+ LatticeVal getLatticeState(Value *V) const {
+ DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
+ return I != ValueState.end() ? I->second : LatticeFunc->getUntrackedVal();
+ }
+
+ /// getOrInitValueState - Return the LatticeVal object that corresponds to the
+ /// value, initializing the value's state if it hasn't been entered into the
+ /// map yet. This function is necessary because not all values should start
+ /// out in the underdefined state... Arguments should be overdefined, and
+ /// constants should be marked as constants.
+ ///
+ LatticeVal getOrInitValueState(Value *V);
+
+ /// isEdgeFeasible - Return true if the control flow edge from the 'From'
+ /// basic block to the 'To' basic block is currently feasible. If
+ /// AggressiveUndef is true, then this treats values with unknown lattice
+ /// values as undefined. This is generally only useful when solving the
+ /// lattice, not when querying it.
+ bool isEdgeFeasible(BasicBlock *From, BasicBlock *To,
+ bool AggressiveUndef = false);
+
+ /// isBlockExecutable - Return true if there are any known feasible
+ /// edges into the basic block. This is generally only useful when
+ /// querying the lattice.
+ bool isBlockExecutable(BasicBlock *BB) const {
+ return BBExecutable.count(BB);
+ }
+
+private:
+ /// UpdateState - When the state for some instruction is potentially updated,
+ /// this function notices and adds I to the worklist if needed.
+ void UpdateState(Instruction &Inst, LatticeVal V);
+
+ /// MarkBlockExecutable - This method can be used by clients to mark all of
+ /// the blocks that are known to be intrinsically live in the processed unit.
+ void MarkBlockExecutable(BasicBlock *BB);
+
+ /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
+ /// work list if it is not already executable.
+ void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
+
+ /// getFeasibleSuccessors - Return a vector of booleans to indicate which
+ /// successors are reachable from a given terminator instruction.
+ void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs,
+ bool AggressiveUndef);
+
+ void visitInst(Instruction &I);
+ void visitPHINode(PHINode &I);
+ void visitTerminatorInst(TerminatorInst &TI);
+
+};
+
+} // end namespace llvm
+
+#endif // LLVM_ANALYSIS_SPARSE_PROPAGATION_H
diff --git a/include/llvm/Analysis/Trace.h b/include/llvm/Analysis/Trace.h
new file mode 100644
index 00000000000..99651e192d3
--- /dev/null
+++ b/include/llvm/Analysis/Trace.h
@@ -0,0 +1,119 @@
+//===- llvm/Analysis/Trace.h - Represent one trace of LLVM code -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This class represents a single trace of LLVM basic blocks. A trace is a
+// single entry, multiple exit, region of code that is often hot. Trace-based
+// optimizations treat traces almost like they are a large, strange, basic
+// block: because the trace path is assumed to be hot, optimizations for the
+// fall-through path are made at the expense of the non-fall-through paths.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_TRACE_H
+#define LLVM_ANALYSIS_TRACE_H
+
+#include <vector>
+#include <cassert>
+
+namespace llvm {
+ class BasicBlock;
+ class Function;
+ class Module;
+ class raw_ostream;
+
+class Trace {
+ typedef std::vector<BasicBlock *> BasicBlockListType;
+ BasicBlockListType BasicBlocks;
+
+public:
+ /// Trace ctor - Make a new trace from a vector of basic blocks,
+ /// residing in the function which is the parent of the first
+ /// basic block in the vector.
+ ///
+ Trace(const std::vector<BasicBlock *> &vBB) : BasicBlocks (vBB) {}
+
+ /// getEntryBasicBlock - Return the entry basic block (first block)
+ /// of the trace.
+ ///
+ BasicBlock *getEntryBasicBlock () const { return BasicBlocks[0]; }
+
+ /// operator[]/getBlock - Return basic block N in the trace.
+ ///
+ BasicBlock *operator[](unsigned i) const { return BasicBlocks[i]; }
+ BasicBlock *getBlock(unsigned i) const { return BasicBlocks[i]; }
+
+ /// getFunction - Return this trace's parent function.
+ ///
+ Function *getFunction () const;
+
+ /// getModule - Return this Module that contains this trace's parent
+ /// function.
+ ///
+ Module *getModule () const;
+
+ /// getBlockIndex - Return the index of the specified basic block in the
+ /// trace, or -1 if it is not in the trace.
+ int getBlockIndex(const BasicBlock *X) const {
+ for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
+ if (BasicBlocks[i] == X)
+ return i;
+ return -1;
+ }
+
+ /// contains - Returns true if this trace contains the given basic
+ /// block.
+ ///
+ bool contains(const BasicBlock *X) const {
+ return getBlockIndex(X) != -1;
+ }
+
+ /// Returns true if B1 occurs before B2 in the trace, or if it is the same
+ /// block as B2.. Both blocks must be in the trace.
+ ///
+ bool dominates(const BasicBlock *B1, const BasicBlock *B2) const {
+ int B1Idx = getBlockIndex(B1), B2Idx = getBlockIndex(B2);
+ assert(B1Idx != -1 && B2Idx != -1 && "Block is not in the trace!");
+ return B1Idx <= B2Idx;
+ }
+
+ // BasicBlock iterators...
+ typedef BasicBlockListType::iterator iterator;
+ typedef BasicBlockListType::const_iterator const_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+
+ iterator begin() { return BasicBlocks.begin(); }
+ const_iterator begin() const { return BasicBlocks.begin(); }
+ iterator end () { return BasicBlocks.end(); }
+ const_iterator end () const { return BasicBlocks.end(); }
+
+ reverse_iterator rbegin() { return BasicBlocks.rbegin(); }
+ const_reverse_iterator rbegin() const { return BasicBlocks.rbegin(); }
+ reverse_iterator rend () { return BasicBlocks.rend(); }
+ const_reverse_iterator rend () const { return BasicBlocks.rend(); }
+
+ unsigned size() const { return BasicBlocks.size(); }
+ bool empty() const { return BasicBlocks.empty(); }
+
+ iterator erase(iterator q) { return BasicBlocks.erase (q); }
+ iterator erase(iterator q1, iterator q2) { return BasicBlocks.erase (q1, q2); }
+
+ /// print - Write trace to output stream.
+ ///
+ void print(raw_ostream &O) const;
+
+ /// dump - Debugger convenience method; writes trace to standard error
+ /// output stream.
+ ///
+ void dump() const;
+};
+
+} // end namespace llvm
+
+#endif // TRACE_H
diff --git a/include/llvm/Analysis/ValueTracking.h b/include/llvm/Analysis/ValueTracking.h
new file mode 100644
index 00000000000..e8d45f6bb8d
--- /dev/null
+++ b/include/llvm/Analysis/ValueTracking.h
@@ -0,0 +1,189 @@
+//===- llvm/Analysis/ValueTracking.h - Walk computations --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains routines that help analyze properties that chains of
+// computations have.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_VALUETRACKING_H
+#define LLVM_ANALYSIS_VALUETRACKING_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+ class Value;
+ class Instruction;
+ class APInt;
+ class TargetData;
+ class StringRef;
+ class MDNode;
+
+ /// ComputeMaskedBits - Determine which of the bits specified in Mask are
+ /// known to be either zero or one and return them in the KnownZero/KnownOne
+ /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
+ /// processing.
+ ///
+ /// This function is defined on values with integer type, values with pointer
+ /// type (but only if TD is non-null), and vectors of integers. In the case
+ /// where V is a vector, the mask, known zero, and known one values are the
+ /// same width as the vector element, and the bit is set only if it is true
+ /// for all of the elements in the vector.
+ void ComputeMaskedBits(Value *V, APInt &KnownZero, APInt &KnownOne,
+ const TargetData *TD = 0, unsigned Depth = 0);
+ void computeMaskedBitsLoad(const MDNode &Ranges, APInt &KnownZero);
+
+ /// ComputeSignBit - Determine whether the sign bit is known to be zero or
+ /// one. Convenience wrapper around ComputeMaskedBits.
+ void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
+ const TargetData *TD = 0, unsigned Depth = 0);
+
+ /// isPowerOfTwo - Return true if the given value is known to have exactly one
+ /// bit set when defined. For vectors return true if every element is known to
+ /// be a power of two when defined. Supports values with integer or pointer
+ /// type and vectors of integers. If 'OrZero' is set then returns true if the
+ /// given value is either a power of two or zero.
+ bool isPowerOfTwo(Value *V, const TargetData *TD = 0, bool OrZero = false,
+ unsigned Depth = 0);
+
+ /// isKnownNonZero - Return true if the given value is known to be non-zero
+ /// when defined. For vectors return true if every element is known to be
+ /// non-zero when defined. Supports values with integer or pointer type and
+ /// vectors of integers.
+ bool isKnownNonZero(Value *V, const TargetData *TD = 0, unsigned Depth = 0);
+
+ /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
+ /// this predicate to simplify operations downstream. Mask is known to be
+ /// zero for bits that V cannot have.
+ ///
+ /// This function is defined on values with integer type, values with pointer
+ /// type (but only if TD is non-null), and vectors of integers. In the case
+ /// where V is a vector, the mask, known zero, and known one values are the
+ /// same width as the vector element, and the bit is set only if it is true
+ /// for all of the elements in the vector.
+ bool MaskedValueIsZero(Value *V, const APInt &Mask,
+ const TargetData *TD = 0, unsigned Depth = 0);
+
+
+ /// ComputeNumSignBits - Return the number of times the sign bit of the
+ /// register is replicated into the other bits. We know that at least 1 bit
+ /// is always equal to the sign bit (itself), but other cases can give us
+ /// information. For example, immediately after an "ashr X, 2", we know that
+ /// the top 3 bits are all equal to each other, so we return 3.
+ ///
+ /// 'Op' must have a scalar integer type.
+ ///
+ unsigned ComputeNumSignBits(Value *Op, const TargetData *TD = 0,
+ unsigned Depth = 0);
+
+ /// ComputeMultiple - This function computes the integer multiple of Base that
+ /// equals V. If successful, it returns true and returns the multiple in
+ /// Multiple. If unsuccessful, it returns false. Also, if V can be
+ /// simplified to an integer, then the simplified V is returned in Val. Look
+ /// through sext only if LookThroughSExt=true.
+ bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
+ bool LookThroughSExt = false,
+ unsigned Depth = 0);
+
+ /// CannotBeNegativeZero - Return true if we can prove that the specified FP
+ /// value is never equal to -0.0.
+ ///
+ bool CannotBeNegativeZero(const Value *V, unsigned Depth = 0);
+
+ /// isBytewiseValue - If the specified value can be set by repeating the same
+ /// byte in memory, return the i8 value that it is represented with. This is
+ /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
+ /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
+ /// byte store (e.g. i16 0x1234), return null.
+ Value *isBytewiseValue(Value *V);
+
+ /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
+ /// the scalar value indexed is already around as a register, for example if
+ /// it were inserted directly into the aggregrate.
+ ///
+ /// If InsertBefore is not null, this function will duplicate (modified)
+ /// insertvalues when a part of a nested struct is extracted.
+ Value *FindInsertedValue(Value *V,
+ ArrayRef<unsigned> idx_range,
+ Instruction *InsertBefore = 0);
+
+ /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
+ /// it can be expressed as a base pointer plus a constant offset. Return the
+ /// base and offset to the caller.
+ Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
+ const TargetData &TD);
+ static inline const Value *
+ GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
+ const TargetData &TD) {
+ return GetPointerBaseWithConstantOffset(const_cast<Value*>(Ptr), Offset,TD);
+ }
+
+ /// getConstantStringInfo - This function computes the length of a
+ /// null-terminated C string pointed to by V. If successful, it returns true
+ /// and returns the string in Str. If unsuccessful, it returns false. This
+ /// does not include the trailing nul character by default. If TrimAtNul is
+ /// set to false, then this returns any trailing nul characters as well as any
+ /// other characters that come after it.
+ bool getConstantStringInfo(const Value *V, StringRef &Str,
+ uint64_t Offset = 0, bool TrimAtNul = true);
+
+ /// GetStringLength - If we can compute the length of the string pointed to by
+ /// the specified pointer, return 'len+1'. If we can't, return 0.
+ uint64_t GetStringLength(Value *V);
+
+ /// GetUnderlyingObject - This method strips off any GEP address adjustments
+ /// and pointer casts from the specified value, returning the original object
+ /// being addressed. Note that the returned value has pointer type if the
+ /// specified value does. If the MaxLookup value is non-zero, it limits the
+ /// number of instructions to be stripped off.
+ Value *GetUnderlyingObject(Value *V, const TargetData *TD = 0,
+ unsigned MaxLookup = 6);
+ static inline const Value *
+ GetUnderlyingObject(const Value *V, const TargetData *TD = 0,
+ unsigned MaxLookup = 6) {
+ return GetUnderlyingObject(const_cast<Value *>(V), TD, MaxLookup);
+ }
+
+ /// GetUnderlyingObjects - This method is similar to GetUnderlyingObject
+ /// except that it can look through phi and select instructions and return
+ /// multiple objects.
+ void GetUnderlyingObjects(Value *V,
+ SmallVectorImpl<Value *> &Objects,
+ const TargetData *TD = 0,
+ unsigned MaxLookup = 6);
+
+ /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
+ /// are lifetime markers.
+ bool onlyUsedByLifetimeMarkers(const Value *V);
+
+ /// isSafeToSpeculativelyExecute - Return true if the instruction does not
+ /// have any effects besides calculating the result and does not have
+ /// undefined behavior.
+ ///
+ /// This method never returns true for an instruction that returns true for
+ /// mayHaveSideEffects; however, this method also does some other checks in
+ /// addition. It checks for undefined behavior, like dividing by zero or
+ /// loading from an invalid pointer (but not for undefined results, like a
+ /// shift with a shift amount larger than the width of the result). It checks
+ /// for malloc and alloca because speculatively executing them might cause a
+ /// memory leak. It also returns false for instructions related to control
+ /// flow, specifically terminators and PHI nodes.
+ ///
+ /// This method only looks at the instruction itself and its operands, so if
+ /// this method returns true, it is safe to move the instruction as long as
+ /// the correct dominance relationships for the operands and users hold.
+ /// However, this method can return true for instructions that read memory;
+ /// for such instructions, moving them may change the resulting value.
+ bool isSafeToSpeculativelyExecute(const Value *V,
+ const TargetData *TD = 0);
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Analysis/Verifier.h b/include/llvm/Analysis/Verifier.h
new file mode 100644
index 00000000000..ce8aeef0764
--- /dev/null
+++ b/include/llvm/Analysis/Verifier.h
@@ -0,0 +1,75 @@
+//===-- llvm/Analysis/Verifier.h - LLVM IR Verifier -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the function verifier interface, that can be used for some
+// sanity checking of input to the system, and for checking that transformations
+// haven't done something bad.
+//
+// Note that this does not provide full 'java style' security and verifications,
+// instead it just tries to ensure that code is well formed.
+//
+// To see what specifically is checked, look at the top of Verifier.cpp
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_VERIFIER_H
+#define LLVM_ANALYSIS_VERIFIER_H
+
+#include <string>
+
+namespace llvm {
+
+class FunctionPass;
+class Module;
+class Function;
+
+/// @brief An enumeration to specify the action to be taken if errors found.
+///
+/// This enumeration is used in the functions below to indicate what should
+/// happen if the verifier finds errors. Each of the functions that uses
+/// this enumeration as an argument provides a default value for it. The
+/// actions are listed below.
+enum VerifierFailureAction {
+ AbortProcessAction, ///< verifyModule will print to stderr and abort()
+ PrintMessageAction, ///< verifyModule will print to stderr and return true
+ ReturnStatusAction ///< verifyModule will just return true
+};
+
+/// @brief Create a verifier pass.
+///
+/// Check a module or function for validity. When the pass is used, the
+/// action indicated by the \p action argument will be used if errors are
+/// found.
+FunctionPass *createVerifierPass(
+ VerifierFailureAction action = AbortProcessAction ///< Action to take
+);
+
+/// @brief Check a module for errors.
+///
+/// If there are no errors, the function returns false. If an error is found,
+/// the action taken depends on the \p action parameter.
+/// This should only be used for debugging, because it plays games with
+/// PassManagers and stuff.
+
+bool verifyModule(
+ const Module &M, ///< The module to be verified
+ VerifierFailureAction action = AbortProcessAction, ///< Action to take
+ std::string *ErrorInfo = 0 ///< Information about failures.
+);
+
+// verifyFunction - Check a function for errors, useful for use when debugging a
+// pass.
+bool verifyFunction(
+ const Function &F, ///< The function to be verified
+ VerifierFailureAction action = AbortProcessAction ///< Action to take
+);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Argument.h b/include/llvm/Argument.h
new file mode 100644
index 00000000000..e66075c1f23
--- /dev/null
+++ b/include/llvm/Argument.h
@@ -0,0 +1,92 @@
+//===-- llvm/Argument.h - Definition of the Argument class ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the Argument class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ARGUMENT_H
+#define LLVM_ARGUMENT_H
+
+#include "llvm/Value.h"
+#include "llvm/Attributes.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/ADT/Twine.h"
+
+namespace llvm {
+
+template<typename ValueSubClass, typename ItemParentClass>
+ class SymbolTableListTraits;
+
+/// A class to represent an incoming formal argument to a Function. An argument
+/// is a very simple Value. It is essentially a named (optional) type. When used
+/// in the body of a function, it represents the value of the actual argument
+/// the function was called with.
+/// @brief LLVM Argument representation
+class Argument : public Value, public ilist_node<Argument> {
+ virtual void anchor();
+ Function *Parent;
+
+ friend class SymbolTableListTraits<Argument, Function>;
+ void setParent(Function *parent);
+
+public:
+ /// Argument ctor - If Function argument is specified, this argument is
+ /// inserted at the end of the argument list for the function.
+ ///
+ explicit Argument(Type *Ty, const Twine &Name = "", Function *F = 0);
+
+ inline const Function *getParent() const { return Parent; }
+ inline Function *getParent() { return Parent; }
+
+ /// getArgNo - Return the index of this formal argument in its containing
+ /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
+ unsigned getArgNo() const;
+
+ /// hasByValAttr - Return true if this argument has the byval attribute on it
+ /// in its containing function.
+ bool hasByValAttr() const;
+
+ /// getParamAlignment - If this is a byval argument, return its alignment.
+ unsigned getParamAlignment() const;
+
+ /// hasNestAttr - Return true if this argument has the nest attribute on
+ /// it in its containing function.
+ bool hasNestAttr() const;
+
+ /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
+ /// it in its containing function.
+ bool hasNoAliasAttr() const;
+
+ /// hasNoCaptureAttr - Return true if this argument has the nocapture
+ /// attribute on it in its containing function.
+ bool hasNoCaptureAttr() const;
+
+ /// hasSRetAttr - Return true if this argument has the sret attribute on it in
+ /// its containing function.
+ bool hasStructRetAttr() const;
+
+ /// addAttr - Add a Attribute to an argument
+ void addAttr(Attributes);
+
+ /// removeAttr - Remove a Attribute from an argument
+ void removeAttr(Attributes);
+
+ /// classof - Methods for support type inquiry through isa, cast, and
+ /// dyn_cast:
+ ///
+ static inline bool classof(const Argument *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == ArgumentVal;
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Assembly/AssemblyAnnotationWriter.h b/include/llvm/Assembly/AssemblyAnnotationWriter.h
new file mode 100644
index 00000000000..37b47c31e8c
--- /dev/null
+++ b/include/llvm/Assembly/AssemblyAnnotationWriter.h
@@ -0,0 +1,63 @@
+//===-- AssemblyAnnotationWriter.h - Annotation .ll files -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Clients of the assembly writer can use this interface to add their own
+// special-purpose annotations to LLVM assembly language printouts. Note that
+// the assembly parser won't be able to parse these, in general, so
+// implementations are advised to print stuff as LLVM comments.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ASSEMBLY_ASMANNOTATIONWRITER_H
+#define LLVM_ASSEMBLY_ASMANNOTATIONWRITER_H
+
+namespace llvm {
+
+class Function;
+class BasicBlock;
+class Instruction;
+class Value;
+class formatted_raw_ostream;
+
+class AssemblyAnnotationWriter {
+public:
+
+ virtual ~AssemblyAnnotationWriter();
+
+ /// emitFunctionAnnot - This may be implemented to emit a string right before
+ /// the start of a function.
+ virtual void emitFunctionAnnot(const Function *,
+ formatted_raw_ostream &) {}
+
+ /// emitBasicBlockStartAnnot - This may be implemented to emit a string right
+ /// after the basic block label, but before the first instruction in the
+ /// block.
+ virtual void emitBasicBlockStartAnnot(const BasicBlock *,
+ formatted_raw_ostream &) {
+ }
+
+ /// emitBasicBlockEndAnnot - This may be implemented to emit a string right
+ /// after the basic block.
+ virtual void emitBasicBlockEndAnnot(const BasicBlock *,
+ formatted_raw_ostream &) {
+ }
+
+ /// emitInstructionAnnot - This may be implemented to emit a string right
+ /// before an instruction is emitted.
+ virtual void emitInstructionAnnot(const Instruction *,
+ formatted_raw_ostream &) {}
+
+ /// printInfoComment - This may be implemented to emit a comment to the
+ /// right of an instruction or global value.
+ virtual void printInfoComment(const Value &, formatted_raw_ostream &) {}
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Assembly/Parser.h b/include/llvm/Assembly/Parser.h
new file mode 100644
index 00000000000..b971c531ae0
--- /dev/null
+++ b/include/llvm/Assembly/Parser.h
@@ -0,0 +1,64 @@
+//===-- llvm/Assembly/Parser.h - Parser for VM assembly files ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// These classes are implemented by the lib/AsmParser library.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ASSEMBLY_PARSER_H
+#define LLVM_ASSEMBLY_PARSER_H
+
+#include <string>
+
+namespace llvm {
+
+class Module;
+class MemoryBuffer;
+class SMDiagnostic;
+class LLVMContext;
+
+/// This function is the main interface to the LLVM Assembly Parser. It parses
+/// an ASCII file that (presumably) contains LLVM Assembly code. It returns a
+/// Module (intermediate representation) with the corresponding features. Note
+/// that this does not verify that the generated Module is valid, so you should
+/// run the verifier after parsing the file to check that it is okay.
+/// @brief Parse LLVM Assembly from a file
+Module *ParseAssemblyFile(
+ const std::string &Filename, ///< The name of the file to parse
+ SMDiagnostic &Error, ///< Error result info.
+ LLVMContext &Context ///< Context in which to allocate globals info.
+);
+
+/// The function is a secondary interface to the LLVM Assembly Parser. It parses
+/// an ASCII string that (presumably) contains LLVM Assembly code. It returns a
+/// Module (intermediate representation) with the corresponding features. Note
+/// that this does not verify that the generated Module is valid, so you should
+/// run the verifier after parsing the file to check that it is okay.
+/// @brief Parse LLVM Assembly from a string
+Module *ParseAssemblyString(
+ const char *AsmString, ///< The string containing assembly
+ Module *M, ///< A module to add the assembly too.
+ SMDiagnostic &Error, ///< Error result info.
+ LLVMContext &Context
+);
+
+/// This function is the low-level interface to the LLVM Assembly Parser.
+/// ParseAssemblyFile and ParseAssemblyString are wrappers around this function.
+/// @brief Parse LLVM Assembly from a MemoryBuffer. This function *always*
+/// takes ownership of the MemoryBuffer.
+Module *ParseAssembly(
+ MemoryBuffer *F, ///< The MemoryBuffer containing assembly
+ Module *M, ///< A module to add the assembly too.
+ SMDiagnostic &Err, ///< Error result info.
+ LLVMContext &Context
+);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Assembly/PrintModulePass.h b/include/llvm/Assembly/PrintModulePass.h
new file mode 100644
index 00000000000..239fbcc0c8c
--- /dev/null
+++ b/include/llvm/Assembly/PrintModulePass.h
@@ -0,0 +1,42 @@
+//===- llvm/Assembly/PrintModulePass.h - Printing Pass ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines two passes to print out a module. The PrintModulePass pass
+// simply prints out the entire module when it is executed. The
+// PrintFunctionPass class is designed to be pipelined with other
+// FunctionPass's, and prints out the functions of the module as they are
+// processed.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ASSEMBLY_PRINTMODULEPASS_H
+#define LLVM_ASSEMBLY_PRINTMODULEPASS_H
+
+#include <string>
+
+namespace llvm {
+ class FunctionPass;
+ class ModulePass;
+ class raw_ostream;
+
+ /// createPrintModulePass - Create and return a pass that writes the
+ /// module to the specified raw_ostream.
+ ModulePass *createPrintModulePass(raw_ostream *OS,
+ bool DeleteStream=false,
+ const std::string &Banner = "");
+
+ /// createPrintFunctionPass - Create and return a pass that prints
+ /// functions to the specified raw_ostream as they are processed.
+ FunctionPass *createPrintFunctionPass(const std::string &Banner,
+ raw_ostream *OS,
+ bool DeleteStream=false);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Assembly/Writer.h b/include/llvm/Assembly/Writer.h
new file mode 100644
index 00000000000..6b89ae022da
--- /dev/null
+++ b/include/llvm/Assembly/Writer.h
@@ -0,0 +1,37 @@
+//===-- llvm/Assembly/Writer.h - Printer for LLVM assembly files --*- C++ -*-=//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This functionality is implemented by lib/VMCore/AsmWriter.cpp.
+// This library is used to print LLVM assembly language files to an iostream. It
+// can print LLVM code at a variety of granularities, including Modules,
+// BasicBlocks, and Instructions. This makes it useful for debugging.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ASSEMBLY_WRITER_H
+#define LLVM_ASSEMBLY_WRITER_H
+
+namespace llvm {
+
+class Module;
+class Value;
+class raw_ostream;
+
+// WriteAsOperand - Write the name of the specified value out to the specified
+// ostream. This can be useful when you just want to print int %reg126, not the
+// whole instruction that generated it. If you specify a Module for context,
+// then even constants get pretty-printed; for example, the type of a null
+// pointer is printed symbolically.
+//
+void WriteAsOperand(raw_ostream &, const Value *, bool PrintTy = true,
+ const Module *Context = 0);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Attributes.h b/include/llvm/Attributes.h
new file mode 100644
index 00000000000..d1497b5005c
--- /dev/null
+++ b/include/llvm/Attributes.h
@@ -0,0 +1,411 @@
+//===-- llvm/Attributes.h - Container for Attributes ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the simple types necessary to represent the
+// attributes associated with functions and their calls.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ATTRIBUTES_H
+#define LLVM_ATTRIBUTES_H
+
+#include "llvm/Support/MathExtras.h"
+#include "llvm/ADT/ArrayRef.h"
+#include <cassert>
+#include <string>
+
+namespace llvm {
+
+class Type;
+
+namespace Attribute {
+
+/// We use this proxy POD type to allow constructing Attributes constants using
+/// initializer lists. Do not use this class directly.
+struct AttrConst {
+ uint64_t v;
+ AttrConst operator | (const AttrConst Attrs) const {
+ AttrConst Res = {v | Attrs.v};
+ return Res;
+ }
+ AttrConst operator ~ () const {
+ AttrConst Res = {~v};
+ return Res;
+ }
+};
+
+/// Function parameters and results can have attributes to indicate how they
+/// should be treated by optimizations and code generation. This enumeration
+/// lists the attributes that can be associated with parameters, function
+/// results or the function itself.
+/// @brief Function attributes.
+
+/// We declare AttrConst objects that will be used throughout the code and also
+/// raw uint64_t objects with _i suffix to be used below for other constant
+/// declarations. This is done to avoid static CTORs and at the same time to
+/// keep type-safety of Attributes.
+#define DECLARE_LLVM_ATTRIBUTE(name, value) \
+ const uint64_t name##_i = value; \
+ const AttrConst name = {value};
+
+DECLARE_LLVM_ATTRIBUTE(None,0) ///< No attributes have been set
+DECLARE_LLVM_ATTRIBUTE(ZExt,1<<0) ///< Zero extended before/after call
+DECLARE_LLVM_ATTRIBUTE(SExt,1<<1) ///< Sign extended before/after call
+DECLARE_LLVM_ATTRIBUTE(NoReturn,1<<2) ///< Mark the function as not returning
+DECLARE_LLVM_ATTRIBUTE(InReg,1<<3) ///< Force argument to be passed in register
+DECLARE_LLVM_ATTRIBUTE(StructRet,1<<4) ///< Hidden pointer to structure to return
+DECLARE_LLVM_ATTRIBUTE(NoUnwind,1<<5) ///< Function doesn't unwind stack
+DECLARE_LLVM_ATTRIBUTE(NoAlias,1<<6) ///< Considered to not alias after call
+DECLARE_LLVM_ATTRIBUTE(ByVal,1<<7) ///< Pass structure by value
+DECLARE_LLVM_ATTRIBUTE(Nest,1<<8) ///< Nested function static chain
+DECLARE_LLVM_ATTRIBUTE(ReadNone,1<<9) ///< Function does not access memory
+DECLARE_LLVM_ATTRIBUTE(ReadOnly,1<<10) ///< Function only reads from memory
+DECLARE_LLVM_ATTRIBUTE(NoInline,1<<11) ///< inline=never
+DECLARE_LLVM_ATTRIBUTE(AlwaysInline,1<<12) ///< inline=always
+DECLARE_LLVM_ATTRIBUTE(OptimizeForSize,1<<13) ///< opt_size
+DECLARE_LLVM_ATTRIBUTE(StackProtect,1<<14) ///< Stack protection.
+DECLARE_LLVM_ATTRIBUTE(StackProtectReq,1<<15) ///< Stack protection required.
+DECLARE_LLVM_ATTRIBUTE(Alignment,31<<16) ///< Alignment of parameter (5 bits)
+ // stored as log2 of alignment with +1 bias
+ // 0 means unaligned different from align 1
+DECLARE_LLVM_ATTRIBUTE(NoCapture,1<<21) ///< Function creates no aliases of pointer
+DECLARE_LLVM_ATTRIBUTE(NoRedZone,1<<22) /// disable redzone
+DECLARE_LLVM_ATTRIBUTE(NoImplicitFloat,1<<23) /// disable implicit floating point
+ /// instructions.
+DECLARE_LLVM_ATTRIBUTE(Naked,1<<24) ///< Naked function
+DECLARE_LLVM_ATTRIBUTE(InlineHint,1<<25) ///< source said inlining was
+ ///desirable
+DECLARE_LLVM_ATTRIBUTE(StackAlignment,7<<26) ///< Alignment of stack for
+ ///function (3 bits) stored as log2
+ ///of alignment with +1 bias
+ ///0 means unaligned (different from
+ ///alignstack= {1))
+DECLARE_LLVM_ATTRIBUTE(ReturnsTwice,1<<29) ///< Function can return twice
+DECLARE_LLVM_ATTRIBUTE(UWTable,1<<30) ///< Function must be in a unwind
+ ///table
+DECLARE_LLVM_ATTRIBUTE(NonLazyBind,1U<<31) ///< Function is called early and/or
+ /// often, so lazy binding isn't
+ /// worthwhile.
+DECLARE_LLVM_ATTRIBUTE(AddressSafety,1ULL<<32) ///< Address safety checking is on.
+
+#undef DECLARE_LLVM_ATTRIBUTE
+
+} // namespace Attribute
+
+/// Attributes - A bitset of attributes.
+class Attributes {
+ // Currently, we need less than 64 bits.
+ uint64_t Bits;
+public:
+ Attributes() : Bits(0) { }
+ explicit Attributes(uint64_t Val) : Bits(Val) { }
+ /*implicit*/ Attributes(Attribute::AttrConst Val) : Bits(Val.v) { }
+ // This is a "safe bool() operator".
+ operator const void *() const { return Bits ? this : 0; }
+ bool isEmptyOrSingleton() const { return (Bits & (Bits - 1)) == 0; }
+ bool operator == (const Attributes &Attrs) const {
+ return Bits == Attrs.Bits;
+ }
+ bool operator != (const Attributes &Attrs) const {
+ return Bits != Attrs.Bits;
+ }
+ Attributes operator | (const Attributes &Attrs) const {
+ return Attributes(Bits | Attrs.Bits);
+ }
+ Attributes operator & (const Attributes &Attrs) const {
+ return Attributes(Bits & Attrs.Bits);
+ }
+ Attributes operator ^ (const Attributes &Attrs) const {
+ return Attributes(Bits ^ Attrs.Bits);
+ }
+ Attributes &operator |= (const Attributes &Attrs) {
+ Bits |= Attrs.Bits;
+ return *this;
+ }
+ Attributes &operator &= (const Attributes &Attrs) {
+ Bits &= Attrs.Bits;
+ return *this;
+ }
+ Attributes operator ~ () const { return Attributes(~Bits); }
+ uint64_t Raw() const { return Bits; }
+};
+
+namespace Attribute {
+
+/// Note that uwtable is about the ABI or the user mandating an entry in the
+/// unwind table. The nounwind attribute is about an exception passing by the
+/// function.
+/// In a theoretical system that uses tables for profiling and sjlj for
+/// exceptions, they would be fully independent. In a normal system that
+/// uses tables for both, the semantics are:
+/// nil = Needs an entry because an exception might pass by.
+/// nounwind = No need for an entry
+/// uwtable = Needs an entry because the ABI says so and because
+/// an exception might pass by.
+/// uwtable + nounwind = Needs an entry because the ABI says so.
+
+/// @brief Attributes that only apply to function parameters.
+const AttrConst ParameterOnly = {ByVal_i | Nest_i |
+ StructRet_i | NoCapture_i};
+
+/// @brief Attributes that may be applied to the function itself. These cannot
+/// be used on return values or function parameters.
+const AttrConst FunctionOnly = {NoReturn_i | NoUnwind_i | ReadNone_i |
+ ReadOnly_i | NoInline_i | AlwaysInline_i | OptimizeForSize_i |
+ StackProtect_i | StackProtectReq_i | NoRedZone_i | NoImplicitFloat_i |
+ Naked_i | InlineHint_i | StackAlignment_i |
+ UWTable_i | NonLazyBind_i | ReturnsTwice_i | AddressSafety_i};
+
+/// @brief Parameter attributes that do not apply to vararg call arguments.
+const AttrConst VarArgsIncompatible = {StructRet_i};
+
+/// @brief Attributes that are mutually incompatible.
+const AttrConst MutuallyIncompatible[5] = {
+ {ByVal_i | Nest_i | StructRet_i},
+ {ByVal_i | Nest_i | InReg_i },
+ {ZExt_i | SExt_i},
+ {ReadNone_i | ReadOnly_i},
+ {NoInline_i | AlwaysInline_i}
+};
+
+/// @brief Which attributes cannot be applied to a type.
+Attributes typeIncompatible(Type *Ty);
+
+/// This turns an int alignment (a power of 2, normally) into the
+/// form used internally in Attributes.
+inline Attributes constructAlignmentFromInt(unsigned i) {
+ // Default alignment, allow the target to define how to align it.
+ if (i == 0)
+ return None;
+
+ assert(isPowerOf2_32(i) && "Alignment must be a power of two.");
+ assert(i <= 0x40000000 && "Alignment too large.");
+ return Attributes((Log2_32(i)+1) << 16);
+}
+
+/// This returns the alignment field of an attribute as a byte alignment value.
+inline unsigned getAlignmentFromAttrs(Attributes A) {
+ Attributes Align = A & Attribute::Alignment;
+ if (!Align)
+ return 0;
+
+ return 1U << ((Align.Raw() >> 16) - 1);
+}
+
+/// This turns an int stack alignment (which must be a power of 2) into
+/// the form used internally in Attributes.
+inline Attributes constructStackAlignmentFromInt(unsigned i) {
+ // Default alignment, allow the target to define how to align it.
+ if (i == 0)
+ return None;
+
+ assert(isPowerOf2_32(i) && "Alignment must be a power of two.");
+ assert(i <= 0x100 && "Alignment too large.");
+ return Attributes((Log2_32(i)+1) << 26);
+}
+
+/// This returns the stack alignment field of an attribute as a byte alignment
+/// value.
+inline unsigned getStackAlignmentFromAttrs(Attributes A) {
+ Attributes StackAlign = A & Attribute::StackAlignment;
+ if (!StackAlign)
+ return 0;
+
+ return 1U << ((StackAlign.Raw() >> 26) - 1);
+}
+
+/// This returns an integer containing an encoding of all the
+/// LLVM attributes found in the given attribute bitset. Any
+/// change to this encoding is a breaking change to bitcode
+/// compatibility.
+inline uint64_t encodeLLVMAttributesForBitcode(Attributes Attrs) {
+ // FIXME: It doesn't make sense to store the alignment information as an
+ // expanded out value, we should store it as a log2 value. However, we can't
+ // just change that here without breaking bitcode compatibility. If this ever
+ // becomes a problem in practice, we should introduce new tag numbers in the
+ // bitcode file and have those tags use a more efficiently encoded alignment
+ // field.
+
+ // Store the alignment in the bitcode as a 16-bit raw value instead of a
+ // 5-bit log2 encoded value. Shift the bits above the alignment up by
+ // 11 bits.
+
+ uint64_t EncodedAttrs = Attrs.Raw() & 0xffff;
+ if (Attrs & Attribute::Alignment)
+ EncodedAttrs |= (1ull << 16) <<
+ (((Attrs & Attribute::Alignment).Raw()-1) >> 16);
+ EncodedAttrs |= (Attrs.Raw() & (0xfffull << 21)) << 11;
+
+ return EncodedAttrs;
+}
+
+/// This returns an attribute bitset containing the LLVM attributes
+/// that have been decoded from the given integer. This function
+/// must stay in sync with 'encodeLLVMAttributesForBitcode'.
+inline Attributes decodeLLVMAttributesForBitcode(uint64_t EncodedAttrs) {
+ // The alignment is stored as a 16-bit raw value from bits 31--16.
+ // We shift the bits above 31 down by 11 bits.
+
+ unsigned Alignment = (EncodedAttrs & (0xffffull << 16)) >> 16;
+ assert((!Alignment || isPowerOf2_32(Alignment)) &&
+ "Alignment must be a power of two.");
+
+ Attributes Attrs(EncodedAttrs & 0xffff);
+ if (Alignment)
+ Attrs |= Attribute::constructAlignmentFromInt(Alignment);
+ Attrs |= Attributes((EncodedAttrs & (0xfffull << 32)) >> 11);
+
+ return Attrs;
+}
+
+
+/// The set of Attributes set in Attributes is converted to a
+/// string of equivalent mnemonics. This is, presumably, for writing out
+/// the mnemonics for the assembly writer.
+/// @brief Convert attribute bits to text
+std::string getAsString(Attributes Attrs);
+} // end namespace Attribute
+
+/// This is just a pair of values to associate a set of attributes
+/// with an index.
+struct AttributeWithIndex {
+ Attributes Attrs; ///< The attributes that are set, or'd together.
+ unsigned Index; ///< Index of the parameter for which the attributes apply.
+ ///< Index 0 is used for return value attributes.
+ ///< Index ~0U is used for function attributes.
+
+ static AttributeWithIndex get(unsigned Idx, Attributes Attrs) {
+ AttributeWithIndex P;
+ P.Index = Idx;
+ P.Attrs = Attrs;
+ return P;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// AttrListPtr Smart Pointer
+//===----------------------------------------------------------------------===//
+
+class AttributeListImpl;
+
+/// AttrListPtr - This class manages the ref count for the opaque
+/// AttributeListImpl object and provides accessors for it.
+class AttrListPtr {
+ /// AttrList - The attributes that we are managing. This can be null
+ /// to represent the empty attributes list.
+ AttributeListImpl *AttrList;
+public:
+ AttrListPtr() : AttrList(0) {}
+ AttrListPtr(const AttrListPtr &P);
+ const AttrListPtr &operator=(const AttrListPtr &RHS);
+ ~AttrListPtr();
+
+ //===--------------------------------------------------------------------===//
+ // Attribute List Construction and Mutation
+ //===--------------------------------------------------------------------===//
+
+ /// get - Return a Attributes list with the specified parameters in it.
+ static AttrListPtr get(ArrayRef<AttributeWithIndex> Attrs);
+
+ /// addAttr - Add the specified attribute at the specified index to this
+ /// attribute list. Since attribute lists are immutable, this
+ /// returns the new list.
+ AttrListPtr addAttr(unsigned Idx, Attributes Attrs) const;
+
+ /// removeAttr - Remove the specified attribute at the specified index from
+ /// this attribute list. Since attribute lists are immutable, this
+ /// returns the new list.
+ AttrListPtr removeAttr(unsigned Idx, Attributes Attrs) const;
+
+ //===--------------------------------------------------------------------===//
+ // Attribute List Accessors
+ //===--------------------------------------------------------------------===//
+ /// getParamAttributes - The attributes for the specified index are
+ /// returned.
+ Attributes getParamAttributes(unsigned Idx) const {
+ assert (Idx && Idx != ~0U && "Invalid parameter index!");
+ return getAttributes(Idx);
+ }
+
+ /// getRetAttributes - The attributes for the ret value are
+ /// returned.
+ Attributes getRetAttributes() const {
+ return getAttributes(0);
+ }
+
+ /// getFnAttributes - The function attributes are returned.
+ Attributes getFnAttributes() const {
+ return getAttributes(~0U);
+ }
+
+ /// paramHasAttr - Return true if the specified parameter index has the
+ /// specified attribute set.
+ bool paramHasAttr(unsigned Idx, Attributes Attr) const {
+ return getAttributes(Idx) & Attr;
+ }
+
+ /// getParamAlignment - Return the alignment for the specified function
+ /// parameter.
+ unsigned getParamAlignment(unsigned Idx) const {
+ return Attribute::getAlignmentFromAttrs(getAttributes(Idx));
+ }
+
+ /// hasAttrSomewhere - Return true if the specified attribute is set for at
+ /// least one parameter or for the return value.
+ bool hasAttrSomewhere(Attributes Attr) const;
+
+ /// operator==/!= - Provide equality predicates.
+ bool operator==(const AttrListPtr &RHS) const
+ { return AttrList == RHS.AttrList; }
+ bool operator!=(const AttrListPtr &RHS) const
+ { return AttrList != RHS.AttrList; }
+
+ void dump() const;
+
+ //===--------------------------------------------------------------------===//
+ // Attribute List Introspection
+ //===--------------------------------------------------------------------===//
+
+ /// getRawPointer - Return a raw pointer that uniquely identifies this
+ /// attribute list.
+ void *getRawPointer() const {
+ return AttrList;
+ }
+
+ // Attributes are stored as a dense set of slots, where there is one
+ // slot for each argument that has an attribute. This allows walking over the
+ // dense set instead of walking the sparse list of attributes.
+
+ /// isEmpty - Return true if there are no attributes.
+ ///
+ bool isEmpty() const {
+ return AttrList == 0;
+ }
+
+ /// getNumSlots - Return the number of slots used in this attribute list.
+ /// This is the number of arguments that have an attribute set on them
+ /// (including the function itself).
+ unsigned getNumSlots() const;
+
+ /// getSlot - Return the AttributeWithIndex at the specified slot. This
+ /// holds a index number plus a set of attributes.
+ const AttributeWithIndex &getSlot(unsigned Slot) const;
+
+private:
+ explicit AttrListPtr(AttributeListImpl *L);
+
+ /// getAttributes - The attributes for the specified index are
+ /// returned. Attributes for the result are denoted with Idx = 0.
+ Attributes getAttributes(unsigned Idx) const;
+
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/AutoUpgrade.h b/include/llvm/AutoUpgrade.h
new file mode 100644
index 00000000000..e13c4c12b0f
--- /dev/null
+++ b/include/llvm/AutoUpgrade.h
@@ -0,0 +1,44 @@
+//===-- llvm/AutoUpgrade.h - AutoUpgrade Helpers ----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// These functions are implemented by lib/VMCore/AutoUpgrade.cpp.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_AUTOUPGRADE_H
+#define LLVM_AUTOUPGRADE_H
+
+namespace llvm {
+ class Module;
+ class GlobalVariable;
+ class Function;
+ class CallInst;
+
+ /// This is a more granular function that simply checks an intrinsic function
+ /// for upgrading, and returns true if it requires upgrading. It may return
+ /// null in NewFn if the all calls to the original intrinsic function
+ /// should be transformed to non-function-call instructions.
+ bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn);
+
+ /// This is the complement to the above, replacing a specific call to an
+ /// intrinsic function with a call to the specified new function.
+ void UpgradeIntrinsicCall(CallInst *CI, Function *NewFn);
+
+ /// This is an auto-upgrade hook for any old intrinsic function syntaxes
+ /// which need to have both the function updated as well as all calls updated
+ /// to the new function. This should only be run in a post-processing fashion
+ /// so that it can update all calls to the old function.
+ void UpgradeCallsToIntrinsic(Function* F);
+
+ /// This checks for global variables which should be upgraded. It returns true
+ /// if it requires upgrading.
+ bool UpgradeGlobalVariable(GlobalVariable *GV);
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/BasicBlock.h b/include/llvm/BasicBlock.h
new file mode 100644
index 00000000000..9ab4a74e5a5
--- /dev/null
+++ b/include/llvm/BasicBlock.h
@@ -0,0 +1,291 @@
+//===-- llvm/BasicBlock.h - Represent a basic block in the VM ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the BasicBlock class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_BASICBLOCK_H
+#define LLVM_BASICBLOCK_H
+
+#include "llvm/Instruction.h"
+#include "llvm/SymbolTableListTraits.h"
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+class LandingPadInst;
+class TerminatorInst;
+class LLVMContext;
+class BlockAddress;
+
+template<> struct ilist_traits<Instruction>
+ : public SymbolTableListTraits<Instruction, BasicBlock> {
+ // createSentinel is used to get hold of a node that marks the end of
+ // the list...
+ // The sentinel is relative to this instance, so we use a non-static
+ // method.
+ Instruction *createSentinel() const {
+ // since i(p)lists always publicly derive from the corresponding
+ // traits, placing a data member in this class will augment i(p)list.
+ // But since the NodeTy is expected to publicly derive from
+ // ilist_node<NodeTy>, there is a legal viable downcast from it
+ // to NodeTy. We use this trick to superpose i(p)list with a "ghostly"
+ // NodeTy, which becomes the sentinel. Dereferencing the sentinel is
+ // forbidden (save the ilist_node<NodeTy>) so no one will ever notice
+ // the superposition.
+ return static_cast<Instruction*>(&Sentinel);
+ }
+ static void destroySentinel(Instruction*) {}
+
+ Instruction *provideInitialHead() const { return createSentinel(); }
+ Instruction *ensureHead(Instruction*) const { return createSentinel(); }
+ static void noteHead(Instruction*, Instruction*) {}
+private:
+ mutable ilist_half_node<Instruction> Sentinel;
+};
+
+/// This represents a single basic block in LLVM. A basic block is simply a
+/// container of instructions that execute sequentially. Basic blocks are Values
+/// because they are referenced by instructions such as branches and switch
+/// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
+/// represents a label to which a branch can jump.
+///
+/// A well formed basic block is formed of a list of non-terminating
+/// instructions followed by a single TerminatorInst instruction.
+/// TerminatorInst's may not occur in the middle of basic blocks, and must
+/// terminate the blocks. The BasicBlock class allows malformed basic blocks to
+/// occur because it may be useful in the intermediate stage of constructing or
+/// modifying a program. However, the verifier will ensure that basic blocks
+/// are "well formed".
+/// @brief LLVM Basic Block Representation
+class BasicBlock : public Value, // Basic blocks are data objects also
+ public ilist_node<BasicBlock> {
+ friend class BlockAddress;
+public:
+ typedef iplist<Instruction> InstListType;
+private:
+ InstListType InstList;
+ Function *Parent;
+
+ void setParent(Function *parent);
+ friend class SymbolTableListTraits<BasicBlock, Function>;
+
+ BasicBlock(const BasicBlock &) LLVM_DELETED_FUNCTION;
+ void operator=(const BasicBlock &) LLVM_DELETED_FUNCTION;
+
+ /// BasicBlock ctor - If the function parameter is specified, the basic block
+ /// is automatically inserted at either the end of the function (if
+ /// InsertBefore is null), or before the specified basic block.
+ ///
+ explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
+ Function *Parent = 0, BasicBlock *InsertBefore = 0);
+public:
+ /// getContext - Get the context in which this basic block lives.
+ LLVMContext &getContext() const;
+
+ /// Instruction iterators...
+ typedef InstListType::iterator iterator;
+ typedef InstListType::const_iterator const_iterator;
+
+ /// Create - Creates a new BasicBlock. If the Parent parameter is specified,
+ /// the basic block is automatically inserted at either the end of the
+ /// function (if InsertBefore is 0), or before the specified basic block.
+ static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
+ Function *Parent = 0,BasicBlock *InsertBefore = 0) {
+ return new BasicBlock(Context, Name, Parent, InsertBefore);
+ }
+ ~BasicBlock();
+
+ /// getParent - Return the enclosing method, or null if none
+ ///
+ const Function *getParent() const { return Parent; }
+ Function *getParent() { return Parent; }
+
+ /// getTerminator() - If this is a well formed basic block, then this returns
+ /// a pointer to the terminator instruction. If it is not, then you get a
+ /// null pointer back.
+ ///
+ TerminatorInst *getTerminator();
+ const TerminatorInst *getTerminator() const;
+
+ /// Returns a pointer to the first instructon in this block that is not a
+ /// PHINode instruction. When adding instruction to the beginning of the
+ /// basic block, they should be added before the returned value, not before
+ /// the first instruction, which might be PHI.
+ /// Returns 0 is there's no non-PHI instruction.
+ Instruction* getFirstNonPHI();
+ const Instruction* getFirstNonPHI() const {
+ return const_cast<BasicBlock*>(this)->getFirstNonPHI();
+ }
+
+ // Same as above, but also skip debug intrinsics.
+ Instruction* getFirstNonPHIOrDbg();
+ const Instruction* getFirstNonPHIOrDbg() const {
+ return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
+ }
+
+ // Same as above, but also skip lifetime intrinsics.
+ Instruction* getFirstNonPHIOrDbgOrLifetime();
+ const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
+ return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
+ }
+
+ /// getFirstInsertionPt - Returns an iterator to the first instruction in this
+ /// block that is suitable for inserting a non-PHI instruction. In particular,
+ /// it skips all PHIs and LandingPad instructions.
+ iterator getFirstInsertionPt();
+ const_iterator getFirstInsertionPt() const {
+ return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
+ }
+
+ /// removeFromParent - This method unlinks 'this' from the containing
+ /// function, but does not delete it.
+ ///
+ void removeFromParent();
+
+ /// eraseFromParent - This method unlinks 'this' from the containing function
+ /// and deletes it.
+ ///
+ void eraseFromParent();
+
+ /// moveBefore - Unlink this basic block from its current function and
+ /// insert it into the function that MovePos lives in, right before MovePos.
+ void moveBefore(BasicBlock *MovePos);
+
+ /// moveAfter - Unlink this basic block from its current function and
+ /// insert it into the function that MovePos lives in, right after MovePos.
+ void moveAfter(BasicBlock *MovePos);
+
+
+ /// getSinglePredecessor - If this basic block has a single predecessor block,
+ /// return the block, otherwise return a null pointer.
+ BasicBlock *getSinglePredecessor();
+ const BasicBlock *getSinglePredecessor() const {
+ return const_cast<BasicBlock*>(this)->getSinglePredecessor();
+ }
+
+ /// getUniquePredecessor - If this basic block has a unique predecessor block,
+ /// return the block, otherwise return a null pointer.
+ /// Note that unique predecessor doesn't mean single edge, there can be
+ /// multiple edges from the unique predecessor to this block (for example
+ /// a switch statement with multiple cases having the same destination).
+ BasicBlock *getUniquePredecessor();
+ const BasicBlock *getUniquePredecessor() const {
+ return const_cast<BasicBlock*>(this)->getUniquePredecessor();
+ }
+
+ //===--------------------------------------------------------------------===//
+ /// Instruction iterator methods
+ ///
+ inline iterator begin() { return InstList.begin(); }
+ inline const_iterator begin() const { return InstList.begin(); }
+ inline iterator end () { return InstList.end(); }
+ inline const_iterator end () const { return InstList.end(); }
+
+ inline size_t size() const { return InstList.size(); }
+ inline bool empty() const { return InstList.empty(); }
+ inline const Instruction &front() const { return InstList.front(); }
+ inline Instruction &front() { return InstList.front(); }
+ inline const Instruction &back() const { return InstList.back(); }
+ inline Instruction &back() { return InstList.back(); }
+
+ /// getInstList() - Return the underlying instruction list container. You
+ /// need to access it directly if you want to modify it currently.
+ ///
+ const InstListType &getInstList() const { return InstList; }
+ InstListType &getInstList() { return InstList; }
+
+ /// getSublistAccess() - returns pointer to member of instruction list
+ static iplist<Instruction> BasicBlock::*getSublistAccess(Instruction*) {
+ return &BasicBlock::InstList;
+ }
+
+ /// getValueSymbolTable() - returns pointer to symbol table (if any)
+ ValueSymbolTable *getValueSymbolTable();
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const BasicBlock *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == Value::BasicBlockVal;
+ }
+
+ /// dropAllReferences() - This function causes all the subinstructions to "let
+ /// go" of all references that they are maintaining. This allows one to
+ /// 'delete' a whole class at a time, even though there may be circular
+ /// references... first all references are dropped, and all use counts go to
+ /// zero. Then everything is delete'd for real. Note that no operations are
+ /// valid on an object that has "dropped all references", except operator
+ /// delete.
+ ///
+ void dropAllReferences();
+
+ /// removePredecessor - This method is used to notify a BasicBlock that the
+ /// specified Predecessor of the block is no longer able to reach it. This is
+ /// actually not used to update the Predecessor list, but is actually used to
+ /// update the PHI nodes that reside in the block. Note that this should be
+ /// called while the predecessor still refers to this block.
+ ///
+ void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
+
+ /// splitBasicBlock - This splits a basic block into two at the specified
+ /// instruction. Note that all instructions BEFORE the specified iterator
+ /// stay as part of the original basic block, an unconditional branch is added
+ /// to the original BB, and the rest of the instructions in the BB are moved
+ /// to the new BB, including the old terminator. The newly formed BasicBlock
+ /// is returned. This function invalidates the specified iterator.
+ ///
+ /// Note that this only works on well formed basic blocks (must have a
+ /// terminator), and 'I' must not be the end of instruction list (which would
+ /// cause a degenerate basic block to be formed, having a terminator inside of
+ /// the basic block).
+ ///
+ /// Also note that this doesn't preserve any passes. To split blocks while
+ /// keeping loop information consistent, use the SplitBlock utility function.
+ ///
+ BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
+
+ /// hasAddressTaken - returns true if there are any uses of this basic block
+ /// other than direct branches, switches, etc. to it.
+ bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
+
+ /// replaceSuccessorsPhiUsesWith - Update all phi nodes in all our successors
+ /// to refer to basic block New instead of to us.
+ void replaceSuccessorsPhiUsesWith(BasicBlock *New);
+
+ /// isLandingPad - Return true if this basic block is a landing pad. I.e.,
+ /// it's the destination of the 'unwind' edge of an invoke instruction.
+ bool isLandingPad() const;
+
+ /// getLandingPadInst() - Return the landingpad instruction associated with
+ /// the landing pad.
+ LandingPadInst *getLandingPadInst();
+ const LandingPadInst *getLandingPadInst() const;
+
+private:
+ /// AdjustBlockAddressRefCount - BasicBlock stores the number of BlockAddress
+ /// objects using it. This is almost always 0, sometimes one, possibly but
+ /// almost never 2, and inconceivably 3 or more.
+ void AdjustBlockAddressRefCount(int Amt) {
+ setValueSubclassData(getSubclassDataFromValue()+Amt);
+ assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
+ "Refcount wrap-around");
+ }
+ // Shadow Value::setValueSubclassData with a private forwarding method so that
+ // any future subclasses cannot accidentally use it.
+ void setValueSubclassData(unsigned short D) {
+ Value::setValueSubclassData(D);
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Bitcode/Archive.h b/include/llvm/Bitcode/Archive.h
new file mode 100644
index 00000000000..4fd4b5d90a9
--- /dev/null
+++ b/include/llvm/Bitcode/Archive.h
@@ -0,0 +1,538 @@
+//===-- llvm/Bitcode/Archive.h - LLVM Bitcode Archive -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header file declares the Archive and ArchiveMember classes that provide
+// manipulation of LLVM Archive files. The implementation is provided by the
+// lib/Bitcode/Archive library. This library is used to read and write
+// archive (*.a) files that contain LLVM bitcode files (or others).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_BITCODE_ARCHIVE_H
+#define LLVM_BITCODE_ARCHIVE_H
+
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/Support/Path.h"
+#include <map>
+#include <set>
+
+namespace llvm {
+ class MemoryBuffer;
+
+// Forward declare classes
+class Module; // From VMCore
+class Archive; // Declared below
+class ArchiveMemberHeader; // Internal implementation class
+class LLVMContext; // Global data
+
+/// This class is the main class manipulated by users of the Archive class. It
+/// holds information about one member of the Archive. It is also the element
+/// stored by the Archive's ilist, the Archive's main abstraction. Because of
+/// the special requirements of archive files, users are not permitted to
+/// construct ArchiveMember instances. You should obtain them from the methods
+/// of the Archive class instead.
+/// @brief This class represents a single archive member.
+class ArchiveMember : public ilist_node<ArchiveMember> {
+ /// @name Types
+ /// @{
+ public:
+ /// These flags are used internally by the archive member to specify various
+ /// characteristics of the member. The various "is" methods below provide
+ /// access to the flags. The flags are not user settable.
+ enum Flags {
+ SVR4SymbolTableFlag = 1, ///< Member is a SVR4 symbol table
+ BSD4SymbolTableFlag = 2, ///< Member is a BSD4 symbol table
+ LLVMSymbolTableFlag = 4, ///< Member is an LLVM symbol table
+ BitcodeFlag = 8, ///< Member is bitcode
+ HasPathFlag = 16, ///< Member has a full or partial path
+ HasLongFilenameFlag = 32, ///< Member uses the long filename syntax
+ StringTableFlag = 64 ///< Member is an ar(1) format string table
+ };
+
+ /// @}
+ /// @name Accessors
+ /// @{
+ public:
+ /// @returns the parent Archive instance
+ /// @brief Get the archive associated with this member
+ Archive* getArchive() const { return parent; }
+
+ /// @returns the path to the Archive's file
+ /// @brief Get the path to the archive member
+ const sys::Path& getPath() const { return path; }
+
+ /// The "user" is the owner of the file per Unix security. This may not
+ /// have any applicability on non-Unix systems but is a required component
+ /// of the "ar" file format.
+ /// @brief Get the user associated with this archive member.
+ unsigned getUser() const { return info.getUser(); }
+
+ /// The "group" is the owning group of the file per Unix security. This
+ /// may not have any applicability on non-Unix systems but is a required
+ /// component of the "ar" file format.
+ /// @brief Get the group associated with this archive member.
+ unsigned getGroup() const { return info.getGroup(); }
+
+ /// The "mode" specifies the access permissions for the file per Unix
+ /// security. This may not have any applicability on non-Unix systems but is
+ /// a required component of the "ar" file format.
+ /// @brief Get the permission mode associated with this archive member.
+ unsigned getMode() const { return info.getMode(); }
+
+ /// This method returns the time at which the archive member was last
+ /// modified when it was not in the archive.
+ /// @brief Get the time of last modification of the archive member.
+ sys::TimeValue getModTime() const { return info.getTimestamp(); }
+
+ /// @returns the size of the archive member in bytes.
+ /// @brief Get the size of the archive member.
+ uint64_t getSize() const { return info.getSize(); }
+
+ /// This method returns the total size of the archive member as it
+ /// appears on disk. This includes the file content, the header, the
+ /// long file name if any, and the padding.
+ /// @brief Get total on-disk member size.
+ unsigned getMemberSize() const;
+
+ /// This method will return a pointer to the in-memory content of the
+ /// archive member, if it is available. If the data has not been loaded
+ /// into memory, the return value will be null.
+ /// @returns a pointer to the member's data.
+ /// @brief Get the data content of the archive member
+ const char* getData() const { return data; }
+
+ /// @returns true iff the member is a SVR4 (non-LLVM) symbol table
+ /// @brief Determine if this member is a SVR4 symbol table.
+ bool isSVR4SymbolTable() const { return flags&SVR4SymbolTableFlag; }
+
+ /// @returns true iff the member is a BSD4.4 (non-LLVM) symbol table
+ /// @brief Determine if this member is a BSD4.4 symbol table.
+ bool isBSD4SymbolTable() const { return flags&BSD4SymbolTableFlag; }
+
+ /// @returns true iff the archive member is the LLVM symbol table
+ /// @brief Determine if this member is the LLVM symbol table.
+ bool isLLVMSymbolTable() const { return flags&LLVMSymbolTableFlag; }
+
+ /// @returns true iff the archive member is the ar(1) string table
+ /// @brief Determine if this member is the ar(1) string table.
+ bool isStringTable() const { return flags&StringTableFlag; }
+
+ /// @returns true iff the archive member is a bitcode file.
+ /// @brief Determine if this member is a bitcode file.
+ bool isBitcode() const { return flags&BitcodeFlag; }
+
+ /// @returns true iff the file name contains a path (directory) component.
+ /// @brief Determine if the member has a path
+ bool hasPath() const { return flags&HasPathFlag; }
+
+ /// Long filenames are an artifact of the ar(1) file format which allows
+ /// up to sixteen characters in its header and doesn't allow a path
+ /// separator character (/). To avoid this, a "long format" member name is
+ /// allowed that doesn't have this restriction. This method determines if
+ /// that "long format" is used for this member.
+ /// @returns true iff the file name uses the long form
+ /// @brief Determine if the member has a long file name
+ bool hasLongFilename() const { return flags&HasLongFilenameFlag; }
+
+ /// This method returns the status info (like Unix stat(2)) for the archive
+ /// member. The status info provides the file's size, permissions, and
+ /// modification time. The contents of the Path::StatusInfo structure, other
+ /// than the size and modification time, may not have utility on non-Unix
+ /// systems.
+ /// @returns the status info for the archive member
+ /// @brief Obtain the status info for the archive member
+ const sys::FileStatus &getFileStatus() const { return info; }
+
+ /// This method causes the archive member to be replaced with the contents
+ /// of the file specified by \p File. The contents of \p this will be
+ /// updated to reflect the new data from \p File. The \p File must exist and
+ /// be readable on entry to this method.
+ /// @returns true if an error occurred, false otherwise
+ /// @brief Replace contents of archive member with a new file.
+ bool replaceWith(const sys::Path &aFile, std::string* ErrMsg);
+
+ /// @}
+ /// @name Data
+ /// @{
+ private:
+ Archive* parent; ///< Pointer to parent archive
+ sys::PathWithStatus path; ///< Path of file containing the member
+ sys::FileStatus info; ///< Status info (size,mode,date)
+ unsigned flags; ///< Flags about the archive member
+ const char* data; ///< Data for the member
+
+ /// @}
+ /// @name Constructors
+ /// @{
+ public:
+ /// The default constructor is only used by the Archive's iplist when it
+ /// constructs the list's sentry node.
+ ArchiveMember();
+
+ private:
+ /// Used internally by the Archive class to construct an ArchiveMember.
+ /// The contents of the ArchiveMember are filled out by the Archive class.
+ explicit ArchiveMember(Archive *PAR);
+
+ // So Archive can construct an ArchiveMember
+ friend class llvm::Archive;
+ /// @}
+};
+
+/// This class defines the interface to LLVM Archive files. The Archive class
+/// presents the archive file as an ilist of ArchiveMember objects. The members
+/// can be rearranged in any fashion either by directly editing the ilist or by
+/// using editing methods on the Archive class (recommended). The Archive
+/// class also provides several ways of accessing the archive file for various
+/// purposes such as editing and linking. Full symbol table support is provided
+/// for loading only those files that resolve symbols. Note that read
+/// performance of this library is _crucial_ for performance of JIT type
+/// applications and the linkers. Consequently, the implementation of the class
+/// is optimized for reading.
+class Archive {
+
+ /// @name Types
+ /// @{
+ public:
+ /// This is the ilist type over which users may iterate to examine
+ /// the contents of the archive
+ /// @brief The ilist type of ArchiveMembers that Archive contains.
+ typedef iplist<ArchiveMember> MembersList;
+
+ /// @brief Forward mutable iterator over ArchiveMember
+ typedef MembersList::iterator iterator;
+
+ /// @brief Forward immutable iterator over ArchiveMember
+ typedef MembersList::const_iterator const_iterator;
+
+ /// @brief Reverse mutable iterator over ArchiveMember
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+
+ /// @brief Reverse immutable iterator over ArchiveMember
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+
+ /// @brief The in-memory version of the symbol table
+ typedef std::map<std::string,unsigned> SymTabType;
+
+ /// @}
+ /// @name ilist accessor methods
+ /// @{
+ public:
+ inline iterator begin() { return members.begin(); }
+ inline const_iterator begin() const { return members.begin(); }
+ inline iterator end () { return members.end(); }
+ inline const_iterator end () const { return members.end(); }
+
+ inline reverse_iterator rbegin() { return members.rbegin(); }
+ inline const_reverse_iterator rbegin() const { return members.rbegin(); }
+ inline reverse_iterator rend () { return members.rend(); }
+ inline const_reverse_iterator rend () const { return members.rend(); }
+
+ inline size_t size() const { return members.size(); }
+ inline bool empty() const { return members.empty(); }
+ inline const ArchiveMember& front() const { return members.front(); }
+ inline ArchiveMember& front() { return members.front(); }
+ inline const ArchiveMember& back() const { return members.back(); }
+ inline ArchiveMember& back() { return members.back(); }
+
+ /// @}
+ /// @name ilist mutator methods
+ /// @{
+ public:
+ /// This method splices a \p src member from an archive (possibly \p this),
+ /// to a position just before the member given by \p dest in \p this. When
+ /// the archive is written, \p src will be written in its new location.
+ /// @brief Move a member to a new location
+ inline void splice(iterator dest, Archive& arch, iterator src)
+ { return members.splice(dest,arch.members,src); }
+
+ /// This method erases a \p target member from the archive. When the
+ /// archive is written, it will no longer contain \p target. The associated
+ /// ArchiveMember is deleted.
+ /// @brief Erase a member.
+ inline iterator erase(iterator target) { return members.erase(target); }
+
+ /// @}
+ /// @name Constructors
+ /// @{
+ public:
+ /// Create an empty archive file and associate it with the \p Filename. This
+ /// method does not actually create the archive disk file. It creates an
+ /// empty Archive object. If the writeToDisk method is called, the archive
+ /// file \p Filename will be created at that point, with whatever content
+ /// the returned Archive object has at that time.
+ /// @returns An Archive* that represents the new archive file.
+ /// @brief Create an empty Archive.
+ static Archive* CreateEmpty(
+ const sys::Path& Filename,///< Name of the archive to (eventually) create.
+ LLVMContext& C ///< Context to use for global information
+ );
+
+ /// Open an existing archive and load its contents in preparation for
+ /// editing. After this call, the member ilist is completely populated based
+ /// on the contents of the archive file. You should use this form of open if
+ /// you intend to modify the archive or traverse its contents (e.g. for
+ /// printing).
+ /// @brief Open and load an archive file
+ static Archive* OpenAndLoad(
+ const sys::Path& filePath, ///< The file path to open and load
+ LLVMContext& C, ///< The context to use for global information
+ std::string* ErrorMessage ///< An optional error string
+ );
+
+ /// This method opens an existing archive file from \p Filename and reads in
+ /// its symbol table without reading in any of the archive's members. This
+ /// reduces both I/O and cpu time in opening the archive if it is to be used
+ /// solely for symbol lookup (e.g. during linking). The \p Filename must
+ /// exist and be an archive file or an error will be returned. This form
+ /// of opening the archive is intended for read-only operations that need to
+ /// locate members via the symbol table for link editing. Since the archve
+ /// members are not read by this method, the archive will appear empty upon
+ /// return. If editing operations are performed on the archive, they will
+ /// completely replace the contents of the archive! It is recommended that
+ /// if this form of opening the archive is used that only the symbol table
+ /// lookup methods (getSymbolTable, findModuleDefiningSymbol, and
+ /// findModulesDefiningSymbols) be used.
+ /// @returns an Archive* that represents the archive file, or null on error.
+ /// @brief Open an existing archive and load its symbols.
+ static Archive* OpenAndLoadSymbols(
+ const sys::Path& Filename, ///< Name of the archive file to open
+ LLVMContext& C, ///< The context to use for global info
+ std::string* ErrorMessage=0 ///< An optional error string
+ );
+
+ /// This destructor cleans up the Archive object, releases all memory, and
+ /// closes files. It does nothing with the archive file on disk. If you
+ /// haven't used the writeToDisk method by the time the destructor is
+ /// called, all changes to the archive will be lost.
+ /// @brief Destruct in-memory archive
+ ~Archive();
+
+ /// @}
+ /// @name Accessors
+ /// @{
+ public:
+ /// @returns the path to the archive file.
+ /// @brief Get the archive path.
+ const sys::Path& getPath() { return archPath; }
+
+ /// This method is provided so that editing methods can be invoked directly
+ /// on the Archive's iplist of ArchiveMember. However, it is recommended
+ /// that the usual STL style iterator interface be used instead.
+ /// @returns the iplist of ArchiveMember
+ /// @brief Get the iplist of the members
+ MembersList& getMembers() { return members; }
+
+ /// This method allows direct query of the Archive's symbol table. The
+ /// symbol table is a std::map of std::string (the symbol) to unsigned (the
+ /// file offset). Note that for efficiency reasons, the offset stored in
+ /// the symbol table is not the actual offset. It is the offset from the
+ /// beginning of the first "real" file member (after the symbol table). Use
+ /// the getFirstFileOffset() to obtain that offset and add this value to the
+ /// offset in the symbol table to obtain the real file offset. Note that
+ /// there is purposefully no interface provided by Archive to look up
+ /// members by their offset. Use the findModulesDefiningSymbols and
+ /// findModuleDefiningSymbol methods instead.
+ /// @returns the Archive's symbol table.
+ /// @brief Get the archive's symbol table
+ const SymTabType& getSymbolTable() { return symTab; }
+
+ /// This method returns the offset in the archive file to the first "real"
+ /// file member. Archive files, on disk, have a signature and might have a
+ /// symbol table that precedes the first actual file member. This method
+ /// allows you to determine what the size of those fields are.
+ /// @returns the offset to the first "real" file member in the archive.
+ /// @brief Get the offset to the first "real" file member in the archive.
+ unsigned getFirstFileOffset() { return firstFileOffset; }
+
+ /// This method will scan the archive for bitcode modules, interpret them
+ /// and return a vector of the instantiated modules in \p Modules. If an
+ /// error occurs, this method will return true. If \p ErrMessage is not null
+ /// and an error occurs, \p *ErrMessage will be set to a string explaining
+ /// the error that occurred.
+ /// @returns true if an error occurred
+ /// @brief Instantiate all the bitcode modules located in the archive
+ bool getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage);
+
+ /// This accessor looks up the \p symbol in the archive's symbol table and
+ /// returns the associated module that defines that symbol. This method can
+ /// be called as many times as necessary. This is handy for linking the
+ /// archive into another module based on unresolved symbols. Note that the
+ /// Module returned by this accessor should not be deleted by the caller. It
+ /// is managed internally by the Archive class. It is possible that multiple
+ /// calls to this accessor will return the same Module instance because the
+ /// associated module defines multiple symbols.
+ /// @returns The Module* found or null if the archive does not contain a
+ /// module that defines the \p symbol.
+ /// @brief Look up a module by symbol name.
+ Module* findModuleDefiningSymbol(
+ const std::string& symbol, ///< Symbol to be sought
+ std::string* ErrMessage ///< Error message storage, if non-zero
+ );
+
+ /// This method is similar to findModuleDefiningSymbol but allows lookup of
+ /// more than one symbol at a time. If \p symbols contains a list of
+ /// undefined symbols in some module, then calling this method is like
+ /// making one complete pass through the archive to resolve symbols but is
+ /// more efficient than looking at the individual members. Note that on
+ /// exit, the symbols resolved by this method will be removed from \p
+ /// symbols to ensure they are not re-searched on a subsequent call. If
+ /// you need to retain the list of symbols, make a copy.
+ /// @brief Look up multiple symbols in the archive.
+ bool findModulesDefiningSymbols(
+ std::set<std::string>& symbols, ///< Symbols to be sought
+ SmallVectorImpl<Module*>& modules, ///< The modules matching \p symbols
+ std::string* ErrMessage ///< Error msg storage, if non-zero
+ );
+
+ /// This method determines whether the archive is a properly formed llvm
+ /// bitcode archive. It first makes sure the symbol table has been loaded
+ /// and has a non-zero size. If it does, then it is an archive. If not,
+ /// then it tries to load all the bitcode modules of the archive. Finally,
+ /// it returns whether it was successful.
+ /// @returns true if the archive is a proper llvm bitcode archive
+ /// @brief Determine whether the archive is a proper llvm bitcode archive.
+ bool isBitcodeArchive();
+
+ /// @}
+ /// @name Mutators
+ /// @{
+ public:
+ /// This method is the only way to get the archive written to disk. It
+ /// creates or overwrites the file specified when \p this was created
+ /// or opened. The arguments provide options for writing the archive. If
+ /// \p CreateSymbolTable is true, the archive is scanned for bitcode files
+ /// and a symbol table of the externally visible function and global
+ /// variable names is created. If \p TruncateNames is true, the names of the
+ /// archive members will have their path component stripped and the file
+ /// name will be truncated at 15 characters. If \p Compress is specified,
+ /// all archive members will be compressed before being written. If
+ /// \p PrintSymTab is true, the symbol table will be printed to std::cout.
+ /// @returns true if an error occurred, \p error set to error message;
+ /// returns false if the writing succeeded.
+ /// @brief Write (possibly modified) archive contents to disk
+ bool writeToDisk(
+ bool CreateSymbolTable=false, ///< Create Symbol table
+ bool TruncateNames=false, ///< Truncate the filename to 15 chars
+ std::string* ErrMessage=0 ///< If non-null, where error msg is set
+ );
+
+ /// This method adds a new file to the archive. The \p filename is examined
+ /// to determine just enough information to create an ArchiveMember object
+ /// which is then inserted into the Archive object's ilist at the location
+ /// given by \p where.
+ /// @returns true if an error occurred, false otherwise
+ /// @brief Add a file to the archive.
+ bool addFileBefore(
+ const sys::Path& filename, ///< The file to be added
+ iterator where, ///< Insertion point
+ std::string* ErrMsg ///< Optional error message location
+ );
+
+ /// @}
+ /// @name Implementation
+ /// @{
+ protected:
+ /// @brief Construct an Archive for \p filename and optionally map it
+ /// into memory.
+ explicit Archive(const sys::Path& filename, LLVMContext& C);
+
+ /// @param data The symbol table data to be parsed
+ /// @param len The length of the symbol table data
+ /// @param error Set to address of a std::string to get error messages
+ /// @returns false on error
+ /// @brief Parse the symbol table at \p data.
+ bool parseSymbolTable(const void* data,unsigned len,std::string* error);
+
+ /// @returns A fully populated ArchiveMember or 0 if an error occurred.
+ /// @brief Parse the header of a member starting at \p At
+ ArchiveMember* parseMemberHeader(
+ const char*&At, ///< The pointer to the location we're parsing
+ const char*End, ///< The pointer to the end of the archive
+ std::string* error ///< Optional error message catcher
+ );
+
+ /// @param ErrMessage Set to address of a std::string to get error messages
+ /// @returns false on error
+ /// @brief Check that the archive signature is correct
+ bool checkSignature(std::string* ErrMessage);
+
+ /// @param ErrMessage Set to address of a std::string to get error messages
+ /// @returns false on error
+ /// @brief Load the entire archive.
+ bool loadArchive(std::string* ErrMessage);
+
+ /// @param ErrMessage Set to address of a std::string to get error messages
+ /// @returns false on error
+ /// @brief Load just the symbol table.
+ bool loadSymbolTable(std::string* ErrMessage);
+
+ /// @brief Write the symbol table to an ofstream.
+ void writeSymbolTable(std::ofstream& ARFile);
+
+ /// Writes one ArchiveMember to an ofstream. If an error occurs, returns
+ /// false, otherwise true. If an error occurs and error is non-null then
+ /// it will be set to an error message.
+ /// @returns false if writing member succeeded,
+ /// returns true if writing member failed, \p error set to error message.
+ bool writeMember(
+ const ArchiveMember& member, ///< The member to be written
+ std::ofstream& ARFile, ///< The file to write member onto
+ bool CreateSymbolTable, ///< Should symbol table be created?
+ bool TruncateNames, ///< Should names be truncated to 11 chars?
+ std::string* ErrMessage ///< If non-null, place were error msg is set
+ );
+
+ /// @brief Fill in an ArchiveMemberHeader from ArchiveMember.
+ bool fillHeader(const ArchiveMember&mbr,
+ ArchiveMemberHeader& hdr,int sz, bool TruncateNames) const;
+
+ /// @brief Maps archive into memory
+ bool mapToMemory(std::string* ErrMsg);
+
+ /// @brief Frees all the members and unmaps the archive file.
+ void cleanUpMemory();
+
+ /// This type is used to keep track of bitcode modules loaded from the
+ /// symbol table. It maps the file offset to a pair that consists of the
+ /// associated ArchiveMember and the Module.
+ /// @brief Module mapping type
+ typedef std::map<unsigned,std::pair<Module*,ArchiveMember*> >
+ ModuleMap;
+
+
+ /// @}
+ /// @name Data
+ /// @{
+ protected:
+ sys::Path archPath; ///< Path to the archive file we read/write
+ MembersList members; ///< The ilist of ArchiveMember
+ MemoryBuffer *mapfile; ///< Raw Archive contents mapped into memory
+ const char* base; ///< Base of the memory mapped file data
+ SymTabType symTab; ///< The symbol table
+ std::string strtab; ///< The string table for long file names
+ unsigned symTabSize; ///< Size in bytes of symbol table
+ unsigned firstFileOffset; ///< Offset to first normal file.
+ ModuleMap modules; ///< The modules loaded via symbol lookup.
+ ArchiveMember* foreignST; ///< This holds the foreign symbol table.
+ LLVMContext& Context; ///< This holds global data.
+ /// @}
+ /// @name Hidden
+ /// @{
+ private:
+ Archive() LLVM_DELETED_FUNCTION;
+ Archive(const Archive&) LLVM_DELETED_FUNCTION;
+ Archive& operator=(const Archive&) LLVM_DELETED_FUNCTION;
+ /// @}
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Bitcode/BitCodes.h b/include/llvm/Bitcode/BitCodes.h
new file mode 100644
index 00000000000..28e1ab1c871
--- /dev/null
+++ b/include/llvm/Bitcode/BitCodes.h
@@ -0,0 +1,186 @@
+//===- BitCodes.h - Enum values for the bitcode format ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header Bitcode enum values.
+//
+// The enum values defined in this file should be considered permanent. If
+// new features are added, they should have values added at the end of the
+// respective lists.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_BITCODE_BITCODES_H
+#define LLVM_BITCODE_BITCODES_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include <cassert>
+
+namespace llvm {
+namespace bitc {
+ enum StandardWidths {
+ BlockIDWidth = 8, // We use VBR-8 for block IDs.
+ CodeLenWidth = 4, // Codelen are VBR-4.
+ BlockSizeWidth = 32 // BlockSize up to 2^32 32-bit words = 16GB per block.
+ };
+
+ // The standard abbrev namespace always has a way to exit a block, enter a
+ // nested block, define abbrevs, and define an unabbreviated record.
+ enum FixedAbbrevIDs {
+ END_BLOCK = 0, // Must be zero to guarantee termination for broken bitcode.
+ ENTER_SUBBLOCK = 1,
+
+ /// DEFINE_ABBREV - Defines an abbrev for the current block. It consists
+ /// of a vbr5 for # operand infos. Each operand info is emitted with a
+ /// single bit to indicate if it is a literal encoding. If so, the value is
+ /// emitted with a vbr8. If not, the encoding is emitted as 3 bits followed
+ /// by the info value as a vbr5 if needed.
+ DEFINE_ABBREV = 2,
+
+ // UNABBREV_RECORDs are emitted with a vbr6 for the record code, followed by
+ // a vbr6 for the # operands, followed by vbr6's for each operand.
+ UNABBREV_RECORD = 3,
+
+ // This is not a code, this is a marker for the first abbrev assignment.
+ FIRST_APPLICATION_ABBREV = 4
+ };
+
+ /// StandardBlockIDs - All bitcode files can optionally include a BLOCKINFO
+ /// block, which contains metadata about other blocks in the file.
+ enum StandardBlockIDs {
+ /// BLOCKINFO_BLOCK is used to define metadata about blocks, for example,
+ /// standard abbrevs that should be available to all blocks of a specified
+ /// ID.
+ BLOCKINFO_BLOCK_ID = 0,
+
+ // Block IDs 1-7 are reserved for future expansion.
+ FIRST_APPLICATION_BLOCKID = 8
+ };
+
+ /// BlockInfoCodes - The blockinfo block contains metadata about user-defined
+ /// blocks.
+ enum BlockInfoCodes {
+ // DEFINE_ABBREV has magic semantics here, applying to the current SETBID'd
+ // block, instead of the BlockInfo block.
+
+ BLOCKINFO_CODE_SETBID = 1, // SETBID: [blockid#]
+ BLOCKINFO_CODE_BLOCKNAME = 2, // BLOCKNAME: [name]
+ BLOCKINFO_CODE_SETRECORDNAME = 3 // BLOCKINFO_CODE_SETRECORDNAME: [id, name]
+ };
+
+} // End bitc namespace
+
+/// BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
+/// This is actually a union of two different things:
+/// 1. It could be a literal integer value ("the operand is always 17").
+/// 2. It could be an encoding specification ("this operand encoded like so").
+///
+class BitCodeAbbrevOp {
+ uint64_t Val; // A literal value or data for an encoding.
+ bool IsLiteral : 1; // Indicate whether this is a literal value or not.
+ unsigned Enc : 3; // The encoding to use.
+public:
+ enum Encoding {
+ Fixed = 1, // A fixed width field, Val specifies number of bits.
+ VBR = 2, // A VBR field where Val specifies the width of each chunk.
+ Array = 3, // A sequence of fields, next field species elt encoding.
+ Char6 = 4, // A 6-bit fixed field which maps to [a-zA-Z0-9._].
+ Blob = 5 // 32-bit aligned array of 8-bit characters.
+ };
+
+ explicit BitCodeAbbrevOp(uint64_t V) : Val(V), IsLiteral(true) {}
+ explicit BitCodeAbbrevOp(Encoding E, uint64_t Data = 0)
+ : Val(Data), IsLiteral(false), Enc(E) {}
+
+ bool isLiteral() const { return IsLiteral; }
+ bool isEncoding() const { return !IsLiteral; }
+
+ // Accessors for literals.
+ uint64_t getLiteralValue() const { assert(isLiteral()); return Val; }
+
+ // Accessors for encoding info.
+ Encoding getEncoding() const { assert(isEncoding()); return (Encoding)Enc; }
+ uint64_t getEncodingData() const {
+ assert(isEncoding() && hasEncodingData());
+ return Val;
+ }
+
+ bool hasEncodingData() const { return hasEncodingData(getEncoding()); }
+ static bool hasEncodingData(Encoding E) {
+ switch (E) {
+ case Fixed:
+ case VBR:
+ return true;
+ case Array:
+ case Char6:
+ case Blob:
+ return false;
+ }
+ llvm_unreachable("Invalid encoding");
+ }
+
+ /// isChar6 - Return true if this character is legal in the Char6 encoding.
+ static bool isChar6(char C) {
+ if (C >= 'a' && C <= 'z') return true;
+ if (C >= 'A' && C <= 'Z') return true;
+ if (C >= '0' && C <= '9') return true;
+ if (C == '.' || C == '_') return true;
+ return false;
+ }
+ static unsigned EncodeChar6(char C) {
+ if (C >= 'a' && C <= 'z') return C-'a';
+ if (C >= 'A' && C <= 'Z') return C-'A'+26;
+ if (C >= '0' && C <= '9') return C-'0'+26+26;
+ if (C == '.') return 62;
+ if (C == '_') return 63;
+ llvm_unreachable("Not a value Char6 character!");
+ }
+
+ static char DecodeChar6(unsigned V) {
+ assert((V & ~63) == 0 && "Not a Char6 encoded character!");
+ if (V < 26) return V+'a';
+ if (V < 26+26) return V-26+'A';
+ if (V < 26+26+10) return V-26-26+'0';
+ if (V == 62) return '.';
+ if (V == 63) return '_';
+ llvm_unreachable("Not a value Char6 character!");
+ }
+
+};
+
+template <> struct isPodLike<BitCodeAbbrevOp> { static const bool value=true; };
+
+/// BitCodeAbbrev - This class represents an abbreviation record. An
+/// abbreviation allows a complex record that has redundancy to be stored in a
+/// specialized format instead of the fully-general, fully-vbr, format.
+class BitCodeAbbrev {
+ SmallVector<BitCodeAbbrevOp, 32> OperandList;
+ unsigned char RefCount; // Number of things using this.
+ ~BitCodeAbbrev() {}
+public:
+ BitCodeAbbrev() : RefCount(1) {}
+
+ void addRef() { ++RefCount; }
+ void dropRef() { if (--RefCount == 0) delete this; }
+
+ unsigned getNumOperandInfos() const {
+ return static_cast<unsigned>(OperandList.size());
+ }
+ const BitCodeAbbrevOp &getOperandInfo(unsigned N) const {
+ return OperandList[N];
+ }
+
+ void Add(const BitCodeAbbrevOp &OpInfo) {
+ OperandList.push_back(OpInfo);
+ }
+};
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Bitcode/BitstreamReader.h b/include/llvm/Bitcode/BitstreamReader.h
new file mode 100644
index 00000000000..3daef789d61
--- /dev/null
+++ b/include/llvm/Bitcode/BitstreamReader.h
@@ -0,0 +1,668 @@
+//===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header defines the BitstreamReader class. This class can be used to
+// read an arbitrary bitstream, regardless of its contents.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef BITSTREAM_READER_H
+#define BITSTREAM_READER_H
+
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/Bitcode/BitCodes.h"
+#include "llvm/Support/Endian.h"
+#include "llvm/Support/StreamableMemoryObject.h"
+#include <climits>
+#include <string>
+#include <vector>
+
+namespace llvm {
+
+ class Deserializer;
+
+class BitstreamReader {
+public:
+ /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
+ /// These describe abbreviations that all blocks of the specified ID inherit.
+ struct BlockInfo {
+ unsigned BlockID;
+ std::vector<BitCodeAbbrev*> Abbrevs;
+ std::string Name;
+
+ std::vector<std::pair<unsigned, std::string> > RecordNames;
+ };
+private:
+ OwningPtr<StreamableMemoryObject> BitcodeBytes;
+
+ std::vector<BlockInfo> BlockInfoRecords;
+
+ /// IgnoreBlockInfoNames - This is set to true if we don't care about the
+ /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
+ /// uses this.
+ bool IgnoreBlockInfoNames;
+
+ BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
+ void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
+public:
+ BitstreamReader() : IgnoreBlockInfoNames(true) {
+ }
+
+ BitstreamReader(const unsigned char *Start, const unsigned char *End) {
+ IgnoreBlockInfoNames = true;
+ init(Start, End);
+ }
+
+ BitstreamReader(StreamableMemoryObject *bytes) {
+ BitcodeBytes.reset(bytes);
+ }
+
+ void init(const unsigned char *Start, const unsigned char *End) {
+ assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
+ BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
+ }
+
+ StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
+
+ ~BitstreamReader() {
+ // Free the BlockInfoRecords.
+ while (!BlockInfoRecords.empty()) {
+ BlockInfo &Info = BlockInfoRecords.back();
+ // Free blockinfo abbrev info.
+ for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
+ i != e; ++i)
+ Info.Abbrevs[i]->dropRef();
+ BlockInfoRecords.pop_back();
+ }
+ }
+
+ /// CollectBlockInfoNames - This is called by clients that want block/record
+ /// name information.
+ void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
+ bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
+
+ //===--------------------------------------------------------------------===//
+ // Block Manipulation
+ //===--------------------------------------------------------------------===//
+
+ /// hasBlockInfoRecords - Return true if we've already read and processed the
+ /// block info block for this Bitstream. We only process it for the first
+ /// cursor that walks over it.
+ bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
+
+ /// getBlockInfo - If there is block info for the specified ID, return it,
+ /// otherwise return null.
+ const BlockInfo *getBlockInfo(unsigned BlockID) const {
+ // Common case, the most recent entry matches BlockID.
+ if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
+ return &BlockInfoRecords.back();
+
+ for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
+ i != e; ++i)
+ if (BlockInfoRecords[i].BlockID == BlockID)
+ return &BlockInfoRecords[i];
+ return 0;
+ }
+
+ BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
+ if (const BlockInfo *BI = getBlockInfo(BlockID))
+ return *const_cast<BlockInfo*>(BI);
+
+ // Otherwise, add a new record.
+ BlockInfoRecords.push_back(BlockInfo());
+ BlockInfoRecords.back().BlockID = BlockID;
+ return BlockInfoRecords.back();
+ }
+
+};
+
+class BitstreamCursor {
+ friend class Deserializer;
+ BitstreamReader *BitStream;
+ size_t NextChar;
+
+ /// CurWord - This is the current data we have pulled from the stream but have
+ /// not returned to the client.
+ uint32_t CurWord;
+
+ /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
+ /// is always from [0...31] inclusive.
+ unsigned BitsInCurWord;
+
+ // CurCodeSize - This is the declared size of code values used for the current
+ // block, in bits.
+ unsigned CurCodeSize;
+
+ /// CurAbbrevs - Abbrevs installed at in this block.
+ std::vector<BitCodeAbbrev*> CurAbbrevs;
+
+ struct Block {
+ unsigned PrevCodeSize;
+ std::vector<BitCodeAbbrev*> PrevAbbrevs;
+ explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
+ };
+
+ /// BlockScope - This tracks the codesize of parent blocks.
+ SmallVector<Block, 8> BlockScope;
+
+public:
+ BitstreamCursor() : BitStream(0), NextChar(0) {
+ }
+ BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
+ operator=(RHS);
+ }
+
+ explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
+ NextChar = 0;
+ CurWord = 0;
+ BitsInCurWord = 0;
+ CurCodeSize = 2;
+ }
+
+ void init(BitstreamReader &R) {
+ freeState();
+
+ BitStream = &R;
+ NextChar = 0;
+ CurWord = 0;
+ BitsInCurWord = 0;
+ CurCodeSize = 2;
+ }
+
+ ~BitstreamCursor() {
+ freeState();
+ }
+
+ void operator=(const BitstreamCursor &RHS) {
+ freeState();
+
+ BitStream = RHS.BitStream;
+ NextChar = RHS.NextChar;
+ CurWord = RHS.CurWord;
+ BitsInCurWord = RHS.BitsInCurWord;
+ CurCodeSize = RHS.CurCodeSize;
+
+ // Copy abbreviations, and bump ref counts.
+ CurAbbrevs = RHS.CurAbbrevs;
+ for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
+ i != e; ++i)
+ CurAbbrevs[i]->addRef();
+
+ // Copy block scope and bump ref counts.
+ BlockScope = RHS.BlockScope;
+ for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
+ S != e; ++S) {
+ std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
+ for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
+ i != e; ++i)
+ Abbrevs[i]->addRef();
+ }
+ }
+
+ void freeState() {
+ // Free all the Abbrevs.
+ for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
+ i != e; ++i)
+ CurAbbrevs[i]->dropRef();
+ CurAbbrevs.clear();
+
+ // Free all the Abbrevs in the block scope.
+ for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
+ S != e; ++S) {
+ std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
+ for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
+ i != e; ++i)
+ Abbrevs[i]->dropRef();
+ }
+ BlockScope.clear();
+ }
+
+ /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
+ unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
+
+ bool isEndPos(size_t pos) {
+ return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
+ }
+
+ bool canSkipToPos(size_t pos) const {
+ // pos can be skipped to if it is a valid address or one byte past the end.
+ return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
+ static_cast<uint64_t>(pos - 1));
+ }
+
+ unsigned char getByte(size_t pos) {
+ uint8_t byte = -1;
+ BitStream->getBitcodeBytes().readByte(pos, &byte);
+ return byte;
+ }
+
+ uint32_t getWord(size_t pos) {
+ uint8_t buf[sizeof(uint32_t)];
+ memset(buf, 0xFF, sizeof(buf));
+ BitStream->getBitcodeBytes().readBytes(pos,
+ sizeof(buf),
+ buf,
+ NULL);
+ return *reinterpret_cast<support::ulittle32_t *>(buf);
+ }
+
+ bool AtEndOfStream() {
+ return isEndPos(NextChar) && BitsInCurWord == 0;
+ }
+
+ /// GetCurrentBitNo - Return the bit # of the bit we are reading.
+ uint64_t GetCurrentBitNo() const {
+ return NextChar*CHAR_BIT - BitsInCurWord;
+ }
+
+ BitstreamReader *getBitStreamReader() {
+ return BitStream;
+ }
+ const BitstreamReader *getBitStreamReader() const {
+ return BitStream;
+ }
+
+
+ /// JumpToBit - Reset the stream to the specified bit number.
+ void JumpToBit(uint64_t BitNo) {
+ uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
+ uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
+ assert(canSkipToPos(ByteNo) && "Invalid location");
+
+ // Move the cursor to the right word.
+ NextChar = ByteNo;
+ BitsInCurWord = 0;
+ CurWord = 0;
+
+ // Skip over any bits that are already consumed.
+ if (WordBitNo)
+ Read(static_cast<unsigned>(WordBitNo));
+ }
+
+
+ uint32_t Read(unsigned NumBits) {
+ assert(NumBits <= 32 && "Cannot return more than 32 bits!");
+ // If the field is fully contained by CurWord, return it quickly.
+ if (BitsInCurWord >= NumBits) {
+ uint32_t R = CurWord & ((1U << NumBits)-1);
+ CurWord >>= NumBits;
+ BitsInCurWord -= NumBits;
+ return R;
+ }
+
+ // If we run out of data, stop at the end of the stream.
+ if (isEndPos(NextChar)) {
+ CurWord = 0;
+ BitsInCurWord = 0;
+ return 0;
+ }
+
+ unsigned R = CurWord;
+
+ // Read the next word from the stream.
+ CurWord = getWord(NextChar);
+ NextChar += 4;
+
+ // Extract NumBits-BitsInCurWord from what we just read.
+ unsigned BitsLeft = NumBits-BitsInCurWord;
+
+ // Be careful here, BitsLeft is in the range [1..32] inclusive.
+ R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
+
+ // BitsLeft bits have just been used up from CurWord.
+ if (BitsLeft != 32)
+ CurWord >>= BitsLeft;
+ else
+ CurWord = 0;
+ BitsInCurWord = 32-BitsLeft;
+ return R;
+ }
+
+ uint64_t Read64(unsigned NumBits) {
+ if (NumBits <= 32) return Read(NumBits);
+
+ uint64_t V = Read(32);
+ return V | (uint64_t)Read(NumBits-32) << 32;
+ }
+
+ uint32_t ReadVBR(unsigned NumBits) {
+ uint32_t Piece = Read(NumBits);
+ if ((Piece & (1U << (NumBits-1))) == 0)
+ return Piece;
+
+ uint32_t Result = 0;
+ unsigned NextBit = 0;
+ while (1) {
+ Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
+
+ if ((Piece & (1U << (NumBits-1))) == 0)
+ return Result;
+
+ NextBit += NumBits-1;
+ Piece = Read(NumBits);
+ }
+ }
+
+ // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
+ // chunk size of the VBR must still be <= 32 bits though.
+ uint64_t ReadVBR64(unsigned NumBits) {
+ uint32_t Piece = Read(NumBits);
+ if ((Piece & (1U << (NumBits-1))) == 0)
+ return uint64_t(Piece);
+
+ uint64_t Result = 0;
+ unsigned NextBit = 0;
+ while (1) {
+ Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
+
+ if ((Piece & (1U << (NumBits-1))) == 0)
+ return Result;
+
+ NextBit += NumBits-1;
+ Piece = Read(NumBits);
+ }
+ }
+
+ void SkipToWord() {
+ BitsInCurWord = 0;
+ CurWord = 0;
+ }
+
+ unsigned ReadCode() {
+ return Read(CurCodeSize);
+ }
+
+
+ // Block header:
+ // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
+
+ /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
+ /// the block.
+ unsigned ReadSubBlockID() {
+ return ReadVBR(bitc::BlockIDWidth);
+ }
+
+ /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
+ /// over the body of this block. If the block record is malformed, return
+ /// true.
+ bool SkipBlock() {
+ // Read and ignore the codelen value. Since we are skipping this block, we
+ // don't care what code widths are used inside of it.
+ ReadVBR(bitc::CodeLenWidth);
+ SkipToWord();
+ unsigned NumWords = Read(bitc::BlockSizeWidth);
+
+ // Check that the block wasn't partially defined, and that the offset isn't
+ // bogus.
+ size_t SkipTo = NextChar + NumWords*4;
+ if (AtEndOfStream() || !canSkipToPos(SkipTo))
+ return true;
+
+ NextChar = SkipTo;
+ return false;
+ }
+
+ /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
+ /// the block, and return true if the block is valid.
+ bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
+ // Save the current block's state on BlockScope.
+ BlockScope.push_back(Block(CurCodeSize));
+ BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
+
+ // Add the abbrevs specific to this block to the CurAbbrevs list.
+ if (const BitstreamReader::BlockInfo *Info =
+ BitStream->getBlockInfo(BlockID)) {
+ for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
+ i != e; ++i) {
+ CurAbbrevs.push_back(Info->Abbrevs[i]);
+ CurAbbrevs.back()->addRef();
+ }
+ }
+
+ // Get the codesize of this block.
+ CurCodeSize = ReadVBR(bitc::CodeLenWidth);
+ SkipToWord();
+ unsigned NumWords = Read(bitc::BlockSizeWidth);
+ if (NumWordsP) *NumWordsP = NumWords;
+
+ // Validate that this block is sane.
+ if (CurCodeSize == 0 || AtEndOfStream())
+ return true;
+
+ return false;
+ }
+
+ bool ReadBlockEnd() {
+ if (BlockScope.empty()) return true;
+
+ // Block tail:
+ // [END_BLOCK, <align4bytes>]
+ SkipToWord();
+
+ PopBlockScope();
+ return false;
+ }
+
+private:
+ void PopBlockScope() {
+ CurCodeSize = BlockScope.back().PrevCodeSize;
+
+ // Delete abbrevs from popped scope.
+ for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
+ i != e; ++i)
+ CurAbbrevs[i]->dropRef();
+
+ BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
+ BlockScope.pop_back();
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Record Processing
+ //===--------------------------------------------------------------------===//
+
+private:
+ void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
+ SmallVectorImpl<uint64_t> &Vals) {
+ assert(Op.isLiteral() && "Not a literal");
+ // If the abbrev specifies the literal value to use, use it.
+ Vals.push_back(Op.getLiteralValue());
+ }
+
+ void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
+ SmallVectorImpl<uint64_t> &Vals) {
+ assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
+
+ // Decode the value as we are commanded.
+ switch (Op.getEncoding()) {
+ default: llvm_unreachable("Unknown encoding!");
+ case BitCodeAbbrevOp::Fixed:
+ Vals.push_back(Read((unsigned)Op.getEncodingData()));
+ break;
+ case BitCodeAbbrevOp::VBR:
+ Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
+ break;
+ case BitCodeAbbrevOp::Char6:
+ Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
+ break;
+ }
+ }
+public:
+
+ /// getAbbrev - Return the abbreviation for the specified AbbrevId.
+ const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
+ unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
+ assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
+ return CurAbbrevs[AbbrevNo];
+ }
+
+ unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
+ const char **BlobStart = 0, unsigned *BlobLen = 0) {
+ if (AbbrevID == bitc::UNABBREV_RECORD) {
+ unsigned Code = ReadVBR(6);
+ unsigned NumElts = ReadVBR(6);
+ for (unsigned i = 0; i != NumElts; ++i)
+ Vals.push_back(ReadVBR64(6));
+ return Code;
+ }
+
+ const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
+
+ for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
+ const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
+ if (Op.isLiteral()) {
+ ReadAbbreviatedLiteral(Op, Vals);
+ } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
+ // Array case. Read the number of elements as a vbr6.
+ unsigned NumElts = ReadVBR(6);
+
+ // Get the element encoding.
+ assert(i+2 == e && "array op not second to last?");
+ const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
+
+ // Read all the elements.
+ for (; NumElts; --NumElts)
+ ReadAbbreviatedField(EltEnc, Vals);
+ } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
+ // Blob case. Read the number of bytes as a vbr6.
+ unsigned NumElts = ReadVBR(6);
+ SkipToWord(); // 32-bit alignment
+
+ // Figure out where the end of this blob will be including tail padding.
+ size_t NewEnd = NextChar+((NumElts+3)&~3);
+
+ // If this would read off the end of the bitcode file, just set the
+ // record to empty and return.
+ if (!canSkipToPos(NewEnd)) {
+ Vals.append(NumElts, 0);
+ NextChar = BitStream->getBitcodeBytes().getExtent();
+ break;
+ }
+
+ // Otherwise, read the number of bytes. If we can return a reference to
+ // the data, do so to avoid copying it.
+ if (BlobStart) {
+ *BlobStart = (const char*)BitStream->getBitcodeBytes().getPointer(
+ NextChar, NumElts);
+ *BlobLen = NumElts;
+ } else {
+ for (; NumElts; ++NextChar, --NumElts)
+ Vals.push_back(getByte(NextChar));
+ }
+ // Skip over tail padding.
+ NextChar = NewEnd;
+ } else {
+ ReadAbbreviatedField(Op, Vals);
+ }
+ }
+
+ unsigned Code = (unsigned)Vals[0];
+ Vals.erase(Vals.begin());
+ return Code;
+ }
+
+ unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
+ const char *&BlobStart, unsigned &BlobLen) {
+ return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
+ }
+
+
+ //===--------------------------------------------------------------------===//
+ // Abbrev Processing
+ //===--------------------------------------------------------------------===//
+
+ void ReadAbbrevRecord() {
+ BitCodeAbbrev *Abbv = new BitCodeAbbrev();
+ unsigned NumOpInfo = ReadVBR(5);
+ for (unsigned i = 0; i != NumOpInfo; ++i) {
+ bool IsLiteral = Read(1) ? true : false;
+ if (IsLiteral) {
+ Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
+ continue;
+ }
+
+ BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
+ if (BitCodeAbbrevOp::hasEncodingData(E))
+ Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
+ else
+ Abbv->Add(BitCodeAbbrevOp(E));
+ }
+ CurAbbrevs.push_back(Abbv);
+ }
+
+public:
+
+ bool ReadBlockInfoBlock() {
+ // If this is the second stream to get to the block info block, skip it.
+ if (BitStream->hasBlockInfoRecords())
+ return SkipBlock();
+
+ if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
+
+ SmallVector<uint64_t, 64> Record;
+ BitstreamReader::BlockInfo *CurBlockInfo = 0;
+
+ // Read all the records for this module.
+ while (1) {
+ unsigned Code = ReadCode();
+ if (Code == bitc::END_BLOCK)
+ return ReadBlockEnd();
+ if (Code == bitc::ENTER_SUBBLOCK) {
+ ReadSubBlockID();
+ if (SkipBlock()) return true;
+ continue;
+ }
+
+ // Read abbrev records, associate them with CurBID.
+ if (Code == bitc::DEFINE_ABBREV) {
+ if (!CurBlockInfo) return true;
+ ReadAbbrevRecord();
+
+ // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
+ // appropriate BlockInfo.
+ BitCodeAbbrev *Abbv = CurAbbrevs.back();
+ CurAbbrevs.pop_back();
+ CurBlockInfo->Abbrevs.push_back(Abbv);
+ continue;
+ }
+
+ // Read a record.
+ Record.clear();
+ switch (ReadRecord(Code, Record)) {
+ default: break; // Default behavior, ignore unknown content.
+ case bitc::BLOCKINFO_CODE_SETBID:
+ if (Record.size() < 1) return true;
+ CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
+ break;
+ case bitc::BLOCKINFO_CODE_BLOCKNAME: {
+ if (!CurBlockInfo) return true;
+ if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
+ std::string Name;
+ for (unsigned i = 0, e = Record.size(); i != e; ++i)
+ Name += (char)Record[i];
+ CurBlockInfo->Name = Name;
+ break;
+ }
+ case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
+ if (!CurBlockInfo) return true;
+ if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
+ std::string Name;
+ for (unsigned i = 1, e = Record.size(); i != e; ++i)
+ Name += (char)Record[i];
+ CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
+ Name));
+ break;
+ }
+ }
+ }
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Bitcode/BitstreamWriter.h b/include/llvm/Bitcode/BitstreamWriter.h
new file mode 100644
index 00000000000..dea118f98ed
--- /dev/null
+++ b/include/llvm/Bitcode/BitstreamWriter.h
@@ -0,0 +1,548 @@
+//===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header defines the BitstreamWriter class. This class can be used to
+// write an arbitrary bitstream, regardless of its contents.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef BITSTREAM_WRITER_H
+#define BITSTREAM_WRITER_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Bitcode/BitCodes.h"
+#include <vector>
+
+namespace llvm {
+
+class BitstreamWriter {
+ SmallVectorImpl<char> &Out;
+
+ /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
+ unsigned CurBit;
+
+ /// CurValue - The current value. Only bits < CurBit are valid.
+ uint32_t CurValue;
+
+ /// CurCodeSize - This is the declared size of code values used for the
+ /// current block, in bits.
+ unsigned CurCodeSize;
+
+ /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
+ /// selected BLOCK ID.
+ unsigned BlockInfoCurBID;
+
+ /// CurAbbrevs - Abbrevs installed at in this block.
+ std::vector<BitCodeAbbrev*> CurAbbrevs;
+
+ struct Block {
+ unsigned PrevCodeSize;
+ unsigned StartSizeWord;
+ std::vector<BitCodeAbbrev*> PrevAbbrevs;
+ Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
+ };
+
+ /// BlockScope - This tracks the current blocks that we have entered.
+ std::vector<Block> BlockScope;
+
+ /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
+ /// These describe abbreviations that all blocks of the specified ID inherit.
+ struct BlockInfo {
+ unsigned BlockID;
+ std::vector<BitCodeAbbrev*> Abbrevs;
+ };
+ std::vector<BlockInfo> BlockInfoRecords;
+
+ // BackpatchWord - Backpatch a 32-bit word in the output with the specified
+ // value.
+ void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
+ Out[ByteNo++] = (unsigned char)(NewWord >> 0);
+ Out[ByteNo++] = (unsigned char)(NewWord >> 8);
+ Out[ByteNo++] = (unsigned char)(NewWord >> 16);
+ Out[ByteNo ] = (unsigned char)(NewWord >> 24);
+ }
+
+ void WriteByte(unsigned char Value) {
+ Out.push_back(Value);
+ }
+
+ void WriteWord(unsigned Value) {
+ unsigned char Bytes[4] = {
+ (unsigned char)(Value >> 0),
+ (unsigned char)(Value >> 8),
+ (unsigned char)(Value >> 16),
+ (unsigned char)(Value >> 24) };
+ Out.append(&Bytes[0], &Bytes[4]);
+ }
+
+ unsigned GetBufferOffset() const {
+ return Out.size();
+ }
+
+ unsigned GetWordIndex() const {
+ unsigned Offset = GetBufferOffset();
+ assert((Offset & 3) == 0 && "Not 32-bit aligned");
+ return Offset / 4;
+ }
+
+public:
+ explicit BitstreamWriter(SmallVectorImpl<char> &O)
+ : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
+
+ ~BitstreamWriter() {
+ assert(CurBit == 0 && "Unflused data remaining");
+ assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
+
+ // Free the BlockInfoRecords.
+ while (!BlockInfoRecords.empty()) {
+ BlockInfo &Info = BlockInfoRecords.back();
+ // Free blockinfo abbrev info.
+ for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
+ i != e; ++i)
+ Info.Abbrevs[i]->dropRef();
+ BlockInfoRecords.pop_back();
+ }
+ }
+
+ /// \brief Retrieve the current position in the stream, in bits.
+ uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
+
+ //===--------------------------------------------------------------------===//
+ // Basic Primitives for emitting bits to the stream.
+ //===--------------------------------------------------------------------===//
+
+ void Emit(uint32_t Val, unsigned NumBits) {
+ assert(NumBits && NumBits <= 32 && "Invalid value size!");
+ assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
+ CurValue |= Val << CurBit;
+ if (CurBit + NumBits < 32) {
+ CurBit += NumBits;
+ return;
+ }
+
+ // Add the current word.
+ WriteWord(CurValue);
+
+ if (CurBit)
+ CurValue = Val >> (32-CurBit);
+ else
+ CurValue = 0;
+ CurBit = (CurBit+NumBits) & 31;
+ }
+
+ void Emit64(uint64_t Val, unsigned NumBits) {
+ if (NumBits <= 32)
+ Emit((uint32_t)Val, NumBits);
+ else {
+ Emit((uint32_t)Val, 32);
+ Emit((uint32_t)(Val >> 32), NumBits-32);
+ }
+ }
+
+ void FlushToWord() {
+ if (CurBit) {
+ WriteWord(CurValue);
+ CurBit = 0;
+ CurValue = 0;
+ }
+ }
+
+ void EmitVBR(uint32_t Val, unsigned NumBits) {
+ assert(NumBits <= 32 && "Too many bits to emit!");
+ uint32_t Threshold = 1U << (NumBits-1);
+
+ // Emit the bits with VBR encoding, NumBits-1 bits at a time.
+ while (Val >= Threshold) {
+ Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
+ Val >>= NumBits-1;
+ }
+
+ Emit(Val, NumBits);
+ }
+
+ void EmitVBR64(uint64_t Val, unsigned NumBits) {
+ assert(NumBits <= 32 && "Too many bits to emit!");
+ if ((uint32_t)Val == Val)
+ return EmitVBR((uint32_t)Val, NumBits);
+
+ uint32_t Threshold = 1U << (NumBits-1);
+
+ // Emit the bits with VBR encoding, NumBits-1 bits at a time.
+ while (Val >= Threshold) {
+ Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
+ (1 << (NumBits-1)), NumBits);
+ Val >>= NumBits-1;
+ }
+
+ Emit((uint32_t)Val, NumBits);
+ }
+
+ /// EmitCode - Emit the specified code.
+ void EmitCode(unsigned Val) {
+ Emit(Val, CurCodeSize);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Block Manipulation
+ //===--------------------------------------------------------------------===//
+
+ /// getBlockInfo - If there is block info for the specified ID, return it,
+ /// otherwise return null.
+ BlockInfo *getBlockInfo(unsigned BlockID) {
+ // Common case, the most recent entry matches BlockID.
+ if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
+ return &BlockInfoRecords.back();
+
+ for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
+ i != e; ++i)
+ if (BlockInfoRecords[i].BlockID == BlockID)
+ return &BlockInfoRecords[i];
+ return 0;
+ }
+
+ void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
+ // Block header:
+ // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
+ EmitCode(bitc::ENTER_SUBBLOCK);
+ EmitVBR(BlockID, bitc::BlockIDWidth);
+ EmitVBR(CodeLen, bitc::CodeLenWidth);
+ FlushToWord();
+
+ unsigned BlockSizeWordIndex = GetWordIndex();
+ unsigned OldCodeSize = CurCodeSize;
+
+ // Emit a placeholder, which will be replaced when the block is popped.
+ Emit(0, bitc::BlockSizeWidth);
+
+ CurCodeSize = CodeLen;
+
+ // Push the outer block's abbrev set onto the stack, start out with an
+ // empty abbrev set.
+ BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
+ BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
+
+ // If there is a blockinfo for this BlockID, add all the predefined abbrevs
+ // to the abbrev list.
+ if (BlockInfo *Info = getBlockInfo(BlockID)) {
+ for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
+ i != e; ++i) {
+ CurAbbrevs.push_back(Info->Abbrevs[i]);
+ Info->Abbrevs[i]->addRef();
+ }
+ }
+ }
+
+ void ExitBlock() {
+ assert(!BlockScope.empty() && "Block scope imbalance!");
+
+ // Delete all abbrevs.
+ for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
+ i != e; ++i)
+ CurAbbrevs[i]->dropRef();
+
+ const Block &B = BlockScope.back();
+
+ // Block tail:
+ // [END_BLOCK, <align4bytes>]
+ EmitCode(bitc::END_BLOCK);
+ FlushToWord();
+
+ // Compute the size of the block, in words, not counting the size field.
+ unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
+ unsigned ByteNo = B.StartSizeWord*4;
+
+ // Update the block size field in the header of this sub-block.
+ BackpatchWord(ByteNo, SizeInWords);
+
+ // Restore the inner block's code size and abbrev table.
+ CurCodeSize = B.PrevCodeSize;
+ BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
+ BlockScope.pop_back();
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Record Emission
+ //===--------------------------------------------------------------------===//
+
+private:
+ /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
+ /// record. This is a no-op, since the abbrev specifies the literal to use.
+ template<typename uintty>
+ void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
+ assert(Op.isLiteral() && "Not a literal");
+ // If the abbrev specifies the literal value to use, don't emit
+ // anything.
+ assert(V == Op.getLiteralValue() &&
+ "Invalid abbrev for record!");
+ }
+
+ /// EmitAbbreviatedField - Emit a single scalar field value with the specified
+ /// encoding.
+ template<typename uintty>
+ void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
+ assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
+
+ // Encode the value as we are commanded.
+ switch (Op.getEncoding()) {
+ default: llvm_unreachable("Unknown encoding!");
+ case BitCodeAbbrevOp::Fixed:
+ if (Op.getEncodingData())
+ Emit((unsigned)V, (unsigned)Op.getEncodingData());
+ break;
+ case BitCodeAbbrevOp::VBR:
+ if (Op.getEncodingData())
+ EmitVBR64(V, (unsigned)Op.getEncodingData());
+ break;
+ case BitCodeAbbrevOp::Char6:
+ Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
+ break;
+ }
+ }
+
+ /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
+ /// emission code. If BlobData is non-null, then it specifies an array of
+ /// data that should be emitted as part of the Blob or Array operand that is
+ /// known to exist at the end of the record.
+ template<typename uintty>
+ void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
+ StringRef Blob) {
+ const char *BlobData = Blob.data();
+ unsigned BlobLen = (unsigned) Blob.size();
+ unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
+ assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
+ BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
+
+ EmitCode(Abbrev);
+
+ unsigned RecordIdx = 0;
+ for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
+ i != e; ++i) {
+ const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
+ if (Op.isLiteral()) {
+ assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
+ EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
+ ++RecordIdx;
+ } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
+ // Array case.
+ assert(i+2 == e && "array op not second to last?");
+ const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
+
+ // If this record has blob data, emit it, otherwise we must have record
+ // entries to encode this way.
+ if (BlobData) {
+ assert(RecordIdx == Vals.size() &&
+ "Blob data and record entries specified for array!");
+ // Emit a vbr6 to indicate the number of elements present.
+ EmitVBR(static_cast<uint32_t>(BlobLen), 6);
+
+ // Emit each field.
+ for (unsigned i = 0; i != BlobLen; ++i)
+ EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
+
+ // Know that blob data is consumed for assertion below.
+ BlobData = 0;
+ } else {
+ // Emit a vbr6 to indicate the number of elements present.
+ EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
+
+ // Emit each field.
+ for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
+ EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
+ }
+ } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
+ // If this record has blob data, emit it, otherwise we must have record
+ // entries to encode this way.
+
+ // Emit a vbr6 to indicate the number of elements present.
+ if (BlobData) {
+ EmitVBR(static_cast<uint32_t>(BlobLen), 6);
+ assert(RecordIdx == Vals.size() &&
+ "Blob data and record entries specified for blob operand!");
+ } else {
+ EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
+ }
+
+ // Flush to a 32-bit alignment boundary.
+ FlushToWord();
+
+ // Emit each field as a literal byte.
+ if (BlobData) {
+ for (unsigned i = 0; i != BlobLen; ++i)
+ WriteByte((unsigned char)BlobData[i]);
+
+ // Know that blob data is consumed for assertion below.
+ BlobData = 0;
+ } else {
+ for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
+ assert(Vals[RecordIdx] < 256 && "Value too large to emit as blob");
+ WriteByte((unsigned char)Vals[RecordIdx]);
+ }
+ }
+
+ // Align end to 32-bits.
+ while (GetBufferOffset() & 3)
+ WriteByte(0);
+ } else { // Single scalar field.
+ assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
+ EmitAbbreviatedField(Op, Vals[RecordIdx]);
+ ++RecordIdx;
+ }
+ }
+ assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
+ assert(BlobData == 0 &&
+ "Blob data specified for record that doesn't use it!");
+ }
+
+public:
+
+ /// EmitRecord - Emit the specified record to the stream, using an abbrev if
+ /// we have one to compress the output.
+ template<typename uintty>
+ void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
+ unsigned Abbrev = 0) {
+ if (!Abbrev) {
+ // If we don't have an abbrev to use, emit this in its fully unabbreviated
+ // form.
+ EmitCode(bitc::UNABBREV_RECORD);
+ EmitVBR(Code, 6);
+ EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
+ for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
+ EmitVBR64(Vals[i], 6);
+ return;
+ }
+
+ // Insert the code into Vals to treat it uniformly.
+ Vals.insert(Vals.begin(), Code);
+
+ EmitRecordWithAbbrev(Abbrev, Vals);
+ }
+
+ /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
+ /// Unlike EmitRecord, the code for the record should be included in Vals as
+ /// the first entry.
+ template<typename uintty>
+ void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
+ EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
+ }
+
+ /// EmitRecordWithBlob - Emit the specified record to the stream, using an
+ /// abbrev that includes a blob at the end. The blob data to emit is
+ /// specified by the pointer and length specified at the end. In contrast to
+ /// EmitRecord, this routine expects that the first entry in Vals is the code
+ /// of the record.
+ template<typename uintty>
+ void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
+ StringRef Blob) {
+ EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
+ }
+ template<typename uintty>
+ void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
+ const char *BlobData, unsigned BlobLen) {
+ return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
+ }
+
+ /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
+ /// that end with an array.
+ template<typename uintty>
+ void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
+ StringRef Array) {
+ EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
+ }
+ template<typename uintty>
+ void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
+ const char *ArrayData, unsigned ArrayLen) {
+ return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
+ ArrayLen));
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Abbrev Emission
+ //===--------------------------------------------------------------------===//
+
+private:
+ // Emit the abbreviation as a DEFINE_ABBREV record.
+ void EncodeAbbrev(BitCodeAbbrev *Abbv) {
+ EmitCode(bitc::DEFINE_ABBREV);
+ EmitVBR(Abbv->getNumOperandInfos(), 5);
+ for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
+ i != e; ++i) {
+ const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
+ Emit(Op.isLiteral(), 1);
+ if (Op.isLiteral()) {
+ EmitVBR64(Op.getLiteralValue(), 8);
+ } else {
+ Emit(Op.getEncoding(), 3);
+ if (Op.hasEncodingData())
+ EmitVBR64(Op.getEncodingData(), 5);
+ }
+ }
+ }
+public:
+
+ /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
+ /// method takes ownership of the specified abbrev.
+ unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
+ // Emit the abbreviation as a record.
+ EncodeAbbrev(Abbv);
+ CurAbbrevs.push_back(Abbv);
+ return static_cast<unsigned>(CurAbbrevs.size())-1 +
+ bitc::FIRST_APPLICATION_ABBREV;
+ }
+
+ //===--------------------------------------------------------------------===//
+ // BlockInfo Block Emission
+ //===--------------------------------------------------------------------===//
+
+ /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
+ void EnterBlockInfoBlock(unsigned CodeWidth) {
+ EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
+ BlockInfoCurBID = ~0U;
+ }
+private:
+ /// SwitchToBlockID - If we aren't already talking about the specified block
+ /// ID, emit a BLOCKINFO_CODE_SETBID record.
+ void SwitchToBlockID(unsigned BlockID) {
+ if (BlockInfoCurBID == BlockID) return;
+ SmallVector<unsigned, 2> V;
+ V.push_back(BlockID);
+ EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
+ BlockInfoCurBID = BlockID;
+ }
+
+ BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
+ if (BlockInfo *BI = getBlockInfo(BlockID))
+ return *BI;
+
+ // Otherwise, add a new record.
+ BlockInfoRecords.push_back(BlockInfo());
+ BlockInfoRecords.back().BlockID = BlockID;
+ return BlockInfoRecords.back();
+ }
+
+public:
+
+ /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
+ /// BlockID.
+ unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
+ SwitchToBlockID(BlockID);
+ EncodeAbbrev(Abbv);
+
+ // Add the abbrev to the specified block record.
+ BlockInfo &Info = getOrCreateBlockInfo(BlockID);
+ Info.Abbrevs.push_back(Abbv);
+
+ return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
+ }
+};
+
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Bitcode/LLVMBitCodes.h b/include/llvm/Bitcode/LLVMBitCodes.h
new file mode 100644
index 00000000000..c1dc190304c
--- /dev/null
+++ b/include/llvm/Bitcode/LLVMBitCodes.h
@@ -0,0 +1,329 @@
+//===- LLVMBitCodes.h - Enum values for the LLVM bitcode format -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header defines Bitcode enum values for LLVM IR bitcode files.
+//
+// The enum values defined in this file should be considered permanent. If
+// new features are added, they should have values added at the end of the
+// respective lists.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_BITCODE_LLVMBITCODES_H
+#define LLVM_BITCODE_LLVMBITCODES_H
+
+#include "llvm/Bitcode/BitCodes.h"
+
+namespace llvm {
+namespace bitc {
+ // The only top-level block type defined is for a module.
+ enum BlockIDs {
+ // Blocks
+ MODULE_BLOCK_ID = FIRST_APPLICATION_BLOCKID,
+
+ // Module sub-block id's.
+ PARAMATTR_BLOCK_ID,
+
+ UNUSED_ID1,
+
+ CONSTANTS_BLOCK_ID,
+ FUNCTION_BLOCK_ID,
+
+ UNUSED_ID2,
+
+ VALUE_SYMTAB_BLOCK_ID,
+ METADATA_BLOCK_ID,
+ METADATA_ATTACHMENT_ID,
+
+ TYPE_BLOCK_ID_NEW,
+
+ USELIST_BLOCK_ID
+ };
+
+
+ /// MODULE blocks have a number of optional fields and subblocks.
+ enum ModuleCodes {
+ MODULE_CODE_VERSION = 1, // VERSION: [version#]
+ MODULE_CODE_TRIPLE = 2, // TRIPLE: [strchr x N]
+ MODULE_CODE_DATALAYOUT = 3, // DATALAYOUT: [strchr x N]
+ MODULE_CODE_ASM = 4, // ASM: [strchr x N]
+ MODULE_CODE_SECTIONNAME = 5, // SECTIONNAME: [strchr x N]
+ MODULE_CODE_DEPLIB = 6, // DEPLIB: [strchr x N]
+
+ // GLOBALVAR: [pointer type, isconst, initid,
+ // linkage, alignment, section, visibility, threadlocal]
+ MODULE_CODE_GLOBALVAR = 7,
+
+ // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
+ // section, visibility, gc, unnamed_addr]
+ MODULE_CODE_FUNCTION = 8,
+
+ // ALIAS: [alias type, aliasee val#, linkage, visibility]
+ MODULE_CODE_ALIAS = 9,
+
+ /// MODULE_CODE_PURGEVALS: [numvals]
+ MODULE_CODE_PURGEVALS = 10,
+
+ MODULE_CODE_GCNAME = 11 // GCNAME: [strchr x N]
+ };
+
+ /// PARAMATTR blocks have code for defining a parameter attribute set.
+ enum AttributeCodes {
+ PARAMATTR_CODE_ENTRY = 1 // ENTRY: [paramidx0, attr0, paramidx1, attr1...]
+ };
+
+ /// TYPE blocks have codes for each type primitive they use.
+ enum TypeCodes {
+ TYPE_CODE_NUMENTRY = 1, // NUMENTRY: [numentries]
+
+ // Type Codes
+ TYPE_CODE_VOID = 2, // VOID
+ TYPE_CODE_FLOAT = 3, // FLOAT
+ TYPE_CODE_DOUBLE = 4, // DOUBLE
+ TYPE_CODE_LABEL = 5, // LABEL
+ TYPE_CODE_OPAQUE = 6, // OPAQUE
+ TYPE_CODE_INTEGER = 7, // INTEGER: [width]
+ TYPE_CODE_POINTER = 8, // POINTER: [pointee type]
+
+ TYPE_CODE_FUNCTION_OLD = 9, // FUNCTION: [vararg, attrid, retty,
+ // paramty x N]
+
+ TYPE_CODE_HALF = 10, // HALF
+
+ TYPE_CODE_ARRAY = 11, // ARRAY: [numelts, eltty]
+ TYPE_CODE_VECTOR = 12, // VECTOR: [numelts, eltty]
+
+ // These are not with the other floating point types because they're
+ // a late addition, and putting them in the right place breaks
+ // binary compatibility.
+ TYPE_CODE_X86_FP80 = 13, // X86 LONG DOUBLE
+ TYPE_CODE_FP128 = 14, // LONG DOUBLE (112 bit mantissa)
+ TYPE_CODE_PPC_FP128= 15, // PPC LONG DOUBLE (2 doubles)
+
+ TYPE_CODE_METADATA = 16, // METADATA
+
+ TYPE_CODE_X86_MMX = 17, // X86 MMX
+
+ TYPE_CODE_STRUCT_ANON = 18, // STRUCT_ANON: [ispacked, eltty x N]
+ TYPE_CODE_STRUCT_NAME = 19, // STRUCT_NAME: [strchr x N]
+ TYPE_CODE_STRUCT_NAMED = 20,// STRUCT_NAMED: [ispacked, eltty x N]
+
+ TYPE_CODE_FUNCTION = 21 // FUNCTION: [vararg, retty, paramty x N]
+ };
+
+ // The type symbol table only has one code (TST_ENTRY_CODE).
+ enum TypeSymtabCodes {
+ TST_CODE_ENTRY = 1 // TST_ENTRY: [typeid, namechar x N]
+ };
+
+ // The value symbol table only has one code (VST_ENTRY_CODE).
+ enum ValueSymtabCodes {
+ VST_CODE_ENTRY = 1, // VST_ENTRY: [valid, namechar x N]
+ VST_CODE_BBENTRY = 2 // VST_BBENTRY: [bbid, namechar x N]
+ };
+
+ enum MetadataCodes {
+ METADATA_STRING = 1, // MDSTRING: [values]
+ // 2 is unused.
+ // 3 is unused.
+ METADATA_NAME = 4, // STRING: [values]
+ // 5 is unused.
+ METADATA_KIND = 6, // [n x [id, name]]
+ // 7 is unused.
+ METADATA_NODE = 8, // NODE: [n x (type num, value num)]
+ METADATA_FN_NODE = 9, // FN_NODE: [n x (type num, value num)]
+ METADATA_NAMED_NODE = 10, // NAMED_NODE: [n x mdnodes]
+ METADATA_ATTACHMENT = 11 // [m x [value, [n x [id, mdnode]]]
+ };
+ // The constants block (CONSTANTS_BLOCK_ID) describes emission for each
+ // constant and maintains an implicit current type value.
+ enum ConstantsCodes {
+ CST_CODE_SETTYPE = 1, // SETTYPE: [typeid]
+ CST_CODE_NULL = 2, // NULL
+ CST_CODE_UNDEF = 3, // UNDEF
+ CST_CODE_INTEGER = 4, // INTEGER: [intval]
+ CST_CODE_WIDE_INTEGER = 5, // WIDE_INTEGER: [n x intval]
+ CST_CODE_FLOAT = 6, // FLOAT: [fpval]
+ CST_CODE_AGGREGATE = 7, // AGGREGATE: [n x value number]
+ CST_CODE_STRING = 8, // STRING: [values]
+ CST_CODE_CSTRING = 9, // CSTRING: [values]
+ CST_CODE_CE_BINOP = 10, // CE_BINOP: [opcode, opval, opval]
+ CST_CODE_CE_CAST = 11, // CE_CAST: [opcode, opty, opval]
+ CST_CODE_CE_GEP = 12, // CE_GEP: [n x operands]
+ CST_CODE_CE_SELECT = 13, // CE_SELECT: [opval, opval, opval]
+ CST_CODE_CE_EXTRACTELT = 14, // CE_EXTRACTELT: [opty, opval, opval]
+ CST_CODE_CE_INSERTELT = 15, // CE_INSERTELT: [opval, opval, opval]
+ CST_CODE_CE_SHUFFLEVEC = 16, // CE_SHUFFLEVEC: [opval, opval, opval]
+ CST_CODE_CE_CMP = 17, // CE_CMP: [opty, opval, opval, pred]
+ CST_CODE_INLINEASM_OLD = 18, // INLINEASM: [sideeffect|alignstack,
+ // asmstr,conststr]
+ CST_CODE_CE_SHUFVEC_EX = 19, // SHUFVEC_EX: [opty, opval, opval, opval]
+ CST_CODE_CE_INBOUNDS_GEP = 20,// INBOUNDS_GEP: [n x operands]
+ CST_CODE_BLOCKADDRESS = 21, // CST_CODE_BLOCKADDRESS [fnty, fnval, bb#]
+ CST_CODE_DATA = 22, // DATA: [n x elements]
+ CST_CODE_INLINEASM = 23 // INLINEASM: [sideeffect|alignstack|
+ // asmdialect,asmstr,conststr]
+ };
+
+ /// CastOpcodes - These are values used in the bitcode files to encode which
+ /// cast a CST_CODE_CE_CAST or a XXX refers to. The values of these enums
+ /// have no fixed relation to the LLVM IR enum values. Changing these will
+ /// break compatibility with old files.
+ enum CastOpcodes {
+ CAST_TRUNC = 0,
+ CAST_ZEXT = 1,
+ CAST_SEXT = 2,
+ CAST_FPTOUI = 3,
+ CAST_FPTOSI = 4,
+ CAST_UITOFP = 5,
+ CAST_SITOFP = 6,
+ CAST_FPTRUNC = 7,
+ CAST_FPEXT = 8,
+ CAST_PTRTOINT = 9,
+ CAST_INTTOPTR = 10,
+ CAST_BITCAST = 11
+ };
+
+ /// BinaryOpcodes - These are values used in the bitcode files to encode which
+ /// binop a CST_CODE_CE_BINOP or a XXX refers to. The values of these enums
+ /// have no fixed relation to the LLVM IR enum values. Changing these will
+ /// break compatibility with old files.
+ enum BinaryOpcodes {
+ BINOP_ADD = 0,
+ BINOP_SUB = 1,
+ BINOP_MUL = 2,
+ BINOP_UDIV = 3,
+ BINOP_SDIV = 4, // overloaded for FP
+ BINOP_UREM = 5,
+ BINOP_SREM = 6, // overloaded for FP
+ BINOP_SHL = 7,
+ BINOP_LSHR = 8,
+ BINOP_ASHR = 9,
+ BINOP_AND = 10,
+ BINOP_OR = 11,
+ BINOP_XOR = 12
+ };
+
+ /// These are values used in the bitcode files to encode AtomicRMW operations.
+ /// The values of these enums have no fixed relation to the LLVM IR enum
+ /// values. Changing these will break compatibility with old files.
+ enum RMWOperations {
+ RMW_XCHG = 0,
+ RMW_ADD = 1,
+ RMW_SUB = 2,
+ RMW_AND = 3,
+ RMW_NAND = 4,
+ RMW_OR = 5,
+ RMW_XOR = 6,
+ RMW_MAX = 7,
+ RMW_MIN = 8,
+ RMW_UMAX = 9,
+ RMW_UMIN = 10
+ };
+
+ /// OverflowingBinaryOperatorOptionalFlags - Flags for serializing
+ /// OverflowingBinaryOperator's SubclassOptionalData contents.
+ enum OverflowingBinaryOperatorOptionalFlags {
+ OBO_NO_UNSIGNED_WRAP = 0,
+ OBO_NO_SIGNED_WRAP = 1
+ };
+
+ /// PossiblyExactOperatorOptionalFlags - Flags for serializing
+ /// PossiblyExactOperator's SubclassOptionalData contents.
+ enum PossiblyExactOperatorOptionalFlags {
+ PEO_EXACT = 0
+ };
+
+ /// Encoded AtomicOrdering values.
+ enum AtomicOrderingCodes {
+ ORDERING_NOTATOMIC = 0,
+ ORDERING_UNORDERED = 1,
+ ORDERING_MONOTONIC = 2,
+ ORDERING_ACQUIRE = 3,
+ ORDERING_RELEASE = 4,
+ ORDERING_ACQREL = 5,
+ ORDERING_SEQCST = 6
+ };
+
+ /// Encoded SynchronizationScope values.
+ enum AtomicSynchScopeCodes {
+ SYNCHSCOPE_SINGLETHREAD = 0,
+ SYNCHSCOPE_CROSSTHREAD = 1
+ };
+
+ // The function body block (FUNCTION_BLOCK_ID) describes function bodies. It
+ // can contain a constant block (CONSTANTS_BLOCK_ID).
+ enum FunctionCodes {
+ FUNC_CODE_DECLAREBLOCKS = 1, // DECLAREBLOCKS: [n]
+
+ FUNC_CODE_INST_BINOP = 2, // BINOP: [opcode, ty, opval, opval]
+ FUNC_CODE_INST_CAST = 3, // CAST: [opcode, ty, opty, opval]
+ FUNC_CODE_INST_GEP = 4, // GEP: [n x operands]
+ FUNC_CODE_INST_SELECT = 5, // SELECT: [ty, opval, opval, opval]
+ FUNC_CODE_INST_EXTRACTELT = 6, // EXTRACTELT: [opty, opval, opval]
+ FUNC_CODE_INST_INSERTELT = 7, // INSERTELT: [ty, opval, opval, opval]
+ FUNC_CODE_INST_SHUFFLEVEC = 8, // SHUFFLEVEC: [ty, opval, opval, opval]
+ FUNC_CODE_INST_CMP = 9, // CMP: [opty, opval, opval, pred]
+
+ FUNC_CODE_INST_RET = 10, // RET: [opty,opval<both optional>]
+ FUNC_CODE_INST_BR = 11, // BR: [bb#, bb#, cond] or [bb#]
+ FUNC_CODE_INST_SWITCH = 12, // SWITCH: [opty, op0, op1, ...]
+ FUNC_CODE_INST_INVOKE = 13, // INVOKE: [attr, fnty, op0,op1, ...]
+ // 14 is unused.
+ FUNC_CODE_INST_UNREACHABLE = 15, // UNREACHABLE
+
+ FUNC_CODE_INST_PHI = 16, // PHI: [ty, val0,bb0, ...]
+ // 17 is unused.
+ // 18 is unused.
+ FUNC_CODE_INST_ALLOCA = 19, // ALLOCA: [instty, op, align]
+ FUNC_CODE_INST_LOAD = 20, // LOAD: [opty, op, align, vol]
+ // 21 is unused.
+ // 22 is unused.
+ FUNC_CODE_INST_VAARG = 23, // VAARG: [valistty, valist, instty]
+ // This store code encodes the pointer type, rather than the value type
+ // this is so information only available in the pointer type (e.g. address
+ // spaces) is retained.
+ FUNC_CODE_INST_STORE = 24, // STORE: [ptrty,ptr,val, align, vol]
+ // 25 is unused.
+ FUNC_CODE_INST_EXTRACTVAL = 26, // EXTRACTVAL: [n x operands]
+ FUNC_CODE_INST_INSERTVAL = 27, // INSERTVAL: [n x operands]
+ // fcmp/icmp returning Int1TY or vector of Int1Ty. Same as CMP, exists to
+ // support legacy vicmp/vfcmp instructions.
+ FUNC_CODE_INST_CMP2 = 28, // CMP2: [opty, opval, opval, pred]
+ // new select on i1 or [N x i1]
+ FUNC_CODE_INST_VSELECT = 29, // VSELECT: [ty,opval,opval,predty,pred]
+ FUNC_CODE_INST_INBOUNDS_GEP= 30, // INBOUNDS_GEP: [n x operands]
+ FUNC_CODE_INST_INDIRECTBR = 31, // INDIRECTBR: [opty, op0, op1, ...]
+ // 32 is unused.
+ FUNC_CODE_DEBUG_LOC_AGAIN = 33, // DEBUG_LOC_AGAIN
+
+ FUNC_CODE_INST_CALL = 34, // CALL: [attr, fnty, fnid, args...]
+
+ FUNC_CODE_DEBUG_LOC = 35, // DEBUG_LOC: [Line,Col,ScopeVal, IAVal]
+ FUNC_CODE_INST_FENCE = 36, // FENCE: [ordering, synchscope]
+ FUNC_CODE_INST_CMPXCHG = 37, // CMPXCHG: [ptrty,ptr,cmp,new, align, vol,
+ // ordering, synchscope]
+ FUNC_CODE_INST_ATOMICRMW = 38, // ATOMICRMW: [ptrty,ptr,val, operation,
+ // align, vol,
+ // ordering, synchscope]
+ FUNC_CODE_INST_RESUME = 39, // RESUME: [opval]
+ FUNC_CODE_INST_LANDINGPAD = 40, // LANDINGPAD: [ty,val,val,num,id0,val0...]
+ FUNC_CODE_INST_LOADATOMIC = 41, // LOAD: [opty, op, align, vol,
+ // ordering, synchscope]
+ FUNC_CODE_INST_STOREATOMIC = 42 // STORE: [ptrty,ptr,val, align, vol
+ // ordering, synchscope]
+ };
+
+ enum UseListCodes {
+ USELIST_CODE_ENTRY = 1 // USELIST_CODE_ENTRY: TBD.
+ };
+} // End bitc namespace
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Bitcode/ReaderWriter.h b/include/llvm/Bitcode/ReaderWriter.h
new file mode 100644
index 00000000000..dd96b043fc9
--- /dev/null
+++ b/include/llvm/Bitcode/ReaderWriter.h
@@ -0,0 +1,154 @@
+//===-- llvm/Bitcode/ReaderWriter.h - Bitcode reader/writers ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header defines interfaces to read and write LLVM bitcode files/streams.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_BITCODE_H
+#define LLVM_BITCODE_H
+
+#include <string>
+
+namespace llvm {
+ class BitstreamWriter;
+ class MemoryBuffer;
+ class DataStreamer;
+ class LLVMContext;
+ class Module;
+ class ModulePass;
+ class raw_ostream;
+
+ /// getLazyBitcodeModule - Read the header of the specified bitcode buffer
+ /// and prepare for lazy deserialization of function bodies. If successful,
+ /// this takes ownership of 'buffer' and returns a non-null pointer. On
+ /// error, this returns null, *does not* take ownership of Buffer, and fills
+ /// in *ErrMsg with an error description if ErrMsg is non-null.
+ Module *getLazyBitcodeModule(MemoryBuffer *Buffer,
+ LLVMContext &Context,
+ std::string *ErrMsg = 0);
+
+ /// getStreamedBitcodeModule - Read the header of the specified stream
+ /// and prepare for lazy deserialization and streaming of function bodies.
+ /// On error, this returns null, and fills in *ErrMsg with an error
+ /// description if ErrMsg is non-null.
+ Module *getStreamedBitcodeModule(const std::string &name,
+ DataStreamer *streamer,
+ LLVMContext &Context,
+ std::string *ErrMsg = 0);
+
+ /// getBitcodeTargetTriple - Read the header of the specified bitcode
+ /// buffer and extract just the triple information. If successful,
+ /// this returns a string and *does not* take ownership
+ /// of 'buffer'. On error, this returns "", and fills in *ErrMsg
+ /// if ErrMsg is non-null.
+ std::string getBitcodeTargetTriple(MemoryBuffer *Buffer,
+ LLVMContext &Context,
+ std::string *ErrMsg = 0);
+
+ /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
+ /// If an error occurs, this returns null and fills in *ErrMsg if it is
+ /// non-null. This method *never* takes ownership of Buffer.
+ Module *ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext &Context,
+ std::string *ErrMsg = 0);
+
+ /// WriteBitcodeToFile - Write the specified module to the specified
+ /// raw output stream. For streams where it matters, the given stream
+ /// should be in "binary" mode.
+ void WriteBitcodeToFile(const Module *M, raw_ostream &Out);
+
+ /// createBitcodeWriterPass - Create and return a pass that writes the module
+ /// to the specified ostream.
+ ModulePass *createBitcodeWriterPass(raw_ostream &Str);
+
+
+ /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
+ /// for an LLVM IR bitcode wrapper.
+ ///
+ inline bool isBitcodeWrapper(const unsigned char *BufPtr,
+ const unsigned char *BufEnd) {
+ // See if you can find the hidden message in the magic bytes :-).
+ // (Hint: it's a little-endian encoding.)
+ return BufPtr != BufEnd &&
+ BufPtr[0] == 0xDE &&
+ BufPtr[1] == 0xC0 &&
+ BufPtr[2] == 0x17 &&
+ BufPtr[3] == 0x0B;
+ }
+
+ /// isRawBitcode - Return true if the given bytes are the magic bytes for
+ /// raw LLVM IR bitcode (without a wrapper).
+ ///
+ inline bool isRawBitcode(const unsigned char *BufPtr,
+ const unsigned char *BufEnd) {
+ // These bytes sort of have a hidden message, but it's not in
+ // little-endian this time, and it's a little redundant.
+ return BufPtr != BufEnd &&
+ BufPtr[0] == 'B' &&
+ BufPtr[1] == 'C' &&
+ BufPtr[2] == 0xc0 &&
+ BufPtr[3] == 0xde;
+ }
+
+ /// isBitcode - Return true if the given bytes are the magic bytes for
+ /// LLVM IR bitcode, either with or without a wrapper.
+ ///
+ inline bool isBitcode(const unsigned char *BufPtr,
+ const unsigned char *BufEnd) {
+ return isBitcodeWrapper(BufPtr, BufEnd) ||
+ isRawBitcode(BufPtr, BufEnd);
+ }
+
+ /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
+ /// header for padding or other reasons. The format of this header is:
+ ///
+ /// struct bc_header {
+ /// uint32_t Magic; // 0x0B17C0DE
+ /// uint32_t Version; // Version, currently always 0.
+ /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
+ /// uint32_t BitcodeSize; // Size of traditional bitcode file.
+ /// ... potentially other gunk ...
+ /// };
+ ///
+ /// This function is called when we find a file with a matching magic number.
+ /// In this case, skip down to the subsection of the file that is actually a
+ /// BC file.
+ /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
+ /// contain the whole bitcode file.
+ inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
+ const unsigned char *&BufEnd,
+ bool VerifyBufferSize) {
+ enum {
+ KnownHeaderSize = 4*4, // Size of header we read.
+ OffsetField = 2*4, // Offset in bytes to Offset field.
+ SizeField = 3*4 // Offset in bytes to Size field.
+ };
+
+ // Must contain the header!
+ if (BufEnd-BufPtr < KnownHeaderSize) return true;
+
+ unsigned Offset = ( BufPtr[OffsetField ] |
+ (BufPtr[OffsetField+1] << 8) |
+ (BufPtr[OffsetField+2] << 16) |
+ (BufPtr[OffsetField+3] << 24));
+ unsigned Size = ( BufPtr[SizeField ] |
+ (BufPtr[SizeField +1] << 8) |
+ (BufPtr[SizeField +2] << 16) |
+ (BufPtr[SizeField +3] << 24));
+
+ // Verify that Offset+Size fits in the file.
+ if (VerifyBufferSize && Offset+Size > unsigned(BufEnd-BufPtr))
+ return true;
+ BufPtr += Offset;
+ BufEnd = BufPtr+Size;
+ return false;
+ }
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CMakeLists.txt b/include/llvm/CMakeLists.txt
new file mode 100644
index 00000000000..f8cb4250584
--- /dev/null
+++ b/include/llvm/CMakeLists.txt
@@ -0,0 +1,19 @@
+set(LLVM_TARGET_DEFINITIONS Intrinsics.td)
+
+tablegen(LLVM Intrinsics.gen -gen-intrinsic)
+
+add_custom_target(intrinsics_gen ALL
+ DEPENDS ${llvm_builded_incs_dir}/Intrinsics.gen)
+set_target_properties(intrinsics_gen PROPERTIES FOLDER "Tablegenning")
+
+if( MSVC_IDE OR XCODE )
+ # Creates a dummy target containing all headers for the benefit of
+ # Visual Studio users.
+ file(GLOB_RECURSE headers *.h)
+ add_td_sources(headers)
+ add_library(llvm_headers_do_not_build EXCLUDE_FROM_ALL
+ # We need at least one source file:
+ ${LLVM_MAIN_SRC_DIR}/lib/Transforms/Hello/Hello.cpp
+ ${headers})
+ set_target_properties(llvm_headers_do_not_build PROPERTIES FOLDER "Misc")
+endif()
diff --git a/include/llvm/CallGraphSCCPass.h b/include/llvm/CallGraphSCCPass.h
new file mode 100644
index 00000000000..7154aa3259d
--- /dev/null
+++ b/include/llvm/CallGraphSCCPass.h
@@ -0,0 +1,104 @@
+//===- CallGraphSCCPass.h - Pass that operates BU on call graph -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the CallGraphSCCPass class, which is used for passes which
+// are implemented as bottom-up traversals on the call graph. Because there may
+// be cycles in the call graph, passes of this type operate on the call-graph in
+// SCC order: that is, they process function bottom-up, except for recursive
+// functions, which they process all at once.
+//
+// These passes are inherently interprocedural, and are required to keep the
+// call graph up-to-date if they do anything which could modify it.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CALL_GRAPH_SCC_PASS_H
+#define LLVM_CALL_GRAPH_SCC_PASS_H
+
+#include "llvm/Pass.h"
+#include "llvm/Analysis/CallGraph.h"
+
+namespace llvm {
+
+class CallGraphNode;
+class CallGraph;
+class PMStack;
+class CallGraphSCC;
+
+class CallGraphSCCPass : public Pass {
+public:
+ explicit CallGraphSCCPass(char &pid) : Pass(PT_CallGraphSCC, pid) {}
+
+ /// createPrinterPass - Get a pass that prints the Module
+ /// corresponding to a CallGraph.
+ Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
+
+ /// doInitialization - This method is called before the SCC's of the program
+ /// has been processed, allowing the pass to do initialization as necessary.
+ virtual bool doInitialization(CallGraph &CG) {
+ return false;
+ }
+
+ /// runOnSCC - This method should be implemented by the subclass to perform
+ /// whatever action is necessary for the specified SCC. Note that
+ /// non-recursive (or only self-recursive) functions will have an SCC size of
+ /// 1, where recursive portions of the call graph will have SCC size > 1.
+ ///
+ /// SCC passes that add or delete functions to the SCC are required to update
+ /// the SCC list, otherwise stale pointers may be dereferenced.
+ ///
+ virtual bool runOnSCC(CallGraphSCC &SCC) = 0;
+
+ /// doFinalization - This method is called after the SCC's of the program has
+ /// been processed, allowing the pass to do final cleanup as necessary.
+ virtual bool doFinalization(CallGraph &CG) {
+ return false;
+ }
+
+ /// Assign pass manager to manager this pass
+ virtual void assignPassManager(PMStack &PMS,
+ PassManagerType PMT);
+
+ /// Return what kind of Pass Manager can manage this pass.
+ virtual PassManagerType getPotentialPassManagerType() const {
+ return PMT_CallGraphPassManager;
+ }
+
+ /// getAnalysisUsage - For this class, we declare that we require and preserve
+ /// the call graph. If the derived class implements this method, it should
+ /// always explicitly call the implementation here.
+ virtual void getAnalysisUsage(AnalysisUsage &Info) const;
+};
+
+/// CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
+class CallGraphSCC {
+ void *Context; // The CGPassManager object that is vending this.
+ std::vector<CallGraphNode*> Nodes;
+public:
+ CallGraphSCC(void *context) : Context(context) {}
+
+ void initialize(CallGraphNode*const*I, CallGraphNode*const*E) {
+ Nodes.assign(I, E);
+ }
+
+ bool isSingular() const { return Nodes.size() == 1; }
+ unsigned size() const { return Nodes.size(); }
+
+ /// ReplaceNode - This informs the SCC and the pass manager that the specified
+ /// Old node has been deleted, and New is to be used in its place.
+ void ReplaceNode(CallGraphNode *Old, CallGraphNode *New);
+
+ typedef std::vector<CallGraphNode*>::const_iterator iterator;
+ iterator begin() const { return Nodes.begin(); }
+ iterator end() const { return Nodes.end(); }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CallingConv.h b/include/llvm/CallingConv.h
new file mode 100644
index 00000000000..4c5ee626709
--- /dev/null
+++ b/include/llvm/CallingConv.h
@@ -0,0 +1,103 @@
+//===-- llvm/CallingConv.h - LLVM Calling Conventions -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines LLVM's set of calling conventions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CALLINGCONV_H
+#define LLVM_CALLINGCONV_H
+
+namespace llvm {
+
+/// CallingConv Namespace - This namespace contains an enum with a value for
+/// the well-known calling conventions.
+///
+namespace CallingConv {
+ /// A set of enums which specify the assigned numeric values for known llvm
+ /// calling conventions.
+ /// @brief LLVM Calling Convention Representation
+ enum ID {
+ /// C - The default llvm calling convention, compatible with C. This
+ /// convention is the only calling convention that supports varargs calls.
+ /// As with typical C calling conventions, the callee/caller have to
+ /// tolerate certain amounts of prototype mismatch.
+ C = 0,
+
+ // Generic LLVM calling conventions. None of these calling conventions
+ // support varargs calls, and all assume that the caller and callee
+ // prototype exactly match.
+
+ /// Fast - This calling convention attempts to make calls as fast as
+ /// possible (e.g. by passing things in registers).
+ Fast = 8,
+
+ // Cold - This calling convention attempts to make code in the caller as
+ // efficient as possible under the assumption that the call is not commonly
+ // executed. As such, these calls often preserve all registers so that the
+ // call does not break any live ranges in the caller side.
+ Cold = 9,
+
+ // GHC - Calling convention used by the Glasgow Haskell Compiler (GHC).
+ GHC = 10,
+
+ // Target - This is the start of the target-specific calling conventions,
+ // e.g. fastcall and thiscall on X86.
+ FirstTargetCC = 64,
+
+ /// X86_StdCall - stdcall is the calling conventions mostly used by the
+ /// Win32 API. It is basically the same as the C convention with the
+ /// difference in that the callee is responsible for popping the arguments
+ /// from the stack.
+ X86_StdCall = 64,
+
+ /// X86_FastCall - 'fast' analog of X86_StdCall. Passes first two arguments
+ /// in ECX:EDX registers, others - via stack. Callee is responsible for
+ /// stack cleaning.
+ X86_FastCall = 65,
+
+ /// ARM_APCS - ARM Procedure Calling Standard calling convention (obsolete,
+ /// but still used on some targets).
+ ARM_APCS = 66,
+
+ /// ARM_AAPCS - ARM Architecture Procedure Calling Standard calling
+ /// convention (aka EABI). Soft float variant.
+ ARM_AAPCS = 67,
+
+ /// ARM_AAPCS_VFP - Same as ARM_AAPCS, but uses hard floating point ABI.
+ ARM_AAPCS_VFP = 68,
+
+ /// MSP430_INTR - Calling convention used for MSP430 interrupt routines.
+ MSP430_INTR = 69,
+
+ /// X86_ThisCall - Similar to X86_StdCall. Passes first argument in ECX,
+ /// others via stack. Callee is responsible for stack cleaning. MSVC uses
+ /// this by default for methods in its ABI.
+ X86_ThisCall = 70,
+
+ /// PTX_Kernel - Call to a PTX kernel.
+ /// Passes all arguments in parameter space.
+ PTX_Kernel = 71,
+
+ /// PTX_Device - Call to a PTX device function.
+ /// Passes all arguments in register or parameter space.
+ PTX_Device = 72,
+
+ /// MBLAZE_INTR - Calling convention used for MBlaze interrupt routines.
+ MBLAZE_INTR = 73,
+
+ /// MBLAZE_INTR - Calling convention used for MBlaze interrupt support
+ /// routines (i.e. GCC's save_volatiles attribute).
+ MBLAZE_SVOL = 74
+ };
+} // End CallingConv namespace
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/Analysis.h b/include/llvm/CodeGen/Analysis.h
new file mode 100644
index 00000000000..0b609ed6586
--- /dev/null
+++ b/include/llvm/CodeGen/Analysis.h
@@ -0,0 +1,97 @@
+//===- CodeGen/Analysis.h - CodeGen LLVM IR Analysis Utilities --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares several CodeGen-specific LLVM IR analysis utilties.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_ANALYSIS_H
+#define LLVM_CODEGEN_ANALYSIS_H
+
+#include "llvm/Instructions.h"
+#include "llvm/InlineAsm.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/CodeGen/ValueTypes.h"
+#include "llvm/CodeGen/ISDOpcodes.h"
+#include "llvm/Support/CallSite.h"
+
+namespace llvm {
+
+class GlobalVariable;
+class TargetLowering;
+class SDNode;
+class SDValue;
+class SelectionDAG;
+
+/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
+/// of insertvalue or extractvalue indices that identify a member, return
+/// the linearized index of the start of the member.
+///
+unsigned ComputeLinearIndex(Type *Ty,
+ const unsigned *Indices,
+ const unsigned *IndicesEnd,
+ unsigned CurIndex = 0);
+
+inline unsigned ComputeLinearIndex(Type *Ty,
+ ArrayRef<unsigned> Indices,
+ unsigned CurIndex = 0) {
+ return ComputeLinearIndex(Ty, Indices.begin(), Indices.end(), CurIndex);
+}
+
+/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
+/// EVTs that represent all the individual underlying
+/// non-aggregate types that comprise it.
+///
+/// If Offsets is non-null, it points to a vector to be filled in
+/// with the in-memory offsets of each of the individual values.
+///
+void ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
+ SmallVectorImpl<EVT> &ValueVTs,
+ SmallVectorImpl<uint64_t> *Offsets = 0,
+ uint64_t StartingOffset = 0);
+
+/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
+GlobalVariable *ExtractTypeInfo(Value *V);
+
+/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
+/// processed uses a memory 'm' constraint.
+bool hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
+ const TargetLowering &TLI);
+
+/// getFCmpCondCode - Return the ISD condition code corresponding to
+/// the given LLVM IR floating-point condition code. This includes
+/// consideration of global floating-point math flags.
+///
+ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred);
+
+/// getFCmpCodeWithoutNaN - Given an ISD condition code comparing floats,
+/// return the equivalent code if we're allowed to assume that NaNs won't occur.
+ISD::CondCode getFCmpCodeWithoutNaN(ISD::CondCode CC);
+
+/// getICmpCondCode - Return the ISD condition code corresponding to
+/// the given LLVM IR integer condition code.
+///
+ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred);
+
+/// Test if the given instruction is in a position to be optimized
+/// with a tail-call. This roughly means that it's in a block with
+/// a return and there's nothing that needs to be scheduled
+/// between it and the return.
+///
+/// This function only tests target-independent requirements.
+bool isInTailCallPosition(ImmutableCallSite CS, Attributes CalleeRetAttr,
+ const TargetLowering &TLI);
+
+bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
+ SDValue &Chain, const TargetLowering &TLI);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/AsmPrinter.h b/include/llvm/CodeGen/AsmPrinter.h
new file mode 100644
index 00000000000..2920675231b
--- /dev/null
+++ b/include/llvm/CodeGen/AsmPrinter.h
@@ -0,0 +1,491 @@
+//===-- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains a class to be used as the base class for target specific
+// asm writers. This class primarily handles common functionality used by
+// all asm writers.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_ASMPRINTER_H
+#define LLVM_CODEGEN_ASMPRINTER_H
+
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/InlineAsm.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+
+namespace llvm {
+ class BlockAddress;
+ class GCStrategy;
+ class Constant;
+ class GCMetadataPrinter;
+ class GlobalValue;
+ class GlobalVariable;
+ class MachineBasicBlock;
+ class MachineFunction;
+ class MachineInstr;
+ class MachineLocation;
+ class MachineLoopInfo;
+ class MachineLoop;
+ class MachineConstantPoolValue;
+ class MachineJumpTableInfo;
+ class MachineModuleInfo;
+ class MachineMove;
+ class MCAsmInfo;
+ class MCContext;
+ class MCSection;
+ class MCStreamer;
+ class MCSymbol;
+ class MDNode;
+ class DwarfDebug;
+ class DwarfException;
+ class Mangler;
+ class TargetLoweringObjectFile;
+ class TargetData;
+ class TargetMachine;
+
+ /// AsmPrinter - This class is intended to be used as a driving class for all
+ /// asm writers.
+ class AsmPrinter : public MachineFunctionPass {
+ public:
+ /// Target machine description.
+ ///
+ TargetMachine &TM;
+
+ /// Target Asm Printer information.
+ ///
+ const MCAsmInfo *MAI;
+
+ /// OutContext - This is the context for the output file that we are
+ /// streaming. This owns all of the global MC-related objects for the
+ /// generated translation unit.
+ MCContext &OutContext;
+
+ /// OutStreamer - This is the MCStreamer object for the file we are
+ /// generating. This contains the transient state for the current
+ /// translation unit that we are generating (such as the current section
+ /// etc).
+ MCStreamer &OutStreamer;
+
+ /// The current machine function.
+ const MachineFunction *MF;
+
+ /// MMI - This is a pointer to the current MachineModuleInfo.
+ MachineModuleInfo *MMI;
+
+ /// Name-mangler for global names.
+ ///
+ Mangler *Mang;
+
+ /// The symbol for the current function. This is recalculated at the
+ /// beginning of each call to runOnMachineFunction().
+ ///
+ MCSymbol *CurrentFnSym;
+
+ /// The symbol used to represent the start of the current function for the
+ /// purpose of calculating its size (e.g. using the .size directive). By
+ /// default, this is equal to CurrentFnSym.
+ MCSymbol *CurrentFnSymForSize;
+
+ private:
+ // GCMetadataPrinters - The garbage collection metadata printer table.
+ void *GCMetadataPrinters; // Really a DenseMap.
+
+ /// VerboseAsm - Emit comments in assembly output if this is true.
+ ///
+ bool VerboseAsm;
+ static char ID;
+
+ /// If VerboseAsm is set, a pointer to the loop info for this
+ /// function.
+ MachineLoopInfo *LI;
+
+ /// DD - If the target supports dwarf debug info, this pointer is non-null.
+ DwarfDebug *DD;
+
+ /// DE - If the target supports dwarf exception info, this pointer is
+ /// non-null.
+ DwarfException *DE;
+
+ protected:
+ explicit AsmPrinter(TargetMachine &TM, MCStreamer &Streamer);
+
+ public:
+ virtual ~AsmPrinter();
+
+ /// isVerbose - Return true if assembly output should contain comments.
+ ///
+ bool isVerbose() const { return VerboseAsm; }
+
+ /// getFunctionNumber - Return a unique ID for the current function.
+ ///
+ unsigned getFunctionNumber() const;
+
+ /// getObjFileLowering - Return information about object file lowering.
+ const TargetLoweringObjectFile &getObjFileLowering() const;
+
+ /// getTargetData - Return information about data layout.
+ const TargetData &getTargetData() const;
+
+ /// getCurrentSection() - Return the current section we are emitting to.
+ const MCSection *getCurrentSection() const;
+
+
+ //===------------------------------------------------------------------===//
+ // MachineFunctionPass Implementation.
+ //===------------------------------------------------------------------===//
+
+ /// getAnalysisUsage - Record analysis usage.
+ ///
+ void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ /// doInitialization - Set up the AsmPrinter when we are working on a new
+ /// module. If your pass overrides this, it must make sure to explicitly
+ /// call this implementation.
+ bool doInitialization(Module &M);
+
+ /// doFinalization - Shut down the asmprinter. If you override this in your
+ /// pass, you must make sure to call it explicitly.
+ bool doFinalization(Module &M);
+
+ /// runOnMachineFunction - Emit the specified function out to the
+ /// OutStreamer.
+ virtual bool runOnMachineFunction(MachineFunction &MF) {
+ SetupMachineFunction(MF);
+ EmitFunctionHeader();
+ EmitFunctionBody();
+ return false;
+ }
+
+ //===------------------------------------------------------------------===//
+ // Coarse grained IR lowering routines.
+ //===------------------------------------------------------------------===//
+
+ /// SetupMachineFunction - This should be called when a new MachineFunction
+ /// is being processed from runOnMachineFunction.
+ void SetupMachineFunction(MachineFunction &MF);
+
+ /// EmitFunctionHeader - This method emits the header for the current
+ /// function.
+ void EmitFunctionHeader();
+
+ /// EmitFunctionBody - This method emits the body and trailer for a
+ /// function.
+ void EmitFunctionBody();
+
+ void emitPrologLabel(const MachineInstr &MI);
+
+ enum CFIMoveType {
+ CFI_M_None,
+ CFI_M_EH,
+ CFI_M_Debug
+ };
+ CFIMoveType needsCFIMoves();
+
+ bool needsSEHMoves();
+
+ /// needsRelocationsForDwarfStringPool - Specifies whether the object format
+ /// expects to use relocations to refer to debug entries. Alternatively we
+ /// emit section offsets in bytes from the start of the string pool.
+ bool needsRelocationsForDwarfStringPool() const;
+
+ /// EmitConstantPool - Print to the current output stream assembly
+ /// representations of the constants in the constant pool MCP. This is
+ /// used to print out constants which have been "spilled to memory" by
+ /// the code generator.
+ ///
+ virtual void EmitConstantPool();
+
+ /// EmitJumpTableInfo - Print assembly representations of the jump tables
+ /// used by the current function to the current output stream.
+ ///
+ void EmitJumpTableInfo();
+
+ /// EmitGlobalVariable - Emit the specified global variable to the .s file.
+ virtual void EmitGlobalVariable(const GlobalVariable *GV);
+
+ /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
+ /// special global used by LLVM. If so, emit it and return true, otherwise
+ /// do nothing and return false.
+ bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
+
+ /// EmitAlignment - Emit an alignment directive to the specified power of
+ /// two boundary. For example, if you pass in 3 here, you will get an 8
+ /// byte alignment. If a global value is specified, and if that global has
+ /// an explicit alignment requested, it will override the alignment request
+ /// if required for correctness.
+ ///
+ void EmitAlignment(unsigned NumBits, const GlobalValue *GV = 0) const;
+
+ /// EmitBasicBlockStart - This method prints the label for the specified
+ /// MachineBasicBlock, an alignment (if present) and a comment describing
+ /// it if appropriate.
+ void EmitBasicBlockStart(const MachineBasicBlock *MBB) const;
+
+ /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
+ void EmitGlobalConstant(const Constant *CV, unsigned AddrSpace = 0);
+
+
+ //===------------------------------------------------------------------===//
+ // Overridable Hooks
+ //===------------------------------------------------------------------===//
+
+ // Targets can, or in the case of EmitInstruction, must implement these to
+ // customize output.
+
+ /// EmitStartOfAsmFile - This virtual method can be overridden by targets
+ /// that want to emit something at the start of their file.
+ virtual void EmitStartOfAsmFile(Module &) {}
+
+ /// EmitEndOfAsmFile - This virtual method can be overridden by targets that
+ /// want to emit something at the end of their file.
+ virtual void EmitEndOfAsmFile(Module &) {}
+
+ /// EmitFunctionBodyStart - Targets can override this to emit stuff before
+ /// the first basic block in the function.
+ virtual void EmitFunctionBodyStart() {}
+
+ /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
+ /// the last basic block in the function.
+ virtual void EmitFunctionBodyEnd() {}
+
+ /// EmitInstruction - Targets should implement this to emit instructions.
+ virtual void EmitInstruction(const MachineInstr *) {
+ llvm_unreachable("EmitInstruction not implemented");
+ }
+
+ virtual void EmitFunctionEntryLabel();
+
+ virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
+
+ /// EmitXXStructor - Targets can override this to change how global
+ /// constants that are part of a C++ static/global constructor list are
+ /// emitted.
+ virtual void EmitXXStructor(const Constant *CV) {
+ EmitGlobalConstant(CV);
+ }
+
+ /// isBlockOnlyReachableByFallthough - Return true if the basic block has
+ /// exactly one predecessor and the control transfer mechanism between
+ /// the predecessor and this block is a fall-through.
+ virtual bool
+ isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
+
+ //===------------------------------------------------------------------===//
+ // Symbol Lowering Routines.
+ //===------------------------------------------------------------------===//
+ public:
+
+ /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
+ /// temporary label with the specified stem and unique ID.
+ MCSymbol *GetTempSymbol(StringRef Name, unsigned ID) const;
+
+ /// GetTempSymbol - Return an assembler temporary label with the specified
+ /// stem.
+ MCSymbol *GetTempSymbol(StringRef Name) const;
+
+
+ /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
+ /// global value name as its base, with the specified suffix, and where the
+ /// symbol is forced to have private linkage if ForcePrivate is true.
+ MCSymbol *GetSymbolWithGlobalValueBase(const GlobalValue *GV,
+ StringRef Suffix,
+ bool ForcePrivate = true) const;
+
+ /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
+ /// ExternalSymbol.
+ MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
+
+ /// GetCPISymbol - Return the symbol for the specified constant pool entry.
+ MCSymbol *GetCPISymbol(unsigned CPID) const;
+
+ /// GetJTISymbol - Return the symbol for the specified jump table entry.
+ MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
+
+ /// GetJTSetSymbol - Return the symbol for the specified jump table .set
+ /// FIXME: privatize to AsmPrinter.
+ MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
+
+ /// GetBlockAddressSymbol - Return the MCSymbol used to satisfy BlockAddress
+ /// uses of the specified basic block.
+ MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
+ MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
+
+ //===------------------------------------------------------------------===//
+ // Emission Helper Routines.
+ //===------------------------------------------------------------------===//
+ public:
+ /// printOffset - This is just convenient handler for printing offsets.
+ void printOffset(int64_t Offset, raw_ostream &OS) const;
+
+ /// EmitInt8 - Emit a byte directive and value.
+ ///
+ void EmitInt8(int Value) const;
+
+ /// EmitInt16 - Emit a short directive and value.
+ ///
+ void EmitInt16(int Value) const;
+
+ /// EmitInt32 - Emit a long directive and value.
+ ///
+ void EmitInt32(int Value) const;
+
+ /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
+ /// in bytes of the directive is specified by Size and Hi/Lo specify the
+ /// labels. This implicitly uses .set if it is available.
+ void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
+ unsigned Size) const;
+
+ /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
+ /// where the size in bytes of the directive is specified by Size and Hi/Lo
+ /// specify the labels. This implicitly uses .set if it is available.
+ void EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
+ const MCSymbol *Lo, unsigned Size) const;
+
+ /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
+ /// where the size in bytes of the directive is specified by Size and Label
+ /// specifies the label. This implicitly uses .set if it is available.
+ void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
+ unsigned Size) const;
+
+ /// EmitLabelReference - Emit something like ".long Label"
+ /// where the size in bytes of the directive is specified by Size and Label
+ /// specifies the label.
+ void EmitLabelReference(const MCSymbol *Label, unsigned Size) const {
+ EmitLabelPlusOffset(Label, 0, Size);
+ }
+
+ //===------------------------------------------------------------------===//
+ // Dwarf Emission Helper Routines
+ //===------------------------------------------------------------------===//
+
+ /// EmitSLEB128 - emit the specified signed leb128 value.
+ void EmitSLEB128(int Value, const char *Desc = 0) const;
+
+ /// EmitULEB128 - emit the specified unsigned leb128 value.
+ void EmitULEB128(unsigned Value, const char *Desc = 0,
+ unsigned PadTo = 0) const;
+
+ /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value.
+ void EmitCFAByte(unsigned Val) const;
+
+ /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an
+ /// encoding. If verbose assembly output is enabled, we output comments
+ /// describing the encoding. Desc is a string saying what the encoding is
+ /// specifying (e.g. "LSDA").
+ void EmitEncodingByte(unsigned Val, const char *Desc = 0) const;
+
+ /// GetSizeOfEncodedValue - Return the size of the encoding in bytes.
+ unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
+
+ /// EmitReference - Emit a reference to a label with a specified encoding.
+ ///
+ void EmitReference(const MCSymbol *Sym, unsigned Encoding) const;
+ void EmitReference(const GlobalValue *GV, unsigned Encoding) const;
+
+ /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of
+ /// its section. This can be done with a special directive if the target
+ /// supports it (e.g. cygwin) or by emitting it as an offset from a label at
+ /// the start of the section.
+ ///
+ /// SectionLabel is a temporary label emitted at the start of the section
+ /// that Label lives in.
+ void EmitSectionOffset(const MCSymbol *Label,
+ const MCSymbol *SectionLabel) const;
+
+ /// getDebugValueLocation - Get location information encoded by DBG_VALUE
+ /// operands.
+ virtual MachineLocation getDebugValueLocation(const MachineInstr *MI) const;
+
+ /// getISAEncoding - Get the value for DW_AT_APPLE_isa. Zero if no isa
+ /// encoding specified.
+ virtual unsigned getISAEncoding() { return 0; }
+
+ /// EmitDwarfRegOp - Emit dwarf register operation.
+ virtual void EmitDwarfRegOp(const MachineLocation &MLoc) const;
+
+ //===------------------------------------------------------------------===//
+ // Dwarf Lowering Routines
+ //===------------------------------------------------------------------===//
+
+ /// EmitCFIFrameMove - Emit frame instruction to describe the layout of the
+ /// frame.
+ void EmitCFIFrameMove(const MachineMove &Move) const;
+
+ //===------------------------------------------------------------------===//
+ // Inline Asm Support
+ //===------------------------------------------------------------------===//
+ public:
+ // These are hooks that targets can override to implement inline asm
+ // support. These should probably be moved out of AsmPrinter someday.
+
+ /// PrintSpecial - Print information related to the specified machine instr
+ /// that is independent of the operand, and may be independent of the instr
+ /// itself. This can be useful for portably encoding the comment character
+ /// or other bits of target-specific knowledge into the asmstrings. The
+ /// syntax used is ${:comment}. Targets can override this to add support
+ /// for their own strange codes.
+ virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
+ const char *Code) const;
+
+ /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
+ /// instruction, using the specified assembler variant. Targets should
+ /// override this to format as appropriate. This method can return true if
+ /// the operand is erroneous.
+ virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
+ unsigned AsmVariant, const char *ExtraCode,
+ raw_ostream &OS);
+
+ /// PrintAsmMemoryOperand - Print the specified operand of MI, an INLINEASM
+ /// instruction, using the specified assembler variant as an address.
+ /// Targets should override this to format as appropriate. This method can
+ /// return true if the operand is erroneous.
+ virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
+ unsigned AsmVariant,
+ const char *ExtraCode,
+ raw_ostream &OS);
+
+ private:
+ /// Private state for PrintSpecial()
+ // Assign a unique ID to this machine instruction.
+ mutable const MachineInstr *LastMI;
+ mutable unsigned LastFn;
+ mutable unsigned Counter;
+ mutable unsigned SetCounter;
+
+ /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
+ void EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = 0,
+ InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
+
+ /// EmitInlineAsm - This method formats and emits the specified machine
+ /// instruction that is an inline asm.
+ void EmitInlineAsm(const MachineInstr *MI) const;
+
+ //===------------------------------------------------------------------===//
+ // Internal Implementation Details
+ //===------------------------------------------------------------------===//
+
+ /// EmitVisibility - This emits visibility information about symbol, if
+ /// this is suported by the target.
+ void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
+ bool IsDefinition = true) const;
+
+ void EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const;
+
+ void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
+ const MachineBasicBlock *MBB,
+ unsigned uid) const;
+ void EmitLLVMUsedList(const Constant *List);
+ void EmitXXStructorList(const Constant *List, bool isCtor);
+ GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy *C);
+ };
+}
+
+#endif
diff --git a/include/llvm/CodeGen/CalcSpillWeights.h b/include/llvm/CodeGen/CalcSpillWeights.h
new file mode 100644
index 00000000000..2f76a6cc558
--- /dev/null
+++ b/include/llvm/CodeGen/CalcSpillWeights.h
@@ -0,0 +1,78 @@
+//===---------------- lib/CodeGen/CalcSpillWeights.h ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+
+#ifndef LLVM_CODEGEN_CALCSPILLWEIGHTS_H
+#define LLVM_CODEGEN_CALCSPILLWEIGHTS_H
+
+#include "llvm/CodeGen/SlotIndexes.h"
+#include "llvm/ADT/DenseMap.h"
+
+namespace llvm {
+
+ class LiveInterval;
+ class LiveIntervals;
+ class MachineLoopInfo;
+
+ /// normalizeSpillWeight - The spill weight of a live interval is computed as:
+ ///
+ /// (sum(use freq) + sum(def freq)) / (K + size)
+ ///
+ /// @param UseDefFreq Expected number of executed use and def instructions
+ /// per function call. Derived from block frequencies.
+ /// @param Size Size of live interval as returnexd by getSize()
+ ///
+ static inline float normalizeSpillWeight(float UseDefFreq, unsigned Size) {
+ // The constant 25 instructions is added to avoid depending too much on
+ // accidental SlotIndex gaps for small intervals. The effect is that small
+ // intervals have a spill weight that is mostly proportional to the number
+ // of uses, while large intervals get a spill weight that is closer to a use
+ // density.
+ return UseDefFreq / (Size + 25*SlotIndex::InstrDist);
+ }
+
+ /// VirtRegAuxInfo - Calculate auxiliary information for a virtual
+ /// register such as its spill weight and allocation hint.
+ class VirtRegAuxInfo {
+ MachineFunction &MF;
+ LiveIntervals &LIS;
+ const MachineLoopInfo &Loops;
+ DenseMap<unsigned, float> Hint;
+ public:
+ VirtRegAuxInfo(MachineFunction &mf, LiveIntervals &lis,
+ const MachineLoopInfo &loops) :
+ MF(mf), LIS(lis), Loops(loops) {}
+
+ /// CalculateWeightAndHint - (re)compute li's spill weight and allocation
+ /// hint.
+ void CalculateWeightAndHint(LiveInterval &li);
+ };
+
+ /// CalculateSpillWeights - Compute spill weights for all virtual register
+ /// live intervals.
+ class CalculateSpillWeights : public MachineFunctionPass {
+ public:
+ static char ID;
+
+ CalculateSpillWeights() : MachineFunctionPass(ID) {
+ initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
+ }
+
+ virtual void getAnalysisUsage(AnalysisUsage &au) const;
+
+ virtual bool runOnMachineFunction(MachineFunction &fn);
+
+ private:
+ /// Returns true if the given live interval is zero length.
+ bool isZeroLengthInterval(LiveInterval *li) const;
+ };
+
+}
+
+#endif // LLVM_CODEGEN_CALCSPILLWEIGHTS_H
diff --git a/include/llvm/CodeGen/CallingConvLower.h b/include/llvm/CodeGen/CallingConvLower.h
new file mode 100644
index 00000000000..3afe3095d4f
--- /dev/null
+++ b/include/llvm/CodeGen/CallingConvLower.h
@@ -0,0 +1,325 @@
+//===-- llvm/CallingConvLower.h - Calling Conventions -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the CCState and CCValAssign classes, used for lowering
+// and implementing calling conventions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_CALLINGCONVLOWER_H
+#define LLVM_CODEGEN_CALLINGCONVLOWER_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/ValueTypes.h"
+#include "llvm/Target/TargetCallingConv.h"
+#include "llvm/CallingConv.h"
+
+namespace llvm {
+ class TargetRegisterInfo;
+ class TargetMachine;
+ class CCState;
+
+/// CCValAssign - Represent assignment of one arg/retval to a location.
+class CCValAssign {
+public:
+ enum LocInfo {
+ Full, // The value fills the full location.
+ SExt, // The value is sign extended in the location.
+ ZExt, // The value is zero extended in the location.
+ AExt, // The value is extended with undefined upper bits.
+ BCvt, // The value is bit-converted in the location.
+ VExt, // The value is vector-widened in the location.
+ // FIXME: Not implemented yet. Code that uses AExt to mean
+ // vector-widen should be fixed to use VExt instead.
+ Indirect // The location contains pointer to the value.
+ // TODO: a subset of the value is in the location.
+ };
+private:
+ /// ValNo - This is the value number begin assigned (e.g. an argument number).
+ unsigned ValNo;
+
+ /// Loc is either a stack offset or a register number.
+ unsigned Loc;
+
+ /// isMem - True if this is a memory loc, false if it is a register loc.
+ bool isMem : 1;
+
+ /// isCustom - True if this arg/retval requires special handling.
+ bool isCustom : 1;
+
+ /// Information about how the value is assigned.
+ LocInfo HTP : 6;
+
+ /// ValVT - The type of the value being assigned.
+ MVT ValVT;
+
+ /// LocVT - The type of the location being assigned to.
+ MVT LocVT;
+public:
+
+ static CCValAssign getReg(unsigned ValNo, MVT ValVT,
+ unsigned RegNo, MVT LocVT,
+ LocInfo HTP) {
+ CCValAssign Ret;
+ Ret.ValNo = ValNo;
+ Ret.Loc = RegNo;
+ Ret.isMem = false;
+ Ret.isCustom = false;
+ Ret.HTP = HTP;
+ Ret.ValVT = ValVT;
+ Ret.LocVT = LocVT;
+ return Ret;
+ }
+
+ static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT,
+ unsigned RegNo, MVT LocVT,
+ LocInfo HTP) {
+ CCValAssign Ret;
+ Ret = getReg(ValNo, ValVT, RegNo, LocVT, HTP);
+ Ret.isCustom = true;
+ return Ret;
+ }
+
+ static CCValAssign getMem(unsigned ValNo, MVT ValVT,
+ unsigned Offset, MVT LocVT,
+ LocInfo HTP) {
+ CCValAssign Ret;
+ Ret.ValNo = ValNo;
+ Ret.Loc = Offset;
+ Ret.isMem = true;
+ Ret.isCustom = false;
+ Ret.HTP = HTP;
+ Ret.ValVT = ValVT;
+ Ret.LocVT = LocVT;
+ return Ret;
+ }
+
+ static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT,
+ unsigned Offset, MVT LocVT,
+ LocInfo HTP) {
+ CCValAssign Ret;
+ Ret = getMem(ValNo, ValVT, Offset, LocVT, HTP);
+ Ret.isCustom = true;
+ return Ret;
+ }
+
+ unsigned getValNo() const { return ValNo; }
+ MVT getValVT() const { return ValVT; }
+
+ bool isRegLoc() const { return !isMem; }
+ bool isMemLoc() const { return isMem; }
+
+ bool needsCustom() const { return isCustom; }
+
+ unsigned getLocReg() const { assert(isRegLoc()); return Loc; }
+ unsigned getLocMemOffset() const { assert(isMemLoc()); return Loc; }
+ MVT getLocVT() const { return LocVT; }
+
+ LocInfo getLocInfo() const { return HTP; }
+ bool isExtInLoc() const {
+ return (HTP == AExt || HTP == SExt || HTP == ZExt);
+ }
+
+};
+
+/// CCAssignFn - This function assigns a location for Val, updating State to
+/// reflect the change. It returns 'true' if it failed to handle Val.
+typedef bool CCAssignFn(unsigned ValNo, MVT ValVT,
+ MVT LocVT, CCValAssign::LocInfo LocInfo,
+ ISD::ArgFlagsTy ArgFlags, CCState &State);
+
+/// CCCustomFn - This function assigns a location for Val, possibly updating
+/// all args to reflect changes and indicates if it handled it. It must set
+/// isCustom if it handles the arg and returns true.
+typedef bool CCCustomFn(unsigned &ValNo, MVT &ValVT,
+ MVT &LocVT, CCValAssign::LocInfo &LocInfo,
+ ISD::ArgFlagsTy &ArgFlags, CCState &State);
+
+/// ParmContext - This enum tracks whether calling convention lowering is in
+/// the context of prologue or call generation. Not all backends make use of
+/// this information.
+typedef enum { Unknown, Prologue, Call } ParmContext;
+
+/// CCState - This class holds information needed while lowering arguments and
+/// return values. It captures which registers are already assigned and which
+/// stack slots are used. It provides accessors to allocate these values.
+class CCState {
+private:
+ CallingConv::ID CallingConv;
+ bool IsVarArg;
+ MachineFunction &MF;
+ const TargetMachine &TM;
+ const TargetRegisterInfo &TRI;
+ SmallVector<CCValAssign, 16> &Locs;
+ LLVMContext &Context;
+
+ unsigned StackOffset;
+ SmallVector<uint32_t, 16> UsedRegs;
+ unsigned FirstByValReg;
+ bool FirstByValRegValid;
+
+protected:
+ ParmContext CallOrPrologue;
+
+public:
+ CCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
+ const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
+ LLVMContext &C);
+
+ void addLoc(const CCValAssign &V) {
+ Locs.push_back(V);
+ }
+
+ LLVMContext &getContext() const { return Context; }
+ const TargetMachine &getTarget() const { return TM; }
+ MachineFunction &getMachineFunction() const { return MF; }
+ CallingConv::ID getCallingConv() const { return CallingConv; }
+ bool isVarArg() const { return IsVarArg; }
+
+ unsigned getNextStackOffset() const { return StackOffset; }
+
+ /// isAllocated - Return true if the specified register (or an alias) is
+ /// allocated.
+ bool isAllocated(unsigned Reg) const {
+ return UsedRegs[Reg/32] & (1 << (Reg&31));
+ }
+
+ /// AnalyzeFormalArguments - Analyze an array of argument values,
+ /// incorporating info about the formals into this state.
+ void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
+ CCAssignFn Fn);
+
+ /// AnalyzeReturn - Analyze the returned values of a return,
+ /// incorporating info about the result values into this state.
+ void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
+ CCAssignFn Fn);
+
+ /// CheckReturn - Analyze the return values of a function, returning
+ /// true if the return can be performed without sret-demotion, and
+ /// false otherwise.
+ bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
+ CCAssignFn Fn);
+
+ /// AnalyzeCallOperands - Analyze the outgoing arguments to a call,
+ /// incorporating info about the passed values into this state.
+ void AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs,
+ CCAssignFn Fn);
+
+ /// AnalyzeCallOperands - Same as above except it takes vectors of types
+ /// and argument flags.
+ void AnalyzeCallOperands(SmallVectorImpl<MVT> &ArgVTs,
+ SmallVectorImpl<ISD::ArgFlagsTy> &Flags,
+ CCAssignFn Fn);
+
+ /// AnalyzeCallResult - Analyze the return values of a call,
+ /// incorporating info about the passed values into this state.
+ void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
+ CCAssignFn Fn);
+
+ /// AnalyzeCallResult - Same as above except it's specialized for calls which
+ /// produce a single value.
+ void AnalyzeCallResult(MVT VT, CCAssignFn Fn);
+
+ /// getFirstUnallocated - Return the first unallocated register in the set, or
+ /// NumRegs if they are all allocated.
+ unsigned getFirstUnallocated(const uint16_t *Regs, unsigned NumRegs) const {
+ for (unsigned i = 0; i != NumRegs; ++i)
+ if (!isAllocated(Regs[i]))
+ return i;
+ return NumRegs;
+ }
+
+ /// AllocateReg - Attempt to allocate one register. If it is not available,
+ /// return zero. Otherwise, return the register, marking it and any aliases
+ /// as allocated.
+ unsigned AllocateReg(unsigned Reg) {
+ if (isAllocated(Reg)) return 0;
+ MarkAllocated(Reg);
+ return Reg;
+ }
+
+ /// Version of AllocateReg with extra register to be shadowed.
+ unsigned AllocateReg(unsigned Reg, unsigned ShadowReg) {
+ if (isAllocated(Reg)) return 0;
+ MarkAllocated(Reg);
+ MarkAllocated(ShadowReg);
+ return Reg;
+ }
+
+ /// AllocateReg - Attempt to allocate one of the specified registers. If none
+ /// are available, return zero. Otherwise, return the first one available,
+ /// marking it and any aliases as allocated.
+ unsigned AllocateReg(const uint16_t *Regs, unsigned NumRegs) {
+ unsigned FirstUnalloc = getFirstUnallocated(Regs, NumRegs);
+ if (FirstUnalloc == NumRegs)
+ return 0; // Didn't find the reg.
+
+ // Mark the register and any aliases as allocated.
+ unsigned Reg = Regs[FirstUnalloc];
+ MarkAllocated(Reg);
+ return Reg;
+ }
+
+ /// Version of AllocateReg with list of registers to be shadowed.
+ unsigned AllocateReg(const uint16_t *Regs, const uint16_t *ShadowRegs,
+ unsigned NumRegs) {
+ unsigned FirstUnalloc = getFirstUnallocated(Regs, NumRegs);
+ if (FirstUnalloc == NumRegs)
+ return 0; // Didn't find the reg.
+
+ // Mark the register and any aliases as allocated.
+ unsigned Reg = Regs[FirstUnalloc], ShadowReg = ShadowRegs[FirstUnalloc];
+ MarkAllocated(Reg);
+ MarkAllocated(ShadowReg);
+ return Reg;
+ }
+
+ /// AllocateStack - Allocate a chunk of stack space with the specified size
+ /// and alignment.
+ unsigned AllocateStack(unsigned Size, unsigned Align) {
+ assert(Align && ((Align-1) & Align) == 0); // Align is power of 2.
+ StackOffset = ((StackOffset + Align-1) & ~(Align-1));
+ unsigned Result = StackOffset;
+ StackOffset += Size;
+ return Result;
+ }
+
+ /// Version of AllocateStack with extra register to be shadowed.
+ unsigned AllocateStack(unsigned Size, unsigned Align, unsigned ShadowReg) {
+ MarkAllocated(ShadowReg);
+ return AllocateStack(Size, Align);
+ }
+
+ // HandleByVal - Allocate a stack slot large enough to pass an argument by
+ // value. The size and alignment information of the argument is encoded in its
+ // parameter attribute.
+ void HandleByVal(unsigned ValNo, MVT ValVT,
+ MVT LocVT, CCValAssign::LocInfo LocInfo,
+ int MinSize, int MinAlign, ISD::ArgFlagsTy ArgFlags);
+
+ // First GPR that carries part of a byval aggregate that's split
+ // between registers and memory.
+ unsigned getFirstByValReg() const { return FirstByValRegValid ? FirstByValReg : 0; }
+ void setFirstByValReg(unsigned r) { FirstByValReg = r; FirstByValRegValid = true; }
+ void clearFirstByValReg() { FirstByValReg = 0; FirstByValRegValid = false; }
+ bool isFirstByValRegValid() const { return FirstByValRegValid; }
+
+ ParmContext getCallOrPrologue() const { return CallOrPrologue; }
+
+private:
+ /// MarkAllocated - Mark a register and all of its aliases as allocated.
+ void MarkAllocated(unsigned Reg);
+};
+
+
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/DFAPacketizer.h b/include/llvm/CodeGen/DFAPacketizer.h
new file mode 100644
index 00000000000..2d2db78144a
--- /dev/null
+++ b/include/llvm/CodeGen/DFAPacketizer.h
@@ -0,0 +1,167 @@
+//=- llvm/CodeGen/DFAPacketizer.h - DFA Packetizer for VLIW ---*- C++ -*-=====//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+// This class implements a deterministic finite automaton (DFA) based
+// packetizing mechanism for VLIW architectures. It provides APIs to
+// determine whether there exists a legal mapping of instructions to
+// functional unit assignments in a packet. The DFA is auto-generated from
+// the target's Schedule.td file.
+//
+// A DFA consists of 3 major elements: states, inputs, and transitions. For
+// the packetizing mechanism, the input is the set of instruction classes for
+// a target. The state models all possible combinations of functional unit
+// consumption for a given set of instructions in a packet. A transition
+// models the addition of an instruction to a packet. In the DFA constructed
+// by this class, if an instruction can be added to a packet, then a valid
+// transition exists from the corresponding state. Invalid transitions
+// indicate that the instruction cannot be added to the current packet.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_DFAPACKETIZER_H
+#define LLVM_CODEGEN_DFAPACKETIZER_H
+
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/ADT/DenseMap.h"
+#include <map>
+
+namespace llvm {
+
+class MCInstrDesc;
+class MachineInstr;
+class MachineLoopInfo;
+class MachineDominatorTree;
+class InstrItineraryData;
+class DefaultVLIWScheduler;
+class SUnit;
+
+class DFAPacketizer {
+private:
+ typedef std::pair<unsigned, unsigned> UnsignPair;
+ const InstrItineraryData *InstrItins;
+ int CurrentState;
+ const int (*DFAStateInputTable)[2];
+ const unsigned *DFAStateEntryTable;
+
+ // CachedTable is a map from <FromState, Input> to ToState.
+ DenseMap<UnsignPair, unsigned> CachedTable;
+
+ // ReadTable - Read the DFA transition table and update CachedTable.
+ void ReadTable(unsigned int state);
+
+public:
+ DFAPacketizer(const InstrItineraryData *I, const int (*SIT)[2],
+ const unsigned *SET);
+
+ // Reset the current state to make all resources available.
+ void clearResources() {
+ CurrentState = 0;
+ }
+
+ // canReserveResources - Check if the resources occupied by a MCInstrDesc
+ // are available in the current state.
+ bool canReserveResources(const llvm::MCInstrDesc *MID);
+
+ // reserveResources - Reserve the resources occupied by a MCInstrDesc and
+ // change the current state to reflect that change.
+ void reserveResources(const llvm::MCInstrDesc *MID);
+
+ // canReserveResources - Check if the resources occupied by a machine
+ // instruction are available in the current state.
+ bool canReserveResources(llvm::MachineInstr *MI);
+
+ // reserveResources - Reserve the resources occupied by a machine
+ // instruction and change the current state to reflect that change.
+ void reserveResources(llvm::MachineInstr *MI);
+
+ const InstrItineraryData *getInstrItins() const { return InstrItins; }
+};
+
+// VLIWPacketizerList - Implements a simple VLIW packetizer using DFA. The
+// packetizer works on machine basic blocks. For each instruction I in BB, the
+// packetizer consults the DFA to see if machine resources are available to
+// execute I. If so, the packetizer checks if I depends on any instruction J in
+// the current packet. If no dependency is found, I is added to current packet
+// and machine resource is marked as taken. If any dependency is found, a target
+// API call is made to prune the dependence.
+class VLIWPacketizerList {
+protected:
+ const TargetMachine &TM;
+ const MachineFunction &MF;
+ const TargetInstrInfo *TII;
+
+ // The VLIW Scheduler.
+ DefaultVLIWScheduler *VLIWScheduler;
+
+ // Vector of instructions assigned to the current packet.
+ std::vector<MachineInstr*> CurrentPacketMIs;
+ // DFA resource tracker.
+ DFAPacketizer *ResourceTracker;
+
+ // Generate MI -> SU map.
+ std::map<MachineInstr*, SUnit*> MIToSUnit;
+
+public:
+ VLIWPacketizerList(
+ MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
+ bool IsPostRA);
+
+ virtual ~VLIWPacketizerList();
+
+ // PacketizeMIs - Implement this API in the backend to bundle instructions.
+ void PacketizeMIs(MachineBasicBlock *MBB,
+ MachineBasicBlock::iterator BeginItr,
+ MachineBasicBlock::iterator EndItr);
+
+ // getResourceTracker - return ResourceTracker
+ DFAPacketizer *getResourceTracker() {return ResourceTracker;}
+
+ // addToPacket - Add MI to the current packet.
+ virtual MachineBasicBlock::iterator addToPacket(MachineInstr *MI) {
+ MachineBasicBlock::iterator MII = MI;
+ CurrentPacketMIs.push_back(MI);
+ ResourceTracker->reserveResources(MI);
+ return MII;
+ }
+
+ // endPacket - End the current packet.
+ void endPacket(MachineBasicBlock *MBB, MachineInstr *MI);
+
+ // initPacketizerState - perform initialization before packetizing
+ // an instruction. This function is supposed to be overrided by
+ // the target dependent packetizer.
+ virtual void initPacketizerState(void) { return; }
+
+ // ignorePseudoInstruction - Ignore bundling of pseudo instructions.
+ virtual bool ignorePseudoInstruction(MachineInstr *I,
+ MachineBasicBlock *MBB) {
+ return false;
+ }
+
+ // isSoloInstruction - return true if instruction MI can not be packetized
+ // with any other instruction, which means that MI itself is a packet.
+ virtual bool isSoloInstruction(MachineInstr *MI) {
+ return true;
+ }
+
+ // isLegalToPacketizeTogether - Is it legal to packetize SUI and SUJ
+ // together.
+ virtual bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {
+ return false;
+ }
+
+ // isLegalToPruneDependencies - Is it legal to prune dependece between SUI
+ // and SUJ.
+ virtual bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) {
+ return false;
+ }
+
+};
+}
+
+#endif
diff --git a/include/llvm/CodeGen/EdgeBundles.h b/include/llvm/CodeGen/EdgeBundles.h
new file mode 100644
index 00000000000..e8a4a2d2d89
--- /dev/null
+++ b/include/llvm/CodeGen/EdgeBundles.h
@@ -0,0 +1,69 @@
+//===-------- EdgeBundles.h - Bundles of CFG edges --------------*- c++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The EdgeBundles analysis forms equivalence classes of CFG edges such that all
+// edges leaving a machine basic block are in the same bundle, and all edges
+// leaving a basic block are in the same bundle.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_EDGEBUNDLES_H
+#define LLVM_CODEGEN_EDGEBUNDLES_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntEqClasses.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+
+namespace llvm {
+
+class EdgeBundles : public MachineFunctionPass {
+ const MachineFunction *MF;
+
+ /// EC - Each edge bundle is an equivalence class. The keys are:
+ /// 2*BB->getNumber() -> Ingoing bundle.
+ /// 2*BB->getNumber()+1 -> Outgoing bundle.
+ IntEqClasses EC;
+
+ /// Blocks - Map each bundle to a list of basic block numbers.
+ SmallVector<SmallVector<unsigned, 8>, 4> Blocks;
+
+public:
+ static char ID;
+ EdgeBundles() : MachineFunctionPass(ID) {}
+
+ /// getBundle - Return the ingoing (Out = false) or outgoing (Out = true)
+ /// bundle number for basic block #N
+ unsigned getBundle(unsigned N, bool Out) const { return EC[2 * N + Out]; }
+
+ /// getNumBundles - Return the total number of bundles in the CFG.
+ unsigned getNumBundles() const { return EC.getNumClasses(); }
+
+ /// getBlocks - Return an array of blocks that are connected to Bundle.
+ ArrayRef<unsigned> getBlocks(unsigned Bundle) const { return Blocks[Bundle]; }
+
+ /// getMachineFunction - Return the last machine function computed.
+ const MachineFunction *getMachineFunction() const { return MF; }
+
+ /// view - Visualize the annotated bipartite CFG with Graphviz.
+ void view() const;
+
+private:
+ virtual bool runOnMachineFunction(MachineFunction&);
+ virtual void getAnalysisUsage(AnalysisUsage&) const;
+};
+
+/// Specialize WriteGraph, the standard implementation won't work.
+raw_ostream &WriteGraph(raw_ostream &O, const EdgeBundles &G,
+ bool ShortNames = false,
+ const Twine &Title = "");
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/FastISel.h b/include/llvm/CodeGen/FastISel.h
new file mode 100644
index 00000000000..7cb96952aa6
--- /dev/null
+++ b/include/llvm/CodeGen/FastISel.h
@@ -0,0 +1,406 @@
+//===-- FastISel.h - Definition of the FastISel class ---------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the FastISel class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_FASTISEL_H
+#define LLVM_CODEGEN_FASTISEL_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/CodeGen/ValueTypes.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+
+namespace llvm {
+
+class AllocaInst;
+class Constant;
+class ConstantFP;
+class FunctionLoweringInfo;
+class Instruction;
+class LoadInst;
+class MachineBasicBlock;
+class MachineConstantPool;
+class MachineFunction;
+class MachineInstr;
+class MachineFrameInfo;
+class MachineRegisterInfo;
+class TargetData;
+class TargetInstrInfo;
+class TargetLibraryInfo;
+class TargetLowering;
+class TargetMachine;
+class TargetRegisterClass;
+class TargetRegisterInfo;
+class User;
+class Value;
+
+/// FastISel - This is a fast-path instruction selection class that
+/// generates poor code and doesn't support illegal types or non-trivial
+/// lowering, but runs quickly.
+class FastISel {
+protected:
+ DenseMap<const Value *, unsigned> LocalValueMap;
+ FunctionLoweringInfo &FuncInfo;
+ MachineRegisterInfo &MRI;
+ MachineFrameInfo &MFI;
+ MachineConstantPool &MCP;
+ DebugLoc DL;
+ const TargetMachine &TM;
+ const TargetData &TD;
+ const TargetInstrInfo &TII;
+ const TargetLowering &TLI;
+ const TargetRegisterInfo &TRI;
+ const TargetLibraryInfo *LibInfo;
+
+ /// The position of the last instruction for materializing constants
+ /// for use in the current block. It resets to EmitStartPt when it
+ /// makes sense (for example, it's usually profitable to avoid function
+ /// calls between the definition and the use)
+ MachineInstr *LastLocalValue;
+
+ /// The top most instruction in the current block that is allowed for
+ /// emitting local variables. LastLocalValue resets to EmitStartPt when
+ /// it makes sense (for example, on function calls)
+ MachineInstr *EmitStartPt;
+
+public:
+ /// getLastLocalValue - Return the position of the last instruction
+ /// emitted for materializing constants for use in the current block.
+ MachineInstr *getLastLocalValue() { return LastLocalValue; }
+
+ /// setLastLocalValue - Update the position of the last instruction
+ /// emitted for materializing constants for use in the current block.
+ void setLastLocalValue(MachineInstr *I) {
+ EmitStartPt = I;
+ LastLocalValue = I;
+ }
+
+ /// startNewBlock - Set the current block to which generated machine
+ /// instructions will be appended, and clear the local CSE map.
+ ///
+ void startNewBlock();
+
+ /// getCurDebugLoc() - Return current debug location information.
+ DebugLoc getCurDebugLoc() const { return DL; }
+
+ /// SelectInstruction - Do "fast" instruction selection for the given
+ /// LLVM IR instruction, and append generated machine instructions to
+ /// the current block. Return true if selection was successful.
+ ///
+ bool SelectInstruction(const Instruction *I);
+
+ /// SelectOperator - Do "fast" instruction selection for the given
+ /// LLVM IR operator (Instruction or ConstantExpr), and append
+ /// generated machine instructions to the current block. Return true
+ /// if selection was successful.
+ ///
+ bool SelectOperator(const User *I, unsigned Opcode);
+
+ /// getRegForValue - Create a virtual register and arrange for it to
+ /// be assigned the value for the given LLVM value.
+ unsigned getRegForValue(const Value *V);
+
+ /// lookUpRegForValue - Look up the value to see if its value is already
+ /// cached in a register. It may be defined by instructions across blocks or
+ /// defined locally.
+ unsigned lookUpRegForValue(const Value *V);
+
+ /// getRegForGEPIndex - This is a wrapper around getRegForValue that also
+ /// takes care of truncating or sign-extending the given getelementptr
+ /// index value.
+ std::pair<unsigned, bool> getRegForGEPIndex(const Value *V);
+
+ /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
+ /// vreg is being provided by the specified load instruction. If possible,
+ /// try to fold the load as an operand to the instruction, returning true if
+ /// possible.
+ virtual bool TryToFoldLoad(MachineInstr * /*MI*/, unsigned /*OpNo*/,
+ const LoadInst * /*LI*/) {
+ return false;
+ }
+
+ /// recomputeInsertPt - Reset InsertPt to prepare for inserting instructions
+ /// into the current block.
+ void recomputeInsertPt();
+
+ struct SavePoint {
+ MachineBasicBlock::iterator InsertPt;
+ DebugLoc DL;
+ };
+
+ /// enterLocalValueArea - Prepare InsertPt to begin inserting instructions
+ /// into the local value area and return the old insert position.
+ SavePoint enterLocalValueArea();
+
+ /// leaveLocalValueArea - Reset InsertPt to the given old insert position.
+ void leaveLocalValueArea(SavePoint Old);
+
+ virtual ~FastISel();
+
+protected:
+ explicit FastISel(FunctionLoweringInfo &funcInfo,
+ const TargetLibraryInfo *libInfo);
+
+ /// TargetSelectInstruction - This method is called by target-independent
+ /// code when the normal FastISel process fails to select an instruction.
+ /// This gives targets a chance to emit code for anything that doesn't
+ /// fit into FastISel's framework. It returns true if it was successful.
+ ///
+ virtual bool
+ TargetSelectInstruction(const Instruction *I) = 0;
+
+ /// FastEmit_r - This method is called by target-independent code
+ /// to request that an instruction with the given type and opcode
+ /// be emitted.
+ virtual unsigned FastEmit_(MVT VT,
+ MVT RetVT,
+ unsigned Opcode);
+
+ /// FastEmit_r - This method is called by target-independent code
+ /// to request that an instruction with the given type, opcode, and
+ /// register operand be emitted.
+ ///
+ virtual unsigned FastEmit_r(MVT VT,
+ MVT RetVT,
+ unsigned Opcode,
+ unsigned Op0, bool Op0IsKill);
+
+ /// FastEmit_rr - This method is called by target-independent code
+ /// to request that an instruction with the given type, opcode, and
+ /// register operands be emitted.
+ ///
+ virtual unsigned FastEmit_rr(MVT VT,
+ MVT RetVT,
+ unsigned Opcode,
+ unsigned Op0, bool Op0IsKill,
+ unsigned Op1, bool Op1IsKill);
+
+ /// FastEmit_ri - This method is called by target-independent code
+ /// to request that an instruction with the given type, opcode, and
+ /// register and immediate operands be emitted.
+ ///
+ virtual unsigned FastEmit_ri(MVT VT,
+ MVT RetVT,
+ unsigned Opcode,
+ unsigned Op0, bool Op0IsKill,
+ uint64_t Imm);
+
+ /// FastEmit_rf - This method is called by target-independent code
+ /// to request that an instruction with the given type, opcode, and
+ /// register and floating-point immediate operands be emitted.
+ ///
+ virtual unsigned FastEmit_rf(MVT VT,
+ MVT RetVT,
+ unsigned Opcode,
+ unsigned Op0, bool Op0IsKill,
+ const ConstantFP *FPImm);
+
+ /// FastEmit_rri - This method is called by target-independent code
+ /// to request that an instruction with the given type, opcode, and
+ /// register and immediate operands be emitted.
+ ///
+ virtual unsigned FastEmit_rri(MVT VT,
+ MVT RetVT,
+ unsigned Opcode,
+ unsigned Op0, bool Op0IsKill,
+ unsigned Op1, bool Op1IsKill,
+ uint64_t Imm);
+
+ /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
+ /// to emit an instruction with an immediate operand using FastEmit_ri.
+ /// If that fails, it materializes the immediate into a register and try
+ /// FastEmit_rr instead.
+ unsigned FastEmit_ri_(MVT VT,
+ unsigned Opcode,
+ unsigned Op0, bool Op0IsKill,
+ uint64_t Imm, MVT ImmType);
+
+ /// FastEmit_i - This method is called by target-independent code
+ /// to request that an instruction with the given type, opcode, and
+ /// immediate operand be emitted.
+ virtual unsigned FastEmit_i(MVT VT,
+ MVT RetVT,
+ unsigned Opcode,
+ uint64_t Imm);
+
+ /// FastEmit_f - This method is called by target-independent code
+ /// to request that an instruction with the given type, opcode, and
+ /// floating-point immediate operand be emitted.
+ virtual unsigned FastEmit_f(MVT VT,
+ MVT RetVT,
+ unsigned Opcode,
+ const ConstantFP *FPImm);
+
+ /// FastEmitInst_ - Emit a MachineInstr with no operands and a
+ /// result register in the given register class.
+ ///
+ unsigned FastEmitInst_(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC);
+
+ /// FastEmitInst_r - Emit a MachineInstr with one register operand
+ /// and a result register in the given register class.
+ ///
+ unsigned FastEmitInst_r(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC,
+ unsigned Op0, bool Op0IsKill);
+
+ /// FastEmitInst_rr - Emit a MachineInstr with two register operands
+ /// and a result register in the given register class.
+ ///
+ unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC,
+ unsigned Op0, bool Op0IsKill,
+ unsigned Op1, bool Op1IsKill);
+
+ /// FastEmitInst_rrr - Emit a MachineInstr with three register operands
+ /// and a result register in the given register class.
+ ///
+ unsigned FastEmitInst_rrr(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC,
+ unsigned Op0, bool Op0IsKill,
+ unsigned Op1, bool Op1IsKill,
+ unsigned Op2, bool Op2IsKill);
+
+ /// FastEmitInst_ri - Emit a MachineInstr with a register operand,
+ /// an immediate, and a result register in the given register class.
+ ///
+ unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC,
+ unsigned Op0, bool Op0IsKill,
+ uint64_t Imm);
+
+ /// FastEmitInst_rii - Emit a MachineInstr with one register operand
+ /// and two immediate operands.
+ ///
+ unsigned FastEmitInst_rii(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC,
+ unsigned Op0, bool Op0IsKill,
+ uint64_t Imm1, uint64_t Imm2);
+
+ /// FastEmitInst_rf - Emit a MachineInstr with two register operands
+ /// and a result register in the given register class.
+ ///
+ unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC,
+ unsigned Op0, bool Op0IsKill,
+ const ConstantFP *FPImm);
+
+ /// FastEmitInst_rri - Emit a MachineInstr with two register operands,
+ /// an immediate, and a result register in the given register class.
+ ///
+ unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC,
+ unsigned Op0, bool Op0IsKill,
+ unsigned Op1, bool Op1IsKill,
+ uint64_t Imm);
+
+ /// FastEmitInst_rrii - Emit a MachineInstr with two register operands,
+ /// two immediates operands, and a result register in the given register
+ /// class.
+ unsigned FastEmitInst_rrii(unsigned MachineInstOpcode,
+ const TargetRegisterClass *RC,
+ unsigned Op0, bool Op0IsKill,
+ unsigned Op1, bool Op1IsKill,
+ uint64_t Imm1, uint64_t Imm2);
+
+ /// FastEmitInst_i - Emit a MachineInstr with a single immediate
+ /// operand, and a result register in the given register class.
+ unsigned FastEmitInst_i(unsigned MachineInstrOpcode,
+ const TargetRegisterClass *RC,
+ uint64_t Imm);
+
+ /// FastEmitInst_ii - Emit a MachineInstr with a two immediate operands.
+ unsigned FastEmitInst_ii(unsigned MachineInstrOpcode,
+ const TargetRegisterClass *RC,
+ uint64_t Imm1, uint64_t Imm2);
+
+ /// FastEmitInst_extractsubreg - Emit a MachineInstr for an extract_subreg
+ /// from a specified index of a superregister to a specified type.
+ unsigned FastEmitInst_extractsubreg(MVT RetVT,
+ unsigned Op0, bool Op0IsKill,
+ uint32_t Idx);
+
+ /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
+ /// with all but the least significant bit set to zero.
+ unsigned FastEmitZExtFromI1(MVT VT,
+ unsigned Op0, bool Op0IsKill);
+
+ /// FastEmitBranch - Emit an unconditional branch to the given block,
+ /// unless it is the immediate (fall-through) successor, and update
+ /// the CFG.
+ void FastEmitBranch(MachineBasicBlock *MBB, DebugLoc DL);
+
+ void UpdateValueMap(const Value* I, unsigned Reg, unsigned NumRegs = 1);
+
+ unsigned createResultReg(const TargetRegisterClass *RC);
+
+ /// TargetMaterializeConstant - Emit a constant in a register using
+ /// target-specific logic, such as constant pool loads.
+ virtual unsigned TargetMaterializeConstant(const Constant* C) {
+ return 0;
+ }
+
+ /// TargetMaterializeAlloca - Emit an alloca address in a register using
+ /// target-specific logic.
+ virtual unsigned TargetMaterializeAlloca(const AllocaInst* C) {
+ return 0;
+ }
+
+ virtual unsigned TargetMaterializeFloatZero(const ConstantFP* CF) {
+ return 0;
+ }
+
+private:
+ bool SelectBinaryOp(const User *I, unsigned ISDOpcode);
+
+ bool SelectFNeg(const User *I);
+
+ bool SelectGetElementPtr(const User *I);
+
+ bool SelectCall(const User *I);
+
+ bool SelectBitCast(const User *I);
+
+ bool SelectCast(const User *I, unsigned Opcode);
+
+ bool SelectExtractValue(const User *I);
+
+ bool SelectInsertValue(const User *I);
+
+ /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
+ /// Emit code to ensure constants are copied into registers when needed.
+ /// Remember the virtual registers that need to be added to the Machine PHI
+ /// nodes as input. We cannot just directly add them, because expansion
+ /// might result in multiple MBB's for one BB. As such, the start of the
+ /// BB might correspond to a different MBB than the end.
+ bool HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
+
+ /// materializeRegForValue - Helper for getRegForVale. This function is
+ /// called when the value isn't already available in a register and must
+ /// be materialized with new instructions.
+ unsigned materializeRegForValue(const Value *V, MVT VT);
+
+ /// flushLocalValueMap - clears LocalValueMap and moves the area for the
+ /// new local variables to the beginning of the block. It helps to avoid
+ /// spilling cached variables across heavy instructions like calls.
+ void flushLocalValueMap();
+
+ /// hasTrivialKill - Test whether the given value has exactly one use.
+ bool hasTrivialKill(const Value *V) const;
+
+ /// removeDeadCode - Remove all dead instructions between the I and E.
+ void removeDeadCode(MachineBasicBlock::iterator I,
+ MachineBasicBlock::iterator E);
+};
+
+}
+
+#endif
diff --git a/include/llvm/CodeGen/FunctionLoweringInfo.h b/include/llvm/CodeGen/FunctionLoweringInfo.h
new file mode 100644
index 00000000000..8cf22eca4fa
--- /dev/null
+++ b/include/llvm/CodeGen/FunctionLoweringInfo.h
@@ -0,0 +1,231 @@
+//===-- FunctionLoweringInfo.h - Lower functions from LLVM IR to CodeGen --===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This implements routines for translating functions from LLVM IR into
+// Machine IR.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_FUNCTIONLOWERINGINFO_H
+#define LLVM_CODEGEN_FUNCTIONLOWERINGINFO_H
+
+#include "llvm/InlineAsm.h"
+#include "llvm/Instructions.h"
+#include "llvm/ADT/APInt.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/IndexedMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Analysis/BranchProbabilityInfo.h"
+#include "llvm/CodeGen/ValueTypes.h"
+#include "llvm/CodeGen/ISDOpcodes.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/Support/CallSite.h"
+#include "llvm/Target/TargetRegisterInfo.h"
+#include <vector>
+
+namespace llvm {
+
+class AllocaInst;
+class BasicBlock;
+class CallInst;
+class Function;
+class GlobalVariable;
+class Instruction;
+class MachineInstr;
+class MachineBasicBlock;
+class MachineFunction;
+class MachineModuleInfo;
+class MachineRegisterInfo;
+class TargetLowering;
+class Value;
+
+//===--------------------------------------------------------------------===//
+/// FunctionLoweringInfo - This contains information that is global to a
+/// function that is used when lowering a region of the function.
+///
+class FunctionLoweringInfo {
+public:
+ const TargetLowering &TLI;
+ const Function *Fn;
+ MachineFunction *MF;
+ MachineRegisterInfo *RegInfo;
+ BranchProbabilityInfo *BPI;
+ /// CanLowerReturn - true iff the function's return value can be lowered to
+ /// registers.
+ bool CanLowerReturn;
+
+ /// DemoteRegister - if CanLowerReturn is false, DemoteRegister is a vreg
+ /// allocated to hold a pointer to the hidden sret parameter.
+ unsigned DemoteRegister;
+
+ /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
+ DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
+
+ /// ValueMap - Since we emit code for the function a basic block at a time,
+ /// we must remember which virtual registers hold the values for
+ /// cross-basic-block values.
+ DenseMap<const Value*, unsigned> ValueMap;
+
+ /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
+ /// the entry block. This allows the allocas to be efficiently referenced
+ /// anywhere in the function.
+ DenseMap<const AllocaInst*, int> StaticAllocaMap;
+
+ /// ByValArgFrameIndexMap - Keep track of frame indices for byval arguments.
+ DenseMap<const Argument*, int> ByValArgFrameIndexMap;
+
+ /// ArgDbgValues - A list of DBG_VALUE instructions created during isel for
+ /// function arguments that are inserted after scheduling is completed.
+ SmallVector<MachineInstr*, 8> ArgDbgValues;
+
+ /// RegFixups - Registers which need to be replaced after isel is done.
+ DenseMap<unsigned, unsigned> RegFixups;
+
+ /// MBB - The current block.
+ MachineBasicBlock *MBB;
+
+ /// MBB - The current insert position inside the current block.
+ MachineBasicBlock::iterator InsertPt;
+
+#ifndef NDEBUG
+ SmallPtrSet<const Instruction *, 8> CatchInfoLost;
+ SmallPtrSet<const Instruction *, 8> CatchInfoFound;
+#endif
+
+ struct LiveOutInfo {
+ unsigned NumSignBits : 31;
+ bool IsValid : 1;
+ APInt KnownOne, KnownZero;
+ LiveOutInfo() : NumSignBits(0), IsValid(true), KnownOne(1, 0),
+ KnownZero(1, 0) {}
+ };
+
+ /// VisitedBBs - The set of basic blocks visited thus far by instruction
+ /// selection.
+ SmallPtrSet<const BasicBlock*, 4> VisitedBBs;
+
+ /// PHINodesToUpdate - A list of phi instructions whose operand list will
+ /// be updated after processing the current basic block.
+ /// TODO: This isn't per-function state, it's per-basic-block state. But
+ /// there's no other convenient place for it to live right now.
+ std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
+
+ explicit FunctionLoweringInfo(const TargetLowering &TLI);
+
+ /// set - Initialize this FunctionLoweringInfo with the given Function
+ /// and its associated MachineFunction.
+ ///
+ void set(const Function &Fn, MachineFunction &MF);
+
+ /// clear - Clear out all the function-specific state. This returns this
+ /// FunctionLoweringInfo to an empty state, ready to be used for a
+ /// different function.
+ void clear();
+
+ /// isExportedInst - Return true if the specified value is an instruction
+ /// exported from its block.
+ bool isExportedInst(const Value *V) {
+ return ValueMap.count(V);
+ }
+
+ unsigned CreateReg(EVT VT);
+
+ unsigned CreateRegs(Type *Ty);
+
+ unsigned InitializeRegForValue(const Value *V) {
+ unsigned &R = ValueMap[V];
+ assert(R == 0 && "Already initialized this value register!");
+ return R = CreateRegs(V->getType());
+ }
+
+ /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
+ /// register is a PHI destination and the PHI's LiveOutInfo is not valid.
+ const LiveOutInfo *GetLiveOutRegInfo(unsigned Reg) {
+ if (!LiveOutRegInfo.inBounds(Reg))
+ return NULL;
+
+ const LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
+ if (!LOI->IsValid)
+ return NULL;
+
+ return LOI;
+ }
+
+ /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
+ /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
+ /// the register's LiveOutInfo is for a smaller bit width, it is extended to
+ /// the larger bit width by zero extension. The bit width must be no smaller
+ /// than the LiveOutInfo's existing bit width.
+ const LiveOutInfo *GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth);
+
+ /// AddLiveOutRegInfo - Adds LiveOutInfo for a register.
+ void AddLiveOutRegInfo(unsigned Reg, unsigned NumSignBits,
+ const APInt &KnownZero, const APInt &KnownOne) {
+ // Only install this information if it tells us something.
+ if (NumSignBits == 1 && KnownZero == 0 && KnownOne == 0)
+ return;
+
+ LiveOutRegInfo.grow(Reg);
+ LiveOutInfo &LOI = LiveOutRegInfo[Reg];
+ LOI.NumSignBits = NumSignBits;
+ LOI.KnownOne = KnownOne;
+ LOI.KnownZero = KnownZero;
+ }
+
+ /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
+ /// register based on the LiveOutInfo of its operands.
+ void ComputePHILiveOutRegInfo(const PHINode*);
+
+ /// InvalidatePHILiveOutRegInfo - Invalidates a PHI's LiveOutInfo, to be
+ /// called when a block is visited before all of its predecessors.
+ void InvalidatePHILiveOutRegInfo(const PHINode *PN) {
+ // PHIs with no uses have no ValueMap entry.
+ DenseMap<const Value*, unsigned>::const_iterator It = ValueMap.find(PN);
+ if (It == ValueMap.end())
+ return;
+
+ unsigned Reg = It->second;
+ LiveOutRegInfo.grow(Reg);
+ LiveOutRegInfo[Reg].IsValid = false;
+ }
+
+ /// setArgumentFrameIndex - Record frame index for the byval
+ /// argument.
+ void setArgumentFrameIndex(const Argument *A, int FI);
+
+ /// getArgumentFrameIndex - Get frame index for the byval argument.
+ int getArgumentFrameIndex(const Argument *A);
+
+private:
+ /// LiveOutRegInfo - Information about live out vregs.
+ IndexedMap<LiveOutInfo, VirtReg2IndexFunctor> LiveOutRegInfo;
+};
+
+/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
+/// being passed to this variadic function, and set the MachineModuleInfo's
+/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
+/// reference to _fltused on Windows, which will link in MSVCRT's
+/// floating-point support.
+void ComputeUsesVAFloatArgument(const CallInst &I, MachineModuleInfo *MMI);
+
+/// AddCatchInfo - Extract the personality and type infos from an eh.selector
+/// call, and add them to the specified machine basic block.
+void AddCatchInfo(const CallInst &I,
+ MachineModuleInfo *MMI, MachineBasicBlock *MBB);
+
+/// AddLandingPadInfo - Extract the exception handling information from the
+/// landingpad instruction and add them to the specified machine module info.
+void AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
+ MachineBasicBlock *MBB);
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/GCMetadata.h b/include/llvm/CodeGen/GCMetadata.h
new file mode 100644
index 00000000000..20e33f74f65
--- /dev/null
+++ b/include/llvm/CodeGen/GCMetadata.h
@@ -0,0 +1,194 @@
+//===-- GCMetadata.h - Garbage collector metadata ---------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the GCFunctionInfo and GCModuleInfo classes, which are
+// used as a communication channel from the target code generator to the target
+// garbage collectors. This interface allows code generators and garbage
+// collectors to be developed independently.
+//
+// The GCFunctionInfo class logs the data necessary to build a type accurate
+// stack map. The code generator outputs:
+//
+// - Safe points as specified by the GCStrategy's NeededSafePoints.
+// - Stack offsets for GC roots, as specified by calls to llvm.gcroot
+//
+// As a refinement, liveness analysis calculates the set of live roots at each
+// safe point. Liveness analysis is not presently performed by the code
+// generator, so all roots are assumed live.
+//
+// GCModuleInfo simply collects GCFunctionInfo instances for each Function as
+// they are compiled. This accretion is necessary for collectors which must emit
+// a stack map for the compilation unit as a whole. Therefore, GCFunctionInfo
+// outlives the MachineFunction from which it is derived and must not refer to
+// any code generator data structures.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_GCMETADATA_H
+#define LLVM_CODEGEN_GCMETADATA_H
+
+#include "llvm/Pass.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/Support/DebugLoc.h"
+
+namespace llvm {
+ class AsmPrinter;
+ class GCStrategy;
+ class Constant;
+ class MCSymbol;
+
+ namespace GC {
+ /// PointKind - The type of a collector-safe point.
+ ///
+ enum PointKind {
+ Loop, ///< Instr is a loop (backwards branch).
+ Return, ///< Instr is a return instruction.
+ PreCall, ///< Instr is a call instruction.
+ PostCall ///< Instr is the return address of a call.
+ };
+ }
+
+ /// GCPoint - Metadata for a collector-safe point in machine code.
+ ///
+ struct GCPoint {
+ GC::PointKind Kind; ///< The kind of the safe point.
+ MCSymbol *Label; ///< A label.
+ DebugLoc Loc;
+
+ GCPoint(GC::PointKind K, MCSymbol *L, DebugLoc DL)
+ : Kind(K), Label(L), Loc(DL) {}
+ };
+
+ /// GCRoot - Metadata for a pointer to an object managed by the garbage
+ /// collector.
+ struct GCRoot {
+ int Num; ///< Usually a frame index.
+ int StackOffset; ///< Offset from the stack pointer.
+ const Constant *Metadata; ///< Metadata straight from the call
+ ///< to llvm.gcroot.
+
+ GCRoot(int N, const Constant *MD) : Num(N), StackOffset(-1), Metadata(MD) {}
+ };
+
+
+ /// GCFunctionInfo - Garbage collection metadata for a single function.
+ ///
+ class GCFunctionInfo {
+ public:
+ typedef std::vector<GCPoint>::iterator iterator;
+ typedef std::vector<GCRoot>::iterator roots_iterator;
+ typedef std::vector<GCRoot>::const_iterator live_iterator;
+
+ private:
+ const Function &F;
+ GCStrategy &S;
+ uint64_t FrameSize;
+ std::vector<GCRoot> Roots;
+ std::vector<GCPoint> SafePoints;
+
+ // FIXME: Liveness. A 2D BitVector, perhaps?
+ //
+ // BitVector Liveness;
+ //
+ // bool islive(int point, int root) =
+ // Liveness[point * SafePoints.size() + root]
+ //
+ // The bit vector is the more compact representation where >3.2% of roots
+ // are live per safe point (1.5% on 64-bit hosts).
+
+ public:
+ GCFunctionInfo(const Function &F, GCStrategy &S);
+ ~GCFunctionInfo();
+
+ /// getFunction - Return the function to which this metadata applies.
+ ///
+ const Function &getFunction() const { return F; }
+
+ /// getStrategy - Return the GC strategy for the function.
+ ///
+ GCStrategy &getStrategy() { return S; }
+
+ /// addStackRoot - Registers a root that lives on the stack. Num is the
+ /// stack object ID for the alloca (if the code generator is
+ // using MachineFrameInfo).
+ void addStackRoot(int Num, const Constant *Metadata) {
+ Roots.push_back(GCRoot(Num, Metadata));
+ }
+
+ /// addSafePoint - Notes the existence of a safe point. Num is the ID of the
+ /// label just prior to the safe point (if the code generator is using
+ /// MachineModuleInfo).
+ void addSafePoint(GC::PointKind Kind, MCSymbol *Label, DebugLoc DL) {
+ SafePoints.push_back(GCPoint(Kind, Label, DL));
+ }
+
+ /// getFrameSize/setFrameSize - Records the function's frame size.
+ ///
+ uint64_t getFrameSize() const { return FrameSize; }
+ void setFrameSize(uint64_t S) { FrameSize = S; }
+
+ /// begin/end - Iterators for safe points.
+ ///
+ iterator begin() { return SafePoints.begin(); }
+ iterator end() { return SafePoints.end(); }
+ size_t size() const { return SafePoints.size(); }
+
+ /// roots_begin/roots_end - Iterators for all roots in the function.
+ ///
+ roots_iterator roots_begin() { return Roots.begin(); }
+ roots_iterator roots_end () { return Roots.end(); }
+ size_t roots_size() const { return Roots.size(); }
+
+ /// live_begin/live_end - Iterators for live roots at a given safe point.
+ ///
+ live_iterator live_begin(const iterator &p) { return roots_begin(); }
+ live_iterator live_end (const iterator &p) { return roots_end(); }
+ size_t live_size(const iterator &p) const { return roots_size(); }
+ };
+
+
+ /// GCModuleInfo - Garbage collection metadata for a whole module.
+ ///
+ class GCModuleInfo : public ImmutablePass {
+ typedef StringMap<GCStrategy*> strategy_map_type;
+ typedef std::vector<GCStrategy*> list_type;
+ typedef DenseMap<const Function*,GCFunctionInfo*> finfo_map_type;
+
+ strategy_map_type StrategyMap;
+ list_type StrategyList;
+ finfo_map_type FInfoMap;
+
+ GCStrategy *getOrCreateStrategy(const Module *M, const std::string &Name);
+
+ public:
+ typedef list_type::const_iterator iterator;
+
+ static char ID;
+
+ GCModuleInfo();
+ ~GCModuleInfo();
+
+ /// clear - Resets the pass. The metadata deleter pass calls this.
+ ///
+ void clear();
+
+ /// begin/end - Iterators for used strategies.
+ ///
+ iterator begin() const { return StrategyList.begin(); }
+ iterator end() const { return StrategyList.end(); }
+
+ /// get - Look up function metadata.
+ ///
+ GCFunctionInfo &getFunctionInfo(const Function &F);
+ };
+
+}
+
+#endif
diff --git a/include/llvm/CodeGen/GCMetadataPrinter.h b/include/llvm/CodeGen/GCMetadataPrinter.h
new file mode 100644
index 00000000000..4a6b5ac19c3
--- /dev/null
+++ b/include/llvm/CodeGen/GCMetadataPrinter.h
@@ -0,0 +1,74 @@
+//===-- llvm/CodeGen/GCMetadataPrinter.h - Prints asm GC tables -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The abstract base class GCMetadataPrinter supports writing GC metadata tables
+// as assembly code. This is a separate class from GCStrategy in order to allow
+// users of the LLVM JIT to avoid linking with the AsmWriter.
+//
+// Subclasses of GCMetadataPrinter must be registered using the
+// GCMetadataPrinterRegistry. This is separate from the GCStrategy itself
+// because these subclasses are logically plugins for the AsmWriter.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_GCMETADATAPRINTER_H
+#define LLVM_CODEGEN_GCMETADATAPRINTER_H
+
+#include "llvm/CodeGen/GCMetadata.h"
+#include "llvm/CodeGen/GCStrategy.h"
+#include "llvm/Support/Registry.h"
+
+namespace llvm {
+
+ class GCMetadataPrinter;
+
+ /// GCMetadataPrinterRegistry - The GC assembly printer registry uses all the
+ /// defaults from Registry.
+ typedef Registry<GCMetadataPrinter> GCMetadataPrinterRegistry;
+
+ /// GCMetadataPrinter - Emits GC metadata as assembly code.
+ ///
+ class GCMetadataPrinter {
+ public:
+ typedef GCStrategy::list_type list_type;
+ typedef GCStrategy::iterator iterator;
+
+ private:
+ GCStrategy *S;
+
+ friend class AsmPrinter;
+
+ protected:
+ // May only be subclassed.
+ GCMetadataPrinter();
+
+ private:
+ GCMetadataPrinter(const GCMetadataPrinter &) LLVM_DELETED_FUNCTION;
+ GCMetadataPrinter &
+ operator=(const GCMetadataPrinter &) LLVM_DELETED_FUNCTION;
+
+ public:
+ GCStrategy &getStrategy() { return *S; }
+ const Module &getModule() const { return S->getModule(); }
+
+ /// begin/end - Iterate over the collected function metadata.
+ iterator begin() { return S->begin(); }
+ iterator end() { return S->end(); }
+
+ /// beginAssembly/finishAssembly - Emit module metadata as assembly code.
+ virtual void beginAssembly(AsmPrinter &AP);
+
+ virtual void finishAssembly(AsmPrinter &AP);
+
+ virtual ~GCMetadataPrinter();
+ };
+
+}
+
+#endif
diff --git a/include/llvm/CodeGen/GCStrategy.h b/include/llvm/CodeGen/GCStrategy.h
new file mode 100644
index 00000000000..dfc26d72dc9
--- /dev/null
+++ b/include/llvm/CodeGen/GCStrategy.h
@@ -0,0 +1,153 @@
+//===-- llvm/CodeGen/GCStrategy.h - Garbage collection ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// GCStrategy coordinates code generation algorithms and implements some itself
+// in order to generate code compatible with a target code generator as
+// specified in a function's 'gc' attribute. Algorithms are enabled by setting
+// flags in a subclass's constructor, and some virtual methods can be
+// overridden.
+//
+// When requested, the GCStrategy will be populated with data about each
+// function which uses it. Specifically:
+//
+// - Safe points
+// Garbage collection is generally only possible at certain points in code.
+// GCStrategy can request that the collector insert such points:
+//
+// - At and after any call to a subroutine
+// - Before returning from the current function
+// - Before backwards branches (loops)
+//
+// - Roots
+// When a reference to a GC-allocated object exists on the stack, it must be
+// stored in an alloca registered with llvm.gcoot.
+//
+// This information can used to emit the metadata tables which are required by
+// the target garbage collector runtime.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_GCSTRATEGY_H
+#define LLVM_CODEGEN_GCSTRATEGY_H
+
+#include "llvm/CodeGen/GCMetadata.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/Support/Registry.h"
+#include <string>
+
+namespace llvm {
+
+ class GCStrategy;
+
+ /// The GC strategy registry uses all the defaults from Registry.
+ ///
+ typedef Registry<GCStrategy> GCRegistry;
+
+ /// GCStrategy describes a garbage collector algorithm's code generation
+ /// requirements, and provides overridable hooks for those needs which cannot
+ /// be abstractly described.
+ class GCStrategy {
+ public:
+ typedef std::vector<GCFunctionInfo*> list_type;
+ typedef list_type::iterator iterator;
+
+ private:
+ friend class GCModuleInfo;
+ const Module *M;
+ std::string Name;
+
+ list_type Functions;
+
+ protected:
+ unsigned NeededSafePoints; ///< Bitmask of required safe points.
+ bool CustomReadBarriers; ///< Default is to insert loads.
+ bool CustomWriteBarriers; ///< Default is to insert stores.
+ bool CustomRoots; ///< Default is to pass through to backend.
+ bool CustomSafePoints; ///< Default is to use NeededSafePoints
+ ///< to find safe points.
+ bool InitRoots; ///< If set, roots are nulled during lowering.
+ bool UsesMetadata; ///< If set, backend must emit metadata tables.
+
+ public:
+ GCStrategy();
+
+ virtual ~GCStrategy();
+
+
+ /// getName - The name of the GC strategy, for debugging.
+ ///
+ const std::string &getName() const { return Name; }
+
+ /// getModule - The module within which the GC strategy is operating.
+ ///
+ const Module &getModule() const { return *M; }
+
+ /// needsSafePoitns - True if safe points of any kind are required. By
+ // default, none are recorded.
+ bool needsSafePoints() const {
+ return CustomSafePoints || NeededSafePoints != 0;
+ }
+
+ /// needsSafePoint(Kind) - True if the given kind of safe point is
+ // required. By default, none are recorded.
+ bool needsSafePoint(GC::PointKind Kind) const {
+ return (NeededSafePoints & 1 << Kind) != 0;
+ }
+
+ /// customWriteBarrier - By default, write barriers are replaced with simple
+ /// store instructions. If true, then
+ /// performCustomLowering must instead lower them.
+ bool customWriteBarrier() const { return CustomWriteBarriers; }
+
+ /// customReadBarrier - By default, read barriers are replaced with simple
+ /// load instructions. If true, then
+ /// performCustomLowering must instead lower them.
+ bool customReadBarrier() const { return CustomReadBarriers; }
+
+ /// customRoots - By default, roots are left for the code generator so it
+ /// can generate a stack map. If true, then
+ // performCustomLowering must delete them.
+ bool customRoots() const { return CustomRoots; }
+
+ /// customSafePoints - By default, the GC analysis will find safe
+ /// points according to NeededSafePoints. If true,
+ /// then findCustomSafePoints must create them.
+ bool customSafePoints() const { return CustomSafePoints; }
+
+ /// initializeRoots - If set, gcroot intrinsics should initialize their
+ // allocas to null before the first use. This is
+ // necessary for most GCs and is enabled by default.
+ bool initializeRoots() const { return InitRoots; }
+
+ /// usesMetadata - If set, appropriate metadata tables must be emitted by
+ /// the back-end (assembler, JIT, or otherwise).
+ bool usesMetadata() const { return UsesMetadata; }
+
+ /// begin/end - Iterators for function metadata.
+ ///
+ iterator begin() { return Functions.begin(); }
+ iterator end() { return Functions.end(); }
+
+ /// insertFunctionMetadata - Creates metadata for a function.
+ ///
+ GCFunctionInfo *insertFunctionInfo(const Function &F);
+
+ /// initializeCustomLowering/performCustomLowering - If any of the actions
+ /// are set to custom, performCustomLowering must be overriden to transform
+ /// the corresponding actions to LLVM IR. initializeCustomLowering is
+ /// optional to override. These are the only GCStrategy methods through
+ /// which the LLVM IR can be modified.
+ virtual bool initializeCustomLowering(Module &F);
+ virtual bool performCustomLowering(Function &F);
+ virtual bool findCustomSafePoints(GCFunctionInfo& FI, MachineFunction& MF);
+ };
+
+}
+
+#endif
diff --git a/include/llvm/CodeGen/GCs.h b/include/llvm/CodeGen/GCs.h
new file mode 100644
index 00000000000..c407b616748
--- /dev/null
+++ b/include/llvm/CodeGen/GCs.h
@@ -0,0 +1,35 @@
+//===-- GCs.h - Garbage collector linkage hacks ---------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains hack functions to force linking in the GC components.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_GCS_H
+#define LLVM_CODEGEN_GCS_H
+
+namespace llvm {
+ class GCStrategy;
+ class GCMetadataPrinter;
+
+ /// FIXME: Collector instances are not useful on their own. These no longer
+ /// serve any purpose except to link in the plugins.
+
+ /// Creates an ocaml-compatible garbage collector.
+ void linkOcamlGC();
+
+ /// Creates an ocaml-compatible metadata printer.
+ void linkOcamlGCPrinter();
+
+ /// Creates a shadow stack garbage collector. This collector requires no code
+ /// generator support.
+ void linkShadowStackGC();
+}
+
+#endif
diff --git a/include/llvm/CodeGen/ISDOpcodes.h b/include/llvm/CodeGen/ISDOpcodes.h
new file mode 100644
index 00000000000..5d0a3b4c706
--- /dev/null
+++ b/include/llvm/CodeGen/ISDOpcodes.h
@@ -0,0 +1,822 @@
+//===-- llvm/CodeGen/ISDOpcodes.h - CodeGen opcodes -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares codegen opcodes and related utilities.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_ISDOPCODES_H
+#define LLVM_CODEGEN_ISDOPCODES_H
+
+namespace llvm {
+
+/// ISD namespace - This namespace contains an enum which represents all of the
+/// SelectionDAG node types and value types.
+///
+namespace ISD {
+
+ //===--------------------------------------------------------------------===//
+ /// ISD::NodeType enum - This enum defines the target-independent operators
+ /// for a SelectionDAG.
+ ///
+ /// Targets may also define target-dependent operator codes for SDNodes. For
+ /// example, on x86, these are the enum values in the X86ISD namespace.
+ /// Targets should aim to use target-independent operators to model their
+ /// instruction sets as much as possible, and only use target-dependent
+ /// operators when they have special requirements.
+ ///
+ /// Finally, during and after selection proper, SNodes may use special
+ /// operator codes that correspond directly with MachineInstr opcodes. These
+ /// are used to represent selected instructions. See the isMachineOpcode()
+ /// and getMachineOpcode() member functions of SDNode.
+ ///
+ enum NodeType {
+ /// DELETED_NODE - This is an illegal value that is used to catch
+ /// errors. This opcode is not a legal opcode for any node.
+ DELETED_NODE,
+
+ /// EntryToken - This is the marker used to indicate the start of a region.
+ EntryToken,
+
+ /// TokenFactor - This node takes multiple tokens as input and produces a
+ /// single token result. This is used to represent the fact that the operand
+ /// operators are independent of each other.
+ TokenFactor,
+
+ /// AssertSext, AssertZext - These nodes record if a register contains a
+ /// value that has already been zero or sign extended from a narrower type.
+ /// These nodes take two operands. The first is the node that has already
+ /// been extended, and the second is a value type node indicating the width
+ /// of the extension
+ AssertSext, AssertZext,
+
+ /// Various leaf nodes.
+ BasicBlock, VALUETYPE, CONDCODE, Register, RegisterMask,
+ Constant, ConstantFP,
+ GlobalAddress, GlobalTLSAddress, FrameIndex,
+ JumpTable, ConstantPool, ExternalSymbol, BlockAddress,
+
+ /// The address of the GOT
+ GLOBAL_OFFSET_TABLE,
+
+ /// FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and
+ /// llvm.returnaddress on the DAG. These nodes take one operand, the index
+ /// of the frame or return address to return. An index of zero corresponds
+ /// to the current function's frame or return address, an index of one to
+ /// the parent's frame or return address, and so on.
+ FRAMEADDR, RETURNADDR,
+
+ /// FRAME_TO_ARGS_OFFSET - This node represents offset from frame pointer to
+ /// first (possible) on-stack argument. This is needed for correct stack
+ /// adjustment during unwind.
+ FRAME_TO_ARGS_OFFSET,
+
+ /// RESULT, OUTCHAIN = EXCEPTIONADDR(INCHAIN) - This node represents the
+ /// address of the exception block on entry to an landing pad block.
+ EXCEPTIONADDR,
+
+ /// RESULT, OUTCHAIN = LSDAADDR(INCHAIN) - This node represents the
+ /// address of the Language Specific Data Area for the enclosing function.
+ LSDAADDR,
+
+ /// RESULT, OUTCHAIN = EHSELECTION(INCHAIN, EXCEPTION) - This node
+ /// represents the selection index of the exception thrown.
+ EHSELECTION,
+
+ /// OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents
+ /// 'eh_return' gcc dwarf builtin, which is used to return from
+ /// exception. The general meaning is: adjust stack by OFFSET and pass
+ /// execution to HANDLER. Many platform-related details also :)
+ EH_RETURN,
+
+ /// RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer)
+ /// This corresponds to the eh.sjlj.setjmp intrinsic.
+ /// It takes an input chain and a pointer to the jump buffer as inputs
+ /// and returns an outchain.
+ EH_SJLJ_SETJMP,
+
+ /// OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer)
+ /// This corresponds to the eh.sjlj.longjmp intrinsic.
+ /// It takes an input chain and a pointer to the jump buffer as inputs
+ /// and returns an outchain.
+ EH_SJLJ_LONGJMP,
+
+ /// TargetConstant* - Like Constant*, but the DAG does not do any folding,
+ /// simplification, or lowering of the constant. They are used for constants
+ /// which are known to fit in the immediate fields of their users, or for
+ /// carrying magic numbers which are not values which need to be
+ /// materialized in registers.
+ TargetConstant,
+ TargetConstantFP,
+
+ /// TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or
+ /// anything else with this node, and this is valid in the target-specific
+ /// dag, turning into a GlobalAddress operand.
+ TargetGlobalAddress,
+ TargetGlobalTLSAddress,
+ TargetFrameIndex,
+ TargetJumpTable,
+ TargetConstantPool,
+ TargetExternalSymbol,
+ TargetBlockAddress,
+
+ /// TargetIndex - Like a constant pool entry, but with completely
+ /// target-dependent semantics. Holds target flags, a 32-bit index, and a
+ /// 64-bit index. Targets can use this however they like.
+ TargetIndex,
+
+ /// RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...)
+ /// This node represents a target intrinsic function with no side effects.
+ /// The first operand is the ID number of the intrinsic from the
+ /// llvm::Intrinsic namespace. The operands to the intrinsic follow. The
+ /// node returns the result of the intrinsic.
+ INTRINSIC_WO_CHAIN,
+
+ /// RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...)
+ /// This node represents a target intrinsic function with side effects that
+ /// returns a result. The first operand is a chain pointer. The second is
+ /// the ID number of the intrinsic from the llvm::Intrinsic namespace. The
+ /// operands to the intrinsic follow. The node has two results, the result
+ /// of the intrinsic and an output chain.
+ INTRINSIC_W_CHAIN,
+
+ /// OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...)
+ /// This node represents a target intrinsic function with side effects that
+ /// does not return a result. The first operand is a chain pointer. The
+ /// second is the ID number of the intrinsic from the llvm::Intrinsic
+ /// namespace. The operands to the intrinsic follow.
+ INTRINSIC_VOID,
+
+ /// CopyToReg - This node has three operands: a chain, a register number to
+ /// set to this value, and a value.
+ CopyToReg,
+
+ /// CopyFromReg - This node indicates that the input value is a virtual or
+ /// physical register that is defined outside of the scope of this
+ /// SelectionDAG. The register is available from the RegisterSDNode object.
+ CopyFromReg,
+
+ /// UNDEF - An undefined node.
+ UNDEF,
+
+ /// EXTRACT_ELEMENT - This is used to get the lower or upper (determined by
+ /// a Constant, which is required to be operand #1) half of the integer or
+ /// float value specified as operand #0. This is only for use before
+ /// legalization, for values that will be broken into multiple registers.
+ EXTRACT_ELEMENT,
+
+ /// BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
+ /// Given two values of the same integer value type, this produces a value
+ /// twice as big. Like EXTRACT_ELEMENT, this can only be used before
+ /// legalization.
+ BUILD_PAIR,
+
+ /// MERGE_VALUES - This node takes multiple discrete operands and returns
+ /// them all as its individual results. This nodes has exactly the same
+ /// number of inputs and outputs. This node is useful for some pieces of the
+ /// code generator that want to think about a single node with multiple
+ /// results, not multiple nodes.
+ MERGE_VALUES,
+
+ /// Simple integer binary arithmetic operators.
+ ADD, SUB, MUL, SDIV, UDIV, SREM, UREM,
+
+ /// SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing
+ /// a signed/unsigned value of type i[2*N], and return the full value as
+ /// two results, each of type iN.
+ SMUL_LOHI, UMUL_LOHI,
+
+ /// SDIVREM/UDIVREM - Divide two integers and produce both a quotient and
+ /// remainder result.
+ SDIVREM, UDIVREM,
+
+ /// CARRY_FALSE - This node is used when folding other nodes,
+ /// like ADDC/SUBC, which indicate the carry result is always false.
+ CARRY_FALSE,
+
+ /// Carry-setting nodes for multiple precision addition and subtraction.
+ /// These nodes take two operands of the same value type, and produce two
+ /// results. The first result is the normal add or sub result, the second
+ /// result is the carry flag result.
+ ADDC, SUBC,
+
+ /// Carry-using nodes for multiple precision addition and subtraction. These
+ /// nodes take three operands: The first two are the normal lhs and rhs to
+ /// the add or sub, and the third is the input carry flag. These nodes
+ /// produce two results; the normal result of the add or sub, and the output
+ /// carry flag. These nodes both read and write a carry flag to allow them
+ /// to them to be chained together for add and sub of arbitrarily large
+ /// values.
+ ADDE, SUBE,
+
+ /// RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
+ /// These nodes take two operands: the normal LHS and RHS to the add. They
+ /// produce two results: the normal result of the add, and a boolean that
+ /// indicates if an overflow occurred (*not* a flag, because it may be store
+ /// to memory, etc.). If the type of the boolean is not i1 then the high
+ /// bits conform to getBooleanContents.
+ /// These nodes are generated from llvm.[su]add.with.overflow intrinsics.
+ SADDO, UADDO,
+
+ /// Same for subtraction.
+ SSUBO, USUBO,
+
+ /// Same for multiplication.
+ SMULO, UMULO,
+
+ /// Simple binary floating point operators.
+ FADD, FSUB, FMUL, FMA, FDIV, FREM,
+
+ /// FCOPYSIGN(X, Y) - Return the value of X with the sign of Y. NOTE: This
+ /// DAG node does not require that X and Y have the same type, just that the
+ /// are both floating point. X and the result must have the same type.
+ /// FCOPYSIGN(f32, f64) is allowed.
+ FCOPYSIGN,
+
+ /// INT = FGETSIGN(FP) - Return the sign bit of the specified floating point
+ /// value as an integer 0/1 value.
+ FGETSIGN,
+
+ /// BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a vector with the
+ /// specified, possibly variable, elements. The number of elements is
+ /// required to be a power of two. The types of the operands must all be
+ /// the same and must match the vector element type, except that integer
+ /// types are allowed to be larger than the element type, in which case
+ /// the operands are implicitly truncated.
+ BUILD_VECTOR,
+
+ /// INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element
+ /// at IDX replaced with VAL. If the type of VAL is larger than the vector
+ /// element type then VAL is truncated before replacement.
+ INSERT_VECTOR_ELT,
+
+ /// EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR
+ /// identified by the (potentially variable) element number IDX. If the
+ /// return type is an integer type larger than the element type of the
+ /// vector, the result is extended to the width of the return type.
+ EXTRACT_VECTOR_ELT,
+
+ /// CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of
+ /// vector type with the same length and element type, this produces a
+ /// concatenated vector result value, with length equal to the sum of the
+ /// lengths of the input vectors.
+ CONCAT_VECTORS,
+
+ /// INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector
+ /// with VECTOR2 inserted into VECTOR1 at the (potentially
+ /// variable) element number IDX, which must be a multiple of the
+ /// VECTOR2 vector length. The elements of VECTOR1 starting at
+ /// IDX are overwritten with VECTOR2. Elements IDX through
+ /// vector_length(VECTOR2) must be valid VECTOR1 indices.
+ INSERT_SUBVECTOR,
+
+ /// EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR (an
+ /// vector value) starting with the element number IDX, which must be a
+ /// constant multiple of the result vector length.
+ EXTRACT_SUBVECTOR,
+
+ /// VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as
+ /// VEC1/VEC2. A VECTOR_SHUFFLE node also contains an array of constant int
+ /// values that indicate which value (or undef) each result element will
+ /// get. These constant ints are accessible through the
+ /// ShuffleVectorSDNode class. This is quite similar to the Altivec
+ /// 'vperm' instruction, except that the indices must be constants and are
+ /// in terms of the element size of VEC1/VEC2, not in terms of bytes.
+ VECTOR_SHUFFLE,
+
+ /// SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a
+ /// scalar value into element 0 of the resultant vector type. The top
+ /// elements 1 to N-1 of the N-element vector are undefined. The type
+ /// of the operand must match the vector element type, except when they
+ /// are integer types. In this case the operand is allowed to be wider
+ /// than the vector element type, and is implicitly truncated to it.
+ SCALAR_TO_VECTOR,
+
+ /// MULHU/MULHS - Multiply high - Multiply two integers of type iN,
+ /// producing an unsigned/signed value of type i[2*N], then return the top
+ /// part.
+ MULHU, MULHS,
+
+ /// Bitwise operators - logical and, logical or, logical xor.
+ AND, OR, XOR,
+
+ /// Shift and rotation operations. After legalization, the type of the
+ /// shift amount is known to be TLI.getShiftAmountTy(). Before legalization
+ /// the shift amount can be any type, but care must be taken to ensure it is
+ /// large enough. TLI.getShiftAmountTy() is i8 on some targets, but before
+ /// legalization, types like i1024 can occur and i8 doesn't have enough bits
+ /// to represent the shift amount. By convention, DAGCombine and
+ /// SelectionDAGBuilder forces these shift amounts to i32 for simplicity.
+ SHL, SRA, SRL, ROTL, ROTR,
+
+ /// Byte Swap and Counting operators.
+ BSWAP, CTTZ, CTLZ, CTPOP,
+
+ /// Bit counting operators with an undefined result for zero inputs.
+ CTTZ_ZERO_UNDEF, CTLZ_ZERO_UNDEF,
+
+ /// Select(COND, TRUEVAL, FALSEVAL). If the type of the boolean COND is not
+ /// i1 then the high bits must conform to getBooleanContents.
+ SELECT,
+
+ /// Select with a vector condition (op #0) and two vector operands (ops #1
+ /// and #2), returning a vector result. All vectors have the same length.
+ /// Much like the scalar select and setcc, each bit in the condition selects
+ /// whether the corresponding result element is taken from op #1 or op #2.
+ /// At first, the VSELECT condition is of vXi1 type. Later, targets may
+ /// change the condition type in order to match the VSELECT node using a
+ /// pattern. The condition follows the BooleanContent format of the target.
+ VSELECT,
+
+ /// Select with condition operator - This selects between a true value and
+ /// a false value (ops #2 and #3) based on the boolean result of comparing
+ /// the lhs and rhs (ops #0 and #1) of a conditional expression with the
+ /// condition code in op #4, a CondCodeSDNode.
+ SELECT_CC,
+
+ /// SetCC operator - This evaluates to a true value iff the condition is
+ /// true. If the result value type is not i1 then the high bits conform
+ /// to getBooleanContents. The operands to this are the left and right
+ /// operands to compare (ops #0, and #1) and the condition code to compare
+ /// them with (op #2) as a CondCodeSDNode. If the operands are vector types
+ /// then the result type must also be a vector type.
+ SETCC,
+
+ /// SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded
+ /// integer shift operations, just like ADD/SUB_PARTS. The operation
+ /// ordering is:
+ /// [Lo,Hi] = op [LoLHS,HiLHS], Amt
+ SHL_PARTS, SRA_PARTS, SRL_PARTS,
+
+ /// Conversion operators. These are all single input single output
+ /// operations. For all of these, the result type must be strictly
+ /// wider or narrower (depending on the operation) than the source
+ /// type.
+
+ /// SIGN_EXTEND - Used for integer types, replicating the sign bit
+ /// into new bits.
+ SIGN_EXTEND,
+
+ /// ZERO_EXTEND - Used for integer types, zeroing the new bits.
+ ZERO_EXTEND,
+
+ /// ANY_EXTEND - Used for integer types. The high bits are undefined.
+ ANY_EXTEND,
+
+ /// TRUNCATE - Completely drop the high bits.
+ TRUNCATE,
+
+ /// [SU]INT_TO_FP - These operators convert integers (whose interpreted sign
+ /// depends on the first letter) to floating point.
+ SINT_TO_FP,
+ UINT_TO_FP,
+
+ /// SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to
+ /// sign extend a small value in a large integer register (e.g. sign
+ /// extending the low 8 bits of a 32-bit register to fill the top 24 bits
+ /// with the 7th bit). The size of the smaller type is indicated by the 1th
+ /// operand, a ValueType node.
+ SIGN_EXTEND_INREG,
+
+ /// FP_TO_[US]INT - Convert a floating point value to a signed or unsigned
+ /// integer.
+ FP_TO_SINT,
+ FP_TO_UINT,
+
+ /// X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type
+ /// down to the precision of the destination VT. TRUNC is a flag, which is
+ /// always an integer that is zero or one. If TRUNC is 0, this is a
+ /// normal rounding, if it is 1, this FP_ROUND is known to not change the
+ /// value of Y.
+ ///
+ /// The TRUNC = 1 case is used in cases where we know that the value will
+ /// not be modified by the node, because Y is not using any of the extra
+ /// precision of source type. This allows certain transformations like
+ /// FP_EXTEND(FP_ROUND(X,1)) -> X which are not safe for
+ /// FP_EXTEND(FP_ROUND(X,0)) because the extra bits aren't removed.
+ FP_ROUND,
+
+ /// FLT_ROUNDS_ - Returns current rounding mode:
+ /// -1 Undefined
+ /// 0 Round to 0
+ /// 1 Round to nearest
+ /// 2 Round to +inf
+ /// 3 Round to -inf
+ FLT_ROUNDS_,
+
+ /// X = FP_ROUND_INREG(Y, VT) - This operator takes an FP register, and
+ /// rounds it to a floating point value. It then promotes it and returns it
+ /// in a register of the same size. This operation effectively just
+ /// discards excess precision. The type to round down to is specified by
+ /// the VT operand, a VTSDNode.
+ FP_ROUND_INREG,
+
+ /// X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
+ FP_EXTEND,
+
+ /// BITCAST - This operator converts between integer, vector and FP
+ /// values, as if the value was stored to memory with one type and loaded
+ /// from the same address with the other type (or equivalently for vector
+ /// format conversions, etc). The source and result are required to have
+ /// the same bit size (e.g. f32 <-> i32). This can also be used for
+ /// int-to-int or fp-to-fp conversions, but that is a noop, deleted by
+ /// getNode().
+ BITCAST,
+
+ /// CONVERT_RNDSAT - This operator is used to support various conversions
+ /// between various types (float, signed, unsigned and vectors of those
+ /// types) with rounding and saturation. NOTE: Avoid using this operator as
+ /// most target don't support it and the operator might be removed in the
+ /// future. It takes the following arguments:
+ /// 0) value
+ /// 1) dest type (type to convert to)
+ /// 2) src type (type to convert from)
+ /// 3) rounding imm
+ /// 4) saturation imm
+ /// 5) ISD::CvtCode indicating the type of conversion to do
+ CONVERT_RNDSAT,
+
+ /// FP16_TO_FP32, FP32_TO_FP16 - These operators are used to perform
+ /// promotions and truncation for half-precision (16 bit) floating
+ /// numbers. We need special nodes since FP16 is a storage-only type with
+ /// special semantics of operations.
+ FP16_TO_FP32, FP32_TO_FP16,
+
+ /// FNEG, FABS, FSQRT, FSIN, FCOS, FPOWI, FPOW,
+ /// FLOG, FLOG2, FLOG10, FEXP, FEXP2,
+ /// FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR - Perform various unary
+ /// floating point operations. These are inspired by libm.
+ FNEG, FABS, FSQRT, FSIN, FCOS, FPOWI, FPOW,
+ FLOG, FLOG2, FLOG10, FEXP, FEXP2,
+ FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR,
+
+ /// LOAD and STORE have token chains as their first operand, then the same
+ /// operands as an LLVM load/store instruction, then an offset node that
+ /// is added / subtracted from the base pointer to form the address (for
+ /// indexed memory ops).
+ LOAD, STORE,
+
+ /// DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned
+ /// to a specified boundary. This node always has two return values: a new
+ /// stack pointer value and a chain. The first operand is the token chain,
+ /// the second is the number of bytes to allocate, and the third is the
+ /// alignment boundary. The size is guaranteed to be a multiple of the
+ /// stack alignment, and the alignment is guaranteed to be bigger than the
+ /// stack alignment (if required) or 0 to get standard stack alignment.
+ DYNAMIC_STACKALLOC,
+
+ /// Control flow instructions. These all have token chains.
+
+ /// BR - Unconditional branch. The first operand is the chain
+ /// operand, the second is the MBB to branch to.
+ BR,
+
+ /// BRIND - Indirect branch. The first operand is the chain, the second
+ /// is the value to branch to, which must be of the same type as the
+ /// target's pointer type.
+ BRIND,
+
+ /// BR_JT - Jumptable branch. The first operand is the chain, the second
+ /// is the jumptable index, the last one is the jumptable entry index.
+ BR_JT,
+
+ /// BRCOND - Conditional branch. The first operand is the chain, the
+ /// second is the condition, the third is the block to branch to if the
+ /// condition is true. If the type of the condition is not i1, then the
+ /// high bits must conform to getBooleanContents.
+ BRCOND,
+
+ /// BR_CC - Conditional branch. The behavior is like that of SELECT_CC, in
+ /// that the condition is represented as condition code, and two nodes to
+ /// compare, rather than as a combined SetCC node. The operands in order
+ /// are chain, cc, lhs, rhs, block to branch to if condition is true.
+ BR_CC,
+
+ /// INLINEASM - Represents an inline asm block. This node always has two
+ /// return values: a chain and a flag result. The inputs are as follows:
+ /// Operand #0 : Input chain.
+ /// Operand #1 : a ExternalSymbolSDNode with a pointer to the asm string.
+ /// Operand #2 : a MDNodeSDNode with the !srcloc metadata.
+ /// Operand #3 : HasSideEffect, IsAlignStack bits.
+ /// After this, it is followed by a list of operands with this format:
+ /// ConstantSDNode: Flags that encode whether it is a mem or not, the
+ /// of operands that follow, etc. See InlineAsm.h.
+ /// ... however many operands ...
+ /// Operand #last: Optional, an incoming flag.
+ ///
+ /// The variable width operands are required to represent target addressing
+ /// modes as a single "operand", even though they may have multiple
+ /// SDOperands.
+ INLINEASM,
+
+ /// EH_LABEL - Represents a label in mid basic block used to track
+ /// locations needed for debug and exception handling tables. These nodes
+ /// take a chain as input and return a chain.
+ EH_LABEL,
+
+ /// STACKSAVE - STACKSAVE has one operand, an input chain. It produces a
+ /// value, the same type as the pointer type for the system, and an output
+ /// chain.
+ STACKSAVE,
+
+ /// STACKRESTORE has two operands, an input chain and a pointer to restore
+ /// to it returns an output chain.
+ STACKRESTORE,
+
+ /// CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end
+ /// of a call sequence, and carry arbitrary information that target might
+ /// want to know. The first operand is a chain, the rest are specified by
+ /// the target and not touched by the DAG optimizers.
+ /// CALLSEQ_START..CALLSEQ_END pairs may not be nested.
+ CALLSEQ_START, // Beginning of a call sequence
+ CALLSEQ_END, // End of a call sequence
+
+ /// VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE,
+ /// and the alignment. It returns a pair of values: the vaarg value and a
+ /// new chain.
+ VAARG,
+
+ /// VACOPY - VACOPY has 5 operands: an input chain, a destination pointer,
+ /// a source pointer, a SRCVALUE for the destination, and a SRCVALUE for the
+ /// source.
+ VACOPY,
+
+ /// VAEND, VASTART - VAEND and VASTART have three operands: an input chain,
+ /// pointer, and a SRCVALUE.
+ VAEND, VASTART,
+
+ /// SRCVALUE - This is a node type that holds a Value* that is used to
+ /// make reference to a value in the LLVM IR.
+ SRCVALUE,
+
+ /// MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to
+ /// reference metadata in the IR.
+ MDNODE_SDNODE,
+
+ /// PCMARKER - This corresponds to the pcmarker intrinsic.
+ PCMARKER,
+
+ /// READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
+ /// The only operand is a chain and a value and a chain are produced. The
+ /// value is the contents of the architecture specific cycle counter like
+ /// register (or other high accuracy low latency clock source)
+ READCYCLECOUNTER,
+
+ /// HANDLENODE node - Used as a handle for various purposes.
+ HANDLENODE,
+
+ /// INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic. It
+ /// takes as input a token chain, the pointer to the trampoline, the pointer
+ /// to the nested function, the pointer to pass for the 'nest' parameter, a
+ /// SRCVALUE for the trampoline and another for the nested function
+ /// (allowing targets to access the original Function*).
+ /// It produces a token chain as output.
+ INIT_TRAMPOLINE,
+
+ /// ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
+ /// It takes a pointer to the trampoline and produces a (possibly) new
+ /// pointer to the same trampoline with platform-specific adjustments
+ /// applied. The pointer it returns points to an executable block of code.
+ ADJUST_TRAMPOLINE,
+
+ /// TRAP - Trapping instruction
+ TRAP,
+
+ /// DEBUGTRAP - Trap intended to get the attention of a debugger.
+ DEBUGTRAP,
+
+ /// PREFETCH - This corresponds to a prefetch intrinsic. The first operand
+ /// is the chain. The other operands are the address to prefetch,
+ /// read / write specifier, locality specifier and instruction / data cache
+ /// specifier.
+ PREFETCH,
+
+ /// OUTCHAIN = MEMBARRIER(INCHAIN, load-load, load-store, store-load,
+ /// store-store, device)
+ /// This corresponds to the memory.barrier intrinsic.
+ /// it takes an input chain, 4 operands to specify the type of barrier, an
+ /// operand specifying if the barrier applies to device and uncached memory
+ /// and produces an output chain.
+ MEMBARRIER,
+
+ /// OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope)
+ /// This corresponds to the fence instruction. It takes an input chain, and
+ /// two integer constants: an AtomicOrdering and a SynchronizationScope.
+ ATOMIC_FENCE,
+
+ /// Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr)
+ /// This corresponds to "load atomic" instruction.
+ ATOMIC_LOAD,
+
+ /// OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr, val)
+ /// This corresponds to "store atomic" instruction.
+ ATOMIC_STORE,
+
+ /// Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap)
+ /// This corresponds to the cmpxchg instruction.
+ ATOMIC_CMP_SWAP,
+
+ /// Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt)
+ /// Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN, ptr, amt)
+ /// These correspond to the atomicrmw instruction.
+ ATOMIC_SWAP,
+ ATOMIC_LOAD_ADD,
+ ATOMIC_LOAD_SUB,
+ ATOMIC_LOAD_AND,
+ ATOMIC_LOAD_OR,
+ ATOMIC_LOAD_XOR,
+ ATOMIC_LOAD_NAND,
+ ATOMIC_LOAD_MIN,
+ ATOMIC_LOAD_MAX,
+ ATOMIC_LOAD_UMIN,
+ ATOMIC_LOAD_UMAX,
+
+ /// This corresponds to the llvm.lifetime.* intrinsics. The first operand
+ /// is the chain and the second operand is the alloca pointer.
+ LIFETIME_START, LIFETIME_END,
+
+ /// BUILTIN_OP_END - This must be the last enum value in this list.
+ /// The target-specific pre-isel opcode values start here.
+ BUILTIN_OP_END
+ };
+
+ /// FIRST_TARGET_MEMORY_OPCODE - Target-specific pre-isel operations
+ /// which do not reference a specific memory location should be less than
+ /// this value. Those that do must not be less than this value, and can
+ /// be used with SelectionDAG::getMemIntrinsicNode.
+ static const int FIRST_TARGET_MEMORY_OPCODE = BUILTIN_OP_END+150;
+
+ //===--------------------------------------------------------------------===//
+ /// MemIndexedMode enum - This enum defines the load / store indexed
+ /// addressing modes.
+ ///
+ /// UNINDEXED "Normal" load / store. The effective address is already
+ /// computed and is available in the base pointer. The offset
+ /// operand is always undefined. In addition to producing a
+ /// chain, an unindexed load produces one value (result of the
+ /// load); an unindexed store does not produce a value.
+ ///
+ /// PRE_INC Similar to the unindexed mode where the effective address is
+ /// PRE_DEC the value of the base pointer add / subtract the offset.
+ /// It considers the computation as being folded into the load /
+ /// store operation (i.e. the load / store does the address
+ /// computation as well as performing the memory transaction).
+ /// The base operand is always undefined. In addition to
+ /// producing a chain, pre-indexed load produces two values
+ /// (result of the load and the result of the address
+ /// computation); a pre-indexed store produces one value (result
+ /// of the address computation).
+ ///
+ /// POST_INC The effective address is the value of the base pointer. The
+ /// POST_DEC value of the offset operand is then added to / subtracted
+ /// from the base after memory transaction. In addition to
+ /// producing a chain, post-indexed load produces two values
+ /// (the result of the load and the result of the base +/- offset
+ /// computation); a post-indexed store produces one value (the
+ /// the result of the base +/- offset computation).
+ enum MemIndexedMode {
+ UNINDEXED = 0,
+ PRE_INC,
+ PRE_DEC,
+ POST_INC,
+ POST_DEC,
+ LAST_INDEXED_MODE
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// LoadExtType enum - This enum defines the three variants of LOADEXT
+ /// (load with extension).
+ ///
+ /// SEXTLOAD loads the integer operand and sign extends it to a larger
+ /// integer result type.
+ /// ZEXTLOAD loads the integer operand and zero extends it to a larger
+ /// integer result type.
+ /// EXTLOAD is used for two things: floating point extending loads and
+ /// integer extending loads [the top bits are undefined].
+ enum LoadExtType {
+ NON_EXTLOAD = 0,
+ EXTLOAD,
+ SEXTLOAD,
+ ZEXTLOAD,
+ LAST_LOADEXT_TYPE
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// ISD::CondCode enum - These are ordered carefully to make the bitfields
+ /// below work out, when considering SETFALSE (something that never exists
+ /// dynamically) as 0. "U" -> Unsigned (for integer operands) or Unordered
+ /// (for floating point), "L" -> Less than, "G" -> Greater than, "E" -> Equal
+ /// to. If the "N" column is 1, the result of the comparison is undefined if
+ /// the input is a NAN.
+ ///
+ /// All of these (except for the 'always folded ops') should be handled for
+ /// floating point. For integer, only the SETEQ,SETNE,SETLT,SETLE,SETGT,
+ /// SETGE,SETULT,SETULE,SETUGT, and SETUGE opcodes are used.
+ ///
+ /// Note that these are laid out in a specific order to allow bit-twiddling
+ /// to transform conditions.
+ enum CondCode {
+ // Opcode N U L G E Intuitive operation
+ SETFALSE, // 0 0 0 0 Always false (always folded)
+ SETOEQ, // 0 0 0 1 True if ordered and equal
+ SETOGT, // 0 0 1 0 True if ordered and greater than
+ SETOGE, // 0 0 1 1 True if ordered and greater than or equal
+ SETOLT, // 0 1 0 0 True if ordered and less than
+ SETOLE, // 0 1 0 1 True if ordered and less than or equal
+ SETONE, // 0 1 1 0 True if ordered and operands are unequal
+ SETO, // 0 1 1 1 True if ordered (no nans)
+ SETUO, // 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
+ SETUEQ, // 1 0 0 1 True if unordered or equal
+ SETUGT, // 1 0 1 0 True if unordered or greater than
+ SETUGE, // 1 0 1 1 True if unordered, greater than, or equal
+ SETULT, // 1 1 0 0 True if unordered or less than
+ SETULE, // 1 1 0 1 True if unordered, less than, or equal
+ SETUNE, // 1 1 1 0 True if unordered or not equal
+ SETTRUE, // 1 1 1 1 Always true (always folded)
+ // Don't care operations: undefined if the input is a nan.
+ SETFALSE2, // 1 X 0 0 0 Always false (always folded)
+ SETEQ, // 1 X 0 0 1 True if equal
+ SETGT, // 1 X 0 1 0 True if greater than
+ SETGE, // 1 X 0 1 1 True if greater than or equal
+ SETLT, // 1 X 1 0 0 True if less than
+ SETLE, // 1 X 1 0 1 True if less than or equal
+ SETNE, // 1 X 1 1 0 True if not equal
+ SETTRUE2, // 1 X 1 1 1 Always true (always folded)
+
+ SETCC_INVALID // Marker value.
+ };
+
+ /// isSignedIntSetCC - Return true if this is a setcc instruction that
+ /// performs a signed comparison when used with integer operands.
+ inline bool isSignedIntSetCC(CondCode Code) {
+ return Code == SETGT || Code == SETGE || Code == SETLT || Code == SETLE;
+ }
+
+ /// isUnsignedIntSetCC - Return true if this is a setcc instruction that
+ /// performs an unsigned comparison when used with integer operands.
+ inline bool isUnsignedIntSetCC(CondCode Code) {
+ return Code == SETUGT || Code == SETUGE || Code == SETULT || Code == SETULE;
+ }
+
+ /// isTrueWhenEqual - Return true if the specified condition returns true if
+ /// the two operands to the condition are equal. Note that if one of the two
+ /// operands is a NaN, this value is meaningless.
+ inline bool isTrueWhenEqual(CondCode Cond) {
+ return ((int)Cond & 1) != 0;
+ }
+
+ /// getUnorderedFlavor - This function returns 0 if the condition is always
+ /// false if an operand is a NaN, 1 if the condition is always true if the
+ /// operand is a NaN, and 2 if the condition is undefined if the operand is a
+ /// NaN.
+ inline unsigned getUnorderedFlavor(CondCode Cond) {
+ return ((int)Cond >> 3) & 3;
+ }
+
+ /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
+ /// 'op' is a valid SetCC operation.
+ CondCode getSetCCInverse(CondCode Operation, bool isInteger);
+
+ /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
+ /// when given the operation for (X op Y).
+ CondCode getSetCCSwappedOperands(CondCode Operation);
+
+ /// getSetCCOrOperation - Return the result of a logical OR between different
+ /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This
+ /// function returns SETCC_INVALID if it is not possible to represent the
+ /// resultant comparison.
+ CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, bool isInteger);
+
+ /// getSetCCAndOperation - Return the result of a logical AND between
+ /// different comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
+ /// function returns SETCC_INVALID if it is not possible to represent the
+ /// resultant comparison.
+ CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, bool isInteger);
+
+ //===--------------------------------------------------------------------===//
+ /// CvtCode enum - This enum defines the various converts CONVERT_RNDSAT
+ /// supports.
+ enum CvtCode {
+ CVT_FF, /// Float from Float
+ CVT_FS, /// Float from Signed
+ CVT_FU, /// Float from Unsigned
+ CVT_SF, /// Signed from Float
+ CVT_UF, /// Unsigned from Float
+ CVT_SS, /// Signed from Signed
+ CVT_SU, /// Signed from Unsigned
+ CVT_US, /// Unsigned from Signed
+ CVT_UU, /// Unsigned from Unsigned
+ CVT_INVALID /// Marker - Invalid opcode
+ };
+
+} // end llvm::ISD namespace
+
+} // end llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/IntrinsicLowering.h b/include/llvm/CodeGen/IntrinsicLowering.h
new file mode 100644
index 00000000000..767b6662254
--- /dev/null
+++ b/include/llvm/CodeGen/IntrinsicLowering.h
@@ -0,0 +1,59 @@
+//===-- IntrinsicLowering.h - Intrinsic Function Lowering -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the IntrinsicLowering interface. This interface allows
+// addition of domain-specific or front-end specific intrinsics to LLVM without
+// having to modify all of the C backend or interpreter.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_INTRINSICLOWERING_H
+#define LLVM_CODEGEN_INTRINSICLOWERING_H
+
+#include "llvm/Intrinsics.h"
+
+namespace llvm {
+ class CallInst;
+ class Module;
+ class TargetData;
+
+ class IntrinsicLowering {
+ const TargetData& TD;
+
+
+ bool Warned;
+ public:
+ explicit IntrinsicLowering(const TargetData &td) :
+ TD(td), Warned(false) {}
+
+ /// AddPrototypes - This method, if called, causes all of the prototypes
+ /// that might be needed by an intrinsic lowering implementation to be
+ /// inserted into the module specified.
+ void AddPrototypes(Module &M);
+
+ /// LowerIntrinsicCall - This method replaces a call with the LLVM function
+ /// which should be used to implement the specified intrinsic function call.
+ /// If an intrinsic function must be implemented by the code generator
+ /// (such as va_start), this function should print a message and abort.
+ ///
+ /// Otherwise, if an intrinsic function call can be lowered, the code to
+ /// implement it (often a call to a non-intrinsic function) is inserted
+ /// _after_ the call instruction and the call is deleted. The caller must
+ /// be capable of handling this kind of change.
+ ///
+ void LowerIntrinsicCall(CallInst *CI);
+
+ /// LowerToByteSwap - Replace a call instruction into a call to bswap
+ /// intrinsic. Return false if it has determined the call is not a
+ /// simple integer bswap.
+ static bool LowerToByteSwap(CallInst *CI);
+ };
+}
+
+#endif
diff --git a/include/llvm/CodeGen/JITCodeEmitter.h b/include/llvm/CodeGen/JITCodeEmitter.h
new file mode 100644
index 00000000000..89f00e91f78
--- /dev/null
+++ b/include/llvm/CodeGen/JITCodeEmitter.h
@@ -0,0 +1,342 @@
+//===-- llvm/CodeGen/JITCodeEmitter.h - Code emission ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines an abstract interface that is used by the machine code
+// emission framework to output the code. This allows machine code emission to
+// be separated from concerns such as resolution of call targets, and where the
+// machine code will be written (memory or disk, f.e.).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_JITCODEEMITTER_H
+#define LLVM_CODEGEN_JITCODEEMITTER_H
+
+#include <string>
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/CodeGen/MachineCodeEmitter.h"
+#include "llvm/ADT/DenseMap.h"
+
+namespace llvm {
+
+class MachineBasicBlock;
+class MachineConstantPool;
+class MachineJumpTableInfo;
+class MachineFunction;
+class MachineModuleInfo;
+class MachineRelocation;
+class Value;
+class GlobalValue;
+class Function;
+
+/// JITCodeEmitter - This class defines two sorts of methods: those for
+/// emitting the actual bytes of machine code, and those for emitting auxiliary
+/// structures, such as jump tables, relocations, etc.
+///
+/// Emission of machine code is complicated by the fact that we don't (in
+/// general) know the size of the machine code that we're about to emit before
+/// we emit it. As such, we preallocate a certain amount of memory, and set the
+/// BufferBegin/BufferEnd pointers to the start and end of the buffer. As we
+/// emit machine instructions, we advance the CurBufferPtr to indicate the
+/// location of the next byte to emit. In the case of a buffer overflow (we
+/// need to emit more machine code than we have allocated space for), the
+/// CurBufferPtr will saturate to BufferEnd and ignore stores. Once the entire
+/// function has been emitted, the overflow condition is checked, and if it has
+/// occurred, more memory is allocated, and we reemit the code into it.
+///
+class JITCodeEmitter : public MachineCodeEmitter {
+ virtual void anchor();
+public:
+ virtual ~JITCodeEmitter() {}
+
+ /// startFunction - This callback is invoked when the specified function is
+ /// about to be code generated. This initializes the BufferBegin/End/Ptr
+ /// fields.
+ ///
+ virtual void startFunction(MachineFunction &F) = 0;
+
+ /// finishFunction - This callback is invoked when the specified function has
+ /// finished code generation. If a buffer overflow has occurred, this method
+ /// returns true (the callee is required to try again), otherwise it returns
+ /// false.
+ ///
+ virtual bool finishFunction(MachineFunction &F) = 0;
+
+ /// allocIndirectGV - Allocates and fills storage for an indirect
+ /// GlobalValue, and returns the address.
+ virtual void *allocIndirectGV(const GlobalValue *GV,
+ const uint8_t *Buffer, size_t Size,
+ unsigned Alignment) = 0;
+
+ /// emitByte - This callback is invoked when a byte needs to be written to the
+ /// output stream.
+ ///
+ void emitByte(uint8_t B) {
+ if (CurBufferPtr != BufferEnd)
+ *CurBufferPtr++ = B;
+ }
+
+ /// emitWordLE - This callback is invoked when a 32-bit word needs to be
+ /// written to the output stream in little-endian format.
+ ///
+ void emitWordLE(uint32_t W) {
+ if (4 <= BufferEnd-CurBufferPtr) {
+ *CurBufferPtr++ = (uint8_t)(W >> 0);
+ *CurBufferPtr++ = (uint8_t)(W >> 8);
+ *CurBufferPtr++ = (uint8_t)(W >> 16);
+ *CurBufferPtr++ = (uint8_t)(W >> 24);
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitWordBE - This callback is invoked when a 32-bit word needs to be
+ /// written to the output stream in big-endian format.
+ ///
+ void emitWordBE(uint32_t W) {
+ if (4 <= BufferEnd-CurBufferPtr) {
+ *CurBufferPtr++ = (uint8_t)(W >> 24);
+ *CurBufferPtr++ = (uint8_t)(W >> 16);
+ *CurBufferPtr++ = (uint8_t)(W >> 8);
+ *CurBufferPtr++ = (uint8_t)(W >> 0);
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitDWordLE - This callback is invoked when a 64-bit word needs to be
+ /// written to the output stream in little-endian format.
+ ///
+ void emitDWordLE(uint64_t W) {
+ if (8 <= BufferEnd-CurBufferPtr) {
+ *CurBufferPtr++ = (uint8_t)(W >> 0);
+ *CurBufferPtr++ = (uint8_t)(W >> 8);
+ *CurBufferPtr++ = (uint8_t)(W >> 16);
+ *CurBufferPtr++ = (uint8_t)(W >> 24);
+ *CurBufferPtr++ = (uint8_t)(W >> 32);
+ *CurBufferPtr++ = (uint8_t)(W >> 40);
+ *CurBufferPtr++ = (uint8_t)(W >> 48);
+ *CurBufferPtr++ = (uint8_t)(W >> 56);
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitDWordBE - This callback is invoked when a 64-bit word needs to be
+ /// written to the output stream in big-endian format.
+ ///
+ void emitDWordBE(uint64_t W) {
+ if (8 <= BufferEnd-CurBufferPtr) {
+ *CurBufferPtr++ = (uint8_t)(W >> 56);
+ *CurBufferPtr++ = (uint8_t)(W >> 48);
+ *CurBufferPtr++ = (uint8_t)(W >> 40);
+ *CurBufferPtr++ = (uint8_t)(W >> 32);
+ *CurBufferPtr++ = (uint8_t)(W >> 24);
+ *CurBufferPtr++ = (uint8_t)(W >> 16);
+ *CurBufferPtr++ = (uint8_t)(W >> 8);
+ *CurBufferPtr++ = (uint8_t)(W >> 0);
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitAlignment - Move the CurBufferPtr pointer up to the specified
+ /// alignment (saturated to BufferEnd of course).
+ void emitAlignment(unsigned Alignment) {
+ if (Alignment == 0) Alignment = 1;
+ uint8_t *NewPtr = (uint8_t*)RoundUpToAlignment((uintptr_t)CurBufferPtr,
+ Alignment);
+ CurBufferPtr = std::min(NewPtr, BufferEnd);
+ }
+
+ /// emitAlignmentWithFill - Similar to emitAlignment, except that the
+ /// extra bytes are filled with the provided byte.
+ void emitAlignmentWithFill(unsigned Alignment, uint8_t Fill) {
+ if (Alignment == 0) Alignment = 1;
+ uint8_t *NewPtr = (uint8_t*)RoundUpToAlignment((uintptr_t)CurBufferPtr,
+ Alignment);
+ // Fail if we don't have room.
+ if (NewPtr > BufferEnd) {
+ CurBufferPtr = BufferEnd;
+ return;
+ }
+ while (CurBufferPtr < NewPtr) {
+ *CurBufferPtr++ = Fill;
+ }
+ }
+
+ /// emitULEB128Bytes - This callback is invoked when a ULEB128 needs to be
+ /// written to the output stream.
+ void emitULEB128Bytes(uint64_t Value, unsigned PadTo = 0) {
+ do {
+ uint8_t Byte = Value & 0x7f;
+ Value >>= 7;
+ if (Value || PadTo != 0) Byte |= 0x80;
+ emitByte(Byte);
+ } while (Value);
+
+ if (PadTo) {
+ do {
+ uint8_t Byte = (PadTo > 1) ? 0x80 : 0x0;
+ emitByte(Byte);
+ } while (--PadTo);
+ }
+ }
+
+ /// emitSLEB128Bytes - This callback is invoked when a SLEB128 needs to be
+ /// written to the output stream.
+ void emitSLEB128Bytes(int64_t Value) {
+ int32_t Sign = Value >> (8 * sizeof(Value) - 1);
+ bool IsMore;
+
+ do {
+ uint8_t Byte = Value & 0x7f;
+ Value >>= 7;
+ IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
+ if (IsMore) Byte |= 0x80;
+ emitByte(Byte);
+ } while (IsMore);
+ }
+
+ /// emitString - This callback is invoked when a String needs to be
+ /// written to the output stream.
+ void emitString(const std::string &String) {
+ for (unsigned i = 0, N = static_cast<unsigned>(String.size());
+ i < N; ++i) {
+ uint8_t C = String[i];
+ emitByte(C);
+ }
+ emitByte(0);
+ }
+
+ /// emitInt32 - Emit a int32 directive.
+ void emitInt32(uint32_t Value) {
+ if (4 <= BufferEnd-CurBufferPtr) {
+ *((uint32_t*)CurBufferPtr) = Value;
+ CurBufferPtr += 4;
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitInt64 - Emit a int64 directive.
+ void emitInt64(uint64_t Value) {
+ if (8 <= BufferEnd-CurBufferPtr) {
+ *((uint64_t*)CurBufferPtr) = Value;
+ CurBufferPtr += 8;
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitInt32At - Emit the Int32 Value in Addr.
+ void emitInt32At(uintptr_t *Addr, uintptr_t Value) {
+ if (Addr >= (uintptr_t*)BufferBegin && Addr < (uintptr_t*)BufferEnd)
+ (*(uint32_t*)Addr) = (uint32_t)Value;
+ }
+
+ /// emitInt64At - Emit the Int64 Value in Addr.
+ void emitInt64At(uintptr_t *Addr, uintptr_t Value) {
+ if (Addr >= (uintptr_t*)BufferBegin && Addr < (uintptr_t*)BufferEnd)
+ (*(uint64_t*)Addr) = (uint64_t)Value;
+ }
+
+
+ /// emitLabel - Emits a label
+ virtual void emitLabel(MCSymbol *Label) = 0;
+
+ /// allocateSpace - Allocate a block of space in the current output buffer,
+ /// returning null (and setting conditions to indicate buffer overflow) on
+ /// failure. Alignment is the alignment in bytes of the buffer desired.
+ virtual void *allocateSpace(uintptr_t Size, unsigned Alignment) {
+ emitAlignment(Alignment);
+ void *Result;
+
+ // Check for buffer overflow.
+ if (Size >= (uintptr_t)(BufferEnd-CurBufferPtr)) {
+ CurBufferPtr = BufferEnd;
+ Result = 0;
+ } else {
+ // Allocate the space.
+ Result = CurBufferPtr;
+ CurBufferPtr += Size;
+ }
+
+ return Result;
+ }
+
+ /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
+ /// this method does not allocate memory in the current output buffer,
+ /// because a global may live longer than the current function.
+ virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment) = 0;
+
+ /// StartMachineBasicBlock - This should be called by the target when a new
+ /// basic block is about to be emitted. This way the MCE knows where the
+ /// start of the block is, and can implement getMachineBasicBlockAddress.
+ virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) = 0;
+
+ /// getCurrentPCValue - This returns the address that the next emitted byte
+ /// will be output to.
+ ///
+ virtual uintptr_t getCurrentPCValue() const {
+ return (uintptr_t)CurBufferPtr;
+ }
+
+ /// getCurrentPCOffset - Return the offset from the start of the emitted
+ /// buffer that we are currently writing to.
+ uintptr_t getCurrentPCOffset() const {
+ return CurBufferPtr-BufferBegin;
+ }
+
+ /// earlyResolveAddresses - True if the code emitter can use symbol addresses
+ /// during code emission time. The JIT is capable of doing this because it
+ /// creates jump tables or constant pools in memory on the fly while the
+ /// object code emitters rely on a linker to have real addresses and should
+ /// use relocations instead.
+ bool earlyResolveAddresses() const { return true; }
+
+ /// addRelocation - Whenever a relocatable address is needed, it should be
+ /// noted with this interface.
+ virtual void addRelocation(const MachineRelocation &MR) = 0;
+
+ /// FIXME: These should all be handled with relocations!
+
+ /// getConstantPoolEntryAddress - Return the address of the 'Index' entry in
+ /// the constant pool that was last emitted with the emitConstantPool method.
+ ///
+ virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const = 0;
+
+ /// getJumpTableEntryAddress - Return the address of the jump table with index
+ /// 'Index' in the function that last called initJumpTableInfo.
+ ///
+ virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const = 0;
+
+ /// getMachineBasicBlockAddress - Return the address of the specified
+ /// MachineBasicBlock, only usable after the label for the MBB has been
+ /// emitted.
+ ///
+ virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const= 0;
+
+ /// getLabelAddress - Return the address of the specified Label, only usable
+ /// after the Label has been emitted.
+ ///
+ virtual uintptr_t getLabelAddress(MCSymbol *Label) const = 0;
+
+ /// Specifies the MachineModuleInfo object. This is used for exception handling
+ /// purposes.
+ virtual void setModuleInfo(MachineModuleInfo* Info) = 0;
+
+ /// getLabelLocations - Return the label locations map of the label IDs to
+ /// their address.
+ virtual DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() { return 0; }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/LatencyPriorityQueue.h b/include/llvm/CodeGen/LatencyPriorityQueue.h
new file mode 100644
index 00000000000..8fb31aa8a6d
--- /dev/null
+++ b/include/llvm/CodeGen/LatencyPriorityQueue.h
@@ -0,0 +1,100 @@
+//===---- LatencyPriorityQueue.h - A latency-oriented priority queue ------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the LatencyPriorityQueue class, which is a
+// SchedulingPriorityQueue that schedules using latency information to
+// reduce the length of the critical path through the basic block.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LATENCY_PRIORITY_QUEUE_H
+#define LATENCY_PRIORITY_QUEUE_H
+
+#include "llvm/CodeGen/ScheduleDAG.h"
+
+namespace llvm {
+ class LatencyPriorityQueue;
+
+ /// Sorting functions for the Available queue.
+ struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
+ LatencyPriorityQueue *PQ;
+ explicit latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
+
+ bool operator()(const SUnit* left, const SUnit* right) const;
+ };
+
+ class LatencyPriorityQueue : public SchedulingPriorityQueue {
+ // SUnits - The SUnits for the current graph.
+ std::vector<SUnit> *SUnits;
+
+ /// NumNodesSolelyBlocking - This vector contains, for every node in the
+ /// Queue, the number of nodes that the node is the sole unscheduled
+ /// predecessor for. This is used as a tie-breaker heuristic for better
+ /// mobility.
+ std::vector<unsigned> NumNodesSolelyBlocking;
+
+ /// Queue - The queue.
+ std::vector<SUnit*> Queue;
+ latency_sort Picker;
+
+ public:
+ LatencyPriorityQueue() : Picker(this) {
+ }
+
+ bool isBottomUp() const { return false; }
+
+ void initNodes(std::vector<SUnit> &sunits) {
+ SUnits = &sunits;
+ NumNodesSolelyBlocking.resize(SUnits->size(), 0);
+ }
+
+ void addNode(const SUnit *SU) {
+ NumNodesSolelyBlocking.resize(SUnits->size(), 0);
+ }
+
+ void updateNode(const SUnit *SU) {
+ }
+
+ void releaseState() {
+ SUnits = 0;
+ }
+
+ unsigned getLatency(unsigned NodeNum) const {
+ assert(NodeNum < (*SUnits).size());
+ return (*SUnits)[NodeNum].getHeight();
+ }
+
+ unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
+ assert(NodeNum < NumNodesSolelyBlocking.size());
+ return NumNodesSolelyBlocking[NodeNum];
+ }
+
+ bool empty() const { return Queue.empty(); }
+
+ virtual void push(SUnit *U);
+
+ virtual SUnit *pop();
+
+ virtual void remove(SUnit *SU);
+
+ virtual void dump(ScheduleDAG* DAG) const;
+
+ // scheduledNode - As nodes are scheduled, we look to see if there are any
+ // successor nodes that have a single unscheduled predecessor. If so, that
+ // single predecessor has a higher priority, since scheduling it will make
+ // the node available.
+ void scheduledNode(SUnit *Node);
+
+private:
+ void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
+ SUnit *getSingleUnscheduledPred(SUnit *SU);
+ };
+}
+
+#endif
diff --git a/include/llvm/CodeGen/LexicalScopes.h b/include/llvm/CodeGen/LexicalScopes.h
new file mode 100644
index 00000000000..8414c64544e
--- /dev/null
+++ b/include/llvm/CodeGen/LexicalScopes.h
@@ -0,0 +1,254 @@
+//===- LexicalScopes.cpp - Collecting lexical scope info -*- C++ -*--------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements LexicalScopes analysis.
+//
+// This pass collects lexical scope information and maps machine instructions
+// to respective lexical scopes.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_LEXICALSCOPES_H
+#define LLVM_CODEGEN_LEXICALSCOPES_H
+
+#include "llvm/Metadata.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/DebugLoc.h"
+#include "llvm/Support/ValueHandle.h"
+#include <utility>
+namespace llvm {
+
+class MachineInstr;
+class MachineBasicBlock;
+class MachineFunction;
+class LexicalScope;
+
+//===----------------------------------------------------------------------===//
+/// InsnRange - This is used to track range of instructions with identical
+/// lexical scope.
+///
+typedef std::pair<const MachineInstr *, const MachineInstr *> InsnRange;
+
+//===----------------------------------------------------------------------===//
+/// LexicalScopes - This class provides interface to collect and use lexical
+/// scoping information from machine instruction.
+///
+class LexicalScopes {
+public:
+ LexicalScopes() : MF(NULL), CurrentFnLexicalScope(NULL) { }
+ virtual ~LexicalScopes();
+
+ /// initialize - Scan machine function and constuct lexical scope nest.
+ virtual void initialize(const MachineFunction &);
+
+ /// releaseMemory - release memory.
+ virtual void releaseMemory();
+
+ /// empty - Return true if there is any lexical scope information available.
+ bool empty() { return CurrentFnLexicalScope == NULL; }
+
+ /// isCurrentFunctionScope - Return true if given lexical scope represents
+ /// current function.
+ bool isCurrentFunctionScope(const LexicalScope *LS) {
+ return LS == CurrentFnLexicalScope;
+ }
+
+ /// getCurrentFunctionScope - Return lexical scope for the current function.
+ LexicalScope *getCurrentFunctionScope() const { return CurrentFnLexicalScope;}
+
+ /// getMachineBasicBlocks - Populate given set using machine basic blocks
+ /// which have machine instructions that belong to lexical scope identified by
+ /// DebugLoc.
+ void getMachineBasicBlocks(DebugLoc DL,
+ SmallPtrSet<const MachineBasicBlock*, 4> &MBBs);
+
+ /// dominates - Return true if DebugLoc's lexical scope dominates at least one
+ /// machine instruction's lexical scope in a given machine basic block.
+ bool dominates(DebugLoc DL, MachineBasicBlock *MBB);
+
+ /// findLexicalScope - Find lexical scope, either regular or inlined, for the
+ /// given DebugLoc. Return NULL if not found.
+ LexicalScope *findLexicalScope(DebugLoc DL);
+
+ /// getAbstractScopesList - Return a reference to list of abstract scopes.
+ ArrayRef<LexicalScope *> getAbstractScopesList() const {
+ return AbstractScopesList;
+ }
+
+ /// findAbstractScope - Find an abstract scope or return NULL.
+ LexicalScope *findAbstractScope(const MDNode *N) {
+ return AbstractScopeMap.lookup(N);
+ }
+
+ /// findInlinedScope - Find an inlined scope for the given DebugLoc or return
+ /// NULL.
+ LexicalScope *findInlinedScope(DebugLoc DL) {
+ return InlinedLexicalScopeMap.lookup(DL);
+ }
+
+ /// findLexicalScope - Find regular lexical scope or return NULL.
+ LexicalScope *findLexicalScope(const MDNode *N) {
+ return LexicalScopeMap.lookup(N);
+ }
+
+ /// dump - Print data structures to dbgs().
+ void dump();
+
+private:
+
+ /// getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If
+ /// not available then create new lexical scope.
+ LexicalScope *getOrCreateLexicalScope(DebugLoc DL);
+
+ /// getOrCreateRegularScope - Find or create a regular lexical scope.
+ LexicalScope *getOrCreateRegularScope(MDNode *Scope);
+
+ /// getOrCreateInlinedScope - Find or create an inlined lexical scope.
+ LexicalScope *getOrCreateInlinedScope(MDNode *Scope, MDNode *InlinedAt);
+
+ /// getOrCreateAbstractScope - Find or create an abstract lexical scope.
+ LexicalScope *getOrCreateAbstractScope(const MDNode *N);
+
+ /// extractLexicalScopes - Extract instruction ranges for each lexical scopes
+ /// for the given machine function.
+ void extractLexicalScopes(SmallVectorImpl<InsnRange> &MIRanges,
+ DenseMap<const MachineInstr *, LexicalScope *> &M);
+ void constructScopeNest(LexicalScope *Scope);
+ void assignInstructionRanges(SmallVectorImpl<InsnRange> &MIRanges,
+ DenseMap<const MachineInstr *, LexicalScope *> &M);
+
+private:
+ const MachineFunction *MF;
+
+ /// LexicalScopeMap - Tracks the scopes in the current function. Owns the
+ /// contained LexicalScope*s.
+ DenseMap<const MDNode *, LexicalScope *> LexicalScopeMap;
+
+ /// InlinedLexicalScopeMap - Tracks inlined function scopes in current function.
+ DenseMap<DebugLoc, LexicalScope *> InlinedLexicalScopeMap;
+
+ /// AbstractScopeMap - These scopes are not included LexicalScopeMap.
+ /// AbstractScopes owns its LexicalScope*s.
+ DenseMap<const MDNode *, LexicalScope *> AbstractScopeMap;
+
+ /// AbstractScopesList - Tracks abstract scopes constructed while processing
+ /// a function.
+ SmallVector<LexicalScope *, 4>AbstractScopesList;
+
+ /// CurrentFnLexicalScope - Top level scope for the current function.
+ ///
+ LexicalScope *CurrentFnLexicalScope;
+};
+
+//===----------------------------------------------------------------------===//
+/// LexicalScope - This class is used to track scope information.
+///
+class LexicalScope {
+ virtual void anchor();
+
+public:
+ LexicalScope(LexicalScope *P, const MDNode *D, const MDNode *I, bool A)
+ : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(A),
+ LastInsn(0), FirstInsn(0), DFSIn(0), DFSOut(0) {
+#ifndef NDEBUG
+ IndentLevel = 0;
+#endif
+ if (Parent)
+ Parent->addChild(this);
+ }
+
+ virtual ~LexicalScope() {}
+
+ // Accessors.
+ LexicalScope *getParent() const { return Parent; }
+ const MDNode *getDesc() const { return Desc; }
+ const MDNode *getInlinedAt() const { return InlinedAtLocation; }
+ const MDNode *getScopeNode() const { return Desc; }
+ bool isAbstractScope() const { return AbstractScope; }
+ SmallVector<LexicalScope *, 4> &getChildren() { return Children; }
+ SmallVector<InsnRange, 4> &getRanges() { return Ranges; }
+
+ /// addChild - Add a child scope.
+ void addChild(LexicalScope *S) { Children.push_back(S); }
+
+ /// openInsnRange - This scope covers instruction range starting from MI.
+ void openInsnRange(const MachineInstr *MI) {
+ if (!FirstInsn)
+ FirstInsn = MI;
+
+ if (Parent)
+ Parent->openInsnRange(MI);
+ }
+
+ /// extendInsnRange - Extend the current instruction range covered by
+ /// this scope.
+ void extendInsnRange(const MachineInstr *MI) {
+ assert (FirstInsn && "MI Range is not open!");
+ LastInsn = MI;
+ if (Parent)
+ Parent->extendInsnRange(MI);
+ }
+
+ /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
+ /// until now. This is used when a new scope is encountered while walking
+ /// machine instructions.
+ void closeInsnRange(LexicalScope *NewScope = NULL) {
+ assert (LastInsn && "Last insn missing!");
+ Ranges.push_back(InsnRange(FirstInsn, LastInsn));
+ FirstInsn = NULL;
+ LastInsn = NULL;
+ // If Parent dominates NewScope then do not close Parent's instruction
+ // range.
+ if (Parent && (!NewScope || !Parent->dominates(NewScope)))
+ Parent->closeInsnRange(NewScope);
+ }
+
+ /// dominates - Return true if current scope dominates given lexical scope.
+ bool dominates(const LexicalScope *S) const {
+ if (S == this)
+ return true;
+ if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
+ return true;
+ return false;
+ }
+
+ // Depth First Search support to walk and manipulate LexicalScope hierarchy.
+ unsigned getDFSOut() const { return DFSOut; }
+ void setDFSOut(unsigned O) { DFSOut = O; }
+ unsigned getDFSIn() const { return DFSIn; }
+ void setDFSIn(unsigned I) { DFSIn = I; }
+
+ /// dump - print lexical scope.
+ void dump() const;
+
+private:
+ LexicalScope *Parent; // Parent to this scope.
+ AssertingVH<const MDNode> Desc; // Debug info descriptor.
+ AssertingVH<const MDNode> InlinedAtLocation; // Location at which this
+ // scope is inlined.
+ bool AbstractScope; // Abstract Scope
+ SmallVector<LexicalScope *, 4> Children; // Scopes defined in scope.
+ // Contents not owned.
+ SmallVector<InsnRange, 4> Ranges;
+
+ const MachineInstr *LastInsn; // Last instruction of this scope.
+ const MachineInstr *FirstInsn; // First instruction of this scope.
+ unsigned DFSIn, DFSOut; // In & Out Depth use to determine
+ // scope nesting.
+#ifndef NDEBUG
+ mutable unsigned IndentLevel; // Private state for dump()
+#endif
+};
+
+} // end llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/LinkAllAsmWriterComponents.h b/include/llvm/CodeGen/LinkAllAsmWriterComponents.h
new file mode 100644
index 00000000000..7d1b1fe477a
--- /dev/null
+++ b/include/llvm/CodeGen/LinkAllAsmWriterComponents.h
@@ -0,0 +1,37 @@
+//===- llvm/Codegen/LinkAllAsmWriterComponents.h ----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header file pulls in all assembler writer related passes for tools like
+// llc that need this functionality.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_LINKALLASMWRITERCOMPONENTS_H
+#define LLVM_CODEGEN_LINKALLASMWRITERCOMPONENTS_H
+
+#include "llvm/CodeGen/GCs.h"
+#include <cstdlib>
+
+namespace {
+ struct ForceAsmWriterLinking {
+ ForceAsmWriterLinking() {
+ // We must reference the plug-ins in such a way that compilers will not
+ // delete it all as dead code, even with whole program optimization,
+ // yet is effectively a NO-OP. As the compiler isn't smart enough
+ // to know that getenv() never returns -1, this will do the job.
+ if (std::getenv("bar") != (char*) -1)
+ return;
+
+ llvm::linkOcamlGCPrinter();
+
+ }
+ } ForceAsmWriterLinking; // Force link by creating a global definition.
+}
+
+#endif // LLVM_CODEGEN_LINKALLASMWRITERCOMPONENTS_H
diff --git a/include/llvm/CodeGen/LinkAllCodegenComponents.h b/include/llvm/CodeGen/LinkAllCodegenComponents.h
new file mode 100644
index 00000000000..46dd004609f
--- /dev/null
+++ b/include/llvm/CodeGen/LinkAllCodegenComponents.h
@@ -0,0 +1,53 @@
+//===- llvm/Codegen/LinkAllCodegenComponents.h ------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header file pulls in all codegen related passes for tools like lli and
+// llc that need this functionality.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_LINKALLCODEGENCOMPONENTS_H
+#define LLVM_CODEGEN_LINKALLCODEGENCOMPONENTS_H
+
+#include "llvm/CodeGen/Passes.h"
+#include "llvm/CodeGen/SchedulerRegistry.h"
+#include "llvm/CodeGen/GCs.h"
+#include "llvm/Target/TargetMachine.h"
+#include <cstdlib>
+
+namespace {
+ struct ForceCodegenLinking {
+ ForceCodegenLinking() {
+ // We must reference the passes in such a way that compilers will not
+ // delete it all as dead code, even with whole program optimization,
+ // yet is effectively a NO-OP. As the compiler isn't smart enough
+ // to know that getenv() never returns -1, this will do the job.
+ if (std::getenv("bar") != (char*) -1)
+ return;
+
+ (void) llvm::createFastRegisterAllocator();
+ (void) llvm::createBasicRegisterAllocator();
+ (void) llvm::createGreedyRegisterAllocator();
+ (void) llvm::createDefaultPBQPRegisterAllocator();
+
+ llvm::linkOcamlGC();
+ llvm::linkShadowStackGC();
+
+ (void) llvm::createBURRListDAGScheduler(NULL, llvm::CodeGenOpt::Default);
+ (void) llvm::createSourceListDAGScheduler(NULL,llvm::CodeGenOpt::Default);
+ (void) llvm::createHybridListDAGScheduler(NULL,llvm::CodeGenOpt::Default);
+ (void) llvm::createFastDAGScheduler(NULL, llvm::CodeGenOpt::Default);
+ (void) llvm::createDefaultScheduler(NULL, llvm::CodeGenOpt::Default);
+ (void) llvm::createVLIWDAGScheduler(NULL, llvm::CodeGenOpt::Default);
+
+ }
+ } ForceCodegenLinking; // Force link by creating a global definition.
+}
+
+#endif
diff --git a/include/llvm/CodeGen/LiveInterval.h b/include/llvm/CodeGen/LiveInterval.h
new file mode 100644
index 00000000000..185e414ae2c
--- /dev/null
+++ b/include/llvm/CodeGen/LiveInterval.h
@@ -0,0 +1,611 @@
+//===-- llvm/CodeGen/LiveInterval.h - Interval representation ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the LiveRange and LiveInterval classes. Given some
+// numbering of each the machine instructions an interval [i, j) is said to be a
+// live interval for register v if there is no instruction with number j' >= j
+// such that v is live at j' and there is no instruction with number i' < i such
+// that v is live at i'. In this implementation intervals can have holes,
+// i.e. an interval might look like [1,20), [50,65), [1000,1001). Each
+// individual range is represented as an instance of LiveRange, and the whole
+// interval is represented as an instance of LiveInterval.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_LIVEINTERVAL_H
+#define LLVM_CODEGEN_LIVEINTERVAL_H
+
+#include "llvm/ADT/IntEqClasses.h"
+#include "llvm/Support/Allocator.h"
+#include "llvm/Support/AlignOf.h"
+#include "llvm/CodeGen/SlotIndexes.h"
+#include <cassert>
+#include <climits>
+
+namespace llvm {
+ class CoalescerPair;
+ class LiveIntervals;
+ class MachineInstr;
+ class MachineRegisterInfo;
+ class TargetRegisterInfo;
+ class raw_ostream;
+
+ /// VNInfo - Value Number Information.
+ /// This class holds information about a machine level values, including
+ /// definition and use points.
+ ///
+ class VNInfo {
+ public:
+ typedef BumpPtrAllocator Allocator;
+
+ /// The ID number of this value.
+ unsigned id;
+
+ /// The index of the defining instruction.
+ SlotIndex def;
+
+ /// VNInfo constructor.
+ VNInfo(unsigned i, SlotIndex d)
+ : id(i), def(d)
+ { }
+
+ /// VNInfo construtor, copies values from orig, except for the value number.
+ VNInfo(unsigned i, const VNInfo &orig)
+ : id(i), def(orig.def)
+ { }
+
+ /// Copy from the parameter into this VNInfo.
+ void copyFrom(VNInfo &src) {
+ def = src.def;
+ }
+
+ /// Returns true if this value is defined by a PHI instruction (or was,
+ /// PHI instrucions may have been eliminated).
+ /// PHI-defs begin at a block boundary, all other defs begin at register or
+ /// EC slots.
+ bool isPHIDef() const { return def.isBlock(); }
+
+ /// Returns true if this value is unused.
+ bool isUnused() const { return !def.isValid(); }
+
+ /// Mark this value as unused.
+ void markUnused() { def = SlotIndex(); }
+ };
+
+ /// LiveRange structure - This represents a simple register range in the
+ /// program, with an inclusive start point and an exclusive end point.
+ /// These ranges are rendered as [start,end).
+ struct LiveRange {
+ SlotIndex start; // Start point of the interval (inclusive)
+ SlotIndex end; // End point of the interval (exclusive)
+ VNInfo *valno; // identifier for the value contained in this interval.
+
+ LiveRange(SlotIndex S, SlotIndex E, VNInfo *V)
+ : start(S), end(E), valno(V) {
+
+ assert(S < E && "Cannot create empty or backwards range");
+ }
+
+ /// contains - Return true if the index is covered by this range.
+ ///
+ bool contains(SlotIndex I) const {
+ return start <= I && I < end;
+ }
+
+ /// containsRange - Return true if the given range, [S, E), is covered by
+ /// this range.
+ bool containsRange(SlotIndex S, SlotIndex E) const {
+ assert((S < E) && "Backwards interval?");
+ return (start <= S && S < end) && (start < E && E <= end);
+ }
+
+ bool operator<(const LiveRange &LR) const {
+ return start < LR.start || (start == LR.start && end < LR.end);
+ }
+ bool operator==(const LiveRange &LR) const {
+ return start == LR.start && end == LR.end;
+ }
+
+ void dump() const;
+ void print(raw_ostream &os) const;
+ };
+
+ template <> struct isPodLike<LiveRange> { static const bool value = true; };
+
+ raw_ostream& operator<<(raw_ostream& os, const LiveRange &LR);
+
+
+ inline bool operator<(SlotIndex V, const LiveRange &LR) {
+ return V < LR.start;
+ }
+
+ inline bool operator<(const LiveRange &LR, SlotIndex V) {
+ return LR.start < V;
+ }
+
+ /// LiveInterval - This class represents some number of live ranges for a
+ /// register or value. This class also contains a bit of register allocator
+ /// state.
+ class LiveInterval {
+ public:
+
+ typedef SmallVector<LiveRange,4> Ranges;
+ typedef SmallVector<VNInfo*,4> VNInfoList;
+
+ const unsigned reg; // the register or stack slot of this interval.
+ float weight; // weight of this interval
+ Ranges ranges; // the ranges in which this register is live
+ VNInfoList valnos; // value#'s
+
+ struct InstrSlots {
+ enum {
+ LOAD = 0,
+ USE = 1,
+ DEF = 2,
+ STORE = 3,
+ NUM = 4
+ };
+
+ };
+
+ LiveInterval(unsigned Reg, float Weight)
+ : reg(Reg), weight(Weight) {}
+
+ typedef Ranges::iterator iterator;
+ iterator begin() { return ranges.begin(); }
+ iterator end() { return ranges.end(); }
+
+ typedef Ranges::const_iterator const_iterator;
+ const_iterator begin() const { return ranges.begin(); }
+ const_iterator end() const { return ranges.end(); }
+
+ typedef VNInfoList::iterator vni_iterator;
+ vni_iterator vni_begin() { return valnos.begin(); }
+ vni_iterator vni_end() { return valnos.end(); }
+
+ typedef VNInfoList::const_iterator const_vni_iterator;
+ const_vni_iterator vni_begin() const { return valnos.begin(); }
+ const_vni_iterator vni_end() const { return valnos.end(); }
+
+ /// advanceTo - Advance the specified iterator to point to the LiveRange
+ /// containing the specified position, or end() if the position is past the
+ /// end of the interval. If no LiveRange contains this position, but the
+ /// position is in a hole, this method returns an iterator pointing to the
+ /// LiveRange immediately after the hole.
+ iterator advanceTo(iterator I, SlotIndex Pos) {
+ assert(I != end());
+ if (Pos >= endIndex())
+ return end();
+ while (I->end <= Pos) ++I;
+ return I;
+ }
+
+ /// find - Return an iterator pointing to the first range that ends after
+ /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
+ /// when searching large intervals.
+ ///
+ /// If Pos is contained in a LiveRange, that range is returned.
+ /// If Pos is in a hole, the following LiveRange is returned.
+ /// If Pos is beyond endIndex, end() is returned.
+ iterator find(SlotIndex Pos);
+
+ const_iterator find(SlotIndex Pos) const {
+ return const_cast<LiveInterval*>(this)->find(Pos);
+ }
+
+ void clear() {
+ valnos.clear();
+ ranges.clear();
+ }
+
+ bool hasAtLeastOneValue() const { return !valnos.empty(); }
+
+ bool containsOneValue() const { return valnos.size() == 1; }
+
+ unsigned getNumValNums() const { return (unsigned)valnos.size(); }
+
+ /// getValNumInfo - Returns pointer to the specified val#.
+ ///
+ inline VNInfo *getValNumInfo(unsigned ValNo) {
+ return valnos[ValNo];
+ }
+ inline const VNInfo *getValNumInfo(unsigned ValNo) const {
+ return valnos[ValNo];
+ }
+
+ /// containsValue - Returns true if VNI belongs to this interval.
+ bool containsValue(const VNInfo *VNI) const {
+ return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
+ }
+
+ /// getNextValue - Create a new value number and return it. MIIdx specifies
+ /// the instruction that defines the value number.
+ VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator) {
+ VNInfo *VNI =
+ new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
+ valnos.push_back(VNI);
+ return VNI;
+ }
+
+ /// createDeadDef - Make sure the interval has a value defined at Def.
+ /// If one already exists, return it. Otherwise allocate a new value and
+ /// add liveness for a dead def.
+ VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator);
+
+ /// Create a copy of the given value. The new value will be identical except
+ /// for the Value number.
+ VNInfo *createValueCopy(const VNInfo *orig,
+ VNInfo::Allocator &VNInfoAllocator) {
+ VNInfo *VNI =
+ new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
+ valnos.push_back(VNI);
+ return VNI;
+ }
+
+ /// RenumberValues - Renumber all values in order of appearance and remove
+ /// unused values.
+ void RenumberValues(LiveIntervals &lis);
+
+ /// MergeValueNumberInto - This method is called when two value nubmers
+ /// are found to be equivalent. This eliminates V1, replacing all
+ /// LiveRanges with the V1 value number with the V2 value number. This can
+ /// cause merging of V1/V2 values numbers and compaction of the value space.
+ VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
+
+ /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
+ /// in RHS into this live interval as the specified value number.
+ /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
+ /// current interval, it will replace the value numbers of the overlaped
+ /// live ranges with the specified value number.
+ void MergeRangesInAsValue(const LiveInterval &RHS, VNInfo *LHSValNo);
+
+ /// MergeValueInAsValue - Merge all of the live ranges of a specific val#
+ /// in RHS into this live interval as the specified value number.
+ /// The LiveRanges in RHS are allowed to overlap with LiveRanges in the
+ /// current interval, but only if the overlapping LiveRanges have the
+ /// specified value number.
+ void MergeValueInAsValue(const LiveInterval &RHS,
+ const VNInfo *RHSValNo, VNInfo *LHSValNo);
+
+ bool empty() const { return ranges.empty(); }
+
+ /// beginIndex - Return the lowest numbered slot covered by interval.
+ SlotIndex beginIndex() const {
+ assert(!empty() && "Call to beginIndex() on empty interval.");
+ return ranges.front().start;
+ }
+
+ /// endNumber - return the maximum point of the interval of the whole,
+ /// exclusive.
+ SlotIndex endIndex() const {
+ assert(!empty() && "Call to endIndex() on empty interval.");
+ return ranges.back().end;
+ }
+
+ bool expiredAt(SlotIndex index) const {
+ return index >= endIndex();
+ }
+
+ bool liveAt(SlotIndex index) const {
+ const_iterator r = find(index);
+ return r != end() && r->start <= index;
+ }
+
+ /// killedAt - Return true if a live range ends at index. Note that the kill
+ /// point is not contained in the half-open live range. It is usually the
+ /// getDefIndex() slot following its last use.
+ bool killedAt(SlotIndex index) const {
+ const_iterator r = find(index.getRegSlot(true));
+ return r != end() && r->end == index;
+ }
+
+ /// getLiveRangeContaining - Return the live range that contains the
+ /// specified index, or null if there is none.
+ const LiveRange *getLiveRangeContaining(SlotIndex Idx) const {
+ const_iterator I = FindLiveRangeContaining(Idx);
+ return I == end() ? 0 : &*I;
+ }
+
+ /// getLiveRangeContaining - Return the live range that contains the
+ /// specified index, or null if there is none.
+ LiveRange *getLiveRangeContaining(SlotIndex Idx) {
+ iterator I = FindLiveRangeContaining(Idx);
+ return I == end() ? 0 : &*I;
+ }
+
+ /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
+ VNInfo *getVNInfoAt(SlotIndex Idx) const {
+ const_iterator I = FindLiveRangeContaining(Idx);
+ return I == end() ? 0 : I->valno;
+ }
+
+ /// getVNInfoBefore - Return the VNInfo that is live up to but not
+ /// necessarilly including Idx, or NULL. Use this to find the reaching def
+ /// used by an instruction at this SlotIndex position.
+ VNInfo *getVNInfoBefore(SlotIndex Idx) const {
+ const_iterator I = FindLiveRangeContaining(Idx.getPrevSlot());
+ return I == end() ? 0 : I->valno;
+ }
+
+ /// FindLiveRangeContaining - Return an iterator to the live range that
+ /// contains the specified index, or end() if there is none.
+ iterator FindLiveRangeContaining(SlotIndex Idx) {
+ iterator I = find(Idx);
+ return I != end() && I->start <= Idx ? I : end();
+ }
+
+ const_iterator FindLiveRangeContaining(SlotIndex Idx) const {
+ const_iterator I = find(Idx);
+ return I != end() && I->start <= Idx ? I : end();
+ }
+
+ /// overlaps - Return true if the intersection of the two live intervals is
+ /// not empty.
+ bool overlaps(const LiveInterval& other) const {
+ if (other.empty())
+ return false;
+ return overlapsFrom(other, other.begin());
+ }
+
+ /// overlaps - Return true if the two intervals have overlapping segments
+ /// that are not coalescable according to CP.
+ ///
+ /// Overlapping segments where one interval is defined by a coalescable
+ /// copy are allowed.
+ bool overlaps(const LiveInterval &Other, const CoalescerPair &CP,
+ const SlotIndexes&) const;
+
+ /// overlaps - Return true if the live interval overlaps a range specified
+ /// by [Start, End).
+ bool overlaps(SlotIndex Start, SlotIndex End) const;
+
+ /// overlapsFrom - Return true if the intersection of the two live intervals
+ /// is not empty. The specified iterator is a hint that we can begin
+ /// scanning the Other interval starting at I.
+ bool overlapsFrom(const LiveInterval& other, const_iterator I) const;
+
+ /// addRange - Add the specified LiveRange to this interval, merging
+ /// intervals as appropriate. This returns an iterator to the inserted live
+ /// range (which may have grown since it was inserted.
+ void addRange(LiveRange LR) {
+ addRangeFrom(LR, ranges.begin());
+ }
+
+ /// extendInBlock - If this interval is live before Kill in the basic block
+ /// that starts at StartIdx, extend it to be live up to Kill, and return
+ /// the value. If there is no live range before Kill, return NULL.
+ VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
+
+ /// join - Join two live intervals (this, and other) together. This applies
+ /// mappings to the value numbers in the LHS/RHS intervals as specified. If
+ /// the intervals are not joinable, this aborts.
+ void join(LiveInterval &Other,
+ const int *ValNoAssignments,
+ const int *RHSValNoAssignments,
+ SmallVector<VNInfo*, 16> &NewVNInfo,
+ MachineRegisterInfo *MRI);
+
+ /// isInOneLiveRange - Return true if the range specified is entirely in the
+ /// a single LiveRange of the live interval.
+ bool isInOneLiveRange(SlotIndex Start, SlotIndex End) const {
+ const_iterator r = find(Start);
+ return r != end() && r->containsRange(Start, End);
+ }
+
+ /// removeRange - Remove the specified range from this interval. Note that
+ /// the range must be a single LiveRange in its entirety.
+ void removeRange(SlotIndex Start, SlotIndex End,
+ bool RemoveDeadValNo = false);
+
+ void removeRange(LiveRange LR, bool RemoveDeadValNo = false) {
+ removeRange(LR.start, LR.end, RemoveDeadValNo);
+ }
+
+ /// removeValNo - Remove all the ranges defined by the specified value#.
+ /// Also remove the value# from value# list.
+ void removeValNo(VNInfo *ValNo);
+
+ /// getSize - Returns the sum of sizes of all the LiveRange's.
+ ///
+ unsigned getSize() const;
+
+ /// Returns true if the live interval is zero length, i.e. no live ranges
+ /// span instructions. It doesn't pay to spill such an interval.
+ bool isZeroLength(SlotIndexes *Indexes) const {
+ for (const_iterator i = begin(), e = end(); i != e; ++i)
+ if (Indexes->getNextNonNullIndex(i->start).getBaseIndex() <
+ i->end.getBaseIndex())
+ return false;
+ return true;
+ }
+
+ /// isSpillable - Can this interval be spilled?
+ bool isSpillable() const {
+ return weight != HUGE_VALF;
+ }
+
+ /// markNotSpillable - Mark interval as not spillable
+ void markNotSpillable() {
+ weight = HUGE_VALF;
+ }
+
+ bool operator<(const LiveInterval& other) const {
+ const SlotIndex &thisIndex = beginIndex();
+ const SlotIndex &otherIndex = other.beginIndex();
+ return (thisIndex < otherIndex ||
+ (thisIndex == otherIndex && reg < other.reg));
+ }
+
+ void print(raw_ostream &OS) const;
+ void dump() const;
+
+ /// \brief Walk the interval and assert if any invariants fail to hold.
+ ///
+ /// Note that this is a no-op when asserts are disabled.
+#ifdef NDEBUG
+ void verify() const {}
+#else
+ void verify() const;
+#endif
+
+ private:
+
+ Ranges::iterator addRangeFrom(LiveRange LR, Ranges::iterator From);
+ void extendIntervalEndTo(Ranges::iterator I, SlotIndex NewEnd);
+ Ranges::iterator extendIntervalStartTo(Ranges::iterator I, SlotIndex NewStr);
+ void markValNoForDeletion(VNInfo *V);
+ void mergeIntervalRanges(const LiveInterval &RHS,
+ VNInfo *LHSValNo = 0,
+ const VNInfo *RHSValNo = 0);
+
+ LiveInterval& operator=(const LiveInterval& rhs) LLVM_DELETED_FUNCTION;
+
+ };
+
+ inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
+ LI.print(OS);
+ return OS;
+ }
+
+ /// LiveRangeQuery - Query information about a live range around a given
+ /// instruction. This class hides the implementation details of live ranges,
+ /// and it should be used as the primary interface for examining live ranges
+ /// around instructions.
+ ///
+ class LiveRangeQuery {
+ VNInfo *EarlyVal;
+ VNInfo *LateVal;
+ SlotIndex EndPoint;
+ bool Kill;
+
+ public:
+ /// Create a LiveRangeQuery for the given live range and instruction index.
+ /// The sub-instruction slot of Idx doesn't matter, only the instruction it
+ /// refers to is considered.
+ LiveRangeQuery(const LiveInterval &LI, SlotIndex Idx)
+ : EarlyVal(0), LateVal(0), Kill(false) {
+ // Find the segment that enters the instruction.
+ LiveInterval::const_iterator I = LI.find(Idx.getBaseIndex());
+ LiveInterval::const_iterator E = LI.end();
+ if (I == E)
+ return;
+ // Is this an instruction live-in segment?
+ // If Idx is the start index of a basic block, include live-in segments
+ // that start at Idx.getBaseIndex().
+ if (I->start <= Idx.getBaseIndex()) {
+ EarlyVal = I->valno;
+ EndPoint = I->end;
+ // Move to the potentially live-out segment.
+ if (SlotIndex::isSameInstr(Idx, I->end)) {
+ Kill = true;
+ if (++I == E)
+ return;
+ }
+ // Special case: A PHIDef value can have its def in the middle of a
+ // segment if the value happens to be live out of the layout
+ // predecessor.
+ // Such a value is not live-in.
+ if (EarlyVal->def == Idx.getBaseIndex())
+ EarlyVal = 0;
+ }
+ // I now points to the segment that may be live-through, or defined by
+ // this instr. Ignore segments starting after the current instr.
+ if (SlotIndex::isEarlierInstr(Idx, I->start))
+ return;
+ LateVal = I->valno;
+ EndPoint = I->end;
+ }
+
+ /// Return the value that is live-in to the instruction. This is the value
+ /// that will be read by the instruction's use operands. Return NULL if no
+ /// value is live-in.
+ VNInfo *valueIn() const {
+ return EarlyVal;
+ }
+
+ /// Return true if the live-in value is killed by this instruction. This
+ /// means that either the live range ends at the instruction, or it changes
+ /// value.
+ bool isKill() const {
+ return Kill;
+ }
+
+ /// Return true if this instruction has a dead def.
+ bool isDeadDef() const {
+ return EndPoint.isDead();
+ }
+
+ /// Return the value leaving the instruction, if any. This can be a
+ /// live-through value, or a live def. A dead def returns NULL.
+ VNInfo *valueOut() const {
+ return isDeadDef() ? 0 : LateVal;
+ }
+
+ /// Return the value defined by this instruction, if any. This includes
+ /// dead defs, it is the value created by the instruction's def operands.
+ VNInfo *valueDefined() const {
+ return EarlyVal == LateVal ? 0 : LateVal;
+ }
+
+ /// Return the end point of the last live range segment to interact with
+ /// the instruction, if any.
+ ///
+ /// The end point is an invalid SlotIndex only if the live range doesn't
+ /// intersect the instruction at all.
+ ///
+ /// The end point may be at or past the end of the instruction's basic
+ /// block. That means the value was live out of the block.
+ SlotIndex endPoint() const {
+ return EndPoint;
+ }
+ };
+
+ /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
+ /// LiveInterval into equivalence clases of connected components. A
+ /// LiveInterval that has multiple connected components can be broken into
+ /// multiple LiveIntervals.
+ ///
+ /// Given a LiveInterval that may have multiple connected components, run:
+ ///
+ /// unsigned numComps = ConEQ.Classify(LI);
+ /// if (numComps > 1) {
+ /// // allocate numComps-1 new LiveIntervals into LIS[1..]
+ /// ConEQ.Distribute(LIS);
+ /// }
+
+ class ConnectedVNInfoEqClasses {
+ LiveIntervals &LIS;
+ IntEqClasses EqClass;
+
+ // Note that values a and b are connected.
+ void Connect(unsigned a, unsigned b);
+
+ unsigned Renumber();
+
+ public:
+ explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
+
+ /// Classify - Classify the values in LI into connected components.
+ /// Return the number of connected components.
+ unsigned Classify(const LiveInterval *LI);
+
+ /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
+ /// the equivalence class assigned the VNI.
+ unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
+
+ /// Distribute - Distribute values in LIV[0] into a separate LiveInterval
+ /// for each connected component. LIV must have a LiveInterval for each
+ /// connected component. The LiveIntervals in Liv[1..] must be empty.
+ /// Instructions using LIV[0] are rewritten.
+ void Distribute(LiveInterval *LIV[], MachineRegisterInfo &MRI);
+
+ };
+
+}
+#endif
diff --git a/include/llvm/CodeGen/LiveIntervalAnalysis.h b/include/llvm/CodeGen/LiveIntervalAnalysis.h
new file mode 100644
index 00000000000..1e8dde12553
--- /dev/null
+++ b/include/llvm/CodeGen/LiveIntervalAnalysis.h
@@ -0,0 +1,407 @@
+//===-- LiveIntervalAnalysis.h - Live Interval Analysis ---------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the LiveInterval analysis pass. Given some numbering of
+// each the machine instructions (in this implemention depth-first order) an
+// interval [i, j) is said to be a live interval for register v if there is no
+// instruction with number j' > j such that v is live at j' and there is no
+// instruction with number i' < i such that v is live at i'. In this
+// implementation intervals can have holes, i.e. an interval might look like
+// [1,20), [50,65), [1000,1001).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
+#define LLVM_CODEGEN_LIVEINTERVAL_ANALYSIS_H
+
+#include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/LiveInterval.h"
+#include "llvm/CodeGen/SlotIndexes.h"
+#include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/IndexedMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Allocator.h"
+#include <cmath>
+#include <iterator>
+
+namespace llvm {
+
+ class AliasAnalysis;
+ class LiveRangeCalc;
+ class LiveVariables;
+ class MachineDominatorTree;
+ class MachineLoopInfo;
+ class TargetRegisterInfo;
+ class MachineRegisterInfo;
+ class TargetInstrInfo;
+ class TargetRegisterClass;
+ class VirtRegMap;
+
+ class LiveIntervals : public MachineFunctionPass {
+ MachineFunction* MF;
+ MachineRegisterInfo* MRI;
+ const TargetMachine* TM;
+ const TargetRegisterInfo* TRI;
+ const TargetInstrInfo* TII;
+ AliasAnalysis *AA;
+ LiveVariables* LV;
+ SlotIndexes* Indexes;
+ MachineDominatorTree *DomTree;
+ LiveRangeCalc *LRCalc;
+
+ /// Special pool allocator for VNInfo's (LiveInterval val#).
+ ///
+ VNInfo::Allocator VNInfoAllocator;
+
+ /// Live interval pointers for all the virtual registers.
+ IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals;
+
+ /// AllocatableRegs - A bit vector of allocatable registers.
+ BitVector AllocatableRegs;
+
+ /// ReservedRegs - A bit vector of reserved registers.
+ BitVector ReservedRegs;
+
+ /// RegMaskSlots - Sorted list of instructions with register mask operands.
+ /// Always use the 'r' slot, RegMasks are normal clobbers, not early
+ /// clobbers.
+ SmallVector<SlotIndex, 8> RegMaskSlots;
+
+ /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
+ /// pointer to the corresponding register mask. This pointer can be
+ /// recomputed as:
+ ///
+ /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
+ /// unsigned OpNum = findRegMaskOperand(MI);
+ /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
+ ///
+ /// This is kept in a separate vector partly because some standard
+ /// libraries don't support lower_bound() with mixed objects, partly to
+ /// improve locality when searching in RegMaskSlots.
+ /// Also see the comment in LiveInterval::find().
+ SmallVector<const uint32_t*, 8> RegMaskBits;
+
+ /// For each basic block number, keep (begin, size) pairs indexing into the
+ /// RegMaskSlots and RegMaskBits arrays.
+ /// Note that basic block numbers may not be layout contiguous, that's why
+ /// we can't just keep track of the first register mask in each basic
+ /// block.
+ SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
+
+ /// RegUnitIntervals - Keep a live interval for each register unit as a way
+ /// of tracking fixed physreg interference.
+ SmallVector<LiveInterval*, 0> RegUnitIntervals;
+
+ public:
+ static char ID; // Pass identification, replacement for typeid
+ LiveIntervals();
+ virtual ~LiveIntervals();
+
+ // Calculate the spill weight to assign to a single instruction.
+ static float getSpillWeight(bool isDef, bool isUse, unsigned loopDepth);
+
+ LiveInterval &getInterval(unsigned Reg) {
+ LiveInterval *LI = VirtRegIntervals[Reg];
+ assert(LI && "Interval does not exist for virtual register");
+ return *LI;
+ }
+
+ const LiveInterval &getInterval(unsigned Reg) const {
+ return const_cast<LiveIntervals*>(this)->getInterval(Reg);
+ }
+
+ bool hasInterval(unsigned Reg) const {
+ return VirtRegIntervals.inBounds(Reg) && VirtRegIntervals[Reg];
+ }
+
+ /// isAllocatable - is the physical register reg allocatable in the current
+ /// function?
+ bool isAllocatable(unsigned reg) const {
+ return AllocatableRegs.test(reg);
+ }
+
+ /// isReserved - is the physical register reg reserved in the current
+ /// function
+ bool isReserved(unsigned reg) const {
+ return ReservedRegs.test(reg);
+ }
+
+ // Interval creation.
+ LiveInterval &getOrCreateInterval(unsigned Reg) {
+ if (!hasInterval(Reg)) {
+ VirtRegIntervals.grow(Reg);
+ VirtRegIntervals[Reg] = createInterval(Reg);
+ }
+ return getInterval(Reg);
+ }
+
+ // Interval removal.
+ void removeInterval(unsigned Reg) {
+ delete VirtRegIntervals[Reg];
+ VirtRegIntervals[Reg] = 0;
+ }
+
+ /// addLiveRangeToEndOfBlock - Given a register and an instruction,
+ /// adds a live range from that instruction to the end of its MBB.
+ LiveRange addLiveRangeToEndOfBlock(unsigned reg,
+ MachineInstr* startInst);
+
+ /// shrinkToUses - After removing some uses of a register, shrink its live
+ /// range to just the remaining uses. This method does not compute reaching
+ /// defs for new uses, and it doesn't remove dead defs.
+ /// Dead PHIDef values are marked as unused.
+ /// New dead machine instructions are added to the dead vector.
+ /// Return true if the interval may have been separated into multiple
+ /// connected components.
+ bool shrinkToUses(LiveInterval *li,
+ SmallVectorImpl<MachineInstr*> *dead = 0);
+
+ /// extendToIndices - Extend the live range of LI to reach all points in
+ /// Indices. The points in the Indices array must be jointly dominated by
+ /// existing defs in LI. PHI-defs are added as needed to maintain SSA form.
+ ///
+ /// If a SlotIndex in Indices is the end index of a basic block, LI will be
+ /// extended to be live out of the basic block.
+ ///
+ /// See also LiveRangeCalc::extend().
+ void extendToIndices(LiveInterval *LI, ArrayRef<SlotIndex> Indices);
+
+ /// pruneValue - If an LI value is live at Kill, prune its live range by
+ /// removing any liveness reachable from Kill. Add live range end points to
+ /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
+ /// value's live range.
+ ///
+ /// Calling pruneValue() and extendToIndices() can be used to reconstruct
+ /// SSA form after adding defs to a virtual register.
+ void pruneValue(LiveInterval *LI, SlotIndex Kill,
+ SmallVectorImpl<SlotIndex> *EndPoints);
+
+ SlotIndexes *getSlotIndexes() const {
+ return Indexes;
+ }
+
+ AliasAnalysis *getAliasAnalysis() const {
+ return AA;
+ }
+
+ /// isNotInMIMap - returns true if the specified machine instr has been
+ /// removed or was never entered in the map.
+ bool isNotInMIMap(const MachineInstr* Instr) const {
+ return !Indexes->hasIndex(Instr);
+ }
+
+ /// Returns the base index of the given instruction.
+ SlotIndex getInstructionIndex(const MachineInstr *instr) const {
+ return Indexes->getInstructionIndex(instr);
+ }
+
+ /// Returns the instruction associated with the given index.
+ MachineInstr* getInstructionFromIndex(SlotIndex index) const {
+ return Indexes->getInstructionFromIndex(index);
+ }
+
+ /// Return the first index in the given basic block.
+ SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
+ return Indexes->getMBBStartIdx(mbb);
+ }
+
+ /// Return the last index in the given basic block.
+ SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
+ return Indexes->getMBBEndIdx(mbb);
+ }
+
+ bool isLiveInToMBB(const LiveInterval &li,
+ const MachineBasicBlock *mbb) const {
+ return li.liveAt(getMBBStartIdx(mbb));
+ }
+
+ bool isLiveOutOfMBB(const LiveInterval &li,
+ const MachineBasicBlock *mbb) const {
+ return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
+ }
+
+ MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
+ return Indexes->getMBBFromIndex(index);
+ }
+
+ SlotIndex InsertMachineInstrInMaps(MachineInstr *MI) {
+ return Indexes->insertMachineInstrInMaps(MI);
+ }
+
+ void RemoveMachineInstrFromMaps(MachineInstr *MI) {
+ Indexes->removeMachineInstrFromMaps(MI);
+ }
+
+ void ReplaceMachineInstrInMaps(MachineInstr *MI, MachineInstr *NewMI) {
+ Indexes->replaceMachineInstrInMaps(MI, NewMI);
+ }
+
+ bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
+ SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
+ return Indexes->findLiveInMBBs(Start, End, MBBs);
+ }
+
+ VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+ virtual void releaseMemory();
+
+ /// runOnMachineFunction - pass entry point
+ virtual bool runOnMachineFunction(MachineFunction&);
+
+ /// print - Implement the dump method.
+ virtual void print(raw_ostream &O, const Module* = 0) const;
+
+ /// intervalIsInOneMBB - If LI is confined to a single basic block, return
+ /// a pointer to that block. If LI is live in to or out of any block,
+ /// return NULL.
+ MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
+
+ /// Returns true if VNI is killed by any PHI-def values in LI.
+ /// This may conservatively return true to avoid expensive computations.
+ bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
+
+ /// addKillFlags - Add kill flags to any instruction that kills a virtual
+ /// register.
+ void addKillFlags(const VirtRegMap*);
+
+ /// handleMove - call this method to notify LiveIntervals that
+ /// instruction 'mi' has been moved within a basic block. This will update
+ /// the live intervals for all operands of mi. Moves between basic blocks
+ /// are not supported.
+ void handleMove(MachineInstr* MI);
+
+ /// moveIntoBundle - Update intervals for operands of MI so that they
+ /// begin/end on the SlotIndex for BundleStart.
+ ///
+ /// Requires MI and BundleStart to have SlotIndexes, and assumes
+ /// existing liveness is accurate. BundleStart should be the first
+ /// instruction in the Bundle.
+ void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
+
+ // Register mask functions.
+ //
+ // Machine instructions may use a register mask operand to indicate that a
+ // large number of registers are clobbered by the instruction. This is
+ // typically used for calls.
+ //
+ // For compile time performance reasons, these clobbers are not recorded in
+ // the live intervals for individual physical registers. Instead,
+ // LiveIntervalAnalysis maintains a sorted list of instructions with
+ // register mask operands.
+
+ /// getRegMaskSlots - Returns a sorted array of slot indices of all
+ /// instructions with register mask operands.
+ ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
+
+ /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of all
+ /// instructions with register mask operands in the basic block numbered
+ /// MBBNum.
+ ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
+ std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
+ return getRegMaskSlots().slice(P.first, P.second);
+ }
+
+ /// getRegMaskBits() - Returns an array of register mask pointers
+ /// corresponding to getRegMaskSlots().
+ ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
+
+ /// getRegMaskBitsInBlock - Returns an array of mask pointers corresponding
+ /// to getRegMaskSlotsInBlock(MBBNum).
+ ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
+ std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
+ return getRegMaskBits().slice(P.first, P.second);
+ }
+
+ /// checkRegMaskInterference - Test if LI is live across any register mask
+ /// instructions, and compute a bit mask of physical registers that are not
+ /// clobbered by any of them.
+ ///
+ /// Returns false if LI doesn't cross any register mask instructions. In
+ /// that case, the bit vector is not filled in.
+ bool checkRegMaskInterference(LiveInterval &LI,
+ BitVector &UsableRegs);
+
+ // Register unit functions.
+ //
+ // Fixed interference occurs when MachineInstrs use physregs directly
+ // instead of virtual registers. This typically happens when passing
+ // arguments to a function call, or when instructions require operands in
+ // fixed registers.
+ //
+ // Each physreg has one or more register units, see MCRegisterInfo. We
+ // track liveness per register unit to handle aliasing registers more
+ // efficiently.
+
+ /// getRegUnit - Return the live range for Unit.
+ /// It will be computed if it doesn't exist.
+ LiveInterval &getRegUnit(unsigned Unit) {
+ LiveInterval *LI = RegUnitIntervals[Unit];
+ if (!LI) {
+ // Compute missing ranges on demand.
+ RegUnitIntervals[Unit] = LI = new LiveInterval(Unit, HUGE_VALF);
+ computeRegUnitInterval(LI);
+ }
+ return *LI;
+ }
+
+ /// getCachedRegUnit - Return the live range for Unit if it has already
+ /// been computed, or NULL if it hasn't been computed yet.
+ LiveInterval *getCachedRegUnit(unsigned Unit) {
+ return RegUnitIntervals[Unit];
+ }
+
+ private:
+ /// computeIntervals - Compute live intervals.
+ void computeIntervals();
+
+ /// Compute live intervals for all virtual registers.
+ void computeVirtRegs();
+
+ /// Compute RegMaskSlots and RegMaskBits.
+ void computeRegMasks();
+
+ /// handleRegisterDef - update intervals for a register def
+ /// (calls handleVirtualRegisterDef)
+ void handleRegisterDef(MachineBasicBlock *MBB,
+ MachineBasicBlock::iterator MI,
+ SlotIndex MIIdx,
+ MachineOperand& MO, unsigned MOIdx);
+
+ /// isPartialRedef - Return true if the specified def at the specific index
+ /// is partially re-defining the specified live interval. A common case of
+ /// this is a definition of the sub-register.
+ bool isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
+ LiveInterval &interval);
+
+ /// handleVirtualRegisterDef - update intervals for a virtual
+ /// register def
+ void handleVirtualRegisterDef(MachineBasicBlock *MBB,
+ MachineBasicBlock::iterator MI,
+ SlotIndex MIIdx, MachineOperand& MO,
+ unsigned MOIdx,
+ LiveInterval& interval);
+
+ static LiveInterval* createInterval(unsigned Reg);
+
+ void printInstrs(raw_ostream &O) const;
+ void dumpInstrs() const;
+
+ void computeLiveInRegUnits();
+ void computeRegUnitInterval(LiveInterval*);
+ void computeVirtRegInterval(LiveInterval*);
+
+ class HMEditor;
+ };
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/LiveRangeEdit.h b/include/llvm/CodeGen/LiveRangeEdit.h
new file mode 100644
index 00000000000..def7b00ce76
--- /dev/null
+++ b/include/llvm/CodeGen/LiveRangeEdit.h
@@ -0,0 +1,210 @@
+//===---- LiveRangeEdit.h - Basic tools for split and spill -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The LiveRangeEdit class represents changes done to a virtual register when it
+// is spilled or split.
+//
+// The parent register is never changed. Instead, a number of new virtual
+// registers are created and added to the newRegs vector.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_LIVERANGEEDIT_H
+#define LLVM_CODEGEN_LIVERANGEEDIT_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/CodeGen/LiveInterval.h"
+#include "llvm/Target/TargetMachine.h"
+
+namespace llvm {
+
+class AliasAnalysis;
+class LiveIntervals;
+class MachineLoopInfo;
+class MachineRegisterInfo;
+class VirtRegMap;
+
+class LiveRangeEdit {
+public:
+ /// Callback methods for LiveRangeEdit owners.
+ class Delegate {
+ virtual void anchor();
+ public:
+ /// Called immediately before erasing a dead machine instruction.
+ virtual void LRE_WillEraseInstruction(MachineInstr *MI) {}
+
+ /// Called when a virtual register is no longer used. Return false to defer
+ /// its deletion from LiveIntervals.
+ virtual bool LRE_CanEraseVirtReg(unsigned) { return true; }
+
+ /// Called before shrinking the live range of a virtual register.
+ virtual void LRE_WillShrinkVirtReg(unsigned) {}
+
+ /// Called after cloning a virtual register.
+ /// This is used for new registers representing connected components of Old.
+ virtual void LRE_DidCloneVirtReg(unsigned New, unsigned Old) {}
+
+ virtual ~Delegate() {}
+ };
+
+private:
+ LiveInterval *Parent;
+ SmallVectorImpl<LiveInterval*> &NewRegs;
+ MachineRegisterInfo &MRI;
+ LiveIntervals &LIS;
+ VirtRegMap *VRM;
+ const TargetInstrInfo &TII;
+ Delegate *const TheDelegate;
+
+ /// FirstNew - Index of the first register added to NewRegs.
+ const unsigned FirstNew;
+
+ /// ScannedRemattable - true when remattable values have been identified.
+ bool ScannedRemattable;
+
+ /// Remattable - Values defined by remattable instructions as identified by
+ /// tii.isTriviallyReMaterializable().
+ SmallPtrSet<const VNInfo*,4> Remattable;
+
+ /// Rematted - Values that were actually rematted, and so need to have their
+ /// live range trimmed or entirely removed.
+ SmallPtrSet<const VNInfo*,4> Rematted;
+
+ /// scanRemattable - Identify the Parent values that may rematerialize.
+ void scanRemattable(AliasAnalysis *aa);
+
+ /// allUsesAvailableAt - Return true if all registers used by OrigMI at
+ /// OrigIdx are also available with the same value at UseIdx.
+ bool allUsesAvailableAt(const MachineInstr *OrigMI, SlotIndex OrigIdx,
+ SlotIndex UseIdx);
+
+ /// foldAsLoad - If LI has a single use and a single def that can be folded as
+ /// a load, eliminate the register by folding the def into the use.
+ bool foldAsLoad(LiveInterval *LI, SmallVectorImpl<MachineInstr*> &Dead);
+
+public:
+ /// Create a LiveRangeEdit for breaking down parent into smaller pieces.
+ /// @param parent The register being spilled or split.
+ /// @param newRegs List to receive any new registers created. This needn't be
+ /// empty initially, any existing registers are ignored.
+ /// @param MF The MachineFunction the live range edit is taking place in.
+ /// @param lis The collection of all live intervals in this function.
+ /// @param vrm Map of virtual registers to physical registers for this
+ /// function. If NULL, no virtual register map updates will
+ /// be done. This could be the case if called before Regalloc.
+ LiveRangeEdit(LiveInterval *parent,
+ SmallVectorImpl<LiveInterval*> &newRegs,
+ MachineFunction &MF,
+ LiveIntervals &lis,
+ VirtRegMap *vrm,
+ Delegate *delegate = 0)
+ : Parent(parent), NewRegs(newRegs),
+ MRI(MF.getRegInfo()), LIS(lis), VRM(vrm),
+ TII(*MF.getTarget().getInstrInfo()),
+ TheDelegate(delegate),
+ FirstNew(newRegs.size()),
+ ScannedRemattable(false) {}
+
+ LiveInterval &getParent() const {
+ assert(Parent && "No parent LiveInterval");
+ return *Parent;
+ }
+ unsigned getReg() const { return getParent().reg; }
+
+ /// Iterator for accessing the new registers added by this edit.
+ typedef SmallVectorImpl<LiveInterval*>::const_iterator iterator;
+ iterator begin() const { return NewRegs.begin()+FirstNew; }
+ iterator end() const { return NewRegs.end(); }
+ unsigned size() const { return NewRegs.size()-FirstNew; }
+ bool empty() const { return size() == 0; }
+ LiveInterval *get(unsigned idx) const { return NewRegs[idx+FirstNew]; }
+
+ ArrayRef<LiveInterval*> regs() const {
+ return makeArrayRef(NewRegs).slice(FirstNew);
+ }
+
+ /// createFrom - Create a new virtual register based on OldReg.
+ LiveInterval &createFrom(unsigned OldReg);
+
+ /// create - Create a new register with the same class and original slot as
+ /// parent.
+ LiveInterval &create() {
+ return createFrom(getReg());
+ }
+
+ /// anyRematerializable - Return true if any parent values may be
+ /// rematerializable.
+ /// This function must be called before any rematerialization is attempted.
+ bool anyRematerializable(AliasAnalysis*);
+
+ /// checkRematerializable - Manually add VNI to the list of rematerializable
+ /// values if DefMI may be rematerializable.
+ bool checkRematerializable(VNInfo *VNI, const MachineInstr *DefMI,
+ AliasAnalysis*);
+
+ /// Remat - Information needed to rematerialize at a specific location.
+ struct Remat {
+ VNInfo *ParentVNI; // parent_'s value at the remat location.
+ MachineInstr *OrigMI; // Instruction defining ParentVNI.
+ explicit Remat(VNInfo *ParentVNI) : ParentVNI(ParentVNI), OrigMI(0) {}
+ };
+
+ /// canRematerializeAt - Determine if ParentVNI can be rematerialized at
+ /// UseIdx. It is assumed that parent_.getVNINfoAt(UseIdx) == ParentVNI.
+ /// When cheapAsAMove is set, only cheap remats are allowed.
+ bool canRematerializeAt(Remat &RM,
+ SlotIndex UseIdx,
+ bool cheapAsAMove);
+
+ /// rematerializeAt - Rematerialize RM.ParentVNI into DestReg by inserting an
+ /// instruction into MBB before MI. The new instruction is mapped, but
+ /// liveness is not updated.
+ /// Return the SlotIndex of the new instruction.
+ SlotIndex rematerializeAt(MachineBasicBlock &MBB,
+ MachineBasicBlock::iterator MI,
+ unsigned DestReg,
+ const Remat &RM,
+ const TargetRegisterInfo&,
+ bool Late = false);
+
+ /// markRematerialized - explicitly mark a value as rematerialized after doing
+ /// it manually.
+ void markRematerialized(const VNInfo *ParentVNI) {
+ Rematted.insert(ParentVNI);
+ }
+
+ /// didRematerialize - Return true if ParentVNI was rematerialized anywhere.
+ bool didRematerialize(const VNInfo *ParentVNI) const {
+ return Rematted.count(ParentVNI);
+ }
+
+ /// eraseVirtReg - Notify the delegate that Reg is no longer in use, and try
+ /// to erase it from LIS.
+ void eraseVirtReg(unsigned Reg);
+
+ /// eliminateDeadDefs - Try to delete machine instructions that are now dead
+ /// (allDefsAreDead returns true). This may cause live intervals to be trimmed
+ /// and further dead efs to be eliminated.
+ /// RegsBeingSpilled lists registers currently being spilled by the register
+ /// allocator. These registers should not be split into new intervals
+ /// as currently those new intervals are not guaranteed to spill.
+ void eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
+ ArrayRef<unsigned> RegsBeingSpilled
+ = ArrayRef<unsigned>());
+
+ /// calculateRegClassAndHint - Recompute register class and hint for each new
+ /// register.
+ void calculateRegClassAndHint(MachineFunction&,
+ const MachineLoopInfo&);
+};
+
+}
+
+#endif
diff --git a/include/llvm/CodeGen/LiveStackAnalysis.h b/include/llvm/CodeGen/LiveStackAnalysis.h
new file mode 100644
index 00000000000..86c4d7c1106
--- /dev/null
+++ b/include/llvm/CodeGen/LiveStackAnalysis.h
@@ -0,0 +1,99 @@
+//===-- LiveStackAnalysis.h - Live Stack Slot Analysis ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the live stack slot analysis pass. It is analogous to
+// live interval analysis except it's analyzing liveness of stack slots rather
+// than registers.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_LIVESTACK_ANALYSIS_H
+#define LLVM_CODEGEN_LIVESTACK_ANALYSIS_H
+
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/LiveInterval.h"
+#include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/Support/Allocator.h"
+#include <map>
+
+namespace llvm {
+
+ class LiveStacks : public MachineFunctionPass {
+ const TargetRegisterInfo *TRI;
+
+ /// Special pool allocator for VNInfo's (LiveInterval val#).
+ ///
+ VNInfo::Allocator VNInfoAllocator;
+
+ /// S2IMap - Stack slot indices to live interval mapping.
+ ///
+ typedef std::map<int, LiveInterval> SS2IntervalMap;
+ SS2IntervalMap S2IMap;
+
+ /// S2RCMap - Stack slot indices to register class mapping.
+ std::map<int, const TargetRegisterClass*> S2RCMap;
+
+ public:
+ static char ID; // Pass identification, replacement for typeid
+ LiveStacks() : MachineFunctionPass(ID) {
+ initializeLiveStacksPass(*PassRegistry::getPassRegistry());
+ }
+
+ typedef SS2IntervalMap::iterator iterator;
+ typedef SS2IntervalMap::const_iterator const_iterator;
+ const_iterator begin() const { return S2IMap.begin(); }
+ const_iterator end() const { return S2IMap.end(); }
+ iterator begin() { return S2IMap.begin(); }
+ iterator end() { return S2IMap.end(); }
+
+ unsigned getNumIntervals() const { return (unsigned)S2IMap.size(); }
+
+ LiveInterval &getOrCreateInterval(int Slot, const TargetRegisterClass *RC);
+
+ LiveInterval &getInterval(int Slot) {
+ assert(Slot >= 0 && "Spill slot indice must be >= 0");
+ SS2IntervalMap::iterator I = S2IMap.find(Slot);
+ assert(I != S2IMap.end() && "Interval does not exist for stack slot");
+ return I->second;
+ }
+
+ const LiveInterval &getInterval(int Slot) const {
+ assert(Slot >= 0 && "Spill slot indice must be >= 0");
+ SS2IntervalMap::const_iterator I = S2IMap.find(Slot);
+ assert(I != S2IMap.end() && "Interval does not exist for stack slot");
+ return I->second;
+ }
+
+ bool hasInterval(int Slot) const {
+ return S2IMap.count(Slot);
+ }
+
+ const TargetRegisterClass *getIntervalRegClass(int Slot) const {
+ assert(Slot >= 0 && "Spill slot indice must be >= 0");
+ std::map<int, const TargetRegisterClass*>::const_iterator
+ I = S2RCMap.find(Slot);
+ assert(I != S2RCMap.end() &&
+ "Register class info does not exist for stack slot");
+ return I->second;
+ }
+
+ VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+ virtual void releaseMemory();
+
+ /// runOnMachineFunction - pass entry point
+ virtual bool runOnMachineFunction(MachineFunction&);
+
+ /// print - Implement the dump method.
+ virtual void print(raw_ostream &O, const Module* = 0) const;
+ };
+}
+
+#endif /* LLVM_CODEGEN_LIVESTACK_ANALYSIS_H */
diff --git a/include/llvm/CodeGen/LiveVariables.h b/include/llvm/CodeGen/LiveVariables.h
new file mode 100644
index 00000000000..d4bb409e060
--- /dev/null
+++ b/include/llvm/CodeGen/LiveVariables.h
@@ -0,0 +1,315 @@
+//===-- llvm/CodeGen/LiveVariables.h - Live Variable Analysis ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the LiveVariables analysis pass. For each machine
+// instruction in the function, this pass calculates the set of registers that
+// are immediately dead after the instruction (i.e., the instruction calculates
+// the value, but it is never used) and the set of registers that are used by
+// the instruction, but are never used after the instruction (i.e., they are
+// killed).
+//
+// This class computes live variables using a sparse implementation based on
+// the machine code SSA form. This class computes live variable information for
+// each virtual and _register allocatable_ physical register in a function. It
+// uses the dominance properties of SSA form to efficiently compute live
+// variables for virtual registers, and assumes that physical registers are only
+// live within a single basic block (allowing it to do a single local analysis
+// to resolve physical register lifetimes in each basic block). If a physical
+// register is not register allocatable, it is not tracked. This is useful for
+// things like the stack pointer and condition codes.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_LIVEVARIABLES_H
+#define LLVM_CODEGEN_LIVEVARIABLES_H
+
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/MachineInstr.h"
+#include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/IndexedMap.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SparseBitVector.h"
+
+namespace llvm {
+
+class MachineRegisterInfo;
+class TargetRegisterInfo;
+
+class LiveVariables : public MachineFunctionPass {
+public:
+ static char ID; // Pass identification, replacement for typeid
+ LiveVariables() : MachineFunctionPass(ID) {
+ initializeLiveVariablesPass(*PassRegistry::getPassRegistry());
+ }
+
+ /// VarInfo - This represents the regions where a virtual register is live in
+ /// the program. We represent this with three different pieces of
+ /// information: the set of blocks in which the instruction is live
+ /// throughout, the set of blocks in which the instruction is actually used,
+ /// and the set of non-phi instructions that are the last users of the value.
+ ///
+ /// In the common case where a value is defined and killed in the same block,
+ /// There is one killing instruction, and AliveBlocks is empty.
+ ///
+ /// Otherwise, the value is live out of the block. If the value is live
+ /// throughout any blocks, these blocks are listed in AliveBlocks. Blocks
+ /// where the liveness range ends are not included in AliveBlocks, instead
+ /// being captured by the Kills set. In these blocks, the value is live into
+ /// the block (unless the value is defined and killed in the same block) and
+ /// lives until the specified instruction. Note that there cannot ever be a
+ /// value whose Kills set contains two instructions from the same basic block.
+ ///
+ /// PHI nodes complicate things a bit. If a PHI node is the last user of a
+ /// value in one of its predecessor blocks, it is not listed in the kills set,
+ /// but does include the predecessor block in the AliveBlocks set (unless that
+ /// block also defines the value). This leads to the (perfectly sensical)
+ /// situation where a value is defined in a block, and the last use is a phi
+ /// node in the successor. In this case, AliveBlocks is empty (the value is
+ /// not live across any blocks) and Kills is empty (phi nodes are not
+ /// included). This is sensical because the value must be live to the end of
+ /// the block, but is not live in any successor blocks.
+ struct VarInfo {
+ /// AliveBlocks - Set of blocks in which this value is alive completely
+ /// through. This is a bit set which uses the basic block number as an
+ /// index.
+ ///
+ SparseBitVector<> AliveBlocks;
+
+ /// Kills - List of MachineInstruction's which are the last use of this
+ /// virtual register (kill it) in their basic block.
+ ///
+ std::vector<MachineInstr*> Kills;
+
+ /// removeKill - Delete a kill corresponding to the specified
+ /// machine instruction. Returns true if there was a kill
+ /// corresponding to this instruction, false otherwise.
+ bool removeKill(MachineInstr *MI) {
+ std::vector<MachineInstr*>::iterator
+ I = std::find(Kills.begin(), Kills.end(), MI);
+ if (I == Kills.end())
+ return false;
+ Kills.erase(I);
+ return true;
+ }
+
+ /// findKill - Find a kill instruction in MBB. Return NULL if none is found.
+ MachineInstr *findKill(const MachineBasicBlock *MBB) const;
+
+ /// isLiveIn - Is Reg live in to MBB? This means that Reg is live through
+ /// MBB, or it is killed in MBB. If Reg is only used by PHI instructions in
+ /// MBB, it is not considered live in.
+ bool isLiveIn(const MachineBasicBlock &MBB,
+ unsigned Reg,
+ MachineRegisterInfo &MRI);
+
+ void dump() const;
+ };
+
+private:
+ /// VirtRegInfo - This list is a mapping from virtual register number to
+ /// variable information.
+ ///
+ IndexedMap<VarInfo, VirtReg2IndexFunctor> VirtRegInfo;
+
+ /// PHIJoins - list of virtual registers that are PHI joins. These registers
+ /// may have multiple definitions, and they require special handling when
+ /// building live intervals.
+ SparseBitVector<> PHIJoins;
+
+ /// ReservedRegisters - This vector keeps track of which registers
+ /// are reserved register which are not allocatable by the target machine.
+ /// We can not track liveness for values that are in this set.
+ ///
+ BitVector ReservedRegisters;
+
+private: // Intermediate data structures
+ MachineFunction *MF;
+
+ MachineRegisterInfo* MRI;
+
+ const TargetRegisterInfo *TRI;
+
+ // PhysRegInfo - Keep track of which instruction was the last def of a
+ // physical register. This is a purely local property, because all physical
+ // register references are presumed dead across basic blocks.
+ MachineInstr **PhysRegDef;
+
+ // PhysRegInfo - Keep track of which instruction was the last use of a
+ // physical register. This is a purely local property, because all physical
+ // register references are presumed dead across basic blocks.
+ MachineInstr **PhysRegUse;
+
+ SmallVector<unsigned, 4> *PHIVarInfo;
+
+ // DistanceMap - Keep track the distance of a MI from the start of the
+ // current basic block.
+ DenseMap<MachineInstr*, unsigned> DistanceMap;
+
+ /// HandlePhysRegKill - Add kills of Reg and its sub-registers to the
+ /// uses. Pay special attention to the sub-register uses which may come below
+ /// the last use of the whole register.
+ bool HandlePhysRegKill(unsigned Reg, MachineInstr *MI);
+
+ /// HandleRegMask - Call HandlePhysRegKill for all registers clobbered by Mask.
+ void HandleRegMask(const MachineOperand&);
+
+ void HandlePhysRegUse(unsigned Reg, MachineInstr *MI);
+ void HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
+ SmallVector<unsigned, 4> &Defs);
+ void UpdatePhysRegDefs(MachineInstr *MI, SmallVector<unsigned, 4> &Defs);
+
+ /// FindLastRefOrPartRef - Return the last reference or partial reference of
+ /// the specified register.
+ MachineInstr *FindLastRefOrPartRef(unsigned Reg);
+
+ /// FindLastPartialDef - Return the last partial def of the specified
+ /// register. Also returns the sub-registers that're defined by the
+ /// instruction.
+ MachineInstr *FindLastPartialDef(unsigned Reg,
+ SmallSet<unsigned,4> &PartDefRegs);
+
+ /// analyzePHINodes - Gather information about the PHI nodes in here. In
+ /// particular, we want to map the variable information of a virtual
+ /// register which is used in a PHI node. We map that to the BB the vreg
+ /// is coming from.
+ void analyzePHINodes(const MachineFunction& Fn);
+public:
+
+ virtual bool runOnMachineFunction(MachineFunction &MF);
+
+ /// RegisterDefIsDead - Return true if the specified instruction defines the
+ /// specified register, but that definition is dead.
+ bool RegisterDefIsDead(MachineInstr *MI, unsigned Reg) const;
+
+ //===--------------------------------------------------------------------===//
+ // API to update live variable information
+
+ /// replaceKillInstruction - Update register kill info by replacing a kill
+ /// instruction with a new one.
+ void replaceKillInstruction(unsigned Reg, MachineInstr *OldMI,
+ MachineInstr *NewMI);
+
+ /// addVirtualRegisterKilled - Add information about the fact that the
+ /// specified register is killed after being used by the specified
+ /// instruction. If AddIfNotFound is true, add a implicit operand if it's
+ /// not found.
+ void addVirtualRegisterKilled(unsigned IncomingReg, MachineInstr *MI,
+ bool AddIfNotFound = false) {
+ if (MI->addRegisterKilled(IncomingReg, TRI, AddIfNotFound))
+ getVarInfo(IncomingReg).Kills.push_back(MI);
+ }
+
+ /// removeVirtualRegisterKilled - Remove the specified kill of the virtual
+ /// register from the live variable information. Returns true if the
+ /// variable was marked as killed by the specified instruction,
+ /// false otherwise.
+ bool removeVirtualRegisterKilled(unsigned reg, MachineInstr *MI) {
+ if (!getVarInfo(reg).removeKill(MI))
+ return false;
+
+ bool Removed = false;
+ for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
+ MachineOperand &MO = MI->getOperand(i);
+ if (MO.isReg() && MO.isKill() && MO.getReg() == reg) {
+ MO.setIsKill(false);
+ Removed = true;
+ break;
+ }
+ }
+
+ assert(Removed && "Register is not used by this instruction!");
+ (void)Removed;
+ return true;
+ }
+
+ /// removeVirtualRegistersKilled - Remove all killed info for the specified
+ /// instruction.
+ void removeVirtualRegistersKilled(MachineInstr *MI);
+
+ /// addVirtualRegisterDead - Add information about the fact that the specified
+ /// register is dead after being used by the specified instruction. If
+ /// AddIfNotFound is true, add a implicit operand if it's not found.
+ void addVirtualRegisterDead(unsigned IncomingReg, MachineInstr *MI,
+ bool AddIfNotFound = false) {
+ if (MI->addRegisterDead(IncomingReg, TRI, AddIfNotFound))
+ getVarInfo(IncomingReg).Kills.push_back(MI);
+ }
+
+ /// removeVirtualRegisterDead - Remove the specified kill of the virtual
+ /// register from the live variable information. Returns true if the
+ /// variable was marked dead at the specified instruction, false
+ /// otherwise.
+ bool removeVirtualRegisterDead(unsigned reg, MachineInstr *MI) {
+ if (!getVarInfo(reg).removeKill(MI))
+ return false;
+
+ bool Removed = false;
+ for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
+ MachineOperand &MO = MI->getOperand(i);
+ if (MO.isReg() && MO.isDef() && MO.getReg() == reg) {
+ MO.setIsDead(false);
+ Removed = true;
+ break;
+ }
+ }
+ assert(Removed && "Register is not defined by this instruction!");
+ (void)Removed;
+ return true;
+ }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ virtual void releaseMemory() {
+ VirtRegInfo.clear();
+ }
+
+ /// getVarInfo - Return the VarInfo structure for the specified VIRTUAL
+ /// register.
+ VarInfo &getVarInfo(unsigned RegIdx);
+
+ void MarkVirtRegAliveInBlock(VarInfo& VRInfo, MachineBasicBlock* DefBlock,
+ MachineBasicBlock *BB);
+ void MarkVirtRegAliveInBlock(VarInfo& VRInfo, MachineBasicBlock* DefBlock,
+ MachineBasicBlock *BB,
+ std::vector<MachineBasicBlock*> &WorkList);
+ void HandleVirtRegDef(unsigned reg, MachineInstr *MI);
+ void HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB,
+ MachineInstr *MI);
+
+ bool isLiveIn(unsigned Reg, const MachineBasicBlock &MBB) {
+ return getVarInfo(Reg).isLiveIn(MBB, Reg, *MRI);
+ }
+
+ /// isLiveOut - Determine if Reg is live out from MBB, when not considering
+ /// PHI nodes. This means that Reg is either killed by a successor block or
+ /// passed through one.
+ bool isLiveOut(unsigned Reg, const MachineBasicBlock &MBB);
+
+ /// addNewBlock - Add a new basic block BB between DomBB and SuccBB. All
+ /// variables that are live out of DomBB and live into SuccBB will be marked
+ /// as passing live through BB. This method assumes that the machine code is
+ /// still in SSA form.
+ void addNewBlock(MachineBasicBlock *BB,
+ MachineBasicBlock *DomBB,
+ MachineBasicBlock *SuccBB);
+
+ /// isPHIJoin - Return true if Reg is a phi join register.
+ bool isPHIJoin(unsigned Reg) { return PHIJoins.test(Reg); }
+
+ /// setPHIJoin - Mark Reg as a phi join register.
+ void setPHIJoin(unsigned Reg) { PHIJoins.set(Reg); }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachORelocation.h b/include/llvm/CodeGen/MachORelocation.h
new file mode 100644
index 00000000000..21fe74f8e1c
--- /dev/null
+++ b/include/llvm/CodeGen/MachORelocation.h
@@ -0,0 +1,56 @@
+//=== MachORelocation.h - Mach-O Relocation Info ----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MachORelocation class.
+//
+//===----------------------------------------------------------------------===//
+
+
+#ifndef LLVM_CODEGEN_MACHO_RELOCATION_H
+#define LLVM_CODEGEN_MACHO_RELOCATION_H
+
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+ /// MachORelocation - This struct contains information about each relocation
+ /// that needs to be emitted to the file.
+ /// see <mach-o/reloc.h>
+ class MachORelocation {
+ uint32_t r_address; // offset in the section to what is being relocated
+ uint32_t r_symbolnum; // symbol index if r_extern == 1 else section index
+ bool r_pcrel; // was relocated pc-relative already
+ uint8_t r_length; // length = 2 ^ r_length
+ bool r_extern; //
+ uint8_t r_type; // if not 0, machine-specific relocation type.
+ bool r_scattered; // 1 = scattered, 0 = non-scattered
+ int32_t r_value; // the value the item to be relocated is referring
+ // to.
+ public:
+ uint32_t getPackedFields() const {
+ if (r_scattered)
+ return (1 << 31) | (r_pcrel << 30) | ((r_length & 3) << 28) |
+ ((r_type & 15) << 24) | (r_address & 0x00FFFFFF);
+ else
+ return (r_symbolnum << 8) | (r_pcrel << 7) | ((r_length & 3) << 5) |
+ (r_extern << 4) | (r_type & 15);
+ }
+ uint32_t getAddress() const { return r_scattered ? r_value : r_address; }
+ uint32_t getRawAddress() const { return r_address; }
+
+ MachORelocation(uint32_t addr, uint32_t index, bool pcrel, uint8_t len,
+ bool ext, uint8_t type, bool scattered = false,
+ int32_t value = 0) :
+ r_address(addr), r_symbolnum(index), r_pcrel(pcrel), r_length(len),
+ r_extern(ext), r_type(type), r_scattered(scattered), r_value(value) {}
+ };
+
+} // end llvm namespace
+
+#endif // LLVM_CODEGEN_MACHO_RELOCATION_H
diff --git a/include/llvm/CodeGen/MachineBasicBlock.h b/include/llvm/CodeGen/MachineBasicBlock.h
new file mode 100644
index 00000000000..97c39458d93
--- /dev/null
+++ b/include/llvm/CodeGen/MachineBasicBlock.h
@@ -0,0 +1,703 @@
+//===-- llvm/CodeGen/MachineBasicBlock.h ------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Collect the sequence of machine instructions for a basic block.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
+#define LLVM_CODEGEN_MACHINEBASICBLOCK_H
+
+#include "llvm/CodeGen/MachineInstr.h"
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/Support/DataTypes.h"
+#include <functional>
+
+namespace llvm {
+
+class Pass;
+class BasicBlock;
+class MachineFunction;
+class MCSymbol;
+class SlotIndexes;
+class StringRef;
+class raw_ostream;
+class MachineBranchProbabilityInfo;
+
+template <>
+struct ilist_traits<MachineInstr> : public ilist_default_traits<MachineInstr> {
+private:
+ mutable ilist_half_node<MachineInstr> Sentinel;
+
+ // this is only set by the MachineBasicBlock owning the LiveList
+ friend class MachineBasicBlock;
+ MachineBasicBlock* Parent;
+
+public:
+ MachineInstr *createSentinel() const {
+ return static_cast<MachineInstr*>(&Sentinel);
+ }
+ void destroySentinel(MachineInstr *) const {}
+
+ MachineInstr *provideInitialHead() const { return createSentinel(); }
+ MachineInstr *ensureHead(MachineInstr*) const { return createSentinel(); }
+ static void noteHead(MachineInstr*, MachineInstr*) {}
+
+ void addNodeToList(MachineInstr* N);
+ void removeNodeFromList(MachineInstr* N);
+ void transferNodesFromList(ilist_traits &SrcTraits,
+ ilist_iterator<MachineInstr> first,
+ ilist_iterator<MachineInstr> last);
+ void deleteNode(MachineInstr *N);
+private:
+ void createNode(const MachineInstr &);
+};
+
+class MachineBasicBlock : public ilist_node<MachineBasicBlock> {
+ typedef ilist<MachineInstr> Instructions;
+ Instructions Insts;
+ const BasicBlock *BB;
+ int Number;
+ MachineFunction *xParent;
+
+ /// Predecessors/Successors - Keep track of the predecessor / successor
+ /// basicblocks.
+ std::vector<MachineBasicBlock *> Predecessors;
+ std::vector<MachineBasicBlock *> Successors;
+
+
+ /// Weights - Keep track of the weights to the successors. This vector
+ /// has the same order as Successors, or it is empty if we don't use it
+ /// (disable optimization).
+ std::vector<uint32_t> Weights;
+ typedef std::vector<uint32_t>::iterator weight_iterator;
+ typedef std::vector<uint32_t>::const_iterator const_weight_iterator;
+
+ /// LiveIns - Keep track of the physical registers that are livein of
+ /// the basicblock.
+ std::vector<unsigned> LiveIns;
+
+ /// Alignment - Alignment of the basic block. Zero if the basic block does
+ /// not need to be aligned.
+ /// The alignment is specified as log2(bytes).
+ unsigned Alignment;
+
+ /// IsLandingPad - Indicate that this basic block is entered via an
+ /// exception handler.
+ bool IsLandingPad;
+
+ /// AddressTaken - Indicate that this basic block is potentially the
+ /// target of an indirect branch.
+ bool AddressTaken;
+
+ // Intrusive list support
+ MachineBasicBlock() {}
+
+ explicit MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb);
+
+ ~MachineBasicBlock();
+
+ // MachineBasicBlocks are allocated and owned by MachineFunction.
+ friend class MachineFunction;
+
+public:
+ /// getBasicBlock - Return the LLVM basic block that this instance
+ /// corresponded to originally. Note that this may be NULL if this instance
+ /// does not correspond directly to an LLVM basic block.
+ ///
+ const BasicBlock *getBasicBlock() const { return BB; }
+
+ /// getName - Return the name of the corresponding LLVM basic block, or
+ /// "(null)".
+ StringRef getName() const;
+
+ /// getFullName - Return a formatted string to identify this block and its
+ /// parent function.
+ std::string getFullName() const;
+
+ /// hasAddressTaken - Test whether this block is potentially the target
+ /// of an indirect branch.
+ bool hasAddressTaken() const { return AddressTaken; }
+
+ /// setHasAddressTaken - Set this block to reflect that it potentially
+ /// is the target of an indirect branch.
+ void setHasAddressTaken() { AddressTaken = true; }
+
+ /// getParent - Return the MachineFunction containing this basic block.
+ ///
+ const MachineFunction *getParent() const { return xParent; }
+ MachineFunction *getParent() { return xParent; }
+
+
+ /// bundle_iterator - MachineBasicBlock iterator that automatically skips over
+ /// MIs that are inside bundles (i.e. walk top level MIs only).
+ template<typename Ty, typename IterTy>
+ class bundle_iterator
+ : public std::iterator<std::bidirectional_iterator_tag, Ty, ptrdiff_t> {
+ IterTy MII;
+
+ public:
+ bundle_iterator(IterTy mii) : MII(mii) {}
+
+ bundle_iterator(Ty &mi) : MII(mi) {
+ assert(!mi.isInsideBundle() &&
+ "It's not legal to initialize bundle_iterator with a bundled MI");
+ }
+ bundle_iterator(Ty *mi) : MII(mi) {
+ assert((!mi || !mi->isInsideBundle()) &&
+ "It's not legal to initialize bundle_iterator with a bundled MI");
+ }
+ // Template allows conversion from const to nonconst.
+ template<class OtherTy, class OtherIterTy>
+ bundle_iterator(const bundle_iterator<OtherTy, OtherIterTy> &I)
+ : MII(I.getInstrIterator()) {}
+ bundle_iterator() : MII(0) {}
+
+ Ty &operator*() const { return *MII; }
+ Ty *operator->() const { return &operator*(); }
+
+ operator Ty*() const { return MII; }
+
+ bool operator==(const bundle_iterator &x) const {
+ return MII == x.MII;
+ }
+ bool operator!=(const bundle_iterator &x) const {
+ return !operator==(x);
+ }
+
+ // Increment and decrement operators...
+ bundle_iterator &operator--() { // predecrement - Back up
+ do --MII;
+ while (MII->isInsideBundle());
+ return *this;
+ }
+ bundle_iterator &operator++() { // preincrement - Advance
+ IterTy E = MII->getParent()->instr_end();
+ do ++MII;
+ while (MII != E && MII->isInsideBundle());
+ return *this;
+ }
+ bundle_iterator operator--(int) { // postdecrement operators...
+ bundle_iterator tmp = *this;
+ --*this;
+ return tmp;
+ }
+ bundle_iterator operator++(int) { // postincrement operators...
+ bundle_iterator tmp = *this;
+ ++*this;
+ return tmp;
+ }
+
+ IterTy getInstrIterator() const {
+ return MII;
+ }
+ };
+
+ typedef Instructions::iterator instr_iterator;
+ typedef Instructions::const_iterator const_instr_iterator;
+ typedef std::reverse_iterator<instr_iterator> reverse_instr_iterator;
+ typedef
+ std::reverse_iterator<const_instr_iterator> const_reverse_instr_iterator;
+
+ typedef
+ bundle_iterator<MachineInstr,instr_iterator> iterator;
+ typedef
+ bundle_iterator<const MachineInstr,const_instr_iterator> const_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+
+
+ unsigned size() const { return (unsigned)Insts.size(); }
+ bool empty() const { return Insts.empty(); }
+
+ MachineInstr& front() { return Insts.front(); }
+ MachineInstr& back() { return Insts.back(); }
+ const MachineInstr& front() const { return Insts.front(); }
+ const MachineInstr& back() const { return Insts.back(); }
+
+ instr_iterator instr_begin() { return Insts.begin(); }
+ const_instr_iterator instr_begin() const { return Insts.begin(); }
+ instr_iterator instr_end() { return Insts.end(); }
+ const_instr_iterator instr_end() const { return Insts.end(); }
+ reverse_instr_iterator instr_rbegin() { return Insts.rbegin(); }
+ const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
+ reverse_instr_iterator instr_rend () { return Insts.rend(); }
+ const_reverse_instr_iterator instr_rend () const { return Insts.rend(); }
+
+ iterator begin() { return instr_begin(); }
+ const_iterator begin() const { return instr_begin(); }
+ iterator end () { return instr_end(); }
+ const_iterator end () const { return instr_end(); }
+ reverse_iterator rbegin() { return instr_rbegin(); }
+ const_reverse_iterator rbegin() const { return instr_rbegin(); }
+ reverse_iterator rend () { return instr_rend(); }
+ const_reverse_iterator rend () const { return instr_rend(); }
+
+
+ // Machine-CFG iterators
+ typedef std::vector<MachineBasicBlock *>::iterator pred_iterator;
+ typedef std::vector<MachineBasicBlock *>::const_iterator const_pred_iterator;
+ typedef std::vector<MachineBasicBlock *>::iterator succ_iterator;
+ typedef std::vector<MachineBasicBlock *>::const_iterator const_succ_iterator;
+ typedef std::vector<MachineBasicBlock *>::reverse_iterator
+ pred_reverse_iterator;
+ typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
+ const_pred_reverse_iterator;
+ typedef std::vector<MachineBasicBlock *>::reverse_iterator
+ succ_reverse_iterator;
+ typedef std::vector<MachineBasicBlock *>::const_reverse_iterator
+ const_succ_reverse_iterator;
+
+ pred_iterator pred_begin() { return Predecessors.begin(); }
+ const_pred_iterator pred_begin() const { return Predecessors.begin(); }
+ pred_iterator pred_end() { return Predecessors.end(); }
+ const_pred_iterator pred_end() const { return Predecessors.end(); }
+ pred_reverse_iterator pred_rbegin()
+ { return Predecessors.rbegin();}
+ const_pred_reverse_iterator pred_rbegin() const
+ { return Predecessors.rbegin();}
+ pred_reverse_iterator pred_rend()
+ { return Predecessors.rend(); }
+ const_pred_reverse_iterator pred_rend() const
+ { return Predecessors.rend(); }
+ unsigned pred_size() const {
+ return (unsigned)Predecessors.size();
+ }
+ bool pred_empty() const { return Predecessors.empty(); }
+ succ_iterator succ_begin() { return Successors.begin(); }
+ const_succ_iterator succ_begin() const { return Successors.begin(); }
+ succ_iterator succ_end() { return Successors.end(); }
+ const_succ_iterator succ_end() const { return Successors.end(); }
+ succ_reverse_iterator succ_rbegin()
+ { return Successors.rbegin(); }
+ const_succ_reverse_iterator succ_rbegin() const
+ { return Successors.rbegin(); }
+ succ_reverse_iterator succ_rend()
+ { return Successors.rend(); }
+ const_succ_reverse_iterator succ_rend() const
+ { return Successors.rend(); }
+ unsigned succ_size() const {
+ return (unsigned)Successors.size();
+ }
+ bool succ_empty() const { return Successors.empty(); }
+
+ // LiveIn management methods.
+
+ /// addLiveIn - Add the specified register as a live in. Note that it
+ /// is an error to add the same register to the same set more than once.
+ void addLiveIn(unsigned Reg) { LiveIns.push_back(Reg); }
+
+ /// removeLiveIn - Remove the specified register from the live in set.
+ ///
+ void removeLiveIn(unsigned Reg);
+
+ /// isLiveIn - Return true if the specified register is in the live in set.
+ ///
+ bool isLiveIn(unsigned Reg) const;
+
+ // Iteration support for live in sets. These sets are kept in sorted
+ // order by their register number.
+ typedef std::vector<unsigned>::const_iterator livein_iterator;
+ livein_iterator livein_begin() const { return LiveIns.begin(); }
+ livein_iterator livein_end() const { return LiveIns.end(); }
+ bool livein_empty() const { return LiveIns.empty(); }
+
+ /// getAlignment - Return alignment of the basic block.
+ /// The alignment is specified as log2(bytes).
+ ///
+ unsigned getAlignment() const { return Alignment; }
+
+ /// setAlignment - Set alignment of the basic block.
+ /// The alignment is specified as log2(bytes).
+ ///
+ void setAlignment(unsigned Align) { Alignment = Align; }
+
+ /// isLandingPad - Returns true if the block is a landing pad. That is
+ /// this basic block is entered via an exception handler.
+ bool isLandingPad() const { return IsLandingPad; }
+
+ /// setIsLandingPad - Indicates the block is a landing pad. That is
+ /// this basic block is entered via an exception handler.
+ void setIsLandingPad(bool V = true) { IsLandingPad = V; }
+
+ /// getLandingPadSuccessor - If this block has a successor that is a landing
+ /// pad, return it. Otherwise return NULL.
+ const MachineBasicBlock *getLandingPadSuccessor() const;
+
+ // Code Layout methods.
+
+ /// moveBefore/moveAfter - move 'this' block before or after the specified
+ /// block. This only moves the block, it does not modify the CFG or adjust
+ /// potential fall-throughs at the end of the block.
+ void moveBefore(MachineBasicBlock *NewAfter);
+ void moveAfter(MachineBasicBlock *NewBefore);
+
+ /// updateTerminator - Update the terminator instructions in block to account
+ /// for changes to the layout. If the block previously used a fallthrough,
+ /// it may now need a branch, and if it previously used branching it may now
+ /// be able to use a fallthrough.
+ void updateTerminator();
+
+ // Machine-CFG mutators
+
+ /// addSuccessor - Add succ as a successor of this MachineBasicBlock.
+ /// The Predecessors list of succ is automatically updated. WEIGHT
+ /// parameter is stored in Weights list and it may be used by
+ /// MachineBranchProbabilityInfo analysis to calculate branch probability.
+ ///
+ /// Note that duplicate Machine CFG edges are not allowed.
+ ///
+ void addSuccessor(MachineBasicBlock *succ, uint32_t weight = 0);
+
+ /// removeSuccessor - Remove successor from the successors list of this
+ /// MachineBasicBlock. The Predecessors list of succ is automatically updated.
+ ///
+ void removeSuccessor(MachineBasicBlock *succ);
+
+ /// removeSuccessor - Remove specified successor from the successors list of
+ /// this MachineBasicBlock. The Predecessors list of succ is automatically
+ /// updated. Return the iterator to the element after the one removed.
+ ///
+ succ_iterator removeSuccessor(succ_iterator I);
+
+ /// replaceSuccessor - Replace successor OLD with NEW and update weight info.
+ ///
+ void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
+
+
+ /// transferSuccessors - Transfers all the successors from MBB to this
+ /// machine basic block (i.e., copies all the successors fromMBB and
+ /// remove all the successors from fromMBB).
+ void transferSuccessors(MachineBasicBlock *fromMBB);
+
+ /// transferSuccessorsAndUpdatePHIs - Transfers all the successors, as
+ /// in transferSuccessors, and update PHI operands in the successor blocks
+ /// which refer to fromMBB to refer to this.
+ void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB);
+
+ /// isPredecessor - Return true if the specified MBB is a predecessor of this
+ /// block.
+ bool isPredecessor(const MachineBasicBlock *MBB) const;
+
+ /// isSuccessor - Return true if the specified MBB is a successor of this
+ /// block.
+ bool isSuccessor(const MachineBasicBlock *MBB) const;
+
+ /// isLayoutSuccessor - Return true if the specified MBB will be emitted
+ /// immediately after this block, such that if this block exits by
+ /// falling through, control will transfer to the specified MBB. Note
+ /// that MBB need not be a successor at all, for example if this block
+ /// ends with an unconditional branch to some other block.
+ bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
+
+ /// canFallThrough - Return true if the block can implicitly transfer
+ /// control to the block after it by falling off the end of it. This should
+ /// return false if it can reach the block after it, but it uses an explicit
+ /// branch to do so (e.g., a table jump). True is a conservative answer.
+ bool canFallThrough();
+
+ /// Returns a pointer to the first instructon in this block that is not a
+ /// PHINode instruction. When adding instruction to the beginning of the
+ /// basic block, they should be added before the returned value, not before
+ /// the first instruction, which might be PHI.
+ /// Returns end() is there's no non-PHI instruction.
+ iterator getFirstNonPHI();
+
+ /// SkipPHIsAndLabels - Return the first instruction in MBB after I that is
+ /// not a PHI or a label. This is the correct point to insert copies at the
+ /// beginning of a basic block.
+ iterator SkipPHIsAndLabels(iterator I);
+
+ /// getFirstTerminator - returns an iterator to the first terminator
+ /// instruction of this basic block. If a terminator does not exist,
+ /// it returns end()
+ iterator getFirstTerminator();
+ const_iterator getFirstTerminator() const;
+
+ /// getFirstInstrTerminator - Same getFirstTerminator but it ignores bundles
+ /// and return an instr_iterator instead.
+ instr_iterator getFirstInstrTerminator();
+
+ /// getLastNonDebugInstr - returns an iterator to the last non-debug
+ /// instruction in the basic block, or end()
+ iterator getLastNonDebugInstr();
+ const_iterator getLastNonDebugInstr() const;
+
+ /// SplitCriticalEdge - Split the critical edge from this block to the
+ /// given successor block, and return the newly created block, or null
+ /// if splitting is not possible.
+ ///
+ /// This function updates LiveVariables, MachineDominatorTree, and
+ /// MachineLoopInfo, as applicable.
+ MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P);
+
+ void pop_front() { Insts.pop_front(); }
+ void pop_back() { Insts.pop_back(); }
+ void push_back(MachineInstr *MI) { Insts.push_back(MI); }
+
+ template<typename IT>
+ void insert(instr_iterator I, IT S, IT E) {
+ Insts.insert(I, S, E);
+ }
+ instr_iterator insert(instr_iterator I, MachineInstr *M) {
+ return Insts.insert(I, M);
+ }
+ instr_iterator insertAfter(instr_iterator I, MachineInstr *M) {
+ return Insts.insertAfter(I, M);
+ }
+
+ template<typename IT>
+ void insert(iterator I, IT S, IT E) {
+ Insts.insert(I.getInstrIterator(), S, E);
+ }
+ iterator insert(iterator I, MachineInstr *M) {
+ return Insts.insert(I.getInstrIterator(), M);
+ }
+ iterator insertAfter(iterator I, MachineInstr *M) {
+ return Insts.insertAfter(I.getInstrIterator(), M);
+ }
+
+ /// erase - Remove the specified element or range from the instruction list.
+ /// These functions delete any instructions removed.
+ ///
+ instr_iterator erase(instr_iterator I) {
+ return Insts.erase(I);
+ }
+ instr_iterator erase(instr_iterator I, instr_iterator E) {
+ return Insts.erase(I, E);
+ }
+ instr_iterator erase_instr(MachineInstr *I) {
+ instr_iterator MII(I);
+ return erase(MII);
+ }
+
+ iterator erase(iterator I);
+ iterator erase(iterator I, iterator E) {
+ return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
+ }
+ iterator erase(MachineInstr *I) {
+ iterator MII(I);
+ return erase(MII);
+ }
+
+ /// remove - Remove the instruction from the instruction list. This function
+ /// does not delete the instruction. WARNING: Note, if the specified
+ /// instruction is a bundle this function will remove all the bundled
+ /// instructions as well. It is up to the caller to keep a list of the
+ /// bundled instructions and re-insert them if desired. This function is
+ /// *not recommended* for manipulating instructions with bundles. Use
+ /// splice instead.
+ MachineInstr *remove(MachineInstr *I);
+ void clear() {
+ Insts.clear();
+ }
+
+ /// splice - Take an instruction from MBB 'Other' at the position From,
+ /// and insert it into this MBB right before 'where'.
+ void splice(instr_iterator where, MachineBasicBlock *Other,
+ instr_iterator From) {
+ Insts.splice(where, Other->Insts, From);
+ }
+ void splice(iterator where, MachineBasicBlock *Other, iterator From);
+
+ /// splice - Take a block of instructions from MBB 'Other' in the range [From,
+ /// To), and insert them into this MBB right before 'where'.
+ void splice(instr_iterator where, MachineBasicBlock *Other, instr_iterator From,
+ instr_iterator To) {
+ Insts.splice(where, Other->Insts, From, To);
+ }
+ void splice(iterator where, MachineBasicBlock *Other, iterator From,
+ iterator To) {
+ Insts.splice(where.getInstrIterator(), Other->Insts,
+ From.getInstrIterator(), To.getInstrIterator());
+ }
+
+ /// removeFromParent - This method unlinks 'this' from the containing
+ /// function, and returns it, but does not delete it.
+ MachineBasicBlock *removeFromParent();
+
+ /// eraseFromParent - This method unlinks 'this' from the containing
+ /// function and deletes it.
+ void eraseFromParent();
+
+ /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
+ /// 'Old', change the code and CFG so that it branches to 'New' instead.
+ void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
+
+ /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in
+ /// the CFG to be inserted. If we have proven that MBB can only branch to
+ /// DestA and DestB, remove any other MBB successors from the CFG. DestA and
+ /// DestB can be null. Besides DestA and DestB, retain other edges leading
+ /// to LandingPads (currently there can be only one; we don't check or require
+ /// that here). Note it is possible that DestA and/or DestB are LandingPads.
+ bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
+ MachineBasicBlock *DestB,
+ bool isCond);
+
+ /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
+ /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
+ DebugLoc findDebugLoc(instr_iterator MBBI);
+ DebugLoc findDebugLoc(iterator MBBI) {
+ return findDebugLoc(MBBI.getInstrIterator());
+ }
+
+ /// Possible outcome of a register liveness query to computeRegisterLiveness()
+ enum LivenessQueryResult {
+ LQR_Live, ///< Register is known to be live.
+ LQR_OverlappingLive, ///< Register itself is not live, but some overlapping
+ ///< register is.
+ LQR_Dead, ///< Register is known to be dead.
+ LQR_Unknown ///< Register liveness not decidable from local
+ ///< neighborhood.
+ };
+
+ /// computeRegisterLiveness - Return whether (physical) register \c Reg
+ /// has been <def>ined and not <kill>ed as of just before \c MI.
+ ///
+ /// Search is localised to a neighborhood of
+ /// \c Neighborhood instructions before (searching for defs or kills) and
+ /// Neighborhood instructions after (searching just for defs) MI.
+ ///
+ /// \c Reg must be a physical register.
+ LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
+ unsigned Reg, MachineInstr *MI,
+ unsigned Neighborhood=10);
+
+ // Debugging methods.
+ void dump() const;
+ void print(raw_ostream &OS, SlotIndexes* = 0) const;
+
+ /// getNumber - MachineBasicBlocks are uniquely numbered at the function
+ /// level, unless they're not in a MachineFunction yet, in which case this
+ /// will return -1.
+ ///
+ int getNumber() const { return Number; }
+ void setNumber(int N) { Number = N; }
+
+ /// getSymbol - Return the MCSymbol for this basic block.
+ ///
+ MCSymbol *getSymbol() const;
+
+
+private:
+ /// getWeightIterator - Return weight iterator corresponding to the I
+ /// successor iterator.
+ weight_iterator getWeightIterator(succ_iterator I);
+ const_weight_iterator getWeightIterator(const_succ_iterator I) const;
+
+ friend class MachineBranchProbabilityInfo;
+
+ /// getSuccWeight - Return weight of the edge from this block to MBB. This
+ /// method should NOT be called directly, but by using getEdgeWeight method
+ /// from MachineBranchProbabilityInfo class.
+ uint32_t getSuccWeight(const_succ_iterator Succ) const;
+
+
+ // Methods used to maintain doubly linked list of blocks...
+ friend struct ilist_traits<MachineBasicBlock>;
+
+ // Machine-CFG mutators
+
+ /// addPredecessor - Remove pred as a predecessor of this MachineBasicBlock.
+ /// Don't do this unless you know what you're doing, because it doesn't
+ /// update pred's successors list. Use pred->addSuccessor instead.
+ ///
+ void addPredecessor(MachineBasicBlock *pred);
+
+ /// removePredecessor - Remove pred as a predecessor of this
+ /// MachineBasicBlock. Don't do this unless you know what you're
+ /// doing, because it doesn't update pred's successors list. Use
+ /// pred->removeSuccessor instead.
+ ///
+ void removePredecessor(MachineBasicBlock *pred);
+};
+
+raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
+
+void WriteAsOperand(raw_ostream &, const MachineBasicBlock*, bool t);
+
+// This is useful when building IndexedMaps keyed on basic block pointers.
+struct MBB2NumberFunctor :
+ public std::unary_function<const MachineBasicBlock*, unsigned> {
+ unsigned operator()(const MachineBasicBlock *MBB) const {
+ return MBB->getNumber();
+ }
+};
+
+//===--------------------------------------------------------------------===//
+// GraphTraits specializations for machine basic block graphs (machine-CFGs)
+//===--------------------------------------------------------------------===//
+
+// Provide specializations of GraphTraits to be able to treat a
+// MachineFunction as a graph of MachineBasicBlocks...
+//
+
+template <> struct GraphTraits<MachineBasicBlock *> {
+ typedef MachineBasicBlock NodeType;
+ typedef MachineBasicBlock::succ_iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(MachineBasicBlock *BB) { return BB; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->succ_begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->succ_end();
+ }
+};
+
+template <> struct GraphTraits<const MachineBasicBlock *> {
+ typedef const MachineBasicBlock NodeType;
+ typedef MachineBasicBlock::const_succ_iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(const MachineBasicBlock *BB) { return BB; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->succ_begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->succ_end();
+ }
+};
+
+// Provide specializations of GraphTraits to be able to treat a
+// MachineFunction as a graph of MachineBasicBlocks... and to walk it
+// in inverse order. Inverse order for a function is considered
+// to be when traversing the predecessor edges of a MBB
+// instead of the successor edges.
+//
+template <> struct GraphTraits<Inverse<MachineBasicBlock*> > {
+ typedef MachineBasicBlock NodeType;
+ typedef MachineBasicBlock::pred_iterator ChildIteratorType;
+ static NodeType *getEntryNode(Inverse<MachineBasicBlock *> G) {
+ return G.Graph;
+ }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->pred_begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->pred_end();
+ }
+};
+
+template <> struct GraphTraits<Inverse<const MachineBasicBlock*> > {
+ typedef const MachineBasicBlock NodeType;
+ typedef MachineBasicBlock::const_pred_iterator ChildIteratorType;
+ static NodeType *getEntryNode(Inverse<const MachineBasicBlock*> G) {
+ return G.Graph;
+ }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->pred_begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->pred_end();
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineBlockFrequencyInfo.h b/include/llvm/CodeGen/MachineBlockFrequencyInfo.h
new file mode 100644
index 00000000000..a9c7bf7dbc6
--- /dev/null
+++ b/include/llvm/CodeGen/MachineBlockFrequencyInfo.h
@@ -0,0 +1,56 @@
+//====----- MachineBlockFrequencyInfo.h - MachineBlock Frequency Analysis ----====//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Loops should be simplified before this analysis.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEBLOCKFREQUENCYINFO_H
+#define LLVM_CODEGEN_MACHINEBLOCKFREQUENCYINFO_H
+
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/Support/BlockFrequency.h"
+#include <climits>
+
+namespace llvm {
+
+class MachineBasicBlock;
+class MachineBranchProbabilityInfo;
+template<class BlockT, class FunctionT, class BranchProbInfoT>
+class BlockFrequencyImpl;
+
+/// MachineBlockFrequencyInfo pass uses BlockFrequencyImpl implementation to estimate
+/// machine basic block frequencies.
+class MachineBlockFrequencyInfo : public MachineFunctionPass {
+
+ BlockFrequencyImpl<MachineBasicBlock, MachineFunction,
+ MachineBranchProbabilityInfo> *MBFI;
+
+public:
+ static char ID;
+
+ MachineBlockFrequencyInfo();
+
+ ~MachineBlockFrequencyInfo();
+
+ void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ bool runOnMachineFunction(MachineFunction &F);
+
+ /// getblockFreq - Return block frequency. Return 0 if we don't have the
+ /// information. Please note that initial frequency is equal to 1024. It means
+ /// that we should not rely on the value itself, but only on the comparison to
+ /// the other block frequencies. We do this to avoid using of floating points.
+ ///
+ BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const;
+};
+
+}
+
+#endif
diff --git a/include/llvm/CodeGen/MachineBranchProbabilityInfo.h b/include/llvm/CodeGen/MachineBranchProbabilityInfo.h
new file mode 100644
index 00000000000..12189ceb7f1
--- /dev/null
+++ b/include/llvm/CodeGen/MachineBranchProbabilityInfo.h
@@ -0,0 +1,89 @@
+
+//==- MachineBranchProbabilityInfo.h - Machine Branch Probability Analysis -==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This pass is used to evaluate branch probabilties on machine basic blocks.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEBRANCHPROBABILITYINFO_H
+#define LLVM_CODEGEN_MACHINEBRANCHPROBABILITYINFO_H
+
+#include "llvm/Pass.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/Support/BranchProbability.h"
+#include <climits>
+
+namespace llvm {
+
+class MachineBranchProbabilityInfo : public ImmutablePass {
+ virtual void anchor();
+
+ // Default weight value. Used when we don't have information about the edge.
+ // TODO: DEFAULT_WEIGHT makes sense during static predication, when none of
+ // the successors have a weight yet. But it doesn't make sense when providing
+ // weight to an edge that may have siblings with non-zero weights. This can
+ // be handled various ways, but it's probably fine for an edge with unknown
+ // weight to just "inherit" the non-zero weight of an adjacent successor.
+ static const uint32_t DEFAULT_WEIGHT = 16;
+
+public:
+ static char ID;
+
+ MachineBranchProbabilityInfo() : ImmutablePass(ID) {
+ PassRegistry &Registry = *PassRegistry::getPassRegistry();
+ initializeMachineBranchProbabilityInfoPass(Registry);
+ }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const {
+ AU.setPreservesAll();
+ }
+
+ // Return edge weight. If we don't have any informations about it - return
+ // DEFAULT_WEIGHT.
+ uint32_t getEdgeWeight(const MachineBasicBlock *Src,
+ const MachineBasicBlock *Dst) const;
+
+ // Same thing, but using a const_succ_iterator from Src. This is faster when
+ // the iterator is already available.
+ uint32_t getEdgeWeight(const MachineBasicBlock *Src,
+ MachineBasicBlock::const_succ_iterator Dst) const;
+
+ // Get sum of the block successors' weights, potentially scaling them to fit
+ // within 32-bits. If scaling is required, sets Scale based on the necessary
+ // adjustment. Any edge weights used with the sum should be divided by Scale.
+ uint32_t getSumForBlock(const MachineBasicBlock *MBB, uint32_t &Scale) const;
+
+ // A 'Hot' edge is an edge which probability is >= 80%.
+ bool isEdgeHot(MachineBasicBlock *Src, MachineBasicBlock *Dst) const;
+
+ // Return a hot successor for the block BB or null if there isn't one.
+ // NB: This routine's complexity is linear on the number of successors.
+ MachineBasicBlock *getHotSucc(MachineBasicBlock *MBB) const;
+
+ // Return a probability as a fraction between 0 (0% probability) and
+ // 1 (100% probability), however the value is never equal to 0, and can be 1
+ // only iff SRC block has only one successor.
+ // NB: This routine's complexity is linear on the number of successors of
+ // Src. Querying sequentially for each successor's probability is a quadratic
+ // query pattern.
+ BranchProbability getEdgeProbability(MachineBasicBlock *Src,
+ MachineBasicBlock *Dst) const;
+
+ // Print value between 0 (0% probability) and 1 (100% probability),
+ // however the value is never equal to 0, and can be 1 only iff SRC block
+ // has only one successor.
+ raw_ostream &printEdgeProbability(raw_ostream &OS, MachineBasicBlock *Src,
+ MachineBasicBlock *Dst) const;
+};
+
+}
+
+
+#endif
diff --git a/include/llvm/CodeGen/MachineCodeEmitter.h b/include/llvm/CodeGen/MachineCodeEmitter.h
new file mode 100644
index 00000000000..86e8f27877e
--- /dev/null
+++ b/include/llvm/CodeGen/MachineCodeEmitter.h
@@ -0,0 +1,335 @@
+//===-- llvm/CodeGen/MachineCodeEmitter.h - Code emission -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines an abstract interface that is used by the machine code
+// emission framework to output the code. This allows machine code emission to
+// be separated from concerns such as resolution of call targets, and where the
+// machine code will be written (memory or disk, f.e.).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINECODEEMITTER_H
+#define LLVM_CODEGEN_MACHINECODEEMITTER_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/DebugLoc.h"
+
+#include <string>
+
+namespace llvm {
+
+class MachineBasicBlock;
+class MachineConstantPool;
+class MachineJumpTableInfo;
+class MachineFunction;
+class MachineModuleInfo;
+class MachineRelocation;
+class Value;
+class GlobalValue;
+class Function;
+class MCSymbol;
+
+/// MachineCodeEmitter - This class defines two sorts of methods: those for
+/// emitting the actual bytes of machine code, and those for emitting auxiliary
+/// structures, such as jump tables, relocations, etc.
+///
+/// Emission of machine code is complicated by the fact that we don't (in
+/// general) know the size of the machine code that we're about to emit before
+/// we emit it. As such, we preallocate a certain amount of memory, and set the
+/// BufferBegin/BufferEnd pointers to the start and end of the buffer. As we
+/// emit machine instructions, we advance the CurBufferPtr to indicate the
+/// location of the next byte to emit. In the case of a buffer overflow (we
+/// need to emit more machine code than we have allocated space for), the
+/// CurBufferPtr will saturate to BufferEnd and ignore stores. Once the entire
+/// function has been emitted, the overflow condition is checked, and if it has
+/// occurred, more memory is allocated, and we reemit the code into it.
+///
+class MachineCodeEmitter {
+ virtual void anchor();
+protected:
+ /// BufferBegin/BufferEnd - Pointers to the start and end of the memory
+ /// allocated for this code buffer.
+ uint8_t *BufferBegin, *BufferEnd;
+ /// CurBufferPtr - Pointer to the next byte of memory to fill when emitting
+ /// code. This is guaranteed to be in the range [BufferBegin,BufferEnd]. If
+ /// this pointer is at BufferEnd, it will never move due to code emission, and
+ /// all code emission requests will be ignored (this is the buffer overflow
+ /// condition).
+ uint8_t *CurBufferPtr;
+
+public:
+ virtual ~MachineCodeEmitter() {}
+
+ /// startFunction - This callback is invoked when the specified function is
+ /// about to be code generated. This initializes the BufferBegin/End/Ptr
+ /// fields.
+ ///
+ virtual void startFunction(MachineFunction &F) = 0;
+
+ /// finishFunction - This callback is invoked when the specified function has
+ /// finished code generation. If a buffer overflow has occurred, this method
+ /// returns true (the callee is required to try again), otherwise it returns
+ /// false.
+ ///
+ virtual bool finishFunction(MachineFunction &F) = 0;
+
+ /// emitByte - This callback is invoked when a byte needs to be written to the
+ /// output stream.
+ ///
+ void emitByte(uint8_t B) {
+ if (CurBufferPtr != BufferEnd)
+ *CurBufferPtr++ = B;
+ }
+
+ /// emitWordLE - This callback is invoked when a 32-bit word needs to be
+ /// written to the output stream in little-endian format.
+ ///
+ void emitWordLE(uint32_t W) {
+ if (4 <= BufferEnd-CurBufferPtr) {
+ emitWordLEInto(CurBufferPtr, W);
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitWordLEInto - This callback is invoked when a 32-bit word needs to be
+ /// written to an arbitrary buffer in little-endian format. Buf must have at
+ /// least 4 bytes of available space.
+ ///
+ static void emitWordLEInto(uint8_t *&Buf, uint32_t W) {
+ *Buf++ = (uint8_t)(W >> 0);
+ *Buf++ = (uint8_t)(W >> 8);
+ *Buf++ = (uint8_t)(W >> 16);
+ *Buf++ = (uint8_t)(W >> 24);
+ }
+
+ /// emitWordBE - This callback is invoked when a 32-bit word needs to be
+ /// written to the output stream in big-endian format.
+ ///
+ void emitWordBE(uint32_t W) {
+ if (4 <= BufferEnd-CurBufferPtr) {
+ *CurBufferPtr++ = (uint8_t)(W >> 24);
+ *CurBufferPtr++ = (uint8_t)(W >> 16);
+ *CurBufferPtr++ = (uint8_t)(W >> 8);
+ *CurBufferPtr++ = (uint8_t)(W >> 0);
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitDWordLE - This callback is invoked when a 64-bit word needs to be
+ /// written to the output stream in little-endian format.
+ ///
+ void emitDWordLE(uint64_t W) {
+ if (8 <= BufferEnd-CurBufferPtr) {
+ *CurBufferPtr++ = (uint8_t)(W >> 0);
+ *CurBufferPtr++ = (uint8_t)(W >> 8);
+ *CurBufferPtr++ = (uint8_t)(W >> 16);
+ *CurBufferPtr++ = (uint8_t)(W >> 24);
+ *CurBufferPtr++ = (uint8_t)(W >> 32);
+ *CurBufferPtr++ = (uint8_t)(W >> 40);
+ *CurBufferPtr++ = (uint8_t)(W >> 48);
+ *CurBufferPtr++ = (uint8_t)(W >> 56);
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitDWordBE - This callback is invoked when a 64-bit word needs to be
+ /// written to the output stream in big-endian format.
+ ///
+ void emitDWordBE(uint64_t W) {
+ if (8 <= BufferEnd-CurBufferPtr) {
+ *CurBufferPtr++ = (uint8_t)(W >> 56);
+ *CurBufferPtr++ = (uint8_t)(W >> 48);
+ *CurBufferPtr++ = (uint8_t)(W >> 40);
+ *CurBufferPtr++ = (uint8_t)(W >> 32);
+ *CurBufferPtr++ = (uint8_t)(W >> 24);
+ *CurBufferPtr++ = (uint8_t)(W >> 16);
+ *CurBufferPtr++ = (uint8_t)(W >> 8);
+ *CurBufferPtr++ = (uint8_t)(W >> 0);
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitAlignment - Move the CurBufferPtr pointer up to the specified
+ /// alignment (saturated to BufferEnd of course).
+ void emitAlignment(unsigned Alignment) {
+ if (Alignment == 0) Alignment = 1;
+
+ if(Alignment <= (uintptr_t)(BufferEnd-CurBufferPtr)) {
+ // Move the current buffer ptr up to the specified alignment.
+ CurBufferPtr =
+ (uint8_t*)(((uintptr_t)CurBufferPtr+Alignment-1) &
+ ~(uintptr_t)(Alignment-1));
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+
+ /// emitULEB128Bytes - This callback is invoked when a ULEB128 needs to be
+ /// written to the output stream.
+ void emitULEB128Bytes(uint64_t Value) {
+ do {
+ uint8_t Byte = Value & 0x7f;
+ Value >>= 7;
+ if (Value) Byte |= 0x80;
+ emitByte(Byte);
+ } while (Value);
+ }
+
+ /// emitSLEB128Bytes - This callback is invoked when a SLEB128 needs to be
+ /// written to the output stream.
+ void emitSLEB128Bytes(uint64_t Value) {
+ uint64_t Sign = Value >> (8 * sizeof(Value) - 1);
+ bool IsMore;
+
+ do {
+ uint8_t Byte = Value & 0x7f;
+ Value >>= 7;
+ IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
+ if (IsMore) Byte |= 0x80;
+ emitByte(Byte);
+ } while (IsMore);
+ }
+
+ /// emitString - This callback is invoked when a String needs to be
+ /// written to the output stream.
+ void emitString(const std::string &String) {
+ for (unsigned i = 0, N = static_cast<unsigned>(String.size());
+ i < N; ++i) {
+ uint8_t C = String[i];
+ emitByte(C);
+ }
+ emitByte(0);
+ }
+
+ /// emitInt32 - Emit a int32 directive.
+ void emitInt32(int32_t Value) {
+ if (4 <= BufferEnd-CurBufferPtr) {
+ *((uint32_t*)CurBufferPtr) = Value;
+ CurBufferPtr += 4;
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitInt64 - Emit a int64 directive.
+ void emitInt64(uint64_t Value) {
+ if (8 <= BufferEnd-CurBufferPtr) {
+ *((uint64_t*)CurBufferPtr) = Value;
+ CurBufferPtr += 8;
+ } else {
+ CurBufferPtr = BufferEnd;
+ }
+ }
+
+ /// emitInt32At - Emit the Int32 Value in Addr.
+ void emitInt32At(uintptr_t *Addr, uintptr_t Value) {
+ if (Addr >= (uintptr_t*)BufferBegin && Addr < (uintptr_t*)BufferEnd)
+ (*(uint32_t*)Addr) = (uint32_t)Value;
+ }
+
+ /// emitInt64At - Emit the Int64 Value in Addr.
+ void emitInt64At(uintptr_t *Addr, uintptr_t Value) {
+ if (Addr >= (uintptr_t*)BufferBegin && Addr < (uintptr_t*)BufferEnd)
+ (*(uint64_t*)Addr) = (uint64_t)Value;
+ }
+
+ /// processDebugLoc - Records debug location information about a
+ /// MachineInstruction. This is called before emitting any bytes associated
+ /// with the instruction. Even if successive instructions have the same debug
+ /// location, this method will be called for each one.
+ virtual void processDebugLoc(DebugLoc DL, bool BeforePrintintInsn) {}
+
+ /// emitLabel - Emits a label
+ virtual void emitLabel(MCSymbol *Label) = 0;
+
+ /// allocateSpace - Allocate a block of space in the current output buffer,
+ /// returning null (and setting conditions to indicate buffer overflow) on
+ /// failure. Alignment is the alignment in bytes of the buffer desired.
+ virtual void *allocateSpace(uintptr_t Size, unsigned Alignment) {
+ emitAlignment(Alignment);
+ void *Result;
+
+ // Check for buffer overflow.
+ if (Size >= (uintptr_t)(BufferEnd-CurBufferPtr)) {
+ CurBufferPtr = BufferEnd;
+ Result = 0;
+ } else {
+ // Allocate the space.
+ Result = CurBufferPtr;
+ CurBufferPtr += Size;
+ }
+
+ return Result;
+ }
+
+ /// StartMachineBasicBlock - This should be called by the target when a new
+ /// basic block is about to be emitted. This way the MCE knows where the
+ /// start of the block is, and can implement getMachineBasicBlockAddress.
+ virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) = 0;
+
+ /// getCurrentPCValue - This returns the address that the next emitted byte
+ /// will be output to.
+ ///
+ virtual uintptr_t getCurrentPCValue() const {
+ return (uintptr_t)CurBufferPtr;
+ }
+
+ /// getCurrentPCOffset - Return the offset from the start of the emitted
+ /// buffer that we are currently writing to.
+ virtual uintptr_t getCurrentPCOffset() const {
+ return CurBufferPtr-BufferBegin;
+ }
+
+ /// earlyResolveAddresses - True if the code emitter can use symbol addresses
+ /// during code emission time. The JIT is capable of doing this because it
+ /// creates jump tables or constant pools in memory on the fly while the
+ /// object code emitters rely on a linker to have real addresses and should
+ /// use relocations instead.
+ virtual bool earlyResolveAddresses() const = 0;
+
+ /// addRelocation - Whenever a relocatable address is needed, it should be
+ /// noted with this interface.
+ virtual void addRelocation(const MachineRelocation &MR) = 0;
+
+ /// FIXME: These should all be handled with relocations!
+
+ /// getConstantPoolEntryAddress - Return the address of the 'Index' entry in
+ /// the constant pool that was last emitted with the emitConstantPool method.
+ ///
+ virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const = 0;
+
+ /// getJumpTableEntryAddress - Return the address of the jump table with index
+ /// 'Index' in the function that last called initJumpTableInfo.
+ ///
+ virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const = 0;
+
+ /// getMachineBasicBlockAddress - Return the address of the specified
+ /// MachineBasicBlock, only usable after the label for the MBB has been
+ /// emitted.
+ ///
+ virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const= 0;
+
+ /// getLabelAddress - Return the address of the specified Label, only usable
+ /// after the LabelID has been emitted.
+ ///
+ virtual uintptr_t getLabelAddress(MCSymbol *Label) const = 0;
+
+ /// Specifies the MachineModuleInfo object. This is used for exception handling
+ /// purposes.
+ virtual void setModuleInfo(MachineModuleInfo* Info) = 0;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineCodeInfo.h b/include/llvm/CodeGen/MachineCodeInfo.h
new file mode 100644
index 00000000000..c5c0c445045
--- /dev/null
+++ b/include/llvm/CodeGen/MachineCodeInfo.h
@@ -0,0 +1,53 @@
+//===-- MachineCodeInfo.h - Class used to report JIT info -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines MachineCodeInfo, a class used by the JIT ExecutionEngine
+// to report information about the generated machine code.
+//
+// See JIT::runJITOnFunction for usage.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef EE_MACHINE_CODE_INFO_H
+#define EE_MACHINE_CODE_INFO_H
+
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+class MachineCodeInfo {
+private:
+ size_t Size; // Number of bytes in memory used
+ void *Address; // The address of the function in memory
+
+public:
+ MachineCodeInfo() : Size(0), Address(0) {}
+
+ void setSize(size_t s) {
+ Size = s;
+ }
+
+ void setAddress(void *a) {
+ Address = a;
+ }
+
+ size_t size() const {
+ return Size;
+ }
+
+ void *address() const {
+ return Address;
+ }
+
+};
+
+}
+
+#endif
+
diff --git a/include/llvm/CodeGen/MachineConstantPool.h b/include/llvm/CodeGen/MachineConstantPool.h
new file mode 100644
index 00000000000..d6d65a24def
--- /dev/null
+++ b/include/llvm/CodeGen/MachineConstantPool.h
@@ -0,0 +1,174 @@
+//===-- CodeGen/MachineConstantPool.h - Abstract Constant Pool --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+/// @file
+/// This file declares the MachineConstantPool class which is an abstract
+/// constant pool to keep track of constants referenced by a function.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINECONSTANTPOOL_H
+#define LLVM_CODEGEN_MACHINECONSTANTPOOL_H
+
+#include "llvm/ADT/DenseSet.h"
+#include <cassert>
+#include <climits>
+#include <vector>
+
+namespace llvm {
+
+class Constant;
+class FoldingSetNodeID;
+class TargetData;
+class TargetMachine;
+class Type;
+class MachineConstantPool;
+class raw_ostream;
+
+/// Abstract base class for all machine specific constantpool value subclasses.
+///
+class MachineConstantPoolValue {
+ virtual void anchor();
+ Type *Ty;
+
+public:
+ explicit MachineConstantPoolValue(Type *ty) : Ty(ty) {}
+ virtual ~MachineConstantPoolValue() {}
+
+ /// getType - get type of this MachineConstantPoolValue.
+ ///
+ Type *getType() const { return Ty; }
+
+
+ /// getRelocationInfo - This method classifies the entry according to
+ /// whether or not it may generate a relocation entry. This must be
+ /// conservative, so if it might codegen to a relocatable entry, it should say
+ /// so. The return values are the same as Constant::getRelocationInfo().
+ virtual unsigned getRelocationInfo() const = 0;
+
+ virtual int getExistingMachineCPValue(MachineConstantPool *CP,
+ unsigned Alignment) = 0;
+
+ virtual void addSelectionDAGCSEId(FoldingSetNodeID &ID) = 0;
+
+ /// print - Implement operator<<
+ virtual void print(raw_ostream &O) const = 0;
+};
+
+inline raw_ostream &operator<<(raw_ostream &OS,
+ const MachineConstantPoolValue &V) {
+ V.print(OS);
+ return OS;
+}
+
+
+/// This class is a data container for one entry in a MachineConstantPool.
+/// It contains a pointer to the value and an offset from the start of
+/// the constant pool.
+/// @brief An entry in a MachineConstantPool
+class MachineConstantPoolEntry {
+public:
+ /// The constant itself.
+ union {
+ const Constant *ConstVal;
+ MachineConstantPoolValue *MachineCPVal;
+ } Val;
+
+ /// The required alignment for this entry. The top bit is set when Val is
+ /// a target specific MachineConstantPoolValue.
+ unsigned Alignment;
+
+ MachineConstantPoolEntry(const Constant *V, unsigned A)
+ : Alignment(A) {
+ Val.ConstVal = V;
+ }
+ MachineConstantPoolEntry(MachineConstantPoolValue *V, unsigned A)
+ : Alignment(A) {
+ Val.MachineCPVal = V;
+ Alignment |= 1U << (sizeof(unsigned)*CHAR_BIT-1);
+ }
+
+ /// isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry
+ /// is indeed a target specific constantpool entry, not a wrapper over a
+ /// Constant.
+ bool isMachineConstantPoolEntry() const {
+ return (int)Alignment < 0;
+ }
+
+ int getAlignment() const {
+ return Alignment & ~(1 << (sizeof(unsigned)*CHAR_BIT-1));
+ }
+
+ Type *getType() const;
+
+ /// getRelocationInfo - This method classifies the entry according to
+ /// whether or not it may generate a relocation entry. This must be
+ /// conservative, so if it might codegen to a relocatable entry, it should say
+ /// so. The return values are:
+ ///
+ /// 0: This constant pool entry is guaranteed to never have a relocation
+ /// applied to it (because it holds a simple constant like '4').
+ /// 1: This entry has relocations, but the entries are guaranteed to be
+ /// resolvable by the static linker, so the dynamic linker will never see
+ /// them.
+ /// 2: This entry may have arbitrary relocations.
+ unsigned getRelocationInfo() const;
+};
+
+/// The MachineConstantPool class keeps track of constants referenced by a
+/// function which must be spilled to memory. This is used for constants which
+/// are unable to be used directly as operands to instructions, which typically
+/// include floating point and large integer constants.
+///
+/// Instructions reference the address of these constant pool constants through
+/// the use of MO_ConstantPoolIndex values. When emitting assembly or machine
+/// code, these virtual address references are converted to refer to the
+/// address of the function constant pool values.
+/// @brief The machine constant pool.
+class MachineConstantPool {
+ const TargetData *TD; ///< The machine's TargetData.
+ unsigned PoolAlignment; ///< The alignment for the pool.
+ std::vector<MachineConstantPoolEntry> Constants; ///< The pool of constants.
+ /// MachineConstantPoolValues that use an existing MachineConstantPoolEntry.
+ DenseSet<MachineConstantPoolValue*> MachineCPVsSharingEntries;
+public:
+ /// @brief The only constructor.
+ explicit MachineConstantPool(const TargetData *td)
+ : TD(td), PoolAlignment(1) {}
+ ~MachineConstantPool();
+
+ /// getConstantPoolAlignment - Return the alignment required by
+ /// the whole constant pool, of which the first element must be aligned.
+ unsigned getConstantPoolAlignment() const { return PoolAlignment; }
+
+ /// getConstantPoolIndex - Create a new entry in the constant pool or return
+ /// an existing one. User must specify the minimum required alignment for
+ /// the object.
+ unsigned getConstantPoolIndex(const Constant *C, unsigned Alignment);
+ unsigned getConstantPoolIndex(MachineConstantPoolValue *V,unsigned Alignment);
+
+ /// isEmpty - Return true if this constant pool contains no constants.
+ bool isEmpty() const { return Constants.empty(); }
+
+ const std::vector<MachineConstantPoolEntry> &getConstants() const {
+ return Constants;
+ }
+
+ /// print - Used by the MachineFunction printer to print information about
+ /// constant pool objects. Implemented in MachineFunction.cpp
+ ///
+ void print(raw_ostream &OS) const;
+
+ /// dump - Call print(cerr) to be called from the debugger.
+ void dump() const;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineDominators.h b/include/llvm/CodeGen/MachineDominators.h
new file mode 100644
index 00000000000..82a4ac821b6
--- /dev/null
+++ b/include/llvm/CodeGen/MachineDominators.h
@@ -0,0 +1,203 @@
+//=- llvm/CodeGen/MachineDominators.h - Machine Dom Calculation --*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines classes mirroring those in llvm/Analysis/Dominators.h,
+// but for target-specific code rather than target-independent IR.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEDOMINATORS_H
+#define LLVM_CODEGEN_MACHINEDOMINATORS_H
+
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/Analysis/Dominators.h"
+#include "llvm/Analysis/DominatorInternals.h"
+
+namespace llvm {
+
+template<>
+inline void DominatorTreeBase<MachineBasicBlock>::addRoot(MachineBasicBlock* MBB) {
+ this->Roots.push_back(MBB);
+}
+
+EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
+EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>);
+
+typedef DomTreeNodeBase<MachineBasicBlock> MachineDomTreeNode;
+
+//===-------------------------------------
+/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
+/// compute a normal dominator tree.
+///
+class MachineDominatorTree : public MachineFunctionPass {
+public:
+ static char ID; // Pass ID, replacement for typeid
+ DominatorTreeBase<MachineBasicBlock>* DT;
+
+ MachineDominatorTree();
+
+ ~MachineDominatorTree();
+
+ DominatorTreeBase<MachineBasicBlock>& getBase() { return *DT; }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ /// getRoots - Return the root blocks of the current CFG. This may include
+ /// multiple blocks if we are computing post dominators. For forward
+ /// dominators, this will always be a single block (the entry node).
+ ///
+ inline const std::vector<MachineBasicBlock*> &getRoots() const {
+ return DT->getRoots();
+ }
+
+ inline MachineBasicBlock *getRoot() const {
+ return DT->getRoot();
+ }
+
+ inline MachineDomTreeNode *getRootNode() const {
+ return DT->getRootNode();
+ }
+
+ virtual bool runOnMachineFunction(MachineFunction &F);
+
+ inline bool dominates(MachineDomTreeNode* A, MachineDomTreeNode* B) const {
+ return DT->dominates(A, B);
+ }
+
+ inline bool dominates(MachineBasicBlock* A, MachineBasicBlock* B) const {
+ return DT->dominates(A, B);
+ }
+
+ // dominates - Return true if A dominates B. This performs the
+ // special checks necessary if A and B are in the same basic block.
+ bool dominates(MachineInstr *A, MachineInstr *B) const {
+ MachineBasicBlock *BBA = A->getParent(), *BBB = B->getParent();
+ if (BBA != BBB) return DT->dominates(BBA, BBB);
+
+ // Loop through the basic block until we find A or B.
+ MachineBasicBlock::iterator I = BBA->begin();
+ for (; &*I != A && &*I != B; ++I)
+ /*empty*/ ;
+
+ //if(!DT.IsPostDominators) {
+ // A dominates B if it is found first in the basic block.
+ return &*I == A;
+ //} else {
+ // // A post-dominates B if B is found first in the basic block.
+ // return &*I == B;
+ //}
+ }
+
+ inline bool properlyDominates(const MachineDomTreeNode* A,
+ MachineDomTreeNode* B) const {
+ return DT->properlyDominates(A, B);
+ }
+
+ inline bool properlyDominates(MachineBasicBlock* A,
+ MachineBasicBlock* B) const {
+ return DT->properlyDominates(A, B);
+ }
+
+ /// findNearestCommonDominator - Find nearest common dominator basic block
+ /// for basic block A and B. If there is no such block then return NULL.
+ inline MachineBasicBlock *findNearestCommonDominator(MachineBasicBlock *A,
+ MachineBasicBlock *B) {
+ return DT->findNearestCommonDominator(A, B);
+ }
+
+ inline MachineDomTreeNode *operator[](MachineBasicBlock *BB) const {
+ return DT->getNode(BB);
+ }
+
+ /// getNode - return the (Post)DominatorTree node for the specified basic
+ /// block. This is the same as using operator[] on this class.
+ ///
+ inline MachineDomTreeNode *getNode(MachineBasicBlock *BB) const {
+ return DT->getNode(BB);
+ }
+
+ /// addNewBlock - Add a new node to the dominator tree information. This
+ /// creates a new node as a child of DomBB dominator node,linking it into
+ /// the children list of the immediate dominator.
+ inline MachineDomTreeNode *addNewBlock(MachineBasicBlock *BB,
+ MachineBasicBlock *DomBB) {
+ return DT->addNewBlock(BB, DomBB);
+ }
+
+ /// changeImmediateDominator - This method is used to update the dominator
+ /// tree information when a node's immediate dominator changes.
+ ///
+ inline void changeImmediateDominator(MachineBasicBlock *N,
+ MachineBasicBlock* NewIDom) {
+ DT->changeImmediateDominator(N, NewIDom);
+ }
+
+ inline void changeImmediateDominator(MachineDomTreeNode *N,
+ MachineDomTreeNode* NewIDom) {
+ DT->changeImmediateDominator(N, NewIDom);
+ }
+
+ /// eraseNode - Removes a node from the dominator tree. Block must not
+ /// dominate any other blocks. Removes node from its immediate dominator's
+ /// children list. Deletes dominator node associated with basic block BB.
+ inline void eraseNode(MachineBasicBlock *BB) {
+ DT->eraseNode(BB);
+ }
+
+ /// splitBlock - BB is split and now it has one successor. Update dominator
+ /// tree to reflect this change.
+ inline void splitBlock(MachineBasicBlock* NewBB) {
+ DT->splitBlock(NewBB);
+ }
+
+ /// isReachableFromEntry - Return true if A is dominated by the entry
+ /// block of the function containing it.
+ bool isReachableFromEntry(MachineBasicBlock *A) {
+ return DT->isReachableFromEntry(A);
+ }
+
+ virtual void releaseMemory();
+
+ virtual void print(raw_ostream &OS, const Module*) const;
+};
+
+//===-------------------------------------
+/// DominatorTree GraphTraits specialization so the DominatorTree can be
+/// iterable by generic graph iterators.
+///
+
+template<class T> struct GraphTraits;
+
+template <> struct GraphTraits<MachineDomTreeNode *> {
+ typedef MachineDomTreeNode NodeType;
+ typedef NodeType::iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(NodeType *N) {
+ return N;
+ }
+ static inline ChildIteratorType child_begin(NodeType* N) {
+ return N->begin();
+ }
+ static inline ChildIteratorType child_end(NodeType* N) {
+ return N->end();
+ }
+};
+
+template <> struct GraphTraits<MachineDominatorTree*>
+ : public GraphTraits<MachineDomTreeNode *> {
+ static NodeType *getEntryNode(MachineDominatorTree *DT) {
+ return DT->getRootNode();
+ }
+};
+
+}
+
+#endif
diff --git a/include/llvm/CodeGen/MachineFrameInfo.h b/include/llvm/CodeGen/MachineFrameInfo.h
new file mode 100644
index 00000000000..3c07cebfcc6
--- /dev/null
+++ b/include/llvm/CodeGen/MachineFrameInfo.h
@@ -0,0 +1,577 @@
+//===-- CodeGen/MachineFrameInfo.h - Abstract Stack Frame Rep. --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The file defines the MachineFrameInfo class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEFRAMEINFO_H
+#define LLVM_CODEGEN_MACHINEFRAMEINFO_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+#include <vector>
+
+namespace llvm {
+class raw_ostream;
+class TargetData;
+class TargetRegisterClass;
+class Type;
+class MachineFunction;
+class MachineBasicBlock;
+class TargetFrameLowering;
+class BitVector;
+class Value;
+
+/// The CalleeSavedInfo class tracks the information need to locate where a
+/// callee saved register is in the current frame.
+class CalleeSavedInfo {
+ unsigned Reg;
+ int FrameIdx;
+
+public:
+ explicit CalleeSavedInfo(unsigned R, int FI = 0)
+ : Reg(R), FrameIdx(FI) {}
+
+ // Accessors.
+ unsigned getReg() const { return Reg; }
+ int getFrameIdx() const { return FrameIdx; }
+ void setFrameIdx(int FI) { FrameIdx = FI; }
+};
+
+/// The MachineFrameInfo class represents an abstract stack frame until
+/// prolog/epilog code is inserted. This class is key to allowing stack frame
+/// representation optimizations, such as frame pointer elimination. It also
+/// allows more mundane (but still important) optimizations, such as reordering
+/// of abstract objects on the stack frame.
+///
+/// To support this, the class assigns unique integer identifiers to stack
+/// objects requested clients. These identifiers are negative integers for
+/// fixed stack objects (such as arguments passed on the stack) or nonnegative
+/// for objects that may be reordered. Instructions which refer to stack
+/// objects use a special MO_FrameIndex operand to represent these frame
+/// indexes.
+///
+/// Because this class keeps track of all references to the stack frame, it
+/// knows when a variable sized object is allocated on the stack. This is the
+/// sole condition which prevents frame pointer elimination, which is an
+/// important optimization on register-poor architectures. Because original
+/// variable sized alloca's in the source program are the only source of
+/// variable sized stack objects, it is safe to decide whether there will be
+/// any variable sized objects before all stack objects are known (for
+/// example, register allocator spill code never needs variable sized
+/// objects).
+///
+/// When prolog/epilog code emission is performed, the final stack frame is
+/// built and the machine instructions are modified to refer to the actual
+/// stack offsets of the object, eliminating all MO_FrameIndex operands from
+/// the program.
+///
+/// @brief Abstract Stack Frame Information
+class MachineFrameInfo {
+
+ // StackObject - Represent a single object allocated on the stack.
+ struct StackObject {
+ // SPOffset - The offset of this object from the stack pointer on entry to
+ // the function. This field has no meaning for a variable sized element.
+ int64_t SPOffset;
+
+ // The size of this object on the stack. 0 means a variable sized object,
+ // ~0ULL means a dead object.
+ uint64_t Size;
+
+ // Alignment - The required alignment of this stack slot.
+ unsigned Alignment;
+
+ // isImmutable - If true, the value of the stack object is set before
+ // entering the function and is not modified inside the function. By
+ // default, fixed objects are immutable unless marked otherwise.
+ bool isImmutable;
+
+ // isSpillSlot - If true the stack object is used as spill slot. It
+ // cannot alias any other memory objects.
+ bool isSpillSlot;
+
+ // MayNeedSP - If true the stack object triggered the creation of the stack
+ // protector. We should allocate this object right after the stack
+ // protector.
+ bool MayNeedSP;
+
+ /// Alloca - If this stack object is originated from an Alloca instruction
+ /// this value saves the original IR allocation. Can be NULL.
+ const Value *Alloca;
+
+ // PreAllocated - If true, the object was mapped into the local frame
+ // block and doesn't need additional handling for allocation beyond that.
+ bool PreAllocated;
+
+ StackObject(uint64_t Sz, unsigned Al, int64_t SP, bool IM,
+ bool isSS, bool NSP, const Value *Val)
+ : SPOffset(SP), Size(Sz), Alignment(Al), isImmutable(IM),
+ isSpillSlot(isSS), MayNeedSP(NSP), Alloca(Val), PreAllocated(false) {}
+ };
+
+ /// Objects - The list of stack objects allocated...
+ ///
+ std::vector<StackObject> Objects;
+
+ /// NumFixedObjects - This contains the number of fixed objects contained on
+ /// the stack. Because fixed objects are stored at a negative index in the
+ /// Objects list, this is also the index to the 0th object in the list.
+ ///
+ unsigned NumFixedObjects;
+
+ /// HasVarSizedObjects - This boolean keeps track of whether any variable
+ /// sized objects have been allocated yet.
+ ///
+ bool HasVarSizedObjects;
+
+ /// FrameAddressTaken - This boolean keeps track of whether there is a call
+ /// to builtin \@llvm.frameaddress.
+ bool FrameAddressTaken;
+
+ /// ReturnAddressTaken - This boolean keeps track of whether there is a call
+ /// to builtin \@llvm.returnaddress.
+ bool ReturnAddressTaken;
+
+ /// StackSize - The prolog/epilog code inserter calculates the final stack
+ /// offsets for all of the fixed size objects, updating the Objects list
+ /// above. It then updates StackSize to contain the number of bytes that need
+ /// to be allocated on entry to the function.
+ ///
+ uint64_t StackSize;
+
+ /// OffsetAdjustment - The amount that a frame offset needs to be adjusted to
+ /// have the actual offset from the stack/frame pointer. The exact usage of
+ /// this is target-dependent, but it is typically used to adjust between
+ /// SP-relative and FP-relative offsets. E.G., if objects are accessed via
+ /// SP then OffsetAdjustment is zero; if FP is used, OffsetAdjustment is set
+ /// to the distance between the initial SP and the value in FP. For many
+ /// targets, this value is only used when generating debug info (via
+ /// TargetRegisterInfo::getFrameIndexOffset); when generating code, the
+ /// corresponding adjustments are performed directly.
+ int OffsetAdjustment;
+
+ /// MaxAlignment - The prolog/epilog code inserter may process objects
+ /// that require greater alignment than the default alignment the target
+ /// provides. To handle this, MaxAlignment is set to the maximum alignment
+ /// needed by the objects on the current frame. If this is greater than the
+ /// native alignment maintained by the compiler, dynamic alignment code will
+ /// be needed.
+ ///
+ unsigned MaxAlignment;
+
+ /// AdjustsStack - Set to true if this function adjusts the stack -- e.g.,
+ /// when calling another function. This is only valid during and after
+ /// prolog/epilog code insertion.
+ bool AdjustsStack;
+
+ /// HasCalls - Set to true if this function has any function calls.
+ bool HasCalls;
+
+ /// StackProtectorIdx - The frame index for the stack protector.
+ int StackProtectorIdx;
+
+ /// FunctionContextIdx - The frame index for the function context. Used for
+ /// SjLj exceptions.
+ int FunctionContextIdx;
+
+ /// MaxCallFrameSize - This contains the size of the largest call frame if the
+ /// target uses frame setup/destroy pseudo instructions (as defined in the
+ /// TargetFrameInfo class). This information is important for frame pointer
+ /// elimination. If is only valid during and after prolog/epilog code
+ /// insertion.
+ ///
+ unsigned MaxCallFrameSize;
+
+ /// CSInfo - The prolog/epilog code inserter fills in this vector with each
+ /// callee saved register saved in the frame. Beyond its use by the prolog/
+ /// epilog code inserter, this data used for debug info and exception
+ /// handling.
+ std::vector<CalleeSavedInfo> CSInfo;
+
+ /// CSIValid - Has CSInfo been set yet?
+ bool CSIValid;
+
+ /// TargetFrameLowering - Target information about frame layout.
+ ///
+ const TargetFrameLowering &TFI;
+
+ /// LocalFrameObjects - References to frame indices which are mapped
+ /// into the local frame allocation block. <FrameIdx, LocalOffset>
+ SmallVector<std::pair<int, int64_t>, 32> LocalFrameObjects;
+
+ /// LocalFrameSize - Size of the pre-allocated local frame block.
+ int64_t LocalFrameSize;
+
+ /// Required alignment of the local object blob, which is the strictest
+ /// alignment of any object in it.
+ unsigned LocalFrameMaxAlign;
+
+ /// Whether the local object blob needs to be allocated together. If not,
+ /// PEI should ignore the isPreAllocated flags on the stack objects and
+ /// just allocate them normally.
+ bool UseLocalStackAllocationBlock;
+
+public:
+ explicit MachineFrameInfo(const TargetFrameLowering &tfi) : TFI(tfi) {
+ StackSize = NumFixedObjects = OffsetAdjustment = MaxAlignment = 0;
+ HasVarSizedObjects = false;
+ FrameAddressTaken = false;
+ ReturnAddressTaken = false;
+ AdjustsStack = false;
+ HasCalls = false;
+ StackProtectorIdx = -1;
+ FunctionContextIdx = -1;
+ MaxCallFrameSize = 0;
+ CSIValid = false;
+ LocalFrameSize = 0;
+ LocalFrameMaxAlign = 0;
+ UseLocalStackAllocationBlock = false;
+ }
+
+ /// hasStackObjects - Return true if there are any stack objects in this
+ /// function.
+ ///
+ bool hasStackObjects() const { return !Objects.empty(); }
+
+ /// hasVarSizedObjects - This method may be called any time after instruction
+ /// selection is complete to determine if the stack frame for this function
+ /// contains any variable sized objects.
+ ///
+ bool hasVarSizedObjects() const { return HasVarSizedObjects; }
+
+ /// getStackProtectorIndex/setStackProtectorIndex - Return the index for the
+ /// stack protector object.
+ ///
+ int getStackProtectorIndex() const { return StackProtectorIdx; }
+ void setStackProtectorIndex(int I) { StackProtectorIdx = I; }
+
+ /// getFunctionContextIndex/setFunctionContextIndex - Return the index for the
+ /// function context object. This object is used for SjLj exceptions.
+ int getFunctionContextIndex() const { return FunctionContextIdx; }
+ void setFunctionContextIndex(int I) { FunctionContextIdx = I; }
+
+ /// isFrameAddressTaken - This method may be called any time after instruction
+ /// selection is complete to determine if there is a call to
+ /// \@llvm.frameaddress in this function.
+ bool isFrameAddressTaken() const { return FrameAddressTaken; }
+ void setFrameAddressIsTaken(bool T) { FrameAddressTaken = T; }
+
+ /// isReturnAddressTaken - This method may be called any time after
+ /// instruction selection is complete to determine if there is a call to
+ /// \@llvm.returnaddress in this function.
+ bool isReturnAddressTaken() const { return ReturnAddressTaken; }
+ void setReturnAddressIsTaken(bool s) { ReturnAddressTaken = s; }
+
+ /// getObjectIndexBegin - Return the minimum frame object index.
+ ///
+ int getObjectIndexBegin() const { return -NumFixedObjects; }
+
+ /// getObjectIndexEnd - Return one past the maximum frame object index.
+ ///
+ int getObjectIndexEnd() const { return (int)Objects.size()-NumFixedObjects; }
+
+ /// getNumFixedObjects - Return the number of fixed objects.
+ unsigned getNumFixedObjects() const { return NumFixedObjects; }
+
+ /// getNumObjects - Return the number of objects.
+ ///
+ unsigned getNumObjects() const { return Objects.size(); }
+
+ /// mapLocalFrameObject - Map a frame index into the local object block
+ void mapLocalFrameObject(int ObjectIndex, int64_t Offset) {
+ LocalFrameObjects.push_back(std::pair<int, int64_t>(ObjectIndex, Offset));
+ Objects[ObjectIndex + NumFixedObjects].PreAllocated = true;
+ }
+
+ /// getLocalFrameObjectMap - Get the local offset mapping for a for an object
+ std::pair<int, int64_t> getLocalFrameObjectMap(int i) {
+ assert (i >= 0 && (unsigned)i < LocalFrameObjects.size() &&
+ "Invalid local object reference!");
+ return LocalFrameObjects[i];
+ }
+
+ /// getLocalFrameObjectCount - Return the number of objects allocated into
+ /// the local object block.
+ int64_t getLocalFrameObjectCount() { return LocalFrameObjects.size(); }
+
+ /// setLocalFrameSize - Set the size of the local object blob.
+ void setLocalFrameSize(int64_t sz) { LocalFrameSize = sz; }
+
+ /// getLocalFrameSize - Get the size of the local object blob.
+ int64_t getLocalFrameSize() const { return LocalFrameSize; }
+
+ /// setLocalFrameMaxAlign - Required alignment of the local object blob,
+ /// which is the strictest alignment of any object in it.
+ void setLocalFrameMaxAlign(unsigned Align) { LocalFrameMaxAlign = Align; }
+
+ /// getLocalFrameMaxAlign - Return the required alignment of the local
+ /// object blob.
+ unsigned getLocalFrameMaxAlign() const { return LocalFrameMaxAlign; }
+
+ /// getUseLocalStackAllocationBlock - Get whether the local allocation blob
+ /// should be allocated together or let PEI allocate the locals in it
+ /// directly.
+ bool getUseLocalStackAllocationBlock() {return UseLocalStackAllocationBlock;}
+
+ /// setUseLocalStackAllocationBlock - Set whether the local allocation blob
+ /// should be allocated together or let PEI allocate the locals in it
+ /// directly.
+ void setUseLocalStackAllocationBlock(bool v) {
+ UseLocalStackAllocationBlock = v;
+ }
+
+ /// isObjectPreAllocated - Return true if the object was pre-allocated into
+ /// the local block.
+ bool isObjectPreAllocated(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ return Objects[ObjectIdx+NumFixedObjects].PreAllocated;
+ }
+
+ /// getObjectSize - Return the size of the specified object.
+ ///
+ int64_t getObjectSize(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ return Objects[ObjectIdx+NumFixedObjects].Size;
+ }
+
+ /// setObjectSize - Change the size of the specified stack object.
+ void setObjectSize(int ObjectIdx, int64_t Size) {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ Objects[ObjectIdx+NumFixedObjects].Size = Size;
+ }
+
+ /// getObjectAlignment - Return the alignment of the specified stack object.
+ unsigned getObjectAlignment(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ return Objects[ObjectIdx+NumFixedObjects].Alignment;
+ }
+
+ /// setObjectAlignment - Change the alignment of the specified stack object.
+ void setObjectAlignment(int ObjectIdx, unsigned Align) {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ Objects[ObjectIdx+NumFixedObjects].Alignment = Align;
+ ensureMaxAlignment(Align);
+ }
+
+ /// getObjectAllocation - Return the underlying Alloca of the specified
+ /// stack object if it exists. Returns 0 if none exists.
+ const Value* getObjectAllocation(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ return Objects[ObjectIdx+NumFixedObjects].Alloca;
+ }
+
+ /// NeedsStackProtector - Returns true if the object may need stack
+ /// protectors.
+ bool MayNeedStackProtector(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ return Objects[ObjectIdx+NumFixedObjects].MayNeedSP;
+ }
+
+ /// getObjectOffset - Return the assigned stack offset of the specified object
+ /// from the incoming stack pointer.
+ ///
+ int64_t getObjectOffset(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ assert(!isDeadObjectIndex(ObjectIdx) &&
+ "Getting frame offset for a dead object?");
+ return Objects[ObjectIdx+NumFixedObjects].SPOffset;
+ }
+
+ /// setObjectOffset - Set the stack frame offset of the specified object. The
+ /// offset is relative to the stack pointer on entry to the function.
+ ///
+ void setObjectOffset(int ObjectIdx, int64_t SPOffset) {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ assert(!isDeadObjectIndex(ObjectIdx) &&
+ "Setting frame offset for a dead object?");
+ Objects[ObjectIdx+NumFixedObjects].SPOffset = SPOffset;
+ }
+
+ /// getStackSize - Return the number of bytes that must be allocated to hold
+ /// all of the fixed size frame objects. This is only valid after
+ /// Prolog/Epilog code insertion has finalized the stack frame layout.
+ ///
+ uint64_t getStackSize() const { return StackSize; }
+
+ /// setStackSize - Set the size of the stack...
+ ///
+ void setStackSize(uint64_t Size) { StackSize = Size; }
+
+ /// getOffsetAdjustment - Return the correction for frame offsets.
+ ///
+ int getOffsetAdjustment() const { return OffsetAdjustment; }
+
+ /// setOffsetAdjustment - Set the correction for frame offsets.
+ ///
+ void setOffsetAdjustment(int Adj) { OffsetAdjustment = Adj; }
+
+ /// getMaxAlignment - Return the alignment in bytes that this function must be
+ /// aligned to, which is greater than the default stack alignment provided by
+ /// the target.
+ ///
+ unsigned getMaxAlignment() const { return MaxAlignment; }
+
+ /// ensureMaxAlignment - Make sure the function is at least Align bytes
+ /// aligned.
+ void ensureMaxAlignment(unsigned Align) {
+ if (MaxAlignment < Align) MaxAlignment = Align;
+ }
+
+ /// AdjustsStack - Return true if this function adjusts the stack -- e.g.,
+ /// when calling another function. This is only valid during and after
+ /// prolog/epilog code insertion.
+ bool adjustsStack() const { return AdjustsStack; }
+ void setAdjustsStack(bool V) { AdjustsStack = V; }
+
+ /// hasCalls - Return true if the current function has any function calls.
+ bool hasCalls() const { return HasCalls; }
+ void setHasCalls(bool V) { HasCalls = V; }
+
+ /// getMaxCallFrameSize - Return the maximum size of a call frame that must be
+ /// allocated for an outgoing function call. This is only available if
+ /// CallFrameSetup/Destroy pseudo instructions are used by the target, and
+ /// then only during or after prolog/epilog code insertion.
+ ///
+ unsigned getMaxCallFrameSize() const { return MaxCallFrameSize; }
+ void setMaxCallFrameSize(unsigned S) { MaxCallFrameSize = S; }
+
+ /// CreateFixedObject - Create a new object at a fixed location on the stack.
+ /// All fixed objects should be created before other objects are created for
+ /// efficiency. By default, fixed objects are immutable. This returns an
+ /// index with a negative value.
+ ///
+ int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool Immutable);
+
+
+ /// isFixedObjectIndex - Returns true if the specified index corresponds to a
+ /// fixed stack object.
+ bool isFixedObjectIndex(int ObjectIdx) const {
+ return ObjectIdx < 0 && (ObjectIdx >= -(int)NumFixedObjects);
+ }
+
+ /// isImmutableObjectIndex - Returns true if the specified index corresponds
+ /// to an immutable object.
+ bool isImmutableObjectIndex(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ return Objects[ObjectIdx+NumFixedObjects].isImmutable;
+ }
+
+ /// isSpillSlotObjectIndex - Returns true if the specified index corresponds
+ /// to a spill slot..
+ bool isSpillSlotObjectIndex(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;
+ }
+
+ /// isDeadObjectIndex - Returns true if the specified index corresponds to
+ /// a dead object.
+ bool isDeadObjectIndex(int ObjectIdx) const {
+ assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
+ "Invalid Object Idx!");
+ return Objects[ObjectIdx+NumFixedObjects].Size == ~0ULL;
+ }
+
+ /// CreateStackObject - Create a new statically sized stack object, returning
+ /// a nonnegative identifier to represent it.
+ ///
+ int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS,
+ bool MayNeedSP = false, const Value *Alloca = 0) {
+ assert(Size != 0 && "Cannot allocate zero size stack objects!");
+ Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, MayNeedSP,
+ Alloca));
+ int Index = (int)Objects.size() - NumFixedObjects - 1;
+ assert(Index >= 0 && "Bad frame index!");
+ ensureMaxAlignment(Alignment);
+ return Index;
+ }
+
+ /// CreateSpillStackObject - Create a new statically sized stack object that
+ /// represents a spill slot, returning a nonnegative identifier to represent
+ /// it.
+ ///
+ int CreateSpillStackObject(uint64_t Size, unsigned Alignment) {
+ CreateStackObject(Size, Alignment, true, false);
+ int Index = (int)Objects.size() - NumFixedObjects - 1;
+ ensureMaxAlignment(Alignment);
+ return Index;
+ }
+
+ /// RemoveStackObject - Remove or mark dead a statically sized stack object.
+ ///
+ void RemoveStackObject(int ObjectIdx) {
+ // Mark it dead.
+ Objects[ObjectIdx+NumFixedObjects].Size = ~0ULL;
+ }
+
+ /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
+ /// variable sized object has been created. This must be created whenever a
+ /// variable sized object is created, whether or not the index returned is
+ /// actually used.
+ ///
+ int CreateVariableSizedObject(unsigned Alignment) {
+ HasVarSizedObjects = true;
+ Objects.push_back(StackObject(0, Alignment, 0, false, false, true, 0));
+ ensureMaxAlignment(Alignment);
+ return (int)Objects.size()-NumFixedObjects-1;
+ }
+
+ /// getCalleeSavedInfo - Returns a reference to call saved info vector for the
+ /// current function.
+ const std::vector<CalleeSavedInfo> &getCalleeSavedInfo() const {
+ return CSInfo;
+ }
+
+ /// setCalleeSavedInfo - Used by prolog/epilog inserter to set the function's
+ /// callee saved information.
+ void setCalleeSavedInfo(const std::vector<CalleeSavedInfo> &CSI) {
+ CSInfo = CSI;
+ }
+
+ /// isCalleeSavedInfoValid - Has the callee saved info been calculated yet?
+ bool isCalleeSavedInfoValid() const { return CSIValid; }
+
+ void setCalleeSavedInfoValid(bool v) { CSIValid = v; }
+
+ /// getPristineRegs - Return a set of physical registers that are pristine on
+ /// entry to the MBB.
+ ///
+ /// Pristine registers hold a value that is useless to the current function,
+ /// but that must be preserved - they are callee saved registers that have not
+ /// been saved yet.
+ ///
+ /// Before the PrologueEpilogueInserter has placed the CSR spill code, this
+ /// method always returns an empty set.
+ BitVector getPristineRegs(const MachineBasicBlock *MBB) const;
+
+ /// print - Used by the MachineFunction printer to print information about
+ /// stack objects. Implemented in MachineFunction.cpp
+ ///
+ void print(const MachineFunction &MF, raw_ostream &OS) const;
+
+ /// dump - Print the function to stderr.
+ void dump(const MachineFunction &MF) const;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineFunction.h b/include/llvm/CodeGen/MachineFunction.h
new file mode 100644
index 00000000000..025e18a9dde
--- /dev/null
+++ b/include/llvm/CodeGen/MachineFunction.h
@@ -0,0 +1,491 @@
+//===-- llvm/CodeGen/MachineFunction.h --------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Collect native machine code for a function. This class contains a list of
+// MachineBasicBlock instances that make up the current compiled function.
+//
+// This class also contains pointers to various classes which hold
+// target-specific information about the generated code.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
+#define LLVM_CODEGEN_MACHINEFUNCTION_H
+
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/ADT/ilist.h"
+#include "llvm/Support/DebugLoc.h"
+#include "llvm/Support/Allocator.h"
+#include "llvm/Support/Recycler.h"
+
+namespace llvm {
+
+class Value;
+class Function;
+class GCModuleInfo;
+class MachineRegisterInfo;
+class MachineFrameInfo;
+class MachineConstantPool;
+class MachineJumpTableInfo;
+class MachineModuleInfo;
+class MCContext;
+class Pass;
+class TargetMachine;
+class TargetRegisterClass;
+struct MachinePointerInfo;
+
+template <>
+struct ilist_traits<MachineBasicBlock>
+ : public ilist_default_traits<MachineBasicBlock> {
+ mutable ilist_half_node<MachineBasicBlock> Sentinel;
+public:
+ MachineBasicBlock *createSentinel() const {
+ return static_cast<MachineBasicBlock*>(&Sentinel);
+ }
+ void destroySentinel(MachineBasicBlock *) const {}
+
+ MachineBasicBlock *provideInitialHead() const { return createSentinel(); }
+ MachineBasicBlock *ensureHead(MachineBasicBlock*) const {
+ return createSentinel();
+ }
+ static void noteHead(MachineBasicBlock*, MachineBasicBlock*) {}
+
+ void addNodeToList(MachineBasicBlock* MBB);
+ void removeNodeFromList(MachineBasicBlock* MBB);
+ void deleteNode(MachineBasicBlock *MBB);
+private:
+ void createNode(const MachineBasicBlock &);
+};
+
+/// MachineFunctionInfo - This class can be derived from and used by targets to
+/// hold private target-specific information for each MachineFunction. Objects
+/// of type are accessed/created with MF::getInfo and destroyed when the
+/// MachineFunction is destroyed.
+struct MachineFunctionInfo {
+ virtual ~MachineFunctionInfo();
+};
+
+class MachineFunction {
+ const Function *Fn;
+ const TargetMachine &Target;
+ MCContext &Ctx;
+ MachineModuleInfo &MMI;
+ GCModuleInfo *GMI;
+
+ // RegInfo - Information about each register in use in the function.
+ MachineRegisterInfo *RegInfo;
+
+ // Used to keep track of target-specific per-machine function information for
+ // the target implementation.
+ MachineFunctionInfo *MFInfo;
+
+ // Keep track of objects allocated on the stack.
+ MachineFrameInfo *FrameInfo;
+
+ // Keep track of constants which are spilled to memory
+ MachineConstantPool *ConstantPool;
+
+ // Keep track of jump tables for switch instructions
+ MachineJumpTableInfo *JumpTableInfo;
+
+ // Function-level unique numbering for MachineBasicBlocks. When a
+ // MachineBasicBlock is inserted into a MachineFunction is it automatically
+ // numbered and this vector keeps track of the mapping from ID's to MBB's.
+ std::vector<MachineBasicBlock*> MBBNumbering;
+
+ // Pool-allocate MachineFunction-lifetime and IR objects.
+ BumpPtrAllocator Allocator;
+
+ // Allocation management for instructions in function.
+ Recycler<MachineInstr> InstructionRecycler;
+
+ // Allocation management for basic blocks in function.
+ Recycler<MachineBasicBlock> BasicBlockRecycler;
+
+ // List of machine basic blocks in function
+ typedef ilist<MachineBasicBlock> BasicBlockListType;
+ BasicBlockListType BasicBlocks;
+
+ /// FunctionNumber - This provides a unique ID for each function emitted in
+ /// this translation unit.
+ ///
+ unsigned FunctionNumber;
+
+ /// Alignment - The alignment of the function.
+ unsigned Alignment;
+
+ /// ExposesReturnsTwice - True if the function calls setjmp or related
+ /// functions with attribute "returns twice", but doesn't have
+ /// the attribute itself.
+ /// This is used to limit optimizations which cannot reason
+ /// about the control flow of such functions.
+ bool ExposesReturnsTwice;
+
+ MachineFunction(const MachineFunction &) LLVM_DELETED_FUNCTION;
+ void operator=(const MachineFunction&) LLVM_DELETED_FUNCTION;
+public:
+ MachineFunction(const Function *Fn, const TargetMachine &TM,
+ unsigned FunctionNum, MachineModuleInfo &MMI,
+ GCModuleInfo* GMI);
+ ~MachineFunction();
+
+ MachineModuleInfo &getMMI() const { return MMI; }
+ GCModuleInfo *getGMI() const { return GMI; }
+ MCContext &getContext() const { return Ctx; }
+
+ /// getFunction - Return the LLVM function that this machine code represents
+ ///
+ const Function *getFunction() const { return Fn; }
+
+ /// getName - Return the name of the corresponding LLVM function.
+ ///
+ StringRef getName() const;
+
+ /// getFunctionNumber - Return a unique ID for the current function.
+ ///
+ unsigned getFunctionNumber() const { return FunctionNumber; }
+
+ /// getTarget - Return the target machine this machine code is compiled with
+ ///
+ const TargetMachine &getTarget() const { return Target; }
+
+ /// getRegInfo - Return information about the registers currently in use.
+ ///
+ MachineRegisterInfo &getRegInfo() { return *RegInfo; }
+ const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
+
+ /// getFrameInfo - Return the frame info object for the current function.
+ /// This object contains information about objects allocated on the stack
+ /// frame of the current function in an abstract way.
+ ///
+ MachineFrameInfo *getFrameInfo() { return FrameInfo; }
+ const MachineFrameInfo *getFrameInfo() const { return FrameInfo; }
+
+ /// getJumpTableInfo - Return the jump table info object for the current
+ /// function. This object contains information about jump tables in the
+ /// current function. If the current function has no jump tables, this will
+ /// return null.
+ const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
+ MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
+
+ /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
+ /// does already exist, allocate one.
+ MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
+
+
+ /// getConstantPool - Return the constant pool object for the current
+ /// function.
+ ///
+ MachineConstantPool *getConstantPool() { return ConstantPool; }
+ const MachineConstantPool *getConstantPool() const { return ConstantPool; }
+
+ /// getAlignment - Return the alignment (log2, not bytes) of the function.
+ ///
+ unsigned getAlignment() const { return Alignment; }
+
+ /// setAlignment - Set the alignment (log2, not bytes) of the function.
+ ///
+ void setAlignment(unsigned A) { Alignment = A; }
+
+ /// ensureAlignment - Make sure the function is at least 1 << A bytes aligned.
+ void ensureAlignment(unsigned A) {
+ if (Alignment < A) Alignment = A;
+ }
+
+ /// exposesReturnsTwice - Returns true if the function calls setjmp or
+ /// any other similar functions with attribute "returns twice" without
+ /// having the attribute itself.
+ bool exposesReturnsTwice() const {
+ return ExposesReturnsTwice;
+ }
+
+ /// setCallsSetJmp - Set a flag that indicates if there's a call to
+ /// a "returns twice" function.
+ void setExposesReturnsTwice(bool B) {
+ ExposesReturnsTwice = B;
+ }
+
+ /// getInfo - Keep track of various per-function pieces of information for
+ /// backends that would like to do so.
+ ///
+ template<typename Ty>
+ Ty *getInfo() {
+ if (!MFInfo) {
+ // This should be just `new (Allocator.Allocate<Ty>()) Ty(*this)', but
+ // that apparently breaks GCC 3.3.
+ Ty *Loc = static_cast<Ty*>(Allocator.Allocate(sizeof(Ty),
+ AlignOf<Ty>::Alignment));
+ MFInfo = new (Loc) Ty(*this);
+ }
+ return static_cast<Ty*>(MFInfo);
+ }
+
+ template<typename Ty>
+ const Ty *getInfo() const {
+ return const_cast<MachineFunction*>(this)->getInfo<Ty>();
+ }
+
+ /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
+ /// are inserted into the machine function. The block number for a machine
+ /// basic block can be found by using the MBB::getBlockNumber method, this
+ /// method provides the inverse mapping.
+ ///
+ MachineBasicBlock *getBlockNumbered(unsigned N) const {
+ assert(N < MBBNumbering.size() && "Illegal block number");
+ assert(MBBNumbering[N] && "Block was removed from the machine function!");
+ return MBBNumbering[N];
+ }
+
+ /// getNumBlockIDs - Return the number of MBB ID's allocated.
+ ///
+ unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
+
+ /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
+ /// recomputes them. This guarantees that the MBB numbers are sequential,
+ /// dense, and match the ordering of the blocks within the function. If a
+ /// specific MachineBasicBlock is specified, only that block and those after
+ /// it are renumbered.
+ void RenumberBlocks(MachineBasicBlock *MBBFrom = 0);
+
+ /// print - Print out the MachineFunction in a format suitable for debugging
+ /// to the specified stream.
+ ///
+ void print(raw_ostream &OS, SlotIndexes* = 0) const;
+
+ /// viewCFG - This function is meant for use from the debugger. You can just
+ /// say 'call F->viewCFG()' and a ghostview window should pop up from the
+ /// program, displaying the CFG of the current function with the code for each
+ /// basic block inside. This depends on there being a 'dot' and 'gv' program
+ /// in your path.
+ ///
+ void viewCFG() const;
+
+ /// viewCFGOnly - This function is meant for use from the debugger. It works
+ /// just like viewCFG, but it does not include the contents of basic blocks
+ /// into the nodes, just the label. If you are only interested in the CFG
+ /// this can make the graph smaller.
+ ///
+ void viewCFGOnly() const;
+
+ /// dump - Print the current MachineFunction to cerr, useful for debugger use.
+ ///
+ void dump() const;
+
+ /// verify - Run the current MachineFunction through the machine code
+ /// verifier, useful for debugger use.
+ void verify(Pass *p = NULL, const char *Banner = NULL) const;
+
+ // Provide accessors for the MachineBasicBlock list...
+ typedef BasicBlockListType::iterator iterator;
+ typedef BasicBlockListType::const_iterator const_iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+
+ /// addLiveIn - Add the specified physical register as a live-in value and
+ /// create a corresponding virtual register for it.
+ unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC);
+
+ //===--------------------------------------------------------------------===//
+ // BasicBlock accessor functions.
+ //
+ iterator begin() { return BasicBlocks.begin(); }
+ const_iterator begin() const { return BasicBlocks.begin(); }
+ iterator end () { return BasicBlocks.end(); }
+ const_iterator end () const { return BasicBlocks.end(); }
+
+ reverse_iterator rbegin() { return BasicBlocks.rbegin(); }
+ const_reverse_iterator rbegin() const { return BasicBlocks.rbegin(); }
+ reverse_iterator rend () { return BasicBlocks.rend(); }
+ const_reverse_iterator rend () const { return BasicBlocks.rend(); }
+
+ unsigned size() const { return (unsigned)BasicBlocks.size();}
+ bool empty() const { return BasicBlocks.empty(); }
+ const MachineBasicBlock &front() const { return BasicBlocks.front(); }
+ MachineBasicBlock &front() { return BasicBlocks.front(); }
+ const MachineBasicBlock & back() const { return BasicBlocks.back(); }
+ MachineBasicBlock & back() { return BasicBlocks.back(); }
+
+ void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
+ void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
+ void insert(iterator MBBI, MachineBasicBlock *MBB) {
+ BasicBlocks.insert(MBBI, MBB);
+ }
+ void splice(iterator InsertPt, iterator MBBI) {
+ BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
+ }
+ void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
+ BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
+ }
+
+ void remove(iterator MBBI) {
+ BasicBlocks.remove(MBBI);
+ }
+ void erase(iterator MBBI) {
+ BasicBlocks.erase(MBBI);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Internal functions used to automatically number MachineBasicBlocks
+ //
+
+ /// getNextMBBNumber - Returns the next unique number to be assigned
+ /// to a MachineBasicBlock in this MachineFunction.
+ ///
+ unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
+ MBBNumbering.push_back(MBB);
+ return (unsigned)MBBNumbering.size()-1;
+ }
+
+ /// removeFromMBBNumbering - Remove the specific machine basic block from our
+ /// tracker, this is only really to be used by the MachineBasicBlock
+ /// implementation.
+ void removeFromMBBNumbering(unsigned N) {
+ assert(N < MBBNumbering.size() && "Illegal basic block #");
+ MBBNumbering[N] = 0;
+ }
+
+ /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
+ /// of `new MachineInstr'.
+ ///
+ MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID,
+ DebugLoc DL,
+ bool NoImp = false);
+
+ /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
+ /// 'Orig' instruction, identical in all ways except the instruction
+ /// has no parent, prev, or next.
+ ///
+ /// See also TargetInstrInfo::duplicate() for target-specific fixes to cloned
+ /// instructions.
+ MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
+
+ /// DeleteMachineInstr - Delete the given MachineInstr.
+ ///
+ void DeleteMachineInstr(MachineInstr *MI);
+
+ /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
+ /// instead of `new MachineBasicBlock'.
+ ///
+ MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = 0);
+
+ /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
+ ///
+ void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
+
+ /// getMachineMemOperand - Allocate a new MachineMemOperand.
+ /// MachineMemOperands are owned by the MachineFunction and need not be
+ /// explicitly deallocated.
+ MachineMemOperand *getMachineMemOperand(MachinePointerInfo PtrInfo,
+ unsigned f, uint64_t s,
+ unsigned base_alignment,
+ const MDNode *TBAAInfo = 0,
+ const MDNode *Ranges = 0);
+
+ /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
+ /// an existing one, adjusting by an offset and using the given size.
+ /// MachineMemOperands are owned by the MachineFunction and need not be
+ /// explicitly deallocated.
+ MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
+ int64_t Offset, uint64_t Size);
+
+ /// allocateMemRefsArray - Allocate an array to hold MachineMemOperand
+ /// pointers. This array is owned by the MachineFunction.
+ MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num);
+
+ /// extractLoadMemRefs - Allocate an array and populate it with just the
+ /// load information from the given MachineMemOperand sequence.
+ std::pair<MachineInstr::mmo_iterator,
+ MachineInstr::mmo_iterator>
+ extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
+ MachineInstr::mmo_iterator End);
+
+ /// extractStoreMemRefs - Allocate an array and populate it with just the
+ /// store information from the given MachineMemOperand sequence.
+ std::pair<MachineInstr::mmo_iterator,
+ MachineInstr::mmo_iterator>
+ extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
+ MachineInstr::mmo_iterator End);
+
+ //===--------------------------------------------------------------------===//
+ // Label Manipulation.
+ //
+
+ /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
+ /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
+ /// normal 'L' label is returned.
+ MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
+ bool isLinkerPrivate = false) const;
+
+ /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
+ /// base.
+ MCSymbol *getPICBaseSymbol() const;
+};
+
+//===--------------------------------------------------------------------===//
+// GraphTraits specializations for function basic block graphs (CFGs)
+//===--------------------------------------------------------------------===//
+
+// Provide specializations of GraphTraits to be able to treat a
+// machine function as a graph of machine basic blocks... these are
+// the same as the machine basic block iterators, except that the root
+// node is implicitly the first node of the function.
+//
+template <> struct GraphTraits<MachineFunction*> :
+ public GraphTraits<MachineBasicBlock*> {
+ static NodeType *getEntryNode(MachineFunction *F) {
+ return &F->front();
+ }
+
+ // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
+ typedef MachineFunction::iterator nodes_iterator;
+ static nodes_iterator nodes_begin(MachineFunction *F) { return F->begin(); }
+ static nodes_iterator nodes_end (MachineFunction *F) { return F->end(); }
+ static unsigned size (MachineFunction *F) { return F->size(); }
+};
+template <> struct GraphTraits<const MachineFunction*> :
+ public GraphTraits<const MachineBasicBlock*> {
+ static NodeType *getEntryNode(const MachineFunction *F) {
+ return &F->front();
+ }
+
+ // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
+ typedef MachineFunction::const_iterator nodes_iterator;
+ static nodes_iterator nodes_begin(const MachineFunction *F) {
+ return F->begin();
+ }
+ static nodes_iterator nodes_end (const MachineFunction *F) {
+ return F->end();
+ }
+ static unsigned size (const MachineFunction *F) {
+ return F->size();
+ }
+};
+
+
+// Provide specializations of GraphTraits to be able to treat a function as a
+// graph of basic blocks... and to walk it in inverse order. Inverse order for
+// a function is considered to be when traversing the predecessor edges of a BB
+// instead of the successor edges.
+//
+template <> struct GraphTraits<Inverse<MachineFunction*> > :
+ public GraphTraits<Inverse<MachineBasicBlock*> > {
+ static NodeType *getEntryNode(Inverse<MachineFunction*> G) {
+ return &G.Graph->front();
+ }
+};
+template <> struct GraphTraits<Inverse<const MachineFunction*> > :
+ public GraphTraits<Inverse<const MachineBasicBlock*> > {
+ static NodeType *getEntryNode(Inverse<const MachineFunction *> G) {
+ return &G.Graph->front();
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineFunctionAnalysis.h b/include/llvm/CodeGen/MachineFunctionAnalysis.h
new file mode 100644
index 00000000000..50ea2062f30
--- /dev/null
+++ b/include/llvm/CodeGen/MachineFunctionAnalysis.h
@@ -0,0 +1,51 @@
+//===-- MachineFunctionAnalysis.h - Owner of MachineFunctions ----*-C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the MachineFunctionAnalysis class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINE_FUNCTION_ANALYSIS_H
+#define LLVM_CODEGEN_MACHINE_FUNCTION_ANALYSIS_H
+
+#include "llvm/Pass.h"
+#include "llvm/Target/TargetMachine.h"
+
+namespace llvm {
+
+class MachineFunction;
+
+/// MachineFunctionAnalysis - This class is a Pass that manages a
+/// MachineFunction object.
+struct MachineFunctionAnalysis : public FunctionPass {
+private:
+ const TargetMachine &TM;
+ MachineFunction *MF;
+ unsigned NextFnNum;
+public:
+ static char ID;
+ explicit MachineFunctionAnalysis(const TargetMachine &tm);
+ ~MachineFunctionAnalysis();
+
+ MachineFunction &getMF() const { return *MF; }
+
+ virtual const char* getPassName() const {
+ return "Machine Function Analysis";
+ }
+
+private:
+ virtual bool doInitialization(Module &M);
+ virtual bool runOnFunction(Function &F);
+ virtual void releaseMemory();
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineFunctionPass.h b/include/llvm/CodeGen/MachineFunctionPass.h
new file mode 100644
index 00000000000..b7bf0a36c44
--- /dev/null
+++ b/include/llvm/CodeGen/MachineFunctionPass.h
@@ -0,0 +1,59 @@
+//===-- MachineFunctionPass.h - Pass for MachineFunctions --------*-C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MachineFunctionPass class. MachineFunctionPass's are
+// just FunctionPass's, except they operate on machine code as part of a code
+// generator. Because they operate on machine code, not the LLVM
+// representation, MachineFunctionPass's are not allowed to modify the LLVM
+// representation. Due to this limitation, the MachineFunctionPass class takes
+// care of declaring that no LLVM passes are invalidated.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINE_FUNCTION_PASS_H
+#define LLVM_CODEGEN_MACHINE_FUNCTION_PASS_H
+
+#include "llvm/Pass.h"
+
+namespace llvm {
+
+class MachineFunction;
+
+/// MachineFunctionPass - This class adapts the FunctionPass interface to
+/// allow convenient creation of passes that operate on the MachineFunction
+/// representation. Instead of overriding runOnFunction, subclasses
+/// override runOnMachineFunction.
+class MachineFunctionPass : public FunctionPass {
+protected:
+ explicit MachineFunctionPass(char &ID) : FunctionPass(ID) {}
+
+ /// runOnMachineFunction - This method must be overloaded to perform the
+ /// desired machine code transformation or analysis.
+ ///
+ virtual bool runOnMachineFunction(MachineFunction &MF) = 0;
+
+ /// getAnalysisUsage - Subclasses that override getAnalysisUsage
+ /// must call this.
+ ///
+ /// For MachineFunctionPasses, calling AU.preservesCFG() indicates that
+ /// the pass does not modify the MachineBasicBlock CFG.
+ ///
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+private:
+ /// createPrinterPass - Get a machine function printer pass.
+ virtual Pass *createPrinterPass(raw_ostream &O,
+ const std::string &Banner) const;
+
+ virtual bool runOnFunction(Function &F);
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineInstr.h b/include/llvm/CodeGen/MachineInstr.h
new file mode 100644
index 00000000000..32c79510d89
--- /dev/null
+++ b/include/llvm/CodeGen/MachineInstr.h
@@ -0,0 +1,1029 @@
+//===-- llvm/CodeGen/MachineInstr.h - MachineInstr class --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MachineInstr class, which is the
+// basic representation for all target dependent machine instructions used by
+// the back end.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEINSTR_H
+#define LLVM_CODEGEN_MACHINEINSTR_H
+
+#include "llvm/CodeGen/MachineOperand.h"
+#include "llvm/MC/MCInstrDesc.h"
+#include "llvm/Target/TargetOpcodes.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/DenseMapInfo.h"
+#include "llvm/InlineAsm.h"
+#include "llvm/Support/DebugLoc.h"
+#include <vector>
+
+namespace llvm {
+
+template <typename T> class SmallVectorImpl;
+class AliasAnalysis;
+class TargetInstrInfo;
+class TargetRegisterClass;
+class TargetRegisterInfo;
+class MachineFunction;
+class MachineMemOperand;
+
+//===----------------------------------------------------------------------===//
+/// MachineInstr - Representation of each machine instruction.
+///
+class MachineInstr : public ilist_node<MachineInstr> {
+public:
+ typedef MachineMemOperand **mmo_iterator;
+
+ /// Flags to specify different kinds of comments to output in
+ /// assembly code. These flags carry semantic information not
+ /// otherwise easily derivable from the IR text.
+ ///
+ enum CommentFlag {
+ ReloadReuse = 0x1
+ };
+
+ enum MIFlag {
+ NoFlags = 0,
+ FrameSetup = 1 << 0, // Instruction is used as a part of
+ // function frame setup code.
+ InsideBundle = 1 << 1 // Instruction is inside a bundle (not
+ // the first MI in a bundle)
+ };
+private:
+ const MCInstrDesc *MCID; // Instruction descriptor.
+
+ uint8_t Flags; // Various bits of additional
+ // information about machine
+ // instruction.
+
+ uint8_t AsmPrinterFlags; // Various bits of information used by
+ // the AsmPrinter to emit helpful
+ // comments. This is *not* semantic
+ // information. Do not use this for
+ // anything other than to convey comment
+ // information to AsmPrinter.
+
+ uint16_t NumMemRefs; // information on memory references
+ mmo_iterator MemRefs;
+
+ std::vector<MachineOperand> Operands; // the operands
+ MachineBasicBlock *Parent; // Pointer to the owning basic block.
+ DebugLoc debugLoc; // Source line information.
+
+ MachineInstr(const MachineInstr&) LLVM_DELETED_FUNCTION;
+ void operator=(const MachineInstr&) LLVM_DELETED_FUNCTION;
+
+ // Intrusive list support
+ friend struct ilist_traits<MachineInstr>;
+ friend struct ilist_traits<MachineBasicBlock>;
+ void setParent(MachineBasicBlock *P) { Parent = P; }
+
+ /// MachineInstr ctor - This constructor creates a copy of the given
+ /// MachineInstr in the given MachineFunction.
+ MachineInstr(MachineFunction &, const MachineInstr &);
+
+ /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
+ /// MCID NULL and no operands.
+ MachineInstr();
+
+ // The next two constructors have DebugLoc and non-DebugLoc versions;
+ // over time, the non-DebugLoc versions should be phased out and eventually
+ // removed.
+
+ /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
+ /// implicit operands. It reserves space for the number of operands specified
+ /// by the MCInstrDesc. The version with a DebugLoc should be preferred.
+ explicit MachineInstr(const MCInstrDesc &MCID, bool NoImp = false);
+
+ /// MachineInstr ctor - Work exactly the same as the ctor above, except that
+ /// the MachineInstr is created and added to the end of the specified basic
+ /// block. The version with a DebugLoc should be preferred.
+ MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &MCID);
+
+ /// MachineInstr ctor - This constructor create a MachineInstr and add the
+ /// implicit operands. It reserves space for number of operands specified by
+ /// MCInstrDesc. An explicit DebugLoc is supplied.
+ explicit MachineInstr(const MCInstrDesc &MCID, const DebugLoc dl,
+ bool NoImp = false);
+
+ /// MachineInstr ctor - Work exactly the same as the ctor above, except that
+ /// the MachineInstr is created and added to the end of the specified basic
+ /// block.
+ MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
+ const MCInstrDesc &MCID);
+
+ ~MachineInstr();
+
+ // MachineInstrs are pool-allocated and owned by MachineFunction.
+ friend class MachineFunction;
+
+public:
+ const MachineBasicBlock* getParent() const { return Parent; }
+ MachineBasicBlock* getParent() { return Parent; }
+
+ /// getAsmPrinterFlags - Return the asm printer flags bitvector.
+ ///
+ uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
+
+ /// clearAsmPrinterFlags - clear the AsmPrinter bitvector
+ ///
+ void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
+
+ /// getAsmPrinterFlag - Return whether an AsmPrinter flag is set.
+ ///
+ bool getAsmPrinterFlag(CommentFlag Flag) const {
+ return AsmPrinterFlags & Flag;
+ }
+
+ /// setAsmPrinterFlag - Set a flag for the AsmPrinter.
+ ///
+ void setAsmPrinterFlag(CommentFlag Flag) {
+ AsmPrinterFlags |= (uint8_t)Flag;
+ }
+
+ /// clearAsmPrinterFlag - clear specific AsmPrinter flags
+ ///
+ void clearAsmPrinterFlag(CommentFlag Flag) {
+ AsmPrinterFlags &= ~Flag;
+ }
+
+ /// getFlags - Return the MI flags bitvector.
+ uint8_t getFlags() const {
+ return Flags;
+ }
+
+ /// getFlag - Return whether an MI flag is set.
+ bool getFlag(MIFlag Flag) const {
+ return Flags & Flag;
+ }
+
+ /// setFlag - Set a MI flag.
+ void setFlag(MIFlag Flag) {
+ Flags |= (uint8_t)Flag;
+ }
+
+ void setFlags(unsigned flags) {
+ Flags = flags;
+ }
+
+ /// clearFlag - Clear a MI flag.
+ void clearFlag(MIFlag Flag) {
+ Flags &= ~((uint8_t)Flag);
+ }
+
+ /// isInsideBundle - Return true if MI is in a bundle (but not the first MI
+ /// in a bundle).
+ ///
+ /// A bundle looks like this before it's finalized:
+ /// ----------------
+ /// | MI |
+ /// ----------------
+ /// |
+ /// ----------------
+ /// | MI * |
+ /// ----------------
+ /// |
+ /// ----------------
+ /// | MI * |
+ /// ----------------
+ /// In this case, the first MI starts a bundle but is not inside a bundle, the
+ /// next 2 MIs are considered "inside" the bundle.
+ ///
+ /// After a bundle is finalized, it looks like this:
+ /// ----------------
+ /// | Bundle |
+ /// ----------------
+ /// |
+ /// ----------------
+ /// | MI * |
+ /// ----------------
+ /// |
+ /// ----------------
+ /// | MI * |
+ /// ----------------
+ /// |
+ /// ----------------
+ /// | MI * |
+ /// ----------------
+ /// The first instruction has the special opcode "BUNDLE". It's not "inside"
+ /// a bundle, but the next three MIs are.
+ bool isInsideBundle() const {
+ return getFlag(InsideBundle);
+ }
+
+ /// setIsInsideBundle - Set InsideBundle bit.
+ ///
+ void setIsInsideBundle(bool Val = true) {
+ if (Val)
+ setFlag(InsideBundle);
+ else
+ clearFlag(InsideBundle);
+ }
+
+ /// isBundled - Return true if this instruction part of a bundle. This is true
+ /// if either itself or its following instruction is marked "InsideBundle".
+ bool isBundled() const;
+
+ /// getDebugLoc - Returns the debug location id of this MachineInstr.
+ ///
+ DebugLoc getDebugLoc() const { return debugLoc; }
+
+ /// emitError - Emit an error referring to the source location of this
+ /// instruction. This should only be used for inline assembly that is somehow
+ /// impossible to compile. Other errors should have been handled much
+ /// earlier.
+ ///
+ /// If this method returns, the caller should try to recover from the error.
+ ///
+ void emitError(StringRef Msg) const;
+
+ /// getDesc - Returns the target instruction descriptor of this
+ /// MachineInstr.
+ const MCInstrDesc &getDesc() const { return *MCID; }
+
+ /// getOpcode - Returns the opcode of this MachineInstr.
+ ///
+ int getOpcode() const { return MCID->Opcode; }
+
+ /// Access to explicit operands of the instruction.
+ ///
+ unsigned getNumOperands() const { return (unsigned)Operands.size(); }
+
+ const MachineOperand& getOperand(unsigned i) const {
+ assert(i < getNumOperands() && "getOperand() out of range!");
+ return Operands[i];
+ }
+ MachineOperand& getOperand(unsigned i) {
+ assert(i < getNumOperands() && "getOperand() out of range!");
+ return Operands[i];
+ }
+
+ /// getNumExplicitOperands - Returns the number of non-implicit operands.
+ ///
+ unsigned getNumExplicitOperands() const;
+
+ /// iterator/begin/end - Iterate over all operands of a machine instruction.
+ typedef std::vector<MachineOperand>::iterator mop_iterator;
+ typedef std::vector<MachineOperand>::const_iterator const_mop_iterator;
+
+ mop_iterator operands_begin() { return Operands.begin(); }
+ mop_iterator operands_end() { return Operands.end(); }
+
+ const_mop_iterator operands_begin() const { return Operands.begin(); }
+ const_mop_iterator operands_end() const { return Operands.end(); }
+
+ /// Access to memory operands of the instruction
+ mmo_iterator memoperands_begin() const { return MemRefs; }
+ mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
+ bool memoperands_empty() const { return NumMemRefs == 0; }
+
+ /// hasOneMemOperand - Return true if this instruction has exactly one
+ /// MachineMemOperand.
+ bool hasOneMemOperand() const {
+ return NumMemRefs == 1;
+ }
+
+ /// API for querying MachineInstr properties. They are the same as MCInstrDesc
+ /// queries but they are bundle aware.
+
+ enum QueryType {
+ IgnoreBundle, // Ignore bundles
+ AnyInBundle, // Return true if any instruction in bundle has property
+ AllInBundle // Return true if all instructions in bundle have property
+ };
+
+ /// hasProperty - Return true if the instruction (or in the case of a bundle,
+ /// the instructions inside the bundle) has the specified property.
+ /// The first argument is the property being queried.
+ /// The second argument indicates whether the query should look inside
+ /// instruction bundles.
+ bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
+ // Inline the fast path.
+ if (Type == IgnoreBundle || !isBundle())
+ return getDesc().getFlags() & (1 << MCFlag);
+
+ // If we have a bundle, take the slow path.
+ return hasPropertyInBundle(1 << MCFlag, Type);
+ }
+
+ /// isVariadic - Return true if this instruction can have a variable number of
+ /// operands. In this case, the variable operands will be after the normal
+ /// operands but before the implicit definitions and uses (if any are
+ /// present).
+ bool isVariadic(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::Variadic, Type);
+ }
+
+ /// hasOptionalDef - Set if this instruction has an optional definition, e.g.
+ /// ARM instructions which can set condition code if 's' bit is set.
+ bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::HasOptionalDef, Type);
+ }
+
+ /// isPseudo - Return true if this is a pseudo instruction that doesn't
+ /// correspond to a real machine instruction.
+ ///
+ bool isPseudo(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::Pseudo, Type);
+ }
+
+ bool isReturn(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::Return, Type);
+ }
+
+ bool isCall(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::Call, Type);
+ }
+
+ /// isBarrier - Returns true if the specified instruction stops control flow
+ /// from executing the instruction immediately following it. Examples include
+ /// unconditional branches and return instructions.
+ bool isBarrier(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::Barrier, Type);
+ }
+
+ /// isTerminator - Returns true if this instruction part of the terminator for
+ /// a basic block. Typically this is things like return and branch
+ /// instructions.
+ ///
+ /// Various passes use this to insert code into the bottom of a basic block,
+ /// but before control flow occurs.
+ bool isTerminator(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::Terminator, Type);
+ }
+
+ /// isBranch - Returns true if this is a conditional, unconditional, or
+ /// indirect branch. Predicates below can be used to discriminate between
+ /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
+ /// get more information.
+ bool isBranch(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::Branch, Type);
+ }
+
+ /// isIndirectBranch - Return true if this is an indirect branch, such as a
+ /// branch through a register.
+ bool isIndirectBranch(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::IndirectBranch, Type);
+ }
+
+ /// isConditionalBranch - Return true if this is a branch which may fall
+ /// through to the next instruction or may transfer control flow to some other
+ /// block. The TargetInstrInfo::AnalyzeBranch method can be used to get more
+ /// information about this branch.
+ bool isConditionalBranch(QueryType Type = AnyInBundle) const {
+ return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
+ }
+
+ /// isUnconditionalBranch - Return true if this is a branch which always
+ /// transfers control flow to some other block. The
+ /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
+ /// about this branch.
+ bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
+ return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
+ }
+
+ // isPredicable - Return true if this instruction has a predicate operand that
+ // controls execution. It may be set to 'always', or may be set to other
+ /// values. There are various methods in TargetInstrInfo that can be used to
+ /// control and modify the predicate in this instruction.
+ bool isPredicable(QueryType Type = AllInBundle) const {
+ // If it's a bundle than all bundled instructions must be predicable for this
+ // to return true.
+ return hasProperty(MCID::Predicable, Type);
+ }
+
+ /// isCompare - Return true if this instruction is a comparison.
+ bool isCompare(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::Compare, Type);
+ }
+
+ /// isMoveImmediate - Return true if this instruction is a move immediate
+ /// (including conditional moves) instruction.
+ bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::MoveImm, Type);
+ }
+
+ /// isBitcast - Return true if this instruction is a bitcast instruction.
+ ///
+ bool isBitcast(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::Bitcast, Type);
+ }
+
+ /// isSelect - Return true if this instruction is a select instruction.
+ ///
+ bool isSelect(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::Select, Type);
+ }
+
+ /// isNotDuplicable - Return true if this instruction cannot be safely
+ /// duplicated. For example, if the instruction has a unique labels attached
+ /// to it, duplicating it would cause multiple definition errors.
+ bool isNotDuplicable(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::NotDuplicable, Type);
+ }
+
+ /// hasDelaySlot - Returns true if the specified instruction has a delay slot
+ /// which must be filled by the code generator.
+ bool hasDelaySlot(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::DelaySlot, Type);
+ }
+
+ /// canFoldAsLoad - Return true for instructions that can be folded as
+ /// memory operands in other instructions. The most common use for this
+ /// is instructions that are simple loads from memory that don't modify
+ /// the loaded value in any way, but it can also be used for instructions
+ /// that can be expressed as constant-pool loads, such as V_SETALLONES
+ /// on x86, to allow them to be folded when it is beneficial.
+ /// This should only be set on instructions that return a value in their
+ /// only virtual register definition.
+ bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::FoldableAsLoad, Type);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Side Effect Analysis
+ //===--------------------------------------------------------------------===//
+
+ /// mayLoad - Return true if this instruction could possibly read memory.
+ /// Instructions with this flag set are not necessarily simple load
+ /// instructions, they may load a value and modify it, for example.
+ bool mayLoad(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::MayLoad, Type);
+ }
+
+
+ /// mayStore - Return true if this instruction could possibly modify memory.
+ /// Instructions with this flag set are not necessarily simple store
+ /// instructions, they may store a modified value based on their operands, or
+ /// may not actually modify anything, for example.
+ bool mayStore(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::MayStore, Type);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Flags that indicate whether an instruction can be modified by a method.
+ //===--------------------------------------------------------------------===//
+
+ /// isCommutable - Return true if this may be a 2- or 3-address
+ /// instruction (of the form "X = op Y, Z, ..."), which produces the same
+ /// result if Y and Z are exchanged. If this flag is set, then the
+ /// TargetInstrInfo::commuteInstruction method may be used to hack on the
+ /// instruction.
+ ///
+ /// Note that this flag may be set on instructions that are only commutable
+ /// sometimes. In these cases, the call to commuteInstruction will fail.
+ /// Also note that some instructions require non-trivial modification to
+ /// commute them.
+ bool isCommutable(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::Commutable, Type);
+ }
+
+ /// isConvertibleTo3Addr - Return true if this is a 2-address instruction
+ /// which can be changed into a 3-address instruction if needed. Doing this
+ /// transformation can be profitable in the register allocator, because it
+ /// means that the instruction can use a 2-address form if possible, but
+ /// degrade into a less efficient form if the source and dest register cannot
+ /// be assigned to the same register. For example, this allows the x86
+ /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
+ /// is the same speed as the shift but has bigger code size.
+ ///
+ /// If this returns true, then the target must implement the
+ /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
+ /// is allowed to fail if the transformation isn't valid for this specific
+ /// instruction (e.g. shl reg, 4 on x86).
+ ///
+ bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::ConvertibleTo3Addr, Type);
+ }
+
+ /// usesCustomInsertionHook - Return true if this instruction requires
+ /// custom insertion support when the DAG scheduler is inserting it into a
+ /// machine basic block. If this is true for the instruction, it basically
+ /// means that it is a pseudo instruction used at SelectionDAG time that is
+ /// expanded out into magic code by the target when MachineInstrs are formed.
+ ///
+ /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
+ /// is used to insert this into the MachineBasicBlock.
+ bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::UsesCustomInserter, Type);
+ }
+
+ /// hasPostISelHook - Return true if this instruction requires *adjustment*
+ /// after instruction selection by calling a target hook. For example, this
+ /// can be used to fill in ARM 's' optional operand depending on whether
+ /// the conditional flag register is used.
+ bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
+ return hasProperty(MCID::HasPostISelHook, Type);
+ }
+
+ /// isRematerializable - Returns true if this instruction is a candidate for
+ /// remat. This flag is deprecated, please don't use it anymore. If this
+ /// flag is set, the isReallyTriviallyReMaterializable() method is called to
+ /// verify the instruction is really rematable.
+ bool isRematerializable(QueryType Type = AllInBundle) const {
+ // It's only possible to re-mat a bundle if all bundled instructions are
+ // re-materializable.
+ return hasProperty(MCID::Rematerializable, Type);
+ }
+
+ /// isAsCheapAsAMove - Returns true if this instruction has the same cost (or
+ /// less) than a move instruction. This is useful during certain types of
+ /// optimizations (e.g., remat during two-address conversion or machine licm)
+ /// where we would like to remat or hoist the instruction, but not if it costs
+ /// more than moving the instruction into the appropriate register. Note, we
+ /// are not marking copies from and to the same register class with this flag.
+ bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
+ // Only returns true for a bundle if all bundled instructions are cheap.
+ // FIXME: This probably requires a target hook.
+ return hasProperty(MCID::CheapAsAMove, Type);
+ }
+
+ /// hasExtraSrcRegAllocReq - Returns true if this instruction source operands
+ /// have special register allocation requirements that are not captured by the
+ /// operand register classes. e.g. ARM::STRD's two source registers must be an
+ /// even / odd pair, ARM::STM registers have to be in ascending order.
+ /// Post-register allocation passes should not attempt to change allocations
+ /// for sources of instructions with this flag.
+ bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
+ }
+
+ /// hasExtraDefRegAllocReq - Returns true if this instruction def operands
+ /// have special register allocation requirements that are not captured by the
+ /// operand register classes. e.g. ARM::LDRD's two def registers must be an
+ /// even / odd pair, ARM::LDM registers have to be in ascending order.
+ /// Post-register allocation passes should not attempt to change allocations
+ /// for definitions of instructions with this flag.
+ bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
+ return hasProperty(MCID::ExtraDefRegAllocReq, Type);
+ }
+
+
+ enum MICheckType {
+ CheckDefs, // Check all operands for equality
+ CheckKillDead, // Check all operands including kill / dead markers
+ IgnoreDefs, // Ignore all definitions
+ IgnoreVRegDefs // Ignore virtual register definitions
+ };
+
+ /// isIdenticalTo - Return true if this instruction is identical to (same
+ /// opcode and same operands as) the specified instruction.
+ bool isIdenticalTo(const MachineInstr *Other,
+ MICheckType Check = CheckDefs) const;
+
+ /// removeFromParent - This method unlinks 'this' from the containing basic
+ /// block, and returns it, but does not delete it.
+ MachineInstr *removeFromParent();
+
+ /// eraseFromParent - This method unlinks 'this' from the containing basic
+ /// block and deletes it.
+ void eraseFromParent();
+
+ /// isLabel - Returns true if the MachineInstr represents a label.
+ ///
+ bool isLabel() const {
+ return getOpcode() == TargetOpcode::PROLOG_LABEL ||
+ getOpcode() == TargetOpcode::EH_LABEL ||
+ getOpcode() == TargetOpcode::GC_LABEL;
+ }
+
+ bool isPrologLabel() const {
+ return getOpcode() == TargetOpcode::PROLOG_LABEL;
+ }
+ bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
+ bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
+ bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
+
+ bool isPHI() const { return getOpcode() == TargetOpcode::PHI; }
+ bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
+ bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
+ bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
+ bool isStackAligningInlineAsm() const;
+ InlineAsm::AsmDialect getInlineAsmDialect() const;
+ bool isInsertSubreg() const {
+ return getOpcode() == TargetOpcode::INSERT_SUBREG;
+ }
+ bool isSubregToReg() const {
+ return getOpcode() == TargetOpcode::SUBREG_TO_REG;
+ }
+ bool isRegSequence() const {
+ return getOpcode() == TargetOpcode::REG_SEQUENCE;
+ }
+ bool isBundle() const {
+ return getOpcode() == TargetOpcode::BUNDLE;
+ }
+ bool isCopy() const {
+ return getOpcode() == TargetOpcode::COPY;
+ }
+ bool isFullCopy() const {
+ return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
+ }
+
+ /// isCopyLike - Return true if the instruction behaves like a copy.
+ /// This does not include native copy instructions.
+ bool isCopyLike() const {
+ return isCopy() || isSubregToReg();
+ }
+
+ /// isIdentityCopy - Return true is the instruction is an identity copy.
+ bool isIdentityCopy() const {
+ return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
+ getOperand(0).getSubReg() == getOperand(1).getSubReg();
+ }
+
+ /// isTransient - Return true if this is a transient instruction that is
+ /// either very likely to be eliminated during register allocation (such as
+ /// copy-like instructions), or if this instruction doesn't have an
+ /// execution-time cost.
+ bool isTransient() const {
+ switch(getOpcode()) {
+ default: return false;
+ // Copy-like instructions are usually eliminated during register allocation.
+ case TargetOpcode::PHI:
+ case TargetOpcode::COPY:
+ case TargetOpcode::INSERT_SUBREG:
+ case TargetOpcode::SUBREG_TO_REG:
+ case TargetOpcode::REG_SEQUENCE:
+ // Pseudo-instructions that don't produce any real output.
+ case TargetOpcode::IMPLICIT_DEF:
+ case TargetOpcode::KILL:
+ case TargetOpcode::PROLOG_LABEL:
+ case TargetOpcode::EH_LABEL:
+ case TargetOpcode::GC_LABEL:
+ case TargetOpcode::DBG_VALUE:
+ return true;
+ }
+ }
+
+ /// getBundleSize - Return the number of instructions inside the MI bundle.
+ unsigned getBundleSize() const;
+
+ /// readsRegister - Return true if the MachineInstr reads the specified
+ /// register. If TargetRegisterInfo is passed, then it also checks if there
+ /// is a read of a super-register.
+ /// This does not count partial redefines of virtual registers as reads:
+ /// %reg1024:6 = OP.
+ bool readsRegister(unsigned Reg, const TargetRegisterInfo *TRI = NULL) const {
+ return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
+ }
+
+ /// readsVirtualRegister - Return true if the MachineInstr reads the specified
+ /// virtual register. Take into account that a partial define is a
+ /// read-modify-write operation.
+ bool readsVirtualRegister(unsigned Reg) const {
+ return readsWritesVirtualRegister(Reg).first;
+ }
+
+ /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
+ /// indicating if this instruction reads or writes Reg. This also considers
+ /// partial defines.
+ /// If Ops is not null, all operand indices for Reg are added.
+ std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
+ SmallVectorImpl<unsigned> *Ops = 0) const;
+
+ /// killsRegister - Return true if the MachineInstr kills the specified
+ /// register. If TargetRegisterInfo is passed, then it also checks if there is
+ /// a kill of a super-register.
+ bool killsRegister(unsigned Reg, const TargetRegisterInfo *TRI = NULL) const {
+ return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
+ }
+
+ /// definesRegister - Return true if the MachineInstr fully defines the
+ /// specified register. If TargetRegisterInfo is passed, then it also checks
+ /// if there is a def of a super-register.
+ /// NOTE: It's ignoring subreg indices on virtual registers.
+ bool definesRegister(unsigned Reg, const TargetRegisterInfo *TRI=NULL) const {
+ return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
+ }
+
+ /// modifiesRegister - Return true if the MachineInstr modifies (fully define
+ /// or partially define) the specified register.
+ /// NOTE: It's ignoring subreg indices on virtual registers.
+ bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
+ return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
+ }
+
+ /// registerDefIsDead - Returns true if the register is dead in this machine
+ /// instruction. If TargetRegisterInfo is passed, then it also checks
+ /// if there is a dead def of a super-register.
+ bool registerDefIsDead(unsigned Reg,
+ const TargetRegisterInfo *TRI = NULL) const {
+ return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
+ }
+
+ /// findRegisterUseOperandIdx() - Returns the operand index that is a use of
+ /// the specific register or -1 if it is not found. It further tightens
+ /// the search criteria to a use that kills the register if isKill is true.
+ int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
+ const TargetRegisterInfo *TRI = NULL) const;
+
+ /// findRegisterUseOperand - Wrapper for findRegisterUseOperandIdx, it returns
+ /// a pointer to the MachineOperand rather than an index.
+ MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
+ const TargetRegisterInfo *TRI = NULL) {
+ int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
+ return (Idx == -1) ? NULL : &getOperand(Idx);
+ }
+
+ /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
+ /// the specified register or -1 if it is not found. If isDead is true, defs
+ /// that are not dead are skipped. If Overlap is true, then it also looks for
+ /// defs that merely overlap the specified register. If TargetRegisterInfo is
+ /// non-null, then it also checks if there is a def of a super-register.
+ /// This may also return a register mask operand when Overlap is true.
+ int findRegisterDefOperandIdx(unsigned Reg,
+ bool isDead = false, bool Overlap = false,
+ const TargetRegisterInfo *TRI = NULL) const;
+
+ /// findRegisterDefOperand - Wrapper for findRegisterDefOperandIdx, it returns
+ /// a pointer to the MachineOperand rather than an index.
+ MachineOperand *findRegisterDefOperand(unsigned Reg, bool isDead = false,
+ const TargetRegisterInfo *TRI = NULL) {
+ int Idx = findRegisterDefOperandIdx(Reg, isDead, false, TRI);
+ return (Idx == -1) ? NULL : &getOperand(Idx);
+ }
+
+ /// findFirstPredOperandIdx() - Find the index of the first operand in the
+ /// operand list that is used to represent the predicate. It returns -1 if
+ /// none is found.
+ int findFirstPredOperandIdx() const;
+
+ /// findInlineAsmFlagIdx() - Find the index of the flag word operand that
+ /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if
+ /// getOperand(OpIdx) does not belong to an inline asm operand group.
+ ///
+ /// If GroupNo is not NULL, it will receive the number of the operand group
+ /// containing OpIdx.
+ ///
+ /// The flag operand is an immediate that can be decoded with methods like
+ /// InlineAsm::hasRegClassConstraint().
+ ///
+ int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = 0) const;
+
+ /// getRegClassConstraint - Compute the static register class constraint for
+ /// operand OpIdx. For normal instructions, this is derived from the
+ /// MCInstrDesc. For inline assembly it is derived from the flag words.
+ ///
+ /// Returns NULL if the static register classs constraint cannot be
+ /// determined.
+ ///
+ const TargetRegisterClass*
+ getRegClassConstraint(unsigned OpIdx,
+ const TargetInstrInfo *TII,
+ const TargetRegisterInfo *TRI) const;
+
+ /// tieOperands - Add a tie between the register operands at DefIdx and
+ /// UseIdx. The tie will cause the register allocator to ensure that the two
+ /// operands are assigned the same physical register.
+ ///
+ /// Tied operands are managed automatically for explicit operands in the
+ /// MCInstrDesc. This method is for exceptional cases like inline asm.
+ void tieOperands(unsigned DefIdx, unsigned UseIdx);
+
+ /// findTiedOperandIdx - Given the index of a tied register operand, find the
+ /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
+ /// index of the tied operand which must exist.
+ unsigned findTiedOperandIdx(unsigned OpIdx) const;
+
+ /// isRegTiedToUseOperand - Given the index of a register def operand,
+ /// check if the register def is tied to a source operand, due to either
+ /// two-address elimination or inline assembly constraints. Returns the
+ /// first tied use operand index by reference if UseOpIdx is not null.
+ bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx = 0) const {
+ const MachineOperand &MO = getOperand(DefOpIdx);
+ if (!MO.isReg() || !MO.isDef() || !MO.isTied())
+ return false;
+ if (UseOpIdx)
+ *UseOpIdx = findTiedOperandIdx(DefOpIdx);
+ return true;
+ }
+
+ /// isRegTiedToDefOperand - Return true if the use operand of the specified
+ /// index is tied to an def operand. It also returns the def operand index by
+ /// reference if DefOpIdx is not null.
+ bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx = 0) const {
+ const MachineOperand &MO = getOperand(UseOpIdx);
+ if (!MO.isReg() || !MO.isUse() || !MO.isTied())
+ return false;
+ if (DefOpIdx)
+ *DefOpIdx = findTiedOperandIdx(UseOpIdx);
+ return true;
+ }
+
+ /// clearKillInfo - Clears kill flags on all operands.
+ ///
+ void clearKillInfo();
+
+ /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
+ ///
+ void copyKillDeadInfo(const MachineInstr *MI);
+
+ /// copyPredicates - Copies predicate operand(s) from MI.
+ void copyPredicates(const MachineInstr *MI);
+
+ /// substituteRegister - Replace all occurrences of FromReg with ToReg:SubIdx,
+ /// properly composing subreg indices where necessary.
+ void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
+ const TargetRegisterInfo &RegInfo);
+
+ /// addRegisterKilled - We have determined MI kills a register. Look for the
+ /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
+ /// add a implicit operand if it's not found. Returns true if the operand
+ /// exists / is added.
+ bool addRegisterKilled(unsigned IncomingReg,
+ const TargetRegisterInfo *RegInfo,
+ bool AddIfNotFound = false);
+
+ /// clearRegisterKills - Clear all kill flags affecting Reg. If RegInfo is
+ /// provided, this includes super-register kills.
+ void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
+
+ /// addRegisterDead - We have determined MI defined a register without a use.
+ /// Look for the operand that defines it and mark it as IsDead. If
+ /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
+ /// true if the operand exists / is added.
+ bool addRegisterDead(unsigned IncomingReg, const TargetRegisterInfo *RegInfo,
+ bool AddIfNotFound = false);
+
+ /// addRegisterDefined - We have determined MI defines a register. Make sure
+ /// there is an operand defining Reg.
+ void addRegisterDefined(unsigned IncomingReg,
+ const TargetRegisterInfo *RegInfo = 0);
+
+ /// setPhysRegsDeadExcept - Mark every physreg used by this instruction as
+ /// dead except those in the UsedRegs list.
+ ///
+ /// On instructions with register mask operands, also add implicit-def
+ /// operands for all registers in UsedRegs.
+ void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
+ const TargetRegisterInfo &TRI);
+
+ /// isSafeToMove - Return true if it is safe to move this instruction. If
+ /// SawStore is set to true, it means that there is a store (or call) between
+ /// the instruction's location and its intended destination.
+ bool isSafeToMove(const TargetInstrInfo *TII, AliasAnalysis *AA,
+ bool &SawStore) const;
+
+ /// isSafeToReMat - Return true if it's safe to rematerialize the specified
+ /// instruction which defined the specified register instead of copying it.
+ bool isSafeToReMat(const TargetInstrInfo *TII, AliasAnalysis *AA,
+ unsigned DstReg) const;
+
+ /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
+ /// or volatile memory reference, or if the information describing the memory
+ /// reference is not available. Return false if it is known to have no
+ /// ordered or volatile memory references.
+ bool hasOrderedMemoryRef() const;
+
+ /// isInvariantLoad - Return true if this instruction is loading from a
+ /// location whose value is invariant across the function. For example,
+ /// loading a value from the constant pool or from the argument area of
+ /// a function if it does not change. This should only return true of *all*
+ /// loads the instruction does are invariant (if it does multiple loads).
+ bool isInvariantLoad(AliasAnalysis *AA) const;
+
+ /// isConstantValuePHI - If the specified instruction is a PHI that always
+ /// merges together the same virtual register, return the register, otherwise
+ /// return 0.
+ unsigned isConstantValuePHI() const;
+
+ /// hasUnmodeledSideEffects - Return true if this instruction has side
+ /// effects that are not modeled by mayLoad / mayStore, etc.
+ /// For all instructions, the property is encoded in MCInstrDesc::Flags
+ /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
+ /// INLINEASM instruction, in which case the side effect property is encoded
+ /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
+ ///
+ bool hasUnmodeledSideEffects() const;
+
+ /// allDefsAreDead - Return true if all the defs of this instruction are dead.
+ ///
+ bool allDefsAreDead() const;
+
+ /// copyImplicitOps - Copy implicit register operands from specified
+ /// instruction to this instruction.
+ void copyImplicitOps(const MachineInstr *MI);
+
+ //
+ // Debugging support
+ //
+ void print(raw_ostream &OS, const TargetMachine *TM = 0) const;
+ void dump() const;
+
+ //===--------------------------------------------------------------------===//
+ // Accessors used to build up machine instructions.
+
+ /// addOperand - Add the specified operand to the instruction. If it is an
+ /// implicit operand, it is added to the end of the operand list. If it is
+ /// an explicit operand it is added at the end of the explicit operand list
+ /// (before the first implicit operand).
+ void addOperand(const MachineOperand &Op);
+
+ /// setDesc - Replace the instruction descriptor (thus opcode) of
+ /// the current instruction with a new one.
+ ///
+ void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
+
+ /// setDebugLoc - Replace current source information with new such.
+ /// Avoid using this, the constructor argument is preferable.
+ ///
+ void setDebugLoc(const DebugLoc dl) { debugLoc = dl; }
+
+ /// RemoveOperand - Erase an operand from an instruction, leaving it with one
+ /// fewer operand than it started with.
+ ///
+ void RemoveOperand(unsigned i);
+
+ /// addMemOperand - Add a MachineMemOperand to the machine instruction.
+ /// This function should be used only occasionally. The setMemRefs function
+ /// is the primary method for setting up a MachineInstr's MemRefs list.
+ void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
+
+ /// setMemRefs - Assign this MachineInstr's memory reference descriptor
+ /// list. This does not transfer ownership.
+ void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
+ MemRefs = NewMemRefs;
+ NumMemRefs = NewMemRefsEnd - NewMemRefs;
+ }
+
+private:
+ /// getRegInfo - If this instruction is embedded into a MachineFunction,
+ /// return the MachineRegisterInfo object for the current function, otherwise
+ /// return null.
+ MachineRegisterInfo *getRegInfo();
+
+ /// untieRegOperand - Break any tie involving OpIdx.
+ void untieRegOperand(unsigned OpIdx) {
+ MachineOperand &MO = getOperand(OpIdx);
+ if (MO.isReg() && MO.isTied()) {
+ getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
+ MO.TiedTo = 0;
+ }
+ }
+
+ /// addImplicitDefUseOperands - Add all implicit def and use operands to
+ /// this instruction.
+ void addImplicitDefUseOperands();
+
+ /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
+ /// this instruction from their respective use lists. This requires that the
+ /// operands already be on their use lists.
+ void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
+
+ /// AddRegOperandsToUseLists - Add all of the register operands in
+ /// this instruction from their respective use lists. This requires that the
+ /// operands not be on their use lists yet.
+ void AddRegOperandsToUseLists(MachineRegisterInfo&);
+
+ /// hasPropertyInBundle - Slow path for hasProperty when we're dealing with a
+ /// bundle.
+ bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
+};
+
+/// MachineInstrExpressionTrait - Special DenseMapInfo traits to compare
+/// MachineInstr* by *value* of the instruction rather than by pointer value.
+/// The hashing and equality testing functions ignore definitions so this is
+/// useful for CSE, etc.
+struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
+ static inline MachineInstr *getEmptyKey() {
+ return 0;
+ }
+
+ static inline MachineInstr *getTombstoneKey() {
+ return reinterpret_cast<MachineInstr*>(-1);
+ }
+
+ static unsigned getHashValue(const MachineInstr* const &MI);
+
+ static bool isEqual(const MachineInstr* const &LHS,
+ const MachineInstr* const &RHS) {
+ if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
+ LHS == getEmptyKey() || LHS == getTombstoneKey())
+ return LHS == RHS;
+ return LHS->isIdenticalTo(RHS, MachineInstr::IgnoreVRegDefs);
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// Debugging Support
+
+inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
+ MI.print(OS);
+ return OS;
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineInstrBuilder.h b/include/llvm/CodeGen/MachineInstrBuilder.h
new file mode 100644
index 00000000000..654361f9d42
--- /dev/null
+++ b/include/llvm/CodeGen/MachineInstrBuilder.h
@@ -0,0 +1,327 @@
+//===-- CodeGen/MachineInstBuilder.h - Simplify creation of MIs -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file exposes a function named BuildMI, which is useful for dramatically
+// simplifying how MachineInstr's are created. It allows use of code like this:
+//
+// M = BuildMI(X86::ADDrr8, 2).addReg(argVal1).addReg(argVal2);
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEINSTRBUILDER_H
+#define LLVM_CODEGEN_MACHINEINSTRBUILDER_H
+
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/Support/ErrorHandling.h"
+
+namespace llvm {
+
+class MCInstrDesc;
+class MDNode;
+
+namespace RegState {
+ enum {
+ Define = 0x2,
+ Implicit = 0x4,
+ Kill = 0x8,
+ Dead = 0x10,
+ Undef = 0x20,
+ EarlyClobber = 0x40,
+ Debug = 0x80,
+ InternalRead = 0x100,
+ DefineNoRead = Define | Undef,
+ ImplicitDefine = Implicit | Define,
+ ImplicitKill = Implicit | Kill
+ };
+}
+
+class MachineInstrBuilder {
+ MachineInstr *MI;
+public:
+ MachineInstrBuilder() : MI(0) {}
+ explicit MachineInstrBuilder(MachineInstr *mi) : MI(mi) {}
+
+ /// Allow automatic conversion to the machine instruction we are working on.
+ ///
+ operator MachineInstr*() const { return MI; }
+ MachineInstr *operator->() const { return MI; }
+ operator MachineBasicBlock::iterator() const { return MI; }
+
+ /// addReg - Add a new virtual register operand...
+ ///
+ const
+ MachineInstrBuilder &addReg(unsigned RegNo, unsigned flags = 0,
+ unsigned SubReg = 0) const {
+ assert((flags & 0x1) == 0 &&
+ "Passing in 'true' to addReg is forbidden! Use enums instead.");
+ MI->addOperand(MachineOperand::CreateReg(RegNo,
+ flags & RegState::Define,
+ flags & RegState::Implicit,
+ flags & RegState::Kill,
+ flags & RegState::Dead,
+ flags & RegState::Undef,
+ flags & RegState::EarlyClobber,
+ SubReg,
+ flags & RegState::Debug,
+ flags & RegState::InternalRead));
+ return *this;
+ }
+
+ /// addImm - Add a new immediate operand.
+ ///
+ const MachineInstrBuilder &addImm(int64_t Val) const {
+ MI->addOperand(MachineOperand::CreateImm(Val));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addCImm(const ConstantInt *Val) const {
+ MI->addOperand(MachineOperand::CreateCImm(Val));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addFPImm(const ConstantFP *Val) const {
+ MI->addOperand(MachineOperand::CreateFPImm(Val));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addMBB(MachineBasicBlock *MBB,
+ unsigned char TargetFlags = 0) const {
+ MI->addOperand(MachineOperand::CreateMBB(MBB, TargetFlags));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addFrameIndex(int Idx) const {
+ MI->addOperand(MachineOperand::CreateFI(Idx));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addConstantPoolIndex(unsigned Idx,
+ int Offset = 0,
+ unsigned char TargetFlags = 0) const {
+ MI->addOperand(MachineOperand::CreateCPI(Idx, Offset, TargetFlags));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addTargetIndex(unsigned Idx, int64_t Offset = 0,
+ unsigned char TargetFlags = 0) const {
+ MI->addOperand(MachineOperand::CreateTargetIndex(Idx, Offset, TargetFlags));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addJumpTableIndex(unsigned Idx,
+ unsigned char TargetFlags = 0) const {
+ MI->addOperand(MachineOperand::CreateJTI(Idx, TargetFlags));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addGlobalAddress(const GlobalValue *GV,
+ int64_t Offset = 0,
+ unsigned char TargetFlags = 0) const {
+ MI->addOperand(MachineOperand::CreateGA(GV, Offset, TargetFlags));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addExternalSymbol(const char *FnName,
+ unsigned char TargetFlags = 0) const {
+ MI->addOperand(MachineOperand::CreateES(FnName, TargetFlags));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addRegMask(const uint32_t *Mask) const {
+ MI->addOperand(MachineOperand::CreateRegMask(Mask));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addMemOperand(MachineMemOperand *MMO) const {
+ MI->addMemOperand(*MI->getParent()->getParent(), MMO);
+ return *this;
+ }
+
+ const MachineInstrBuilder &setMemRefs(MachineInstr::mmo_iterator b,
+ MachineInstr::mmo_iterator e) const {
+ MI->setMemRefs(b, e);
+ return *this;
+ }
+
+
+ const MachineInstrBuilder &addOperand(const MachineOperand &MO) const {
+ MI->addOperand(MO);
+ return *this;
+ }
+
+ const MachineInstrBuilder &addMetadata(const MDNode *MD) const {
+ MI->addOperand(MachineOperand::CreateMetadata(MD));
+ return *this;
+ }
+
+ const MachineInstrBuilder &addSym(MCSymbol *Sym) const {
+ MI->addOperand(MachineOperand::CreateMCSymbol(Sym));
+ return *this;
+ }
+
+ const MachineInstrBuilder &setMIFlags(unsigned Flags) const {
+ MI->setFlags(Flags);
+ return *this;
+ }
+
+ const MachineInstrBuilder &setMIFlag(MachineInstr::MIFlag Flag) const {
+ MI->setFlag(Flag);
+ return *this;
+ }
+
+ // Add a displacement from an existing MachineOperand with an added offset.
+ const MachineInstrBuilder &addDisp(const MachineOperand &Disp,
+ int64_t off) const {
+ switch (Disp.getType()) {
+ default:
+ llvm_unreachable("Unhandled operand type in addDisp()");
+ case MachineOperand::MO_Immediate:
+ return addImm(Disp.getImm() + off);
+ case MachineOperand::MO_GlobalAddress:
+ return addGlobalAddress(Disp.getGlobal(), Disp.getOffset() + off);
+ }
+ }
+};
+
+/// BuildMI - Builder interface. Specify how to create the initial instruction
+/// itself.
+///
+inline MachineInstrBuilder BuildMI(MachineFunction &MF,
+ DebugLoc DL,
+ const MCInstrDesc &MCID) {
+ return MachineInstrBuilder(MF.CreateMachineInstr(MCID, DL));
+}
+
+/// BuildMI - This version of the builder sets up the first operand as a
+/// destination virtual register.
+///
+inline MachineInstrBuilder BuildMI(MachineFunction &MF,
+ DebugLoc DL,
+ const MCInstrDesc &MCID,
+ unsigned DestReg) {
+ return MachineInstrBuilder(MF.CreateMachineInstr(MCID, DL))
+ .addReg(DestReg, RegState::Define);
+}
+
+/// BuildMI - This version of the builder inserts the newly-built
+/// instruction before the given position in the given MachineBasicBlock, and
+/// sets up the first operand as a destination virtual register.
+///
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+ MachineBasicBlock::iterator I,
+ DebugLoc DL,
+ const MCInstrDesc &MCID,
+ unsigned DestReg) {
+ MachineInstr *MI = BB.getParent()->CreateMachineInstr(MCID, DL);
+ BB.insert(I, MI);
+ return MachineInstrBuilder(MI).addReg(DestReg, RegState::Define);
+}
+
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+ MachineBasicBlock::instr_iterator I,
+ DebugLoc DL,
+ const MCInstrDesc &MCID,
+ unsigned DestReg) {
+ MachineInstr *MI = BB.getParent()->CreateMachineInstr(MCID, DL);
+ BB.insert(I, MI);
+ return MachineInstrBuilder(MI).addReg(DestReg, RegState::Define);
+}
+
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+ MachineInstr *I,
+ DebugLoc DL,
+ const MCInstrDesc &MCID,
+ unsigned DestReg) {
+ if (I->isInsideBundle()) {
+ MachineBasicBlock::instr_iterator MII = I;
+ return BuildMI(BB, MII, DL, MCID, DestReg);
+ }
+
+ MachineBasicBlock::iterator MII = I;
+ return BuildMI(BB, MII, DL, MCID, DestReg);
+}
+
+/// BuildMI - This version of the builder inserts the newly-built
+/// instruction before the given position in the given MachineBasicBlock, and
+/// does NOT take a destination register.
+///
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+ MachineBasicBlock::iterator I,
+ DebugLoc DL,
+ const MCInstrDesc &MCID) {
+ MachineInstr *MI = BB.getParent()->CreateMachineInstr(MCID, DL);
+ BB.insert(I, MI);
+ return MachineInstrBuilder(MI);
+}
+
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+ MachineBasicBlock::instr_iterator I,
+ DebugLoc DL,
+ const MCInstrDesc &MCID) {
+ MachineInstr *MI = BB.getParent()->CreateMachineInstr(MCID, DL);
+ BB.insert(I, MI);
+ return MachineInstrBuilder(MI);
+}
+
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+ MachineInstr *I,
+ DebugLoc DL,
+ const MCInstrDesc &MCID) {
+ if (I->isInsideBundle()) {
+ MachineBasicBlock::instr_iterator MII = I;
+ return BuildMI(BB, MII, DL, MCID);
+ }
+
+ MachineBasicBlock::iterator MII = I;
+ return BuildMI(BB, MII, DL, MCID);
+}
+
+/// BuildMI - This version of the builder inserts the newly-built
+/// instruction at the end of the given MachineBasicBlock, and does NOT take a
+/// destination register.
+///
+inline MachineInstrBuilder BuildMI(MachineBasicBlock *BB,
+ DebugLoc DL,
+ const MCInstrDesc &MCID) {
+ return BuildMI(*BB, BB->end(), DL, MCID);
+}
+
+/// BuildMI - This version of the builder inserts the newly-built
+/// instruction at the end of the given MachineBasicBlock, and sets up the first
+/// operand as a destination virtual register.
+///
+inline MachineInstrBuilder BuildMI(MachineBasicBlock *BB,
+ DebugLoc DL,
+ const MCInstrDesc &MCID,
+ unsigned DestReg) {
+ return BuildMI(*BB, BB->end(), DL, MCID, DestReg);
+}
+
+inline unsigned getDefRegState(bool B) {
+ return B ? RegState::Define : 0;
+}
+inline unsigned getImplRegState(bool B) {
+ return B ? RegState::Implicit : 0;
+}
+inline unsigned getKillRegState(bool B) {
+ return B ? RegState::Kill : 0;
+}
+inline unsigned getDeadRegState(bool B) {
+ return B ? RegState::Dead : 0;
+}
+inline unsigned getUndefRegState(bool B) {
+ return B ? RegState::Undef : 0;
+}
+inline unsigned getInternalReadRegState(bool B) {
+ return B ? RegState::InternalRead : 0;
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineInstrBundle.h b/include/llvm/CodeGen/MachineInstrBundle.h
new file mode 100644
index 00000000000..854ba06209c
--- /dev/null
+++ b/include/llvm/CodeGen/MachineInstrBundle.h
@@ -0,0 +1,237 @@
+//===-- CodeGen/MachineInstBundle.h - MI bundle utilities -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file provide utility functions to manipulate machine instruction
+// bundles.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEINSTRBUNDLE_H
+#define LLVM_CODEGEN_MACHINEINSTRBUNDLE_H
+
+#include "llvm/CodeGen/MachineBasicBlock.h"
+
+namespace llvm {
+
+/// finalizeBundle - Finalize a machine instruction bundle which includes
+/// a sequence of instructions starting from FirstMI to LastMI (exclusive).
+/// This routine adds a BUNDLE instruction to represent the bundle, it adds
+/// IsInternalRead markers to MachineOperands which are defined inside the
+/// bundle, and it copies externally visible defs and uses to the BUNDLE
+/// instruction.
+void finalizeBundle(MachineBasicBlock &MBB,
+ MachineBasicBlock::instr_iterator FirstMI,
+ MachineBasicBlock::instr_iterator LastMI);
+
+/// finalizeBundle - Same functionality as the previous finalizeBundle except
+/// the last instruction in the bundle is not provided as an input. This is
+/// used in cases where bundles are pre-determined by marking instructions
+/// with 'InsideBundle' marker. It returns the MBB instruction iterator that
+/// points to the end of the bundle.
+MachineBasicBlock::instr_iterator finalizeBundle(MachineBasicBlock &MBB,
+ MachineBasicBlock::instr_iterator FirstMI);
+
+/// finalizeBundles - Finalize instruction bundles in the specified
+/// MachineFunction. Return true if any bundles are finalized.
+bool finalizeBundles(MachineFunction &MF);
+
+/// getBundleStart - Returns the first instruction in the bundle containing MI.
+///
+inline MachineInstr *getBundleStart(MachineInstr *MI) {
+ MachineBasicBlock::instr_iterator I = MI;
+ while (I->isInsideBundle())
+ --I;
+ return I;
+}
+
+inline const MachineInstr *getBundleStart(const MachineInstr *MI) {
+ MachineBasicBlock::const_instr_iterator I = MI;
+ while (I->isInsideBundle())
+ --I;
+ return I;
+}
+
+//===----------------------------------------------------------------------===//
+// MachineOperand iterator
+//
+
+/// MachineOperandIteratorBase - Iterator that can visit all operands on a
+/// MachineInstr, or all operands on a bundle of MachineInstrs. This class is
+/// not intended to be used directly, use one of the sub-classes instead.
+///
+/// Intended use:
+///
+/// for (MIBundleOperands MIO(MI); MIO.isValid(); ++MIO) {
+/// if (!MIO->isReg())
+/// continue;
+/// ...
+/// }
+///
+class MachineOperandIteratorBase {
+ MachineBasicBlock::instr_iterator InstrI, InstrE;
+ MachineInstr::mop_iterator OpI, OpE;
+
+ // If the operands on InstrI are exhausted, advance InstrI to the next
+ // bundled instruction with operands.
+ void advance() {
+ while (OpI == OpE) {
+ // Don't advance off the basic block, or into a new bundle.
+ if (++InstrI == InstrE || !InstrI->isInsideBundle())
+ break;
+ OpI = InstrI->operands_begin();
+ OpE = InstrI->operands_end();
+ }
+ }
+
+protected:
+ /// MachineOperandIteratorBase - Create an iterator that visits all operands
+ /// on MI, or all operands on every instruction in the bundle containing MI.
+ ///
+ /// @param MI The instruction to examine.
+ /// @param WholeBundle When true, visit all operands on the entire bundle.
+ ///
+ explicit MachineOperandIteratorBase(MachineInstr *MI, bool WholeBundle) {
+ if (WholeBundle) {
+ InstrI = getBundleStart(MI);
+ InstrE = MI->getParent()->instr_end();
+ } else {
+ InstrI = InstrE = MI;
+ ++InstrE;
+ }
+ OpI = InstrI->operands_begin();
+ OpE = InstrI->operands_end();
+ if (WholeBundle)
+ advance();
+ }
+
+ MachineOperand &deref() const { return *OpI; }
+
+public:
+ /// isValid - Returns true until all the operands have been visited.
+ bool isValid() const { return OpI != OpE; }
+
+ /// Preincrement. Move to the next operand.
+ void operator++() {
+ assert(isValid() && "Cannot advance MIOperands beyond the last operand");
+ ++OpI;
+ advance();
+ }
+
+ /// getOperandNo - Returns the number of the current operand relative to its
+ /// instruction.
+ ///
+ unsigned getOperandNo() const {
+ return OpI - InstrI->operands_begin();
+ }
+
+ /// VirtRegInfo - Information about a virtual register used by a set of operands.
+ ///
+ struct VirtRegInfo {
+ /// Reads - One of the operands read the virtual register. This does not
+ /// include <undef> or <internal> use operands, see MO::readsReg().
+ bool Reads;
+
+ /// Writes - One of the operands writes the virtual register.
+ bool Writes;
+
+ /// Tied - Uses and defs must use the same register. This can be because of
+ /// a two-address constraint, or there may be a partial redefinition of a
+ /// sub-register.
+ bool Tied;
+ };
+
+ /// PhysRegInfo - Information about a physical register used by a set of
+ /// operands.
+ struct PhysRegInfo {
+ /// Clobbers - Reg or an overlapping register is defined, or a regmask
+ /// clobbers Reg.
+ bool Clobbers;
+
+ /// Defines - Reg or a super-register is defined.
+ bool Defines;
+
+ /// DefinesOverlap - Reg or an overlapping register is defined.
+ bool DefinesOverlap;
+
+ /// Reads - Read or a super-register is read.
+ bool Reads;
+
+ /// ReadsOverlap - Reg or an overlapping register is read.
+ bool ReadsOverlap;
+
+ /// DefinesDead - All defs of a Reg or a super-register are dead.
+ bool DefinesDead;
+
+ /// There is a kill of Reg or a super-register.
+ bool Kills;
+ };
+
+ /// analyzeVirtReg - Analyze how the current instruction or bundle uses a
+ /// virtual register. This function should not be called after operator++(),
+ /// it expects a fresh iterator.
+ ///
+ /// @param Reg The virtual register to analyze.
+ /// @param Ops When set, this vector will receive an (MI, OpNum) entry for
+ /// each operand referring to Reg.
+ /// @returns A filled-in RegInfo struct.
+ VirtRegInfo analyzeVirtReg(unsigned Reg,
+ SmallVectorImpl<std::pair<MachineInstr*, unsigned> > *Ops = 0);
+
+ /// analyzePhysReg - Analyze how the current instruction or bundle uses a
+ /// physical register. This function should not be called after operator++(),
+ /// it expects a fresh iterator.
+ ///
+ /// @param Reg The physical register to analyze.
+ /// @returns A filled-in PhysRegInfo struct.
+ PhysRegInfo analyzePhysReg(unsigned Reg, const TargetRegisterInfo *TRI);
+};
+
+/// MIOperands - Iterate over operands of a single instruction.
+///
+class MIOperands : public MachineOperandIteratorBase {
+public:
+ MIOperands(MachineInstr *MI) : MachineOperandIteratorBase(MI, false) {}
+ MachineOperand &operator* () const { return deref(); }
+ MachineOperand *operator->() const { return &deref(); }
+};
+
+/// ConstMIOperands - Iterate over operands of a single const instruction.
+///
+class ConstMIOperands : public MachineOperandIteratorBase {
+public:
+ ConstMIOperands(const MachineInstr *MI)
+ : MachineOperandIteratorBase(const_cast<MachineInstr*>(MI), false) {}
+ const MachineOperand &operator* () const { return deref(); }
+ const MachineOperand *operator->() const { return &deref(); }
+};
+
+/// MIBundleOperands - Iterate over all operands in a bundle of machine
+/// instructions.
+///
+class MIBundleOperands : public MachineOperandIteratorBase {
+public:
+ MIBundleOperands(MachineInstr *MI) : MachineOperandIteratorBase(MI, true) {}
+ MachineOperand &operator* () const { return deref(); }
+ MachineOperand *operator->() const { return &deref(); }
+};
+
+/// ConstMIBundleOperands - Iterate over all operands in a const bundle of
+/// machine instructions.
+///
+class ConstMIBundleOperands : public MachineOperandIteratorBase {
+public:
+ ConstMIBundleOperands(const MachineInstr *MI)
+ : MachineOperandIteratorBase(const_cast<MachineInstr*>(MI), true) {}
+ const MachineOperand &operator* () const { return deref(); }
+ const MachineOperand *operator->() const { return &deref(); }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineJumpTableInfo.h b/include/llvm/CodeGen/MachineJumpTableInfo.h
new file mode 100644
index 00000000000..f7c4e8642d5
--- /dev/null
+++ b/include/llvm/CodeGen/MachineJumpTableInfo.h
@@ -0,0 +1,130 @@
+//===-- CodeGen/MachineJumpTableInfo.h - Abstract Jump Tables --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The MachineJumpTableInfo class keeps track of jump tables referenced by
+// lowered switch instructions in the MachineFunction.
+//
+// Instructions reference the address of these jump tables through the use of
+// MO_JumpTableIndex values. When emitting assembly or machine code, these
+// virtual address references are converted to refer to the address of the
+// function jump tables.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEJUMPTABLEINFO_H
+#define LLVM_CODEGEN_MACHINEJUMPTABLEINFO_H
+
+#include <vector>
+#include <cassert>
+
+namespace llvm {
+
+class MachineBasicBlock;
+class TargetData;
+class raw_ostream;
+
+/// MachineJumpTableEntry - One jump table in the jump table info.
+///
+struct MachineJumpTableEntry {
+ /// MBBs - The vector of basic blocks from which to create the jump table.
+ std::vector<MachineBasicBlock*> MBBs;
+
+ explicit MachineJumpTableEntry(const std::vector<MachineBasicBlock*> &M)
+ : MBBs(M) {}
+};
+
+class MachineJumpTableInfo {
+public:
+ /// JTEntryKind - This enum indicates how each entry of the jump table is
+ /// represented and emitted.
+ enum JTEntryKind {
+ /// EK_BlockAddress - Each entry is a plain address of block, e.g.:
+ /// .word LBB123
+ EK_BlockAddress,
+
+ /// EK_GPRel64BlockAddress - Each entry is an address of block, encoded
+ /// with a relocation as gp-relative, e.g.:
+ /// .gpdword LBB123
+ EK_GPRel64BlockAddress,
+
+ /// EK_GPRel32BlockAddress - Each entry is an address of block, encoded
+ /// with a relocation as gp-relative, e.g.:
+ /// .gprel32 LBB123
+ EK_GPRel32BlockAddress,
+
+ /// EK_LabelDifference32 - Each entry is the address of the block minus
+ /// the address of the jump table. This is used for PIC jump tables where
+ /// gprel32 is not supported. e.g.:
+ /// .word LBB123 - LJTI1_2
+ /// If the .set directive is supported, this is emitted as:
+ /// .set L4_5_set_123, LBB123 - LJTI1_2
+ /// .word L4_5_set_123
+ EK_LabelDifference32,
+
+ /// EK_Inline - Jump table entries are emitted inline at their point of
+ /// use. It is the responsibility of the target to emit the entries.
+ EK_Inline,
+
+ /// EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the
+ /// TargetLowering::LowerCustomJumpTableEntry hook.
+ EK_Custom32
+ };
+private:
+ JTEntryKind EntryKind;
+ std::vector<MachineJumpTableEntry> JumpTables;
+public:
+ explicit MachineJumpTableInfo(JTEntryKind Kind): EntryKind(Kind) {}
+
+ JTEntryKind getEntryKind() const { return EntryKind; }
+
+ /// getEntrySize - Return the size of each entry in the jump table.
+ unsigned getEntrySize(const TargetData &TD) const;
+ /// getEntryAlignment - Return the alignment of each entry in the jump table.
+ unsigned getEntryAlignment(const TargetData &TD) const;
+
+ /// createJumpTableIndex - Create a new jump table.
+ ///
+ unsigned createJumpTableIndex(const std::vector<MachineBasicBlock*> &DestBBs);
+
+ /// isEmpty - Return true if there are no jump tables.
+ ///
+ bool isEmpty() const { return JumpTables.empty(); }
+
+ const std::vector<MachineJumpTableEntry> &getJumpTables() const {
+ return JumpTables;
+ }
+
+ /// RemoveJumpTable - Mark the specific index as being dead. This will
+ /// prevent it from being emitted.
+ void RemoveJumpTable(unsigned Idx) {
+ JumpTables[Idx].MBBs.clear();
+ }
+
+ /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
+ /// the jump tables to branch to New instead.
+ bool ReplaceMBBInJumpTables(MachineBasicBlock *Old, MachineBasicBlock *New);
+
+ /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
+ /// the jump table to branch to New instead.
+ bool ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old,
+ MachineBasicBlock *New);
+
+ /// print - Used by the MachineFunction printer to print information about
+ /// jump tables. Implemented in MachineFunction.cpp
+ ///
+ void print(raw_ostream &OS) const;
+
+ /// dump - Call to stderr.
+ ///
+ void dump() const;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineLoopInfo.h b/include/llvm/CodeGen/MachineLoopInfo.h
new file mode 100644
index 00000000000..d53f041128a
--- /dev/null
+++ b/include/llvm/CodeGen/MachineLoopInfo.h
@@ -0,0 +1,190 @@
+//===- llvm/CodeGen/MachineLoopInfo.h - Natural Loop Calculator -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MachineLoopInfo class that is used to identify natural
+// loops and determine the loop depth of various nodes of the CFG. Note that
+// natural loops may actually be several loops that share the same header node.
+//
+// This analysis calculates the nesting structure of loops in a function. For
+// each natural loop identified, this analysis identifies natural loops
+// contained entirely within the loop and the basic blocks the make up the loop.
+//
+// It can calculate on the fly various bits of information, for example:
+//
+// * whether there is a preheader for the loop
+// * the number of back edges to the header
+// * whether or not a particular block branches out of the loop
+// * the successor blocks of the loop
+// * the loop depth
+// * the trip count
+// * etc...
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINE_LOOP_INFO_H
+#define LLVM_CODEGEN_MACHINE_LOOP_INFO_H
+
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/Analysis/LoopInfo.h"
+
+namespace llvm {
+
+// Implementation in LoopInfoImpl.h
+#ifdef __GNUC__
+class MachineLoop;
+__extension__ extern template class LoopBase<MachineBasicBlock, MachineLoop>;
+#endif
+
+class MachineLoop : public LoopBase<MachineBasicBlock, MachineLoop> {
+public:
+ MachineLoop();
+
+ /// getTopBlock - Return the "top" block in the loop, which is the first
+ /// block in the linear layout, ignoring any parts of the loop not
+ /// contiguous with the part the contains the header.
+ MachineBasicBlock *getTopBlock();
+
+ /// getBottomBlock - Return the "bottom" block in the loop, which is the last
+ /// block in the linear layout, ignoring any parts of the loop not
+ /// contiguous with the part the contains the header.
+ MachineBasicBlock *getBottomBlock();
+
+ void dump() const;
+
+private:
+ friend class LoopInfoBase<MachineBasicBlock, MachineLoop>;
+ explicit MachineLoop(MachineBasicBlock *MBB)
+ : LoopBase<MachineBasicBlock, MachineLoop>(MBB) {}
+};
+
+// Implementation in LoopInfoImpl.h
+#ifdef __GNUC__
+__extension__ extern template
+class LoopInfoBase<MachineBasicBlock, MachineLoop>;
+#endif
+
+class MachineLoopInfo : public MachineFunctionPass {
+ LoopInfoBase<MachineBasicBlock, MachineLoop> LI;
+ friend class LoopBase<MachineBasicBlock, MachineLoop>;
+
+ void operator=(const MachineLoopInfo &) LLVM_DELETED_FUNCTION;
+ MachineLoopInfo(const MachineLoopInfo &) LLVM_DELETED_FUNCTION;
+
+public:
+ static char ID; // Pass identification, replacement for typeid
+
+ MachineLoopInfo() : MachineFunctionPass(ID) {
+ initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
+ }
+
+ LoopInfoBase<MachineBasicBlock, MachineLoop>& getBase() { return LI; }
+
+ /// iterator/begin/end - The interface to the top-level loops in the current
+ /// function.
+ ///
+ typedef LoopInfoBase<MachineBasicBlock, MachineLoop>::iterator iterator;
+ inline iterator begin() const { return LI.begin(); }
+ inline iterator end() const { return LI.end(); }
+ bool empty() const { return LI.empty(); }
+
+ /// getLoopFor - Return the inner most loop that BB lives in. If a basic
+ /// block is in no loop (for example the entry node), null is returned.
+ ///
+ inline MachineLoop *getLoopFor(const MachineBasicBlock *BB) const {
+ return LI.getLoopFor(BB);
+ }
+
+ /// operator[] - same as getLoopFor...
+ ///
+ inline const MachineLoop *operator[](const MachineBasicBlock *BB) const {
+ return LI.getLoopFor(BB);
+ }
+
+ /// getLoopDepth - Return the loop nesting level of the specified block...
+ ///
+ inline unsigned getLoopDepth(const MachineBasicBlock *BB) const {
+ return LI.getLoopDepth(BB);
+ }
+
+ // isLoopHeader - True if the block is a loop header node
+ inline bool isLoopHeader(MachineBasicBlock *BB) const {
+ return LI.isLoopHeader(BB);
+ }
+
+ /// runOnFunction - Calculate the natural loop information.
+ ///
+ virtual bool runOnMachineFunction(MachineFunction &F);
+
+ virtual void releaseMemory() { LI.releaseMemory(); }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ /// removeLoop - This removes the specified top-level loop from this loop info
+ /// object. The loop is not deleted, as it will presumably be inserted into
+ /// another loop.
+ inline MachineLoop *removeLoop(iterator I) { return LI.removeLoop(I); }
+
+ /// changeLoopFor - Change the top-level loop that contains BB to the
+ /// specified loop. This should be used by transformations that restructure
+ /// the loop hierarchy tree.
+ inline void changeLoopFor(MachineBasicBlock *BB, MachineLoop *L) {
+ LI.changeLoopFor(BB, L);
+ }
+
+ /// changeTopLevelLoop - Replace the specified loop in the top-level loops
+ /// list with the indicated loop.
+ inline void changeTopLevelLoop(MachineLoop *OldLoop, MachineLoop *NewLoop) {
+ LI.changeTopLevelLoop(OldLoop, NewLoop);
+ }
+
+ /// addTopLevelLoop - This adds the specified loop to the collection of
+ /// top-level loops.
+ inline void addTopLevelLoop(MachineLoop *New) {
+ LI.addTopLevelLoop(New);
+ }
+
+ /// removeBlock - This method completely removes BB from all data structures,
+ /// including all of the Loop objects it is nested in and our mapping from
+ /// MachineBasicBlocks to loops.
+ void removeBlock(MachineBasicBlock *BB) {
+ LI.removeBlock(BB);
+ }
+};
+
+
+// Allow clients to walk the list of nested loops...
+template <> struct GraphTraits<const MachineLoop*> {
+ typedef const MachineLoop NodeType;
+ typedef MachineLoopInfo::iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(const MachineLoop *L) { return L; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->end();
+ }
+};
+
+template <> struct GraphTraits<MachineLoop*> {
+ typedef MachineLoop NodeType;
+ typedef MachineLoopInfo::iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(MachineLoop *L) { return L; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return N->begin();
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return N->end();
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineLoopRanges.h b/include/llvm/CodeGen/MachineLoopRanges.h
new file mode 100644
index 00000000000..6a30e8b53c0
--- /dev/null
+++ b/include/llvm/CodeGen/MachineLoopRanges.h
@@ -0,0 +1,112 @@
+//===- MachineLoopRanges.h - Ranges of machine loops -----------*- c++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file provides the interface to the MachineLoopRanges analysis.
+//
+// Provide on-demand information about the ranges of machine instructions
+// covered by a loop.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINELOOPRANGES_H
+#define LLVM_CODEGEN_MACHINELOOPRANGES_H
+
+#include "llvm/ADT/IntervalMap.h"
+#include "llvm/CodeGen/SlotIndexes.h"
+
+namespace llvm {
+
+class MachineLoop;
+class MachineLoopInfo;
+class raw_ostream;
+
+/// MachineLoopRange - Range information for a single loop.
+class MachineLoopRange {
+ friend class MachineLoopRanges;
+
+public:
+ typedef IntervalMap<SlotIndex, unsigned, 4> Map;
+ typedef Map::Allocator Allocator;
+
+private:
+ /// The mapped loop.
+ const MachineLoop *const Loop;
+
+ /// Map intervals to a bit mask.
+ /// Bit 0 = inside loop block.
+ Map Intervals;
+
+ /// Loop area as measured by SlotIndex::distance.
+ unsigned Area;
+
+ /// Create a MachineLoopRange, only accessible to MachineLoopRanges.
+ MachineLoopRange(const MachineLoop*, Allocator&, SlotIndexes&);
+
+public:
+ /// getLoop - Return the mapped machine loop.
+ const MachineLoop *getLoop() const { return Loop; }
+
+ /// overlaps - Return true if this loop overlaps the given range of machine
+ /// inteructions.
+ bool overlaps(SlotIndex Start, SlotIndex Stop);
+
+ /// getNumber - Return the loop number. This is the same as the number of the
+ /// header block.
+ unsigned getNumber() const;
+
+ /// getArea - Return the loop area. This number is approximately proportional
+ /// to the number of instructions in the loop.
+ unsigned getArea() const { return Area; }
+
+ /// getMap - Allow public read-only access for IntervalMapOverlaps.
+ const Map &getMap() { return Intervals; }
+
+ /// print - Print loop ranges on OS.
+ void print(raw_ostream&) const;
+
+ /// byNumber - Comparator for array_pod_sort that sorts a list of
+ /// MachineLoopRange pointers by number.
+ static int byNumber(const void*, const void*);
+
+ /// byAreaDesc - Comparator for array_pod_sort that sorts a list of
+ /// MachineLoopRange pointers by descending area, then by number.
+ static int byAreaDesc(const void*, const void*);
+};
+
+raw_ostream &operator<<(raw_ostream&, const MachineLoopRange&);
+
+/// MachineLoopRanges - Analysis pass that provides on-demand per-loop range
+/// information.
+class MachineLoopRanges : public MachineFunctionPass {
+ typedef DenseMap<const MachineLoop*, MachineLoopRange*> CacheMap;
+ typedef MachineLoopRange::Allocator MapAllocator;
+
+ MapAllocator Allocator;
+ SlotIndexes *Indexes;
+ CacheMap Cache;
+
+public:
+ static char ID; // Pass identification, replacement for typeid
+
+ MachineLoopRanges() : MachineFunctionPass(ID), Indexes(0) {}
+ ~MachineLoopRanges() { releaseMemory(); }
+
+ /// getLoopRange - Return the range of loop.
+ MachineLoopRange *getLoopRange(const MachineLoop *Loop);
+
+private:
+ virtual bool runOnMachineFunction(MachineFunction&);
+ virtual void releaseMemory();
+ virtual void getAnalysisUsage(AnalysisUsage&) const;
+};
+
+
+} // end namespace llvm
+
+#endif // LLVM_CODEGEN_MACHINELOOPRANGES_H
diff --git a/include/llvm/CodeGen/MachineMemOperand.h b/include/llvm/CodeGen/MachineMemOperand.h
new file mode 100644
index 00000000000..ddb127120f2
--- /dev/null
+++ b/include/llvm/CodeGen/MachineMemOperand.h
@@ -0,0 +1,183 @@
+//==- llvm/CodeGen/MachineMemOperand.h - MachineMemOperand class -*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MachineMemOperand class, which is a
+// description of a memory reference. It is used to help track dependencies
+// in the backend.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEMEMOPERAND_H
+#define LLVM_CODEGEN_MACHINEMEMOPERAND_H
+
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+class Value;
+class FoldingSetNodeID;
+class MDNode;
+class raw_ostream;
+
+/// MachinePointerInfo - This class contains a discriminated union of
+/// information about pointers in memory operands, relating them back to LLVM IR
+/// or to virtual locations (such as frame indices) that are exposed during
+/// codegen.
+struct MachinePointerInfo {
+ /// V - This is the IR pointer value for the access, or it is null if unknown.
+ /// If this is null, then the access is to a pointer in the default address
+ /// space.
+ const Value *V;
+
+ /// Offset - This is an offset from the base Value*.
+ int64_t Offset;
+
+ explicit MachinePointerInfo(const Value *v = 0, int64_t offset = 0)
+ : V(v), Offset(offset) {}
+
+ MachinePointerInfo getWithOffset(int64_t O) const {
+ if (V == 0) return MachinePointerInfo(0, 0);
+ return MachinePointerInfo(V, Offset+O);
+ }
+
+ /// getAddrSpace - Return the LLVM IR address space number that this pointer
+ /// points into.
+ unsigned getAddrSpace() const;
+
+ /// getConstantPool - Return a MachinePointerInfo record that refers to the
+ /// constant pool.
+ static MachinePointerInfo getConstantPool();
+
+ /// getFixedStack - Return a MachinePointerInfo record that refers to the
+ /// the specified FrameIndex.
+ static MachinePointerInfo getFixedStack(int FI, int64_t offset = 0);
+
+ /// getJumpTable - Return a MachinePointerInfo record that refers to a
+ /// jump table entry.
+ static MachinePointerInfo getJumpTable();
+
+ /// getGOT - Return a MachinePointerInfo record that refers to a
+ /// GOT entry.
+ static MachinePointerInfo getGOT();
+
+ /// getStack - stack pointer relative access.
+ static MachinePointerInfo getStack(int64_t Offset);
+};
+
+
+//===----------------------------------------------------------------------===//
+/// MachineMemOperand - A description of a memory reference used in the backend.
+/// Instead of holding a StoreInst or LoadInst, this class holds the address
+/// Value of the reference along with a byte size and offset. This allows it
+/// to describe lowered loads and stores. Also, the special PseudoSourceValue
+/// objects can be used to represent loads and stores to memory locations
+/// that aren't explicit in the regular LLVM IR.
+///
+class MachineMemOperand {
+ MachinePointerInfo PtrInfo;
+ uint64_t Size;
+ unsigned Flags;
+ const MDNode *TBAAInfo;
+ const MDNode *Ranges;
+
+public:
+ /// Flags values. These may be or'd together.
+ enum MemOperandFlags {
+ /// The memory access reads data.
+ MOLoad = 1,
+ /// The memory access writes data.
+ MOStore = 2,
+ /// The memory access is volatile.
+ MOVolatile = 4,
+ /// The memory access is non-temporal.
+ MONonTemporal = 8,
+ /// The memory access is invariant.
+ MOInvariant = 16,
+ // This is the number of bits we need to represent flags.
+ MOMaxBits = 5
+ };
+
+ /// MachineMemOperand - Construct an MachineMemOperand object with the
+ /// specified PtrInfo, flags, size, and base alignment.
+ MachineMemOperand(MachinePointerInfo PtrInfo, unsigned flags, uint64_t s,
+ unsigned base_alignment, const MDNode *TBAAInfo = 0,
+ const MDNode *Ranges = 0);
+
+ const MachinePointerInfo &getPointerInfo() const { return PtrInfo; }
+
+ /// getValue - Return the base address of the memory access. This may either
+ /// be a normal LLVM IR Value, or one of the special values used in CodeGen.
+ /// Special values are those obtained via
+ /// PseudoSourceValue::getFixedStack(int), PseudoSourceValue::getStack, and
+ /// other PseudoSourceValue member functions which return objects which stand
+ /// for frame/stack pointer relative references and other special references
+ /// which are not representable in the high-level IR.
+ const Value *getValue() const { return PtrInfo.V; }
+
+ /// getFlags - Return the raw flags of the source value, \see MemOperandFlags.
+ unsigned int getFlags() const { return Flags & ((1 << MOMaxBits) - 1); }
+
+ /// getOffset - For normal values, this is a byte offset added to the base
+ /// address. For PseudoSourceValue::FPRel values, this is the FrameIndex
+ /// number.
+ int64_t getOffset() const { return PtrInfo.Offset; }
+
+ /// getSize - Return the size in bytes of the memory reference.
+ uint64_t getSize() const { return Size; }
+
+ /// getAlignment - Return the minimum known alignment in bytes of the
+ /// actual memory reference.
+ uint64_t getAlignment() const;
+
+ /// getBaseAlignment - Return the minimum known alignment in bytes of the
+ /// base address, without the offset.
+ uint64_t getBaseAlignment() const { return (1u << (Flags >> MOMaxBits)) >> 1; }
+
+ /// getTBAAInfo - Return the TBAA tag for the memory reference.
+ const MDNode *getTBAAInfo() const { return TBAAInfo; }
+
+ /// getRanges - Return the range tag for the memory reference.
+ const MDNode *getRanges() const { return Ranges; }
+
+ bool isLoad() const { return Flags & MOLoad; }
+ bool isStore() const { return Flags & MOStore; }
+ bool isVolatile() const { return Flags & MOVolatile; }
+ bool isNonTemporal() const { return Flags & MONonTemporal; }
+ bool isInvariant() const { return Flags & MOInvariant; }
+
+ /// isUnordered - Returns true if this memory operation doesn't have any
+ /// ordering constraints other than normal aliasing. Volatile and atomic
+ /// memory operations can't be reordered.
+ ///
+ /// Currently, we don't model the difference between volatile and atomic
+ /// operations. They should retain their ordering relative to all memory
+ /// operations.
+ bool isUnordered() const { return !isVolatile(); }
+
+ /// refineAlignment - Update this MachineMemOperand to reflect the alignment
+ /// of MMO, if it has a greater alignment. This must only be used when the
+ /// new alignment applies to all users of this MachineMemOperand.
+ void refineAlignment(const MachineMemOperand *MMO);
+
+ /// setValue - Change the SourceValue for this MachineMemOperand. This
+ /// should only be used when an object is being relocated and all references
+ /// to it are being updated.
+ void setValue(const Value *NewSV) { PtrInfo.V = NewSV; }
+ void setOffset(int64_t NewOffset) { PtrInfo.Offset = NewOffset; }
+
+ /// Profile - Gather unique data for the object.
+ ///
+ void Profile(FoldingSetNodeID &ID) const;
+};
+
+raw_ostream &operator<<(raw_ostream &OS, const MachineMemOperand &MRO);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineModuleInfo.h b/include/llvm/CodeGen/MachineModuleInfo.h
new file mode 100644
index 00000000000..6b88d4a9499
--- /dev/null
+++ b/include/llvm/CodeGen/MachineModuleInfo.h
@@ -0,0 +1,405 @@
+//===-- llvm/CodeGen/MachineModuleInfo.h ------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Collect meta information for a module. This information should be in a
+// neutral form that can be used by different debugging and exception handling
+// schemes.
+//
+// The organization of information is primarily clustered around the source
+// compile units. The main exception is source line correspondence where
+// inlining may interleave code from various compile units.
+//
+// The following information can be retrieved from the MachineModuleInfo.
+//
+// -- Source directories - Directories are uniqued based on their canonical
+// string and assigned a sequential numeric ID (base 1.)
+// -- Source files - Files are also uniqued based on their name and directory
+// ID. A file ID is sequential number (base 1.)
+// -- Source line correspondence - A vector of file ID, line#, column# triples.
+// A DEBUG_LOCATION instruction is generated by the DAG Legalizer
+// corresponding to each entry in the source line list. This allows a debug
+// emitter to generate labels referenced by debug information tables.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEMODULEINFO_H
+#define LLVM_CODEGEN_MACHINEMODULEINFO_H
+
+#include "llvm/Pass.h"
+#include "llvm/GlobalValue.h"
+#include "llvm/Metadata.h"
+#include "llvm/MC/MachineLocation.h"
+#include "llvm/MC/MCContext.h"
+#include "llvm/Support/Dwarf.h"
+#include "llvm/Support/DebugLoc.h"
+#include "llvm/Support/ValueHandle.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// Forward declarations.
+class Constant;
+class GlobalVariable;
+class MDNode;
+class MMIAddrLabelMap;
+class MachineBasicBlock;
+class MachineFunction;
+class Module;
+class PointerType;
+class StructType;
+
+//===----------------------------------------------------------------------===//
+/// LandingPadInfo - This structure is used to retain landing pad info for
+/// the current function.
+///
+struct LandingPadInfo {
+ MachineBasicBlock *LandingPadBlock; // Landing pad block.
+ SmallVector<MCSymbol*, 1> BeginLabels; // Labels prior to invoke.
+ SmallVector<MCSymbol*, 1> EndLabels; // Labels after invoke.
+ MCSymbol *LandingPadLabel; // Label at beginning of landing pad.
+ const Function *Personality; // Personality function.
+ std::vector<int> TypeIds; // List of type ids (filters negative)
+
+ explicit LandingPadInfo(MachineBasicBlock *MBB)
+ : LandingPadBlock(MBB), LandingPadLabel(0), Personality(0) {}
+};
+
+//===----------------------------------------------------------------------===//
+/// MachineModuleInfoImpl - This class can be derived from and used by targets
+/// to hold private target-specific information for each Module. Objects of
+/// type are accessed/created with MMI::getInfo and destroyed when the
+/// MachineModuleInfo is destroyed.
+///
+class MachineModuleInfoImpl {
+public:
+ typedef PointerIntPair<MCSymbol*, 1, bool> StubValueTy;
+ virtual ~MachineModuleInfoImpl();
+ typedef std::vector<std::pair<MCSymbol*, StubValueTy> > SymbolListTy;
+protected:
+ static SymbolListTy GetSortedStubs(const DenseMap<MCSymbol*, StubValueTy>&);
+};
+
+//===----------------------------------------------------------------------===//
+/// MachineModuleInfo - This class contains meta information specific to a
+/// module. Queries can be made by different debugging and exception handling
+/// schemes and reformated for specific use.
+///
+class MachineModuleInfo : public ImmutablePass {
+ /// Context - This is the MCContext used for the entire code generator.
+ MCContext Context;
+
+ /// TheModule - This is the LLVM Module being worked on.
+ const Module *TheModule;
+
+ /// ObjFileMMI - This is the object-file-format-specific implementation of
+ /// MachineModuleInfoImpl, which lets targets accumulate whatever info they
+ /// want.
+ MachineModuleInfoImpl *ObjFileMMI;
+
+ /// FrameMoves - List of moves done by a function's prolog. Used to construct
+ /// frame maps by debug and exception handling consumers.
+ std::vector<MachineMove> FrameMoves;
+
+ /// CompactUnwindEncoding - If the target supports it, this is the compact
+ /// unwind encoding. It replaces a function's CIE and FDE.
+ uint32_t CompactUnwindEncoding;
+
+ /// LandingPads - List of LandingPadInfo describing the landing pad
+ /// information in the current function.
+ std::vector<LandingPadInfo> LandingPads;
+
+ /// LPadToCallSiteMap - Map a landing pad's EH symbol to the call site
+ /// indexes.
+ DenseMap<MCSymbol*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
+
+ /// CallSiteMap - Map of invoke call site index values to associated begin
+ /// EH_LABEL for the current function.
+ DenseMap<MCSymbol*, unsigned> CallSiteMap;
+
+ /// CurCallSite - The current call site index being processed, if any. 0 if
+ /// none.
+ unsigned CurCallSite;
+
+ /// TypeInfos - List of C++ TypeInfo used in the current function.
+ std::vector<const GlobalVariable *> TypeInfos;
+
+ /// FilterIds - List of typeids encoding filters used in the current function.
+ std::vector<unsigned> FilterIds;
+
+ /// FilterEnds - List of the indices in FilterIds corresponding to filter
+ /// terminators.
+ std::vector<unsigned> FilterEnds;
+
+ /// Personalities - Vector of all personality functions ever seen. Used to
+ /// emit common EH frames.
+ std::vector<const Function *> Personalities;
+
+ /// UsedFunctions - The functions in the @llvm.used list in a more easily
+ /// searchable format. This does not include the functions in
+ /// llvm.compiler.used.
+ SmallPtrSet<const Function *, 32> UsedFunctions;
+
+ /// AddrLabelSymbols - This map keeps track of which symbol is being used for
+ /// the specified basic block's address of label.
+ MMIAddrLabelMap *AddrLabelSymbols;
+
+ bool CallsEHReturn;
+ bool CallsUnwindInit;
+
+ /// DbgInfoAvailable - True if debugging information is available
+ /// in this module.
+ bool DbgInfoAvailable;
+
+ /// UsesVAFloatArgument - True if this module calls VarArg function with
+ /// floating-point arguments. This is used to emit an undefined reference
+ /// to _fltused on Windows targets.
+ bool UsesVAFloatArgument;
+
+public:
+ static char ID; // Pass identification, replacement for typeid
+
+ typedef std::pair<unsigned, DebugLoc> UnsignedDebugLocPair;
+ typedef SmallVector<std::pair<TrackingVH<MDNode>, UnsignedDebugLocPair>, 4>
+ VariableDbgInfoMapTy;
+ VariableDbgInfoMapTy VariableDbgInfo;
+
+ MachineModuleInfo(); // DUMMY CONSTRUCTOR, DO NOT CALL.
+ // Real constructor.
+ MachineModuleInfo(const MCAsmInfo &MAI, const MCRegisterInfo &MRI,
+ const MCObjectFileInfo *MOFI);
+ ~MachineModuleInfo();
+
+ bool doInitialization();
+ bool doFinalization();
+
+ /// EndFunction - Discard function meta information.
+ ///
+ void EndFunction();
+
+ const MCContext &getContext() const { return Context; }
+ MCContext &getContext() { return Context; }
+
+ void setModule(const Module *M) { TheModule = M; }
+ const Module *getModule() const { return TheModule; }
+
+ /// getInfo - Keep track of various per-function pieces of information for
+ /// backends that would like to do so.
+ ///
+ template<typename Ty>
+ Ty &getObjFileInfo() {
+ if (ObjFileMMI == 0)
+ ObjFileMMI = new Ty(*this);
+ return *static_cast<Ty*>(ObjFileMMI);
+ }
+
+ template<typename Ty>
+ const Ty &getObjFileInfo() const {
+ return const_cast<MachineModuleInfo*>(this)->getObjFileInfo<Ty>();
+ }
+
+ /// AnalyzeModule - Scan the module for global debug information.
+ ///
+ void AnalyzeModule(const Module &M);
+
+ /// hasDebugInfo - Returns true if valid debug info is present.
+ ///
+ bool hasDebugInfo() const { return DbgInfoAvailable; }
+ void setDebugInfoAvailability(bool avail) { DbgInfoAvailable = avail; }
+
+ bool callsEHReturn() const { return CallsEHReturn; }
+ void setCallsEHReturn(bool b) { CallsEHReturn = b; }
+
+ bool callsUnwindInit() const { return CallsUnwindInit; }
+ void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
+
+ bool usesVAFloatArgument() const {
+ return UsesVAFloatArgument;
+ }
+
+ void setUsesVAFloatArgument(bool b) {
+ UsesVAFloatArgument = b;
+ }
+
+ /// getFrameMoves - Returns a reference to a list of moves done in the current
+ /// function's prologue. Used to construct frame maps for debug and exception
+ /// handling comsumers.
+ std::vector<MachineMove> &getFrameMoves() { return FrameMoves; }
+
+ /// getCompactUnwindEncoding - Returns the compact unwind encoding for a
+ /// function if the target supports the encoding. This encoding replaces a
+ /// function's CIE and FDE.
+ uint32_t getCompactUnwindEncoding() const { return CompactUnwindEncoding; }
+
+ /// setCompactUnwindEncoding - Set the compact unwind encoding for a function
+ /// if the target supports the encoding.
+ void setCompactUnwindEncoding(uint32_t Enc) { CompactUnwindEncoding = Enc; }
+
+ /// getAddrLabelSymbol - Return the symbol to be used for the specified basic
+ /// block when its address is taken. This cannot be its normal LBB label
+ /// because the block may be accessed outside its containing function.
+ MCSymbol *getAddrLabelSymbol(const BasicBlock *BB);
+
+ /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified
+ /// basic block when its address is taken. If other blocks were RAUW'd to
+ /// this one, we may have to emit them as well, return the whole set.
+ std::vector<MCSymbol*> getAddrLabelSymbolToEmit(const BasicBlock *BB);
+
+ /// takeDeletedSymbolsForFunction - If the specified function has had any
+ /// references to address-taken blocks generated, but the block got deleted,
+ /// return the symbol now so we can emit it. This prevents emitting a
+ /// reference to a symbol that has no definition.
+ void takeDeletedSymbolsForFunction(const Function *F,
+ std::vector<MCSymbol*> &Result);
+
+
+ //===- EH ---------------------------------------------------------------===//
+
+ /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
+ /// specified MachineBasicBlock.
+ LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
+
+ /// addInvoke - Provide the begin and end labels of an invoke style call and
+ /// associate it with a try landing pad block.
+ void addInvoke(MachineBasicBlock *LandingPad,
+ MCSymbol *BeginLabel, MCSymbol *EndLabel);
+
+ /// addLandingPad - Add a new panding pad. Returns the label ID for the
+ /// landing pad entry.
+ MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
+
+ /// addPersonality - Provide the personality function for the exception
+ /// information.
+ void addPersonality(MachineBasicBlock *LandingPad,
+ const Function *Personality);
+
+ /// getPersonalityIndex - Get index of the current personality function inside
+ /// Personalitites array
+ unsigned getPersonalityIndex() const;
+
+ /// getPersonalities - Return array of personality functions ever seen.
+ const std::vector<const Function *>& getPersonalities() const {
+ return Personalities;
+ }
+
+ /// isUsedFunction - Return true if the functions in the llvm.used list. This
+ /// does not return true for things in llvm.compiler.used unless they are also
+ /// in llvm.used.
+ bool isUsedFunction(const Function *F) {
+ return UsedFunctions.count(F);
+ }
+
+ /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
+ ///
+ void addCatchTypeInfo(MachineBasicBlock *LandingPad,
+ ArrayRef<const GlobalVariable *> TyInfo);
+
+ /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
+ ///
+ void addFilterTypeInfo(MachineBasicBlock *LandingPad,
+ ArrayRef<const GlobalVariable *> TyInfo);
+
+ /// addCleanup - Add a cleanup action for a landing pad.
+ ///
+ void addCleanup(MachineBasicBlock *LandingPad);
+
+ /// getTypeIDFor - Return the type id for the specified typeinfo. This is
+ /// function wide.
+ unsigned getTypeIDFor(const GlobalVariable *TI);
+
+ /// getFilterIDFor - Return the id of the filter encoded by TyIds. This is
+ /// function wide.
+ int getFilterIDFor(std::vector<unsigned> &TyIds);
+
+ /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
+ /// pads.
+ void TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap = 0);
+
+ /// getLandingPads - Return a reference to the landing pad info for the
+ /// current function.
+ const std::vector<LandingPadInfo> &getLandingPads() const {
+ return LandingPads;
+ }
+
+ /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call
+ /// site indexes.
+ void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
+
+ /// getCallSiteLandingPad - Get the call site indexes for a landing pad EH
+ /// symbol.
+ SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
+ assert(hasCallSiteLandingPad(Sym) &&
+ "missing call site number for landing pad!");
+ return LPadToCallSiteMap[Sym];
+ }
+
+ /// hasCallSiteLandingPad - Return true if the landing pad Eh symbol has an
+ /// associated call site.
+ bool hasCallSiteLandingPad(MCSymbol *Sym) {
+ return !LPadToCallSiteMap[Sym].empty();
+ }
+
+ /// setCallSiteBeginLabel - Map the begin label for a call site.
+ void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
+ CallSiteMap[BeginLabel] = Site;
+ }
+
+ /// getCallSiteBeginLabel - Get the call site number for a begin label.
+ unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) {
+ assert(hasCallSiteBeginLabel(BeginLabel) &&
+ "Missing call site number for EH_LABEL!");
+ return CallSiteMap[BeginLabel];
+ }
+
+ /// hasCallSiteBeginLabel - Return true if the begin label has a call site
+ /// number associated with it.
+ bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) {
+ return CallSiteMap[BeginLabel] != 0;
+ }
+
+ /// setCurrentCallSite - Set the call site currently being processed.
+ void setCurrentCallSite(unsigned Site) { CurCallSite = Site; }
+
+ /// getCurrentCallSite - Get the call site currently being processed, if any.
+ /// return zero if none.
+ unsigned getCurrentCallSite(void) { return CurCallSite; }
+
+ /// getTypeInfos - Return a reference to the C++ typeinfo for the current
+ /// function.
+ const std::vector<const GlobalVariable *> &getTypeInfos() const {
+ return TypeInfos;
+ }
+
+ /// getFilterIds - Return a reference to the typeids encoding filters used in
+ /// the current function.
+ const std::vector<unsigned> &getFilterIds() const {
+ return FilterIds;
+ }
+
+ /// getPersonality - Return a personality function if available. The presence
+ /// of one is required to emit exception handling info.
+ const Function *getPersonality() const;
+
+ /// setVariableDbgInfo - Collect information used to emit debugging
+ /// information of a variable.
+ void setVariableDbgInfo(MDNode *N, unsigned Slot, DebugLoc Loc) {
+ VariableDbgInfo.push_back(std::make_pair(N, std::make_pair(Slot, Loc)));
+ }
+
+ VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfo; }
+
+}; // End class MachineModuleInfo
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineModuleInfoImpls.h b/include/llvm/CodeGen/MachineModuleInfoImpls.h
new file mode 100644
index 00000000000..9401ffd199d
--- /dev/null
+++ b/include/llvm/CodeGen/MachineModuleInfoImpls.h
@@ -0,0 +1,97 @@
+//===-- llvm/CodeGen/MachineModuleInfoImpls.h -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines object-file format specific implementations of
+// MachineModuleInfoImpl.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEMODULEINFOIMPLS_H
+#define LLVM_CODEGEN_MACHINEMODULEINFOIMPLS_H
+
+#include "llvm/CodeGen/MachineModuleInfo.h"
+
+namespace llvm {
+ class MCSymbol;
+
+ /// MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation
+ /// for MachO targets.
+ class MachineModuleInfoMachO : public MachineModuleInfoImpl {
+ /// FnStubs - Darwin '$stub' stubs. The key is something like "Lfoo$stub",
+ /// the value is something like "_foo".
+ DenseMap<MCSymbol*, StubValueTy> FnStubs;
+
+ /// GVStubs - Darwin '$non_lazy_ptr' stubs. The key is something like
+ /// "Lfoo$non_lazy_ptr", the value is something like "_foo". The extra bit
+ /// is true if this GV is external.
+ DenseMap<MCSymbol*, StubValueTy> GVStubs;
+
+ /// HiddenGVStubs - Darwin '$non_lazy_ptr' stubs. The key is something like
+ /// "Lfoo$non_lazy_ptr", the value is something like "_foo". Unlike GVStubs
+ /// these are for things with hidden visibility. The extra bit is true if
+ /// this GV is external.
+ DenseMap<MCSymbol*, StubValueTy> HiddenGVStubs;
+
+ virtual void Anchor(); // Out of line virtual method.
+ public:
+ MachineModuleInfoMachO(const MachineModuleInfo &) {}
+
+ StubValueTy &getFnStubEntry(MCSymbol *Sym) {
+ assert(Sym && "Key cannot be null");
+ return FnStubs[Sym];
+ }
+
+ StubValueTy &getGVStubEntry(MCSymbol *Sym) {
+ assert(Sym && "Key cannot be null");
+ return GVStubs[Sym];
+ }
+
+ StubValueTy &getHiddenGVStubEntry(MCSymbol *Sym) {
+ assert(Sym && "Key cannot be null");
+ return HiddenGVStubs[Sym];
+ }
+
+ /// Accessor methods to return the set of stubs in sorted order.
+ SymbolListTy GetFnStubList() const {
+ return GetSortedStubs(FnStubs);
+ }
+ SymbolListTy GetGVStubList() const {
+ return GetSortedStubs(GVStubs);
+ }
+ SymbolListTy GetHiddenGVStubList() const {
+ return GetSortedStubs(HiddenGVStubs);
+ }
+ };
+
+ /// MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation
+ /// for ELF targets.
+ class MachineModuleInfoELF : public MachineModuleInfoImpl {
+ /// GVStubs - These stubs are used to materialize global addresses in PIC
+ /// mode.
+ DenseMap<MCSymbol*, StubValueTy> GVStubs;
+
+ virtual void Anchor(); // Out of line virtual method.
+ public:
+ MachineModuleInfoELF(const MachineModuleInfo &) {}
+
+ StubValueTy &getGVStubEntry(MCSymbol *Sym) {
+ assert(Sym && "Key cannot be null");
+ return GVStubs[Sym];
+ }
+
+ /// Accessor methods to return the set of stubs in sorted order.
+
+ SymbolListTy GetGVStubList() const {
+ return GetSortedStubs(GVStubs);
+ }
+ };
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/MachineOperand.h b/include/llvm/CodeGen/MachineOperand.h
new file mode 100644
index 00000000000..5a182101c13
--- /dev/null
+++ b/include/llvm/CodeGen/MachineOperand.h
@@ -0,0 +1,692 @@
+//===-- llvm/CodeGen/MachineOperand.h - MachineOperand class ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MachineOperand class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEOPERAND_H
+#define LLVM_CODEGEN_MACHINEOPERAND_H
+
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+
+namespace llvm {
+
+class BlockAddress;
+class ConstantFP;
+class ConstantInt;
+class GlobalValue;
+class MachineBasicBlock;
+class MachineInstr;
+class MachineRegisterInfo;
+class MDNode;
+class TargetMachine;
+class TargetRegisterInfo;
+class hash_code;
+class raw_ostream;
+class MCSymbol;
+
+/// MachineOperand class - Representation of each machine instruction operand.
+///
+class MachineOperand {
+public:
+ enum MachineOperandType {
+ MO_Register, ///< Register operand.
+ MO_Immediate, ///< Immediate operand
+ MO_CImmediate, ///< Immediate >64bit operand
+ MO_FPImmediate, ///< Floating-point immediate operand
+ MO_MachineBasicBlock, ///< MachineBasicBlock reference
+ MO_FrameIndex, ///< Abstract Stack Frame Index
+ MO_ConstantPoolIndex, ///< Address of indexed Constant in Constant Pool
+ MO_TargetIndex, ///< Target-dependent index+offset operand.
+ MO_JumpTableIndex, ///< Address of indexed Jump Table for switch
+ MO_ExternalSymbol, ///< Name of external global symbol
+ MO_GlobalAddress, ///< Address of a global value
+ MO_BlockAddress, ///< Address of a basic block
+ MO_RegisterMask, ///< Mask of preserved registers.
+ MO_Metadata, ///< Metadata reference (for debug info)
+ MO_MCSymbol ///< MCSymbol reference (for debug/eh info)
+ };
+
+private:
+ /// OpKind - Specify what kind of operand this is. This discriminates the
+ /// union.
+ unsigned char OpKind; // MachineOperandType
+
+ // This union is discriminated by OpKind.
+ union {
+ /// SubReg - Subregister number, only valid for MO_Register. A value of 0
+ /// indicates the MO_Register has no subReg.
+ unsigned char SubReg;
+
+ /// TargetFlags - This is a set of target-specific operand flags.
+ unsigned char TargetFlags;
+ };
+
+ /// TiedTo - Non-zero when this register operand is tied to another register
+ /// operand. The encoding of this field is described in the block comment
+ /// before MachineInstr::tieOperands().
+ unsigned char TiedTo : 4;
+
+ /// IsDef/IsImp/IsKill/IsDead flags - These are only valid for MO_Register
+ /// operands.
+
+ /// IsDef - True if this is a def, false if this is a use of the register.
+ ///
+ bool IsDef : 1;
+
+ /// IsImp - True if this is an implicit def or use, false if it is explicit.
+ ///
+ bool IsImp : 1;
+
+ /// IsKill - True if this instruction is the last use of the register on this
+ /// path through the function. This is only valid on uses of registers.
+ bool IsKill : 1;
+
+ /// IsDead - True if this register is never used by a subsequent instruction.
+ /// This is only valid on definitions of registers.
+ bool IsDead : 1;
+
+ /// IsUndef - True if this register operand reads an "undef" value, i.e. the
+ /// read value doesn't matter. This flag can be set on both use and def
+ /// operands. On a sub-register def operand, it refers to the part of the
+ /// register that isn't written. On a full-register def operand, it is a
+ /// noop. See readsReg().
+ ///
+ /// This is only valid on registers.
+ ///
+ /// Note that an instruction may have multiple <undef> operands referring to
+ /// the same register. In that case, the instruction may depend on those
+ /// operands reading the same dont-care value. For example:
+ ///
+ /// %vreg1<def> = XOR %vreg2<undef>, %vreg2<undef>
+ ///
+ /// Any register can be used for %vreg2, and its value doesn't matter, but
+ /// the two operands must be the same register.
+ ///
+ bool IsUndef : 1;
+
+ /// IsInternalRead - True if this operand reads a value that was defined
+ /// inside the same instruction or bundle. This flag can be set on both use
+ /// and def operands. On a sub-register def operand, it refers to the part
+ /// of the register that isn't written. On a full-register def operand, it
+ /// is a noop.
+ ///
+ /// When this flag is set, the instruction bundle must contain at least one
+ /// other def of the register. If multiple instructions in the bundle define
+ /// the register, the meaning is target-defined.
+ bool IsInternalRead : 1;
+
+ /// IsEarlyClobber - True if this MO_Register 'def' operand is written to
+ /// by the MachineInstr before all input registers are read. This is used to
+ /// model the GCC inline asm '&' constraint modifier.
+ bool IsEarlyClobber : 1;
+
+ /// IsDebug - True if this MO_Register 'use' operand is in a debug pseudo,
+ /// not a real instruction. Such uses should be ignored during codegen.
+ bool IsDebug : 1;
+
+ /// SmallContents - This really should be part of the Contents union, but
+ /// lives out here so we can get a better packed struct.
+ /// MO_Register: Register number.
+ /// OffsetedInfo: Low bits of offset.
+ union {
+ unsigned RegNo; // For MO_Register.
+ unsigned OffsetLo; // Matches Contents.OffsetedInfo.OffsetHi.
+ } SmallContents;
+
+ /// ParentMI - This is the instruction that this operand is embedded into.
+ /// This is valid for all operand types, when the operand is in an instr.
+ MachineInstr *ParentMI;
+
+ /// Contents union - This contains the payload for the various operand types.
+ union {
+ MachineBasicBlock *MBB; // For MO_MachineBasicBlock.
+ const ConstantFP *CFP; // For MO_FPImmediate.
+ const ConstantInt *CI; // For MO_CImmediate. Integers > 64bit.
+ int64_t ImmVal; // For MO_Immediate.
+ const uint32_t *RegMask; // For MO_RegisterMask.
+ const MDNode *MD; // For MO_Metadata.
+ MCSymbol *Sym; // For MO_MCSymbol
+
+ struct { // For MO_Register.
+ // Register number is in SmallContents.RegNo.
+ MachineOperand *Prev; // Access list for register. See MRI.
+ MachineOperand *Next;
+ } Reg;
+
+ /// OffsetedInfo - This struct contains the offset and an object identifier.
+ /// this represent the object as with an optional offset from it.
+ struct {
+ union {
+ int Index; // For MO_*Index - The index itself.
+ const char *SymbolName; // For MO_ExternalSymbol.
+ const GlobalValue *GV; // For MO_GlobalAddress.
+ const BlockAddress *BA; // For MO_BlockAddress.
+ } Val;
+ // Low bits of offset are in SmallContents.OffsetLo.
+ int OffsetHi; // An offset from the object, high 32 bits.
+ } OffsetedInfo;
+ } Contents;
+
+ explicit MachineOperand(MachineOperandType K) : OpKind(K), ParentMI(0) {
+ TargetFlags = 0;
+ }
+public:
+ /// getType - Returns the MachineOperandType for this operand.
+ ///
+ MachineOperandType getType() const { return (MachineOperandType)OpKind; }
+
+ unsigned char getTargetFlags() const {
+ return isReg() ? 0 : TargetFlags;
+ }
+ void setTargetFlags(unsigned char F) {
+ assert(!isReg() && "Register operands can't have target flags");
+ TargetFlags = F;
+ }
+ void addTargetFlag(unsigned char F) {
+ assert(!isReg() && "Register operands can't have target flags");
+ TargetFlags |= F;
+ }
+
+
+ /// getParent - Return the instruction that this operand belongs to.
+ ///
+ MachineInstr *getParent() { return ParentMI; }
+ const MachineInstr *getParent() const { return ParentMI; }
+
+ /// clearParent - Reset the parent pointer.
+ ///
+ /// The MachineOperand copy constructor also copies ParentMI, expecting the
+ /// original to be deleted. If a MachineOperand is ever stored outside a
+ /// MachineInstr, the parent pointer must be cleared.
+ ///
+ /// Never call clearParent() on an operand in a MachineInstr.
+ ///
+ void clearParent() { ParentMI = 0; }
+
+ void print(raw_ostream &os, const TargetMachine *TM = 0) const;
+
+ //===--------------------------------------------------------------------===//
+ // Accessors that tell you what kind of MachineOperand you're looking at.
+ //===--------------------------------------------------------------------===//
+
+ /// isReg - Tests if this is a MO_Register operand.
+ bool isReg() const { return OpKind == MO_Register; }
+ /// isImm - Tests if this is a MO_Immediate operand.
+ bool isImm() const { return OpKind == MO_Immediate; }
+ /// isCImm - Test if t his is a MO_CImmediate operand.
+ bool isCImm() const { return OpKind == MO_CImmediate; }
+ /// isFPImm - Tests if this is a MO_FPImmediate operand.
+ bool isFPImm() const { return OpKind == MO_FPImmediate; }
+ /// isMBB - Tests if this is a MO_MachineBasicBlock operand.
+ bool isMBB() const { return OpKind == MO_MachineBasicBlock; }
+ /// isFI - Tests if this is a MO_FrameIndex operand.
+ bool isFI() const { return OpKind == MO_FrameIndex; }
+ /// isCPI - Tests if this is a MO_ConstantPoolIndex operand.
+ bool isCPI() const { return OpKind == MO_ConstantPoolIndex; }
+ /// isTargetIndex - Tests if this is a MO_TargetIndex operand.
+ bool isTargetIndex() const { return OpKind == MO_TargetIndex; }
+ /// isJTI - Tests if this is a MO_JumpTableIndex operand.
+ bool isJTI() const { return OpKind == MO_JumpTableIndex; }
+ /// isGlobal - Tests if this is a MO_GlobalAddress operand.
+ bool isGlobal() const { return OpKind == MO_GlobalAddress; }
+ /// isSymbol - Tests if this is a MO_ExternalSymbol operand.
+ bool isSymbol() const { return OpKind == MO_ExternalSymbol; }
+ /// isBlockAddress - Tests if this is a MO_BlockAddress operand.
+ bool isBlockAddress() const { return OpKind == MO_BlockAddress; }
+ /// isRegMask - Tests if this is a MO_RegisterMask operand.
+ bool isRegMask() const { return OpKind == MO_RegisterMask; }
+ /// isMetadata - Tests if this is a MO_Metadata operand.
+ bool isMetadata() const { return OpKind == MO_Metadata; }
+ bool isMCSymbol() const { return OpKind == MO_MCSymbol; }
+
+
+ //===--------------------------------------------------------------------===//
+ // Accessors for Register Operands
+ //===--------------------------------------------------------------------===//
+
+ /// getReg - Returns the register number.
+ unsigned getReg() const {
+ assert(isReg() && "This is not a register operand!");
+ return SmallContents.RegNo;
+ }
+
+ unsigned getSubReg() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return (unsigned)SubReg;
+ }
+
+ bool isUse() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return !IsDef;
+ }
+
+ bool isDef() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return IsDef;
+ }
+
+ bool isImplicit() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return IsImp;
+ }
+
+ bool isDead() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return IsDead;
+ }
+
+ bool isKill() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return IsKill;
+ }
+
+ bool isUndef() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return IsUndef;
+ }
+
+ bool isInternalRead() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return IsInternalRead;
+ }
+
+ bool isEarlyClobber() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return IsEarlyClobber;
+ }
+
+ bool isTied() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return TiedTo;
+ }
+
+ bool isDebug() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return IsDebug;
+ }
+
+ /// readsReg - Returns true if this operand reads the previous value of its
+ /// register. A use operand with the <undef> flag set doesn't read its
+ /// register. A sub-register def implicitly reads the other parts of the
+ /// register being redefined unless the <undef> flag is set.
+ ///
+ /// This refers to reading the register value from before the current
+ /// instruction or bundle. Internal bundle reads are not included.
+ bool readsReg() const {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ return !isUndef() && !isInternalRead() && (isUse() || getSubReg());
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Mutators for Register Operands
+ //===--------------------------------------------------------------------===//
+
+ /// Change the register this operand corresponds to.
+ ///
+ void setReg(unsigned Reg);
+
+ void setSubReg(unsigned subReg) {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ SubReg = (unsigned char)subReg;
+ }
+
+ /// substVirtReg - Substitute the current register with the virtual
+ /// subregister Reg:SubReg. Take any existing SubReg index into account,
+ /// using TargetRegisterInfo to compose the subreg indices if necessary.
+ /// Reg must be a virtual register, SubIdx can be 0.
+ ///
+ void substVirtReg(unsigned Reg, unsigned SubIdx, const TargetRegisterInfo&);
+
+ /// substPhysReg - Substitute the current register with the physical register
+ /// Reg, taking any existing SubReg into account. For instance,
+ /// substPhysReg(%EAX) will change %reg1024:sub_8bit to %AL.
+ ///
+ void substPhysReg(unsigned Reg, const TargetRegisterInfo&);
+
+ void setIsUse(bool Val = true) { setIsDef(!Val); }
+
+ void setIsDef(bool Val = true);
+
+ void setImplicit(bool Val = true) {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ IsImp = Val;
+ }
+
+ void setIsKill(bool Val = true) {
+ assert(isReg() && !IsDef && "Wrong MachineOperand accessor");
+ assert((!Val || !isDebug()) && "Marking a debug operation as kill");
+ IsKill = Val;
+ }
+
+ void setIsDead(bool Val = true) {
+ assert(isReg() && IsDef && "Wrong MachineOperand accessor");
+ IsDead = Val;
+ }
+
+ void setIsUndef(bool Val = true) {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ IsUndef = Val;
+ }
+
+ void setIsInternalRead(bool Val = true) {
+ assert(isReg() && "Wrong MachineOperand accessor");
+ IsInternalRead = Val;
+ }
+
+ void setIsEarlyClobber(bool Val = true) {
+ assert(isReg() && IsDef && "Wrong MachineOperand accessor");
+ IsEarlyClobber = Val;
+ }
+
+ void setIsDebug(bool Val = true) {
+ assert(isReg() && IsDef && "Wrong MachineOperand accessor");
+ IsDebug = Val;
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Accessors for various operand types.
+ //===--------------------------------------------------------------------===//
+
+ int64_t getImm() const {
+ assert(isImm() && "Wrong MachineOperand accessor");
+ return Contents.ImmVal;
+ }
+
+ const ConstantInt *getCImm() const {
+ assert(isCImm() && "Wrong MachineOperand accessor");
+ return Contents.CI;
+ }
+
+ const ConstantFP *getFPImm() const {
+ assert(isFPImm() && "Wrong MachineOperand accessor");
+ return Contents.CFP;
+ }
+
+ MachineBasicBlock *getMBB() const {
+ assert(isMBB() && "Wrong MachineOperand accessor");
+ return Contents.MBB;
+ }
+
+ int getIndex() const {
+ assert((isFI() || isCPI() || isTargetIndex() || isJTI()) &&
+ "Wrong MachineOperand accessor");
+ return Contents.OffsetedInfo.Val.Index;
+ }
+
+ const GlobalValue *getGlobal() const {
+ assert(isGlobal() && "Wrong MachineOperand accessor");
+ return Contents.OffsetedInfo.Val.GV;
+ }
+
+ const BlockAddress *getBlockAddress() const {
+ assert(isBlockAddress() && "Wrong MachineOperand accessor");
+ return Contents.OffsetedInfo.Val.BA;
+ }
+
+ MCSymbol *getMCSymbol() const {
+ assert(isMCSymbol() && "Wrong MachineOperand accessor");
+ return Contents.Sym;
+ }
+
+ /// getOffset - Return the offset from the symbol in this operand. This always
+ /// returns 0 for ExternalSymbol operands.
+ int64_t getOffset() const {
+ assert((isGlobal() || isSymbol() || isCPI() || isTargetIndex() ||
+ isBlockAddress()) && "Wrong MachineOperand accessor");
+ return int64_t(uint64_t(Contents.OffsetedInfo.OffsetHi) << 32) |
+ SmallContents.OffsetLo;
+ }
+
+ const char *getSymbolName() const {
+ assert(isSymbol() && "Wrong MachineOperand accessor");
+ return Contents.OffsetedInfo.Val.SymbolName;
+ }
+
+ /// clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
+ /// It is sometimes necessary to detach the register mask pointer from its
+ /// machine operand. This static method can be used for such detached bit
+ /// mask pointers.
+ static bool clobbersPhysReg(const uint32_t *RegMask, unsigned PhysReg) {
+ // See TargetRegisterInfo.h.
+ assert(PhysReg < (1u << 30) && "Not a physical register");
+ return !(RegMask[PhysReg / 32] & (1u << PhysReg % 32));
+ }
+
+ /// clobbersPhysReg - Returns true if this RegMask operand clobbers PhysReg.
+ bool clobbersPhysReg(unsigned PhysReg) const {
+ return clobbersPhysReg(getRegMask(), PhysReg);
+ }
+
+ /// getRegMask - Returns a bit mask of registers preserved by this RegMask
+ /// operand.
+ const uint32_t *getRegMask() const {
+ assert(isRegMask() && "Wrong MachineOperand accessor");
+ return Contents.RegMask;
+ }
+
+ const MDNode *getMetadata() const {
+ assert(isMetadata() && "Wrong MachineOperand accessor");
+ return Contents.MD;
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Mutators for various operand types.
+ //===--------------------------------------------------------------------===//
+
+ void setImm(int64_t immVal) {
+ assert(isImm() && "Wrong MachineOperand mutator");
+ Contents.ImmVal = immVal;
+ }
+
+ void setOffset(int64_t Offset) {
+ assert((isGlobal() || isSymbol() || isCPI() || isTargetIndex() ||
+ isBlockAddress()) && "Wrong MachineOperand accessor");
+ SmallContents.OffsetLo = unsigned(Offset);
+ Contents.OffsetedInfo.OffsetHi = int(Offset >> 32);
+ }
+
+ void setIndex(int Idx) {
+ assert((isFI() || isCPI() || isTargetIndex() || isJTI()) &&
+ "Wrong MachineOperand accessor");
+ Contents.OffsetedInfo.Val.Index = Idx;
+ }
+
+ void setMBB(MachineBasicBlock *MBB) {
+ assert(isMBB() && "Wrong MachineOperand accessor");
+ Contents.MBB = MBB;
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Other methods.
+ //===--------------------------------------------------------------------===//
+
+ /// isIdenticalTo - Return true if this operand is identical to the specified
+ /// operand. Note: This method ignores isKill and isDead properties.
+ bool isIdenticalTo(const MachineOperand &Other) const;
+
+ /// \brief MachineOperand hash_value overload.
+ ///
+ /// Note that this includes the same information in the hash that
+ /// isIdenticalTo uses for comparison. It is thus suited for use in hash
+ /// tables which use that function for equality comparisons only.
+ friend hash_code hash_value(const MachineOperand &MO);
+
+ /// ChangeToImmediate - Replace this operand with a new immediate operand of
+ /// the specified value. If an operand is known to be an immediate already,
+ /// the setImm method should be used.
+ void ChangeToImmediate(int64_t ImmVal);
+
+ /// ChangeToRegister - Replace this operand with a new register operand of
+ /// the specified value. If an operand is known to be an register already,
+ /// the setReg method should be used.
+ void ChangeToRegister(unsigned Reg, bool isDef, bool isImp = false,
+ bool isKill = false, bool isDead = false,
+ bool isUndef = false, bool isDebug = false);
+
+ //===--------------------------------------------------------------------===//
+ // Construction methods.
+ //===--------------------------------------------------------------------===//
+
+ static MachineOperand CreateImm(int64_t Val) {
+ MachineOperand Op(MachineOperand::MO_Immediate);
+ Op.setImm(Val);
+ return Op;
+ }
+
+ static MachineOperand CreateCImm(const ConstantInt *CI) {
+ MachineOperand Op(MachineOperand::MO_CImmediate);
+ Op.Contents.CI = CI;
+ return Op;
+ }
+
+ static MachineOperand CreateFPImm(const ConstantFP *CFP) {
+ MachineOperand Op(MachineOperand::MO_FPImmediate);
+ Op.Contents.CFP = CFP;
+ return Op;
+ }
+
+ static MachineOperand CreateReg(unsigned Reg, bool isDef, bool isImp = false,
+ bool isKill = false, bool isDead = false,
+ bool isUndef = false,
+ bool isEarlyClobber = false,
+ unsigned SubReg = 0,
+ bool isDebug = false,
+ bool isInternalRead = false) {
+ MachineOperand Op(MachineOperand::MO_Register);
+ Op.IsDef = isDef;
+ Op.IsImp = isImp;
+ Op.IsKill = isKill;
+ Op.IsDead = isDead;
+ Op.IsUndef = isUndef;
+ Op.IsInternalRead = isInternalRead;
+ Op.IsEarlyClobber = isEarlyClobber;
+ Op.TiedTo = 0;
+ Op.IsDebug = isDebug;
+ Op.SmallContents.RegNo = Reg;
+ Op.Contents.Reg.Prev = 0;
+ Op.Contents.Reg.Next = 0;
+ Op.SubReg = SubReg;
+ return Op;
+ }
+ static MachineOperand CreateMBB(MachineBasicBlock *MBB,
+ unsigned char TargetFlags = 0) {
+ MachineOperand Op(MachineOperand::MO_MachineBasicBlock);
+ Op.setMBB(MBB);
+ Op.setTargetFlags(TargetFlags);
+ return Op;
+ }
+ static MachineOperand CreateFI(int Idx) {
+ MachineOperand Op(MachineOperand::MO_FrameIndex);
+ Op.setIndex(Idx);
+ return Op;
+ }
+ static MachineOperand CreateCPI(unsigned Idx, int Offset,
+ unsigned char TargetFlags = 0) {
+ MachineOperand Op(MachineOperand::MO_ConstantPoolIndex);
+ Op.setIndex(Idx);
+ Op.setOffset(Offset);
+ Op.setTargetFlags(TargetFlags);
+ return Op;
+ }
+ static MachineOperand CreateTargetIndex(unsigned Idx, int64_t Offset,
+ unsigned char TargetFlags = 0) {
+ MachineOperand Op(MachineOperand::MO_TargetIndex);
+ Op.setIndex(Idx);
+ Op.setOffset(Offset);
+ Op.setTargetFlags(TargetFlags);
+ return Op;
+ }
+ static MachineOperand CreateJTI(unsigned Idx,
+ unsigned char TargetFlags = 0) {
+ MachineOperand Op(MachineOperand::MO_JumpTableIndex);
+ Op.setIndex(Idx);
+ Op.setTargetFlags(TargetFlags);
+ return Op;
+ }
+ static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset,
+ unsigned char TargetFlags = 0) {
+ MachineOperand Op(MachineOperand::MO_GlobalAddress);
+ Op.Contents.OffsetedInfo.Val.GV = GV;
+ Op.setOffset(Offset);
+ Op.setTargetFlags(TargetFlags);
+ return Op;
+ }
+ static MachineOperand CreateES(const char *SymName,
+ unsigned char TargetFlags = 0) {
+ MachineOperand Op(MachineOperand::MO_ExternalSymbol);
+ Op.Contents.OffsetedInfo.Val.SymbolName = SymName;
+ Op.setOffset(0); // Offset is always 0.
+ Op.setTargetFlags(TargetFlags);
+ return Op;
+ }
+ static MachineOperand CreateBA(const BlockAddress *BA, int64_t Offset,
+ unsigned char TargetFlags = 0) {
+ MachineOperand Op(MachineOperand::MO_BlockAddress);
+ Op.Contents.OffsetedInfo.Val.BA = BA;
+ Op.setOffset(Offset);
+ Op.setTargetFlags(TargetFlags);
+ return Op;
+ }
+ /// CreateRegMask - Creates a register mask operand referencing Mask. The
+ /// operand does not take ownership of the memory referenced by Mask, it must
+ /// remain valid for the lifetime of the operand.
+ ///
+ /// A RegMask operand represents a set of non-clobbered physical registers on
+ /// an instruction that clobbers many registers, typically a call. The bit
+ /// mask has a bit set for each physreg that is preserved by this
+ /// instruction, as described in the documentation for
+ /// TargetRegisterInfo::getCallPreservedMask().
+ ///
+ /// Any physreg with a 0 bit in the mask is clobbered by the instruction.
+ ///
+ static MachineOperand CreateRegMask(const uint32_t *Mask) {
+ assert(Mask && "Missing register mask");
+ MachineOperand Op(MachineOperand::MO_RegisterMask);
+ Op.Contents.RegMask = Mask;
+ return Op;
+ }
+ static MachineOperand CreateMetadata(const MDNode *Meta) {
+ MachineOperand Op(MachineOperand::MO_Metadata);
+ Op.Contents.MD = Meta;
+ return Op;
+ }
+
+ static MachineOperand CreateMCSymbol(MCSymbol *Sym) {
+ MachineOperand Op(MachineOperand::MO_MCSymbol);
+ Op.Contents.Sym = Sym;
+ return Op;
+ }
+
+ friend class MachineInstr;
+ friend class MachineRegisterInfo;
+private:
+ //===--------------------------------------------------------------------===//
+ // Methods for handling register use/def lists.
+ //===--------------------------------------------------------------------===//
+
+ /// isOnRegUseList - Return true if this operand is on a register use/def list
+ /// or false if not. This can only be called for register operands that are
+ /// part of a machine instruction.
+ bool isOnRegUseList() const {
+ assert(isReg() && "Can only add reg operand to use lists");
+ return Contents.Reg.Prev != 0;
+ }
+};
+
+inline raw_ostream &operator<<(raw_ostream &OS, const MachineOperand& MO) {
+ MO.print(OS, 0);
+ return OS;
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachinePassRegistry.h b/include/llvm/CodeGen/MachinePassRegistry.h
new file mode 100644
index 00000000000..90ee7f4bb9e
--- /dev/null
+++ b/include/llvm/CodeGen/MachinePassRegistry.h
@@ -0,0 +1,158 @@
+//===-- llvm/CodeGen/MachinePassRegistry.h ----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the mechanics for machine function pass registries. A
+// function pass registry (MachinePassRegistry) is auto filled by the static
+// constructors of MachinePassRegistryNode. Further there is a command line
+// parser (RegisterPassParser) which listens to each registry for additions
+// and deletions, so that the appropriate command option is updated.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEPASSREGISTRY_H
+#define LLVM_CODEGEN_MACHINEPASSREGISTRY_H
+
+#include "llvm/CodeGen/Passes.h"
+#include "llvm/Support/CommandLine.h"
+
+namespace llvm {
+
+typedef void *(*MachinePassCtor)();
+
+
+//===----------------------------------------------------------------------===//
+///
+/// MachinePassRegistryListener - Listener to adds and removals of nodes in
+/// registration list.
+///
+//===----------------------------------------------------------------------===//
+class MachinePassRegistryListener {
+ virtual void anchor();
+public:
+ MachinePassRegistryListener() {}
+ virtual ~MachinePassRegistryListener() {}
+ virtual void NotifyAdd(const char *N, MachinePassCtor C, const char *D) = 0;
+ virtual void NotifyRemove(const char *N) = 0;
+};
+
+
+//===----------------------------------------------------------------------===//
+///
+/// MachinePassRegistryNode - Machine pass node stored in registration list.
+///
+//===----------------------------------------------------------------------===//
+class MachinePassRegistryNode {
+
+private:
+
+ MachinePassRegistryNode *Next; // Next function pass in list.
+ const char *Name; // Name of function pass.
+ const char *Description; // Description string.
+ MachinePassCtor Ctor; // Function pass creator.
+
+public:
+
+ MachinePassRegistryNode(const char *N, const char *D, MachinePassCtor C)
+ : Next(NULL)
+ , Name(N)
+ , Description(D)
+ , Ctor(C)
+ {}
+
+ // Accessors
+ MachinePassRegistryNode *getNext() const { return Next; }
+ MachinePassRegistryNode **getNextAddress() { return &Next; }
+ const char *getName() const { return Name; }
+ const char *getDescription() const { return Description; }
+ MachinePassCtor getCtor() const { return Ctor; }
+ void setNext(MachinePassRegistryNode *N) { Next = N; }
+
+};
+
+
+//===----------------------------------------------------------------------===//
+///
+/// MachinePassRegistry - Track the registration of machine passes.
+///
+//===----------------------------------------------------------------------===//
+class MachinePassRegistry {
+
+private:
+
+ MachinePassRegistryNode *List; // List of registry nodes.
+ MachinePassCtor Default; // Default function pass creator.
+ MachinePassRegistryListener* Listener;// Listener for list adds are removes.
+
+public:
+
+ // NO CONSTRUCTOR - we don't want static constructor ordering to mess
+ // with the registry.
+
+ // Accessors.
+ //
+ MachinePassRegistryNode *getList() { return List; }
+ MachinePassCtor getDefault() { return Default; }
+ void setDefault(MachinePassCtor C) { Default = C; }
+ void setDefault(StringRef Name);
+ void setListener(MachinePassRegistryListener *L) { Listener = L; }
+
+ /// Add - Adds a function pass to the registration list.
+ ///
+ void Add(MachinePassRegistryNode *Node);
+
+ /// Remove - Removes a function pass from the registration list.
+ ///
+ void Remove(MachinePassRegistryNode *Node);
+
+};
+
+
+//===----------------------------------------------------------------------===//
+///
+/// RegisterPassParser class - Handle the addition of new machine passes.
+///
+//===----------------------------------------------------------------------===//
+template<class RegistryClass>
+class RegisterPassParser : public MachinePassRegistryListener,
+ public cl::parser<typename RegistryClass::FunctionPassCtor> {
+public:
+ RegisterPassParser() {}
+ ~RegisterPassParser() { RegistryClass::setListener(NULL); }
+
+ void initialize(cl::Option &O) {
+ cl::parser<typename RegistryClass::FunctionPassCtor>::initialize(O);
+
+ // Add existing passes to option.
+ for (RegistryClass *Node = RegistryClass::getList();
+ Node; Node = Node->getNext()) {
+ this->addLiteralOption(Node->getName(),
+ (typename RegistryClass::FunctionPassCtor)Node->getCtor(),
+ Node->getDescription());
+ }
+
+ // Make sure we listen for list changes.
+ RegistryClass::setListener(this);
+ }
+
+ // Implement the MachinePassRegistryListener callbacks.
+ //
+ virtual void NotifyAdd(const char *N,
+ MachinePassCtor C,
+ const char *D) {
+ this->addLiteralOption(N, (typename RegistryClass::FunctionPassCtor)C, D);
+ }
+ virtual void NotifyRemove(const char *N) {
+ this->removeLiteralOption(N);
+ }
+};
+
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/MachinePostDominators.h b/include/llvm/CodeGen/MachinePostDominators.h
new file mode 100644
index 00000000000..a9fc8434abe
--- /dev/null
+++ b/include/llvm/CodeGen/MachinePostDominators.h
@@ -0,0 +1,87 @@
+//=- llvm/CodeGen/MachineDominators.h ----------------------------*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file exposes interfaces to post dominance information for
+// target-specific code.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEPOSTDOMINATORS_H
+#define LLVM_CODEGEN_MACHINEPOSTDOMINATORS_H
+
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/MachineDominators.h"
+#include "llvm/Analysis/Dominators.h"
+#include "llvm/Analysis/DominatorInternals.h"
+
+namespace llvm {
+
+///
+/// PostDominatorTree Class - Concrete subclass of DominatorTree that is used
+/// to compute the a post-dominator tree.
+///
+struct MachinePostDominatorTree : public MachineFunctionPass {
+private:
+ DominatorTreeBase<MachineBasicBlock> *DT;
+
+public:
+ static char ID;
+
+ MachinePostDominatorTree();
+
+ ~MachinePostDominatorTree();
+
+ FunctionPass *createMachinePostDominatorTreePass();
+
+ const std::vector<MachineBasicBlock *> &getRoots() const {
+ return DT->getRoots();
+ }
+
+ MachineDomTreeNode *getRootNode() const {
+ return DT->getRootNode();
+ }
+
+ MachineDomTreeNode *operator[](MachineBasicBlock *BB) const {
+ return DT->getNode(BB);
+ }
+
+ MachineDomTreeNode *getNode(MachineBasicBlock *BB) const {
+ return DT->getNode(BB);
+ }
+
+ bool dominates(MachineDomTreeNode *A, MachineDomTreeNode *B) const {
+ return DT->dominates(A, B);
+ }
+
+ bool dominates(MachineBasicBlock *A, MachineBasicBlock *B) const {
+ return DT->dominates(A, B);
+ }
+
+ bool
+ properlyDominates(const MachineDomTreeNode *A, MachineDomTreeNode *B) const {
+ return DT->properlyDominates(A, B);
+ }
+
+ bool
+ properlyDominates(MachineBasicBlock *A, MachineBasicBlock *B) const {
+ return DT->properlyDominates(A, B);
+ }
+
+ MachineBasicBlock *findNearestCommonDominator(MachineBasicBlock *A,
+ MachineBasicBlock *B) {
+ return DT->findNearestCommonDominator(A, B);
+ }
+
+ virtual bool runOnMachineFunction(MachineFunction &MF);
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+ virtual void print(llvm::raw_ostream &OS, const Module *M = 0) const;
+};
+} //end of namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/MachineRegisterInfo.h b/include/llvm/CodeGen/MachineRegisterInfo.h
new file mode 100644
index 00000000000..91d24dd0fc0
--- /dev/null
+++ b/include/llvm/CodeGen/MachineRegisterInfo.h
@@ -0,0 +1,584 @@
+//===-- llvm/CodeGen/MachineRegisterInfo.h ----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MachineRegisterInfo class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINEREGISTERINFO_H
+#define LLVM_CODEGEN_MACHINEREGISTERINFO_H
+
+#include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/CodeGen/MachineInstrBundle.h"
+#include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/IndexedMap.h"
+#include <vector>
+
+namespace llvm {
+
+/// MachineRegisterInfo - Keep track of information for virtual and physical
+/// registers, including vreg register classes, use/def chains for registers,
+/// etc.
+class MachineRegisterInfo {
+ const TargetRegisterInfo *const TRI;
+
+ /// IsSSA - True when the machine function is in SSA form and virtual
+ /// registers have a single def.
+ bool IsSSA;
+
+ /// TracksLiveness - True while register liveness is being tracked accurately.
+ /// Basic block live-in lists, kill flags, and implicit defs may not be
+ /// accurate when after this flag is cleared.
+ bool TracksLiveness;
+
+ /// VRegInfo - Information we keep for each virtual register.
+ ///
+ /// Each element in this list contains the register class of the vreg and the
+ /// start of the use/def list for the register.
+ IndexedMap<std::pair<const TargetRegisterClass*, MachineOperand*>,
+ VirtReg2IndexFunctor> VRegInfo;
+
+ /// RegAllocHints - This vector records register allocation hints for virtual
+ /// registers. For each virtual register, it keeps a register and hint type
+ /// pair making up the allocation hint. Hint type is target specific except
+ /// for the value 0 which means the second value of the pair is the preferred
+ /// register for allocation. For example, if the hint is <0, 1024>, it means
+ /// the allocator should prefer the physical register allocated to the virtual
+ /// register of the hint.
+ IndexedMap<std::pair<unsigned, unsigned>, VirtReg2IndexFunctor> RegAllocHints;
+
+ /// PhysRegUseDefLists - This is an array of the head of the use/def list for
+ /// physical registers.
+ MachineOperand **PhysRegUseDefLists;
+
+ /// getRegUseDefListHead - Return the head pointer for the register use/def
+ /// list for the specified virtual or physical register.
+ MachineOperand *&getRegUseDefListHead(unsigned RegNo) {
+ if (TargetRegisterInfo::isVirtualRegister(RegNo))
+ return VRegInfo[RegNo].second;
+ return PhysRegUseDefLists[RegNo];
+ }
+
+ MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
+ if (TargetRegisterInfo::isVirtualRegister(RegNo))
+ return VRegInfo[RegNo].second;
+ return PhysRegUseDefLists[RegNo];
+ }
+
+ /// Get the next element in the use-def chain.
+ static MachineOperand *getNextOperandForReg(const MachineOperand *MO) {
+ assert(MO && MO->isReg() && "This is not a register operand!");
+ return MO->Contents.Reg.Next;
+ }
+
+ /// UsedPhysRegs - This is a bit vector that is computed and set by the
+ /// register allocator, and must be kept up to date by passes that run after
+ /// register allocation (though most don't modify this). This is used
+ /// so that the code generator knows which callee save registers to save and
+ /// for other target specific uses.
+ /// This vector only has bits set for registers explicitly used, not their
+ /// aliases.
+ BitVector UsedPhysRegs;
+
+ /// UsedPhysRegMask - Additional used physregs, but including aliases.
+ BitVector UsedPhysRegMask;
+
+ /// ReservedRegs - This is a bit vector of reserved registers. The target
+ /// may change its mind about which registers should be reserved. This
+ /// vector is the frozen set of reserved registers when register allocation
+ /// started.
+ BitVector ReservedRegs;
+
+ /// AllocatableRegs - From TRI->getAllocatableSet.
+ mutable BitVector AllocatableRegs;
+
+ /// LiveIns/LiveOuts - Keep track of the physical registers that are
+ /// livein/liveout of the function. Live in values are typically arguments in
+ /// registers, live out values are typically return values in registers.
+ /// LiveIn values are allowed to have virtual registers associated with them,
+ /// stored in the second element.
+ std::vector<std::pair<unsigned, unsigned> > LiveIns;
+ std::vector<unsigned> LiveOuts;
+
+ MachineRegisterInfo(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
+ void operator=(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
+public:
+ explicit MachineRegisterInfo(const TargetRegisterInfo &TRI);
+ ~MachineRegisterInfo();
+
+ //===--------------------------------------------------------------------===//
+ // Function State
+ //===--------------------------------------------------------------------===//
+
+ // isSSA - Returns true when the machine function is in SSA form. Early
+ // passes require the machine function to be in SSA form where every virtual
+ // register has a single defining instruction.
+ //
+ // The TwoAddressInstructionPass and PHIElimination passes take the machine
+ // function out of SSA form when they introduce multiple defs per virtual
+ // register.
+ bool isSSA() const { return IsSSA; }
+
+ // leaveSSA - Indicates that the machine function is no longer in SSA form.
+ void leaveSSA() { IsSSA = false; }
+
+ /// tracksLiveness - Returns true when tracking register liveness accurately.
+ ///
+ /// While this flag is true, register liveness information in basic block
+ /// live-in lists and machine instruction operands is accurate. This means it
+ /// can be used to change the code in ways that affect the values in
+ /// registers, for example by the register scavenger.
+ ///
+ /// When this flag is false, liveness is no longer reliable.
+ bool tracksLiveness() const { return TracksLiveness; }
+
+ /// invalidateLiveness - Indicates that register liveness is no longer being
+ /// tracked accurately.
+ ///
+ /// This should be called by late passes that invalidate the liveness
+ /// information.
+ void invalidateLiveness() { TracksLiveness = false; }
+
+ //===--------------------------------------------------------------------===//
+ // Register Info
+ //===--------------------------------------------------------------------===//
+
+ // Strictly for use by MachineInstr.cpp.
+ void addRegOperandToUseList(MachineOperand *MO);
+
+ // Strictly for use by MachineInstr.cpp.
+ void removeRegOperandFromUseList(MachineOperand *MO);
+
+ /// reg_begin/reg_end - Provide iteration support to walk over all definitions
+ /// and uses of a register within the MachineFunction that corresponds to this
+ /// MachineRegisterInfo object.
+ template<bool Uses, bool Defs, bool SkipDebug>
+ class defusechain_iterator;
+
+ // Make it a friend so it can access getNextOperandForReg().
+ template<bool, bool, bool> friend class defusechain_iterator;
+
+ /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
+ /// register.
+ typedef defusechain_iterator<true,true,false> reg_iterator;
+ reg_iterator reg_begin(unsigned RegNo) const {
+ return reg_iterator(getRegUseDefListHead(RegNo));
+ }
+ static reg_iterator reg_end() { return reg_iterator(0); }
+
+ /// reg_empty - Return true if there are no instructions using or defining the
+ /// specified register (it may be live-in).
+ bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
+
+ /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
+ /// of the specified register, skipping those marked as Debug.
+ typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
+ reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
+ return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
+ }
+ static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
+
+ /// reg_nodbg_empty - Return true if the only instructions using or defining
+ /// Reg are Debug instructions.
+ bool reg_nodbg_empty(unsigned RegNo) const {
+ return reg_nodbg_begin(RegNo) == reg_nodbg_end();
+ }
+
+ /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
+ typedef defusechain_iterator<false,true,false> def_iterator;
+ def_iterator def_begin(unsigned RegNo) const {
+ return def_iterator(getRegUseDefListHead(RegNo));
+ }
+ static def_iterator def_end() { return def_iterator(0); }
+
+ /// def_empty - Return true if there are no instructions defining the
+ /// specified register (it may be live-in).
+ bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
+
+ /// hasOneDef - Return true if there is exactly one instruction defining the
+ /// specified register.
+ bool hasOneDef(unsigned RegNo) const {
+ def_iterator DI = def_begin(RegNo);
+ if (DI == def_end())
+ return false;
+ return ++DI == def_end();
+ }
+
+ /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
+ typedef defusechain_iterator<true,false,false> use_iterator;
+ use_iterator use_begin(unsigned RegNo) const {
+ return use_iterator(getRegUseDefListHead(RegNo));
+ }
+ static use_iterator use_end() { return use_iterator(0); }
+
+ /// use_empty - Return true if there are no instructions using the specified
+ /// register.
+ bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
+
+ /// hasOneUse - Return true if there is exactly one instruction using the
+ /// specified register.
+ bool hasOneUse(unsigned RegNo) const {
+ use_iterator UI = use_begin(RegNo);
+ if (UI == use_end())
+ return false;
+ return ++UI == use_end();
+ }
+
+ /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
+ /// specified register, skipping those marked as Debug.
+ typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
+ use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
+ return use_nodbg_iterator(getRegUseDefListHead(RegNo));
+ }
+ static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
+
+ /// use_nodbg_empty - Return true if there are no non-Debug instructions
+ /// using the specified register.
+ bool use_nodbg_empty(unsigned RegNo) const {
+ return use_nodbg_begin(RegNo) == use_nodbg_end();
+ }
+
+ /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
+ /// instruction using the specified register.
+ bool hasOneNonDBGUse(unsigned RegNo) const;
+
+ /// replaceRegWith - Replace all instances of FromReg with ToReg in the
+ /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
+ /// except that it also changes any definitions of the register as well.
+ ///
+ /// Note that it is usually necessary to first constrain ToReg's register
+ /// class to match the FromReg constraints using:
+ ///
+ /// constrainRegClass(ToReg, getRegClass(FromReg))
+ ///
+ /// That function will return NULL if the virtual registers have incompatible
+ /// constraints.
+ void replaceRegWith(unsigned FromReg, unsigned ToReg);
+
+ /// getVRegDef - Return the machine instr that defines the specified virtual
+ /// register or null if none is found. This assumes that the code is in SSA
+ /// form, so there should only be one definition.
+ MachineInstr *getVRegDef(unsigned Reg) const;
+
+ /// getUniqueVRegDef - Return the unique machine instr that defines the
+ /// specified virtual register or null if none is found. If there are
+ /// multiple definitions or no definition, return null.
+ MachineInstr *getUniqueVRegDef(unsigned Reg) const;
+
+ /// clearKillFlags - Iterate over all the uses of the given register and
+ /// clear the kill flag from the MachineOperand. This function is used by
+ /// optimization passes which extend register lifetimes and need only
+ /// preserve conservative kill flag information.
+ void clearKillFlags(unsigned Reg) const;
+
+#ifndef NDEBUG
+ void dumpUses(unsigned RegNo) const;
+#endif
+
+ /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
+ /// throughout the function. It is safe to move instructions that read such
+ /// a physreg.
+ bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
+
+ //===--------------------------------------------------------------------===//
+ // Virtual Register Info
+ //===--------------------------------------------------------------------===//
+
+ /// getRegClass - Return the register class of the specified virtual register.
+ ///
+ const TargetRegisterClass *getRegClass(unsigned Reg) const {
+ return VRegInfo[Reg].first;
+ }
+
+ /// setRegClass - Set the register class of the specified virtual register.
+ ///
+ void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
+
+ /// constrainRegClass - Constrain the register class of the specified virtual
+ /// register to be a common subclass of RC and the current register class,
+ /// but only if the new class has at least MinNumRegs registers. Return the
+ /// new register class, or NULL if no such class exists.
+ /// This should only be used when the constraint is known to be trivial, like
+ /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
+ ///
+ const TargetRegisterClass *constrainRegClass(unsigned Reg,
+ const TargetRegisterClass *RC,
+ unsigned MinNumRegs = 0);
+
+ /// recomputeRegClass - Try to find a legal super-class of Reg's register
+ /// class that still satisfies the constraints from the instructions using
+ /// Reg. Returns true if Reg was upgraded.
+ ///
+ /// This method can be used after constraints have been removed from a
+ /// virtual register, for example after removing instructions or splitting
+ /// the live range.
+ ///
+ bool recomputeRegClass(unsigned Reg, const TargetMachine&);
+
+ /// createVirtualRegister - Create and return a new virtual register in the
+ /// function with the specified register class.
+ ///
+ unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
+
+ /// getNumVirtRegs - Return the number of virtual registers created.
+ ///
+ unsigned getNumVirtRegs() const { return VRegInfo.size(); }
+
+ /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
+ void clearVirtRegs();
+
+ /// setRegAllocationHint - Specify a register allocation hint for the
+ /// specified virtual register.
+ void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
+ RegAllocHints[Reg].first = Type;
+ RegAllocHints[Reg].second = PrefReg;
+ }
+
+ /// getRegAllocationHint - Return the register allocation hint for the
+ /// specified virtual register.
+ std::pair<unsigned, unsigned>
+ getRegAllocationHint(unsigned Reg) const {
+ return RegAllocHints[Reg];
+ }
+
+ /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
+ /// standard simple hint (Type == 0) is not set.
+ unsigned getSimpleHint(unsigned Reg) const {
+ std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
+ return Hint.first ? 0 : Hint.second;
+ }
+
+
+ //===--------------------------------------------------------------------===//
+ // Physical Register Use Info
+ //===--------------------------------------------------------------------===//
+
+ /// isPhysRegUsed - Return true if the specified register is used in this
+ /// function. This only works after register allocation.
+ bool isPhysRegUsed(unsigned Reg) const {
+ return UsedPhysRegs.test(Reg) || UsedPhysRegMask.test(Reg);
+ }
+
+ /// isPhysRegOrOverlapUsed - Return true if Reg or any overlapping register
+ /// is used in this function.
+ bool isPhysRegOrOverlapUsed(unsigned Reg) const {
+ if (UsedPhysRegMask.test(Reg))
+ return true;
+ for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
+ if (UsedPhysRegs.test(*AI))
+ return true;
+ return false;
+ }
+
+ /// setPhysRegUsed - Mark the specified register used in this function.
+ /// This should only be called during and after register allocation.
+ void setPhysRegUsed(unsigned Reg) { UsedPhysRegs.set(Reg); }
+
+ /// addPhysRegsUsed - Mark the specified registers used in this function.
+ /// This should only be called during and after register allocation.
+ void addPhysRegsUsed(const BitVector &Regs) { UsedPhysRegs |= Regs; }
+
+ /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
+ /// This corresponds to the bit mask attached to register mask operands.
+ void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
+ UsedPhysRegMask.setBitsNotInMask(RegMask);
+ }
+
+ /// setPhysRegUnused - Mark the specified register unused in this function.
+ /// This should only be called during and after register allocation.
+ void setPhysRegUnused(unsigned Reg) {
+ UsedPhysRegs.reset(Reg);
+ UsedPhysRegMask.reset(Reg);
+ }
+
+
+ //===--------------------------------------------------------------------===//
+ // Reserved Register Info
+ //===--------------------------------------------------------------------===//
+ //
+ // The set of reserved registers must be invariant during register
+ // allocation. For example, the target cannot suddenly decide it needs a
+ // frame pointer when the register allocator has already used the frame
+ // pointer register for something else.
+ //
+ // These methods can be used by target hooks like hasFP() to avoid changing
+ // the reserved register set during register allocation.
+
+ /// freezeReservedRegs - Called by the register allocator to freeze the set
+ /// of reserved registers before allocation begins.
+ void freezeReservedRegs(const MachineFunction&);
+
+ /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
+ /// to ensure the set of reserved registers stays constant.
+ bool reservedRegsFrozen() const {
+ return !ReservedRegs.empty();
+ }
+
+ /// canReserveReg - Returns true if PhysReg can be used as a reserved
+ /// register. Any register can be reserved before freezeReservedRegs() is
+ /// called.
+ bool canReserveReg(unsigned PhysReg) const {
+ return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
+ }
+
+
+ //===--------------------------------------------------------------------===//
+ // LiveIn/LiveOut Management
+ //===--------------------------------------------------------------------===//
+
+ /// addLiveIn/Out - Add the specified register as a live in/out. Note that it
+ /// is an error to add the same register to the same set more than once.
+ void addLiveIn(unsigned Reg, unsigned vreg = 0) {
+ LiveIns.push_back(std::make_pair(Reg, vreg));
+ }
+ void addLiveOut(unsigned Reg) { LiveOuts.push_back(Reg); }
+
+ // Iteration support for live in/out sets. These sets are kept in sorted
+ // order by their register number.
+ typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
+ livein_iterator;
+ typedef std::vector<unsigned>::const_iterator liveout_iterator;
+ livein_iterator livein_begin() const { return LiveIns.begin(); }
+ livein_iterator livein_end() const { return LiveIns.end(); }
+ bool livein_empty() const { return LiveIns.empty(); }
+ liveout_iterator liveout_begin() const { return LiveOuts.begin(); }
+ liveout_iterator liveout_end() const { return LiveOuts.end(); }
+ bool liveout_empty() const { return LiveOuts.empty(); }
+
+ bool isLiveIn(unsigned Reg) const;
+ bool isLiveOut(unsigned Reg) const;
+
+ /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
+ /// corresponding live-in physical register.
+ unsigned getLiveInPhysReg(unsigned VReg) const;
+
+ /// getLiveInVirtReg - If PReg is a live-in physical register, return the
+ /// corresponding live-in physical register.
+ unsigned getLiveInVirtReg(unsigned PReg) const;
+
+ /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
+ /// into the given entry block.
+ void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
+ const TargetRegisterInfo &TRI,
+ const TargetInstrInfo &TII);
+
+ /// defusechain_iterator - This class provides iterator support for machine
+ /// operands in the function that use or define a specific register. If
+ /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
+ /// returns defs. If neither are true then you are silly and it always
+ /// returns end(). If SkipDebug is true it skips uses marked Debug
+ /// when incrementing.
+ template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
+ class defusechain_iterator
+ : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
+ MachineOperand *Op;
+ explicit defusechain_iterator(MachineOperand *op) : Op(op) {
+ // If the first node isn't one we're interested in, advance to one that
+ // we are interested in.
+ if (op) {
+ if ((!ReturnUses && op->isUse()) ||
+ (!ReturnDefs && op->isDef()) ||
+ (SkipDebug && op->isDebug()))
+ ++*this;
+ }
+ }
+ friend class MachineRegisterInfo;
+ public:
+ typedef std::iterator<std::forward_iterator_tag,
+ MachineInstr, ptrdiff_t>::reference reference;
+ typedef std::iterator<std::forward_iterator_tag,
+ MachineInstr, ptrdiff_t>::pointer pointer;
+
+ defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
+ defusechain_iterator() : Op(0) {}
+
+ bool operator==(const defusechain_iterator &x) const {
+ return Op == x.Op;
+ }
+ bool operator!=(const defusechain_iterator &x) const {
+ return !operator==(x);
+ }
+
+ /// atEnd - return true if this iterator is equal to reg_end() on the value.
+ bool atEnd() const { return Op == 0; }
+
+ // Iterator traversal: forward iteration only
+ defusechain_iterator &operator++() { // Preincrement
+ assert(Op && "Cannot increment end iterator!");
+ Op = getNextOperandForReg(Op);
+
+ // All defs come before the uses, so stop def_iterator early.
+ if (!ReturnUses) {
+ if (Op) {
+ if (Op->isUse())
+ Op = 0;
+ else
+ assert(!Op->isDebug() && "Can't have debug defs");
+ }
+ } else {
+ // If this is an operand we don't care about, skip it.
+ while (Op && ((!ReturnDefs && Op->isDef()) ||
+ (SkipDebug && Op->isDebug())))
+ Op = getNextOperandForReg(Op);
+ }
+
+ return *this;
+ }
+ defusechain_iterator operator++(int) { // Postincrement
+ defusechain_iterator tmp = *this; ++*this; return tmp;
+ }
+
+ /// skipInstruction - move forward until reaching a different instruction.
+ /// Return the skipped instruction that is no longer pointed to, or NULL if
+ /// already pointing to end().
+ MachineInstr *skipInstruction() {
+ if (!Op) return 0;
+ MachineInstr *MI = Op->getParent();
+ do ++*this;
+ while (Op && Op->getParent() == MI);
+ return MI;
+ }
+
+ MachineInstr *skipBundle() {
+ if (!Op) return 0;
+ MachineInstr *MI = getBundleStart(Op->getParent());
+ do ++*this;
+ while (Op && getBundleStart(Op->getParent()) == MI);
+ return MI;
+ }
+
+ MachineOperand &getOperand() const {
+ assert(Op && "Cannot dereference end iterator!");
+ return *Op;
+ }
+
+ /// getOperandNo - Return the operand # of this MachineOperand in its
+ /// MachineInstr.
+ unsigned getOperandNo() const {
+ assert(Op && "Cannot dereference end iterator!");
+ return Op - &Op->getParent()->getOperand(0);
+ }
+
+ // Retrieve a reference to the current operand.
+ MachineInstr &operator*() const {
+ assert(Op && "Cannot dereference end iterator!");
+ return *Op->getParent();
+ }
+
+ MachineInstr *operator->() const {
+ assert(Op && "Cannot dereference end iterator!");
+ return Op->getParent();
+ }
+ };
+
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineRelocation.h b/include/llvm/CodeGen/MachineRelocation.h
new file mode 100644
index 00000000000..244b466e172
--- /dev/null
+++ b/include/llvm/CodeGen/MachineRelocation.h
@@ -0,0 +1,342 @@
+//===-- llvm/CodeGen/MachineRelocation.h - Target Relocation ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MachineRelocation class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINERELOCATION_H
+#define LLVM_CODEGEN_MACHINERELOCATION_H
+
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+
+namespace llvm {
+class GlobalValue;
+class MachineBasicBlock;
+
+/// MachineRelocation - This represents a target-specific relocation value,
+/// produced by the code emitter. This relocation is resolved after the has
+/// been emitted, either to an object file or to memory, when the target of the
+/// relocation can be resolved.
+///
+/// A relocation is made up of the following logical portions:
+/// 1. An offset in the machine code buffer, the location to modify.
+/// 2. A target specific relocation type (a number from 0 to 63).
+/// 3. A symbol being referenced, either as a GlobalValue* or as a string.
+/// 4. An optional constant value to be added to the reference.
+/// 5. A bit, CanRewrite, which indicates to the JIT that a function stub is
+/// not needed for the relocation.
+/// 6. An index into the GOT, if the target uses a GOT
+///
+class MachineRelocation {
+ enum AddressType {
+ isResult, // Relocation has be transformed into its result pointer.
+ isGV, // The Target.GV field is valid.
+ isIndirectSym, // Relocation of an indirect symbol.
+ isBB, // Relocation of BB address.
+ isExtSym, // The Target.ExtSym field is valid.
+ isConstPool, // Relocation of constant pool address.
+ isJumpTable, // Relocation of jump table address.
+ isGOTIndex // The Target.GOTIndex field is valid.
+ };
+
+ /// Offset - This is the offset from the start of the code buffer of the
+ /// relocation to perform.
+ uintptr_t Offset;
+
+ /// ConstantVal - A field that may be used by the target relocation type.
+ intptr_t ConstantVal;
+
+ union {
+ void *Result; // If this has been resolved to a resolved pointer
+ GlobalValue *GV; // If this is a pointer to a GV or an indirect ref.
+ MachineBasicBlock *MBB; // If this is a pointer to a LLVM BB
+ const char *ExtSym; // If this is a pointer to a named symbol
+ unsigned Index; // Constant pool / jump table index
+ unsigned GOTIndex; // Index in the GOT of this symbol/global
+ } Target;
+
+ unsigned TargetReloType : 6; // The target relocation ID
+ AddressType AddrType : 4; // The field of Target to use
+ bool MayNeedFarStub : 1; // True if this relocation may require a far-stub
+ bool GOTRelative : 1; // Should this relocation be relative to the GOT?
+ bool TargetResolve : 1; // True if target should resolve the address
+
+public:
+ // Relocation types used in a generic implementation. Currently, relocation
+ // entries for all things use the generic VANILLA type until they are refined
+ // into target relocation types.
+ enum RelocationType {
+ VANILLA
+ };
+
+ /// MachineRelocation::getGV - Return a relocation entry for a GlobalValue.
+ ///
+ static MachineRelocation getGV(uintptr_t offset, unsigned RelocationType,
+ GlobalValue *GV, intptr_t cst = 0,
+ bool MayNeedFarStub = 0,
+ bool GOTrelative = 0) {
+ assert((RelocationType & ~63) == 0 && "Relocation type too large!");
+ MachineRelocation Result;
+ Result.Offset = offset;
+ Result.ConstantVal = cst;
+ Result.TargetReloType = RelocationType;
+ Result.AddrType = isGV;
+ Result.MayNeedFarStub = MayNeedFarStub;
+ Result.GOTRelative = GOTrelative;
+ Result.TargetResolve = false;
+ Result.Target.GV = GV;
+ return Result;
+ }
+
+ /// MachineRelocation::getIndirectSymbol - Return a relocation entry for an
+ /// indirect symbol.
+ static MachineRelocation getIndirectSymbol(uintptr_t offset,
+ unsigned RelocationType,
+ GlobalValue *GV, intptr_t cst = 0,
+ bool MayNeedFarStub = 0,
+ bool GOTrelative = 0) {
+ assert((RelocationType & ~63) == 0 && "Relocation type too large!");
+ MachineRelocation Result;
+ Result.Offset = offset;
+ Result.ConstantVal = cst;
+ Result.TargetReloType = RelocationType;
+ Result.AddrType = isIndirectSym;
+ Result.MayNeedFarStub = MayNeedFarStub;
+ Result.GOTRelative = GOTrelative;
+ Result.TargetResolve = false;
+ Result.Target.GV = GV;
+ return Result;
+ }
+
+ /// MachineRelocation::getBB - Return a relocation entry for a BB.
+ ///
+ static MachineRelocation getBB(uintptr_t offset,unsigned RelocationType,
+ MachineBasicBlock *MBB, intptr_t cst = 0) {
+ assert((RelocationType & ~63) == 0 && "Relocation type too large!");
+ MachineRelocation Result;
+ Result.Offset = offset;
+ Result.ConstantVal = cst;
+ Result.TargetReloType = RelocationType;
+ Result.AddrType = isBB;
+ Result.MayNeedFarStub = false;
+ Result.GOTRelative = false;
+ Result.TargetResolve = false;
+ Result.Target.MBB = MBB;
+ return Result;
+ }
+
+ /// MachineRelocation::getExtSym - Return a relocation entry for an external
+ /// symbol, like "free".
+ ///
+ static MachineRelocation getExtSym(uintptr_t offset, unsigned RelocationType,
+ const char *ES, intptr_t cst = 0,
+ bool GOTrelative = 0,
+ bool NeedStub = true) {
+ assert((RelocationType & ~63) == 0 && "Relocation type too large!");
+ MachineRelocation Result;
+ Result.Offset = offset;
+ Result.ConstantVal = cst;
+ Result.TargetReloType = RelocationType;
+ Result.AddrType = isExtSym;
+ Result.MayNeedFarStub = NeedStub;
+ Result.GOTRelative = GOTrelative;
+ Result.TargetResolve = false;
+ Result.Target.ExtSym = ES;
+ return Result;
+ }
+
+ /// MachineRelocation::getConstPool - Return a relocation entry for a constant
+ /// pool entry.
+ ///
+ static MachineRelocation getConstPool(uintptr_t offset,unsigned RelocationType,
+ unsigned CPI, intptr_t cst = 0,
+ bool letTargetResolve = false) {
+ assert((RelocationType & ~63) == 0 && "Relocation type too large!");
+ MachineRelocation Result;
+ Result.Offset = offset;
+ Result.ConstantVal = cst;
+ Result.TargetReloType = RelocationType;
+ Result.AddrType = isConstPool;
+ Result.MayNeedFarStub = false;
+ Result.GOTRelative = false;
+ Result.TargetResolve = letTargetResolve;
+ Result.Target.Index = CPI;
+ return Result;
+ }
+
+ /// MachineRelocation::getJumpTable - Return a relocation entry for a jump
+ /// table entry.
+ ///
+ static MachineRelocation getJumpTable(uintptr_t offset,unsigned RelocationType,
+ unsigned JTI, intptr_t cst = 0,
+ bool letTargetResolve = false) {
+ assert((RelocationType & ~63) == 0 && "Relocation type too large!");
+ MachineRelocation Result;
+ Result.Offset = offset;
+ Result.ConstantVal = cst;
+ Result.TargetReloType = RelocationType;
+ Result.AddrType = isJumpTable;
+ Result.MayNeedFarStub = false;
+ Result.GOTRelative = false;
+ Result.TargetResolve = letTargetResolve;
+ Result.Target.Index = JTI;
+ return Result;
+ }
+
+ /// getMachineCodeOffset - Return the offset into the code buffer that the
+ /// relocation should be performed.
+ intptr_t getMachineCodeOffset() const {
+ return Offset;
+ }
+
+ /// getRelocationType - Return the target-specific relocation ID for this
+ /// relocation.
+ unsigned getRelocationType() const {
+ return TargetReloType;
+ }
+
+ /// getConstantVal - Get the constant value associated with this relocation.
+ /// This is often an offset from the symbol.
+ ///
+ intptr_t getConstantVal() const {
+ return ConstantVal;
+ }
+
+ /// setConstantVal - Set the constant value associated with this relocation.
+ /// This is often an offset from the symbol.
+ ///
+ void setConstantVal(intptr_t val) {
+ ConstantVal = val;
+ }
+
+ /// isGlobalValue - Return true if this relocation is a GlobalValue, as
+ /// opposed to a constant string.
+ bool isGlobalValue() const {
+ return AddrType == isGV;
+ }
+
+ /// isIndirectSymbol - Return true if this relocation is the address an
+ /// indirect symbol
+ bool isIndirectSymbol() const {
+ return AddrType == isIndirectSym;
+ }
+
+ /// isBasicBlock - Return true if this relocation is a basic block reference.
+ ///
+ bool isBasicBlock() const {
+ return AddrType == isBB;
+ }
+
+ /// isExternalSymbol - Return true if this is a constant string.
+ ///
+ bool isExternalSymbol() const {
+ return AddrType == isExtSym;
+ }
+
+ /// isConstantPoolIndex - Return true if this is a constant pool reference.
+ ///
+ bool isConstantPoolIndex() const {
+ return AddrType == isConstPool;
+ }
+
+ /// isJumpTableIndex - Return true if this is a jump table reference.
+ ///
+ bool isJumpTableIndex() const {
+ return AddrType == isJumpTable;
+ }
+
+ /// isGOTRelative - Return true the target wants the index into the GOT of
+ /// the symbol rather than the address of the symbol.
+ bool isGOTRelative() const {
+ return GOTRelative;
+ }
+
+ /// mayNeedFarStub - This function returns true if the JIT for this target may
+ /// need either a stub function or an indirect global-variable load to handle
+ /// the relocated GlobalValue reference. For example, the x86-64 call
+ /// instruction can only call functions within +/-2GB of the call site.
+ /// Anything farther away needs a longer mov+call sequence, which can't just
+ /// be written on top of the existing call.
+ bool mayNeedFarStub() const {
+ return MayNeedFarStub;
+ }
+
+ /// letTargetResolve - Return true if the target JITInfo is usually
+ /// responsible for resolving the address of this relocation.
+ bool letTargetResolve() const {
+ return TargetResolve;
+ }
+
+ /// getGlobalValue - If this is a global value reference, return the
+ /// referenced global.
+ GlobalValue *getGlobalValue() const {
+ assert((isGlobalValue() || isIndirectSymbol()) &&
+ "This is not a global value reference!");
+ return Target.GV;
+ }
+
+ MachineBasicBlock *getBasicBlock() const {
+ assert(isBasicBlock() && "This is not a basic block reference!");
+ return Target.MBB;
+ }
+
+ /// getString - If this is a string value, return the string reference.
+ ///
+ const char *getExternalSymbol() const {
+ assert(isExternalSymbol() && "This is not an external symbol reference!");
+ return Target.ExtSym;
+ }
+
+ /// getConstantPoolIndex - If this is a const pool reference, return
+ /// the index into the constant pool.
+ unsigned getConstantPoolIndex() const {
+ assert(isConstantPoolIndex() && "This is not a constant pool reference!");
+ return Target.Index;
+ }
+
+ /// getJumpTableIndex - If this is a jump table reference, return
+ /// the index into the jump table.
+ unsigned getJumpTableIndex() const {
+ assert(isJumpTableIndex() && "This is not a jump table reference!");
+ return Target.Index;
+ }
+
+ /// getResultPointer - Once this has been resolved to point to an actual
+ /// address, this returns the pointer.
+ void *getResultPointer() const {
+ assert(AddrType == isResult && "Result pointer isn't set yet!");
+ return Target.Result;
+ }
+
+ /// setResultPointer - Set the result to the specified pointer value.
+ ///
+ void setResultPointer(void *Ptr) {
+ Target.Result = Ptr;
+ AddrType = isResult;
+ }
+
+ /// setGOTIndex - Set the GOT index to a specific value.
+ void setGOTIndex(unsigned idx) {
+ AddrType = isGOTIndex;
+ Target.GOTIndex = idx;
+ }
+
+ /// getGOTIndex - Once this has been resolved to an entry in the GOT,
+ /// this returns that index. The index is from the lowest address entry
+ /// in the GOT.
+ unsigned getGOTIndex() const {
+ assert(AddrType == isGOTIndex);
+ return Target.GOTIndex;
+ }
+};
+}
+
+#endif
diff --git a/include/llvm/CodeGen/MachineSSAUpdater.h b/include/llvm/CodeGen/MachineSSAUpdater.h
new file mode 100644
index 00000000000..edf93d13bd1
--- /dev/null
+++ b/include/llvm/CodeGen/MachineSSAUpdater.h
@@ -0,0 +1,117 @@
+//===-- MachineSSAUpdater.h - Unstructured SSA Update Tool ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the MachineSSAUpdater class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_MACHINESSAUPDATER_H
+#define LLVM_CODEGEN_MACHINESSAUPDATER_H
+
+#include "llvm/Support/Compiler.h"
+
+namespace llvm {
+ class MachineBasicBlock;
+ class MachineFunction;
+ class MachineInstr;
+ class MachineOperand;
+ class MachineRegisterInfo;
+ class TargetInstrInfo;
+ class TargetRegisterClass;
+ template<typename T> class SmallVectorImpl;
+ template<typename T> class SSAUpdaterTraits;
+ class BumpPtrAllocator;
+
+/// MachineSSAUpdater - This class updates SSA form for a set of virtual
+/// registers defined in multiple blocks. This is used when code duplication
+/// or another unstructured transformation wants to rewrite a set of uses of one
+/// vreg with uses of a set of vregs.
+class MachineSSAUpdater {
+ friend class SSAUpdaterTraits<MachineSSAUpdater>;
+
+private:
+ /// AvailableVals - This keeps track of which value to use on a per-block
+ /// basis. When we insert PHI nodes, we keep track of them here.
+ //typedef DenseMap<MachineBasicBlock*, unsigned > AvailableValsTy;
+ void *AV;
+
+ /// VR - Current virtual register whose uses are being updated.
+ unsigned VR;
+
+ /// VRC - Register class of the current virtual register.
+ const TargetRegisterClass *VRC;
+
+ /// InsertedPHIs - If this is non-null, the MachineSSAUpdater adds all PHI
+ /// nodes that it creates to the vector.
+ SmallVectorImpl<MachineInstr*> *InsertedPHIs;
+
+ const TargetInstrInfo *TII;
+ MachineRegisterInfo *MRI;
+public:
+ /// MachineSSAUpdater constructor. If InsertedPHIs is specified, it will be
+ /// filled in with all PHI Nodes created by rewriting.
+ explicit MachineSSAUpdater(MachineFunction &MF,
+ SmallVectorImpl<MachineInstr*> *InsertedPHIs = 0);
+ ~MachineSSAUpdater();
+
+ /// Initialize - Reset this object to get ready for a new set of SSA
+ /// updates.
+ void Initialize(unsigned V);
+
+ /// AddAvailableValue - Indicate that a rewritten value is available at the
+ /// end of the specified block with the specified value.
+ void AddAvailableValue(MachineBasicBlock *BB, unsigned V);
+
+ /// HasValueForBlock - Return true if the MachineSSAUpdater already has a
+ /// value for the specified block.
+ bool HasValueForBlock(MachineBasicBlock *BB) const;
+
+ /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
+ /// live at the end of the specified block.
+ unsigned GetValueAtEndOfBlock(MachineBasicBlock *BB);
+
+ /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
+ /// is live in the middle of the specified block.
+ ///
+ /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
+ /// important case: if there is a definition of the rewritten value after the
+ /// 'use' in BB. Consider code like this:
+ ///
+ /// X1 = ...
+ /// SomeBB:
+ /// use(X)
+ /// X2 = ...
+ /// br Cond, SomeBB, OutBB
+ ///
+ /// In this case, there are two values (X1 and X2) added to the AvailableVals
+ /// set by the client of the rewriter, and those values are both live out of
+ /// their respective blocks. However, the use of X happens in the *middle* of
+ /// a block. Because of this, we need to insert a new PHI node in SomeBB to
+ /// merge the appropriate values, and this value isn't live out of the block.
+ ///
+ unsigned GetValueInMiddleOfBlock(MachineBasicBlock *BB);
+
+ /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
+ /// which use their value in the corresponding predecessor. Note that this
+ /// will not work if the use is supposed to be rewritten to a value defined in
+ /// the same block as the use, but above it. Any 'AddAvailableValue's added
+ /// for the use's block will be considered to be below it.
+ void RewriteUse(MachineOperand &U);
+
+private:
+ void ReplaceRegWith(unsigned OldReg, unsigned NewReg);
+ unsigned GetValueAtEndOfBlockInternal(MachineBasicBlock *BB);
+
+ void operator=(const MachineSSAUpdater&) LLVM_DELETED_FUNCTION;
+ MachineSSAUpdater(const MachineSSAUpdater&) LLVM_DELETED_FUNCTION;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/MachineScheduler.h b/include/llvm/CodeGen/MachineScheduler.h
new file mode 100644
index 00000000000..d88f3fc57d6
--- /dev/null
+++ b/include/llvm/CodeGen/MachineScheduler.h
@@ -0,0 +1,338 @@
+//==- MachineScheduler.h - MachineInstr Scheduling Pass ----------*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file provides a MachineSchedRegistry for registering alternative machine
+// schedulers. A Target may provide an alternative scheduler implementation by
+// implementing the following boilerplate:
+//
+// static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
+// return new CustomMachineScheduler(C);
+// }
+// static MachineSchedRegistry
+// SchedCustomRegistry("custom", "Run my target's custom scheduler",
+// createCustomMachineSched);
+//
+// Inside <Target>PassConfig:
+// enablePass(&MachineSchedulerID);
+// MachineSchedRegistry::setDefault(createCustomMachineSched);
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MACHINESCHEDULER_H
+#define MACHINESCHEDULER_H
+
+#include "llvm/CodeGen/MachinePassRegistry.h"
+#include "llvm/CodeGen/RegisterPressure.h"
+#include "llvm/CodeGen/ScheduleDAGInstrs.h"
+#include "llvm/Target/TargetInstrInfo.h"
+#include "llvm/MC/MCInstrItineraries.h"
+
+namespace llvm {
+
+extern cl::opt<bool> ForceTopDown;
+extern cl::opt<bool> ForceBottomUp;
+
+class AliasAnalysis;
+class LiveIntervals;
+class MachineDominatorTree;
+class MachineLoopInfo;
+class RegisterClassInfo;
+class ScheduleDAGInstrs;
+
+/// MachineSchedContext provides enough context from the MachineScheduler pass
+/// for the target to instantiate a scheduler.
+struct MachineSchedContext {
+ MachineFunction *MF;
+ const MachineLoopInfo *MLI;
+ const MachineDominatorTree *MDT;
+ const TargetPassConfig *PassConfig;
+ AliasAnalysis *AA;
+ LiveIntervals *LIS;
+
+ RegisterClassInfo *RegClassInfo;
+
+ MachineSchedContext();
+ virtual ~MachineSchedContext();
+};
+
+/// MachineSchedRegistry provides a selection of available machine instruction
+/// schedulers.
+class MachineSchedRegistry : public MachinePassRegistryNode {
+public:
+ typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
+
+ // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
+ typedef ScheduleDAGCtor FunctionPassCtor;
+
+ static MachinePassRegistry Registry;
+
+ MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
+ : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
+ Registry.Add(this);
+ }
+ ~MachineSchedRegistry() { Registry.Remove(this); }
+
+ // Accessors.
+ //
+ MachineSchedRegistry *getNext() const {
+ return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
+ }
+ static MachineSchedRegistry *getList() {
+ return (MachineSchedRegistry *)Registry.getList();
+ }
+ static ScheduleDAGCtor getDefault() {
+ return (ScheduleDAGCtor)Registry.getDefault();
+ }
+ static void setDefault(ScheduleDAGCtor C) {
+ Registry.setDefault((MachinePassCtor)C);
+ }
+ static void setDefault(StringRef Name) {
+ Registry.setDefault(Name);
+ }
+ static void setListener(MachinePassRegistryListener *L) {
+ Registry.setListener(L);
+ }
+};
+
+class ScheduleDAGMI;
+
+/// MachineSchedStrategy - Interface to the scheduling algorithm used by
+/// ScheduleDAGMI.
+class MachineSchedStrategy {
+public:
+ virtual ~MachineSchedStrategy() {}
+
+ /// Initialize the strategy after building the DAG for a new region.
+ virtual void initialize(ScheduleDAGMI *DAG) = 0;
+
+ /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
+ /// schedule the node at the top of the unscheduled region. Otherwise it will
+ /// be scheduled at the bottom.
+ virtual SUnit *pickNode(bool &IsTopNode) = 0;
+
+ /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
+ /// instruction and updated scheduled/remaining flags in the DAG nodes.
+ virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
+
+ /// When all predecessor dependencies have been resolved, free this node for
+ /// top-down scheduling.
+ virtual void releaseTopNode(SUnit *SU) = 0;
+ /// When all successor dependencies have been resolved, free this node for
+ /// bottom-up scheduling.
+ virtual void releaseBottomNode(SUnit *SU) = 0;
+};
+
+/// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
+/// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
+/// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
+///
+/// This is a convenience class that may be used by implementations of
+/// MachineSchedStrategy.
+class ReadyQueue {
+ unsigned ID;
+ std::string Name;
+ std::vector<SUnit*> Queue;
+
+public:
+ ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
+
+ unsigned getID() const { return ID; }
+
+ StringRef getName() const { return Name; }
+
+ // SU is in this queue if it's NodeQueueID is a superset of this ID.
+ bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
+
+ bool empty() const { return Queue.empty(); }
+
+ unsigned size() const { return Queue.size(); }
+
+ typedef std::vector<SUnit*>::iterator iterator;
+
+ iterator begin() { return Queue.begin(); }
+
+ iterator end() { return Queue.end(); }
+
+ iterator find(SUnit *SU) {
+ return std::find(Queue.begin(), Queue.end(), SU);
+ }
+
+ void push(SUnit *SU) {
+ Queue.push_back(SU);
+ SU->NodeQueueId |= ID;
+ }
+
+ void remove(iterator I) {
+ (*I)->NodeQueueId &= ~ID;
+ *I = Queue.back();
+ Queue.pop_back();
+ }
+
+#ifndef NDEBUG
+ void dump();
+#endif
+};
+
+/// Mutate the DAG as a postpass after normal DAG building.
+class ScheduleDAGMutation {
+public:
+ virtual ~ScheduleDAGMutation() {}
+
+ virtual void apply(ScheduleDAGMI *DAG) = 0;
+};
+
+/// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
+/// machine instructions while updating LiveIntervals and tracking regpressure.
+class ScheduleDAGMI : public ScheduleDAGInstrs {
+protected:
+ AliasAnalysis *AA;
+ RegisterClassInfo *RegClassInfo;
+ MachineSchedStrategy *SchedImpl;
+
+ /// Ordered list of DAG postprocessing steps.
+ std::vector<ScheduleDAGMutation*> Mutations;
+
+ MachineBasicBlock::iterator LiveRegionEnd;
+
+ /// Register pressure in this region computed by buildSchedGraph.
+ IntervalPressure RegPressure;
+ RegPressureTracker RPTracker;
+
+ /// List of pressure sets that exceed the target's pressure limit before
+ /// scheduling, listed in increasing set ID order. Each pressure set is paired
+ /// with its max pressure in the currently scheduled regions.
+ std::vector<PressureElement> RegionCriticalPSets;
+
+ /// The top of the unscheduled zone.
+ MachineBasicBlock::iterator CurrentTop;
+ IntervalPressure TopPressure;
+ RegPressureTracker TopRPTracker;
+
+ /// The bottom of the unscheduled zone.
+ MachineBasicBlock::iterator CurrentBottom;
+ IntervalPressure BotPressure;
+ RegPressureTracker BotRPTracker;
+
+#ifndef NDEBUG
+ /// The number of instructions scheduled so far. Used to cut off the
+ /// scheduler at the point determined by misched-cutoff.
+ unsigned NumInstrsScheduled;
+#endif
+
+public:
+ ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
+ ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
+ AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S),
+ RPTracker(RegPressure), CurrentTop(), TopRPTracker(TopPressure),
+ CurrentBottom(), BotRPTracker(BotPressure) {
+#ifndef NDEBUG
+ NumInstrsScheduled = 0;
+#endif
+ }
+
+ virtual ~ScheduleDAGMI() {
+ delete SchedImpl;
+ }
+
+ /// Add a postprocessing step to the DAG builder.
+ /// Mutations are applied in the order that they are added after normal DAG
+ /// building and before MachineSchedStrategy initialization.
+ void addMutation(ScheduleDAGMutation *Mutation) {
+ Mutations.push_back(Mutation);
+ }
+
+ MachineBasicBlock::iterator top() const { return CurrentTop; }
+ MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
+
+ /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
+ /// region. This covers all instructions in a block, while schedule() may only
+ /// cover a subset.
+ void enterRegion(MachineBasicBlock *bb,
+ MachineBasicBlock::iterator begin,
+ MachineBasicBlock::iterator end,
+ unsigned endcount);
+
+
+ /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
+ /// reorderable instructions.
+ virtual void schedule();
+
+ /// Get current register pressure for the top scheduled instructions.
+ const IntervalPressure &getTopPressure() const { return TopPressure; }
+ const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
+
+ /// Get current register pressure for the bottom scheduled instructions.
+ const IntervalPressure &getBotPressure() const { return BotPressure; }
+ const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
+
+ /// Get register pressure for the entire scheduling region before scheduling.
+ const IntervalPressure &getRegPressure() const { return RegPressure; }
+
+ const std::vector<PressureElement> &getRegionCriticalPSets() const {
+ return RegionCriticalPSets;
+ }
+
+ /// getIssueWidth - Return the max instructions per scheduling group.
+ unsigned getIssueWidth() const {
+ return (InstrItins && InstrItins->SchedModel)
+ ? InstrItins->SchedModel->IssueWidth : 1;
+ }
+
+ /// getNumMicroOps - Return the number of issue slots required for this MI.
+ unsigned getNumMicroOps(MachineInstr *MI) const {
+ if (!InstrItins) return 1;
+ int UOps = InstrItins->getNumMicroOps(MI->getDesc().getSchedClass());
+ return (UOps >= 0) ? UOps : TII->getNumMicroOps(InstrItins, MI);
+ }
+
+protected:
+ // Top-Level entry points for the schedule() driver...
+
+ /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
+ /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
+ /// region, TopTracker and BottomTracker will be initialized to the top and
+ /// bottom of the DAG region without covereing any unscheduled instruction.
+ void buildDAGWithRegPressure();
+
+ /// Apply each ScheduleDAGMutation step in order. This allows different
+ /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
+ void postprocessDAG();
+
+ /// Identify DAG roots and setup scheduler queues.
+ void initQueues();
+
+ /// Move an instruction and update register pressure.
+ void scheduleMI(SUnit *SU, bool IsTopNode);
+
+ /// Update scheduler DAG and queues after scheduling an instruction.
+ void updateQueues(SUnit *SU, bool IsTopNode);
+
+ /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
+ void placeDebugValues();
+
+ // Lesser helpers...
+
+ void initRegPressure();
+
+ void updateScheduledPressure(std::vector<unsigned> NewMaxPressure);
+
+ void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
+ bool checkSchedLimit();
+
+ void releaseRoots();
+
+ void releaseSucc(SUnit *SU, SDep *SuccEdge);
+ void releaseSuccessors(SUnit *SU);
+ void releasePred(SUnit *SU, SDep *PredEdge);
+ void releasePredecessors(SUnit *SU);
+};
+
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/PBQP/Graph.h b/include/llvm/CodeGen/PBQP/Graph.h
new file mode 100644
index 00000000000..a5d8b0dbd6a
--- /dev/null
+++ b/include/llvm/CodeGen/PBQP/Graph.h
@@ -0,0 +1,461 @@
+//===-------------------- Graph.h - PBQP Graph ------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// PBQP Graph class.
+//
+//===----------------------------------------------------------------------===//
+
+
+#ifndef LLVM_CODEGEN_PBQP_GRAPH_H
+#define LLVM_CODEGEN_PBQP_GRAPH_H
+
+#include "Math.h"
+
+#include <list>
+#include <map>
+
+namespace PBQP {
+
+ /// PBQP Graph class.
+ /// Instances of this class describe PBQP problems.
+ class Graph {
+ private:
+
+ // ----- TYPEDEFS -----
+ class NodeEntry;
+ class EdgeEntry;
+
+ typedef std::list<NodeEntry> NodeList;
+ typedef std::list<EdgeEntry> EdgeList;
+
+ public:
+
+ typedef NodeList::iterator NodeItr;
+ typedef NodeList::const_iterator ConstNodeItr;
+
+ typedef EdgeList::iterator EdgeItr;
+ typedef EdgeList::const_iterator ConstEdgeItr;
+
+ private:
+
+ typedef std::list<EdgeItr> AdjEdgeList;
+
+ public:
+
+ typedef AdjEdgeList::iterator AdjEdgeItr;
+
+ private:
+
+ class NodeEntry {
+ private:
+ Vector costs;
+ AdjEdgeList adjEdges;
+ unsigned degree;
+ void *data;
+ public:
+ NodeEntry(const Vector &costs) : costs(costs), degree(0) {}
+ Vector& getCosts() { return costs; }
+ const Vector& getCosts() const { return costs; }
+ unsigned getDegree() const { return degree; }
+ AdjEdgeItr edgesBegin() { return adjEdges.begin(); }
+ AdjEdgeItr edgesEnd() { return adjEdges.end(); }
+ AdjEdgeItr addEdge(EdgeItr e) {
+ ++degree;
+ return adjEdges.insert(adjEdges.end(), e);
+ }
+ void removeEdge(AdjEdgeItr ae) {
+ --degree;
+ adjEdges.erase(ae);
+ }
+ void setData(void *data) { this->data = data; }
+ void* getData() { return data; }
+ };
+
+ class EdgeEntry {
+ private:
+ NodeItr node1, node2;
+ Matrix costs;
+ AdjEdgeItr node1AEItr, node2AEItr;
+ void *data;
+ public:
+ EdgeEntry(NodeItr node1, NodeItr node2, const Matrix &costs)
+ : node1(node1), node2(node2), costs(costs) {}
+ NodeItr getNode1() const { return node1; }
+ NodeItr getNode2() const { return node2; }
+ Matrix& getCosts() { return costs; }
+ const Matrix& getCosts() const { return costs; }
+ void setNode1AEItr(AdjEdgeItr ae) { node1AEItr = ae; }
+ AdjEdgeItr getNode1AEItr() { return node1AEItr; }
+ void setNode2AEItr(AdjEdgeItr ae) { node2AEItr = ae; }
+ AdjEdgeItr getNode2AEItr() { return node2AEItr; }
+ void setData(void *data) { this->data = data; }
+ void *getData() { return data; }
+ };
+
+ // ----- MEMBERS -----
+
+ NodeList nodes;
+ unsigned numNodes;
+
+ EdgeList edges;
+ unsigned numEdges;
+
+ // ----- INTERNAL METHODS -----
+
+ NodeEntry& getNode(NodeItr nItr) { return *nItr; }
+ const NodeEntry& getNode(ConstNodeItr nItr) const { return *nItr; }
+
+ EdgeEntry& getEdge(EdgeItr eItr) { return *eItr; }
+ const EdgeEntry& getEdge(ConstEdgeItr eItr) const { return *eItr; }
+
+ NodeItr addConstructedNode(const NodeEntry &n) {
+ ++numNodes;
+ return nodes.insert(nodes.end(), n);
+ }
+
+ EdgeItr addConstructedEdge(const EdgeEntry &e) {
+ assert(findEdge(e.getNode1(), e.getNode2()) == edges.end() &&
+ "Attempt to add duplicate edge.");
+ ++numEdges;
+ EdgeItr edgeItr = edges.insert(edges.end(), e);
+ EdgeEntry &ne = getEdge(edgeItr);
+ NodeEntry &n1 = getNode(ne.getNode1());
+ NodeEntry &n2 = getNode(ne.getNode2());
+ // Sanity check on matrix dimensions:
+ assert((n1.getCosts().getLength() == ne.getCosts().getRows()) &&
+ (n2.getCosts().getLength() == ne.getCosts().getCols()) &&
+ "Edge cost dimensions do not match node costs dimensions.");
+ ne.setNode1AEItr(n1.addEdge(edgeItr));
+ ne.setNode2AEItr(n2.addEdge(edgeItr));
+ return edgeItr;
+ }
+
+ inline void copyFrom(const Graph &other);
+ public:
+
+ /// \brief Construct an empty PBQP graph.
+ Graph() : numNodes(0), numEdges(0) {}
+
+ /// \brief Copy construct this graph from "other". Note: Does not copy node
+ /// and edge data, only graph structure and costs.
+ /// @param other Source graph to copy from.
+ Graph(const Graph &other) : numNodes(0), numEdges(0) {
+ copyFrom(other);
+ }
+
+ /// \brief Make this graph a copy of "other". Note: Does not copy node and
+ /// edge data, only graph structure and costs.
+ /// @param other The graph to copy from.
+ /// @return A reference to this graph.
+ ///
+ /// This will clear the current graph, erasing any nodes and edges added,
+ /// before copying from other.
+ Graph& operator=(const Graph &other) {
+ clear();
+ copyFrom(other);
+ return *this;
+ }
+
+ /// \brief Add a node with the given costs.
+ /// @param costs Cost vector for the new node.
+ /// @return Node iterator for the added node.
+ NodeItr addNode(const Vector &costs) {
+ return addConstructedNode(NodeEntry(costs));
+ }
+
+ /// \brief Add an edge between the given nodes with the given costs.
+ /// @param n1Itr First node.
+ /// @param n2Itr Second node.
+ /// @return Edge iterator for the added edge.
+ EdgeItr addEdge(Graph::NodeItr n1Itr, Graph::NodeItr n2Itr,
+ const Matrix &costs) {
+ assert(getNodeCosts(n1Itr).getLength() == costs.getRows() &&
+ getNodeCosts(n2Itr).getLength() == costs.getCols() &&
+ "Matrix dimensions mismatch.");
+ return addConstructedEdge(EdgeEntry(n1Itr, n2Itr, costs));
+ }
+
+ /// \brief Get the number of nodes in the graph.
+ /// @return Number of nodes in the graph.
+ unsigned getNumNodes() const { return numNodes; }
+
+ /// \brief Get the number of edges in the graph.
+ /// @return Number of edges in the graph.
+ unsigned getNumEdges() const { return numEdges; }
+
+ /// \brief Get a node's cost vector.
+ /// @param nItr Node iterator.
+ /// @return Node cost vector.
+ Vector& getNodeCosts(NodeItr nItr) { return getNode(nItr).getCosts(); }
+
+ /// \brief Get a node's cost vector (const version).
+ /// @param nItr Node iterator.
+ /// @return Node cost vector.
+ const Vector& getNodeCosts(ConstNodeItr nItr) const {
+ return getNode(nItr).getCosts();
+ }
+
+ /// \brief Set a node's data pointer.
+ /// @param nItr Node iterator.
+ /// @param data Pointer to node data.
+ ///
+ /// Typically used by a PBQP solver to attach data to aid in solution.
+ void setNodeData(NodeItr nItr, void *data) { getNode(nItr).setData(data); }
+
+ /// \brief Get the node's data pointer.
+ /// @param nItr Node iterator.
+ /// @return Pointer to node data.
+ void* getNodeData(NodeItr nItr) { return getNode(nItr).getData(); }
+
+ /// \brief Get an edge's cost matrix.
+ /// @param eItr Edge iterator.
+ /// @return Edge cost matrix.
+ Matrix& getEdgeCosts(EdgeItr eItr) { return getEdge(eItr).getCosts(); }
+
+ /// \brief Get an edge's cost matrix (const version).
+ /// @param eItr Edge iterator.
+ /// @return Edge cost matrix.
+ const Matrix& getEdgeCosts(ConstEdgeItr eItr) const {
+ return getEdge(eItr).getCosts();
+ }
+
+ /// \brief Set an edge's data pointer.
+ /// @param eItr Edge iterator.
+ /// @param data Pointer to edge data.
+ ///
+ /// Typically used by a PBQP solver to attach data to aid in solution.
+ void setEdgeData(EdgeItr eItr, void *data) { getEdge(eItr).setData(data); }
+
+ /// \brief Get an edge's data pointer.
+ /// @param eItr Edge iterator.
+ /// @return Pointer to edge data.
+ void* getEdgeData(EdgeItr eItr) { return getEdge(eItr).getData(); }
+
+ /// \brief Get a node's degree.
+ /// @param nItr Node iterator.
+ /// @return The degree of the node.
+ unsigned getNodeDegree(NodeItr nItr) const {
+ return getNode(nItr).getDegree();
+ }
+
+ /// \brief Begin iterator for node set.
+ NodeItr nodesBegin() { return nodes.begin(); }
+
+ /// \brief Begin const iterator for node set.
+ ConstNodeItr nodesBegin() const { return nodes.begin(); }
+
+ /// \brief End iterator for node set.
+ NodeItr nodesEnd() { return nodes.end(); }
+
+ /// \brief End const iterator for node set.
+ ConstNodeItr nodesEnd() const { return nodes.end(); }
+
+ /// \brief Begin iterator for edge set.
+ EdgeItr edgesBegin() { return edges.begin(); }
+
+ /// \brief End iterator for edge set.
+ EdgeItr edgesEnd() { return edges.end(); }
+
+ /// \brief Get begin iterator for adjacent edge set.
+ /// @param nItr Node iterator.
+ /// @return Begin iterator for the set of edges connected to the given node.
+ AdjEdgeItr adjEdgesBegin(NodeItr nItr) {
+ return getNode(nItr).edgesBegin();
+ }
+
+ /// \brief Get end iterator for adjacent edge set.
+ /// @param nItr Node iterator.
+ /// @return End iterator for the set of edges connected to the given node.
+ AdjEdgeItr adjEdgesEnd(NodeItr nItr) {
+ return getNode(nItr).edgesEnd();
+ }
+
+ /// \brief Get the first node connected to this edge.
+ /// @param eItr Edge iterator.
+ /// @return The first node connected to the given edge.
+ NodeItr getEdgeNode1(EdgeItr eItr) {
+ return getEdge(eItr).getNode1();
+ }
+
+ /// \brief Get the second node connected to this edge.
+ /// @param eItr Edge iterator.
+ /// @return The second node connected to the given edge.
+ NodeItr getEdgeNode2(EdgeItr eItr) {
+ return getEdge(eItr).getNode2();
+ }
+
+ /// \brief Get the "other" node connected to this edge.
+ /// @param eItr Edge iterator.
+ /// @param nItr Node iterator for the "given" node.
+ /// @return The iterator for the "other" node connected to this edge.
+ NodeItr getEdgeOtherNode(EdgeItr eItr, NodeItr nItr) {
+ EdgeEntry &e = getEdge(eItr);
+ if (e.getNode1() == nItr) {
+ return e.getNode2();
+ } // else
+ return e.getNode1();
+ }
+
+ /// \brief Get the edge connecting two nodes.
+ /// @param n1Itr First node iterator.
+ /// @param n2Itr Second node iterator.
+ /// @return An iterator for edge (n1Itr, n2Itr) if such an edge exists,
+ /// otherwise returns edgesEnd().
+ EdgeItr findEdge(NodeItr n1Itr, NodeItr n2Itr) {
+ for (AdjEdgeItr aeItr = adjEdgesBegin(n1Itr), aeEnd = adjEdgesEnd(n1Itr);
+ aeItr != aeEnd; ++aeItr) {
+ if ((getEdgeNode1(*aeItr) == n2Itr) ||
+ (getEdgeNode2(*aeItr) == n2Itr)) {
+ return *aeItr;
+ }
+ }
+ return edges.end();
+ }
+
+ /// \brief Remove a node from the graph.
+ /// @param nItr Node iterator.
+ void removeNode(NodeItr nItr) {
+ NodeEntry &n = getNode(nItr);
+ for (AdjEdgeItr itr = n.edgesBegin(), end = n.edgesEnd(); itr != end;) {
+ EdgeItr eItr = *itr;
+ ++itr;
+ removeEdge(eItr);
+ }
+ nodes.erase(nItr);
+ --numNodes;
+ }
+
+ /// \brief Remove an edge from the graph.
+ /// @param eItr Edge iterator.
+ void removeEdge(EdgeItr eItr) {
+ EdgeEntry &e = getEdge(eItr);
+ NodeEntry &n1 = getNode(e.getNode1());
+ NodeEntry &n2 = getNode(e.getNode2());
+ n1.removeEdge(e.getNode1AEItr());
+ n2.removeEdge(e.getNode2AEItr());
+ edges.erase(eItr);
+ --numEdges;
+ }
+
+ /// \brief Remove all nodes and edges from the graph.
+ void clear() {
+ nodes.clear();
+ edges.clear();
+ numNodes = numEdges = 0;
+ }
+
+ /// \brief Dump a graph to an output stream.
+ template <typename OStream>
+ void dump(OStream &os) {
+ os << getNumNodes() << " " << getNumEdges() << "\n";
+
+ for (NodeItr nodeItr = nodesBegin(), nodeEnd = nodesEnd();
+ nodeItr != nodeEnd; ++nodeItr) {
+ const Vector& v = getNodeCosts(nodeItr);
+ os << "\n" << v.getLength() << "\n";
+ assert(v.getLength() != 0 && "Empty vector in graph.");
+ os << v[0];
+ for (unsigned i = 1; i < v.getLength(); ++i) {
+ os << " " << v[i];
+ }
+ os << "\n";
+ }
+
+ for (EdgeItr edgeItr = edgesBegin(), edgeEnd = edgesEnd();
+ edgeItr != edgeEnd; ++edgeItr) {
+ unsigned n1 = std::distance(nodesBegin(), getEdgeNode1(edgeItr));
+ unsigned n2 = std::distance(nodesBegin(), getEdgeNode2(edgeItr));
+ assert(n1 != n2 && "PBQP graphs shound not have self-edges.");
+ const Matrix& m = getEdgeCosts(edgeItr);
+ os << "\n" << n1 << " " << n2 << "\n"
+ << m.getRows() << " " << m.getCols() << "\n";
+ assert(m.getRows() != 0 && "No rows in matrix.");
+ assert(m.getCols() != 0 && "No cols in matrix.");
+ for (unsigned i = 0; i < m.getRows(); ++i) {
+ os << m[i][0];
+ for (unsigned j = 1; j < m.getCols(); ++j) {
+ os << " " << m[i][j];
+ }
+ os << "\n";
+ }
+ }
+ }
+
+ /// \brief Print a representation of this graph in DOT format.
+ /// @param os Output stream to print on.
+ template <typename OStream>
+ void printDot(OStream &os) {
+
+ os << "graph {\n";
+
+ for (NodeItr nodeItr = nodesBegin(), nodeEnd = nodesEnd();
+ nodeItr != nodeEnd; ++nodeItr) {
+
+ os << " node" << nodeItr << " [ label=\""
+ << nodeItr << ": " << getNodeCosts(nodeItr) << "\" ]\n";
+ }
+
+ os << " edge [ len=" << getNumNodes() << " ]\n";
+
+ for (EdgeItr edgeItr = edgesBegin(), edgeEnd = edgesEnd();
+ edgeItr != edgeEnd; ++edgeItr) {
+
+ os << " node" << getEdgeNode1(edgeItr)
+ << " -- node" << getEdgeNode2(edgeItr)
+ << " [ label=\"";
+
+ const Matrix &edgeCosts = getEdgeCosts(edgeItr);
+
+ for (unsigned i = 0; i < edgeCosts.getRows(); ++i) {
+ os << edgeCosts.getRowAsVector(i) << "\\n";
+ }
+ os << "\" ]\n";
+ }
+ os << "}\n";
+ }
+
+ };
+
+ class NodeItrComparator {
+ public:
+ bool operator()(Graph::NodeItr n1, Graph::NodeItr n2) const {
+ return &*n1 < &*n2;
+ }
+
+ bool operator()(Graph::ConstNodeItr n1, Graph::ConstNodeItr n2) const {
+ return &*n1 < &*n2;
+ }
+ };
+
+ class EdgeItrCompartor {
+ public:
+ bool operator()(Graph::EdgeItr e1, Graph::EdgeItr e2) const {
+ return &*e1 < &*e2;
+ }
+
+ bool operator()(Graph::ConstEdgeItr e1, Graph::ConstEdgeItr e2) const {
+ return &*e1 < &*e2;
+ }
+ };
+
+ void Graph::copyFrom(const Graph &other) {
+ std::map<Graph::ConstNodeItr, Graph::NodeItr,
+ NodeItrComparator> nodeMap;
+
+ for (Graph::ConstNodeItr nItr = other.nodesBegin(),
+ nEnd = other.nodesEnd();
+ nItr != nEnd; ++nItr) {
+ nodeMap[nItr] = addNode(other.getNodeCosts(nItr));
+ }
+
+ }
+
+}
+
+#endif // LLVM_CODEGEN_PBQP_GRAPH_HPP
diff --git a/include/llvm/CodeGen/PBQP/HeuristicBase.h b/include/llvm/CodeGen/PBQP/HeuristicBase.h
new file mode 100644
index 00000000000..0c1fcb7eaf7
--- /dev/null
+++ b/include/llvm/CodeGen/PBQP/HeuristicBase.h
@@ -0,0 +1,247 @@
+//===-- HeuristcBase.h --- Heuristic base class for PBQP --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_PBQP_HEURISTICBASE_H
+#define LLVM_CODEGEN_PBQP_HEURISTICBASE_H
+
+#include "HeuristicSolver.h"
+
+namespace PBQP {
+
+ /// \brief Abstract base class for heuristic implementations.
+ ///
+ /// This class provides a handy base for heuristic implementations with common
+ /// solver behaviour implemented for a number of methods.
+ ///
+ /// To implement your own heuristic using this class as a base you'll have to
+ /// implement, as a minimum, the following methods:
+ /// <ul>
+ /// <li> void addToHeuristicList(Graph::NodeItr) : Add a node to the
+ /// heuristic reduction list.
+ /// <li> void heuristicReduce() : Perform a single heuristic reduction.
+ /// <li> void preUpdateEdgeCosts(Graph::EdgeItr) : Handle the (imminent)
+ /// change to the cost matrix on the given edge (by R2).
+ /// <li> void postUpdateEdgeCostts(Graph::EdgeItr) : Handle the new
+ /// costs on the given edge.
+ /// <li> void handleAddEdge(Graph::EdgeItr) : Handle the addition of a new
+ /// edge into the PBQP graph (by R2).
+ /// <li> void handleRemoveEdge(Graph::EdgeItr, Graph::NodeItr) : Handle the
+ /// disconnection of the given edge from the given node.
+ /// <li> A constructor for your derived class : to pass back a reference to
+ /// the solver which is using this heuristic.
+ /// </ul>
+ ///
+ /// These methods are implemented in this class for documentation purposes,
+ /// but will assert if called.
+ ///
+ /// Note that this class uses the curiously recursive template idiom to
+ /// forward calls to the derived class. These methods need not be made
+ /// virtual, and indeed probably shouldn't for performance reasons.
+ ///
+ /// You'll also need to provide NodeData and EdgeData structs in your class.
+ /// These can be used to attach data relevant to your heuristic to each
+ /// node/edge in the PBQP graph.
+
+ template <typename HImpl>
+ class HeuristicBase {
+ private:
+
+ typedef std::list<Graph::NodeItr> OptimalList;
+
+ HeuristicSolverImpl<HImpl> &s;
+ Graph &g;
+ OptimalList optimalList;
+
+ // Return a reference to the derived heuristic.
+ HImpl& impl() { return static_cast<HImpl&>(*this); }
+
+ // Add the given node to the optimal reductions list. Keep an iterator to
+ // its location for fast removal.
+ void addToOptimalReductionList(Graph::NodeItr nItr) {
+ optimalList.insert(optimalList.end(), nItr);
+ }
+
+ public:
+
+ /// \brief Construct an instance with a reference to the given solver.
+ /// @param solver The solver which is using this heuristic instance.
+ HeuristicBase(HeuristicSolverImpl<HImpl> &solver)
+ : s(solver), g(s.getGraph()) { }
+
+ /// \brief Get the solver which is using this heuristic instance.
+ /// @return The solver which is using this heuristic instance.
+ ///
+ /// You can use this method to get access to the solver in your derived
+ /// heuristic implementation.
+ HeuristicSolverImpl<HImpl>& getSolver() { return s; }
+
+ /// \brief Get the graph representing the problem to be solved.
+ /// @return The graph representing the problem to be solved.
+ Graph& getGraph() { return g; }
+
+ /// \brief Tell the solver to simplify the graph before the reduction phase.
+ /// @return Whether or not the solver should run a simplification phase
+ /// prior to the main setup and reduction.
+ ///
+ /// HeuristicBase returns true from this method as it's a sensible default,
+ /// however you can over-ride it in your derived class if you want different
+ /// behaviour.
+ bool solverRunSimplify() const { return true; }
+
+ /// \brief Decide whether a node should be optimally or heuristically
+ /// reduced.
+ /// @return Whether or not the given node should be listed for optimal
+ /// reduction (via R0, R1 or R2).
+ ///
+ /// HeuristicBase returns true for any node with degree less than 3. This is
+ /// sane and sensible for many situations, but not all. You can over-ride
+ /// this method in your derived class if you want a different selection
+ /// criteria. Note however that your criteria for selecting optimal nodes
+ /// should be <i>at least</i> as strong as this. I.e. Nodes of degree 3 or
+ /// higher should not be selected under any circumstances.
+ bool shouldOptimallyReduce(Graph::NodeItr nItr) {
+ if (g.getNodeDegree(nItr) < 3)
+ return true;
+ // else
+ return false;
+ }
+
+ /// \brief Add the given node to the list of nodes to be optimally reduced.
+ /// @param nItr Node iterator to be added.
+ ///
+ /// You probably don't want to over-ride this, except perhaps to record
+ /// statistics before calling this implementation. HeuristicBase relies on
+ /// its behaviour.
+ void addToOptimalReduceList(Graph::NodeItr nItr) {
+ optimalList.push_back(nItr);
+ }
+
+ /// \brief Initialise the heuristic.
+ ///
+ /// HeuristicBase iterates over all nodes in the problem and adds them to
+ /// the appropriate list using addToOptimalReduceList or
+ /// addToHeuristicReduceList based on the result of shouldOptimallyReduce.
+ ///
+ /// This behaviour should be fine for most situations.
+ void setup() {
+ for (Graph::NodeItr nItr = g.nodesBegin(), nEnd = g.nodesEnd();
+ nItr != nEnd; ++nItr) {
+ if (impl().shouldOptimallyReduce(nItr)) {
+ addToOptimalReduceList(nItr);
+ } else {
+ impl().addToHeuristicReduceList(nItr);
+ }
+ }
+ }
+
+ /// \brief Optimally reduce one of the nodes in the optimal reduce list.
+ /// @return True if a reduction takes place, false if the optimal reduce
+ /// list is empty.
+ ///
+ /// Selects a node from the optimal reduce list and removes it, applying
+ /// R0, R1 or R2 as appropriate based on the selected node's degree.
+ bool optimalReduce() {
+ if (optimalList.empty())
+ return false;
+
+ Graph::NodeItr nItr = optimalList.front();
+ optimalList.pop_front();
+
+ switch (s.getSolverDegree(nItr)) {
+ case 0: s.applyR0(nItr); break;
+ case 1: s.applyR1(nItr); break;
+ case 2: s.applyR2(nItr); break;
+ default: llvm_unreachable(
+ "Optimal reductions of degree > 2 nodes is invalid.");
+ }
+
+ return true;
+ }
+
+ /// \brief Perform the PBQP reduction process.
+ ///
+ /// Reduces the problem to the empty graph by repeated application of the
+ /// reduction rules R0, R1, R2 and RN.
+ /// R0, R1 or R2 are always applied if possible before RN is used.
+ void reduce() {
+ bool finished = false;
+
+ while (!finished) {
+ if (!optimalReduce()) {
+ if (impl().heuristicReduce()) {
+ getSolver().recordRN();
+ } else {
+ finished = true;
+ }
+ }
+ }
+ }
+
+ /// \brief Add a node to the heuristic reduce list.
+ /// @param nItr Node iterator to add to the heuristic reduce list.
+ void addToHeuristicList(Graph::NodeItr nItr) {
+ llvm_unreachable("Must be implemented in derived class.");
+ }
+
+ /// \brief Heuristically reduce one of the nodes in the heuristic
+ /// reduce list.
+ /// @return True if a reduction takes place, false if the heuristic reduce
+ /// list is empty.
+ bool heuristicReduce() {
+ llvm_unreachable("Must be implemented in derived class.");
+ return false;
+ }
+
+ /// \brief Prepare a change in the costs on the given edge.
+ /// @param eItr Edge iterator.
+ void preUpdateEdgeCosts(Graph::EdgeItr eItr) {
+ llvm_unreachable("Must be implemented in derived class.");
+ }
+
+ /// \brief Handle the change in the costs on the given edge.
+ /// @param eItr Edge iterator.
+ void postUpdateEdgeCostts(Graph::EdgeItr eItr) {
+ llvm_unreachable("Must be implemented in derived class.");
+ }
+
+ /// \brief Handle the addition of a new edge into the PBQP graph.
+ /// @param eItr Edge iterator for the added edge.
+ void handleAddEdge(Graph::EdgeItr eItr) {
+ llvm_unreachable("Must be implemented in derived class.");
+ }
+
+ /// \brief Handle disconnection of an edge from a node.
+ /// @param eItr Edge iterator for edge being disconnected.
+ /// @param nItr Node iterator for the node being disconnected from.
+ ///
+ /// Edges are frequently removed due to the removal of a node. This
+ /// method allows for the effect to be computed only for the remaining
+ /// node in the graph.
+ void handleRemoveEdge(Graph::EdgeItr eItr, Graph::NodeItr nItr) {
+ llvm_unreachable("Must be implemented in derived class.");
+ }
+
+ /// \brief Clean up any structures used by HeuristicBase.
+ ///
+ /// At present this just performs a sanity check: that the optimal reduce
+ /// list is empty now that reduction has completed.
+ ///
+ /// If your derived class has more complex structures which need tearing
+ /// down you should over-ride this method but include a call back to this
+ /// implementation.
+ void cleanup() {
+ assert(optimalList.empty() && "Nodes left over in optimal reduce list?");
+ }
+
+ };
+
+}
+
+
+#endif // LLVM_CODEGEN_PBQP_HEURISTICBASE_H
diff --git a/include/llvm/CodeGen/PBQP/HeuristicSolver.h b/include/llvm/CodeGen/PBQP/HeuristicSolver.h
new file mode 100644
index 00000000000..35514f96747
--- /dev/null
+++ b/include/llvm/CodeGen/PBQP/HeuristicSolver.h
@@ -0,0 +1,616 @@
+//===-- HeuristicSolver.h - Heuristic PBQP Solver --------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Heuristic PBQP solver. This solver is able to perform optimal reductions for
+// nodes of degree 0, 1 or 2. For nodes of degree >2 a plugable heuristic is
+// used to select a node for reduction.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_PBQP_HEURISTICSOLVER_H
+#define LLVM_CODEGEN_PBQP_HEURISTICSOLVER_H
+
+#include "Graph.h"
+#include "Solution.h"
+#include <vector>
+#include <limits>
+
+namespace PBQP {
+
+ /// \brief Heuristic PBQP solver implementation.
+ ///
+ /// This class should usually be created (and destroyed) indirectly via a call
+ /// to HeuristicSolver<HImpl>::solve(Graph&).
+ /// See the comments for HeuristicSolver.
+ ///
+ /// HeuristicSolverImpl provides the R0, R1 and R2 reduction rules,
+ /// backpropagation phase, and maintains the internal copy of the graph on
+ /// which the reduction is carried out (the original being kept to facilitate
+ /// backpropagation).
+ template <typename HImpl>
+ class HeuristicSolverImpl {
+ private:
+
+ typedef typename HImpl::NodeData HeuristicNodeData;
+ typedef typename HImpl::EdgeData HeuristicEdgeData;
+
+ typedef std::list<Graph::EdgeItr> SolverEdges;
+
+ public:
+
+ /// \brief Iterator type for edges in the solver graph.
+ typedef SolverEdges::iterator SolverEdgeItr;
+
+ private:
+
+ class NodeData {
+ public:
+ NodeData() : solverDegree(0) {}
+
+ HeuristicNodeData& getHeuristicData() { return hData; }
+
+ SolverEdgeItr addSolverEdge(Graph::EdgeItr eItr) {
+ ++solverDegree;
+ return solverEdges.insert(solverEdges.end(), eItr);
+ }
+
+ void removeSolverEdge(SolverEdgeItr seItr) {
+ --solverDegree;
+ solverEdges.erase(seItr);
+ }
+
+ SolverEdgeItr solverEdgesBegin() { return solverEdges.begin(); }
+ SolverEdgeItr solverEdgesEnd() { return solverEdges.end(); }
+ unsigned getSolverDegree() const { return solverDegree; }
+ void clearSolverEdges() {
+ solverDegree = 0;
+ solverEdges.clear();
+ }
+
+ private:
+ HeuristicNodeData hData;
+ unsigned solverDegree;
+ SolverEdges solverEdges;
+ };
+
+ class EdgeData {
+ public:
+ HeuristicEdgeData& getHeuristicData() { return hData; }
+
+ void setN1SolverEdgeItr(SolverEdgeItr n1SolverEdgeItr) {
+ this->n1SolverEdgeItr = n1SolverEdgeItr;
+ }
+
+ SolverEdgeItr getN1SolverEdgeItr() { return n1SolverEdgeItr; }
+
+ void setN2SolverEdgeItr(SolverEdgeItr n2SolverEdgeItr){
+ this->n2SolverEdgeItr = n2SolverEdgeItr;
+ }
+
+ SolverEdgeItr getN2SolverEdgeItr() { return n2SolverEdgeItr; }
+
+ private:
+
+ HeuristicEdgeData hData;
+ SolverEdgeItr n1SolverEdgeItr, n2SolverEdgeItr;
+ };
+
+ Graph &g;
+ HImpl h;
+ Solution s;
+ std::vector<Graph::NodeItr> stack;
+
+ typedef std::list<NodeData> NodeDataList;
+ NodeDataList nodeDataList;
+
+ typedef std::list<EdgeData> EdgeDataList;
+ EdgeDataList edgeDataList;
+
+ public:
+
+ /// \brief Construct a heuristic solver implementation to solve the given
+ /// graph.
+ /// @param g The graph representing the problem instance to be solved.
+ HeuristicSolverImpl(Graph &g) : g(g), h(*this) {}
+
+ /// \brief Get the graph being solved by this solver.
+ /// @return The graph representing the problem instance being solved by this
+ /// solver.
+ Graph& getGraph() { return g; }
+
+ /// \brief Get the heuristic data attached to the given node.
+ /// @param nItr Node iterator.
+ /// @return The heuristic data attached to the given node.
+ HeuristicNodeData& getHeuristicNodeData(Graph::NodeItr nItr) {
+ return getSolverNodeData(nItr).getHeuristicData();
+ }
+
+ /// \brief Get the heuristic data attached to the given edge.
+ /// @param eItr Edge iterator.
+ /// @return The heuristic data attached to the given node.
+ HeuristicEdgeData& getHeuristicEdgeData(Graph::EdgeItr eItr) {
+ return getSolverEdgeData(eItr).getHeuristicData();
+ }
+
+ /// \brief Begin iterator for the set of edges adjacent to the given node in
+ /// the solver graph.
+ /// @param nItr Node iterator.
+ /// @return Begin iterator for the set of edges adjacent to the given node
+ /// in the solver graph.
+ SolverEdgeItr solverEdgesBegin(Graph::NodeItr nItr) {
+ return getSolverNodeData(nItr).solverEdgesBegin();
+ }
+
+ /// \brief End iterator for the set of edges adjacent to the given node in
+ /// the solver graph.
+ /// @param nItr Node iterator.
+ /// @return End iterator for the set of edges adjacent to the given node in
+ /// the solver graph.
+ SolverEdgeItr solverEdgesEnd(Graph::NodeItr nItr) {
+ return getSolverNodeData(nItr).solverEdgesEnd();
+ }
+
+ /// \brief Remove a node from the solver graph.
+ /// @param eItr Edge iterator for edge to be removed.
+ ///
+ /// Does <i>not</i> notify the heuristic of the removal. That should be
+ /// done manually if necessary.
+ void removeSolverEdge(Graph::EdgeItr eItr) {
+ EdgeData &eData = getSolverEdgeData(eItr);
+ NodeData &n1Data = getSolverNodeData(g.getEdgeNode1(eItr)),
+ &n2Data = getSolverNodeData(g.getEdgeNode2(eItr));
+
+ n1Data.removeSolverEdge(eData.getN1SolverEdgeItr());
+ n2Data.removeSolverEdge(eData.getN2SolverEdgeItr());
+ }
+
+ /// \brief Compute a solution to the PBQP problem instance with which this
+ /// heuristic solver was constructed.
+ /// @return A solution to the PBQP problem.
+ ///
+ /// Performs the full PBQP heuristic solver algorithm, including setup,
+ /// calls to the heuristic (which will call back to the reduction rules in
+ /// this class), and cleanup.
+ Solution computeSolution() {
+ setup();
+ h.setup();
+ h.reduce();
+ backpropagate();
+ h.cleanup();
+ cleanup();
+ return s;
+ }
+
+ /// \brief Add to the end of the stack.
+ /// @param nItr Node iterator to add to the reduction stack.
+ void pushToStack(Graph::NodeItr nItr) {
+ getSolverNodeData(nItr).clearSolverEdges();
+ stack.push_back(nItr);
+ }
+
+ /// \brief Returns the solver degree of the given node.
+ /// @param nItr Node iterator for which degree is requested.
+ /// @return Node degree in the <i>solver</i> graph (not the original graph).
+ unsigned getSolverDegree(Graph::NodeItr nItr) {
+ return getSolverNodeData(nItr).getSolverDegree();
+ }
+
+ /// \brief Set the solution of the given node.
+ /// @param nItr Node iterator to set solution for.
+ /// @param selection Selection for node.
+ void setSolution(const Graph::NodeItr &nItr, unsigned selection) {
+ s.setSelection(nItr, selection);
+
+ for (Graph::AdjEdgeItr aeItr = g.adjEdgesBegin(nItr),
+ aeEnd = g.adjEdgesEnd(nItr);
+ aeItr != aeEnd; ++aeItr) {
+ Graph::EdgeItr eItr(*aeItr);
+ Graph::NodeItr anItr(g.getEdgeOtherNode(eItr, nItr));
+ getSolverNodeData(anItr).addSolverEdge(eItr);
+ }
+ }
+
+ /// \brief Apply rule R0.
+ /// @param nItr Node iterator for node to apply R0 to.
+ ///
+ /// Node will be automatically pushed to the solver stack.
+ void applyR0(Graph::NodeItr nItr) {
+ assert(getSolverNodeData(nItr).getSolverDegree() == 0 &&
+ "R0 applied to node with degree != 0.");
+
+ // Nothing to do. Just push the node onto the reduction stack.
+ pushToStack(nItr);
+
+ s.recordR0();
+ }
+
+ /// \brief Apply rule R1.
+ /// @param xnItr Node iterator for node to apply R1 to.
+ ///
+ /// Node will be automatically pushed to the solver stack.
+ void applyR1(Graph::NodeItr xnItr) {
+ NodeData &nd = getSolverNodeData(xnItr);
+ assert(nd.getSolverDegree() == 1 &&
+ "R1 applied to node with degree != 1.");
+
+ Graph::EdgeItr eItr = *nd.solverEdgesBegin();
+
+ const Matrix &eCosts = g.getEdgeCosts(eItr);
+ const Vector &xCosts = g.getNodeCosts(xnItr);
+
+ // Duplicate a little to avoid transposing matrices.
+ if (xnItr == g.getEdgeNode1(eItr)) {
+ Graph::NodeItr ynItr = g.getEdgeNode2(eItr);
+ Vector &yCosts = g.getNodeCosts(ynItr);
+ for (unsigned j = 0; j < yCosts.getLength(); ++j) {
+ PBQPNum min = eCosts[0][j] + xCosts[0];
+ for (unsigned i = 1; i < xCosts.getLength(); ++i) {
+ PBQPNum c = eCosts[i][j] + xCosts[i];
+ if (c < min)
+ min = c;
+ }
+ yCosts[j] += min;
+ }
+ h.handleRemoveEdge(eItr, ynItr);
+ } else {
+ Graph::NodeItr ynItr = g.getEdgeNode1(eItr);
+ Vector &yCosts = g.getNodeCosts(ynItr);
+ for (unsigned i = 0; i < yCosts.getLength(); ++i) {
+ PBQPNum min = eCosts[i][0] + xCosts[0];
+ for (unsigned j = 1; j < xCosts.getLength(); ++j) {
+ PBQPNum c = eCosts[i][j] + xCosts[j];
+ if (c < min)
+ min = c;
+ }
+ yCosts[i] += min;
+ }
+ h.handleRemoveEdge(eItr, ynItr);
+ }
+ removeSolverEdge(eItr);
+ assert(nd.getSolverDegree() == 0 &&
+ "Degree 1 with edge removed should be 0.");
+ pushToStack(xnItr);
+ s.recordR1();
+ }
+
+ /// \brief Apply rule R2.
+ /// @param xnItr Node iterator for node to apply R2 to.
+ ///
+ /// Node will be automatically pushed to the solver stack.
+ void applyR2(Graph::NodeItr xnItr) {
+ assert(getSolverNodeData(xnItr).getSolverDegree() == 2 &&
+ "R2 applied to node with degree != 2.");
+
+ NodeData &nd = getSolverNodeData(xnItr);
+ const Vector &xCosts = g.getNodeCosts(xnItr);
+
+ SolverEdgeItr aeItr = nd.solverEdgesBegin();
+ Graph::EdgeItr yxeItr = *aeItr,
+ zxeItr = *(++aeItr);
+
+ Graph::NodeItr ynItr = g.getEdgeOtherNode(yxeItr, xnItr),
+ znItr = g.getEdgeOtherNode(zxeItr, xnItr);
+
+ bool flipEdge1 = (g.getEdgeNode1(yxeItr) == xnItr),
+ flipEdge2 = (g.getEdgeNode1(zxeItr) == xnItr);
+
+ const Matrix *yxeCosts = flipEdge1 ?
+ new Matrix(g.getEdgeCosts(yxeItr).transpose()) :
+ &g.getEdgeCosts(yxeItr);
+
+ const Matrix *zxeCosts = flipEdge2 ?
+ new Matrix(g.getEdgeCosts(zxeItr).transpose()) :
+ &g.getEdgeCosts(zxeItr);
+
+ unsigned xLen = xCosts.getLength(),
+ yLen = yxeCosts->getRows(),
+ zLen = zxeCosts->getRows();
+
+ Matrix delta(yLen, zLen);
+
+ for (unsigned i = 0; i < yLen; ++i) {
+ for (unsigned j = 0; j < zLen; ++j) {
+ PBQPNum min = (*yxeCosts)[i][0] + (*zxeCosts)[j][0] + xCosts[0];
+ for (unsigned k = 1; k < xLen; ++k) {
+ PBQPNum c = (*yxeCosts)[i][k] + (*zxeCosts)[j][k] + xCosts[k];
+ if (c < min) {
+ min = c;
+ }
+ }
+ delta[i][j] = min;
+ }
+ }
+
+ if (flipEdge1)
+ delete yxeCosts;
+
+ if (flipEdge2)
+ delete zxeCosts;
+
+ Graph::EdgeItr yzeItr = g.findEdge(ynItr, znItr);
+ bool addedEdge = false;
+
+ if (yzeItr == g.edgesEnd()) {
+ yzeItr = g.addEdge(ynItr, znItr, delta);
+ addedEdge = true;
+ } else {
+ Matrix &yzeCosts = g.getEdgeCosts(yzeItr);
+ h.preUpdateEdgeCosts(yzeItr);
+ if (ynItr == g.getEdgeNode1(yzeItr)) {
+ yzeCosts += delta;
+ } else {
+ yzeCosts += delta.transpose();
+ }
+ }
+
+ bool nullCostEdge = tryNormaliseEdgeMatrix(yzeItr);
+
+ if (!addedEdge) {
+ // If we modified the edge costs let the heuristic know.
+ h.postUpdateEdgeCosts(yzeItr);
+ }
+
+ if (nullCostEdge) {
+ // If this edge ended up null remove it.
+ if (!addedEdge) {
+ // We didn't just add it, so we need to notify the heuristic
+ // and remove it from the solver.
+ h.handleRemoveEdge(yzeItr, ynItr);
+ h.handleRemoveEdge(yzeItr, znItr);
+ removeSolverEdge(yzeItr);
+ }
+ g.removeEdge(yzeItr);
+ } else if (addedEdge) {
+ // If the edge was added, and non-null, finish setting it up, add it to
+ // the solver & notify heuristic.
+ edgeDataList.push_back(EdgeData());
+ g.setEdgeData(yzeItr, &edgeDataList.back());
+ addSolverEdge(yzeItr);
+ h.handleAddEdge(yzeItr);
+ }
+
+ h.handleRemoveEdge(yxeItr, ynItr);
+ removeSolverEdge(yxeItr);
+ h.handleRemoveEdge(zxeItr, znItr);
+ removeSolverEdge(zxeItr);
+
+ pushToStack(xnItr);
+ s.recordR2();
+ }
+
+ /// \brief Record an application of the RN rule.
+ ///
+ /// For use by the HeuristicBase.
+ void recordRN() { s.recordRN(); }
+
+ private:
+
+ NodeData& getSolverNodeData(Graph::NodeItr nItr) {
+ return *static_cast<NodeData*>(g.getNodeData(nItr));
+ }
+
+ EdgeData& getSolverEdgeData(Graph::EdgeItr eItr) {
+ return *static_cast<EdgeData*>(g.getEdgeData(eItr));
+ }
+
+ void addSolverEdge(Graph::EdgeItr eItr) {
+ EdgeData &eData = getSolverEdgeData(eItr);
+ NodeData &n1Data = getSolverNodeData(g.getEdgeNode1(eItr)),
+ &n2Data = getSolverNodeData(g.getEdgeNode2(eItr));
+
+ eData.setN1SolverEdgeItr(n1Data.addSolverEdge(eItr));
+ eData.setN2SolverEdgeItr(n2Data.addSolverEdge(eItr));
+ }
+
+ void setup() {
+ if (h.solverRunSimplify()) {
+ simplify();
+ }
+
+ // Create node data objects.
+ for (Graph::NodeItr nItr = g.nodesBegin(), nEnd = g.nodesEnd();
+ nItr != nEnd; ++nItr) {
+ nodeDataList.push_back(NodeData());
+ g.setNodeData(nItr, &nodeDataList.back());
+ }
+
+ // Create edge data objects.
+ for (Graph::EdgeItr eItr = g.edgesBegin(), eEnd = g.edgesEnd();
+ eItr != eEnd; ++eItr) {
+ edgeDataList.push_back(EdgeData());
+ g.setEdgeData(eItr, &edgeDataList.back());
+ addSolverEdge(eItr);
+ }
+ }
+
+ void simplify() {
+ disconnectTrivialNodes();
+ eliminateIndependentEdges();
+ }
+
+ // Eliminate trivial nodes.
+ void disconnectTrivialNodes() {
+ unsigned numDisconnected = 0;
+
+ for (Graph::NodeItr nItr = g.nodesBegin(), nEnd = g.nodesEnd();
+ nItr != nEnd; ++nItr) {
+
+ if (g.getNodeCosts(nItr).getLength() == 1) {
+
+ std::vector<Graph::EdgeItr> edgesToRemove;
+
+ for (Graph::AdjEdgeItr aeItr = g.adjEdgesBegin(nItr),
+ aeEnd = g.adjEdgesEnd(nItr);
+ aeItr != aeEnd; ++aeItr) {
+
+ Graph::EdgeItr eItr = *aeItr;
+
+ if (g.getEdgeNode1(eItr) == nItr) {
+ Graph::NodeItr otherNodeItr = g.getEdgeNode2(eItr);
+ g.getNodeCosts(otherNodeItr) +=
+ g.getEdgeCosts(eItr).getRowAsVector(0);
+ }
+ else {
+ Graph::NodeItr otherNodeItr = g.getEdgeNode1(eItr);
+ g.getNodeCosts(otherNodeItr) +=
+ g.getEdgeCosts(eItr).getColAsVector(0);
+ }
+
+ edgesToRemove.push_back(eItr);
+ }
+
+ if (!edgesToRemove.empty())
+ ++numDisconnected;
+
+ while (!edgesToRemove.empty()) {
+ g.removeEdge(edgesToRemove.back());
+ edgesToRemove.pop_back();
+ }
+ }
+ }
+ }
+
+ void eliminateIndependentEdges() {
+ std::vector<Graph::EdgeItr> edgesToProcess;
+ unsigned numEliminated = 0;
+
+ for (Graph::EdgeItr eItr = g.edgesBegin(), eEnd = g.edgesEnd();
+ eItr != eEnd; ++eItr) {
+ edgesToProcess.push_back(eItr);
+ }
+
+ while (!edgesToProcess.empty()) {
+ if (tryToEliminateEdge(edgesToProcess.back()))
+ ++numEliminated;
+ edgesToProcess.pop_back();
+ }
+ }
+
+ bool tryToEliminateEdge(Graph::EdgeItr eItr) {
+ if (tryNormaliseEdgeMatrix(eItr)) {
+ g.removeEdge(eItr);
+ return true;
+ }
+ return false;
+ }
+
+ bool tryNormaliseEdgeMatrix(Graph::EdgeItr &eItr) {
+
+ const PBQPNum infinity = std::numeric_limits<PBQPNum>::infinity();
+
+ Matrix &edgeCosts = g.getEdgeCosts(eItr);
+ Vector &uCosts = g.getNodeCosts(g.getEdgeNode1(eItr)),
+ &vCosts = g.getNodeCosts(g.getEdgeNode2(eItr));
+
+ for (unsigned r = 0; r < edgeCosts.getRows(); ++r) {
+ PBQPNum rowMin = infinity;
+
+ for (unsigned c = 0; c < edgeCosts.getCols(); ++c) {
+ if (vCosts[c] != infinity && edgeCosts[r][c] < rowMin)
+ rowMin = edgeCosts[r][c];
+ }
+
+ uCosts[r] += rowMin;
+
+ if (rowMin != infinity) {
+ edgeCosts.subFromRow(r, rowMin);
+ }
+ else {
+ edgeCosts.setRow(r, 0);
+ }
+ }
+
+ for (unsigned c = 0; c < edgeCosts.getCols(); ++c) {
+ PBQPNum colMin = infinity;
+
+ for (unsigned r = 0; r < edgeCosts.getRows(); ++r) {
+ if (uCosts[r] != infinity && edgeCosts[r][c] < colMin)
+ colMin = edgeCosts[r][c];
+ }
+
+ vCosts[c] += colMin;
+
+ if (colMin != infinity) {
+ edgeCosts.subFromCol(c, colMin);
+ }
+ else {
+ edgeCosts.setCol(c, 0);
+ }
+ }
+
+ return edgeCosts.isZero();
+ }
+
+ void backpropagate() {
+ while (!stack.empty()) {
+ computeSolution(stack.back());
+ stack.pop_back();
+ }
+ }
+
+ void computeSolution(Graph::NodeItr nItr) {
+
+ NodeData &nodeData = getSolverNodeData(nItr);
+
+ Vector v(g.getNodeCosts(nItr));
+
+ // Solve based on existing solved edges.
+ for (SolverEdgeItr solvedEdgeItr = nodeData.solverEdgesBegin(),
+ solvedEdgeEnd = nodeData.solverEdgesEnd();
+ solvedEdgeItr != solvedEdgeEnd; ++solvedEdgeItr) {
+
+ Graph::EdgeItr eItr(*solvedEdgeItr);
+ Matrix &edgeCosts = g.getEdgeCosts(eItr);
+
+ if (nItr == g.getEdgeNode1(eItr)) {
+ Graph::NodeItr adjNode(g.getEdgeNode2(eItr));
+ unsigned adjSolution = s.getSelection(adjNode);
+ v += edgeCosts.getColAsVector(adjSolution);
+ }
+ else {
+ Graph::NodeItr adjNode(g.getEdgeNode1(eItr));
+ unsigned adjSolution = s.getSelection(adjNode);
+ v += edgeCosts.getRowAsVector(adjSolution);
+ }
+
+ }
+
+ setSolution(nItr, v.minIndex());
+ }
+
+ void cleanup() {
+ h.cleanup();
+ nodeDataList.clear();
+ edgeDataList.clear();
+ }
+ };
+
+ /// \brief PBQP heuristic solver class.
+ ///
+ /// Given a PBQP Graph g representing a PBQP problem, you can find a solution
+ /// by calling
+ /// <tt>Solution s = HeuristicSolver<H>::solve(g);</tt>
+ ///
+ /// The choice of heuristic for the H parameter will affect both the solver
+ /// speed and solution quality. The heuristic should be chosen based on the
+ /// nature of the problem being solved.
+ /// Currently the only solver included with LLVM is the Briggs heuristic for
+ /// register allocation.
+ template <typename HImpl>
+ class HeuristicSolver {
+ public:
+ static Solution solve(Graph &g) {
+ HeuristicSolverImpl<HImpl> hs(g);
+ return hs.computeSolution();
+ }
+ };
+
+}
+
+#endif // LLVM_CODEGEN_PBQP_HEURISTICSOLVER_H
diff --git a/include/llvm/CodeGen/PBQP/Heuristics/Briggs.h b/include/llvm/CodeGen/PBQP/Heuristics/Briggs.h
new file mode 100644
index 00000000000..a859e5899f0
--- /dev/null
+++ b/include/llvm/CodeGen/PBQP/Heuristics/Briggs.h
@@ -0,0 +1,469 @@
+//===-- Briggs.h --- Briggs Heuristic for PBQP ------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This class implements the Briggs test for "allocability" of nodes in a
+// PBQP graph representing a register allocation problem. Nodes which can be
+// proven allocable (by a safe and relatively accurate test) are removed from
+// the PBQP graph first. If no provably allocable node is present in the graph
+// then the node with the minimal spill-cost to degree ratio is removed.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_PBQP_HEURISTICS_BRIGGS_H
+#define LLVM_CODEGEN_PBQP_HEURISTICS_BRIGGS_H
+
+#include "../HeuristicSolver.h"
+#include "../HeuristicBase.h"
+
+#include <limits>
+
+namespace PBQP {
+ namespace Heuristics {
+
+ /// \brief PBQP Heuristic which applies an allocability test based on
+ /// Briggs.
+ ///
+ /// This heuristic assumes that the elements of cost vectors in the PBQP
+ /// problem represent storage options, with the first being the spill
+ /// option and subsequent elements representing legal registers for the
+ /// corresponding node. Edge cost matrices are likewise assumed to represent
+ /// register constraints.
+ /// If one or more nodes can be proven allocable by this heuristic (by
+ /// inspection of their constraint matrices) then the allocable node of
+ /// highest degree is selected for the next reduction and pushed to the
+ /// solver stack. If no nodes can be proven allocable then the node with
+ /// the lowest estimated spill cost is selected and push to the solver stack
+ /// instead.
+ ///
+ /// This implementation is built on top of HeuristicBase.
+ class Briggs : public HeuristicBase<Briggs> {
+ private:
+
+ class LinkDegreeComparator {
+ public:
+ LinkDegreeComparator(HeuristicSolverImpl<Briggs> &s) : s(&s) {}
+ bool operator()(Graph::NodeItr n1Itr, Graph::NodeItr n2Itr) const {
+ if (s->getSolverDegree(n1Itr) > s->getSolverDegree(n2Itr))
+ return true;
+ return false;
+ }
+ private:
+ HeuristicSolverImpl<Briggs> *s;
+ };
+
+ class SpillCostComparator {
+ public:
+ SpillCostComparator(HeuristicSolverImpl<Briggs> &s)
+ : s(&s), g(&s.getGraph()) {}
+ bool operator()(Graph::NodeItr n1Itr, Graph::NodeItr n2Itr) const {
+ const PBQP::Vector &cv1 = g->getNodeCosts(n1Itr);
+ const PBQP::Vector &cv2 = g->getNodeCosts(n2Itr);
+
+ PBQPNum cost1 = cv1[0] / s->getSolverDegree(n1Itr);
+ PBQPNum cost2 = cv2[0] / s->getSolverDegree(n2Itr);
+
+ if (cost1 < cost2)
+ return true;
+ return false;
+ }
+
+ private:
+ HeuristicSolverImpl<Briggs> *s;
+ Graph *g;
+ };
+
+ typedef std::list<Graph::NodeItr> RNAllocableList;
+ typedef RNAllocableList::iterator RNAllocableListItr;
+
+ typedef std::list<Graph::NodeItr> RNUnallocableList;
+ typedef RNUnallocableList::iterator RNUnallocableListItr;
+
+ public:
+
+ struct NodeData {
+ typedef std::vector<unsigned> UnsafeDegreesArray;
+ bool isHeuristic, isAllocable, isInitialized;
+ unsigned numDenied, numSafe;
+ UnsafeDegreesArray unsafeDegrees;
+ RNAllocableListItr rnaItr;
+ RNUnallocableListItr rnuItr;
+
+ NodeData()
+ : isHeuristic(false), isAllocable(false), isInitialized(false),
+ numDenied(0), numSafe(0) { }
+ };
+
+ struct EdgeData {
+ typedef std::vector<unsigned> UnsafeArray;
+ unsigned worst, reverseWorst;
+ UnsafeArray unsafe, reverseUnsafe;
+ bool isUpToDate;
+
+ EdgeData() : worst(0), reverseWorst(0), isUpToDate(false) {}
+ };
+
+ /// \brief Construct an instance of the Briggs heuristic.
+ /// @param solver A reference to the solver which is using this heuristic.
+ Briggs(HeuristicSolverImpl<Briggs> &solver) :
+ HeuristicBase<Briggs>(solver) {}
+
+ /// \brief Determine whether a node should be reduced using optimal
+ /// reduction.
+ /// @param nItr Node iterator to be considered.
+ /// @return True if the given node should be optimally reduced, false
+ /// otherwise.
+ ///
+ /// Selects nodes of degree 0, 1 or 2 for optimal reduction, with one
+ /// exception. Nodes whose spill cost (element 0 of their cost vector) is
+ /// infinite are checked for allocability first. Allocable nodes may be
+ /// optimally reduced, but nodes whose allocability cannot be proven are
+ /// selected for heuristic reduction instead.
+ bool shouldOptimallyReduce(Graph::NodeItr nItr) {
+ if (getSolver().getSolverDegree(nItr) < 3) {
+ return true;
+ }
+ // else
+ return false;
+ }
+
+ /// \brief Add a node to the heuristic reduce list.
+ /// @param nItr Node iterator to add to the heuristic reduce list.
+ void addToHeuristicReduceList(Graph::NodeItr nItr) {
+ NodeData &nd = getHeuristicNodeData(nItr);
+ initializeNode(nItr);
+ nd.isHeuristic = true;
+ if (nd.isAllocable) {
+ nd.rnaItr = rnAllocableList.insert(rnAllocableList.end(), nItr);
+ } else {
+ nd.rnuItr = rnUnallocableList.insert(rnUnallocableList.end(), nItr);
+ }
+ }
+
+ /// \brief Heuristically reduce one of the nodes in the heuristic
+ /// reduce list.
+ /// @return True if a reduction takes place, false if the heuristic reduce
+ /// list is empty.
+ ///
+ /// If the list of allocable nodes is non-empty a node is selected
+ /// from it and pushed to the stack. Otherwise if the non-allocable list
+ /// is non-empty a node is selected from it and pushed to the stack.
+ /// If both lists are empty the method simply returns false with no action
+ /// taken.
+ bool heuristicReduce() {
+ if (!rnAllocableList.empty()) {
+ RNAllocableListItr rnaItr =
+ min_element(rnAllocableList.begin(), rnAllocableList.end(),
+ LinkDegreeComparator(getSolver()));
+ Graph::NodeItr nItr = *rnaItr;
+ rnAllocableList.erase(rnaItr);
+ handleRemoveNode(nItr);
+ getSolver().pushToStack(nItr);
+ return true;
+ } else if (!rnUnallocableList.empty()) {
+ RNUnallocableListItr rnuItr =
+ min_element(rnUnallocableList.begin(), rnUnallocableList.end(),
+ SpillCostComparator(getSolver()));
+ Graph::NodeItr nItr = *rnuItr;
+ rnUnallocableList.erase(rnuItr);
+ handleRemoveNode(nItr);
+ getSolver().pushToStack(nItr);
+ return true;
+ }
+ // else
+ return false;
+ }
+
+ /// \brief Prepare a change in the costs on the given edge.
+ /// @param eItr Edge iterator.
+ void preUpdateEdgeCosts(Graph::EdgeItr eItr) {
+ Graph &g = getGraph();
+ Graph::NodeItr n1Itr = g.getEdgeNode1(eItr),
+ n2Itr = g.getEdgeNode2(eItr);
+ NodeData &n1 = getHeuristicNodeData(n1Itr),
+ &n2 = getHeuristicNodeData(n2Itr);
+
+ if (n1.isHeuristic)
+ subtractEdgeContributions(eItr, getGraph().getEdgeNode1(eItr));
+ if (n2.isHeuristic)
+ subtractEdgeContributions(eItr, getGraph().getEdgeNode2(eItr));
+
+ EdgeData &ed = getHeuristicEdgeData(eItr);
+ ed.isUpToDate = false;
+ }
+
+ /// \brief Handle the change in the costs on the given edge.
+ /// @param eItr Edge iterator.
+ void postUpdateEdgeCosts(Graph::EdgeItr eItr) {
+ // This is effectively the same as adding a new edge now, since
+ // we've factored out the costs of the old one.
+ handleAddEdge(eItr);
+ }
+
+ /// \brief Handle the addition of a new edge into the PBQP graph.
+ /// @param eItr Edge iterator for the added edge.
+ ///
+ /// Updates allocability of any nodes connected by this edge which are
+ /// being managed by the heuristic. If allocability changes they are
+ /// moved to the appropriate list.
+ void handleAddEdge(Graph::EdgeItr eItr) {
+ Graph &g = getGraph();
+ Graph::NodeItr n1Itr = g.getEdgeNode1(eItr),
+ n2Itr = g.getEdgeNode2(eItr);
+ NodeData &n1 = getHeuristicNodeData(n1Itr),
+ &n2 = getHeuristicNodeData(n2Itr);
+
+ // If neither node is managed by the heuristic there's nothing to be
+ // done.
+ if (!n1.isHeuristic && !n2.isHeuristic)
+ return;
+
+ // Ok - we need to update at least one node.
+ computeEdgeContributions(eItr);
+
+ // Update node 1 if it's managed by the heuristic.
+ if (n1.isHeuristic) {
+ bool n1WasAllocable = n1.isAllocable;
+ addEdgeContributions(eItr, n1Itr);
+ updateAllocability(n1Itr);
+ if (n1WasAllocable && !n1.isAllocable) {
+ rnAllocableList.erase(n1.rnaItr);
+ n1.rnuItr =
+ rnUnallocableList.insert(rnUnallocableList.end(), n1Itr);
+ }
+ }
+
+ // Likewise for node 2.
+ if (n2.isHeuristic) {
+ bool n2WasAllocable = n2.isAllocable;
+ addEdgeContributions(eItr, n2Itr);
+ updateAllocability(n2Itr);
+ if (n2WasAllocable && !n2.isAllocable) {
+ rnAllocableList.erase(n2.rnaItr);
+ n2.rnuItr =
+ rnUnallocableList.insert(rnUnallocableList.end(), n2Itr);
+ }
+ }
+ }
+
+ /// \brief Handle disconnection of an edge from a node.
+ /// @param eItr Edge iterator for edge being disconnected.
+ /// @param nItr Node iterator for the node being disconnected from.
+ ///
+ /// Updates allocability of the given node and, if appropriate, moves the
+ /// node to a new list.
+ void handleRemoveEdge(Graph::EdgeItr eItr, Graph::NodeItr nItr) {
+ NodeData &nd = getHeuristicNodeData(nItr);
+
+ // If the node is not managed by the heuristic there's nothing to be
+ // done.
+ if (!nd.isHeuristic)
+ return;
+
+ EdgeData &ed = getHeuristicEdgeData(eItr);
+ (void)ed;
+ assert(ed.isUpToDate && "Edge data is not up to date.");
+
+ // Update node.
+ bool ndWasAllocable = nd.isAllocable;
+ subtractEdgeContributions(eItr, nItr);
+ updateAllocability(nItr);
+
+ // If the node has gone optimal...
+ if (shouldOptimallyReduce(nItr)) {
+ nd.isHeuristic = false;
+ addToOptimalReduceList(nItr);
+ if (ndWasAllocable) {
+ rnAllocableList.erase(nd.rnaItr);
+ } else {
+ rnUnallocableList.erase(nd.rnuItr);
+ }
+ } else {
+ // Node didn't go optimal, but we might have to move it
+ // from "unallocable" to "allocable".
+ if (!ndWasAllocable && nd.isAllocable) {
+ rnUnallocableList.erase(nd.rnuItr);
+ nd.rnaItr = rnAllocableList.insert(rnAllocableList.end(), nItr);
+ }
+ }
+ }
+
+ private:
+
+ NodeData& getHeuristicNodeData(Graph::NodeItr nItr) {
+ return getSolver().getHeuristicNodeData(nItr);
+ }
+
+ EdgeData& getHeuristicEdgeData(Graph::EdgeItr eItr) {
+ return getSolver().getHeuristicEdgeData(eItr);
+ }
+
+ // Work out what this edge will contribute to the allocability of the
+ // nodes connected to it.
+ void computeEdgeContributions(Graph::EdgeItr eItr) {
+ EdgeData &ed = getHeuristicEdgeData(eItr);
+
+ if (ed.isUpToDate)
+ return; // Edge data is already up to date.
+
+ Matrix &eCosts = getGraph().getEdgeCosts(eItr);
+
+ unsigned numRegs = eCosts.getRows() - 1,
+ numReverseRegs = eCosts.getCols() - 1;
+
+ std::vector<unsigned> rowInfCounts(numRegs, 0),
+ colInfCounts(numReverseRegs, 0);
+
+ ed.worst = 0;
+ ed.reverseWorst = 0;
+ ed.unsafe.clear();
+ ed.unsafe.resize(numRegs, 0);
+ ed.reverseUnsafe.clear();
+ ed.reverseUnsafe.resize(numReverseRegs, 0);
+
+ for (unsigned i = 0; i < numRegs; ++i) {
+ for (unsigned j = 0; j < numReverseRegs; ++j) {
+ if (eCosts[i + 1][j + 1] ==
+ std::numeric_limits<PBQPNum>::infinity()) {
+ ed.unsafe[i] = 1;
+ ed.reverseUnsafe[j] = 1;
+ ++rowInfCounts[i];
+ ++colInfCounts[j];
+
+ if (colInfCounts[j] > ed.worst) {
+ ed.worst = colInfCounts[j];
+ }
+
+ if (rowInfCounts[i] > ed.reverseWorst) {
+ ed.reverseWorst = rowInfCounts[i];
+ }
+ }
+ }
+ }
+
+ ed.isUpToDate = true;
+ }
+
+ // Add the contributions of the given edge to the given node's
+ // numDenied and safe members. No action is taken other than to update
+ // these member values. Once updated these numbers can be used by clients
+ // to update the node's allocability.
+ void addEdgeContributions(Graph::EdgeItr eItr, Graph::NodeItr nItr) {
+ EdgeData &ed = getHeuristicEdgeData(eItr);
+
+ assert(ed.isUpToDate && "Using out-of-date edge numbers.");
+
+ NodeData &nd = getHeuristicNodeData(nItr);
+ unsigned numRegs = getGraph().getNodeCosts(nItr).getLength() - 1;
+
+ bool nIsNode1 = nItr == getGraph().getEdgeNode1(eItr);
+ EdgeData::UnsafeArray &unsafe =
+ nIsNode1 ? ed.unsafe : ed.reverseUnsafe;
+ nd.numDenied += nIsNode1 ? ed.worst : ed.reverseWorst;
+
+ for (unsigned r = 0; r < numRegs; ++r) {
+ if (unsafe[r]) {
+ if (nd.unsafeDegrees[r]==0) {
+ --nd.numSafe;
+ }
+ ++nd.unsafeDegrees[r];
+ }
+ }
+ }
+
+ // Subtract the contributions of the given edge to the given node's
+ // numDenied and safe members. No action is taken other than to update
+ // these member values. Once updated these numbers can be used by clients
+ // to update the node's allocability.
+ void subtractEdgeContributions(Graph::EdgeItr eItr, Graph::NodeItr nItr) {
+ EdgeData &ed = getHeuristicEdgeData(eItr);
+
+ assert(ed.isUpToDate && "Using out-of-date edge numbers.");
+
+ NodeData &nd = getHeuristicNodeData(nItr);
+ unsigned numRegs = getGraph().getNodeCosts(nItr).getLength() - 1;
+
+ bool nIsNode1 = nItr == getGraph().getEdgeNode1(eItr);
+ EdgeData::UnsafeArray &unsafe =
+ nIsNode1 ? ed.unsafe : ed.reverseUnsafe;
+ nd.numDenied -= nIsNode1 ? ed.worst : ed.reverseWorst;
+
+ for (unsigned r = 0; r < numRegs; ++r) {
+ if (unsafe[r]) {
+ if (nd.unsafeDegrees[r] == 1) {
+ ++nd.numSafe;
+ }
+ --nd.unsafeDegrees[r];
+ }
+ }
+ }
+
+ void updateAllocability(Graph::NodeItr nItr) {
+ NodeData &nd = getHeuristicNodeData(nItr);
+ unsigned numRegs = getGraph().getNodeCosts(nItr).getLength() - 1;
+ nd.isAllocable = nd.numDenied < numRegs || nd.numSafe > 0;
+ }
+
+ void initializeNode(Graph::NodeItr nItr) {
+ NodeData &nd = getHeuristicNodeData(nItr);
+
+ if (nd.isInitialized)
+ return; // Node data is already up to date.
+
+ unsigned numRegs = getGraph().getNodeCosts(nItr).getLength() - 1;
+
+ nd.numDenied = 0;
+ const Vector& nCosts = getGraph().getNodeCosts(nItr);
+ for (unsigned i = 1; i < nCosts.getLength(); ++i) {
+ if (nCosts[i] == std::numeric_limits<PBQPNum>::infinity())
+ ++nd.numDenied;
+ }
+
+ nd.numSafe = numRegs;
+ nd.unsafeDegrees.resize(numRegs, 0);
+
+ typedef HeuristicSolverImpl<Briggs>::SolverEdgeItr SolverEdgeItr;
+
+ for (SolverEdgeItr aeItr = getSolver().solverEdgesBegin(nItr),
+ aeEnd = getSolver().solverEdgesEnd(nItr);
+ aeItr != aeEnd; ++aeItr) {
+
+ Graph::EdgeItr eItr = *aeItr;
+ computeEdgeContributions(eItr);
+ addEdgeContributions(eItr, nItr);
+ }
+
+ updateAllocability(nItr);
+ nd.isInitialized = true;
+ }
+
+ void handleRemoveNode(Graph::NodeItr xnItr) {
+ typedef HeuristicSolverImpl<Briggs>::SolverEdgeItr SolverEdgeItr;
+ std::vector<Graph::EdgeItr> edgesToRemove;
+ for (SolverEdgeItr aeItr = getSolver().solverEdgesBegin(xnItr),
+ aeEnd = getSolver().solverEdgesEnd(xnItr);
+ aeItr != aeEnd; ++aeItr) {
+ Graph::NodeItr ynItr = getGraph().getEdgeOtherNode(*aeItr, xnItr);
+ handleRemoveEdge(*aeItr, ynItr);
+ edgesToRemove.push_back(*aeItr);
+ }
+ while (!edgesToRemove.empty()) {
+ getSolver().removeSolverEdge(edgesToRemove.back());
+ edgesToRemove.pop_back();
+ }
+ }
+
+ RNAllocableList rnAllocableList;
+ RNUnallocableList rnUnallocableList;
+ };
+
+ }
+}
+
+
+#endif // LLVM_CODEGEN_PBQP_HEURISTICS_BRIGGS_H
diff --git a/include/llvm/CodeGen/PBQP/Math.h b/include/llvm/CodeGen/PBQP/Math.h
new file mode 100644
index 00000000000..e7598bf3e3f
--- /dev/null
+++ b/include/llvm/CodeGen/PBQP/Math.h
@@ -0,0 +1,288 @@
+//===------ Math.h - PBQP Vector and Matrix classes -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_PBQP_MATH_H
+#define LLVM_CODEGEN_PBQP_MATH_H
+
+#include <cassert>
+#include <algorithm>
+#include <functional>
+
+namespace PBQP {
+
+typedef float PBQPNum;
+
+/// \brief PBQP Vector class.
+class Vector {
+ public:
+
+ /// \brief Construct a PBQP vector of the given size.
+ explicit Vector(unsigned length) :
+ length(length), data(new PBQPNum[length]) {
+ }
+
+ /// \brief Construct a PBQP vector with initializer.
+ Vector(unsigned length, PBQPNum initVal) :
+ length(length), data(new PBQPNum[length]) {
+ std::fill(data, data + length, initVal);
+ }
+
+ /// \brief Copy construct a PBQP vector.
+ Vector(const Vector &v) :
+ length(v.length), data(new PBQPNum[length]) {
+ std::copy(v.data, v.data + length, data);
+ }
+
+ /// \brief Destroy this vector, return its memory.
+ ~Vector() { delete[] data; }
+
+ /// \brief Assignment operator.
+ Vector& operator=(const Vector &v) {
+ delete[] data;
+ length = v.length;
+ data = new PBQPNum[length];
+ std::copy(v.data, v.data + length, data);
+ return *this;
+ }
+
+ /// \brief Return the length of the vector
+ unsigned getLength() const {
+ return length;
+ }
+
+ /// \brief Element access.
+ PBQPNum& operator[](unsigned index) {
+ assert(index < length && "Vector element access out of bounds.");
+ return data[index];
+ }
+
+ /// \brief Const element access.
+ const PBQPNum& operator[](unsigned index) const {
+ assert(index < length && "Vector element access out of bounds.");
+ return data[index];
+ }
+
+ /// \brief Add another vector to this one.
+ Vector& operator+=(const Vector &v) {
+ assert(length == v.length && "Vector length mismatch.");
+ std::transform(data, data + length, v.data, data, std::plus<PBQPNum>());
+ return *this;
+ }
+
+ /// \brief Subtract another vector from this one.
+ Vector& operator-=(const Vector &v) {
+ assert(length == v.length && "Vector length mismatch.");
+ std::transform(data, data + length, v.data, data, std::minus<PBQPNum>());
+ return *this;
+ }
+
+ /// \brief Returns the index of the minimum value in this vector
+ unsigned minIndex() const {
+ return std::min_element(data, data + length) - data;
+ }
+
+ private:
+ unsigned length;
+ PBQPNum *data;
+};
+
+/// \brief Output a textual representation of the given vector on the given
+/// output stream.
+template <typename OStream>
+OStream& operator<<(OStream &os, const Vector &v) {
+ assert((v.getLength() != 0) && "Zero-length vector badness.");
+
+ os << "[ " << v[0];
+ for (unsigned i = 1; i < v.getLength(); ++i) {
+ os << ", " << v[i];
+ }
+ os << " ]";
+
+ return os;
+}
+
+
+/// \brief PBQP Matrix class
+class Matrix {
+ public:
+
+ /// \brief Construct a PBQP Matrix with the given dimensions.
+ Matrix(unsigned rows, unsigned cols) :
+ rows(rows), cols(cols), data(new PBQPNum[rows * cols]) {
+ }
+
+ /// \brief Construct a PBQP Matrix with the given dimensions and initial
+ /// value.
+ Matrix(unsigned rows, unsigned cols, PBQPNum initVal) :
+ rows(rows), cols(cols), data(new PBQPNum[rows * cols]) {
+ std::fill(data, data + (rows * cols), initVal);
+ }
+
+ /// \brief Copy construct a PBQP matrix.
+ Matrix(const Matrix &m) :
+ rows(m.rows), cols(m.cols), data(new PBQPNum[rows * cols]) {
+ std::copy(m.data, m.data + (rows * cols), data);
+ }
+
+ /// \brief Destroy this matrix, return its memory.
+ ~Matrix() { delete[] data; }
+
+ /// \brief Assignment operator.
+ Matrix& operator=(const Matrix &m) {
+ delete[] data;
+ rows = m.rows; cols = m.cols;
+ data = new PBQPNum[rows * cols];
+ std::copy(m.data, m.data + (rows * cols), data);
+ return *this;
+ }
+
+ /// \brief Return the number of rows in this matrix.
+ unsigned getRows() const { return rows; }
+
+ /// \brief Return the number of cols in this matrix.
+ unsigned getCols() const { return cols; }
+
+ /// \brief Matrix element access.
+ PBQPNum* operator[](unsigned r) {
+ assert(r < rows && "Row out of bounds.");
+ return data + (r * cols);
+ }
+
+ /// \brief Matrix element access.
+ const PBQPNum* operator[](unsigned r) const {
+ assert(r < rows && "Row out of bounds.");
+ return data + (r * cols);
+ }
+
+ /// \brief Returns the given row as a vector.
+ Vector getRowAsVector(unsigned r) const {
+ Vector v(cols);
+ for (unsigned c = 0; c < cols; ++c)
+ v[c] = (*this)[r][c];
+ return v;
+ }
+
+ /// \brief Returns the given column as a vector.
+ Vector getColAsVector(unsigned c) const {
+ Vector v(rows);
+ for (unsigned r = 0; r < rows; ++r)
+ v[r] = (*this)[r][c];
+ return v;
+ }
+
+ /// \brief Reset the matrix to the given value.
+ Matrix& reset(PBQPNum val = 0) {
+ std::fill(data, data + (rows * cols), val);
+ return *this;
+ }
+
+ /// \brief Set a single row of this matrix to the given value.
+ Matrix& setRow(unsigned r, PBQPNum val) {
+ assert(r < rows && "Row out of bounds.");
+ std::fill(data + (r * cols), data + ((r + 1) * cols), val);
+ return *this;
+ }
+
+ /// \brief Set a single column of this matrix to the given value.
+ Matrix& setCol(unsigned c, PBQPNum val) {
+ assert(c < cols && "Column out of bounds.");
+ for (unsigned r = 0; r < rows; ++r)
+ (*this)[r][c] = val;
+ return *this;
+ }
+
+ /// \brief Matrix transpose.
+ Matrix transpose() const {
+ Matrix m(cols, rows);
+ for (unsigned r = 0; r < rows; ++r)
+ for (unsigned c = 0; c < cols; ++c)
+ m[c][r] = (*this)[r][c];
+ return m;
+ }
+
+ /// \brief Returns the diagonal of the matrix as a vector.
+ ///
+ /// Matrix must be square.
+ Vector diagonalize() const {
+ assert(rows == cols && "Attempt to diagonalize non-square matrix.");
+
+ Vector v(rows);
+ for (unsigned r = 0; r < rows; ++r)
+ v[r] = (*this)[r][r];
+ return v;
+ }
+
+ /// \brief Add the given matrix to this one.
+ Matrix& operator+=(const Matrix &m) {
+ assert(rows == m.rows && cols == m.cols &&
+ "Matrix dimensions mismatch.");
+ std::transform(data, data + (rows * cols), m.data, data,
+ std::plus<PBQPNum>());
+ return *this;
+ }
+
+ /// \brief Returns the minimum of the given row
+ PBQPNum getRowMin(unsigned r) const {
+ assert(r < rows && "Row out of bounds");
+ return *std::min_element(data + (r * cols), data + ((r + 1) * cols));
+ }
+
+ /// \brief Returns the minimum of the given column
+ PBQPNum getColMin(unsigned c) const {
+ PBQPNum minElem = (*this)[0][c];
+ for (unsigned r = 1; r < rows; ++r)
+ if ((*this)[r][c] < minElem) minElem = (*this)[r][c];
+ return minElem;
+ }
+
+ /// \brief Subtracts the given scalar from the elements of the given row.
+ Matrix& subFromRow(unsigned r, PBQPNum val) {
+ assert(r < rows && "Row out of bounds");
+ std::transform(data + (r * cols), data + ((r + 1) * cols),
+ data + (r * cols),
+ std::bind2nd(std::minus<PBQPNum>(), val));
+ return *this;
+ }
+
+ /// \brief Subtracts the given scalar from the elements of the given column.
+ Matrix& subFromCol(unsigned c, PBQPNum val) {
+ for (unsigned r = 0; r < rows; ++r)
+ (*this)[r][c] -= val;
+ return *this;
+ }
+
+ /// \brief Returns true if this is a zero matrix.
+ bool isZero() const {
+ return find_if(data, data + (rows * cols),
+ std::bind2nd(std::not_equal_to<PBQPNum>(), 0)) ==
+ data + (rows * cols);
+ }
+
+ private:
+ unsigned rows, cols;
+ PBQPNum *data;
+};
+
+/// \brief Output a textual representation of the given matrix on the given
+/// output stream.
+template <typename OStream>
+OStream& operator<<(OStream &os, const Matrix &m) {
+
+ assert((m.getRows() != 0) && "Zero-row matrix badness.");
+
+ for (unsigned i = 0; i < m.getRows(); ++i) {
+ os << m.getRowAsVector(i);
+ }
+
+ return os;
+}
+
+}
+
+#endif // LLVM_CODEGEN_PBQP_MATH_H
diff --git a/include/llvm/CodeGen/PBQP/Solution.h b/include/llvm/CodeGen/PBQP/Solution.h
new file mode 100644
index 00000000000..57d9b95fc3b
--- /dev/null
+++ b/include/llvm/CodeGen/PBQP/Solution.h
@@ -0,0 +1,94 @@
+//===-- Solution.h ------- PBQP Solution ------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// PBQP Solution class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_PBQP_SOLUTION_H
+#define LLVM_CODEGEN_PBQP_SOLUTION_H
+
+#include "Math.h"
+#include "Graph.h"
+
+#include <map>
+
+namespace PBQP {
+
+ /// \brief Represents a solution to a PBQP problem.
+ ///
+ /// To get the selection for each node in the problem use the getSelection method.
+ class Solution {
+ private:
+
+ typedef std::map<Graph::ConstNodeItr, unsigned,
+ NodeItrComparator> SelectionsMap;
+ SelectionsMap selections;
+
+ unsigned r0Reductions, r1Reductions, r2Reductions, rNReductions;
+
+ public:
+
+ /// \brief Initialise an empty solution.
+ Solution()
+ : r0Reductions(0), r1Reductions(0), r2Reductions(0), rNReductions(0) {}
+
+ /// \brief Number of nodes for which selections have been made.
+ /// @return Number of nodes for which selections have been made.
+ unsigned numNodes() const { return selections.size(); }
+
+ /// \brief Records a reduction via the R0 rule. Should be called from the
+ /// solver only.
+ void recordR0() { ++r0Reductions; }
+
+ /// \brief Returns the number of R0 reductions applied to solve the problem.
+ unsigned numR0Reductions() const { return r0Reductions; }
+
+ /// \brief Records a reduction via the R1 rule. Should be called from the
+ /// solver only.
+ void recordR1() { ++r1Reductions; }
+
+ /// \brief Returns the number of R1 reductions applied to solve the problem.
+ unsigned numR1Reductions() const { return r1Reductions; }
+
+ /// \brief Records a reduction via the R2 rule. Should be called from the
+ /// solver only.
+ void recordR2() { ++r2Reductions; }
+
+ /// \brief Returns the number of R2 reductions applied to solve the problem.
+ unsigned numR2Reductions() const { return r2Reductions; }
+
+ /// \brief Records a reduction via the RN rule. Should be called from the
+ /// solver only.
+ void recordRN() { ++ rNReductions; }
+
+ /// \brief Returns the number of RN reductions applied to solve the problem.
+ unsigned numRNReductions() const { return rNReductions; }
+
+ /// \brief Set the selection for a given node.
+ /// @param nItr Node iterator.
+ /// @param selection Selection for nItr.
+ void setSelection(Graph::NodeItr nItr, unsigned selection) {
+ selections[nItr] = selection;
+ }
+
+ /// \brief Get a node's selection.
+ /// @param nItr Node iterator.
+ /// @return The selection for nItr;
+ unsigned getSelection(Graph::ConstNodeItr nItr) const {
+ SelectionsMap::const_iterator sItr = selections.find(nItr);
+ assert(sItr != selections.end() && "No selection for node.");
+ return sItr->second;
+ }
+
+ };
+
+}
+
+#endif // LLVM_CODEGEN_PBQP_SOLUTION_H
diff --git a/include/llvm/CodeGen/Passes.h b/include/llvm/CodeGen/Passes.h
new file mode 100644
index 00000000000..7bd576494ef
--- /dev/null
+++ b/include/llvm/CodeGen/Passes.h
@@ -0,0 +1,514 @@
+//===-- Passes.h - Target independent code generation passes ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines interfaces to access the target independent code generation
+// passes provided by the LLVM backend.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_PASSES_H
+#define LLVM_CODEGEN_PASSES_H
+
+#include "llvm/Pass.h"
+#include "llvm/Target/TargetMachine.h"
+#include <string>
+
+namespace llvm {
+
+ class FunctionPass;
+ class MachineFunctionPass;
+ class PassInfo;
+ class PassManagerBase;
+ class TargetLowering;
+ class TargetRegisterClass;
+ class raw_ostream;
+}
+
+namespace llvm {
+
+class PassConfigImpl;
+
+/// Target-Independent Code Generator Pass Configuration Options.
+///
+/// This is an ImmutablePass solely for the purpose of exposing CodeGen options
+/// to the internals of other CodeGen passes.
+class TargetPassConfig : public ImmutablePass {
+public:
+ /// Pseudo Pass IDs. These are defined within TargetPassConfig because they
+ /// are unregistered pass IDs. They are only useful for use with
+ /// TargetPassConfig APIs to identify multiple occurrences of the same pass.
+ ///
+
+ /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
+ /// during codegen, on SSA form.
+ static char EarlyTailDuplicateID;
+
+ /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
+ /// optimization after regalloc.
+ static char PostRAMachineLICMID;
+
+private:
+ PassManagerBase *PM;
+ AnalysisID StartAfter;
+ AnalysisID StopAfter;
+ bool Started;
+ bool Stopped;
+
+protected:
+ TargetMachine *TM;
+ PassConfigImpl *Impl; // Internal data structures
+ bool Initialized; // Flagged after all passes are configured.
+
+ // Target Pass Options
+ // Targets provide a default setting, user flags override.
+ //
+ bool DisableVerify;
+
+ /// Default setting for -enable-tail-merge on this target.
+ bool EnableTailMerge;
+
+public:
+ TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
+ // Dummy constructor.
+ TargetPassConfig();
+
+ virtual ~TargetPassConfig();
+
+ static char ID;
+
+ /// Get the right type of TargetMachine for this target.
+ template<typename TMC> TMC &getTM() const {
+ return *static_cast<TMC*>(TM);
+ }
+
+ const TargetLowering *getTargetLowering() const {
+ return TM->getTargetLowering();
+ }
+
+ //
+ void setInitialized() { Initialized = true; }
+
+ CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
+
+ /// setStartStopPasses - Set the StartAfter and StopAfter passes to allow
+ /// running only a portion of the normal code-gen pass sequence. If the
+ /// Start pass ID is zero, then compilation will begin at the normal point;
+ /// otherwise, clear the Started flag to indicate that passes should not be
+ /// added until the starting pass is seen. If the Stop pass ID is zero,
+ /// then compilation will continue to the end.
+ void setStartStopPasses(AnalysisID Start, AnalysisID Stop) {
+ StartAfter = Start;
+ StopAfter = Stop;
+ Started = (StartAfter == 0);
+ }
+
+ void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
+
+ bool getEnableTailMerge() const { return EnableTailMerge; }
+ void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
+
+ /// Allow the target to override a specific pass without overriding the pass
+ /// pipeline. When passes are added to the standard pipeline at the
+ /// point where StandardID is expected, add TargetID in its place.
+ void substitutePass(AnalysisID StandardID, AnalysisID TargetID);
+
+ /// Insert InsertedPassID pass after TargetPassID pass.
+ void insertPass(AnalysisID TargetPassID, AnalysisID InsertedPassID);
+
+ /// Allow the target to enable a specific standard pass by default.
+ void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
+
+ /// Allow the target to disable a specific standard pass by default.
+ void disablePass(AnalysisID PassID) { substitutePass(PassID, 0); }
+
+ /// Return the pass substituted for StandardID by the target.
+ /// If no substitution exists, return StandardID.
+ AnalysisID getPassSubstitution(AnalysisID StandardID) const;
+
+ /// Return true if the optimized regalloc pipeline is enabled.
+ bool getOptimizeRegAlloc() const;
+
+ /// Add common target configurable passes that perform LLVM IR to IR
+ /// transforms following machine independent optimization.
+ virtual void addIRPasses();
+
+ /// Add passes to lower exception handling for the code generator.
+ void addPassesToHandleExceptions();
+
+ /// Add common passes that perform LLVM IR to IR transforms in preparation for
+ /// instruction selection.
+ virtual void addISelPrepare();
+
+ /// addInstSelector - This method should install an instruction selector pass,
+ /// which converts from LLVM code to machine instructions.
+ virtual bool addInstSelector() {
+ return true;
+ }
+
+ /// Add the complete, standard set of LLVM CodeGen passes.
+ /// Fully developed targets will not generally override this.
+ virtual void addMachinePasses();
+
+protected:
+ // Helper to verify the analysis is really immutable.
+ void setOpt(bool &Opt, bool Val);
+
+ /// Methods with trivial inline returns are convenient points in the common
+ /// codegen pass pipeline where targets may insert passes. Methods with
+ /// out-of-line standard implementations are major CodeGen stages called by
+ /// addMachinePasses. Some targets may override major stages when inserting
+ /// passes is insufficient, but maintaining overriden stages is more work.
+ ///
+
+ /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
+ /// passes (which are run just before instruction selector).
+ virtual bool addPreISel() {
+ return true;
+ }
+
+ /// addMachineSSAOptimization - Add standard passes that optimize machine
+ /// instructions in SSA form.
+ virtual void addMachineSSAOptimization();
+
+ /// addPreRegAlloc - This method may be implemented by targets that want to
+ /// run passes immediately before register allocation. This should return
+ /// true if -print-machineinstrs should print after these passes.
+ virtual bool addPreRegAlloc() {
+ return false;
+ }
+
+ /// createTargetRegisterAllocator - Create the register allocator pass for
+ /// this target at the current optimization level.
+ virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
+
+ /// addFastRegAlloc - Add the minimum set of target-independent passes that
+ /// are required for fast register allocation.
+ virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
+
+ /// addOptimizedRegAlloc - Add passes related to register allocation.
+ /// LLVMTargetMachine provides standard regalloc passes for most targets.
+ virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
+
+ /// addPreRewrite - Add passes to the optimized register allocation pipeline
+ /// after register allocation is complete, but before virtual registers are
+ /// rewritten to physical registers.
+ ///
+ /// These passes must preserve VirtRegMap and LiveIntervals, and when running
+ /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
+ /// When these passes run, VirtRegMap contains legal physreg assignments for
+ /// all virtual registers.
+ virtual bool addPreRewrite() {
+ return false;
+ }
+
+ /// addFinalizeRegAlloc - This method may be implemented by targets that want
+ /// to run passes within the regalloc pipeline, immediately after the register
+ /// allocation pass itself. These passes run as soon as virtual regisiters
+ /// have been rewritten to physical registers but before and other postRA
+ /// optimization happens. Targets that have marked instructions for bundling
+ /// must have finalized those bundles by the time these passes have run,
+ /// because subsequent passes are not guaranteed to be bundle-aware.
+ virtual bool addFinalizeRegAlloc() {
+ return false;
+ }
+
+ /// addPostRegAlloc - This method may be implemented by targets that want to
+ /// run passes after register allocation pass pipeline but before
+ /// prolog-epilog insertion. This should return true if -print-machineinstrs
+ /// should print after these passes.
+ virtual bool addPostRegAlloc() {
+ return false;
+ }
+
+ /// Add passes that optimize machine instructions after register allocation.
+ virtual void addMachineLateOptimization();
+
+ /// addPreSched2 - This method may be implemented by targets that want to
+ /// run passes after prolog-epilog insertion and before the second instruction
+ /// scheduling pass. This should return true if -print-machineinstrs should
+ /// print after these passes.
+ virtual bool addPreSched2() {
+ return false;
+ }
+
+ /// Add standard basic block placement passes.
+ virtual void addBlockPlacement();
+
+ /// addPreEmitPass - This pass may be implemented by targets that want to run
+ /// passes immediately before machine code is emitted. This should return
+ /// true if -print-machineinstrs should print out the code after the passes.
+ virtual bool addPreEmitPass() {
+ return false;
+ }
+
+ /// Utilities for targets to add passes to the pass manager.
+ ///
+
+ /// Add a CodeGen pass at this point in the pipeline after checking overrides.
+ /// Return the pass that was added, or zero if no pass was added.
+ AnalysisID addPass(AnalysisID PassID);
+
+ /// Add a pass to the PassManager if that pass is supposed to be run, as
+ /// determined by the StartAfter and StopAfter options.
+ void addPass(Pass *P);
+
+ /// addMachinePasses helper to create the target-selected or overriden
+ /// regalloc pass.
+ FunctionPass *createRegAllocPass(bool Optimized);
+
+ /// printAndVerify - Add a pass to dump then verify the machine function, if
+ /// those steps are enabled.
+ ///
+ void printAndVerify(const char *Banner);
+};
+} // namespace llvm
+
+/// List of target independent CodeGen pass IDs.
+namespace llvm {
+ /// createUnreachableBlockEliminationPass - The LLVM code generator does not
+ /// work well with unreachable basic blocks (what live ranges make sense for a
+ /// block that cannot be reached?). As such, a code generator should either
+ /// not instruction select unreachable blocks, or run this pass as its
+ /// last LLVM modifying pass to clean up blocks that are not reachable from
+ /// the entry block.
+ FunctionPass *createUnreachableBlockEliminationPass();
+
+ /// MachineFunctionPrinter pass - This pass prints out the machine function to
+ /// the given stream as a debugging tool.
+ MachineFunctionPass *
+ createMachineFunctionPrinterPass(raw_ostream &OS,
+ const std::string &Banner ="");
+
+ /// MachineLoopInfo - This pass is a loop analysis pass.
+ extern char &MachineLoopInfoID;
+
+ /// MachineLoopRanges - This pass is an on-demand loop coverage analysis.
+ extern char &MachineLoopRangesID;
+
+ /// MachineDominators - This pass is a machine dominators analysis pass.
+ extern char &MachineDominatorsID;
+
+ /// EdgeBundles analysis - Bundle machine CFG edges.
+ extern char &EdgeBundlesID;
+
+ /// LiveVariables pass - This pass computes the set of blocks in which each
+ /// variable is life and sets machine operand kill flags.
+ extern char &LiveVariablesID;
+
+ /// PHIElimination - This pass eliminates machine instruction PHI nodes
+ /// by inserting copy instructions. This destroys SSA information, but is the
+ /// desired input for some register allocators. This pass is "required" by
+ /// these register allocator like this: AU.addRequiredID(PHIEliminationID);
+ extern char &PHIEliminationID;
+
+ /// StrongPHIElimination - This pass eliminates machine instruction PHI
+ /// nodes by inserting copy instructions. This destroys SSA information, but
+ /// is the desired input for some register allocators. This pass is
+ /// "required" by these register allocator like this:
+ /// AU.addRequiredID(PHIEliminationID);
+ /// This pass is still in development
+ extern char &StrongPHIEliminationID;
+
+ /// LiveIntervals - This analysis keeps track of the live ranges of virtual
+ /// and physical registers.
+ extern char &LiveIntervalsID;
+
+ /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
+ extern char &LiveStacksID;
+
+ /// TwoAddressInstruction - This pass reduces two-address instructions to
+ /// use two operands. This destroys SSA information but it is desired by
+ /// register allocators.
+ extern char &TwoAddressInstructionPassID;
+
+ /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
+ extern char &ProcessImplicitDefsID;
+
+ /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
+ extern char &RegisterCoalescerID;
+
+ /// MachineScheduler - This pass schedules machine instructions.
+ extern char &MachineSchedulerID;
+
+ /// SpillPlacement analysis. Suggest optimal placement of spill code between
+ /// basic blocks.
+ extern char &SpillPlacementID;
+
+ /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
+ /// assigned in VirtRegMap.
+ extern char &VirtRegRewriterID;
+
+ /// UnreachableMachineBlockElimination - This pass removes unreachable
+ /// machine basic blocks.
+ extern char &UnreachableMachineBlockElimID;
+
+ /// DeadMachineInstructionElim - This pass removes dead machine instructions.
+ extern char &DeadMachineInstructionElimID;
+
+ /// FastRegisterAllocation Pass - This pass register allocates as fast as
+ /// possible. It is best suited for debug code where live ranges are short.
+ ///
+ FunctionPass *createFastRegisterAllocator();
+
+ /// BasicRegisterAllocation Pass - This pass implements a degenerate global
+ /// register allocator using the basic regalloc framework.
+ ///
+ FunctionPass *createBasicRegisterAllocator();
+
+ /// Greedy register allocation pass - This pass implements a global register
+ /// allocator for optimized builds.
+ ///
+ FunctionPass *createGreedyRegisterAllocator();
+
+ /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
+ /// Quadratic Prograaming (PBQP) based register allocator.
+ ///
+ FunctionPass *createDefaultPBQPRegisterAllocator();
+
+ /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
+ /// and eliminates abstract frame references.
+ extern char &PrologEpilogCodeInserterID;
+
+ /// ExpandPostRAPseudos - This pass expands pseudo instructions after
+ /// register allocation.
+ extern char &ExpandPostRAPseudosID;
+
+ /// createPostRAScheduler - This pass performs post register allocation
+ /// scheduling.
+ extern char &PostRASchedulerID;
+
+ /// BranchFolding - This pass performs machine code CFG based
+ /// optimizations to delete branches to branches, eliminate branches to
+ /// successor blocks (creating fall throughs), and eliminating branches over
+ /// branches.
+ extern char &BranchFolderPassID;
+
+ /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
+ extern char &MachineFunctionPrinterPassID;
+
+ /// TailDuplicate - Duplicate blocks with unconditional branches
+ /// into tails of their predecessors.
+ extern char &TailDuplicateID;
+
+ /// MachineTraceMetrics - This pass computes critical path and CPU resource
+ /// usage in an ensemble of traces.
+ extern char &MachineTraceMetricsID;
+
+ /// EarlyIfConverter - This pass performs if-conversion on SSA form by
+ /// inserting cmov instructions.
+ extern char &EarlyIfConverterID;
+
+ /// StackSlotColoring - This pass performs stack coloring and merging.
+ /// It merges disjoint allocas to reduce the stack size.
+ extern char &StackColoringID;
+
+ /// IfConverter - This pass performs machine code if conversion.
+ extern char &IfConverterID;
+
+ /// MachineBlockPlacement - This pass places basic blocks based on branch
+ /// probabilities.
+ extern char &MachineBlockPlacementID;
+
+ /// MachineBlockPlacementStats - This pass collects statistics about the
+ /// basic block placement using branch probabilities and block frequency
+ /// information.
+ extern char &MachineBlockPlacementStatsID;
+
+ /// Code Placement - This pass optimize code placement and aligns loop
+ /// headers to target specific alignment boundary.
+ extern char &CodePlacementOptID;
+
+ /// GCLowering Pass - Performs target-independent LLVM IR transformations for
+ /// highly portable strategies.
+ ///
+ FunctionPass *createGCLoweringPass();
+
+ /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
+ /// in machine code. Must be added very late during code generation, just
+ /// prior to output, and importantly after all CFG transformations (such as
+ /// branch folding).
+ extern char &GCMachineCodeAnalysisID;
+
+ /// Deleter Pass - Releases GC metadata.
+ ///
+ FunctionPass *createGCInfoDeleter();
+
+ /// Creates a pass to print GC metadata.
+ ///
+ FunctionPass *createGCInfoPrinter(raw_ostream &OS);
+
+ /// MachineCSE - This pass performs global CSE on machine instructions.
+ extern char &MachineCSEID;
+
+ /// MachineLICM - This pass performs LICM on machine instructions.
+ extern char &MachineLICMID;
+
+ /// MachineSinking - This pass performs sinking on machine instructions.
+ extern char &MachineSinkingID;
+
+ /// MachineCopyPropagation - This pass performs copy propagation on
+ /// machine instructions.
+ extern char &MachineCopyPropagationID;
+
+ /// PeepholeOptimizer - This pass performs peephole optimizations -
+ /// like extension and comparison eliminations.
+ extern char &PeepholeOptimizerID;
+
+ /// OptimizePHIs - This pass optimizes machine instruction PHIs
+ /// to take advantage of opportunities created during DAG legalization.
+ extern char &OptimizePHIsID;
+
+ /// StackSlotColoring - This pass performs stack slot coloring.
+ extern char &StackSlotColoringID;
+
+ /// createStackProtectorPass - This pass adds stack protectors to functions.
+ ///
+ FunctionPass *createStackProtectorPass(const TargetLowering *tli);
+
+ /// createMachineVerifierPass - This pass verifies cenerated machine code
+ /// instructions for correctness.
+ ///
+ FunctionPass *createMachineVerifierPass(const char *Banner = 0);
+
+ /// createDwarfEHPass - This pass mulches exception handling code into a form
+ /// adapted to code generation. Required if using dwarf exception handling.
+ FunctionPass *createDwarfEHPass(const TargetMachine *tm);
+
+ /// createSjLjEHPreparePass - This pass adapts exception handling code to use
+ /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
+ ///
+ FunctionPass *createSjLjEHPreparePass(const TargetLowering *tli);
+
+ /// LocalStackSlotAllocation - This pass assigns local frame indices to stack
+ /// slots relative to one another and allocates base registers to access them
+ /// when it is estimated by the target to be out of range of normal frame
+ /// pointer or stack pointer index addressing.
+ extern char &LocalStackSlotAllocationID;
+
+ /// ExpandISelPseudos - This pass expands pseudo-instructions.
+ extern char &ExpandISelPseudosID;
+
+ /// createExecutionDependencyFixPass - This pass fixes execution time
+ /// problems with dependent instructions, such as switching execution
+ /// domains to match.
+ ///
+ /// The pass will examine instructions using and defining registers in RC.
+ ///
+ FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
+
+ /// UnpackMachineBundles - This pass unpack machine instruction bundles.
+ extern char &UnpackMachineBundlesID;
+
+ /// FinalizeMachineBundles - This pass finalize machine instruction
+ /// bundles (created earlier, e.g. during pre-RA scheduling).
+ extern char &FinalizeMachineBundlesID;
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/PseudoSourceValue.h b/include/llvm/CodeGen/PseudoSourceValue.h
new file mode 100644
index 00000000000..7dab4f94862
--- /dev/null
+++ b/include/llvm/CodeGen/PseudoSourceValue.h
@@ -0,0 +1,112 @@
+//===-- llvm/CodeGen/PseudoSourceValue.h ------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the PseudoSourceValue class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_PSEUDOSOURCEVALUE_H
+#define LLVM_CODEGEN_PSEUDOSOURCEVALUE_H
+
+#include "llvm/Value.h"
+
+namespace llvm {
+ class MachineFrameInfo;
+ class raw_ostream;
+
+ /// PseudoSourceValue - Special value supplied for machine level alias
+ /// analysis. It indicates that a memory access references the functions
+ /// stack frame (e.g., a spill slot), below the stack frame (e.g., argument
+ /// space), or constant pool.
+ class PseudoSourceValue : public Value {
+ private:
+ /// printCustom - Implement printing for PseudoSourceValue. This is called
+ /// from Value::print or Value's operator<<.
+ ///
+ virtual void printCustom(raw_ostream &O) const;
+
+ public:
+ explicit PseudoSourceValue(enum ValueTy Subclass = PseudoSourceValueVal);
+
+ /// isConstant - Test whether the memory pointed to by this
+ /// PseudoSourceValue has a constant value.
+ ///
+ virtual bool isConstant(const MachineFrameInfo *) const;
+
+ /// isAliased - Test whether the memory pointed to by this
+ /// PseudoSourceValue may also be pointed to by an LLVM IR Value.
+ virtual bool isAliased(const MachineFrameInfo *) const;
+
+ /// mayAlias - Return true if the memory pointed to by this
+ /// PseudoSourceValue can ever alias a LLVM IR Value.
+ virtual bool mayAlias(const MachineFrameInfo *) const;
+
+ /// classof - Methods for support type inquiry through isa, cast, and
+ /// dyn_cast:
+ ///
+ static inline bool classof(const PseudoSourceValue *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == PseudoSourceValueVal ||
+ V->getValueID() == FixedStackPseudoSourceValueVal;
+ }
+
+ /// A pseudo source value referencing a fixed stack frame entry,
+ /// e.g., a spill slot.
+ static const PseudoSourceValue *getFixedStack(int FI);
+
+ /// A pseudo source value referencing the area below the stack frame of
+ /// a function, e.g., the argument space.
+ static const PseudoSourceValue *getStack();
+
+ /// A pseudo source value referencing the global offset table
+ /// (or something the like).
+ static const PseudoSourceValue *getGOT();
+
+ /// A pseudo source value referencing the constant pool. Since constant
+ /// pools are constant, this doesn't need to identify a specific constant
+ /// pool entry.
+ static const PseudoSourceValue *getConstantPool();
+
+ /// A pseudo source value referencing a jump table. Since jump tables are
+ /// constant, this doesn't need to identify a specific jump table.
+ static const PseudoSourceValue *getJumpTable();
+ };
+
+ /// FixedStackPseudoSourceValue - A specialized PseudoSourceValue
+ /// for holding FixedStack values, which must include a frame
+ /// index.
+ class FixedStackPseudoSourceValue : public PseudoSourceValue {
+ const int FI;
+ public:
+ explicit FixedStackPseudoSourceValue(int fi) :
+ PseudoSourceValue(FixedStackPseudoSourceValueVal), FI(fi) {}
+
+ /// classof - Methods for support type inquiry through isa, cast, and
+ /// dyn_cast:
+ ///
+ static inline bool classof(const FixedStackPseudoSourceValue *) {
+ return true;
+ }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == FixedStackPseudoSourceValueVal;
+ }
+
+ virtual bool isConstant(const MachineFrameInfo *MFI) const;
+
+ virtual bool isAliased(const MachineFrameInfo *MFI) const;
+
+ virtual bool mayAlias(const MachineFrameInfo *) const;
+
+ virtual void printCustom(raw_ostream &OS) const;
+
+ int getFrameIndex() const { return FI; }
+ };
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/RegAllocPBQP.h b/include/llvm/CodeGen/RegAllocPBQP.h
new file mode 100644
index 00000000000..acfc07dd31a
--- /dev/null
+++ b/include/llvm/CodeGen/RegAllocPBQP.h
@@ -0,0 +1,168 @@
+//===-- RegAllocPBQP.h ------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the PBQPBuilder interface, for classes which build PBQP
+// instances to represent register allocation problems, and the RegAllocPBQP
+// interface.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_REGALLOCPBQP_H
+#define LLVM_CODEGEN_REGALLOCPBQP_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/PBQP/Graph.h"
+#include "llvm/CodeGen/PBQP/Solution.h"
+
+#include <map>
+#include <set>
+
+namespace llvm {
+
+ class LiveIntervals;
+ class MachineFunction;
+ class MachineLoopInfo;
+
+ /// This class wraps up a PBQP instance representing a register allocation
+ /// problem, plus the structures necessary to map back from the PBQP solution
+ /// to a register allocation solution. (i.e. The PBQP-node <--> vreg map,
+ /// and the PBQP option <--> storage location map).
+
+ class PBQPRAProblem {
+ public:
+
+ typedef SmallVector<unsigned, 16> AllowedSet;
+
+ PBQP::Graph& getGraph() { return graph; }
+
+ const PBQP::Graph& getGraph() const { return graph; }
+
+ /// Record the mapping between the given virtual register and PBQP node,
+ /// and the set of allowed pregs for the vreg.
+ ///
+ /// If you are extending
+ /// PBQPBuilder you are unlikely to need this: Nodes and options for all
+ /// vregs will already have been set up for you by the base class.
+ template <typename AllowedRegsItr>
+ void recordVReg(unsigned vreg, PBQP::Graph::NodeItr node,
+ AllowedRegsItr arBegin, AllowedRegsItr arEnd) {
+ assert(node2VReg.find(node) == node2VReg.end() && "Re-mapping node.");
+ assert(vreg2Node.find(vreg) == vreg2Node.end() && "Re-mapping vreg.");
+ assert(allowedSets[vreg].empty() && "vreg already has pregs.");
+
+ node2VReg[node] = vreg;
+ vreg2Node[vreg] = node;
+ std::copy(arBegin, arEnd, std::back_inserter(allowedSets[vreg]));
+ }
+
+ /// Get the virtual register corresponding to the given PBQP node.
+ unsigned getVRegForNode(PBQP::Graph::ConstNodeItr node) const;
+
+ /// Get the PBQP node corresponding to the given virtual register.
+ PBQP::Graph::NodeItr getNodeForVReg(unsigned vreg) const;
+
+ /// Returns true if the given PBQP option represents a physical register,
+ /// false otherwise.
+ bool isPRegOption(unsigned vreg, unsigned option) const {
+ // At present we only have spills or pregs, so anything that's not a
+ // spill is a preg. (This might be extended one day to support remat).
+ return !isSpillOption(vreg, option);
+ }
+
+ /// Returns true if the given PBQP option represents spilling, false
+ /// otherwise.
+ bool isSpillOption(unsigned vreg, unsigned option) const {
+ // We hardcode option zero as the spill option.
+ return option == 0;
+ }
+
+ /// Returns the allowed set for the given virtual register.
+ const AllowedSet& getAllowedSet(unsigned vreg) const;
+
+ /// Get PReg for option.
+ unsigned getPRegForOption(unsigned vreg, unsigned option) const;
+
+ private:
+
+ typedef std::map<PBQP::Graph::ConstNodeItr, unsigned,
+ PBQP::NodeItrComparator> Node2VReg;
+ typedef DenseMap<unsigned, PBQP::Graph::NodeItr> VReg2Node;
+ typedef DenseMap<unsigned, AllowedSet> AllowedSetMap;
+
+ PBQP::Graph graph;
+ Node2VReg node2VReg;
+ VReg2Node vreg2Node;
+
+ AllowedSetMap allowedSets;
+
+ };
+
+ /// Builds PBQP instances to represent register allocation problems. Includes
+ /// spill, interference and coalescing costs by default. You can extend this
+ /// class to support additional constraints for your architecture.
+ class PBQPBuilder {
+ private:
+ PBQPBuilder(const PBQPBuilder&) LLVM_DELETED_FUNCTION;
+ void operator=(const PBQPBuilder&) LLVM_DELETED_FUNCTION;
+ public:
+
+ typedef std::set<unsigned> RegSet;
+
+ /// Default constructor.
+ PBQPBuilder() {}
+
+ /// Clean up a PBQPBuilder.
+ virtual ~PBQPBuilder() {}
+
+ /// Build a PBQP instance to represent the register allocation problem for
+ /// the given MachineFunction.
+ virtual std::auto_ptr<PBQPRAProblem> build(
+ MachineFunction *mf,
+ const LiveIntervals *lis,
+ const MachineLoopInfo *loopInfo,
+ const RegSet &vregs);
+ private:
+
+ void addSpillCosts(PBQP::Vector &costVec, PBQP::PBQPNum spillCost);
+
+ void addInterferenceCosts(PBQP::Matrix &costMat,
+ const PBQPRAProblem::AllowedSet &vr1Allowed,
+ const PBQPRAProblem::AllowedSet &vr2Allowed,
+ const TargetRegisterInfo *tri);
+ };
+
+ /// Extended builder which adds coalescing constraints to a problem.
+ class PBQPBuilderWithCoalescing : public PBQPBuilder {
+ public:
+
+ /// Build a PBQP instance to represent the register allocation problem for
+ /// the given MachineFunction.
+ virtual std::auto_ptr<PBQPRAProblem> build(
+ MachineFunction *mf,
+ const LiveIntervals *lis,
+ const MachineLoopInfo *loopInfo,
+ const RegSet &vregs);
+
+ private:
+
+ void addPhysRegCoalesce(PBQP::Vector &costVec, unsigned pregOption,
+ PBQP::PBQPNum benefit);
+
+ void addVirtRegCoalesce(PBQP::Matrix &costMat,
+ const PBQPRAProblem::AllowedSet &vr1Allowed,
+ const PBQPRAProblem::AllowedSet &vr2Allowed,
+ PBQP::PBQPNum benefit);
+ };
+
+ FunctionPass* createPBQPRegisterAllocator(std::auto_ptr<PBQPBuilder> builder,
+ char *customPassID=0);
+}
+
+#endif /* LLVM_CODEGEN_REGALLOCPBQP_H */
diff --git a/include/llvm/CodeGen/RegAllocRegistry.h b/include/llvm/CodeGen/RegAllocRegistry.h
new file mode 100644
index 00000000000..100e357654f
--- /dev/null
+++ b/include/llvm/CodeGen/RegAllocRegistry.h
@@ -0,0 +1,66 @@
+//===-- llvm/CodeGen/RegAllocRegistry.h -------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the implementation for register allocator function
+// pass registry (RegisterRegAlloc).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGENREGALLOCREGISTRY_H
+#define LLVM_CODEGENREGALLOCREGISTRY_H
+
+#include "llvm/CodeGen/MachinePassRegistry.h"
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+///
+/// RegisterRegAlloc class - Track the registration of register allocators.
+///
+//===----------------------------------------------------------------------===//
+class RegisterRegAlloc : public MachinePassRegistryNode {
+
+public:
+
+ typedef FunctionPass *(*FunctionPassCtor)();
+
+ static MachinePassRegistry Registry;
+
+ RegisterRegAlloc(const char *N, const char *D, FunctionPassCtor C)
+ : MachinePassRegistryNode(N, D, (MachinePassCtor)C)
+ {
+ Registry.Add(this);
+ }
+ ~RegisterRegAlloc() { Registry.Remove(this); }
+
+
+ // Accessors.
+ //
+ RegisterRegAlloc *getNext() const {
+ return (RegisterRegAlloc *)MachinePassRegistryNode::getNext();
+ }
+ static RegisterRegAlloc *getList() {
+ return (RegisterRegAlloc *)Registry.getList();
+ }
+ static FunctionPassCtor getDefault() {
+ return (FunctionPassCtor)Registry.getDefault();
+ }
+ static void setDefault(FunctionPassCtor C) {
+ Registry.setDefault((MachinePassCtor)C);
+ }
+ static void setListener(MachinePassRegistryListener *L) {
+ Registry.setListener(L);
+ }
+
+};
+
+} // end namespace llvm
+
+
+#endif
diff --git a/include/llvm/CodeGen/RegisterClassInfo.h b/include/llvm/CodeGen/RegisterClassInfo.h
new file mode 100644
index 00000000000..400e1f48ce5
--- /dev/null
+++ b/include/llvm/CodeGen/RegisterClassInfo.h
@@ -0,0 +1,132 @@
+//===-- RegisterClassInfo.h - Dynamic Register Class Info -*- C++ -*-------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the RegisterClassInfo class which provides dynamic
+// information about target register classes. Callee saved and reserved
+// registers depends on calling conventions and other dynamic information, so
+// some things cannot be determined statically.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_REGISTERCLASSINFO_H
+#define LLVM_CODEGEN_REGISTERCLASSINFO_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/Target/TargetRegisterInfo.h"
+
+namespace llvm {
+
+class RegisterClassInfo {
+ struct RCInfo {
+ unsigned Tag;
+ unsigned NumRegs;
+ bool ProperSubClass;
+ OwningArrayPtr<unsigned> Order;
+
+ RCInfo() : Tag(0), NumRegs(0), ProperSubClass(false) {}
+ operator ArrayRef<unsigned>() const {
+ return makeArrayRef(Order.get(), NumRegs);
+ }
+ };
+
+ // Brief cached information for each register class.
+ OwningArrayPtr<RCInfo> RegClass;
+
+ // Tag changes whenever cached information needs to be recomputed. An RCInfo
+ // entry is valid when its tag matches.
+ unsigned Tag;
+
+ const MachineFunction *MF;
+ const TargetRegisterInfo *TRI;
+
+ // Callee saved registers of last MF. Assumed to be valid until the next
+ // runOnFunction() call.
+ const uint16_t *CalleeSaved;
+
+ // Map register number to CalleeSaved index + 1;
+ SmallVector<uint8_t, 4> CSRNum;
+
+ // Reserved registers in the current MF.
+ BitVector Reserved;
+
+ // Compute all information about RC.
+ void compute(const TargetRegisterClass *RC) const;
+
+ // Return an up-to-date RCInfo for RC.
+ const RCInfo &get(const TargetRegisterClass *RC) const {
+ const RCInfo &RCI = RegClass[RC->getID()];
+ if (Tag != RCI.Tag)
+ compute(RC);
+ return RCI;
+ }
+
+public:
+ RegisterClassInfo();
+
+ /// runOnFunction - Prepare to answer questions about MF. This must be called
+ /// before any other methods are used.
+ void runOnMachineFunction(const MachineFunction &MF);
+
+ /// getNumAllocatableRegs - Returns the number of actually allocatable
+ /// registers in RC in the current function.
+ unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const {
+ return get(RC).NumRegs;
+ }
+
+ /// getOrder - Returns the preferred allocation order for RC. The order
+ /// contains no reserved registers, and registers that alias callee saved
+ /// registers come last.
+ ArrayRef<unsigned> getOrder(const TargetRegisterClass *RC) const {
+ return get(RC);
+ }
+
+ /// isProperSubClass - Returns true if RC has a legal super-class with more
+ /// allocatable registers.
+ ///
+ /// Register classes like GR32_NOSP are not proper sub-classes because %esp
+ /// is not allocatable. Similarly, tGPR is not a proper sub-class in Thumb
+ /// mode because the GPR super-class is not legal.
+ bool isProperSubClass(const TargetRegisterClass *RC) const {
+ return get(RC).ProperSubClass;
+ }
+
+ /// getLastCalleeSavedAlias - Returns the last callee saved register that
+ /// overlaps PhysReg, or 0 if Reg doesn't overlap a CSR.
+ unsigned getLastCalleeSavedAlias(unsigned PhysReg) const {
+ assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));
+ if (unsigned N = CSRNum[PhysReg])
+ return CalleeSaved[N-1];
+ return 0;
+ }
+
+ /// isReserved - Returns true when PhysReg is a reserved register.
+ ///
+ /// Reserved registers may belong to an allocatable register class, but the
+ /// target has explicitly requested that they are not used.
+ ///
+ bool isReserved(unsigned PhysReg) const {
+ return Reserved.test(PhysReg);
+ }
+
+ /// isAllocatable - Returns true when PhysReg belongs to an allocatable
+ /// register class and it hasn't been reserved.
+ ///
+ /// Allocatable registers may show up in the allocation order of some virtual
+ /// register, so a register allocator needs to track its liveness and
+ /// availability.
+ bool isAllocatable(unsigned PhysReg) const {
+ return TRI->isInAllocatableClass(PhysReg) && !isReserved(PhysReg);
+ }
+};
+} // end namespace llvm
+
+#endif
+
diff --git a/include/llvm/CodeGen/RegisterPressure.h b/include/llvm/CodeGen/RegisterPressure.h
new file mode 100644
index 00000000000..2043155bc53
--- /dev/null
+++ b/include/llvm/CodeGen/RegisterPressure.h
@@ -0,0 +1,282 @@
+//===-- RegisterPressure.h - Dynamic Register Pressure -*- C++ -*-------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the RegisterPressure class which can be used to track
+// MachineInstr level register pressure.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_REGISTERPRESSURE_H
+#define LLVM_CODEGEN_REGISTERPRESSURE_H
+
+#include "llvm/CodeGen/SlotIndexes.h"
+#include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/ADT/SparseSet.h"
+
+namespace llvm {
+
+class LiveIntervals;
+class RegisterClassInfo;
+class MachineInstr;
+
+/// Base class for register pressure results.
+struct RegisterPressure {
+ /// Map of max reg pressure indexed by pressure set ID, not class ID.
+ std::vector<unsigned> MaxSetPressure;
+
+ /// List of live in registers.
+ SmallVector<unsigned,8> LiveInRegs;
+ SmallVector<unsigned,8> LiveOutRegs;
+
+ /// Increase register pressure for each pressure set impacted by this register
+ /// class. Normally called by RegPressureTracker, but may be called manually
+ /// to account for live through (global liveness).
+ void increase(const TargetRegisterClass *RC, const TargetRegisterInfo *TRI);
+
+ /// Decrease register pressure for each pressure set impacted by this register
+ /// class. This is only useful to account for spilling or rematerialization.
+ void decrease(const TargetRegisterClass *RC, const TargetRegisterInfo *TRI);
+
+ void dump(const TargetRegisterInfo *TRI);
+};
+
+/// RegisterPressure computed within a region of instructions delimited by
+/// TopIdx and BottomIdx. During pressure computation, the maximum pressure per
+/// register pressure set is increased. Once pressure within a region is fully
+/// computed, the live-in and live-out sets are recorded.
+///
+/// This is preferable to RegionPressure when LiveIntervals are available,
+/// because delimiting regions by SlotIndex is more robust and convenient than
+/// holding block iterators. The block contents can change without invalidating
+/// the pressure result.
+struct IntervalPressure : RegisterPressure {
+ /// Record the boundary of the region being tracked.
+ SlotIndex TopIdx;
+ SlotIndex BottomIdx;
+
+ void reset();
+
+ void openTop(SlotIndex NextTop);
+
+ void openBottom(SlotIndex PrevBottom);
+};
+
+/// RegisterPressure computed within a region of instructions delimited by
+/// TopPos and BottomPos. This is a less precise version of IntervalPressure for
+/// use when LiveIntervals are unavailable.
+struct RegionPressure : RegisterPressure {
+ /// Record the boundary of the region being tracked.
+ MachineBasicBlock::const_iterator TopPos;
+ MachineBasicBlock::const_iterator BottomPos;
+
+ void reset();
+
+ void openTop(MachineBasicBlock::const_iterator PrevTop);
+
+ void openBottom(MachineBasicBlock::const_iterator PrevBottom);
+};
+
+/// An element of pressure difference that identifies the pressure set and
+/// amount of increase or decrease in units of pressure.
+struct PressureElement {
+ unsigned PSetID;
+ int UnitIncrease;
+
+ PressureElement(): PSetID(~0U), UnitIncrease(0) {}
+ PressureElement(unsigned id, int inc): PSetID(id), UnitIncrease(inc) {}
+
+ bool isValid() const { return PSetID != ~0U; }
+};
+
+/// Store the effects of a change in pressure on things that MI scheduler cares
+/// about.
+///
+/// Excess records the value of the largest difference in register units beyond
+/// the target's pressure limits across the affected pressure sets, where
+/// largest is defined as the absolute value of the difference. Negative
+/// ExcessUnits indicates a reduction in pressure that had already exceeded the
+/// target's limits.
+///
+/// CriticalMax records the largest increase in the tracker's max pressure that
+/// exceeds the critical limit for some pressure set determined by the client.
+///
+/// CurrentMax records the largest increase in the tracker's max pressure that
+/// exceeds the current limit for some pressure set determined by the client.
+struct RegPressureDelta {
+ PressureElement Excess;
+ PressureElement CriticalMax;
+ PressureElement CurrentMax;
+
+ RegPressureDelta() {}
+};
+
+/// Track the current register pressure at some position in the instruction
+/// stream, and remember the high water mark within the region traversed. This
+/// does not automatically consider live-through ranges. The client may
+/// independently adjust for global liveness.
+///
+/// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
+/// be tracked across a larger region by storing a RegisterPressure result at
+/// each block boundary and explicitly adjusting pressure to account for block
+/// live-in and live-out register sets.
+///
+/// RegPressureTracker holds a reference to a RegisterPressure result that it
+/// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
+/// is invalid until it reaches the end of the block or closeRegion() is
+/// explicitly called. Similarly, P.TopIdx is invalid during upward
+/// tracking. Changing direction has the side effect of closing region, and
+/// traversing past TopIdx or BottomIdx reopens it.
+class RegPressureTracker {
+ const MachineFunction *MF;
+ const TargetRegisterInfo *TRI;
+ const RegisterClassInfo *RCI;
+ const MachineRegisterInfo *MRI;
+ const LiveIntervals *LIS;
+
+ /// We currently only allow pressure tracking within a block.
+ const MachineBasicBlock *MBB;
+
+ /// Track the max pressure within the region traversed so far.
+ RegisterPressure &P;
+
+ /// Run in two modes dependending on whether constructed with IntervalPressure
+ /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
+ bool RequireIntervals;
+
+ /// Register pressure corresponds to liveness before this instruction
+ /// iterator. It may point to the end of the block rather than an instruction.
+ MachineBasicBlock::const_iterator CurrPos;
+
+ /// Pressure map indexed by pressure set ID, not class ID.
+ std::vector<unsigned> CurrSetPressure;
+
+ /// List of live registers.
+ SparseSet<unsigned> LivePhysRegs;
+ SparseSet<unsigned, VirtReg2IndexFunctor> LiveVirtRegs;
+
+public:
+ RegPressureTracker(IntervalPressure &rp) :
+ MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(true) {}
+
+ RegPressureTracker(RegionPressure &rp) :
+ MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(false) {}
+
+ void init(const MachineFunction *mf, const RegisterClassInfo *rci,
+ const LiveIntervals *lis, const MachineBasicBlock *mbb,
+ MachineBasicBlock::const_iterator pos);
+
+ /// Force liveness of registers. Particularly useful to initialize the
+ /// livein/out state of the tracker before the first call to advance/recede.
+ void addLiveRegs(ArrayRef<unsigned> Regs);
+
+ /// Get the MI position corresponding to this register pressure.
+ MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
+
+ // Reset the MI position corresponding to the register pressure. This allows
+ // schedulers to move instructions above the RegPressureTracker's
+ // CurrPos. Since the pressure is computed before CurrPos, the iterator
+ // position changes while pressure does not.
+ void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
+
+ /// Recede across the previous instruction.
+ bool recede();
+
+ /// Advance across the current instruction.
+ bool advance();
+
+ /// Finalize the region boundaries and recored live ins and live outs.
+ void closeRegion();
+
+ /// Get the resulting register pressure over the traversed region.
+ /// This result is complete if either advance() or recede() has returned true,
+ /// or if closeRegion() was explicitly invoked.
+ RegisterPressure &getPressure() { return P; }
+
+ /// Get the register set pressure at the current position, which may be less
+ /// than the pressure across the traversed region.
+ std::vector<unsigned> &getRegSetPressureAtPos() { return CurrSetPressure; }
+
+ void discoverPhysLiveIn(unsigned Reg);
+ void discoverPhysLiveOut(unsigned Reg);
+
+ void discoverVirtLiveIn(unsigned Reg);
+ void discoverVirtLiveOut(unsigned Reg);
+
+ bool isTopClosed() const;
+ bool isBottomClosed() const;
+
+ void closeTop();
+ void closeBottom();
+
+ /// Consider the pressure increase caused by traversing this instruction
+ /// bottom-up. Find the pressure set with the most change beyond its pressure
+ /// limit based on the tracker's current pressure, and record the number of
+ /// excess register units of that pressure set introduced by this instruction.
+ void getMaxUpwardPressureDelta(const MachineInstr *MI,
+ RegPressureDelta &Delta,
+ ArrayRef<PressureElement> CriticalPSets,
+ ArrayRef<unsigned> MaxPressureLimit);
+
+ /// Consider the pressure increase caused by traversing this instruction
+ /// top-down. Find the pressure set with the most change beyond its pressure
+ /// limit based on the tracker's current pressure, and record the number of
+ /// excess register units of that pressure set introduced by this instruction.
+ void getMaxDownwardPressureDelta(const MachineInstr *MI,
+ RegPressureDelta &Delta,
+ ArrayRef<PressureElement> CriticalPSets,
+ ArrayRef<unsigned> MaxPressureLimit);
+
+ /// Find the pressure set with the most change beyond its pressure limit after
+ /// traversing this instruction either upward or downward depending on the
+ /// closed end of the current region.
+ void getMaxPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
+ ArrayRef<PressureElement> CriticalPSets,
+ ArrayRef<unsigned> MaxPressureLimit) {
+ if (isTopClosed())
+ return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
+ MaxPressureLimit);
+
+ assert(isBottomClosed() && "Uninitialized pressure tracker");
+ return getMaxUpwardPressureDelta(MI, Delta, CriticalPSets,
+ MaxPressureLimit);
+ }
+
+ /// Get the pressure of each PSet after traversing this instruction bottom-up.
+ void getUpwardPressure(const MachineInstr *MI,
+ std::vector<unsigned> &PressureResult,
+ std::vector<unsigned> &MaxPressureResult);
+
+ /// Get the pressure of each PSet after traversing this instruction top-down.
+ void getDownwardPressure(const MachineInstr *MI,
+ std::vector<unsigned> &PressureResult,
+ std::vector<unsigned> &MaxPressureResult);
+
+ void getPressureAfterInst(const MachineInstr *MI,
+ std::vector<unsigned> &PressureResult,
+ std::vector<unsigned> &MaxPressureResult) {
+ if (isTopClosed())
+ return getUpwardPressure(MI, PressureResult, MaxPressureResult);
+
+ assert(isBottomClosed() && "Uninitialized pressure tracker");
+ return getDownwardPressure(MI, PressureResult, MaxPressureResult);
+ }
+
+protected:
+ void increasePhysRegPressure(ArrayRef<unsigned> Regs);
+ void decreasePhysRegPressure(ArrayRef<unsigned> Regs);
+
+ void increaseVirtRegPressure(ArrayRef<unsigned> Regs);
+ void decreaseVirtRegPressure(ArrayRef<unsigned> Regs);
+
+ void bumpUpwardPressure(const MachineInstr *MI);
+ void bumpDownwardPressure(const MachineInstr *MI);
+};
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/RegisterScavenging.h b/include/llvm/CodeGen/RegisterScavenging.h
new file mode 100644
index 00000000000..3986a8dd7da
--- /dev/null
+++ b/include/llvm/CodeGen/RegisterScavenging.h
@@ -0,0 +1,170 @@
+//===-- RegisterScavenging.h - Machine register scavenging ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the machine register scavenger class. It can provide
+// information such as unused register at any point in a machine basic block.
+// It also provides a mechanism to make registers availbale by evicting them
+// to spill slots.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_REGISTER_SCAVENGING_H
+#define LLVM_CODEGEN_REGISTER_SCAVENGING_H
+
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/ADT/BitVector.h"
+
+namespace llvm {
+
+class MachineRegisterInfo;
+class TargetRegisterInfo;
+class TargetInstrInfo;
+class TargetRegisterClass;
+
+class RegScavenger {
+ const TargetRegisterInfo *TRI;
+ const TargetInstrInfo *TII;
+ MachineRegisterInfo* MRI;
+ MachineBasicBlock *MBB;
+ MachineBasicBlock::iterator MBBI;
+ unsigned NumPhysRegs;
+
+ /// Tracking - True if RegScavenger is currently tracking the liveness of
+ /// registers.
+ bool Tracking;
+
+ /// ScavengingFrameIndex - Special spill slot used for scavenging a register
+ /// post register allocation.
+ int ScavengingFrameIndex;
+
+ /// ScavengedReg - If none zero, the specific register is currently being
+ /// scavenged. That is, it is spilled to the special scavenging stack slot.
+ unsigned ScavengedReg;
+
+ /// ScavengedRC - Register class of the scavenged register.
+ ///
+ const TargetRegisterClass *ScavengedRC;
+
+ /// ScavengeRestore - Instruction that restores the scavenged register from
+ /// stack.
+ const MachineInstr *ScavengeRestore;
+
+ /// CalleeSavedrRegs - A bitvector of callee saved registers for the target.
+ ///
+ BitVector CalleeSavedRegs;
+
+ /// ReservedRegs - A bitvector of reserved registers.
+ ///
+ BitVector ReservedRegs;
+
+ /// RegsAvailable - The current state of all the physical registers immediately
+ /// before MBBI. One bit per physical register. If bit is set that means it's
+ /// available, unset means the register is currently being used.
+ BitVector RegsAvailable;
+
+ // These BitVectors are only used internally to forward(). They are members
+ // to avoid frequent reallocations.
+ BitVector KillRegs, DefRegs;
+
+public:
+ RegScavenger()
+ : MBB(NULL), NumPhysRegs(0), Tracking(false),
+ ScavengingFrameIndex(-1), ScavengedReg(0), ScavengedRC(NULL) {}
+
+ /// enterBasicBlock - Start tracking liveness from the begin of the specific
+ /// basic block.
+ void enterBasicBlock(MachineBasicBlock *mbb);
+
+ /// initRegState - allow resetting register state info for multiple
+ /// passes over/within the same function.
+ void initRegState();
+
+ /// forward - Move the internal MBB iterator and update register states.
+ void forward();
+
+ /// forward - Move the internal MBB iterator and update register states until
+ /// it has processed the specific iterator.
+ void forward(MachineBasicBlock::iterator I) {
+ if (!Tracking && MBB->begin() != I) forward();
+ while (MBBI != I) forward();
+ }
+
+ /// skipTo - Move the internal MBB iterator but do not update register states.
+ ///
+ void skipTo(MachineBasicBlock::iterator I) { MBBI = I; }
+
+ /// getRegsUsed - return all registers currently in use in used.
+ void getRegsUsed(BitVector &used, bool includeReserved);
+
+ /// getRegsAvailable - Return all available registers in the register class
+ /// in Mask.
+ BitVector getRegsAvailable(const TargetRegisterClass *RC);
+
+ /// FindUnusedReg - Find a unused register of the specified register class.
+ /// Return 0 if none is found.
+ unsigned FindUnusedReg(const TargetRegisterClass *RegClass) const;
+
+ /// setScavengingFrameIndex / getScavengingFrameIndex - accessor and setter of
+ /// ScavengingFrameIndex.
+ void setScavengingFrameIndex(int FI) { ScavengingFrameIndex = FI; }
+ int getScavengingFrameIndex() const { return ScavengingFrameIndex; }
+
+ /// scavengeRegister - Make a register of the specific register class
+ /// available and do the appropriate bookkeeping. SPAdj is the stack
+ /// adjustment due to call frame, it's passed along to eliminateFrameIndex().
+ /// Returns the scavenged register.
+ unsigned scavengeRegister(const TargetRegisterClass *RegClass,
+ MachineBasicBlock::iterator I, int SPAdj);
+ unsigned scavengeRegister(const TargetRegisterClass *RegClass, int SPAdj) {
+ return scavengeRegister(RegClass, MBBI, SPAdj);
+ }
+
+ /// setUsed - Tell the scavenger a register is used.
+ ///
+ void setUsed(unsigned Reg);
+private:
+ /// isReserved - Returns true if a register is reserved. It is never "unused".
+ bool isReserved(unsigned Reg) const { return ReservedRegs.test(Reg); }
+
+ /// isUsed / isUnused - Test if a register is currently being used.
+ ///
+ bool isUsed(unsigned Reg) const {
+ return !RegsAvailable.test(Reg) || ReservedRegs.test(Reg);
+ }
+
+ /// isAliasUsed - Is Reg or an alias currently in use?
+ bool isAliasUsed(unsigned Reg) const;
+
+ /// setUsed / setUnused - Mark the state of one or a number of registers.
+ ///
+ void setUsed(BitVector &Regs) {
+ RegsAvailable.reset(Regs);
+ }
+ void setUnused(BitVector &Regs) {
+ RegsAvailable |= Regs;
+ }
+
+ /// Add Reg and all its sub-registers to BV.
+ void addRegWithSubRegs(BitVector &BV, unsigned Reg);
+
+ /// findSurvivorReg - Return the candidate register that is unused for the
+ /// longest after StartMI. UseMI is set to the instruction where the search
+ /// stopped.
+ ///
+ /// No more than InstrLimit instructions are inspected.
+ unsigned findSurvivorReg(MachineBasicBlock::iterator StartMI,
+ BitVector &Candidates,
+ unsigned InstrLimit,
+ MachineBasicBlock::iterator &UseMI);
+
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/ResourcePriorityQueue.h b/include/llvm/CodeGen/ResourcePriorityQueue.h
new file mode 100644
index 00000000000..56b5855c01c
--- /dev/null
+++ b/include/llvm/CodeGen/ResourcePriorityQueue.h
@@ -0,0 +1,142 @@
+//===----- ResourcePriorityQueue.h - A DFA-oriented priority queue -------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the ResourcePriorityQueue class, which is a
+// SchedulingPriorityQueue that schedules using DFA state to
+// reduce the length of the critical path through the basic block
+// on VLIW platforms.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef RESOURCE_PRIORITY_QUEUE_H
+#define RESOURCE_PRIORITY_QUEUE_H
+
+#include "llvm/CodeGen/DFAPacketizer.h"
+#include "llvm/CodeGen/SelectionDAGISel.h"
+#include "llvm/CodeGen/ScheduleDAG.h"
+#include "llvm/MC/MCInstrItineraries.h"
+#include "llvm/Target/TargetInstrInfo.h"
+#include "llvm/Target/TargetRegisterInfo.h"
+
+namespace llvm {
+ class ResourcePriorityQueue;
+
+ /// Sorting functions for the Available queue.
+ struct resource_sort : public std::binary_function<SUnit*, SUnit*, bool> {
+ ResourcePriorityQueue *PQ;
+ explicit resource_sort(ResourcePriorityQueue *pq) : PQ(pq) {}
+
+ bool operator()(const SUnit* left, const SUnit* right) const;
+ };
+
+ class ResourcePriorityQueue : public SchedulingPriorityQueue {
+ /// SUnits - The SUnits for the current graph.
+ std::vector<SUnit> *SUnits;
+
+ /// NumNodesSolelyBlocking - This vector contains, for every node in the
+ /// Queue, the number of nodes that the node is the sole unscheduled
+ /// predecessor for. This is used as a tie-breaker heuristic for better
+ /// mobility.
+ std::vector<unsigned> NumNodesSolelyBlocking;
+
+ /// Queue - The queue.
+ std::vector<SUnit*> Queue;
+
+ /// RegPressure - Tracking current reg pressure per register class.
+ ///
+ std::vector<unsigned> RegPressure;
+
+ /// RegLimit - Tracking the number of allocatable registers per register
+ /// class.
+ std::vector<unsigned> RegLimit;
+
+ resource_sort Picker;
+ const TargetRegisterInfo *TRI;
+ const TargetLowering *TLI;
+ const TargetInstrInfo *TII;
+ const InstrItineraryData* InstrItins;
+ /// ResourcesModel - Represents VLIW state.
+ /// Not limited to VLIW targets per say, but assumes
+ /// definition of DFA by a target.
+ DFAPacketizer *ResourcesModel;
+
+ /// Resource model - packet/bundle model. Purely
+ /// internal at the time.
+ std::vector<SUnit*> Packet;
+
+ /// Heuristics for estimating register pressure.
+ unsigned ParallelLiveRanges;
+ signed HorizontalVerticalBalance;
+
+ public:
+ ResourcePriorityQueue(SelectionDAGISel *IS);
+
+ ~ResourcePriorityQueue() {
+ delete ResourcesModel;
+ }
+
+ bool isBottomUp() const { return false; }
+
+ void initNodes(std::vector<SUnit> &sunits);
+
+ void addNode(const SUnit *SU) {
+ NumNodesSolelyBlocking.resize(SUnits->size(), 0);
+ }
+
+ void updateNode(const SUnit *SU) {}
+
+ void releaseState() {
+ SUnits = 0;
+ }
+
+ unsigned getLatency(unsigned NodeNum) const {
+ assert(NodeNum < (*SUnits).size());
+ return (*SUnits)[NodeNum].getHeight();
+ }
+
+ unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
+ assert(NodeNum < NumNodesSolelyBlocking.size());
+ return NumNodesSolelyBlocking[NodeNum];
+ }
+
+ /// Single cost function reflecting benefit of scheduling SU
+ /// in the current cycle.
+ signed SUSchedulingCost (SUnit *SU);
+
+ /// InitNumRegDefsLeft - Determine the # of regs defined by this node.
+ ///
+ void initNumRegDefsLeft(SUnit *SU);
+ void updateNumRegDefsLeft(SUnit *SU);
+ signed regPressureDelta(SUnit *SU, bool RawPressure = false);
+ signed rawRegPressureDelta (SUnit *SU, unsigned RCId);
+
+ bool empty() const { return Queue.empty(); }
+
+ virtual void push(SUnit *U);
+
+ virtual SUnit *pop();
+
+ virtual void remove(SUnit *SU);
+
+ virtual void dump(ScheduleDAG* DAG) const;
+
+ /// scheduledNode - Main resource tracking point.
+ void scheduledNode(SUnit *Node);
+ bool isResourceAvailable(SUnit *SU);
+ void reserveResources(SUnit *SU);
+
+private:
+ void adjustPriorityOfUnscheduledPreds(SUnit *SU);
+ SUnit *getSingleUnscheduledPred(SUnit *SU);
+ unsigned numberRCValPredInSU (SUnit *SU, unsigned RCId);
+ unsigned numberRCValSuccInSU (SUnit *SU, unsigned RCId);
+ };
+}
+
+#endif
diff --git a/include/llvm/CodeGen/RuntimeLibcalls.h b/include/llvm/CodeGen/RuntimeLibcalls.h
new file mode 100644
index 00000000000..4bfd4ab530d
--- /dev/null
+++ b/include/llvm/CodeGen/RuntimeLibcalls.h
@@ -0,0 +1,330 @@
+//===-- CodeGen/RuntimeLibcall.h - Runtime Library Calls --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the enum representing the list of runtime library calls
+// the backend may emit during code generation, and also some helper functions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_RUNTIMELIBCALLS_H
+#define LLVM_CODEGEN_RUNTIMELIBCALLS_H
+
+#include "llvm/CodeGen/ValueTypes.h"
+
+namespace llvm {
+namespace RTLIB {
+ /// RTLIB::Libcall enum - This enum defines all of the runtime library calls
+ /// the backend can emit. The various long double types cannot be merged,
+ /// because 80-bit library functions use "xf" and 128-bit use "tf".
+ ///
+ /// When adding PPCF128 functions here, note that their names generally need
+ /// to be overridden for Darwin with the xxx$LDBL128 form. See
+ /// PPCISelLowering.cpp.
+ ///
+ enum Libcall {
+ // Integer
+ SHL_I16,
+ SHL_I32,
+ SHL_I64,
+ SHL_I128,
+ SRL_I16,
+ SRL_I32,
+ SRL_I64,
+ SRL_I128,
+ SRA_I16,
+ SRA_I32,
+ SRA_I64,
+ SRA_I128,
+ MUL_I8,
+ MUL_I16,
+ MUL_I32,
+ MUL_I64,
+ MUL_I128,
+ MULO_I32,
+ MULO_I64,
+ MULO_I128,
+ SDIV_I8,
+ SDIV_I16,
+ SDIV_I32,
+ SDIV_I64,
+ SDIV_I128,
+ UDIV_I8,
+ UDIV_I16,
+ UDIV_I32,
+ UDIV_I64,
+ UDIV_I128,
+ SREM_I8,
+ SREM_I16,
+ SREM_I32,
+ SREM_I64,
+ SREM_I128,
+ UREM_I8,
+ UREM_I16,
+ UREM_I32,
+ UREM_I64,
+ UREM_I128,
+ SDIVREM_I8,
+ SDIVREM_I16,
+ SDIVREM_I32,
+ SDIVREM_I64,
+ SDIVREM_I128,
+ UDIVREM_I8,
+ UDIVREM_I16,
+ UDIVREM_I32,
+ UDIVREM_I64,
+ UDIVREM_I128,
+ NEG_I32,
+ NEG_I64,
+
+ // FLOATING POINT
+ ADD_F32,
+ ADD_F64,
+ ADD_F80,
+ ADD_PPCF128,
+ SUB_F32,
+ SUB_F64,
+ SUB_F80,
+ SUB_PPCF128,
+ MUL_F32,
+ MUL_F64,
+ MUL_F80,
+ MUL_PPCF128,
+ DIV_F32,
+ DIV_F64,
+ DIV_F80,
+ DIV_PPCF128,
+ REM_F32,
+ REM_F64,
+ REM_F80,
+ REM_PPCF128,
+ FMA_F32,
+ FMA_F64,
+ FMA_F80,
+ FMA_PPCF128,
+ POWI_F32,
+ POWI_F64,
+ POWI_F80,
+ POWI_PPCF128,
+ SQRT_F32,
+ SQRT_F64,
+ SQRT_F80,
+ SQRT_PPCF128,
+ LOG_F32,
+ LOG_F64,
+ LOG_F80,
+ LOG_PPCF128,
+ LOG2_F32,
+ LOG2_F64,
+ LOG2_F80,
+ LOG2_PPCF128,
+ LOG10_F32,
+ LOG10_F64,
+ LOG10_F80,
+ LOG10_PPCF128,
+ EXP_F32,
+ EXP_F64,
+ EXP_F80,
+ EXP_PPCF128,
+ EXP2_F32,
+ EXP2_F64,
+ EXP2_F80,
+ EXP2_PPCF128,
+ SIN_F32,
+ SIN_F64,
+ SIN_F80,
+ SIN_PPCF128,
+ COS_F32,
+ COS_F64,
+ COS_F80,
+ COS_PPCF128,
+ POW_F32,
+ POW_F64,
+ POW_F80,
+ POW_PPCF128,
+ CEIL_F32,
+ CEIL_F64,
+ CEIL_F80,
+ CEIL_PPCF128,
+ TRUNC_F32,
+ TRUNC_F64,
+ TRUNC_F80,
+ TRUNC_PPCF128,
+ RINT_F32,
+ RINT_F64,
+ RINT_F80,
+ RINT_PPCF128,
+ NEARBYINT_F32,
+ NEARBYINT_F64,
+ NEARBYINT_F80,
+ NEARBYINT_PPCF128,
+ FLOOR_F32,
+ FLOOR_F64,
+ FLOOR_F80,
+ FLOOR_PPCF128,
+ COPYSIGN_F32,
+ COPYSIGN_F64,
+ COPYSIGN_F80,
+ COPYSIGN_PPCF128,
+
+ // CONVERSION
+ FPEXT_F32_F64,
+ FPEXT_F16_F32,
+ FPROUND_F32_F16,
+ FPROUND_F64_F32,
+ FPROUND_F80_F32,
+ FPROUND_PPCF128_F32,
+ FPROUND_F80_F64,
+ FPROUND_PPCF128_F64,
+ FPTOSINT_F32_I8,
+ FPTOSINT_F32_I16,
+ FPTOSINT_F32_I32,
+ FPTOSINT_F32_I64,
+ FPTOSINT_F32_I128,
+ FPTOSINT_F64_I8,
+ FPTOSINT_F64_I16,
+ FPTOSINT_F64_I32,
+ FPTOSINT_F64_I64,
+ FPTOSINT_F64_I128,
+ FPTOSINT_F80_I32,
+ FPTOSINT_F80_I64,
+ FPTOSINT_F80_I128,
+ FPTOSINT_PPCF128_I32,
+ FPTOSINT_PPCF128_I64,
+ FPTOSINT_PPCF128_I128,
+ FPTOUINT_F32_I8,
+ FPTOUINT_F32_I16,
+ FPTOUINT_F32_I32,
+ FPTOUINT_F32_I64,
+ FPTOUINT_F32_I128,
+ FPTOUINT_F64_I8,
+ FPTOUINT_F64_I16,
+ FPTOUINT_F64_I32,
+ FPTOUINT_F64_I64,
+ FPTOUINT_F64_I128,
+ FPTOUINT_F80_I32,
+ FPTOUINT_F80_I64,
+ FPTOUINT_F80_I128,
+ FPTOUINT_PPCF128_I32,
+ FPTOUINT_PPCF128_I64,
+ FPTOUINT_PPCF128_I128,
+ SINTTOFP_I32_F32,
+ SINTTOFP_I32_F64,
+ SINTTOFP_I32_F80,
+ SINTTOFP_I32_PPCF128,
+ SINTTOFP_I64_F32,
+ SINTTOFP_I64_F64,
+ SINTTOFP_I64_F80,
+ SINTTOFP_I64_PPCF128,
+ SINTTOFP_I128_F32,
+ SINTTOFP_I128_F64,
+ SINTTOFP_I128_F80,
+ SINTTOFP_I128_PPCF128,
+ UINTTOFP_I32_F32,
+ UINTTOFP_I32_F64,
+ UINTTOFP_I32_F80,
+ UINTTOFP_I32_PPCF128,
+ UINTTOFP_I64_F32,
+ UINTTOFP_I64_F64,
+ UINTTOFP_I64_F80,
+ UINTTOFP_I64_PPCF128,
+ UINTTOFP_I128_F32,
+ UINTTOFP_I128_F64,
+ UINTTOFP_I128_F80,
+ UINTTOFP_I128_PPCF128,
+
+ // COMPARISON
+ OEQ_F32,
+ OEQ_F64,
+ UNE_F32,
+ UNE_F64,
+ OGE_F32,
+ OGE_F64,
+ OLT_F32,
+ OLT_F64,
+ OLE_F32,
+ OLE_F64,
+ OGT_F32,
+ OGT_F64,
+ UO_F32,
+ UO_F64,
+ O_F32,
+ O_F64,
+
+ // MEMORY
+ MEMCPY,
+ MEMSET,
+ MEMMOVE,
+
+ // EXCEPTION HANDLING
+ UNWIND_RESUME,
+
+ // Family ATOMICs
+ SYNC_VAL_COMPARE_AND_SWAP_1,
+ SYNC_VAL_COMPARE_AND_SWAP_2,
+ SYNC_VAL_COMPARE_AND_SWAP_4,
+ SYNC_VAL_COMPARE_AND_SWAP_8,
+ SYNC_LOCK_TEST_AND_SET_1,
+ SYNC_LOCK_TEST_AND_SET_2,
+ SYNC_LOCK_TEST_AND_SET_4,
+ SYNC_LOCK_TEST_AND_SET_8,
+ SYNC_FETCH_AND_ADD_1,
+ SYNC_FETCH_AND_ADD_2,
+ SYNC_FETCH_AND_ADD_4,
+ SYNC_FETCH_AND_ADD_8,
+ SYNC_FETCH_AND_SUB_1,
+ SYNC_FETCH_AND_SUB_2,
+ SYNC_FETCH_AND_SUB_4,
+ SYNC_FETCH_AND_SUB_8,
+ SYNC_FETCH_AND_AND_1,
+ SYNC_FETCH_AND_AND_2,
+ SYNC_FETCH_AND_AND_4,
+ SYNC_FETCH_AND_AND_8,
+ SYNC_FETCH_AND_OR_1,
+ SYNC_FETCH_AND_OR_2,
+ SYNC_FETCH_AND_OR_4,
+ SYNC_FETCH_AND_OR_8,
+ SYNC_FETCH_AND_XOR_1,
+ SYNC_FETCH_AND_XOR_2,
+ SYNC_FETCH_AND_XOR_4,
+ SYNC_FETCH_AND_XOR_8,
+ SYNC_FETCH_AND_NAND_1,
+ SYNC_FETCH_AND_NAND_2,
+ SYNC_FETCH_AND_NAND_4,
+ SYNC_FETCH_AND_NAND_8,
+
+ UNKNOWN_LIBCALL
+ };
+
+ /// getFPEXT - Return the FPEXT_*_* value for the given types, or
+ /// UNKNOWN_LIBCALL if there is none.
+ Libcall getFPEXT(EVT OpVT, EVT RetVT);
+
+ /// getFPROUND - Return the FPROUND_*_* value for the given types, or
+ /// UNKNOWN_LIBCALL if there is none.
+ Libcall getFPROUND(EVT OpVT, EVT RetVT);
+
+ /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
+ /// UNKNOWN_LIBCALL if there is none.
+ Libcall getFPTOSINT(EVT OpVT, EVT RetVT);
+
+ /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
+ /// UNKNOWN_LIBCALL if there is none.
+ Libcall getFPTOUINT(EVT OpVT, EVT RetVT);
+
+ /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
+ /// UNKNOWN_LIBCALL if there is none.
+ Libcall getSINTTOFP(EVT OpVT, EVT RetVT);
+
+ /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
+ /// UNKNOWN_LIBCALL if there is none.
+ Libcall getUINTTOFP(EVT OpVT, EVT RetVT);
+}
+}
+
+#endif
diff --git a/include/llvm/CodeGen/ScheduleDAG.h b/include/llvm/CodeGen/ScheduleDAG.h
new file mode 100644
index 00000000000..2567a657338
--- /dev/null
+++ b/include/llvm/CodeGen/ScheduleDAG.h
@@ -0,0 +1,728 @@
+//===------- llvm/CodeGen/ScheduleDAG.h - Common Base Class------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the ScheduleDAG class, which is used as the common
+// base class for instruction schedulers. This encapsulates the scheduling DAG,
+// which is shared between SelectionDAG and MachineInstr scheduling.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_SCHEDULEDAG_H
+#define LLVM_CODEGEN_SCHEDULEDAG_H
+
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/Target/TargetLowering.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/PointerIntPair.h"
+
+namespace llvm {
+ class AliasAnalysis;
+ class SUnit;
+ class MachineConstantPool;
+ class MachineFunction;
+ class MachineRegisterInfo;
+ class MachineInstr;
+ class TargetRegisterInfo;
+ class ScheduleDAG;
+ class SDNode;
+ class TargetInstrInfo;
+ class MCInstrDesc;
+ class TargetMachine;
+ class TargetRegisterClass;
+ template<class Graph> class GraphWriter;
+
+ /// SDep - Scheduling dependency. This represents one direction of an
+ /// edge in the scheduling DAG.
+ class SDep {
+ public:
+ /// Kind - These are the different kinds of scheduling dependencies.
+ enum Kind {
+ Data, ///< Regular data dependence (aka true-dependence).
+ Anti, ///< A register anti-dependedence (aka WAR).
+ Output, ///< A register output-dependence (aka WAW).
+ Order ///< Any other ordering dependency.
+ };
+
+ private:
+ /// Dep - A pointer to the depending/depended-on SUnit, and an enum
+ /// indicating the kind of the dependency.
+ PointerIntPair<SUnit *, 2, Kind> Dep;
+
+ /// Contents - A union discriminated by the dependence kind.
+ union {
+ /// Reg - For Data, Anti, and Output dependencies, the associated
+ /// register. For Data dependencies that don't currently have a register
+ /// assigned, this is set to zero.
+ unsigned Reg;
+
+ /// Order - Additional information about Order dependencies.
+ struct {
+ /// isNormalMemory - True if both sides of the dependence
+ /// access memory in non-volatile and fully modeled ways.
+ bool isNormalMemory : 1;
+
+ /// isMustAlias - True if both sides of the dependence are known to
+ /// access the same memory.
+ bool isMustAlias : 1;
+
+ /// isArtificial - True if this is an artificial dependency, meaning
+ /// it is not necessary for program correctness, and may be safely
+ /// deleted if necessary.
+ bool isArtificial : 1;
+ } Order;
+ } Contents;
+
+ /// Latency - The time associated with this edge. Often this is just
+ /// the value of the Latency field of the predecessor, however advanced
+ /// models may provide additional information about specific edges.
+ unsigned Latency;
+ /// Record MinLatency seperately from "expected" Latency.
+ unsigned MinLatency;
+
+ public:
+ /// SDep - Construct a null SDep. This is only for use by container
+ /// classes which require default constructors. SUnits may not
+ /// have null SDep edges.
+ SDep() : Dep(0, Data) {}
+
+ /// SDep - Construct an SDep with the specified values.
+ SDep(SUnit *S, Kind kind, unsigned latency = 1, unsigned Reg = 0,
+ bool isNormalMemory = false, bool isMustAlias = false,
+ bool isArtificial = false)
+ : Dep(S, kind), Contents(), Latency(latency), MinLatency(latency) {
+ switch (kind) {
+ case Anti:
+ case Output:
+ assert(Reg != 0 &&
+ "SDep::Anti and SDep::Output must use a non-zero Reg!");
+ // fall through
+ case Data:
+ assert(!isMustAlias && "isMustAlias only applies with SDep::Order!");
+ assert(!isArtificial && "isArtificial only applies with SDep::Order!");
+ Contents.Reg = Reg;
+ break;
+ case Order:
+ assert(Reg == 0 && "Reg given for non-register dependence!");
+ Contents.Order.isNormalMemory = isNormalMemory;
+ Contents.Order.isMustAlias = isMustAlias;
+ Contents.Order.isArtificial = isArtificial;
+ break;
+ }
+ }
+
+ /// Return true if the specified SDep is equivalent except for latency.
+ bool overlaps(const SDep &Other) const {
+ if (Dep != Other.Dep) return false;
+ switch (Dep.getInt()) {
+ case Data:
+ case Anti:
+ case Output:
+ return Contents.Reg == Other.Contents.Reg;
+ case Order:
+ return Contents.Order.isNormalMemory ==
+ Other.Contents.Order.isNormalMemory &&
+ Contents.Order.isMustAlias == Other.Contents.Order.isMustAlias &&
+ Contents.Order.isArtificial == Other.Contents.Order.isArtificial;
+ }
+ llvm_unreachable("Invalid dependency kind!");
+ }
+
+ bool operator==(const SDep &Other) const {
+ return overlaps(Other)
+ && Latency == Other.Latency && MinLatency == Other.MinLatency;
+ }
+
+ bool operator!=(const SDep &Other) const {
+ return !operator==(Other);
+ }
+
+ /// getLatency - Return the latency value for this edge, which roughly
+ /// means the minimum number of cycles that must elapse between the
+ /// predecessor and the successor, given that they have this edge
+ /// between them.
+ unsigned getLatency() const {
+ return Latency;
+ }
+
+ /// setLatency - Set the latency for this edge.
+ void setLatency(unsigned Lat) {
+ Latency = Lat;
+ }
+
+ /// getMinLatency - Return the minimum latency for this edge. Minimum
+ /// latency is used for scheduling groups, while normal (expected) latency
+ /// is for instruction cost and critical path.
+ unsigned getMinLatency() const {
+ return MinLatency;
+ }
+
+ /// setMinLatency - Set the minimum latency for this edge.
+ void setMinLatency(unsigned Lat) {
+ MinLatency = Lat;
+ }
+
+ //// getSUnit - Return the SUnit to which this edge points.
+ SUnit *getSUnit() const {
+ return Dep.getPointer();
+ }
+
+ //// setSUnit - Assign the SUnit to which this edge points.
+ void setSUnit(SUnit *SU) {
+ Dep.setPointer(SU);
+ }
+
+ /// getKind - Return an enum value representing the kind of the dependence.
+ Kind getKind() const {
+ return Dep.getInt();
+ }
+
+ /// isCtrl - Shorthand for getKind() != SDep::Data.
+ bool isCtrl() const {
+ return getKind() != Data;
+ }
+
+ /// isNormalMemory - Test if this is an Order dependence between two
+ /// memory accesses where both sides of the dependence access memory
+ /// in non-volatile and fully modeled ways.
+ bool isNormalMemory() const {
+ return getKind() == Order && Contents.Order.isNormalMemory;
+ }
+
+ /// isMustAlias - Test if this is an Order dependence that is marked
+ /// as "must alias", meaning that the SUnits at either end of the edge
+ /// have a memory dependence on a known memory location.
+ bool isMustAlias() const {
+ return getKind() == Order && Contents.Order.isMustAlias;
+ }
+
+ /// isArtificial - Test if this is an Order dependence that is marked
+ /// as "artificial", meaning it isn't necessary for correctness.
+ bool isArtificial() const {
+ return getKind() == Order && Contents.Order.isArtificial;
+ }
+
+ /// isAssignedRegDep - Test if this is a Data dependence that is
+ /// associated with a register.
+ bool isAssignedRegDep() const {
+ return getKind() == Data && Contents.Reg != 0;
+ }
+
+ /// getReg - Return the register associated with this edge. This is
+ /// only valid on Data, Anti, and Output edges. On Data edges, this
+ /// value may be zero, meaning there is no associated register.
+ unsigned getReg() const {
+ assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
+ "getReg called on non-register dependence edge!");
+ return Contents.Reg;
+ }
+
+ /// setReg - Assign the associated register for this edge. This is
+ /// only valid on Data, Anti, and Output edges. On Anti and Output
+ /// edges, this value must not be zero. On Data edges, the value may
+ /// be zero, which would mean that no specific register is associated
+ /// with this edge.
+ void setReg(unsigned Reg) {
+ assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
+ "setReg called on non-register dependence edge!");
+ assert((getKind() != Anti || Reg != 0) &&
+ "SDep::Anti edge cannot use the zero register!");
+ assert((getKind() != Output || Reg != 0) &&
+ "SDep::Output edge cannot use the zero register!");
+ Contents.Reg = Reg;
+ }
+ };
+
+ template <>
+ struct isPodLike<SDep> { static const bool value = true; };
+
+ /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
+ class SUnit {
+ private:
+ SDNode *Node; // Representative node.
+ MachineInstr *Instr; // Alternatively, a MachineInstr.
+ public:
+ SUnit *OrigNode; // If not this, the node from which
+ // this node was cloned.
+ // (SD scheduling only)
+
+ // Preds/Succs - The SUnits before/after us in the graph.
+ SmallVector<SDep, 4> Preds; // All sunit predecessors.
+ SmallVector<SDep, 4> Succs; // All sunit successors.
+
+ typedef SmallVector<SDep, 4>::iterator pred_iterator;
+ typedef SmallVector<SDep, 4>::iterator succ_iterator;
+ typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
+ typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
+
+ unsigned NodeNum; // Entry # of node in the node vector.
+ unsigned NodeQueueId; // Queue id of node.
+ unsigned NumPreds; // # of SDep::Data preds.
+ unsigned NumSuccs; // # of SDep::Data sucss.
+ unsigned NumPredsLeft; // # of preds not scheduled.
+ unsigned NumSuccsLeft; // # of succs not scheduled.
+ unsigned short NumRegDefsLeft; // # of reg defs with no scheduled use.
+ unsigned short Latency; // Node latency.
+ bool isVRegCycle : 1; // May use and def the same vreg.
+ bool isCall : 1; // Is a function call.
+ bool isCallOp : 1; // Is a function call operand.
+ bool isTwoAddress : 1; // Is a two-address instruction.
+ bool isCommutable : 1; // Is a commutable instruction.
+ bool hasPhysRegDefs : 1; // Has physreg defs that are being used.
+ bool hasPhysRegClobbers : 1; // Has any physreg defs, used or not.
+ bool isPending : 1; // True once pending.
+ bool isAvailable : 1; // True once available.
+ bool isScheduled : 1; // True once scheduled.
+ bool isScheduleHigh : 1; // True if preferable to schedule high.
+ bool isScheduleLow : 1; // True if preferable to schedule low.
+ bool isCloned : 1; // True if this node has been cloned.
+ Sched::Preference SchedulingPref; // Scheduling preference.
+
+ private:
+ bool isDepthCurrent : 1; // True if Depth is current.
+ bool isHeightCurrent : 1; // True if Height is current.
+ unsigned Depth; // Node depth.
+ unsigned Height; // Node height.
+ public:
+ unsigned TopReadyCycle; // Cycle relative to start when node is ready.
+ unsigned BotReadyCycle; // Cycle relative to end when node is ready.
+
+ const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
+ const TargetRegisterClass *CopySrcRC;
+
+ /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
+ /// an SDNode and any nodes flagged to it.
+ SUnit(SDNode *node, unsigned nodenum)
+ : Node(node), Instr(0), OrigNode(0), NodeNum(nodenum),
+ NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
+ NumSuccsLeft(0), NumRegDefsLeft(0), Latency(0),
+ isVRegCycle(false), isCall(false), isCallOp(false), isTwoAddress(false),
+ isCommutable(false), hasPhysRegDefs(false), hasPhysRegClobbers(false),
+ isPending(false), isAvailable(false), isScheduled(false),
+ isScheduleHigh(false), isScheduleLow(false), isCloned(false),
+ SchedulingPref(Sched::None),
+ isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
+ TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(NULL), CopySrcRC(NULL) {}
+
+ /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
+ /// a MachineInstr.
+ SUnit(MachineInstr *instr, unsigned nodenum)
+ : Node(0), Instr(instr), OrigNode(0), NodeNum(nodenum),
+ NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
+ NumSuccsLeft(0), NumRegDefsLeft(0), Latency(0),
+ isVRegCycle(false), isCall(false), isCallOp(false), isTwoAddress(false),
+ isCommutable(false), hasPhysRegDefs(false), hasPhysRegClobbers(false),
+ isPending(false), isAvailable(false), isScheduled(false),
+ isScheduleHigh(false), isScheduleLow(false), isCloned(false),
+ SchedulingPref(Sched::None),
+ isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
+ TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(NULL), CopySrcRC(NULL) {}
+
+ /// SUnit - Construct a placeholder SUnit.
+ SUnit()
+ : Node(0), Instr(0), OrigNode(0), NodeNum(~0u),
+ NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
+ NumSuccsLeft(0), NumRegDefsLeft(0), Latency(0),
+ isVRegCycle(false), isCall(false), isCallOp(false), isTwoAddress(false),
+ isCommutable(false), hasPhysRegDefs(false), hasPhysRegClobbers(false),
+ isPending(false), isAvailable(false), isScheduled(false),
+ isScheduleHigh(false), isScheduleLow(false), isCloned(false),
+ SchedulingPref(Sched::None),
+ isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
+ TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(NULL), CopySrcRC(NULL) {}
+
+ /// setNode - Assign the representative SDNode for this SUnit.
+ /// This may be used during pre-regalloc scheduling.
+ void setNode(SDNode *N) {
+ assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
+ Node = N;
+ }
+
+ /// getNode - Return the representative SDNode for this SUnit.
+ /// This may be used during pre-regalloc scheduling.
+ SDNode *getNode() const {
+ assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
+ return Node;
+ }
+
+ /// isInstr - Return true if this SUnit refers to a machine instruction as
+ /// opposed to an SDNode.
+ bool isInstr() const { return Instr; }
+
+ /// setInstr - Assign the instruction for the SUnit.
+ /// This may be used during post-regalloc scheduling.
+ void setInstr(MachineInstr *MI) {
+ assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
+ Instr = MI;
+ }
+
+ /// getInstr - Return the representative MachineInstr for this SUnit.
+ /// This may be used during post-regalloc scheduling.
+ MachineInstr *getInstr() const {
+ assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
+ return Instr;
+ }
+
+ /// addPred - This adds the specified edge as a pred of the current node if
+ /// not already. It also adds the current node as a successor of the
+ /// specified node.
+ bool addPred(const SDep &D);
+
+ /// removePred - This removes the specified edge as a pred of the current
+ /// node if it exists. It also removes the current node as a successor of
+ /// the specified node.
+ void removePred(const SDep &D);
+
+ /// getDepth - Return the depth of this node, which is the length of the
+ /// maximum path up to any node which has no predecessors.
+ unsigned getDepth() const {
+ if (!isDepthCurrent)
+ const_cast<SUnit *>(this)->ComputeDepth();
+ return Depth;
+ }
+
+ /// getHeight - Return the height of this node, which is the length of the
+ /// maximum path down to any node which has no successors.
+ unsigned getHeight() const {
+ if (!isHeightCurrent)
+ const_cast<SUnit *>(this)->ComputeHeight();
+ return Height;
+ }
+
+ /// setDepthToAtLeast - If NewDepth is greater than this node's
+ /// depth value, set it to be the new depth value. This also
+ /// recursively marks successor nodes dirty.
+ void setDepthToAtLeast(unsigned NewDepth);
+
+ /// setDepthToAtLeast - If NewDepth is greater than this node's
+ /// depth value, set it to be the new height value. This also
+ /// recursively marks predecessor nodes dirty.
+ void setHeightToAtLeast(unsigned NewHeight);
+
+ /// setDepthDirty - Set a flag in this node to indicate that its
+ /// stored Depth value will require recomputation the next time
+ /// getDepth() is called.
+ void setDepthDirty();
+
+ /// setHeightDirty - Set a flag in this node to indicate that its
+ /// stored Height value will require recomputation the next time
+ /// getHeight() is called.
+ void setHeightDirty();
+
+ /// isPred - Test if node N is a predecessor of this node.
+ bool isPred(SUnit *N) {
+ for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
+ if (Preds[i].getSUnit() == N)
+ return true;
+ return false;
+ }
+
+ /// isSucc - Test if node N is a successor of this node.
+ bool isSucc(SUnit *N) {
+ for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
+ if (Succs[i].getSUnit() == N)
+ return true;
+ return false;
+ }
+
+ bool isTopReady() const {
+ return NumPredsLeft == 0;
+ }
+ bool isBottomReady() const {
+ return NumSuccsLeft == 0;
+ }
+
+ void dump(const ScheduleDAG *G) const;
+ void dumpAll(const ScheduleDAG *G) const;
+ void print(raw_ostream &O, const ScheduleDAG *G) const;
+
+ private:
+ void ComputeDepth();
+ void ComputeHeight();
+ };
+
+ //===--------------------------------------------------------------------===//
+ /// SchedulingPriorityQueue - This interface is used to plug different
+ /// priorities computation algorithms into the list scheduler. It implements
+ /// the interface of a standard priority queue, where nodes are inserted in
+ /// arbitrary order and returned in priority order. The computation of the
+ /// priority and the representation of the queue are totally up to the
+ /// implementation to decide.
+ ///
+ class SchedulingPriorityQueue {
+ virtual void anchor();
+ unsigned CurCycle;
+ bool HasReadyFilter;
+ public:
+ SchedulingPriorityQueue(bool rf = false):
+ CurCycle(0), HasReadyFilter(rf) {}
+ virtual ~SchedulingPriorityQueue() {}
+
+ virtual bool isBottomUp() const = 0;
+
+ virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
+ virtual void addNode(const SUnit *SU) = 0;
+ virtual void updateNode(const SUnit *SU) = 0;
+ virtual void releaseState() = 0;
+
+ virtual bool empty() const = 0;
+
+ bool hasReadyFilter() const { return HasReadyFilter; }
+
+ virtual bool tracksRegPressure() const { return false; }
+
+ virtual bool isReady(SUnit *) const {
+ assert(!HasReadyFilter && "The ready filter must override isReady()");
+ return true;
+ }
+ virtual void push(SUnit *U) = 0;
+
+ void push_all(const std::vector<SUnit *> &Nodes) {
+ for (std::vector<SUnit *>::const_iterator I = Nodes.begin(),
+ E = Nodes.end(); I != E; ++I)
+ push(*I);
+ }
+
+ virtual SUnit *pop() = 0;
+
+ virtual void remove(SUnit *SU) = 0;
+
+ virtual void dump(ScheduleDAG *) const {}
+
+ /// scheduledNode - As each node is scheduled, this method is invoked. This
+ /// allows the priority function to adjust the priority of related
+ /// unscheduled nodes, for example.
+ ///
+ virtual void scheduledNode(SUnit *) {}
+
+ virtual void unscheduledNode(SUnit *) {}
+
+ void setCurCycle(unsigned Cycle) {
+ CurCycle = Cycle;
+ }
+
+ unsigned getCurCycle() const {
+ return CurCycle;
+ }
+ };
+
+ class ScheduleDAG {
+ public:
+ const TargetMachine &TM; // Target processor
+ const TargetInstrInfo *TII; // Target instruction information
+ const TargetRegisterInfo *TRI; // Target processor register info
+ MachineFunction &MF; // Machine function
+ MachineRegisterInfo &MRI; // Virtual/real register map
+ std::vector<SUnit> SUnits; // The scheduling units.
+ SUnit EntrySU; // Special node for the region entry.
+ SUnit ExitSU; // Special node for the region exit.
+
+#ifdef NDEBUG
+ static const bool StressSched = false;
+#else
+ bool StressSched;
+#endif
+
+ explicit ScheduleDAG(MachineFunction &mf);
+
+ virtual ~ScheduleDAG();
+
+ /// clearDAG - clear the DAG state (between regions).
+ void clearDAG();
+
+ /// getInstrDesc - Return the MCInstrDesc of this SUnit.
+ /// Return NULL for SDNodes without a machine opcode.
+ const MCInstrDesc *getInstrDesc(const SUnit *SU) const {
+ if (SU->isInstr()) return &SU->getInstr()->getDesc();
+ return getNodeDesc(SU->getNode());
+ }
+
+ /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
+ /// using 'dot'.
+ ///
+ void viewGraph(const Twine &Name, const Twine &Title);
+ void viewGraph();
+
+ virtual void dumpNode(const SUnit *SU) const = 0;
+
+ /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
+ /// of the ScheduleDAG.
+ virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
+
+ /// getDAGLabel - Return a label for the region of code covered by the DAG.
+ virtual std::string getDAGName() const = 0;
+
+ /// addCustomGraphFeatures - Add custom features for a visualization of
+ /// the ScheduleDAG.
+ virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {}
+
+#ifndef NDEBUG
+ /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
+ /// their state is consistent. Return the number of scheduled SUnits.
+ unsigned VerifyScheduledDAG(bool isBottomUp);
+#endif
+
+ protected:
+ /// ComputeLatency - Compute node latency.
+ ///
+ virtual void computeLatency(SUnit *SU) = 0;
+
+ /// ForceUnitLatencies - Return true if all scheduling edges should be given
+ /// a latency value of one. The default is to return false; schedulers may
+ /// override this as needed.
+ virtual bool forceUnitLatencies() const { return false; }
+
+ private:
+ // Return the MCInstrDesc of this SDNode or NULL.
+ const MCInstrDesc *getNodeDesc(const SDNode *Node) const;
+ };
+
+ class SUnitIterator : public std::iterator<std::forward_iterator_tag,
+ SUnit, ptrdiff_t> {
+ SUnit *Node;
+ unsigned Operand;
+
+ SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
+ public:
+ bool operator==(const SUnitIterator& x) const {
+ return Operand == x.Operand;
+ }
+ bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
+
+ const SUnitIterator &operator=(const SUnitIterator &I) {
+ assert(I.Node==Node && "Cannot assign iterators to two different nodes!");
+ Operand = I.Operand;
+ return *this;
+ }
+
+ pointer operator*() const {
+ return Node->Preds[Operand].getSUnit();
+ }
+ pointer operator->() const { return operator*(); }
+
+ SUnitIterator& operator++() { // Preincrement
+ ++Operand;
+ return *this;
+ }
+ SUnitIterator operator++(int) { // Postincrement
+ SUnitIterator tmp = *this; ++*this; return tmp;
+ }
+
+ static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
+ static SUnitIterator end (SUnit *N) {
+ return SUnitIterator(N, (unsigned)N->Preds.size());
+ }
+
+ unsigned getOperand() const { return Operand; }
+ const SUnit *getNode() const { return Node; }
+ /// isCtrlDep - Test if this is not an SDep::Data dependence.
+ bool isCtrlDep() const {
+ return getSDep().isCtrl();
+ }
+ bool isArtificialDep() const {
+ return getSDep().isArtificial();
+ }
+ const SDep &getSDep() const {
+ return Node->Preds[Operand];
+ }
+ };
+
+ template <> struct GraphTraits<SUnit*> {
+ typedef SUnit NodeType;
+ typedef SUnitIterator ChildIteratorType;
+ static inline NodeType *getEntryNode(SUnit *N) { return N; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return SUnitIterator::begin(N);
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return SUnitIterator::end(N);
+ }
+ };
+
+ template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
+ typedef std::vector<SUnit>::iterator nodes_iterator;
+ static nodes_iterator nodes_begin(ScheduleDAG *G) {
+ return G->SUnits.begin();
+ }
+ static nodes_iterator nodes_end(ScheduleDAG *G) {
+ return G->SUnits.end();
+ }
+ };
+
+ /// ScheduleDAGTopologicalSort is a class that computes a topological
+ /// ordering for SUnits and provides methods for dynamically updating
+ /// the ordering as new edges are added.
+ ///
+ /// This allows a very fast implementation of IsReachable, for example.
+ ///
+ class ScheduleDAGTopologicalSort {
+ /// SUnits - A reference to the ScheduleDAG's SUnits.
+ std::vector<SUnit> &SUnits;
+
+ /// Index2Node - Maps topological index to the node number.
+ std::vector<int> Index2Node;
+ /// Node2Index - Maps the node number to its topological index.
+ std::vector<int> Node2Index;
+ /// Visited - a set of nodes visited during a DFS traversal.
+ BitVector Visited;
+
+ /// DFS - make a DFS traversal and mark all nodes affected by the
+ /// edge insertion. These nodes will later get new topological indexes
+ /// by means of the Shift method.
+ void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
+
+ /// Shift - reassign topological indexes for the nodes in the DAG
+ /// to preserve the topological ordering.
+ void Shift(BitVector& Visited, int LowerBound, int UpperBound);
+
+ /// Allocate - assign the topological index to the node n.
+ void Allocate(int n, int index);
+
+ public:
+ explicit ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits);
+
+ /// InitDAGTopologicalSorting - create the initial topological
+ /// ordering from the DAG to be scheduled.
+ void InitDAGTopologicalSorting();
+
+ /// IsReachable - Checks if SU is reachable from TargetSU.
+ bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
+
+ /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU
+ /// will create a cycle.
+ bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
+
+ /// AddPred - Updates the topological ordering to accommodate an edge
+ /// to be added from SUnit X to SUnit Y.
+ void AddPred(SUnit *Y, SUnit *X);
+
+ /// RemovePred - Updates the topological ordering to accommodate an
+ /// an edge to be removed from the specified node N from the predecessors
+ /// of the current node M.
+ void RemovePred(SUnit *M, SUnit *N);
+
+ typedef std::vector<int>::iterator iterator;
+ typedef std::vector<int>::const_iterator const_iterator;
+ iterator begin() { return Index2Node.begin(); }
+ const_iterator begin() const { return Index2Node.begin(); }
+ iterator end() { return Index2Node.end(); }
+ const_iterator end() const { return Index2Node.end(); }
+
+ typedef std::vector<int>::reverse_iterator reverse_iterator;
+ typedef std::vector<int>::const_reverse_iterator const_reverse_iterator;
+ reverse_iterator rbegin() { return Index2Node.rbegin(); }
+ const_reverse_iterator rbegin() const { return Index2Node.rbegin(); }
+ reverse_iterator rend() { return Index2Node.rend(); }
+ const_reverse_iterator rend() const { return Index2Node.rend(); }
+ };
+}
+
+#endif
diff --git a/include/llvm/CodeGen/ScheduleDAGInstrs.h b/include/llvm/CodeGen/ScheduleDAGInstrs.h
new file mode 100644
index 00000000000..d13ee842578
--- /dev/null
+++ b/include/llvm/CodeGen/ScheduleDAGInstrs.h
@@ -0,0 +1,352 @@
+//==- ScheduleDAGInstrs.h - MachineInstr Scheduling --------------*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the ScheduleDAGInstrs class, which implements
+// scheduling for a MachineInstr-based dependency graph.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SCHEDULEDAGINSTRS_H
+#define SCHEDULEDAGINSTRS_H
+
+#include "llvm/CodeGen/MachineDominators.h"
+#include "llvm/CodeGen/MachineLoopInfo.h"
+#include "llvm/CodeGen/ScheduleDAG.h"
+#include "llvm/CodeGen/TargetSchedule.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/SparseSet.h"
+#include <map>
+
+namespace llvm {
+ class MachineLoopInfo;
+ class MachineDominatorTree;
+ class LiveIntervals;
+ class RegPressureTracker;
+
+ /// LoopDependencies - This class analyzes loop-oriented register
+ /// dependencies, which are used to guide scheduling decisions.
+ /// For example, loop induction variable increments should be
+ /// scheduled as soon as possible after the variable's last use.
+ ///
+ class LoopDependencies {
+ const MachineDominatorTree &MDT;
+
+ public:
+ typedef std::map<unsigned, std::pair<const MachineOperand *, unsigned> >
+ LoopDeps;
+ LoopDeps Deps;
+
+ LoopDependencies(const MachineDominatorTree &mdt) : MDT(mdt) {}
+
+ /// VisitLoop - Clear out any previous state and analyze the given loop.
+ ///
+ void VisitLoop(const MachineLoop *Loop) {
+ assert(Deps.empty() && "stale loop dependencies");
+
+ MachineBasicBlock *Header = Loop->getHeader();
+ SmallSet<unsigned, 8> LoopLiveIns;
+ for (MachineBasicBlock::livein_iterator LI = Header->livein_begin(),
+ LE = Header->livein_end(); LI != LE; ++LI)
+ LoopLiveIns.insert(*LI);
+
+ const MachineDomTreeNode *Node = MDT.getNode(Header);
+ const MachineBasicBlock *MBB = Node->getBlock();
+ assert(Loop->contains(MBB) &&
+ "Loop does not contain header!");
+ VisitRegion(Node, MBB, Loop, LoopLiveIns);
+ }
+
+ private:
+ void VisitRegion(const MachineDomTreeNode *Node,
+ const MachineBasicBlock *MBB,
+ const MachineLoop *Loop,
+ const SmallSet<unsigned, 8> &LoopLiveIns) {
+ unsigned Count = 0;
+ for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
+ I != E; ++I) {
+ const MachineInstr *MI = I;
+ if (MI->isDebugValue())
+ continue;
+ for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
+ const MachineOperand &MO = MI->getOperand(i);
+ if (!MO.isReg() || !MO.isUse())
+ continue;
+ unsigned MOReg = MO.getReg();
+ if (LoopLiveIns.count(MOReg))
+ Deps.insert(std::make_pair(MOReg, std::make_pair(&MO, Count)));
+ }
+ ++Count; // Not every iteration due to dbg_value above.
+ }
+
+ const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
+ for (std::vector<MachineDomTreeNode*>::const_iterator I =
+ Children.begin(), E = Children.end(); I != E; ++I) {
+ const MachineDomTreeNode *ChildNode = *I;
+ MachineBasicBlock *ChildBlock = ChildNode->getBlock();
+ if (Loop->contains(ChildBlock))
+ VisitRegion(ChildNode, ChildBlock, Loop, LoopLiveIns);
+ }
+ }
+ };
+
+ /// An individual mapping from virtual register number to SUnit.
+ struct VReg2SUnit {
+ unsigned VirtReg;
+ SUnit *SU;
+
+ VReg2SUnit(unsigned reg, SUnit *su): VirtReg(reg), SU(su) {}
+
+ unsigned getSparseSetIndex() const {
+ return TargetRegisterInfo::virtReg2Index(VirtReg);
+ }
+ };
+
+ /// Record a physical register access.
+ /// For non data-dependent uses, OpIdx == -1.
+ struct PhysRegSUOper {
+ SUnit *SU;
+ int OpIdx;
+
+ PhysRegSUOper(SUnit *su, int op): SU(su), OpIdx(op) {}
+ };
+
+ /// Combine a SparseSet with a 1x1 vector to track physical registers.
+ /// The SparseSet allows iterating over the (few) live registers for quickly
+ /// comparing against a regmask or clearing the set.
+ ///
+ /// Storage for the map is allocated once for the pass. The map can be
+ /// cleared between scheduling regions without freeing unused entries.
+ class Reg2SUnitsMap {
+ SparseSet<unsigned> PhysRegSet;
+ std::vector<std::vector<PhysRegSUOper> > SUnits;
+ public:
+ typedef SparseSet<unsigned>::const_iterator const_iterator;
+
+ // Allow iteration over register numbers (keys) in the map. If needed, we
+ // can provide an iterator over SUnits (values) as well.
+ const_iterator reg_begin() const { return PhysRegSet.begin(); }
+ const_iterator reg_end() const { return PhysRegSet.end(); }
+
+ /// Initialize the map with the number of registers.
+ /// If the map is already large enough, no allocation occurs.
+ /// For simplicity we expect the map to be empty().
+ void setRegLimit(unsigned Limit);
+
+ /// Returns true if the map is empty.
+ bool empty() const { return PhysRegSet.empty(); }
+
+ /// Clear the map without deallocating storage.
+ void clear();
+
+ bool contains(unsigned Reg) const { return PhysRegSet.count(Reg); }
+
+ /// If this register is mapped, return its existing SUnits vector.
+ /// Otherwise map the register and return an empty SUnits vector.
+ std::vector<PhysRegSUOper> &operator[](unsigned Reg) {
+ bool New = PhysRegSet.insert(Reg).second;
+ assert((!New || SUnits[Reg].empty()) && "stale SUnits vector");
+ (void)New;
+ return SUnits[Reg];
+ }
+
+ /// Erase an existing element without freeing memory.
+ void erase(unsigned Reg) {
+ PhysRegSet.erase(Reg);
+ SUnits[Reg].clear();
+ }
+ };
+
+ /// Use SparseSet as a SparseMap by relying on the fact that it never
+ /// compares ValueT's, only unsigned keys. This allows the set to be cleared
+ /// between scheduling regions in constant time as long as ValueT does not
+ /// require a destructor.
+ typedef SparseSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2SUnitMap;
+
+ /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of
+ /// MachineInstrs.
+ class ScheduleDAGInstrs : public ScheduleDAG {
+ protected:
+ const MachineLoopInfo &MLI;
+ const MachineDominatorTree &MDT;
+ const MachineFrameInfo *MFI;
+ const InstrItineraryData *InstrItins;
+
+ /// Live Intervals provides reaching defs in preRA scheduling.
+ LiveIntervals *LIS;
+
+ /// TargetSchedModel provides an interface to the machine model.
+ TargetSchedModel SchedModel;
+
+ /// isPostRA flag indicates vregs cannot be present.
+ bool IsPostRA;
+
+ /// UnitLatencies (misnamed) flag avoids computing def-use latencies, using
+ /// the def-side latency only.
+ bool UnitLatencies;
+
+ /// The standard DAG builder does not normally include terminators as DAG
+ /// nodes because it does not create the necessary dependencies to prevent
+ /// reordering. A specialized scheduler can overide
+ /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate
+ /// it has taken responsibility for scheduling the terminator correctly.
+ bool CanHandleTerminators;
+
+ /// State specific to the current scheduling region.
+ /// ------------------------------------------------
+
+ /// The block in which to insert instructions
+ MachineBasicBlock *BB;
+
+ /// The beginning of the range to be scheduled.
+ MachineBasicBlock::iterator RegionBegin;
+
+ /// The end of the range to be scheduled.
+ MachineBasicBlock::iterator RegionEnd;
+
+ /// The index in BB of RegionEnd.
+ unsigned EndIndex;
+
+ /// After calling BuildSchedGraph, each machine instruction in the current
+ /// scheduling region is mapped to an SUnit.
+ DenseMap<MachineInstr*, SUnit*> MISUnitMap;
+
+ /// State internal to DAG building.
+ /// -------------------------------
+
+ /// Defs, Uses - Remember where defs and uses of each register are as we
+ /// iterate upward through the instructions. This is allocated here instead
+ /// of inside BuildSchedGraph to avoid the need for it to be initialized and
+ /// destructed for each block.
+ Reg2SUnitsMap Defs;
+ Reg2SUnitsMap Uses;
+
+ /// Track the last instructon in this region defining each virtual register.
+ VReg2SUnitMap VRegDefs;
+
+ /// PendingLoads - Remember where unknown loads are after the most recent
+ /// unknown store, as we iterate. As with Defs and Uses, this is here
+ /// to minimize construction/destruction.
+ std::vector<SUnit *> PendingLoads;
+
+ /// LoopRegs - Track which registers are used for loop-carried dependencies.
+ ///
+ LoopDependencies LoopRegs;
+
+ /// DbgValues - Remember instruction that precedes DBG_VALUE.
+ /// These are generated by buildSchedGraph but persist so they can be
+ /// referenced when emitting the final schedule.
+ typedef std::vector<std::pair<MachineInstr *, MachineInstr *> >
+ DbgValueVector;
+ DbgValueVector DbgValues;
+ MachineInstr *FirstDbgValue;
+
+ public:
+ explicit ScheduleDAGInstrs(MachineFunction &mf,
+ const MachineLoopInfo &mli,
+ const MachineDominatorTree &mdt,
+ bool IsPostRAFlag,
+ LiveIntervals *LIS = 0);
+
+ virtual ~ScheduleDAGInstrs() {}
+
+ /// begin - Return an iterator to the top of the current scheduling region.
+ MachineBasicBlock::iterator begin() const { return RegionBegin; }
+
+ /// end - Return an iterator to the bottom of the current scheduling region.
+ MachineBasicBlock::iterator end() const { return RegionEnd; }
+
+ /// newSUnit - Creates a new SUnit and return a ptr to it.
+ SUnit *newSUnit(MachineInstr *MI);
+
+ /// getSUnit - Return an existing SUnit for this MI, or NULL.
+ SUnit *getSUnit(MachineInstr *MI) const;
+
+ /// startBlock - Prepare to perform scheduling in the given block.
+ virtual void startBlock(MachineBasicBlock *BB);
+
+ /// finishBlock - Clean up after scheduling in the given block.
+ virtual void finishBlock();
+
+ /// Initialize the scheduler state for the next scheduling region.
+ virtual void enterRegion(MachineBasicBlock *bb,
+ MachineBasicBlock::iterator begin,
+ MachineBasicBlock::iterator end,
+ unsigned endcount);
+
+ /// Notify that the scheduler has finished scheduling the current region.
+ virtual void exitRegion();
+
+ /// buildSchedGraph - Build SUnits from the MachineBasicBlock that we are
+ /// input.
+ void buildSchedGraph(AliasAnalysis *AA, RegPressureTracker *RPTracker = 0);
+
+ /// addSchedBarrierDeps - Add dependencies from instructions in the current
+ /// list of instructions being scheduled to scheduling barrier. We want to
+ /// make sure instructions which define registers that are either used by
+ /// the terminator or are live-out are properly scheduled. This is
+ /// especially important when the definition latency of the return value(s)
+ /// are too high to be hidden by the branch or when the liveout registers
+ /// used by instructions in the fallthrough block.
+ void addSchedBarrierDeps();
+
+ /// computeLatency - Compute node latency.
+ ///
+ virtual void computeLatency(SUnit *SU);
+
+ /// schedule - Order nodes according to selected style, filling
+ /// in the Sequence member.
+ ///
+ /// Typically, a scheduling algorithm will implement schedule() without
+ /// overriding enterRegion() or exitRegion().
+ virtual void schedule() = 0;
+
+ /// finalizeSchedule - Allow targets to perform final scheduling actions at
+ /// the level of the whole MachineFunction. By default does nothing.
+ virtual void finalizeSchedule() {}
+
+ virtual void dumpNode(const SUnit *SU) const;
+
+ /// Return a label for a DAG node that points to an instruction.
+ virtual std::string getGraphNodeLabel(const SUnit *SU) const;
+
+ /// Return a label for the region of code covered by the DAG.
+ virtual std::string getDAGName() const;
+
+ protected:
+ void initSUnits();
+ void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);
+ void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
+ void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
+ void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
+ };
+
+ /// newSUnit - Creates a new SUnit and return a ptr to it.
+ inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) {
+#ifndef NDEBUG
+ const SUnit *Addr = SUnits.empty() ? 0 : &SUnits[0];
+#endif
+ SUnits.push_back(SUnit(MI, (unsigned)SUnits.size()));
+ assert((Addr == 0 || Addr == &SUnits[0]) &&
+ "SUnits std::vector reallocated on the fly!");
+ SUnits.back().OrigNode = &SUnits.back();
+ return &SUnits.back();
+ }
+
+ /// getSUnit - Return an existing SUnit for this MI, or NULL.
+ inline SUnit *ScheduleDAGInstrs::getSUnit(MachineInstr *MI) const {
+ DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI);
+ if (I == MISUnitMap.end())
+ return 0;
+ return I->second;
+ }
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/ScheduleHazardRecognizer.h b/include/llvm/CodeGen/ScheduleHazardRecognizer.h
new file mode 100644
index 00000000000..9dfa3446ef5
--- /dev/null
+++ b/include/llvm/CodeGen/ScheduleHazardRecognizer.h
@@ -0,0 +1,95 @@
+//=- llvm/CodeGen/ScheduleHazardRecognizer.h - Scheduling Support -*- C++ -*-=//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the ScheduleHazardRecognizer class, which implements
+// hazard-avoidance heuristics for scheduling.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_SCHEDULEHAZARDRECOGNIZER_H
+#define LLVM_CODEGEN_SCHEDULEHAZARDRECOGNIZER_H
+
+namespace llvm {
+
+class SUnit;
+
+/// HazardRecognizer - This determines whether or not an instruction can be
+/// issued this cycle, and whether or not a noop needs to be inserted to handle
+/// the hazard.
+class ScheduleHazardRecognizer {
+protected:
+ /// MaxLookAhead - Indicate the number of cycles in the scoreboard
+ /// state. Important to restore the state after backtracking. Additionally,
+ /// MaxLookAhead=0 identifies a fake recognizer, allowing the client to
+ /// bypass virtual calls. Currently the PostRA scheduler ignores it.
+ unsigned MaxLookAhead;
+
+public:
+ ScheduleHazardRecognizer(): MaxLookAhead(0) {}
+ virtual ~ScheduleHazardRecognizer();
+
+ enum HazardType {
+ NoHazard, // This instruction can be emitted at this cycle.
+ Hazard, // This instruction can't be emitted at this cycle.
+ NoopHazard // This instruction can't be emitted, and needs noops.
+ };
+
+ unsigned getMaxLookAhead() const { return MaxLookAhead; }
+
+ bool isEnabled() const { return MaxLookAhead != 0; }
+
+ /// atIssueLimit - Return true if no more instructions may be issued in this
+ /// cycle.
+ ///
+ /// FIXME: remove this once MachineScheduler is the only client.
+ virtual bool atIssueLimit() const { return false; }
+
+ /// getHazardType - Return the hazard type of emitting this node. There are
+ /// three possible results. Either:
+ /// * NoHazard: it is legal to issue this instruction on this cycle.
+ /// * Hazard: issuing this instruction would stall the machine. If some
+ /// other instruction is available, issue it first.
+ /// * NoopHazard: issuing this instruction would break the program. If
+ /// some other instruction can be issued, do so, otherwise issue a noop.
+ virtual HazardType getHazardType(SUnit *m, int Stalls = 0) {
+ return NoHazard;
+ }
+
+ /// Reset - This callback is invoked when a new block of
+ /// instructions is about to be schedule. The hazard state should be
+ /// set to an initialized state.
+ virtual void Reset() {}
+
+ /// EmitInstruction - This callback is invoked when an instruction is
+ /// emitted, to advance the hazard state.
+ virtual void EmitInstruction(SUnit *) {}
+
+ /// AdvanceCycle - This callback is invoked whenever the next top-down
+ /// instruction to be scheduled cannot issue in the current cycle, either
+ /// because of latency or resource conflicts. This should increment the
+ /// internal state of the hazard recognizer so that previously "Hazard"
+ /// instructions will now not be hazards.
+ virtual void AdvanceCycle() {}
+
+ /// RecedeCycle - This callback is invoked whenever the next bottom-up
+ /// instruction to be scheduled cannot issue in the current cycle, either
+ /// because of latency or resource conflicts.
+ virtual void RecedeCycle() {}
+
+ /// EmitNoop - This callback is invoked when a noop was added to the
+ /// instruction stream.
+ virtual void EmitNoop() {
+ // Default implementation: count it as a cycle.
+ AdvanceCycle();
+ }
+};
+
+}
+
+#endif
diff --git a/include/llvm/CodeGen/SchedulerRegistry.h b/include/llvm/CodeGen/SchedulerRegistry.h
new file mode 100644
index 00000000000..a582b0c40c8
--- /dev/null
+++ b/include/llvm/CodeGen/SchedulerRegistry.h
@@ -0,0 +1,107 @@
+//===-- llvm/CodeGen/SchedulerRegistry.h ------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the implementation for instruction scheduler function
+// pass registry (RegisterScheduler).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGENSCHEDULERREGISTRY_H
+#define LLVM_CODEGENSCHEDULERREGISTRY_H
+
+#include "llvm/CodeGen/MachinePassRegistry.h"
+#include "llvm/Target/TargetMachine.h"
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+///
+/// RegisterScheduler class - Track the registration of instruction schedulers.
+///
+//===----------------------------------------------------------------------===//
+
+class SelectionDAGISel;
+class ScheduleDAGSDNodes;
+class SelectionDAG;
+class MachineBasicBlock;
+
+class RegisterScheduler : public MachinePassRegistryNode {
+public:
+ typedef ScheduleDAGSDNodes *(*FunctionPassCtor)(SelectionDAGISel*,
+ CodeGenOpt::Level);
+
+ static MachinePassRegistry Registry;
+
+ RegisterScheduler(const char *N, const char *D, FunctionPassCtor C)
+ : MachinePassRegistryNode(N, D, (MachinePassCtor)C)
+ { Registry.Add(this); }
+ ~RegisterScheduler() { Registry.Remove(this); }
+
+
+ // Accessors.
+ //
+ RegisterScheduler *getNext() const {
+ return (RegisterScheduler *)MachinePassRegistryNode::getNext();
+ }
+ static RegisterScheduler *getList() {
+ return (RegisterScheduler *)Registry.getList();
+ }
+ static FunctionPassCtor getDefault() {
+ return (FunctionPassCtor)Registry.getDefault();
+ }
+ static void setDefault(FunctionPassCtor C) {
+ Registry.setDefault((MachinePassCtor)C);
+ }
+ static void setListener(MachinePassRegistryListener *L) {
+ Registry.setListener(L);
+ }
+};
+
+/// createBURRListDAGScheduler - This creates a bottom up register usage
+/// reduction list scheduler.
+ScheduleDAGSDNodes *createBURRListDAGScheduler(SelectionDAGISel *IS,
+ CodeGenOpt::Level OptLevel);
+
+/// createBURRListDAGScheduler - This creates a bottom up list scheduler that
+/// schedules nodes in source code order when possible.
+ScheduleDAGSDNodes *createSourceListDAGScheduler(SelectionDAGISel *IS,
+ CodeGenOpt::Level OptLevel);
+
+/// createHybridListDAGScheduler - This creates a bottom up register pressure
+/// aware list scheduler that make use of latency information to avoid stalls
+/// for long latency instructions in low register pressure mode. In high
+/// register pressure mode it schedules to reduce register pressure.
+ScheduleDAGSDNodes *createHybridListDAGScheduler(SelectionDAGISel *IS,
+ CodeGenOpt::Level);
+
+/// createILPListDAGScheduler - This creates a bottom up register pressure
+/// aware list scheduler that tries to increase instruction level parallelism
+/// in low register pressure mode. In high register pressure mode it schedules
+/// to reduce register pressure.
+ScheduleDAGSDNodes *createILPListDAGScheduler(SelectionDAGISel *IS,
+ CodeGenOpt::Level);
+
+/// createFastDAGScheduler - This creates a "fast" scheduler.
+///
+ScheduleDAGSDNodes *createFastDAGScheduler(SelectionDAGISel *IS,
+ CodeGenOpt::Level OptLevel);
+
+/// createVLIWDAGScheduler - Scheduler for VLIW targets. This creates top down
+/// DFA driven list scheduler with clustering heuristic to control
+/// register pressure.
+ScheduleDAGSDNodes *createVLIWDAGScheduler(SelectionDAGISel *IS,
+ CodeGenOpt::Level OptLevel);
+/// createDefaultScheduler - This creates an instruction scheduler appropriate
+/// for the target.
+ScheduleDAGSDNodes *createDefaultScheduler(SelectionDAGISel *IS,
+ CodeGenOpt::Level OptLevel);
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/ScoreboardHazardRecognizer.h b/include/llvm/CodeGen/ScoreboardHazardRecognizer.h
new file mode 100644
index 00000000000..060e89a3fdc
--- /dev/null
+++ b/include/llvm/CodeGen/ScoreboardHazardRecognizer.h
@@ -0,0 +1,127 @@
+//=- llvm/CodeGen/ScoreboardHazardRecognizer.h - Schedule Support -*- C++ -*-=//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the ScoreboardHazardRecognizer class, which
+// encapsulates hazard-avoidance heuristics for scheduling, based on the
+// scheduling itineraries specified for the target.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_SCOREBOARDHAZARDRECOGNIZER_H
+#define LLVM_CODEGEN_SCOREBOARDHAZARDRECOGNIZER_H
+
+#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
+#include "llvm/Support/DataTypes.h"
+
+#include <cassert>
+#include <cstring>
+
+namespace llvm {
+
+class InstrItineraryData;
+class ScheduleDAG;
+class SUnit;
+
+class ScoreboardHazardRecognizer : public ScheduleHazardRecognizer {
+ // Scoreboard to track function unit usage. Scoreboard[0] is a
+ // mask of the FUs in use in the cycle currently being
+ // schedule. Scoreboard[1] is a mask for the next cycle. The
+ // Scoreboard is used as a circular buffer with the current cycle
+ // indicated by Head.
+ //
+ // Scoreboard always counts cycles in forward execution order. If used by a
+ // bottom-up scheduler, then the scoreboard cycles are the inverse of the
+ // scheduler's cycles.
+ class Scoreboard {
+ unsigned *Data;
+
+ // The maximum number of cycles monitored by the Scoreboard. This
+ // value is determined based on the target itineraries to ensure
+ // that all hazards can be tracked.
+ size_t Depth;
+ // Indices into the Scoreboard that represent the current cycle.
+ size_t Head;
+ public:
+ Scoreboard():Data(NULL), Depth(0), Head(0) { }
+ ~Scoreboard() {
+ delete[] Data;
+ }
+
+ size_t getDepth() const { return Depth; }
+ unsigned& operator[](size_t idx) const {
+ // Depth is expected to be a power-of-2.
+ assert(Depth && !(Depth & (Depth - 1)) &&
+ "Scoreboard was not initialized properly!");
+
+ return Data[(Head + idx) & (Depth-1)];
+ }
+
+ void reset(size_t d = 1) {
+ if (Data == NULL) {
+ Depth = d;
+ Data = new unsigned[Depth];
+ }
+
+ memset(Data, 0, Depth * sizeof(Data[0]));
+ Head = 0;
+ }
+
+ void advance() {
+ Head = (Head + 1) & (Depth-1);
+ }
+
+ void recede() {
+ Head = (Head - 1) & (Depth-1);
+ }
+
+ // Print the scoreboard.
+ void dump() const;
+ };
+
+#ifndef NDEBUG
+ // Support for tracing ScoreboardHazardRecognizer as a component within
+ // another module. Follows the current thread-unsafe model of tracing.
+ static const char *DebugType;
+#endif
+
+ // Itinerary data for the target.
+ const InstrItineraryData *ItinData;
+
+ const ScheduleDAG *DAG;
+
+ /// IssueWidth - Max issue per cycle. 0=Unknown.
+ unsigned IssueWidth;
+
+ /// IssueCount - Count instructions issued in this cycle.
+ unsigned IssueCount;
+
+ Scoreboard ReservedScoreboard;
+ Scoreboard RequiredScoreboard;
+
+public:
+ ScoreboardHazardRecognizer(const InstrItineraryData *ItinData,
+ const ScheduleDAG *DAG,
+ const char *ParentDebugType = "");
+
+ /// atIssueLimit - Return true if no more instructions may be issued in this
+ /// cycle.
+ virtual bool atIssueLimit() const;
+
+ // Stalls provides an cycle offset at which SU will be scheduled. It will be
+ // negative for bottom-up scheduling.
+ virtual HazardType getHazardType(SUnit *SU, int Stalls);
+ virtual void Reset();
+ virtual void EmitInstruction(SUnit *SU);
+ virtual void AdvanceCycle();
+ virtual void RecedeCycle();
+};
+
+}
+
+#endif //!LLVM_CODEGEN_SCOREBOARDHAZARDRECOGNIZER_H
diff --git a/include/llvm/CodeGen/SelectionDAG.h b/include/llvm/CodeGen/SelectionDAG.h
new file mode 100644
index 00000000000..619ee699430
--- /dev/null
+++ b/include/llvm/CodeGen/SelectionDAG.h
@@ -0,0 +1,1099 @@
+//===-- llvm/CodeGen/SelectionDAG.h - InstSelection DAG ---------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the SelectionDAG class, and transitively defines the
+// SDNode class and subclasses.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_SELECTIONDAG_H
+#define LLVM_CODEGEN_SELECTIONDAG_H
+
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/CodeGen/SelectionDAGNodes.h"
+#include "llvm/Support/RecyclingAllocator.h"
+#include "llvm/Target/TargetMachine.h"
+#include <cassert>
+#include <vector>
+#include <map>
+#include <string>
+
+namespace llvm {
+
+class AliasAnalysis;
+class MachineConstantPoolValue;
+class MachineFunction;
+class MDNode;
+class SDNodeOrdering;
+class SDDbgValue;
+class TargetLowering;
+class TargetSelectionDAGInfo;
+
+template<> struct ilist_traits<SDNode> : public ilist_default_traits<SDNode> {
+private:
+ mutable ilist_half_node<SDNode> Sentinel;
+public:
+ SDNode *createSentinel() const {
+ return static_cast<SDNode*>(&Sentinel);
+ }
+ static void destroySentinel(SDNode *) {}
+
+ SDNode *provideInitialHead() const { return createSentinel(); }
+ SDNode *ensureHead(SDNode*) const { return createSentinel(); }
+ static void noteHead(SDNode*, SDNode*) {}
+
+ static void deleteNode(SDNode *) {
+ llvm_unreachable("ilist_traits<SDNode> shouldn't see a deleteNode call!");
+ }
+private:
+ static void createNode(const SDNode &);
+};
+
+/// SDDbgInfo - Keeps track of dbg_value information through SDISel. We do
+/// not build SDNodes for these so as not to perturb the generated code;
+/// instead the info is kept off to the side in this structure. Each SDNode may
+/// have one or more associated dbg_value entries. This information is kept in
+/// DbgValMap.
+/// Byval parameters are handled separately because they don't use alloca's,
+/// which busts the normal mechanism. There is good reason for handling all
+/// parameters separately: they may not have code generated for them, they
+/// should always go at the beginning of the function regardless of other code
+/// motion, and debug info for them is potentially useful even if the parameter
+/// is unused. Right now only byval parameters are handled separately.
+class SDDbgInfo {
+ SmallVector<SDDbgValue*, 32> DbgValues;
+ SmallVector<SDDbgValue*, 32> ByvalParmDbgValues;
+ DenseMap<const SDNode*, SmallVector<SDDbgValue*, 2> > DbgValMap;
+
+ void operator=(const SDDbgInfo&) LLVM_DELETED_FUNCTION;
+ SDDbgInfo(const SDDbgInfo&) LLVM_DELETED_FUNCTION;
+public:
+ SDDbgInfo() {}
+
+ void add(SDDbgValue *V, const SDNode *Node, bool isParameter) {
+ if (isParameter) {
+ ByvalParmDbgValues.push_back(V);
+ } else DbgValues.push_back(V);
+ if (Node)
+ DbgValMap[Node].push_back(V);
+ }
+
+ void clear() {
+ DbgValMap.clear();
+ DbgValues.clear();
+ ByvalParmDbgValues.clear();
+ }
+
+ bool empty() const {
+ return DbgValues.empty() && ByvalParmDbgValues.empty();
+ }
+
+ ArrayRef<SDDbgValue*> getSDDbgValues(const SDNode *Node) {
+ DenseMap<const SDNode*, SmallVector<SDDbgValue*, 2> >::iterator I =
+ DbgValMap.find(Node);
+ if (I != DbgValMap.end())
+ return I->second;
+ return ArrayRef<SDDbgValue*>();
+ }
+
+ typedef SmallVector<SDDbgValue*,32>::iterator DbgIterator;
+ DbgIterator DbgBegin() { return DbgValues.begin(); }
+ DbgIterator DbgEnd() { return DbgValues.end(); }
+ DbgIterator ByvalParmDbgBegin() { return ByvalParmDbgValues.begin(); }
+ DbgIterator ByvalParmDbgEnd() { return ByvalParmDbgValues.end(); }
+};
+
+enum CombineLevel {
+ BeforeLegalizeTypes,
+ AfterLegalizeTypes,
+ AfterLegalizeVectorOps,
+ AfterLegalizeDAG
+};
+
+class SelectionDAG;
+void checkForCycles(const SDNode *N);
+void checkForCycles(const SelectionDAG *DAG);
+
+/// SelectionDAG class - This is used to represent a portion of an LLVM function
+/// in a low-level Data Dependence DAG representation suitable for instruction
+/// selection. This DAG is constructed as the first step of instruction
+/// selection in order to allow implementation of machine specific optimizations
+/// and code simplifications.
+///
+/// The representation used by the SelectionDAG is a target-independent
+/// representation, which has some similarities to the GCC RTL representation,
+/// but is significantly more simple, powerful, and is a graph form instead of a
+/// linear form.
+///
+class SelectionDAG {
+ const TargetMachine &TM;
+ const TargetLowering &TLI;
+ const TargetSelectionDAGInfo &TSI;
+ MachineFunction *MF;
+ LLVMContext *Context;
+ CodeGenOpt::Level OptLevel;
+
+ /// EntryNode - The starting token.
+ SDNode EntryNode;
+
+ /// Root - The root of the entire DAG.
+ SDValue Root;
+
+ /// AllNodes - A linked list of nodes in the current DAG.
+ ilist<SDNode> AllNodes;
+
+ /// NodeAllocatorType - The AllocatorType for allocating SDNodes. We use
+ /// pool allocation with recycling.
+ typedef RecyclingAllocator<BumpPtrAllocator, SDNode, sizeof(LargestSDNode),
+ AlignOf<MostAlignedSDNode>::Alignment>
+ NodeAllocatorType;
+
+ /// NodeAllocator - Pool allocation for nodes.
+ NodeAllocatorType NodeAllocator;
+
+ /// CSEMap - This structure is used to memoize nodes, automatically performing
+ /// CSE with existing nodes when a duplicate is requested.
+ FoldingSet<SDNode> CSEMap;
+
+ /// OperandAllocator - Pool allocation for machine-opcode SDNode operands.
+ BumpPtrAllocator OperandAllocator;
+
+ /// Allocator - Pool allocation for misc. objects that are created once per
+ /// SelectionDAG.
+ BumpPtrAllocator Allocator;
+
+ /// SDNodeOrdering - The ordering of the SDNodes. It roughly corresponds to
+ /// the ordering of the original LLVM instructions.
+ SDNodeOrdering *Ordering;
+
+ /// DbgInfo - Tracks dbg_value information through SDISel.
+ SDDbgInfo *DbgInfo;
+
+public:
+ /// DAGUpdateListener - Clients of various APIs that cause global effects on
+ /// the DAG can optionally implement this interface. This allows the clients
+ /// to handle the various sorts of updates that happen.
+ ///
+ /// A DAGUpdateListener automatically registers itself with DAG when it is
+ /// constructed, and removes itself when destroyed in RAII fashion.
+ struct DAGUpdateListener {
+ DAGUpdateListener *const Next;
+ SelectionDAG &DAG;
+
+ explicit DAGUpdateListener(SelectionDAG &D)
+ : Next(D.UpdateListeners), DAG(D) {
+ DAG.UpdateListeners = this;
+ }
+
+ virtual ~DAGUpdateListener() {
+ assert(DAG.UpdateListeners == this &&
+ "DAGUpdateListeners must be destroyed in LIFO order");
+ DAG.UpdateListeners = Next;
+ }
+
+ /// NodeDeleted - The node N that was deleted and, if E is not null, an
+ /// equivalent node E that replaced it.
+ virtual void NodeDeleted(SDNode *N, SDNode *E);
+
+ /// NodeUpdated - The node N that was updated.
+ virtual void NodeUpdated(SDNode *N);
+ };
+
+private:
+ /// DAGUpdateListener is a friend so it can manipulate the listener stack.
+ friend struct DAGUpdateListener;
+
+ /// UpdateListeners - Linked list of registered DAGUpdateListener instances.
+ /// This stack is maintained by DAGUpdateListener RAII.
+ DAGUpdateListener *UpdateListeners;
+
+ /// setGraphColorHelper - Implementation of setSubgraphColor.
+ /// Return whether we had to truncate the search.
+ ///
+ bool setSubgraphColorHelper(SDNode *N, const char *Color,
+ DenseSet<SDNode *> &visited,
+ int level, bool &printed);
+
+ void operator=(const SelectionDAG&) LLVM_DELETED_FUNCTION;
+ SelectionDAG(const SelectionDAG&) LLVM_DELETED_FUNCTION;
+
+public:
+ explicit SelectionDAG(const TargetMachine &TM, llvm::CodeGenOpt::Level);
+ ~SelectionDAG();
+
+ /// init - Prepare this SelectionDAG to process code in the given
+ /// MachineFunction.
+ ///
+ void init(MachineFunction &mf);
+
+ /// clear - Clear state and free memory necessary to make this
+ /// SelectionDAG ready to process a new block.
+ ///
+ void clear();
+
+ MachineFunction &getMachineFunction() const { return *MF; }
+ const TargetMachine &getTarget() const { return TM; }
+ const TargetLowering &getTargetLoweringInfo() const { return TLI; }
+ const TargetSelectionDAGInfo &getSelectionDAGInfo() const { return TSI; }
+ LLVMContext *getContext() const {return Context; }
+
+ /// viewGraph - Pop up a GraphViz/gv window with the DAG rendered using 'dot'.
+ ///
+ void viewGraph(const std::string &Title);
+ void viewGraph();
+
+#ifndef NDEBUG
+ std::map<const SDNode *, std::string> NodeGraphAttrs;
+#endif
+
+ /// clearGraphAttrs - Clear all previously defined node graph attributes.
+ /// Intended to be used from a debugging tool (eg. gdb).
+ void clearGraphAttrs();
+
+ /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
+ ///
+ void setGraphAttrs(const SDNode *N, const char *Attrs);
+
+ /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
+ /// Used from getNodeAttributes.
+ const std::string getGraphAttrs(const SDNode *N) const;
+
+ /// setGraphColor - Convenience for setting node color attribute.
+ ///
+ void setGraphColor(const SDNode *N, const char *Color);
+
+ /// setGraphColor - Convenience for setting subgraph color attribute.
+ ///
+ void setSubgraphColor(SDNode *N, const char *Color);
+
+ typedef ilist<SDNode>::const_iterator allnodes_const_iterator;
+ allnodes_const_iterator allnodes_begin() const { return AllNodes.begin(); }
+ allnodes_const_iterator allnodes_end() const { return AllNodes.end(); }
+ typedef ilist<SDNode>::iterator allnodes_iterator;
+ allnodes_iterator allnodes_begin() { return AllNodes.begin(); }
+ allnodes_iterator allnodes_end() { return AllNodes.end(); }
+ ilist<SDNode>::size_type allnodes_size() const {
+ return AllNodes.size();
+ }
+
+ /// getRoot - Return the root tag of the SelectionDAG.
+ ///
+ const SDValue &getRoot() const { return Root; }
+
+ /// getEntryNode - Return the token chain corresponding to the entry of the
+ /// function.
+ SDValue getEntryNode() const {
+ return SDValue(const_cast<SDNode *>(&EntryNode), 0);
+ }
+
+ /// setRoot - Set the current root tag of the SelectionDAG.
+ ///
+ const SDValue &setRoot(SDValue N) {
+ assert((!N.getNode() || N.getValueType() == MVT::Other) &&
+ "DAG root value is not a chain!");
+ if (N.getNode())
+ checkForCycles(N.getNode());
+ Root = N;
+ if (N.getNode())
+ checkForCycles(this);
+ return Root;
+ }
+
+ /// Combine - This iterates over the nodes in the SelectionDAG, folding
+ /// certain types of nodes together, or eliminating superfluous nodes. The
+ /// Level argument controls whether Combine is allowed to produce nodes and
+ /// types that are illegal on the target.
+ void Combine(CombineLevel Level, AliasAnalysis &AA,
+ CodeGenOpt::Level OptLevel);
+
+ /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
+ /// only uses types natively supported by the target. Returns "true" if it
+ /// made any changes.
+ ///
+ /// Note that this is an involved process that may invalidate pointers into
+ /// the graph.
+ bool LegalizeTypes();
+
+ /// Legalize - This transforms the SelectionDAG into a SelectionDAG that is
+ /// compatible with the target instruction selector, as indicated by the
+ /// TargetLowering object.
+ ///
+ /// Note that this is an involved process that may invalidate pointers into
+ /// the graph.
+ void Legalize();
+
+ /// LegalizeVectors - This transforms the SelectionDAG into a SelectionDAG
+ /// that only uses vector math operations supported by the target. This is
+ /// necessary as a separate step from Legalize because unrolling a vector
+ /// operation can introduce illegal types, which requires running
+ /// LegalizeTypes again.
+ ///
+ /// This returns true if it made any changes; in that case, LegalizeTypes
+ /// is called again before Legalize.
+ ///
+ /// Note that this is an involved process that may invalidate pointers into
+ /// the graph.
+ bool LegalizeVectors();
+
+ /// RemoveDeadNodes - This method deletes all unreachable nodes in the
+ /// SelectionDAG.
+ void RemoveDeadNodes();
+
+ /// DeleteNode - Remove the specified node from the system. This node must
+ /// have no referrers.
+ void DeleteNode(SDNode *N);
+
+ /// getVTList - Return an SDVTList that represents the list of values
+ /// specified.
+ SDVTList getVTList(EVT VT);
+ SDVTList getVTList(EVT VT1, EVT VT2);
+ SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3);
+ SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4);
+ SDVTList getVTList(const EVT *VTs, unsigned NumVTs);
+
+ //===--------------------------------------------------------------------===//
+ // Node creation methods.
+ //
+ SDValue getConstant(uint64_t Val, EVT VT, bool isTarget = false);
+ SDValue getConstant(const APInt &Val, EVT VT, bool isTarget = false);
+ SDValue getConstant(const ConstantInt &Val, EVT VT, bool isTarget = false);
+ SDValue getIntPtrConstant(uint64_t Val, bool isTarget = false);
+ SDValue getTargetConstant(uint64_t Val, EVT VT) {
+ return getConstant(Val, VT, true);
+ }
+ SDValue getTargetConstant(const APInt &Val, EVT VT) {
+ return getConstant(Val, VT, true);
+ }
+ SDValue getTargetConstant(const ConstantInt &Val, EVT VT) {
+ return getConstant(Val, VT, true);
+ }
+ // The forms below that take a double should only be used for simple
+ // constants that can be exactly represented in VT. No checks are made.
+ SDValue getConstantFP(double Val, EVT VT, bool isTarget = false);
+ SDValue getConstantFP(const APFloat& Val, EVT VT, bool isTarget = false);
+ SDValue getConstantFP(const ConstantFP &CF, EVT VT, bool isTarget = false);
+ SDValue getTargetConstantFP(double Val, EVT VT) {
+ return getConstantFP(Val, VT, true);
+ }
+ SDValue getTargetConstantFP(const APFloat& Val, EVT VT) {
+ return getConstantFP(Val, VT, true);
+ }
+ SDValue getTargetConstantFP(const ConstantFP &Val, EVT VT) {
+ return getConstantFP(Val, VT, true);
+ }
+ SDValue getGlobalAddress(const GlobalValue *GV, DebugLoc DL, EVT VT,
+ int64_t offset = 0, bool isTargetGA = false,
+ unsigned char TargetFlags = 0);
+ SDValue getTargetGlobalAddress(const GlobalValue *GV, DebugLoc DL, EVT VT,
+ int64_t offset = 0,
+ unsigned char TargetFlags = 0) {
+ return getGlobalAddress(GV, DL, VT, offset, true, TargetFlags);
+ }
+ SDValue getFrameIndex(int FI, EVT VT, bool isTarget = false);
+ SDValue getTargetFrameIndex(int FI, EVT VT) {
+ return getFrameIndex(FI, VT, true);
+ }
+ SDValue getJumpTable(int JTI, EVT VT, bool isTarget = false,
+ unsigned char TargetFlags = 0);
+ SDValue getTargetJumpTable(int JTI, EVT VT, unsigned char TargetFlags = 0) {
+ return getJumpTable(JTI, VT, true, TargetFlags);
+ }
+ SDValue getConstantPool(const Constant *C, EVT VT,
+ unsigned Align = 0, int Offs = 0, bool isT=false,
+ unsigned char TargetFlags = 0);
+ SDValue getTargetConstantPool(const Constant *C, EVT VT,
+ unsigned Align = 0, int Offset = 0,
+ unsigned char TargetFlags = 0) {
+ return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
+ }
+ SDValue getConstantPool(MachineConstantPoolValue *C, EVT VT,
+ unsigned Align = 0, int Offs = 0, bool isT=false,
+ unsigned char TargetFlags = 0);
+ SDValue getTargetConstantPool(MachineConstantPoolValue *C,
+ EVT VT, unsigned Align = 0,
+ int Offset = 0, unsigned char TargetFlags=0) {
+ return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
+ }
+ SDValue getTargetIndex(int Index, EVT VT, int64_t Offset = 0,
+ unsigned char TargetFlags = 0);
+ // When generating a branch to a BB, we don't in general know enough
+ // to provide debug info for the BB at that time, so keep this one around.
+ SDValue getBasicBlock(MachineBasicBlock *MBB);
+ SDValue getBasicBlock(MachineBasicBlock *MBB, DebugLoc dl);
+ SDValue getExternalSymbol(const char *Sym, EVT VT);
+ SDValue getExternalSymbol(const char *Sym, DebugLoc dl, EVT VT);
+ SDValue getTargetExternalSymbol(const char *Sym, EVT VT,
+ unsigned char TargetFlags = 0);
+ SDValue getValueType(EVT);
+ SDValue getRegister(unsigned Reg, EVT VT);
+ SDValue getRegisterMask(const uint32_t *RegMask);
+ SDValue getEHLabel(DebugLoc dl, SDValue Root, MCSymbol *Label);
+ SDValue getBlockAddress(const BlockAddress *BA, EVT VT,
+ int64_t Offset = 0, bool isTarget = false,
+ unsigned char TargetFlags = 0);
+ SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT,
+ int64_t Offset = 0,
+ unsigned char TargetFlags = 0) {
+ return getBlockAddress(BA, VT, Offset, true, TargetFlags);
+ }
+
+ SDValue getCopyToReg(SDValue Chain, DebugLoc dl, unsigned Reg, SDValue N) {
+ return getNode(ISD::CopyToReg, dl, MVT::Other, Chain,
+ getRegister(Reg, N.getValueType()), N);
+ }
+
+ // This version of the getCopyToReg method takes an extra operand, which
+ // indicates that there is potentially an incoming glue value (if Glue is not
+ // null) and that there should be a glue result.
+ SDValue getCopyToReg(SDValue Chain, DebugLoc dl, unsigned Reg, SDValue N,
+ SDValue Glue) {
+ SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
+ SDValue Ops[] = { Chain, getRegister(Reg, N.getValueType()), N, Glue };
+ return getNode(ISD::CopyToReg, dl, VTs, Ops, Glue.getNode() ? 4 : 3);
+ }
+
+ // Similar to last getCopyToReg() except parameter Reg is a SDValue
+ SDValue getCopyToReg(SDValue Chain, DebugLoc dl, SDValue Reg, SDValue N,
+ SDValue Glue) {
+ SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
+ SDValue Ops[] = { Chain, Reg, N, Glue };
+ return getNode(ISD::CopyToReg, dl, VTs, Ops, Glue.getNode() ? 4 : 3);
+ }
+
+ SDValue getCopyFromReg(SDValue Chain, DebugLoc dl, unsigned Reg, EVT VT) {
+ SDVTList VTs = getVTList(VT, MVT::Other);
+ SDValue Ops[] = { Chain, getRegister(Reg, VT) };
+ return getNode(ISD::CopyFromReg, dl, VTs, Ops, 2);
+ }
+
+ // This version of the getCopyFromReg method takes an extra operand, which
+ // indicates that there is potentially an incoming glue value (if Glue is not
+ // null) and that there should be a glue result.
+ SDValue getCopyFromReg(SDValue Chain, DebugLoc dl, unsigned Reg, EVT VT,
+ SDValue Glue) {
+ SDVTList VTs = getVTList(VT, MVT::Other, MVT::Glue);
+ SDValue Ops[] = { Chain, getRegister(Reg, VT), Glue };
+ return getNode(ISD::CopyFromReg, dl, VTs, Ops, Glue.getNode() ? 3 : 2);
+ }
+
+ SDValue getCondCode(ISD::CondCode Cond);
+
+ /// Returns the ConvertRndSat Note: Avoid using this node because it may
+ /// disappear in the future and most targets don't support it.
+ SDValue getConvertRndSat(EVT VT, DebugLoc dl, SDValue Val, SDValue DTy,
+ SDValue STy,
+ SDValue Rnd, SDValue Sat, ISD::CvtCode Code);
+
+ /// getVectorShuffle - Return an ISD::VECTOR_SHUFFLE node. The number of
+ /// elements in VT, which must be a vector type, must match the number of
+ /// mask elements NumElts. A integer mask element equal to -1 is treated as
+ /// undefined.
+ SDValue getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1, SDValue N2,
+ const int *MaskElts);
+
+ /// getAnyExtOrTrunc - Convert Op, which must be of integer type, to the
+ /// integer type VT, by either any-extending or truncating it.
+ SDValue getAnyExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT);
+
+ /// getSExtOrTrunc - Convert Op, which must be of integer type, to the
+ /// integer type VT, by either sign-extending or truncating it.
+ SDValue getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT);
+
+ /// getZExtOrTrunc - Convert Op, which must be of integer type, to the
+ /// integer type VT, by either zero-extending or truncating it.
+ SDValue getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT);
+
+ /// getZeroExtendInReg - Return the expression required to zero extend the Op
+ /// value assuming it was the smaller SrcTy value.
+ SDValue getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT SrcTy);
+
+ /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
+ SDValue getNOT(DebugLoc DL, SDValue Val, EVT VT);
+
+ /// getCALLSEQ_START - Return a new CALLSEQ_START node, which always must have
+ /// a glue result (to ensure it's not CSE'd). CALLSEQ_START does not have a
+ /// useful DebugLoc.
+ SDValue getCALLSEQ_START(SDValue Chain, SDValue Op) {
+ SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
+ SDValue Ops[] = { Chain, Op };
+ return getNode(ISD::CALLSEQ_START, DebugLoc(), VTs, Ops, 2);
+ }
+
+ /// getCALLSEQ_END - Return a new CALLSEQ_END node, which always must have a
+ /// glue result (to ensure it's not CSE'd). CALLSEQ_END does not have
+ /// a useful DebugLoc.
+ SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2,
+ SDValue InGlue) {
+ SDVTList NodeTys = getVTList(MVT::Other, MVT::Glue);
+ SmallVector<SDValue, 4> Ops;
+ Ops.push_back(Chain);
+ Ops.push_back(Op1);
+ Ops.push_back(Op2);
+ Ops.push_back(InGlue);
+ return getNode(ISD::CALLSEQ_END, DebugLoc(), NodeTys, &Ops[0],
+ (unsigned)Ops.size() - (InGlue.getNode() == 0 ? 1 : 0));
+ }
+
+ /// getUNDEF - Return an UNDEF node. UNDEF does not have a useful DebugLoc.
+ SDValue getUNDEF(EVT VT) {
+ return getNode(ISD::UNDEF, DebugLoc(), VT);
+ }
+
+ /// getGLOBAL_OFFSET_TABLE - Return a GLOBAL_OFFSET_TABLE node. This does
+ /// not have a useful DebugLoc.
+ SDValue getGLOBAL_OFFSET_TABLE(EVT VT) {
+ return getNode(ISD::GLOBAL_OFFSET_TABLE, DebugLoc(), VT);
+ }
+
+ /// getNode - Gets or creates the specified node.
+ ///
+ SDValue getNode(unsigned Opcode, DebugLoc DL, EVT VT);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, EVT VT, SDValue N);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, EVT VT, SDValue N1, SDValue N2);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, EVT VT,
+ SDValue N1, SDValue N2, SDValue N3);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, EVT VT,
+ SDValue N1, SDValue N2, SDValue N3, SDValue N4);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, EVT VT,
+ SDValue N1, SDValue N2, SDValue N3, SDValue N4,
+ SDValue N5);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, EVT VT,
+ const SDUse *Ops, unsigned NumOps);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, EVT VT,
+ const SDValue *Ops, unsigned NumOps);
+ SDValue getNode(unsigned Opcode, DebugLoc DL,
+ const std::vector<EVT> &ResultTys,
+ const SDValue *Ops, unsigned NumOps);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, const EVT *VTs, unsigned NumVTs,
+ const SDValue *Ops, unsigned NumOps);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
+ const SDValue *Ops, unsigned NumOps);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, SDVTList VTs);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, SDVTList VTs, SDValue N);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
+ SDValue N1, SDValue N2);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
+ SDValue N1, SDValue N2, SDValue N3);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
+ SDValue N1, SDValue N2, SDValue N3, SDValue N4);
+ SDValue getNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
+ SDValue N1, SDValue N2, SDValue N3, SDValue N4,
+ SDValue N5);
+
+ /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
+ /// the incoming stack arguments to be loaded from the stack. This is
+ /// used in tail call lowering to protect stack arguments from being
+ /// clobbered.
+ SDValue getStackArgumentTokenFactor(SDValue Chain);
+
+ SDValue getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst, SDValue Src,
+ SDValue Size, unsigned Align, bool isVol, bool AlwaysInline,
+ MachinePointerInfo DstPtrInfo,
+ MachinePointerInfo SrcPtrInfo);
+
+ SDValue getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst, SDValue Src,
+ SDValue Size, unsigned Align, bool isVol,
+ MachinePointerInfo DstPtrInfo,
+ MachinePointerInfo SrcPtrInfo);
+
+ SDValue getMemset(SDValue Chain, DebugLoc dl, SDValue Dst, SDValue Src,
+ SDValue Size, unsigned Align, bool isVol,
+ MachinePointerInfo DstPtrInfo);
+
+ /// getSetCC - Helper function to make it easier to build SetCC's if you just
+ /// have an ISD::CondCode instead of an SDValue.
+ ///
+ SDValue getSetCC(DebugLoc DL, EVT VT, SDValue LHS, SDValue RHS,
+ ISD::CondCode Cond) {
+ assert(LHS.getValueType().isVector() == RHS.getValueType().isVector() &&
+ "Cannot compare scalars to vectors");
+ assert(LHS.getValueType().isVector() == VT.isVector() &&
+ "Cannot compare scalars to vectors");
+ return getNode(ISD::SETCC, DL, VT, LHS, RHS, getCondCode(Cond));
+ }
+
+ /// getSelectCC - Helper function to make it easier to build SelectCC's if you
+ /// just have an ISD::CondCode instead of an SDValue.
+ ///
+ SDValue getSelectCC(DebugLoc DL, SDValue LHS, SDValue RHS,
+ SDValue True, SDValue False, ISD::CondCode Cond) {
+ return getNode(ISD::SELECT_CC, DL, True.getValueType(),
+ LHS, RHS, True, False, getCondCode(Cond));
+ }
+
+ /// getVAArg - VAArg produces a result and token chain, and takes a pointer
+ /// and a source value as input.
+ SDValue getVAArg(EVT VT, DebugLoc dl, SDValue Chain, SDValue Ptr,
+ SDValue SV, unsigned Align);
+
+ /// getAtomic - Gets a node for an atomic op, produces result and chain and
+ /// takes 3 operands
+ SDValue getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT, SDValue Chain,
+ SDValue Ptr, SDValue Cmp, SDValue Swp,
+ MachinePointerInfo PtrInfo, unsigned Alignment,
+ AtomicOrdering Ordering,
+ SynchronizationScope SynchScope);
+ SDValue getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT, SDValue Chain,
+ SDValue Ptr, SDValue Cmp, SDValue Swp,
+ MachineMemOperand *MMO,
+ AtomicOrdering Ordering,
+ SynchronizationScope SynchScope);
+
+ /// getAtomic - Gets a node for an atomic op, produces result (if relevant)
+ /// and chain and takes 2 operands.
+ SDValue getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT, SDValue Chain,
+ SDValue Ptr, SDValue Val, const Value* PtrVal,
+ unsigned Alignment, AtomicOrdering Ordering,
+ SynchronizationScope SynchScope);
+ SDValue getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT, SDValue Chain,
+ SDValue Ptr, SDValue Val, MachineMemOperand *MMO,
+ AtomicOrdering Ordering,
+ SynchronizationScope SynchScope);
+
+ /// getAtomic - Gets a node for an atomic op, produces result and chain and
+ /// takes 1 operand.
+ SDValue getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT, EVT VT,
+ SDValue Chain, SDValue Ptr, const Value* PtrVal,
+ unsigned Alignment,
+ AtomicOrdering Ordering,
+ SynchronizationScope SynchScope);
+ SDValue getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT, EVT VT,
+ SDValue Chain, SDValue Ptr, MachineMemOperand *MMO,
+ AtomicOrdering Ordering,
+ SynchronizationScope SynchScope);
+
+ /// getMemIntrinsicNode - Creates a MemIntrinsicNode that may produce a
+ /// result and takes a list of operands. Opcode may be INTRINSIC_VOID,
+ /// INTRINSIC_W_CHAIN, or a target-specific opcode with a value not
+ /// less than FIRST_TARGET_MEMORY_OPCODE.
+ SDValue getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
+ const EVT *VTs, unsigned NumVTs,
+ const SDValue *Ops, unsigned NumOps,
+ EVT MemVT, MachinePointerInfo PtrInfo,
+ unsigned Align = 0, bool Vol = false,
+ bool ReadMem = true, bool WriteMem = true);
+
+ SDValue getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
+ const SDValue *Ops, unsigned NumOps,
+ EVT MemVT, MachinePointerInfo PtrInfo,
+ unsigned Align = 0, bool Vol = false,
+ bool ReadMem = true, bool WriteMem = true);
+
+ SDValue getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
+ const SDValue *Ops, unsigned NumOps,
+ EVT MemVT, MachineMemOperand *MMO);
+
+ /// getMergeValues - Create a MERGE_VALUES node from the given operands.
+ SDValue getMergeValues(const SDValue *Ops, unsigned NumOps, DebugLoc dl);
+
+ /// getLoad - Loads are not normal binary operators: their result type is not
+ /// determined by their operands, and they produce a value AND a token chain.
+ ///
+ SDValue getLoad(EVT VT, DebugLoc dl, SDValue Chain, SDValue Ptr,
+ MachinePointerInfo PtrInfo, bool isVolatile,
+ bool isNonTemporal, bool isInvariant, unsigned Alignment,
+ const MDNode *TBAAInfo = 0, const MDNode *Ranges = 0);
+ SDValue getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
+ SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo,
+ EVT MemVT, bool isVolatile,
+ bool isNonTemporal, unsigned Alignment,
+ const MDNode *TBAAInfo = 0);
+ SDValue getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
+ SDValue Offset, ISD::MemIndexedMode AM);
+ SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
+ EVT VT, DebugLoc dl,
+ SDValue Chain, SDValue Ptr, SDValue Offset,
+ MachinePointerInfo PtrInfo, EVT MemVT,
+ bool isVolatile, bool isNonTemporal, bool isInvariant,
+ unsigned Alignment, const MDNode *TBAAInfo = 0,
+ const MDNode *Ranges = 0);
+ SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
+ EVT VT, DebugLoc dl,
+ SDValue Chain, SDValue Ptr, SDValue Offset,
+ EVT MemVT, MachineMemOperand *MMO);
+
+ /// getStore - Helper function to build ISD::STORE nodes.
+ ///
+ SDValue getStore(SDValue Chain, DebugLoc dl, SDValue Val, SDValue Ptr,
+ MachinePointerInfo PtrInfo, bool isVolatile,
+ bool isNonTemporal, unsigned Alignment,
+ const MDNode *TBAAInfo = 0);
+ SDValue getStore(SDValue Chain, DebugLoc dl, SDValue Val, SDValue Ptr,
+ MachineMemOperand *MMO);
+ SDValue getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val, SDValue Ptr,
+ MachinePointerInfo PtrInfo, EVT TVT,
+ bool isNonTemporal, bool isVolatile,
+ unsigned Alignment,
+ const MDNode *TBAAInfo = 0);
+ SDValue getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val, SDValue Ptr,
+ EVT TVT, MachineMemOperand *MMO);
+ SDValue getIndexedStore(SDValue OrigStoe, DebugLoc dl, SDValue Base,
+ SDValue Offset, ISD::MemIndexedMode AM);
+
+ /// getSrcValue - Construct a node to track a Value* through the backend.
+ SDValue getSrcValue(const Value *v);
+
+ /// getMDNode - Return an MDNodeSDNode which holds an MDNode.
+ SDValue getMDNode(const MDNode *MD);
+
+ /// getShiftAmountOperand - Return the specified value casted to
+ /// the target's desired shift amount type.
+ SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op);
+
+ /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
+ /// specified operands. If the resultant node already exists in the DAG,
+ /// this does not modify the specified node, instead it returns the node that
+ /// already exists. If the resultant node does not exist in the DAG, the
+ /// input node is returned. As a degenerate case, if you specify the same
+ /// input operands as the node already has, the input node is returned.
+ SDNode *UpdateNodeOperands(SDNode *N, SDValue Op);
+ SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2);
+ SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
+ SDValue Op3);
+ SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
+ SDValue Op3, SDValue Op4);
+ SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
+ SDValue Op3, SDValue Op4, SDValue Op5);
+ SDNode *UpdateNodeOperands(SDNode *N,
+ const SDValue *Ops, unsigned NumOps);
+
+ /// SelectNodeTo - These are used for target selectors to *mutate* the
+ /// specified node to have the specified return type, Target opcode, and
+ /// operands. Note that target opcodes are stored as
+ /// ~TargetOpcode in the node opcode field. The resultant node is returned.
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT, SDValue Op1);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
+ SDValue Op1, SDValue Op2);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
+ SDValue Op1, SDValue Op2, SDValue Op3);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
+ const SDValue *Ops, unsigned NumOps);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1, EVT VT2);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
+ EVT VT2, const SDValue *Ops, unsigned NumOps);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
+ EVT VT2, EVT VT3, const SDValue *Ops, unsigned NumOps);
+ SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
+ EVT VT2, EVT VT3, EVT VT4, const SDValue *Ops,
+ unsigned NumOps);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
+ EVT VT2, SDValue Op1);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
+ EVT VT2, SDValue Op1, SDValue Op2);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
+ EVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
+ EVT VT2, EVT VT3, SDValue Op1, SDValue Op2, SDValue Op3);
+ SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, SDVTList VTs,
+ const SDValue *Ops, unsigned NumOps);
+
+ /// MorphNodeTo - This *mutates* the specified node to have the specified
+ /// return type, opcode, and operands.
+ SDNode *MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs,
+ const SDValue *Ops, unsigned NumOps);
+
+ /// getMachineNode - These are used for target selectors to create a new node
+ /// with specified return type(s), MachineInstr opcode, and operands.
+ ///
+ /// Note that getMachineNode returns the resultant node. If there is already
+ /// a node of the specified opcode and operands, it returns that node instead
+ /// of the current one.
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
+ SDValue Op1);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
+ SDValue Op1, SDValue Op2);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
+ SDValue Op1, SDValue Op2, SDValue Op3);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
+ const SDValue *Ops, unsigned NumOps);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2,
+ SDValue Op1);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
+ EVT VT2, SDValue Op1, SDValue Op2);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
+ EVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2,
+ const SDValue *Ops, unsigned NumOps);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2,
+ EVT VT3, SDValue Op1, SDValue Op2);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2,
+ EVT VT3, SDValue Op1, SDValue Op2, SDValue Op3);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2,
+ EVT VT3, const SDValue *Ops, unsigned NumOps);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2,
+ EVT VT3, EVT VT4, const SDValue *Ops, unsigned NumOps);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl,
+ const std::vector<EVT> &ResultTys, const SDValue *Ops,
+ unsigned NumOps);
+ MachineSDNode *getMachineNode(unsigned Opcode, DebugLoc dl, SDVTList VTs,
+ const SDValue *Ops, unsigned NumOps);
+
+ /// getTargetExtractSubreg - A convenience function for creating
+ /// TargetInstrInfo::EXTRACT_SUBREG nodes.
+ SDValue getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
+ SDValue Operand);
+
+ /// getTargetInsertSubreg - A convenience function for creating
+ /// TargetInstrInfo::INSERT_SUBREG nodes.
+ SDValue getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
+ SDValue Operand, SDValue Subreg);
+
+ /// getNodeIfExists - Get the specified node if it's already available, or
+ /// else return NULL.
+ SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTs,
+ const SDValue *Ops, unsigned NumOps);
+
+ /// getDbgValue - Creates a SDDbgValue node.
+ ///
+ SDDbgValue *getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R, uint64_t Off,
+ DebugLoc DL, unsigned O);
+ SDDbgValue *getDbgValue(MDNode *MDPtr, const Value *C, uint64_t Off,
+ DebugLoc DL, unsigned O);
+ SDDbgValue *getDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off,
+ DebugLoc DL, unsigned O);
+
+ /// RemoveDeadNode - Remove the specified node from the system. If any of its
+ /// operands then becomes dead, remove them as well. Inform UpdateListener
+ /// for each node deleted.
+ void RemoveDeadNode(SDNode *N);
+
+ /// RemoveDeadNodes - This method deletes the unreachable nodes in the
+ /// given list, and any nodes that become unreachable as a result.
+ void RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes);
+
+ /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
+ /// This can cause recursive merging of nodes in the DAG. Use the first
+ /// version if 'From' is known to have a single result, use the second
+ /// if you have two nodes with identical results (or if 'To' has a superset
+ /// of the results of 'From'), use the third otherwise.
+ ///
+ /// These methods all take an optional UpdateListener, which (if not null) is
+ /// informed about nodes that are deleted and modified due to recursive
+ /// changes in the dag.
+ ///
+ /// These functions only replace all existing uses. It's possible that as
+ /// these replacements are being performed, CSE may cause the From node
+ /// to be given new uses. These new uses of From are left in place, and
+ /// not automatically transferred to To.
+ ///
+ void ReplaceAllUsesWith(SDValue From, SDValue Op);
+ void ReplaceAllUsesWith(SDNode *From, SDNode *To);
+ void ReplaceAllUsesWith(SDNode *From, const SDValue *To);
+
+ /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
+ /// uses of other values produced by From.Val alone.
+ void ReplaceAllUsesOfValueWith(SDValue From, SDValue To);
+
+ /// ReplaceAllUsesOfValuesWith - Like ReplaceAllUsesOfValueWith, but
+ /// for multiple values at once. This correctly handles the case where
+ /// there is an overlap between the From values and the To values.
+ void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To,
+ unsigned Num);
+
+ /// AssignTopologicalOrder - Topological-sort the AllNodes list and a
+ /// assign a unique node id for each node in the DAG based on their
+ /// topological order. Returns the number of nodes.
+ unsigned AssignTopologicalOrder();
+
+ /// RepositionNode - Move node N in the AllNodes list to be immediately
+ /// before the given iterator Position. This may be used to update the
+ /// topological ordering when the list of nodes is modified.
+ void RepositionNode(allnodes_iterator Position, SDNode *N) {
+ AllNodes.insert(Position, AllNodes.remove(N));
+ }
+
+ /// isCommutativeBinOp - Returns true if the opcode is a commutative binary
+ /// operation.
+ static bool isCommutativeBinOp(unsigned Opcode) {
+ // FIXME: This should get its info from the td file, so that we can include
+ // target info.
+ switch (Opcode) {
+ case ISD::ADD:
+ case ISD::MUL:
+ case ISD::MULHU:
+ case ISD::MULHS:
+ case ISD::SMUL_LOHI:
+ case ISD::UMUL_LOHI:
+ case ISD::FADD:
+ case ISD::FMUL:
+ case ISD::AND:
+ case ISD::OR:
+ case ISD::XOR:
+ case ISD::SADDO:
+ case ISD::UADDO:
+ case ISD::ADDC:
+ case ISD::ADDE: return true;
+ default: return false;
+ }
+ }
+
+ /// AssignOrdering - Assign an order to the SDNode.
+ void AssignOrdering(const SDNode *SD, unsigned Order);
+
+ /// GetOrdering - Get the order for the SDNode.
+ unsigned GetOrdering(const SDNode *SD) const;
+
+ /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
+ /// value is produced by SD.
+ void AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter);
+
+ /// GetDbgValues - Get the debug values which reference the given SDNode.
+ ArrayRef<SDDbgValue*> GetDbgValues(const SDNode* SD) {
+ return DbgInfo->getSDDbgValues(SD);
+ }
+
+ /// TransferDbgValues - Transfer SDDbgValues.
+ void TransferDbgValues(SDValue From, SDValue To);
+
+ /// hasDebugValues - Return true if there are any SDDbgValue nodes associated
+ /// with this SelectionDAG.
+ bool hasDebugValues() const { return !DbgInfo->empty(); }
+
+ SDDbgInfo::DbgIterator DbgBegin() { return DbgInfo->DbgBegin(); }
+ SDDbgInfo::DbgIterator DbgEnd() { return DbgInfo->DbgEnd(); }
+ SDDbgInfo::DbgIterator ByvalParmDbgBegin() {
+ return DbgInfo->ByvalParmDbgBegin();
+ }
+ SDDbgInfo::DbgIterator ByvalParmDbgEnd() {
+ return DbgInfo->ByvalParmDbgEnd();
+ }
+
+ void dump() const;
+
+ /// CreateStackTemporary - Create a stack temporary, suitable for holding the
+ /// specified value type. If minAlign is specified, the slot size will have
+ /// at least that alignment.
+ SDValue CreateStackTemporary(EVT VT, unsigned minAlign = 1);
+
+ /// CreateStackTemporary - Create a stack temporary suitable for holding
+ /// either of the specified value types.
+ SDValue CreateStackTemporary(EVT VT1, EVT VT2);
+
+ /// FoldConstantArithmetic -
+ SDValue FoldConstantArithmetic(unsigned Opcode,
+ EVT VT,
+ ConstantSDNode *Cst1,
+ ConstantSDNode *Cst2);
+
+ /// FoldSetCC - Constant fold a setcc to true or false.
+ SDValue FoldSetCC(EVT VT, SDValue N1,
+ SDValue N2, ISD::CondCode Cond, DebugLoc dl);
+
+ /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
+ /// use this predicate to simplify operations downstream.
+ bool SignBitIsZero(SDValue Op, unsigned Depth = 0) const;
+
+ /// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero. We
+ /// use this predicate to simplify operations downstream. Op and Mask are
+ /// known to be the same type.
+ bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth = 0)
+ const;
+
+ /// ComputeMaskedBits - Determine which of the bits specified in Mask are
+ /// known to be either zero or one and return them in the KnownZero/KnownOne
+ /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
+ /// processing. Targets can implement the computeMaskedBitsForTargetNode
+ /// method in the TargetLowering class to allow target nodes to be understood.
+ void ComputeMaskedBits(SDValue Op, APInt &KnownZero, APInt &KnownOne,
+ unsigned Depth = 0) const;
+
+ /// ComputeNumSignBits - Return the number of times the sign bit of the
+ /// register is replicated into the other bits. We know that at least 1 bit
+ /// is always equal to the sign bit (itself), but other cases can give us
+ /// information. For example, immediately after an "SRA X, 2", we know that
+ /// the top 3 bits are all equal to each other, so we return 3. Targets can
+ /// implement the ComputeNumSignBitsForTarget method in the TargetLowering
+ /// class to allow target nodes to be understood.
+ unsigned ComputeNumSignBits(SDValue Op, unsigned Depth = 0) const;
+
+ /// isBaseWithConstantOffset - Return true if the specified operand is an
+ /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an
+ /// ISD::OR with a ConstantSDNode that is guaranteed to have the same
+ /// semantics as an ADD. This handles the equivalence:
+ /// X|Cst == X+Cst iff X&Cst = 0.
+ bool isBaseWithConstantOffset(SDValue Op) const;
+
+ /// isKnownNeverNan - Test whether the given SDValue is known to never be NaN.
+ bool isKnownNeverNaN(SDValue Op) const;
+
+ /// isKnownNeverZero - Test whether the given SDValue is known to never be
+ /// positive or negative Zero.
+ bool isKnownNeverZero(SDValue Op) const;
+
+ /// isEqualTo - Test whether two SDValues are known to compare equal. This
+ /// is true if they are the same value, or if one is negative zero and the
+ /// other positive zero.
+ bool isEqualTo(SDValue A, SDValue B) const;
+
+ /// UnrollVectorOp - Utility function used by legalize and lowering to
+ /// "unroll" a vector operation by splitting out the scalars and operating
+ /// on each element individually. If the ResNE is 0, fully unroll the vector
+ /// op. If ResNE is less than the width of the vector op, unroll up to ResNE.
+ /// If the ResNE is greater than the width of the vector op, unroll the
+ /// vector op and fill the end of the resulting vector with UNDEFS.
+ SDValue UnrollVectorOp(SDNode *N, unsigned ResNE = 0);
+
+ /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
+ /// location that is 'Dist' units away from the location that the 'Base' load
+ /// is loading from.
+ bool isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
+ unsigned Bytes, int Dist) const;
+
+ /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
+ /// it cannot be inferred.
+ unsigned InferPtrAlignment(SDValue Ptr) const;
+
+private:
+ bool RemoveNodeFromCSEMaps(SDNode *N);
+ void AddModifiedNodeToCSEMaps(SDNode *N);
+ SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op, void *&InsertPos);
+ SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
+ void *&InsertPos);
+ SDNode *FindModifiedNodeSlot(SDNode *N, const SDValue *Ops, unsigned NumOps,
+ void *&InsertPos);
+ SDNode *UpdadeDebugLocOnMergedSDNode(SDNode *N, DebugLoc loc);
+
+ void DeleteNodeNotInCSEMaps(SDNode *N);
+ void DeallocateNode(SDNode *N);
+
+ unsigned getEVTAlignment(EVT MemoryVT) const;
+
+ void allnodes_clear();
+
+ /// VTList - List of non-single value types.
+ std::vector<SDVTList> VTList;
+
+ /// CondCodeNodes - Maps to auto-CSE operations.
+ std::vector<CondCodeSDNode*> CondCodeNodes;
+
+ std::vector<SDNode*> ValueTypeNodes;
+ std::map<EVT, SDNode*, EVT::compareRawBits> ExtendedValueTypeNodes;
+ StringMap<SDNode*> ExternalSymbols;
+
+ std::map<std::pair<std::string, unsigned char>,SDNode*> TargetExternalSymbols;
+};
+
+template <> struct GraphTraits<SelectionDAG*> : public GraphTraits<SDNode*> {
+ typedef SelectionDAG::allnodes_iterator nodes_iterator;
+ static nodes_iterator nodes_begin(SelectionDAG *G) {
+ return G->allnodes_begin();
+ }
+ static nodes_iterator nodes_end(SelectionDAG *G) {
+ return G->allnodes_end();
+ }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/SelectionDAGISel.h b/include/llvm/CodeGen/SelectionDAGISel.h
new file mode 100644
index 00000000000..c42f6558007
--- /dev/null
+++ b/include/llvm/CodeGen/SelectionDAGISel.h
@@ -0,0 +1,282 @@
+//===-- llvm/CodeGen/SelectionDAGISel.h - Common Base Class------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the SelectionDAGISel class, which is used as the common
+// base class for SelectionDAG-based instruction selectors.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_SELECTIONDAG_ISEL_H
+#define LLVM_CODEGEN_SELECTIONDAG_ISEL_H
+
+#include "llvm/BasicBlock.h"
+#include "llvm/Pass.h"
+#include "llvm/CodeGen/SelectionDAG.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+
+namespace llvm {
+ class FastISel;
+ class SelectionDAGBuilder;
+ class SDValue;
+ class MachineRegisterInfo;
+ class MachineBasicBlock;
+ class MachineFunction;
+ class MachineInstr;
+ class TargetLowering;
+ class TargetLibraryInfo;
+ class TargetInstrInfo;
+ class FunctionLoweringInfo;
+ class ScheduleHazardRecognizer;
+ class GCFunctionInfo;
+ class ScheduleDAGSDNodes;
+ class LoadInst;
+
+/// SelectionDAGISel - This is the common base class used for SelectionDAG-based
+/// pattern-matching instruction selectors.
+class SelectionDAGISel : public MachineFunctionPass {
+public:
+ const TargetMachine &TM;
+ const TargetLowering &TLI;
+ const TargetLibraryInfo *LibInfo;
+ FunctionLoweringInfo *FuncInfo;
+ MachineFunction *MF;
+ MachineRegisterInfo *RegInfo;
+ SelectionDAG *CurDAG;
+ SelectionDAGBuilder *SDB;
+ AliasAnalysis *AA;
+ GCFunctionInfo *GFI;
+ CodeGenOpt::Level OptLevel;
+ static char ID;
+
+ explicit SelectionDAGISel(const TargetMachine &tm,
+ CodeGenOpt::Level OL = CodeGenOpt::Default);
+ virtual ~SelectionDAGISel();
+
+ const TargetLowering &getTargetLowering() { return TLI; }
+
+ virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+
+ virtual bool runOnMachineFunction(MachineFunction &MF);
+
+ virtual void EmitFunctionEntryCode() {}
+
+ /// PreprocessISelDAG - This hook allows targets to hack on the graph before
+ /// instruction selection starts.
+ virtual void PreprocessISelDAG() {}
+
+ /// PostprocessISelDAG() - This hook allows the target to hack on the graph
+ /// right after selection.
+ virtual void PostprocessISelDAG() {}
+
+ /// Select - Main hook targets implement to select a node.
+ virtual SDNode *Select(SDNode *N) = 0;
+
+ /// SelectInlineAsmMemoryOperand - Select the specified address as a target
+ /// addressing mode, according to the specified constraint code. If this does
+ /// not match or is not implemented, return true. The resultant operands
+ /// (which will appear in the machine instruction) should be added to the
+ /// OutOps vector.
+ virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
+ char ConstraintCode,
+ std::vector<SDValue> &OutOps) {
+ return true;
+ }
+
+ /// IsProfitableToFold - Returns true if it's profitable to fold the specific
+ /// operand node N of U during instruction selection that starts at Root.
+ virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
+
+ /// IsLegalToFold - Returns true if the specific operand node N of
+ /// U can be folded during instruction selection that starts at Root.
+ /// FIXME: This is a static member function because the MSP430/X86
+ /// targets, which uses it during isel. This could become a proper member.
+ static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
+ CodeGenOpt::Level OptLevel,
+ bool IgnoreChains = false);
+
+ // Opcodes used by the DAG state machine:
+ enum BuiltinOpcodes {
+ OPC_Scope,
+ OPC_RecordNode,
+ OPC_RecordChild0, OPC_RecordChild1, OPC_RecordChild2, OPC_RecordChild3,
+ OPC_RecordChild4, OPC_RecordChild5, OPC_RecordChild6, OPC_RecordChild7,
+ OPC_RecordMemRef,
+ OPC_CaptureGlueInput,
+ OPC_MoveChild,
+ OPC_MoveParent,
+ OPC_CheckSame,
+ OPC_CheckPatternPredicate,
+ OPC_CheckPredicate,
+ OPC_CheckOpcode,
+ OPC_SwitchOpcode,
+ OPC_CheckType,
+ OPC_SwitchType,
+ OPC_CheckChild0Type, OPC_CheckChild1Type, OPC_CheckChild2Type,
+ OPC_CheckChild3Type, OPC_CheckChild4Type, OPC_CheckChild5Type,
+ OPC_CheckChild6Type, OPC_CheckChild7Type,
+ OPC_CheckInteger,
+ OPC_CheckCondCode,
+ OPC_CheckValueType,
+ OPC_CheckComplexPat,
+ OPC_CheckAndImm, OPC_CheckOrImm,
+ OPC_CheckFoldableChainNode,
+
+ OPC_EmitInteger,
+ OPC_EmitRegister,
+ OPC_EmitRegister2,
+ OPC_EmitConvertToTarget,
+ OPC_EmitMergeInputChains,
+ OPC_EmitMergeInputChains1_0,
+ OPC_EmitMergeInputChains1_1,
+ OPC_EmitCopyToReg,
+ OPC_EmitNodeXForm,
+ OPC_EmitNode,
+ OPC_MorphNodeTo,
+ OPC_MarkGlueResults,
+ OPC_CompleteMatch
+ };
+
+ enum {
+ OPFL_None = 0, // Node has no chain or glue input and isn't variadic.
+ OPFL_Chain = 1, // Node has a chain input.
+ OPFL_GlueInput = 2, // Node has a glue input.
+ OPFL_GlueOutput = 4, // Node has a glue output.
+ OPFL_MemRefs = 8, // Node gets accumulated MemRefs.
+ OPFL_Variadic0 = 1<<4, // Node is variadic, root has 0 fixed inputs.
+ OPFL_Variadic1 = 2<<4, // Node is variadic, root has 1 fixed inputs.
+ OPFL_Variadic2 = 3<<4, // Node is variadic, root has 2 fixed inputs.
+ OPFL_Variadic3 = 4<<4, // Node is variadic, root has 3 fixed inputs.
+ OPFL_Variadic4 = 5<<4, // Node is variadic, root has 4 fixed inputs.
+ OPFL_Variadic5 = 6<<4, // Node is variadic, root has 5 fixed inputs.
+ OPFL_Variadic6 = 7<<4, // Node is variadic, root has 6 fixed inputs.
+
+ OPFL_VariadicInfo = OPFL_Variadic6
+ };
+
+ /// getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the
+ /// number of fixed arity values that should be skipped when copying from the
+ /// root.
+ static inline int getNumFixedFromVariadicInfo(unsigned Flags) {
+ return ((Flags&OPFL_VariadicInfo) >> 4)-1;
+ }
+
+
+protected:
+ /// DAGSize - Size of DAG being instruction selected.
+ ///
+ unsigned DAGSize;
+
+ /// ReplaceUses - replace all uses of the old node F with the use
+ /// of the new node T.
+ void ReplaceUses(SDValue F, SDValue T) {
+ CurDAG->ReplaceAllUsesOfValueWith(F, T);
+ }
+
+ /// ReplaceUses - replace all uses of the old nodes F with the use
+ /// of the new nodes T.
+ void ReplaceUses(const SDValue *F, const SDValue *T, unsigned Num) {
+ CurDAG->ReplaceAllUsesOfValuesWith(F, T, Num);
+ }
+
+ /// ReplaceUses - replace all uses of the old node F with the use
+ /// of the new node T.
+ void ReplaceUses(SDNode *F, SDNode *T) {
+ CurDAG->ReplaceAllUsesWith(F, T);
+ }
+
+
+ /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
+ /// by tblgen. Others should not call it.
+ void SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops);
+
+
+public:
+ // Calls to these predicates are generated by tblgen.
+ bool CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
+ int64_t DesiredMaskS) const;
+ bool CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
+ int64_t DesiredMaskS) const;
+
+
+ /// CheckPatternPredicate - This function is generated by tblgen in the
+ /// target. It runs the specified pattern predicate and returns true if it
+ /// succeeds or false if it fails. The number is a private implementation
+ /// detail to the code tblgen produces.
+ virtual bool CheckPatternPredicate(unsigned PredNo) const {
+ llvm_unreachable("Tblgen should generate the implementation of this!");
+ }
+
+ /// CheckNodePredicate - This function is generated by tblgen in the target.
+ /// It runs node predicate number PredNo and returns true if it succeeds or
+ /// false if it fails. The number is a private implementation
+ /// detail to the code tblgen produces.
+ virtual bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {
+ llvm_unreachable("Tblgen should generate the implementation of this!");
+ }
+
+ virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N,
+ unsigned PatternNo,
+ SmallVectorImpl<std::pair<SDValue, SDNode*> > &Result) {
+ llvm_unreachable("Tblgen should generate the implementation of this!");
+ }
+
+ virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {
+ llvm_unreachable("Tblgen should generate this!");
+ }
+
+ SDNode *SelectCodeCommon(SDNode *NodeToMatch,
+ const unsigned char *MatcherTable,
+ unsigned TableSize);
+
+private:
+
+ // Calls to these functions are generated by tblgen.
+ SDNode *Select_INLINEASM(SDNode *N);
+ SDNode *Select_UNDEF(SDNode *N);
+ void CannotYetSelect(SDNode *N);
+
+private:
+ void DoInstructionSelection();
+ SDNode *MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTs,
+ const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo);
+
+ void PrepareEHLandingPad();
+ void SelectAllBasicBlocks(const Function &Fn);
+ bool TryToFoldFastISelLoad(const LoadInst *LI, const Instruction *FoldInst,
+ FastISel *FastIS);
+ void FinishBasicBlock();
+
+ void SelectBasicBlock(BasicBlock::const_iterator Begin,
+ BasicBlock::const_iterator End,
+ bool &HadTailCall);
+ void CodeGenAndEmitDAG();
+ void LowerArguments(const BasicBlock *BB);
+
+ void ComputeLiveOutVRegInfo();
+
+ /// Create the scheduler. If a specific scheduler was specified
+ /// via the SchedulerRegistry, use it, otherwise select the
+ /// one preferred by the target.
+ ///
+ ScheduleDAGSDNodes *CreateScheduler();
+
+ /// OpcodeOffset - This is a cache used to dispatch efficiently into isel
+ /// state machines that start with a OPC_SwitchOpcode node.
+ std::vector<unsigned> OpcodeOffset;
+
+ void UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
+ const SmallVectorImpl<SDNode*> &ChainNodesMatched,
+ SDValue InputGlue, const SmallVectorImpl<SDNode*> &F,
+ bool isMorphNodeTo);
+
+};
+
+}
+
+#endif /* LLVM_CODEGEN_SELECTIONDAG_ISEL_H */
diff --git a/include/llvm/CodeGen/SelectionDAGNodes.h b/include/llvm/CodeGen/SelectionDAGNodes.h
new file mode 100644
index 00000000000..fd899732638
--- /dev/null
+++ b/include/llvm/CodeGen/SelectionDAGNodes.h
@@ -0,0 +1,1888 @@
+//===-- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the SDNode class and derived classes, which are used to
+// represent the nodes and operations present in a SelectionDAG. These nodes
+// and operations are machine code level operations, with some similarities to
+// the GCC RTL representation.
+//
+// Clients should include the SelectionDAG.h file instead of this file directly.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
+#define LLVM_CODEGEN_SELECTIONDAGNODES_H
+
+#include "llvm/Constants.h"
+#include "llvm/Instructions.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/CodeGen/ISDOpcodes.h"
+#include "llvm/CodeGen/ValueTypes.h"
+#include "llvm/CodeGen/MachineMemOperand.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/DebugLoc.h"
+#include <cassert>
+
+namespace llvm {
+
+class SelectionDAG;
+class GlobalValue;
+class MachineBasicBlock;
+class MachineConstantPoolValue;
+class SDNode;
+class Value;
+class MCSymbol;
+template <typename T> struct DenseMapInfo;
+template <typename T> struct simplify_type;
+template <typename T> struct ilist_traits;
+
+void checkForCycles(const SDNode *N);
+
+/// SDVTList - This represents a list of ValueType's that has been intern'd by
+/// a SelectionDAG. Instances of this simple value class are returned by
+/// SelectionDAG::getVTList(...).
+///
+struct SDVTList {
+ const EVT *VTs;
+ unsigned int NumVTs;
+};
+
+namespace ISD {
+ /// Node predicates
+
+ /// isBuildVectorAllOnes - Return true if the specified node is a
+ /// BUILD_VECTOR where all of the elements are ~0 or undef.
+ bool isBuildVectorAllOnes(const SDNode *N);
+
+ /// isBuildVectorAllZeros - Return true if the specified node is a
+ /// BUILD_VECTOR where all of the elements are 0 or undef.
+ bool isBuildVectorAllZeros(const SDNode *N);
+
+ /// isScalarToVector - Return true if the specified node is a
+ /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
+ /// element is not an undef.
+ bool isScalarToVector(const SDNode *N);
+
+ /// allOperandsUndef - Return true if the node has at least one operand
+ /// and all operands of the specified node are ISD::UNDEF.
+ bool allOperandsUndef(const SDNode *N);
+} // end llvm:ISD namespace
+
+//===----------------------------------------------------------------------===//
+/// SDValue - Unlike LLVM values, Selection DAG nodes may return multiple
+/// values as the result of a computation. Many nodes return multiple values,
+/// from loads (which define a token and a return value) to ADDC (which returns
+/// a result and a carry value), to calls (which may return an arbitrary number
+/// of values).
+///
+/// As such, each use of a SelectionDAG computation must indicate the node that
+/// computes it as well as which return value to use from that node. This pair
+/// of information is represented with the SDValue value type.
+///
+class SDValue {
+ SDNode *Node; // The node defining the value we are using.
+ unsigned ResNo; // Which return value of the node we are using.
+public:
+ SDValue() : Node(0), ResNo(0) {}
+ SDValue(SDNode *node, unsigned resno) : Node(node), ResNo(resno) {}
+
+ /// get the index which selects a specific result in the SDNode
+ unsigned getResNo() const { return ResNo; }
+
+ /// get the SDNode which holds the desired result
+ SDNode *getNode() const { return Node; }
+
+ /// set the SDNode
+ void setNode(SDNode *N) { Node = N; }
+
+ inline SDNode *operator->() const { return Node; }
+
+ bool operator==(const SDValue &O) const {
+ return Node == O.Node && ResNo == O.ResNo;
+ }
+ bool operator!=(const SDValue &O) const {
+ return !operator==(O);
+ }
+ bool operator<(const SDValue &O) const {
+ return Node < O.Node || (Node == O.Node && ResNo < O.ResNo);
+ }
+
+ SDValue getValue(unsigned R) const {
+ return SDValue(Node, R);
+ }
+
+ // isOperandOf - Return true if this node is an operand of N.
+ bool isOperandOf(SDNode *N) const;
+
+ /// getValueType - Return the ValueType of the referenced return value.
+ ///
+ inline EVT getValueType() const;
+
+ /// getValueSizeInBits - Returns the size of the value in bits.
+ ///
+ unsigned getValueSizeInBits() const {
+ return getValueType().getSizeInBits();
+ }
+
+ // Forwarding methods - These forward to the corresponding methods in SDNode.
+ inline unsigned getOpcode() const;
+ inline unsigned getNumOperands() const;
+ inline const SDValue &getOperand(unsigned i) const;
+ inline uint64_t getConstantOperandVal(unsigned i) const;
+ inline bool isTargetMemoryOpcode() const;
+ inline bool isTargetOpcode() const;
+ inline bool isMachineOpcode() const;
+ inline unsigned getMachineOpcode() const;
+ inline const DebugLoc getDebugLoc() const;
+ inline void dump() const;
+ inline void dumpr() const;
+
+ /// reachesChainWithoutSideEffects - Return true if this operand (which must
+ /// be a chain) reaches the specified operand without crossing any
+ /// side-effecting instructions. In practice, this looks through token
+ /// factors and non-volatile loads. In order to remain efficient, this only
+ /// looks a couple of nodes in, it does not do an exhaustive search.
+ bool reachesChainWithoutSideEffects(SDValue Dest,
+ unsigned Depth = 2) const;
+
+ /// use_empty - Return true if there are no nodes using value ResNo
+ /// of Node.
+ ///
+ inline bool use_empty() const;
+
+ /// hasOneUse - Return true if there is exactly one node using value
+ /// ResNo of Node.
+ ///
+ inline bool hasOneUse() const;
+};
+
+
+template<> struct DenseMapInfo<SDValue> {
+ static inline SDValue getEmptyKey() {
+ return SDValue((SDNode*)-1, -1U);
+ }
+ static inline SDValue getTombstoneKey() {
+ return SDValue((SDNode*)-1, 0);
+ }
+ static unsigned getHashValue(const SDValue &Val) {
+ return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
+ (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
+ }
+ static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
+ return LHS == RHS;
+ }
+};
+template <> struct isPodLike<SDValue> { static const bool value = true; };
+
+
+/// simplify_type specializations - Allow casting operators to work directly on
+/// SDValues as if they were SDNode*'s.
+template<> struct simplify_type<SDValue> {
+ typedef SDNode* SimpleType;
+ static SimpleType getSimplifiedValue(const SDValue &Val) {
+ return static_cast<SimpleType>(Val.getNode());
+ }
+};
+template<> struct simplify_type<const SDValue> {
+ typedef SDNode* SimpleType;
+ static SimpleType getSimplifiedValue(const SDValue &Val) {
+ return static_cast<SimpleType>(Val.getNode());
+ }
+};
+
+/// SDUse - Represents a use of a SDNode. This class holds an SDValue,
+/// which records the SDNode being used and the result number, a
+/// pointer to the SDNode using the value, and Next and Prev pointers,
+/// which link together all the uses of an SDNode.
+///
+class SDUse {
+ /// Val - The value being used.
+ SDValue Val;
+ /// User - The user of this value.
+ SDNode *User;
+ /// Prev, Next - Pointers to the uses list of the SDNode referred by
+ /// this operand.
+ SDUse **Prev, *Next;
+
+ SDUse(const SDUse &U) LLVM_DELETED_FUNCTION;
+ void operator=(const SDUse &U) LLVM_DELETED_FUNCTION;
+
+public:
+ SDUse() : Val(), User(NULL), Prev(NULL), Next(NULL) {}
+
+ /// Normally SDUse will just implicitly convert to an SDValue that it holds.
+ operator const SDValue&() const { return Val; }
+
+ /// If implicit conversion to SDValue doesn't work, the get() method returns
+ /// the SDValue.
+ const SDValue &get() const { return Val; }
+
+ /// getUser - This returns the SDNode that contains this Use.
+ SDNode *getUser() { return User; }
+
+ /// getNext - Get the next SDUse in the use list.
+ SDUse *getNext() const { return Next; }
+
+ /// getNode - Convenience function for get().getNode().
+ SDNode *getNode() const { return Val.getNode(); }
+ /// getResNo - Convenience function for get().getResNo().
+ unsigned getResNo() const { return Val.getResNo(); }
+ /// getValueType - Convenience function for get().getValueType().
+ EVT getValueType() const { return Val.getValueType(); }
+
+ /// operator== - Convenience function for get().operator==
+ bool operator==(const SDValue &V) const {
+ return Val == V;
+ }
+
+ /// operator!= - Convenience function for get().operator!=
+ bool operator!=(const SDValue &V) const {
+ return Val != V;
+ }
+
+ /// operator< - Convenience function for get().operator<
+ bool operator<(const SDValue &V) const {
+ return Val < V;
+ }
+
+private:
+ friend class SelectionDAG;
+ friend class SDNode;
+
+ void setUser(SDNode *p) { User = p; }
+
+ /// set - Remove this use from its existing use list, assign it the
+ /// given value, and add it to the new value's node's use list.
+ inline void set(const SDValue &V);
+ /// setInitial - like set, but only supports initializing a newly-allocated
+ /// SDUse with a non-null value.
+ inline void setInitial(const SDValue &V);
+ /// setNode - like set, but only sets the Node portion of the value,
+ /// leaving the ResNo portion unmodified.
+ inline void setNode(SDNode *N);
+
+ void addToList(SDUse **List) {
+ Next = *List;
+ if (Next) Next->Prev = &Next;
+ Prev = List;
+ *List = this;
+ }
+
+ void removeFromList() {
+ *Prev = Next;
+ if (Next) Next->Prev = Prev;
+ }
+};
+
+/// simplify_type specializations - Allow casting operators to work directly on
+/// SDValues as if they were SDNode*'s.
+template<> struct simplify_type<SDUse> {
+ typedef SDNode* SimpleType;
+ static SimpleType getSimplifiedValue(const SDUse &Val) {
+ return static_cast<SimpleType>(Val.getNode());
+ }
+};
+template<> struct simplify_type<const SDUse> {
+ typedef SDNode* SimpleType;
+ static SimpleType getSimplifiedValue(const SDUse &Val) {
+ return static_cast<SimpleType>(Val.getNode());
+ }
+};
+
+
+/// SDNode - Represents one node in the SelectionDAG.
+///
+class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
+private:
+ /// NodeType - The operation that this node performs.
+ ///
+ int16_t NodeType;
+
+ /// OperandsNeedDelete - This is true if OperandList was new[]'d. If true,
+ /// then they will be delete[]'d when the node is destroyed.
+ uint16_t OperandsNeedDelete : 1;
+
+ /// HasDebugValue - This tracks whether this node has one or more dbg_value
+ /// nodes corresponding to it.
+ uint16_t HasDebugValue : 1;
+
+protected:
+ /// SubclassData - This member is defined by this class, but is not used for
+ /// anything. Subclasses can use it to hold whatever state they find useful.
+ /// This field is initialized to zero by the ctor.
+ uint16_t SubclassData : 14;
+
+private:
+ /// NodeId - Unique id per SDNode in the DAG.
+ int NodeId;
+
+ /// OperandList - The values that are used by this operation.
+ ///
+ SDUse *OperandList;
+
+ /// ValueList - The types of the values this node defines. SDNode's may
+ /// define multiple values simultaneously.
+ const EVT *ValueList;
+
+ /// UseList - List of uses for this SDNode.
+ SDUse *UseList;
+
+ /// NumOperands/NumValues - The number of entries in the Operand/Value list.
+ unsigned short NumOperands, NumValues;
+
+ /// debugLoc - source line information.
+ DebugLoc debugLoc;
+
+ /// getValueTypeList - Return a pointer to the specified value type.
+ static const EVT *getValueTypeList(EVT VT);
+
+ friend class SelectionDAG;
+ friend struct ilist_traits<SDNode>;
+
+public:
+ //===--------------------------------------------------------------------===//
+ // Accessors
+ //
+
+ /// getOpcode - Return the SelectionDAG opcode value for this node. For
+ /// pre-isel nodes (those for which isMachineOpcode returns false), these
+ /// are the opcode values in the ISD and <target>ISD namespaces. For
+ /// post-isel opcodes, see getMachineOpcode.
+ unsigned getOpcode() const { return (unsigned short)NodeType; }
+
+ /// isTargetOpcode - Test if this node has a target-specific opcode (in the
+ /// \<target\>ISD namespace).
+ bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
+
+ /// isTargetMemoryOpcode - Test if this node has a target-specific
+ /// memory-referencing opcode (in the \<target\>ISD namespace and
+ /// greater than FIRST_TARGET_MEMORY_OPCODE).
+ bool isTargetMemoryOpcode() const {
+ return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
+ }
+
+ /// isMachineOpcode - Test if this node has a post-isel opcode, directly
+ /// corresponding to a MachineInstr opcode.
+ bool isMachineOpcode() const { return NodeType < 0; }
+
+ /// getMachineOpcode - This may only be called if isMachineOpcode returns
+ /// true. It returns the MachineInstr opcode value that the node's opcode
+ /// corresponds to.
+ unsigned getMachineOpcode() const {
+ assert(isMachineOpcode() && "Not a MachineInstr opcode!");
+ return ~NodeType;
+ }
+
+ /// getHasDebugValue - get this bit.
+ bool getHasDebugValue() const { return HasDebugValue; }
+
+ /// setHasDebugValue - set this bit.
+ void setHasDebugValue(bool b) { HasDebugValue = b; }
+
+ /// use_empty - Return true if there are no uses of this node.
+ ///
+ bool use_empty() const { return UseList == NULL; }
+
+ /// hasOneUse - Return true if there is exactly one use of this node.
+ ///
+ bool hasOneUse() const {
+ return !use_empty() && llvm::next(use_begin()) == use_end();
+ }
+
+ /// use_size - Return the number of uses of this node. This method takes
+ /// time proportional to the number of uses.
+ ///
+ size_t use_size() const { return std::distance(use_begin(), use_end()); }
+
+ /// getNodeId - Return the unique node id.
+ ///
+ int getNodeId() const { return NodeId; }
+
+ /// setNodeId - Set unique node id.
+ void setNodeId(int Id) { NodeId = Id; }
+
+ /// getDebugLoc - Return the source location info.
+ const DebugLoc getDebugLoc() const { return debugLoc; }
+
+ /// setDebugLoc - Set source location info. Try to avoid this, putting
+ /// it in the constructor is preferable.
+ void setDebugLoc(const DebugLoc dl) { debugLoc = dl; }
+
+ /// use_iterator - This class provides iterator support for SDUse
+ /// operands that use a specific SDNode.
+ class use_iterator
+ : public std::iterator<std::forward_iterator_tag, SDUse, ptrdiff_t> {
+ SDUse *Op;
+ explicit use_iterator(SDUse *op) : Op(op) {
+ }
+ friend class SDNode;
+ public:
+ typedef std::iterator<std::forward_iterator_tag,
+ SDUse, ptrdiff_t>::reference reference;
+ typedef std::iterator<std::forward_iterator_tag,
+ SDUse, ptrdiff_t>::pointer pointer;
+
+ use_iterator(const use_iterator &I) : Op(I.Op) {}
+ use_iterator() : Op(0) {}
+
+ bool operator==(const use_iterator &x) const {
+ return Op == x.Op;
+ }
+ bool operator!=(const use_iterator &x) const {
+ return !operator==(x);
+ }
+
+ /// atEnd - return true if this iterator is at the end of uses list.
+ bool atEnd() const { return Op == 0; }
+
+ // Iterator traversal: forward iteration only.
+ use_iterator &operator++() { // Preincrement
+ assert(Op && "Cannot increment end iterator!");
+ Op = Op->getNext();
+ return *this;
+ }
+
+ use_iterator operator++(int) { // Postincrement
+ use_iterator tmp = *this; ++*this; return tmp;
+ }
+
+ /// Retrieve a pointer to the current user node.
+ SDNode *operator*() const {
+ assert(Op && "Cannot dereference end iterator!");
+ return Op->getUser();
+ }
+
+ SDNode *operator->() const { return operator*(); }
+
+ SDUse &getUse() const { return *Op; }
+
+ /// getOperandNo - Retrieve the operand # of this use in its user.
+ ///
+ unsigned getOperandNo() const {
+ assert(Op && "Cannot dereference end iterator!");
+ return (unsigned)(Op - Op->getUser()->OperandList);
+ }
+ };
+
+ /// use_begin/use_end - Provide iteration support to walk over all uses
+ /// of an SDNode.
+
+ use_iterator use_begin() const {
+ return use_iterator(UseList);
+ }
+
+ static use_iterator use_end() { return use_iterator(0); }
+
+
+ /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
+ /// indicated value. This method ignores uses of other values defined by this
+ /// operation.
+ bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
+
+ /// hasAnyUseOfValue - Return true if there are any use of the indicated
+ /// value. This method ignores uses of other values defined by this operation.
+ bool hasAnyUseOfValue(unsigned Value) const;
+
+ /// isOnlyUserOf - Return true if this node is the only use of N.
+ ///
+ bool isOnlyUserOf(SDNode *N) const;
+
+ /// isOperandOf - Return true if this node is an operand of N.
+ ///
+ bool isOperandOf(SDNode *N) const;
+
+ /// isPredecessorOf - Return true if this node is a predecessor of N.
+ /// NOTE: Implemented on top of hasPredecessor and every bit as
+ /// expensive. Use carefully.
+ bool isPredecessorOf(const SDNode *N) const { return N->hasPredecessor(this); }
+
+ /// hasPredecessor - Return true if N is a predecessor of this node.
+ /// N is either an operand of this node, or can be reached by recursively
+ /// traversing up the operands.
+ /// NOTE: This is an expensive method. Use it carefully.
+ bool hasPredecessor(const SDNode *N) const;
+
+ /// hasPredecesorHelper - Return true if N is a predecessor of this node.
+ /// N is either an operand of this node, or can be reached by recursively
+ /// traversing up the operands.
+ /// In this helper the Visited and worklist sets are held externally to
+ /// cache predecessors over multiple invocations. If you want to test for
+ /// multiple predecessors this method is preferable to multiple calls to
+ /// hasPredecessor. Be sure to clear Visited and Worklist if the DAG
+ /// changes.
+ /// NOTE: This is still very expensive. Use carefully.
+ bool hasPredecessorHelper(const SDNode *N,
+ SmallPtrSet<const SDNode *, 32> &Visited,
+ SmallVector<const SDNode *, 16> &Worklist) const;
+
+ /// getNumOperands - Return the number of values used by this operation.
+ ///
+ unsigned getNumOperands() const { return NumOperands; }
+
+ /// getConstantOperandVal - Helper method returns the integer value of a
+ /// ConstantSDNode operand.
+ uint64_t getConstantOperandVal(unsigned Num) const;
+
+ const SDValue &getOperand(unsigned Num) const {
+ assert(Num < NumOperands && "Invalid child # of SDNode!");
+ return OperandList[Num];
+ }
+
+ typedef SDUse* op_iterator;
+ op_iterator op_begin() const { return OperandList; }
+ op_iterator op_end() const { return OperandList+NumOperands; }
+
+ SDVTList getVTList() const {
+ SDVTList X = { ValueList, NumValues };
+ return X;
+ }
+
+ /// getGluedNode - If this node has a glue operand, return the node
+ /// to which the glue operand points. Otherwise return NULL.
+ SDNode *getGluedNode() const {
+ if (getNumOperands() != 0 &&
+ getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
+ return getOperand(getNumOperands()-1).getNode();
+ return 0;
+ }
+
+ // If this is a pseudo op, like copyfromreg, look to see if there is a
+ // real target node glued to it. If so, return the target node.
+ const SDNode *getGluedMachineNode() const {
+ const SDNode *FoundNode = this;
+
+ // Climb up glue edges until a machine-opcode node is found, or the
+ // end of the chain is reached.
+ while (!FoundNode->isMachineOpcode()) {
+ const SDNode *N = FoundNode->getGluedNode();
+ if (!N) break;
+ FoundNode = N;
+ }
+
+ return FoundNode;
+ }
+
+ /// getGluedUser - If this node has a glue value with a user, return
+ /// the user (there is at most one). Otherwise return NULL.
+ SDNode *getGluedUser() const {
+ for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
+ if (UI.getUse().get().getValueType() == MVT::Glue)
+ return *UI;
+ return 0;
+ }
+
+ /// getNumValues - Return the number of values defined/returned by this
+ /// operator.
+ ///
+ unsigned getNumValues() const { return NumValues; }
+
+ /// getValueType - Return the type of a specified result.
+ ///
+ EVT getValueType(unsigned ResNo) const {
+ assert(ResNo < NumValues && "Illegal result number!");
+ return ValueList[ResNo];
+ }
+
+ /// getValueSizeInBits - Returns MVT::getSizeInBits(getValueType(ResNo)).
+ ///
+ unsigned getValueSizeInBits(unsigned ResNo) const {
+ return getValueType(ResNo).getSizeInBits();
+ }
+
+ typedef const EVT* value_iterator;
+ value_iterator value_begin() const { return ValueList; }
+ value_iterator value_end() const { return ValueList+NumValues; }
+
+ /// getOperationName - Return the opcode of this operation for printing.
+ ///
+ std::string getOperationName(const SelectionDAG *G = 0) const;
+ static const char* getIndexedModeName(ISD::MemIndexedMode AM);
+ void print_types(raw_ostream &OS, const SelectionDAG *G) const;
+ void print_details(raw_ostream &OS, const SelectionDAG *G) const;
+ void print(raw_ostream &OS, const SelectionDAG *G = 0) const;
+ void printr(raw_ostream &OS, const SelectionDAG *G = 0) const;
+
+ /// printrFull - Print a SelectionDAG node and all children down to
+ /// the leaves. The given SelectionDAG allows target-specific nodes
+ /// to be printed in human-readable form. Unlike printr, this will
+ /// print the whole DAG, including children that appear multiple
+ /// times.
+ ///
+ void printrFull(raw_ostream &O, const SelectionDAG *G = 0) const;
+
+ /// printrWithDepth - Print a SelectionDAG node and children up to
+ /// depth "depth." The given SelectionDAG allows target-specific
+ /// nodes to be printed in human-readable form. Unlike printr, this
+ /// will print children that appear multiple times wherever they are
+ /// used.
+ ///
+ void printrWithDepth(raw_ostream &O, const SelectionDAG *G = 0,
+ unsigned depth = 100) const;
+
+
+ /// dump - Dump this node, for debugging.
+ void dump() const;
+
+ /// dumpr - Dump (recursively) this node and its use-def subgraph.
+ void dumpr() const;
+
+ /// dump - Dump this node, for debugging.
+ /// The given SelectionDAG allows target-specific nodes to be printed
+ /// in human-readable form.
+ void dump(const SelectionDAG *G) const;
+
+ /// dumpr - Dump (recursively) this node and its use-def subgraph.
+ /// The given SelectionDAG allows target-specific nodes to be printed
+ /// in human-readable form.
+ void dumpr(const SelectionDAG *G) const;
+
+ /// dumprFull - printrFull to dbgs(). The given SelectionDAG allows
+ /// target-specific nodes to be printed in human-readable form.
+ /// Unlike dumpr, this will print the whole DAG, including children
+ /// that appear multiple times.
+ ///
+ void dumprFull(const SelectionDAG *G = 0) const;
+
+ /// dumprWithDepth - printrWithDepth to dbgs(). The given
+ /// SelectionDAG allows target-specific nodes to be printed in
+ /// human-readable form. Unlike dumpr, this will print children
+ /// that appear multiple times wherever they are used.
+ ///
+ void dumprWithDepth(const SelectionDAG *G = 0, unsigned depth = 100) const;
+
+
+ static bool classof(const SDNode *) { return true; }
+
+ /// Profile - Gather unique data for the node.
+ ///
+ void Profile(FoldingSetNodeID &ID) const;
+
+ /// addUse - This method should only be used by the SDUse class.
+ ///
+ void addUse(SDUse &U) { U.addToList(&UseList); }
+
+protected:
+ static SDVTList getSDVTList(EVT VT) {
+ SDVTList Ret = { getValueTypeList(VT), 1 };
+ return Ret;
+ }
+
+ SDNode(unsigned Opc, const DebugLoc dl, SDVTList VTs, const SDValue *Ops,
+ unsigned NumOps)
+ : NodeType(Opc), OperandsNeedDelete(true), HasDebugValue(false),
+ SubclassData(0), NodeId(-1),
+ OperandList(NumOps ? new SDUse[NumOps] : 0),
+ ValueList(VTs.VTs), UseList(NULL),
+ NumOperands(NumOps), NumValues(VTs.NumVTs),
+ debugLoc(dl) {
+ for (unsigned i = 0; i != NumOps; ++i) {
+ OperandList[i].setUser(this);
+ OperandList[i].setInitial(Ops[i]);
+ }
+ checkForCycles(this);
+ }
+
+ /// This constructor adds no operands itself; operands can be
+ /// set later with InitOperands.
+ SDNode(unsigned Opc, const DebugLoc dl, SDVTList VTs)
+ : NodeType(Opc), OperandsNeedDelete(false), HasDebugValue(false),
+ SubclassData(0), NodeId(-1), OperandList(0), ValueList(VTs.VTs),
+ UseList(NULL), NumOperands(0), NumValues(VTs.NumVTs),
+ debugLoc(dl) {}
+
+ /// InitOperands - Initialize the operands list of this with 1 operand.
+ void InitOperands(SDUse *Ops, const SDValue &Op0) {
+ Ops[0].setUser(this);
+ Ops[0].setInitial(Op0);
+ NumOperands = 1;
+ OperandList = Ops;
+ checkForCycles(this);
+ }
+
+ /// InitOperands - Initialize the operands list of this with 2 operands.
+ void InitOperands(SDUse *Ops, const SDValue &Op0, const SDValue &Op1) {
+ Ops[0].setUser(this);
+ Ops[0].setInitial(Op0);
+ Ops[1].setUser(this);
+ Ops[1].setInitial(Op1);
+ NumOperands = 2;
+ OperandList = Ops;
+ checkForCycles(this);
+ }
+
+ /// InitOperands - Initialize the operands list of this with 3 operands.
+ void InitOperands(SDUse *Ops, const SDValue &Op0, const SDValue &Op1,
+ const SDValue &Op2) {
+ Ops[0].setUser(this);
+ Ops[0].setInitial(Op0);
+ Ops[1].setUser(this);
+ Ops[1].setInitial(Op1);
+ Ops[2].setUser(this);
+ Ops[2].setInitial(Op2);
+ NumOperands = 3;
+ OperandList = Ops;
+ checkForCycles(this);
+ }
+
+ /// InitOperands - Initialize the operands list of this with 4 operands.
+ void InitOperands(SDUse *Ops, const SDValue &Op0, const SDValue &Op1,
+ const SDValue &Op2, const SDValue &Op3) {
+ Ops[0].setUser(this);
+ Ops[0].setInitial(Op0);
+ Ops[1].setUser(this);
+ Ops[1].setInitial(Op1);
+ Ops[2].setUser(this);
+ Ops[2].setInitial(Op2);
+ Ops[3].setUser(this);
+ Ops[3].setInitial(Op3);
+ NumOperands = 4;
+ OperandList = Ops;
+ checkForCycles(this);
+ }
+
+ /// InitOperands - Initialize the operands list of this with N operands.
+ void InitOperands(SDUse *Ops, const SDValue *Vals, unsigned N) {
+ for (unsigned i = 0; i != N; ++i) {
+ Ops[i].setUser(this);
+ Ops[i].setInitial(Vals[i]);
+ }
+ NumOperands = N;
+ OperandList = Ops;
+ checkForCycles(this);
+ }
+
+ /// DropOperands - Release the operands and set this node to have
+ /// zero operands.
+ void DropOperands();
+};
+
+
+// Define inline functions from the SDValue class.
+
+inline unsigned SDValue::getOpcode() const {
+ return Node->getOpcode();
+}
+inline EVT SDValue::getValueType() const {
+ return Node->getValueType(ResNo);
+}
+inline unsigned SDValue::getNumOperands() const {
+ return Node->getNumOperands();
+}
+inline const SDValue &SDValue::getOperand(unsigned i) const {
+ return Node->getOperand(i);
+}
+inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
+ return Node->getConstantOperandVal(i);
+}
+inline bool SDValue::isTargetOpcode() const {
+ return Node->isTargetOpcode();
+}
+inline bool SDValue::isTargetMemoryOpcode() const {
+ return Node->isTargetMemoryOpcode();
+}
+inline bool SDValue::isMachineOpcode() const {
+ return Node->isMachineOpcode();
+}
+inline unsigned SDValue::getMachineOpcode() const {
+ return Node->getMachineOpcode();
+}
+inline bool SDValue::use_empty() const {
+ return !Node->hasAnyUseOfValue(ResNo);
+}
+inline bool SDValue::hasOneUse() const {
+ return Node->hasNUsesOfValue(1, ResNo);
+}
+inline const DebugLoc SDValue::getDebugLoc() const {
+ return Node->getDebugLoc();
+}
+inline void SDValue::dump() const {
+ return Node->dump();
+}
+inline void SDValue::dumpr() const {
+ return Node->dumpr();
+}
+// Define inline functions from the SDUse class.
+
+inline void SDUse::set(const SDValue &V) {
+ if (Val.getNode()) removeFromList();
+ Val = V;
+ if (V.getNode()) V.getNode()->addUse(*this);
+}
+
+inline void SDUse::setInitial(const SDValue &V) {
+ Val = V;
+ V.getNode()->addUse(*this);
+}
+
+inline void SDUse::setNode(SDNode *N) {
+ if (Val.getNode()) removeFromList();
+ Val.setNode(N);
+ if (N) N->addUse(*this);
+}
+
+/// UnarySDNode - This class is used for single-operand SDNodes. This is solely
+/// to allow co-allocation of node operands with the node itself.
+class UnarySDNode : public SDNode {
+ SDUse Op;
+public:
+ UnarySDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, SDValue X)
+ : SDNode(Opc, dl, VTs) {
+ InitOperands(&Op, X);
+ }
+};
+
+/// BinarySDNode - This class is used for two-operand SDNodes. This is solely
+/// to allow co-allocation of node operands with the node itself.
+class BinarySDNode : public SDNode {
+ SDUse Ops[2];
+public:
+ BinarySDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, SDValue X, SDValue Y)
+ : SDNode(Opc, dl, VTs) {
+ InitOperands(Ops, X, Y);
+ }
+};
+
+/// TernarySDNode - This class is used for three-operand SDNodes. This is solely
+/// to allow co-allocation of node operands with the node itself.
+class TernarySDNode : public SDNode {
+ SDUse Ops[3];
+public:
+ TernarySDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, SDValue X, SDValue Y,
+ SDValue Z)
+ : SDNode(Opc, dl, VTs) {
+ InitOperands(Ops, X, Y, Z);
+ }
+};
+
+
+/// HandleSDNode - This class is used to form a handle around another node that
+/// is persistent and is updated across invocations of replaceAllUsesWith on its
+/// operand. This node should be directly created by end-users and not added to
+/// the AllNodes list.
+class HandleSDNode : public SDNode {
+ SDUse Op;
+public:
+ // FIXME: Remove the "noinline" attribute once <rdar://problem/5852746> is
+ // fixed.
+#if __GNUC__==4 && __GNUC_MINOR__==2 && defined(__APPLE__) && !defined(__llvm__)
+ explicit __attribute__((__noinline__)) HandleSDNode(SDValue X)
+#else
+ explicit HandleSDNode(SDValue X)
+#endif
+ : SDNode(ISD::HANDLENODE, DebugLoc(), getSDVTList(MVT::Other)) {
+ InitOperands(&Op, X);
+ }
+ ~HandleSDNode();
+ const SDValue &getValue() const { return Op; }
+};
+
+/// Abstact virtual class for operations for memory operations
+class MemSDNode : public SDNode {
+private:
+ // MemoryVT - VT of in-memory value.
+ EVT MemoryVT;
+
+protected:
+ /// MMO - Memory reference information.
+ MachineMemOperand *MMO;
+
+public:
+ MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT MemoryVT,
+ MachineMemOperand *MMO);
+
+ MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, const SDValue *Ops,
+ unsigned NumOps, EVT MemoryVT, MachineMemOperand *MMO);
+
+ bool readMem() const { return MMO->isLoad(); }
+ bool writeMem() const { return MMO->isStore(); }
+
+ /// Returns alignment and volatility of the memory access
+ unsigned getOriginalAlignment() const {
+ return MMO->getBaseAlignment();
+ }
+ unsigned getAlignment() const {
+ return MMO->getAlignment();
+ }
+
+ /// getRawSubclassData - Return the SubclassData value, which contains an
+ /// encoding of the volatile flag, as well as bits used by subclasses. This
+ /// function should only be used to compute a FoldingSetNodeID value.
+ unsigned getRawSubclassData() const {
+ return SubclassData;
+ }
+
+ // We access subclass data here so that we can check consistency
+ // with MachineMemOperand information.
+ bool isVolatile() const { return (SubclassData >> 5) & 1; }
+ bool isNonTemporal() const { return (SubclassData >> 6) & 1; }
+ bool isInvariant() const { return (SubclassData >> 7) & 1; }
+
+ AtomicOrdering getOrdering() const {
+ return AtomicOrdering((SubclassData >> 8) & 15);
+ }
+ SynchronizationScope getSynchScope() const {
+ return SynchronizationScope((SubclassData >> 12) & 1);
+ }
+
+ /// Returns the SrcValue and offset that describes the location of the access
+ const Value *getSrcValue() const { return MMO->getValue(); }
+ int64_t getSrcValueOffset() const { return MMO->getOffset(); }
+
+ /// Returns the TBAAInfo that describes the dereference.
+ const MDNode *getTBAAInfo() const { return MMO->getTBAAInfo(); }
+
+ /// Returns the Ranges that describes the dereference.
+ const MDNode *getRanges() const { return MMO->getRanges(); }
+
+ /// getMemoryVT - Return the type of the in-memory value.
+ EVT getMemoryVT() const { return MemoryVT; }
+
+ /// getMemOperand - Return a MachineMemOperand object describing the memory
+ /// reference performed by operation.
+ MachineMemOperand *getMemOperand() const { return MMO; }
+
+ const MachinePointerInfo &getPointerInfo() const {
+ return MMO->getPointerInfo();
+ }
+
+ /// refineAlignment - Update this MemSDNode's MachineMemOperand information
+ /// to reflect the alignment of NewMMO, if it has a greater alignment.
+ /// This must only be used when the new alignment applies to all users of
+ /// this MachineMemOperand.
+ void refineAlignment(const MachineMemOperand *NewMMO) {
+ MMO->refineAlignment(NewMMO);
+ }
+
+ const SDValue &getChain() const { return getOperand(0); }
+ const SDValue &getBasePtr() const {
+ return getOperand(getOpcode() == ISD::STORE ? 2 : 1);
+ }
+
+ // Methods to support isa and dyn_cast
+ static bool classof(const MemSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ // For some targets, we lower some target intrinsics to a MemIntrinsicNode
+ // with either an intrinsic or a target opcode.
+ return N->getOpcode() == ISD::LOAD ||
+ N->getOpcode() == ISD::STORE ||
+ N->getOpcode() == ISD::PREFETCH ||
+ N->getOpcode() == ISD::ATOMIC_CMP_SWAP ||
+ N->getOpcode() == ISD::ATOMIC_SWAP ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_ADD ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_SUB ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_AND ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_OR ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_XOR ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_NAND ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_MIN ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_MAX ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_UMIN ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_UMAX ||
+ N->getOpcode() == ISD::ATOMIC_LOAD ||
+ N->getOpcode() == ISD::ATOMIC_STORE ||
+ N->isTargetMemoryOpcode();
+ }
+};
+
+/// AtomicSDNode - A SDNode reprenting atomic operations.
+///
+class AtomicSDNode : public MemSDNode {
+ SDUse Ops[4];
+
+ void InitAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope) {
+ // This must match encodeMemSDNodeFlags() in SelectionDAG.cpp.
+ assert((Ordering & 15) == Ordering &&
+ "Ordering may not require more than 4 bits!");
+ assert((SynchScope & 1) == SynchScope &&
+ "SynchScope may not require more than 1 bit!");
+ SubclassData |= Ordering << 8;
+ SubclassData |= SynchScope << 12;
+ assert(getOrdering() == Ordering && "Ordering encoding error!");
+ assert(getSynchScope() == SynchScope && "Synch-scope encoding error!");
+ }
+
+public:
+ // Opc: opcode for atomic
+ // VTL: value type list
+ // Chain: memory chain for operaand
+ // Ptr: address to update as a SDValue
+ // Cmp: compare value
+ // Swp: swap value
+ // SrcVal: address to update as a Value (used for MemOperand)
+ // Align: alignment of memory
+ AtomicSDNode(unsigned Opc, DebugLoc dl, SDVTList VTL, EVT MemVT,
+ SDValue Chain, SDValue Ptr,
+ SDValue Cmp, SDValue Swp, MachineMemOperand *MMO,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope)
+ : MemSDNode(Opc, dl, VTL, MemVT, MMO) {
+ InitAtomic(Ordering, SynchScope);
+ InitOperands(Ops, Chain, Ptr, Cmp, Swp);
+ }
+ AtomicSDNode(unsigned Opc, DebugLoc dl, SDVTList VTL, EVT MemVT,
+ SDValue Chain, SDValue Ptr,
+ SDValue Val, MachineMemOperand *MMO,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope)
+ : MemSDNode(Opc, dl, VTL, MemVT, MMO) {
+ InitAtomic(Ordering, SynchScope);
+ InitOperands(Ops, Chain, Ptr, Val);
+ }
+ AtomicSDNode(unsigned Opc, DebugLoc dl, SDVTList VTL, EVT MemVT,
+ SDValue Chain, SDValue Ptr,
+ MachineMemOperand *MMO,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope)
+ : MemSDNode(Opc, dl, VTL, MemVT, MMO) {
+ InitAtomic(Ordering, SynchScope);
+ InitOperands(Ops, Chain, Ptr);
+ }
+
+ const SDValue &getBasePtr() const { return getOperand(1); }
+ const SDValue &getVal() const { return getOperand(2); }
+
+ bool isCompareAndSwap() const {
+ unsigned Op = getOpcode();
+ return Op == ISD::ATOMIC_CMP_SWAP;
+ }
+
+ // Methods to support isa and dyn_cast
+ static bool classof(const AtomicSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::ATOMIC_CMP_SWAP ||
+ N->getOpcode() == ISD::ATOMIC_SWAP ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_ADD ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_SUB ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_AND ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_OR ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_XOR ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_NAND ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_MIN ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_MAX ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_UMIN ||
+ N->getOpcode() == ISD::ATOMIC_LOAD_UMAX ||
+ N->getOpcode() == ISD::ATOMIC_LOAD ||
+ N->getOpcode() == ISD::ATOMIC_STORE;
+ }
+};
+
+/// MemIntrinsicSDNode - This SDNode is used for target intrinsics that touch
+/// memory and need an associated MachineMemOperand. Its opcode may be
+/// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
+/// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
+class MemIntrinsicSDNode : public MemSDNode {
+public:
+ MemIntrinsicSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
+ const SDValue *Ops, unsigned NumOps,
+ EVT MemoryVT, MachineMemOperand *MMO)
+ : MemSDNode(Opc, dl, VTs, Ops, NumOps, MemoryVT, MMO) {
+ }
+
+ // Methods to support isa and dyn_cast
+ static bool classof(const MemIntrinsicSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ // We lower some target intrinsics to their target opcode
+ // early a node with a target opcode can be of this class
+ return N->getOpcode() == ISD::INTRINSIC_W_CHAIN ||
+ N->getOpcode() == ISD::INTRINSIC_VOID ||
+ N->getOpcode() == ISD::PREFETCH ||
+ N->isTargetMemoryOpcode();
+ }
+};
+
+/// ShuffleVectorSDNode - This SDNode is used to implement the code generator
+/// support for the llvm IR shufflevector instruction. It combines elements
+/// from two input vectors into a new input vector, with the selection and
+/// ordering of elements determined by an array of integers, referred to as
+/// the shuffle mask. For input vectors of width N, mask indices of 0..N-1
+/// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
+/// An index of -1 is treated as undef, such that the code generator may put
+/// any value in the corresponding element of the result.
+class ShuffleVectorSDNode : public SDNode {
+ SDUse Ops[2];
+
+ // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
+ // is freed when the SelectionDAG object is destroyed.
+ const int *Mask;
+protected:
+ friend class SelectionDAG;
+ ShuffleVectorSDNode(EVT VT, DebugLoc dl, SDValue N1, SDValue N2,
+ const int *M)
+ : SDNode(ISD::VECTOR_SHUFFLE, dl, getSDVTList(VT)), Mask(M) {
+ InitOperands(Ops, N1, N2);
+ }
+public:
+
+ ArrayRef<int> getMask() const {
+ EVT VT = getValueType(0);
+ return makeArrayRef(Mask, VT.getVectorNumElements());
+ }
+ int getMaskElt(unsigned Idx) const {
+ assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!");
+ return Mask[Idx];
+ }
+
+ bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
+ int getSplatIndex() const {
+ assert(isSplat() && "Cannot get splat index for non-splat!");
+ EVT VT = getValueType(0);
+ for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
+ if (Mask[i] != -1)
+ return Mask[i];
+ }
+ return -1;
+ }
+ static bool isSplatMask(const int *Mask, EVT VT);
+
+ static bool classof(const ShuffleVectorSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::VECTOR_SHUFFLE;
+ }
+};
+
+class ConstantSDNode : public SDNode {
+ const ConstantInt *Value;
+ friend class SelectionDAG;
+ ConstantSDNode(bool isTarget, const ConstantInt *val, EVT VT)
+ : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant,
+ DebugLoc(), getSDVTList(VT)), Value(val) {
+ }
+public:
+
+ const ConstantInt *getConstantIntValue() const { return Value; }
+ const APInt &getAPIntValue() const { return Value->getValue(); }
+ uint64_t getZExtValue() const { return Value->getZExtValue(); }
+ int64_t getSExtValue() const { return Value->getSExtValue(); }
+
+ bool isOne() const { return Value->isOne(); }
+ bool isNullValue() const { return Value->isNullValue(); }
+ bool isAllOnesValue() const { return Value->isAllOnesValue(); }
+
+ static bool classof(const ConstantSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::Constant ||
+ N->getOpcode() == ISD::TargetConstant;
+ }
+};
+
+class ConstantFPSDNode : public SDNode {
+ const ConstantFP *Value;
+ friend class SelectionDAG;
+ ConstantFPSDNode(bool isTarget, const ConstantFP *val, EVT VT)
+ : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP,
+ DebugLoc(), getSDVTList(VT)), Value(val) {
+ }
+public:
+
+ const APFloat& getValueAPF() const { return Value->getValueAPF(); }
+ const ConstantFP *getConstantFPValue() const { return Value; }
+
+ /// isZero - Return true if the value is positive or negative zero.
+ bool isZero() const { return Value->isZero(); }
+
+ /// isNaN - Return true if the value is a NaN.
+ bool isNaN() const { return Value->isNaN(); }
+
+ /// isExactlyValue - We don't rely on operator== working on double values, as
+ /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
+ /// As such, this method can be used to do an exact bit-for-bit comparison of
+ /// two floating point values.
+
+ /// We leave the version with the double argument here because it's just so
+ /// convenient to write "2.0" and the like. Without this function we'd
+ /// have to duplicate its logic everywhere it's called.
+ bool isExactlyValue(double V) const {
+ bool ignored;
+ // convert is not supported on this type
+ if (&Value->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
+ return false;
+ APFloat Tmp(V);
+ Tmp.convert(Value->getValueAPF().getSemantics(),
+ APFloat::rmNearestTiesToEven, &ignored);
+ return isExactlyValue(Tmp);
+ }
+ bool isExactlyValue(const APFloat& V) const;
+
+ static bool isValueValidForType(EVT VT, const APFloat& Val);
+
+ static bool classof(const ConstantFPSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::ConstantFP ||
+ N->getOpcode() == ISD::TargetConstantFP;
+ }
+};
+
+class GlobalAddressSDNode : public SDNode {
+ const GlobalValue *TheGlobal;
+ int64_t Offset;
+ unsigned char TargetFlags;
+ friend class SelectionDAG;
+ GlobalAddressSDNode(unsigned Opc, DebugLoc DL, const GlobalValue *GA, EVT VT,
+ int64_t o, unsigned char TargetFlags);
+public:
+
+ const GlobalValue *getGlobal() const { return TheGlobal; }
+ int64_t getOffset() const { return Offset; }
+ unsigned char getTargetFlags() const { return TargetFlags; }
+ // Return the address space this GlobalAddress belongs to.
+ unsigned getAddressSpace() const;
+
+ static bool classof(const GlobalAddressSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::GlobalAddress ||
+ N->getOpcode() == ISD::TargetGlobalAddress ||
+ N->getOpcode() == ISD::GlobalTLSAddress ||
+ N->getOpcode() == ISD::TargetGlobalTLSAddress;
+ }
+};
+
+class FrameIndexSDNode : public SDNode {
+ int FI;
+ friend class SelectionDAG;
+ FrameIndexSDNode(int fi, EVT VT, bool isTarg)
+ : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
+ DebugLoc(), getSDVTList(VT)), FI(fi) {
+ }
+public:
+
+ int getIndex() const { return FI; }
+
+ static bool classof(const FrameIndexSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::FrameIndex ||
+ N->getOpcode() == ISD::TargetFrameIndex;
+ }
+};
+
+class JumpTableSDNode : public SDNode {
+ int JTI;
+ unsigned char TargetFlags;
+ friend class SelectionDAG;
+ JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned char TF)
+ : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
+ DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
+ }
+public:
+
+ int getIndex() const { return JTI; }
+ unsigned char getTargetFlags() const { return TargetFlags; }
+
+ static bool classof(const JumpTableSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::JumpTable ||
+ N->getOpcode() == ISD::TargetJumpTable;
+ }
+};
+
+class ConstantPoolSDNode : public SDNode {
+ union {
+ const Constant *ConstVal;
+ MachineConstantPoolValue *MachineCPVal;
+ } Val;
+ int Offset; // It's a MachineConstantPoolValue if top bit is set.
+ unsigned Alignment; // Minimum alignment requirement of CP (not log2 value).
+ unsigned char TargetFlags;
+ friend class SelectionDAG;
+ ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
+ unsigned Align, unsigned char TF)
+ : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool,
+ DebugLoc(),
+ getSDVTList(VT)), Offset(o), Alignment(Align), TargetFlags(TF) {
+ assert((int)Offset >= 0 && "Offset is too large");
+ Val.ConstVal = c;
+ }
+ ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v,
+ EVT VT, int o, unsigned Align, unsigned char TF)
+ : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool,
+ DebugLoc(),
+ getSDVTList(VT)), Offset(o), Alignment(Align), TargetFlags(TF) {
+ assert((int)Offset >= 0 && "Offset is too large");
+ Val.MachineCPVal = v;
+ Offset |= 1 << (sizeof(unsigned)*CHAR_BIT-1);
+ }
+public:
+
+
+ bool isMachineConstantPoolEntry() const {
+ return (int)Offset < 0;
+ }
+
+ const Constant *getConstVal() const {
+ assert(!isMachineConstantPoolEntry() && "Wrong constantpool type");
+ return Val.ConstVal;
+ }
+
+ MachineConstantPoolValue *getMachineCPVal() const {
+ assert(isMachineConstantPoolEntry() && "Wrong constantpool type");
+ return Val.MachineCPVal;
+ }
+
+ int getOffset() const {
+ return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT-1));
+ }
+
+ // Return the alignment of this constant pool object, which is either 0 (for
+ // default alignment) or the desired value.
+ unsigned getAlignment() const { return Alignment; }
+ unsigned char getTargetFlags() const { return TargetFlags; }
+
+ Type *getType() const;
+
+ static bool classof(const ConstantPoolSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::ConstantPool ||
+ N->getOpcode() == ISD::TargetConstantPool;
+ }
+};
+
+/// Completely target-dependent object reference.
+class TargetIndexSDNode : public SDNode {
+ unsigned char TargetFlags;
+ int Index;
+ int64_t Offset;
+ friend class SelectionDAG;
+public:
+
+ TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned char TF)
+ : SDNode(ISD::TargetIndex, DebugLoc(), getSDVTList(VT)),
+ TargetFlags(TF), Index(Idx), Offset(Ofs) {}
+public:
+
+ unsigned char getTargetFlags() const { return TargetFlags; }
+ int getIndex() const { return Index; }
+ int64_t getOffset() const { return Offset; }
+
+ static bool classof(const TargetIndexSDNode*) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::TargetIndex;
+ }
+};
+
+class BasicBlockSDNode : public SDNode {
+ MachineBasicBlock *MBB;
+ friend class SelectionDAG;
+ /// Debug info is meaningful and potentially useful here, but we create
+ /// blocks out of order when they're jumped to, which makes it a bit
+ /// harder. Let's see if we need it first.
+ explicit BasicBlockSDNode(MachineBasicBlock *mbb)
+ : SDNode(ISD::BasicBlock, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb) {
+ }
+public:
+
+ MachineBasicBlock *getBasicBlock() const { return MBB; }
+
+ static bool classof(const BasicBlockSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::BasicBlock;
+ }
+};
+
+/// BuildVectorSDNode - A "pseudo-class" with methods for operating on
+/// BUILD_VECTORs.
+class BuildVectorSDNode : public SDNode {
+ // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
+ explicit BuildVectorSDNode() LLVM_DELETED_FUNCTION;
+public:
+ /// isConstantSplat - Check if this is a constant splat, and if so, find the
+ /// smallest element size that splats the vector. If MinSplatBits is
+ /// nonzero, the element size must be at least that large. Note that the
+ /// splat element may be the entire vector (i.e., a one element vector).
+ /// Returns the splat element value in SplatValue. Any undefined bits in
+ /// that value are zero, and the corresponding bits in the SplatUndef mask
+ /// are set. The SplatBitSize value is set to the splat element size in
+ /// bits. HasAnyUndefs is set to true if any bits in the vector are
+ /// undefined. isBigEndian describes the endianness of the target.
+ bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
+ unsigned &SplatBitSize, bool &HasAnyUndefs,
+ unsigned MinSplatBits = 0, bool isBigEndian = false);
+
+ static inline bool classof(const BuildVectorSDNode *) { return true; }
+ static inline bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::BUILD_VECTOR;
+ }
+};
+
+/// SrcValueSDNode - An SDNode that holds an arbitrary LLVM IR Value. This is
+/// used when the SelectionDAG needs to make a simple reference to something
+/// in the LLVM IR representation.
+///
+class SrcValueSDNode : public SDNode {
+ const Value *V;
+ friend class SelectionDAG;
+ /// Create a SrcValue for a general value.
+ explicit SrcValueSDNode(const Value *v)
+ : SDNode(ISD::SRCVALUE, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
+
+public:
+ /// getValue - return the contained Value.
+ const Value *getValue() const { return V; }
+
+ static bool classof(const SrcValueSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::SRCVALUE;
+ }
+};
+
+class MDNodeSDNode : public SDNode {
+ const MDNode *MD;
+ friend class SelectionDAG;
+ explicit MDNodeSDNode(const MDNode *md)
+ : SDNode(ISD::MDNODE_SDNODE, DebugLoc(), getSDVTList(MVT::Other)), MD(md) {}
+public:
+
+ const MDNode *getMD() const { return MD; }
+
+ static bool classof(const MDNodeSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::MDNODE_SDNODE;
+ }
+};
+
+
+class RegisterSDNode : public SDNode {
+ unsigned Reg;
+ friend class SelectionDAG;
+ RegisterSDNode(unsigned reg, EVT VT)
+ : SDNode(ISD::Register, DebugLoc(), getSDVTList(VT)), Reg(reg) {
+ }
+public:
+
+ unsigned getReg() const { return Reg; }
+
+ static bool classof(const RegisterSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::Register;
+ }
+};
+
+class RegisterMaskSDNode : public SDNode {
+ // The memory for RegMask is not owned by the node.
+ const uint32_t *RegMask;
+ friend class SelectionDAG;
+ RegisterMaskSDNode(const uint32_t *mask)
+ : SDNode(ISD::RegisterMask, DebugLoc(), getSDVTList(MVT::Untyped)),
+ RegMask(mask) {}
+public:
+
+ const uint32_t *getRegMask() const { return RegMask; }
+
+ static bool classof(const RegisterMaskSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::RegisterMask;
+ }
+};
+
+class BlockAddressSDNode : public SDNode {
+ const BlockAddress *BA;
+ int64_t Offset;
+ unsigned char TargetFlags;
+ friend class SelectionDAG;
+ BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
+ int64_t o, unsigned char Flags)
+ : SDNode(NodeTy, DebugLoc(), getSDVTList(VT)),
+ BA(ba), Offset(o), TargetFlags(Flags) {
+ }
+public:
+ const BlockAddress *getBlockAddress() const { return BA; }
+ int64_t getOffset() const { return Offset; }
+ unsigned char getTargetFlags() const { return TargetFlags; }
+
+ static bool classof(const BlockAddressSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::BlockAddress ||
+ N->getOpcode() == ISD::TargetBlockAddress;
+ }
+};
+
+class EHLabelSDNode : public SDNode {
+ SDUse Chain;
+ MCSymbol *Label;
+ friend class SelectionDAG;
+ EHLabelSDNode(DebugLoc dl, SDValue ch, MCSymbol *L)
+ : SDNode(ISD::EH_LABEL, dl, getSDVTList(MVT::Other)), Label(L) {
+ InitOperands(&Chain, ch);
+ }
+public:
+ MCSymbol *getLabel() const { return Label; }
+
+ static bool classof(const EHLabelSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::EH_LABEL;
+ }
+};
+
+class ExternalSymbolSDNode : public SDNode {
+ const char *Symbol;
+ unsigned char TargetFlags;
+
+ friend class SelectionDAG;
+ ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned char TF, EVT VT)
+ : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol,
+ DebugLoc(), getSDVTList(VT)), Symbol(Sym), TargetFlags(TF) {
+ }
+public:
+
+ const char *getSymbol() const { return Symbol; }
+ unsigned char getTargetFlags() const { return TargetFlags; }
+
+ static bool classof(const ExternalSymbolSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::ExternalSymbol ||
+ N->getOpcode() == ISD::TargetExternalSymbol;
+ }
+};
+
+class CondCodeSDNode : public SDNode {
+ ISD::CondCode Condition;
+ friend class SelectionDAG;
+ explicit CondCodeSDNode(ISD::CondCode Cond)
+ : SDNode(ISD::CONDCODE, DebugLoc(), getSDVTList(MVT::Other)),
+ Condition(Cond) {
+ }
+public:
+
+ ISD::CondCode get() const { return Condition; }
+
+ static bool classof(const CondCodeSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::CONDCODE;
+ }
+};
+
+/// CvtRndSatSDNode - NOTE: avoid using this node as this may disappear in the
+/// future and most targets don't support it.
+class CvtRndSatSDNode : public SDNode {
+ ISD::CvtCode CvtCode;
+ friend class SelectionDAG;
+ explicit CvtRndSatSDNode(EVT VT, DebugLoc dl, const SDValue *Ops,
+ unsigned NumOps, ISD::CvtCode Code)
+ : SDNode(ISD::CONVERT_RNDSAT, dl, getSDVTList(VT), Ops, NumOps),
+ CvtCode(Code) {
+ assert(NumOps == 5 && "wrong number of operations");
+ }
+public:
+ ISD::CvtCode getCvtCode() const { return CvtCode; }
+
+ static bool classof(const CvtRndSatSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::CONVERT_RNDSAT;
+ }
+};
+
+/// VTSDNode - This class is used to represent EVT's, which are used
+/// to parameterize some operations.
+class VTSDNode : public SDNode {
+ EVT ValueType;
+ friend class SelectionDAG;
+ explicit VTSDNode(EVT VT)
+ : SDNode(ISD::VALUETYPE, DebugLoc(), getSDVTList(MVT::Other)),
+ ValueType(VT) {
+ }
+public:
+
+ EVT getVT() const { return ValueType; }
+
+ static bool classof(const VTSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::VALUETYPE;
+ }
+};
+
+/// LSBaseSDNode - Base class for LoadSDNode and StoreSDNode
+///
+class LSBaseSDNode : public MemSDNode {
+ //! Operand array for load and store
+ /*!
+ \note Moving this array to the base class captures more
+ common functionality shared between LoadSDNode and
+ StoreSDNode
+ */
+ SDUse Ops[4];
+public:
+ LSBaseSDNode(ISD::NodeType NodeTy, DebugLoc dl, SDValue *Operands,
+ unsigned numOperands, SDVTList VTs, ISD::MemIndexedMode AM,
+ EVT MemVT, MachineMemOperand *MMO)
+ : MemSDNode(NodeTy, dl, VTs, MemVT, MMO) {
+ SubclassData |= AM << 2;
+ assert(getAddressingMode() == AM && "MemIndexedMode encoding error!");
+ InitOperands(Ops, Operands, numOperands);
+ assert((getOffset().getOpcode() == ISD::UNDEF || isIndexed()) &&
+ "Only indexed loads and stores have a non-undef offset operand");
+ }
+
+ const SDValue &getOffset() const {
+ return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
+ }
+
+ /// getAddressingMode - Return the addressing mode for this load or store:
+ /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
+ ISD::MemIndexedMode getAddressingMode() const {
+ return ISD::MemIndexedMode((SubclassData >> 2) & 7);
+ }
+
+ /// isIndexed - Return true if this is a pre/post inc/dec load/store.
+ bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
+
+ /// isUnindexed - Return true if this is NOT a pre/post inc/dec load/store.
+ bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
+
+ static bool classof(const LSBaseSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::LOAD ||
+ N->getOpcode() == ISD::STORE;
+ }
+};
+
+/// LoadSDNode - This class is used to represent ISD::LOAD nodes.
+///
+class LoadSDNode : public LSBaseSDNode {
+ friend class SelectionDAG;
+ LoadSDNode(SDValue *ChainPtrOff, DebugLoc dl, SDVTList VTs,
+ ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
+ MachineMemOperand *MMO)
+ : LSBaseSDNode(ISD::LOAD, dl, ChainPtrOff, 3,
+ VTs, AM, MemVT, MMO) {
+ SubclassData |= (unsigned short)ETy;
+ assert(getExtensionType() == ETy && "LoadExtType encoding error!");
+ assert(readMem() && "Load MachineMemOperand is not a load!");
+ assert(!writeMem() && "Load MachineMemOperand is a store!");
+ }
+public:
+
+ /// getExtensionType - Return whether this is a plain node,
+ /// or one of the varieties of value-extending loads.
+ ISD::LoadExtType getExtensionType() const {
+ return ISD::LoadExtType(SubclassData & 3);
+ }
+
+ const SDValue &getBasePtr() const { return getOperand(1); }
+ const SDValue &getOffset() const { return getOperand(2); }
+
+ static bool classof(const LoadSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::LOAD;
+ }
+};
+
+/// StoreSDNode - This class is used to represent ISD::STORE nodes.
+///
+class StoreSDNode : public LSBaseSDNode {
+ friend class SelectionDAG;
+ StoreSDNode(SDValue *ChainValuePtrOff, DebugLoc dl, SDVTList VTs,
+ ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
+ MachineMemOperand *MMO)
+ : LSBaseSDNode(ISD::STORE, dl, ChainValuePtrOff, 4,
+ VTs, AM, MemVT, MMO) {
+ SubclassData |= (unsigned short)isTrunc;
+ assert(isTruncatingStore() == isTrunc && "isTrunc encoding error!");
+ assert(!readMem() && "Store MachineMemOperand is a load!");
+ assert(writeMem() && "Store MachineMemOperand is not a store!");
+ }
+public:
+
+ /// isTruncatingStore - Return true if the op does a truncation before store.
+ /// For integers this is the same as doing a TRUNCATE and storing the result.
+ /// For floats, it is the same as doing an FP_ROUND and storing the result.
+ bool isTruncatingStore() const { return SubclassData & 1; }
+
+ const SDValue &getValue() const { return getOperand(1); }
+ const SDValue &getBasePtr() const { return getOperand(2); }
+ const SDValue &getOffset() const { return getOperand(3); }
+
+ static bool classof(const StoreSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->getOpcode() == ISD::STORE;
+ }
+};
+
+/// MachineSDNode - An SDNode that represents everything that will be needed
+/// to construct a MachineInstr. These nodes are created during the
+/// instruction selection proper phase.
+///
+class MachineSDNode : public SDNode {
+public:
+ typedef MachineMemOperand **mmo_iterator;
+
+private:
+ friend class SelectionDAG;
+ MachineSDNode(unsigned Opc, const DebugLoc DL, SDVTList VTs)
+ : SDNode(Opc, DL, VTs), MemRefs(0), MemRefsEnd(0) {}
+
+ /// LocalOperands - Operands for this instruction, if they fit here. If
+ /// they don't, this field is unused.
+ SDUse LocalOperands[4];
+
+ /// MemRefs - Memory reference descriptions for this instruction.
+ mmo_iterator MemRefs;
+ mmo_iterator MemRefsEnd;
+
+public:
+ mmo_iterator memoperands_begin() const { return MemRefs; }
+ mmo_iterator memoperands_end() const { return MemRefsEnd; }
+ bool memoperands_empty() const { return MemRefsEnd == MemRefs; }
+
+ /// setMemRefs - Assign this MachineSDNodes's memory reference descriptor
+ /// list. This does not transfer ownership.
+ void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
+ for (mmo_iterator MMI = NewMemRefs, MME = NewMemRefsEnd; MMI != MME; ++MMI)
+ assert(*MMI && "Null mem ref detected!");
+ MemRefs = NewMemRefs;
+ MemRefsEnd = NewMemRefsEnd;
+ }
+
+ static bool classof(const MachineSDNode *) { return true; }
+ static bool classof(const SDNode *N) {
+ return N->isMachineOpcode();
+ }
+};
+
+class SDNodeIterator : public std::iterator<std::forward_iterator_tag,
+ SDNode, ptrdiff_t> {
+ const SDNode *Node;
+ unsigned Operand;
+
+ SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
+public:
+ bool operator==(const SDNodeIterator& x) const {
+ return Operand == x.Operand;
+ }
+ bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
+
+ const SDNodeIterator &operator=(const SDNodeIterator &I) {
+ assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
+ Operand = I.Operand;
+ return *this;
+ }
+
+ pointer operator*() const {
+ return Node->getOperand(Operand).getNode();
+ }
+ pointer operator->() const { return operator*(); }
+
+ SDNodeIterator& operator++() { // Preincrement
+ ++Operand;
+ return *this;
+ }
+ SDNodeIterator operator++(int) { // Postincrement
+ SDNodeIterator tmp = *this; ++*this; return tmp;
+ }
+ size_t operator-(SDNodeIterator Other) const {
+ assert(Node == Other.Node &&
+ "Cannot compare iterators of two different nodes!");
+ return Operand - Other.Operand;
+ }
+
+ static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
+ static SDNodeIterator end (const SDNode *N) {
+ return SDNodeIterator(N, N->getNumOperands());
+ }
+
+ unsigned getOperand() const { return Operand; }
+ const SDNode *getNode() const { return Node; }
+};
+
+template <> struct GraphTraits<SDNode*> {
+ typedef SDNode NodeType;
+ typedef SDNodeIterator ChildIteratorType;
+ static inline NodeType *getEntryNode(SDNode *N) { return N; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return SDNodeIterator::begin(N);
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return SDNodeIterator::end(N);
+ }
+};
+
+/// LargestSDNode - The largest SDNode class.
+///
+typedef LoadSDNode LargestSDNode;
+
+/// MostAlignedSDNode - The SDNode class with the greatest alignment
+/// requirement.
+///
+typedef GlobalAddressSDNode MostAlignedSDNode;
+
+namespace ISD {
+ /// isNormalLoad - Returns true if the specified node is a non-extending
+ /// and unindexed load.
+ inline bool isNormalLoad(const SDNode *N) {
+ const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
+ return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
+ Ld->getAddressingMode() == ISD::UNINDEXED;
+ }
+
+ /// isNON_EXTLoad - Returns true if the specified node is a non-extending
+ /// load.
+ inline bool isNON_EXTLoad(const SDNode *N) {
+ return isa<LoadSDNode>(N) &&
+ cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
+ }
+
+ /// isEXTLoad - Returns true if the specified node is a EXTLOAD.
+ ///
+ inline bool isEXTLoad(const SDNode *N) {
+ return isa<LoadSDNode>(N) &&
+ cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
+ }
+
+ /// isSEXTLoad - Returns true if the specified node is a SEXTLOAD.
+ ///
+ inline bool isSEXTLoad(const SDNode *N) {
+ return isa<LoadSDNode>(N) &&
+ cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
+ }
+
+ /// isZEXTLoad - Returns true if the specified node is a ZEXTLOAD.
+ ///
+ inline bool isZEXTLoad(const SDNode *N) {
+ return isa<LoadSDNode>(N) &&
+ cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
+ }
+
+ /// isUNINDEXEDLoad - Returns true if the specified node is an unindexed load.
+ ///
+ inline bool isUNINDEXEDLoad(const SDNode *N) {
+ return isa<LoadSDNode>(N) &&
+ cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
+ }
+
+ /// isNormalStore - Returns true if the specified node is a non-truncating
+ /// and unindexed store.
+ inline bool isNormalStore(const SDNode *N) {
+ const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
+ return St && !St->isTruncatingStore() &&
+ St->getAddressingMode() == ISD::UNINDEXED;
+ }
+
+ /// isNON_TRUNCStore - Returns true if the specified node is a non-truncating
+ /// store.
+ inline bool isNON_TRUNCStore(const SDNode *N) {
+ return isa<StoreSDNode>(N) && !cast<StoreSDNode>(N)->isTruncatingStore();
+ }
+
+ /// isTRUNCStore - Returns true if the specified node is a truncating
+ /// store.
+ inline bool isTRUNCStore(const SDNode *N) {
+ return isa<StoreSDNode>(N) && cast<StoreSDNode>(N)->isTruncatingStore();
+ }
+
+ /// isUNINDEXEDStore - Returns true if the specified node is an
+ /// unindexed store.
+ inline bool isUNINDEXEDStore(const SDNode *N) {
+ return isa<StoreSDNode>(N) &&
+ cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
+ }
+}
+
+} // end llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/SlotIndexes.h b/include/llvm/CodeGen/SlotIndexes.h
new file mode 100644
index 00000000000..c52599b0f6f
--- /dev/null
+++ b/include/llvm/CodeGen/SlotIndexes.h
@@ -0,0 +1,649 @@
+//===- llvm/CodeGen/SlotIndexes.h - Slot indexes representation -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements SlotIndex and related classes. The purpose of SlotIndex
+// is to describe a position at which a register can become live, or cease to
+// be live.
+//
+// SlotIndex is mostly a proxy for entries of the SlotIndexList, a class which
+// is held is LiveIntervals and provides the real numbering. This allows
+// LiveIntervals to perform largely transparent renumbering.
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_SLOTINDEXES_H
+#define LLVM_CODEGEN_SLOTINDEXES_H
+
+#include "llvm/CodeGen/MachineInstrBundle.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/Allocator.h"
+
+namespace llvm {
+
+ /// This class represents an entry in the slot index list held in the
+ /// SlotIndexes pass. It should not be used directly. See the
+ /// SlotIndex & SlotIndexes classes for the public interface to this
+ /// information.
+ class IndexListEntry : public ilist_node<IndexListEntry> {
+ MachineInstr *mi;
+ unsigned index;
+
+ public:
+
+ IndexListEntry(MachineInstr *mi, unsigned index) : mi(mi), index(index) {}
+
+ MachineInstr* getInstr() const { return mi; }
+ void setInstr(MachineInstr *mi) {
+ this->mi = mi;
+ }
+
+ unsigned getIndex() const { return index; }
+ void setIndex(unsigned index) {
+ this->index = index;
+ }
+
+ };
+
+ template <>
+ struct ilist_traits<IndexListEntry> : public ilist_default_traits<IndexListEntry> {
+ private:
+ mutable ilist_half_node<IndexListEntry> Sentinel;
+ public:
+ IndexListEntry *createSentinel() const {
+ return static_cast<IndexListEntry*>(&Sentinel);
+ }
+ void destroySentinel(IndexListEntry *) const {}
+
+ IndexListEntry *provideInitialHead() const { return createSentinel(); }
+ IndexListEntry *ensureHead(IndexListEntry*) const { return createSentinel(); }
+ static void noteHead(IndexListEntry*, IndexListEntry*) {}
+ void deleteNode(IndexListEntry *N) {}
+
+ private:
+ void createNode(const IndexListEntry &);
+ };
+
+ /// SlotIndex - An opaque wrapper around machine indexes.
+ class SlotIndex {
+ friend class SlotIndexes;
+
+ enum Slot {
+ /// Basic block boundary. Used for live ranges entering and leaving a
+ /// block without being live in the layout neighbor. Also used as the
+ /// def slot of PHI-defs.
+ Slot_Block,
+
+ /// Early-clobber register use/def slot. A live range defined at
+ /// Slot_EarlyCLobber interferes with normal live ranges killed at
+ /// Slot_Register. Also used as the kill slot for live ranges tied to an
+ /// early-clobber def.
+ Slot_EarlyClobber,
+
+ /// Normal register use/def slot. Normal instructions kill and define
+ /// register live ranges at this slot.
+ Slot_Register,
+
+ /// Dead def kill point. Kill slot for a live range that is defined by
+ /// the same instruction (Slot_Register or Slot_EarlyClobber), but isn't
+ /// used anywhere.
+ Slot_Dead,
+
+ Slot_Count
+ };
+
+ PointerIntPair<IndexListEntry*, 2, unsigned> lie;
+
+ SlotIndex(IndexListEntry *entry, unsigned slot)
+ : lie(entry, slot) {}
+
+ IndexListEntry* listEntry() const {
+ assert(isValid() && "Attempt to compare reserved index.");
+ return lie.getPointer();
+ }
+
+ int getIndex() const {
+ return listEntry()->getIndex() | getSlot();
+ }
+
+ /// Returns the slot for this SlotIndex.
+ Slot getSlot() const {
+ return static_cast<Slot>(lie.getInt());
+ }
+
+ public:
+ enum {
+ /// The default distance between instructions as returned by distance().
+ /// This may vary as instructions are inserted and removed.
+ InstrDist = 4 * Slot_Count
+ };
+
+ /// Construct an invalid index.
+ SlotIndex() : lie(0, 0) {}
+
+ // Construct a new slot index from the given one, and set the slot.
+ SlotIndex(const SlotIndex &li, Slot s) : lie(li.listEntry(), unsigned(s)) {
+ assert(lie.getPointer() != 0 &&
+ "Attempt to construct index with 0 pointer.");
+ }
+
+ /// Returns true if this is a valid index. Invalid indicies do
+ /// not point into an index table, and cannot be compared.
+ bool isValid() const {
+ return lie.getPointer();
+ }
+
+ /// Return true for a valid index.
+ operator bool() const { return isValid(); }
+
+ /// Print this index to the given raw_ostream.
+ void print(raw_ostream &os) const;
+
+ /// Dump this index to stderr.
+ void dump() const;
+
+ /// Compare two SlotIndex objects for equality.
+ bool operator==(SlotIndex other) const {
+ return lie == other.lie;
+ }
+ /// Compare two SlotIndex objects for inequality.
+ bool operator!=(SlotIndex other) const {
+ return lie != other.lie;
+ }
+
+ /// Compare two SlotIndex objects. Return true if the first index
+ /// is strictly lower than the second.
+ bool operator<(SlotIndex other) const {
+ return getIndex() < other.getIndex();
+ }
+ /// Compare two SlotIndex objects. Return true if the first index
+ /// is lower than, or equal to, the second.
+ bool operator<=(SlotIndex other) const {
+ return getIndex() <= other.getIndex();
+ }
+
+ /// Compare two SlotIndex objects. Return true if the first index
+ /// is greater than the second.
+ bool operator>(SlotIndex other) const {
+ return getIndex() > other.getIndex();
+ }
+
+ /// Compare two SlotIndex objects. Return true if the first index
+ /// is greater than, or equal to, the second.
+ bool operator>=(SlotIndex other) const {
+ return getIndex() >= other.getIndex();
+ }
+
+ /// isSameInstr - Return true if A and B refer to the same instruction.
+ static bool isSameInstr(SlotIndex A, SlotIndex B) {
+ return A.lie.getPointer() == B.lie.getPointer();
+ }
+
+ /// isEarlierInstr - Return true if A refers to an instruction earlier than
+ /// B. This is equivalent to A < B && !isSameInstr(A, B).
+ static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
+ return A.listEntry()->getIndex() < B.listEntry()->getIndex();
+ }
+
+ /// Return the distance from this index to the given one.
+ int distance(SlotIndex other) const {
+ return other.getIndex() - getIndex();
+ }
+
+ /// isBlock - Returns true if this is a block boundary slot.
+ bool isBlock() const { return getSlot() == Slot_Block; }
+
+ /// isEarlyClobber - Returns true if this is an early-clobber slot.
+ bool isEarlyClobber() const { return getSlot() == Slot_EarlyClobber; }
+
+ /// isRegister - Returns true if this is a normal register use/def slot.
+ /// Note that early-clobber slots may also be used for uses and defs.
+ bool isRegister() const { return getSlot() == Slot_Register; }
+
+ /// isDead - Returns true if this is a dead def kill slot.
+ bool isDead() const { return getSlot() == Slot_Dead; }
+
+ /// Returns the base index for associated with this index. The base index
+ /// is the one associated with the Slot_Block slot for the instruction
+ /// pointed to by this index.
+ SlotIndex getBaseIndex() const {
+ return SlotIndex(listEntry(), Slot_Block);
+ }
+
+ /// Returns the boundary index for associated with this index. The boundary
+ /// index is the one associated with the Slot_Block slot for the instruction
+ /// pointed to by this index.
+ SlotIndex getBoundaryIndex() const {
+ return SlotIndex(listEntry(), Slot_Dead);
+ }
+
+ /// Returns the register use/def slot in the current instruction for a
+ /// normal or early-clobber def.
+ SlotIndex getRegSlot(bool EC = false) const {
+ return SlotIndex(listEntry(), EC ? Slot_EarlyClobber : Slot_Register);
+ }
+
+ /// Returns the dead def kill slot for the current instruction.
+ SlotIndex getDeadSlot() const {
+ return SlotIndex(listEntry(), Slot_Dead);
+ }
+
+ /// Returns the next slot in the index list. This could be either the
+ /// next slot for the instruction pointed to by this index or, if this
+ /// index is a STORE, the first slot for the next instruction.
+ /// WARNING: This method is considerably more expensive than the methods
+ /// that return specific slots (getUseIndex(), etc). If you can - please
+ /// use one of those methods.
+ SlotIndex getNextSlot() const {
+ Slot s = getSlot();
+ if (s == Slot_Dead) {
+ return SlotIndex(listEntry()->getNextNode(), Slot_Block);
+ }
+ return SlotIndex(listEntry(), s + 1);
+ }
+
+ /// Returns the next index. This is the index corresponding to the this
+ /// index's slot, but for the next instruction.
+ SlotIndex getNextIndex() const {
+ return SlotIndex(listEntry()->getNextNode(), getSlot());
+ }
+
+ /// Returns the previous slot in the index list. This could be either the
+ /// previous slot for the instruction pointed to by this index or, if this
+ /// index is a Slot_Block, the last slot for the previous instruction.
+ /// WARNING: This method is considerably more expensive than the methods
+ /// that return specific slots (getUseIndex(), etc). If you can - please
+ /// use one of those methods.
+ SlotIndex getPrevSlot() const {
+ Slot s = getSlot();
+ if (s == Slot_Block) {
+ return SlotIndex(listEntry()->getPrevNode(), Slot_Dead);
+ }
+ return SlotIndex(listEntry(), s - 1);
+ }
+
+ /// Returns the previous index. This is the index corresponding to this
+ /// index's slot, but for the previous instruction.
+ SlotIndex getPrevIndex() const {
+ return SlotIndex(listEntry()->getPrevNode(), getSlot());
+ }
+
+ };
+
+ template <> struct isPodLike<SlotIndex> { static const bool value = true; };
+
+
+ inline raw_ostream& operator<<(raw_ostream &os, SlotIndex li) {
+ li.print(os);
+ return os;
+ }
+
+ typedef std::pair<SlotIndex, MachineBasicBlock*> IdxMBBPair;
+
+ inline bool operator<(SlotIndex V, const IdxMBBPair &IM) {
+ return V < IM.first;
+ }
+
+ inline bool operator<(const IdxMBBPair &IM, SlotIndex V) {
+ return IM.first < V;
+ }
+
+ struct Idx2MBBCompare {
+ bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
+ return LHS.first < RHS.first;
+ }
+ };
+
+ /// SlotIndexes pass.
+ ///
+ /// This pass assigns indexes to each instruction.
+ class SlotIndexes : public MachineFunctionPass {
+ private:
+
+ typedef ilist<IndexListEntry> IndexList;
+ IndexList indexList;
+
+ MachineFunction *mf;
+
+ typedef DenseMap<const MachineInstr*, SlotIndex> Mi2IndexMap;
+ Mi2IndexMap mi2iMap;
+
+ /// MBBRanges - Map MBB number to (start, stop) indexes.
+ SmallVector<std::pair<SlotIndex, SlotIndex>, 8> MBBRanges;
+
+ /// Idx2MBBMap - Sorted list of pairs of index of first instruction
+ /// and MBB id.
+ SmallVector<IdxMBBPair, 8> idx2MBBMap;
+
+ // IndexListEntry allocator.
+ BumpPtrAllocator ileAllocator;
+
+ IndexListEntry* createEntry(MachineInstr *mi, unsigned index) {
+ IndexListEntry *entry =
+ static_cast<IndexListEntry*>(
+ ileAllocator.Allocate(sizeof(IndexListEntry),
+ alignOf<IndexListEntry>()));
+
+ new (entry) IndexListEntry(mi, index);
+
+ return entry;
+ }
+
+ /// Renumber locally after inserting curItr.
+ void renumberIndexes(IndexList::iterator curItr);
+
+ public:
+ static char ID;
+
+ SlotIndexes() : MachineFunctionPass(ID) {
+ initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
+ }
+
+ virtual void getAnalysisUsage(AnalysisUsage &au) const;
+ virtual void releaseMemory();
+
+ virtual bool runOnMachineFunction(MachineFunction &fn);
+
+ /// Dump the indexes.
+ void dump() const;
+
+ /// Renumber the index list, providing space for new instructions.
+ void renumberIndexes();
+
+ /// Returns the zero index for this analysis.
+ SlotIndex getZeroIndex() {
+ assert(indexList.front().getIndex() == 0 && "First index is not 0?");
+ return SlotIndex(&indexList.front(), 0);
+ }
+
+ /// Returns the base index of the last slot in this analysis.
+ SlotIndex getLastIndex() {
+ return SlotIndex(&indexList.back(), 0);
+ }
+
+ /// Returns true if the given machine instr is mapped to an index,
+ /// otherwise returns false.
+ bool hasIndex(const MachineInstr *instr) const {
+ return mi2iMap.count(instr);
+ }
+
+ /// Returns the base index for the given instruction.
+ SlotIndex getInstructionIndex(const MachineInstr *MI) const {
+ // Instructions inside a bundle have the same number as the bundle itself.
+ Mi2IndexMap::const_iterator itr = mi2iMap.find(getBundleStart(MI));
+ assert(itr != mi2iMap.end() && "Instruction not found in maps.");
+ return itr->second;
+ }
+
+ /// Returns the instruction for the given index, or null if the given
+ /// index has no instruction associated with it.
+ MachineInstr* getInstructionFromIndex(SlotIndex index) const {
+ return index.isValid() ? index.listEntry()->getInstr() : 0;
+ }
+
+ /// Returns the next non-null index.
+ SlotIndex getNextNonNullIndex(SlotIndex index) {
+ IndexList::iterator itr(index.listEntry());
+ ++itr;
+ while (itr != indexList.end() && itr->getInstr() == 0) { ++itr; }
+ return SlotIndex(itr, index.getSlot());
+ }
+
+ /// getIndexBefore - Returns the index of the last indexed instruction
+ /// before MI, or the start index of its basic block.
+ /// MI is not required to have an index.
+ SlotIndex getIndexBefore(const MachineInstr *MI) const {
+ const MachineBasicBlock *MBB = MI->getParent();
+ assert(MBB && "MI must be inserted inna basic block");
+ MachineBasicBlock::const_iterator I = MI, B = MBB->begin();
+ for (;;) {
+ if (I == B)
+ return getMBBStartIdx(MBB);
+ --I;
+ Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
+ if (MapItr != mi2iMap.end())
+ return MapItr->second;
+ }
+ }
+
+ /// getIndexAfter - Returns the index of the first indexed instruction
+ /// after MI, or the end index of its basic block.
+ /// MI is not required to have an index.
+ SlotIndex getIndexAfter(const MachineInstr *MI) const {
+ const MachineBasicBlock *MBB = MI->getParent();
+ assert(MBB && "MI must be inserted inna basic block");
+ MachineBasicBlock::const_iterator I = MI, E = MBB->end();
+ for (;;) {
+ ++I;
+ if (I == E)
+ return getMBBEndIdx(MBB);
+ Mi2IndexMap::const_iterator MapItr = mi2iMap.find(I);
+ if (MapItr != mi2iMap.end())
+ return MapItr->second;
+ }
+ }
+
+ /// Return the (start,end) range of the given basic block number.
+ const std::pair<SlotIndex, SlotIndex> &
+ getMBBRange(unsigned Num) const {
+ return MBBRanges[Num];
+ }
+
+ /// Return the (start,end) range of the given basic block.
+ const std::pair<SlotIndex, SlotIndex> &
+ getMBBRange(const MachineBasicBlock *MBB) const {
+ return getMBBRange(MBB->getNumber());
+ }
+
+ /// Returns the first index in the given basic block number.
+ SlotIndex getMBBStartIdx(unsigned Num) const {
+ return getMBBRange(Num).first;
+ }
+
+ /// Returns the first index in the given basic block.
+ SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
+ return getMBBRange(mbb).first;
+ }
+
+ /// Returns the last index in the given basic block number.
+ SlotIndex getMBBEndIdx(unsigned Num) const {
+ return getMBBRange(Num).second;
+ }
+
+ /// Returns the last index in the given basic block.
+ SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
+ return getMBBRange(mbb).second;
+ }
+
+ /// Returns the basic block which the given index falls in.
+ MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
+ if (MachineInstr *MI = getInstructionFromIndex(index))
+ return MI->getParent();
+ SmallVectorImpl<IdxMBBPair>::const_iterator I =
+ std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), index);
+ // Take the pair containing the index
+ SmallVectorImpl<IdxMBBPair>::const_iterator J =
+ ((I != idx2MBBMap.end() && I->first > index) ||
+ (I == idx2MBBMap.end() && idx2MBBMap.size()>0)) ? (I-1): I;
+
+ assert(J != idx2MBBMap.end() && J->first <= index &&
+ index < getMBBEndIdx(J->second) &&
+ "index does not correspond to an MBB");
+ return J->second;
+ }
+
+ bool findLiveInMBBs(SlotIndex start, SlotIndex end,
+ SmallVectorImpl<MachineBasicBlock*> &mbbs) const {
+ SmallVectorImpl<IdxMBBPair>::const_iterator itr =
+ std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
+ bool resVal = false;
+
+ while (itr != idx2MBBMap.end()) {
+ if (itr->first >= end)
+ break;
+ mbbs.push_back(itr->second);
+ resVal = true;
+ ++itr;
+ }
+ return resVal;
+ }
+
+ /// Returns the MBB covering the given range, or null if the range covers
+ /// more than one basic block.
+ MachineBasicBlock* getMBBCoveringRange(SlotIndex start, SlotIndex end) const {
+
+ assert(start < end && "Backwards ranges not allowed.");
+
+ SmallVectorImpl<IdxMBBPair>::const_iterator itr =
+ std::lower_bound(idx2MBBMap.begin(), idx2MBBMap.end(), start);
+
+ if (itr == idx2MBBMap.end()) {
+ itr = prior(itr);
+ return itr->second;
+ }
+
+ // Check that we don't cross the boundary into this block.
+ if (itr->first < end)
+ return 0;
+
+ itr = prior(itr);
+
+ if (itr->first <= start)
+ return itr->second;
+
+ return 0;
+ }
+
+ /// Insert the given machine instruction into the mapping. Returns the
+ /// assigned index.
+ /// If Late is set and there are null indexes between mi's neighboring
+ /// instructions, create the new index after the null indexes instead of
+ /// before them.
+ SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late = false) {
+ assert(!mi->isInsideBundle() &&
+ "Instructions inside bundles should use bundle start's slot.");
+ assert(mi2iMap.find(mi) == mi2iMap.end() && "Instr already indexed.");
+ // Numbering DBG_VALUE instructions could cause code generation to be
+ // affected by debug information.
+ assert(!mi->isDebugValue() && "Cannot number DBG_VALUE instructions.");
+
+ assert(mi->getParent() != 0 && "Instr must be added to function.");
+
+ // Get the entries where mi should be inserted.
+ IndexList::iterator prevItr, nextItr;
+ if (Late) {
+ // Insert mi's index immediately before the following instruction.
+ nextItr = getIndexAfter(mi).listEntry();
+ prevItr = prior(nextItr);
+ } else {
+ // Insert mi's index immediately after the preceding instruction.
+ prevItr = getIndexBefore(mi).listEntry();
+ nextItr = llvm::next(prevItr);
+ }
+
+ // Get a number for the new instr, or 0 if there's no room currently.
+ // In the latter case we'll force a renumber later.
+ unsigned dist = ((nextItr->getIndex() - prevItr->getIndex())/2) & ~3u;
+ unsigned newNumber = prevItr->getIndex() + dist;
+
+ // Insert a new list entry for mi.
+ IndexList::iterator newItr =
+ indexList.insert(nextItr, createEntry(mi, newNumber));
+
+ // Renumber locally if we need to.
+ if (dist == 0)
+ renumberIndexes(newItr);
+
+ SlotIndex newIndex(&*newItr, SlotIndex::Slot_Block);
+ mi2iMap.insert(std::make_pair(mi, newIndex));
+ return newIndex;
+ }
+
+ /// Remove the given machine instruction from the mapping.
+ void removeMachineInstrFromMaps(MachineInstr *mi) {
+ // remove index -> MachineInstr and
+ // MachineInstr -> index mappings
+ Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
+ if (mi2iItr != mi2iMap.end()) {
+ IndexListEntry *miEntry(mi2iItr->second.listEntry());
+ assert(miEntry->getInstr() == mi && "Instruction indexes broken.");
+ // FIXME: Eventually we want to actually delete these indexes.
+ miEntry->setInstr(0);
+ mi2iMap.erase(mi2iItr);
+ }
+ }
+
+ /// ReplaceMachineInstrInMaps - Replacing a machine instr with a new one in
+ /// maps used by register allocator.
+ void replaceMachineInstrInMaps(MachineInstr *mi, MachineInstr *newMI) {
+ Mi2IndexMap::iterator mi2iItr = mi2iMap.find(mi);
+ if (mi2iItr == mi2iMap.end())
+ return;
+ SlotIndex replaceBaseIndex = mi2iItr->second;
+ IndexListEntry *miEntry(replaceBaseIndex.listEntry());
+ assert(miEntry->getInstr() == mi &&
+ "Mismatched instruction in index tables.");
+ miEntry->setInstr(newMI);
+ mi2iMap.erase(mi2iItr);
+ mi2iMap.insert(std::make_pair(newMI, replaceBaseIndex));
+ }
+
+ /// Add the given MachineBasicBlock into the maps.
+ void insertMBBInMaps(MachineBasicBlock *mbb) {
+ MachineFunction::iterator nextMBB =
+ llvm::next(MachineFunction::iterator(mbb));
+ IndexListEntry *startEntry = createEntry(0, 0);
+ IndexListEntry *stopEntry = createEntry(0, 0);
+ IndexListEntry *nextEntry = 0;
+
+ if (nextMBB == mbb->getParent()->end()) {
+ nextEntry = indexList.end();
+ } else {
+ nextEntry = getMBBStartIdx(nextMBB).listEntry();
+ }
+
+ indexList.insert(nextEntry, startEntry);
+ indexList.insert(nextEntry, stopEntry);
+
+ SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
+ SlotIndex endIdx(nextEntry, SlotIndex::Slot_Block);
+
+ assert(unsigned(mbb->getNumber()) == MBBRanges.size() &&
+ "Blocks must be added in order");
+ MBBRanges.push_back(std::make_pair(startIdx, endIdx));
+
+ idx2MBBMap.push_back(IdxMBBPair(startIdx, mbb));
+
+ renumberIndexes();
+ std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
+ }
+
+ };
+
+
+ // Specialize IntervalMapInfo for half-open slot index intervals.
+ template <typename> struct IntervalMapInfo;
+ template <> struct IntervalMapInfo<SlotIndex> {
+ static inline bool startLess(const SlotIndex &x, const SlotIndex &a) {
+ return x < a;
+ }
+ static inline bool stopLess(const SlotIndex &b, const SlotIndex &x) {
+ return b <= x;
+ }
+ static inline bool adjacent(const SlotIndex &a, const SlotIndex &b) {
+ return a == b;
+ }
+ };
+
+}
+
+#endif // LLVM_CODEGEN_SLOTINDEXES_H
diff --git a/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h b/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h
new file mode 100644
index 00000000000..9849e92f7de
--- /dev/null
+++ b/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h
@@ -0,0 +1,136 @@
+//==-- llvm/CodeGen/TargetLoweringObjectFileImpl.h - Object Info -*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements classes used to handle lowerings specific to common
+// object file formats.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_TARGETLOWERINGOBJECTFILEIMPL_H
+#define LLVM_CODEGEN_TARGETLOWERINGOBJECTFILEIMPL_H
+
+#include "llvm/MC/SectionKind.h"
+#include "llvm/Target/TargetLoweringObjectFile.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+ class MachineModuleInfo;
+ class Mangler;
+ class MCAsmInfo;
+ class MCExpr;
+ class MCSection;
+ class MCSectionMachO;
+ class MCSymbol;
+ class MCContext;
+ class GlobalValue;
+ class TargetMachine;
+
+
+class TargetLoweringObjectFileELF : public TargetLoweringObjectFile {
+ bool UseInitArray;
+
+public:
+ virtual ~TargetLoweringObjectFileELF() {}
+
+ virtual void emitPersonalityValue(MCStreamer &Streamer,
+ const TargetMachine &TM,
+ const MCSymbol *Sym) const;
+
+ /// getSectionForConstant - Given a constant with the SectionKind, return a
+ /// section that it should be placed in.
+ virtual const MCSection *getSectionForConstant(SectionKind Kind) const;
+
+
+ virtual const MCSection *
+ getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
+ Mangler *Mang, const TargetMachine &TM) const;
+
+ virtual const MCSection *
+ SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
+ Mangler *Mang, const TargetMachine &TM) const;
+
+ /// getExprForDwarfGlobalReference - Return an MCExpr to use for a reference
+ /// to the specified global variable from exception handling information.
+ ///
+ virtual const MCExpr *
+ getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
+ MachineModuleInfo *MMI, unsigned Encoding,
+ MCStreamer &Streamer) const;
+
+ // getCFIPersonalitySymbol - The symbol that gets passed to .cfi_personality.
+ virtual MCSymbol *
+ getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
+ MachineModuleInfo *MMI) const;
+
+ void InitializeELF(bool UseInitArray_);
+ virtual const MCSection *
+ getStaticCtorSection(unsigned Priority = 65535) const;
+ virtual const MCSection *
+ getStaticDtorSection(unsigned Priority = 65535) const;
+};
+
+
+
+class TargetLoweringObjectFileMachO : public TargetLoweringObjectFile {
+public:
+ virtual ~TargetLoweringObjectFileMachO() {}
+
+ /// emitModuleFlags - Emit the module flags that specify the garbage
+ /// collection information.
+ virtual void emitModuleFlags(MCStreamer &Streamer,
+ ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
+ Mangler *Mang, const TargetMachine &TM) const;
+
+ virtual const MCSection *
+ SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
+ Mangler *Mang, const TargetMachine &TM) const;
+
+ virtual const MCSection *
+ getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
+ Mangler *Mang, const TargetMachine &TM) const;
+
+ virtual const MCSection *getSectionForConstant(SectionKind Kind) const;
+
+ /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively
+ /// decide not to emit the UsedDirective for some symbols in llvm.used.
+ /// FIXME: REMOVE this (rdar://7071300)
+ virtual bool shouldEmitUsedDirectiveFor(const GlobalValue *GV,
+ Mangler *) const;
+
+ /// getExprForDwarfGlobalReference - The mach-o version of this method
+ /// defaults to returning a stub reference.
+ virtual const MCExpr *
+ getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
+ MachineModuleInfo *MMI, unsigned Encoding,
+ MCStreamer &Streamer) const;
+
+ // getCFIPersonalitySymbol - The symbol that gets passed to .cfi_personality.
+ virtual MCSymbol *
+ getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
+ MachineModuleInfo *MMI) const;
+};
+
+
+
+class TargetLoweringObjectFileCOFF : public TargetLoweringObjectFile {
+public:
+ virtual ~TargetLoweringObjectFileCOFF() {}
+
+ virtual const MCSection *
+ getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
+ Mangler *Mang, const TargetMachine &TM) const;
+
+ virtual const MCSection *
+ SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
+ Mangler *Mang, const TargetMachine &TM) const;
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/TargetSchedule.h b/include/llvm/CodeGen/TargetSchedule.h
new file mode 100644
index 00000000000..d2a26afe999
--- /dev/null
+++ b/include/llvm/CodeGen/TargetSchedule.h
@@ -0,0 +1,79 @@
+//===-- llvm/CodeGen/TargetSchedule.h - Sched Machine Model -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a wrapper around MCSchedModel that allows the interface to
+// benefit from information currently only available in TargetInstrInfo.
+// Ideally, the scheduling interface would be fully defined in the MC layer.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_TARGET_TARGETSCHEDMODEL_H
+#define LLVM_TARGET_TARGETSCHEDMODEL_H
+
+#include "llvm/MC/MCSchedule.h"
+#include "llvm/MC/MCInstrItineraries.h"
+
+namespace llvm {
+
+class TargetRegisterInfo;
+class TargetSubtargetInfo;
+class TargetInstrInfo;
+class MachineInstr;
+
+/// Provide an instruction scheduling machine model to CodeGen passes.
+class TargetSchedModel {
+ // For efficiency, hold a copy of the statically defined MCSchedModel for this
+ // processor.
+ MCSchedModel SchedModel;
+ InstrItineraryData InstrItins;
+ const TargetSubtargetInfo *STI;
+ const TargetInstrInfo *TII;
+public:
+ TargetSchedModel(): STI(0), TII(0) {}
+
+ void init(const MCSchedModel &sm, const TargetSubtargetInfo *sti,
+ const TargetInstrInfo *tii);
+
+ const TargetInstrInfo *getInstrInfo() const { return TII; }
+
+ /// Return true if this machine model includes an instruction-level scheduling
+ /// model. This is more detailed than the course grain IssueWidth and default
+ /// latency properties, but separate from the per-cycle itinerary data.
+ bool hasInstrSchedModel() const { return SchedModel.hasInstrSchedModel(); }
+
+ /// Return true if this machine model includes cycle-to-cycle itinerary
+ /// data. This models scheduling at each stage in the processor pipeline.
+ bool hasInstrItineraries() const { return !InstrItins.isEmpty(); }
+
+ /// computeOperandLatency - Compute and return the latency of the given data
+ /// dependent def and use when the operand indices are already known. UseMI
+ /// may be NULL for an unknown user.
+ ///
+ /// FindMin may be set to get the minimum vs. expected latency. Minimum
+ /// latency is used for scheduling groups, while expected latency is for
+ /// instruction cost and critical path.
+ unsigned computeOperandLatency(const MachineInstr *DefMI, unsigned DefOperIdx,
+ const MachineInstr *UseMI, unsigned UseOperIdx,
+ bool FindMin) const;
+
+ unsigned getProcessorID() const { return SchedModel.getProcessorID(); }
+
+private:
+ /// getDefLatency is a helper for computeOperandLatency. Return the
+ /// instruction's latency if operand lookup is not required.
+ /// Otherwise return -1.
+ int getDefLatency(const MachineInstr *DefMI, bool FindMin) const;
+
+ /// Return the MCSchedClassDesc for this instruction.
+ const MCSchedClassDesc *resolveSchedClass(const MachineInstr *MI) const;
+};
+
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/CodeGen/ValueTypes.h b/include/llvm/CodeGen/ValueTypes.h
new file mode 100644
index 00000000000..eb38cd33d16
--- /dev/null
+++ b/include/llvm/CodeGen/ValueTypes.h
@@ -0,0 +1,755 @@
+//===- CodeGen/ValueTypes.h - Low-Level Target independ. types --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the set of low-level target independent types which various
+// values in the code generator are. This allows the target specific behavior
+// of instructions to be described to target independent passes.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_VALUETYPES_H
+#define LLVM_CODEGEN_VALUETYPES_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
+#include <cassert>
+#include <string>
+
+namespace llvm {
+ class Type;
+ class LLVMContext;
+ struct EVT;
+
+ /// MVT - Machine Value Type. Every type that is supported natively by some
+ /// processor targeted by LLVM occurs here. This means that any legal value
+ /// type can be represented by a MVT.
+ class MVT {
+ public:
+ enum SimpleValueType {
+ // If you change this numbering, you must change the values in
+ // ValueTypes.td as well!
+ Other = 0, // This is a non-standard value
+ i1 = 1, // This is a 1 bit integer value
+ i8 = 2, // This is an 8 bit integer value
+ i16 = 3, // This is a 16 bit integer value
+ i32 = 4, // This is a 32 bit integer value
+ i64 = 5, // This is a 64 bit integer value
+ i128 = 6, // This is a 128 bit integer value
+
+ FIRST_INTEGER_VALUETYPE = i1,
+ LAST_INTEGER_VALUETYPE = i128,
+
+ f16 = 7, // This is a 16 bit floating point value
+ f32 = 8, // This is a 32 bit floating point value
+ f64 = 9, // This is a 64 bit floating point value
+ f80 = 10, // This is a 80 bit floating point value
+ f128 = 11, // This is a 128 bit floating point value
+ ppcf128 = 12, // This is a PPC 128-bit floating point value
+
+ FIRST_FP_VALUETYPE = f16,
+ LAST_FP_VALUETYPE = ppcf128,
+
+ v2i8 = 13, // 2 x i8
+ v4i8 = 14, // 4 x i8
+ v8i8 = 15, // 8 x i8
+ v16i8 = 16, // 16 x i8
+ v32i8 = 17, // 32 x i8
+ v2i16 = 18, // 2 x i16
+ v4i16 = 19, // 4 x i16
+ v8i16 = 20, // 8 x i16
+ v16i16 = 21, // 16 x i16
+ v2i32 = 22, // 2 x i32
+ v4i32 = 23, // 4 x i32
+ v8i32 = 24, // 8 x i32
+ v16i32 = 25, // 16 x i32
+ v1i64 = 26, // 1 x i64
+ v2i64 = 27, // 2 x i64
+ v4i64 = 28, // 4 x i64
+ v8i64 = 29, // 8 x i64
+ v16i64 = 30, // 16 x i64
+
+ v2f16 = 31, // 2 x f16
+ v2f32 = 32, // 2 x f32
+ v4f32 = 33, // 4 x f32
+ v8f32 = 34, // 8 x f32
+ v2f64 = 35, // 2 x f64
+ v4f64 = 36, // 4 x f64
+
+ FIRST_VECTOR_VALUETYPE = v2i8,
+ LAST_VECTOR_VALUETYPE = v4f64,
+ FIRST_INTEGER_VECTOR_VALUETYPE = v2i8,
+ LAST_INTEGER_VECTOR_VALUETYPE = v16i64,
+ FIRST_FP_VECTOR_VALUETYPE = v2f16,
+ LAST_FP_VECTOR_VALUETYPE = v4f64,
+
+ x86mmx = 37, // This is an X86 MMX value
+
+ Glue = 38, // This glues nodes together during pre-RA sched
+
+ isVoid = 39, // This has no value
+
+ Untyped = 40, // This value takes a register, but has
+ // unspecified type. The register class
+ // will be determined by the opcode.
+
+ LAST_VALUETYPE = 41, // This always remains at the end of the list.
+
+ // This is the current maximum for LAST_VALUETYPE.
+ // MVT::MAX_ALLOWED_VALUETYPE is used for asserts and to size bit vectors
+ // This value must be a multiple of 32.
+ MAX_ALLOWED_VALUETYPE = 64,
+
+ // Metadata - This is MDNode or MDString.
+ Metadata = 250,
+
+ // iPTRAny - An int value the size of the pointer of the current
+ // target to any address space. This must only be used internal to
+ // tblgen. Other than for overloading, we treat iPTRAny the same as iPTR.
+ iPTRAny = 251,
+
+ // vAny - A vector with any length and element size. This is used
+ // for intrinsics that have overloadings based on vector types.
+ // This is only for tblgen's consumption!
+ vAny = 252,
+
+ // fAny - Any floating-point or vector floating-point value. This is used
+ // for intrinsics that have overloadings based on floating-point types.
+ // This is only for tblgen's consumption!
+ fAny = 253,
+
+ // iAny - An integer or vector integer value of any bit width. This is
+ // used for intrinsics that have overloadings based on integer bit widths.
+ // This is only for tblgen's consumption!
+ iAny = 254,
+
+ // iPTR - An int value the size of the pointer of the current
+ // target. This should only be used internal to tblgen!
+ iPTR = 255,
+
+ // LastSimpleValueType - The greatest valid SimpleValueType value.
+ LastSimpleValueType = 255,
+
+ // INVALID_SIMPLE_VALUE_TYPE - Simple value types greater than or equal
+ // to this are considered extended value types.
+ INVALID_SIMPLE_VALUE_TYPE = LastSimpleValueType + 1
+ };
+
+ SimpleValueType SimpleTy;
+
+ MVT() : SimpleTy((SimpleValueType)(INVALID_SIMPLE_VALUE_TYPE)) {}
+ MVT(SimpleValueType SVT) : SimpleTy(SVT) { }
+
+ bool operator>(const MVT& S) const { return SimpleTy > S.SimpleTy; }
+ bool operator<(const MVT& S) const { return SimpleTy < S.SimpleTy; }
+ bool operator==(const MVT& S) const { return SimpleTy == S.SimpleTy; }
+ bool operator!=(const MVT& S) const { return SimpleTy != S.SimpleTy; }
+ bool operator>=(const MVT& S) const { return SimpleTy >= S.SimpleTy; }
+ bool operator<=(const MVT& S) const { return SimpleTy <= S.SimpleTy; }
+
+ /// isFloatingPoint - Return true if this is a FP, or a vector FP type.
+ bool isFloatingPoint() const {
+ return ((SimpleTy >= MVT::FIRST_FP_VALUETYPE &&
+ SimpleTy <= MVT::LAST_FP_VALUETYPE) ||
+ (SimpleTy >= MVT::FIRST_FP_VECTOR_VALUETYPE &&
+ SimpleTy <= MVT::LAST_FP_VECTOR_VALUETYPE));
+ }
+
+ /// isInteger - Return true if this is an integer, or a vector integer type.
+ bool isInteger() const {
+ return ((SimpleTy >= MVT::FIRST_INTEGER_VALUETYPE &&
+ SimpleTy <= MVT::LAST_INTEGER_VALUETYPE) ||
+ (SimpleTy >= MVT::FIRST_INTEGER_VECTOR_VALUETYPE &&
+ SimpleTy <= MVT::LAST_INTEGER_VECTOR_VALUETYPE));
+ }
+
+ /// isVector - Return true if this is a vector value type.
+ bool isVector() const {
+ return (SimpleTy >= MVT::FIRST_VECTOR_VALUETYPE &&
+ SimpleTy <= MVT::LAST_VECTOR_VALUETYPE);
+ }
+
+ /// is64BitVector - Return true if this is a 64-bit vector type.
+ bool is64BitVector() const {
+ return (SimpleTy == MVT::v8i8 || SimpleTy == MVT::v4i16 ||
+ SimpleTy == MVT::v2i32 || SimpleTy == MVT::v1i64 ||
+ SimpleTy == MVT::v2f32);
+ }
+
+ /// is128BitVector - Return true if this is a 128-bit vector type.
+ bool is128BitVector() const {
+ return (SimpleTy == MVT::v16i8 || SimpleTy == MVT::v8i16 ||
+ SimpleTy == MVT::v4i32 || SimpleTy == MVT::v2i64 ||
+ SimpleTy == MVT::v4f32 || SimpleTy == MVT::v2f64);
+ }
+
+ /// is256BitVector - Return true if this is a 256-bit vector type.
+ bool is256BitVector() const {
+ return (SimpleTy == MVT::v8f32 || SimpleTy == MVT::v4f64 ||
+ SimpleTy == MVT::v32i8 || SimpleTy == MVT::v16i16 ||
+ SimpleTy == MVT::v8i32 || SimpleTy == MVT::v4i64);
+ }
+
+ /// is512BitVector - Return true if this is a 512-bit vector type.
+ bool is512BitVector() const {
+ return (SimpleTy == MVT::v8i64 || SimpleTy == MVT::v16i32);
+ }
+
+ /// is1024BitVector - Return true if this is a 1024-bit vector type.
+ bool is1024BitVector() const {
+ return (SimpleTy == MVT::v16i64);
+ }
+
+ /// isPow2VectorType - Returns true if the given vector is a power of 2.
+ bool isPow2VectorType() const {
+ unsigned NElts = getVectorNumElements();
+ return !(NElts & (NElts - 1));
+ }
+
+ /// getPow2VectorType - Widens the length of the given vector MVT up to
+ /// the nearest power of 2 and returns that type.
+ MVT getPow2VectorType() const {
+ if (isPow2VectorType())
+ return *this;
+
+ unsigned NElts = getVectorNumElements();
+ unsigned Pow2NElts = 1 << Log2_32_Ceil(NElts);
+ return MVT::getVectorVT(getVectorElementType(), Pow2NElts);
+ }
+
+ /// getScalarType - If this is a vector type, return the element type,
+ /// otherwise return this.
+ MVT getScalarType() const {
+ return isVector() ? getVectorElementType() : *this;
+ }
+
+ MVT getVectorElementType() const {
+ switch (SimpleTy) {
+ default:
+ llvm_unreachable("Not a vector MVT!");
+ case v2i8 :
+ case v4i8 :
+ case v8i8 :
+ case v16i8:
+ case v32i8: return i8;
+ case v2i16:
+ case v4i16:
+ case v8i16:
+ case v16i16: return i16;
+ case v2i32:
+ case v4i32:
+ case v8i32:
+ case v16i32: return i32;
+ case v1i64:
+ case v2i64:
+ case v4i64:
+ case v8i64:
+ case v16i64: return i64;
+ case v2f16: return f16;
+ case v2f32:
+ case v4f32:
+ case v8f32: return f32;
+ case v2f64:
+ case v4f64: return f64;
+ }
+ }
+
+ unsigned getVectorNumElements() const {
+ switch (SimpleTy) {
+ default:
+ llvm_unreachable("Not a vector MVT!");
+ case v32i8: return 32;
+ case v16i8:
+ case v16i16:
+ case v16i32:
+ case v16i64:return 16;
+ case v8i8 :
+ case v8i16:
+ case v8i32:
+ case v8i64:
+ case v8f32: return 8;
+ case v4i8:
+ case v4i16:
+ case v4i32:
+ case v4i64:
+ case v4f32:
+ case v4f64: return 4;
+ case v2i8:
+ case v2i16:
+ case v2i32:
+ case v2i64:
+ case v2f16:
+ case v2f32:
+ case v2f64: return 2;
+ case v1i64: return 1;
+ }
+ }
+
+ unsigned getSizeInBits() const {
+ switch (SimpleTy) {
+ case iPTR:
+ llvm_unreachable("Value type size is target-dependent. Ask TLI.");
+ case iPTRAny:
+ case iAny:
+ case fAny:
+ llvm_unreachable("Value type is overloaded.");
+ default:
+ llvm_unreachable("getSizeInBits called on extended MVT.");
+ case i1 : return 1;
+ case i8 : return 8;
+ case i16 :
+ case f16:
+ case v2i8: return 16;
+ case f32 :
+ case i32 :
+ case v4i8:
+ case v2i16:
+ case v2f16: return 32;
+ case x86mmx:
+ case f64 :
+ case i64 :
+ case v8i8:
+ case v4i16:
+ case v2i32:
+ case v1i64:
+ case v2f32: return 64;
+ case f80 : return 80;
+ case f128:
+ case ppcf128:
+ case i128:
+ case v16i8:
+ case v8i16:
+ case v4i32:
+ case v2i64:
+ case v4f32:
+ case v2f64: return 128;
+ case v32i8:
+ case v16i16:
+ case v8i32:
+ case v4i64:
+ case v8f32:
+ case v4f64: return 256;
+ case v16i32:
+ case v8i64: return 512;
+ case v16i64:return 1024;
+ }
+ }
+
+ /// getStoreSize - Return the number of bytes overwritten by a store
+ /// of the specified value type.
+ unsigned getStoreSize() const {
+ return (getSizeInBits() + 7) / 8;
+ }
+
+ /// getStoreSizeInBits - Return the number of bits overwritten by a store
+ /// of the specified value type.
+ unsigned getStoreSizeInBits() const {
+ return getStoreSize() * 8;
+ }
+
+ static MVT getFloatingPointVT(unsigned BitWidth) {
+ switch (BitWidth) {
+ default:
+ llvm_unreachable("Bad bit width!");
+ case 16:
+ return MVT::f16;
+ case 32:
+ return MVT::f32;
+ case 64:
+ return MVT::f64;
+ case 80:
+ return MVT::f80;
+ case 128:
+ return MVT::f128;
+ }
+ }
+
+ static MVT getIntegerVT(unsigned BitWidth) {
+ switch (BitWidth) {
+ default:
+ return (MVT::SimpleValueType)(MVT::INVALID_SIMPLE_VALUE_TYPE);
+ case 1:
+ return MVT::i1;
+ case 8:
+ return MVT::i8;
+ case 16:
+ return MVT::i16;
+ case 32:
+ return MVT::i32;
+ case 64:
+ return MVT::i64;
+ case 128:
+ return MVT::i128;
+ }
+ }
+
+ static MVT getVectorVT(MVT VT, unsigned NumElements) {
+ switch (VT.SimpleTy) {
+ default:
+ break;
+ case MVT::i8:
+ if (NumElements == 2) return MVT::v2i8;
+ if (NumElements == 4) return MVT::v4i8;
+ if (NumElements == 8) return MVT::v8i8;
+ if (NumElements == 16) return MVT::v16i8;
+ if (NumElements == 32) return MVT::v32i8;
+ break;
+ case MVT::i16:
+ if (NumElements == 2) return MVT::v2i16;
+ if (NumElements == 4) return MVT::v4i16;
+ if (NumElements == 8) return MVT::v8i16;
+ if (NumElements == 16) return MVT::v16i16;
+ break;
+ case MVT::i32:
+ if (NumElements == 2) return MVT::v2i32;
+ if (NumElements == 4) return MVT::v4i32;
+ if (NumElements == 8) return MVT::v8i32;
+ if (NumElements == 16) return MVT::v16i32;
+ break;
+ case MVT::i64:
+ if (NumElements == 1) return MVT::v1i64;
+ if (NumElements == 2) return MVT::v2i64;
+ if (NumElements == 4) return MVT::v4i64;
+ if (NumElements == 8) return MVT::v8i64;
+ if (NumElements == 16) return MVT::v16i64;
+ break;
+ case MVT::f16:
+ if (NumElements == 2) return MVT::v2f16;
+ break;
+ case MVT::f32:
+ if (NumElements == 2) return MVT::v2f32;
+ if (NumElements == 4) return MVT::v4f32;
+ if (NumElements == 8) return MVT::v8f32;
+ break;
+ case MVT::f64:
+ if (NumElements == 2) return MVT::v2f64;
+ if (NumElements == 4) return MVT::v4f64;
+ break;
+ }
+ return (MVT::SimpleValueType)(MVT::INVALID_SIMPLE_VALUE_TYPE);
+ }
+ };
+
+
+ /// EVT - Extended Value Type. Capable of holding value types which are not
+ /// native for any processor (such as the i12345 type), as well as the types
+ /// a MVT can represent.
+ struct EVT {
+ private:
+ MVT V;
+ Type *LLVMTy;
+
+ public:
+ EVT() : V((MVT::SimpleValueType)(MVT::INVALID_SIMPLE_VALUE_TYPE)),
+ LLVMTy(0) {}
+ EVT(MVT::SimpleValueType SVT) : V(SVT), LLVMTy(0) { }
+ EVT(MVT S) : V(S), LLVMTy(0) {}
+
+ bool operator==(EVT VT) const {
+ return !(*this != VT);
+ }
+ bool operator!=(EVT VT) const {
+ if (V.SimpleTy != VT.V.SimpleTy)
+ return true;
+ if (V.SimpleTy == MVT::INVALID_SIMPLE_VALUE_TYPE)
+ return LLVMTy != VT.LLVMTy;
+ return false;
+ }
+
+ /// getFloatingPointVT - Returns the EVT that represents a floating point
+ /// type with the given number of bits. There are two floating point types
+ /// with 128 bits - this returns f128 rather than ppcf128.
+ static EVT getFloatingPointVT(unsigned BitWidth) {
+ return MVT::getFloatingPointVT(BitWidth);
+ }
+
+ /// getIntegerVT - Returns the EVT that represents an integer with the given
+ /// number of bits.
+ static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth) {
+ MVT M = MVT::getIntegerVT(BitWidth);
+ if (M.SimpleTy != MVT::INVALID_SIMPLE_VALUE_TYPE)
+ return M;
+ return getExtendedIntegerVT(Context, BitWidth);
+ }
+
+ /// getVectorVT - Returns the EVT that represents a vector NumElements in
+ /// length, where each element is of type VT.
+ static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements) {
+ MVT M = MVT::getVectorVT(VT.V, NumElements);
+ if (M.SimpleTy != MVT::INVALID_SIMPLE_VALUE_TYPE)
+ return M;
+ return getExtendedVectorVT(Context, VT, NumElements);
+ }
+
+ /// changeVectorElementTypeToInteger - Return a vector with the same number
+ /// of elements as this vector, but with the element type converted to an
+ /// integer type with the same bitwidth.
+ EVT changeVectorElementTypeToInteger() const {
+ if (!isSimple())
+ return changeExtendedVectorElementTypeToInteger();
+ MVT EltTy = getSimpleVT().getVectorElementType();
+ unsigned BitWidth = EltTy.getSizeInBits();
+ MVT IntTy = MVT::getIntegerVT(BitWidth);
+ MVT VecTy = MVT::getVectorVT(IntTy, getVectorNumElements());
+ assert(VecTy != MVT::INVALID_SIMPLE_VALUE_TYPE &&
+ "Simple vector VT not representable by simple integer vector VT!");
+ return VecTy;
+ }
+
+ /// isSimple - Test if the given EVT is simple (as opposed to being
+ /// extended).
+ bool isSimple() const {
+ return V.SimpleTy <= MVT::LastSimpleValueType;
+ }
+
+ /// isExtended - Test if the given EVT is extended (as opposed to
+ /// being simple).
+ bool isExtended() const {
+ return !isSimple();
+ }
+
+ /// isFloatingPoint - Return true if this is a FP, or a vector FP type.
+ bool isFloatingPoint() const {
+ return isSimple() ? V.isFloatingPoint() : isExtendedFloatingPoint();
+ }
+
+ /// isInteger - Return true if this is an integer, or a vector integer type.
+ bool isInteger() const {
+ return isSimple() ? V.isInteger() : isExtendedInteger();
+ }
+
+ /// isVector - Return true if this is a vector value type.
+ bool isVector() const {
+ return isSimple() ? V.isVector() : isExtendedVector();
+ }
+
+ /// is64BitVector - Return true if this is a 64-bit vector type.
+ bool is64BitVector() const {
+ return isSimple() ? V.is64BitVector() : isExtended64BitVector();
+ }
+
+ /// is128BitVector - Return true if this is a 128-bit vector type.
+ bool is128BitVector() const {
+ return isSimple() ? V.is128BitVector() : isExtended128BitVector();
+ }
+
+ /// is256BitVector - Return true if this is a 256-bit vector type.
+ bool is256BitVector() const {
+ return isSimple() ? V.is256BitVector() : isExtended256BitVector();
+ }
+
+ /// is512BitVector - Return true if this is a 512-bit vector type.
+ bool is512BitVector() const {
+ return isSimple() ? V.is512BitVector() : isExtended512BitVector();
+ }
+
+ /// is1024BitVector - Return true if this is a 1024-bit vector type.
+ bool is1024BitVector() const {
+ return isSimple() ? V.is1024BitVector() : isExtended1024BitVector();
+ }
+
+ /// isOverloaded - Return true if this is an overloaded type for TableGen.
+ bool isOverloaded() const {
+ return (V==MVT::iAny || V==MVT::fAny || V==MVT::vAny || V==MVT::iPTRAny);
+ }
+
+ /// isByteSized - Return true if the bit size is a multiple of 8.
+ bool isByteSized() const {
+ return (getSizeInBits() & 7) == 0;
+ }
+
+ /// isRound - Return true if the size is a power-of-two number of bytes.
+ bool isRound() const {
+ unsigned BitSize = getSizeInBits();
+ return BitSize >= 8 && !(BitSize & (BitSize - 1));
+ }
+
+ /// bitsEq - Return true if this has the same number of bits as VT.
+ bool bitsEq(EVT VT) const {
+ if (EVT::operator==(VT)) return true;
+ return getSizeInBits() == VT.getSizeInBits();
+ }
+
+ /// bitsGT - Return true if this has more bits than VT.
+ bool bitsGT(EVT VT) const {
+ if (EVT::operator==(VT)) return false;
+ return getSizeInBits() > VT.getSizeInBits();
+ }
+
+ /// bitsGE - Return true if this has no less bits than VT.
+ bool bitsGE(EVT VT) const {
+ if (EVT::operator==(VT)) return true;
+ return getSizeInBits() >= VT.getSizeInBits();
+ }
+
+ /// bitsLT - Return true if this has less bits than VT.
+ bool bitsLT(EVT VT) const {
+ if (EVT::operator==(VT)) return false;
+ return getSizeInBits() < VT.getSizeInBits();
+ }
+
+ /// bitsLE - Return true if this has no more bits than VT.
+ bool bitsLE(EVT VT) const {
+ if (EVT::operator==(VT)) return true;
+ return getSizeInBits() <= VT.getSizeInBits();
+ }
+
+
+ /// getSimpleVT - Return the SimpleValueType held in the specified
+ /// simple EVT.
+ MVT getSimpleVT() const {
+ assert(isSimple() && "Expected a SimpleValueType!");
+ return V;
+ }
+
+ /// getScalarType - If this is a vector type, return the element type,
+ /// otherwise return this.
+ EVT getScalarType() const {
+ return isVector() ? getVectorElementType() : *this;
+ }
+
+ /// getVectorElementType - Given a vector type, return the type of
+ /// each element.
+ EVT getVectorElementType() const {
+ assert(isVector() && "Invalid vector type!");
+ if (isSimple())
+ return V.getVectorElementType();
+ return getExtendedVectorElementType();
+ }
+
+ /// getVectorNumElements - Given a vector type, return the number of
+ /// elements it contains.
+ unsigned getVectorNumElements() const {
+ assert(isVector() && "Invalid vector type!");
+ if (isSimple())
+ return V.getVectorNumElements();
+ return getExtendedVectorNumElements();
+ }
+
+ /// getSizeInBits - Return the size of the specified value type in bits.
+ unsigned getSizeInBits() const {
+ if (isSimple())
+ return V.getSizeInBits();
+ return getExtendedSizeInBits();
+ }
+
+ /// getStoreSize - Return the number of bytes overwritten by a store
+ /// of the specified value type.
+ unsigned getStoreSize() const {
+ return (getSizeInBits() + 7) / 8;
+ }
+
+ /// getStoreSizeInBits - Return the number of bits overwritten by a store
+ /// of the specified value type.
+ unsigned getStoreSizeInBits() const {
+ return getStoreSize() * 8;
+ }
+
+ /// getRoundIntegerType - Rounds the bit-width of the given integer EVT up
+ /// to the nearest power of two (and at least to eight), and returns the
+ /// integer EVT with that number of bits.
+ EVT getRoundIntegerType(LLVMContext &Context) const {
+ assert(isInteger() && !isVector() && "Invalid integer type!");
+ unsigned BitWidth = getSizeInBits();
+ if (BitWidth <= 8)
+ return EVT(MVT::i8);
+ return getIntegerVT(Context, 1 << Log2_32_Ceil(BitWidth));
+ }
+
+ /// getHalfSizedIntegerVT - Finds the smallest simple value type that is
+ /// greater than or equal to half the width of this EVT. If no simple
+ /// value type can be found, an extended integer value type of half the
+ /// size (rounded up) is returned.
+ EVT getHalfSizedIntegerVT(LLVMContext &Context) const {
+ assert(isInteger() && !isVector() && "Invalid integer type!");
+ unsigned EVTSize = getSizeInBits();
+ for (unsigned IntVT = MVT::FIRST_INTEGER_VALUETYPE;
+ IntVT <= MVT::LAST_INTEGER_VALUETYPE; ++IntVT) {
+ EVT HalfVT = EVT((MVT::SimpleValueType)IntVT);
+ if (HalfVT.getSizeInBits() * 2 >= EVTSize)
+ return HalfVT;
+ }
+ return getIntegerVT(Context, (EVTSize + 1) / 2);
+ }
+
+ /// isPow2VectorType - Returns true if the given vector is a power of 2.
+ bool isPow2VectorType() const {
+ unsigned NElts = getVectorNumElements();
+ return !(NElts & (NElts - 1));
+ }
+
+ /// getPow2VectorType - Widens the length of the given vector EVT up to
+ /// the nearest power of 2 and returns that type.
+ EVT getPow2VectorType(LLVMContext &Context) const {
+ if (!isPow2VectorType()) {
+ unsigned NElts = getVectorNumElements();
+ unsigned Pow2NElts = 1 << Log2_32_Ceil(NElts);
+ return EVT::getVectorVT(Context, getVectorElementType(), Pow2NElts);
+ }
+ else {
+ return *this;
+ }
+ }
+
+ /// getEVTString - This function returns value type as a string,
+ /// e.g. "i32".
+ std::string getEVTString() const;
+
+ /// getTypeForEVT - This method returns an LLVM type corresponding to the
+ /// specified EVT. For integer types, this returns an unsigned type. Note
+ /// that this will abort for types that cannot be represented.
+ Type *getTypeForEVT(LLVMContext &Context) const;
+
+ /// getEVT - Return the value type corresponding to the specified type.
+ /// This returns all pointers as iPTR. If HandleUnknown is true, unknown
+ /// types are returned as Other, otherwise they are invalid.
+ static EVT getEVT(Type *Ty, bool HandleUnknown = false);
+
+ intptr_t getRawBits() {
+ if (isSimple())
+ return V.SimpleTy;
+ else
+ return (intptr_t)(LLVMTy);
+ }
+
+ /// compareRawBits - A meaningless but well-behaved order, useful for
+ /// constructing containers.
+ struct compareRawBits {
+ bool operator()(EVT L, EVT R) const {
+ if (L.V.SimpleTy == R.V.SimpleTy)
+ return L.LLVMTy < R.LLVMTy;
+ else
+ return L.V.SimpleTy < R.V.SimpleTy;
+ }
+ };
+
+ private:
+ // Methods for handling the Extended-type case in functions above.
+ // These are all out-of-line to prevent users of this header file
+ // from having a dependency on Type.h.
+ EVT changeExtendedVectorElementTypeToInteger() const;
+ static EVT getExtendedIntegerVT(LLVMContext &C, unsigned BitWidth);
+ static EVT getExtendedVectorVT(LLVMContext &C, EVT VT,
+ unsigned NumElements);
+ bool isExtendedFloatingPoint() const;
+ bool isExtendedInteger() const;
+ bool isExtendedVector() const;
+ bool isExtended64BitVector() const;
+ bool isExtended128BitVector() const;
+ bool isExtended256BitVector() const;
+ bool isExtended512BitVector() const;
+ bool isExtended1024BitVector() const;
+ EVT getExtendedVectorElementType() const;
+ unsigned getExtendedVectorNumElements() const;
+ unsigned getExtendedSizeInBits() const;
+ };
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/CodeGen/ValueTypes.td b/include/llvm/CodeGen/ValueTypes.td
new file mode 100644
index 00000000000..f4b75bd1b17
--- /dev/null
+++ b/include/llvm/CodeGen/ValueTypes.td
@@ -0,0 +1,83 @@
+//===- ValueTypes.td - ValueType definitions ---------------*- tablegen -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Value types - These values correspond to the register types defined in the
+// ValueTypes.h file. If you update anything here, you must update it there as
+// well!
+//
+//===----------------------------------------------------------------------===//
+
+class ValueType<int size, int value> {
+ string Namespace = "MVT";
+ int Size = size;
+ int Value = value;
+}
+
+def OtherVT: ValueType<0 , 0>; // "Other" value
+def i1 : ValueType<1 , 1>; // One bit boolean value
+def i8 : ValueType<8 , 2>; // 8-bit integer value
+def i16 : ValueType<16 , 3>; // 16-bit integer value
+def i32 : ValueType<32 , 4>; // 32-bit integer value
+def i64 : ValueType<64 , 5>; // 64-bit integer value
+def i128 : ValueType<128, 6>; // 128-bit integer value
+def f16 : ValueType<16 , 7>; // 32-bit floating point value
+def f32 : ValueType<32 , 8>; // 32-bit floating point value
+def f64 : ValueType<64 , 9>; // 64-bit floating point value
+def f80 : ValueType<80 , 10>; // 80-bit floating point value
+def f128 : ValueType<128, 11>; // 128-bit floating point value
+def ppcf128: ValueType<128, 12>; // PPC 128-bit floating point value
+
+def v2i8 : ValueType<16 , 13>; // 2 x i8 vector value
+def v4i8 : ValueType<32 , 14>; // 4 x i8 vector value
+def v8i8 : ValueType<64 , 15>; // 8 x i8 vector value
+def v16i8 : ValueType<128, 16>; // 16 x i8 vector value
+def v32i8 : ValueType<256, 17>; // 32 x i8 vector value
+def v2i16 : ValueType<32 , 18>; // 2 x i16 vector value
+def v4i16 : ValueType<64 , 19>; // 4 x i16 vector value
+def v8i16 : ValueType<128, 20>; // 8 x i16 vector value
+def v16i16 : ValueType<256, 21>; // 16 x i16 vector value
+def v2i32 : ValueType<64 , 22>; // 2 x i32 vector value
+def v4i32 : ValueType<128, 23>; // 4 x i32 vector value
+def v8i32 : ValueType<256, 24>; // 8 x i32 vector value
+def v16i32 : ValueType<512, 25>; // 16 x i32 vector value
+def v1i64 : ValueType<64 , 26>; // 1 x i64 vector value
+def v2i64 : ValueType<128, 27>; // 2 x i64 vector value
+def v4i64 : ValueType<256, 28>; // 4 x i64 vector value
+def v8i64 : ValueType<512, 29>; // 8 x i64 vector value
+def v16i64 : ValueType<1024,30>; // 16 x i64 vector value
+
+def v2f16 : ValueType<32 , 31>; // 2 x f16 vector value
+def v2f32 : ValueType<64 , 32>; // 2 x f32 vector value
+def v4f32 : ValueType<128, 33>; // 4 x f32 vector value
+def v8f32 : ValueType<256, 34>; // 8 x f32 vector value
+def v2f64 : ValueType<128, 35>; // 2 x f64 vector value
+def v4f64 : ValueType<256, 36>; // 4 x f64 vector value
+
+def x86mmx : ValueType<64 , 37>; // X86 MMX value
+def FlagVT : ValueType<0 , 38>; // Pre-RA sched glue
+def isVoid : ValueType<0 , 39>; // Produces no value
+def untyped: ValueType<8 , 40>; // Produces an untyped value
+
+def MetadataVT: ValueType<0, 250>; // Metadata
+
+// Pseudo valuetype mapped to the current pointer size to any address space.
+// Should only be used in TableGen.
+def iPTRAny : ValueType<0, 251>;
+
+// Pseudo valuetype to represent "vector of any size"
+def vAny : ValueType<0 , 252>;
+
+// Pseudo valuetype to represent "float of any format"
+def fAny : ValueType<0 , 253>;
+
+// Pseudo valuetype to represent "integer of any bit width"
+def iAny : ValueType<0 , 254>;
+
+// Pseudo valuetype mapped to the current pointer size.
+def iPTR : ValueType<0 , 255>;
diff --git a/include/llvm/Config/AsmParsers.def.in b/include/llvm/Config/AsmParsers.def.in
new file mode 100644
index 00000000000..d63675351c8
--- /dev/null
+++ b/include/llvm/Config/AsmParsers.def.in
@@ -0,0 +1,29 @@
+/*===- llvm/Config/AsmParsers.def - LLVM Assembly Parsers -------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file enumerates all of the assembly-language parsers *|
+|* supported by this build of LLVM. Clients of this file should define *|
+|* the LLVM_ASM_PARSER macro to be a function-like macro with a *|
+|* single parameter (the name of the target whose assembly can be *|
+|* generated); including this file will then enumerate all of the *|
+|* targets with assembly parsers. *|
+|* *|
+|* The set of targets supported by LLVM is generated at configuration *|
+|* time, at which point this header is generated. Do not modify this *|
+|* header directly. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_ASM_PARSER
+# error Please define the macro LLVM_ASM_PARSER(TargetName)
+#endif
+
+@LLVM_ENUM_ASM_PARSERS@
+
+#undef LLVM_ASM_PARSER
diff --git a/include/llvm/Config/AsmPrinters.def.in b/include/llvm/Config/AsmPrinters.def.in
new file mode 100644
index 00000000000..f0152a4aa97
--- /dev/null
+++ b/include/llvm/Config/AsmPrinters.def.in
@@ -0,0 +1,29 @@
+/*===- llvm/Config/AsmPrinters.def - LLVM Assembly Printers -----*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file enumerates all of the assembly-language printers *|
+|* supported by this build of LLVM. Clients of this file should define *|
+|* the LLVM_ASM_PRINTER macro to be a function-like macro with a *|
+|* single parameter (the name of the target whose assembly can be *|
+|* generated); including this file will then enumerate all of the *|
+|* targets with assembly printers. *|
+|* *|
+|* The set of targets supported by LLVM is generated at configuration *|
+|* time, at which point this header is generated. Do not modify this *|
+|* header directly. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_ASM_PRINTER
+# error Please define the macro LLVM_ASM_PRINTER(TargetName)
+#endif
+
+@LLVM_ENUM_ASM_PRINTERS@
+
+#undef LLVM_ASM_PRINTER
diff --git a/include/llvm/Config/Disassemblers.def.in b/include/llvm/Config/Disassemblers.def.in
new file mode 100644
index 00000000000..d3a9bbdeaea
--- /dev/null
+++ b/include/llvm/Config/Disassemblers.def.in
@@ -0,0 +1,29 @@
+/*===- llvm/Config/Disassemblers.def - LLVM Assembly Parsers ----*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file enumerates all of the assembly-language parsers *|
+|* supported by this build of LLVM. Clients of this file should define *|
+|* the LLVM_DISASSEMBLER macro to be a function-like macro with a *|
+|* single parameter (the name of the target whose assembly can be *|
+|* generated); including this file will then enumerate all of the *|
+|* targets with assembly parsers. *|
+|* *|
+|* The set of targets supported by LLVM is generated at configuration *|
+|* time, at which point this header is generated. Do not modify this *|
+|* header directly. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_DISASSEMBLER
+# error Please define the macro LLVM_DISASSEMBLER(TargetName)
+#endif
+
+@LLVM_ENUM_DISASSEMBLERS@
+
+#undef LLVM_DISASSEMBLER
diff --git a/include/llvm/Config/Targets.def.in b/include/llvm/Config/Targets.def.in
new file mode 100644
index 00000000000..d589ecee12c
--- /dev/null
+++ b/include/llvm/Config/Targets.def.in
@@ -0,0 +1,28 @@
+/*===- llvm/Config/Targets.def - LLVM Target Architectures ------*- C++ -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This file enumerates all of the target architectures supported by *|
+|* this build of LLVM. Clients of this file should define the *|
+|* LLVM_TARGET macro to be a function-like macro with a single *|
+|* parameter (the name of the target); including this file will then *|
+|* enumerate all of the targets. *|
+|* *|
+|* The set of targets supported by LLVM is generated at configuration *|
+|* time, at which point this header is generated. Do not modify this *|
+|* header directly. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_TARGET
+# error Please define the macro LLVM_TARGET(TargetName)
+#endif
+
+@LLVM_ENUM_TARGETS@
+
+#undef LLVM_TARGET
diff --git a/include/llvm/Config/config.h.cmake b/include/llvm/Config/config.h.cmake
new file mode 100644
index 00000000000..eb20b6470b3
--- /dev/null
+++ b/include/llvm/Config/config.h.cmake
@@ -0,0 +1,731 @@
+/**************************************
+** Created by Kevin from config.h.in **
+***************************************/
+
+#ifndef CONFIG_H
+#define CONFIG_H
+
+/* Bug report URL. */
+#define BUG_REPORT_URL "${BUG_REPORT_URL}"
+
+/* Relative directory for resource files */
+#define CLANG_RESOURCE_DIR "${CLANG_RESOURCE_DIR}"
+
+/* Directories clang will search for headers */
+#define C_INCLUDE_DIRS "${C_INCLUDE_DIRS}"
+
+/* Default <path> to all compiler invocations for --sysroot=<path>. */
+#undef DEFAULT_SYSROOT
+
+/* Define if position independent code is enabled */
+#cmakedefine ENABLE_PIC
+
+/* Define if timestamp information (e.g., __DATE__) is allowed */
+#cmakedefine ENABLE_TIMESTAMPS ${ENABLE_TIMESTAMPS}
+
+/* Directory where gcc is installed. */
+#undef GCC_INSTALL_PREFIX
+
+/* Define to 1 if you have the `arc4random' function. */
+#cmakedefine HAVE_ARC4RANDOM
+
+/* Define to 1 if you have the `argz_append' function. */
+#cmakedefine HAVE_ARGZ_APPEND ${HAVE_ARGZ_APPEND}
+
+/* Define to 1 if you have the `argz_create_sep' function. */
+#cmakedefine HAVE_ARGZ_CREATE_SEP ${HAVE_ARGZ_CREATE_SEP}
+
+/* Define to 1 if you have the <argz.h> header file. */
+#cmakedefine HAVE_ARGZ_H ${HAVE_ARGZ_H}
+
+/* Define to 1 if you have the `argz_insert' function. */
+#cmakedefine HAVE_ARGZ_INSERT ${HAVE_ARGZ_INSERT}
+
+/* Define to 1 if you have the `argz_next' function. */
+#cmakedefine HAVE_ARGZ_NEXT ${HAVE_ARGZ_NEXT}
+
+/* Define to 1 if you have the `argz_stringify' function. */
+#cmakedefine HAVE_ARGZ_STRINGIFY ${HAVE_ARGZ_STRINGIFY}
+
+/* Define to 1 if you have the <assert.h> header file. */
+#cmakedefine HAVE_ASSERT_H ${HAVE_ASSERT_H}
+
+/* Define to 1 if you have the `backtrace' function. */
+#cmakedefine HAVE_BACKTRACE ${HAVE_BACKTRACE}
+
+/* Define to 1 if you have the `bcopy' function. */
+#undef HAVE_BCOPY
+
+/* Define to 1 if you have the `ceilf' function. */
+#cmakedefine HAVE_CEILF ${HAVE_CEILF}
+
+/* Define if the neat program is available */
+#cmakedefine HAVE_CIRCO ${HAVE_CIRCO}
+
+/* Define to 1 if you have the `closedir' function. */
+#cmakedefine HAVE_CLOSEDIR ${HAVE_CLOSEDIR}
+
+/* Define to 1 if you have the <CrashReporterClient.h> header file. */
+#undef HAVE_CRASHREPORTERCLIENT_H
+
+/* Define if __crashreporter_info__ exists. */
+#undef HAVE_CRASHREPORTER_INFO
+
+/* Define to 1 if you have the <ctype.h> header file. */
+#cmakedefine HAVE_CTYPE_H ${HAVE_CTYPE_H}
+
+/* Define to 1 if you have the declaration of `strerror_s', and to 0 if you
+ don't. */
+#cmakedefine01 HAVE_DECL_STRERROR_S
+
+/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
+ */
+#cmakedefine HAVE_DIRENT_H ${HAVE_DIRENT_H}
+
+/* Define if you have the GNU dld library. */
+#undef HAVE_DLD
+
+/* Define to 1 if you have the <dld.h> header file. */
+#cmakedefine HAVE_DLD_H ${HAVE_DLD_H}
+
+/* Define to 1 if you have the `dlerror' function. */
+#cmakedefine HAVE_DLERROR ${HAVE_DLERROR}
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#cmakedefine HAVE_DLFCN_H ${HAVE_DLFCN_H}
+
+/* Define if dlopen() is available on this platform. */
+#cmakedefine HAVE_DLOPEN ${HAVE_DLOPEN}
+
+/* Define to 1 if you have the <dl.h> header file. */
+#cmakedefine HAVE_DL_H ${HAVE_DL_H}
+
+/* Define if the dot program is available */
+#cmakedefine HAVE_DOT ${HAVE_DOT}
+
+/* Define if the dotty program is available */
+#cmakedefine HAVE_DOTTY ${HAVE_DOTTY}
+
+/* Define if you have the _dyld_func_lookup function. */
+#undef HAVE_DYLD
+
+/* Define to 1 if you have the <errno.h> header file. */
+#cmakedefine HAVE_ERRNO_H ${HAVE_ERRNO_H}
+
+/* Define to 1 if the system has the type `error_t'. */
+#cmakedefine HAVE_ERROR_T ${HAVE_ERROR_T}
+
+/* Define to 1 if you have the <execinfo.h> header file. */
+#cmakedefine HAVE_EXECINFO_H ${HAVE_EXECINFO_H}
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#cmakedefine HAVE_FCNTL_H ${HAVE_FCNTL_H}
+
+/* Define if the neat program is available */
+#cmakedefine HAVE_FDP ${HAVE_FDP}
+
+/* Define to 1 if you have the <fenv.h> header file. */
+#cmakedefine HAVE_FENV_H ${HAVE_FENV_H}
+
+/* Define if libffi is available on this platform. */
+#cmakedefine HAVE_FFI_CALL ${HAVE_FFI_CALL}
+
+/* Define to 1 if you have the <ffi/ffi.h> header file. */
+#cmakedefine HAVE_FFI_FFI_H ${HAVE_FFI_FFI_H}
+
+/* Define to 1 if you have the <ffi.h> header file. */
+#cmakedefine HAVE_FFI_H ${HAVE_FFI_H}
+
+/* Set to 1 if the finite function is found in <ieeefp.h> */
+#cmakedefine HAVE_FINITE_IN_IEEEFP_H ${HAVE_FINITE_IN_IEEEFP_H}
+
+/* Define to 1 if you have the `floorf' function. */
+#cmakedefine HAVE_FLOORF ${HAVE_FLOORF}
+
+/* Define to 1 if you have the `fmodf' function. */
+#cmakedefine HAVE_FMODF ${HAVE_FMODF}
+
+/* Define to 1 if you have the `getcwd' function. */
+#cmakedefine HAVE_GETCWD ${HAVE_GETCWD}
+
+/* Define to 1 if you have the `getpagesize' function. */
+#cmakedefine HAVE_GETPAGESIZE ${HAVE_GETPAGESIZE}
+
+/* Define to 1 if you have the `getrlimit' function. */
+#cmakedefine HAVE_GETRLIMIT ${HAVE_GETRLIMIT}
+
+/* Define to 1 if you have the `getrusage' function. */
+#cmakedefine HAVE_GETRUSAGE ${HAVE_GETRUSAGE}
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#cmakedefine HAVE_GETTIMEOFDAY ${HAVE_GETTIMEOFDAY}
+
+/* Define if the Graphviz program is available */
+#cmakedefine HAVE_GRAPHVIZ ${HAVE_GRAPHVIZ}
+
+/* Define if the gv program is available */
+#cmakedefine HAVE_GV ${HAVE_GV}
+
+/* Define to 1 if you have the `index' function. */
+#cmakedefine HAVE_INDEX ${HAVE_INDEX}
+
+/* Define to 1 if the system has the type `int64_t'. */
+#cmakedefine HAVE_INT64_T ${HAVE_INT64_T}
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#cmakedefine HAVE_INTTYPES_H ${HAVE_INTTYPES_H}
+
+/* Define to 1 if you have the `isatty' function. */
+#cmakedefine HAVE_ISATTY 1
+
+/* Set to 1 if the isinf function is found in <cmath> */
+#cmakedefine HAVE_ISINF_IN_CMATH ${HAVE_ISINF_IN_CMATH}
+
+/* Set to 1 if the isinf function is found in <math.h> */
+#cmakedefine HAVE_ISINF_IN_MATH_H ${HAVE_ISINF_IN_MATH_H}
+
+/* Set to 1 if the isnan function is found in <cmath> */
+#cmakedefine HAVE_ISNAN_IN_CMATH ${HAVE_ISNAN_IN_CMATH}
+
+/* Set to 1 if the isnan function is found in <math.h> */
+#cmakedefine HAVE_ISNAN_IN_MATH_H ${HAVE_ISNAN_IN_MATH_H}
+
+/* Define if you have the libdl library or equivalent. */
+#cmakedefine HAVE_LIBDL ${HAVE_LIBDL}
+
+/* Define to 1 if you have the `imagehlp' library (-limagehlp). */
+#cmakedefine HAVE_LIBIMAGEHLP ${HAVE_LIBIMAGEHLP}
+
+/* Define to 1 if you have the `m' library (-lm). */
+#undef HAVE_LIBM
+
+/* Define to 1 if you have the `psapi' library (-lpsapi). */
+#cmakedefine HAVE_LIBPSAPI ${HAVE_LIBPSAPI}
+
+/* Define to 1 if you have the `pthread' library (-lpthread). */
+#cmakedefine HAVE_LIBPTHREAD ${HAVE_LIBPTHREAD}
+
+/* Define to 1 if you have the `udis86' library (-ludis86). */
+#undef HAVE_LIBUDIS86
+
+/* Define to 1 if you have the <limits.h> header file. */
+#cmakedefine HAVE_LIMITS_H ${HAVE_LIMITS_H}
+
+/* Define if you can use -Wl,-export-dynamic. */
+#define HAVE_LINK_EXPORT_DYNAMIC 1
+
+/* Define to 1 if you have the <link.h> header file. */
+#cmakedefine HAVE_LINK_H ${HAVE_LINK_H}
+
+/* Define if you can use -Wl,-R. to pass -R. to the linker, in order to add
+ the current directory to the dynamic linker search path. */
+#undef HAVE_LINK_R
+
+/* Define to 1 if you have the `longjmp' function. */
+#cmakedefine HAVE_LONGJMP ${HAVE_LONGJMP}
+
+/* Define to 1 if you have the <mach/mach.h> header file. */
+#cmakedefine HAVE_MACH_MACH_H ${HAVE_MACH_MACH_H}
+
+/* Define to 1 if you have the <mach-o/dyld.h> header file. */
+#cmakedefine HAVE_MACH_O_DYLD_H ${HAVE_MACH_O_DYLD_H}
+
+/* Define if mallinfo() is available on this platform. */
+#cmakedefine HAVE_MALLINFO ${HAVE_MALLINFO}
+
+/* Define to 1 if you have the <malloc.h> header file. */
+#cmakedefine HAVE_MALLOC_H ${HAVE_MALLOC_H}
+
+/* Define to 1 if you have the <malloc/malloc.h> header file. */
+#cmakedefine HAVE_MALLOC_MALLOC_H ${HAVE_MALLOC_MALLOC_H}
+
+/* Define to 1 if you have the `malloc_zone_statistics' function. */
+#cmakedefine HAVE_MALLOC_ZONE_STATISTICS ${HAVE_MALLOC_ZONE_STATISTICS}
+
+/* Define to 1 if you have the `memcpy' function. */
+#cmakedefine HAVE_MEMCPY ${HAVE_MEMCPY}
+
+/* Define to 1 if you have the `memmove' function. */
+#cmakedefine HAVE_MEMMOVE ${HAVE_MEMMOVE}
+
+/* Define to 1 if you have the <memory.h> header file. */
+#cmakedefine HAVE_MEMORY_H ${HAVE_MEMORY_H}
+
+/* Define to 1 if you have the `mkdtemp' function. */
+#cmakedefine HAVE_MKDTEMP ${HAVE_MKDTEMP}
+
+/* Define to 1 if you have the `mkstemp' function. */
+#cmakedefine HAVE_MKSTEMP ${HAVE_MKSTEMP}
+
+/* Define to 1 if you have the `mktemp' function. */
+#cmakedefine HAVE_MKTEMP ${HAVE_MKTEMP}
+
+/* Define to 1 if you have a working `mmap' system call. */
+#undef HAVE_MMAP
+
+/* Define if mmap() uses MAP_ANONYMOUS to map anonymous pages, or undefine if
+ it uses MAP_ANON */
+#undef HAVE_MMAP_ANONYMOUS
+
+/* Define if mmap() can map files into memory */
+#undef HAVE_MMAP_FILE
+
+/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
+#cmakedefine HAVE_NDIR_H ${HAVE_NDIR_H}
+
+/* Define to 1 if you have the `nearbyintf' function. */
+#cmakedefine HAVE_NEARBYINTF ${HAVE_NEARBYINTF}
+
+/* Define if the neat program is available */
+#cmakedefine HAVE_NEATO ${HAVE_NEATO}
+
+/* Define to 1 if you have the `opendir' function. */
+#cmakedefine HAVE_OPENDIR ${HAVE_OPENDIR}
+
+/* Define to 1 if you have the `posix_spawn' function. */
+#cmakedefine HAVE_POSIX_SPAWN ${HAVE_POSIX_SPAWN}
+
+/* Define to 1 if you have the `powf' function. */
+#cmakedefine HAVE_POWF ${HAVE_POWF}
+
+/* Define to 1 if you have the `pread' function. */
+#cmakedefine HAVE_PREAD ${HAVE_PREAD}
+
+/* Define if libtool can extract symbol lists from object files. */
+#undef HAVE_PRELOADED_SYMBOLS
+
+/* Define to have the %a format string */
+#undef HAVE_PRINTF_A
+
+/* Have pthread_getspecific */
+#cmakedefine HAVE_PTHREAD_GETSPECIFIC ${HAVE_PTHREAD_GETSPECIFIC}
+
+/* Define to 1 if you have the <pthread.h> header file. */
+#cmakedefine HAVE_PTHREAD_H ${HAVE_PTHREAD_H}
+
+/* Have pthread_mutex_lock */
+#cmakedefine HAVE_PTHREAD_MUTEX_LOCK ${HAVE_PTHREAD_MUTEX_LOCK}
+
+/* Have pthread_rwlock_init */
+#cmakedefine HAVE_PTHREAD_RWLOCK_INIT ${HAVE_PTHREAD_RWLOCK_INIT}
+
+/* Define to 1 if srand48/lrand48/drand48 exist in <stdlib.h> */
+#cmakedefine HAVE_RAND48 ${HAVE_RAND48}
+
+/* Define to 1 if you have the `readdir' function. */
+#cmakedefine HAVE_READDIR ${HAVE_READDIR}
+
+/* Define to 1 if you have the `realpath' function. */
+#undef HAVE_REALPATH
+
+/* Define to 1 if you have the `rindex' function. */
+#cmakedefine HAVE_RINDEX ${HAVE_RINDEX}
+
+/* Define to 1 if you have the `rintf' function. */
+#undef HAVE_RINTF
+
+/* Define to 1 if you have the `round' function. */
+#cmakedefine HAVE_ROUND ${HAVE_ROUND}
+
+/* Define to 1 if you have the `roundf' function. */
+#undef HAVE_ROUNDF
+
+/* Define to 1 if you have the `sbrk' function. */
+#cmakedefine HAVE_SBRK ${HAVE_SBRK}
+
+/* Define to 1 if you have the `setenv' function. */
+#cmakedefine HAVE_SETENV ${HAVE_SETENV}
+
+/* Define to 1 if you have the `setjmp' function. */
+#cmakedefine HAVE_SETJMP ${HAVE_SETJMP}
+
+/* Define to 1 if you have the <setjmp.h> header file. */
+#cmakedefine HAVE_SETJMP_H ${HAVE_SETJMP_H}
+
+/* Define to 1 if you have the `setrlimit' function. */
+#cmakedefine HAVE_SETRLIMIT ${HAVE_SETRLIMIT}
+
+/* Define if you have the shl_load function. */
+#undef HAVE_SHL_LOAD
+
+/* Define to 1 if you have the `siglongjmp' function. */
+#cmakedefine HAVE_SIGLONGJMP ${HAVE_SIGLONGJMP}
+
+/* Define to 1 if you have the <signal.h> header file. */
+#cmakedefine HAVE_SIGNAL_H ${HAVE_SIGNAL_H}
+
+/* Define to 1 if you have the `sigsetjmp' function. */
+#cmakedefine HAVE_SIGSETJMP ${HAVE_SIGSETJMP}
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#cmakedefine HAVE_STDINT_H ${HAVE_STDINT_H}
+
+/* Define to 1 if you have the <stdio.h> header file. */
+#cmakedefine HAVE_STDIO_H ${HAVE_STDIO_H}
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#cmakedefine HAVE_STDLIB_H ${HAVE_STDLIB_H}
+
+/* Set to 1 if the std::isinf function is found in <cmath> */
+#undef HAVE_STD_ISINF_IN_CMATH
+
+/* Set to 1 if the std::isnan function is found in <cmath> */
+#undef HAVE_STD_ISNAN_IN_CMATH
+
+/* Define to 1 if you have the `strchr' function. */
+#cmakedefine HAVE_STRCHR ${HAVE_STRCHR}
+
+/* Define to 1 if you have the `strcmp' function. */
+#cmakedefine HAVE_STRCMP ${HAVE_STRCMP}
+
+/* Define to 1 if you have the `strdup' function. */
+#cmakedefine HAVE_STRDUP ${HAVE_STRDUP}
+
+/* Define to 1 if you have the `strerror' function. */
+#cmakedefine HAVE_STRERROR ${HAVE_STRERROR}
+
+/* Define to 1 if you have the `strerror_r' function. */
+#cmakedefine HAVE_STRERROR_R ${HAVE_STRERROR_R}
+
+/* Define to 1 if you have the <strings.h> header file. */
+#cmakedefine HAVE_STRINGS_H ${HAVE_STRINGS_H}
+
+/* Define to 1 if you have the <string.h> header file. */
+#cmakedefine HAVE_STRING_H ${HAVE_STRING_H}
+
+/* Define to 1 if you have the `strrchr' function. */
+#cmakedefine HAVE_STRRCHR ${HAVE_STRRCHR}
+
+/* Define to 1 if you have the `strtof' function. */
+#cmakedefine HAVE_STRTOF ${HAVE_STRTOF}
+
+/* Define to 1 if you have the `strtoll' function. */
+#cmakedefine HAVE_STRTOLL ${HAVE_STRTOLL}
+
+/* Define to 1 if you have the `strtoq' function. */
+#cmakedefine HAVE_STRTOQ ${HAVE_STRTOQ}
+
+/* Define to 1 if you have the `sysconf' function. */
+#undef HAVE_SYSCONF
+
+/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
+ */
+#cmakedefine HAVE_SYS_DIR_H ${HAVE_SYS_DIR_H}
+
+/* Define to 1 if you have the <sys/dl.h> header file. */
+#cmakedefine HAVE_SYS_DL_H ${HAVE_SYS_DL_H}
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#cmakedefine HAVE_SYS_IOCTL_H ${HAVE_SYS_IOCTL_H}
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#cmakedefine HAVE_SYS_MMAN_H ${}
+
+/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
+ */
+#cmakedefine HAVE_SYS_NDIR_H ${HAVE_SYS_NDIR_H}
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#cmakedefine HAVE_SYS_PARAM_H ${HAVE_SYS_PARAM_H}
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#cmakedefine HAVE_SYS_RESOURCE_H ${HAVE_SYS_RESOURCE_H}
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#cmakedefine HAVE_SYS_STAT_H ${HAVE_SYS_STAT_H}
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#cmakedefine HAVE_SYS_TIME_H ${HAVE_SYS_TIME_H}
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#cmakedefine HAVE_SYS_TYPES_H ${HAVE_SYS_TYPES_H}
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#cmakedefine HAVE_SYS_UIO_H ${HAVE_SYS_UIO_H}
+
+/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
+#cmakedefine HAVE_SYS_WAIT_H ${HAVE_SYS_WAIT_H}
+
+/* Define to 1 if you have the <termios.h> header file. */
+#cmakedefine HAVE_TERMIOS_H ${HAVE_TERMIOS_H}
+
+/* Define if the neat program is available */
+#cmakedefine HAVE_TWOPI ${HAVE_TWOPI}
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#cmakedefine HAVE_UINT64_T ${HAVE_UINT64_T}
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#cmakedefine HAVE_UNISTD_H ${HAVE_UNISTD_H}
+
+/* Define to 1 if you have the <utime.h> header file. */
+#cmakedefine HAVE_UTIME_H ${HAVE_UTIME_H}
+
+/* Define to 1 if the system has the type `u_int64_t'. */
+#cmakedefine HAVE_U_INT64_T ${HAVE_U_INT64_T}
+
+/* Define to 1 if you have the <valgrind/valgrind.h> header file. */
+#cmakedefine HAVE_VALGRIND_VALGRIND_H ${HAVE_VALGRIND_VALGRIND_H}
+
+/* Define to 1 if you have the <windows.h> header file. */
+#cmakedefine HAVE_WINDOWS_H ${HAVE_WINDOWS_H}
+
+/* Define to 1 if you have the `writev' function. */
+#cmakedefine HAVE_WRITEV ${HAVE_WRITEV}
+
+/* Define if the xdot.py program is available */
+#cmakedefine HAVE_XDOT_PY ${HAVE_XDOT_PY}
+
+/* Have host's _alloca */
+#cmakedefine HAVE__ALLOCA ${HAVE__ALLOCA}
+
+/* Have host's __alloca */
+#cmakedefine HAVE___ALLOCA ${HAVE___ALLOCA}
+
+/* Have host's __ashldi3 */
+#cmakedefine HAVE___ASHLDI3 ${HAVE___ASHLDI3}
+
+/* Have host's __ashrdi3 */
+#cmakedefine HAVE___ASHRDI3 ${HAVE___ASHRDI3}
+
+/* Have host's __chkstk */
+#cmakedefine HAVE___CHKSTK ${HAVE___CHKSTK}
+
+/* Have host's __cmpdi2 */
+#cmakedefine HAVE___CMPDI2 ${HAVE___CMPDI2}
+
+/* Have host's __divdi3 */
+#cmakedefine HAVE___DIVDI3 ${HAVE___DIVDI3}
+
+/* Define to 1 if you have the `__dso_handle' function. */
+#undef HAVE___DSO_HANDLE
+
+/* Have host's __fixdfdi */
+#cmakedefine HAVE___FIXDFDI ${HAVE___FIXDFDI}
+
+/* Have host's __fixsfdi */
+#cmakedefine HAVE___FIXSFDI ${HAVE___FIXSFDI}
+
+/* Have host's __floatdidf */
+#cmakedefine HAVE___FLOATDIDF ${HAVE___FLOATDIDF}
+
+/* Have host's __lshrdi3 */
+#cmakedefine HAVE___LSHRDI3 ${HAVE___LSHRDI3}
+
+/* Have host's __main */
+#cmakedefine HAVE___MAIN ${HAVE___MAIN}
+
+/* Have host's __moddi3 */
+#cmakedefine HAVE___MODDI3 ${HAVE___MODDI3}
+
+/* Have host's __udivdi3 */
+#cmakedefine HAVE___UDIVDI3 ${HAVE___UDIVDI3}
+
+/* Have host's __umoddi3 */
+#cmakedefine HAVE___UMODDI3 ${HAVE___UMODDI3}
+
+/* Have host's ___chkstk */
+#cmakedefine HAVE____CHKSTK ${HAVE____CHKSTK}
+
+/* Linker version detected at compile time. */
+#undef HOST_LINK_VERSION
+
+/* Installation directory for binary executables */
+#cmakedefine LLVM_BINDIR "${LLVM_BINDIR}"
+
+/* Time at which LLVM was configured */
+#cmakedefine LLVM_CONFIGTIME "${LLVM_CONFIGTIME}"
+
+/* Installation directory for data files */
+#cmakedefine LLVM_DATADIR "${LLVM_DATADIR}"
+
+/* Target triple LLVM will generate code for by default */
+#cmakedefine LLVM_DEFAULT_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}"
+
+/* Installation directory for documentation */
+#cmakedefine LLVM_DOCSDIR "${LLVM_DOCSDIR}"
+
+/* Define if threads enabled */
+#cmakedefine01 LLVM_ENABLE_THREADS
+
+/* Installation directory for config files */
+#cmakedefine LLVM_ETCDIR "${LLVM_ETCDIR}"
+
+/* Has gcc/MSVC atomic intrinsics */
+#cmakedefine01 LLVM_HAS_ATOMICS
+
+/* Host triple LLVM will be executed on */
+#cmakedefine LLVM_HOSTTRIPLE "${LLVM_HOSTTRIPLE}"
+
+/* Installation directory for include files */
+#cmakedefine LLVM_INCLUDEDIR "${LLVM_INCLUDEDIR}"
+
+/* Installation directory for .info files */
+#cmakedefine LLVM_INFODIR "${LLVM_INFODIR}"
+
+/* Installation directory for libraries */
+#cmakedefine LLVM_LIBDIR "${LLVM_LIBDIR}"
+
+/* Installation directory for man pages */
+#cmakedefine LLVM_MANDIR "${LLVM_MANDIR}"
+
+/* LLVM architecture name for the native architecture, if available */
+#cmakedefine LLVM_NATIVE_ARCH ${LLVM_NATIVE_ARCH}
+
+/* LLVM name for the native AsmParser init function, if available */
+#cmakedefine LLVM_NATIVE_ASMPARSER LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser
+
+/* LLVM name for the native AsmPrinter init function, if available */
+#cmakedefine LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter
+
+/* LLVM name for the native Disassembler init function, if available */
+#cmakedefine LLVM_NATIVE_DISASSEMBLER LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler
+
+/* LLVM name for the native Target init function, if available */
+#cmakedefine LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target
+
+/* LLVM name for the native TargetInfo init function, if available */
+#cmakedefine LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo
+
+/* LLVM name for the native target MC init function, if available */
+#cmakedefine LLVM_NATIVE_TARGETMC LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC
+
+/* Define if this is Unixish platform */
+#cmakedefine LLVM_ON_UNIX ${LLVM_ON_UNIX}
+
+/* Define if this is Win32ish platform */
+#cmakedefine LLVM_ON_WIN32 ${LLVM_ON_WIN32}
+
+/* Define to path to circo program if found or 'echo circo' otherwise */
+#cmakedefine LLVM_PATH_CIRCO "${LLVM_PATH_CIRCO}"
+
+/* Define to path to dot program if found or 'echo dot' otherwise */
+#cmakedefine LLVM_PATH_DOT "${LLVM_PATH_DOT}"
+
+/* Define to path to dotty program if found or 'echo dotty' otherwise */
+#cmakedefine LLVM_PATH_DOTTY "${LLVM_PATH_DOTTY}"
+
+/* Define to path to fdp program if found or 'echo fdp' otherwise */
+#cmakedefine LLVM_PATH_FDP "${LLVM_PATH_FDP}"
+
+/* Define to path to Graphviz program if found or 'echo Graphviz' otherwise */
+#cmakedefine LLVM_PATH_GRAPHVIZ "${LLVM_PATH_GRAPHVIZ}"
+
+/* Define to path to gv program if found or 'echo gv' otherwise */
+#cmakedefine LLVM_PATH_GV "${LLVM_PATH_GV}"
+
+/* Define to path to neato program if found or 'echo neato' otherwise */
+#cmakedefine LLVM_PATH_NEATO "${LLVM_PATH_NEATO}"
+
+/* Define to path to twopi program if found or 'echo twopi' otherwise */
+#cmakedefine LLVM_PATH_TWOPI "${LLVM_PATH_TWOPI}"
+
+/* Define to path to xdot.py program if found or 'echo xdot.py' otherwise */
+#cmakedefine LLVM_PATH_XDOT_PY "${LLVM_PATH_XDOT_PY}"
+
+/* Installation prefix directory */
+#cmakedefine LLVM_PREFIX "${LLVM_PREFIX}"
+
+/* Define if we have the Intel JIT API runtime support library */
+#cmakedefine LLVM_USE_INTEL_JITEVENTS 1
+
+/* Define if we have the oprofile JIT-support library */
+#cmakedefine LLVM_USE_OPROFILE 1
+
+/* Major version of the LLVM API */
+#cmakedefine LLVM_VERSION_MAJOR ${LLVM_VERSION_MAJOR}
+
+/* Minor version of the LLVM API */
+#cmakedefine LLVM_VERSION_MINOR ${LLVM_VERSION_MINOR}
+
+/* Define if the OS needs help to load dependent libraries for dlopen(). */
+#cmakedefine LTDL_DLOPEN_DEPLIBS ${LTDL_DLOPEN_DEPLIBS}
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+ */
+#undef LTDL_OBJDIR
+
+/* Define to the name of the environment variable that determines the dynamic
+ library search path. */
+#cmakedefine LTDL_SHLIBPATH_VAR "${LTDL_SHLIBPATH_VAR}"
+
+/* Define to the extension used for shared libraries, say, ".so". */
+#cmakedefine LTDL_SHLIB_EXT "${LTDL_SHLIB_EXT}"
+
+/* Define to the system default library search path. */
+#cmakedefine LTDL_SYSSEARCHPATH "${LTDL_SYSSEARCHPATH}"
+
+/* Define if /dev/zero should be used when mapping RWX memory, or undefine if
+ its not necessary */
+#undef NEED_DEV_ZERO_FOR_MMAP
+
+/* Define if dlsym() requires a leading underscore in symbol names. */
+#undef NEED_USCORE
+
+/* Define to the address where bug reports for this package should be sent. */
+#cmakedefine PACKAGE_BUGREPORT "${PACKAGE_BUGREPORT}"
+
+/* Define to the full name of this package. */
+#cmakedefine PACKAGE_NAME "${PACKAGE_NAME}"
+
+/* Define to the full name and version of this package. */
+#cmakedefine PACKAGE_STRING "${PACKAGE_STRING}"
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the version of this package. */
+#cmakedefine PACKAGE_VERSION "${PACKAGE_VERSION}"
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#cmakedefine RETSIGTYPE ${RETSIGTYPE}
+
+/* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */
+#undef STAT_MACROS_BROKEN
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#undef TIME_WITH_SYS_TIME
+
+/* Define to 1 if your <sys/time.h> declares `struct tm'. */
+#undef TM_IN_SYS_TIME
+
+/* Define if use udis86 library */
+#undef USE_UDIS86
+
+/* Type of 1st arg on ELM Callback */
+#cmakedefine WIN32_ELMCB_PCSTR ${WIN32_ELMCB_PCSTR}
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* Define to a type to use for `error_t' if it is not otherwise available. */
+#cmakedefine error_t ${error_t}
+
+/* Define to `int' if <sys/types.h> does not define. */
+#undef pid_t
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+#undef size_t
+
+/* Define to a function replacing strtoll */
+#cmakedefine strtoll ${strtoll}
+
+/* Define to a function implementing strtoull */
+#cmakedefine strtoull ${strtoull}
+
+/* Define to a function implementing stricmp */
+#cmakedefine stricmp ${stricmp}
+
+/* Define to a function implementing strdup */
+#cmakedefine strdup ${strdup}
+
+/* Define to 1 if you have the `_chsize_s' function. */
+#cmakedefine HAVE__CHSIZE_S ${HAVE__CHSIZE_S}
+
+/* Added by Kevin -- Maximum path length */
+#cmakedefine MAXPATHLEN ${MAXPATHLEN}
+
+#endif
diff --git a/include/llvm/Config/config.h.in b/include/llvm/Config/config.h.in
new file mode 100644
index 00000000000..5a60ba565f0
--- /dev/null
+++ b/include/llvm/Config/config.h.in
@@ -0,0 +1,714 @@
+/* include/llvm/Config/config.h.in. Generated from autoconf/configure.ac by autoheader. */
+
+#ifndef CONFIG_H
+#define CONFIG_H
+
+/* Bug report URL. */
+#undef BUG_REPORT_URL
+
+/* Define if we have libxml2 */
+#undef CLANG_HAVE_LIBXML
+
+/* Relative directory for resource files */
+#undef CLANG_RESOURCE_DIR
+
+/* Directories clang will search for headers */
+#undef C_INCLUDE_DIRS
+
+/* Default <path> to all compiler invocations for --sysroot=<path>. */
+#undef DEFAULT_SYSROOT
+
+/* Define if position independent code is enabled */
+#undef ENABLE_PIC
+
+/* Define if timestamp information (e.g., __DATE__) is allowed */
+#undef ENABLE_TIMESTAMPS
+
+/* Directory where gcc is installed. */
+#undef GCC_INSTALL_PREFIX
+
+/* Define to 1 if you have the `arc4random' function. */
+#undef HAVE_ARC4RANDOM
+
+/* Define to 1 if you have the `argz_append' function. */
+#undef HAVE_ARGZ_APPEND
+
+/* Define to 1 if you have the `argz_create_sep' function. */
+#undef HAVE_ARGZ_CREATE_SEP
+
+/* Define to 1 if you have the <argz.h> header file. */
+#undef HAVE_ARGZ_H
+
+/* Define to 1 if you have the `argz_insert' function. */
+#undef HAVE_ARGZ_INSERT
+
+/* Define to 1 if you have the `argz_next' function. */
+#undef HAVE_ARGZ_NEXT
+
+/* Define to 1 if you have the `argz_stringify' function. */
+#undef HAVE_ARGZ_STRINGIFY
+
+/* Define to 1 if you have the <assert.h> header file. */
+#undef HAVE_ASSERT_H
+
+/* Define to 1 if you have the `backtrace' function. */
+#undef HAVE_BACKTRACE
+
+/* Define to 1 if you have the `bcopy' function. */
+#undef HAVE_BCOPY
+
+/* Define to 1 if you have the `ceilf' function. */
+#undef HAVE_CEILF
+
+/* Define if the neat program is available */
+#undef HAVE_CIRCO
+
+/* Define to 1 if you have the `closedir' function. */
+#undef HAVE_CLOSEDIR
+
+/* Define to 1 if you have the <CrashReporterClient.h> header file. */
+#undef HAVE_CRASHREPORTERCLIENT_H
+
+/* Define if __crashreporter_info__ exists. */
+#undef HAVE_CRASHREPORTER_INFO
+
+/* Define to 1 if you have the <ctype.h> header file. */
+#undef HAVE_CTYPE_H
+
+/* Define to 1 if you have the declaration of `strerror_s', and to 0 if you
+ don't. */
+#undef HAVE_DECL_STRERROR_S
+
+/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
+ */
+#undef HAVE_DIRENT_H
+
+/* Define if you have the GNU dld library. */
+#undef HAVE_DLD
+
+/* Define to 1 if you have the <dld.h> header file. */
+#undef HAVE_DLD_H
+
+/* Define to 1 if you have the `dlerror' function. */
+#undef HAVE_DLERROR
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#undef HAVE_DLFCN_H
+
+/* Define if dlopen() is available on this platform. */
+#undef HAVE_DLOPEN
+
+/* Define to 1 if you have the <dl.h> header file. */
+#undef HAVE_DL_H
+
+/* Define if the dot program is available */
+#undef HAVE_DOT
+
+/* Define if the dotty program is available */
+#undef HAVE_DOTTY
+
+/* Define if you have the _dyld_func_lookup function. */
+#undef HAVE_DYLD
+
+/* Define to 1 if you have the <errno.h> header file. */
+#undef HAVE_ERRNO_H
+
+/* Define to 1 if the system has the type `error_t'. */
+#undef HAVE_ERROR_T
+
+/* Define to 1 if you have the <execinfo.h> header file. */
+#undef HAVE_EXECINFO_H
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#undef HAVE_FCNTL_H
+
+/* Define if the neat program is available */
+#undef HAVE_FDP
+
+/* Define to 1 if you have the <fenv.h> header file. */
+#undef HAVE_FENV_H
+
+/* Define if libffi is available on this platform. */
+#undef HAVE_FFI_CALL
+
+/* Define to 1 if you have the <ffi/ffi.h> header file. */
+#undef HAVE_FFI_FFI_H
+
+/* Define to 1 if you have the <ffi.h> header file. */
+#undef HAVE_FFI_H
+
+/* Set to 1 if the finite function is found in <ieeefp.h> */
+#undef HAVE_FINITE_IN_IEEEFP_H
+
+/* Define to 1 if you have the `floorf' function. */
+#undef HAVE_FLOORF
+
+/* Define to 1 if you have the `fmodf' function. */
+#undef HAVE_FMODF
+
+/* Define to 1 if you have the `getcwd' function. */
+#undef HAVE_GETCWD
+
+/* Define to 1 if you have the `getpagesize' function. */
+#undef HAVE_GETPAGESIZE
+
+/* Define to 1 if you have the `getrlimit' function. */
+#undef HAVE_GETRLIMIT
+
+/* Define to 1 if you have the `getrusage' function. */
+#undef HAVE_GETRUSAGE
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#undef HAVE_GETTIMEOFDAY
+
+/* Define if the Graphviz program is available */
+#undef HAVE_GRAPHVIZ
+
+/* Define if the gv program is available */
+#undef HAVE_GV
+
+/* Define to 1 if you have the `index' function. */
+#undef HAVE_INDEX
+
+/* Define to 1 if the system has the type `int64_t'. */
+#undef HAVE_INT64_T
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#undef HAVE_INTTYPES_H
+
+/* Define to 1 if you have the `isatty' function. */
+#undef HAVE_ISATTY
+
+/* Set to 1 if the isinf function is found in <cmath> */
+#undef HAVE_ISINF_IN_CMATH
+
+/* Set to 1 if the isinf function is found in <math.h> */
+#undef HAVE_ISINF_IN_MATH_H
+
+/* Set to 1 if the isnan function is found in <cmath> */
+#undef HAVE_ISNAN_IN_CMATH
+
+/* Set to 1 if the isnan function is found in <math.h> */
+#undef HAVE_ISNAN_IN_MATH_H
+
+/* Define if you have the libdl library or equivalent. */
+#undef HAVE_LIBDL
+
+/* Define to 1 if you have the `imagehlp' library (-limagehlp). */
+#undef HAVE_LIBIMAGEHLP
+
+/* Define to 1 if you have the `m' library (-lm). */
+#undef HAVE_LIBM
+
+/* Define to 1 if you have the `psapi' library (-lpsapi). */
+#undef HAVE_LIBPSAPI
+
+/* Define to 1 if you have the `pthread' library (-lpthread). */
+#undef HAVE_LIBPTHREAD
+
+/* Define to 1 if you have the `udis86' library (-ludis86). */
+#undef HAVE_LIBUDIS86
+
+/* Define to 1 if you have the <limits.h> header file. */
+#undef HAVE_LIMITS_H
+
+/* Define if you can use -Wl,-export-dynamic. */
+#undef HAVE_LINK_EXPORT_DYNAMIC
+
+/* Define to 1 if you have the <link.h> header file. */
+#undef HAVE_LINK_H
+
+/* Define if you can use -Wl,-R. to pass -R. to the linker, in order to add
+ the current directory to the dynamic linker search path. */
+#undef HAVE_LINK_R
+
+/* Define to 1 if you have the `longjmp' function. */
+#undef HAVE_LONGJMP
+
+/* Define to 1 if you have the <mach/mach.h> header file. */
+#undef HAVE_MACH_MACH_H
+
+/* Define to 1 if you have the <mach-o/dyld.h> header file. */
+#undef HAVE_MACH_O_DYLD_H
+
+/* Define if mallinfo() is available on this platform. */
+#undef HAVE_MALLINFO
+
+/* Define to 1 if you have the <malloc.h> header file. */
+#undef HAVE_MALLOC_H
+
+/* Define to 1 if you have the <malloc/malloc.h> header file. */
+#undef HAVE_MALLOC_MALLOC_H
+
+/* Define to 1 if you have the `malloc_zone_statistics' function. */
+#undef HAVE_MALLOC_ZONE_STATISTICS
+
+/* Define to 1 if you have the `memcpy' function. */
+#undef HAVE_MEMCPY
+
+/* Define to 1 if you have the `memmove' function. */
+#undef HAVE_MEMMOVE
+
+/* Define to 1 if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define to 1 if you have the `mkdtemp' function. */
+#undef HAVE_MKDTEMP
+
+/* Define to 1 if you have the `mkstemp' function. */
+#undef HAVE_MKSTEMP
+
+/* Define to 1 if you have the `mktemp' function. */
+#undef HAVE_MKTEMP
+
+/* Define to 1 if you have a working `mmap' system call. */
+#undef HAVE_MMAP
+
+/* Define if mmap() uses MAP_ANONYMOUS to map anonymous pages, or undefine if
+ it uses MAP_ANON */
+#undef HAVE_MMAP_ANONYMOUS
+
+/* Define if mmap() can map files into memory */
+#undef HAVE_MMAP_FILE
+
+/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
+#undef HAVE_NDIR_H
+
+/* Define to 1 if you have the `nearbyintf' function. */
+#undef HAVE_NEARBYINTF
+
+/* Define if the neat program is available */
+#undef HAVE_NEATO
+
+/* Define to 1 if you have the `opendir' function. */
+#undef HAVE_OPENDIR
+
+/* Define to 1 if you have the `posix_spawn' function. */
+#undef HAVE_POSIX_SPAWN
+
+/* Define to 1 if you have the `powf' function. */
+#undef HAVE_POWF
+
+/* Define to 1 if you have the `pread' function. */
+#undef HAVE_PREAD
+
+/* Define if libtool can extract symbol lists from object files. */
+#undef HAVE_PRELOADED_SYMBOLS
+
+/* Define to have the %a format string */
+#undef HAVE_PRINTF_A
+
+/* Have pthread_getspecific */
+#undef HAVE_PTHREAD_GETSPECIFIC
+
+/* Define to 1 if you have the <pthread.h> header file. */
+#undef HAVE_PTHREAD_H
+
+/* Have pthread_mutex_lock */
+#undef HAVE_PTHREAD_MUTEX_LOCK
+
+/* Have pthread_rwlock_init */
+#undef HAVE_PTHREAD_RWLOCK_INIT
+
+/* Define to 1 if srand48/lrand48/drand48 exist in <stdlib.h> */
+#undef HAVE_RAND48
+
+/* Define to 1 if you have the `readdir' function. */
+#undef HAVE_READDIR
+
+/* Define to 1 if you have the `realpath' function. */
+#undef HAVE_REALPATH
+
+/* Define to 1 if you have the `rindex' function. */
+#undef HAVE_RINDEX
+
+/* Define to 1 if you have the `rintf' function. */
+#undef HAVE_RINTF
+
+/* Define to 1 if you have the `round' function. */
+#undef HAVE_ROUND
+
+/* Define to 1 if you have the `roundf' function. */
+#undef HAVE_ROUNDF
+
+/* Define to 1 if you have the `sbrk' function. */
+#undef HAVE_SBRK
+
+/* Define to 1 if you have the `setenv' function. */
+#undef HAVE_SETENV
+
+/* Define to 1 if you have the `setjmp' function. */
+#undef HAVE_SETJMP
+
+/* Define to 1 if you have the <setjmp.h> header file. */
+#undef HAVE_SETJMP_H
+
+/* Define to 1 if you have the `setrlimit' function. */
+#undef HAVE_SETRLIMIT
+
+/* Define if you have the shl_load function. */
+#undef HAVE_SHL_LOAD
+
+/* Define to 1 if you have the `siglongjmp' function. */
+#undef HAVE_SIGLONGJMP
+
+/* Define to 1 if you have the <signal.h> header file. */
+#undef HAVE_SIGNAL_H
+
+/* Define to 1 if you have the `sigsetjmp' function. */
+#undef HAVE_SIGSETJMP
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define to 1 if you have the <stdio.h> header file. */
+#undef HAVE_STDIO_H
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#undef HAVE_STDLIB_H
+
+/* Set to 1 if the std::isinf function is found in <cmath> */
+#undef HAVE_STD_ISINF_IN_CMATH
+
+/* Set to 1 if the std::isnan function is found in <cmath> */
+#undef HAVE_STD_ISNAN_IN_CMATH
+
+/* Define to 1 if you have the `strchr' function. */
+#undef HAVE_STRCHR
+
+/* Define to 1 if you have the `strcmp' function. */
+#undef HAVE_STRCMP
+
+/* Define to 1 if you have the `strdup' function. */
+#undef HAVE_STRDUP
+
+/* Define to 1 if you have the `strerror' function. */
+#undef HAVE_STRERROR
+
+/* Define to 1 if you have the `strerror_r' function. */
+#undef HAVE_STRERROR_R
+
+/* Define to 1 if you have the <strings.h> header file. */
+#undef HAVE_STRINGS_H
+
+/* Define to 1 if you have the <string.h> header file. */
+#undef HAVE_STRING_H
+
+/* Define to 1 if you have the `strrchr' function. */
+#undef HAVE_STRRCHR
+
+/* Define to 1 if you have the `strtof' function. */
+#undef HAVE_STRTOF
+
+/* Define to 1 if you have the `strtoll' function. */
+#undef HAVE_STRTOLL
+
+/* Define to 1 if you have the `strtoq' function. */
+#undef HAVE_STRTOQ
+
+/* Define to 1 if you have the `sysconf' function. */
+#undef HAVE_SYSCONF
+
+/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
+ */
+#undef HAVE_SYS_DIR_H
+
+/* Define to 1 if you have the <sys/dl.h> header file. */
+#undef HAVE_SYS_DL_H
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#undef HAVE_SYS_IOCTL_H
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#undef HAVE_SYS_MMAN_H
+
+/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
+ */
+#undef HAVE_SYS_NDIR_H
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#undef HAVE_SYS_PARAM_H
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#undef HAVE_SYS_RESOURCE_H
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#undef HAVE_SYS_STAT_H
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#undef HAVE_SYS_TIME_H
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#undef HAVE_SYS_TYPES_H
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#undef HAVE_SYS_UIO_H
+
+/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
+#undef HAVE_SYS_WAIT_H
+
+/* Define to 1 if you have the <termios.h> header file. */
+#undef HAVE_TERMIOS_H
+
+/* Define if the neat program is available */
+#undef HAVE_TWOPI
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#undef HAVE_UINT64_T
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#undef HAVE_UNISTD_H
+
+/* Define to 1 if you have the <utime.h> header file. */
+#undef HAVE_UTIME_H
+
+/* Define to 1 if the system has the type `u_int64_t'. */
+#undef HAVE_U_INT64_T
+
+/* Define to 1 if you have the <valgrind/valgrind.h> header file. */
+#undef HAVE_VALGRIND_VALGRIND_H
+
+/* Define to 1 if you have the <windows.h> header file. */
+#undef HAVE_WINDOWS_H
+
+/* Define to 1 if you have the `writev' function. */
+#undef HAVE_WRITEV
+
+/* Define if the xdot.py program is available */
+#undef HAVE_XDOT_PY
+
+/* Have host's _alloca */
+#undef HAVE__ALLOCA
+
+/* Have host's __alloca */
+#undef HAVE___ALLOCA
+
+/* Have host's __ashldi3 */
+#undef HAVE___ASHLDI3
+
+/* Have host's __ashrdi3 */
+#undef HAVE___ASHRDI3
+
+/* Have host's __chkstk */
+#undef HAVE___CHKSTK
+
+/* Have host's __cmpdi2 */
+#undef HAVE___CMPDI2
+
+/* Have host's __divdi3 */
+#undef HAVE___DIVDI3
+
+/* Define to 1 if you have the `__dso_handle' function. */
+#undef HAVE___DSO_HANDLE
+
+/* Have host's __fixdfdi */
+#undef HAVE___FIXDFDI
+
+/* Have host's __fixsfdi */
+#undef HAVE___FIXSFDI
+
+/* Have host's __floatdidf */
+#undef HAVE___FLOATDIDF
+
+/* Have host's __lshrdi3 */
+#undef HAVE___LSHRDI3
+
+/* Have host's __main */
+#undef HAVE___MAIN
+
+/* Have host's __moddi3 */
+#undef HAVE___MODDI3
+
+/* Have host's __udivdi3 */
+#undef HAVE___UDIVDI3
+
+/* Have host's __umoddi3 */
+#undef HAVE___UMODDI3
+
+/* Have host's ___chkstk */
+#undef HAVE____CHKSTK
+
+/* Linker version detected at compile time. */
+#undef HOST_LINK_VERSION
+
+/* Installation directory for binary executables */
+#undef LLVM_BINDIR
+
+/* Time at which LLVM was configured */
+#undef LLVM_CONFIGTIME
+
+/* Installation directory for data files */
+#undef LLVM_DATADIR
+
+/* Target triple LLVM will generate code for by default */
+#undef LLVM_DEFAULT_TARGET_TRIPLE
+
+/* Installation directory for documentation */
+#undef LLVM_DOCSDIR
+
+/* Define if threads enabled */
+#undef LLVM_ENABLE_THREADS
+
+/* Installation directory for config files */
+#undef LLVM_ETCDIR
+
+/* Has gcc/MSVC atomic intrinsics */
+#undef LLVM_HAS_ATOMICS
+
+/* Host triple LLVM will be executed on */
+#undef LLVM_HOSTTRIPLE
+
+/* Installation directory for include files */
+#undef LLVM_INCLUDEDIR
+
+/* Installation directory for .info files */
+#undef LLVM_INFODIR
+
+/* Installation directory for libraries */
+#undef LLVM_LIBDIR
+
+/* Installation directory for man pages */
+#undef LLVM_MANDIR
+
+/* LLVM architecture name for the native architecture, if available */
+#undef LLVM_NATIVE_ARCH
+
+/* LLVM name for the native AsmParser init function, if available */
+#undef LLVM_NATIVE_ASMPARSER
+
+/* LLVM name for the native AsmPrinter init function, if available */
+#undef LLVM_NATIVE_ASMPRINTER
+
+/* LLVM name for the native Disassembler init function, if available */
+#undef LLVM_NATIVE_DISASSEMBLER
+
+/* LLVM name for the native Target init function, if available */
+#undef LLVM_NATIVE_TARGET
+
+/* LLVM name for the native TargetInfo init function, if available */
+#undef LLVM_NATIVE_TARGETINFO
+
+/* LLVM name for the native target MC init function, if available */
+#undef LLVM_NATIVE_TARGETMC
+
+/* Define if this is Unixish platform */
+#undef LLVM_ON_UNIX
+
+/* Define if this is Win32ish platform */
+#undef LLVM_ON_WIN32
+
+/* Define to path to circo program if found or 'echo circo' otherwise */
+#undef LLVM_PATH_CIRCO
+
+/* Define to path to dot program if found or 'echo dot' otherwise */
+#undef LLVM_PATH_DOT
+
+/* Define to path to dotty program if found or 'echo dotty' otherwise */
+#undef LLVM_PATH_DOTTY
+
+/* Define to path to fdp program if found or 'echo fdp' otherwise */
+#undef LLVM_PATH_FDP
+
+/* Define to path to Graphviz program if found or 'echo Graphviz' otherwise */
+#undef LLVM_PATH_GRAPHVIZ
+
+/* Define to path to gv program if found or 'echo gv' otherwise */
+#undef LLVM_PATH_GV
+
+/* Define to path to neato program if found or 'echo neato' otherwise */
+#undef LLVM_PATH_NEATO
+
+/* Define to path to twopi program if found or 'echo twopi' otherwise */
+#undef LLVM_PATH_TWOPI
+
+/* Define to path to xdot.py program if found or 'echo xdot.py' otherwise */
+#undef LLVM_PATH_XDOT_PY
+
+/* Installation prefix directory */
+#undef LLVM_PREFIX
+
+/* Define if we have the Intel JIT API runtime support library */
+#undef LLVM_USE_INTEL_JITEVENTS
+
+/* Define if we have the oprofile JIT-support library */
+#undef LLVM_USE_OPROFILE
+
+/* Major version of the LLVM API */
+#undef LLVM_VERSION_MAJOR
+
+/* Minor version of the LLVM API */
+#undef LLVM_VERSION_MINOR
+
+/* Define if the OS needs help to load dependent libraries for dlopen(). */
+#undef LTDL_DLOPEN_DEPLIBS
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+ */
+#undef LTDL_OBJDIR
+
+/* Define to the name of the environment variable that determines the dynamic
+ library search path. */
+#undef LTDL_SHLIBPATH_VAR
+
+/* Define to the extension used for shared libraries, say, ".so". */
+#undef LTDL_SHLIB_EXT
+
+/* Define to the system default library search path. */
+#undef LTDL_SYSSEARCHPATH
+
+/* Define if /dev/zero should be used when mapping RWX memory, or undefine if
+ its not necessary */
+#undef NEED_DEV_ZERO_FOR_MMAP
+
+/* Define if dlsym() requires a leading underscore in symbol names. */
+#undef NEED_USCORE
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#undef RETSIGTYPE
+
+/* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */
+#undef STAT_MACROS_BROKEN
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#undef TIME_WITH_SYS_TIME
+
+/* Define to 1 if your <sys/time.h> declares `struct tm'. */
+#undef TM_IN_SYS_TIME
+
+/* Define if use udis86 library */
+#undef USE_UDIS86
+
+/* Type of 1st arg on ELM Callback */
+#undef WIN32_ELMCB_PCSTR
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* Define to a type to use for `error_t' if it is not otherwise available. */
+#undef error_t
+
+/* Define to `int' if <sys/types.h> does not define. */
+#undef pid_t
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+#undef size_t
+
+#endif
diff --git a/include/llvm/Config/llvm-config.h.cmake b/include/llvm/Config/llvm-config.h.cmake
new file mode 100644
index 00000000000..39442926dc9
--- /dev/null
+++ b/include/llvm/Config/llvm-config.h.cmake
@@ -0,0 +1,121 @@
+/*===-- llvm/config/llvm-config.h - llvm configure variable -------*- C -*-===*/
+/* */
+/* The LLVM Compiler Infrastructure */
+/* */
+/* This file is distributed under the University of Illinois Open Source */
+/* License. See LICENSE.TXT for details. */
+/* */
+/*===----------------------------------------------------------------------===*/
+
+/* This file enumerates all of the llvm variables from configure so that
+ they can be in exported headers and won't override package specific
+ directives. This is a C file so we can include it in the llvm-c headers. */
+
+/* To avoid multiple inclusions of these variables when we include the exported
+ headers and config.h, conditionally include these. */
+/* TODO: This is a bit of a hack. */
+#ifndef CONFIG_H
+
+/* Installation directory for binary executables */
+#cmakedefine LLVM_BINDIR "${LLVM_BINDIR}"
+
+/* Time at which LLVM was configured */
+#cmakedefine LLVM_CONFIGTIME "${LLVM_CONFIGTIME}"
+
+/* Installation directory for data files */
+#cmakedefine LLVM_DATADIR "${LLVM_DATADIR}"
+
+/* Target triple LLVM will generate code for by default */
+#cmakedefine LLVM_DEFAULT_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}"
+
+/* Installation directory for documentation */
+#cmakedefine LLVM_DOCSDIR "${LLVM_DOCSDIR}"
+
+/* Define if threads enabled */
+#cmakedefine01 LLVM_ENABLE_THREADS
+
+/* Installation directory for config files */
+#cmakedefine LLVM_ETCDIR "${LLVM_ETCDIR}"
+
+/* Has gcc/MSVC atomic intrinsics */
+#cmakedefine01 LLVM_HAS_ATOMICS
+
+/* Host triple LLVM will be executed on */
+#cmakedefine LLVM_HOSTTRIPLE "${LLVM_HOSTTRIPLE}"
+
+/* Installation directory for include files */
+#cmakedefine LLVM_INCLUDEDIR "${LLVM_INCLUDEDIR}"
+
+/* Installation directory for .info files */
+#cmakedefine LLVM_INFODIR "${LLVM_INFODIR}"
+
+/* Installation directory for libraries */
+#cmakedefine LLVM_LIBDIR "${LLVM_LIBDIR}"
+
+/* Installation directory for man pages */
+#cmakedefine LLVM_MANDIR "${LLVM_MANDIR}"
+
+/* LLVM architecture name for the native architecture, if available */
+#cmakedefine LLVM_NATIVE_ARCH ${LLVM_NATIVE_ARCH}
+
+/* LLVM name for the native AsmParser init function, if available */
+#cmakedefine LLVM_NATIVE_ASMPARSER LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser
+
+/* LLVM name for the native AsmPrinter init function, if available */
+#cmakedefine LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter
+
+/* LLVM name for the native Disassembler init function, if available */
+#cmakedefine LLVM_NATIVE_DISASSEMBLER LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler
+
+/* LLVM name for the native Target init function, if available */
+#cmakedefine LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target
+
+/* LLVM name for the native TargetInfo init function, if available */
+#cmakedefine LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo
+
+/* LLVM name for the native target MC init function, if available */
+#cmakedefine LLVM_NATIVE_TARGETMC LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC
+
+/* Define if this is Unixish platform */
+#cmakedefine LLVM_ON_UNIX ${LLVM_ON_UNIX}
+
+/* Define if this is Win32ish platform */
+#cmakedefine LLVM_ON_WIN32 ${LLVM_ON_WIN32}
+
+/* Define to path to circo program if found or 'echo circo' otherwise */
+#cmakedefine LLVM_PATH_CIRCO "${LLVM_PATH_CIRCO}"
+
+/* Define to path to dot program if found or 'echo dot' otherwise */
+#cmakedefine LLVM_PATH_DOT "${LLVM_PATH_DOT}"
+
+/* Define to path to dotty program if found or 'echo dotty' otherwise */
+#cmakedefine LLVM_PATH_DOTTY "${LLVM_PATH_DOTTY}"
+
+/* Define to path to fdp program if found or 'echo fdp' otherwise */
+#cmakedefine LLVM_PATH_FDP "${LLVM_PATH_FDP}"
+
+/* Define to path to Graphviz program if found or 'echo Graphviz' otherwise */
+#cmakedefine LLVM_PATH_GRAPHVIZ "${LLVM_PATH_GRAPHVIZ}"
+
+/* Define to path to gv program if found or 'echo gv' otherwise */
+#cmakedefine LLVM_PATH_GV "${LLVM_PATH_GV}"
+
+/* Define to path to neato program if found or 'echo neato' otherwise */
+#cmakedefine LLVM_PATH_NEATO "${LLVM_PATH_NEATO}"
+
+/* Define to path to twopi program if found or 'echo twopi' otherwise */
+#cmakedefine LLVM_PATH_TWOPI "${LLVM_PATH_TWOPI}"
+
+/* Define to path to xdot.py program if found or 'echo xdot.py' otherwise */
+#cmakedefine LLVM_PATH_XDOT_PY "${LLVM_PATH_XDOT_PY}"
+
+/* Installation prefix directory */
+#cmakedefine LLVM_PREFIX "${LLVM_PREFIX}"
+
+/* Major version of the LLVM API */
+#cmakedefine LLVM_VERSION_MAJOR ${LLVM_VERSION_MAJOR}
+
+/* Minor version of the LLVM API */
+#cmakedefine LLVM_VERSION_MINOR ${LLVM_VERSION_MINOR}
+
+#endif
diff --git a/include/llvm/Config/llvm-config.h.in b/include/llvm/Config/llvm-config.h.in
new file mode 100644
index 00000000000..9489dfe0163
--- /dev/null
+++ b/include/llvm/Config/llvm-config.h.in
@@ -0,0 +1,121 @@
+/*===-- llvm/config/llvm-config.h - llvm configure variable -------*- C -*-===*/
+/* */
+/* The LLVM Compiler Infrastructure */
+/* */
+/* This file is distributed under the University of Illinois Open Source */
+/* License. See LICENSE.TXT for details. */
+/* */
+/*===----------------------------------------------------------------------===*/
+
+/* This file enumerates all of the llvm variables from configure so that
+ they can be in exported headers and won't override package specific
+ directives. This is a C file so we can include it in the llvm-c headers. */
+
+/* To avoid multiple inclusions of these variables when we include the exported
+ headers and config.h, conditionally include these. */
+/* TODO: This is a bit of a hack. */
+#ifndef CONFIG_H
+
+/* Installation directory for binary executables */
+#undef LLVM_BINDIR
+
+/* Time at which LLVM was configured */
+#undef LLVM_CONFIGTIME
+
+/* Installation directory for data files */
+#undef LLVM_DATADIR
+
+/* Target triple LLVM will generate code for by default */
+#undef LLVM_DEFAULT_TARGET_TRIPLE
+
+/* Installation directory for documentation */
+#undef LLVM_DOCSDIR
+
+/* Define if threads enabled */
+#undef LLVM_ENABLE_THREADS
+
+/* Installation directory for config files */
+#undef LLVM_ETCDIR
+
+/* Has gcc/MSVC atomic intrinsics */
+#undef LLVM_HAS_ATOMICS
+
+/* Host triple LLVM will be executed on */
+#undef LLVM_HOSTTRIPLE
+
+/* Installation directory for include files */
+#undef LLVM_INCLUDEDIR
+
+/* Installation directory for .info files */
+#undef LLVM_INFODIR
+
+/* Installation directory for libraries */
+#undef LLVM_LIBDIR
+
+/* Installation directory for man pages */
+#undef LLVM_MANDIR
+
+/* LLVM architecture name for the native architecture, if available */
+#undef LLVM_NATIVE_ARCH
+
+/* LLVM name for the native AsmParser init function, if available */
+#undef LLVM_NATIVE_ASMPARSER
+
+/* LLVM name for the native AsmPrinter init function, if available */
+#undef LLVM_NATIVE_ASMPRINTER
+
+/* LLVM name for the native Disassembler init function, if available */
+#undef LLVM_NATIVE_DISASSEMBLER
+
+/* LLVM name for the native Target init function, if available */
+#undef LLVM_NATIVE_TARGET
+
+/* LLVM name for the native TargetInfo init function, if available */
+#undef LLVM_NATIVE_TARGETINFO
+
+/* LLVM name for the native target MC init function, if available */
+#undef LLVM_NATIVE_TARGETMC
+
+/* Define if this is Unixish platform */
+#undef LLVM_ON_UNIX
+
+/* Define if this is Win32ish platform */
+#undef LLVM_ON_WIN32
+
+/* Define to path to circo program if found or 'echo circo' otherwise */
+#undef LLVM_PATH_CIRCO
+
+/* Define to path to dot program if found or 'echo dot' otherwise */
+#undef LLVM_PATH_DOT
+
+/* Define to path to dotty program if found or 'echo dotty' otherwise */
+#undef LLVM_PATH_DOTTY
+
+/* Define to path to fdp program if found or 'echo fdp' otherwise */
+#undef LLVM_PATH_FDP
+
+/* Define to path to Graphviz program if found or 'echo Graphviz' otherwise */
+#undef LLVM_PATH_GRAPHVIZ
+
+/* Define to path to gv program if found or 'echo gv' otherwise */
+#undef LLVM_PATH_GV
+
+/* Define to path to neato program if found or 'echo neato' otherwise */
+#undef LLVM_PATH_NEATO
+
+/* Define to path to twopi program if found or 'echo twopi' otherwise */
+#undef LLVM_PATH_TWOPI
+
+/* Define to path to xdot.py program if found or 'echo xdot.py' otherwise */
+#undef LLVM_PATH_XDOT_PY
+
+/* Installation prefix directory */
+#undef LLVM_PREFIX
+
+/* Major version of the LLVM API */
+#undef LLVM_VERSION_MAJOR
+
+/* Minor version of the LLVM API */
+#undef LLVM_VERSION_MINOR
+
+#endif
diff --git a/include/llvm/Constant.h b/include/llvm/Constant.h
new file mode 100644
index 00000000000..7464dce3303
--- /dev/null
+++ b/include/llvm/Constant.h
@@ -0,0 +1,158 @@
+//===-- llvm/Constant.h - Constant class definition -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the Constant class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CONSTANT_H
+#define LLVM_CONSTANT_H
+
+#include "llvm/User.h"
+
+namespace llvm {
+ class APInt;
+
+ template<typename T> class SmallVectorImpl;
+
+/// This is an important base class in LLVM. It provides the common facilities
+/// of all constant values in an LLVM program. A constant is a value that is
+/// immutable at runtime. Functions are constants because their address is
+/// immutable. Same with global variables.
+///
+/// All constants share the capabilities provided in this class. All constants
+/// can have a null value. They can have an operand list. Constants can be
+/// simple (integer and floating point values), complex (arrays and structures),
+/// or expression based (computations yielding a constant value composed of
+/// only certain operators and other constant values).
+///
+/// Note that Constants are immutable (once created they never change)
+/// and are fully shared by structural equivalence. This means that two
+/// structurally equivalent constants will always have the same address.
+/// Constants are created on demand as needed and never deleted: thus clients
+/// don't have to worry about the lifetime of the objects.
+/// @brief LLVM Constant Representation
+class Constant : public User {
+ void operator=(const Constant &) LLVM_DELETED_FUNCTION;
+ Constant(const Constant &) LLVM_DELETED_FUNCTION;
+ virtual void anchor();
+
+protected:
+ Constant(Type *ty, ValueTy vty, Use *Ops, unsigned NumOps)
+ : User(ty, vty, Ops, NumOps) {}
+
+ void destroyConstantImpl();
+public:
+ /// isNullValue - Return true if this is the value that would be returned by
+ /// getNullValue.
+ bool isNullValue() const;
+
+ /// isAllOnesValue - Return true if this is the value that would be returned by
+ /// getAllOnesValue.
+ bool isAllOnesValue() const;
+
+ /// isNegativeZeroValue - Return true if the value is what would be returned
+ /// by getZeroValueForNegation.
+ bool isNegativeZeroValue() const;
+
+ /// canTrap - Return true if evaluation of this constant could trap. This is
+ /// true for things like constant expressions that could divide by zero.
+ bool canTrap() const;
+
+ /// isConstantUsed - Return true if the constant has users other than constant
+ /// exprs and other dangling things.
+ bool isConstantUsed() const;
+
+ enum PossibleRelocationsTy {
+ NoRelocation = 0,
+ LocalRelocation = 1,
+ GlobalRelocations = 2
+ };
+
+ /// getRelocationInfo - This method classifies the entry according to
+ /// whether or not it may generate a relocation entry. This must be
+ /// conservative, so if it might codegen to a relocatable entry, it should say
+ /// so. The return values are:
+ ///
+ /// NoRelocation: This constant pool entry is guaranteed to never have a
+ /// relocation applied to it (because it holds a simple constant like
+ /// '4').
+ /// LocalRelocation: This entry has relocations, but the entries are
+ /// guaranteed to be resolvable by the static linker, so the dynamic
+ /// linker will never see them.
+ /// GlobalRelocations: This entry may have arbitrary relocations.
+ ///
+ /// FIXME: This really should not be in VMCore.
+ PossibleRelocationsTy getRelocationInfo() const;
+
+ /// getAggregateElement - For aggregates (struct/array/vector) return the
+ /// constant that corresponds to the specified element if possible, or null if
+ /// not. This can return null if the element index is a ConstantExpr, or if
+ /// 'this' is a constant expr.
+ Constant *getAggregateElement(unsigned Elt) const;
+ Constant *getAggregateElement(Constant *Elt) const;
+
+ /// destroyConstant - Called if some element of this constant is no longer
+ /// valid. At this point only other constants may be on the use_list for this
+ /// constant. Any constants on our Use list must also be destroy'd. The
+ /// implementation must be sure to remove the constant from the list of
+ /// available cached constants. Implementations should call
+ /// destroyConstantImpl as the last thing they do, to destroy all users and
+ /// delete this.
+ virtual void destroyConstant() { llvm_unreachable("Not reached!"); }
+
+ //// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const Constant *) { return true; }
+ static inline bool classof(const GlobalValue *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() >= ConstantFirstVal &&
+ V->getValueID() <= ConstantLastVal;
+ }
+
+ /// replaceUsesOfWithOnConstant - This method is a special form of
+ /// User::replaceUsesOfWith (which does not work on constants) that does work
+ /// on constants. Basically this method goes through the trouble of building
+ /// a new constant that is equivalent to the current one, with all uses of
+ /// From replaced with uses of To. After this construction is completed, all
+ /// of the users of 'this' are replaced to use the new constant, and then
+ /// 'this' is deleted. In general, you should not call this method, instead,
+ /// use Value::replaceAllUsesWith, which automatically dispatches to this
+ /// method as needed.
+ ///
+ virtual void replaceUsesOfWithOnConstant(Value *, Value *, Use *) {
+ // Provide a default implementation for constants (like integers) that
+ // cannot use any other values. This cannot be called at runtime, but needs
+ // to be here to avoid link errors.
+ assert(getNumOperands() == 0 && "replaceUsesOfWithOnConstant must be "
+ "implemented for all constants that have operands!");
+ llvm_unreachable("Constants that do not have operands cannot be using "
+ "'From'!");
+ }
+
+ static Constant *getNullValue(Type* Ty);
+
+ /// @returns the value for an integer or vector of integer constant of the
+ /// given type that has all its bits set to true.
+ /// @brief Get the all ones value
+ static Constant *getAllOnesValue(Type* Ty);
+
+ /// getIntegerValue - Return the value for an integer or pointer constant,
+ /// or a vector thereof, with the given scalar value.
+ static Constant *getIntegerValue(Type* Ty, const APInt &V);
+
+ /// removeDeadConstantUsers - If there are any dead constant users dangling
+ /// off of this constant, remove them. This method is useful for clients
+ /// that want to check to see if a global is unused, but don't want to deal
+ /// with potentially dead constants hanging off of the globals.
+ void removeDeadConstantUsers() const;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Constants.h b/include/llvm/Constants.h
new file mode 100644
index 00000000000..85fed4259d3
--- /dev/null
+++ b/include/llvm/Constants.h
@@ -0,0 +1,1170 @@
+//===-- llvm/Constants.h - Constant class subclass definitions --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+/// @file
+/// This file contains the declarations for the subclasses of Constant,
+/// which represent the different flavors of constant values that live in LLVM.
+/// Note that Constants are immutable (once created they never change) and are
+/// fully shared by structural equivalence. This means that two structurally
+/// equivalent constants will always have the same address. Constant's are
+/// created on demand as needed and never deleted: thus clients don't have to
+/// worry about the lifetime of the objects.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CONSTANTS_H
+#define LLVM_CONSTANTS_H
+
+#include "llvm/Constant.h"
+#include "llvm/OperandTraits.h"
+#include "llvm/ADT/APInt.h"
+#include "llvm/ADT/APFloat.h"
+#include "llvm/ADT/ArrayRef.h"
+
+namespace llvm {
+
+class ArrayType;
+class IntegerType;
+class StructType;
+class PointerType;
+class VectorType;
+class SequentialType;
+
+template<class ConstantClass, class TypeClass, class ValType>
+struct ConstantCreator;
+template<class ConstantClass, class TypeClass>
+struct ConstantArrayCreator;
+template<class ConstantClass, class TypeClass>
+struct ConvertConstantType;
+
+//===----------------------------------------------------------------------===//
+/// This is the shared class of boolean and integer constants. This class
+/// represents both boolean and integral constants.
+/// @brief Class for constant integers.
+class ConstantInt : public Constant {
+ virtual void anchor();
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ ConstantInt(const ConstantInt &) LLVM_DELETED_FUNCTION;
+ ConstantInt(IntegerType *Ty, const APInt& V);
+ APInt Val;
+protected:
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+public:
+ static ConstantInt *getTrue(LLVMContext &Context);
+ static ConstantInt *getFalse(LLVMContext &Context);
+ static Constant *getTrue(Type *Ty);
+ static Constant *getFalse(Type *Ty);
+
+ /// If Ty is a vector type, return a Constant with a splat of the given
+ /// value. Otherwise return a ConstantInt for the given value.
+ static Constant *get(Type *Ty, uint64_t V, bool isSigned = false);
+
+ /// Return a ConstantInt with the specified integer value for the specified
+ /// type. If the type is wider than 64 bits, the value will be zero-extended
+ /// to fit the type, unless isSigned is true, in which case the value will
+ /// be interpreted as a 64-bit signed integer and sign-extended to fit
+ /// the type.
+ /// @brief Get a ConstantInt for a specific value.
+ static ConstantInt *get(IntegerType *Ty, uint64_t V,
+ bool isSigned = false);
+
+ /// Return a ConstantInt with the specified value for the specified type. The
+ /// value V will be canonicalized to a an unsigned APInt. Accessing it with
+ /// either getSExtValue() or getZExtValue() will yield a correctly sized and
+ /// signed value for the type Ty.
+ /// @brief Get a ConstantInt for a specific signed value.
+ static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
+ static Constant *getSigned(Type *Ty, int64_t V);
+
+ /// Return a ConstantInt with the specified value and an implied Type. The
+ /// type is the integer type that corresponds to the bit width of the value.
+ static ConstantInt *get(LLVMContext &Context, const APInt &V);
+
+ /// Return a ConstantInt constructed from the string strStart with the given
+ /// radix.
+ static ConstantInt *get(IntegerType *Ty, StringRef Str,
+ uint8_t radix);
+
+ /// If Ty is a vector type, return a Constant with a splat of the given
+ /// value. Otherwise return a ConstantInt for the given value.
+ static Constant *get(Type* Ty, const APInt& V);
+
+ /// Return the constant as an APInt value reference. This allows clients to
+ /// obtain a copy of the value, with all its precision in tact.
+ /// @brief Return the constant's value.
+ inline const APInt &getValue() const {
+ return Val;
+ }
+
+ /// getBitWidth - Return the bitwidth of this constant.
+ unsigned getBitWidth() const { return Val.getBitWidth(); }
+
+ /// Return the constant as a 64-bit unsigned integer value after it
+ /// has been zero extended as appropriate for the type of this constant. Note
+ /// that this method can assert if the value does not fit in 64 bits.
+ /// @deprecated
+ /// @brief Return the zero extended value.
+ inline uint64_t getZExtValue() const {
+ return Val.getZExtValue();
+ }
+
+ /// Return the constant as a 64-bit integer value after it has been sign
+ /// extended as appropriate for the type of this constant. Note that
+ /// this method can assert if the value does not fit in 64 bits.
+ /// @deprecated
+ /// @brief Return the sign extended value.
+ inline int64_t getSExtValue() const {
+ return Val.getSExtValue();
+ }
+
+ /// A helper method that can be used to determine if the constant contained
+ /// within is equal to a constant. This only works for very small values,
+ /// because this is all that can be represented with all types.
+ /// @brief Determine if this constant's value is same as an unsigned char.
+ bool equalsInt(uint64_t V) const {
+ return Val == V;
+ }
+
+ /// getType - Specialize the getType() method to always return an IntegerType,
+ /// which reduces the amount of casting needed in parts of the compiler.
+ ///
+ inline IntegerType *getType() const {
+ return reinterpret_cast<IntegerType*>(Value::getType());
+ }
+
+ /// This static method returns true if the type Ty is big enough to
+ /// represent the value V. This can be used to avoid having the get method
+ /// assert when V is larger than Ty can represent. Note that there are two
+ /// versions of this method, one for unsigned and one for signed integers.
+ /// Although ConstantInt canonicalizes everything to an unsigned integer,
+ /// the signed version avoids callers having to convert a signed quantity
+ /// to the appropriate unsigned type before calling the method.
+ /// @returns true if V is a valid value for type Ty
+ /// @brief Determine if the value is in range for the given type.
+ static bool isValueValidForType(Type *Ty, uint64_t V);
+ static bool isValueValidForType(Type *Ty, int64_t V);
+
+ bool isNegative() const { return Val.isNegative(); }
+
+ /// This is just a convenience method to make client code smaller for a
+ /// common code. It also correctly performs the comparison without the
+ /// potential for an assertion from getZExtValue().
+ bool isZero() const {
+ return Val == 0;
+ }
+
+ /// This is just a convenience method to make client code smaller for a
+ /// common case. It also correctly performs the comparison without the
+ /// potential for an assertion from getZExtValue().
+ /// @brief Determine if the value is one.
+ bool isOne() const {
+ return Val == 1;
+ }
+
+ /// This function will return true iff every bit in this constant is set
+ /// to true.
+ /// @returns true iff this constant's bits are all set to true.
+ /// @brief Determine if the value is all ones.
+ bool isMinusOne() const {
+ return Val.isAllOnesValue();
+ }
+
+ /// This function will return true iff this constant represents the largest
+ /// value that may be represented by the constant's type.
+ /// @returns true iff this is the largest value that may be represented
+ /// by this type.
+ /// @brief Determine if the value is maximal.
+ bool isMaxValue(bool isSigned) const {
+ if (isSigned)
+ return Val.isMaxSignedValue();
+ else
+ return Val.isMaxValue();
+ }
+
+ /// This function will return true iff this constant represents the smallest
+ /// value that may be represented by this constant's type.
+ /// @returns true if this is the smallest value that may be represented by
+ /// this type.
+ /// @brief Determine if the value is minimal.
+ bool isMinValue(bool isSigned) const {
+ if (isSigned)
+ return Val.isMinSignedValue();
+ else
+ return Val.isMinValue();
+ }
+
+ /// This function will return true iff this constant represents a value with
+ /// active bits bigger than 64 bits or a value greater than the given uint64_t
+ /// value.
+ /// @returns true iff this constant is greater or equal to the given number.
+ /// @brief Determine if the value is greater or equal to the given number.
+ bool uge(uint64_t Num) const {
+ return Val.getActiveBits() > 64 || Val.getZExtValue() >= Num;
+ }
+
+ /// getLimitedValue - If the value is smaller than the specified limit,
+ /// return it, otherwise return the limit value. This causes the value
+ /// to saturate to the limit.
+ /// @returns the min of the value of the constant and the specified value
+ /// @brief Get the constant's value with a saturation limit
+ uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
+ return Val.getLimitedValue(Limit);
+ }
+
+ /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const ConstantInt *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantIntVal;
+ }
+};
+
+
+//===----------------------------------------------------------------------===//
+/// ConstantFP - Floating Point Values [float, double]
+///
+class ConstantFP : public Constant {
+ APFloat Val;
+ virtual void anchor();
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ ConstantFP(const ConstantFP &) LLVM_DELETED_FUNCTION;
+ friend class LLVMContextImpl;
+protected:
+ ConstantFP(Type *Ty, const APFloat& V);
+protected:
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+public:
+ /// Floating point negation must be implemented with f(x) = -0.0 - x. This
+ /// method returns the negative zero constant for floating point or vector
+ /// floating point types; for all other types, it returns the null value.
+ static Constant *getZeroValueForNegation(Type *Ty);
+
+ /// get() - This returns a ConstantFP, or a vector containing a splat of a
+ /// ConstantFP, for the specified value in the specified type. This should
+ /// only be used for simple constant values like 2.0/1.0 etc, that are
+ /// known-valid both as host double and as the target format.
+ static Constant *get(Type* Ty, double V);
+ static Constant *get(Type* Ty, StringRef Str);
+ static ConstantFP *get(LLVMContext &Context, const APFloat &V);
+ static ConstantFP *getNegativeZero(Type* Ty);
+ static ConstantFP *getInfinity(Type *Ty, bool Negative = false);
+
+ /// isValueValidForType - return true if Ty is big enough to represent V.
+ static bool isValueValidForType(Type *Ty, const APFloat &V);
+ inline const APFloat &getValueAPF() const { return Val; }
+
+ /// isZero - Return true if the value is positive or negative zero.
+ bool isZero() const { return Val.isZero(); }
+
+ /// isNegative - Return true if the sign bit is set.
+ bool isNegative() const { return Val.isNegative(); }
+
+ /// isNaN - Return true if the value is a NaN.
+ bool isNaN() const { return Val.isNaN(); }
+
+ /// isExactlyValue - We don't rely on operator== working on double values, as
+ /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
+ /// As such, this method can be used to do an exact bit-for-bit comparison of
+ /// two floating point values. The version with a double operand is retained
+ /// because it's so convenient to write isExactlyValue(2.0), but please use
+ /// it only for simple constants.
+ bool isExactlyValue(const APFloat &V) const;
+
+ bool isExactlyValue(double V) const {
+ bool ignored;
+ // convert is not supported on this type
+ if (&Val.getSemantics() == &APFloat::PPCDoubleDouble)
+ return false;
+ APFloat FV(V);
+ FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
+ return isExactlyValue(FV);
+ }
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ConstantFP *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantFPVal;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// ConstantAggregateZero - All zero aggregate value
+///
+class ConstantAggregateZero : public Constant {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ ConstantAggregateZero(const ConstantAggregateZero &) LLVM_DELETED_FUNCTION;
+protected:
+ explicit ConstantAggregateZero(Type *ty)
+ : Constant(ty, ConstantAggregateZeroVal, 0, 0) {}
+protected:
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+public:
+ static ConstantAggregateZero *get(Type *Ty);
+
+ virtual void destroyConstant();
+
+ /// getSequentialElement - If this CAZ has array or vector type, return a zero
+ /// with the right element type.
+ Constant *getSequentialElement() const;
+
+ /// getStructElement - If this CAZ has struct type, return a zero with the
+ /// right element type for the specified element.
+ Constant *getStructElement(unsigned Elt) const;
+
+ /// getElementValue - Return a zero of the right value for the specified GEP
+ /// index.
+ Constant *getElementValue(Constant *C) const;
+
+ /// getElementValue - Return a zero of the right value for the specified GEP
+ /// index.
+ Constant *getElementValue(unsigned Idx) const;
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ ///
+ static bool classof(const ConstantAggregateZero *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantAggregateZeroVal;
+ }
+};
+
+
+//===----------------------------------------------------------------------===//
+/// ConstantArray - Constant Array Declarations
+///
+class ConstantArray : public Constant {
+ friend struct ConstantArrayCreator<ConstantArray, ArrayType>;
+ ConstantArray(const ConstantArray &) LLVM_DELETED_FUNCTION;
+protected:
+ ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
+public:
+ // ConstantArray accessors
+ static Constant *get(ArrayType *T, ArrayRef<Constant*> V);
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
+
+ /// getType - Specialize the getType() method to always return an ArrayType,
+ /// which reduces the amount of casting needed in parts of the compiler.
+ ///
+ inline ArrayType *getType() const {
+ return reinterpret_cast<ArrayType*>(Value::getType());
+ }
+
+ virtual void destroyConstant();
+ virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ConstantArray *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantArrayVal;
+ }
+};
+
+template <>
+struct OperandTraits<ConstantArray> :
+ public VariadicOperandTraits<ConstantArray> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantArray, Constant)
+
+//===----------------------------------------------------------------------===//
+// ConstantStruct - Constant Struct Declarations
+//
+class ConstantStruct : public Constant {
+ friend struct ConstantArrayCreator<ConstantStruct, StructType>;
+ ConstantStruct(const ConstantStruct &) LLVM_DELETED_FUNCTION;
+protected:
+ ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
+public:
+ // ConstantStruct accessors
+ static Constant *get(StructType *T, ArrayRef<Constant*> V);
+ static Constant *get(StructType *T, ...) END_WITH_NULL;
+
+ /// getAnon - Return an anonymous struct that has the specified
+ /// elements. If the struct is possibly empty, then you must specify a
+ /// context.
+ static Constant *getAnon(ArrayRef<Constant*> V, bool Packed = false) {
+ return get(getTypeForElements(V, Packed), V);
+ }
+ static Constant *getAnon(LLVMContext &Ctx,
+ ArrayRef<Constant*> V, bool Packed = false) {
+ return get(getTypeForElements(Ctx, V, Packed), V);
+ }
+
+ /// getTypeForElements - Return an anonymous struct type to use for a constant
+ /// with the specified set of elements. The list must not be empty.
+ static StructType *getTypeForElements(ArrayRef<Constant*> V,
+ bool Packed = false);
+ /// getTypeForElements - This version of the method allows an empty list.
+ static StructType *getTypeForElements(LLVMContext &Ctx,
+ ArrayRef<Constant*> V,
+ bool Packed = false);
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
+
+ /// getType() specialization - Reduce amount of casting...
+ ///
+ inline StructType *getType() const {
+ return reinterpret_cast<StructType*>(Value::getType());
+ }
+
+ virtual void destroyConstant();
+ virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ConstantStruct *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantStructVal;
+ }
+};
+
+template <>
+struct OperandTraits<ConstantStruct> :
+ public VariadicOperandTraits<ConstantStruct> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantStruct, Constant)
+
+
+//===----------------------------------------------------------------------===//
+/// ConstantVector - Constant Vector Declarations
+///
+class ConstantVector : public Constant {
+ friend struct ConstantArrayCreator<ConstantVector, VectorType>;
+ ConstantVector(const ConstantVector &) LLVM_DELETED_FUNCTION;
+protected:
+ ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
+public:
+ // ConstantVector accessors
+ static Constant *get(ArrayRef<Constant*> V);
+
+ /// getSplat - Return a ConstantVector with the specified constant in each
+ /// element.
+ static Constant *getSplat(unsigned NumElts, Constant *Elt);
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
+
+ /// getType - Specialize the getType() method to always return a VectorType,
+ /// which reduces the amount of casting needed in parts of the compiler.
+ ///
+ inline VectorType *getType() const {
+ return reinterpret_cast<VectorType*>(Value::getType());
+ }
+
+ /// getSplatValue - If this is a splat constant, meaning that all of the
+ /// elements have the same value, return that value. Otherwise return NULL.
+ Constant *getSplatValue() const;
+
+ virtual void destroyConstant();
+ virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ConstantVector *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantVectorVal;
+ }
+};
+
+template <>
+struct OperandTraits<ConstantVector> :
+ public VariadicOperandTraits<ConstantVector> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantVector, Constant)
+
+//===----------------------------------------------------------------------===//
+/// ConstantPointerNull - a constant pointer value that points to null
+///
+class ConstantPointerNull : public Constant {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ ConstantPointerNull(const ConstantPointerNull &) LLVM_DELETED_FUNCTION;
+protected:
+ explicit ConstantPointerNull(PointerType *T)
+ : Constant(reinterpret_cast<Type*>(T),
+ Value::ConstantPointerNullVal, 0, 0) {}
+
+protected:
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+public:
+ /// get() - Static factory methods - Return objects of the specified value
+ static ConstantPointerNull *get(PointerType *T);
+
+ virtual void destroyConstant();
+
+ /// getType - Specialize the getType() method to always return an PointerType,
+ /// which reduces the amount of casting needed in parts of the compiler.
+ ///
+ inline PointerType *getType() const {
+ return reinterpret_cast<PointerType*>(Value::getType());
+ }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ConstantPointerNull *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantPointerNullVal;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// ConstantDataSequential - A vector or array constant whose element type is a
+/// simple 1/2/4/8-byte integer or float/double, and whose elements are just
+/// simple data values (i.e. ConstantInt/ConstantFP). This Constant node has no
+/// operands because it stores all of the elements of the constant as densely
+/// packed data, instead of as Value*'s.
+///
+/// This is the common base class of ConstantDataArray and ConstantDataVector.
+///
+class ConstantDataSequential : public Constant {
+ friend class LLVMContextImpl;
+ /// DataElements - A pointer to the bytes underlying this constant (which is
+ /// owned by the uniquing StringMap).
+ const char *DataElements;
+
+ /// Next - This forms a link list of ConstantDataSequential nodes that have
+ /// the same value but different type. For example, 0,0,0,1 could be a 4
+ /// element array of i8, or a 1-element array of i32. They'll both end up in
+ /// the same StringMap bucket, linked up.
+ ConstantDataSequential *Next;
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ ConstantDataSequential(const ConstantDataSequential &) LLVM_DELETED_FUNCTION;
+protected:
+ explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
+ : Constant(ty, VT, 0, 0), DataElements(Data), Next(0) {}
+ ~ConstantDataSequential() { delete Next; }
+
+ static Constant *getImpl(StringRef Bytes, Type *Ty);
+
+protected:
+ // allocate space for exactly zero operands.
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+public:
+
+ /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
+ /// formed with a vector or array of the specified element type.
+ /// ConstantDataArray only works with normal float and int types that are
+ /// stored densely in memory, not with things like i42 or x86_f80.
+ static bool isElementTypeCompatible(const Type *Ty);
+
+ /// getElementAsInteger - If this is a sequential container of integers (of
+ /// any size), return the specified element in the low bits of a uint64_t.
+ uint64_t getElementAsInteger(unsigned i) const;
+
+ /// getElementAsAPFloat - If this is a sequential container of floating point
+ /// type, return the specified element as an APFloat.
+ APFloat getElementAsAPFloat(unsigned i) const;
+
+ /// getElementAsFloat - If this is an sequential container of floats, return
+ /// the specified element as a float.
+ float getElementAsFloat(unsigned i) const;
+
+ /// getElementAsDouble - If this is an sequential container of doubles, return
+ /// the specified element as a double.
+ double getElementAsDouble(unsigned i) const;
+
+ /// getElementAsConstant - Return a Constant for a specified index's element.
+ /// Note that this has to compute a new constant to return, so it isn't as
+ /// efficient as getElementAsInteger/Float/Double.
+ Constant *getElementAsConstant(unsigned i) const;
+
+ /// getType - Specialize the getType() method to always return a
+ /// SequentialType, which reduces the amount of casting needed in parts of the
+ /// compiler.
+ inline SequentialType *getType() const {
+ return reinterpret_cast<SequentialType*>(Value::getType());
+ }
+
+ /// getElementType - Return the element type of the array/vector.
+ Type *getElementType() const;
+
+ /// getNumElements - Return the number of elements in the array or vector.
+ unsigned getNumElements() const;
+
+ /// getElementByteSize - Return the size (in bytes) of each element in the
+ /// array/vector. The size of the elements is known to be a multiple of one
+ /// byte.
+ uint64_t getElementByteSize() const;
+
+
+ /// isString - This method returns true if this is an array of i8.
+ bool isString() const;
+
+ /// isCString - This method returns true if the array "isString", ends with a
+ /// nul byte, and does not contains any other nul bytes.
+ bool isCString() const;
+
+ /// getAsString - If this array is isString(), then this method returns the
+ /// array as a StringRef. Otherwise, it asserts out.
+ ///
+ StringRef getAsString() const {
+ assert(isString() && "Not a string");
+ return getRawDataValues();
+ }
+
+ /// getAsCString - If this array is isCString(), then this method returns the
+ /// array (without the trailing null byte) as a StringRef. Otherwise, it
+ /// asserts out.
+ ///
+ StringRef getAsCString() const {
+ assert(isCString() && "Isn't a C string");
+ StringRef Str = getAsString();
+ return Str.substr(0, Str.size()-1);
+ }
+
+ /// getRawDataValues - Return the raw, underlying, bytes of this data. Note
+ /// that this is an extremely tricky thing to work with, as it exposes the
+ /// host endianness of the data elements.
+ StringRef getRawDataValues() const;
+
+ virtual void destroyConstant();
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ ///
+ static bool classof(const ConstantDataSequential *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantDataArrayVal ||
+ V->getValueID() == ConstantDataVectorVal;
+ }
+private:
+ const char *getElementPointer(unsigned Elt) const;
+};
+
+//===----------------------------------------------------------------------===//
+/// ConstantDataArray - An array constant whose element type is a simple
+/// 1/2/4/8-byte integer or float/double, and whose elements are just simple
+/// data values (i.e. ConstantInt/ConstantFP). This Constant node has no
+/// operands because it stores all of the elements of the constant as densely
+/// packed data, instead of as Value*'s.
+class ConstantDataArray : public ConstantDataSequential {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ ConstantDataArray(const ConstantDataArray &) LLVM_DELETED_FUNCTION;
+ virtual void anchor();
+ friend class ConstantDataSequential;
+ explicit ConstantDataArray(Type *ty, const char *Data)
+ : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
+protected:
+ // allocate space for exactly zero operands.
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+public:
+
+ /// get() constructors - Return a constant with array type with an element
+ /// count and element type matching the ArrayRef passed in. Note that this
+ /// can return a ConstantAggregateZero object.
+ static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
+
+ /// getString - This method constructs a CDS and initializes it with a text
+ /// string. The default behavior (AddNull==true) causes a null terminator to
+ /// be placed at the end of the array (increasing the length of the string by
+ /// one more than the StringRef would normally indicate. Pass AddNull=false
+ /// to disable this behavior.
+ static Constant *getString(LLVMContext &Context, StringRef Initializer,
+ bool AddNull = true);
+
+ /// getType - Specialize the getType() method to always return an ArrayType,
+ /// which reduces the amount of casting needed in parts of the compiler.
+ ///
+ inline ArrayType *getType() const {
+ return reinterpret_cast<ArrayType*>(Value::getType());
+ }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ ///
+ static bool classof(const ConstantDataArray *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantDataArrayVal;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// ConstantDataVector - A vector constant whose element type is a simple
+/// 1/2/4/8-byte integer or float/double, and whose elements are just simple
+/// data values (i.e. ConstantInt/ConstantFP). This Constant node has no
+/// operands because it stores all of the elements of the constant as densely
+/// packed data, instead of as Value*'s.
+class ConstantDataVector : public ConstantDataSequential {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ ConstantDataVector(const ConstantDataVector &) LLVM_DELETED_FUNCTION;
+ virtual void anchor();
+ friend class ConstantDataSequential;
+ explicit ConstantDataVector(Type *ty, const char *Data)
+ : ConstantDataSequential(ty, ConstantDataVectorVal, Data) {}
+protected:
+ // allocate space for exactly zero operands.
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+public:
+
+ /// get() constructors - Return a constant with vector type with an element
+ /// count and element type matching the ArrayRef passed in. Note that this
+ /// can return a ConstantAggregateZero object.
+ static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
+ static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
+
+ /// getSplat - Return a ConstantVector with the specified constant in each
+ /// element. The specified constant has to be a of a compatible type (i8/i16/
+ /// i32/i64/float/double) and must be a ConstantFP or ConstantInt.
+ static Constant *getSplat(unsigned NumElts, Constant *Elt);
+
+ /// getSplatValue - If this is a splat constant, meaning that all of the
+ /// elements have the same value, return that value. Otherwise return NULL.
+ Constant *getSplatValue() const;
+
+ /// getType - Specialize the getType() method to always return a VectorType,
+ /// which reduces the amount of casting needed in parts of the compiler.
+ ///
+ inline VectorType *getType() const {
+ return reinterpret_cast<VectorType*>(Value::getType());
+ }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ ///
+ static bool classof(const ConstantDataVector *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == ConstantDataVectorVal;
+ }
+};
+
+
+
+/// BlockAddress - The address of a basic block.
+///
+class BlockAddress : public Constant {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ void *operator new(size_t s) { return User::operator new(s, 2); }
+ BlockAddress(Function *F, BasicBlock *BB);
+public:
+ /// get - Return a BlockAddress for the specified function and basic block.
+ static BlockAddress *get(Function *F, BasicBlock *BB);
+
+ /// get - Return a BlockAddress for the specified basic block. The basic
+ /// block must be embedded into a function.
+ static BlockAddress *get(BasicBlock *BB);
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ Function *getFunction() const { return (Function*)Op<0>().get(); }
+ BasicBlock *getBasicBlock() const { return (BasicBlock*)Op<1>().get(); }
+
+ virtual void destroyConstant();
+ virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const BlockAddress *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == BlockAddressVal;
+ }
+};
+
+template <>
+struct OperandTraits<BlockAddress> :
+ public FixedNumOperandTraits<BlockAddress, 2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)
+
+
+//===----------------------------------------------------------------------===//
+/// ConstantExpr - a constant value that is initialized with an expression using
+/// other constant values.
+///
+/// This class uses the standard Instruction opcodes to define the various
+/// constant expressions. The Opcode field for the ConstantExpr class is
+/// maintained in the Value::SubclassData field.
+class ConstantExpr : public Constant {
+ friend struct ConstantCreator<ConstantExpr,Type,
+ std::pair<unsigned, std::vector<Constant*> > >;
+ friend struct ConvertConstantType<ConstantExpr, Type>;
+
+protected:
+ ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
+ : Constant(ty, ConstantExprVal, Ops, NumOps) {
+ // Operation type (an Instruction opcode) is stored as the SubclassData.
+ setValueSubclassData(Opcode);
+ }
+
+public:
+ // Static methods to construct a ConstantExpr of different kinds. Note that
+ // these methods may return a object that is not an instance of the
+ // ConstantExpr class, because they will attempt to fold the constant
+ // expression into something simpler if possible.
+
+ /// getAlignOf constant expr - computes the alignment of a type in a target
+ /// independent way (Note: the return type is an i64).
+ static Constant *getAlignOf(Type *Ty);
+
+ /// getSizeOf constant expr - computes the (alloc) size of a type (in
+ /// address-units, not bits) in a target independent way (Note: the return
+ /// type is an i64).
+ ///
+ static Constant *getSizeOf(Type *Ty);
+
+ /// getOffsetOf constant expr - computes the offset of a struct field in a
+ /// target independent way (Note: the return type is an i64).
+ ///
+ static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
+
+ /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
+ /// which supports any aggregate type, and any Constant index.
+ ///
+ static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
+
+ static Constant *getNeg(Constant *C, bool HasNUW = false, bool HasNSW =false);
+ static Constant *getFNeg(Constant *C);
+ static Constant *getNot(Constant *C);
+ static Constant *getAdd(Constant *C1, Constant *C2,
+ bool HasNUW = false, bool HasNSW = false);
+ static Constant *getFAdd(Constant *C1, Constant *C2);
+ static Constant *getSub(Constant *C1, Constant *C2,
+ bool HasNUW = false, bool HasNSW = false);
+ static Constant *getFSub(Constant *C1, Constant *C2);
+ static Constant *getMul(Constant *C1, Constant *C2,
+ bool HasNUW = false, bool HasNSW = false);
+ static Constant *getFMul(Constant *C1, Constant *C2);
+ static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false);
+ static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false);
+ static Constant *getFDiv(Constant *C1, Constant *C2);
+ static Constant *getURem(Constant *C1, Constant *C2);
+ static Constant *getSRem(Constant *C1, Constant *C2);
+ static Constant *getFRem(Constant *C1, Constant *C2);
+ static Constant *getAnd(Constant *C1, Constant *C2);
+ static Constant *getOr(Constant *C1, Constant *C2);
+ static Constant *getXor(Constant *C1, Constant *C2);
+ static Constant *getShl(Constant *C1, Constant *C2,
+ bool HasNUW = false, bool HasNSW = false);
+ static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
+ static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
+ static Constant *getTrunc (Constant *C, Type *Ty);
+ static Constant *getSExt (Constant *C, Type *Ty);
+ static Constant *getZExt (Constant *C, Type *Ty);
+ static Constant *getFPTrunc (Constant *C, Type *Ty);
+ static Constant *getFPExtend(Constant *C, Type *Ty);
+ static Constant *getUIToFP (Constant *C, Type *Ty);
+ static Constant *getSIToFP (Constant *C, Type *Ty);
+ static Constant *getFPToUI (Constant *C, Type *Ty);
+ static Constant *getFPToSI (Constant *C, Type *Ty);
+ static Constant *getPtrToInt(Constant *C, Type *Ty);
+ static Constant *getIntToPtr(Constant *C, Type *Ty);
+ static Constant *getBitCast (Constant *C, Type *Ty);
+
+ static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
+ static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
+ static Constant *getNSWAdd(Constant *C1, Constant *C2) {
+ return getAdd(C1, C2, false, true);
+ }
+ static Constant *getNUWAdd(Constant *C1, Constant *C2) {
+ return getAdd(C1, C2, true, false);
+ }
+ static Constant *getNSWSub(Constant *C1, Constant *C2) {
+ return getSub(C1, C2, false, true);
+ }
+ static Constant *getNUWSub(Constant *C1, Constant *C2) {
+ return getSub(C1, C2, true, false);
+ }
+ static Constant *getNSWMul(Constant *C1, Constant *C2) {
+ return getMul(C1, C2, false, true);
+ }
+ static Constant *getNUWMul(Constant *C1, Constant *C2) {
+ return getMul(C1, C2, true, false);
+ }
+ static Constant *getNSWShl(Constant *C1, Constant *C2) {
+ return getShl(C1, C2, false, true);
+ }
+ static Constant *getNUWShl(Constant *C1, Constant *C2) {
+ return getShl(C1, C2, true, false);
+ }
+ static Constant *getExactSDiv(Constant *C1, Constant *C2) {
+ return getSDiv(C1, C2, true);
+ }
+ static Constant *getExactUDiv(Constant *C1, Constant *C2) {
+ return getUDiv(C1, C2, true);
+ }
+ static Constant *getExactAShr(Constant *C1, Constant *C2) {
+ return getAShr(C1, C2, true);
+ }
+ static Constant *getExactLShr(Constant *C1, Constant *C2) {
+ return getLShr(C1, C2, true);
+ }
+
+ /// getBinOpIdentity - Return the identity for the given binary operation,
+ /// i.e. a constant C such that X op C = X and C op X = X for every X. It
+ /// returns null if the operator doesn't have an identity.
+ static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty);
+
+ /// getBinOpAbsorber - Return the absorbing element for the given binary
+ /// operation, i.e. a constant C such that X op C = C and C op X = C for
+ /// every X. For example, this returns zero for integer multiplication.
+ /// It returns null if the operator doesn't have an absorbing element.
+ static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
+
+ // @brief Convenience function for getting one of the casting operations
+ // using a CastOps opcode.
+ static Constant *getCast(
+ unsigned ops, ///< The opcode for the conversion
+ Constant *C, ///< The constant to be converted
+ Type *Ty ///< The type to which the constant is converted
+ );
+
+ // @brief Create a ZExt or BitCast cast constant expression
+ static Constant *getZExtOrBitCast(
+ Constant *C, ///< The constant to zext or bitcast
+ Type *Ty ///< The type to zext or bitcast C to
+ );
+
+ // @brief Create a SExt or BitCast cast constant expression
+ static Constant *getSExtOrBitCast(
+ Constant *C, ///< The constant to sext or bitcast
+ Type *Ty ///< The type to sext or bitcast C to
+ );
+
+ // @brief Create a Trunc or BitCast cast constant expression
+ static Constant *getTruncOrBitCast(
+ Constant *C, ///< The constant to trunc or bitcast
+ Type *Ty ///< The type to trunc or bitcast C to
+ );
+
+ /// @brief Create a BitCast or a PtrToInt cast constant expression
+ static Constant *getPointerCast(
+ Constant *C, ///< The pointer value to be casted (operand 0)
+ Type *Ty ///< The type to which cast should be made
+ );
+
+ /// @brief Create a ZExt, Bitcast or Trunc for integer -> integer casts
+ static Constant *getIntegerCast(
+ Constant *C, ///< The integer constant to be casted
+ Type *Ty, ///< The integer type to cast to
+ bool isSigned ///< Whether C should be treated as signed or not
+ );
+
+ /// @brief Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
+ static Constant *getFPCast(
+ Constant *C, ///< The integer constant to be casted
+ Type *Ty ///< The integer type to cast to
+ );
+
+ /// @brief Return true if this is a convert constant expression
+ bool isCast() const;
+
+ /// @brief Return true if this is a compare constant expression
+ bool isCompare() const;
+
+ /// @brief Return true if this is an insertvalue or extractvalue expression,
+ /// and the getIndices() method may be used.
+ bool hasIndices() const;
+
+ /// @brief Return true if this is a getelementptr expression and all
+ /// the index operands are compile-time known integers within the
+ /// corresponding notional static array extents. Note that this is
+ /// not equivalant to, a subset of, or a superset of the "inbounds"
+ /// property.
+ bool isGEPWithNoNotionalOverIndexing() const;
+
+ /// Select constant expr
+ ///
+ static Constant *getSelect(Constant *C, Constant *V1, Constant *V2);
+
+ /// get - Return a binary or shift operator constant expression,
+ /// folding if possible.
+ ///
+ static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
+ unsigned Flags = 0);
+
+ /// @brief Return an ICmp or FCmp comparison operator constant expression.
+ static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2);
+
+ /// get* - Return some common constants without having to
+ /// specify the full Instruction::OPCODE identifier.
+ ///
+ static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS);
+ static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS);
+
+ /// Getelementptr form. Value* is only accepted for convenience;
+ /// all elements must be Constant's.
+ ///
+ static Constant *getGetElementPtr(Constant *C,
+ ArrayRef<Constant *> IdxList,
+ bool InBounds = false) {
+ return getGetElementPtr(C, makeArrayRef((Value * const *)IdxList.data(),
+ IdxList.size()),
+ InBounds);
+ }
+ static Constant *getGetElementPtr(Constant *C,
+ Constant *Idx,
+ bool InBounds = false) {
+ // This form of the function only exists to avoid ambiguous overload
+ // warnings about whether to convert Idx to ArrayRef<Constant *> or
+ // ArrayRef<Value *>.
+ return getGetElementPtr(C, cast<Value>(Idx), InBounds);
+ }
+ static Constant *getGetElementPtr(Constant *C,
+ ArrayRef<Value *> IdxList,
+ bool InBounds = false);
+
+ /// Create an "inbounds" getelementptr. See the documentation for the
+ /// "inbounds" flag in LangRef.html for details.
+ static Constant *getInBoundsGetElementPtr(Constant *C,
+ ArrayRef<Constant *> IdxList) {
+ return getGetElementPtr(C, IdxList, true);
+ }
+ static Constant *getInBoundsGetElementPtr(Constant *C,
+ Constant *Idx) {
+ // This form of the function only exists to avoid ambiguous overload
+ // warnings about whether to convert Idx to ArrayRef<Constant *> or
+ // ArrayRef<Value *>.
+ return getGetElementPtr(C, Idx, true);
+ }
+ static Constant *getInBoundsGetElementPtr(Constant *C,
+ ArrayRef<Value *> IdxList) {
+ return getGetElementPtr(C, IdxList, true);
+ }
+
+ static Constant *getExtractElement(Constant *Vec, Constant *Idx);
+ static Constant *getInsertElement(Constant *Vec, Constant *Elt,Constant *Idx);
+ static Constant *getShuffleVector(Constant *V1, Constant *V2, Constant *Mask);
+ static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs);
+ static Constant *getInsertValue(Constant *Agg, Constant *Val,
+ ArrayRef<unsigned> Idxs);
+
+ /// getOpcode - Return the opcode at the root of this constant expression
+ unsigned getOpcode() const { return getSubclassDataFromValue(); }
+
+ /// getPredicate - Return the ICMP or FCMP predicate value. Assert if this is
+ /// not an ICMP or FCMP constant expression.
+ unsigned getPredicate() const;
+
+ /// getIndices - Assert that this is an insertvalue or exactvalue
+ /// expression and return the list of indices.
+ ArrayRef<unsigned> getIndices() const;
+
+ /// getOpcodeName - Return a string representation for an opcode.
+ const char *getOpcodeName() const;
+
+ /// getWithOperandReplaced - Return a constant expression identical to this
+ /// one, but with the specified operand set to the specified value.
+ Constant *getWithOperandReplaced(unsigned OpNo, Constant *Op) const;
+
+ /// getWithOperands - This returns the current constant expression with the
+ /// operands replaced with the specified values. The specified array must
+ /// have the same number of operands as our current one.
+ Constant *getWithOperands(ArrayRef<Constant*> Ops) const {
+ return getWithOperands(Ops, getType());
+ }
+
+ /// getWithOperands - This returns the current constant expression with the
+ /// operands replaced with the specified values and with the specified result
+ /// type. The specified array must have the same number of operands as our
+ /// current one.
+ Constant *getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const;
+
+ virtual void destroyConstant();
+ virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ConstantExpr *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == ConstantExprVal;
+ }
+
+private:
+ // Shadow Value::setValueSubclassData with a private forwarding method so that
+ // subclasses cannot accidentally use it.
+ void setValueSubclassData(unsigned short D) {
+ Value::setValueSubclassData(D);
+ }
+};
+
+template <>
+struct OperandTraits<ConstantExpr> :
+ public VariadicOperandTraits<ConstantExpr, 1> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)
+
+//===----------------------------------------------------------------------===//
+/// UndefValue - 'undef' values are things that do not have specified contents.
+/// These are used for a variety of purposes, including global variable
+/// initializers and operands to instructions. 'undef' values can occur with
+/// any first-class type.
+///
+/// Undef values aren't exactly constants; if they have multiple uses, they
+/// can appear to have different bit patterns at each use. See
+/// LangRef.html#undefvalues for details.
+///
+class UndefValue : public Constant {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ UndefValue(const UndefValue &) LLVM_DELETED_FUNCTION;
+protected:
+ explicit UndefValue(Type *T) : Constant(T, UndefValueVal, 0, 0) {}
+protected:
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+public:
+ /// get() - Static factory methods - Return an 'undef' object of the specified
+ /// type.
+ ///
+ static UndefValue *get(Type *T);
+
+ /// getSequentialElement - If this Undef has array or vector type, return a
+ /// undef with the right element type.
+ UndefValue *getSequentialElement() const;
+
+ /// getStructElement - If this undef has struct type, return a undef with the
+ /// right element type for the specified element.
+ UndefValue *getStructElement(unsigned Elt) const;
+
+ /// getElementValue - Return an undef of the right value for the specified GEP
+ /// index.
+ UndefValue *getElementValue(Constant *C) const;
+
+ /// getElementValue - Return an undef of the right value for the specified GEP
+ /// index.
+ UndefValue *getElementValue(unsigned Idx) const;
+
+ virtual void destroyConstant();
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const UndefValue *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == UndefValueVal;
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/DIBuilder.h b/include/llvm/DIBuilder.h
new file mode 100644
index 00000000000..80880094d22
--- /dev/null
+++ b/include/llvm/DIBuilder.h
@@ -0,0 +1,568 @@
+//===--- llvm/DIBuilder.h - Debug Information Builder -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a DIBuilder that is useful for creating debugging
+// information entries in LLVM IR form.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_DIBUILDER_H
+#define LLVM_ANALYSIS_DIBUILDER_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+ class BasicBlock;
+ class Instruction;
+ class Function;
+ class Module;
+ class Value;
+ class LLVMContext;
+ class MDNode;
+ class StringRef;
+ class DIDescriptor;
+ class DIFile;
+ class DIEnumerator;
+ class DIType;
+ class DIArray;
+ class DIGlobalVariable;
+ class DINameSpace;
+ class DIVariable;
+ class DISubrange;
+ class DILexicalBlockFile;
+ class DILexicalBlock;
+ class DISubprogram;
+ class DITemplateTypeParameter;
+ class DITemplateValueParameter;
+ class DIObjCProperty;
+
+ class DIBuilder {
+ private:
+ Module &M;
+ LLVMContext & VMContext;
+ MDNode *TheCU;
+
+ MDNode *TempEnumTypes;
+ MDNode *TempRetainTypes;
+ MDNode *TempSubprograms;
+ MDNode *TempGVs;
+
+ Function *DeclareFn; // llvm.dbg.declare
+ Function *ValueFn; // llvm.dbg.value
+
+ SmallVector<Value *, 4> AllEnumTypes;
+ SmallVector<Value *, 4> AllRetainTypes;
+ SmallVector<Value *, 4> AllSubprograms;
+ SmallVector<Value *, 4> AllGVs;
+
+ DIBuilder(const DIBuilder &) LLVM_DELETED_FUNCTION;
+ void operator=(const DIBuilder &) LLVM_DELETED_FUNCTION;
+
+ public:
+ explicit DIBuilder(Module &M);
+ const MDNode *getCU() { return TheCU; }
+ enum ComplexAddrKind { OpPlus=1, OpDeref };
+
+ /// finalize - Construct any deferred debug info descriptors.
+ void finalize();
+
+ /// createCompileUnit - A CompileUnit provides an anchor for all debugging
+ /// information generated during this instance of compilation.
+ /// @param Lang Source programming language, eg. dwarf::DW_LANG_C99
+ /// @param File File name
+ /// @param Dir Directory
+ /// @param Producer String identify producer of debugging information.
+ /// Usuall this is a compiler version string.
+ /// @param isOptimized A boolean flag which indicates whether optimization
+ /// is ON or not.
+ /// @param Flags This string lists command line options. This string is
+ /// directly embedded in debug info output which may be used
+ /// by a tool analyzing generated debugging information.
+ /// @param RV This indicates runtime version for languages like
+ /// Objective-C.
+ void createCompileUnit(unsigned Lang, StringRef File, StringRef Dir,
+ StringRef Producer,
+ bool isOptimized, StringRef Flags, unsigned RV);
+
+ /// createFile - Create a file descriptor to hold debugging information
+ /// for a file.
+ DIFile createFile(StringRef Filename, StringRef Directory);
+
+ /// createEnumerator - Create a single enumerator value.
+ DIEnumerator createEnumerator(StringRef Name, uint64_t Val);
+
+ /// createNullPtrType - Create C++0x nullptr type.
+ DIType createNullPtrType(StringRef Name);
+
+ /// createBasicType - Create debugging information entry for a basic
+ /// type.
+ /// @param Name Type name.
+ /// @param SizeInBits Size of the type.
+ /// @param AlignInBits Type alignment.
+ /// @param Encoding DWARF encoding code, e.g. dwarf::DW_ATE_float.
+ DIType createBasicType(StringRef Name, uint64_t SizeInBits,
+ uint64_t AlignInBits, unsigned Encoding);
+
+ /// createQualifiedType - Create debugging information entry for a qualified
+ /// type, e.g. 'const int'.
+ /// @param Tag Tag identifing type, e.g. dwarf::TAG_volatile_type
+ /// @param FromTy Base Type.
+ DIType createQualifiedType(unsigned Tag, DIType FromTy);
+
+ /// createPointerType - Create debugging information entry for a pointer.
+ /// @param PointeeTy Type pointed by this pointer.
+ /// @param SizeInBits Size.
+ /// @param AlignInBits Alignment. (optional)
+ /// @param Name Pointer type name. (optional)
+ DIType createPointerType(DIType PointeeTy, uint64_t SizeInBits,
+ uint64_t AlignInBits = 0,
+ StringRef Name = StringRef());
+
+ /// createReferenceType - Create debugging information entry for a c++
+ /// style reference or rvalue reference type.
+ DIType createReferenceType(unsigned Tag, DIType RTy);
+
+ /// createTypedef - Create debugging information entry for a typedef.
+ /// @param Ty Original type.
+ /// @param Name Typedef name.
+ /// @param File File where this type is defined.
+ /// @param LineNo Line number.
+ /// @param Context The surrounding context for the typedef.
+ DIType createTypedef(DIType Ty, StringRef Name, DIFile File,
+ unsigned LineNo, DIDescriptor Context);
+
+ /// createFriend - Create debugging information entry for a 'friend'.
+ DIType createFriend(DIType Ty, DIType FriendTy);
+
+ /// createInheritance - Create debugging information entry to establish
+ /// inheritance relationship between two types.
+ /// @param Ty Original type.
+ /// @param BaseTy Base type. Ty is inherits from base.
+ /// @param BaseOffset Base offset.
+ /// @param Flags Flags to describe inheritance attribute,
+ /// e.g. private
+ DIType createInheritance(DIType Ty, DIType BaseTy, uint64_t BaseOffset,
+ unsigned Flags);
+
+ /// createMemberType - Create debugging information entry for a member.
+ /// @param Scope Member scope.
+ /// @param Name Member name.
+ /// @param File File where this member is defined.
+ /// @param LineNo Line number.
+ /// @param SizeInBits Member size.
+ /// @param AlignInBits Member alignment.
+ /// @param OffsetInBits Member offset.
+ /// @param Flags Flags to encode member attribute, e.g. private
+ /// @param Ty Parent type.
+ DIType createMemberType(DIDescriptor Scope, StringRef Name, DIFile File,
+ unsigned LineNo, uint64_t SizeInBits,
+ uint64_t AlignInBits, uint64_t OffsetInBits,
+ unsigned Flags, DIType Ty);
+
+ /// createObjCIVar - Create debugging information entry for Objective-C
+ /// instance variable.
+ /// @param Name Member name.
+ /// @param File File where this member is defined.
+ /// @param LineNo Line number.
+ /// @param SizeInBits Member size.
+ /// @param AlignInBits Member alignment.
+ /// @param OffsetInBits Member offset.
+ /// @param Flags Flags to encode member attribute, e.g. private
+ /// @param Ty Parent type.
+ /// @param PropertyName Name of the Objective C property associated with
+ /// this ivar.
+ /// @param PropertyGetterName Name of the Objective C property getter
+ /// selector.
+ /// @param PropertySetterName Name of the Objective C property setter
+ /// selector.
+ /// @param PropertyAttributes Objective C property attributes.
+ DIType createObjCIVar(StringRef Name, DIFile File,
+ unsigned LineNo, uint64_t SizeInBits,
+ uint64_t AlignInBits, uint64_t OffsetInBits,
+ unsigned Flags, DIType Ty,
+ StringRef PropertyName = StringRef(),
+ StringRef PropertyGetterName = StringRef(),
+ StringRef PropertySetterName = StringRef(),
+ unsigned PropertyAttributes = 0);
+
+ /// createObjCIVar - Create debugging information entry for Objective-C
+ /// instance variable.
+ /// @param Name Member name.
+ /// @param File File where this member is defined.
+ /// @param LineNo Line number.
+ /// @param SizeInBits Member size.
+ /// @param AlignInBits Member alignment.
+ /// @param OffsetInBits Member offset.
+ /// @param Flags Flags to encode member attribute, e.g. private
+ /// @param Ty Parent type.
+ /// @param PropertyNode Property associated with this ivar.
+ DIType createObjCIVar(StringRef Name, DIFile File,
+ unsigned LineNo, uint64_t SizeInBits,
+ uint64_t AlignInBits, uint64_t OffsetInBits,
+ unsigned Flags, DIType Ty,
+ MDNode *PropertyNode);
+
+ /// createObjCProperty - Create debugging information entry for Objective-C
+ /// property.
+ /// @param Name Property name.
+ /// @param File File where this property is defined.
+ /// @param LineNumber Line number.
+ /// @param GetterName Name of the Objective C property getter selector.
+ /// @param SetterName Name of the Objective C property setter selector.
+ /// @param PropertyAttributes Objective C property attributes.
+ /// @param Ty Type.
+ DIObjCProperty createObjCProperty(StringRef Name,
+ DIFile File, unsigned LineNumber,
+ StringRef GetterName,
+ StringRef SetterName,
+ unsigned PropertyAttributes,
+ DIType Ty);
+
+ /// createClassType - Create debugging information entry for a class.
+ /// @param Scope Scope in which this class is defined.
+ /// @param Name class name.
+ /// @param File File where this member is defined.
+ /// @param LineNumber Line number.
+ /// @param SizeInBits Member size.
+ /// @param AlignInBits Member alignment.
+ /// @param OffsetInBits Member offset.
+ /// @param Flags Flags to encode member attribute, e.g. private
+ /// @param Elements class members.
+ /// @param VTableHolder Debug info of the base class that contains vtable
+ /// for this type. This is used in
+ /// DW_AT_containing_type. See DWARF documentation
+ /// for more info.
+ /// @param TemplateParms Template type parameters.
+ DIType createClassType(DIDescriptor Scope, StringRef Name, DIFile File,
+ unsigned LineNumber, uint64_t SizeInBits,
+ uint64_t AlignInBits, uint64_t OffsetInBits,
+ unsigned Flags, DIType DerivedFrom,
+ DIArray Elements, MDNode *VTableHolder = 0,
+ MDNode *TemplateParms = 0);
+
+ /// createStructType - Create debugging information entry for a struct.
+ /// @param Scope Scope in which this struct is defined.
+ /// @param Name Struct name.
+ /// @param File File where this member is defined.
+ /// @param LineNumber Line number.
+ /// @param SizeInBits Member size.
+ /// @param AlignInBits Member alignment.
+ /// @param Flags Flags to encode member attribute, e.g. private
+ /// @param Elements Struct elements.
+ /// @param RunTimeLang Optional parameter, Objective-C runtime version.
+ DIType createStructType(DIDescriptor Scope, StringRef Name, DIFile File,
+ unsigned LineNumber, uint64_t SizeInBits,
+ uint64_t AlignInBits, unsigned Flags,
+ DIArray Elements, unsigned RunTimeLang = 0);
+
+ /// createUnionType - Create debugging information entry for an union.
+ /// @param Scope Scope in which this union is defined.
+ /// @param Name Union name.
+ /// @param File File where this member is defined.
+ /// @param LineNumber Line number.
+ /// @param SizeInBits Member size.
+ /// @param AlignInBits Member alignment.
+ /// @param Flags Flags to encode member attribute, e.g. private
+ /// @param Elements Union elements.
+ /// @param RunTimeLang Optional parameter, Objective-C runtime version.
+ DIType createUnionType(DIDescriptor Scope, StringRef Name, DIFile File,
+ unsigned LineNumber, uint64_t SizeInBits,
+ uint64_t AlignInBits, unsigned Flags,
+ DIArray Elements, unsigned RunTimeLang = 0);
+
+ /// createTemplateTypeParameter - Create debugging information for template
+ /// type parameter.
+ /// @param Scope Scope in which this type is defined.
+ /// @param Name Type parameter name.
+ /// @param Ty Parameter type.
+ /// @param File File where this type parameter is defined.
+ /// @param LineNo Line number.
+ /// @param ColumnNo Column Number.
+ DITemplateTypeParameter
+ createTemplateTypeParameter(DIDescriptor Scope, StringRef Name, DIType Ty,
+ MDNode *File = 0, unsigned LineNo = 0,
+ unsigned ColumnNo = 0);
+
+ /// createTemplateValueParameter - Create debugging information for template
+ /// value parameter.
+ /// @param Scope Scope in which this type is defined.
+ /// @param Name Value parameter name.
+ /// @param Ty Parameter type.
+ /// @param Value Constant parameter value.
+ /// @param File File where this type parameter is defined.
+ /// @param LineNo Line number.
+ /// @param ColumnNo Column Number.
+ DITemplateValueParameter
+ createTemplateValueParameter(DIDescriptor Scope, StringRef Name, DIType Ty,
+ uint64_t Value,
+ MDNode *File = 0, unsigned LineNo = 0,
+ unsigned ColumnNo = 0);
+
+ /// createArrayType - Create debugging information entry for an array.
+ /// @param Size Array size.
+ /// @param AlignInBits Alignment.
+ /// @param Ty Element type.
+ /// @param Subscripts Subscripts.
+ DIType createArrayType(uint64_t Size, uint64_t AlignInBits,
+ DIType Ty, DIArray Subscripts);
+
+ /// createVectorType - Create debugging information entry for a vector type.
+ /// @param Size Array size.
+ /// @param AlignInBits Alignment.
+ /// @param Ty Element type.
+ /// @param Subscripts Subscripts.
+ DIType createVectorType(uint64_t Size, uint64_t AlignInBits,
+ DIType Ty, DIArray Subscripts);
+
+ /// createEnumerationType - Create debugging information entry for an
+ /// enumeration.
+ /// @param Scope Scope in which this enumeration is defined.
+ /// @param Name Union name.
+ /// @param File File where this member is defined.
+ /// @param LineNumber Line number.
+ /// @param SizeInBits Member size.
+ /// @param AlignInBits Member alignment.
+ /// @param Elements Enumeration elements.
+ /// @param Flags Flags (e.g. forward decl)
+ DIType createEnumerationType(DIDescriptor Scope, StringRef Name,
+ DIFile File, unsigned LineNumber,
+ uint64_t SizeInBits, uint64_t AlignInBits,
+ DIArray Elements, DIType ClassType,
+ unsigned Flags);
+
+ /// createSubroutineType - Create subroutine type.
+ /// @param File File in which this subroutine is defined.
+ /// @param ParameterTypes An array of subroutine parameter types. This
+ /// includes return type at 0th index.
+ DIType createSubroutineType(DIFile File, DIArray ParameterTypes);
+
+ /// createArtificialType - Create a new DIType with "artificial" flag set.
+ DIType createArtificialType(DIType Ty);
+
+ /// createObjectPointerType - Create a new DIType with the "object pointer"
+ /// flag set.
+ DIType createObjectPointerType(DIType Ty);
+
+ /// createTemporaryType - Create a temporary forward-declared type.
+ DIType createTemporaryType();
+ DIType createTemporaryType(DIFile F);
+
+ /// createForwardDecl - Create a temporary forward-declared type.
+ DIType createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
+ DIFile F, unsigned Line, unsigned RuntimeLang = 0);
+
+ /// retainType - Retain DIType in a module even if it is not referenced
+ /// through debug info anchors.
+ void retainType(DIType T);
+
+ /// createUnspecifiedParameter - Create unspeicified type descriptor
+ /// for a subroutine type.
+ DIDescriptor createUnspecifiedParameter();
+
+ /// getOrCreateArray - Get a DIArray, create one if required.
+ DIArray getOrCreateArray(ArrayRef<Value *> Elements);
+
+ /// getOrCreateSubrange - Create a descriptor for a value range. This
+ /// implicitly uniques the values returned.
+ DISubrange getOrCreateSubrange(int64_t Lo, int64_t Hi);
+
+ /// createGlobalVariable - Create a new descriptor for the specified global.
+ /// @param Name Name of the variable.
+ /// @param File File where this variable is defined.
+ /// @param LineNo Line number.
+ /// @param Ty Variable Type.
+ /// @param isLocalToUnit Boolean flag indicate whether this variable is
+ /// externally visible or not.
+ /// @param Val llvm::Value of the variable.
+ DIGlobalVariable
+ createGlobalVariable(StringRef Name, DIFile File, unsigned LineNo,
+ DIType Ty, bool isLocalToUnit, llvm::Value *Val);
+
+
+ /// createStaticVariable - Create a new descriptor for the specified
+ /// variable.
+ /// @param Context Variable scope.
+ /// @param Name Name of the variable.
+ /// @param LinkageName Mangled name of the variable.
+ /// @param File File where this variable is defined.
+ /// @param LineNo Line number.
+ /// @param Ty Variable Type.
+ /// @param isLocalToUnit Boolean flag indicate whether this variable is
+ /// externally visible or not.
+ /// @param Val llvm::Value of the variable.
+ DIGlobalVariable
+ createStaticVariable(DIDescriptor Context, StringRef Name,
+ StringRef LinkageName, DIFile File, unsigned LineNo,
+ DIType Ty, bool isLocalToUnit, llvm::Value *Val);
+
+
+ /// createLocalVariable - Create a new descriptor for the specified
+ /// local variable.
+ /// @param Tag Dwarf TAG. Usually DW_TAG_auto_variable or
+ /// DW_TAG_arg_variable.
+ /// @param Scope Variable scope.
+ /// @param Name Variable name.
+ /// @param File File where this variable is defined.
+ /// @param LineNo Line number.
+ /// @param Ty Variable Type
+ /// @param AlwaysPreserve Boolean. Set to true if debug info for this
+ /// variable should be preserved in optimized build.
+ /// @param Flags Flags, e.g. artificial variable.
+ /// @param ArgNo If this variable is an arugment then this argument's
+ /// number. 1 indicates 1st argument.
+ DIVariable createLocalVariable(unsigned Tag, DIDescriptor Scope,
+ StringRef Name,
+ DIFile File, unsigned LineNo,
+ DIType Ty, bool AlwaysPreserve = false,
+ unsigned Flags = 0,
+ unsigned ArgNo = 0);
+
+
+ /// createComplexVariable - Create a new descriptor for the specified
+ /// variable which has a complex address expression for its address.
+ /// @param Tag Dwarf TAG. Usually DW_TAG_auto_variable or
+ /// DW_TAG_arg_variable.
+ /// @param Scope Variable scope.
+ /// @param Name Variable name.
+ /// @param F File where this variable is defined.
+ /// @param LineNo Line number.
+ /// @param Ty Variable Type
+ /// @param Addr An array of complex address operations.
+ /// @param ArgNo If this variable is an arugment then this argument's
+ /// number. 1 indicates 1st argument.
+ DIVariable createComplexVariable(unsigned Tag, DIDescriptor Scope,
+ StringRef Name, DIFile F, unsigned LineNo,
+ DIType Ty, ArrayRef<Value *> Addr,
+ unsigned ArgNo = 0);
+
+ /// createFunction - Create a new descriptor for the specified subprogram.
+ /// See comments in DISubprogram for descriptions of these fields.
+ /// @param Scope Function scope.
+ /// @param Name Function name.
+ /// @param LinkageName Mangled function name.
+ /// @param File File where this variable is defined.
+ /// @param LineNo Line number.
+ /// @param Ty Function type.
+ /// @param isLocalToUnit True if this function is not externally visible..
+ /// @param isDefinition True if this is a function definition.
+ /// @param ScopeLine Set to the beginning of the scope this starts
+ /// @param Flags e.g. is this function prototyped or not.
+ /// This flags are used to emit dwarf attributes.
+ /// @param isOptimized True if optimization is ON.
+ /// @param Fn llvm::Function pointer.
+ /// @param TParam Function template parameters.
+ DISubprogram createFunction(DIDescriptor Scope, StringRef Name,
+ StringRef LinkageName,
+ DIFile File, unsigned LineNo,
+ DIType Ty, bool isLocalToUnit,
+ bool isDefinition,
+ unsigned ScopeLine,
+ unsigned Flags = 0,
+ bool isOptimized = false,
+ Function *Fn = 0,
+ MDNode *TParam = 0,
+ MDNode *Decl = 0);
+
+ /// createMethod - Create a new descriptor for the specified C++ method.
+ /// See comments in DISubprogram for descriptions of these fields.
+ /// @param Scope Function scope.
+ /// @param Name Function name.
+ /// @param LinkageName Mangled function name.
+ /// @param File File where this variable is defined.
+ /// @param LineNo Line number.
+ /// @param Ty Function type.
+ /// @param isLocalToUnit True if this function is not externally visible..
+ /// @param isDefinition True if this is a function definition.
+ /// @param Virtuality Attributes describing virtualness. e.g. pure
+ /// virtual function.
+ /// @param VTableIndex Index no of this method in virtual table.
+ /// @param VTableHolder Type that holds vtable.
+ /// @param Flags e.g. is this function prototyped or not.
+ /// This flags are used to emit dwarf attributes.
+ /// @param isOptimized True if optimization is ON.
+ /// @param Fn llvm::Function pointer.
+ /// @param TParam Function template parameters.
+ DISubprogram createMethod(DIDescriptor Scope, StringRef Name,
+ StringRef LinkageName,
+ DIFile File, unsigned LineNo,
+ DIType Ty, bool isLocalToUnit,
+ bool isDefinition,
+ unsigned Virtuality = 0, unsigned VTableIndex = 0,
+ MDNode *VTableHolder = 0,
+ unsigned Flags = 0,
+ bool isOptimized = false,
+ Function *Fn = 0,
+ MDNode *TParam = 0);
+
+ /// createNameSpace - This creates new descriptor for a namespace
+ /// with the specified parent scope.
+ /// @param Scope Namespace scope
+ /// @param Name Name of this namespace
+ /// @param File Source file
+ /// @param LineNo Line number
+ DINameSpace createNameSpace(DIDescriptor Scope, StringRef Name,
+ DIFile File, unsigned LineNo);
+
+
+ /// createLexicalBlockFile - This creates a descriptor for a lexical
+ /// block with a new file attached. This merely extends the existing
+ /// lexical block as it crosses a file.
+ /// @param Scope Lexical block.
+ /// @param File Source file.
+ DILexicalBlockFile createLexicalBlockFile(DIDescriptor Scope,
+ DIFile File);
+
+ /// createLexicalBlock - This creates a descriptor for a lexical block
+ /// with the specified parent context.
+ /// @param Scope Parent lexical scope.
+ /// @param File Source file
+ /// @param Line Line number
+ /// @param Col Column number
+ DILexicalBlock createLexicalBlock(DIDescriptor Scope, DIFile File,
+ unsigned Line, unsigned Col);
+
+ /// insertDeclare - Insert a new llvm.dbg.declare intrinsic call.
+ /// @param Storage llvm::Value of the variable
+ /// @param VarInfo Variable's debug info descriptor.
+ /// @param InsertAtEnd Location for the new intrinsic.
+ Instruction *insertDeclare(llvm::Value *Storage, DIVariable VarInfo,
+ BasicBlock *InsertAtEnd);
+
+ /// insertDeclare - Insert a new llvm.dbg.declare intrinsic call.
+ /// @param Storage llvm::Value of the variable
+ /// @param VarInfo Variable's debug info descriptor.
+ /// @param InsertBefore Location for the new intrinsic.
+ Instruction *insertDeclare(llvm::Value *Storage, DIVariable VarInfo,
+ Instruction *InsertBefore);
+
+
+ /// insertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
+ /// @param Val llvm::Value of the variable
+ /// @param Offset Offset
+ /// @param VarInfo Variable's debug info descriptor.
+ /// @param InsertAtEnd Location for the new intrinsic.
+ Instruction *insertDbgValueIntrinsic(llvm::Value *Val, uint64_t Offset,
+ DIVariable VarInfo,
+ BasicBlock *InsertAtEnd);
+
+ /// insertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
+ /// @param Val llvm::Value of the variable
+ /// @param Offset Offset
+ /// @param VarInfo Variable's debug info descriptor.
+ /// @param InsertBefore Location for the new intrinsic.
+ Instruction *insertDbgValueIntrinsic(llvm::Value *Val, uint64_t Offset,
+ DIVariable VarInfo,
+ Instruction *InsertBefore);
+
+ };
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/DebugInfo.h b/include/llvm/DebugInfo.h
new file mode 100644
index 00000000000..4c1d045fa0d
--- /dev/null
+++ b/include/llvm/DebugInfo.h
@@ -0,0 +1,892 @@
+//===--- llvm/Analysis/DebugInfo.h - Debug Information Helpers --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a bunch of datatypes that are useful for creating and
+// walking debug info in LLVM IR form. They essentially provide wrappers around
+// the information in the global variables that's needed when constructing the
+// DWARF information.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_DEBUGINFO_H
+#define LLVM_ANALYSIS_DEBUGINFO_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Dwarf.h"
+
+namespace llvm {
+ class BasicBlock;
+ class Constant;
+ class Function;
+ class GlobalVariable;
+ class Module;
+ class Type;
+ class Value;
+ class DbgDeclareInst;
+ class Instruction;
+ class MDNode;
+ class NamedMDNode;
+ class LLVMContext;
+ class raw_ostream;
+
+ class DIFile;
+ class DISubprogram;
+ class DILexicalBlock;
+ class DILexicalBlockFile;
+ class DIVariable;
+ class DIType;
+ class DIObjCProperty;
+
+ /// DIDescriptor - A thin wraper around MDNode to access encoded debug info.
+ /// This should not be stored in a container, because the underlying MDNode
+ /// may change in certain situations.
+ class DIDescriptor {
+ public:
+ enum {
+ FlagPrivate = 1 << 0,
+ FlagProtected = 1 << 1,
+ FlagFwdDecl = 1 << 2,
+ FlagAppleBlock = 1 << 3,
+ FlagBlockByrefStruct = 1 << 4,
+ FlagVirtual = 1 << 5,
+ FlagArtificial = 1 << 6,
+ FlagExplicit = 1 << 7,
+ FlagPrototyped = 1 << 8,
+ FlagObjcClassComplete = 1 << 9,
+ FlagObjectPointer = 1 << 10
+ };
+ protected:
+ const MDNode *DbgNode;
+
+ StringRef getStringField(unsigned Elt) const;
+ unsigned getUnsignedField(unsigned Elt) const {
+ return (unsigned)getUInt64Field(Elt);
+ }
+ uint64_t getUInt64Field(unsigned Elt) const;
+ DIDescriptor getDescriptorField(unsigned Elt) const;
+
+ template <typename DescTy>
+ DescTy getFieldAs(unsigned Elt) const {
+ return DescTy(getDescriptorField(Elt));
+ }
+
+ GlobalVariable *getGlobalVariableField(unsigned Elt) const;
+ Constant *getConstantField(unsigned Elt) const;
+ Function *getFunctionField(unsigned Elt) const;
+
+ public:
+ explicit DIDescriptor() : DbgNode(0) {}
+ explicit DIDescriptor(const MDNode *N) : DbgNode(N) {}
+ explicit DIDescriptor(const DIFile F);
+ explicit DIDescriptor(const DISubprogram F);
+ explicit DIDescriptor(const DILexicalBlockFile F);
+ explicit DIDescriptor(const DILexicalBlock F);
+ explicit DIDescriptor(const DIVariable F);
+ explicit DIDescriptor(const DIType F);
+
+ bool Verify() const { return DbgNode != 0; }
+
+ operator MDNode *() const { return const_cast<MDNode*>(DbgNode); }
+ MDNode *operator ->() const { return const_cast<MDNode*>(DbgNode); }
+
+ unsigned getVersion() const {
+ return getUnsignedField(0) & LLVMDebugVersionMask;
+ }
+
+ unsigned getTag() const {
+ return getUnsignedField(0) & ~LLVMDebugVersionMask;
+ }
+
+ bool isDerivedType() const;
+ bool isCompositeType() const;
+ bool isBasicType() const;
+ bool isVariable() const;
+ bool isSubprogram() const;
+ bool isGlobalVariable() const;
+ bool isScope() const;
+ bool isFile() const;
+ bool isCompileUnit() const;
+ bool isNameSpace() const;
+ bool isLexicalBlockFile() const;
+ bool isLexicalBlock() const;
+ bool isSubrange() const;
+ bool isEnumerator() const;
+ bool isType() const;
+ bool isGlobal() const;
+ bool isUnspecifiedParameter() const;
+ bool isTemplateTypeParameter() const;
+ bool isTemplateValueParameter() const;
+ bool isObjCProperty() const;
+
+ /// print - print descriptor.
+ void print(raw_ostream &OS) const;
+
+ /// dump - print descriptor to dbgs() with a newline.
+ void dump() const;
+ };
+
+ /// DISubrange - This is used to represent ranges, for array bounds.
+ class DISubrange : public DIDescriptor {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DISubrange(const MDNode *N = 0) : DIDescriptor(N) {}
+
+ uint64_t getLo() const { return getUInt64Field(1); }
+ uint64_t getHi() const { return getUInt64Field(2); }
+ };
+
+ /// DIArray - This descriptor holds an array of descriptors.
+ class DIArray : public DIDescriptor {
+ public:
+ explicit DIArray(const MDNode *N = 0)
+ : DIDescriptor(N) {}
+
+ unsigned getNumElements() const;
+ DIDescriptor getElement(unsigned Idx) const {
+ return getDescriptorField(Idx);
+ }
+ };
+
+ /// DIScope - A base class for various scopes.
+ class DIScope : public DIDescriptor {
+ protected:
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DIScope(const MDNode *N = 0) : DIDescriptor (N) {}
+
+ StringRef getFilename() const;
+ StringRef getDirectory() const;
+ };
+
+ /// DICompileUnit - A wrapper for a compile unit.
+ class DICompileUnit : public DIScope {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DICompileUnit(const MDNode *N = 0) : DIScope(N) {}
+
+ unsigned getLanguage() const { return getUnsignedField(2); }
+ StringRef getFilename() const { return getStringField(3); }
+ StringRef getDirectory() const { return getStringField(4); }
+ StringRef getProducer() const { return getStringField(5); }
+
+ /// isMain - Each input file is encoded as a separate compile unit in LLVM
+ /// debugging information output. However, many target specific tool chains
+ /// prefer to encode only one compile unit in an object file. In this
+ /// situation, the LLVM code generator will include debugging information
+ /// entities in the compile unit that is marked as main compile unit. The
+ /// code generator accepts maximum one main compile unit per module. If a
+ /// module does not contain any main compile unit then the code generator
+ /// will emit multiple compile units in the output object file.
+
+ bool isMain() const { return getUnsignedField(6) != 0; }
+ bool isOptimized() const { return getUnsignedField(7) != 0; }
+ StringRef getFlags() const { return getStringField(8); }
+ unsigned getRunTimeVersion() const { return getUnsignedField(9); }
+
+ DIArray getEnumTypes() const;
+ DIArray getRetainedTypes() const;
+ DIArray getSubprograms() const;
+ DIArray getGlobalVariables() const;
+
+ /// Verify - Verify that a compile unit is well formed.
+ bool Verify() const;
+ };
+
+ /// DIFile - This is a wrapper for a file.
+ class DIFile : public DIScope {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const {} // FIXME: Output something?
+ public:
+ explicit DIFile(const MDNode *N = 0) : DIScope(N) {
+ if (DbgNode && !isFile())
+ DbgNode = 0;
+ }
+ StringRef getFilename() const { return getStringField(1); }
+ StringRef getDirectory() const { return getStringField(2); }
+ DICompileUnit getCompileUnit() const{
+ assert (getVersion() <= LLVMDebugVersion10 && "Invalid CompileUnit!");
+ return getFieldAs<DICompileUnit>(3);
+ }
+ };
+
+ /// DIEnumerator - A wrapper for an enumerator (e.g. X and Y in 'enum {X,Y}').
+ /// FIXME: it seems strange that this doesn't have either a reference to the
+ /// type/precision or a file/line pair for location info.
+ class DIEnumerator : public DIDescriptor {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DIEnumerator(const MDNode *N = 0) : DIDescriptor(N) {}
+
+ StringRef getName() const { return getStringField(1); }
+ uint64_t getEnumValue() const { return getUInt64Field(2); }
+ };
+
+ /// DIType - This is a wrapper for a type.
+ /// FIXME: Types should be factored much better so that CV qualifiers and
+ /// others do not require a huge and empty descriptor full of zeros.
+ class DIType : public DIScope {
+ protected:
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ // This ctor is used when the Tag has already been validated by a derived
+ // ctor.
+ DIType(const MDNode *N, bool, bool) : DIScope(N) {}
+ public:
+ /// Verify - Verify that a type descriptor is well formed.
+ bool Verify() const;
+ explicit DIType(const MDNode *N);
+ explicit DIType() {}
+
+ DIScope getContext() const { return getFieldAs<DIScope>(1); }
+ StringRef getName() const { return getStringField(2); }
+ DICompileUnit getCompileUnit() const{
+ assert (getVersion() <= LLVMDebugVersion10 && "Invalid getCompileUnit!");
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getFieldAs<DICompileUnit>(3);
+
+ return getFieldAs<DIFile>(3).getCompileUnit();
+ }
+ DIFile getFile() const { return getFieldAs<DIFile>(3); }
+ unsigned getLineNumber() const { return getUnsignedField(4); }
+ uint64_t getSizeInBits() const { return getUInt64Field(5); }
+ uint64_t getAlignInBits() const { return getUInt64Field(6); }
+ // FIXME: Offset is only used for DW_TAG_member nodes. Making every type
+ // carry this is just plain insane.
+ uint64_t getOffsetInBits() const { return getUInt64Field(7); }
+ unsigned getFlags() const { return getUnsignedField(8); }
+ bool isPrivate() const {
+ return (getFlags() & FlagPrivate) != 0;
+ }
+ bool isProtected() const {
+ return (getFlags() & FlagProtected) != 0;
+ }
+ bool isForwardDecl() const {
+ return (getFlags() & FlagFwdDecl) != 0;
+ }
+ // isAppleBlock - Return true if this is the Apple Blocks extension.
+ bool isAppleBlockExtension() const {
+ return (getFlags() & FlagAppleBlock) != 0;
+ }
+ bool isBlockByrefStruct() const {
+ return (getFlags() & FlagBlockByrefStruct) != 0;
+ }
+ bool isVirtual() const {
+ return (getFlags() & FlagVirtual) != 0;
+ }
+ bool isArtificial() const {
+ return (getFlags() & FlagArtificial) != 0;
+ }
+ bool isObjectPointer() const {
+ return (getFlags() & FlagObjectPointer) != 0;
+ }
+ bool isObjcClassComplete() const {
+ return (getFlags() & FlagObjcClassComplete) != 0;
+ }
+ bool isValid() const {
+ return DbgNode && (isBasicType() || isDerivedType() || isCompositeType());
+ }
+ StringRef getDirectory() const {
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getCompileUnit().getDirectory();
+
+ return getFieldAs<DIFile>(3).getDirectory();
+ }
+ StringRef getFilename() const {
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getCompileUnit().getFilename();
+
+ return getFieldAs<DIFile>(3).getFilename();
+ }
+
+ /// isUnsignedDIType - Return true if type encoding is unsigned.
+ bool isUnsignedDIType();
+
+ /// replaceAllUsesWith - Replace all uses of debug info referenced by
+ /// this descriptor.
+ void replaceAllUsesWith(DIDescriptor &D);
+ void replaceAllUsesWith(MDNode *D);
+ };
+
+ /// DIBasicType - A basic type, like 'int' or 'float'.
+ class DIBasicType : public DIType {
+ public:
+ explicit DIBasicType(const MDNode *N = 0) : DIType(N) {}
+
+ unsigned getEncoding() const { return getUnsignedField(9); }
+
+ /// Verify - Verify that a basic type descriptor is well formed.
+ bool Verify() const;
+ };
+
+ /// DIDerivedType - A simple derived type, like a const qualified type,
+ /// a typedef, a pointer or reference, etc.
+ class DIDerivedType : public DIType {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ protected:
+ explicit DIDerivedType(const MDNode *N, bool, bool)
+ : DIType(N, true, true) {}
+ public:
+ explicit DIDerivedType(const MDNode *N = 0)
+ : DIType(N, true, true) {}
+
+ DIType getTypeDerivedFrom() const { return getFieldAs<DIType>(9); }
+
+ /// getOriginalTypeSize - If this type is derived from a base type then
+ /// return base type size.
+ uint64_t getOriginalTypeSize() const;
+
+ /// getObjCProperty - Return property node, if this ivar is
+ /// associated with one.
+ MDNode *getObjCProperty() const;
+
+ StringRef getObjCPropertyName() const {
+ if (getVersion() > LLVMDebugVersion11)
+ return StringRef();
+ return getStringField(10);
+ }
+ StringRef getObjCPropertyGetterName() const {
+ assert (getVersion() <= LLVMDebugVersion11 && "Invalid Request");
+ return getStringField(11);
+ }
+ StringRef getObjCPropertySetterName() const {
+ assert (getVersion() <= LLVMDebugVersion11 && "Invalid Request");
+ return getStringField(12);
+ }
+ bool isReadOnlyObjCProperty() {
+ assert (getVersion() <= LLVMDebugVersion11 && "Invalid Request");
+ return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
+ }
+ bool isReadWriteObjCProperty() {
+ assert (getVersion() <= LLVMDebugVersion11 && "Invalid Request");
+ return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
+ }
+ bool isAssignObjCProperty() {
+ assert (getVersion() <= LLVMDebugVersion11 && "Invalid Request");
+ return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_assign) != 0;
+ }
+ bool isRetainObjCProperty() {
+ assert (getVersion() <= LLVMDebugVersion11 && "Invalid Request");
+ return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_retain) != 0;
+ }
+ bool isCopyObjCProperty() {
+ assert (getVersion() <= LLVMDebugVersion11 && "Invalid Request");
+ return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_copy) != 0;
+ }
+ bool isNonAtomicObjCProperty() {
+ assert (getVersion() <= LLVMDebugVersion11 && "Invalid Request");
+ return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
+ }
+
+ /// Verify - Verify that a derived type descriptor is well formed.
+ bool Verify() const;
+ };
+
+ /// DICompositeType - This descriptor holds a type that can refer to multiple
+ /// other types, like a function or struct.
+ /// FIXME: Why is this a DIDerivedType??
+ class DICompositeType : public DIDerivedType {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DICompositeType(const MDNode *N = 0)
+ : DIDerivedType(N, true, true) {
+ if (N && !isCompositeType())
+ DbgNode = 0;
+ }
+
+ DIArray getTypeArray() const { return getFieldAs<DIArray>(10); }
+ unsigned getRunTimeLang() const { return getUnsignedField(11); }
+ DICompositeType getContainingType() const {
+ return getFieldAs<DICompositeType>(12);
+ }
+ DIArray getTemplateParams() const { return getFieldAs<DIArray>(13); }
+
+ /// Verify - Verify that a composite type descriptor is well formed.
+ bool Verify() const;
+ };
+
+ /// DITemplateTypeParameter - This is a wrapper for template type parameter.
+ class DITemplateTypeParameter : public DIDescriptor {
+ public:
+ explicit DITemplateTypeParameter(const MDNode *N = 0) : DIDescriptor(N) {}
+
+ DIScope getContext() const { return getFieldAs<DIScope>(1); }
+ StringRef getName() const { return getStringField(2); }
+ DIType getType() const { return getFieldAs<DIType>(3); }
+ StringRef getFilename() const {
+ return getFieldAs<DIFile>(4).getFilename();
+ }
+ StringRef getDirectory() const {
+ return getFieldAs<DIFile>(4).getDirectory();
+ }
+ unsigned getLineNumber() const { return getUnsignedField(5); }
+ unsigned getColumnNumber() const { return getUnsignedField(6); }
+ };
+
+ /// DITemplateValueParameter - This is a wrapper for template value parameter.
+ class DITemplateValueParameter : public DIDescriptor {
+ public:
+ explicit DITemplateValueParameter(const MDNode *N = 0) : DIDescriptor(N) {}
+
+ DIScope getContext() const { return getFieldAs<DIScope>(1); }
+ StringRef getName() const { return getStringField(2); }
+ DIType getType() const { return getFieldAs<DIType>(3); }
+ uint64_t getValue() const { return getUInt64Field(4); }
+ StringRef getFilename() const {
+ return getFieldAs<DIFile>(5).getFilename();
+ }
+ StringRef getDirectory() const {
+ return getFieldAs<DIFile>(5).getDirectory();
+ }
+ unsigned getLineNumber() const { return getUnsignedField(6); }
+ unsigned getColumnNumber() const { return getUnsignedField(7); }
+ };
+
+ /// DISubprogram - This is a wrapper for a subprogram (e.g. a function).
+ class DISubprogram : public DIScope {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DISubprogram(const MDNode *N = 0) : DIScope(N) {}
+
+ DIScope getContext() const { return getFieldAs<DIScope>(2); }
+ StringRef getName() const { return getStringField(3); }
+ StringRef getDisplayName() const { return getStringField(4); }
+ StringRef getLinkageName() const { return getStringField(5); }
+ DICompileUnit getCompileUnit() const{
+ assert (getVersion() <= LLVMDebugVersion10 && "Invalid getCompileUnit!");
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getFieldAs<DICompileUnit>(6);
+
+ return getFieldAs<DIFile>(6).getCompileUnit();
+ }
+ unsigned getLineNumber() const { return getUnsignedField(7); }
+ DICompositeType getType() const { return getFieldAs<DICompositeType>(8); }
+
+ /// getReturnTypeName - Subprogram return types are encoded either as
+ /// DIType or as DICompositeType.
+ StringRef getReturnTypeName() const {
+ DICompositeType DCT(getFieldAs<DICompositeType>(8));
+ if (DCT.Verify()) {
+ DIArray A = DCT.getTypeArray();
+ DIType T(A.getElement(0));
+ return T.getName();
+ }
+ DIType T(getFieldAs<DIType>(8));
+ return T.getName();
+ }
+
+ /// isLocalToUnit - Return true if this subprogram is local to the current
+ /// compile unit, like 'static' in C.
+ unsigned isLocalToUnit() const { return getUnsignedField(9); }
+ unsigned isDefinition() const { return getUnsignedField(10); }
+
+ unsigned getVirtuality() const { return getUnsignedField(11); }
+ unsigned getVirtualIndex() const { return getUnsignedField(12); }
+
+ DICompositeType getContainingType() const {
+ return getFieldAs<DICompositeType>(13);
+ }
+
+ unsigned isArtificial() const {
+ if (getVersion() <= llvm::LLVMDebugVersion8)
+ return getUnsignedField(14);
+ return (getUnsignedField(14) & FlagArtificial) != 0;
+ }
+ /// isPrivate - Return true if this subprogram has "private"
+ /// access specifier.
+ bool isPrivate() const {
+ if (getVersion() <= llvm::LLVMDebugVersion8)
+ return false;
+ return (getUnsignedField(14) & FlagPrivate) != 0;
+ }
+ /// isProtected - Return true if this subprogram has "protected"
+ /// access specifier.
+ bool isProtected() const {
+ if (getVersion() <= llvm::LLVMDebugVersion8)
+ return false;
+ return (getUnsignedField(14) & FlagProtected) != 0;
+ }
+ /// isExplicit - Return true if this subprogram is marked as explicit.
+ bool isExplicit() const {
+ if (getVersion() <= llvm::LLVMDebugVersion8)
+ return false;
+ return (getUnsignedField(14) & FlagExplicit) != 0;
+ }
+ /// isPrototyped - Return true if this subprogram is prototyped.
+ bool isPrototyped() const {
+ if (getVersion() <= llvm::LLVMDebugVersion8)
+ return false;
+ return (getUnsignedField(14) & FlagPrototyped) != 0;
+ }
+
+ unsigned isOptimized() const;
+
+ StringRef getFilename() const {
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getCompileUnit().getFilename();
+
+ return getFieldAs<DIFile>(6).getFilename();
+ }
+
+ StringRef getDirectory() const {
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getCompileUnit().getFilename();
+
+ return getFieldAs<DIFile>(6).getDirectory();
+ }
+
+ /// getScopeLineNumber - Get the beginning of the scope of the
+ /// function, not necessarily where the name of the program
+ /// starts.
+ unsigned getScopeLineNumber() const { return getUnsignedField(20); }
+
+ /// Verify - Verify that a subprogram descriptor is well formed.
+ bool Verify() const;
+
+ /// describes - Return true if this subprogram provides debugging
+ /// information for the function F.
+ bool describes(const Function *F);
+
+ Function *getFunction() const { return getFunctionField(16); }
+ DIArray getTemplateParams() const { return getFieldAs<DIArray>(17); }
+ DISubprogram getFunctionDeclaration() const {
+ return getFieldAs<DISubprogram>(18);
+ }
+ MDNode *getVariablesNodes() const;
+ DIArray getVariables() const;
+ };
+
+ /// DIGlobalVariable - This is a wrapper for a global variable.
+ class DIGlobalVariable : public DIDescriptor {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DIGlobalVariable(const MDNode *N = 0) : DIDescriptor(N) {}
+
+ DIScope getContext() const { return getFieldAs<DIScope>(2); }
+ StringRef getName() const { return getStringField(3); }
+ StringRef getDisplayName() const { return getStringField(4); }
+ StringRef getLinkageName() const { return getStringField(5); }
+ DICompileUnit getCompileUnit() const{
+ assert (getVersion() <= LLVMDebugVersion10 && "Invalid getCompileUnit!");
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getFieldAs<DICompileUnit>(6);
+
+ DIFile F = getFieldAs<DIFile>(6);
+ return F.getCompileUnit();
+ }
+ StringRef getFilename() const {
+ if (getVersion() <= llvm::LLVMDebugVersion10)
+ return getContext().getFilename();
+ return getFieldAs<DIFile>(6).getFilename();
+ }
+ StringRef getDirectory() const {
+ if (getVersion() <= llvm::LLVMDebugVersion10)
+ return getContext().getDirectory();
+ return getFieldAs<DIFile>(6).getDirectory();
+
+ }
+
+ unsigned getLineNumber() const { return getUnsignedField(7); }
+ DIType getType() const { return getFieldAs<DIType>(8); }
+ unsigned isLocalToUnit() const { return getUnsignedField(9); }
+ unsigned isDefinition() const { return getUnsignedField(10); }
+
+ GlobalVariable *getGlobal() const { return getGlobalVariableField(11); }
+ Constant *getConstant() const { return getConstantField(11); }
+
+ /// Verify - Verify that a global variable descriptor is well formed.
+ bool Verify() const;
+ };
+
+ /// DIVariable - This is a wrapper for a variable (e.g. parameter, local,
+ /// global etc).
+ class DIVariable : public DIDescriptor {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DIVariable(const MDNode *N = 0)
+ : DIDescriptor(N) {}
+
+ DIScope getContext() const { return getFieldAs<DIScope>(1); }
+ StringRef getName() const { return getStringField(2); }
+ DICompileUnit getCompileUnit() const {
+ assert (getVersion() <= LLVMDebugVersion10 && "Invalid getCompileUnit!");
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getFieldAs<DICompileUnit>(3);
+
+ DIFile F = getFieldAs<DIFile>(3);
+ return F.getCompileUnit();
+ }
+ unsigned getLineNumber() const {
+ return (getUnsignedField(4) << 8) >> 8;
+ }
+ unsigned getArgNumber() const {
+ unsigned L = getUnsignedField(4);
+ return L >> 24;
+ }
+ DIType getType() const { return getFieldAs<DIType>(5); }
+
+ /// isArtificial - Return true if this variable is marked as "artificial".
+ bool isArtificial() const {
+ if (getVersion() <= llvm::LLVMDebugVersion8)
+ return false;
+ return (getUnsignedField(6) & FlagArtificial) != 0;
+ }
+
+ bool isObjectPointer() const {
+ return (getUnsignedField(6) & FlagObjectPointer) != 0;
+ }
+
+ /// getInlinedAt - If this variable is inlined then return inline location.
+ MDNode *getInlinedAt() const;
+
+ /// Verify - Verify that a variable descriptor is well formed.
+ bool Verify() const;
+
+ /// HasComplexAddr - Return true if the variable has a complex address.
+ bool hasComplexAddress() const {
+ return getNumAddrElements() > 0;
+ }
+
+ unsigned getNumAddrElements() const;
+
+ uint64_t getAddrElement(unsigned Idx) const {
+ if (getVersion() <= llvm::LLVMDebugVersion8)
+ return getUInt64Field(Idx+6);
+ if (getVersion() == llvm::LLVMDebugVersion9)
+ return getUInt64Field(Idx+7);
+ return getUInt64Field(Idx+8);
+ }
+
+ /// isBlockByrefVariable - Return true if the variable was declared as
+ /// a "__block" variable (Apple Blocks).
+ bool isBlockByrefVariable() const {
+ return getType().isBlockByrefStruct();
+ }
+
+ /// isInlinedFnArgument - Return trule if this variable provides debugging
+ /// information for an inlined function arguments.
+ bool isInlinedFnArgument(const Function *CurFn);
+
+ void printExtendedName(raw_ostream &OS) const;
+ };
+
+ /// DILexicalBlock - This is a wrapper for a lexical block.
+ class DILexicalBlock : public DIScope {
+ public:
+ explicit DILexicalBlock(const MDNode *N = 0) : DIScope(N) {}
+ DIScope getContext() const { return getFieldAs<DIScope>(1); }
+ unsigned getLineNumber() const { return getUnsignedField(2); }
+ unsigned getColumnNumber() const { return getUnsignedField(3); }
+ StringRef getDirectory() const {
+ StringRef dir = getFieldAs<DIFile>(4).getDirectory();
+ return !dir.empty() ? dir : getContext().getDirectory();
+ }
+ StringRef getFilename() const {
+ StringRef filename = getFieldAs<DIFile>(4).getFilename();
+ return !filename.empty() ? filename : getContext().getFilename();
+ }
+ };
+
+ /// DILexicalBlockFile - This is a wrapper for a lexical block with
+ /// a filename change.
+ class DILexicalBlockFile : public DIScope {
+ public:
+ explicit DILexicalBlockFile(const MDNode *N = 0) : DIScope(N) {}
+ DIScope getContext() const { return getScope().getContext(); }
+ unsigned getLineNumber() const { return getScope().getLineNumber(); }
+ unsigned getColumnNumber() const { return getScope().getColumnNumber(); }
+ StringRef getDirectory() const {
+ StringRef dir = getFieldAs<DIFile>(2).getDirectory();
+ return !dir.empty() ? dir : getContext().getDirectory();
+ }
+ StringRef getFilename() const {
+ StringRef filename = getFieldAs<DIFile>(2).getFilename();
+ assert(!filename.empty() && "Why'd you create this then?");
+ return filename;
+ }
+ DILexicalBlock getScope() const { return getFieldAs<DILexicalBlock>(1); }
+ };
+
+ /// DINameSpace - A wrapper for a C++ style name space.
+ class DINameSpace : public DIScope {
+ public:
+ explicit DINameSpace(const MDNode *N = 0) : DIScope(N) {}
+ DIScope getContext() const { return getFieldAs<DIScope>(1); }
+ StringRef getName() const { return getStringField(2); }
+ StringRef getDirectory() const {
+ return getFieldAs<DIFile>(3).getDirectory();
+ }
+ StringRef getFilename() const {
+ return getFieldAs<DIFile>(3).getFilename();
+ }
+ DICompileUnit getCompileUnit() const{
+ assert (getVersion() <= LLVMDebugVersion10 && "Invalid getCompileUnit!");
+ if (getVersion() == llvm::LLVMDebugVersion7)
+ return getFieldAs<DICompileUnit>(3);
+
+ return getFieldAs<DIFile>(3).getCompileUnit();
+ }
+ unsigned getLineNumber() const { return getUnsignedField(4); }
+ bool Verify() const;
+ };
+
+ /// DILocation - This object holds location information. This object
+ /// is not associated with any DWARF tag.
+ class DILocation : public DIDescriptor {
+ public:
+ explicit DILocation(const MDNode *N) : DIDescriptor(N) { }
+
+ unsigned getLineNumber() const { return getUnsignedField(0); }
+ unsigned getColumnNumber() const { return getUnsignedField(1); }
+ DIScope getScope() const { return getFieldAs<DIScope>(2); }
+ DILocation getOrigLocation() const { return getFieldAs<DILocation>(3); }
+ StringRef getFilename() const { return getScope().getFilename(); }
+ StringRef getDirectory() const { return getScope().getDirectory(); }
+ bool Verify() const;
+ };
+
+ class DIObjCProperty : public DIDescriptor {
+ friend class DIDescriptor;
+ void printInternal(raw_ostream &OS) const;
+ public:
+ explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) { }
+
+ StringRef getObjCPropertyName() const { return getStringField(1); }
+ DIFile getFile() const { return getFieldAs<DIFile>(2); }
+ unsigned getLineNumber() const { return getUnsignedField(3); }
+
+ StringRef getObjCPropertyGetterName() const {
+ return getStringField(4);
+ }
+ StringRef getObjCPropertySetterName() const {
+ return getStringField(5);
+ }
+ bool isReadOnlyObjCProperty() {
+ return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_readonly) != 0;
+ }
+ bool isReadWriteObjCProperty() {
+ return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_readwrite) != 0;
+ }
+ bool isAssignObjCProperty() {
+ return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_assign) != 0;
+ }
+ bool isRetainObjCProperty() {
+ return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_retain) != 0;
+ }
+ bool isCopyObjCProperty() {
+ return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_copy) != 0;
+ }
+ bool isNonAtomicObjCProperty() {
+ return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_nonatomic) != 0;
+ }
+
+ DIType getType() const { return getFieldAs<DIType>(7); }
+
+ /// Verify - Verify that a derived type descriptor is well formed.
+ bool Verify() const;
+ };
+
+ /// getDISubprogram - Find subprogram that is enclosing this scope.
+ DISubprogram getDISubprogram(const MDNode *Scope);
+
+ /// getDICompositeType - Find underlying composite type.
+ DICompositeType getDICompositeType(DIType T);
+
+ /// isSubprogramContext - Return true if Context is either a subprogram
+ /// or another context nested inside a subprogram.
+ bool isSubprogramContext(const MDNode *Context);
+
+ /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
+ /// to hold function specific information.
+ NamedMDNode *getOrInsertFnSpecificMDNode(Module &M, DISubprogram SP);
+
+ /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
+ /// suitable to hold function specific information.
+ NamedMDNode *getFnSpecificMDNode(const Module &M, DISubprogram SP);
+
+ /// createInlinedVariable - Create a new inlined variable based on current
+ /// variable.
+ /// @param DV Current Variable.
+ /// @param InlinedScope Location at current variable is inlined.
+ DIVariable createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
+ LLVMContext &VMContext);
+
+ /// cleanseInlinedVariable - Remove inlined scope from the variable.
+ DIVariable cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext);
+
+ class DebugInfoFinder {
+ public:
+ /// processModule - Process entire module and collect debug info
+ /// anchors.
+ void processModule(Module &M);
+
+ private:
+ /// processType - Process DIType.
+ void processType(DIType DT);
+
+ /// processLexicalBlock - Process DILexicalBlock.
+ void processLexicalBlock(DILexicalBlock LB);
+
+ /// processSubprogram - Process DISubprogram.
+ void processSubprogram(DISubprogram SP);
+
+ /// processDeclare - Process DbgDeclareInst.
+ void processDeclare(DbgDeclareInst *DDI);
+
+ /// processLocation - Process DILocation.
+ void processLocation(DILocation Loc);
+
+ /// addCompileUnit - Add compile unit into CUs.
+ bool addCompileUnit(DICompileUnit CU);
+
+ /// addGlobalVariable - Add global variable into GVs.
+ bool addGlobalVariable(DIGlobalVariable DIG);
+
+ // addSubprogram - Add subprogram into SPs.
+ bool addSubprogram(DISubprogram SP);
+
+ /// addType - Add type into Tys.
+ bool addType(DIType DT);
+
+ public:
+ typedef SmallVector<MDNode *, 8>::const_iterator iterator;
+ iterator compile_unit_begin() const { return CUs.begin(); }
+ iterator compile_unit_end() const { return CUs.end(); }
+ iterator subprogram_begin() const { return SPs.begin(); }
+ iterator subprogram_end() const { return SPs.end(); }
+ iterator global_variable_begin() const { return GVs.begin(); }
+ iterator global_variable_end() const { return GVs.end(); }
+ iterator type_begin() const { return TYs.begin(); }
+ iterator type_end() const { return TYs.end(); }
+
+ unsigned compile_unit_count() const { return CUs.size(); }
+ unsigned global_variable_count() const { return GVs.size(); }
+ unsigned subprogram_count() const { return SPs.size(); }
+ unsigned type_count() const { return TYs.size(); }
+
+ private:
+ SmallVector<MDNode *, 8> CUs; // Compile Units
+ SmallVector<MDNode *, 8> SPs; // Subprograms
+ SmallVector<MDNode *, 8> GVs; // Global Variables;
+ SmallVector<MDNode *, 8> TYs; // Types
+ SmallPtrSet<MDNode *, 64> NodesSeen;
+ };
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/DebugInfo/DIContext.h b/include/llvm/DebugInfo/DIContext.h
new file mode 100644
index 00000000000..8d6054aa456
--- /dev/null
+++ b/include/llvm/DebugInfo/DIContext.h
@@ -0,0 +1,115 @@
+//===-- DIContext.h ---------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines DIContext, an abstract data structure that holds
+// debug information data.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_DEBUGINFO_DICONTEXT_H
+#define LLVM_DEBUGINFO_DICONTEXT_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+class raw_ostream;
+
+/// DILineInfo - a format-neutral container for source line information.
+class DILineInfo {
+ SmallString<16> FileName;
+ SmallString<16> FunctionName;
+ uint32_t Line;
+ uint32_t Column;
+public:
+ DILineInfo()
+ : FileName("<invalid>"), FunctionName("<invalid>"),
+ Line(0), Column(0) {}
+ DILineInfo(const SmallString<16> &fileName,
+ const SmallString<16> &functionName,
+ uint32_t line, uint32_t column)
+ : FileName(fileName), FunctionName(functionName),
+ Line(line), Column(column) {}
+
+ const char *getFileName() { return FileName.c_str(); }
+ const char *getFunctionName() { return FunctionName.c_str(); }
+ uint32_t getLine() const { return Line; }
+ uint32_t getColumn() const { return Column; }
+
+ bool operator==(const DILineInfo &RHS) const {
+ return Line == RHS.Line && Column == RHS.Column &&
+ FileName.equals(RHS.FileName) &&
+ FunctionName.equals(RHS.FunctionName);
+ }
+ bool operator!=(const DILineInfo &RHS) const {
+ return !(*this == RHS);
+ }
+};
+
+/// DIInliningInfo - a format-neutral container for inlined code description.
+class DIInliningInfo {
+ SmallVector<DILineInfo, 4> Frames;
+ public:
+ DIInliningInfo() {}
+ DILineInfo getFrame(unsigned Index) const {
+ assert(Index < Frames.size());
+ return Frames[Index];
+ }
+ uint32_t getNumberOfFrames() const {
+ return Frames.size();
+ }
+ void addFrame(const DILineInfo &Frame) {
+ Frames.push_back(Frame);
+ }
+};
+
+/// DILineInfoSpecifier - controls which fields of DILineInfo container
+/// should be filled with data.
+class DILineInfoSpecifier {
+ const uint32_t Flags; // Or'ed flags that set the info we want to fetch.
+public:
+ enum Specification {
+ FileLineInfo = 1 << 0,
+ AbsoluteFilePath = 1 << 1,
+ FunctionName = 1 << 2
+ };
+ // Use file/line info by default.
+ DILineInfoSpecifier(uint32_t flags = FileLineInfo) : Flags(flags) {}
+ bool needs(Specification spec) const {
+ return (Flags & spec) > 0;
+ }
+};
+
+class DIContext {
+public:
+ virtual ~DIContext();
+
+ /// getDWARFContext - get a context for binary DWARF data.
+ static DIContext *getDWARFContext(bool isLittleEndian,
+ StringRef infoSection,
+ StringRef abbrevSection,
+ StringRef aRangeSection = StringRef(),
+ StringRef lineSection = StringRef(),
+ StringRef stringSection = StringRef(),
+ StringRef rangeSection = StringRef());
+
+ virtual void dump(raw_ostream &OS) = 0;
+
+ virtual DILineInfo getLineInfoForAddress(uint64_t Address,
+ DILineInfoSpecifier Specifier = DILineInfoSpecifier()) = 0;
+ virtual DIInliningInfo getInliningInfoForAddress(uint64_t Address,
+ DILineInfoSpecifier Specifier = DILineInfoSpecifier()) = 0;
+};
+
+}
+
+#endif
diff --git a/include/llvm/DefaultPasses.h b/include/llvm/DefaultPasses.h
new file mode 100644
index 00000000000..9f1ade86aba
--- /dev/null
+++ b/include/llvm/DefaultPasses.h
@@ -0,0 +1,168 @@
+//===- llvm/DefaultPasses.h - Default Pass Support code --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+// This file defines the infrastructure for registering the standard pass list.
+// This defines sets of standard optimizations that plugins can modify and
+// front ends can use.
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_DEFAULT_PASS_SUPPORT_H
+#define LLVM_DEFAULT_PASS_SUPPORT_H
+
+#include "llvm/PassSupport.h"
+
+namespace llvm {
+
+class PassManagerBase;
+
+/// Unique identifiers for the default standard passes. The addresses of
+/// these symbols are used to uniquely identify passes from the default list.
+namespace DefaultStandardPasses {
+extern unsigned char AggressiveDCEID;
+extern unsigned char ArgumentPromotionID;
+extern unsigned char BasicAliasAnalysisID;
+extern unsigned char CFGSimplificationID;
+extern unsigned char ConstantMergeID;
+extern unsigned char CorrelatedValuePropagationID;
+extern unsigned char DeadArgEliminationID;
+extern unsigned char DeadStoreEliminationID;
+extern unsigned char EarlyCSEID;
+extern unsigned char FunctionAttrsID;
+extern unsigned char FunctionInliningID;
+extern unsigned char GVNID;
+extern unsigned char GlobalDCEID;
+extern unsigned char GlobalOptimizerID;
+extern unsigned char GlobalsModRefID;
+extern unsigned char IPSCCPID;
+extern unsigned char IndVarSimplifyID;
+extern unsigned char InlinerPlaceholderID;
+extern unsigned char InstructionCombiningID;
+extern unsigned char JumpThreadingID;
+extern unsigned char LICMID;
+extern unsigned char LoopDeletionID;
+extern unsigned char LoopIdiomID;
+extern unsigned char LoopRotateID;
+extern unsigned char LoopUnrollID;
+extern unsigned char LoopUnswitchID;
+extern unsigned char MemCpyOptID;
+extern unsigned char PruneEHID;
+extern unsigned char ReassociateID;
+extern unsigned char SCCPID;
+extern unsigned char ScalarReplAggregatesID;
+extern unsigned char SimplifyLibCallsID;
+extern unsigned char StripDeadPrototypesID;
+extern unsigned char TailCallEliminationID;
+extern unsigned char TypeBasedAliasAnalysisID;
+}
+
+/// StandardPass - The class responsible for maintaining the lists of standard
+class StandardPass {
+ friend class RegisterStandardPassLists;
+ public:
+ /// Predefined standard sets of passes
+ enum StandardSet {
+ AliasAnalysis,
+ Function,
+ Module,
+ LTO
+ };
+ /// Flags to specify whether a pass should be enabled. Passes registered
+ /// with the standard sets may specify a minimum optimization level and one
+ /// or more flags that must be set when constructing the set for the pass to
+ /// be used.
+ enum OptimizationFlags {
+ /// Optimize for size was requested.
+ OptimizeSize = 1<<0,
+ /// Allow passes which may make global module changes.
+ UnitAtATime = 1<<1,
+ /// UnrollLoops - Allow loop unrolling.
+ UnrollLoops = 1<<2,
+ /// Allow library calls to be simplified.
+ SimplifyLibCalls = 1<<3,
+ /// Whether the module may have code using exceptions.
+ HaveExceptions = 1<<4,
+ // Run an inliner pass as part of this set.
+ RunInliner = 1<<5
+ };
+ enum OptimizationFlagComponents {
+ /// The low bits are used to store the optimization level. When requesting
+ /// passes, this should store the requested optimisation level. When
+ /// setting passes, this should set the minimum optimization level at which
+ /// the pass will run.
+ OptimizationLevelMask=0xf,
+ /// The maximum optimisation level at which the pass is run.
+ MaxOptimizationLevelMask=0xf0,
+ // Flags that must be set
+ RequiredFlagMask=0xff00,
+ // Flags that may not be set.
+ DisallowedFlagMask=0xff0000,
+ MaxOptimizationLevelShift=4,
+ RequiredFlagShift=8,
+ DisallowedFlagShift=16
+ };
+ /// Returns the optimisation level from a set of flags.
+ static unsigned OptimizationLevel(unsigned flags) {
+ return flags & OptimizationLevelMask;
+ }
+ /// Returns the maximum optimization level for this set of flags
+ static unsigned MaxOptimizationLevel(unsigned flags) {
+ return (flags & MaxOptimizationLevelMask) >> 4;
+ }
+ /// Constructs a set of flags from the specified minimum and maximum
+ /// optimisation level
+ static unsigned OptimzationFlags(unsigned minLevel=0, unsigned maxLevel=0xf,
+ unsigned requiredFlags=0, unsigned disallowedFlags=0) {
+ return ((minLevel & OptimizationLevelMask) |
+ ((maxLevel<<MaxOptimizationLevelShift) & MaxOptimizationLevelMask)
+ | ((requiredFlags<<RequiredFlagShift) & RequiredFlagMask)
+ | ((disallowedFlags<<DisallowedFlagShift) & DisallowedFlagMask));
+ }
+ /// Returns the flags that must be set for this to match
+ static unsigned RequiredFlags(unsigned flags) {
+ return (flags & RequiredFlagMask) >> RequiredFlagShift;
+ }
+ /// Returns the flags that must not be set for this to match
+ static unsigned DisallowedFlags(unsigned flags) {
+ return (flags & DisallowedFlagMask) >> DisallowedFlagShift;
+ }
+ /// Register a standard pass in the specified set. If flags is non-zero,
+ /// then the pass will only be returned when the specified flags are set.
+ template<typename passName>
+ class RegisterStandardPass {
+ public:
+ RegisterStandardPass(StandardSet set, unsigned char *runBefore=0,
+ unsigned flags=0, unsigned char *ID=0) {
+ // Use the pass's ID if one is not specified
+ RegisterDefaultPass(PassInfo::NormalCtor_t(callDefaultCtor<passName>),
+ ID ? ID : (unsigned char*)&passName::ID, runBefore, set, flags);
+ }
+ };
+ /// Adds the passes from the specified set to the provided pass manager
+ static void AddPassesFromSet(PassManagerBase *PM,
+ StandardSet set,
+ unsigned flags=0,
+ bool VerifyEach=false,
+ Pass *inliner=0);
+ private:
+ /// Registers the default passes. This is set by RegisterStandardPassLists
+ /// and is called lazily.
+ static void (*RegisterDefaultPasses)(void);
+ /// Creates the verifier pass that is inserted when a VerifyEach is passed to
+ /// AddPassesFromSet()
+ static Pass* (*CreateVerifierPass)(void);
+ /// Registers the pass
+ static void RegisterDefaultPass(PassInfo::NormalCtor_t constructor,
+ unsigned char *newPass,
+ unsigned char *oldPass,
+ StandardSet set,
+ unsigned flags=0);
+};
+
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/DerivedTypes.h b/include/llvm/DerivedTypes.h
new file mode 100644
index 00000000000..9a723084a6c
--- /dev/null
+++ b/include/llvm/DerivedTypes.h
@@ -0,0 +1,463 @@
+//===-- llvm/DerivedTypes.h - Classes for handling data types ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declarations of classes that represent "derived
+// types". These are things like "arrays of x" or "structure of x, y, z" or
+// "function returning x taking (y,z) as parameters", etc...
+//
+// The implementations of these classes live in the Type.cpp file.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_DERIVED_TYPES_H
+#define LLVM_DERIVED_TYPES_H
+
+#include "llvm/Type.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+class Value;
+class APInt;
+class LLVMContext;
+template<typename T> class ArrayRef;
+class StringRef;
+
+/// Class to represent integer types. Note that this class is also used to
+/// represent the built-in integer types: Int1Ty, Int8Ty, Int16Ty, Int32Ty and
+/// Int64Ty.
+/// @brief Integer representation type
+class IntegerType : public Type {
+ friend class LLVMContextImpl;
+
+protected:
+ explicit IntegerType(LLVMContext &C, unsigned NumBits) : Type(C, IntegerTyID){
+ setSubclassData(NumBits);
+ }
+public:
+ /// This enum is just used to hold constants we need for IntegerType.
+ enum {
+ MIN_INT_BITS = 1, ///< Minimum number of bits that can be specified
+ MAX_INT_BITS = (1<<23)-1 ///< Maximum number of bits that can be specified
+ ///< Note that bit width is stored in the Type classes SubclassData field
+ ///< which has 23 bits. This yields a maximum bit width of 8,388,607 bits.
+ };
+
+ /// This static method is the primary way of constructing an IntegerType.
+ /// If an IntegerType with the same NumBits value was previously instantiated,
+ /// that instance will be returned. Otherwise a new one will be created. Only
+ /// one instance with a given NumBits value is ever created.
+ /// @brief Get or create an IntegerType instance.
+ static IntegerType *get(LLVMContext &C, unsigned NumBits);
+
+ /// @brief Get the number of bits in this IntegerType
+ unsigned getBitWidth() const { return getSubclassData(); }
+
+ /// getBitMask - Return a bitmask with ones set for all of the bits
+ /// that can be set by an unsigned version of this type. This is 0xFF for
+ /// i8, 0xFFFF for i16, etc.
+ uint64_t getBitMask() const {
+ return ~uint64_t(0UL) >> (64-getBitWidth());
+ }
+
+ /// getSignBit - Return a uint64_t with just the most significant bit set (the
+ /// sign bit, if the value is treated as a signed number).
+ uint64_t getSignBit() const {
+ return 1ULL << (getBitWidth()-1);
+ }
+
+ /// For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
+ /// @returns a bit mask with ones set for all the bits of this type.
+ /// @brief Get a bit mask for this type.
+ APInt getMask() const;
+
+ /// This method determines if the width of this IntegerType is a power-of-2
+ /// in terms of 8 bit bytes.
+ /// @returns true if this is a power-of-2 byte width.
+ /// @brief Is this a power-of-2 byte-width IntegerType ?
+ bool isPowerOf2ByteWidth() const;
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const IntegerType *) { return true; }
+ static inline bool classof(const Type *T) {
+ return T->getTypeID() == IntegerTyID;
+ }
+};
+
+
+/// FunctionType - Class to represent function types
+///
+class FunctionType : public Type {
+ FunctionType(const FunctionType &) LLVM_DELETED_FUNCTION;
+ const FunctionType &operator=(const FunctionType &) LLVM_DELETED_FUNCTION;
+ FunctionType(Type *Result, ArrayRef<Type*> Params, bool IsVarArgs);
+
+public:
+ /// FunctionType::get - This static method is the primary way of constructing
+ /// a FunctionType.
+ ///
+ static FunctionType *get(Type *Result,
+ ArrayRef<Type*> Params, bool isVarArg);
+
+ /// FunctionType::get - Create a FunctionType taking no parameters.
+ ///
+ static FunctionType *get(Type *Result, bool isVarArg);
+
+ /// isValidReturnType - Return true if the specified type is valid as a return
+ /// type.
+ static bool isValidReturnType(Type *RetTy);
+
+ /// isValidArgumentType - Return true if the specified type is valid as an
+ /// argument type.
+ static bool isValidArgumentType(Type *ArgTy);
+
+ bool isVarArg() const { return getSubclassData(); }
+ Type *getReturnType() const { return ContainedTys[0]; }
+
+ typedef Type::subtype_iterator param_iterator;
+ param_iterator param_begin() const { return ContainedTys + 1; }
+ param_iterator param_end() const { return &ContainedTys[NumContainedTys]; }
+
+ // Parameter type accessors.
+ Type *getParamType(unsigned i) const { return ContainedTys[i+1]; }
+
+ /// getNumParams - Return the number of fixed parameters this function type
+ /// requires. This does not consider varargs.
+ ///
+ unsigned getNumParams() const { return NumContainedTys - 1; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const FunctionType *) { return true; }
+ static inline bool classof(const Type *T) {
+ return T->getTypeID() == FunctionTyID;
+ }
+};
+
+
+/// CompositeType - Common super class of ArrayType, StructType, PointerType
+/// and VectorType.
+class CompositeType : public Type {
+protected:
+ explicit CompositeType(LLVMContext &C, TypeID tid) : Type(C, tid) { }
+public:
+
+ /// getTypeAtIndex - Given an index value into the type, return the type of
+ /// the element.
+ ///
+ Type *getTypeAtIndex(const Value *V);
+ Type *getTypeAtIndex(unsigned Idx);
+ bool indexValid(const Value *V) const;
+ bool indexValid(unsigned Idx) const;
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const CompositeType *) { return true; }
+ static inline bool classof(const Type *T) {
+ return T->getTypeID() == ArrayTyID ||
+ T->getTypeID() == StructTyID ||
+ T->getTypeID() == PointerTyID ||
+ T->getTypeID() == VectorTyID;
+ }
+};
+
+
+/// StructType - Class to represent struct types. There are two different kinds
+/// of struct types: Literal structs and Identified structs.
+///
+/// Literal struct types (e.g. { i32, i32 }) are uniqued structurally, and must
+/// always have a body when created. You can get one of these by using one of
+/// the StructType::get() forms.
+///
+/// Identified structs (e.g. %foo or %42) may optionally have a name and are not
+/// uniqued. The names for identified structs are managed at the LLVMContext
+/// level, so there can only be a single identified struct with a given name in
+/// a particular LLVMContext. Identified structs may also optionally be opaque
+/// (have no body specified). You get one of these by using one of the
+/// StructType::create() forms.
+///
+/// Independent of what kind of struct you have, the body of a struct type are
+/// laid out in memory consequtively with the elements directly one after the
+/// other (if the struct is packed) or (if not packed) with padding between the
+/// elements as defined by TargetData (which is required to match what the code
+/// generator for a target expects).
+///
+class StructType : public CompositeType {
+ StructType(const StructType &) LLVM_DELETED_FUNCTION;
+ const StructType &operator=(const StructType &) LLVM_DELETED_FUNCTION;
+ StructType(LLVMContext &C)
+ : CompositeType(C, StructTyID), SymbolTableEntry(0) {}
+ enum {
+ // This is the contents of the SubClassData field.
+ SCDB_HasBody = 1,
+ SCDB_Packed = 2,
+ SCDB_IsLiteral = 4,
+ SCDB_IsSized = 8
+ };
+
+ /// SymbolTableEntry - For a named struct that actually has a name, this is a
+ /// pointer to the symbol table entry (maintained by LLVMContext) for the
+ /// struct. This is null if the type is an literal struct or if it is
+ /// a identified type that has an empty name.
+ ///
+ void *SymbolTableEntry;
+public:
+ ~StructType() {
+ delete [] ContainedTys; // Delete the body.
+ }
+
+ /// StructType::create - This creates an identified struct.
+ static StructType *create(LLVMContext &Context, StringRef Name);
+ static StructType *create(LLVMContext &Context);
+
+ static StructType *create(ArrayRef<Type*> Elements,
+ StringRef Name,
+ bool isPacked = false);
+ static StructType *create(ArrayRef<Type*> Elements);
+ static StructType *create(LLVMContext &Context,
+ ArrayRef<Type*> Elements,
+ StringRef Name,
+ bool isPacked = false);
+ static StructType *create(LLVMContext &Context, ArrayRef<Type*> Elements);
+ static StructType *create(StringRef Name, Type *elt1, ...) END_WITH_NULL;
+
+ /// StructType::get - This static method is the primary way to create a
+ /// literal StructType.
+ static StructType *get(LLVMContext &Context, ArrayRef<Type*> Elements,
+ bool isPacked = false);
+
+ /// StructType::get - Create an empty structure type.
+ ///
+ static StructType *get(LLVMContext &Context, bool isPacked = false);
+
+ /// StructType::get - This static method is a convenience method for creating
+ /// structure types by specifying the elements as arguments. Note that this
+ /// method always returns a non-packed struct, and requires at least one
+ /// element type.
+ static StructType *get(Type *elt1, ...) END_WITH_NULL;
+
+ bool isPacked() const { return (getSubclassData() & SCDB_Packed) != 0; }
+
+ /// isLiteral - Return true if this type is uniqued by structural
+ /// equivalence, false if it is a struct definition.
+ bool isLiteral() const { return (getSubclassData() & SCDB_IsLiteral) != 0; }
+
+ /// isOpaque - Return true if this is a type with an identity that has no body
+ /// specified yet. These prints as 'opaque' in .ll files.
+ bool isOpaque() const { return (getSubclassData() & SCDB_HasBody) == 0; }
+
+ /// isSized - Return true if this is a sized type.
+ bool isSized() const;
+
+ /// hasName - Return true if this is a named struct that has a non-empty name.
+ bool hasName() const { return SymbolTableEntry != 0; }
+
+ /// getName - Return the name for this struct type if it has an identity.
+ /// This may return an empty string for an unnamed struct type. Do not call
+ /// this on an literal type.
+ StringRef getName() const;
+
+ /// setName - Change the name of this type to the specified name, or to a name
+ /// with a suffix if there is a collision. Do not call this on an literal
+ /// type.
+ void setName(StringRef Name);
+
+ /// setBody - Specify a body for an opaque identified type.
+ void setBody(ArrayRef<Type*> Elements, bool isPacked = false);
+ void setBody(Type *elt1, ...) END_WITH_NULL;
+
+ /// isValidElementType - Return true if the specified type is valid as a
+ /// element type.
+ static bool isValidElementType(Type *ElemTy);
+
+
+ // Iterator access to the elements.
+ typedef Type::subtype_iterator element_iterator;
+ element_iterator element_begin() const { return ContainedTys; }
+ element_iterator element_end() const { return &ContainedTys[NumContainedTys];}
+
+ /// isLayoutIdentical - Return true if this is layout identical to the
+ /// specified struct.
+ bool isLayoutIdentical(StructType *Other) const;
+
+ // Random access to the elements
+ unsigned getNumElements() const { return NumContainedTys; }
+ Type *getElementType(unsigned N) const {
+ assert(N < NumContainedTys && "Element number out of range!");
+ return ContainedTys[N];
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const StructType *) { return true; }
+ static inline bool classof(const Type *T) {
+ return T->getTypeID() == StructTyID;
+ }
+};
+
+/// SequentialType - This is the superclass of the array, pointer and vector
+/// type classes. All of these represent "arrays" in memory. The array type
+/// represents a specifically sized array, pointer types are unsized/unknown
+/// size arrays, vector types represent specifically sized arrays that
+/// allow for use of SIMD instructions. SequentialType holds the common
+/// features of all, which stem from the fact that all three lay their
+/// components out in memory identically.
+///
+class SequentialType : public CompositeType {
+ Type *ContainedType; ///< Storage for the single contained type.
+ SequentialType(const SequentialType &) LLVM_DELETED_FUNCTION;
+ const SequentialType &operator=(const SequentialType &) LLVM_DELETED_FUNCTION;
+
+protected:
+ SequentialType(TypeID TID, Type *ElType)
+ : CompositeType(ElType->getContext(), TID), ContainedType(ElType) {
+ ContainedTys = &ContainedType;
+ NumContainedTys = 1;
+ }
+
+public:
+ Type *getElementType() const { return ContainedTys[0]; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const SequentialType *) { return true; }
+ static inline bool classof(const Type *T) {
+ return T->getTypeID() == ArrayTyID ||
+ T->getTypeID() == PointerTyID ||
+ T->getTypeID() == VectorTyID;
+ }
+};
+
+
+/// ArrayType - Class to represent array types.
+///
+class ArrayType : public SequentialType {
+ uint64_t NumElements;
+
+ ArrayType(const ArrayType &) LLVM_DELETED_FUNCTION;
+ const ArrayType &operator=(const ArrayType &) LLVM_DELETED_FUNCTION;
+ ArrayType(Type *ElType, uint64_t NumEl);
+public:
+ /// ArrayType::get - This static method is the primary way to construct an
+ /// ArrayType
+ ///
+ static ArrayType *get(Type *ElementType, uint64_t NumElements);
+
+ /// isValidElementType - Return true if the specified type is valid as a
+ /// element type.
+ static bool isValidElementType(Type *ElemTy);
+
+ uint64_t getNumElements() const { return NumElements; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const ArrayType *) { return true; }
+ static inline bool classof(const Type *T) {
+ return T->getTypeID() == ArrayTyID;
+ }
+};
+
+/// VectorType - Class to represent vector types.
+///
+class VectorType : public SequentialType {
+ unsigned NumElements;
+
+ VectorType(const VectorType &) LLVM_DELETED_FUNCTION;
+ const VectorType &operator=(const VectorType &) LLVM_DELETED_FUNCTION;
+ VectorType(Type *ElType, unsigned NumEl);
+public:
+ /// VectorType::get - This static method is the primary way to construct an
+ /// VectorType.
+ ///
+ static VectorType *get(Type *ElementType, unsigned NumElements);
+
+ /// VectorType::getInteger - This static method gets a VectorType with the
+ /// same number of elements as the input type, and the element type is an
+ /// integer type of the same width as the input element type.
+ ///
+ static VectorType *getInteger(VectorType *VTy) {
+ unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
+ assert(EltBits && "Element size must be of a non-zero size");
+ Type *EltTy = IntegerType::get(VTy->getContext(), EltBits);
+ return VectorType::get(EltTy, VTy->getNumElements());
+ }
+
+ /// VectorType::getExtendedElementVectorType - This static method is like
+ /// getInteger except that the element types are twice as wide as the
+ /// elements in the input type.
+ ///
+ static VectorType *getExtendedElementVectorType(VectorType *VTy) {
+ unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
+ Type *EltTy = IntegerType::get(VTy->getContext(), EltBits * 2);
+ return VectorType::get(EltTy, VTy->getNumElements());
+ }
+
+ /// VectorType::getTruncatedElementVectorType - This static method is like
+ /// getInteger except that the element types are half as wide as the
+ /// elements in the input type.
+ ///
+ static VectorType *getTruncatedElementVectorType(VectorType *VTy) {
+ unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
+ assert((EltBits & 1) == 0 &&
+ "Cannot truncate vector element with odd bit-width");
+ Type *EltTy = IntegerType::get(VTy->getContext(), EltBits / 2);
+ return VectorType::get(EltTy, VTy->getNumElements());
+ }
+
+ /// isValidElementType - Return true if the specified type is valid as a
+ /// element type.
+ static bool isValidElementType(Type *ElemTy);
+
+ /// @brief Return the number of elements in the Vector type.
+ unsigned getNumElements() const { return NumElements; }
+
+ /// @brief Return the number of bits in the Vector type.
+ /// Returns zero when the vector is a vector of pointers.
+ unsigned getBitWidth() const {
+ return NumElements * getElementType()->getPrimitiveSizeInBits();
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const VectorType *) { return true; }
+ static inline bool classof(const Type *T) {
+ return T->getTypeID() == VectorTyID;
+ }
+};
+
+
+/// PointerType - Class to represent pointers.
+///
+class PointerType : public SequentialType {
+ PointerType(const PointerType &) LLVM_DELETED_FUNCTION;
+ const PointerType &operator=(const PointerType &) LLVM_DELETED_FUNCTION;
+ explicit PointerType(Type *ElType, unsigned AddrSpace);
+public:
+ /// PointerType::get - This constructs a pointer to an object of the specified
+ /// type in a numbered address space.
+ static PointerType *get(Type *ElementType, unsigned AddressSpace);
+
+ /// PointerType::getUnqual - This constructs a pointer to an object of the
+ /// specified type in the generic address space (address space zero).
+ static PointerType *getUnqual(Type *ElementType) {
+ return PointerType::get(ElementType, 0);
+ }
+
+ /// isValidElementType - Return true if the specified type is valid as a
+ /// element type.
+ static bool isValidElementType(Type *ElemTy);
+
+ /// @brief Return the address space of the Pointer type.
+ inline unsigned getAddressSpace() const { return getSubclassData(); }
+
+ // Implement support type inquiry through isa, cast, and dyn_cast.
+ static inline bool classof(const PointerType *) { return true; }
+ static inline bool classof(const Type *T) {
+ return T->getTypeID() == PointerTyID;
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ExecutionEngine/ExecutionEngine.h b/include/llvm/ExecutionEngine/ExecutionEngine.h
new file mode 100644
index 00000000000..3c6d3b8dbf3
--- /dev/null
+++ b/include/llvm/ExecutionEngine/ExecutionEngine.h
@@ -0,0 +1,623 @@
+//===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the abstract interface that implements execution support
+// for LLVM.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_EXECUTION_ENGINE_H
+#define LLVM_EXECUTION_ENGINE_H
+
+#include "llvm/MC/MCCodeGenInfo.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/ValueMap.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/ValueHandle.h"
+#include "llvm/Support/Mutex.h"
+#include "llvm/Target/TargetMachine.h"
+#include "llvm/Target/TargetOptions.h"
+#include <vector>
+#include <map>
+#include <string>
+
+namespace llvm {
+
+struct GenericValue;
+class Constant;
+class ExecutionEngine;
+class Function;
+class GlobalVariable;
+class GlobalValue;
+class JITEventListener;
+class JITMemoryManager;
+class MachineCodeInfo;
+class Module;
+class MutexGuard;
+class TargetData;
+class Triple;
+class Type;
+
+/// \brief Helper class for helping synchronize access to the global address map
+/// table.
+class ExecutionEngineState {
+public:
+ struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
+ typedef ExecutionEngineState *ExtraData;
+ static sys::Mutex *getMutex(ExecutionEngineState *EES);
+ static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
+ static void onRAUW(ExecutionEngineState *, const GlobalValue *,
+ const GlobalValue *);
+ };
+
+ typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
+ GlobalAddressMapTy;
+
+private:
+ ExecutionEngine &EE;
+
+ /// GlobalAddressMap - A mapping between LLVM global values and their
+ /// actualized version...
+ GlobalAddressMapTy GlobalAddressMap;
+
+ /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
+ /// used to convert raw addresses into the LLVM global value that is emitted
+ /// at the address. This map is not computed unless getGlobalValueAtAddress
+ /// is called at some point.
+ std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
+
+public:
+ ExecutionEngineState(ExecutionEngine &EE);
+
+ GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
+ return GlobalAddressMap;
+ }
+
+ std::map<void*, AssertingVH<const GlobalValue> > &
+ getGlobalAddressReverseMap(const MutexGuard &) {
+ return GlobalAddressReverseMap;
+ }
+
+ /// \brief Erase an entry from the mapping table.
+ ///
+ /// \returns The address that \p ToUnmap was happed to.
+ void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
+};
+
+/// \brief Abstract interface for implementation execution of LLVM modules,
+/// designed to support both interpreter and just-in-time (JIT) compiler
+/// implementations.
+class ExecutionEngine {
+ /// The state object holding the global address mapping, which must be
+ /// accessed synchronously.
+ //
+ // FIXME: There is no particular need the entire map needs to be
+ // synchronized. Wouldn't a reader-writer design be better here?
+ ExecutionEngineState EEState;
+
+ /// The target data for the platform for which execution is being performed.
+ const TargetData *TD;
+
+ /// Whether lazy JIT compilation is enabled.
+ bool CompilingLazily;
+
+ /// Whether JIT compilation of external global variables is allowed.
+ bool GVCompilationDisabled;
+
+ /// Whether the JIT should perform lookups of external symbols (e.g.,
+ /// using dlsym).
+ bool SymbolSearchingDisabled;
+
+ friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
+
+protected:
+ /// The list of Modules that we are JIT'ing from. We use a SmallVector to
+ /// optimize for the case where there is only one module.
+ SmallVector<Module*, 1> Modules;
+
+ void setTargetData(const TargetData *td) { TD = td; }
+
+ /// getMemoryforGV - Allocate memory for a global variable.
+ virtual char *getMemoryForGV(const GlobalVariable *GV);
+
+ // To avoid having libexecutionengine depend on the JIT and interpreter
+ // libraries, the execution engine implementations set these functions to ctor
+ // pointers at startup time if they are linked in.
+ static ExecutionEngine *(*JITCtor)(
+ Module *M,
+ std::string *ErrorStr,
+ JITMemoryManager *JMM,
+ bool GVsWithCode,
+ TargetMachine *TM);
+ static ExecutionEngine *(*MCJITCtor)(
+ Module *M,
+ std::string *ErrorStr,
+ JITMemoryManager *JMM,
+ bool GVsWithCode,
+ TargetMachine *TM);
+ static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
+
+ /// LazyFunctionCreator - If an unknown function is needed, this function
+ /// pointer is invoked to create it. If this returns null, the JIT will
+ /// abort.
+ void *(*LazyFunctionCreator)(const std::string &);
+
+ /// ExceptionTableRegister - If Exception Handling is set, the JIT will
+ /// register dwarf tables with this function.
+ typedef void (*EERegisterFn)(void*);
+ EERegisterFn ExceptionTableRegister;
+ EERegisterFn ExceptionTableDeregister;
+ /// This maps functions to their exception tables frames.
+ DenseMap<const Function*, void*> AllExceptionTables;
+
+
+public:
+ /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
+ /// JITEmitter classes. It must be held while changing the internal state of
+ /// any of those classes.
+ sys::Mutex lock;
+
+ //===--------------------------------------------------------------------===//
+ // ExecutionEngine Startup
+ //===--------------------------------------------------------------------===//
+
+ virtual ~ExecutionEngine();
+
+ /// create - This is the factory method for creating an execution engine which
+ /// is appropriate for the current machine. This takes ownership of the
+ /// module.
+ ///
+ /// \param GVsWithCode - Allocating globals with code breaks
+ /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
+ /// However, we have clients who depend on this behavior, so we must support
+ /// it. Eventually, when we're willing to break some backwards compatibility,
+ /// this flag should be flipped to false, so that by default
+ /// freeMachineCodeForFunction works.
+ static ExecutionEngine *create(Module *M,
+ bool ForceInterpreter = false,
+ std::string *ErrorStr = 0,
+ CodeGenOpt::Level OptLevel =
+ CodeGenOpt::Default,
+ bool GVsWithCode = true);
+
+ /// createJIT - This is the factory method for creating a JIT for the current
+ /// machine, it does not fall back to the interpreter. This takes ownership
+ /// of the Module and JITMemoryManager if successful.
+ ///
+ /// Clients should make sure to initialize targets prior to calling this
+ /// function.
+ static ExecutionEngine *createJIT(Module *M,
+ std::string *ErrorStr = 0,
+ JITMemoryManager *JMM = 0,
+ CodeGenOpt::Level OptLevel =
+ CodeGenOpt::Default,
+ bool GVsWithCode = true,
+ Reloc::Model RM = Reloc::Default,
+ CodeModel::Model CMM =
+ CodeModel::JITDefault);
+
+ /// addModule - Add a Module to the list of modules that we can JIT from.
+ /// Note that this takes ownership of the Module: when the ExecutionEngine is
+ /// destroyed, it destroys the Module as well.
+ virtual void addModule(Module *M) {
+ Modules.push_back(M);
+ }
+
+ //===--------------------------------------------------------------------===//
+
+ const TargetData *getTargetData() const { return TD; }
+
+ /// removeModule - Remove a Module from the list of modules. Returns true if
+ /// M is found.
+ virtual bool removeModule(Module *M);
+
+ /// FindFunctionNamed - Search all of the active modules to find the one that
+ /// defines FnName. This is very slow operation and shouldn't be used for
+ /// general code.
+ Function *FindFunctionNamed(const char *FnName);
+
+ /// runFunction - Execute the specified function with the specified arguments,
+ /// and return the result.
+ virtual GenericValue runFunction(Function *F,
+ const std::vector<GenericValue> &ArgValues) = 0;
+
+ /// getPointerToNamedFunction - This method returns the address of the
+ /// specified function by using the dlsym function call. As such it is only
+ /// useful for resolving library symbols, not code generated symbols.
+ ///
+ /// If AbortOnFailure is false and no function with the given name is
+ /// found, this function silently returns a null pointer. Otherwise,
+ /// it prints a message to stderr and aborts.
+ ///
+ virtual void *getPointerToNamedFunction(const std::string &Name,
+ bool AbortOnFailure = true) = 0;
+
+ /// mapSectionAddress - map a section to its target address space value.
+ /// Map the address of a JIT section as returned from the memory manager
+ /// to the address in the target process as the running code will see it.
+ /// This is the address which will be used for relocation resolution.
+ virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
+ llvm_unreachable("Re-mapping of section addresses not supported with this "
+ "EE!");
+ }
+
+ /// runStaticConstructorsDestructors - This method is used to execute all of
+ /// the static constructors or destructors for a program.
+ ///
+ /// \param isDtors - Run the destructors instead of constructors.
+ void runStaticConstructorsDestructors(bool isDtors);
+
+ /// runStaticConstructorsDestructors - This method is used to execute all of
+ /// the static constructors or destructors for a particular module.
+ ///
+ /// \param isDtors - Run the destructors instead of constructors.
+ void runStaticConstructorsDestructors(Module *module, bool isDtors);
+
+
+ /// runFunctionAsMain - This is a helper function which wraps runFunction to
+ /// handle the common task of starting up main with the specified argc, argv,
+ /// and envp parameters.
+ int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
+ const char * const * envp);
+
+
+ /// addGlobalMapping - Tell the execution engine that the specified global is
+ /// at the specified location. This is used internally as functions are JIT'd
+ /// and as global variables are laid out in memory. It can and should also be
+ /// used by clients of the EE that want to have an LLVM global overlay
+ /// existing data in memory. Mappings are automatically removed when their
+ /// GlobalValue is destroyed.
+ void addGlobalMapping(const GlobalValue *GV, void *Addr);
+
+ /// clearAllGlobalMappings - Clear all global mappings and start over again,
+ /// for use in dynamic compilation scenarios to move globals.
+ void clearAllGlobalMappings();
+
+ /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
+ /// particular module, because it has been removed from the JIT.
+ void clearGlobalMappingsFromModule(Module *M);
+
+ /// updateGlobalMapping - Replace an existing mapping for GV with a new
+ /// address. This updates both maps as required. If "Addr" is null, the
+ /// entry for the global is removed from the mappings. This returns the old
+ /// value of the pointer, or null if it was not in the map.
+ void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
+
+ /// getPointerToGlobalIfAvailable - This returns the address of the specified
+ /// global value if it is has already been codegen'd, otherwise it returns
+ /// null.
+ void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
+
+ /// getPointerToGlobal - This returns the address of the specified global
+ /// value. This may involve code generation if it's a function.
+ void *getPointerToGlobal(const GlobalValue *GV);
+
+ /// getPointerToFunction - The different EE's represent function bodies in
+ /// different ways. They should each implement this to say what a function
+ /// pointer should look like. When F is destroyed, the ExecutionEngine will
+ /// remove its global mapping and free any machine code. Be sure no threads
+ /// are running inside F when that happens.
+ virtual void *getPointerToFunction(Function *F) = 0;
+
+ /// getPointerToBasicBlock - The different EE's represent basic blocks in
+ /// different ways. Return the representation for a blockaddress of the
+ /// specified block.
+ virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
+
+ /// getPointerToFunctionOrStub - If the specified function has been
+ /// code-gen'd, return a pointer to the function. If not, compile it, or use
+ /// a stub to implement lazy compilation if available. See
+ /// getPointerToFunction for the requirements on destroying F.
+ virtual void *getPointerToFunctionOrStub(Function *F) {
+ // Default implementation, just codegen the function.
+ return getPointerToFunction(F);
+ }
+
+ // The JIT overrides a version that actually does this.
+ virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
+
+ /// getGlobalValueAtAddress - Return the LLVM global value object that starts
+ /// at the specified address.
+ ///
+ const GlobalValue *getGlobalValueAtAddress(void *Addr);
+
+ /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
+ /// Ptr is the address of the memory at which to store Val, cast to
+ /// GenericValue *. It is not a pointer to a GenericValue containing the
+ /// address at which to store Val.
+ void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
+ Type *Ty);
+
+ void InitializeMemory(const Constant *Init, void *Addr);
+
+ /// recompileAndRelinkFunction - This method is used to force a function which
+ /// has already been compiled to be compiled again, possibly after it has been
+ /// modified. Then the entry to the old copy is overwritten with a branch to
+ /// the new copy. If there was no old copy, this acts just like
+ /// VM::getPointerToFunction().
+ virtual void *recompileAndRelinkFunction(Function *F) = 0;
+
+ /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
+ /// corresponding to the machine code emitted to execute this function, useful
+ /// for garbage-collecting generated code.
+ virtual void freeMachineCodeForFunction(Function *F) = 0;
+
+ /// getOrEmitGlobalVariable - Return the address of the specified global
+ /// variable, possibly emitting it to memory if needed. This is used by the
+ /// Emitter.
+ virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
+ return getPointerToGlobal((const GlobalValue *)GV);
+ }
+
+ /// Registers a listener to be called back on various events within
+ /// the JIT. See JITEventListener.h for more details. Does not
+ /// take ownership of the argument. The argument may be NULL, in
+ /// which case these functions do nothing.
+ virtual void RegisterJITEventListener(JITEventListener *) {}
+ virtual void UnregisterJITEventListener(JITEventListener *) {}
+
+ /// DisableLazyCompilation - When lazy compilation is off (the default), the
+ /// JIT will eagerly compile every function reachable from the argument to
+ /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
+ /// compile the one function and emit stubs to compile the rest when they're
+ /// first called. If lazy compilation is turned off again while some lazy
+ /// stubs are still around, and one of those stubs is called, the program will
+ /// abort.
+ ///
+ /// In order to safely compile lazily in a threaded program, the user must
+ /// ensure that 1) only one thread at a time can call any particular lazy
+ /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
+ /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
+ /// lazy stub. See http://llvm.org/PR5184 for details.
+ void DisableLazyCompilation(bool Disabled = true) {
+ CompilingLazily = !Disabled;
+ }
+ bool isCompilingLazily() const {
+ return CompilingLazily;
+ }
+ // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
+ // Remove this in LLVM 2.8.
+ bool isLazyCompilationDisabled() const {
+ return !CompilingLazily;
+ }
+
+ /// DisableGVCompilation - If called, the JIT will abort if it's asked to
+ /// allocate space and populate a GlobalVariable that is not internal to
+ /// the module.
+ void DisableGVCompilation(bool Disabled = true) {
+ GVCompilationDisabled = Disabled;
+ }
+ bool isGVCompilationDisabled() const {
+ return GVCompilationDisabled;
+ }
+
+ /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
+ /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
+ /// resolve symbols in a custom way.
+ void DisableSymbolSearching(bool Disabled = true) {
+ SymbolSearchingDisabled = Disabled;
+ }
+ bool isSymbolSearchingDisabled() const {
+ return SymbolSearchingDisabled;
+ }
+
+ /// InstallLazyFunctionCreator - If an unknown function is needed, the
+ /// specified function pointer is invoked to create it. If it returns null,
+ /// the JIT will abort.
+ void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
+ LazyFunctionCreator = P;
+ }
+
+ /// InstallExceptionTableRegister - The JIT will use the given function
+ /// to register the exception tables it generates.
+ void InstallExceptionTableRegister(EERegisterFn F) {
+ ExceptionTableRegister = F;
+ }
+ void InstallExceptionTableDeregister(EERegisterFn F) {
+ ExceptionTableDeregister = F;
+ }
+
+ /// RegisterTable - Registers the given pointer as an exception table. It
+ /// uses the ExceptionTableRegister function.
+ void RegisterTable(const Function *fn, void* res) {
+ if (ExceptionTableRegister) {
+ ExceptionTableRegister(res);
+ AllExceptionTables[fn] = res;
+ }
+ }
+
+ /// DeregisterTable - Deregisters the exception frame previously registered
+ /// for the given function.
+ void DeregisterTable(const Function *Fn) {
+ if (ExceptionTableDeregister) {
+ DenseMap<const Function*, void*>::iterator frame =
+ AllExceptionTables.find(Fn);
+ if(frame != AllExceptionTables.end()) {
+ ExceptionTableDeregister(frame->second);
+ AllExceptionTables.erase(frame);
+ }
+ }
+ }
+
+ /// DeregisterAllTables - Deregisters all previously registered pointers to an
+ /// exception tables. It uses the ExceptionTableoDeregister function.
+ void DeregisterAllTables();
+
+protected:
+ explicit ExecutionEngine(Module *M);
+
+ void emitGlobals();
+
+ void EmitGlobalVariable(const GlobalVariable *GV);
+
+ GenericValue getConstantValue(const Constant *C);
+ void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
+ Type *Ty);
+};
+
+namespace EngineKind {
+ // These are actually bitmasks that get or-ed together.
+ enum Kind {
+ JIT = 0x1,
+ Interpreter = 0x2
+ };
+ const static Kind Either = (Kind)(JIT | Interpreter);
+}
+
+/// EngineBuilder - Builder class for ExecutionEngines. Use this by
+/// stack-allocating a builder, chaining the various set* methods, and
+/// terminating it with a .create() call.
+class EngineBuilder {
+private:
+ Module *M;
+ EngineKind::Kind WhichEngine;
+ std::string *ErrorStr;
+ CodeGenOpt::Level OptLevel;
+ JITMemoryManager *JMM;
+ bool AllocateGVsWithCode;
+ TargetOptions Options;
+ Reloc::Model RelocModel;
+ CodeModel::Model CMModel;
+ std::string MArch;
+ std::string MCPU;
+ SmallVector<std::string, 4> MAttrs;
+ bool UseMCJIT;
+
+ /// InitEngine - Does the common initialization of default options.
+ void InitEngine() {
+ WhichEngine = EngineKind::Either;
+ ErrorStr = NULL;
+ OptLevel = CodeGenOpt::Default;
+ JMM = NULL;
+ Options = TargetOptions();
+ AllocateGVsWithCode = false;
+ RelocModel = Reloc::Default;
+ CMModel = CodeModel::JITDefault;
+ UseMCJIT = false;
+ }
+
+public:
+ /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
+ /// is successful, the created engine takes ownership of the module.
+ EngineBuilder(Module *m) : M(m) {
+ InitEngine();
+ }
+
+ /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
+ /// or whichever engine works. This option defaults to EngineKind::Either.
+ EngineBuilder &setEngineKind(EngineKind::Kind w) {
+ WhichEngine = w;
+ return *this;
+ }
+
+ /// setJITMemoryManager - Sets the memory manager to use. This allows
+ /// clients to customize their memory allocation policies. If create() is
+ /// called and is successful, the created engine takes ownership of the
+ /// memory manager. This option defaults to NULL.
+ EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
+ JMM = jmm;
+ return *this;
+ }
+
+ /// setErrorStr - Set the error string to write to on error. This option
+ /// defaults to NULL.
+ EngineBuilder &setErrorStr(std::string *e) {
+ ErrorStr = e;
+ return *this;
+ }
+
+ /// setOptLevel - Set the optimization level for the JIT. This option
+ /// defaults to CodeGenOpt::Default.
+ EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
+ OptLevel = l;
+ return *this;
+ }
+
+ /// setTargetOptions - Set the target options that the ExecutionEngine
+ /// target is using. Defaults to TargetOptions().
+ EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
+ Options = Opts;
+ return *this;
+ }
+
+ /// setRelocationModel - Set the relocation model that the ExecutionEngine
+ /// target is using. Defaults to target specific default "Reloc::Default".
+ EngineBuilder &setRelocationModel(Reloc::Model RM) {
+ RelocModel = RM;
+ return *this;
+ }
+
+ /// setCodeModel - Set the CodeModel that the ExecutionEngine target
+ /// data is using. Defaults to target specific default
+ /// "CodeModel::JITDefault".
+ EngineBuilder &setCodeModel(CodeModel::Model M) {
+ CMModel = M;
+ return *this;
+ }
+
+ /// setAllocateGVsWithCode - Sets whether global values should be allocated
+ /// into the same buffer as code. For most applications this should be set
+ /// to false. Allocating globals with code breaks freeMachineCodeForFunction
+ /// and is probably unsafe and bad for performance. However, we have clients
+ /// who depend on this behavior, so we must support it. This option defaults
+ /// to false so that users of the new API can safely use the new memory
+ /// manager and free machine code.
+ EngineBuilder &setAllocateGVsWithCode(bool a) {
+ AllocateGVsWithCode = a;
+ return *this;
+ }
+
+ /// setMArch - Override the architecture set by the Module's triple.
+ EngineBuilder &setMArch(StringRef march) {
+ MArch.assign(march.begin(), march.end());
+ return *this;
+ }
+
+ /// setMCPU - Target a specific cpu type.
+ EngineBuilder &setMCPU(StringRef mcpu) {
+ MCPU.assign(mcpu.begin(), mcpu.end());
+ return *this;
+ }
+
+ /// setUseMCJIT - Set whether the MC-JIT implementation should be used
+ /// (experimental).
+ EngineBuilder &setUseMCJIT(bool Value) {
+ UseMCJIT = Value;
+ return *this;
+ }
+
+ /// setMAttrs - Set cpu-specific attributes.
+ template<typename StringSequence>
+ EngineBuilder &setMAttrs(const StringSequence &mattrs) {
+ MAttrs.clear();
+ MAttrs.append(mattrs.begin(), mattrs.end());
+ return *this;
+ }
+
+ TargetMachine *selectTarget();
+
+ /// selectTarget - Pick a target either via -march or by guessing the native
+ /// arch. Add any CPU features specified via -mcpu or -mattr.
+ TargetMachine *selectTarget(const Triple &TargetTriple,
+ StringRef MArch,
+ StringRef MCPU,
+ const SmallVectorImpl<std::string>& MAttrs);
+
+ ExecutionEngine *create() {
+ return create(selectTarget());
+ }
+
+ ExecutionEngine *create(TargetMachine *TM);
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/ExecutionEngine/GenericValue.h b/include/llvm/ExecutionEngine/GenericValue.h
new file mode 100644
index 00000000000..a2fed98c150
--- /dev/null
+++ b/include/llvm/ExecutionEngine/GenericValue.h
@@ -0,0 +1,44 @@
+//===-- GenericValue.h - Represent any type of LLVM value -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// The GenericValue class is used to represent an LLVM value of arbitrary type.
+//
+//===----------------------------------------------------------------------===//
+
+
+#ifndef GENERIC_VALUE_H
+#define GENERIC_VALUE_H
+
+#include "llvm/ADT/APInt.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+typedef void* PointerTy;
+class APInt;
+
+struct GenericValue {
+ union {
+ double DoubleVal;
+ float FloatVal;
+ PointerTy PointerVal;
+ struct { unsigned int first; unsigned int second; } UIntPairVal;
+ unsigned char Untyped[8];
+ };
+ APInt IntVal; // also used for long doubles
+
+ GenericValue() : DoubleVal(0.0), IntVal(1,0) {}
+ explicit GenericValue(void *V) : PointerVal(V), IntVal(1,0) { }
+};
+
+inline GenericValue PTOGV(void *P) { return GenericValue(P); }
+inline void* GVTOP(const GenericValue &GV) { return GV.PointerVal; }
+
+} // End llvm namespace
+#endif
diff --git a/include/llvm/ExecutionEngine/IntelJITEventsWrapper.h b/include/llvm/ExecutionEngine/IntelJITEventsWrapper.h
new file mode 100644
index 00000000000..ca873420299
--- /dev/null
+++ b/include/llvm/ExecutionEngine/IntelJITEventsWrapper.h
@@ -0,0 +1,102 @@
+//===-- IntelJITEventsWrapper.h - Intel JIT Events API Wrapper --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a wrapper for the Intel JIT Events API. It allows for the
+// implementation of the jitprofiling library to be swapped with an alternative
+// implementation (for testing). To include this file, you must have the
+// jitprofiling.h header available; it is available in Intel(R) VTune(TM)
+// Amplifier XE 2011.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef INTEL_JIT_EVENTS_WRAPPER_H
+#define INTEL_JIT_EVENTS_WRAPPER_H
+
+#include <jitprofiling.h>
+
+namespace llvm {
+
+class IntelJITEventsWrapper {
+ // Function pointer types for testing implementation of Intel jitprofiling
+ // library
+ typedef int (*NotifyEventPtr)(iJIT_JVM_EVENT, void*);
+ typedef void (*RegisterCallbackExPtr)(void *, iJIT_ModeChangedEx );
+ typedef iJIT_IsProfilingActiveFlags (*IsProfilingActivePtr)(void);
+ typedef void (*FinalizeThreadPtr)(void);
+ typedef void (*FinalizeProcessPtr)(void);
+ typedef unsigned int (*GetNewMethodIDPtr)(void);
+
+ NotifyEventPtr NotifyEventFunc;
+ RegisterCallbackExPtr RegisterCallbackExFunc;
+ IsProfilingActivePtr IsProfilingActiveFunc;
+ FinalizeThreadPtr FinalizeThreadFunc;
+ FinalizeProcessPtr FinalizeProcessFunc;
+ GetNewMethodIDPtr GetNewMethodIDFunc;
+
+public:
+ bool isAmplifierRunning() {
+ return iJIT_IsProfilingActive() == iJIT_SAMPLING_ON;
+ }
+
+ IntelJITEventsWrapper()
+ : NotifyEventFunc(::iJIT_NotifyEvent),
+ RegisterCallbackExFunc(::iJIT_RegisterCallbackEx),
+ IsProfilingActiveFunc(::iJIT_IsProfilingActive),
+ FinalizeThreadFunc(::FinalizeThread),
+ FinalizeProcessFunc(::FinalizeProcess),
+ GetNewMethodIDFunc(::iJIT_GetNewMethodID) {
+ }
+
+ IntelJITEventsWrapper(NotifyEventPtr NotifyEventImpl,
+ RegisterCallbackExPtr RegisterCallbackExImpl,
+ IsProfilingActivePtr IsProfilingActiveImpl,
+ FinalizeThreadPtr FinalizeThreadImpl,
+ FinalizeProcessPtr FinalizeProcessImpl,
+ GetNewMethodIDPtr GetNewMethodIDImpl)
+ : NotifyEventFunc(NotifyEventImpl),
+ RegisterCallbackExFunc(RegisterCallbackExImpl),
+ IsProfilingActiveFunc(IsProfilingActiveImpl),
+ FinalizeThreadFunc(FinalizeThreadImpl),
+ FinalizeProcessFunc(FinalizeProcessImpl),
+ GetNewMethodIDFunc(GetNewMethodIDImpl) {
+ }
+
+ // Sends an event anncouncing that a function has been emitted
+ // return values are event-specific. See Intel documentation for details.
+ int iJIT_NotifyEvent(iJIT_JVM_EVENT EventType, void *EventSpecificData) {
+ if (!NotifyEventFunc)
+ return -1;
+ return NotifyEventFunc(EventType, EventSpecificData);
+ }
+
+ // Registers a callback function to receive notice of profiling state changes
+ void iJIT_RegisterCallbackEx(void *UserData,
+ iJIT_ModeChangedEx NewModeCallBackFuncEx) {
+ if (RegisterCallbackExFunc)
+ RegisterCallbackExFunc(UserData, NewModeCallBackFuncEx);
+ }
+
+ // Returns the current profiler mode
+ iJIT_IsProfilingActiveFlags iJIT_IsProfilingActive(void) {
+ if (!IsProfilingActiveFunc)
+ return iJIT_NOTHING_RUNNING;
+ return IsProfilingActiveFunc();
+ }
+
+ // Generates a locally unique method ID for use in code registration
+ unsigned int iJIT_GetNewMethodID(void) {
+ if (!GetNewMethodIDFunc)
+ return -1;
+ return GetNewMethodIDFunc();
+ }
+};
+
+} //namespace llvm
+
+#endif //INTEL_JIT_EVENTS_WRAPPER_H
diff --git a/include/llvm/ExecutionEngine/Interpreter.h b/include/llvm/ExecutionEngine/Interpreter.h
new file mode 100644
index 00000000000..72d97ef8e12
--- /dev/null
+++ b/include/llvm/ExecutionEngine/Interpreter.h
@@ -0,0 +1,38 @@
+//===-- Interpreter.h - Abstract Execution Engine Interface -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file forces the interpreter to link in on certain operating systems.
+// (Windows).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef EXECUTION_ENGINE_INTERPRETER_H
+#define EXECUTION_ENGINE_INTERPRETER_H
+
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include <cstdlib>
+
+extern "C" void LLVMLinkInInterpreter();
+
+namespace {
+ struct ForceInterpreterLinking {
+ ForceInterpreterLinking() {
+ // We must reference the interpreter in such a way that compilers will not
+ // delete it all as dead code, even with whole program optimization,
+ // yet is effectively a NO-OP. As the compiler isn't smart enough
+ // to know that getenv() never returns -1, this will do the job.
+ if (std::getenv("bar") != (char*) -1)
+ return;
+
+ LLVMLinkInInterpreter();
+ }
+ } ForceInterpreterLinking;
+}
+
+#endif
diff --git a/include/llvm/ExecutionEngine/JIT.h b/include/llvm/ExecutionEngine/JIT.h
new file mode 100644
index 00000000000..b4cda1d513f
--- /dev/null
+++ b/include/llvm/ExecutionEngine/JIT.h
@@ -0,0 +1,38 @@
+//===-- JIT.h - Abstract Execution Engine Interface -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file forces the JIT to link in on certain operating systems.
+// (Windows).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_EXECUTION_ENGINE_JIT_H
+#define LLVM_EXECUTION_ENGINE_JIT_H
+
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include <cstdlib>
+
+extern "C" void LLVMLinkInJIT();
+
+namespace {
+ struct ForceJITLinking {
+ ForceJITLinking() {
+ // We must reference JIT in such a way that compilers will not
+ // delete it all as dead code, even with whole program optimization,
+ // yet is effectively a NO-OP. As the compiler isn't smart enough
+ // to know that getenv() never returns -1, this will do the job.
+ if (std::getenv("bar") != (char*) -1)
+ return;
+
+ LLVMLinkInJIT();
+ }
+ } ForceJITLinking;
+}
+
+#endif
diff --git a/include/llvm/ExecutionEngine/JITEventListener.h b/include/llvm/ExecutionEngine/JITEventListener.h
new file mode 100644
index 00000000000..eea603fcee2
--- /dev/null
+++ b/include/llvm/ExecutionEngine/JITEventListener.h
@@ -0,0 +1,116 @@
+//===- JITEventListener.h - Exposes events from JIT compilation -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the JITEventListener interface, which lets users get
+// callbacks when significant events happen during the JIT compilation process.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_EXECUTION_ENGINE_JIT_EVENTLISTENER_H
+#define LLVM_EXECUTION_ENGINE_JIT_EVENTLISTENER_H
+
+#include "llvm/Config/config.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/DebugLoc.h"
+
+#include <vector>
+
+namespace llvm {
+class Function;
+class MachineFunction;
+class OProfileWrapper;
+class IntelJITEventsWrapper;
+
+/// JITEvent_EmittedFunctionDetails - Helper struct for containing information
+/// about a generated machine code function.
+struct JITEvent_EmittedFunctionDetails {
+ struct LineStart {
+ /// The address at which the current line changes.
+ uintptr_t Address;
+
+ /// The new location information. These can be translated to DebugLocTuples
+ /// using MF->getDebugLocTuple().
+ DebugLoc Loc;
+ };
+
+ /// The machine function the struct contains information for.
+ const MachineFunction *MF;
+
+ /// The list of line boundary information, sorted by address.
+ std::vector<LineStart> LineStarts;
+};
+
+/// JITEventListener - Abstract interface for use by the JIT to notify clients
+/// about significant events during compilation. For example, to notify
+/// profilers and debuggers that need to know where functions have been emitted.
+///
+/// The default implementation of each method does nothing.
+class JITEventListener {
+public:
+ typedef JITEvent_EmittedFunctionDetails EmittedFunctionDetails;
+
+public:
+ JITEventListener() {}
+ virtual ~JITEventListener();
+
+ /// NotifyFunctionEmitted - Called after a function has been successfully
+ /// emitted to memory. The function still has its MachineFunction attached,
+ /// if you should happen to need that.
+ virtual void NotifyFunctionEmitted(const Function &,
+ void *, size_t,
+ const EmittedFunctionDetails &) {}
+
+ /// NotifyFreeingMachineCode - Called from freeMachineCodeForFunction(), after
+ /// the global mapping is removed, but before the machine code is returned to
+ /// the allocator.
+ ///
+ /// OldPtr is the address of the machine code and will be the same as the Code
+ /// parameter to a previous NotifyFunctionEmitted call. The Function passed
+ /// to NotifyFunctionEmitted may have been destroyed by the time of the
+ /// matching NotifyFreeingMachineCode call.
+ virtual void NotifyFreeingMachineCode(void *) {}
+
+#if LLVM_USE_INTEL_JITEVENTS
+ // Construct an IntelJITEventListener
+ static JITEventListener *createIntelJITEventListener();
+
+ // Construct an IntelJITEventListener with a test Intel JIT API implementation
+ static JITEventListener *createIntelJITEventListener(
+ IntelJITEventsWrapper* AlternativeImpl);
+#else
+ static JITEventListener *createIntelJITEventListener() { return 0; }
+
+ static JITEventListener *createIntelJITEventListener(
+ IntelJITEventsWrapper* AlternativeImpl) {
+ return 0;
+ }
+#endif // USE_INTEL_JITEVENTS
+
+#if LLVM_USE_OPROFILE
+ // Construct an OProfileJITEventListener
+ static JITEventListener *createOProfileJITEventListener();
+
+ // Construct an OProfileJITEventListener with a test opagent implementation
+ static JITEventListener *createOProfileJITEventListener(
+ OProfileWrapper* AlternativeImpl);
+#else
+
+ static JITEventListener *createOProfileJITEventListener() { return 0; }
+
+ static JITEventListener *createOProfileJITEventListener(
+ OProfileWrapper* AlternativeImpl) {
+ return 0;
+ }
+#endif // USE_OPROFILE
+
+};
+
+} // end namespace llvm.
+
+#endif // defined LLVM_EXECUTION_ENGINE_JIT_EVENTLISTENER_H
diff --git a/include/llvm/ExecutionEngine/JITMemoryManager.h b/include/llvm/ExecutionEngine/JITMemoryManager.h
new file mode 100644
index 00000000000..4c75b6ab970
--- /dev/null
+++ b/include/llvm/ExecutionEngine/JITMemoryManager.h
@@ -0,0 +1,206 @@
+//===-- JITMemoryManager.h - Interface JIT uses to Allocate Mem -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_EXECUTION_ENGINE_JIT_MEMMANAGER_H
+#define LLVM_EXECUTION_ENGINE_JIT_MEMMANAGER_H
+
+#include "llvm/Support/DataTypes.h"
+#include <string>
+
+namespace llvm {
+
+ class Function;
+ class GlobalValue;
+
+/// JITMemoryManager - This interface is used by the JIT to allocate and manage
+/// memory for the code generated by the JIT. This can be reimplemented by
+/// clients that have a strong desire to control how the layout of JIT'd memory
+/// works.
+class JITMemoryManager {
+protected:
+ bool HasGOT;
+
+public:
+ JITMemoryManager() : HasGOT(false) {}
+ virtual ~JITMemoryManager();
+
+ /// CreateDefaultMemManager - This is used to create the default
+ /// JIT Memory Manager if the client does not provide one to the JIT.
+ static JITMemoryManager *CreateDefaultMemManager();
+
+ /// setMemoryWritable - When code generation is in progress,
+ /// the code pages may need permissions changed.
+ virtual void setMemoryWritable() = 0;
+
+ /// setMemoryExecutable - When code generation is done and we're ready to
+ /// start execution, the code pages may need permissions changed.
+ virtual void setMemoryExecutable() = 0;
+
+ /// setPoisonMemory - Setting this flag to true makes the memory manager
+ /// garbage values over freed memory. This is useful for testing and
+ /// debugging, and may be turned on by default in debug mode.
+ virtual void setPoisonMemory(bool poison) = 0;
+
+ /// getPointerToNamedFunction - This method returns the address of the
+ /// specified function. As such it is only useful for resolving library
+ /// symbols, not code generated symbols.
+ ///
+ /// If AbortOnFailure is false and no function with the given name is
+ /// found, this function silently returns a null pointer. Otherwise,
+ /// it prints a message to stderr and aborts.
+ ///
+ virtual void *getPointerToNamedFunction(const std::string &Name,
+ bool AbortOnFailure = true) = 0;
+
+ //===--------------------------------------------------------------------===//
+ // Global Offset Table Management
+ //===--------------------------------------------------------------------===//
+
+ /// AllocateGOT - If the current table requires a Global Offset Table, this
+ /// method is invoked to allocate it. This method is required to set HasGOT
+ /// to true.
+ virtual void AllocateGOT() = 0;
+
+ /// isManagingGOT - Return true if the AllocateGOT method is called.
+ bool isManagingGOT() const {
+ return HasGOT;
+ }
+
+ /// getGOTBase - If this is managing a Global Offset Table, this method should
+ /// return a pointer to its base.
+ virtual uint8_t *getGOTBase() const = 0;
+
+ //===--------------------------------------------------------------------===//
+ // Main Allocation Functions
+ //===--------------------------------------------------------------------===//
+
+ /// startFunctionBody - When we start JITing a function, the JIT calls this
+ /// method to allocate a block of free RWX memory, which returns a pointer to
+ /// it. If the JIT wants to request a block of memory of at least a certain
+ /// size, it passes that value as ActualSize, and this method returns a block
+ /// with at least that much space. If the JIT doesn't know ahead of time how
+ /// much space it will need to emit the function, it passes 0 for the
+ /// ActualSize. In either case, this method is required to pass back the size
+ /// of the allocated block through ActualSize. The JIT will be careful to
+ /// not write more than the returned ActualSize bytes of memory.
+ virtual uint8_t *startFunctionBody(const Function *F,
+ uintptr_t &ActualSize) = 0;
+
+ /// allocateStub - This method is called by the JIT to allocate space for a
+ /// function stub (used to handle limited branch displacements) while it is
+ /// JIT compiling a function. For example, if foo calls bar, and if bar
+ /// either needs to be lazily compiled or is a native function that exists too
+ /// far away from the call site to work, this method will be used to make a
+ /// thunk for it. The stub should be "close" to the current function body,
+ /// but should not be included in the 'actualsize' returned by
+ /// startFunctionBody.
+ virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
+ unsigned Alignment) = 0;
+
+ /// endFunctionBody - This method is called when the JIT is done codegen'ing
+ /// the specified function. At this point we know the size of the JIT
+ /// compiled function. This passes in FunctionStart (which was returned by
+ /// the startFunctionBody method) and FunctionEnd which is a pointer to the
+ /// actual end of the function. This method should mark the space allocated
+ /// and remember where it is in case the client wants to deallocate it.
+ virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
+ uint8_t *FunctionEnd) = 0;
+
+ /// allocateCodeSection - Allocate a memory block of (at least) the given
+ /// size suitable for executable code. The SectionID is a unique identifier
+ /// assigned by the JIT and passed through to the memory manager for
+ /// the instance class to use if it needs to communicate to the JIT about
+ /// a given section after the fact.
+ virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
+ unsigned SectionID) = 0;
+
+ /// allocateDataSection - Allocate a memory block of (at least) the given
+ /// size suitable for data. The SectionID is a unique identifier
+ /// assigned by the JIT and passed through to the memory manager for
+ /// the instance class to use if it needs to communicate to the JIT about
+ /// a given section after the fact.
+ virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
+ unsigned SectionID) = 0;
+
+ /// allocateSpace - Allocate a memory block of the given size. This method
+ /// cannot be called between calls to startFunctionBody and endFunctionBody.
+ virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) = 0;
+
+ /// allocateGlobal - Allocate memory for a global.
+ virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) = 0;
+
+ /// deallocateFunctionBody - Free the specified function body. The argument
+ /// must be the return value from a call to startFunctionBody() that hasn't
+ /// been deallocated yet. This is never called when the JIT is currently
+ /// emitting a function.
+ virtual void deallocateFunctionBody(void *Body) = 0;
+
+ /// startExceptionTable - When we finished JITing the function, if exception
+ /// handling is set, we emit the exception table.
+ virtual uint8_t* startExceptionTable(const Function* F,
+ uintptr_t &ActualSize) = 0;
+
+ /// endExceptionTable - This method is called when the JIT is done emitting
+ /// the exception table.
+ virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
+ uint8_t *TableEnd, uint8_t* FrameRegister) = 0;
+
+ /// deallocateExceptionTable - Free the specified exception table's memory.
+ /// The argument must be the return value from a call to startExceptionTable()
+ /// that hasn't been deallocated yet. This is never called when the JIT is
+ /// currently emitting an exception table.
+ virtual void deallocateExceptionTable(void *ET) = 0;
+
+ /// CheckInvariants - For testing only. Return true if all internal
+ /// invariants are preserved, or return false and set ErrorStr to a helpful
+ /// error message.
+ virtual bool CheckInvariants(std::string &) {
+ return true;
+ }
+
+ /// GetDefaultCodeSlabSize - For testing only. Returns DefaultCodeSlabSize
+ /// from DefaultJITMemoryManager.
+ virtual size_t GetDefaultCodeSlabSize() {
+ return 0;
+ }
+
+ /// GetDefaultDataSlabSize - For testing only. Returns DefaultCodeSlabSize
+ /// from DefaultJITMemoryManager.
+ virtual size_t GetDefaultDataSlabSize() {
+ return 0;
+ }
+
+ /// GetDefaultStubSlabSize - For testing only. Returns DefaultCodeSlabSize
+ /// from DefaultJITMemoryManager.
+ virtual size_t GetDefaultStubSlabSize() {
+ return 0;
+ }
+
+ /// GetNumCodeSlabs - For testing only. Returns the number of MemoryBlocks
+ /// allocated for code.
+ virtual unsigned GetNumCodeSlabs() {
+ return 0;
+ }
+
+ /// GetNumDataSlabs - For testing only. Returns the number of MemoryBlocks
+ /// allocated for data.
+ virtual unsigned GetNumDataSlabs() {
+ return 0;
+ }
+
+ /// GetNumStubSlabs - For testing only. Returns the number of MemoryBlocks
+ /// allocated for function stubs.
+ virtual unsigned GetNumStubSlabs() {
+ return 0;
+ }
+};
+
+} // end namespace llvm.
+
+#endif
diff --git a/include/llvm/ExecutionEngine/MCJIT.h b/include/llvm/ExecutionEngine/MCJIT.h
new file mode 100644
index 00000000000..ac16bdc7df1
--- /dev/null
+++ b/include/llvm/ExecutionEngine/MCJIT.h
@@ -0,0 +1,38 @@
+//===-- MCJIT.h - MC-Based Just-In-Time Execution Engine --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file forces the MCJIT to link in on certain operating systems.
+// (Windows).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_EXECUTION_ENGINE_MCJIT_H
+#define LLVM_EXECUTION_ENGINE_MCJIT_H
+
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include <cstdlib>
+
+extern "C" void LLVMLinkInMCJIT();
+
+namespace {
+ struct ForceMCJITLinking {
+ ForceMCJITLinking() {
+ // We must reference MCJIT in such a way that compilers will not
+ // delete it all as dead code, even with whole program optimization,
+ // yet is effectively a NO-OP. As the compiler isn't smart enough
+ // to know that getenv() never returns -1, this will do the job.
+ if (std::getenv("bar") != (char*) -1)
+ return;
+
+ LLVMLinkInMCJIT();
+ }
+ } ForceMCJITLinking;
+}
+
+#endif
diff --git a/include/llvm/ExecutionEngine/OProfileWrapper.h b/include/llvm/ExecutionEngine/OProfileWrapper.h
new file mode 100644
index 00000000000..ab7f25e9d03
--- /dev/null
+++ b/include/llvm/ExecutionEngine/OProfileWrapper.h
@@ -0,0 +1,124 @@
+//===-- OProfileWrapper.h - OProfile JIT API Wrapper ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+// This file defines a OProfileWrapper object that detects if the oprofile
+// daemon is running, and provides wrappers for opagent functions used to
+// communicate with the oprofile JIT interface. The dynamic library libopagent
+// does not need to be linked directly as this object lazily loads the library
+// when the first op_ function is called.
+//
+// See http://oprofile.sourceforge.net/doc/devel/jit-interface.html for the
+// definition of the interface.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef OPROFILE_WRAPPER_H
+#define OPROFILE_WRAPPER_H
+
+#include "llvm/Support/DataTypes.h"
+#include <opagent.h>
+
+namespace llvm {
+
+
+class OProfileWrapper {
+ typedef op_agent_t (*op_open_agent_ptr_t)();
+ typedef int (*op_close_agent_ptr_t)(op_agent_t);
+ typedef int (*op_write_native_code_ptr_t)(op_agent_t,
+ const char*,
+ uint64_t,
+ void const*,
+ const unsigned int);
+ typedef int (*op_write_debug_line_info_ptr_t)(op_agent_t,
+ void const*,
+ size_t,
+ struct debug_line_info const*);
+ typedef int (*op_unload_native_code_ptr_t)(op_agent_t, uint64_t);
+
+ // Also used for op_minor_version function which has the same signature
+ typedef int (*op_major_version_ptr_t)(void);
+
+ // This is not a part of the opagent API, but is useful nonetheless
+ typedef bool (*IsOProfileRunningPtrT)(void);
+
+
+ op_agent_t Agent;
+ op_open_agent_ptr_t OpenAgentFunc;
+ op_close_agent_ptr_t CloseAgentFunc;
+ op_write_native_code_ptr_t WriteNativeCodeFunc;
+ op_write_debug_line_info_ptr_t WriteDebugLineInfoFunc;
+ op_unload_native_code_ptr_t UnloadNativeCodeFunc;
+ op_major_version_ptr_t MajorVersionFunc;
+ op_major_version_ptr_t MinorVersionFunc;
+ IsOProfileRunningPtrT IsOProfileRunningFunc;
+
+ bool Initialized;
+
+public:
+ OProfileWrapper();
+
+ // For testing with a mock opagent implementation, skips the dynamic load and
+ // the function resolution.
+ OProfileWrapper(op_open_agent_ptr_t OpenAgentImpl,
+ op_close_agent_ptr_t CloseAgentImpl,
+ op_write_native_code_ptr_t WriteNativeCodeImpl,
+ op_write_debug_line_info_ptr_t WriteDebugLineInfoImpl,
+ op_unload_native_code_ptr_t UnloadNativeCodeImpl,
+ op_major_version_ptr_t MajorVersionImpl,
+ op_major_version_ptr_t MinorVersionImpl,
+ IsOProfileRunningPtrT MockIsOProfileRunningImpl = 0)
+ : OpenAgentFunc(OpenAgentImpl),
+ CloseAgentFunc(CloseAgentImpl),
+ WriteNativeCodeFunc(WriteNativeCodeImpl),
+ WriteDebugLineInfoFunc(WriteDebugLineInfoImpl),
+ UnloadNativeCodeFunc(UnloadNativeCodeImpl),
+ MajorVersionFunc(MajorVersionImpl),
+ MinorVersionFunc(MinorVersionImpl),
+ IsOProfileRunningFunc(MockIsOProfileRunningImpl),
+ Initialized(true)
+ {
+ }
+
+ // Calls op_open_agent in the oprofile JIT library and saves the returned
+ // op_agent_t handle internally so it can be used when calling all the other
+ // op_* functions. Callers of this class do not need to keep track of
+ // op_agent_t objects.
+ bool op_open_agent();
+
+ int op_close_agent();
+ int op_write_native_code(const char* name,
+ uint64_t addr,
+ void const* code,
+ const unsigned int size);
+ int op_write_debug_line_info(void const* code,
+ size_t num_entries,
+ struct debug_line_info const* info);
+ int op_unload_native_code(uint64_t addr);
+ int op_major_version(void);
+ int op_minor_version(void);
+
+ // Returns true if the oprofiled process is running, the opagent library is
+ // loaded and a connection to the agent has been established, and false
+ // otherwise.
+ bool isAgentAvailable();
+
+private:
+ // Loads the libopagent library and initializes this wrapper if the oprofile
+ // daemon is running
+ bool initialize();
+
+ // Searches /proc for the oprofile daemon and returns true if the process if
+ // found, or false otherwise.
+ bool checkForOProfileProcEntry();
+
+ bool isOProfileRunning();
+};
+
+} // namespace llvm
+
+#endif //OPROFILE_WRAPPER_H
diff --git a/include/llvm/ExecutionEngine/RuntimeDyld.h b/include/llvm/ExecutionEngine/RuntimeDyld.h
new file mode 100644
index 00000000000..a02cbe2d908
--- /dev/null
+++ b/include/llvm/ExecutionEngine/RuntimeDyld.h
@@ -0,0 +1,94 @@
+//===-- RuntimeDyld.h - Run-time dynamic linker for MC-JIT ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Interface for the runtime dynamic linker facilities of the MC-JIT.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_RUNTIME_DYLD_H
+#define LLVM_RUNTIME_DYLD_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Memory.h"
+
+namespace llvm {
+
+class RuntimeDyldImpl;
+class MemoryBuffer;
+
+// RuntimeDyld clients often want to handle the memory management of
+// what gets placed where. For JIT clients, this is an abstraction layer
+// over the JITMemoryManager, which references objects by their source
+// representations in LLVM IR.
+// FIXME: As the RuntimeDyld fills out, additional routines will be needed
+// for the varying types of objects to be allocated.
+class RTDyldMemoryManager {
+ RTDyldMemoryManager(const RTDyldMemoryManager&) LLVM_DELETED_FUNCTION;
+ void operator=(const RTDyldMemoryManager&) LLVM_DELETED_FUNCTION;
+public:
+ RTDyldMemoryManager() {}
+ virtual ~RTDyldMemoryManager();
+
+ /// allocateCodeSection - Allocate a memory block of (at least) the given
+ /// size suitable for executable code.
+ virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
+ unsigned SectionID) = 0;
+
+ /// allocateDataSection - Allocate a memory block of (at least) the given
+ /// size suitable for data.
+ virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
+ unsigned SectionID) = 0;
+
+ virtual void *getPointerToNamedFunction(const std::string &Name,
+ bool AbortOnFailure = true) = 0;
+};
+
+class RuntimeDyld {
+ RuntimeDyld(const RuntimeDyld &) LLVM_DELETED_FUNCTION;
+ void operator=(const RuntimeDyld &) LLVM_DELETED_FUNCTION;
+
+ // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
+ // interface.
+ RuntimeDyldImpl *Dyld;
+ RTDyldMemoryManager *MM;
+protected:
+ // Change the address associated with a section when resolving relocations.
+ // Any relocations already associated with the symbol will be re-resolved.
+ void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
+public:
+ RuntimeDyld(RTDyldMemoryManager*);
+ ~RuntimeDyld();
+
+ /// Load an in-memory object file into the dynamic linker.
+ bool loadObject(MemoryBuffer *InputBuffer);
+
+ /// Get the address of our local copy of the symbol. This may or may not
+ /// be the address used for relocation (clients can copy the data around
+ /// and resolve relocatons based on where they put it).
+ void *getSymbolAddress(StringRef Name);
+
+ /// Get the address of the target copy of the symbol. This is the address
+ /// used for relocation.
+ uint64_t getSymbolLoadAddress(StringRef Name);
+
+ /// Resolve the relocations for all symbols we currently know about.
+ void resolveRelocations();
+
+ /// mapSectionAddress - map a section to its target address space value.
+ /// Map the address of a JIT section as returned from the memory manager
+ /// to the address in the target process as the running code will see it.
+ /// This is the address which will be used for relocation resolution.
+ void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
+
+ StringRef getErrorString();
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Function.h b/include/llvm/Function.h
new file mode 100644
index 00000000000..fbd2594a452
--- /dev/null
+++ b/include/llvm/Function.h
@@ -0,0 +1,458 @@
+//===-- llvm/Function.h - Class to represent a single function --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the Function class, which represents a
+// single function/procedure in LLVM.
+//
+// A function basically consists of a list of basic blocks, a list of arguments,
+// and a symbol table.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FUNCTION_H
+#define LLVM_FUNCTION_H
+
+#include "llvm/GlobalValue.h"
+#include "llvm/CallingConv.h"
+#include "llvm/BasicBlock.h"
+#include "llvm/Argument.h"
+#include "llvm/Attributes.h"
+#include "llvm/Support/Compiler.h"
+
+namespace llvm {
+
+class FunctionType;
+class LLVMContext;
+
+// Traits for intrusive list of basic blocks...
+template<> struct ilist_traits<BasicBlock>
+ : public SymbolTableListTraits<BasicBlock, Function> {
+
+ // createSentinel is used to get hold of the node that marks the end of the
+ // list... (same trick used here as in ilist_traits<Instruction>)
+ BasicBlock *createSentinel() const {
+ return static_cast<BasicBlock*>(&Sentinel);
+ }
+ static void destroySentinel(BasicBlock*) {}
+
+ BasicBlock *provideInitialHead() const { return createSentinel(); }
+ BasicBlock *ensureHead(BasicBlock*) const { return createSentinel(); }
+ static void noteHead(BasicBlock*, BasicBlock*) {}
+
+ static ValueSymbolTable *getSymTab(Function *ItemParent);
+private:
+ mutable ilist_half_node<BasicBlock> Sentinel;
+};
+
+template<> struct ilist_traits<Argument>
+ : public SymbolTableListTraits<Argument, Function> {
+
+ Argument *createSentinel() const {
+ return static_cast<Argument*>(&Sentinel);
+ }
+ static void destroySentinel(Argument*) {}
+
+ Argument *provideInitialHead() const { return createSentinel(); }
+ Argument *ensureHead(Argument*) const { return createSentinel(); }
+ static void noteHead(Argument*, Argument*) {}
+
+ static ValueSymbolTable *getSymTab(Function *ItemParent);
+private:
+ mutable ilist_half_node<Argument> Sentinel;
+};
+
+class Function : public GlobalValue,
+ public ilist_node<Function> {
+public:
+ typedef iplist<Argument> ArgumentListType;
+ typedef iplist<BasicBlock> BasicBlockListType;
+
+ // BasicBlock iterators...
+ typedef BasicBlockListType::iterator iterator;
+ typedef BasicBlockListType::const_iterator const_iterator;
+
+ typedef ArgumentListType::iterator arg_iterator;
+ typedef ArgumentListType::const_iterator const_arg_iterator;
+
+private:
+ // Important things that make up a function!
+ BasicBlockListType BasicBlocks; ///< The basic blocks
+ mutable ArgumentListType ArgumentList; ///< The formal arguments
+ ValueSymbolTable *SymTab; ///< Symbol table of args/instructions
+ AttrListPtr AttributeList; ///< Parameter attributes
+
+ // HasLazyArguments is stored in Value::SubclassData.
+ /*bool HasLazyArguments;*/
+
+ // The Calling Convention is stored in Value::SubclassData.
+ /*CallingConv::ID CallingConvention;*/
+
+ friend class SymbolTableListTraits<Function, Module>;
+
+ void setParent(Module *parent);
+
+ /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
+ /// built on demand, so that the list isn't allocated until the first client
+ /// needs it. The hasLazyArguments predicate returns true if the arg list
+ /// hasn't been set up yet.
+ bool hasLazyArguments() const {
+ return getSubclassDataFromValue() & 1;
+ }
+ void CheckLazyArguments() const {
+ if (hasLazyArguments())
+ BuildLazyArguments();
+ }
+ void BuildLazyArguments() const;
+
+ Function(const Function&) LLVM_DELETED_FUNCTION;
+ void operator=(const Function&) LLVM_DELETED_FUNCTION;
+
+ /// Function ctor - If the (optional) Module argument is specified, the
+ /// function is automatically inserted into the end of the function list for
+ /// the module.
+ ///
+ Function(FunctionType *Ty, LinkageTypes Linkage,
+ const Twine &N = "", Module *M = 0);
+
+public:
+ static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
+ const Twine &N = "", Module *M = 0) {
+ return new(0) Function(Ty, Linkage, N, M);
+ }
+
+ ~Function();
+
+ Type *getReturnType() const; // Return the type of the ret val
+ FunctionType *getFunctionType() const; // Return the FunctionType for me
+
+ /// getContext - Return a pointer to the LLVMContext associated with this
+ /// function, or NULL if this function is not bound to a context yet.
+ LLVMContext &getContext() const;
+
+ /// isVarArg - Return true if this function takes a variable number of
+ /// arguments.
+ bool isVarArg() const;
+
+ /// getIntrinsicID - This method returns the ID number of the specified
+ /// function, or Intrinsic::not_intrinsic if the function is not an
+ /// instrinsic, or if the pointer is null. This value is always defined to be
+ /// zero to allow easy checking for whether a function is intrinsic or not.
+ /// The particular intrinsic functions which correspond to this value are
+ /// defined in llvm/Intrinsics.h.
+ ///
+ unsigned getIntrinsicID() const LLVM_READONLY;
+ bool isIntrinsic() const { return getIntrinsicID() != 0; }
+
+ /// getCallingConv()/setCallingConv(CC) - These method get and set the
+ /// calling convention of this function. The enum values for the known
+ /// calling conventions are defined in CallingConv.h.
+ CallingConv::ID getCallingConv() const {
+ return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 1);
+ }
+ void setCallingConv(CallingConv::ID CC) {
+ setValueSubclassData((getSubclassDataFromValue() & 1) |
+ (static_cast<unsigned>(CC) << 1));
+ }
+
+ /// getAttributes - Return the attribute list for this Function.
+ ///
+ const AttrListPtr &getAttributes() const { return AttributeList; }
+
+ /// setAttributes - Set the attribute list for this Function.
+ ///
+ void setAttributes(const AttrListPtr &attrs) { AttributeList = attrs; }
+
+ /// hasFnAttr - Return true if this function has the given attribute.
+ bool hasFnAttr(Attributes N) const {
+ // Function Attributes are stored at ~0 index
+ return AttributeList.paramHasAttr(~0U, N);
+ }
+
+ /// addFnAttr - Add function attributes to this function.
+ ///
+ void addFnAttr(Attributes N) {
+ // Function Attributes are stored at ~0 index
+ addAttribute(~0U, N);
+ }
+
+ /// removeFnAttr - Remove function attributes from this function.
+ ///
+ void removeFnAttr(Attributes N) {
+ // Function Attributes are stored at ~0 index
+ removeAttribute(~0U, N);
+ }
+
+ /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
+ /// to use during code generation.
+ bool hasGC() const;
+ const char *getGC() const;
+ void setGC(const char *Str);
+ void clearGC();
+
+ /// @brief Determine whether the function has the given attribute.
+ bool paramHasAttr(unsigned i, Attributes attr) const {
+ return AttributeList.paramHasAttr(i, attr);
+ }
+
+ /// addAttribute - adds the attribute to the list of attributes.
+ void addAttribute(unsigned i, Attributes attr);
+
+ /// removeAttribute - removes the attribute from the list of attributes.
+ void removeAttribute(unsigned i, Attributes attr);
+
+ /// @brief Extract the alignment for a call or parameter (0=unknown).
+ unsigned getParamAlignment(unsigned i) const {
+ return AttributeList.getParamAlignment(i);
+ }
+
+ /// @brief Determine if the function does not access memory.
+ bool doesNotAccessMemory() const {
+ return hasFnAttr(Attribute::ReadNone);
+ }
+ void setDoesNotAccessMemory(bool DoesNotAccessMemory = true) {
+ if (DoesNotAccessMemory) addFnAttr(Attribute::ReadNone);
+ else removeFnAttr(Attribute::ReadNone);
+ }
+
+ /// @brief Determine if the function does not access or only reads memory.
+ bool onlyReadsMemory() const {
+ return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
+ }
+ void setOnlyReadsMemory(bool OnlyReadsMemory = true) {
+ if (OnlyReadsMemory) addFnAttr(Attribute::ReadOnly);
+ else removeFnAttr(Attribute::ReadOnly | Attribute::ReadNone);
+ }
+
+ /// @brief Determine if the function cannot return.
+ bool doesNotReturn() const {
+ return hasFnAttr(Attribute::NoReturn);
+ }
+ void setDoesNotReturn(bool DoesNotReturn = true) {
+ if (DoesNotReturn) addFnAttr(Attribute::NoReturn);
+ else removeFnAttr(Attribute::NoReturn);
+ }
+
+ /// @brief Determine if the function cannot unwind.
+ bool doesNotThrow() const {
+ return hasFnAttr(Attribute::NoUnwind);
+ }
+ void setDoesNotThrow(bool DoesNotThrow = true) {
+ if (DoesNotThrow) addFnAttr(Attribute::NoUnwind);
+ else removeFnAttr(Attribute::NoUnwind);
+ }
+
+ /// @brief True if the ABI mandates (or the user requested) that this
+ /// function be in a unwind table.
+ bool hasUWTable() const {
+ return hasFnAttr(Attribute::UWTable);
+ }
+ void setHasUWTable(bool HasUWTable = true) {
+ if (HasUWTable)
+ addFnAttr(Attribute::UWTable);
+ else
+ removeFnAttr(Attribute::UWTable);
+ }
+
+ /// @brief True if this function needs an unwind table.
+ bool needsUnwindTableEntry() const {
+ return hasUWTable() || !doesNotThrow();
+ }
+
+ /// @brief Determine if the function returns a structure through first
+ /// pointer argument.
+ bool hasStructRetAttr() const {
+ return paramHasAttr(1, Attribute::StructRet);
+ }
+
+ /// @brief Determine if the parameter does not alias other parameters.
+ /// @param n The parameter to check. 1 is the first parameter, 0 is the return
+ bool doesNotAlias(unsigned n) const {
+ return paramHasAttr(n, Attribute::NoAlias);
+ }
+ void setDoesNotAlias(unsigned n, bool DoesNotAlias = true) {
+ if (DoesNotAlias) addAttribute(n, Attribute::NoAlias);
+ else removeAttribute(n, Attribute::NoAlias);
+ }
+
+ /// @brief Determine if the parameter can be captured.
+ /// @param n The parameter to check. 1 is the first parameter, 0 is the return
+ bool doesNotCapture(unsigned n) const {
+ return paramHasAttr(n, Attribute::NoCapture);
+ }
+ void setDoesNotCapture(unsigned n, bool DoesNotCapture = true) {
+ if (DoesNotCapture) addAttribute(n, Attribute::NoCapture);
+ else removeAttribute(n, Attribute::NoCapture);
+ }
+
+ /// copyAttributesFrom - copy all additional attributes (those not needed to
+ /// create a Function) from the Function Src to this one.
+ void copyAttributesFrom(const GlobalValue *Src);
+
+ /// deleteBody - This method deletes the body of the function, and converts
+ /// the linkage to external.
+ ///
+ void deleteBody() {
+ dropAllReferences();
+ setLinkage(ExternalLinkage);
+ }
+
+ /// removeFromParent - This method unlinks 'this' from the containing module,
+ /// but does not delete it.
+ ///
+ virtual void removeFromParent();
+
+ /// eraseFromParent - This method unlinks 'this' from the containing module
+ /// and deletes it.
+ ///
+ virtual void eraseFromParent();
+
+
+ /// Get the underlying elements of the Function... the basic block list is
+ /// empty for external functions.
+ ///
+ const ArgumentListType &getArgumentList() const {
+ CheckLazyArguments();
+ return ArgumentList;
+ }
+ ArgumentListType &getArgumentList() {
+ CheckLazyArguments();
+ return ArgumentList;
+ }
+ static iplist<Argument> Function::*getSublistAccess(Argument*) {
+ return &Function::ArgumentList;
+ }
+
+ const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
+ BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
+ static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
+ return &Function::BasicBlocks;
+ }
+
+ const BasicBlock &getEntryBlock() const { return front(); }
+ BasicBlock &getEntryBlock() { return front(); }
+
+ //===--------------------------------------------------------------------===//
+ // Symbol Table Accessing functions...
+
+ /// getSymbolTable() - Return the symbol table...
+ ///
+ inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
+ inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
+
+
+ //===--------------------------------------------------------------------===//
+ // BasicBlock iterator forwarding functions
+ //
+ iterator begin() { return BasicBlocks.begin(); }
+ const_iterator begin() const { return BasicBlocks.begin(); }
+ iterator end () { return BasicBlocks.end(); }
+ const_iterator end () const { return BasicBlocks.end(); }
+
+ size_t size() const { return BasicBlocks.size(); }
+ bool empty() const { return BasicBlocks.empty(); }
+ const BasicBlock &front() const { return BasicBlocks.front(); }
+ BasicBlock &front() { return BasicBlocks.front(); }
+ const BasicBlock &back() const { return BasicBlocks.back(); }
+ BasicBlock &back() { return BasicBlocks.back(); }
+
+ //===--------------------------------------------------------------------===//
+ // Argument iterator forwarding functions
+ //
+ arg_iterator arg_begin() {
+ CheckLazyArguments();
+ return ArgumentList.begin();
+ }
+ const_arg_iterator arg_begin() const {
+ CheckLazyArguments();
+ return ArgumentList.begin();
+ }
+ arg_iterator arg_end() {
+ CheckLazyArguments();
+ return ArgumentList.end();
+ }
+ const_arg_iterator arg_end() const {
+ CheckLazyArguments();
+ return ArgumentList.end();
+ }
+
+ size_t arg_size() const;
+ bool arg_empty() const;
+
+ /// viewCFG - This function is meant for use from the debugger. You can just
+ /// say 'call F->viewCFG()' and a ghostview window should pop up from the
+ /// program, displaying the CFG of the current function with the code for each
+ /// basic block inside. This depends on there being a 'dot' and 'gv' program
+ /// in your path.
+ ///
+ void viewCFG() const;
+
+ /// viewCFGOnly - This function is meant for use from the debugger. It works
+ /// just like viewCFG, but it does not include the contents of basic blocks
+ /// into the nodes, just the label. If you are only interested in the CFG
+ /// this can make the graph smaller.
+ ///
+ void viewCFGOnly() const;
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const Function *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == Value::FunctionVal;
+ }
+
+ /// dropAllReferences() - This method causes all the subinstructions to "let
+ /// go" of all references that they are maintaining. This allows one to
+ /// 'delete' a whole module at a time, even though there may be circular
+ /// references... first all references are dropped, and all use counts go to
+ /// zero. Then everything is deleted for real. Note that no operations are
+ /// valid on an object that has "dropped all references", except operator
+ /// delete.
+ ///
+ /// Since no other object in the module can have references into the body of a
+ /// function, dropping all references deletes the entire body of the function,
+ /// including any contained basic blocks.
+ ///
+ void dropAllReferences();
+
+ /// hasAddressTaken - returns true if there are any uses of this function
+ /// other than direct calls or invokes to it, or blockaddress expressions.
+ /// Optionally passes back an offending user for diagnostic purposes.
+ ///
+ bool hasAddressTaken(const User** = 0) const;
+
+ /// isDefTriviallyDead - Return true if it is trivially safe to remove
+ /// this function definition from the module (because it isn't externally
+ /// visible, does not have its address taken, and has no callers). To make
+ /// this more accurate, call removeDeadConstantUsers first.
+ bool isDefTriviallyDead() const;
+
+ /// callsFunctionThatReturnsTwice - Return true if the function has a call to
+ /// setjmp or other function that gcc recognizes as "returning twice".
+ bool callsFunctionThatReturnsTwice() const;
+
+private:
+ // Shadow Value::setValueSubclassData with a private forwarding method so that
+ // subclasses cannot accidentally use it.
+ void setValueSubclassData(unsigned short D) {
+ Value::setValueSubclassData(D);
+ }
+};
+
+inline ValueSymbolTable *
+ilist_traits<BasicBlock>::getSymTab(Function *F) {
+ return F ? &F->getValueSymbolTable() : 0;
+}
+
+inline ValueSymbolTable *
+ilist_traits<Argument>::getSymTab(Function *F) {
+ return F ? &F->getValueSymbolTable() : 0;
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/GVMaterializer.h b/include/llvm/GVMaterializer.h
new file mode 100644
index 00000000000..c1435523886
--- /dev/null
+++ b/include/llvm/GVMaterializer.h
@@ -0,0 +1,66 @@
+//===-- llvm/GVMaterializer.h - Interface for GV materializers --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file provides an abstract interface for loading a module from some
+// place. This interface allows incremental or random access loading of
+// functions from the file. This is useful for applications like JIT compilers
+// or interprocedural optimizers that do not need the entire program in memory
+// at the same time.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef GVMATERIALIZER_H
+#define GVMATERIALIZER_H
+
+#include <string>
+
+namespace llvm {
+
+class Function;
+class GlobalValue;
+class Module;
+
+class GVMaterializer {
+protected:
+ GVMaterializer() {}
+
+public:
+ virtual ~GVMaterializer();
+
+ /// isMaterializable - True if GV can be materialized from whatever backing
+ /// store this GVMaterializer uses and has not been materialized yet.
+ virtual bool isMaterializable(const GlobalValue *GV) const = 0;
+
+ /// isDematerializable - True if GV has been materialized and can be
+ /// dematerialized back to whatever backing store this GVMaterializer uses.
+ virtual bool isDematerializable(const GlobalValue *GV) const = 0;
+
+ /// Materialize - make sure the given GlobalValue is fully read. If the
+ /// module is corrupt, this returns true and fills in the optional string with
+ /// information about the problem. If successful, this returns false.
+ ///
+ virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0) = 0;
+
+ /// Dematerialize - If the given GlobalValue is read in, and if the
+ /// GVMaterializer supports it, release the memory for the GV, and set it up
+ /// to be materialized lazily. If the Materializer doesn't support this
+ /// capability, this method is a noop.
+ ///
+ virtual void Dematerialize(GlobalValue *) {}
+
+ /// MaterializeModule - make sure the entire Module has been completely read.
+ /// On error, this returns true and fills in the optional string with
+ /// information about the problem. If successful, this returns false.
+ ///
+ virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0) = 0;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/GlobalAlias.h b/include/llvm/GlobalAlias.h
new file mode 100644
index 00000000000..a97ecd30c9d
--- /dev/null
+++ b/include/llvm/GlobalAlias.h
@@ -0,0 +1,94 @@
+//===-------- llvm/GlobalAlias.h - GlobalAlias class ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the GlobalAlias class, which
+// represents a single function or variable alias in the IR.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_GLOBAL_ALIAS_H
+#define LLVM_GLOBAL_ALIAS_H
+
+#include "llvm/GlobalValue.h"
+#include "llvm/OperandTraits.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/ADT/Twine.h"
+
+namespace llvm {
+
+class Module;
+template<typename ValueSubClass, typename ItemParentClass>
+ class SymbolTableListTraits;
+
+class GlobalAlias : public GlobalValue, public ilist_node<GlobalAlias> {
+ friend class SymbolTableListTraits<GlobalAlias, Module>;
+ void operator=(const GlobalAlias &) LLVM_DELETED_FUNCTION;
+ GlobalAlias(const GlobalAlias &) LLVM_DELETED_FUNCTION;
+
+ void setParent(Module *parent);
+
+public:
+ // allocate space for exactly one operand
+ void *operator new(size_t s) {
+ return User::operator new(s, 1);
+ }
+ /// GlobalAlias ctor - If a parent module is specified, the alias is
+ /// automatically inserted into the end of the specified module's alias list.
+ GlobalAlias(Type *Ty, LinkageTypes Linkage, const Twine &Name = "",
+ Constant* Aliasee = 0, Module *Parent = 0);
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
+
+ /// removeFromParent - This method unlinks 'this' from the containing module,
+ /// but does not delete it.
+ ///
+ virtual void removeFromParent();
+
+ /// eraseFromParent - This method unlinks 'this' from the containing module
+ /// and deletes it.
+ ///
+ virtual void eraseFromParent();
+
+ /// set/getAliasee - These methods retrive and set alias target.
+ void setAliasee(Constant *GV);
+ const Constant *getAliasee() const {
+ return getOperand(0);
+ }
+ Constant *getAliasee() {
+ return getOperand(0);
+ }
+ /// getAliasedGlobal() - Aliasee can be either global or bitcast of
+ /// global. This method retrives the global for both aliasee flavours.
+ const GlobalValue *getAliasedGlobal() const;
+
+ /// resolveAliasedGlobal() - This method tries to ultimately resolve the alias
+ /// by going through the aliasing chain and trying to find the very last
+ /// global. Returns NULL if a cycle was found. If stopOnWeak is false, then
+ /// the whole chain aliasing chain is traversed, otherwise - only strong
+ /// aliases.
+ const GlobalValue *resolveAliasedGlobal(bool stopOnWeak = true) const;
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const GlobalAlias *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == Value::GlobalAliasVal;
+ }
+};
+
+template <>
+struct OperandTraits<GlobalAlias> :
+ public FixedNumOperandTraits<GlobalAlias, 1> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GlobalAlias, Constant)
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/GlobalValue.h b/include/llvm/GlobalValue.h
new file mode 100644
index 00000000000..58d02576c17
--- /dev/null
+++ b/include/llvm/GlobalValue.h
@@ -0,0 +1,300 @@
+//===-- llvm/GlobalValue.h - Class to represent a global value --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a common base class of all globally definable objects. As such,
+// it is subclassed by GlobalVariable, GlobalAlias and by Function. This is
+// used because you can do certain things with these global objects that you
+// can't do to anything else. For example, use the address of one as a
+// constant.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_GLOBALVALUE_H
+#define LLVM_GLOBALVALUE_H
+
+#include "llvm/Constant.h"
+
+namespace llvm {
+
+class PointerType;
+class Module;
+
+class GlobalValue : public Constant {
+ GlobalValue(const GlobalValue &) LLVM_DELETED_FUNCTION;
+public:
+ /// @brief An enumeration for the kinds of linkage for global values.
+ enum LinkageTypes {
+ ExternalLinkage = 0,///< Externally visible function
+ AvailableExternallyLinkage, ///< Available for inspection, not emission.
+ LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
+ LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
+ LinkOnceODRAutoHideLinkage, ///< Like LinkOnceODRLinkage but addr not taken.
+ WeakAnyLinkage, ///< Keep one copy of named function when linking (weak)
+ WeakODRLinkage, ///< Same, but only replaced by something equivalent.
+ AppendingLinkage, ///< Special purpose, only applies to global arrays
+ InternalLinkage, ///< Rename collisions when linking (static functions).
+ PrivateLinkage, ///< Like Internal, but omit from symbol table.
+ LinkerPrivateLinkage, ///< Like Private, but linker removes.
+ LinkerPrivateWeakLinkage, ///< Like LinkerPrivate, but weak.
+ DLLImportLinkage, ///< Function to be imported from DLL
+ DLLExportLinkage, ///< Function to be accessible from DLL.
+ ExternalWeakLinkage,///< ExternalWeak linkage description.
+ CommonLinkage ///< Tentative definitions.
+ };
+
+ /// @brief An enumeration for the kinds of visibility of global values.
+ enum VisibilityTypes {
+ DefaultVisibility = 0, ///< The GV is visible
+ HiddenVisibility, ///< The GV is hidden
+ ProtectedVisibility ///< The GV is protected
+ };
+
+protected:
+ GlobalValue(Type *ty, ValueTy vty, Use *Ops, unsigned NumOps,
+ LinkageTypes linkage, const Twine &Name)
+ : Constant(ty, vty, Ops, NumOps), Linkage(linkage),
+ Visibility(DefaultVisibility), Alignment(0), UnnamedAddr(0), Parent(0) {
+ setName(Name);
+ }
+
+ // Note: VC++ treats enums as signed, so an extra bit is required to prevent
+ // Linkage and Visibility from turning into negative values.
+ LinkageTypes Linkage : 5; // The linkage of this global
+ unsigned Visibility : 2; // The visibility style of this global
+ unsigned Alignment : 16; // Alignment of this symbol, must be power of two
+ unsigned UnnamedAddr : 1; // This value's address is not significant
+ Module *Parent; // The containing module.
+ std::string Section; // Section to emit this into, empty mean default
+public:
+ ~GlobalValue() {
+ removeDeadConstantUsers(); // remove any dead constants using this.
+ }
+
+ unsigned getAlignment() const {
+ return (1u << Alignment) >> 1;
+ }
+ void setAlignment(unsigned Align);
+
+ bool hasUnnamedAddr() const { return UnnamedAddr; }
+ void setUnnamedAddr(bool Val) { UnnamedAddr = Val; }
+
+ VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
+ bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
+ bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
+ bool hasProtectedVisibility() const {
+ return Visibility == ProtectedVisibility;
+ }
+ void setVisibility(VisibilityTypes V) { Visibility = V; }
+
+ bool hasSection() const { return !Section.empty(); }
+ const std::string &getSection() const { return Section; }
+ void setSection(StringRef S) { Section = S; }
+
+ /// If the usage is empty (except transitively dead constants), then this
+ /// global value can be safely deleted since the destructor will
+ /// delete the dead constants as well.
+ /// @brief Determine if the usage of this global value is empty except
+ /// for transitively dead constants.
+ bool use_empty_except_constants();
+
+ /// getType - Global values are always pointers.
+ inline PointerType *getType() const {
+ return reinterpret_cast<PointerType*>(User::getType());
+ }
+
+ static LinkageTypes getLinkOnceLinkage(bool ODR) {
+ return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
+ }
+ static LinkageTypes getWeakLinkage(bool ODR) {
+ return ODR ? WeakODRLinkage : WeakAnyLinkage;
+ }
+
+ static bool isExternalLinkage(LinkageTypes Linkage) {
+ return Linkage == ExternalLinkage;
+ }
+ static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
+ return Linkage == AvailableExternallyLinkage;
+ }
+ static bool isLinkOnceLinkage(LinkageTypes Linkage) {
+ return Linkage == LinkOnceAnyLinkage ||
+ Linkage == LinkOnceODRLinkage ||
+ Linkage == LinkOnceODRAutoHideLinkage;
+ }
+ static bool isLinkOnceODRAutoHideLinkage(LinkageTypes Linkage) {
+ return Linkage == LinkOnceODRAutoHideLinkage;
+ }
+ static bool isWeakLinkage(LinkageTypes Linkage) {
+ return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage;
+ }
+ static bool isAppendingLinkage(LinkageTypes Linkage) {
+ return Linkage == AppendingLinkage;
+ }
+ static bool isInternalLinkage(LinkageTypes Linkage) {
+ return Linkage == InternalLinkage;
+ }
+ static bool isPrivateLinkage(LinkageTypes Linkage) {
+ return Linkage == PrivateLinkage;
+ }
+ static bool isLinkerPrivateLinkage(LinkageTypes Linkage) {
+ return Linkage == LinkerPrivateLinkage;
+ }
+ static bool isLinkerPrivateWeakLinkage(LinkageTypes Linkage) {
+ return Linkage == LinkerPrivateWeakLinkage;
+ }
+ static bool isLocalLinkage(LinkageTypes Linkage) {
+ return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage) ||
+ isLinkerPrivateLinkage(Linkage) || isLinkerPrivateWeakLinkage(Linkage);
+ }
+ static bool isDLLImportLinkage(LinkageTypes Linkage) {
+ return Linkage == DLLImportLinkage;
+ }
+ static bool isDLLExportLinkage(LinkageTypes Linkage) {
+ return Linkage == DLLExportLinkage;
+ }
+ static bool isExternalWeakLinkage(LinkageTypes Linkage) {
+ return Linkage == ExternalWeakLinkage;
+ }
+ static bool isCommonLinkage(LinkageTypes Linkage) {
+ return Linkage == CommonLinkage;
+ }
+
+ /// isDiscardableIfUnused - Whether the definition of this global may be
+ /// discarded if it is not used in its compilation unit.
+ static bool isDiscardableIfUnused(LinkageTypes Linkage) {
+ return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage);
+ }
+
+ /// mayBeOverridden - Whether the definition of this global may be replaced
+ /// by something non-equivalent at link time. For example, if a function has
+ /// weak linkage then the code defining it may be replaced by different code.
+ static bool mayBeOverridden(LinkageTypes Linkage) {
+ return Linkage == WeakAnyLinkage ||
+ Linkage == LinkOnceAnyLinkage ||
+ Linkage == CommonLinkage ||
+ Linkage == ExternalWeakLinkage ||
+ Linkage == LinkerPrivateWeakLinkage;
+ }
+
+ /// isWeakForLinker - Whether the definition of this global may be replaced at
+ /// link time. NB: Using this method outside of the code generators is almost
+ /// always a mistake: when working at the IR level use mayBeOverridden instead
+ /// as it knows about ODR semantics.
+ static bool isWeakForLinker(LinkageTypes Linkage) {
+ return Linkage == AvailableExternallyLinkage ||
+ Linkage == WeakAnyLinkage ||
+ Linkage == WeakODRLinkage ||
+ Linkage == LinkOnceAnyLinkage ||
+ Linkage == LinkOnceODRLinkage ||
+ Linkage == LinkOnceODRAutoHideLinkage ||
+ Linkage == CommonLinkage ||
+ Linkage == ExternalWeakLinkage ||
+ Linkage == LinkerPrivateWeakLinkage;
+ }
+
+ bool hasExternalLinkage() const { return isExternalLinkage(Linkage); }
+ bool hasAvailableExternallyLinkage() const {
+ return isAvailableExternallyLinkage(Linkage);
+ }
+ bool hasLinkOnceLinkage() const {
+ return isLinkOnceLinkage(Linkage);
+ }
+ bool hasLinkOnceODRAutoHideLinkage() const {
+ return isLinkOnceODRAutoHideLinkage(Linkage);
+ }
+ bool hasWeakLinkage() const {
+ return isWeakLinkage(Linkage);
+ }
+ bool hasAppendingLinkage() const { return isAppendingLinkage(Linkage); }
+ bool hasInternalLinkage() const { return isInternalLinkage(Linkage); }
+ bool hasPrivateLinkage() const { return isPrivateLinkage(Linkage); }
+ bool hasLinkerPrivateLinkage() const { return isLinkerPrivateLinkage(Linkage); }
+ bool hasLinkerPrivateWeakLinkage() const {
+ return isLinkerPrivateWeakLinkage(Linkage);
+ }
+ bool hasLocalLinkage() const { return isLocalLinkage(Linkage); }
+ bool hasDLLImportLinkage() const { return isDLLImportLinkage(Linkage); }
+ bool hasDLLExportLinkage() const { return isDLLExportLinkage(Linkage); }
+ bool hasExternalWeakLinkage() const { return isExternalWeakLinkage(Linkage); }
+ bool hasCommonLinkage() const { return isCommonLinkage(Linkage); }
+
+ void setLinkage(LinkageTypes LT) { Linkage = LT; }
+ LinkageTypes getLinkage() const { return Linkage; }
+
+ bool isDiscardableIfUnused() const {
+ return isDiscardableIfUnused(Linkage);
+ }
+
+ bool mayBeOverridden() const { return mayBeOverridden(Linkage); }
+
+ bool isWeakForLinker() const { return isWeakForLinker(Linkage); }
+
+ /// copyAttributesFrom - copy all additional attributes (those not needed to
+ /// create a GlobalValue) from the GlobalValue Src to this one.
+ virtual void copyAttributesFrom(const GlobalValue *Src);
+
+/// @name Materialization
+/// Materialization is used to construct functions only as they're needed. This
+/// is useful to reduce memory usage in LLVM or parsing work done by the
+/// BitcodeReader to load the Module.
+/// @{
+
+ /// isMaterializable - If this function's Module is being lazily streamed in
+ /// functions from disk or some other source, this method can be used to check
+ /// to see if the function has been read in yet or not.
+ bool isMaterializable() const;
+
+ /// isDematerializable - Returns true if this function was loaded from a
+ /// GVMaterializer that's still attached to its Module and that knows how to
+ /// dematerialize the function.
+ bool isDematerializable() const;
+
+ /// Materialize - make sure this GlobalValue is fully read. If the module is
+ /// corrupt, this returns true and fills in the optional string with
+ /// information about the problem. If successful, this returns false.
+ bool Materialize(std::string *ErrInfo = 0);
+
+ /// Dematerialize - If this GlobalValue is read in, and if the GVMaterializer
+ /// supports it, release the memory for the function, and set it up to be
+ /// materialized lazily. If !isDematerializable(), this method is a noop.
+ void Dematerialize();
+
+/// @}
+
+ /// Override from Constant class.
+ virtual void destroyConstant();
+
+ /// isDeclaration - Return true if the primary definition of this global
+ /// value is outside of the current translation unit.
+ bool isDeclaration() const;
+
+ /// removeFromParent - This method unlinks 'this' from the containing module,
+ /// but does not delete it.
+ virtual void removeFromParent() = 0;
+
+ /// eraseFromParent - This method unlinks 'this' from the containing module
+ /// and deletes it.
+ virtual void eraseFromParent() = 0;
+
+ /// getParent - Get the module that this global value is contained inside
+ /// of...
+ inline Module *getParent() { return Parent; }
+ inline const Module *getParent() const { return Parent; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const GlobalValue *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == Value::FunctionVal ||
+ V->getValueID() == Value::GlobalVariableVal ||
+ V->getValueID() == Value::GlobalAliasVal;
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/GlobalVariable.h b/include/llvm/GlobalVariable.h
new file mode 100644
index 00000000000..27a2ea7fb9f
--- /dev/null
+++ b/include/llvm/GlobalVariable.h
@@ -0,0 +1,192 @@
+//===-- llvm/GlobalVariable.h - GlobalVariable class ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the GlobalVariable class, which
+// represents a single global variable (or constant) in the VM.
+//
+// Global variables are constant pointers that refer to hunks of space that are
+// allocated by either the VM, or by the linker in a static compiler. A global
+// variable may have an initial value, which is copied into the executables .data
+// area. Global Constants are required to have initializers.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_GLOBAL_VARIABLE_H
+#define LLVM_GLOBAL_VARIABLE_H
+
+#include "llvm/GlobalValue.h"
+#include "llvm/OperandTraits.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/ADT/Twine.h"
+
+namespace llvm {
+
+class Module;
+class Constant;
+template<typename ValueSubClass, typename ItemParentClass>
+ class SymbolTableListTraits;
+
+class GlobalVariable : public GlobalValue, public ilist_node<GlobalVariable> {
+ friend class SymbolTableListTraits<GlobalVariable, Module>;
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ void operator=(const GlobalVariable &) LLVM_DELETED_FUNCTION;
+ GlobalVariable(const GlobalVariable &) LLVM_DELETED_FUNCTION;
+
+ void setParent(Module *parent);
+
+ bool isConstantGlobal : 1; // Is this a global constant?
+ unsigned threadLocalMode : 3; // Is this symbol "Thread Local",
+ // if so, what is the desired model?
+
+public:
+ // allocate space for exactly one operand
+ void *operator new(size_t s) {
+ return User::operator new(s, 1);
+ }
+
+ enum ThreadLocalMode {
+ NotThreadLocal = 0,
+ GeneralDynamicTLSModel,
+ LocalDynamicTLSModel,
+ InitialExecTLSModel,
+ LocalExecTLSModel
+ };
+
+ /// GlobalVariable ctor - If a parent module is specified, the global is
+ /// automatically inserted into the end of the specified modules global list.
+ GlobalVariable(Type *Ty, bool isConstant, LinkageTypes Linkage,
+ Constant *Initializer = 0, const Twine &Name = "",
+ ThreadLocalMode = NotThreadLocal, unsigned AddressSpace = 0);
+ /// GlobalVariable ctor - This creates a global and inserts it before the
+ /// specified other global.
+ GlobalVariable(Module &M, Type *Ty, bool isConstant,
+ LinkageTypes Linkage, Constant *Initializer,
+ const Twine &Name = "",
+ GlobalVariable *InsertBefore = 0,
+ ThreadLocalMode = NotThreadLocal,
+ unsigned AddressSpace = 0);
+
+ ~GlobalVariable() {
+ NumOperands = 1; // FIXME: needed by operator delete
+ }
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// hasInitializer - Unless a global variable isExternal(), it has an
+ /// initializer. The initializer for the global variable/constant is held by
+ /// Initializer if an initializer is specified.
+ ///
+ inline bool hasInitializer() const { return !isDeclaration(); }
+
+ /// hasDefinitiveInitializer - Whether the global variable has an initializer,
+ /// and any other instances of the global (this can happen due to weak
+ /// linkage) are guaranteed to have the same initializer.
+ ///
+ /// Note that if you want to transform a global, you must use
+ /// hasUniqueInitializer() instead, because of the *_odr linkage type.
+ ///
+ /// Example:
+ ///
+ /// @a = global SomeType* null - Initializer is both definitive and unique.
+ ///
+ /// @b = global weak SomeType* null - Initializer is neither definitive nor
+ /// unique.
+ ///
+ /// @c = global weak_odr SomeType* null - Initializer is definitive, but not
+ /// unique.
+ inline bool hasDefinitiveInitializer() const {
+ return hasInitializer() &&
+ // The initializer of a global variable with weak linkage may change at
+ // link time.
+ !mayBeOverridden();
+ }
+
+ /// hasUniqueInitializer - Whether the global variable has an initializer, and
+ /// any changes made to the initializer will turn up in the final executable.
+ inline bool hasUniqueInitializer() const {
+ return hasInitializer() &&
+ // It's not safe to modify initializers of global variables with weak
+ // linkage, because the linker might choose to discard the initializer and
+ // use the initializer from another instance of the global variable
+ // instead. It is wrong to modify the initializer of a global variable
+ // with *_odr linkage because then different instances of the global may
+ // have different initializers, breaking the One Definition Rule.
+ !isWeakForLinker();
+ }
+
+ /// getInitializer - Return the initializer for this global variable. It is
+ /// illegal to call this method if the global is external, because we cannot
+ /// tell what the value is initialized to!
+ ///
+ inline const Constant *getInitializer() const {
+ assert(hasInitializer() && "GV doesn't have initializer!");
+ return static_cast<Constant*>(Op<0>().get());
+ }
+ inline Constant *getInitializer() {
+ assert(hasInitializer() && "GV doesn't have initializer!");
+ return static_cast<Constant*>(Op<0>().get());
+ }
+ /// setInitializer - Sets the initializer for this global variable, removing
+ /// any existing initializer if InitVal==NULL. If this GV has type T*, the
+ /// initializer must have type T.
+ void setInitializer(Constant *InitVal);
+
+ /// If the value is a global constant, its value is immutable throughout the
+ /// runtime execution of the program. Assigning a value into the constant
+ /// leads to undefined behavior.
+ ///
+ bool isConstant() const { return isConstantGlobal; }
+ void setConstant(bool Val) { isConstantGlobal = Val; }
+
+ /// If the value is "Thread Local", its value isn't shared by the threads.
+ bool isThreadLocal() const { return threadLocalMode != NotThreadLocal; }
+ void setThreadLocal(bool Val) {
+ threadLocalMode = Val ? GeneralDynamicTLSModel : NotThreadLocal;
+ }
+ void setThreadLocalMode(ThreadLocalMode Val) { threadLocalMode = Val; }
+ ThreadLocalMode getThreadLocalMode() const {
+ return static_cast<ThreadLocalMode>(threadLocalMode);
+ }
+
+ /// copyAttributesFrom - copy all additional attributes (those not needed to
+ /// create a GlobalVariable) from the GlobalVariable Src to this one.
+ void copyAttributesFrom(const GlobalValue *Src);
+
+ /// removeFromParent - This method unlinks 'this' from the containing module,
+ /// but does not delete it.
+ ///
+ virtual void removeFromParent();
+
+ /// eraseFromParent - This method unlinks 'this' from the containing module
+ /// and deletes it.
+ ///
+ virtual void eraseFromParent();
+
+ /// Override Constant's implementation of this method so we can
+ /// replace constant initializers.
+ virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const GlobalVariable *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == Value::GlobalVariableVal;
+ }
+};
+
+template <>
+struct OperandTraits<GlobalVariable> :
+ public OptionalOperandTraits<GlobalVariable> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GlobalVariable, Value)
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/IRBuilder.h b/include/llvm/IRBuilder.h
new file mode 100644
index 00000000000..ae82c25e3d6
--- /dev/null
+++ b/include/llvm/IRBuilder.h
@@ -0,0 +1,1296 @@
+//===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the IRBuilder class, which is used as a convenient way
+// to create LLVM instructions with a consistent and simplified interface.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_IRBUILDER_H
+#define LLVM_IRBUILDER_H
+
+#include "llvm/Instructions.h"
+#include "llvm/BasicBlock.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Support/ConstantFolder.h"
+
+namespace llvm {
+ class MDNode;
+
+/// IRBuilderDefaultInserter - This provides the default implementation of the
+/// IRBuilder 'InsertHelper' method that is called whenever an instruction is
+/// created by IRBuilder and needs to be inserted. By default, this inserts the
+/// instruction at the insertion point.
+template <bool preserveNames = true>
+class IRBuilderDefaultInserter {
+protected:
+ void InsertHelper(Instruction *I, const Twine &Name,
+ BasicBlock *BB, BasicBlock::iterator InsertPt) const {
+ if (BB) BB->getInstList().insert(InsertPt, I);
+ if (preserveNames)
+ I->setName(Name);
+ }
+};
+
+/// IRBuilderBase - Common base class shared among various IRBuilders.
+class IRBuilderBase {
+ DebugLoc CurDbgLocation;
+protected:
+ BasicBlock *BB;
+ BasicBlock::iterator InsertPt;
+ LLVMContext &Context;
+public:
+
+ IRBuilderBase(LLVMContext &context)
+ : Context(context) {
+ ClearInsertionPoint();
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Builder configuration methods
+ //===--------------------------------------------------------------------===//
+
+ /// ClearInsertionPoint - Clear the insertion point: created instructions will
+ /// not be inserted into a block.
+ void ClearInsertionPoint() {
+ BB = 0;
+ }
+
+ BasicBlock *GetInsertBlock() const { return BB; }
+ BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
+ LLVMContext &getContext() const { return Context; }
+
+ /// SetInsertPoint - This specifies that created instructions should be
+ /// appended to the end of the specified block.
+ void SetInsertPoint(BasicBlock *TheBB) {
+ BB = TheBB;
+ InsertPt = BB->end();
+ }
+
+ /// SetInsertPoint - This specifies that created instructions should be
+ /// inserted before the specified instruction.
+ void SetInsertPoint(Instruction *I) {
+ BB = I->getParent();
+ InsertPt = I;
+ SetCurrentDebugLocation(I->getDebugLoc());
+ }
+
+ /// SetInsertPoint - This specifies that created instructions should be
+ /// inserted at the specified point.
+ void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
+ BB = TheBB;
+ InsertPt = IP;
+ }
+
+ /// SetInsertPoint(Use) - Find the nearest point that dominates this use, and
+ /// specify that created instructions should be inserted at this point.
+ void SetInsertPoint(Use &U) {
+ Instruction *UseInst = cast<Instruction>(U.getUser());
+ if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
+ BasicBlock *PredBB = Phi->getIncomingBlock(U);
+ assert(U != PredBB->getTerminator() && "critical edge not split");
+ SetInsertPoint(PredBB, PredBB->getTerminator());
+ return;
+ }
+ SetInsertPoint(UseInst);
+ }
+
+ /// SetCurrentDebugLocation - Set location information used by debugging
+ /// information.
+ void SetCurrentDebugLocation(const DebugLoc &L) {
+ CurDbgLocation = L;
+ }
+
+ /// getCurrentDebugLocation - Get location information used by debugging
+ /// information.
+ DebugLoc getCurrentDebugLocation() const { return CurDbgLocation; }
+
+ /// SetInstDebugLocation - If this builder has a current debug location, set
+ /// it on the specified instruction.
+ void SetInstDebugLocation(Instruction *I) const {
+ if (!CurDbgLocation.isUnknown())
+ I->setDebugLoc(CurDbgLocation);
+ }
+
+ /// getCurrentFunctionReturnType - Get the return type of the current function
+ /// that we're emitting into.
+ Type *getCurrentFunctionReturnType() const;
+
+ /// InsertPoint - A saved insertion point.
+ class InsertPoint {
+ BasicBlock *Block;
+ BasicBlock::iterator Point;
+
+ public:
+ /// Creates a new insertion point which doesn't point to anything.
+ InsertPoint() : Block(0) {}
+
+ /// Creates a new insertion point at the given location.
+ InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
+ : Block(InsertBlock), Point(InsertPoint) {}
+
+ /// isSet - Returns true if this insert point is set.
+ bool isSet() const { return (Block != 0); }
+
+ llvm::BasicBlock *getBlock() const { return Block; }
+ llvm::BasicBlock::iterator getPoint() const { return Point; }
+ };
+
+ /// saveIP - Returns the current insert point.
+ InsertPoint saveIP() const {
+ return InsertPoint(GetInsertBlock(), GetInsertPoint());
+ }
+
+ /// saveAndClearIP - Returns the current insert point, clearing it
+ /// in the process.
+ InsertPoint saveAndClearIP() {
+ InsertPoint IP(GetInsertBlock(), GetInsertPoint());
+ ClearInsertionPoint();
+ return IP;
+ }
+
+ /// restoreIP - Sets the current insert point to a previously-saved
+ /// location.
+ void restoreIP(InsertPoint IP) {
+ if (IP.isSet())
+ SetInsertPoint(IP.getBlock(), IP.getPoint());
+ else
+ ClearInsertionPoint();
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Miscellaneous creation methods.
+ //===--------------------------------------------------------------------===//
+
+ /// CreateGlobalString - Make a new global variable with an initializer that
+ /// has array of i8 type filled in with the nul terminated string value
+ /// specified. The new global variable will be marked mergable with any
+ /// others of the same contents. If Name is specified, it is the name of the
+ /// global variable created.
+ Value *CreateGlobalString(StringRef Str, const Twine &Name = "");
+
+ /// getInt1 - Get a constant value representing either true or false.
+ ConstantInt *getInt1(bool V) {
+ return ConstantInt::get(getInt1Ty(), V);
+ }
+
+ /// getTrue - Get the constant value for i1 true.
+ ConstantInt *getTrue() {
+ return ConstantInt::getTrue(Context);
+ }
+
+ /// getFalse - Get the constant value for i1 false.
+ ConstantInt *getFalse() {
+ return ConstantInt::getFalse(Context);
+ }
+
+ /// getInt8 - Get a constant 8-bit value.
+ ConstantInt *getInt8(uint8_t C) {
+ return ConstantInt::get(getInt8Ty(), C);
+ }
+
+ /// getInt16 - Get a constant 16-bit value.
+ ConstantInt *getInt16(uint16_t C) {
+ return ConstantInt::get(getInt16Ty(), C);
+ }
+
+ /// getInt32 - Get a constant 32-bit value.
+ ConstantInt *getInt32(uint32_t C) {
+ return ConstantInt::get(getInt32Ty(), C);
+ }
+
+ /// getInt64 - Get a constant 64-bit value.
+ ConstantInt *getInt64(uint64_t C) {
+ return ConstantInt::get(getInt64Ty(), C);
+ }
+
+ /// getInt - Get a constant integer value.
+ ConstantInt *getInt(const APInt &AI) {
+ return ConstantInt::get(Context, AI);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Type creation methods
+ //===--------------------------------------------------------------------===//
+
+ /// getInt1Ty - Fetch the type representing a single bit
+ IntegerType *getInt1Ty() {
+ return Type::getInt1Ty(Context);
+ }
+
+ /// getInt8Ty - Fetch the type representing an 8-bit integer.
+ IntegerType *getInt8Ty() {
+ return Type::getInt8Ty(Context);
+ }
+
+ /// getInt16Ty - Fetch the type representing a 16-bit integer.
+ IntegerType *getInt16Ty() {
+ return Type::getInt16Ty(Context);
+ }
+
+ /// getInt32Ty - Fetch the type resepresenting a 32-bit integer.
+ IntegerType *getInt32Ty() {
+ return Type::getInt32Ty(Context);
+ }
+
+ /// getInt64Ty - Fetch the type representing a 64-bit integer.
+ IntegerType *getInt64Ty() {
+ return Type::getInt64Ty(Context);
+ }
+
+ /// getFloatTy - Fetch the type representing a 32-bit floating point value.
+ Type *getFloatTy() {
+ return Type::getFloatTy(Context);
+ }
+
+ /// getDoubleTy - Fetch the type representing a 64-bit floating point value.
+ Type *getDoubleTy() {
+ return Type::getDoubleTy(Context);
+ }
+
+ /// getVoidTy - Fetch the type representing void.
+ Type *getVoidTy() {
+ return Type::getVoidTy(Context);
+ }
+
+ PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
+ return Type::getInt8PtrTy(Context, AddrSpace);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Intrinsic creation methods
+ //===--------------------------------------------------------------------===//
+
+ /// CreateMemSet - Create and insert a memset to the specified pointer and the
+ /// specified value. If the pointer isn't an i8*, it will be converted. If a
+ /// TBAA tag is specified, it will be added to the instruction.
+ CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
+ bool isVolatile = false, MDNode *TBAATag = 0) {
+ return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile, TBAATag);
+ }
+
+ CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
+ bool isVolatile = false, MDNode *TBAATag = 0);
+
+ /// CreateMemCpy - Create and insert a memcpy between the specified pointers.
+ /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
+ /// specified, it will be added to the instruction.
+ CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
+ bool isVolatile = false, MDNode *TBAATag = 0) {
+ return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag);
+ }
+
+ CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
+ bool isVolatile = false, MDNode *TBAATag = 0);
+
+ /// CreateMemMove - Create and insert a memmove between the specified
+ /// pointers. If the pointers aren't i8*, they will be converted. If a TBAA
+ /// tag is specified, it will be added to the instruction.
+ CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
+ bool isVolatile = false, MDNode *TBAATag = 0) {
+ return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag);
+ }
+
+ CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
+ bool isVolatile = false, MDNode *TBAATag = 0);
+
+ /// CreateLifetimeStart - Create a lifetime.start intrinsic. If the pointer
+ /// isn't i8* it will be converted.
+ CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = 0);
+
+ /// CreateLifetimeEnd - Create a lifetime.end intrinsic. If the pointer isn't
+ /// i8* it will be converted.
+ CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = 0);
+
+private:
+ Value *getCastedInt8PtrValue(Value *Ptr);
+};
+
+/// IRBuilder - This provides a uniform API for creating instructions and
+/// inserting them into a basic block: either at the end of a BasicBlock, or
+/// at a specific iterator location in a block.
+///
+/// Note that the builder does not expose the full generality of LLVM
+/// instructions. For access to extra instruction properties, use the mutators
+/// (e.g. setVolatile) on the instructions after they have been created.
+/// The first template argument handles whether or not to preserve names in the
+/// final instruction output. This defaults to on. The second template argument
+/// specifies a class to use for creating constants. This defaults to creating
+/// minimally folded constants. The fourth template argument allows clients to
+/// specify custom insertion hooks that are called on every newly created
+/// insertion.
+template<bool preserveNames = true, typename T = ConstantFolder,
+ typename Inserter = IRBuilderDefaultInserter<preserveNames> >
+class IRBuilder : public IRBuilderBase, public Inserter {
+ T Folder;
+ MDNode *DefaultFPMathTag;
+public:
+ IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
+ MDNode *FPMathTag = 0)
+ : IRBuilderBase(C), Inserter(I), Folder(F), DefaultFPMathTag(FPMathTag) {
+ }
+
+ explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = 0) : IRBuilderBase(C),
+ Folder(), DefaultFPMathTag(FPMathTag) {
+ }
+
+ explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = 0)
+ : IRBuilderBase(TheBB->getContext()), Folder(F),
+ DefaultFPMathTag(FPMathTag) {
+ SetInsertPoint(TheBB);
+ }
+
+ explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = 0)
+ : IRBuilderBase(TheBB->getContext()), Folder(),
+ DefaultFPMathTag(FPMathTag) {
+ SetInsertPoint(TheBB);
+ }
+
+ explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = 0)
+ : IRBuilderBase(IP->getContext()), Folder(), DefaultFPMathTag(FPMathTag) {
+ SetInsertPoint(IP);
+ SetCurrentDebugLocation(IP->getDebugLoc());
+ }
+
+ explicit IRBuilder(Use &U, MDNode *FPMathTag = 0)
+ : IRBuilderBase(U->getContext()), Folder(), DefaultFPMathTag(FPMathTag) {
+ SetInsertPoint(U);
+ SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
+ }
+
+ IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
+ MDNode *FPMathTag = 0)
+ : IRBuilderBase(TheBB->getContext()), Folder(F),
+ DefaultFPMathTag(FPMathTag) {
+ SetInsertPoint(TheBB, IP);
+ }
+
+ IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, MDNode *FPMathTag = 0)
+ : IRBuilderBase(TheBB->getContext()), Folder(),
+ DefaultFPMathTag(FPMathTag) {
+ SetInsertPoint(TheBB, IP);
+ }
+
+ /// getFolder - Get the constant folder being used.
+ const T &getFolder() { return Folder; }
+
+ /// getDefaultFPMathTag - Get the floating point math metadata being used.
+ MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
+
+ /// SetDefaultFPMathTag - Set the floating point math metadata to be used.
+ void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
+
+ /// isNamePreserving - Return true if this builder is configured to actually
+ /// add the requested names to IR created through it.
+ bool isNamePreserving() const { return preserveNames; }
+
+ /// Insert - Insert and return the specified instruction.
+ template<typename InstTy>
+ InstTy *Insert(InstTy *I, const Twine &Name = "") const {
+ this->InsertHelper(I, Name, BB, InsertPt);
+ if (!getCurrentDebugLocation().isUnknown())
+ this->SetInstDebugLocation(I);
+ return I;
+ }
+
+ /// Insert - No-op overload to handle constants.
+ Constant *Insert(Constant *C, const Twine& = "") const {
+ return C;
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Instruction creation methods: Terminators
+ //===--------------------------------------------------------------------===//
+
+private:
+ /// \brief Helper to add branch weight metadata onto an instruction.
+ /// \returns The annotated instruction.
+ template <typename InstTy>
+ InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
+ if (Weights)
+ I->setMetadata(LLVMContext::MD_prof, Weights);
+ return I;
+ }
+
+public:
+ /// CreateRetVoid - Create a 'ret void' instruction.
+ ReturnInst *CreateRetVoid() {
+ return Insert(ReturnInst::Create(Context));
+ }
+
+ /// @verbatim
+ /// CreateRet - Create a 'ret <val>' instruction.
+ /// @endverbatim
+ ReturnInst *CreateRet(Value *V) {
+ return Insert(ReturnInst::Create(Context, V));
+ }
+
+ /// CreateAggregateRet - Create a sequence of N insertvalue instructions,
+ /// with one Value from the retVals array each, that build a aggregate
+ /// return value one value at a time, and a ret instruction to return
+ /// the resulting aggregate value. This is a convenience function for
+ /// code that uses aggregate return values as a vehicle for having
+ /// multiple return values.
+ ///
+ ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
+ Value *V = UndefValue::get(getCurrentFunctionReturnType());
+ for (unsigned i = 0; i != N; ++i)
+ V = CreateInsertValue(V, retVals[i], i, "mrv");
+ return Insert(ReturnInst::Create(Context, V));
+ }
+
+ /// CreateBr - Create an unconditional 'br label X' instruction.
+ BranchInst *CreateBr(BasicBlock *Dest) {
+ return Insert(BranchInst::Create(Dest));
+ }
+
+ /// CreateCondBr - Create a conditional 'br Cond, TrueDest, FalseDest'
+ /// instruction.
+ BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
+ MDNode *BranchWeights = 0) {
+ return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
+ BranchWeights));
+ }
+
+ /// CreateSwitch - Create a switch instruction with the specified value,
+ /// default dest, and with a hint for the number of cases that will be added
+ /// (for efficient allocation).
+ SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
+ MDNode *BranchWeights = 0) {
+ return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
+ BranchWeights));
+ }
+
+ /// CreateIndirectBr - Create an indirect branch instruction with the
+ /// specified address operand, with an optional hint for the number of
+ /// destinations that will be added (for efficient allocation).
+ IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
+ return Insert(IndirectBrInst::Create(Addr, NumDests));
+ }
+
+ InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
+ BasicBlock *UnwindDest, const Twine &Name = "") {
+ return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest,
+ ArrayRef<Value *>()),
+ Name);
+ }
+ InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
+ BasicBlock *UnwindDest, Value *Arg1,
+ const Twine &Name = "") {
+ return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
+ Name);
+ }
+ InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
+ BasicBlock *UnwindDest, Value *Arg1,
+ Value *Arg2, Value *Arg3,
+ const Twine &Name = "") {
+ Value *Args[] = { Arg1, Arg2, Arg3 };
+ return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
+ Name);
+ }
+ /// CreateInvoke - Create an invoke instruction.
+ InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
+ BasicBlock *UnwindDest, ArrayRef<Value *> Args,
+ const Twine &Name = "") {
+ return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
+ Name);
+ }
+
+ ResumeInst *CreateResume(Value *Exn) {
+ return Insert(ResumeInst::Create(Exn));
+ }
+
+ UnreachableInst *CreateUnreachable() {
+ return Insert(new UnreachableInst(Context));
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Instruction creation methods: Binary Operators
+ //===--------------------------------------------------------------------===//
+private:
+ BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
+ Value *LHS, Value *RHS,
+ const Twine &Name,
+ bool HasNUW, bool HasNSW) {
+ BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
+ if (HasNUW) BO->setHasNoUnsignedWrap();
+ if (HasNSW) BO->setHasNoSignedWrap();
+ return BO;
+ }
+
+ Instruction *AddFPMathTag(Instruction *I, MDNode *FPMathTag) const {
+ if (!FPMathTag)
+ FPMathTag = DefaultFPMathTag;
+ if (FPMathTag)
+ I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
+ return I;
+ }
+public:
+ Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
+ bool HasNUW = false, bool HasNSW = false) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
+ return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
+ HasNUW, HasNSW);
+ }
+ Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateAdd(LHS, RHS, Name, false, true);
+ }
+ Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateAdd(LHS, RHS, Name, true, false);
+ }
+ Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
+ MDNode *FPMathTag = 0) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateFAdd(LC, RC), Name);
+ return Insert(AddFPMathTag(BinaryOperator::CreateFAdd(LHS, RHS),
+ FPMathTag), Name);
+ }
+ Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
+ bool HasNUW = false, bool HasNSW = false) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateSub(LC, RC), Name);
+ return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
+ HasNUW, HasNSW);
+ }
+ Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateSub(LHS, RHS, Name, false, true);
+ }
+ Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateSub(LHS, RHS, Name, true, false);
+ }
+ Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
+ MDNode *FPMathTag = 0) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateFSub(LC, RC), Name);
+ return Insert(AddFPMathTag(BinaryOperator::CreateFSub(LHS, RHS),
+ FPMathTag), Name);
+ }
+ Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
+ bool HasNUW = false, bool HasNSW = false) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateMul(LC, RC), Name);
+ return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
+ HasNUW, HasNSW);
+ }
+ Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateMul(LHS, RHS, Name, false, true);
+ }
+ Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateMul(LHS, RHS, Name, true, false);
+ }
+ Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
+ MDNode *FPMathTag = 0) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateFMul(LC, RC), Name);
+ return Insert(AddFPMathTag(BinaryOperator::CreateFMul(LHS, RHS),
+ FPMathTag), Name);
+ }
+ Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
+ bool isExact = false) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
+ if (!isExact)
+ return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
+ return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
+ }
+ Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateUDiv(LHS, RHS, Name, true);
+ }
+ Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
+ bool isExact = false) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
+ if (!isExact)
+ return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
+ return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
+ }
+ Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateSDiv(LHS, RHS, Name, true);
+ }
+ Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
+ MDNode *FPMathTag = 0) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateFDiv(LC, RC), Name);
+ return Insert(AddFPMathTag(BinaryOperator::CreateFDiv(LHS, RHS),
+ FPMathTag), Name);
+ }
+ Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateURem(LC, RC), Name);
+ return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
+ }
+ Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateSRem(LC, RC), Name);
+ return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
+ }
+ Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
+ MDNode *FPMathTag = 0) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateFRem(LC, RC), Name);
+ return Insert(AddFPMathTag(BinaryOperator::CreateFRem(LHS, RHS),
+ FPMathTag), Name);
+ }
+
+ Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
+ bool HasNUW = false, bool HasNSW = false) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
+ return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
+ HasNUW, HasNSW);
+ }
+ Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
+ bool HasNUW = false, bool HasNSW = false) {
+ return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
+ HasNUW, HasNSW);
+ }
+ Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
+ bool HasNUW = false, bool HasNSW = false) {
+ return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
+ HasNUW, HasNSW);
+ }
+
+ Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
+ bool isExact = false) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
+ if (!isExact)
+ return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
+ return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
+ }
+ Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
+ bool isExact = false) {
+ return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
+ }
+ Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
+ bool isExact = false) {
+ return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
+ }
+
+ Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
+ bool isExact = false) {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
+ if (!isExact)
+ return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
+ return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
+ }
+ Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
+ bool isExact = false) {
+ return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
+ }
+ Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
+ bool isExact = false) {
+ return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
+ }
+
+ Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
+ if (Constant *RC = dyn_cast<Constant>(RHS)) {
+ if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
+ return LHS; // LHS & -1 -> LHS
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ return Insert(Folder.CreateAnd(LC, RC), Name);
+ }
+ return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
+ }
+ Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
+ return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
+ }
+ Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
+ return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
+ }
+
+ Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
+ if (Constant *RC = dyn_cast<Constant>(RHS)) {
+ if (RC->isNullValue())
+ return LHS; // LHS | 0 -> LHS
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ return Insert(Folder.CreateOr(LC, RC), Name);
+ }
+ return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
+ }
+ Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
+ return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
+ }
+ Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
+ return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
+ }
+
+ Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateXor(LC, RC), Name);
+ return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
+ }
+ Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
+ return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
+ }
+ Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
+ return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
+ }
+
+ Value *CreateBinOp(Instruction::BinaryOps Opc,
+ Value *LHS, Value *RHS, const Twine &Name = "") {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
+ return Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
+ }
+
+ Value *CreateNeg(Value *V, const Twine &Name = "",
+ bool HasNUW = false, bool HasNSW = false) {
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
+ BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
+ if (HasNUW) BO->setHasNoUnsignedWrap();
+ if (HasNSW) BO->setHasNoSignedWrap();
+ return BO;
+ }
+ Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
+ return CreateNeg(V, Name, false, true);
+ }
+ Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
+ return CreateNeg(V, Name, true, false);
+ }
+ Value *CreateFNeg(Value *V, const Twine &Name = "", MDNode *FPMathTag = 0) {
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateFNeg(VC), Name);
+ return Insert(AddFPMathTag(BinaryOperator::CreateFNeg(V), FPMathTag), Name);
+ }
+ Value *CreateNot(Value *V, const Twine &Name = "") {
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateNot(VC), Name);
+ return Insert(BinaryOperator::CreateNot(V), Name);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Instruction creation methods: Memory Instructions
+ //===--------------------------------------------------------------------===//
+
+ AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = 0,
+ const Twine &Name = "") {
+ return Insert(new AllocaInst(Ty, ArraySize), Name);
+ }
+ // Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
+ // converting the string to 'bool' for the isVolatile parameter.
+ LoadInst *CreateLoad(Value *Ptr, const char *Name) {
+ return Insert(new LoadInst(Ptr), Name);
+ }
+ LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
+ return Insert(new LoadInst(Ptr), Name);
+ }
+ LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
+ return Insert(new LoadInst(Ptr, 0, isVolatile), Name);
+ }
+ StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
+ return Insert(new StoreInst(Val, Ptr, isVolatile));
+ }
+ FenceInst *CreateFence(AtomicOrdering Ordering,
+ SynchronizationScope SynchScope = CrossThread) {
+ return Insert(new FenceInst(Context, Ordering, SynchScope));
+ }
+ AtomicCmpXchgInst *CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
+ AtomicOrdering Ordering,
+ SynchronizationScope SynchScope = CrossThread) {
+ return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope));
+ }
+ AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
+ AtomicOrdering Ordering,
+ SynchronizationScope SynchScope = CrossThread) {
+ return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
+ }
+ Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
+ const Twine &Name = "") {
+ if (Constant *PC = dyn_cast<Constant>(Ptr)) {
+ // Every index must be constant.
+ size_t i, e;
+ for (i = 0, e = IdxList.size(); i != e; ++i)
+ if (!isa<Constant>(IdxList[i]))
+ break;
+ if (i == e)
+ return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
+ }
+ return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
+ }
+ Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
+ const Twine &Name = "") {
+ if (Constant *PC = dyn_cast<Constant>(Ptr)) {
+ // Every index must be constant.
+ size_t i, e;
+ for (i = 0, e = IdxList.size(); i != e; ++i)
+ if (!isa<Constant>(IdxList[i]))
+ break;
+ if (i == e)
+ return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
+ }
+ return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
+ }
+ Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ if (Constant *IC = dyn_cast<Constant>(Idx))
+ return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
+ return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
+ }
+ Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ if (Constant *IC = dyn_cast<Constant>(Idx))
+ return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
+ return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
+ }
+ Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
+ Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
+
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
+
+ return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
+ }
+ Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
+ const Twine &Name = "") {
+ Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
+
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
+
+ return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
+ }
+ Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
+ const Twine &Name = "") {
+ Value *Idxs[] = {
+ ConstantInt::get(Type::getInt32Ty(Context), Idx0),
+ ConstantInt::get(Type::getInt32Ty(Context), Idx1)
+ };
+
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
+
+ return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
+ }
+ Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
+ const Twine &Name = "") {
+ Value *Idxs[] = {
+ ConstantInt::get(Type::getInt32Ty(Context), Idx0),
+ ConstantInt::get(Type::getInt32Ty(Context), Idx1)
+ };
+
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
+
+ return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
+ }
+ Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
+ Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
+
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
+
+ return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
+ }
+ Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
+ const Twine &Name = "") {
+ Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
+
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
+
+ return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
+ }
+ Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
+ const Twine &Name = "") {
+ Value *Idxs[] = {
+ ConstantInt::get(Type::getInt64Ty(Context), Idx0),
+ ConstantInt::get(Type::getInt64Ty(Context), Idx1)
+ };
+
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
+
+ return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
+ }
+ Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
+ const Twine &Name = "") {
+ Value *Idxs[] = {
+ ConstantInt::get(Type::getInt64Ty(Context), Idx0),
+ ConstantInt::get(Type::getInt64Ty(Context), Idx1)
+ };
+
+ if (Constant *PC = dyn_cast<Constant>(Ptr))
+ return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
+
+ return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
+ }
+ Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
+ return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
+ }
+
+ /// CreateGlobalStringPtr - Same as CreateGlobalString, but return a pointer
+ /// with "i8*" type instead of a pointer to array of i8.
+ Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
+ Value *gv = CreateGlobalString(Str, Name);
+ Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
+ Value *Args[] = { zero, zero };
+ return CreateInBoundsGEP(gv, Args, Name);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Instruction creation methods: Cast/Conversion Operators
+ //===--------------------------------------------------------------------===//
+
+ Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
+ return CreateCast(Instruction::Trunc, V, DestTy, Name);
+ }
+ Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
+ return CreateCast(Instruction::ZExt, V, DestTy, Name);
+ }
+ Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
+ return CreateCast(Instruction::SExt, V, DestTy, Name);
+ }
+ Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
+ return CreateCast(Instruction::FPToUI, V, DestTy, Name);
+ }
+ Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
+ return CreateCast(Instruction::FPToSI, V, DestTy, Name);
+ }
+ Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
+ return CreateCast(Instruction::UIToFP, V, DestTy, Name);
+ }
+ Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
+ return CreateCast(Instruction::SIToFP, V, DestTy, Name);
+ }
+ Value *CreateFPTrunc(Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
+ }
+ Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
+ return CreateCast(Instruction::FPExt, V, DestTy, Name);
+ }
+ Value *CreatePtrToInt(Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
+ }
+ Value *CreateIntToPtr(Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
+ }
+ Value *CreateBitCast(Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ return CreateCast(Instruction::BitCast, V, DestTy, Name);
+ }
+ Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ if (V->getType() == DestTy)
+ return V;
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
+ return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
+ }
+ Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ if (V->getType() == DestTy)
+ return V;
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
+ return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
+ }
+ Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ if (V->getType() == DestTy)
+ return V;
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
+ return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
+ }
+ Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ if (V->getType() == DestTy)
+ return V;
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
+ return Insert(CastInst::Create(Op, V, DestTy), Name);
+ }
+ Value *CreatePointerCast(Value *V, Type *DestTy,
+ const Twine &Name = "") {
+ if (V->getType() == DestTy)
+ return V;
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
+ return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
+ }
+ Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
+ const Twine &Name = "") {
+ if (V->getType() == DestTy)
+ return V;
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
+ return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
+ }
+private:
+ // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a compile time
+ // error, instead of converting the string to bool for the isSigned parameter.
+ Value *CreateIntCast(Value *, Type *, const char *) LLVM_DELETED_FUNCTION;
+public:
+ Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
+ if (V->getType() == DestTy)
+ return V;
+ if (Constant *VC = dyn_cast<Constant>(V))
+ return Insert(Folder.CreateFPCast(VC, DestTy), Name);
+ return Insert(CastInst::CreateFPCast(V, DestTy), Name);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Instruction creation methods: Compare Instructions
+ //===--------------------------------------------------------------------===//
+
+ Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
+ }
+ Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
+ }
+ Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
+ }
+ Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
+ }
+ Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
+ }
+ Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
+ }
+ Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
+ }
+ Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
+ }
+ Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
+ }
+ Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
+ }
+
+ Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
+ }
+ Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
+ }
+ Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
+ }
+ Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
+ }
+ Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
+ }
+ Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
+ }
+ Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
+ }
+ Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
+ }
+ Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
+ }
+ Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
+ }
+ Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
+ }
+ Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
+ }
+ Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
+ }
+ Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
+ return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
+ }
+
+ Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
+ const Twine &Name = "") {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateICmp(P, LC, RC), Name);
+ return Insert(new ICmpInst(P, LHS, RHS), Name);
+ }
+ Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
+ const Twine &Name = "") {
+ if (Constant *LC = dyn_cast<Constant>(LHS))
+ if (Constant *RC = dyn_cast<Constant>(RHS))
+ return Insert(Folder.CreateFCmp(P, LC, RC), Name);
+ return Insert(new FCmpInst(P, LHS, RHS), Name);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Instruction creation methods: Other Instructions
+ //===--------------------------------------------------------------------===//
+
+ PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
+ const Twine &Name = "") {
+ return Insert(PHINode::Create(Ty, NumReservedValues), Name);
+ }
+
+ CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
+ return Insert(CallInst::Create(Callee), Name);
+ }
+ CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
+ return Insert(CallInst::Create(Callee, Arg), Name);
+ }
+ CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
+ const Twine &Name = "") {
+ Value *Args[] = { Arg1, Arg2 };
+ return Insert(CallInst::Create(Callee, Args), Name);
+ }
+ CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
+ const Twine &Name = "") {
+ Value *Args[] = { Arg1, Arg2, Arg3 };
+ return Insert(CallInst::Create(Callee, Args), Name);
+ }
+ CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
+ Value *Arg4, const Twine &Name = "") {
+ Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
+ return Insert(CallInst::Create(Callee, Args), Name);
+ }
+ CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
+ Value *Arg4, Value *Arg5, const Twine &Name = "") {
+ Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
+ return Insert(CallInst::Create(Callee, Args), Name);
+ }
+
+ CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
+ const Twine &Name = "") {
+ return Insert(CallInst::Create(Callee, Args), Name);
+ }
+
+ Value *CreateSelect(Value *C, Value *True, Value *False,
+ const Twine &Name = "") {
+ if (Constant *CC = dyn_cast<Constant>(C))
+ if (Constant *TC = dyn_cast<Constant>(True))
+ if (Constant *FC = dyn_cast<Constant>(False))
+ return Insert(Folder.CreateSelect(CC, TC, FC), Name);
+ return Insert(SelectInst::Create(C, True, False), Name);
+ }
+
+ VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
+ return Insert(new VAArgInst(List, Ty), Name);
+ }
+
+ Value *CreateExtractElement(Value *Vec, Value *Idx,
+ const Twine &Name = "") {
+ if (Constant *VC = dyn_cast<Constant>(Vec))
+ if (Constant *IC = dyn_cast<Constant>(Idx))
+ return Insert(Folder.CreateExtractElement(VC, IC), Name);
+ return Insert(ExtractElementInst::Create(Vec, Idx), Name);
+ }
+
+ Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
+ const Twine &Name = "") {
+ if (Constant *VC = dyn_cast<Constant>(Vec))
+ if (Constant *NC = dyn_cast<Constant>(NewElt))
+ if (Constant *IC = dyn_cast<Constant>(Idx))
+ return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
+ return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
+ }
+
+ Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
+ const Twine &Name = "") {
+ if (Constant *V1C = dyn_cast<Constant>(V1))
+ if (Constant *V2C = dyn_cast<Constant>(V2))
+ if (Constant *MC = dyn_cast<Constant>(Mask))
+ return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
+ return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
+ }
+
+ Value *CreateExtractValue(Value *Agg,
+ ArrayRef<unsigned> Idxs,
+ const Twine &Name = "") {
+ if (Constant *AggC = dyn_cast<Constant>(Agg))
+ return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
+ return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
+ }
+
+ Value *CreateInsertValue(Value *Agg, Value *Val,
+ ArrayRef<unsigned> Idxs,
+ const Twine &Name = "") {
+ if (Constant *AggC = dyn_cast<Constant>(Agg))
+ if (Constant *ValC = dyn_cast<Constant>(Val))
+ return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
+ return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
+ }
+
+ LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
+ const Twine &Name = "") {
+ return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses, Name));
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Utility creation methods
+ //===--------------------------------------------------------------------===//
+
+ /// CreateIsNull - Return an i1 value testing if \p Arg is null.
+ Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
+ return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
+ Name);
+ }
+
+ /// CreateIsNotNull - Return an i1 value testing if \p Arg is not null.
+ Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
+ return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
+ Name);
+ }
+
+ /// CreatePtrDiff - Return the i64 difference between two pointer values,
+ /// dividing out the size of the pointed-to objects. This is intended to
+ /// implement C-style pointer subtraction. As such, the pointers must be
+ /// appropriately aligned for their element types and pointing into the
+ /// same object.
+ Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
+ assert(LHS->getType() == RHS->getType() &&
+ "Pointer subtraction operand types must match!");
+ PointerType *ArgType = cast<PointerType>(LHS->getType());
+ Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
+ Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
+ Value *Difference = CreateSub(LHS_int, RHS_int);
+ return CreateExactSDiv(Difference,
+ ConstantExpr::getSizeOf(ArgType->getElementType()),
+ Name);
+ }
+};
+
+}
+
+#endif
diff --git a/include/llvm/InitializePasses.h b/include/llvm/InitializePasses.h
new file mode 100644
index 00000000000..76c22b0fb8f
--- /dev/null
+++ b/include/llvm/InitializePasses.h
@@ -0,0 +1,266 @@
+//===- llvm/InitializePasses.h -------- Initialize All Passes ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declarations for the pass initialization routines
+// for the entire LLVM project.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INITIALIZEPASSES_H
+#define LLVM_INITIALIZEPASSES_H
+
+namespace llvm {
+
+class PassRegistry;
+
+/// initializeCore - Initialize all passes linked into the
+/// TransformUtils library.
+void initializeCore(PassRegistry&);
+
+/// initializeTransformUtils - Initialize all passes linked into the
+/// TransformUtils library.
+void initializeTransformUtils(PassRegistry&);
+
+/// initializeScalarOpts - Initialize all passes linked into the
+/// ScalarOpts library.
+void initializeScalarOpts(PassRegistry&);
+
+/// initializeVectorization - Initialize all passes linked into the
+/// Vectorize library.
+void initializeVectorization(PassRegistry&);
+
+/// initializeInstCombine - Initialize all passes linked into the
+/// ScalarOpts library.
+void initializeInstCombine(PassRegistry&);
+
+/// initializeIPO - Initialize all passes linked into the IPO library.
+void initializeIPO(PassRegistry&);
+
+/// initializeInstrumentation - Initialize all passes linked into the
+/// Instrumentation library.
+void initializeInstrumentation(PassRegistry&);
+
+/// initializeAnalysis - Initialize all passes linked into the Analysis library.
+void initializeAnalysis(PassRegistry&);
+
+/// initializeIPA - Initialize all passes linked into the IPA library.
+void initializeIPA(PassRegistry&);
+
+/// initializeCodeGen - Initialize all passes linked into the CodeGen library.
+void initializeCodeGen(PassRegistry&);
+
+/// initializeCodeGen - Initialize all passes linked into the CodeGen library.
+void initializeTarget(PassRegistry&);
+
+void initializeAAEvalPass(PassRegistry&);
+void initializeADCEPass(PassRegistry&);
+void initializeAliasAnalysisAnalysisGroup(PassRegistry&);
+void initializeAliasAnalysisCounterPass(PassRegistry&);
+void initializeAliasDebuggerPass(PassRegistry&);
+void initializeAliasSetPrinterPass(PassRegistry&);
+void initializeAlwaysInlinerPass(PassRegistry&);
+void initializeArgPromotionPass(PassRegistry&);
+void initializeBasicAliasAnalysisPass(PassRegistry&);
+void initializeBasicCallGraphPass(PassRegistry&);
+void initializeBlockExtractorPassPass(PassRegistry&);
+void initializeBlockFrequencyInfoPass(PassRegistry&);
+void initializeBlockPlacementPass(PassRegistry&);
+void initializeBoundsCheckingPass(PassRegistry&);
+void initializeBranchFolderPassPass(PassRegistry&);
+void initializeBranchProbabilityInfoPass(PassRegistry&);
+void initializeBreakCriticalEdgesPass(PassRegistry&);
+void initializeCFGOnlyPrinterPass(PassRegistry&);
+void initializeCFGOnlyViewerPass(PassRegistry&);
+void initializeCFGPrinterPass(PassRegistry&);
+void initializeCFGSimplifyPassPass(PassRegistry&);
+void initializeCFGViewerPass(PassRegistry&);
+void initializeCalculateSpillWeightsPass(PassRegistry&);
+void initializeCallGraphAnalysisGroup(PassRegistry&);
+void initializeCodeGenPreparePass(PassRegistry&);
+void initializeCodePlacementOptPass(PassRegistry&);
+void initializeConstantMergePass(PassRegistry&);
+void initializeConstantPropagationPass(PassRegistry&);
+void initializeMachineCopyPropagationPass(PassRegistry&);
+void initializeCorrelatedValuePropagationPass(PassRegistry&);
+void initializeDAEPass(PassRegistry&);
+void initializeDAHPass(PassRegistry&);
+void initializeDCEPass(PassRegistry&);
+void initializeDSEPass(PassRegistry&);
+void initializeDeadInstEliminationPass(PassRegistry&);
+void initializeDeadMachineInstructionElimPass(PassRegistry&);
+void initializeDomOnlyPrinterPass(PassRegistry&);
+void initializeDomOnlyViewerPass(PassRegistry&);
+void initializeDomPrinterPass(PassRegistry&);
+void initializeDomViewerPass(PassRegistry&);
+void initializeDominanceFrontierPass(PassRegistry&);
+void initializeDominatorTreePass(PassRegistry&);
+void initializeEarlyIfConverterPass(PassRegistry&);
+void initializeEdgeBundlesPass(PassRegistry&);
+void initializeEdgeProfilerPass(PassRegistry&);
+void initializeExpandPostRAPass(PassRegistry&);
+void initializePathProfilerPass(PassRegistry&);
+void initializeGCOVProfilerPass(PassRegistry&);
+void initializeAddressSanitizerPass(PassRegistry&);
+void initializeThreadSanitizerPass(PassRegistry&);
+void initializeEarlyCSEPass(PassRegistry&);
+void initializeExpandISelPseudosPass(PassRegistry&);
+void initializeFindUsedTypesPass(PassRegistry&);
+void initializeFunctionAttrsPass(PassRegistry&);
+void initializeGCInfoDeleterPass(PassRegistry&);
+void initializeGCMachineCodeAnalysisPass(PassRegistry&);
+void initializeGCModuleInfoPass(PassRegistry&);
+void initializeGVNPass(PassRegistry&);
+void initializeGlobalDCEPass(PassRegistry&);
+void initializeGlobalOptPass(PassRegistry&);
+void initializeGlobalsModRefPass(PassRegistry&);
+void initializeIPCPPass(PassRegistry&);
+void initializeIPSCCPPass(PassRegistry&);
+void initializeIVUsersPass(PassRegistry&);
+void initializeIfConverterPass(PassRegistry&);
+void initializeIndVarSimplifyPass(PassRegistry&);
+void initializeInstCombinerPass(PassRegistry&);
+void initializeInstCountPass(PassRegistry&);
+void initializeInstNamerPass(PassRegistry&);
+void initializeInternalizePassPass(PassRegistry&);
+void initializeIntervalPartitionPass(PassRegistry&);
+void initializeJumpThreadingPass(PassRegistry&);
+void initializeLCSSAPass(PassRegistry&);
+void initializeLICMPass(PassRegistry&);
+void initializeLazyValueInfoPass(PassRegistry&);
+void initializeLibCallAliasAnalysisPass(PassRegistry&);
+void initializeLintPass(PassRegistry&);
+void initializeLiveDebugVariablesPass(PassRegistry&);
+void initializeLiveIntervalsPass(PassRegistry&);
+void initializeLiveRegMatrixPass(PassRegistry&);
+void initializeLiveStacksPass(PassRegistry&);
+void initializeLiveVariablesPass(PassRegistry&);
+void initializeLoaderPassPass(PassRegistry&);
+void initializeProfileMetadataLoaderPassPass(PassRegistry&);
+void initializePathProfileLoaderPassPass(PassRegistry&);
+void initializeLocalStackSlotPassPass(PassRegistry&);
+void initializeLoopDeletionPass(PassRegistry&);
+void initializeLoopDependenceAnalysisPass(PassRegistry&);
+void initializeLoopExtractorPass(PassRegistry&);
+void initializeLoopInfoPass(PassRegistry&);
+void initializeLoopInstSimplifyPass(PassRegistry&);
+void initializeLoopRotatePass(PassRegistry&);
+void initializeLoopSimplifyPass(PassRegistry&);
+void initializeLoopStrengthReducePass(PassRegistry&);
+void initializeGlobalMergePass(PassRegistry&);
+void initializeLoopUnrollPass(PassRegistry&);
+void initializeLoopUnswitchPass(PassRegistry&);
+void initializeLoopIdiomRecognizePass(PassRegistry&);
+void initializeLowerAtomicPass(PassRegistry&);
+void initializeLowerExpectIntrinsicPass(PassRegistry&);
+void initializeLowerIntrinsicsPass(PassRegistry&);
+void initializeLowerInvokePass(PassRegistry&);
+void initializeLowerSwitchPass(PassRegistry&);
+void initializeMachineBlockFrequencyInfoPass(PassRegistry&);
+void initializeMachineBlockPlacementPass(PassRegistry&);
+void initializeMachineBlockPlacementStatsPass(PassRegistry&);
+void initializeMachineBranchProbabilityInfoPass(PassRegistry&);
+void initializeMachineCSEPass(PassRegistry&);
+void initializeMachineDominatorTreePass(PassRegistry&);
+void initializeMachinePostDominatorTreePass(PassRegistry&);
+void initializeMachineLICMPass(PassRegistry&);
+void initializeMachineLoopInfoPass(PassRegistry&);
+void initializeMachineLoopRangesPass(PassRegistry&);
+void initializeMachineModuleInfoPass(PassRegistry&);
+void initializeMachineSchedulerPass(PassRegistry&);
+void initializeMachineSinkingPass(PassRegistry&);
+void initializeMachineTraceMetricsPass(PassRegistry&);
+void initializeMachineVerifierPassPass(PassRegistry&);
+void initializeMemCpyOptPass(PassRegistry&);
+void initializeMemDepPrinterPass(PassRegistry&);
+void initializeMemoryDependenceAnalysisPass(PassRegistry&);
+void initializeMetaRenamerPass(PassRegistry&);
+void initializeMergeFunctionsPass(PassRegistry&);
+void initializeModuleDebugInfoPrinterPass(PassRegistry&);
+void initializeNoAAPass(PassRegistry&);
+void initializeNoProfileInfoPass(PassRegistry&);
+void initializeNoPathProfileInfoPass(PassRegistry&);
+void initializeObjCARCAliasAnalysisPass(PassRegistry&);
+void initializeObjCARCAPElimPass(PassRegistry&);
+void initializeObjCARCExpandPass(PassRegistry&);
+void initializeObjCARCContractPass(PassRegistry&);
+void initializeObjCARCOptPass(PassRegistry&);
+void initializeOptimalEdgeProfilerPass(PassRegistry&);
+void initializeOptimizePHIsPass(PassRegistry&);
+void initializePEIPass(PassRegistry&);
+void initializePHIEliminationPass(PassRegistry&);
+void initializePartialInlinerPass(PassRegistry&);
+void initializePeepholeOptimizerPass(PassRegistry&);
+void initializePostDomOnlyPrinterPass(PassRegistry&);
+void initializePostDomOnlyViewerPass(PassRegistry&);
+void initializePostDomPrinterPass(PassRegistry&);
+void initializePostDomViewerPass(PassRegistry&);
+void initializePostDominatorTreePass(PassRegistry&);
+void initializePostRASchedulerPass(PassRegistry&);
+void initializePreVerifierPass(PassRegistry&);
+void initializePrintDbgInfoPass(PassRegistry&);
+void initializePrintFunctionPassPass(PassRegistry&);
+void initializePrintModulePassPass(PassRegistry&);
+void initializeProcessImplicitDefsPass(PassRegistry&);
+void initializeProfileEstimatorPassPass(PassRegistry&);
+void initializeProfileInfoAnalysisGroup(PassRegistry&);
+void initializePathProfileInfoAnalysisGroup(PassRegistry&);
+void initializePathProfileVerifierPass(PassRegistry&);
+void initializeProfileVerifierPassPass(PassRegistry&);
+void initializePromotePassPass(PassRegistry&);
+void initializePruneEHPass(PassRegistry&);
+void initializeReassociatePass(PassRegistry&);
+void initializeRegToMemPass(PassRegistry&);
+void initializeRegionInfoPass(PassRegistry&);
+void initializeRegionOnlyPrinterPass(PassRegistry&);
+void initializeRegionOnlyViewerPass(PassRegistry&);
+void initializeRegionPrinterPass(PassRegistry&);
+void initializeRegionViewerPass(PassRegistry&);
+void initializeSCCPPass(PassRegistry&);
+void initializeSROAPass(PassRegistry&);
+void initializeSROA_DTPass(PassRegistry&);
+void initializeSROA_SSAUpPass(PassRegistry&);
+void initializeScalarEvolutionAliasAnalysisPass(PassRegistry&);
+void initializeScalarEvolutionPass(PassRegistry&);
+void initializeSimpleInlinerPass(PassRegistry&);
+void initializeRegisterCoalescerPass(PassRegistry&);
+void initializeSimplifyLibCallsPass(PassRegistry&);
+void initializeSingleLoopExtractorPass(PassRegistry&);
+void initializeSinkingPass(PassRegistry&);
+void initializeSlotIndexesPass(PassRegistry&);
+void initializeSpillPlacementPass(PassRegistry&);
+void initializeStackProtectorPass(PassRegistry&);
+void initializeStackColoringPass(PassRegistry&);
+void initializeStackSlotColoringPass(PassRegistry&);
+void initializeStripDeadDebugInfoPass(PassRegistry&);
+void initializeStripDeadPrototypesPassPass(PassRegistry&);
+void initializeStripDebugDeclarePass(PassRegistry&);
+void initializeStripNonDebugSymbolsPass(PassRegistry&);
+void initializeStripSymbolsPass(PassRegistry&);
+void initializeStrongPHIEliminationPass(PassRegistry&);
+void initializeTailCallElimPass(PassRegistry&);
+void initializeTailDuplicatePassPass(PassRegistry&);
+void initializeTargetPassConfigPass(PassRegistry&);
+void initializeTargetDataPass(PassRegistry&);
+void initializeTargetLibraryInfoPass(PassRegistry&);
+void initializeTwoAddressInstructionPassPass(PassRegistry&);
+void initializeTypeBasedAliasAnalysisPass(PassRegistry&);
+void initializeUnifyFunctionExitNodesPass(PassRegistry&);
+void initializeUnreachableBlockElimPass(PassRegistry&);
+void initializeUnreachableMachineBlockElimPass(PassRegistry&);
+void initializeVerifierPass(PassRegistry&);
+void initializeVirtRegMapPass(PassRegistry&);
+void initializeVirtRegRewriterPass(PassRegistry&);
+void initializeInstSimplifierPass(PassRegistry&);
+void initializeUnpackMachineBundlesPass(PassRegistry&);
+void initializeFinalizeMachineBundlesPass(PassRegistry&);
+void initializeBBVectorizePass(PassRegistry&);
+void initializeMachineFunctionPrinterPassPass(PassRegistry&);
+}
+
+#endif
diff --git a/include/llvm/InlineAsm.h b/include/llvm/InlineAsm.h
new file mode 100644
index 00000000000..58c1e84e53f
--- /dev/null
+++ b/include/llvm/InlineAsm.h
@@ -0,0 +1,308 @@
+//===-- llvm/InlineAsm.h - Class to represent inline asm strings-*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This class represents the inline asm strings, which are Value*'s that are
+// used as the callee operand of call instructions. InlineAsm's are uniqued
+// like constants, and created via InlineAsm::get(...).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INLINEASM_H
+#define LLVM_INLINEASM_H
+
+#include "llvm/Value.h"
+#include "llvm/ADT/StringRef.h"
+#include <vector>
+
+namespace llvm {
+
+class PointerType;
+class FunctionType;
+class Module;
+struct InlineAsmKeyType;
+template<class ValType, class ValRefType, class TypeClass, class ConstantClass,
+ bool HasLargeKey>
+class ConstantUniqueMap;
+template<class ConstantClass, class TypeClass, class ValType>
+struct ConstantCreator;
+
+class InlineAsm : public Value {
+public:
+ enum AsmDialect {
+ AD_ATT,
+ AD_Intel
+ };
+
+private:
+ friend struct ConstantCreator<InlineAsm, PointerType, InlineAsmKeyType>;
+ friend class ConstantUniqueMap<InlineAsmKeyType, const InlineAsmKeyType&,
+ PointerType, InlineAsm, false>;
+
+ InlineAsm(const InlineAsm &) LLVM_DELETED_FUNCTION;
+ void operator=(const InlineAsm&) LLVM_DELETED_FUNCTION;
+
+ std::string AsmString, Constraints;
+ bool HasSideEffects;
+ bool IsAlignStack;
+ AsmDialect Dialect;
+
+ InlineAsm(PointerType *Ty, const std::string &AsmString,
+ const std::string &Constraints, bool hasSideEffects,
+ bool isAlignStack, AsmDialect asmDialect);
+ virtual ~InlineAsm();
+
+ /// When the ConstantUniqueMap merges two types and makes two InlineAsms
+ /// identical, it destroys one of them with this method.
+ void destroyConstant();
+public:
+
+ /// InlineAsm::get - Return the specified uniqued inline asm string.
+ ///
+ static InlineAsm *get(FunctionType *Ty, StringRef AsmString,
+ StringRef Constraints, bool hasSideEffects,
+ bool isAlignStack = false,
+ AsmDialect asmDialect = AD_ATT);
+
+ bool hasSideEffects() const { return HasSideEffects; }
+ bool isAlignStack() const { return IsAlignStack; }
+ AsmDialect getDialect() const { return Dialect; }
+
+ /// getType - InlineAsm's are always pointers.
+ ///
+ PointerType *getType() const {
+ return reinterpret_cast<PointerType*>(Value::getType());
+ }
+
+ /// getFunctionType - InlineAsm's are always pointers to functions.
+ ///
+ FunctionType *getFunctionType() const;
+
+ const std::string &getAsmString() const { return AsmString; }
+ const std::string &getConstraintString() const { return Constraints; }
+
+ /// Verify - This static method can be used by the parser to check to see if
+ /// the specified constraint string is legal for the type. This returns true
+ /// if legal, false if not.
+ ///
+ static bool Verify(FunctionType *Ty, StringRef Constraints);
+
+ // Constraint String Parsing
+ enum ConstraintPrefix {
+ isInput, // 'x'
+ isOutput, // '=x'
+ isClobber // '~x'
+ };
+
+ typedef std::vector<std::string> ConstraintCodeVector;
+
+ struct SubConstraintInfo {
+ /// MatchingInput - If this is not -1, this is an output constraint where an
+ /// input constraint is required to match it (e.g. "0"). The value is the
+ /// constraint number that matches this one (for example, if this is
+ /// constraint #0 and constraint #4 has the value "0", this will be 4).
+ signed char MatchingInput;
+ /// Code - The constraint code, either the register name (in braces) or the
+ /// constraint letter/number.
+ ConstraintCodeVector Codes;
+ /// Default constructor.
+ SubConstraintInfo() : MatchingInput(-1) {}
+ };
+
+ typedef std::vector<SubConstraintInfo> SubConstraintInfoVector;
+ struct ConstraintInfo;
+ typedef std::vector<ConstraintInfo> ConstraintInfoVector;
+
+ struct ConstraintInfo {
+ /// Type - The basic type of the constraint: input/output/clobber
+ ///
+ ConstraintPrefix Type;
+
+ /// isEarlyClobber - "&": output operand writes result before inputs are all
+ /// read. This is only ever set for an output operand.
+ bool isEarlyClobber;
+
+ /// MatchingInput - If this is not -1, this is an output constraint where an
+ /// input constraint is required to match it (e.g. "0"). The value is the
+ /// constraint number that matches this one (for example, if this is
+ /// constraint #0 and constraint #4 has the value "0", this will be 4).
+ signed char MatchingInput;
+
+ /// hasMatchingInput - Return true if this is an output constraint that has
+ /// a matching input constraint.
+ bool hasMatchingInput() const { return MatchingInput != -1; }
+
+ /// isCommutative - This is set to true for a constraint that is commutative
+ /// with the next operand.
+ bool isCommutative;
+
+ /// isIndirect - True if this operand is an indirect operand. This means
+ /// that the address of the source or destination is present in the call
+ /// instruction, instead of it being returned or passed in explicitly. This
+ /// is represented with a '*' in the asm string.
+ bool isIndirect;
+
+ /// Code - The constraint code, either the register name (in braces) or the
+ /// constraint letter/number.
+ ConstraintCodeVector Codes;
+
+ /// isMultipleAlternative - '|': has multiple-alternative constraints.
+ bool isMultipleAlternative;
+
+ /// multipleAlternatives - If there are multiple alternative constraints,
+ /// this array will contain them. Otherwise it will be empty.
+ SubConstraintInfoVector multipleAlternatives;
+
+ /// The currently selected alternative constraint index.
+ unsigned currentAlternativeIndex;
+
+ ///Default constructor.
+ ConstraintInfo();
+
+ /// Copy constructor.
+ ConstraintInfo(const ConstraintInfo &other);
+
+ /// Parse - Analyze the specified string (e.g. "=*&{eax}") and fill in the
+ /// fields in this structure. If the constraint string is not understood,
+ /// return true, otherwise return false.
+ bool Parse(StringRef Str, ConstraintInfoVector &ConstraintsSoFar);
+
+ /// selectAlternative - Point this constraint to the alternative constraint
+ /// indicated by the index.
+ void selectAlternative(unsigned index);
+ };
+
+ /// ParseConstraints - Split up the constraint string into the specific
+ /// constraints and their prefixes. If this returns an empty vector, and if
+ /// the constraint string itself isn't empty, there was an error parsing.
+ static ConstraintInfoVector ParseConstraints(StringRef ConstraintString);
+
+ /// ParseConstraints - Parse the constraints of this inlineasm object,
+ /// returning them the same way that ParseConstraints(str) does.
+ ConstraintInfoVector ParseConstraints() const {
+ return ParseConstraints(Constraints);
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const InlineAsm *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() == Value::InlineAsmVal;
+ }
+
+
+ // These are helper methods for dealing with flags in the INLINEASM SDNode
+ // in the backend.
+
+ enum {
+ // Fixed operands on an INLINEASM SDNode.
+ Op_InputChain = 0,
+ Op_AsmString = 1,
+ Op_MDNode = 2,
+ Op_ExtraInfo = 3, // HasSideEffects, IsAlignStack, AsmDialect.
+ Op_FirstOperand = 4,
+
+ // Fixed operands on an INLINEASM MachineInstr.
+ MIOp_AsmString = 0,
+ MIOp_ExtraInfo = 1, // HasSideEffects, IsAlignStack, AsmDialect.
+ MIOp_FirstOperand = 2,
+
+ // Interpretation of the MIOp_ExtraInfo bit field.
+ Extra_HasSideEffects = 1,
+ Extra_IsAlignStack = 2,
+ Extra_AsmDialect = 4,
+
+ // Inline asm operands map to multiple SDNode / MachineInstr operands.
+ // The first operand is an immediate describing the asm operand, the low
+ // bits is the kind:
+ Kind_RegUse = 1, // Input register, "r".
+ Kind_RegDef = 2, // Output register, "=r".
+ Kind_RegDefEarlyClobber = 3, // Early-clobber output register, "=&r".
+ Kind_Clobber = 4, // Clobbered register, "~r".
+ Kind_Imm = 5, // Immediate.
+ Kind_Mem = 6, // Memory operand, "m".
+
+ Flag_MatchingOperand = 0x80000000
+ };
+
+ static unsigned getFlagWord(unsigned Kind, unsigned NumOps) {
+ assert(((NumOps << 3) & ~0xffff) == 0 && "Too many inline asm operands!");
+ assert(Kind >= Kind_RegUse && Kind <= Kind_Mem && "Invalid Kind");
+ return Kind | (NumOps << 3);
+ }
+
+ /// getFlagWordForMatchingOp - Augment an existing flag word returned by
+ /// getFlagWord with information indicating that this input operand is tied
+ /// to a previous output operand.
+ static unsigned getFlagWordForMatchingOp(unsigned InputFlag,
+ unsigned MatchedOperandNo) {
+ assert(MatchedOperandNo <= 0x7fff && "Too big matched operand");
+ assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
+ return InputFlag | Flag_MatchingOperand | (MatchedOperandNo << 16);
+ }
+
+ /// getFlagWordForRegClass - Augment an existing flag word returned by
+ /// getFlagWord with the required register class for the following register
+ /// operands.
+ /// A tied use operand cannot have a register class, use the register class
+ /// from the def operand instead.
+ static unsigned getFlagWordForRegClass(unsigned InputFlag, unsigned RC) {
+ // Store RC + 1, reserve the value 0 to mean 'no register class'.
+ ++RC;
+ assert(RC <= 0x7fff && "Too large register class ID");
+ assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
+ return InputFlag | (RC << 16);
+ }
+
+ static unsigned getKind(unsigned Flags) {
+ return Flags & 7;
+ }
+
+ static bool isRegDefKind(unsigned Flag){ return getKind(Flag) == Kind_RegDef;}
+ static bool isImmKind(unsigned Flag) { return getKind(Flag) == Kind_Imm; }
+ static bool isMemKind(unsigned Flag) { return getKind(Flag) == Kind_Mem; }
+ static bool isRegDefEarlyClobberKind(unsigned Flag) {
+ return getKind(Flag) == Kind_RegDefEarlyClobber;
+ }
+ static bool isClobberKind(unsigned Flag) {
+ return getKind(Flag) == Kind_Clobber;
+ }
+
+ /// getNumOperandRegisters - Extract the number of registers field from the
+ /// inline asm operand flag.
+ static unsigned getNumOperandRegisters(unsigned Flag) {
+ return (Flag & 0xffff) >> 3;
+ }
+
+ /// isUseOperandTiedToDef - Return true if the flag of the inline asm
+ /// operand indicates it is an use operand that's matched to a def operand.
+ static bool isUseOperandTiedToDef(unsigned Flag, unsigned &Idx) {
+ if ((Flag & Flag_MatchingOperand) == 0)
+ return false;
+ Idx = (Flag & ~Flag_MatchingOperand) >> 16;
+ return true;
+ }
+
+ /// hasRegClassConstraint - Returns true if the flag contains a register
+ /// class constraint. Sets RC to the register class ID.
+ static bool hasRegClassConstraint(unsigned Flag, unsigned &RC) {
+ if (Flag & Flag_MatchingOperand)
+ return false;
+ unsigned High = Flag >> 16;
+ // getFlagWordForRegClass() uses 0 to mean no register class, and otherwise
+ // stores RC + 1.
+ if (!High)
+ return false;
+ RC = High - 1;
+ return true;
+ }
+
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/InstrTypes.h b/include/llvm/InstrTypes.h
new file mode 100644
index 00000000000..99f4ea6c53e
--- /dev/null
+++ b/include/llvm/InstrTypes.h
@@ -0,0 +1,854 @@
+//===-- llvm/InstrTypes.h - Important Instruction subclasses ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines various meta classes of instructions that exist in the VM
+// representation. Specific concrete subclasses of these may be found in the
+// i*.h files...
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INSTRUCTION_TYPES_H
+#define LLVM_INSTRUCTION_TYPES_H
+
+#include "llvm/Instruction.h"
+#include "llvm/OperandTraits.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/ADT/Twine.h"
+
+namespace llvm {
+
+class LLVMContext;
+
+//===----------------------------------------------------------------------===//
+// TerminatorInst Class
+//===----------------------------------------------------------------------===//
+
+/// TerminatorInst - Subclasses of this class are all able to terminate a basic
+/// block. Thus, these are all the flow control type of operations.
+///
+class TerminatorInst : public Instruction {
+protected:
+ TerminatorInst(Type *Ty, Instruction::TermOps iType,
+ Use *Ops, unsigned NumOps,
+ Instruction *InsertBefore = 0)
+ : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {}
+
+ TerminatorInst(Type *Ty, Instruction::TermOps iType,
+ Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd)
+ : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {}
+
+ // Out of line virtual method, so the vtable, etc has a home.
+ ~TerminatorInst();
+
+ /// Virtual methods - Terminators should overload these and provide inline
+ /// overrides of non-V methods.
+ virtual BasicBlock *getSuccessorV(unsigned idx) const = 0;
+ virtual unsigned getNumSuccessorsV() const = 0;
+ virtual void setSuccessorV(unsigned idx, BasicBlock *B) = 0;
+ virtual TerminatorInst *clone_impl() const = 0;
+public:
+
+ /// getNumSuccessors - Return the number of successors that this terminator
+ /// has.
+ unsigned getNumSuccessors() const {
+ return getNumSuccessorsV();
+ }
+
+ /// getSuccessor - Return the specified successor.
+ ///
+ BasicBlock *getSuccessor(unsigned idx) const {
+ return getSuccessorV(idx);
+ }
+
+ /// setSuccessor - Update the specified successor to point at the provided
+ /// block.
+ void setSuccessor(unsigned idx, BasicBlock *B) {
+ setSuccessorV(idx, B);
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const TerminatorInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->isTerminator();
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+
+//===----------------------------------------------------------------------===//
+// UnaryInstruction Class
+//===----------------------------------------------------------------------===//
+
+class UnaryInstruction : public Instruction {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+
+protected:
+ UnaryInstruction(Type *Ty, unsigned iType, Value *V,
+ Instruction *IB = 0)
+ : Instruction(Ty, iType, &Op<0>(), 1, IB) {
+ Op<0>() = V;
+ }
+ UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE)
+ : Instruction(Ty, iType, &Op<0>(), 1, IAE) {
+ Op<0>() = V;
+ }
+public:
+ // allocate space for exactly one operand
+ void *operator new(size_t s) {
+ return User::operator new(s, 1);
+ }
+
+ // Out of line virtual method, so the vtable, etc has a home.
+ ~UnaryInstruction();
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const UnaryInstruction *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Alloca ||
+ I->getOpcode() == Instruction::Load ||
+ I->getOpcode() == Instruction::VAArg ||
+ I->getOpcode() == Instruction::ExtractValue ||
+ (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<UnaryInstruction> :
+ public FixedNumOperandTraits<UnaryInstruction, 1> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
+
+//===----------------------------------------------------------------------===//
+// BinaryOperator Class
+//===----------------------------------------------------------------------===//
+
+class BinaryOperator : public Instruction {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+protected:
+ void init(BinaryOps iType);
+ BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
+ const Twine &Name, Instruction *InsertBefore);
+ BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
+ const Twine &Name, BasicBlock *InsertAtEnd);
+ virtual BinaryOperator *clone_impl() const;
+public:
+ // allocate space for exactly two operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 2);
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// Create() - Construct a binary instruction, given the opcode and the two
+ /// operands. Optionally (if InstBefore is specified) insert the instruction
+ /// into a BasicBlock right before the specified instruction. The specified
+ /// Instruction is allowed to be a dereferenced end iterator.
+ ///
+ static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
+ const Twine &Name = Twine(),
+ Instruction *InsertBefore = 0);
+
+ /// Create() - Construct a binary instruction, given the opcode and the two
+ /// operands. Also automatically insert this instruction to the end of the
+ /// BasicBlock specified.
+ ///
+ static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
+ const Twine &Name, BasicBlock *InsertAtEnd);
+
+ /// Create* - These methods just forward to Create, and are useful when you
+ /// statically know what type of instruction you're going to create. These
+ /// helpers just save some typing.
+#define HANDLE_BINARY_INST(N, OPC, CLASS) \
+ static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
+ const Twine &Name = "") {\
+ return Create(Instruction::OPC, V1, V2, Name);\
+ }
+#include "llvm/Instruction.def"
+#define HANDLE_BINARY_INST(N, OPC, CLASS) \
+ static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
+ const Twine &Name, BasicBlock *BB) {\
+ return Create(Instruction::OPC, V1, V2, Name, BB);\
+ }
+#include "llvm/Instruction.def"
+#define HANDLE_BINARY_INST(N, OPC, CLASS) \
+ static BinaryOperator *Create##OPC(Value *V1, Value *V2, \
+ const Twine &Name, Instruction *I) {\
+ return Create(Instruction::OPC, V1, V2, Name, I);\
+ }
+#include "llvm/Instruction.def"
+
+ static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name = "") {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name);
+ BO->setHasNoSignedWrap(true);
+ return BO;
+ }
+ static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name, BasicBlock *BB) {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
+ BO->setHasNoSignedWrap(true);
+ return BO;
+ }
+ static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name, Instruction *I) {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
+ BO->setHasNoSignedWrap(true);
+ return BO;
+ }
+
+ static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name = "") {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name);
+ BO->setHasNoUnsignedWrap(true);
+ return BO;
+ }
+ static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name, BasicBlock *BB) {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
+ BO->setHasNoUnsignedWrap(true);
+ return BO;
+ }
+ static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name, Instruction *I) {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
+ BO->setHasNoUnsignedWrap(true);
+ return BO;
+ }
+
+ static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name = "") {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name);
+ BO->setIsExact(true);
+ return BO;
+ }
+ static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name, BasicBlock *BB) {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name, BB);
+ BO->setIsExact(true);
+ return BO;
+ }
+ static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
+ const Twine &Name, Instruction *I) {
+ BinaryOperator *BO = Create(Opc, V1, V2, Name, I);
+ BO->setIsExact(true);
+ return BO;
+ }
+
+#define DEFINE_HELPERS(OPC, NUWNSWEXACT) \
+ static BinaryOperator *Create ## NUWNSWEXACT ## OPC \
+ (Value *V1, Value *V2, const Twine &Name = "") { \
+ return Create ## NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \
+ } \
+ static BinaryOperator *Create ## NUWNSWEXACT ## OPC \
+ (Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \
+ return Create ## NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \
+ } \
+ static BinaryOperator *Create ## NUWNSWEXACT ## OPC \
+ (Value *V1, Value *V2, const Twine &Name, Instruction *I) { \
+ return Create ## NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \
+ }
+
+ DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
+ DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
+ DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
+ DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
+ DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
+ DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
+ DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
+ DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
+
+ DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv
+ DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv
+ DEFINE_HELPERS(AShr, Exact) // CreateExactAShr
+ DEFINE_HELPERS(LShr, Exact) // CreateExactLShr
+
+#undef DEFINE_HELPERS
+
+ /// Helper functions to construct and inspect unary operations (NEG and NOT)
+ /// via binary operators SUB and XOR:
+ ///
+ /// CreateNeg, CreateNot - Create the NEG and NOT
+ /// instructions out of SUB and XOR instructions.
+ ///
+ static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
+ Instruction *InsertBefore = 0);
+ static BinaryOperator *CreateNeg(Value *Op, const Twine &Name,
+ BasicBlock *InsertAtEnd);
+ static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
+ Instruction *InsertBefore = 0);
+ static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name,
+ BasicBlock *InsertAtEnd);
+ static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "",
+ Instruction *InsertBefore = 0);
+ static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name,
+ BasicBlock *InsertAtEnd);
+ static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "",
+ Instruction *InsertBefore = 0);
+ static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name,
+ BasicBlock *InsertAtEnd);
+ static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
+ Instruction *InsertBefore = 0);
+ static BinaryOperator *CreateNot(Value *Op, const Twine &Name,
+ BasicBlock *InsertAtEnd);
+
+ /// isNeg, isFNeg, isNot - Check if the given Value is a
+ /// NEG, FNeg, or NOT instruction.
+ ///
+ static bool isNeg(const Value *V);
+ static bool isFNeg(const Value *V);
+ static bool isNot(const Value *V);
+
+ /// getNegArgument, getNotArgument - Helper functions to extract the
+ /// unary argument of a NEG, FNEG or NOT operation implemented via
+ /// Sub, FSub, or Xor.
+ ///
+ static const Value *getNegArgument(const Value *BinOp);
+ static Value *getNegArgument( Value *BinOp);
+ static const Value *getFNegArgument(const Value *BinOp);
+ static Value *getFNegArgument( Value *BinOp);
+ static const Value *getNotArgument(const Value *BinOp);
+ static Value *getNotArgument( Value *BinOp);
+
+ BinaryOps getOpcode() const {
+ return static_cast<BinaryOps>(Instruction::getOpcode());
+ }
+
+ /// swapOperands - Exchange the two operands to this instruction.
+ /// This instruction is safe to use on any binary instruction and
+ /// does not modify the semantics of the instruction. If the instruction
+ /// cannot be reversed (ie, it's a Div), then return true.
+ ///
+ bool swapOperands();
+
+ /// setHasNoUnsignedWrap - Set or clear the nsw flag on this instruction,
+ /// which must be an operator which supports this flag. See LangRef.html
+ /// for the meaning of this flag.
+ void setHasNoUnsignedWrap(bool b = true);
+
+ /// setHasNoSignedWrap - Set or clear the nsw flag on this instruction,
+ /// which must be an operator which supports this flag. See LangRef.html
+ /// for the meaning of this flag.
+ void setHasNoSignedWrap(bool b = true);
+
+ /// setIsExact - Set or clear the exact flag on this instruction,
+ /// which must be an operator which supports this flag. See LangRef.html
+ /// for the meaning of this flag.
+ void setIsExact(bool b = true);
+
+ /// hasNoUnsignedWrap - Determine whether the no unsigned wrap flag is set.
+ bool hasNoUnsignedWrap() const;
+
+ /// hasNoSignedWrap - Determine whether the no signed wrap flag is set.
+ bool hasNoSignedWrap() const;
+
+ /// isExact - Determine whether the exact flag is set.
+ bool isExact() const;
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const BinaryOperator *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->isBinaryOp();
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<BinaryOperator> :
+ public FixedNumOperandTraits<BinaryOperator, 2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
+
+//===----------------------------------------------------------------------===//
+// CastInst Class
+//===----------------------------------------------------------------------===//
+
+/// CastInst - This is the base class for all instructions that perform data
+/// casts. It is simply provided so that instruction category testing
+/// can be performed with code like:
+///
+/// if (isa<CastInst>(Instr)) { ... }
+/// @brief Base class of casting instructions.
+class CastInst : public UnaryInstruction {
+ virtual void anchor();
+protected:
+ /// @brief Constructor with insert-before-instruction semantics for subclasses
+ CastInst(Type *Ty, unsigned iType, Value *S,
+ const Twine &NameStr = "", Instruction *InsertBefore = 0)
+ : UnaryInstruction(Ty, iType, S, InsertBefore) {
+ setName(NameStr);
+ }
+ /// @brief Constructor with insert-at-end-of-block semantics for subclasses
+ CastInst(Type *Ty, unsigned iType, Value *S,
+ const Twine &NameStr, BasicBlock *InsertAtEnd)
+ : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
+ setName(NameStr);
+ }
+public:
+ /// Provides a way to construct any of the CastInst subclasses using an
+ /// opcode instead of the subclass's constructor. The opcode must be in the
+ /// CastOps category (Instruction::isCast(opcode) returns true). This
+ /// constructor has insert-before-instruction semantics to automatically
+ /// insert the new CastInst before InsertBefore (if it is non-null).
+ /// @brief Construct any of the CastInst subclasses
+ static CastInst *Create(
+ Instruction::CastOps, ///< The opcode of the cast instruction
+ Value *S, ///< The value to be casted (operand 0)
+ Type *Ty, ///< The type to which cast should be made
+ const Twine &Name = "", ///< Name for the instruction
+ Instruction *InsertBefore = 0 ///< Place to insert the instruction
+ );
+ /// Provides a way to construct any of the CastInst subclasses using an
+ /// opcode instead of the subclass's constructor. The opcode must be in the
+ /// CastOps category. This constructor has insert-at-end-of-block semantics
+ /// to automatically insert the new CastInst at the end of InsertAtEnd (if
+ /// its non-null).
+ /// @brief Construct any of the CastInst subclasses
+ static CastInst *Create(
+ Instruction::CastOps, ///< The opcode for the cast instruction
+ Value *S, ///< The value to be casted (operand 0)
+ Type *Ty, ///< The type to which operand is casted
+ const Twine &Name, ///< The name for the instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Create a ZExt or BitCast cast instruction
+ static CastInst *CreateZExtOrBitCast(
+ Value *S, ///< The value to be casted (operand 0)
+ Type *Ty, ///< The type to which cast should be made
+ const Twine &Name = "", ///< Name for the instruction
+ Instruction *InsertBefore = 0 ///< Place to insert the instruction
+ );
+
+ /// @brief Create a ZExt or BitCast cast instruction
+ static CastInst *CreateZExtOrBitCast(
+ Value *S, ///< The value to be casted (operand 0)
+ Type *Ty, ///< The type to which operand is casted
+ const Twine &Name, ///< The name for the instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Create a SExt or BitCast cast instruction
+ static CastInst *CreateSExtOrBitCast(
+ Value *S, ///< The value to be casted (operand 0)
+ Type *Ty, ///< The type to which cast should be made
+ const Twine &Name = "", ///< Name for the instruction
+ Instruction *InsertBefore = 0 ///< Place to insert the instruction
+ );
+
+ /// @brief Create a SExt or BitCast cast instruction
+ static CastInst *CreateSExtOrBitCast(
+ Value *S, ///< The value to be casted (operand 0)
+ Type *Ty, ///< The type to which operand is casted
+ const Twine &Name, ///< The name for the instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Create a BitCast or a PtrToInt cast instruction
+ static CastInst *CreatePointerCast(
+ Value *S, ///< The pointer value to be casted (operand 0)
+ Type *Ty, ///< The type to which operand is casted
+ const Twine &Name, ///< The name for the instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Create a BitCast or a PtrToInt cast instruction
+ static CastInst *CreatePointerCast(
+ Value *S, ///< The pointer value to be casted (operand 0)
+ Type *Ty, ///< The type to which cast should be made
+ const Twine &Name = "", ///< Name for the instruction
+ Instruction *InsertBefore = 0 ///< Place to insert the instruction
+ );
+
+ /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
+ static CastInst *CreateIntegerCast(
+ Value *S, ///< The pointer value to be casted (operand 0)
+ Type *Ty, ///< The type to which cast should be made
+ bool isSigned, ///< Whether to regard S as signed or not
+ const Twine &Name = "", ///< Name for the instruction
+ Instruction *InsertBefore = 0 ///< Place to insert the instruction
+ );
+
+ /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts.
+ static CastInst *CreateIntegerCast(
+ Value *S, ///< The integer value to be casted (operand 0)
+ Type *Ty, ///< The integer type to which operand is casted
+ bool isSigned, ///< Whether to regard S as signed or not
+ const Twine &Name, ///< The name for the instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
+ static CastInst *CreateFPCast(
+ Value *S, ///< The floating point value to be casted
+ Type *Ty, ///< The floating point type to cast to
+ const Twine &Name = "", ///< Name for the instruction
+ Instruction *InsertBefore = 0 ///< Place to insert the instruction
+ );
+
+ /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
+ static CastInst *CreateFPCast(
+ Value *S, ///< The floating point value to be casted
+ Type *Ty, ///< The floating point type to cast to
+ const Twine &Name, ///< The name for the instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Create a Trunc or BitCast cast instruction
+ static CastInst *CreateTruncOrBitCast(
+ Value *S, ///< The value to be casted (operand 0)
+ Type *Ty, ///< The type to which cast should be made
+ const Twine &Name = "", ///< Name for the instruction
+ Instruction *InsertBefore = 0 ///< Place to insert the instruction
+ );
+
+ /// @brief Create a Trunc or BitCast cast instruction
+ static CastInst *CreateTruncOrBitCast(
+ Value *S, ///< The value to be casted (operand 0)
+ Type *Ty, ///< The type to which operand is casted
+ const Twine &Name, ///< The name for the instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Check whether it is valid to call getCastOpcode for these types.
+ static bool isCastable(
+ Type *SrcTy, ///< The Type from which the value should be cast.
+ Type *DestTy ///< The Type to which the value should be cast.
+ );
+
+ /// Returns the opcode necessary to cast Val into Ty using usual casting
+ /// rules.
+ /// @brief Infer the opcode for cast operand and type
+ static Instruction::CastOps getCastOpcode(
+ const Value *Val, ///< The value to cast
+ bool SrcIsSigned, ///< Whether to treat the source as signed
+ Type *Ty, ///< The Type to which the value should be casted
+ bool DstIsSigned ///< Whether to treate the dest. as signed
+ );
+
+ /// There are several places where we need to know if a cast instruction
+ /// only deals with integer source and destination types. To simplify that
+ /// logic, this method is provided.
+ /// @returns true iff the cast has only integral typed operand and dest type.
+ /// @brief Determine if this is an integer-only cast.
+ bool isIntegerCast() const;
+
+ /// A lossless cast is one that does not alter the basic value. It implies
+ /// a no-op cast but is more stringent, preventing things like int->float,
+ /// long->double, or int->ptr.
+ /// @returns true iff the cast is lossless.
+ /// @brief Determine if this is a lossless cast.
+ bool isLosslessCast() const;
+
+ /// A no-op cast is one that can be effected without changing any bits.
+ /// It implies that the source and destination types are the same size. The
+ /// IntPtrTy argument is used to make accurate determinations for casts
+ /// involving Integer and Pointer types. They are no-op casts if the integer
+ /// is the same size as the pointer. However, pointer size varies with
+ /// platform. Generally, the result of TargetData::getIntPtrType() should be
+ /// passed in. If that's not available, use Type::Int64Ty, which will make
+ /// the isNoopCast call conservative.
+ /// @brief Determine if the described cast is a no-op cast.
+ static bool isNoopCast(
+ Instruction::CastOps Opcode, ///< Opcode of cast
+ Type *SrcTy, ///< SrcTy of cast
+ Type *DstTy, ///< DstTy of cast
+ Type *IntPtrTy ///< Integer type corresponding to Ptr types, or null
+ );
+
+ /// @brief Determine if this cast is a no-op cast.
+ bool isNoopCast(
+ Type *IntPtrTy ///< Integer type corresponding to pointer
+ ) const;
+
+ /// Determine how a pair of casts can be eliminated, if they can be at all.
+ /// This is a helper function for both CastInst and ConstantExpr.
+ /// @returns 0 if the CastInst pair can't be eliminated, otherwise
+ /// returns Instruction::CastOps value for a cast that can replace
+ /// the pair, casting SrcTy to DstTy.
+ /// @brief Determine if a cast pair is eliminable
+ static unsigned isEliminableCastPair(
+ Instruction::CastOps firstOpcode, ///< Opcode of first cast
+ Instruction::CastOps secondOpcode, ///< Opcode of second cast
+ Type *SrcTy, ///< SrcTy of 1st cast
+ Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
+ Type *DstTy, ///< DstTy of 2nd cast
+ Type *IntPtrTy ///< Integer type corresponding to Ptr types, or null
+ );
+
+ /// @brief Return the opcode of this CastInst
+ Instruction::CastOps getOpcode() const {
+ return Instruction::CastOps(Instruction::getOpcode());
+ }
+
+ /// @brief Return the source type, as a convenience
+ Type* getSrcTy() const { return getOperand(0)->getType(); }
+ /// @brief Return the destination type, as a convenience
+ Type* getDestTy() const { return getType(); }
+
+ /// This method can be used to determine if a cast from S to DstTy using
+ /// Opcode op is valid or not.
+ /// @returns true iff the proposed cast is valid.
+ /// @brief Determine if a cast is valid without creating one.
+ static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy);
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const CastInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->isCast();
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// CmpInst Class
+//===----------------------------------------------------------------------===//
+
+/// This class is the base class for the comparison instructions.
+/// @brief Abstract base class of comparison instructions.
+class CmpInst : public Instruction {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ CmpInst() LLVM_DELETED_FUNCTION;
+protected:
+ CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
+ Value *LHS, Value *RHS, const Twine &Name = "",
+ Instruction *InsertBefore = 0);
+
+ CmpInst(Type *ty, Instruction::OtherOps op, unsigned short pred,
+ Value *LHS, Value *RHS, const Twine &Name,
+ BasicBlock *InsertAtEnd);
+
+ virtual void Anchor() const; // Out of line virtual method.
+public:
+ /// This enumeration lists the possible predicates for CmpInst subclasses.
+ /// Values in the range 0-31 are reserved for FCmpInst, while values in the
+ /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
+ /// predicate values are not overlapping between the classes.
+ enum Predicate {
+ // Opcode U L G E Intuitive operation
+ FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded)
+ FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal
+ FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than
+ FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal
+ FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than
+ FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal
+ FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal
+ FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans)
+ FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y)
+ FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal
+ FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than
+ FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal
+ FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than
+ FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal
+ FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal
+ FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded)
+ FIRST_FCMP_PREDICATE = FCMP_FALSE,
+ LAST_FCMP_PREDICATE = FCMP_TRUE,
+ BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
+ ICMP_EQ = 32, ///< equal
+ ICMP_NE = 33, ///< not equal
+ ICMP_UGT = 34, ///< unsigned greater than
+ ICMP_UGE = 35, ///< unsigned greater or equal
+ ICMP_ULT = 36, ///< unsigned less than
+ ICMP_ULE = 37, ///< unsigned less or equal
+ ICMP_SGT = 38, ///< signed greater than
+ ICMP_SGE = 39, ///< signed greater or equal
+ ICMP_SLT = 40, ///< signed less than
+ ICMP_SLE = 41, ///< signed less or equal
+ FIRST_ICMP_PREDICATE = ICMP_EQ,
+ LAST_ICMP_PREDICATE = ICMP_SLE,
+ BAD_ICMP_PREDICATE = ICMP_SLE + 1
+ };
+
+ // allocate space for exactly two operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 2);
+ }
+ /// Construct a compare instruction, given the opcode, the predicate and
+ /// the two operands. Optionally (if InstBefore is specified) insert the
+ /// instruction into a BasicBlock right before the specified instruction.
+ /// The specified Instruction is allowed to be a dereferenced end iterator.
+ /// @brief Create a CmpInst
+ static CmpInst *Create(OtherOps Op,
+ unsigned short predicate, Value *S1,
+ Value *S2, const Twine &Name = "",
+ Instruction *InsertBefore = 0);
+
+ /// Construct a compare instruction, given the opcode, the predicate and the
+ /// two operands. Also automatically insert this instruction to the end of
+ /// the BasicBlock specified.
+ /// @brief Create a CmpInst
+ static CmpInst *Create(OtherOps Op, unsigned short predicate, Value *S1,
+ Value *S2, const Twine &Name, BasicBlock *InsertAtEnd);
+
+ /// @brief Get the opcode casted to the right type
+ OtherOps getOpcode() const {
+ return static_cast<OtherOps>(Instruction::getOpcode());
+ }
+
+ /// @brief Return the predicate for this instruction.
+ Predicate getPredicate() const {
+ return Predicate(getSubclassDataFromInstruction());
+ }
+
+ /// @brief Set the predicate for this instruction to the specified value.
+ void setPredicate(Predicate P) { setInstructionSubclassData(P); }
+
+ static bool isFPPredicate(Predicate P) {
+ return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE;
+ }
+
+ static bool isIntPredicate(Predicate P) {
+ return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
+ }
+
+ bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
+ bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
+
+
+ /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
+ /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
+ /// @returns the inverse predicate for the instruction's current predicate.
+ /// @brief Return the inverse of the instruction's predicate.
+ Predicate getInversePredicate() const {
+ return getInversePredicate(getPredicate());
+ }
+
+ /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
+ /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
+ /// @returns the inverse predicate for predicate provided in \p pred.
+ /// @brief Return the inverse of a given predicate
+ static Predicate getInversePredicate(Predicate pred);
+
+ /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
+ /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
+ /// @returns the predicate that would be the result of exchanging the two
+ /// operands of the CmpInst instruction without changing the result
+ /// produced.
+ /// @brief Return the predicate as if the operands were swapped
+ Predicate getSwappedPredicate() const {
+ return getSwappedPredicate(getPredicate());
+ }
+
+ /// This is a static version that you can use without an instruction
+ /// available.
+ /// @brief Return the predicate as if the operands were swapped.
+ static Predicate getSwappedPredicate(Predicate pred);
+
+ /// @brief Provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// This is just a convenience that dispatches to the subclasses.
+ /// @brief Swap the operands and adjust predicate accordingly to retain
+ /// the same comparison.
+ void swapOperands();
+
+ /// This is just a convenience that dispatches to the subclasses.
+ /// @brief Determine if this CmpInst is commutative.
+ bool isCommutative() const;
+
+ /// This is just a convenience that dispatches to the subclasses.
+ /// @brief Determine if this is an equals/not equals predicate.
+ bool isEquality() const;
+
+ /// @returns true if the comparison is signed, false otherwise.
+ /// @brief Determine if this instruction is using a signed comparison.
+ bool isSigned() const {
+ return isSigned(getPredicate());
+ }
+
+ /// @returns true if the comparison is unsigned, false otherwise.
+ /// @brief Determine if this instruction is using an unsigned comparison.
+ bool isUnsigned() const {
+ return isUnsigned(getPredicate());
+ }
+
+ /// This is just a convenience.
+ /// @brief Determine if this is true when both operands are the same.
+ bool isTrueWhenEqual() const {
+ return isTrueWhenEqual(getPredicate());
+ }
+
+ /// This is just a convenience.
+ /// @brief Determine if this is false when both operands are the same.
+ bool isFalseWhenEqual() const {
+ return isFalseWhenEqual(getPredicate());
+ }
+
+ /// @returns true if the predicate is unsigned, false otherwise.
+ /// @brief Determine if the predicate is an unsigned operation.
+ static bool isUnsigned(unsigned short predicate);
+
+ /// @returns true if the predicate is signed, false otherwise.
+ /// @brief Determine if the predicate is an signed operation.
+ static bool isSigned(unsigned short predicate);
+
+ /// @brief Determine if the predicate is an ordered operation.
+ static bool isOrdered(unsigned short predicate);
+
+ /// @brief Determine if the predicate is an unordered operation.
+ static bool isUnordered(unsigned short predicate);
+
+ /// Determine if the predicate is true when comparing a value with itself.
+ static bool isTrueWhenEqual(unsigned short predicate);
+
+ /// Determine if the predicate is false when comparing a value with itself.
+ static bool isFalseWhenEqual(unsigned short predicate);
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const CmpInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::ICmp ||
+ I->getOpcode() == Instruction::FCmp;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+
+ /// @brief Create a result type for fcmp/icmp
+ static Type* makeCmpResultType(Type* opnd_type) {
+ if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
+ return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
+ vt->getNumElements());
+ }
+ return Type::getInt1Ty(opnd_type->getContext());
+ }
+private:
+ // Shadow Value::setValueSubclassData with a private forwarding method so that
+ // subclasses cannot accidentally use it.
+ void setValueSubclassData(unsigned short D) {
+ Value::setValueSubclassData(D);
+ }
+};
+
+
+// FIXME: these are redundant if CmpInst < BinaryOperator
+template <>
+struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Instruction.def b/include/llvm/Instruction.def
new file mode 100644
index 00000000000..e59a0528e90
--- /dev/null
+++ b/include/llvm/Instruction.def
@@ -0,0 +1,199 @@
+//===-- llvm/Instruction.def - File that describes Instructions -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains descriptions of the various LLVM instructions. This is
+// used as a central place for enumerating the different instructions and
+// should eventually be the place to put comments about the instructions.
+//
+//===----------------------------------------------------------------------===//
+
+// NOTE: NO INCLUDE GUARD DESIRED!
+
+// Provide definitions of macros so that users of this file do not have to
+// define everything to use it...
+//
+#ifndef FIRST_TERM_INST
+#define FIRST_TERM_INST(num)
+#endif
+#ifndef HANDLE_TERM_INST
+#ifndef HANDLE_INST
+#define HANDLE_TERM_INST(num, opcode, Class)
+#else
+#define HANDLE_TERM_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
+#endif
+#endif
+#ifndef LAST_TERM_INST
+#define LAST_TERM_INST(num)
+#endif
+
+#ifndef FIRST_BINARY_INST
+#define FIRST_BINARY_INST(num)
+#endif
+#ifndef HANDLE_BINARY_INST
+#ifndef HANDLE_INST
+#define HANDLE_BINARY_INST(num, opcode, instclass)
+#else
+#define HANDLE_BINARY_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
+#endif
+#endif
+#ifndef LAST_BINARY_INST
+#define LAST_BINARY_INST(num)
+#endif
+
+#ifndef FIRST_MEMORY_INST
+#define FIRST_MEMORY_INST(num)
+#endif
+#ifndef HANDLE_MEMORY_INST
+#ifndef HANDLE_INST
+#define HANDLE_MEMORY_INST(num, opcode, Class)
+#else
+#define HANDLE_MEMORY_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
+#endif
+#endif
+#ifndef LAST_MEMORY_INST
+#define LAST_MEMORY_INST(num)
+#endif
+
+#ifndef FIRST_CAST_INST
+#define FIRST_CAST_INST(num)
+#endif
+#ifndef HANDLE_CAST_INST
+#ifndef HANDLE_INST
+#define HANDLE_CAST_INST(num, opcode, Class)
+#else
+#define HANDLE_CAST_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
+#endif
+#endif
+#ifndef LAST_CAST_INST
+#define LAST_CAST_INST(num)
+#endif
+
+#ifndef FIRST_OTHER_INST
+#define FIRST_OTHER_INST(num)
+#endif
+#ifndef HANDLE_OTHER_INST
+#ifndef HANDLE_INST
+#define HANDLE_OTHER_INST(num, opcode, Class)
+#else
+#define HANDLE_OTHER_INST(num, opcode, Class) HANDLE_INST(num, opcode, Class)
+#endif
+#endif
+#ifndef LAST_OTHER_INST
+#define LAST_OTHER_INST(num)
+#endif
+
+
+// Terminator Instructions - These instructions are used to terminate a basic
+// block of the program. Every basic block must end with one of these
+// instructions for it to be a well formed basic block.
+//
+ FIRST_TERM_INST ( 1)
+HANDLE_TERM_INST ( 1, Ret , ReturnInst)
+HANDLE_TERM_INST ( 2, Br , BranchInst)
+HANDLE_TERM_INST ( 3, Switch , SwitchInst)
+HANDLE_TERM_INST ( 4, IndirectBr , IndirectBrInst)
+HANDLE_TERM_INST ( 5, Invoke , InvokeInst)
+HANDLE_TERM_INST ( 6, Resume , ResumeInst)
+HANDLE_TERM_INST ( 7, Unreachable, UnreachableInst)
+ LAST_TERM_INST ( 7)
+
+// Standard binary operators...
+ FIRST_BINARY_INST( 8)
+HANDLE_BINARY_INST( 8, Add , BinaryOperator)
+HANDLE_BINARY_INST( 9, FAdd , BinaryOperator)
+HANDLE_BINARY_INST(10, Sub , BinaryOperator)
+HANDLE_BINARY_INST(11, FSub , BinaryOperator)
+HANDLE_BINARY_INST(12, Mul , BinaryOperator)
+HANDLE_BINARY_INST(13, FMul , BinaryOperator)
+HANDLE_BINARY_INST(14, UDiv , BinaryOperator)
+HANDLE_BINARY_INST(15, SDiv , BinaryOperator)
+HANDLE_BINARY_INST(16, FDiv , BinaryOperator)
+HANDLE_BINARY_INST(17, URem , BinaryOperator)
+HANDLE_BINARY_INST(18, SRem , BinaryOperator)
+HANDLE_BINARY_INST(19, FRem , BinaryOperator)
+
+// Logical operators (integer operands)
+HANDLE_BINARY_INST(20, Shl , BinaryOperator) // Shift left (logical)
+HANDLE_BINARY_INST(21, LShr , BinaryOperator) // Shift right (logical)
+HANDLE_BINARY_INST(22, AShr , BinaryOperator) // Shift right (arithmetic)
+HANDLE_BINARY_INST(23, And , BinaryOperator)
+HANDLE_BINARY_INST(24, Or , BinaryOperator)
+HANDLE_BINARY_INST(25, Xor , BinaryOperator)
+ LAST_BINARY_INST(25)
+
+// Memory operators...
+ FIRST_MEMORY_INST(26)
+HANDLE_MEMORY_INST(26, Alloca, AllocaInst) // Stack management
+HANDLE_MEMORY_INST(27, Load , LoadInst ) // Memory manipulation instrs
+HANDLE_MEMORY_INST(28, Store , StoreInst )
+HANDLE_MEMORY_INST(29, GetElementPtr, GetElementPtrInst)
+HANDLE_MEMORY_INST(30, Fence , FenceInst )
+HANDLE_MEMORY_INST(31, AtomicCmpXchg , AtomicCmpXchgInst )
+HANDLE_MEMORY_INST(32, AtomicRMW , AtomicRMWInst )
+ LAST_MEMORY_INST(32)
+
+// Cast operators ...
+// NOTE: The order matters here because CastInst::isEliminableCastPair
+// NOTE: (see Instructions.cpp) encodes a table based on this ordering.
+ FIRST_CAST_INST(33)
+HANDLE_CAST_INST(33, Trunc , TruncInst ) // Truncate integers
+HANDLE_CAST_INST(34, ZExt , ZExtInst ) // Zero extend integers
+HANDLE_CAST_INST(35, SExt , SExtInst ) // Sign extend integers
+HANDLE_CAST_INST(36, FPToUI , FPToUIInst ) // floating point -> UInt
+HANDLE_CAST_INST(37, FPToSI , FPToSIInst ) // floating point -> SInt
+HANDLE_CAST_INST(38, UIToFP , UIToFPInst ) // UInt -> floating point
+HANDLE_CAST_INST(39, SIToFP , SIToFPInst ) // SInt -> floating point
+HANDLE_CAST_INST(40, FPTrunc , FPTruncInst ) // Truncate floating point
+HANDLE_CAST_INST(41, FPExt , FPExtInst ) // Extend floating point
+HANDLE_CAST_INST(42, PtrToInt, PtrToIntInst) // Pointer -> Integer
+HANDLE_CAST_INST(43, IntToPtr, IntToPtrInst) // Integer -> Pointer
+HANDLE_CAST_INST(44, BitCast , BitCastInst ) // Type cast
+ LAST_CAST_INST(44)
+
+// Other operators...
+ FIRST_OTHER_INST(45)
+HANDLE_OTHER_INST(45, ICmp , ICmpInst ) // Integer comparison instruction
+HANDLE_OTHER_INST(46, FCmp , FCmpInst ) // Floating point comparison instr.
+HANDLE_OTHER_INST(47, PHI , PHINode ) // PHI node instruction
+HANDLE_OTHER_INST(48, Call , CallInst ) // Call a function
+HANDLE_OTHER_INST(49, Select , SelectInst ) // select instruction
+HANDLE_OTHER_INST(50, UserOp1, Instruction) // May be used internally in a pass
+HANDLE_OTHER_INST(51, UserOp2, Instruction) // Internal to passes only
+HANDLE_OTHER_INST(52, VAArg , VAArgInst ) // vaarg instruction
+HANDLE_OTHER_INST(53, ExtractElement, ExtractElementInst)// extract from vector
+HANDLE_OTHER_INST(54, InsertElement, InsertElementInst) // insert into vector
+HANDLE_OTHER_INST(55, ShuffleVector, ShuffleVectorInst) // shuffle two vectors.
+HANDLE_OTHER_INST(56, ExtractValue, ExtractValueInst)// extract from aggregate
+HANDLE_OTHER_INST(57, InsertValue, InsertValueInst) // insert into aggregate
+HANDLE_OTHER_INST(58, LandingPad, LandingPadInst) // Landing pad instruction.
+ LAST_OTHER_INST(58)
+
+#undef FIRST_TERM_INST
+#undef HANDLE_TERM_INST
+#undef LAST_TERM_INST
+
+#undef FIRST_BINARY_INST
+#undef HANDLE_BINARY_INST
+#undef LAST_BINARY_INST
+
+#undef FIRST_MEMORY_INST
+#undef HANDLE_MEMORY_INST
+#undef LAST_MEMORY_INST
+
+#undef FIRST_CAST_INST
+#undef HANDLE_CAST_INST
+#undef LAST_CAST_INST
+
+#undef FIRST_OTHER_INST
+#undef HANDLE_OTHER_INST
+#undef LAST_OTHER_INST
+
+#ifdef HANDLE_INST
+#undef HANDLE_INST
+#endif
diff --git a/include/llvm/Instruction.h b/include/llvm/Instruction.h
new file mode 100644
index 00000000000..c85eda28f42
--- /dev/null
+++ b/include/llvm/Instruction.h
@@ -0,0 +1,408 @@
+//===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the Instruction class, which is the
+// base class for all of the LLVM instructions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INSTRUCTION_H
+#define LLVM_INSTRUCTION_H
+
+#include "llvm/User.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/Support/DebugLoc.h"
+
+namespace llvm {
+
+class LLVMContext;
+class MDNode;
+
+template<typename ValueSubClass, typename ItemParentClass>
+ class SymbolTableListTraits;
+
+class Instruction : public User, public ilist_node<Instruction> {
+ void operator=(const Instruction &) LLVM_DELETED_FUNCTION;
+ Instruction(const Instruction &) LLVM_DELETED_FUNCTION;
+
+ BasicBlock *Parent;
+ DebugLoc DbgLoc; // 'dbg' Metadata cache.
+
+ enum {
+ /// HasMetadataBit - This is a bit stored in the SubClassData field which
+ /// indicates whether this instruction has metadata attached to it or not.
+ HasMetadataBit = 1 << 15
+ };
+public:
+ // Out of line virtual method, so the vtable, etc has a home.
+ ~Instruction();
+
+ /// use_back - Specialize the methods defined in Value, as we know that an
+ /// instruction can only be used by other instructions.
+ Instruction *use_back() { return cast<Instruction>(*use_begin());}
+ const Instruction *use_back() const { return cast<Instruction>(*use_begin());}
+
+ inline const BasicBlock *getParent() const { return Parent; }
+ inline BasicBlock *getParent() { return Parent; }
+
+ /// removeFromParent - This method unlinks 'this' from the containing basic
+ /// block, but does not delete it.
+ ///
+ void removeFromParent();
+
+ /// eraseFromParent - This method unlinks 'this' from the containing basic
+ /// block and deletes it.
+ ///
+ void eraseFromParent();
+
+ /// insertBefore - Insert an unlinked instructions into a basic block
+ /// immediately before the specified instruction.
+ void insertBefore(Instruction *InsertPos);
+
+ /// insertAfter - Insert an unlinked instructions into a basic block
+ /// immediately after the specified instruction.
+ void insertAfter(Instruction *InsertPos);
+
+ /// moveBefore - Unlink this instruction from its current basic block and
+ /// insert it into the basic block that MovePos lives in, right before
+ /// MovePos.
+ void moveBefore(Instruction *MovePos);
+
+ //===--------------------------------------------------------------------===//
+ // Subclass classification.
+ //===--------------------------------------------------------------------===//
+
+ /// getOpcode() returns a member of one of the enums like Instruction::Add.
+ unsigned getOpcode() const { return getValueID() - InstructionVal; }
+
+ const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
+ bool isTerminator() const { return isTerminator(getOpcode()); }
+ bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
+ bool isShift() { return isShift(getOpcode()); }
+ bool isCast() const { return isCast(getOpcode()); }
+
+ static const char* getOpcodeName(unsigned OpCode);
+
+ static inline bool isTerminator(unsigned OpCode) {
+ return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
+ }
+
+ static inline bool isBinaryOp(unsigned Opcode) {
+ return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
+ }
+
+ /// @brief Determine if the Opcode is one of the shift instructions.
+ static inline bool isShift(unsigned Opcode) {
+ return Opcode >= Shl && Opcode <= AShr;
+ }
+
+ /// isLogicalShift - Return true if this is a logical shift left or a logical
+ /// shift right.
+ inline bool isLogicalShift() const {
+ return getOpcode() == Shl || getOpcode() == LShr;
+ }
+
+ /// isArithmeticShift - Return true if this is an arithmetic shift right.
+ inline bool isArithmeticShift() const {
+ return getOpcode() == AShr;
+ }
+
+ /// @brief Determine if the OpCode is one of the CastInst instructions.
+ static inline bool isCast(unsigned OpCode) {
+ return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Metadata manipulation.
+ //===--------------------------------------------------------------------===//
+
+ /// hasMetadata() - Return true if this instruction has any metadata attached
+ /// to it.
+ bool hasMetadata() const {
+ return !DbgLoc.isUnknown() || hasMetadataHashEntry();
+ }
+
+ /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
+ /// metadata attached to it other than a debug location.
+ bool hasMetadataOtherThanDebugLoc() const {
+ return hasMetadataHashEntry();
+ }
+
+ /// getMetadata - Get the metadata of given kind attached to this Instruction.
+ /// If the metadata is not found then return null.
+ MDNode *getMetadata(unsigned KindID) const {
+ if (!hasMetadata()) return 0;
+ return getMetadataImpl(KindID);
+ }
+
+ /// getMetadata - Get the metadata of given kind attached to this Instruction.
+ /// If the metadata is not found then return null.
+ MDNode *getMetadata(StringRef Kind) const {
+ if (!hasMetadata()) return 0;
+ return getMetadataImpl(Kind);
+ }
+
+ /// getAllMetadata - Get all metadata attached to this Instruction. The first
+ /// element of each pair returned is the KindID, the second element is the
+ /// metadata value. This list is returned sorted by the KindID.
+ void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
+ if (hasMetadata())
+ getAllMetadataImpl(MDs);
+ }
+
+ /// getAllMetadataOtherThanDebugLoc - This does the same thing as
+ /// getAllMetadata, except that it filters out the debug location.
+ void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
+ MDNode*> > &MDs) const {
+ if (hasMetadataOtherThanDebugLoc())
+ getAllMetadataOtherThanDebugLocImpl(MDs);
+ }
+
+ /// setMetadata - Set the metadata of the specified kind to the specified
+ /// node. This updates/replaces metadata if already present, or removes it if
+ /// Node is null.
+ void setMetadata(unsigned KindID, MDNode *Node);
+ void setMetadata(StringRef Kind, MDNode *Node);
+
+ /// setDebugLoc - Set the debug location information for this instruction.
+ void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
+
+ /// getDebugLoc - Return the debug location for this node as a DebugLoc.
+ const DebugLoc &getDebugLoc() const { return DbgLoc; }
+
+private:
+ /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
+ /// metadata hash.
+ bool hasMetadataHashEntry() const {
+ return (getSubclassDataFromValue() & HasMetadataBit) != 0;
+ }
+
+ // These are all implemented in Metadata.cpp.
+ MDNode *getMetadataImpl(unsigned KindID) const;
+ MDNode *getMetadataImpl(StringRef Kind) const;
+ void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
+ void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
+ MDNode*> > &) const;
+ void clearMetadataHashEntries();
+public:
+ //===--------------------------------------------------------------------===//
+ // Predicates and helper methods.
+ //===--------------------------------------------------------------------===//
+
+
+ /// isAssociative - Return true if the instruction is associative:
+ ///
+ /// Associative operators satisfy: x op (y op z) === (x op y) op z
+ ///
+ /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
+ ///
+ bool isAssociative() const { return isAssociative(getOpcode()); }
+ static bool isAssociative(unsigned op);
+
+ /// isCommutative - Return true if the instruction is commutative:
+ ///
+ /// Commutative operators satisfy: (x op y) === (y op x)
+ ///
+ /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
+ /// applied to any type.
+ ///
+ bool isCommutative() const { return isCommutative(getOpcode()); }
+ static bool isCommutative(unsigned op);
+
+ /// isIdempotent - Return true if the instruction is idempotent:
+ ///
+ /// Idempotent operators satisfy: x op x === x
+ ///
+ /// In LLVM, the And and Or operators are idempotent.
+ ///
+ bool isIdempotent() const { return isIdempotent(getOpcode()); }
+ static bool isIdempotent(unsigned op);
+
+ /// isNilpotent - Return true if the instruction is nilpotent:
+ ///
+ /// Nilpotent operators satisfy: x op x === Id,
+ ///
+ /// where Id is the identity for the operator, i.e. a constant such that
+ /// x op Id === x and Id op x === x for all x.
+ ///
+ /// In LLVM, the Xor operator is nilpotent.
+ ///
+ bool isNilpotent() const { return isNilpotent(getOpcode()); }
+ static bool isNilpotent(unsigned op);
+
+ /// mayWriteToMemory - Return true if this instruction may modify memory.
+ ///
+ bool mayWriteToMemory() const;
+
+ /// mayReadFromMemory - Return true if this instruction may read memory.
+ ///
+ bool mayReadFromMemory() const;
+
+ /// mayReadOrWriteMemory - Return true if this instruction may read or
+ /// write memory.
+ ///
+ bool mayReadOrWriteMemory() const {
+ return mayReadFromMemory() || mayWriteToMemory();
+ }
+
+ /// mayThrow - Return true if this instruction may throw an exception.
+ ///
+ bool mayThrow() const;
+
+ /// mayHaveSideEffects - Return true if the instruction may have side effects.
+ ///
+ /// Note that this does not consider malloc and alloca to have side
+ /// effects because the newly allocated memory is completely invisible to
+ /// instructions which don't used the returned value. For cases where this
+ /// matters, isSafeToSpeculativelyExecute may be more appropriate.
+ bool mayHaveSideEffects() const {
+ return mayWriteToMemory() || mayThrow();
+ }
+
+ /// clone() - Create a copy of 'this' instruction that is identical in all
+ /// ways except the following:
+ /// * The instruction has no parent
+ /// * The instruction has no name
+ ///
+ Instruction *clone() const;
+
+ /// isIdenticalTo - Return true if the specified instruction is exactly
+ /// identical to the current one. This means that all operands match and any
+ /// extra information (e.g. load is volatile) agree.
+ bool isIdenticalTo(const Instruction *I) const;
+
+ /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
+ /// ignores the SubclassOptionalData flags, which specify conditions
+ /// under which the instruction's result is undefined.
+ bool isIdenticalToWhenDefined(const Instruction *I) const;
+
+ /// When checking for operation equivalence (using isSameOperationAs) it is
+ /// sometimes useful to ignore certain attributes.
+ enum OperationEquivalenceFlags {
+ /// Check for equivalence ignoring load/store alignment.
+ CompareIgnoringAlignment = 1<<0,
+ /// Check for equivalence treating a type and a vector of that type
+ /// as equivalent.
+ CompareUsingScalarTypes = 1<<1
+ };
+
+ /// This function determines if the specified instruction executes the same
+ /// operation as the current one. This means that the opcodes, type, operand
+ /// types and any other factors affecting the operation must be the same. This
+ /// is similar to isIdenticalTo except the operands themselves don't have to
+ /// be identical.
+ /// @returns true if the specified instruction is the same operation as
+ /// the current one.
+ /// @brief Determine if one instruction is the same operation as another.
+ bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
+
+ /// isUsedOutsideOfBlock - Return true if there are any uses of this
+ /// instruction in blocks other than the specified block. Note that PHI nodes
+ /// are considered to evaluate their operands in the corresponding predecessor
+ /// block.
+ bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
+
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const Instruction *) { return true; }
+ static inline bool classof(const Value *V) {
+ return V->getValueID() >= Value::InstructionVal;
+ }
+
+ //----------------------------------------------------------------------
+ // Exported enumerations.
+ //
+ enum TermOps { // These terminate basic blocks
+#define FIRST_TERM_INST(N) TermOpsBegin = N,
+#define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
+#define LAST_TERM_INST(N) TermOpsEnd = N+1
+#include "llvm/Instruction.def"
+ };
+
+ enum BinaryOps {
+#define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
+#define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
+#define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
+#include "llvm/Instruction.def"
+ };
+
+ enum MemoryOps {
+#define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
+#define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
+#define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
+#include "llvm/Instruction.def"
+ };
+
+ enum CastOps {
+#define FIRST_CAST_INST(N) CastOpsBegin = N,
+#define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
+#define LAST_CAST_INST(N) CastOpsEnd = N+1
+#include "llvm/Instruction.def"
+ };
+
+ enum OtherOps {
+#define FIRST_OTHER_INST(N) OtherOpsBegin = N,
+#define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
+#define LAST_OTHER_INST(N) OtherOpsEnd = N+1
+#include "llvm/Instruction.def"
+ };
+private:
+ // Shadow Value::setValueSubclassData with a private forwarding method so that
+ // subclasses cannot accidentally use it.
+ void setValueSubclassData(unsigned short D) {
+ Value::setValueSubclassData(D);
+ }
+ unsigned short getSubclassDataFromValue() const {
+ return Value::getSubclassDataFromValue();
+ }
+
+ void setHasMetadataHashEntry(bool V) {
+ setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
+ (V ? HasMetadataBit : 0));
+ }
+
+ friend class SymbolTableListTraits<Instruction, BasicBlock>;
+ void setParent(BasicBlock *P);
+protected:
+ // Instruction subclasses can stick up to 15 bits of stuff into the
+ // SubclassData field of instruction with these members.
+
+ // Verify that only the low 15 bits are used.
+ void setInstructionSubclassData(unsigned short D) {
+ assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
+ setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
+ }
+
+ unsigned getSubclassDataFromInstruction() const {
+ return getSubclassDataFromValue() & ~HasMetadataBit;
+ }
+
+ Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
+ Instruction *InsertBefore = 0);
+ Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
+ BasicBlock *InsertAtEnd);
+ virtual Instruction *clone_impl() const = 0;
+
+};
+
+// Instruction* is only 4-byte aligned.
+template<>
+class PointerLikeTypeTraits<Instruction*> {
+ typedef Instruction* PT;
+public:
+ static inline void *getAsVoidPointer(PT P) { return P; }
+ static inline PT getFromVoidPointer(void *P) {
+ return static_cast<PT>(P);
+ }
+ enum { NumLowBitsAvailable = 2 };
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Instructions.h b/include/llvm/Instructions.h
new file mode 100644
index 00000000000..7a0379e371b
--- /dev/null
+++ b/include/llvm/Instructions.h
@@ -0,0 +1,3727 @@
+//===-- llvm/Instructions.h - Instruction subclass definitions --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file exposes the class definitions of all of the subclasses of the
+// Instruction class. This is meant to be an easy way to get access to all
+// instruction subclasses.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INSTRUCTIONS_H
+#define LLVM_INSTRUCTIONS_H
+
+#include "llvm/InstrTypes.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/Attributes.h"
+#include "llvm/CallingConv.h"
+#include "llvm/Support/IntegersSubset.h"
+#include "llvm/Support/IntegersSubsetMapping.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/ErrorHandling.h"
+#include <iterator>
+
+namespace llvm {
+
+class ConstantInt;
+class ConstantRange;
+class APInt;
+class LLVMContext;
+
+enum AtomicOrdering {
+ NotAtomic = 0,
+ Unordered = 1,
+ Monotonic = 2,
+ // Consume = 3, // Not specified yet.
+ Acquire = 4,
+ Release = 5,
+ AcquireRelease = 6,
+ SequentiallyConsistent = 7
+};
+
+enum SynchronizationScope {
+ SingleThread = 0,
+ CrossThread = 1
+};
+
+//===----------------------------------------------------------------------===//
+// AllocaInst Class
+//===----------------------------------------------------------------------===//
+
+/// AllocaInst - an instruction to allocate memory on the stack
+///
+class AllocaInst : public UnaryInstruction {
+protected:
+ virtual AllocaInst *clone_impl() const;
+public:
+ explicit AllocaInst(Type *Ty, Value *ArraySize = 0,
+ const Twine &Name = "", Instruction *InsertBefore = 0);
+ AllocaInst(Type *Ty, Value *ArraySize,
+ const Twine &Name, BasicBlock *InsertAtEnd);
+
+ AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore = 0);
+ AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd);
+
+ AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
+ const Twine &Name = "", Instruction *InsertBefore = 0);
+ AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
+ const Twine &Name, BasicBlock *InsertAtEnd);
+
+ // Out of line virtual method, so the vtable, etc. has a home.
+ virtual ~AllocaInst();
+
+ /// isArrayAllocation - Return true if there is an allocation size parameter
+ /// to the allocation instruction that is not 1.
+ ///
+ bool isArrayAllocation() const;
+
+ /// getArraySize - Get the number of elements allocated. For a simple
+ /// allocation of a single element, this will return a constant 1 value.
+ ///
+ const Value *getArraySize() const { return getOperand(0); }
+ Value *getArraySize() { return getOperand(0); }
+
+ /// getType - Overload to return most specific pointer type
+ ///
+ PointerType *getType() const {
+ return reinterpret_cast<PointerType*>(Instruction::getType());
+ }
+
+ /// getAllocatedType - Return the type that is being allocated by the
+ /// instruction.
+ ///
+ Type *getAllocatedType() const;
+
+ /// getAlignment - Return the alignment of the memory that is being allocated
+ /// by the instruction.
+ ///
+ unsigned getAlignment() const {
+ return (1u << getSubclassDataFromInstruction()) >> 1;
+ }
+ void setAlignment(unsigned Align);
+
+ /// isStaticAlloca - Return true if this alloca is in the entry block of the
+ /// function and is a constant size. If so, the code generator will fold it
+ /// into the prolog/epilog code, so it is basically free.
+ bool isStaticAlloca() const;
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const AllocaInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return (I->getOpcode() == Instruction::Alloca);
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ // Shadow Instruction::setInstructionSubclassData with a private forwarding
+ // method so that subclasses cannot accidentally use it.
+ void setInstructionSubclassData(unsigned short D) {
+ Instruction::setInstructionSubclassData(D);
+ }
+};
+
+
+//===----------------------------------------------------------------------===//
+// LoadInst Class
+//===----------------------------------------------------------------------===//
+
+/// LoadInst - an instruction for reading from memory. This uses the
+/// SubclassData field in Value to store whether or not the load is volatile.
+///
+class LoadInst : public UnaryInstruction {
+ void AssertOK();
+protected:
+ virtual LoadInst *clone_impl() const;
+public:
+ LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
+ LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
+ LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
+ Instruction *InsertBefore = 0);
+ LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
+ BasicBlock *InsertAtEnd);
+ LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
+ unsigned Align, Instruction *InsertBefore = 0);
+ LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
+ unsigned Align, BasicBlock *InsertAtEnd);
+ LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
+ unsigned Align, AtomicOrdering Order,
+ SynchronizationScope SynchScope = CrossThread,
+ Instruction *InsertBefore = 0);
+ LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
+ unsigned Align, AtomicOrdering Order,
+ SynchronizationScope SynchScope,
+ BasicBlock *InsertAtEnd);
+
+ LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
+ LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
+ explicit LoadInst(Value *Ptr, const char *NameStr = 0,
+ bool isVolatile = false, Instruction *InsertBefore = 0);
+ LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
+ BasicBlock *InsertAtEnd);
+
+ /// isVolatile - Return true if this is a load from a volatile memory
+ /// location.
+ ///
+ bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
+
+ /// setVolatile - Specify whether this is a volatile load or not.
+ ///
+ void setVolatile(bool V) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
+ (V ? 1 : 0));
+ }
+
+ /// getAlignment - Return the alignment of the access that is being performed
+ ///
+ unsigned getAlignment() const {
+ return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
+ }
+
+ void setAlignment(unsigned Align);
+
+ /// Returns the ordering effect of this fence.
+ AtomicOrdering getOrdering() const {
+ return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
+ }
+
+ /// Set the ordering constraint on this load. May not be Release or
+ /// AcquireRelease.
+ void setOrdering(AtomicOrdering Ordering) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
+ (Ordering << 7));
+ }
+
+ SynchronizationScope getSynchScope() const {
+ return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
+ }
+
+ /// Specify whether this load is ordered with respect to all
+ /// concurrently executing threads, or only with respect to signal handlers
+ /// executing in the same thread.
+ void setSynchScope(SynchronizationScope xthread) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
+ (xthread << 6));
+ }
+
+ bool isAtomic() const { return getOrdering() != NotAtomic; }
+ void setAtomic(AtomicOrdering Ordering,
+ SynchronizationScope SynchScope = CrossThread) {
+ setOrdering(Ordering);
+ setSynchScope(SynchScope);
+ }
+
+ bool isSimple() const { return !isAtomic() && !isVolatile(); }
+ bool isUnordered() const {
+ return getOrdering() <= Unordered && !isVolatile();
+ }
+
+ Value *getPointerOperand() { return getOperand(0); }
+ const Value *getPointerOperand() const { return getOperand(0); }
+ static unsigned getPointerOperandIndex() { return 0U; }
+
+ unsigned getPointerAddressSpace() const {
+ return cast<PointerType>(getPointerOperand()->getType())->getAddressSpace();
+ }
+
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const LoadInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Load;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ // Shadow Instruction::setInstructionSubclassData with a private forwarding
+ // method so that subclasses cannot accidentally use it.
+ void setInstructionSubclassData(unsigned short D) {
+ Instruction::setInstructionSubclassData(D);
+ }
+};
+
+
+//===----------------------------------------------------------------------===//
+// StoreInst Class
+//===----------------------------------------------------------------------===//
+
+/// StoreInst - an instruction for storing to memory
+///
+class StoreInst : public Instruction {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ void AssertOK();
+protected:
+ virtual StoreInst *clone_impl() const;
+public:
+ // allocate space for exactly two operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 2);
+ }
+ StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
+ StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
+ StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
+ Instruction *InsertBefore = 0);
+ StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
+ StoreInst(Value *Val, Value *Ptr, bool isVolatile,
+ unsigned Align, Instruction *InsertBefore = 0);
+ StoreInst(Value *Val, Value *Ptr, bool isVolatile,
+ unsigned Align, BasicBlock *InsertAtEnd);
+ StoreInst(Value *Val, Value *Ptr, bool isVolatile,
+ unsigned Align, AtomicOrdering Order,
+ SynchronizationScope SynchScope = CrossThread,
+ Instruction *InsertBefore = 0);
+ StoreInst(Value *Val, Value *Ptr, bool isVolatile,
+ unsigned Align, AtomicOrdering Order,
+ SynchronizationScope SynchScope,
+ BasicBlock *InsertAtEnd);
+
+
+ /// isVolatile - Return true if this is a store to a volatile memory
+ /// location.
+ ///
+ bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
+
+ /// setVolatile - Specify whether this is a volatile store or not.
+ ///
+ void setVolatile(bool V) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
+ (V ? 1 : 0));
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// getAlignment - Return the alignment of the access that is being performed
+ ///
+ unsigned getAlignment() const {
+ return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
+ }
+
+ void setAlignment(unsigned Align);
+
+ /// Returns the ordering effect of this store.
+ AtomicOrdering getOrdering() const {
+ return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
+ }
+
+ /// Set the ordering constraint on this store. May not be Acquire or
+ /// AcquireRelease.
+ void setOrdering(AtomicOrdering Ordering) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
+ (Ordering << 7));
+ }
+
+ SynchronizationScope getSynchScope() const {
+ return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
+ }
+
+ /// Specify whether this store instruction is ordered with respect to all
+ /// concurrently executing threads, or only with respect to signal handlers
+ /// executing in the same thread.
+ void setSynchScope(SynchronizationScope xthread) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
+ (xthread << 6));
+ }
+
+ bool isAtomic() const { return getOrdering() != NotAtomic; }
+ void setAtomic(AtomicOrdering Ordering,
+ SynchronizationScope SynchScope = CrossThread) {
+ setOrdering(Ordering);
+ setSynchScope(SynchScope);
+ }
+
+ bool isSimple() const { return !isAtomic() && !isVolatile(); }
+ bool isUnordered() const {
+ return getOrdering() <= Unordered && !isVolatile();
+ }
+
+ Value *getValueOperand() { return getOperand(0); }
+ const Value *getValueOperand() const { return getOperand(0); }
+
+ Value *getPointerOperand() { return getOperand(1); }
+ const Value *getPointerOperand() const { return getOperand(1); }
+ static unsigned getPointerOperandIndex() { return 1U; }
+
+ unsigned getPointerAddressSpace() const {
+ return cast<PointerType>(getPointerOperand()->getType())->getAddressSpace();
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const StoreInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Store;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ // Shadow Instruction::setInstructionSubclassData with a private forwarding
+ // method so that subclasses cannot accidentally use it.
+ void setInstructionSubclassData(unsigned short D) {
+ Instruction::setInstructionSubclassData(D);
+ }
+};
+
+template <>
+struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
+
+//===----------------------------------------------------------------------===//
+// FenceInst Class
+//===----------------------------------------------------------------------===//
+
+/// FenceInst - an instruction for ordering other memory operations
+///
+class FenceInst : public Instruction {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ void Init(AtomicOrdering Ordering, SynchronizationScope SynchScope);
+protected:
+ virtual FenceInst *clone_impl() const;
+public:
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+
+ // Ordering may only be Acquire, Release, AcquireRelease, or
+ // SequentiallyConsistent.
+ FenceInst(LLVMContext &C, AtomicOrdering Ordering,
+ SynchronizationScope SynchScope = CrossThread,
+ Instruction *InsertBefore = 0);
+ FenceInst(LLVMContext &C, AtomicOrdering Ordering,
+ SynchronizationScope SynchScope,
+ BasicBlock *InsertAtEnd);
+
+ /// Returns the ordering effect of this fence.
+ AtomicOrdering getOrdering() const {
+ return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
+ }
+
+ /// Set the ordering constraint on this fence. May only be Acquire, Release,
+ /// AcquireRelease, or SequentiallyConsistent.
+ void setOrdering(AtomicOrdering Ordering) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
+ (Ordering << 1));
+ }
+
+ SynchronizationScope getSynchScope() const {
+ return SynchronizationScope(getSubclassDataFromInstruction() & 1);
+ }
+
+ /// Specify whether this fence orders other operations with respect to all
+ /// concurrently executing threads, or only with respect to signal handlers
+ /// executing in the same thread.
+ void setSynchScope(SynchronizationScope xthread) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
+ xthread);
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const FenceInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Fence;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ // Shadow Instruction::setInstructionSubclassData with a private forwarding
+ // method so that subclasses cannot accidentally use it.
+ void setInstructionSubclassData(unsigned short D) {
+ Instruction::setInstructionSubclassData(D);
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// AtomicCmpXchgInst Class
+//===----------------------------------------------------------------------===//
+
+/// AtomicCmpXchgInst - an instruction that atomically checks whether a
+/// specified value is in a memory location, and, if it is, stores a new value
+/// there. Returns the value that was loaded.
+///
+class AtomicCmpXchgInst : public Instruction {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ void Init(Value *Ptr, Value *Cmp, Value *NewVal,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope);
+protected:
+ virtual AtomicCmpXchgInst *clone_impl() const;
+public:
+ // allocate space for exactly three operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 3);
+ }
+ AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope,
+ Instruction *InsertBefore = 0);
+ AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope,
+ BasicBlock *InsertAtEnd);
+
+ /// isVolatile - Return true if this is a cmpxchg from a volatile memory
+ /// location.
+ ///
+ bool isVolatile() const {
+ return getSubclassDataFromInstruction() & 1;
+ }
+
+ /// setVolatile - Specify whether this is a volatile cmpxchg.
+ ///
+ void setVolatile(bool V) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
+ (unsigned)V);
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// Set the ordering constraint on this cmpxchg.
+ void setOrdering(AtomicOrdering Ordering) {
+ assert(Ordering != NotAtomic &&
+ "CmpXchg instructions can only be atomic.");
+ setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
+ (Ordering << 2));
+ }
+
+ /// Specify whether this cmpxchg is atomic and orders other operations with
+ /// respect to all concurrently executing threads, or only with respect to
+ /// signal handlers executing in the same thread.
+ void setSynchScope(SynchronizationScope SynchScope) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
+ (SynchScope << 1));
+ }
+
+ /// Returns the ordering constraint on this cmpxchg.
+ AtomicOrdering getOrdering() const {
+ return AtomicOrdering(getSubclassDataFromInstruction() >> 2);
+ }
+
+ /// Returns whether this cmpxchg is atomic between threads or only within a
+ /// single thread.
+ SynchronizationScope getSynchScope() const {
+ return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
+ }
+
+ Value *getPointerOperand() { return getOperand(0); }
+ const Value *getPointerOperand() const { return getOperand(0); }
+ static unsigned getPointerOperandIndex() { return 0U; }
+
+ Value *getCompareOperand() { return getOperand(1); }
+ const Value *getCompareOperand() const { return getOperand(1); }
+
+ Value *getNewValOperand() { return getOperand(2); }
+ const Value *getNewValOperand() const { return getOperand(2); }
+
+ unsigned getPointerAddressSpace() const {
+ return cast<PointerType>(getPointerOperand()->getType())->getAddressSpace();
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const AtomicCmpXchgInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::AtomicCmpXchg;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ // Shadow Instruction::setInstructionSubclassData with a private forwarding
+ // method so that subclasses cannot accidentally use it.
+ void setInstructionSubclassData(unsigned short D) {
+ Instruction::setInstructionSubclassData(D);
+ }
+};
+
+template <>
+struct OperandTraits<AtomicCmpXchgInst> :
+ public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
+
+//===----------------------------------------------------------------------===//
+// AtomicRMWInst Class
+//===----------------------------------------------------------------------===//
+
+/// AtomicRMWInst - an instruction that atomically reads a memory location,
+/// combines it with another value, and then stores the result back. Returns
+/// the old value.
+///
+class AtomicRMWInst : public Instruction {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+protected:
+ virtual AtomicRMWInst *clone_impl() const;
+public:
+ /// This enumeration lists the possible modifications atomicrmw can make. In
+ /// the descriptions, 'p' is the pointer to the instruction's memory location,
+ /// 'old' is the initial value of *p, and 'v' is the other value passed to the
+ /// instruction. These instructions always return 'old'.
+ enum BinOp {
+ /// *p = v
+ Xchg,
+ /// *p = old + v
+ Add,
+ /// *p = old - v
+ Sub,
+ /// *p = old & v
+ And,
+ /// *p = ~old & v
+ Nand,
+ /// *p = old | v
+ Or,
+ /// *p = old ^ v
+ Xor,
+ /// *p = old >signed v ? old : v
+ Max,
+ /// *p = old <signed v ? old : v
+ Min,
+ /// *p = old >unsigned v ? old : v
+ UMax,
+ /// *p = old <unsigned v ? old : v
+ UMin,
+
+ FIRST_BINOP = Xchg,
+ LAST_BINOP = UMin,
+ BAD_BINOP
+ };
+
+ // allocate space for exactly two operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 2);
+ }
+ AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope,
+ Instruction *InsertBefore = 0);
+ AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope,
+ BasicBlock *InsertAtEnd);
+
+ BinOp getOperation() const {
+ return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
+ }
+
+ void setOperation(BinOp Operation) {
+ unsigned short SubclassData = getSubclassDataFromInstruction();
+ setInstructionSubclassData((SubclassData & 31) |
+ (Operation << 5));
+ }
+
+ /// isVolatile - Return true if this is a RMW on a volatile memory location.
+ ///
+ bool isVolatile() const {
+ return getSubclassDataFromInstruction() & 1;
+ }
+
+ /// setVolatile - Specify whether this is a volatile RMW or not.
+ ///
+ void setVolatile(bool V) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
+ (unsigned)V);
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// Set the ordering constraint on this RMW.
+ void setOrdering(AtomicOrdering Ordering) {
+ assert(Ordering != NotAtomic &&
+ "atomicrmw instructions can only be atomic.");
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
+ (Ordering << 2));
+ }
+
+ /// Specify whether this RMW orders other operations with respect to all
+ /// concurrently executing threads, or only with respect to signal handlers
+ /// executing in the same thread.
+ void setSynchScope(SynchronizationScope SynchScope) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
+ (SynchScope << 1));
+ }
+
+ /// Returns the ordering constraint on this RMW.
+ AtomicOrdering getOrdering() const {
+ return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
+ }
+
+ /// Returns whether this RMW is atomic between threads or only within a
+ /// single thread.
+ SynchronizationScope getSynchScope() const {
+ return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
+ }
+
+ Value *getPointerOperand() { return getOperand(0); }
+ const Value *getPointerOperand() const { return getOperand(0); }
+ static unsigned getPointerOperandIndex() { return 0U; }
+
+ Value *getValOperand() { return getOperand(1); }
+ const Value *getValOperand() const { return getOperand(1); }
+
+ unsigned getPointerAddressSpace() const {
+ return cast<PointerType>(getPointerOperand()->getType())->getAddressSpace();
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const AtomicRMWInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::AtomicRMW;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ void Init(BinOp Operation, Value *Ptr, Value *Val,
+ AtomicOrdering Ordering, SynchronizationScope SynchScope);
+ // Shadow Instruction::setInstructionSubclassData with a private forwarding
+ // method so that subclasses cannot accidentally use it.
+ void setInstructionSubclassData(unsigned short D) {
+ Instruction::setInstructionSubclassData(D);
+ }
+};
+
+template <>
+struct OperandTraits<AtomicRMWInst>
+ : public FixedNumOperandTraits<AtomicRMWInst,2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
+
+//===----------------------------------------------------------------------===//
+// GetElementPtrInst Class
+//===----------------------------------------------------------------------===//
+
+// checkGEPType - Simple wrapper function to give a better assertion failure
+// message on bad indexes for a gep instruction.
+//
+inline Type *checkGEPType(Type *Ty) {
+ assert(Ty && "Invalid GetElementPtrInst indices for type!");
+ return Ty;
+}
+
+/// GetElementPtrInst - an instruction for type-safe pointer arithmetic to
+/// access elements of arrays and structs
+///
+class GetElementPtrInst : public Instruction {
+ GetElementPtrInst(const GetElementPtrInst &GEPI);
+ void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
+
+ /// Constructors - Create a getelementptr instruction with a base pointer an
+ /// list of indices. The first ctor can optionally insert before an existing
+ /// instruction, the second appends the new instruction to the specified
+ /// BasicBlock.
+ inline GetElementPtrInst(Value *Ptr, ArrayRef<Value *> IdxList,
+ unsigned Values, const Twine &NameStr,
+ Instruction *InsertBefore);
+ inline GetElementPtrInst(Value *Ptr, ArrayRef<Value *> IdxList,
+ unsigned Values, const Twine &NameStr,
+ BasicBlock *InsertAtEnd);
+protected:
+ virtual GetElementPtrInst *clone_impl() const;
+public:
+ static GetElementPtrInst *Create(Value *Ptr, ArrayRef<Value *> IdxList,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ unsigned Values = 1 + unsigned(IdxList.size());
+ return new(Values)
+ GetElementPtrInst(Ptr, IdxList, Values, NameStr, InsertBefore);
+ }
+ static GetElementPtrInst *Create(Value *Ptr, ArrayRef<Value *> IdxList,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ unsigned Values = 1 + unsigned(IdxList.size());
+ return new(Values)
+ GetElementPtrInst(Ptr, IdxList, Values, NameStr, InsertAtEnd);
+ }
+
+ /// Create an "inbounds" getelementptr. See the documentation for the
+ /// "inbounds" flag in LangRef.html for details.
+ static GetElementPtrInst *CreateInBounds(Value *Ptr,
+ ArrayRef<Value *> IdxList,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ GetElementPtrInst *GEP = Create(Ptr, IdxList, NameStr, InsertBefore);
+ GEP->setIsInBounds(true);
+ return GEP;
+ }
+ static GetElementPtrInst *CreateInBounds(Value *Ptr,
+ ArrayRef<Value *> IdxList,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ GetElementPtrInst *GEP = Create(Ptr, IdxList, NameStr, InsertAtEnd);
+ GEP->setIsInBounds(true);
+ return GEP;
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ // getType - Overload to return most specific pointer type...
+ PointerType *getType() const {
+ return reinterpret_cast<PointerType*>(Instruction::getType());
+ }
+
+ /// getIndexedType - Returns the type of the element that would be loaded with
+ /// a load instruction with the specified parameters.
+ ///
+ /// Null is returned if the indices are invalid for the specified
+ /// pointer type.
+ ///
+ static Type *getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList);
+ static Type *getIndexedType(Type *Ptr, ArrayRef<Constant *> IdxList);
+ static Type *getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList);
+
+ /// getIndexedType - Returns the address space used by the GEP pointer.
+ ///
+ static unsigned getAddressSpace(Value *Ptr);
+
+ inline op_iterator idx_begin() { return op_begin()+1; }
+ inline const_op_iterator idx_begin() const { return op_begin()+1; }
+ inline op_iterator idx_end() { return op_end(); }
+ inline const_op_iterator idx_end() const { return op_end(); }
+
+ Value *getPointerOperand() {
+ return getOperand(0);
+ }
+ const Value *getPointerOperand() const {
+ return getOperand(0);
+ }
+ static unsigned getPointerOperandIndex() {
+ return 0U; // get index for modifying correct operand.
+ }
+
+ unsigned getPointerAddressSpace() const {
+ return cast<PointerType>(getType())->getAddressSpace();
+ }
+
+ /// getPointerOperandType - Method to return the pointer operand as a
+ /// PointerType.
+ Type *getPointerOperandType() const {
+ return getPointerOperand()->getType();
+ }
+
+ /// GetGEPReturnType - Returns the pointer type returned by the GEP
+ /// instruction, which may be a vector of pointers.
+ static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
+ Type *PtrTy = PointerType::get(checkGEPType(
+ getIndexedType(Ptr->getType(), IdxList)),
+ getAddressSpace(Ptr));
+ // Vector GEP
+ if (Ptr->getType()->isVectorTy()) {
+ unsigned NumElem = cast<VectorType>(Ptr->getType())->getNumElements();
+ return VectorType::get(PtrTy, NumElem);
+ }
+
+ // Scalar GEP
+ return PtrTy;
+ }
+
+ unsigned getNumIndices() const { // Note: always non-negative
+ return getNumOperands() - 1;
+ }
+
+ bool hasIndices() const {
+ return getNumOperands() > 1;
+ }
+
+ /// hasAllZeroIndices - Return true if all of the indices of this GEP are
+ /// zeros. If so, the result pointer and the first operand have the same
+ /// value, just potentially different types.
+ bool hasAllZeroIndices() const;
+
+ /// hasAllConstantIndices - Return true if all of the indices of this GEP are
+ /// constant integers. If so, the result pointer and the first operand have
+ /// a constant offset between them.
+ bool hasAllConstantIndices() const;
+
+ /// setIsInBounds - Set or clear the inbounds flag on this GEP instruction.
+ /// See LangRef.html for the meaning of inbounds on a getelementptr.
+ void setIsInBounds(bool b = true);
+
+ /// isInBounds - Determine whether the GEP has the inbounds flag.
+ bool isInBounds() const;
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const GetElementPtrInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return (I->getOpcode() == Instruction::GetElementPtr);
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<GetElementPtrInst> :
+ public VariadicOperandTraits<GetElementPtrInst, 1> {
+};
+
+GetElementPtrInst::GetElementPtrInst(Value *Ptr,
+ ArrayRef<Value *> IdxList,
+ unsigned Values,
+ const Twine &NameStr,
+ Instruction *InsertBefore)
+ : Instruction(getGEPReturnType(Ptr, IdxList),
+ GetElementPtr,
+ OperandTraits<GetElementPtrInst>::op_end(this) - Values,
+ Values, InsertBefore) {
+ init(Ptr, IdxList, NameStr);
+}
+GetElementPtrInst::GetElementPtrInst(Value *Ptr,
+ ArrayRef<Value *> IdxList,
+ unsigned Values,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd)
+ : Instruction(getGEPReturnType(Ptr, IdxList),
+ GetElementPtr,
+ OperandTraits<GetElementPtrInst>::op_end(this) - Values,
+ Values, InsertAtEnd) {
+ init(Ptr, IdxList, NameStr);
+}
+
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
+
+
+//===----------------------------------------------------------------------===//
+// ICmpInst Class
+//===----------------------------------------------------------------------===//
+
+/// This instruction compares its operands according to the predicate given
+/// to the constructor. It only operates on integers or pointers. The operands
+/// must be identical types.
+/// @brief Represent an integer comparison operator.
+class ICmpInst: public CmpInst {
+protected:
+ /// @brief Clone an identical ICmpInst
+ virtual ICmpInst *clone_impl() const;
+public:
+ /// @brief Constructor with insert-before-instruction semantics.
+ ICmpInst(
+ Instruction *InsertBefore, ///< Where to insert
+ Predicate pred, ///< The predicate to use for the comparison
+ Value *LHS, ///< The left-hand-side of the expression
+ Value *RHS, ///< The right-hand-side of the expression
+ const Twine &NameStr = "" ///< Name of the instruction
+ ) : CmpInst(makeCmpResultType(LHS->getType()),
+ Instruction::ICmp, pred, LHS, RHS, NameStr,
+ InsertBefore) {
+ assert(pred >= CmpInst::FIRST_ICMP_PREDICATE &&
+ pred <= CmpInst::LAST_ICMP_PREDICATE &&
+ "Invalid ICmp predicate value");
+ assert(getOperand(0)->getType() == getOperand(1)->getType() &&
+ "Both operands to ICmp instruction are not of the same type!");
+ // Check that the operands are the right type
+ assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
+ getOperand(0)->getType()->getScalarType()->isPointerTy()) &&
+ "Invalid operand types for ICmp instruction");
+ }
+
+ /// @brief Constructor with insert-at-end semantics.
+ ICmpInst(
+ BasicBlock &InsertAtEnd, ///< Block to insert into.
+ Predicate pred, ///< The predicate to use for the comparison
+ Value *LHS, ///< The left-hand-side of the expression
+ Value *RHS, ///< The right-hand-side of the expression
+ const Twine &NameStr = "" ///< Name of the instruction
+ ) : CmpInst(makeCmpResultType(LHS->getType()),
+ Instruction::ICmp, pred, LHS, RHS, NameStr,
+ &InsertAtEnd) {
+ assert(pred >= CmpInst::FIRST_ICMP_PREDICATE &&
+ pred <= CmpInst::LAST_ICMP_PREDICATE &&
+ "Invalid ICmp predicate value");
+ assert(getOperand(0)->getType() == getOperand(1)->getType() &&
+ "Both operands to ICmp instruction are not of the same type!");
+ // Check that the operands are the right type
+ assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
+ getOperand(0)->getType()->isPointerTy()) &&
+ "Invalid operand types for ICmp instruction");
+ }
+
+ /// @brief Constructor with no-insertion semantics
+ ICmpInst(
+ Predicate pred, ///< The predicate to use for the comparison
+ Value *LHS, ///< The left-hand-side of the expression
+ Value *RHS, ///< The right-hand-side of the expression
+ const Twine &NameStr = "" ///< Name of the instruction
+ ) : CmpInst(makeCmpResultType(LHS->getType()),
+ Instruction::ICmp, pred, LHS, RHS, NameStr) {
+ assert(pred >= CmpInst::FIRST_ICMP_PREDICATE &&
+ pred <= CmpInst::LAST_ICMP_PREDICATE &&
+ "Invalid ICmp predicate value");
+ assert(getOperand(0)->getType() == getOperand(1)->getType() &&
+ "Both operands to ICmp instruction are not of the same type!");
+ // Check that the operands are the right type
+ assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
+ getOperand(0)->getType()->getScalarType()->isPointerTy()) &&
+ "Invalid operand types for ICmp instruction");
+ }
+
+ /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
+ /// @returns the predicate that would be the result if the operand were
+ /// regarded as signed.
+ /// @brief Return the signed version of the predicate
+ Predicate getSignedPredicate() const {
+ return getSignedPredicate(getPredicate());
+ }
+
+ /// This is a static version that you can use without an instruction.
+ /// @brief Return the signed version of the predicate.
+ static Predicate getSignedPredicate(Predicate pred);
+
+ /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
+ /// @returns the predicate that would be the result if the operand were
+ /// regarded as unsigned.
+ /// @brief Return the unsigned version of the predicate
+ Predicate getUnsignedPredicate() const {
+ return getUnsignedPredicate(getPredicate());
+ }
+
+ /// This is a static version that you can use without an instruction.
+ /// @brief Return the unsigned version of the predicate.
+ static Predicate getUnsignedPredicate(Predicate pred);
+
+ /// isEquality - Return true if this predicate is either EQ or NE. This also
+ /// tests for commutativity.
+ static bool isEquality(Predicate P) {
+ return P == ICMP_EQ || P == ICMP_NE;
+ }
+
+ /// isEquality - Return true if this predicate is either EQ or NE. This also
+ /// tests for commutativity.
+ bool isEquality() const {
+ return isEquality(getPredicate());
+ }
+
+ /// @returns true if the predicate of this ICmpInst is commutative
+ /// @brief Determine if this relation is commutative.
+ bool isCommutative() const { return isEquality(); }
+
+ /// isRelational - Return true if the predicate is relational (not EQ or NE).
+ ///
+ bool isRelational() const {
+ return !isEquality();
+ }
+
+ /// isRelational - Return true if the predicate is relational (not EQ or NE).
+ ///
+ static bool isRelational(Predicate P) {
+ return !isEquality(P);
+ }
+
+ /// Initialize a set of values that all satisfy the predicate with C.
+ /// @brief Make a ConstantRange for a relation with a constant value.
+ static ConstantRange makeConstantRange(Predicate pred, const APInt &C);
+
+ /// Exchange the two operands to this instruction in such a way that it does
+ /// not modify the semantics of the instruction. The predicate value may be
+ /// changed to retain the same result if the predicate is order dependent
+ /// (e.g. ult).
+ /// @brief Swap operands and adjust predicate.
+ void swapOperands() {
+ setPredicate(getSwappedPredicate());
+ Op<0>().swap(Op<1>());
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ICmpInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::ICmp;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+
+};
+
+//===----------------------------------------------------------------------===//
+// FCmpInst Class
+//===----------------------------------------------------------------------===//
+
+/// This instruction compares its operands according to the predicate given
+/// to the constructor. It only operates on floating point values or packed
+/// vectors of floating point values. The operands must be identical types.
+/// @brief Represents a floating point comparison operator.
+class FCmpInst: public CmpInst {
+protected:
+ /// @brief Clone an identical FCmpInst
+ virtual FCmpInst *clone_impl() const;
+public:
+ /// @brief Constructor with insert-before-instruction semantics.
+ FCmpInst(
+ Instruction *InsertBefore, ///< Where to insert
+ Predicate pred, ///< The predicate to use for the comparison
+ Value *LHS, ///< The left-hand-side of the expression
+ Value *RHS, ///< The right-hand-side of the expression
+ const Twine &NameStr = "" ///< Name of the instruction
+ ) : CmpInst(makeCmpResultType(LHS->getType()),
+ Instruction::FCmp, pred, LHS, RHS, NameStr,
+ InsertBefore) {
+ assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
+ "Invalid FCmp predicate value");
+ assert(getOperand(0)->getType() == getOperand(1)->getType() &&
+ "Both operands to FCmp instruction are not of the same type!");
+ // Check that the operands are the right type
+ assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
+ "Invalid operand types for FCmp instruction");
+ }
+
+ /// @brief Constructor with insert-at-end semantics.
+ FCmpInst(
+ BasicBlock &InsertAtEnd, ///< Block to insert into.
+ Predicate pred, ///< The predicate to use for the comparison
+ Value *LHS, ///< The left-hand-side of the expression
+ Value *RHS, ///< The right-hand-side of the expression
+ const Twine &NameStr = "" ///< Name of the instruction
+ ) : CmpInst(makeCmpResultType(LHS->getType()),
+ Instruction::FCmp, pred, LHS, RHS, NameStr,
+ &InsertAtEnd) {
+ assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
+ "Invalid FCmp predicate value");
+ assert(getOperand(0)->getType() == getOperand(1)->getType() &&
+ "Both operands to FCmp instruction are not of the same type!");
+ // Check that the operands are the right type
+ assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
+ "Invalid operand types for FCmp instruction");
+ }
+
+ /// @brief Constructor with no-insertion semantics
+ FCmpInst(
+ Predicate pred, ///< The predicate to use for the comparison
+ Value *LHS, ///< The left-hand-side of the expression
+ Value *RHS, ///< The right-hand-side of the expression
+ const Twine &NameStr = "" ///< Name of the instruction
+ ) : CmpInst(makeCmpResultType(LHS->getType()),
+ Instruction::FCmp, pred, LHS, RHS, NameStr) {
+ assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
+ "Invalid FCmp predicate value");
+ assert(getOperand(0)->getType() == getOperand(1)->getType() &&
+ "Both operands to FCmp instruction are not of the same type!");
+ // Check that the operands are the right type
+ assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
+ "Invalid operand types for FCmp instruction");
+ }
+
+ /// @returns true if the predicate of this instruction is EQ or NE.
+ /// @brief Determine if this is an equality predicate.
+ bool isEquality() const {
+ return getPredicate() == FCMP_OEQ || getPredicate() == FCMP_ONE ||
+ getPredicate() == FCMP_UEQ || getPredicate() == FCMP_UNE;
+ }
+
+ /// @returns true if the predicate of this instruction is commutative.
+ /// @brief Determine if this is a commutative predicate.
+ bool isCommutative() const {
+ return isEquality() ||
+ getPredicate() == FCMP_FALSE ||
+ getPredicate() == FCMP_TRUE ||
+ getPredicate() == FCMP_ORD ||
+ getPredicate() == FCMP_UNO;
+ }
+
+ /// @returns true if the predicate is relational (not EQ or NE).
+ /// @brief Determine if this a relational predicate.
+ bool isRelational() const { return !isEquality(); }
+
+ /// Exchange the two operands to this instruction in such a way that it does
+ /// not modify the semantics of the instruction. The predicate value may be
+ /// changed to retain the same result if the predicate is order dependent
+ /// (e.g. ult).
+ /// @brief Swap operands and adjust predicate.
+ void swapOperands() {
+ setPredicate(getSwappedPredicate());
+ Op<0>().swap(Op<1>());
+ }
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const FCmpInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::FCmp;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// CallInst - This class represents a function call, abstracting a target
+/// machine's calling convention. This class uses low bit of the SubClassData
+/// field to indicate whether or not this is a tail call. The rest of the bits
+/// hold the calling convention of the call.
+///
+class CallInst : public Instruction {
+ AttrListPtr AttributeList; ///< parameter attributes for call
+ CallInst(const CallInst &CI);
+ void init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr);
+ void init(Value *Func, const Twine &NameStr);
+
+ /// Construct a CallInst given a range of arguments.
+ /// @brief Construct a CallInst from a range of arguments
+ inline CallInst(Value *Func, ArrayRef<Value *> Args,
+ const Twine &NameStr, Instruction *InsertBefore);
+
+ /// Construct a CallInst given a range of arguments.
+ /// @brief Construct a CallInst from a range of arguments
+ inline CallInst(Value *Func, ArrayRef<Value *> Args,
+ const Twine &NameStr, BasicBlock *InsertAtEnd);
+
+ CallInst(Value *F, Value *Actual, const Twine &NameStr,
+ Instruction *InsertBefore);
+ CallInst(Value *F, Value *Actual, const Twine &NameStr,
+ BasicBlock *InsertAtEnd);
+ explicit CallInst(Value *F, const Twine &NameStr,
+ Instruction *InsertBefore);
+ CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
+protected:
+ virtual CallInst *clone_impl() const;
+public:
+ static CallInst *Create(Value *Func,
+ ArrayRef<Value *> Args,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ return new(unsigned(Args.size() + 1))
+ CallInst(Func, Args, NameStr, InsertBefore);
+ }
+ static CallInst *Create(Value *Func,
+ ArrayRef<Value *> Args,
+ const Twine &NameStr, BasicBlock *InsertAtEnd) {
+ return new(unsigned(Args.size() + 1))
+ CallInst(Func, Args, NameStr, InsertAtEnd);
+ }
+ static CallInst *Create(Value *F, const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ return new(1) CallInst(F, NameStr, InsertBefore);
+ }
+ static CallInst *Create(Value *F, const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ return new(1) CallInst(F, NameStr, InsertAtEnd);
+ }
+ /// CreateMalloc - Generate the IR for a call to malloc:
+ /// 1. Compute the malloc call's argument as the specified type's size,
+ /// possibly multiplied by the array size if the array size is not
+ /// constant 1.
+ /// 2. Call malloc with that argument.
+ /// 3. Bitcast the result of the malloc call to the specified type.
+ static Instruction *CreateMalloc(Instruction *InsertBefore,
+ Type *IntPtrTy, Type *AllocTy,
+ Value *AllocSize, Value *ArraySize = 0,
+ Function* MallocF = 0,
+ const Twine &Name = "");
+ static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
+ Type *IntPtrTy, Type *AllocTy,
+ Value *AllocSize, Value *ArraySize = 0,
+ Function* MallocF = 0,
+ const Twine &Name = "");
+ /// CreateFree - Generate the IR for a call to the builtin free function.
+ static Instruction* CreateFree(Value* Source, Instruction *InsertBefore);
+ static Instruction* CreateFree(Value* Source, BasicBlock *InsertAtEnd);
+
+ ~CallInst();
+
+ bool isTailCall() const { return getSubclassDataFromInstruction() & 1; }
+ void setTailCall(bool isTC = true) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
+ unsigned(isTC));
+ }
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// getNumArgOperands - Return the number of call arguments.
+ ///
+ unsigned getNumArgOperands() const { return getNumOperands() - 1; }
+
+ /// getArgOperand/setArgOperand - Return/set the i-th call argument.
+ ///
+ Value *getArgOperand(unsigned i) const { return getOperand(i); }
+ void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
+
+ /// getCallingConv/setCallingConv - Get or set the calling convention of this
+ /// function call.
+ CallingConv::ID getCallingConv() const {
+ return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 1);
+ }
+ void setCallingConv(CallingConv::ID CC) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
+ (static_cast<unsigned>(CC) << 1));
+ }
+
+ /// getAttributes - Return the parameter attributes for this call.
+ ///
+ const AttrListPtr &getAttributes() const { return AttributeList; }
+
+ /// setAttributes - Set the parameter attributes for this call.
+ ///
+ void setAttributes(const AttrListPtr &Attrs) { AttributeList = Attrs; }
+
+ /// addAttribute - adds the attribute to the list of attributes.
+ void addAttribute(unsigned i, Attributes attr);
+
+ /// removeAttribute - removes the attribute from the list of attributes.
+ void removeAttribute(unsigned i, Attributes attr);
+
+ /// \brief Return true if this call has the given attribute.
+ bool hasFnAttr(Attributes N) const {
+ return paramHasAttr(~0, N);
+ }
+
+ /// @brief Determine whether the call or the callee has the given attribute.
+ bool paramHasAttr(unsigned i, Attributes attr) const;
+
+ /// @brief Extract the alignment for a call or parameter (0=unknown).
+ unsigned getParamAlignment(unsigned i) const {
+ return AttributeList.getParamAlignment(i);
+ }
+
+ /// @brief Return true if the call should not be inlined.
+ bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
+ void setIsNoInline(bool Value = true) {
+ if (Value) addAttribute(~0, Attribute::NoInline);
+ else removeAttribute(~0, Attribute::NoInline);
+ }
+
+ /// @brief Return true if the call can return twice
+ bool canReturnTwice() const {
+ return hasFnAttr(Attribute::ReturnsTwice);
+ }
+ void setCanReturnTwice(bool Value = true) {
+ if (Value) addAttribute(~0, Attribute::ReturnsTwice);
+ else removeAttribute(~0, Attribute::ReturnsTwice);
+ }
+
+ /// @brief Determine if the call does not access memory.
+ bool doesNotAccessMemory() const {
+ return hasFnAttr(Attribute::ReadNone);
+ }
+ void setDoesNotAccessMemory(bool NotAccessMemory = true) {
+ if (NotAccessMemory) addAttribute(~0, Attribute::ReadNone);
+ else removeAttribute(~0, Attribute::ReadNone);
+ }
+
+ /// @brief Determine if the call does not access or only reads memory.
+ bool onlyReadsMemory() const {
+ return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
+ }
+ void setOnlyReadsMemory(bool OnlyReadsMemory = true) {
+ if (OnlyReadsMemory) addAttribute(~0, Attribute::ReadOnly);
+ else removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
+ }
+
+ /// @brief Determine if the call cannot return.
+ bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
+ void setDoesNotReturn(bool DoesNotReturn = true) {
+ if (DoesNotReturn) addAttribute(~0, Attribute::NoReturn);
+ else removeAttribute(~0, Attribute::NoReturn);
+ }
+
+ /// @brief Determine if the call cannot unwind.
+ bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
+ void setDoesNotThrow(bool DoesNotThrow = true) {
+ if (DoesNotThrow) addAttribute(~0, Attribute::NoUnwind);
+ else removeAttribute(~0, Attribute::NoUnwind);
+ }
+
+ /// @brief Determine if the call returns a structure through first
+ /// pointer argument.
+ bool hasStructRetAttr() const {
+ // Be friendly and also check the callee.
+ return paramHasAttr(1, Attribute::StructRet);
+ }
+
+ /// @brief Determine if any call argument is an aggregate passed by value.
+ bool hasByValArgument() const {
+ return AttributeList.hasAttrSomewhere(Attribute::ByVal);
+ }
+
+ /// getCalledFunction - Return the function called, or null if this is an
+ /// indirect function invocation.
+ ///
+ Function *getCalledFunction() const {
+ return dyn_cast<Function>(Op<-1>());
+ }
+
+ /// getCalledValue - Get a pointer to the function that is invoked by this
+ /// instruction.
+ const Value *getCalledValue() const { return Op<-1>(); }
+ Value *getCalledValue() { return Op<-1>(); }
+
+ /// setCalledFunction - Set the function called.
+ void setCalledFunction(Value* Fn) {
+ Op<-1>() = Fn;
+ }
+
+ /// isInlineAsm - Check if this call is an inline asm statement.
+ bool isInlineAsm() const {
+ return isa<InlineAsm>(Op<-1>());
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const CallInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Call;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ // Shadow Instruction::setInstructionSubclassData with a private forwarding
+ // method so that subclasses cannot accidentally use it.
+ void setInstructionSubclassData(unsigned short D) {
+ Instruction::setInstructionSubclassData(D);
+ }
+};
+
+template <>
+struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
+};
+
+CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
+ const Twine &NameStr, BasicBlock *InsertAtEnd)
+ : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
+ ->getElementType())->getReturnType(),
+ Instruction::Call,
+ OperandTraits<CallInst>::op_end(this) - (Args.size() + 1),
+ unsigned(Args.size() + 1), InsertAtEnd) {
+ init(Func, Args, NameStr);
+}
+
+CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
+ const Twine &NameStr, Instruction *InsertBefore)
+ : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
+ ->getElementType())->getReturnType(),
+ Instruction::Call,
+ OperandTraits<CallInst>::op_end(this) - (Args.size() + 1),
+ unsigned(Args.size() + 1), InsertBefore) {
+ init(Func, Args, NameStr);
+}
+
+
+// Note: if you get compile errors about private methods then
+// please update your code to use the high-level operand
+// interfaces. See line 943 above.
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
+
+//===----------------------------------------------------------------------===//
+// SelectInst Class
+//===----------------------------------------------------------------------===//
+
+/// SelectInst - This class represents the LLVM 'select' instruction.
+///
+class SelectInst : public Instruction {
+ void init(Value *C, Value *S1, Value *S2) {
+ assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
+ Op<0>() = C;
+ Op<1>() = S1;
+ Op<2>() = S2;
+ }
+
+ SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
+ Instruction *InsertBefore)
+ : Instruction(S1->getType(), Instruction::Select,
+ &Op<0>(), 3, InsertBefore) {
+ init(C, S1, S2);
+ setName(NameStr);
+ }
+ SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
+ BasicBlock *InsertAtEnd)
+ : Instruction(S1->getType(), Instruction::Select,
+ &Op<0>(), 3, InsertAtEnd) {
+ init(C, S1, S2);
+ setName(NameStr);
+ }
+protected:
+ virtual SelectInst *clone_impl() const;
+public:
+ static SelectInst *Create(Value *C, Value *S1, Value *S2,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ return new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
+ }
+ static SelectInst *Create(Value *C, Value *S1, Value *S2,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
+ }
+
+ const Value *getCondition() const { return Op<0>(); }
+ const Value *getTrueValue() const { return Op<1>(); }
+ const Value *getFalseValue() const { return Op<2>(); }
+ Value *getCondition() { return Op<0>(); }
+ Value *getTrueValue() { return Op<1>(); }
+ Value *getFalseValue() { return Op<2>(); }
+
+ /// areInvalidOperands - Return a string if the specified operands are invalid
+ /// for a select operation, otherwise return null.
+ static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ OtherOps getOpcode() const {
+ return static_cast<OtherOps>(Instruction::getOpcode());
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SelectInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Select;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
+
+//===----------------------------------------------------------------------===//
+// VAArgInst Class
+//===----------------------------------------------------------------------===//
+
+/// VAArgInst - This class represents the va_arg llvm instruction, which returns
+/// an argument of the specified type given a va_list and increments that list
+///
+class VAArgInst : public UnaryInstruction {
+protected:
+ virtual VAArgInst *clone_impl() const;
+
+public:
+ VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
+ Instruction *InsertBefore = 0)
+ : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
+ setName(NameStr);
+ }
+ VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
+ BasicBlock *InsertAtEnd)
+ : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
+ setName(NameStr);
+ }
+
+ Value *getPointerOperand() { return getOperand(0); }
+ const Value *getPointerOperand() const { return getOperand(0); }
+ static unsigned getPointerOperandIndex() { return 0U; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const VAArgInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == VAArg;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// ExtractElementInst Class
+//===----------------------------------------------------------------------===//
+
+/// ExtractElementInst - This instruction extracts a single (scalar)
+/// element from a VectorType value
+///
+class ExtractElementInst : public Instruction {
+ ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
+ Instruction *InsertBefore = 0);
+ ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
+ BasicBlock *InsertAtEnd);
+protected:
+ virtual ExtractElementInst *clone_impl() const;
+
+public:
+ static ExtractElementInst *Create(Value *Vec, Value *Idx,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
+ }
+ static ExtractElementInst *Create(Value *Vec, Value *Idx,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
+ }
+
+ /// isValidOperands - Return true if an extractelement instruction can be
+ /// formed with the specified operands.
+ static bool isValidOperands(const Value *Vec, const Value *Idx);
+
+ Value *getVectorOperand() { return Op<0>(); }
+ Value *getIndexOperand() { return Op<1>(); }
+ const Value *getVectorOperand() const { return Op<0>(); }
+ const Value *getIndexOperand() const { return Op<1>(); }
+
+ VectorType *getVectorOperandType() const {
+ return reinterpret_cast<VectorType*>(getVectorOperand()->getType());
+ }
+
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ExtractElementInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::ExtractElement;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<ExtractElementInst> :
+ public FixedNumOperandTraits<ExtractElementInst, 2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
+
+//===----------------------------------------------------------------------===//
+// InsertElementInst Class
+//===----------------------------------------------------------------------===//
+
+/// InsertElementInst - This instruction inserts a single (scalar)
+/// element into a VectorType value
+///
+class InsertElementInst : public Instruction {
+ InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0);
+ InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
+ const Twine &NameStr, BasicBlock *InsertAtEnd);
+protected:
+ virtual InsertElementInst *clone_impl() const;
+
+public:
+ static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
+ }
+ static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
+ }
+
+ /// isValidOperands - Return true if an insertelement instruction can be
+ /// formed with the specified operands.
+ static bool isValidOperands(const Value *Vec, const Value *NewElt,
+ const Value *Idx);
+
+ /// getType - Overload to return most specific vector type.
+ ///
+ VectorType *getType() const {
+ return reinterpret_cast<VectorType*>(Instruction::getType());
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const InsertElementInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::InsertElement;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<InsertElementInst> :
+ public FixedNumOperandTraits<InsertElementInst, 3> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
+
+//===----------------------------------------------------------------------===//
+// ShuffleVectorInst Class
+//===----------------------------------------------------------------------===//
+
+/// ShuffleVectorInst - This instruction constructs a fixed permutation of two
+/// input vectors.
+///
+class ShuffleVectorInst : public Instruction {
+protected:
+ virtual ShuffleVectorInst *clone_impl() const;
+
+public:
+ // allocate space for exactly three operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 3);
+ }
+ ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
+ const Twine &NameStr = "",
+ Instruction *InsertBefor = 0);
+ ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
+ const Twine &NameStr, BasicBlock *InsertAtEnd);
+
+ /// isValidOperands - Return true if a shufflevector instruction can be
+ /// formed with the specified operands.
+ static bool isValidOperands(const Value *V1, const Value *V2,
+ const Value *Mask);
+
+ /// getType - Overload to return most specific vector type.
+ ///
+ VectorType *getType() const {
+ return reinterpret_cast<VectorType*>(Instruction::getType());
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ Constant *getMask() const {
+ return reinterpret_cast<Constant*>(getOperand(2));
+ }
+
+ /// getMaskValue - Return the index from the shuffle mask for the specified
+ /// output result. This is either -1 if the element is undef or a number less
+ /// than 2*numelements.
+ static int getMaskValue(Constant *Mask, unsigned i);
+
+ int getMaskValue(unsigned i) const {
+ return getMaskValue(getMask(), i);
+ }
+
+ /// getShuffleMask - Return the full mask for this instruction, where each
+ /// element is the element number and undef's are returned as -1.
+ static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
+
+ void getShuffleMask(SmallVectorImpl<int> &Result) const {
+ return getShuffleMask(getMask(), Result);
+ }
+
+ SmallVector<int, 16> getShuffleMask() const {
+ SmallVector<int, 16> Mask;
+ getShuffleMask(Mask);
+ return Mask;
+ }
+
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ShuffleVectorInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::ShuffleVector;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<ShuffleVectorInst> :
+ public FixedNumOperandTraits<ShuffleVectorInst, 3> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
+
+//===----------------------------------------------------------------------===//
+// ExtractValueInst Class
+//===----------------------------------------------------------------------===//
+
+/// ExtractValueInst - This instruction extracts a struct member or array
+/// element value from an aggregate value.
+///
+class ExtractValueInst : public UnaryInstruction {
+ SmallVector<unsigned, 4> Indices;
+
+ ExtractValueInst(const ExtractValueInst &EVI);
+ void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
+
+ /// Constructors - Create a extractvalue instruction with a base aggregate
+ /// value and a list of indices. The first ctor can optionally insert before
+ /// an existing instruction, the second appends the new instruction to the
+ /// specified BasicBlock.
+ inline ExtractValueInst(Value *Agg,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr,
+ Instruction *InsertBefore);
+ inline ExtractValueInst(Value *Agg,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr, BasicBlock *InsertAtEnd);
+
+ // allocate space for exactly one operand
+ void *operator new(size_t s) {
+ return User::operator new(s, 1);
+ }
+protected:
+ virtual ExtractValueInst *clone_impl() const;
+
+public:
+ static ExtractValueInst *Create(Value *Agg,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ return new
+ ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
+ }
+ static ExtractValueInst *Create(Value *Agg,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
+ }
+
+ /// getIndexedType - Returns the type of the element that would be extracted
+ /// with an extractvalue instruction with the specified parameters.
+ ///
+ /// Null is returned if the indices are invalid for the specified type.
+ static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
+
+ typedef const unsigned* idx_iterator;
+ inline idx_iterator idx_begin() const { return Indices.begin(); }
+ inline idx_iterator idx_end() const { return Indices.end(); }
+
+ Value *getAggregateOperand() {
+ return getOperand(0);
+ }
+ const Value *getAggregateOperand() const {
+ return getOperand(0);
+ }
+ static unsigned getAggregateOperandIndex() {
+ return 0U; // get index for modifying correct operand
+ }
+
+ ArrayRef<unsigned> getIndices() const {
+ return Indices;
+ }
+
+ unsigned getNumIndices() const {
+ return (unsigned)Indices.size();
+ }
+
+ bool hasIndices() const {
+ return true;
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ExtractValueInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::ExtractValue;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+ExtractValueInst::ExtractValueInst(Value *Agg,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr,
+ Instruction *InsertBefore)
+ : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
+ ExtractValue, Agg, InsertBefore) {
+ init(Idxs, NameStr);
+}
+ExtractValueInst::ExtractValueInst(Value *Agg,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd)
+ : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
+ ExtractValue, Agg, InsertAtEnd) {
+ init(Idxs, NameStr);
+}
+
+
+//===----------------------------------------------------------------------===//
+// InsertValueInst Class
+//===----------------------------------------------------------------------===//
+
+/// InsertValueInst - This instruction inserts a struct field of array element
+/// value into an aggregate value.
+///
+class InsertValueInst : public Instruction {
+ SmallVector<unsigned, 4> Indices;
+
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ InsertValueInst(const InsertValueInst &IVI);
+ void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
+ const Twine &NameStr);
+
+ /// Constructors - Create a insertvalue instruction with a base aggregate
+ /// value, a value to insert, and a list of indices. The first ctor can
+ /// optionally insert before an existing instruction, the second appends
+ /// the new instruction to the specified BasicBlock.
+ inline InsertValueInst(Value *Agg, Value *Val,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr,
+ Instruction *InsertBefore);
+ inline InsertValueInst(Value *Agg, Value *Val,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr, BasicBlock *InsertAtEnd);
+
+ /// Constructors - These two constructors are convenience methods because one
+ /// and two index insertvalue instructions are so common.
+ InsertValueInst(Value *Agg, Value *Val,
+ unsigned Idx, const Twine &NameStr = "",
+ Instruction *InsertBefore = 0);
+ InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
+ const Twine &NameStr, BasicBlock *InsertAtEnd);
+protected:
+ virtual InsertValueInst *clone_impl() const;
+public:
+ // allocate space for exactly two operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 2);
+ }
+
+ static InsertValueInst *Create(Value *Agg, Value *Val,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
+ }
+ static InsertValueInst *Create(Value *Agg, Value *Val,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ typedef const unsigned* idx_iterator;
+ inline idx_iterator idx_begin() const { return Indices.begin(); }
+ inline idx_iterator idx_end() const { return Indices.end(); }
+
+ Value *getAggregateOperand() {
+ return getOperand(0);
+ }
+ const Value *getAggregateOperand() const {
+ return getOperand(0);
+ }
+ static unsigned getAggregateOperandIndex() {
+ return 0U; // get index for modifying correct operand
+ }
+
+ Value *getInsertedValueOperand() {
+ return getOperand(1);
+ }
+ const Value *getInsertedValueOperand() const {
+ return getOperand(1);
+ }
+ static unsigned getInsertedValueOperandIndex() {
+ return 1U; // get index for modifying correct operand
+ }
+
+ ArrayRef<unsigned> getIndices() const {
+ return Indices;
+ }
+
+ unsigned getNumIndices() const {
+ return (unsigned)Indices.size();
+ }
+
+ bool hasIndices() const {
+ return true;
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const InsertValueInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::InsertValue;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<InsertValueInst> :
+ public FixedNumOperandTraits<InsertValueInst, 2> {
+};
+
+InsertValueInst::InsertValueInst(Value *Agg,
+ Value *Val,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr,
+ Instruction *InsertBefore)
+ : Instruction(Agg->getType(), InsertValue,
+ OperandTraits<InsertValueInst>::op_begin(this),
+ 2, InsertBefore) {
+ init(Agg, Val, Idxs, NameStr);
+}
+InsertValueInst::InsertValueInst(Value *Agg,
+ Value *Val,
+ ArrayRef<unsigned> Idxs,
+ const Twine &NameStr,
+ BasicBlock *InsertAtEnd)
+ : Instruction(Agg->getType(), InsertValue,
+ OperandTraits<InsertValueInst>::op_begin(this),
+ 2, InsertAtEnd) {
+ init(Agg, Val, Idxs, NameStr);
+}
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
+
+//===----------------------------------------------------------------------===//
+// PHINode Class
+//===----------------------------------------------------------------------===//
+
+// PHINode - The PHINode class is used to represent the magical mystical PHI
+// node, that can not exist in nature, but can be synthesized in a computer
+// scientist's overactive imagination.
+//
+class PHINode : public Instruction {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ /// ReservedSpace - The number of operands actually allocated. NumOperands is
+ /// the number actually in use.
+ unsigned ReservedSpace;
+ PHINode(const PHINode &PN);
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+ explicit PHINode(Type *Ty, unsigned NumReservedValues,
+ const Twine &NameStr = "", Instruction *InsertBefore = 0)
+ : Instruction(Ty, Instruction::PHI, 0, 0, InsertBefore),
+ ReservedSpace(NumReservedValues) {
+ setName(NameStr);
+ OperandList = allocHungoffUses(ReservedSpace);
+ }
+
+ PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
+ BasicBlock *InsertAtEnd)
+ : Instruction(Ty, Instruction::PHI, 0, 0, InsertAtEnd),
+ ReservedSpace(NumReservedValues) {
+ setName(NameStr);
+ OperandList = allocHungoffUses(ReservedSpace);
+ }
+protected:
+ // allocHungoffUses - this is more complicated than the generic
+ // User::allocHungoffUses, because we have to allocate Uses for the incoming
+ // values and pointers to the incoming blocks, all in one allocation.
+ Use *allocHungoffUses(unsigned) const;
+
+ virtual PHINode *clone_impl() const;
+public:
+ /// Constructors - NumReservedValues is a hint for the number of incoming
+ /// edges that this phi node will have (use 0 if you really have no idea).
+ static PHINode *Create(Type *Ty, unsigned NumReservedValues,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
+ }
+ static PHINode *Create(Type *Ty, unsigned NumReservedValues,
+ const Twine &NameStr, BasicBlock *InsertAtEnd) {
+ return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
+ }
+ ~PHINode();
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ // Block iterator interface. This provides access to the list of incoming
+ // basic blocks, which parallels the list of incoming values.
+
+ typedef BasicBlock **block_iterator;
+ typedef BasicBlock * const *const_block_iterator;
+
+ block_iterator block_begin() {
+ Use::UserRef *ref =
+ reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
+ return reinterpret_cast<block_iterator>(ref + 1);
+ }
+
+ const_block_iterator block_begin() const {
+ const Use::UserRef *ref =
+ reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
+ return reinterpret_cast<const_block_iterator>(ref + 1);
+ }
+
+ block_iterator block_end() {
+ return block_begin() + getNumOperands();
+ }
+
+ const_block_iterator block_end() const {
+ return block_begin() + getNumOperands();
+ }
+
+ /// getNumIncomingValues - Return the number of incoming edges
+ ///
+ unsigned getNumIncomingValues() const { return getNumOperands(); }
+
+ /// getIncomingValue - Return incoming value number x
+ ///
+ Value *getIncomingValue(unsigned i) const {
+ return getOperand(i);
+ }
+ void setIncomingValue(unsigned i, Value *V) {
+ setOperand(i, V);
+ }
+ static unsigned getOperandNumForIncomingValue(unsigned i) {
+ return i;
+ }
+ static unsigned getIncomingValueNumForOperand(unsigned i) {
+ return i;
+ }
+
+ /// getIncomingBlock - Return incoming basic block number @p i.
+ ///
+ BasicBlock *getIncomingBlock(unsigned i) const {
+ return block_begin()[i];
+ }
+
+ /// getIncomingBlock - Return incoming basic block corresponding
+ /// to an operand of the PHI.
+ ///
+ BasicBlock *getIncomingBlock(const Use &U) const {
+ assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
+ return getIncomingBlock(unsigned(&U - op_begin()));
+ }
+
+ /// getIncomingBlock - Return incoming basic block corresponding
+ /// to value use iterator.
+ ///
+ template <typename U>
+ BasicBlock *getIncomingBlock(value_use_iterator<U> I) const {
+ return getIncomingBlock(I.getUse());
+ }
+
+ void setIncomingBlock(unsigned i, BasicBlock *BB) {
+ block_begin()[i] = BB;
+ }
+
+ /// addIncoming - Add an incoming value to the end of the PHI list
+ ///
+ void addIncoming(Value *V, BasicBlock *BB) {
+ assert(V && "PHI node got a null value!");
+ assert(BB && "PHI node got a null basic block!");
+ assert(getType() == V->getType() &&
+ "All operands to PHI node must be the same type as the PHI node!");
+ if (NumOperands == ReservedSpace)
+ growOperands(); // Get more space!
+ // Initialize some new operands.
+ ++NumOperands;
+ setIncomingValue(NumOperands - 1, V);
+ setIncomingBlock(NumOperands - 1, BB);
+ }
+
+ /// removeIncomingValue - Remove an incoming value. This is useful if a
+ /// predecessor basic block is deleted. The value removed is returned.
+ ///
+ /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
+ /// is true), the PHI node is destroyed and any uses of it are replaced with
+ /// dummy values. The only time there should be zero incoming values to a PHI
+ /// node is when the block is dead, so this strategy is sound.
+ ///
+ Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
+
+ Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
+ int Idx = getBasicBlockIndex(BB);
+ assert(Idx >= 0 && "Invalid basic block argument to remove!");
+ return removeIncomingValue(Idx, DeletePHIIfEmpty);
+ }
+
+ /// getBasicBlockIndex - Return the first index of the specified basic
+ /// block in the value list for this PHI. Returns -1 if no instance.
+ ///
+ int getBasicBlockIndex(const BasicBlock *BB) const {
+ for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
+ if (block_begin()[i] == BB)
+ return i;
+ return -1;
+ }
+
+ Value *getIncomingValueForBlock(const BasicBlock *BB) const {
+ int Idx = getBasicBlockIndex(BB);
+ assert(Idx >= 0 && "Invalid basic block argument!");
+ return getIncomingValue(Idx);
+ }
+
+ /// hasConstantValue - If the specified PHI node always merges together the
+ /// same value, return the value, otherwise return null.
+ Value *hasConstantValue() const;
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const PHINode *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::PHI;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+ private:
+ void growOperands();
+};
+
+template <>
+struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
+
+//===----------------------------------------------------------------------===//
+// LandingPadInst Class
+//===----------------------------------------------------------------------===//
+
+//===---------------------------------------------------------------------------
+/// LandingPadInst - The landingpad instruction holds all of the information
+/// necessary to generate correct exception handling. The landingpad instruction
+/// cannot be moved from the top of a landing pad block, which itself is
+/// accessible only from the 'unwind' edge of an invoke. This uses the
+/// SubclassData field in Value to store whether or not the landingpad is a
+/// cleanup.
+///
+class LandingPadInst : public Instruction {
+ /// ReservedSpace - The number of operands actually allocated. NumOperands is
+ /// the number actually in use.
+ unsigned ReservedSpace;
+ LandingPadInst(const LandingPadInst &LP);
+public:
+ enum ClauseType { Catch, Filter };
+private:
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ // Allocate space for exactly zero operands.
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+ void growOperands(unsigned Size);
+ void init(Value *PersFn, unsigned NumReservedValues, const Twine &NameStr);
+
+ explicit LandingPadInst(Type *RetTy, Value *PersonalityFn,
+ unsigned NumReservedValues, const Twine &NameStr,
+ Instruction *InsertBefore);
+ explicit LandingPadInst(Type *RetTy, Value *PersonalityFn,
+ unsigned NumReservedValues, const Twine &NameStr,
+ BasicBlock *InsertAtEnd);
+protected:
+ virtual LandingPadInst *clone_impl() const;
+public:
+ /// Constructors - NumReservedClauses is a hint for the number of incoming
+ /// clauses that this landingpad will have (use 0 if you really have no idea).
+ static LandingPadInst *Create(Type *RetTy, Value *PersonalityFn,
+ unsigned NumReservedClauses,
+ const Twine &NameStr = "",
+ Instruction *InsertBefore = 0);
+ static LandingPadInst *Create(Type *RetTy, Value *PersonalityFn,
+ unsigned NumReservedClauses,
+ const Twine &NameStr, BasicBlock *InsertAtEnd);
+ ~LandingPadInst();
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// getPersonalityFn - Get the personality function associated with this
+ /// landing pad.
+ Value *getPersonalityFn() const { return getOperand(0); }
+
+ /// isCleanup - Return 'true' if this landingpad instruction is a
+ /// cleanup. I.e., it should be run when unwinding even if its landing pad
+ /// doesn't catch the exception.
+ bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
+
+ /// setCleanup - Indicate that this landingpad instruction is a cleanup.
+ void setCleanup(bool V) {
+ setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
+ (V ? 1 : 0));
+ }
+
+ /// addClause - Add a catch or filter clause to the landing pad.
+ void addClause(Value *ClauseVal);
+
+ /// getClause - Get the value of the clause at index Idx. Use isCatch/isFilter
+ /// to determine what type of clause this is.
+ Value *getClause(unsigned Idx) const { return OperandList[Idx + 1]; }
+
+ /// isCatch - Return 'true' if the clause and index Idx is a catch clause.
+ bool isCatch(unsigned Idx) const {
+ return !isa<ArrayType>(OperandList[Idx + 1]->getType());
+ }
+
+ /// isFilter - Return 'true' if the clause and index Idx is a filter clause.
+ bool isFilter(unsigned Idx) const {
+ return isa<ArrayType>(OperandList[Idx + 1]->getType());
+ }
+
+ /// getNumClauses - Get the number of clauses for this landing pad.
+ unsigned getNumClauses() const { return getNumOperands() - 1; }
+
+ /// reserveClauses - Grow the size of the operand list to accommodate the new
+ /// number of clauses.
+ void reserveClauses(unsigned Size) { growOperands(Size); }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const LandingPadInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::LandingPad;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+template <>
+struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
+
+//===----------------------------------------------------------------------===//
+// ReturnInst Class
+//===----------------------------------------------------------------------===//
+
+//===---------------------------------------------------------------------------
+/// ReturnInst - Return a value (possibly void), from a function. Execution
+/// does not continue in this function any longer.
+///
+class ReturnInst : public TerminatorInst {
+ ReturnInst(const ReturnInst &RI);
+
+private:
+ // ReturnInst constructors:
+ // ReturnInst() - 'ret void' instruction
+ // ReturnInst( null) - 'ret void' instruction
+ // ReturnInst(Value* X) - 'ret X' instruction
+ // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
+ // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
+ // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
+ // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
+ //
+ // NOTE: If the Value* passed is of type void then the constructor behaves as
+ // if it was passed NULL.
+ explicit ReturnInst(LLVMContext &C, Value *retVal = 0,
+ Instruction *InsertBefore = 0);
+ ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
+ explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
+protected:
+ virtual ReturnInst *clone_impl() const;
+public:
+ static ReturnInst* Create(LLVMContext &C, Value *retVal = 0,
+ Instruction *InsertBefore = 0) {
+ return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
+ }
+ static ReturnInst* Create(LLVMContext &C, Value *retVal,
+ BasicBlock *InsertAtEnd) {
+ return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
+ }
+ static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
+ return new(0) ReturnInst(C, InsertAtEnd);
+ }
+ virtual ~ReturnInst();
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// Convenience accessor. Returns null if there is no return value.
+ Value *getReturnValue() const {
+ return getNumOperands() != 0 ? getOperand(0) : 0;
+ }
+
+ unsigned getNumSuccessors() const { return 0; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ReturnInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return (I->getOpcode() == Instruction::Ret);
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+ private:
+ virtual BasicBlock *getSuccessorV(unsigned idx) const;
+ virtual unsigned getNumSuccessorsV() const;
+ virtual void setSuccessorV(unsigned idx, BasicBlock *B);
+};
+
+template <>
+struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
+
+//===----------------------------------------------------------------------===//
+// BranchInst Class
+//===----------------------------------------------------------------------===//
+
+//===---------------------------------------------------------------------------
+/// BranchInst - Conditional or Unconditional Branch instruction.
+///
+class BranchInst : public TerminatorInst {
+ /// Ops list - Branches are strange. The operands are ordered:
+ /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
+ /// they don't have to check for cond/uncond branchness. These are mostly
+ /// accessed relative from op_end().
+ BranchInst(const BranchInst &BI);
+ void AssertOK();
+ // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
+ // BranchInst(BB *B) - 'br B'
+ // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
+ // BranchInst(BB* B, Inst *I) - 'br B' insert before I
+ // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
+ // BranchInst(BB* B, BB *I) - 'br B' insert at end
+ // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
+ explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = 0);
+ BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
+ Instruction *InsertBefore = 0);
+ BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
+ BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
+ BasicBlock *InsertAtEnd);
+protected:
+ virtual BranchInst *clone_impl() const;
+public:
+ static BranchInst *Create(BasicBlock *IfTrue, Instruction *InsertBefore = 0) {
+ return new(1) BranchInst(IfTrue, InsertBefore);
+ }
+ static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
+ Value *Cond, Instruction *InsertBefore = 0) {
+ return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
+ }
+ static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
+ return new(1) BranchInst(IfTrue, InsertAtEnd);
+ }
+ static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
+ Value *Cond, BasicBlock *InsertAtEnd) {
+ return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
+ }
+
+ /// Transparently provide more efficient getOperand methods.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ bool isUnconditional() const { return getNumOperands() == 1; }
+ bool isConditional() const { return getNumOperands() == 3; }
+
+ Value *getCondition() const {
+ assert(isConditional() && "Cannot get condition of an uncond branch!");
+ return Op<-3>();
+ }
+
+ void setCondition(Value *V) {
+ assert(isConditional() && "Cannot set condition of unconditional branch!");
+ Op<-3>() = V;
+ }
+
+ unsigned getNumSuccessors() const { return 1+isConditional(); }
+
+ BasicBlock *getSuccessor(unsigned i) const {
+ assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
+ return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
+ }
+
+ void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
+ assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
+ *(&Op<-1>() - idx) = (Value*)NewSucc;
+ }
+
+ /// \brief Swap the successors of this branch instruction.
+ ///
+ /// Swaps the successors of the branch instruction. This also swaps any
+ /// branch weight metadata associated with the instruction so that it
+ /// continues to map correctly to each operand.
+ void swapSuccessors();
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const BranchInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return (I->getOpcode() == Instruction::Br);
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ virtual BasicBlock *getSuccessorV(unsigned idx) const;
+ virtual unsigned getNumSuccessorsV() const;
+ virtual void setSuccessorV(unsigned idx, BasicBlock *B);
+};
+
+template <>
+struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
+
+//===----------------------------------------------------------------------===//
+// SwitchInst Class
+//===----------------------------------------------------------------------===//
+
+//===---------------------------------------------------------------------------
+/// SwitchInst - Multiway switch
+///
+class SwitchInst : public TerminatorInst {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ unsigned ReservedSpace;
+ // Operands format:
+ // Operand[0] = Value to switch on
+ // Operand[1] = Default basic block destination
+ // Operand[2n ] = Value to match
+ // Operand[2n+1] = BasicBlock to go to on match
+
+ // Store case values separately from operands list. We needn't User-Use
+ // concept here, since it is just a case value, it will always constant,
+ // and case value couldn't reused with another instructions/values.
+ // Additionally:
+ // It allows us to use custom type for case values that is not inherited
+ // from Value. Since case value is a complex type that implements
+ // the subset of integers, we needn't extract sub-constants within
+ // slow getAggregateElement method.
+ // For case values we will use std::list to by two reasons:
+ // 1. It allows to add/remove cases without whole collection reallocation.
+ // 2. In most of cases we needn't random access.
+ // Currently case values are also stored in Operands List, but it will moved
+ // out in future commits.
+ typedef std::list<IntegersSubset> Subsets;
+ typedef Subsets::iterator SubsetsIt;
+ typedef Subsets::const_iterator SubsetsConstIt;
+
+ Subsets TheSubsets;
+
+ SwitchInst(const SwitchInst &SI);
+ void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
+ void growOperands();
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+ /// SwitchInst ctor - Create a new switch instruction, specifying a value to
+ /// switch on and a default destination. The number of additional cases can
+ /// be specified here to make memory allocation more efficient. This
+ /// constructor can also autoinsert before another instruction.
+ SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
+ Instruction *InsertBefore);
+
+ /// SwitchInst ctor - Create a new switch instruction, specifying a value to
+ /// switch on and a default destination. The number of additional cases can
+ /// be specified here to make memory allocation more efficient. This
+ /// constructor also autoinserts at the end of the specified BasicBlock.
+ SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
+ BasicBlock *InsertAtEnd);
+protected:
+ virtual SwitchInst *clone_impl() const;
+public:
+
+ // FIXME: Currently there are a lot of unclean template parameters,
+ // we need to make refactoring in future.
+ // All these parameters are used to implement both iterator and const_iterator
+ // without code duplication.
+ // SwitchInstTy may be "const SwitchInst" or "SwitchInst"
+ // ConstantIntTy may be "const ConstantInt" or "ConstantInt"
+ // SubsetsItTy may be SubsetsConstIt or SubsetsIt
+ // BasicBlockTy may be "const BasicBlock" or "BasicBlock"
+ template <class SwitchInstTy, class ConstantIntTy,
+ class SubsetsItTy, class BasicBlockTy>
+ class CaseIteratorT;
+
+ typedef CaseIteratorT<const SwitchInst, const ConstantInt,
+ SubsetsConstIt, const BasicBlock> ConstCaseIt;
+ class CaseIt;
+
+ // -2
+ static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
+
+ static SwitchInst *Create(Value *Value, BasicBlock *Default,
+ unsigned NumCases, Instruction *InsertBefore = 0) {
+ return new SwitchInst(Value, Default, NumCases, InsertBefore);
+ }
+ static SwitchInst *Create(Value *Value, BasicBlock *Default,
+ unsigned NumCases, BasicBlock *InsertAtEnd) {
+ return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
+ }
+
+ ~SwitchInst();
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ // Accessor Methods for Switch stmt
+ Value *getCondition() const { return getOperand(0); }
+ void setCondition(Value *V) { setOperand(0, V); }
+
+ BasicBlock *getDefaultDest() const {
+ return cast<BasicBlock>(getOperand(1));
+ }
+
+ void setDefaultDest(BasicBlock *DefaultCase) {
+ setOperand(1, reinterpret_cast<Value*>(DefaultCase));
+ }
+
+ /// getNumCases - return the number of 'cases' in this switch instruction,
+ /// except the default case
+ unsigned getNumCases() const {
+ return getNumOperands()/2 - 1;
+ }
+
+ /// Returns a read/write iterator that points to the first
+ /// case in SwitchInst.
+ CaseIt case_begin() {
+ return CaseIt(this, 0, TheSubsets.begin());
+ }
+ /// Returns a read-only iterator that points to the first
+ /// case in the SwitchInst.
+ ConstCaseIt case_begin() const {
+ return ConstCaseIt(this, 0, TheSubsets.begin());
+ }
+
+ /// Returns a read/write iterator that points one past the last
+ /// in the SwitchInst.
+ CaseIt case_end() {
+ return CaseIt(this, getNumCases(), TheSubsets.end());
+ }
+ /// Returns a read-only iterator that points one past the last
+ /// in the SwitchInst.
+ ConstCaseIt case_end() const {
+ return ConstCaseIt(this, getNumCases(), TheSubsets.end());
+ }
+ /// Returns an iterator that points to the default case.
+ /// Note: this iterator allows to resolve successor only. Attempt
+ /// to resolve case value causes an assertion.
+ /// Also note, that increment and decrement also causes an assertion and
+ /// makes iterator invalid.
+ CaseIt case_default() {
+ return CaseIt(this, DefaultPseudoIndex, TheSubsets.end());
+ }
+ ConstCaseIt case_default() const {
+ return ConstCaseIt(this, DefaultPseudoIndex, TheSubsets.end());
+ }
+
+ /// findCaseValue - Search all of the case values for the specified constant.
+ /// If it is explicitly handled, return the case iterator of it, otherwise
+ /// return default case iterator to indicate
+ /// that it is handled by the default handler.
+ CaseIt findCaseValue(const ConstantInt *C) {
+ for (CaseIt i = case_begin(), e = case_end(); i != e; ++i)
+ if (i.getCaseValueEx().isSatisfies(IntItem::fromConstantInt(C)))
+ return i;
+ return case_default();
+ }
+ ConstCaseIt findCaseValue(const ConstantInt *C) const {
+ for (ConstCaseIt i = case_begin(), e = case_end(); i != e; ++i)
+ if (i.getCaseValueEx().isSatisfies(IntItem::fromConstantInt(C)))
+ return i;
+ return case_default();
+ }
+
+ /// findCaseDest - Finds the unique case value for a given successor. Returns
+ /// null if the successor is not found, not unique, or is the default case.
+ ConstantInt *findCaseDest(BasicBlock *BB) {
+ if (BB == getDefaultDest()) return NULL;
+
+ ConstantInt *CI = NULL;
+ for (CaseIt i = case_begin(), e = case_end(); i != e; ++i) {
+ if (i.getCaseSuccessor() == BB) {
+ if (CI) return NULL; // Multiple cases lead to BB.
+ else CI = i.getCaseValue();
+ }
+ }
+ return CI;
+ }
+
+ /// addCase - Add an entry to the switch instruction...
+ /// @deprecated
+ /// Note:
+ /// This action invalidates case_end(). Old case_end() iterator will
+ /// point to the added case.
+ void addCase(ConstantInt *OnVal, BasicBlock *Dest);
+
+ /// addCase - Add an entry to the switch instruction.
+ /// Note:
+ /// This action invalidates case_end(). Old case_end() iterator will
+ /// point to the added case.
+ void addCase(IntegersSubset& OnVal, BasicBlock *Dest);
+
+ /// removeCase - This method removes the specified case and its successor
+ /// from the switch instruction. Note that this operation may reorder the
+ /// remaining cases at index idx and above.
+ /// Note:
+ /// This action invalidates iterators for all cases following the one removed,
+ /// including the case_end() iterator.
+ void removeCase(CaseIt& i);
+
+ unsigned getNumSuccessors() const { return getNumOperands()/2; }
+ BasicBlock *getSuccessor(unsigned idx) const {
+ assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
+ return cast<BasicBlock>(getOperand(idx*2+1));
+ }
+ void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
+ assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
+ setOperand(idx*2+1, (Value*)NewSucc);
+ }
+
+ uint16_t hash() const {
+ uint32_t NumberOfCases = (uint32_t)getNumCases();
+ uint16_t Hash = (0xFFFF & NumberOfCases) ^ (NumberOfCases >> 16);
+ for (ConstCaseIt i = case_begin(), e = case_end();
+ i != e; ++i) {
+ uint32_t NumItems = (uint32_t)i.getCaseValueEx().getNumItems();
+ Hash = (Hash << 1) ^ (0xFFFF & NumItems) ^ (NumItems >> 16);
+ }
+ return Hash;
+ }
+
+ // Case iterators definition.
+
+ template <class SwitchInstTy, class ConstantIntTy,
+ class SubsetsItTy, class BasicBlockTy>
+ class CaseIteratorT {
+ protected:
+
+ SwitchInstTy *SI;
+ unsigned long Index;
+ SubsetsItTy SubsetIt;
+
+ /// Initializes case iterator for given SwitchInst and for given
+ /// case number.
+ friend class SwitchInst;
+ CaseIteratorT(SwitchInstTy *SI, unsigned SuccessorIndex,
+ SubsetsItTy CaseValueIt) {
+ this->SI = SI;
+ Index = SuccessorIndex;
+ this->SubsetIt = CaseValueIt;
+ }
+
+ public:
+ typedef typename SubsetsItTy::reference IntegersSubsetRef;
+ typedef CaseIteratorT<SwitchInstTy, ConstantIntTy,
+ SubsetsItTy, BasicBlockTy> Self;
+
+ CaseIteratorT(SwitchInstTy *SI, unsigned CaseNum) {
+ this->SI = SI;
+ Index = CaseNum;
+ SubsetIt = SI->TheSubsets.begin();
+ std::advance(SubsetIt, CaseNum);
+ }
+
+
+ /// Initializes case iterator for given SwitchInst and for given
+ /// TerminatorInst's successor index.
+ static Self fromSuccessorIndex(SwitchInstTy *SI, unsigned SuccessorIndex) {
+ assert(SuccessorIndex < SI->getNumSuccessors() &&
+ "Successor index # out of range!");
+ return SuccessorIndex != 0 ?
+ Self(SI, SuccessorIndex - 1) :
+ Self(SI, DefaultPseudoIndex);
+ }
+
+ /// Resolves case value for current case.
+ /// @deprecated
+ ConstantIntTy *getCaseValue() {
+ assert(Index < SI->getNumCases() && "Index out the number of cases.");
+ IntegersSubsetRef CaseRanges = *SubsetIt;
+
+ // FIXME: Currently we work with ConstantInt based cases.
+ // So return CaseValue as ConstantInt.
+ return CaseRanges.getSingleNumber(0).toConstantInt();
+ }
+
+ /// Resolves case value for current case.
+ IntegersSubsetRef getCaseValueEx() {
+ assert(Index < SI->getNumCases() && "Index out the number of cases.");
+ return *SubsetIt;
+ }
+
+ /// Resolves successor for current case.
+ BasicBlockTy *getCaseSuccessor() {
+ assert((Index < SI->getNumCases() ||
+ Index == DefaultPseudoIndex) &&
+ "Index out the number of cases.");
+ return SI->getSuccessor(getSuccessorIndex());
+ }
+
+ /// Returns number of current case.
+ unsigned getCaseIndex() const { return Index; }
+
+ /// Returns TerminatorInst's successor index for current case successor.
+ unsigned getSuccessorIndex() const {
+ assert((Index == DefaultPseudoIndex || Index < SI->getNumCases()) &&
+ "Index out the number of cases.");
+ return Index != DefaultPseudoIndex ? Index + 1 : 0;
+ }
+
+ Self operator++() {
+ // Check index correctness after increment.
+ // Note: Index == getNumCases() means end().
+ assert(Index+1 <= SI->getNumCases() && "Index out the number of cases.");
+ ++Index;
+ if (Index == 0)
+ SubsetIt = SI->TheSubsets.begin();
+ else
+ ++SubsetIt;
+ return *this;
+ }
+ Self operator++(int) {
+ Self tmp = *this;
+ ++(*this);
+ return tmp;
+ }
+ Self operator--() {
+ // Check index correctness after decrement.
+ // Note: Index == getNumCases() means end().
+ // Also allow "-1" iterator here. That will became valid after ++.
+ unsigned NumCases = SI->getNumCases();
+ assert((Index == 0 || Index-1 <= NumCases) &&
+ "Index out the number of cases.");
+ --Index;
+ if (Index == NumCases) {
+ SubsetIt = SI->TheSubsets.end();
+ return *this;
+ }
+
+ if (Index != -1UL)
+ --SubsetIt;
+
+ return *this;
+ }
+ Self operator--(int) {
+ Self tmp = *this;
+ --(*this);
+ return tmp;
+ }
+ bool operator==(const Self& RHS) const {
+ assert(RHS.SI == SI && "Incompatible operators.");
+ return RHS.Index == Index;
+ }
+ bool operator!=(const Self& RHS) const {
+ assert(RHS.SI == SI && "Incompatible operators.");
+ return RHS.Index != Index;
+ }
+ };
+
+ class CaseIt : public CaseIteratorT<SwitchInst, ConstantInt,
+ SubsetsIt, BasicBlock> {
+ typedef CaseIteratorT<SwitchInst, ConstantInt, SubsetsIt, BasicBlock>
+ ParentTy;
+
+ protected:
+ friend class SwitchInst;
+ CaseIt(SwitchInst *SI, unsigned CaseNum, SubsetsIt SubsetIt) :
+ ParentTy(SI, CaseNum, SubsetIt) {}
+
+ void updateCaseValueOperand(IntegersSubset& V) {
+ SI->setOperand(2 + Index*2, reinterpret_cast<Value*>((Constant*)V));
+ }
+
+ public:
+
+ CaseIt(SwitchInst *SI, unsigned CaseNum) : ParentTy(SI, CaseNum) {}
+
+ CaseIt(const ParentTy& Src) : ParentTy(Src) {}
+
+ /// Sets the new value for current case.
+ /// @deprecated.
+ void setValue(ConstantInt *V) {
+ assert(Index < SI->getNumCases() && "Index out the number of cases.");
+ IntegersSubsetToBB Mapping;
+ // FIXME: Currently we work with ConstantInt based cases.
+ // So inititalize IntItem container directly from ConstantInt.
+ Mapping.add(IntItem::fromConstantInt(V));
+ *SubsetIt = Mapping.getCase();
+ updateCaseValueOperand(*SubsetIt);
+ }
+
+ /// Sets the new value for current case.
+ void setValueEx(IntegersSubset& V) {
+ assert(Index < SI->getNumCases() && "Index out the number of cases.");
+ *SubsetIt = V;
+ updateCaseValueOperand(*SubsetIt);
+ }
+
+ /// Sets the new successor for current case.
+ void setSuccessor(BasicBlock *S) {
+ SI->setSuccessor(getSuccessorIndex(), S);
+ }
+ };
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+
+ static inline bool classof(const SwitchInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Switch;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ virtual BasicBlock *getSuccessorV(unsigned idx) const;
+ virtual unsigned getNumSuccessorsV() const;
+ virtual void setSuccessorV(unsigned idx, BasicBlock *B);
+};
+
+template <>
+struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
+
+
+//===----------------------------------------------------------------------===//
+// IndirectBrInst Class
+//===----------------------------------------------------------------------===//
+
+//===---------------------------------------------------------------------------
+/// IndirectBrInst - Indirect Branch Instruction.
+///
+class IndirectBrInst : public TerminatorInst {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ unsigned ReservedSpace;
+ // Operand[0] = Value to switch on
+ // Operand[1] = Default basic block destination
+ // Operand[2n ] = Value to match
+ // Operand[2n+1] = BasicBlock to go to on match
+ IndirectBrInst(const IndirectBrInst &IBI);
+ void init(Value *Address, unsigned NumDests);
+ void growOperands();
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+ /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
+ /// Address to jump to. The number of expected destinations can be specified
+ /// here to make memory allocation more efficient. This constructor can also
+ /// autoinsert before another instruction.
+ IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
+
+ /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
+ /// Address to jump to. The number of expected destinations can be specified
+ /// here to make memory allocation more efficient. This constructor also
+ /// autoinserts at the end of the specified BasicBlock.
+ IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
+protected:
+ virtual IndirectBrInst *clone_impl() const;
+public:
+ static IndirectBrInst *Create(Value *Address, unsigned NumDests,
+ Instruction *InsertBefore = 0) {
+ return new IndirectBrInst(Address, NumDests, InsertBefore);
+ }
+ static IndirectBrInst *Create(Value *Address, unsigned NumDests,
+ BasicBlock *InsertAtEnd) {
+ return new IndirectBrInst(Address, NumDests, InsertAtEnd);
+ }
+ ~IndirectBrInst();
+
+ /// Provide fast operand accessors.
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ // Accessor Methods for IndirectBrInst instruction.
+ Value *getAddress() { return getOperand(0); }
+ const Value *getAddress() const { return getOperand(0); }
+ void setAddress(Value *V) { setOperand(0, V); }
+
+
+ /// getNumDestinations - return the number of possible destinations in this
+ /// indirectbr instruction.
+ unsigned getNumDestinations() const { return getNumOperands()-1; }
+
+ /// getDestination - Return the specified destination.
+ BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
+ const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
+
+ /// addDestination - Add a destination.
+ ///
+ void addDestination(BasicBlock *Dest);
+
+ /// removeDestination - This method removes the specified successor from the
+ /// indirectbr instruction.
+ void removeDestination(unsigned i);
+
+ unsigned getNumSuccessors() const { return getNumOperands()-1; }
+ BasicBlock *getSuccessor(unsigned i) const {
+ return cast<BasicBlock>(getOperand(i+1));
+ }
+ void setSuccessor(unsigned i, BasicBlock *NewSucc) {
+ setOperand(i+1, (Value*)NewSucc);
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const IndirectBrInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::IndirectBr;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ virtual BasicBlock *getSuccessorV(unsigned idx) const;
+ virtual unsigned getNumSuccessorsV() const;
+ virtual void setSuccessorV(unsigned idx, BasicBlock *B);
+};
+
+template <>
+struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
+
+
+//===----------------------------------------------------------------------===//
+// InvokeInst Class
+//===----------------------------------------------------------------------===//
+
+/// InvokeInst - Invoke instruction. The SubclassData field is used to hold the
+/// calling convention of the call.
+///
+class InvokeInst : public TerminatorInst {
+ AttrListPtr AttributeList;
+ InvokeInst(const InvokeInst &BI);
+ void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
+ ArrayRef<Value *> Args, const Twine &NameStr);
+
+ /// Construct an InvokeInst given a range of arguments.
+ ///
+ /// @brief Construct an InvokeInst from a range of arguments
+ inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
+ ArrayRef<Value *> Args, unsigned Values,
+ const Twine &NameStr, Instruction *InsertBefore);
+
+ /// Construct an InvokeInst given a range of arguments.
+ ///
+ /// @brief Construct an InvokeInst from a range of arguments
+ inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
+ ArrayRef<Value *> Args, unsigned Values,
+ const Twine &NameStr, BasicBlock *InsertAtEnd);
+protected:
+ virtual InvokeInst *clone_impl() const;
+public:
+ static InvokeInst *Create(Value *Func,
+ BasicBlock *IfNormal, BasicBlock *IfException,
+ ArrayRef<Value *> Args, const Twine &NameStr = "",
+ Instruction *InsertBefore = 0) {
+ unsigned Values = unsigned(Args.size()) + 3;
+ return new(Values) InvokeInst(Func, IfNormal, IfException, Args,
+ Values, NameStr, InsertBefore);
+ }
+ static InvokeInst *Create(Value *Func,
+ BasicBlock *IfNormal, BasicBlock *IfException,
+ ArrayRef<Value *> Args, const Twine &NameStr,
+ BasicBlock *InsertAtEnd) {
+ unsigned Values = unsigned(Args.size()) + 3;
+ return new(Values) InvokeInst(Func, IfNormal, IfException, Args,
+ Values, NameStr, InsertAtEnd);
+ }
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// getNumArgOperands - Return the number of invoke arguments.
+ ///
+ unsigned getNumArgOperands() const { return getNumOperands() - 3; }
+
+ /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
+ ///
+ Value *getArgOperand(unsigned i) const { return getOperand(i); }
+ void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
+
+ /// getCallingConv/setCallingConv - Get or set the calling convention of this
+ /// function call.
+ CallingConv::ID getCallingConv() const {
+ return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
+ }
+ void setCallingConv(CallingConv::ID CC) {
+ setInstructionSubclassData(static_cast<unsigned>(CC));
+ }
+
+ /// getAttributes - Return the parameter attributes for this invoke.
+ ///
+ const AttrListPtr &getAttributes() const { return AttributeList; }
+
+ /// setAttributes - Set the parameter attributes for this invoke.
+ ///
+ void setAttributes(const AttrListPtr &Attrs) { AttributeList = Attrs; }
+
+ /// addAttribute - adds the attribute to the list of attributes.
+ void addAttribute(unsigned i, Attributes attr);
+
+ /// removeAttribute - removes the attribute from the list of attributes.
+ void removeAttribute(unsigned i, Attributes attr);
+
+ /// \brief Return true if this call has the given attribute.
+ bool hasFnAttr(Attributes N) const {
+ return paramHasAttr(~0, N);
+ }
+
+ /// @brief Determine whether the call or the callee has the given attribute.
+ bool paramHasAttr(unsigned i, Attributes attr) const;
+
+ /// @brief Extract the alignment for a call or parameter (0=unknown).
+ unsigned getParamAlignment(unsigned i) const {
+ return AttributeList.getParamAlignment(i);
+ }
+
+ /// @brief Return true if the call should not be inlined.
+ bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
+ void setIsNoInline(bool Value = true) {
+ if (Value) addAttribute(~0, Attribute::NoInline);
+ else removeAttribute(~0, Attribute::NoInline);
+ }
+
+ /// @brief Determine if the call does not access memory.
+ bool doesNotAccessMemory() const {
+ return hasFnAttr(Attribute::ReadNone);
+ }
+ void setDoesNotAccessMemory(bool NotAccessMemory = true) {
+ if (NotAccessMemory) addAttribute(~0, Attribute::ReadNone);
+ else removeAttribute(~0, Attribute::ReadNone);
+ }
+
+ /// @brief Determine if the call does not access or only reads memory.
+ bool onlyReadsMemory() const {
+ return doesNotAccessMemory() || hasFnAttr(Attribute::ReadOnly);
+ }
+ void setOnlyReadsMemory(bool OnlyReadsMemory = true) {
+ if (OnlyReadsMemory) addAttribute(~0, Attribute::ReadOnly);
+ else removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
+ }
+
+ /// @brief Determine if the call cannot return.
+ bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
+ void setDoesNotReturn(bool DoesNotReturn = true) {
+ if (DoesNotReturn) addAttribute(~0, Attribute::NoReturn);
+ else removeAttribute(~0, Attribute::NoReturn);
+ }
+
+ /// @brief Determine if the call cannot unwind.
+ bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
+ void setDoesNotThrow(bool DoesNotThrow = true) {
+ if (DoesNotThrow) addAttribute(~0, Attribute::NoUnwind);
+ else removeAttribute(~0, Attribute::NoUnwind);
+ }
+
+ /// @brief Determine if the call returns a structure through first
+ /// pointer argument.
+ bool hasStructRetAttr() const {
+ // Be friendly and also check the callee.
+ return paramHasAttr(1, Attribute::StructRet);
+ }
+
+ /// @brief Determine if any call argument is an aggregate passed by value.
+ bool hasByValArgument() const {
+ return AttributeList.hasAttrSomewhere(Attribute::ByVal);
+ }
+
+ /// getCalledFunction - Return the function called, or null if this is an
+ /// indirect function invocation.
+ ///
+ Function *getCalledFunction() const {
+ return dyn_cast<Function>(Op<-3>());
+ }
+
+ /// getCalledValue - Get a pointer to the function that is invoked by this
+ /// instruction
+ const Value *getCalledValue() const { return Op<-3>(); }
+ Value *getCalledValue() { return Op<-3>(); }
+
+ /// setCalledFunction - Set the function called.
+ void setCalledFunction(Value* Fn) {
+ Op<-3>() = Fn;
+ }
+
+ // get*Dest - Return the destination basic blocks...
+ BasicBlock *getNormalDest() const {
+ return cast<BasicBlock>(Op<-2>());
+ }
+ BasicBlock *getUnwindDest() const {
+ return cast<BasicBlock>(Op<-1>());
+ }
+ void setNormalDest(BasicBlock *B) {
+ Op<-2>() = reinterpret_cast<Value*>(B);
+ }
+ void setUnwindDest(BasicBlock *B) {
+ Op<-1>() = reinterpret_cast<Value*>(B);
+ }
+
+ /// getLandingPadInst - Get the landingpad instruction from the landing pad
+ /// block (the unwind destination).
+ LandingPadInst *getLandingPadInst() const;
+
+ BasicBlock *getSuccessor(unsigned i) const {
+ assert(i < 2 && "Successor # out of range for invoke!");
+ return i == 0 ? getNormalDest() : getUnwindDest();
+ }
+
+ void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
+ assert(idx < 2 && "Successor # out of range for invoke!");
+ *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
+ }
+
+ unsigned getNumSuccessors() const { return 2; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const InvokeInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return (I->getOpcode() == Instruction::Invoke);
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+
+private:
+ virtual BasicBlock *getSuccessorV(unsigned idx) const;
+ virtual unsigned getNumSuccessorsV() const;
+ virtual void setSuccessorV(unsigned idx, BasicBlock *B);
+
+ // Shadow Instruction::setInstructionSubclassData with a private forwarding
+ // method so that subclasses cannot accidentally use it.
+ void setInstructionSubclassData(unsigned short D) {
+ Instruction::setInstructionSubclassData(D);
+ }
+};
+
+template <>
+struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
+};
+
+InvokeInst::InvokeInst(Value *Func,
+ BasicBlock *IfNormal, BasicBlock *IfException,
+ ArrayRef<Value *> Args, unsigned Values,
+ const Twine &NameStr, Instruction *InsertBefore)
+ : TerminatorInst(cast<FunctionType>(cast<PointerType>(Func->getType())
+ ->getElementType())->getReturnType(),
+ Instruction::Invoke,
+ OperandTraits<InvokeInst>::op_end(this) - Values,
+ Values, InsertBefore) {
+ init(Func, IfNormal, IfException, Args, NameStr);
+}
+InvokeInst::InvokeInst(Value *Func,
+ BasicBlock *IfNormal, BasicBlock *IfException,
+ ArrayRef<Value *> Args, unsigned Values,
+ const Twine &NameStr, BasicBlock *InsertAtEnd)
+ : TerminatorInst(cast<FunctionType>(cast<PointerType>(Func->getType())
+ ->getElementType())->getReturnType(),
+ Instruction::Invoke,
+ OperandTraits<InvokeInst>::op_end(this) - Values,
+ Values, InsertAtEnd) {
+ init(Func, IfNormal, IfException, Args, NameStr);
+}
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
+
+//===----------------------------------------------------------------------===//
+// ResumeInst Class
+//===----------------------------------------------------------------------===//
+
+//===---------------------------------------------------------------------------
+/// ResumeInst - Resume the propagation of an exception.
+///
+class ResumeInst : public TerminatorInst {
+ ResumeInst(const ResumeInst &RI);
+
+ explicit ResumeInst(Value *Exn, Instruction *InsertBefore=0);
+ ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
+protected:
+ virtual ResumeInst *clone_impl() const;
+public:
+ static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = 0) {
+ return new(1) ResumeInst(Exn, InsertBefore);
+ }
+ static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
+ return new(1) ResumeInst(Exn, InsertAtEnd);
+ }
+
+ /// Provide fast operand accessors
+ DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
+
+ /// Convenience accessor.
+ Value *getValue() const { return Op<0>(); }
+
+ unsigned getNumSuccessors() const { return 0; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ResumeInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Resume;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ virtual BasicBlock *getSuccessorV(unsigned idx) const;
+ virtual unsigned getNumSuccessorsV() const;
+ virtual void setSuccessorV(unsigned idx, BasicBlock *B);
+};
+
+template <>
+struct OperandTraits<ResumeInst> :
+ public FixedNumOperandTraits<ResumeInst, 1> {
+};
+
+DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
+
+//===----------------------------------------------------------------------===//
+// UnreachableInst Class
+//===----------------------------------------------------------------------===//
+
+//===---------------------------------------------------------------------------
+/// UnreachableInst - This function has undefined behavior. In particular, the
+/// presence of this instruction indicates some higher level knowledge that the
+/// end of the block cannot be reached.
+///
+class UnreachableInst : public TerminatorInst {
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+protected:
+ virtual UnreachableInst *clone_impl() const;
+
+public:
+ // allocate space for exactly zero operands
+ void *operator new(size_t s) {
+ return User::operator new(s, 0);
+ }
+ explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = 0);
+ explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
+
+ unsigned getNumSuccessors() const { return 0; }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const UnreachableInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Unreachable;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+private:
+ virtual BasicBlock *getSuccessorV(unsigned idx) const;
+ virtual unsigned getNumSuccessorsV() const;
+ virtual void setSuccessorV(unsigned idx, BasicBlock *B);
+};
+
+//===----------------------------------------------------------------------===//
+// TruncInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a truncation of integer types.
+class TruncInst : public CastInst {
+protected:
+ /// @brief Clone an identical TruncInst
+ virtual TruncInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ TruncInst(
+ Value *S, ///< The value to be truncated
+ Type *Ty, ///< The (smaller) type to truncate to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ TruncInst(
+ Value *S, ///< The value to be truncated
+ Type *Ty, ///< The (smaller) type to truncate to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const TruncInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Trunc;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// ZExtInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents zero extension of integer types.
+class ZExtInst : public CastInst {
+protected:
+ /// @brief Clone an identical ZExtInst
+ virtual ZExtInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ ZExtInst(
+ Value *S, ///< The value to be zero extended
+ Type *Ty, ///< The type to zero extend to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end semantics.
+ ZExtInst(
+ Value *S, ///< The value to be zero extended
+ Type *Ty, ///< The type to zero extend to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const ZExtInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == ZExt;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// SExtInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a sign extension of integer types.
+class SExtInst : public CastInst {
+protected:
+ /// @brief Clone an identical SExtInst
+ virtual SExtInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ SExtInst(
+ Value *S, ///< The value to be sign extended
+ Type *Ty, ///< The type to sign extend to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ SExtInst(
+ Value *S, ///< The value to be sign extended
+ Type *Ty, ///< The type to sign extend to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SExtInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == SExt;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// FPTruncInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a truncation of floating point types.
+class FPTruncInst : public CastInst {
+protected:
+ /// @brief Clone an identical FPTruncInst
+ virtual FPTruncInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ FPTruncInst(
+ Value *S, ///< The value to be truncated
+ Type *Ty, ///< The type to truncate to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-before-instruction semantics
+ FPTruncInst(
+ Value *S, ///< The value to be truncated
+ Type *Ty, ///< The type to truncate to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const FPTruncInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == FPTrunc;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// FPExtInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents an extension of floating point types.
+class FPExtInst : public CastInst {
+protected:
+ /// @brief Clone an identical FPExtInst
+ virtual FPExtInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ FPExtInst(
+ Value *S, ///< The value to be extended
+ Type *Ty, ///< The type to extend to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ FPExtInst(
+ Value *S, ///< The value to be extended
+ Type *Ty, ///< The type to extend to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const FPExtInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == FPExt;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// UIToFPInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a cast unsigned integer to floating point.
+class UIToFPInst : public CastInst {
+protected:
+ /// @brief Clone an identical UIToFPInst
+ virtual UIToFPInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ UIToFPInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ UIToFPInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const UIToFPInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == UIToFP;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// SIToFPInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a cast from signed integer to floating point.
+class SIToFPInst : public CastInst {
+protected:
+ /// @brief Clone an identical SIToFPInst
+ virtual SIToFPInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ SIToFPInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ SIToFPInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const SIToFPInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == SIToFP;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// FPToUIInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a cast from floating point to unsigned integer
+class FPToUIInst : public CastInst {
+protected:
+ /// @brief Clone an identical FPToUIInst
+ virtual FPToUIInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ FPToUIInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ FPToUIInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< Where to insert the new instruction
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const FPToUIInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == FPToUI;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// FPToSIInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a cast from floating point to signed integer.
+class FPToSIInst : public CastInst {
+protected:
+ /// @brief Clone an identical FPToSIInst
+ virtual FPToSIInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ FPToSIInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ FPToSIInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const FPToSIInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == FPToSI;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// IntToPtrInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a cast from an integer to a pointer.
+class IntToPtrInst : public CastInst {
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ IntToPtrInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ IntToPtrInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ /// @brief Clone an identical IntToPtrInst
+ virtual IntToPtrInst *clone_impl() const;
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const IntToPtrInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == IntToPtr;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// PtrToIntInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a cast from a pointer to an integer
+class PtrToIntInst : public CastInst {
+protected:
+ /// @brief Clone an identical PtrToIntInst
+ virtual PtrToIntInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ PtrToIntInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ PtrToIntInst(
+ Value *S, ///< The value to be converted
+ Type *Ty, ///< The type to convert to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const PtrToIntInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == PtrToInt;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// BitCastInst Class
+//===----------------------------------------------------------------------===//
+
+/// @brief This class represents a no-op cast from one type to another.
+class BitCastInst : public CastInst {
+protected:
+ /// @brief Clone an identical BitCastInst
+ virtual BitCastInst *clone_impl() const;
+
+public:
+ /// @brief Constructor with insert-before-instruction semantics
+ BitCastInst(
+ Value *S, ///< The value to be casted
+ Type *Ty, ///< The type to casted to
+ const Twine &NameStr = "", ///< A name for the new instruction
+ Instruction *InsertBefore = 0 ///< Where to insert the new instruction
+ );
+
+ /// @brief Constructor with insert-at-end-of-block semantics
+ BitCastInst(
+ Value *S, ///< The value to be casted
+ Type *Ty, ///< The type to casted to
+ const Twine &NameStr, ///< A name for the new instruction
+ BasicBlock *InsertAtEnd ///< The block to insert the instruction into
+ );
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const BitCastInst *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == BitCast;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/IntrinsicInst.h b/include/llvm/IntrinsicInst.h
new file mode 100644
index 00000000000..e9bf0f6759b
--- /dev/null
+++ b/include/llvm/IntrinsicInst.h
@@ -0,0 +1,282 @@
+//===-- llvm/IntrinsicInst.h - Intrinsic Instruction Wrappers ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines classes that make it really easy to deal with intrinsic
+// functions with the isa/dyncast family of functions. In particular, this
+// allows you to do things like:
+//
+// if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(Inst))
+// ... MCI->getDest() ... MCI->getSource() ...
+//
+// All intrinsic function calls are instances of the call instruction, so these
+// are all subclasses of the CallInst class. Note that none of these classes
+// has state or virtual methods, which is an important part of this gross/neat
+// hack working.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INTRINSICINST_H
+#define LLVM_INTRINSICINST_H
+
+#include "llvm/Constants.h"
+#include "llvm/Function.h"
+#include "llvm/Instructions.h"
+#include "llvm/Intrinsics.h"
+
+namespace llvm {
+ /// IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic
+ /// functions. This allows the standard isa/dyncast/cast functionality to
+ /// work with calls to intrinsic functions.
+ class IntrinsicInst : public CallInst {
+ IntrinsicInst() LLVM_DELETED_FUNCTION;
+ IntrinsicInst(const IntrinsicInst&) LLVM_DELETED_FUNCTION;
+ void operator=(const IntrinsicInst&) LLVM_DELETED_FUNCTION;
+ public:
+ /// getIntrinsicID - Return the intrinsic ID of this intrinsic.
+ ///
+ Intrinsic::ID getIntrinsicID() const {
+ return (Intrinsic::ID)getCalledFunction()->getIntrinsicID();
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const IntrinsicInst *) { return true; }
+ static inline bool classof(const CallInst *I) {
+ if (const Function *CF = I->getCalledFunction())
+ return CF->getIntrinsicID() != 0;
+ return false;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<CallInst>(V) && classof(cast<CallInst>(V));
+ }
+ };
+
+ /// DbgInfoIntrinsic - This is the common base class for debug info intrinsics
+ ///
+ class DbgInfoIntrinsic : public IntrinsicInst {
+ public:
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const DbgInfoIntrinsic *) { return true; }
+ static inline bool classof(const IntrinsicInst *I) {
+ switch (I->getIntrinsicID()) {
+ case Intrinsic::dbg_declare:
+ case Intrinsic::dbg_value:
+ return true;
+ default: return false;
+ }
+ }
+ static inline bool classof(const Value *V) {
+ return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
+ }
+
+ static Value *StripCast(Value *C);
+ };
+
+ /// DbgDeclareInst - This represents the llvm.dbg.declare instruction.
+ ///
+ class DbgDeclareInst : public DbgInfoIntrinsic {
+ public:
+ Value *getAddress() const;
+ MDNode *getVariable() const { return cast<MDNode>(getArgOperand(1)); }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const DbgDeclareInst *) { return true; }
+ static inline bool classof(const IntrinsicInst *I) {
+ return I->getIntrinsicID() == Intrinsic::dbg_declare;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
+ }
+ };
+
+ /// DbgValueInst - This represents the llvm.dbg.value instruction.
+ ///
+ class DbgValueInst : public DbgInfoIntrinsic {
+ public:
+ const Value *getValue() const;
+ Value *getValue();
+ uint64_t getOffset() const {
+ return cast<ConstantInt>(
+ const_cast<Value*>(getArgOperand(1)))->getZExtValue();
+ }
+ MDNode *getVariable() const { return cast<MDNode>(getArgOperand(2)); }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const DbgValueInst *) { return true; }
+ static inline bool classof(const IntrinsicInst *I) {
+ return I->getIntrinsicID() == Intrinsic::dbg_value;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
+ }
+ };
+
+ /// MemIntrinsic - This is the common base class for memset/memcpy/memmove.
+ ///
+ class MemIntrinsic : public IntrinsicInst {
+ public:
+ Value *getRawDest() const { return const_cast<Value*>(getArgOperand(0)); }
+
+ Value *getLength() const { return const_cast<Value*>(getArgOperand(2)); }
+ ConstantInt *getAlignmentCst() const {
+ return cast<ConstantInt>(const_cast<Value*>(getArgOperand(3)));
+ }
+
+ unsigned getAlignment() const {
+ return getAlignmentCst()->getZExtValue();
+ }
+
+ ConstantInt *getVolatileCst() const {
+ return cast<ConstantInt>(const_cast<Value*>(getArgOperand(4)));
+ }
+ bool isVolatile() const {
+ return !getVolatileCst()->isZero();
+ }
+
+ unsigned getDestAddressSpace() const {
+ return cast<PointerType>(getRawDest()->getType())->getAddressSpace();
+ }
+
+ /// getDest - This is just like getRawDest, but it strips off any cast
+ /// instructions that feed it, giving the original input. The returned
+ /// value is guaranteed to be a pointer.
+ Value *getDest() const { return getRawDest()->stripPointerCasts(); }
+
+ /// set* - Set the specified arguments of the instruction.
+ ///
+ void setDest(Value *Ptr) {
+ assert(getRawDest()->getType() == Ptr->getType() &&
+ "setDest called with pointer of wrong type!");
+ setArgOperand(0, Ptr);
+ }
+
+ void setLength(Value *L) {
+ assert(getLength()->getType() == L->getType() &&
+ "setLength called with value of wrong type!");
+ setArgOperand(2, L);
+ }
+
+ void setAlignment(Constant* A) {
+ setArgOperand(3, A);
+ }
+
+ void setVolatile(Constant* V) {
+ setArgOperand(4, V);
+ }
+
+ Type *getAlignmentType() const {
+ return getArgOperand(3)->getType();
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const MemIntrinsic *) { return true; }
+ static inline bool classof(const IntrinsicInst *I) {
+ switch (I->getIntrinsicID()) {
+ case Intrinsic::memcpy:
+ case Intrinsic::memmove:
+ case Intrinsic::memset:
+ return true;
+ default: return false;
+ }
+ }
+ static inline bool classof(const Value *V) {
+ return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
+ }
+ };
+
+ /// MemSetInst - This class wraps the llvm.memset intrinsic.
+ ///
+ class MemSetInst : public MemIntrinsic {
+ public:
+ /// get* - Return the arguments to the instruction.
+ ///
+ Value *getValue() const { return const_cast<Value*>(getArgOperand(1)); }
+
+ void setValue(Value *Val) {
+ assert(getValue()->getType() == Val->getType() &&
+ "setValue called with value of wrong type!");
+ setArgOperand(1, Val);
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const MemSetInst *) { return true; }
+ static inline bool classof(const IntrinsicInst *I) {
+ return I->getIntrinsicID() == Intrinsic::memset;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
+ }
+ };
+
+ /// MemTransferInst - This class wraps the llvm.memcpy/memmove intrinsics.
+ ///
+ class MemTransferInst : public MemIntrinsic {
+ public:
+ /// get* - Return the arguments to the instruction.
+ ///
+ Value *getRawSource() const { return const_cast<Value*>(getArgOperand(1)); }
+
+ /// getSource - This is just like getRawSource, but it strips off any cast
+ /// instructions that feed it, giving the original input. The returned
+ /// value is guaranteed to be a pointer.
+ Value *getSource() const { return getRawSource()->stripPointerCasts(); }
+
+ unsigned getSourceAddressSpace() const {
+ return cast<PointerType>(getRawSource()->getType())->getAddressSpace();
+ }
+
+ void setSource(Value *Ptr) {
+ assert(getRawSource()->getType() == Ptr->getType() &&
+ "setSource called with pointer of wrong type!");
+ setArgOperand(1, Ptr);
+ }
+
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const MemTransferInst *) { return true; }
+ static inline bool classof(const IntrinsicInst *I) {
+ return I->getIntrinsicID() == Intrinsic::memcpy ||
+ I->getIntrinsicID() == Intrinsic::memmove;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
+ }
+ };
+
+
+ /// MemCpyInst - This class wraps the llvm.memcpy intrinsic.
+ ///
+ class MemCpyInst : public MemTransferInst {
+ public:
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const MemCpyInst *) { return true; }
+ static inline bool classof(const IntrinsicInst *I) {
+ return I->getIntrinsicID() == Intrinsic::memcpy;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
+ }
+ };
+
+ /// MemMoveInst - This class wraps the llvm.memmove intrinsic.
+ ///
+ class MemMoveInst : public MemTransferInst {
+ public:
+ // Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const MemMoveInst *) { return true; }
+ static inline bool classof(const IntrinsicInst *I) {
+ return I->getIntrinsicID() == Intrinsic::memmove;
+ }
+ static inline bool classof(const Value *V) {
+ return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
+ }
+ };
+
+}
+
+#endif
diff --git a/include/llvm/Intrinsics.h b/include/llvm/Intrinsics.h
new file mode 100644
index 00000000000..c3503889e70
--- /dev/null
+++ b/include/llvm/Intrinsics.h
@@ -0,0 +1,128 @@
+//===-- llvm/Instrinsics.h - LLVM Intrinsic Function Handling ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a set of enums which allow processing of intrinsic
+// functions. Values of these enum types are returned by
+// Function::getIntrinsicID.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_INTRINSICS_H
+#define LLVM_INTRINSICS_H
+
+#include "llvm/ADT/ArrayRef.h"
+#include <string>
+
+namespace llvm {
+
+class Type;
+class FunctionType;
+class Function;
+class LLVMContext;
+class Module;
+class AttrListPtr;
+
+/// Intrinsic Namespace - This namespace contains an enum with a value for
+/// every intrinsic/builtin function known by LLVM. These enum values are
+/// returned by Function::getIntrinsicID().
+///
+namespace Intrinsic {
+ enum ID {
+ not_intrinsic = 0, // Must be zero
+
+ // Get the intrinsic enums generated from Intrinsics.td
+#define GET_INTRINSIC_ENUM_VALUES
+#include "llvm/Intrinsics.gen"
+#undef GET_INTRINSIC_ENUM_VALUES
+ , num_intrinsics
+ };
+
+ /// Intrinsic::getName(ID) - Return the LLVM name for an intrinsic, such as
+ /// "llvm.ppc.altivec.lvx".
+ std::string getName(ID id, ArrayRef<Type*> Tys = ArrayRef<Type*>());
+
+ /// Intrinsic::getType(ID) - Return the function type for an intrinsic.
+ ///
+ FunctionType *getType(LLVMContext &Context, ID id,
+ ArrayRef<Type*> Tys = ArrayRef<Type*>());
+
+ /// Intrinsic::isOverloaded(ID) - Returns true if the intrinsic can be
+ /// overloaded.
+ bool isOverloaded(ID id);
+
+ /// Intrinsic::getAttributes(ID) - Return the attributes for an intrinsic.
+ ///
+ AttrListPtr getAttributes(ID id);
+
+ /// Intrinsic::getDeclaration(M, ID) - Create or insert an LLVM Function
+ /// declaration for an intrinsic, and return it.
+ ///
+ /// The Tys and numTys parameters are for intrinsics with overloaded types
+ /// (e.g., those using iAny, fAny, vAny, or iPTRAny). For a declaration for an
+ /// overloaded intrinsic, Tys should point to an array of numTys pointers to
+ /// Type, and must provide exactly one type for each overloaded type in the
+ /// intrinsic.
+ Function *getDeclaration(Module *M, ID id,
+ ArrayRef<Type*> Tys = ArrayRef<Type*>());
+
+ /// Map a GCC builtin name to an intrinsic ID.
+ ID getIntrinsicForGCCBuiltin(const char *Prefix, const char *BuiltinName);
+
+ /// IITDescriptor - This is a type descriptor which explains the type
+ /// requirements of an intrinsic. This is returned by
+ /// getIntrinsicInfoTableEntries.
+ struct IITDescriptor {
+ enum IITDescriptorKind {
+ Void, MMX, Metadata, Float, Double,
+ Integer, Vector, Pointer, Struct,
+ Argument, ExtendVecArgument, TruncVecArgument
+ } Kind;
+
+ union {
+ unsigned Integer_Width;
+ unsigned Float_Width;
+ unsigned Vector_Width;
+ unsigned Pointer_AddressSpace;
+ unsigned Struct_NumElements;
+ unsigned Argument_Info;
+ };
+
+ enum ArgKind {
+ AK_AnyInteger,
+ AK_AnyFloat,
+ AK_AnyVector,
+ AK_AnyPointer
+ };
+ unsigned getArgumentNumber() const {
+ assert(Kind == Argument || Kind == ExtendVecArgument ||
+ Kind == TruncVecArgument);
+ return Argument_Info >> 2;
+ }
+ ArgKind getArgumentKind() const {
+ assert(Kind == Argument || Kind == ExtendVecArgument ||
+ Kind == TruncVecArgument);
+ return (ArgKind)(Argument_Info&3);
+ }
+
+ static IITDescriptor get(IITDescriptorKind K, unsigned Field) {
+ IITDescriptor Result = { K, { Field } };
+ return Result;
+ }
+ };
+
+ /// getIntrinsicInfoTableEntries - Return the IIT table descriptor for the
+ /// specified intrinsic into an array of IITDescriptors.
+ ///
+ void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl<IITDescriptor> &T);
+
+} // End Intrinsic namespace
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Intrinsics.td b/include/llvm/Intrinsics.td
new file mode 100644
index 00000000000..d1a0feef1d5
--- /dev/null
+++ b/include/llvm/Intrinsics.td
@@ -0,0 +1,465 @@
+//===- Intrinsics.td - Defines all LLVM intrinsics ---------*- tablegen -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines properties of all LLVM intrinsics.
+//
+//===----------------------------------------------------------------------===//
+
+include "llvm/CodeGen/ValueTypes.td"
+
+//===----------------------------------------------------------------------===//
+// Properties we keep track of for intrinsics.
+//===----------------------------------------------------------------------===//
+
+class IntrinsicProperty;
+
+// Intr*Mem - Memory properties. An intrinsic is allowed to have at most one of
+// these properties set. They are listed from the most aggressive (best to use
+// if correct) to the least aggressive. If no property is set, the worst case
+// is assumed (it may read and write any memory it can get access to and it may
+// have other side effects).
+
+// IntrNoMem - The intrinsic does not access memory or have any other side
+// effects. It may be CSE'd deleted if dead, etc.
+def IntrNoMem : IntrinsicProperty;
+
+// IntrReadArgMem - This intrinsic reads only from memory that one of its
+// pointer-typed arguments points to, but may read an unspecified amount.
+def IntrReadArgMem : IntrinsicProperty;
+
+// IntrReadMem - This intrinsic reads from unspecified memory, so it cannot be
+// moved across stores. However, it can be reordered otherwise and can be
+// deleted if dead.
+def IntrReadMem : IntrinsicProperty;
+
+// IntrReadWriteArgMem - This intrinsic reads and writes only from memory that
+// one of its arguments points to, but may access an unspecified amount. The
+// reads and writes may be volatile, but except for this it has no other side
+// effects.
+def IntrReadWriteArgMem : IntrinsicProperty;
+
+// Commutative - This intrinsic is commutative: X op Y == Y op X.
+def Commutative : IntrinsicProperty;
+
+// Throws - This intrinsic can throw.
+def Throws : IntrinsicProperty;
+
+// NoCapture - The specified argument pointer is not captured by the intrinsic.
+class NoCapture<int argNo> : IntrinsicProperty {
+ int ArgNo = argNo;
+}
+
+def IntrNoReturn : IntrinsicProperty;
+
+//===----------------------------------------------------------------------===//
+// Types used by intrinsics.
+//===----------------------------------------------------------------------===//
+
+class LLVMType<ValueType vt> {
+ ValueType VT = vt;
+}
+
+class LLVMQualPointerType<LLVMType elty, int addrspace>
+ : LLVMType<iPTR>{
+ LLVMType ElTy = elty;
+ int AddrSpace = addrspace;
+}
+
+class LLVMPointerType<LLVMType elty>
+ : LLVMQualPointerType<elty, 0>;
+
+class LLVMAnyPointerType<LLVMType elty>
+ : LLVMType<iPTRAny>{
+ LLVMType ElTy = elty;
+}
+
+// Match the type of another intrinsic parameter. Number is an index into the
+// list of overloaded types for the intrinsic, excluding all the fixed types.
+// The Number value must refer to a previously listed type. For example:
+// Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_anyfloat_ty, LLVMMatchType<0>]>
+// has two overloaded types, the 2nd and 3rd arguments. LLVMMatchType<0>
+// refers to the first overloaded type, which is the 2nd argument.
+class LLVMMatchType<int num>
+ : LLVMType<OtherVT>{
+ int Number = num;
+}
+
+// Match the type of another intrinsic parameter that is expected to be
+// an integral vector type, but change the element size to be twice as wide
+// or half as wide as the other type. This is only useful when the intrinsic
+// is overloaded, so the matched type should be declared as iAny.
+class LLVMExtendedElementVectorType<int num> : LLVMMatchType<num>;
+class LLVMTruncatedElementVectorType<int num> : LLVMMatchType<num>;
+
+def llvm_void_ty : LLVMType<isVoid>;
+def llvm_anyint_ty : LLVMType<iAny>;
+def llvm_anyfloat_ty : LLVMType<fAny>;
+def llvm_anyvector_ty : LLVMType<vAny>;
+def llvm_i1_ty : LLVMType<i1>;
+def llvm_i8_ty : LLVMType<i8>;
+def llvm_i16_ty : LLVMType<i16>;
+def llvm_i32_ty : LLVMType<i32>;
+def llvm_i64_ty : LLVMType<i64>;
+def llvm_float_ty : LLVMType<f32>;
+def llvm_double_ty : LLVMType<f64>;
+def llvm_f80_ty : LLVMType<f80>;
+def llvm_f128_ty : LLVMType<f128>;
+def llvm_ppcf128_ty : LLVMType<ppcf128>;
+def llvm_ptr_ty : LLVMPointerType<llvm_i8_ty>; // i8*
+def llvm_ptrptr_ty : LLVMPointerType<llvm_ptr_ty>; // i8**
+def llvm_anyptr_ty : LLVMAnyPointerType<llvm_i8_ty>; // (space)i8*
+def llvm_empty_ty : LLVMType<OtherVT>; // { }
+def llvm_descriptor_ty : LLVMPointerType<llvm_empty_ty>; // { }*
+def llvm_metadata_ty : LLVMType<MetadataVT>; // !{...}
+
+def llvm_x86mmx_ty : LLVMType<x86mmx>;
+def llvm_ptrx86mmx_ty : LLVMPointerType<llvm_x86mmx_ty>; // <1 x i64>*
+
+def llvm_v2i8_ty : LLVMType<v2i8>; // 2 x i8
+def llvm_v4i8_ty : LLVMType<v4i8>; // 4 x i8
+def llvm_v8i8_ty : LLVMType<v8i8>; // 8 x i8
+def llvm_v16i8_ty : LLVMType<v16i8>; // 16 x i8
+def llvm_v32i8_ty : LLVMType<v32i8>; // 32 x i8
+def llvm_v2i16_ty : LLVMType<v2i16>; // 2 x i16
+def llvm_v4i16_ty : LLVMType<v4i16>; // 4 x i16
+def llvm_v8i16_ty : LLVMType<v8i16>; // 8 x i16
+def llvm_v16i16_ty : LLVMType<v16i16>; // 16 x i16
+def llvm_v2i32_ty : LLVMType<v2i32>; // 2 x i32
+def llvm_v4i32_ty : LLVMType<v4i32>; // 4 x i32
+def llvm_v8i32_ty : LLVMType<v8i32>; // 8 x i32
+def llvm_v16i32_ty : LLVMType<v16i32>; // 16 x i32
+def llvm_v1i64_ty : LLVMType<v1i64>; // 1 x i64
+def llvm_v2i64_ty : LLVMType<v2i64>; // 2 x i64
+def llvm_v4i64_ty : LLVMType<v4i64>; // 4 x i64
+def llvm_v8i64_ty : LLVMType<v8i64>; // 8 x i64
+def llvm_v16i64_ty : LLVMType<v16i64>; // 16 x i64
+
+def llvm_v2f32_ty : LLVMType<v2f32>; // 2 x float
+def llvm_v4f32_ty : LLVMType<v4f32>; // 4 x float
+def llvm_v8f32_ty : LLVMType<v8f32>; // 8 x float
+def llvm_v2f64_ty : LLVMType<v2f64>; // 2 x double
+def llvm_v4f64_ty : LLVMType<v4f64>; // 4 x double
+
+def llvm_vararg_ty : LLVMType<isVoid>; // this means vararg here
+
+
+//===----------------------------------------------------------------------===//
+// Intrinsic Definitions.
+//===----------------------------------------------------------------------===//
+
+// Intrinsic class - This is used to define one LLVM intrinsic. The name of the
+// intrinsic definition should start with "int_", then match the LLVM intrinsic
+// name with the "llvm." prefix removed, and all "."s turned into "_"s. For
+// example, llvm.bswap.i16 -> int_bswap_i16.
+//
+// * RetTypes is a list containing the return types expected for the
+// intrinsic.
+// * ParamTypes is a list containing the parameter types expected for the
+// intrinsic.
+// * Properties can be set to describe the behavior of the intrinsic.
+//
+class SDPatternOperator;
+class Intrinsic<list<LLVMType> ret_types,
+ list<LLVMType> param_types = [],
+ list<IntrinsicProperty> properties = [],
+ string name = ""> : SDPatternOperator {
+ string LLVMName = name;
+ string TargetPrefix = ""; // Set to a prefix for target-specific intrinsics.
+ list<LLVMType> RetTypes = ret_types;
+ list<LLVMType> ParamTypes = param_types;
+ list<IntrinsicProperty> Properties = properties;
+
+ bit isTarget = 0;
+}
+
+/// GCCBuiltin - If this intrinsic exactly corresponds to a GCC builtin, this
+/// specifies the name of the builtin. This provides automatic CBE and CFE
+/// support.
+class GCCBuiltin<string name> {
+ string GCCBuiltinName = name;
+}
+
+
+//===--------------- Variable Argument Handling Intrinsics ----------------===//
+//
+
+def int_vastart : Intrinsic<[], [llvm_ptr_ty], [], "llvm.va_start">;
+def int_vacopy : Intrinsic<[], [llvm_ptr_ty, llvm_ptr_ty], [],
+ "llvm.va_copy">;
+def int_vaend : Intrinsic<[], [llvm_ptr_ty], [], "llvm.va_end">;
+
+//===------------------- Garbage Collection Intrinsics --------------------===//
+//
+def int_gcroot : Intrinsic<[],
+ [llvm_ptrptr_ty, llvm_ptr_ty]>;
+def int_gcread : Intrinsic<[llvm_ptr_ty],
+ [llvm_ptr_ty, llvm_ptrptr_ty],
+ [IntrReadArgMem]>;
+def int_gcwrite : Intrinsic<[],
+ [llvm_ptr_ty, llvm_ptr_ty, llvm_ptrptr_ty],
+ [IntrReadWriteArgMem, NoCapture<1>, NoCapture<2>]>;
+
+//===--------------------- Code Generator Intrinsics ----------------------===//
+//
+def int_returnaddress : Intrinsic<[llvm_ptr_ty], [llvm_i32_ty], [IntrNoMem]>;
+def int_frameaddress : Intrinsic<[llvm_ptr_ty], [llvm_i32_ty], [IntrNoMem]>;
+
+// Note: we treat stacksave/stackrestore as writemem because we don't otherwise
+// model their dependencies on allocas.
+def int_stacksave : Intrinsic<[llvm_ptr_ty]>,
+ GCCBuiltin<"__builtin_stack_save">;
+def int_stackrestore : Intrinsic<[], [llvm_ptr_ty]>,
+ GCCBuiltin<"__builtin_stack_restore">;
+
+// IntrReadWriteArgMem is more pessimistic than strictly necessary for prefetch,
+// however it does conveniently prevent the prefetch from being reordered
+// with respect to nearby accesses to the same memory.
+def int_prefetch : Intrinsic<[],
+ [llvm_ptr_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty],
+ [IntrReadWriteArgMem, NoCapture<0>]>;
+def int_pcmarker : Intrinsic<[], [llvm_i32_ty]>;
+
+def int_readcyclecounter : Intrinsic<[llvm_i64_ty]>;
+
+// Stack Protector Intrinsic - The stackprotector intrinsic writes the stack
+// guard to the correct place on the stack frame.
+def int_stackprotector : Intrinsic<[], [llvm_ptr_ty, llvm_ptrptr_ty], []>;
+
+//===------------------- Standard C Library Intrinsics --------------------===//
+//
+
+def int_memcpy : Intrinsic<[],
+ [llvm_anyptr_ty, llvm_anyptr_ty, llvm_anyint_ty,
+ llvm_i32_ty, llvm_i1_ty],
+ [IntrReadWriteArgMem, NoCapture<0>, NoCapture<1>]>;
+def int_memmove : Intrinsic<[],
+ [llvm_anyptr_ty, llvm_anyptr_ty, llvm_anyint_ty,
+ llvm_i32_ty, llvm_i1_ty],
+ [IntrReadWriteArgMem, NoCapture<0>, NoCapture<1>]>;
+def int_memset : Intrinsic<[],
+ [llvm_anyptr_ty, llvm_i8_ty, llvm_anyint_ty,
+ llvm_i32_ty, llvm_i1_ty],
+ [IntrReadWriteArgMem, NoCapture<0>]>;
+
+// These functions do not actually read memory, but they are sensitive to the
+// rounding mode. This needs to be modelled separately; in the meantime
+// declaring them as reading memory is conservatively correct.
+let Properties = [IntrReadMem] in {
+ def int_sqrt : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_powi : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>, llvm_i32_ty]>;
+ def int_sin : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_cos : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_pow : Intrinsic<[llvm_anyfloat_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>]>;
+ def int_log : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_log10: Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_log2 : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_exp : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_exp2 : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_fabs : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+ def int_floor : Intrinsic<[llvm_anyfloat_ty], [LLVMMatchType<0>]>;
+}
+
+let Properties = [IntrNoMem] in {
+ def int_fma : Intrinsic<[llvm_anyfloat_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>,
+ LLVMMatchType<0>]>;
+
+ def int_fmuladd : Intrinsic<[llvm_anyfloat_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>,
+ LLVMMatchType<0>]>;
+}
+
+// NOTE: these are internal interfaces.
+def int_setjmp : Intrinsic<[llvm_i32_ty], [llvm_ptr_ty]>;
+def int_longjmp : Intrinsic<[], [llvm_ptr_ty, llvm_i32_ty]>;
+def int_sigsetjmp : Intrinsic<[llvm_i32_ty] , [llvm_ptr_ty, llvm_i32_ty]>;
+def int_siglongjmp : Intrinsic<[], [llvm_ptr_ty, llvm_i32_ty]>;
+
+// Internal interface for object size checking
+def int_objectsize : Intrinsic<[llvm_anyint_ty], [llvm_ptr_ty, llvm_i1_ty],
+ [IntrNoMem]>,
+ GCCBuiltin<"__builtin_object_size">;
+
+//===------------------------- Expect Intrinsics --------------------------===//
+//
+def int_expect : Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>,
+ LLVMMatchType<0>], [IntrNoMem]>;
+
+//===-------------------- Bit Manipulation Intrinsics ---------------------===//
+//
+
+// None of these intrinsics accesses memory at all.
+let Properties = [IntrNoMem] in {
+ def int_bswap: Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>]>;
+ def int_ctpop: Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>]>;
+ def int_ctlz : Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>, llvm_i1_ty]>;
+ def int_cttz : Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>, llvm_i1_ty]>;
+}
+
+//===------------------------ Debugger Intrinsics -------------------------===//
+//
+
+// None of these intrinsics accesses memory at all...but that doesn't mean the
+// optimizers can change them aggressively. Special handling needed in a few
+// places.
+let Properties = [IntrNoMem] in {
+ def int_dbg_declare : Intrinsic<[],
+ [llvm_metadata_ty, llvm_metadata_ty]>;
+ def int_dbg_value : Intrinsic<[],
+ [llvm_metadata_ty, llvm_i64_ty,
+ llvm_metadata_ty]>;
+}
+
+//===------------------ Exception Handling Intrinsics----------------------===//
+//
+
+// The result of eh.typeid.for depends on the enclosing function, but inside a
+// given function it is 'const' and may be CSE'd etc.
+def int_eh_typeid_for : Intrinsic<[llvm_i32_ty], [llvm_ptr_ty], [IntrNoMem]>;
+
+def int_eh_return_i32 : Intrinsic<[], [llvm_i32_ty, llvm_ptr_ty]>;
+def int_eh_return_i64 : Intrinsic<[], [llvm_i64_ty, llvm_ptr_ty]>;
+
+def int_eh_unwind_init: Intrinsic<[]>,
+ GCCBuiltin<"__builtin_unwind_init">;
+
+def int_eh_dwarf_cfa : Intrinsic<[llvm_ptr_ty], [llvm_i32_ty]>;
+
+let Properties = [IntrNoMem] in {
+ def int_eh_sjlj_lsda : Intrinsic<[llvm_ptr_ty]>;
+ def int_eh_sjlj_callsite : Intrinsic<[], [llvm_i32_ty]>;
+}
+def int_eh_sjlj_functioncontext : Intrinsic<[], [llvm_ptr_ty]>;
+def int_eh_sjlj_setjmp : Intrinsic<[llvm_i32_ty], [llvm_ptr_ty]>;
+def int_eh_sjlj_longjmp : Intrinsic<[], [llvm_ptr_ty]>;
+
+//===---------------- Generic Variable Attribute Intrinsics----------------===//
+//
+def int_var_annotation : Intrinsic<[],
+ [llvm_ptr_ty, llvm_ptr_ty,
+ llvm_ptr_ty, llvm_i32_ty],
+ [], "llvm.var.annotation">;
+def int_ptr_annotation : Intrinsic<[LLVMAnyPointerType<llvm_anyint_ty>],
+ [LLVMMatchType<0>, llvm_ptr_ty, llvm_ptr_ty,
+ llvm_i32_ty],
+ [], "llvm.ptr.annotation">;
+def int_annotation : Intrinsic<[llvm_anyint_ty],
+ [LLVMMatchType<0>, llvm_ptr_ty,
+ llvm_ptr_ty, llvm_i32_ty],
+ [], "llvm.annotation">;
+
+//===------------------------ Trampoline Intrinsics -----------------------===//
+//
+def int_init_trampoline : Intrinsic<[],
+ [llvm_ptr_ty, llvm_ptr_ty, llvm_ptr_ty],
+ [IntrReadWriteArgMem, NoCapture<0>]>,
+ GCCBuiltin<"__builtin_init_trampoline">;
+
+def int_adjust_trampoline : Intrinsic<[llvm_ptr_ty], [llvm_ptr_ty],
+ [IntrReadArgMem]>,
+ GCCBuiltin<"__builtin_adjust_trampoline">;
+
+//===------------------------ Overflow Intrinsics -------------------------===//
+//
+
+// Expose the carry flag from add operations on two integrals.
+def int_sadd_with_overflow : Intrinsic<[llvm_anyint_ty, llvm_i1_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>],
+ [IntrNoMem]>;
+def int_uadd_with_overflow : Intrinsic<[llvm_anyint_ty, llvm_i1_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>],
+ [IntrNoMem]>;
+
+def int_ssub_with_overflow : Intrinsic<[llvm_anyint_ty, llvm_i1_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>],
+ [IntrNoMem]>;
+def int_usub_with_overflow : Intrinsic<[llvm_anyint_ty, llvm_i1_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>],
+ [IntrNoMem]>;
+
+def int_smul_with_overflow : Intrinsic<[llvm_anyint_ty, llvm_i1_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>],
+ [IntrNoMem]>;
+def int_umul_with_overflow : Intrinsic<[llvm_anyint_ty, llvm_i1_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>],
+ [IntrNoMem]>;
+
+//===------------------------- Memory Use Markers -------------------------===//
+//
+def int_lifetime_start : Intrinsic<[],
+ [llvm_i64_ty, llvm_ptr_ty],
+ [IntrReadWriteArgMem, NoCapture<1>]>;
+def int_lifetime_end : Intrinsic<[],
+ [llvm_i64_ty, llvm_ptr_ty],
+ [IntrReadWriteArgMem, NoCapture<1>]>;
+def int_invariant_start : Intrinsic<[llvm_descriptor_ty],
+ [llvm_i64_ty, llvm_ptr_ty],
+ [IntrReadWriteArgMem, NoCapture<1>]>;
+def int_invariant_end : Intrinsic<[],
+ [llvm_descriptor_ty, llvm_i64_ty,
+ llvm_ptr_ty],
+ [IntrReadWriteArgMem, NoCapture<2>]>;
+
+//===-------------------------- Other Intrinsics --------------------------===//
+//
+def int_flt_rounds : Intrinsic<[llvm_i32_ty]>,
+ GCCBuiltin<"__builtin_flt_rounds">;
+def int_trap : Intrinsic<[], [], [IntrNoReturn]>,
+ GCCBuiltin<"__builtin_trap">;
+def int_debugtrap : Intrinsic<[]>,
+ GCCBuiltin<"__builtin_debugtrap">;
+
+// NOP: calls/invokes to this intrinsic are removed by codegen
+def int_donothing : Intrinsic<[], [], [IntrNoMem]>;
+
+// Intrisics to support half precision floating point format
+let Properties = [IntrNoMem] in {
+def int_convert_to_fp16 : Intrinsic<[llvm_i16_ty], [llvm_float_ty]>,
+ GCCBuiltin<"__gnu_f2h_ieee">;
+def int_convert_from_fp16 : Intrinsic<[llvm_float_ty], [llvm_i16_ty]>,
+ GCCBuiltin<"__gnu_h2f_ieee">;
+}
+
+// These convert intrinsics are to support various conversions between
+// various types with rounding and saturation. NOTE: avoid using these
+// intrinsics as they might be removed sometime in the future and
+// most targets don't support them.
+def int_convertff : Intrinsic<[llvm_anyfloat_ty],
+ [llvm_anyfloat_ty, llvm_i32_ty, llvm_i32_ty]>;
+def int_convertfsi : Intrinsic<[llvm_anyfloat_ty],
+ [llvm_anyint_ty, llvm_i32_ty, llvm_i32_ty]>;
+def int_convertfui : Intrinsic<[llvm_anyfloat_ty],
+ [llvm_anyint_ty, llvm_i32_ty, llvm_i32_ty]>;
+def int_convertsif : Intrinsic<[llvm_anyint_ty],
+ [llvm_anyfloat_ty, llvm_i32_ty, llvm_i32_ty]>;
+def int_convertuif : Intrinsic<[llvm_anyint_ty],
+ [llvm_anyfloat_ty, llvm_i32_ty, llvm_i32_ty]>;
+def int_convertss : Intrinsic<[llvm_anyint_ty],
+ [llvm_anyint_ty, llvm_i32_ty, llvm_i32_ty]>;
+def int_convertsu : Intrinsic<[llvm_anyint_ty],
+ [llvm_anyint_ty, llvm_i32_ty, llvm_i32_ty]>;
+def int_convertus : Intrinsic<[llvm_anyint_ty],
+ [llvm_anyint_ty, llvm_i32_ty, llvm_i32_ty]>;
+def int_convertuu : Intrinsic<[llvm_anyint_ty],
+ [llvm_anyint_ty, llvm_i32_ty, llvm_i32_ty]>;
+
+//===----------------------------------------------------------------------===//
+// Target-specific intrinsics
+//===----------------------------------------------------------------------===//
+
+include "llvm/IntrinsicsPowerPC.td"
+include "llvm/IntrinsicsX86.td"
+include "llvm/IntrinsicsARM.td"
+include "llvm/IntrinsicsCellSPU.td"
+include "llvm/IntrinsicsXCore.td"
+include "llvm/IntrinsicsHexagon.td"
+include "llvm/IntrinsicsNVVM.td"
+include "llvm/IntrinsicsMips.td"
diff --git a/include/llvm/IntrinsicsARM.td b/include/llvm/IntrinsicsARM.td
new file mode 100644
index 00000000000..fa8034e0c2c
--- /dev/null
+++ b/include/llvm/IntrinsicsARM.td
@@ -0,0 +1,442 @@
+//===- IntrinsicsARM.td - Defines ARM intrinsics -----------*- tablegen -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines all of the ARM-specific intrinsics.
+//
+//===----------------------------------------------------------------------===//
+
+
+//===----------------------------------------------------------------------===//
+// TLS
+
+let TargetPrefix = "arm" in { // All intrinsics start with "llvm.arm.".
+ def int_arm_thread_pointer : GCCBuiltin<"__builtin_thread_pointer">,
+ Intrinsic<[llvm_ptr_ty], [], [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// Saturating Arithmentic
+
+let TargetPrefix = "arm" in { // All intrinsics start with "llvm.arm.".
+ def int_arm_qadd : GCCBuiltin<"__builtin_arm_qadd">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_arm_qsub : GCCBuiltin<"__builtin_arm_qsub">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+ def int_arm_ssat : GCCBuiltin<"__builtin_arm_ssat">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+ def int_arm_usat : GCCBuiltin<"__builtin_arm_usat">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// Load and Store exclusive doubleword
+
+let TargetPrefix = "arm" in { // All intrinsics start with "llvm.arm.".
+ def int_arm_strexd : Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty,
+ llvm_ptr_ty], [IntrReadWriteArgMem]>;
+ def int_arm_ldrexd : Intrinsic<[llvm_i32_ty, llvm_i32_ty], [llvm_ptr_ty],
+ [IntrReadArgMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// VFP
+
+let TargetPrefix = "arm" in { // All intrinsics start with "llvm.arm.".
+ def int_arm_get_fpscr : GCCBuiltin<"__builtin_arm_get_fpscr">,
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>;
+ def int_arm_set_fpscr : GCCBuiltin<"__builtin_arm_set_fpscr">,
+ Intrinsic<[], [llvm_i32_ty], []>;
+ def int_arm_vcvtr : Intrinsic<[llvm_float_ty], [llvm_anyfloat_ty],
+ [IntrNoMem]>;
+ def int_arm_vcvtru : Intrinsic<[llvm_float_ty], [llvm_anyfloat_ty],
+ [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// Coprocessor
+
+let TargetPrefix = "arm" in { // All intrinsics start with "llvm.arm.".
+ // Move to coprocessor
+ def int_arm_mcr : GCCBuiltin<"__builtin_arm_mcr">,
+ Intrinsic<[], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty, llvm_i32_ty], []>;
+ def int_arm_mcr2 : GCCBuiltin<"__builtin_arm_mcr2">,
+ Intrinsic<[], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty, llvm_i32_ty], []>;
+
+ // Move from coprocessor
+ def int_arm_mrc : GCCBuiltin<"__builtin_arm_mrc">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty], []>;
+ def int_arm_mrc2 : GCCBuiltin<"__builtin_arm_mrc2">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty], []>;
+
+ // Coprocessor data processing
+ def int_arm_cdp : GCCBuiltin<"__builtin_arm_cdp">,
+ Intrinsic<[], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty, llvm_i32_ty], []>;
+ def int_arm_cdp2 : GCCBuiltin<"__builtin_arm_cdp2">,
+ Intrinsic<[], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty, llvm_i32_ty], []>;
+
+ // Move from two registers to coprocessor
+ def int_arm_mcrr : GCCBuiltin<"__builtin_arm_mcrr">,
+ Intrinsic<[], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty], []>;
+ def int_arm_mcrr2 : GCCBuiltin<"__builtin_arm_mcrr2">,
+ Intrinsic<[], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty], []>;
+}
+
+//===----------------------------------------------------------------------===//
+// Advanced SIMD (NEON)
+
+let TargetPrefix = "arm" in { // All intrinsics start with "llvm.arm.".
+
+ // The following classes do not correspond directly to GCC builtins.
+ class Neon_1Arg_Intrinsic
+ : Intrinsic<[llvm_anyvector_ty], [LLVMMatchType<0>], [IntrNoMem]>;
+ class Neon_1Arg_Narrow_Intrinsic
+ : Intrinsic<[llvm_anyvector_ty],
+ [LLVMExtendedElementVectorType<0>], [IntrNoMem]>;
+ class Neon_2Arg_Intrinsic
+ : Intrinsic<[llvm_anyvector_ty], [LLVMMatchType<0>, LLVMMatchType<0>],
+ [IntrNoMem]>;
+ class Neon_2Arg_Narrow_Intrinsic
+ : Intrinsic<[llvm_anyvector_ty],
+ [LLVMExtendedElementVectorType<0>,
+ LLVMExtendedElementVectorType<0>],
+ [IntrNoMem]>;
+ class Neon_2Arg_Long_Intrinsic
+ : Intrinsic<[llvm_anyvector_ty],
+ [LLVMTruncatedElementVectorType<0>,
+ LLVMTruncatedElementVectorType<0>],
+ [IntrNoMem]>;
+ class Neon_3Arg_Intrinsic
+ : Intrinsic<[llvm_anyvector_ty],
+ [LLVMMatchType<0>, LLVMMatchType<0>, LLVMMatchType<0>],
+ [IntrNoMem]>;
+ class Neon_3Arg_Long_Intrinsic
+ : Intrinsic<[llvm_anyvector_ty],
+ [LLVMMatchType<0>,
+ LLVMTruncatedElementVectorType<0>,
+ LLVMTruncatedElementVectorType<0>],
+ [IntrNoMem]>;
+ class Neon_CvtFxToFP_Intrinsic
+ : Intrinsic<[llvm_anyfloat_ty], [llvm_anyint_ty, llvm_i32_ty], [IntrNoMem]>;
+ class Neon_CvtFPToFx_Intrinsic
+ : Intrinsic<[llvm_anyint_ty], [llvm_anyfloat_ty, llvm_i32_ty], [IntrNoMem]>;
+
+ // The table operands for VTBL and VTBX consist of 1 to 4 v8i8 vectors.
+ // Besides the table, VTBL has one other v8i8 argument and VTBX has two.
+ // Overall, the classes range from 2 to 6 v8i8 arguments.
+ class Neon_Tbl2Arg_Intrinsic
+ : Intrinsic<[llvm_v8i8_ty],
+ [llvm_v8i8_ty, llvm_v8i8_ty], [IntrNoMem]>;
+ class Neon_Tbl3Arg_Intrinsic
+ : Intrinsic<[llvm_v8i8_ty],
+ [llvm_v8i8_ty, llvm_v8i8_ty, llvm_v8i8_ty], [IntrNoMem]>;
+ class Neon_Tbl4Arg_Intrinsic
+ : Intrinsic<[llvm_v8i8_ty],
+ [llvm_v8i8_ty, llvm_v8i8_ty, llvm_v8i8_ty, llvm_v8i8_ty],
+ [IntrNoMem]>;
+ class Neon_Tbl5Arg_Intrinsic
+ : Intrinsic<[llvm_v8i8_ty],
+ [llvm_v8i8_ty, llvm_v8i8_ty, llvm_v8i8_ty, llvm_v8i8_ty,
+ llvm_v8i8_ty], [IntrNoMem]>;
+ class Neon_Tbl6Arg_Intrinsic
+ : Intrinsic<[llvm_v8i8_ty],
+ [llvm_v8i8_ty, llvm_v8i8_ty, llvm_v8i8_ty, llvm_v8i8_ty,
+ llvm_v8i8_ty, llvm_v8i8_ty], [IntrNoMem]>;
+}
+
+// Arithmetic ops
+
+let Properties = [IntrNoMem, Commutative] in {
+
+ // Vector Add.
+ def int_arm_neon_vhadds : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vhaddu : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vrhadds : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vrhaddu : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vqadds : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vqaddu : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vaddhn : Neon_2Arg_Narrow_Intrinsic;
+ def int_arm_neon_vraddhn : Neon_2Arg_Narrow_Intrinsic;
+
+ // Vector Multiply.
+ def int_arm_neon_vmulp : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vqdmulh : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vqrdmulh : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vmulls : Neon_2Arg_Long_Intrinsic;
+ def int_arm_neon_vmullu : Neon_2Arg_Long_Intrinsic;
+ def int_arm_neon_vmullp : Neon_2Arg_Long_Intrinsic;
+ def int_arm_neon_vqdmull : Neon_2Arg_Long_Intrinsic;
+
+ // Vector Multiply and Accumulate/Subtract.
+ def int_arm_neon_vqdmlal : Neon_3Arg_Long_Intrinsic;
+ def int_arm_neon_vqdmlsl : Neon_3Arg_Long_Intrinsic;
+
+ // Vector Maximum.
+ def int_arm_neon_vmaxs : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vmaxu : Neon_2Arg_Intrinsic;
+
+ // Vector Minimum.
+ def int_arm_neon_vmins : Neon_2Arg_Intrinsic;
+ def int_arm_neon_vminu : Neon_2Arg_Intrinsic;
+
+ // Vector Reciprocal Step.
+ def int_arm_neon_vrecps : Neon_2Arg_Intrinsic;
+
+ // Vector Reciprocal Square Root Step.
+ def int_arm_neon_vrsqrts : Neon_2Arg_Intrinsic;
+}
+
+// Vector Subtract.
+def int_arm_neon_vhsubs : Neon_2Arg_Intrinsic;
+def int_arm_neon_vhsubu : Neon_2Arg_Intrinsic;
+def int_arm_neon_vqsubs : Neon_2Arg_Intrinsic;
+def int_arm_neon_vqsubu : Neon_2Arg_Intrinsic;
+def int_arm_neon_vsubhn : Neon_2Arg_Narrow_Intrinsic;
+def int_arm_neon_vrsubhn : Neon_2Arg_Narrow_Intrinsic;
+
+// Vector Absolute Compare.
+let TargetPrefix = "arm" in {
+ def int_arm_neon_vacged : Intrinsic<[llvm_v2i32_ty],
+ [llvm_v2f32_ty, llvm_v2f32_ty],
+ [IntrNoMem]>;
+ def int_arm_neon_vacgeq : Intrinsic<[llvm_v4i32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_arm_neon_vacgtd : Intrinsic<[llvm_v2i32_ty],
+ [llvm_v2f32_ty, llvm_v2f32_ty],
+ [IntrNoMem]>;
+ def int_arm_neon_vacgtq : Intrinsic<[llvm_v4i32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+}
+
+// Vector Absolute Differences.
+def int_arm_neon_vabds : Neon_2Arg_Intrinsic;
+def int_arm_neon_vabdu : Neon_2Arg_Intrinsic;
+
+// Vector Pairwise Add.
+def int_arm_neon_vpadd : Neon_2Arg_Intrinsic;
+
+// Vector Pairwise Add Long.
+// Note: This is different than the other "long" NEON intrinsics because
+// the result vector has half as many elements as the source vector.
+// The source and destination vector types must be specified separately.
+let TargetPrefix = "arm" in {
+ def int_arm_neon_vpaddls : Intrinsic<[llvm_anyvector_ty], [llvm_anyvector_ty],
+ [IntrNoMem]>;
+ def int_arm_neon_vpaddlu : Intrinsic<[llvm_anyvector_ty], [llvm_anyvector_ty],
+ [IntrNoMem]>;
+}
+
+// Vector Pairwise Add and Accumulate Long.
+// Note: This is similar to vpaddl but the destination vector also appears
+// as the first argument.
+let TargetPrefix = "arm" in {
+ def int_arm_neon_vpadals : Intrinsic<[llvm_anyvector_ty],
+ [LLVMMatchType<0>, llvm_anyvector_ty],
+ [IntrNoMem]>;
+ def int_arm_neon_vpadalu : Intrinsic<[llvm_anyvector_ty],
+ [LLVMMatchType<0>, llvm_anyvector_ty],
+ [IntrNoMem]>;
+}
+
+// Vector Pairwise Maximum and Minimum.
+def int_arm_neon_vpmaxs : Neon_2Arg_Intrinsic;
+def int_arm_neon_vpmaxu : Neon_2Arg_Intrinsic;
+def int_arm_neon_vpmins : Neon_2Arg_Intrinsic;
+def int_arm_neon_vpminu : Neon_2Arg_Intrinsic;
+
+// Vector Shifts:
+//
+// The various saturating and rounding vector shift operations need to be
+// represented by intrinsics in LLVM, and even the basic VSHL variable shift
+// operation cannot be safely translated to LLVM's shift operators. VSHL can
+// be used for both left and right shifts, or even combinations of the two,
+// depending on the signs of the shift amounts. It also has well-defined
+// behavior for shift amounts that LLVM leaves undefined. Only basic shifts
+// by constants can be represented with LLVM's shift operators.
+//
+// The shift counts for these intrinsics are always vectors, even for constant
+// shifts, where the constant is replicated. For consistency with VSHL (and
+// other variable shift instructions), left shifts have positive shift counts
+// and right shifts have negative shift counts. This convention is also used
+// for constant right shift intrinsics, and to help preserve sanity, the
+// intrinsic names use "shift" instead of either "shl" or "shr". Where
+// applicable, signed and unsigned versions of the intrinsics are
+// distinguished with "s" and "u" suffixes. A few NEON shift instructions,
+// such as VQSHLU, take signed operands but produce unsigned results; these
+// use a "su" suffix.
+
+// Vector Shift.
+def int_arm_neon_vshifts : Neon_2Arg_Intrinsic;
+def int_arm_neon_vshiftu : Neon_2Arg_Intrinsic;
+def int_arm_neon_vshiftls : Neon_2Arg_Long_Intrinsic;
+def int_arm_neon_vshiftlu : Neon_2Arg_Long_Intrinsic;
+def int_arm_neon_vshiftn : Neon_2Arg_Narrow_Intrinsic;
+
+// Vector Rounding Shift.
+def int_arm_neon_vrshifts : Neon_2Arg_Intrinsic;
+def int_arm_neon_vrshiftu : Neon_2Arg_Intrinsic;
+def int_arm_neon_vrshiftn : Neon_2Arg_Narrow_Intrinsic;
+
+// Vector Saturating Shift.
+def int_arm_neon_vqshifts : Neon_2Arg_Intrinsic;
+def int_arm_neon_vqshiftu : Neon_2Arg_Intrinsic;
+def int_arm_neon_vqshiftsu : Neon_2Arg_Intrinsic;
+def int_arm_neon_vqshiftns : Neon_2Arg_Narrow_Intrinsic;
+def int_arm_neon_vqshiftnu : Neon_2Arg_Narrow_Intrinsic;
+def int_arm_neon_vqshiftnsu : Neon_2Arg_Narrow_Intrinsic;
+
+// Vector Saturating Rounding Shift.
+def int_arm_neon_vqrshifts : Neon_2Arg_Intrinsic;
+def int_arm_neon_vqrshiftu : Neon_2Arg_Intrinsic;
+def int_arm_neon_vqrshiftns : Neon_2Arg_Narrow_Intrinsic;
+def int_arm_neon_vqrshiftnu : Neon_2Arg_Narrow_Intrinsic;
+def int_arm_neon_vqrshiftnsu : Neon_2Arg_Narrow_Intrinsic;
+
+// Vector Shift and Insert.
+def int_arm_neon_vshiftins : Neon_3Arg_Intrinsic;
+
+// Vector Absolute Value and Saturating Absolute Value.
+def int_arm_neon_vabs : Neon_1Arg_Intrinsic;
+def int_arm_neon_vqabs : Neon_1Arg_Intrinsic;
+
+// Vector Saturating Negate.
+def int_arm_neon_vqneg : Neon_1Arg_Intrinsic;
+
+// Vector Count Leading Sign/Zero Bits.
+def int_arm_neon_vcls : Neon_1Arg_Intrinsic;
+def int_arm_neon_vclz : Neon_1Arg_Intrinsic;
+
+// Vector Count One Bits.
+def int_arm_neon_vcnt : Neon_1Arg_Intrinsic;
+
+// Vector Reciprocal Estimate.
+def int_arm_neon_vrecpe : Neon_1Arg_Intrinsic;
+
+// Vector Reciprocal Square Root Estimate.
+def int_arm_neon_vrsqrte : Neon_1Arg_Intrinsic;
+
+// Vector Conversions Between Floating-point and Fixed-point.
+def int_arm_neon_vcvtfp2fxs : Neon_CvtFPToFx_Intrinsic;
+def int_arm_neon_vcvtfp2fxu : Neon_CvtFPToFx_Intrinsic;
+def int_arm_neon_vcvtfxs2fp : Neon_CvtFxToFP_Intrinsic;
+def int_arm_neon_vcvtfxu2fp : Neon_CvtFxToFP_Intrinsic;
+
+// Vector Conversions Between Half-Precision and Single-Precision.
+def int_arm_neon_vcvtfp2hf
+ : Intrinsic<[llvm_v4i16_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+def int_arm_neon_vcvthf2fp
+ : Intrinsic<[llvm_v4f32_ty], [llvm_v4i16_ty], [IntrNoMem]>;
+
+// Narrowing Saturating Vector Moves.
+def int_arm_neon_vqmovns : Neon_1Arg_Narrow_Intrinsic;
+def int_arm_neon_vqmovnu : Neon_1Arg_Narrow_Intrinsic;
+def int_arm_neon_vqmovnsu : Neon_1Arg_Narrow_Intrinsic;
+
+// Vector Table Lookup.
+// The first 1-4 arguments are the table.
+def int_arm_neon_vtbl1 : Neon_Tbl2Arg_Intrinsic;
+def int_arm_neon_vtbl2 : Neon_Tbl3Arg_Intrinsic;
+def int_arm_neon_vtbl3 : Neon_Tbl4Arg_Intrinsic;
+def int_arm_neon_vtbl4 : Neon_Tbl5Arg_Intrinsic;
+
+// Vector Table Extension.
+// Some elements of the destination vector may not be updated, so the original
+// value of that vector is passed as the first argument. The next 1-4
+// arguments after that are the table.
+def int_arm_neon_vtbx1 : Neon_Tbl3Arg_Intrinsic;
+def int_arm_neon_vtbx2 : Neon_Tbl4Arg_Intrinsic;
+def int_arm_neon_vtbx3 : Neon_Tbl5Arg_Intrinsic;
+def int_arm_neon_vtbx4 : Neon_Tbl6Arg_Intrinsic;
+
+let TargetPrefix = "arm" in {
+
+ // De-interleaving vector loads from N-element structures.
+ // Source operands are the address and alignment.
+ def int_arm_neon_vld1 : Intrinsic<[llvm_anyvector_ty],
+ [llvm_ptr_ty, llvm_i32_ty],
+ [IntrReadArgMem]>;
+ def int_arm_neon_vld2 : Intrinsic<[llvm_anyvector_ty, LLVMMatchType<0>],
+ [llvm_ptr_ty, llvm_i32_ty],
+ [IntrReadArgMem]>;
+ def int_arm_neon_vld3 : Intrinsic<[llvm_anyvector_ty, LLVMMatchType<0>,
+ LLVMMatchType<0>],
+ [llvm_ptr_ty, llvm_i32_ty],
+ [IntrReadArgMem]>;
+ def int_arm_neon_vld4 : Intrinsic<[llvm_anyvector_ty, LLVMMatchType<0>,
+ LLVMMatchType<0>, LLVMMatchType<0>],
+ [llvm_ptr_ty, llvm_i32_ty],
+ [IntrReadArgMem]>;
+
+ // Vector load N-element structure to one lane.
+ // Source operands are: the address, the N input vectors (since only one
+ // lane is assigned), the lane number, and the alignment.
+ def int_arm_neon_vld2lane : Intrinsic<[llvm_anyvector_ty, LLVMMatchType<0>],
+ [llvm_ptr_ty, LLVMMatchType<0>,
+ LLVMMatchType<0>, llvm_i32_ty,
+ llvm_i32_ty], [IntrReadArgMem]>;
+ def int_arm_neon_vld3lane : Intrinsic<[llvm_anyvector_ty, LLVMMatchType<0>,
+ LLVMMatchType<0>],
+ [llvm_ptr_ty, LLVMMatchType<0>,
+ LLVMMatchType<0>, LLVMMatchType<0>,
+ llvm_i32_ty, llvm_i32_ty],
+ [IntrReadArgMem]>;
+ def int_arm_neon_vld4lane : Intrinsic<[llvm_anyvector_ty, LLVMMatchType<0>,
+ LLVMMatchType<0>, LLVMMatchType<0>],
+ [llvm_ptr_ty, LLVMMatchType<0>,
+ LLVMMatchType<0>, LLVMMatchType<0>,
+ LLVMMatchType<0>, llvm_i32_ty,
+ llvm_i32_ty], [IntrReadArgMem]>;
+
+ // Interleaving vector stores from N-element structures.
+ // Source operands are: the address, the N vectors, and the alignment.
+ def int_arm_neon_vst1 : Intrinsic<[],
+ [llvm_ptr_ty, llvm_anyvector_ty,
+ llvm_i32_ty], [IntrReadWriteArgMem]>;
+ def int_arm_neon_vst2 : Intrinsic<[],
+ [llvm_ptr_ty, llvm_anyvector_ty,
+ LLVMMatchType<0>, llvm_i32_ty],
+ [IntrReadWriteArgMem]>;
+ def int_arm_neon_vst3 : Intrinsic<[],
+ [llvm_ptr_ty, llvm_anyvector_ty,
+ LLVMMatchType<0>, LLVMMatchType<0>,
+ llvm_i32_ty], [IntrReadWriteArgMem]>;
+ def int_arm_neon_vst4 : Intrinsic<[],
+ [llvm_ptr_ty, llvm_anyvector_ty,
+ LLVMMatchType<0>, LLVMMatchType<0>,
+ LLVMMatchType<0>, llvm_i32_ty],
+ [IntrReadWriteArgMem]>;
+
+ // Vector store N-element structure from one lane.
+ // Source operands are: the address, the N vectors, the lane number, and
+ // the alignment.
+ def int_arm_neon_vst2lane : Intrinsic<[],
+ [llvm_ptr_ty, llvm_anyvector_ty,
+ LLVMMatchType<0>, llvm_i32_ty,
+ llvm_i32_ty], [IntrReadWriteArgMem]>;
+ def int_arm_neon_vst3lane : Intrinsic<[],
+ [llvm_ptr_ty, llvm_anyvector_ty,
+ LLVMMatchType<0>, LLVMMatchType<0>,
+ llvm_i32_ty, llvm_i32_ty],
+ [IntrReadWriteArgMem]>;
+ def int_arm_neon_vst4lane : Intrinsic<[],
+ [llvm_ptr_ty, llvm_anyvector_ty,
+ LLVMMatchType<0>, LLVMMatchType<0>,
+ LLVMMatchType<0>, llvm_i32_ty,
+ llvm_i32_ty], [IntrReadWriteArgMem]>;
+}
diff --git a/include/llvm/IntrinsicsCellSPU.td b/include/llvm/IntrinsicsCellSPU.td
new file mode 100644
index 00000000000..1e311bbecbc
--- /dev/null
+++ b/include/llvm/IntrinsicsCellSPU.td
@@ -0,0 +1,242 @@
+//==- IntrinsicsCellSPU.td - Cell SDK intrinsics -*- tablegen -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// Department at The Aerospace Corporation and is distributed under the
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+// Cell SPU Instructions:
+//===----------------------------------------------------------------------===//
+// TODO Items (not urgent today, but would be nice, low priority)
+//
+// ANDBI, ORBI: SPU constructs a 4-byte constant for these instructions by
+// concatenating the byte argument b as "bbbb". Could recognize this bit pattern
+// in 16-bit and 32-bit constants and reduce instruction count.
+//===----------------------------------------------------------------------===//
+
+// 7-bit integer type, used as an immediate:
+def cell_i7_ty: LLVMType<i8>;
+def cell_i8_ty: LLVMType<i8>;
+
+// Keep this here until it's actually supported:
+def llvm_i128_ty : LLVMType<i128>;
+
+class v16i8_u7imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, cell_i7_ty],
+ [IntrNoMem]>;
+
+class v16i8_u8imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+
+class v16i8_s10imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+
+class v16i8_u16imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+
+class v16i8_rr<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+
+class v8i16_s10imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+
+class v8i16_u16imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+
+class v8i16_rr<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+
+class v4i32_rr<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+
+class v4i32_u7imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, cell_i7_ty],
+ [IntrNoMem]>;
+
+class v4i32_s10imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+
+class v4i32_u16imm<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+
+class v4f32_rr<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+
+class v4f32_rrr<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+
+class v2f64_rr<string builtin_suffix> :
+ GCCBuiltin<!strconcat("__builtin_si_", builtin_suffix)>,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+
+// All Cell SPU intrinsics start with "llvm.spu.".
+let TargetPrefix = "spu" in {
+ def int_spu_si_fsmbi : v8i16_u16imm<"fsmbi">;
+ def int_spu_si_ah : v8i16_rr<"ah">;
+ def int_spu_si_ahi : v8i16_s10imm<"ahi">;
+ def int_spu_si_a : v4i32_rr<"a">;
+ def int_spu_si_ai : v4i32_s10imm<"ai">;
+ def int_spu_si_sfh : v8i16_rr<"sfh">;
+ def int_spu_si_sfhi : v8i16_s10imm<"sfhi">;
+ def int_spu_si_sf : v4i32_rr<"sf">;
+ def int_spu_si_sfi : v4i32_s10imm<"sfi">;
+ def int_spu_si_addx : v4i32_rr<"addx">;
+ def int_spu_si_cg : v4i32_rr<"cg">;
+ def int_spu_si_cgx : v4i32_rr<"cgx">;
+ def int_spu_si_sfx : v4i32_rr<"sfx">;
+ def int_spu_si_bg : v4i32_rr<"bg">;
+ def int_spu_si_bgx : v4i32_rr<"bgx">;
+ def int_spu_si_mpy : // This is special:
+ GCCBuiltin<"__builtin_si_mpy">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpyu : // This is special:
+ GCCBuiltin<"__builtin_si_mpyu">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpyi : // This is special:
+ GCCBuiltin<"__builtin_si_mpyi">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpyui : // This is special:
+ GCCBuiltin<"__builtin_si_mpyui">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpya : // This is special:
+ GCCBuiltin<"__builtin_si_mpya">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpyh : // This is special:
+ GCCBuiltin<"__builtin_si_mpyh">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpys : // This is special:
+ GCCBuiltin<"__builtin_si_mpys">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpyhh : // This is special:
+ GCCBuiltin<"__builtin_si_mpyhh">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpyhha : // This is special:
+ GCCBuiltin<"__builtin_si_mpyhha">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpyhhu : // This is special:
+ GCCBuiltin<"__builtin_si_mpyhhu">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_spu_si_mpyhhau : // This is special:
+ GCCBuiltin<"__builtin_si_mpyhhau">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+
+ def int_spu_si_shli: v4i32_u7imm<"shli">;
+
+ def int_spu_si_shlqbi:
+ GCCBuiltin<!strconcat("__builtin_si_", "shlqbi")>,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+
+ def int_spu_si_shlqbii: v16i8_u7imm<"shlqbii">;
+ def int_spu_si_shlqby:
+ GCCBuiltin<!strconcat("__builtin_si_", "shlqby")>,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_spu_si_shlqbyi: v16i8_u7imm<"shlqbyi">;
+
+ def int_spu_si_ceq: v4i32_rr<"ceq">;
+ def int_spu_si_ceqi: v4i32_s10imm<"ceqi">;
+ def int_spu_si_ceqb: v16i8_rr<"ceqb">;
+ def int_spu_si_ceqbi: v16i8_u8imm<"ceqbi">;
+ def int_spu_si_ceqh: v8i16_rr<"ceqh">;
+ def int_spu_si_ceqhi: v8i16_s10imm<"ceqhi">;
+ def int_spu_si_cgt: v4i32_rr<"cgt">;
+ def int_spu_si_cgti: v4i32_s10imm<"cgti">;
+ def int_spu_si_cgtb: v16i8_rr<"cgtb">;
+ def int_spu_si_cgtbi: v16i8_u8imm<"cgtbi">;
+ def int_spu_si_cgth: v8i16_rr<"cgth">;
+ def int_spu_si_cgthi: v8i16_s10imm<"cgthi">;
+ def int_spu_si_clgtb: v16i8_rr<"clgtb">;
+ def int_spu_si_clgtbi: v16i8_u8imm<"clgtbi">;
+ def int_spu_si_clgth: v8i16_rr<"clgth">;
+ def int_spu_si_clgthi: v8i16_s10imm<"clgthi">;
+ def int_spu_si_clgt: v4i32_rr<"clgt">;
+ def int_spu_si_clgti: v4i32_s10imm<"clgti">;
+
+ def int_spu_si_and: v4i32_rr<"and">;
+ def int_spu_si_andbi: v16i8_u8imm<"andbi">;
+ def int_spu_si_andc: v4i32_rr<"andc">;
+ def int_spu_si_andhi: v8i16_s10imm<"andhi">;
+ def int_spu_si_andi: v4i32_s10imm<"andi">;
+
+ def int_spu_si_or: v4i32_rr<"or">;
+ def int_spu_si_orbi: v16i8_u8imm<"orbi">;
+ def int_spu_si_orc: v4i32_rr<"orc">;
+ def int_spu_si_orhi: v8i16_s10imm<"orhi">;
+ def int_spu_si_ori: v4i32_s10imm<"ori">;
+
+ def int_spu_si_xor: v4i32_rr<"xor">;
+ def int_spu_si_xorbi: v16i8_u8imm<"xorbi">;
+ def int_spu_si_xorhi: v8i16_s10imm<"xorhi">;
+ def int_spu_si_xori: v4i32_s10imm<"xori">;
+
+ def int_spu_si_nor: v4i32_rr<"nor">;
+ def int_spu_si_nand: v4i32_rr<"nand">;
+
+ def int_spu_si_fa: v4f32_rr<"fa">;
+ def int_spu_si_fs: v4f32_rr<"fs">;
+ def int_spu_si_fm: v4f32_rr<"fm">;
+
+ def int_spu_si_fceq: v4f32_rr<"fceq">;
+ def int_spu_si_fcmeq: v4f32_rr<"fcmeq">;
+ def int_spu_si_fcgt: v4f32_rr<"fcgt">;
+ def int_spu_si_fcmgt: v4f32_rr<"fcmgt">;
+
+ def int_spu_si_fma: v4f32_rrr<"fma">;
+ def int_spu_si_fnms: v4f32_rrr<"fnms">;
+ def int_spu_si_fms: v4f32_rrr<"fms">;
+
+ def int_spu_si_dfa: v2f64_rr<"dfa">;
+ def int_spu_si_dfs: v2f64_rr<"dfs">;
+ def int_spu_si_dfm: v2f64_rr<"dfm">;
+
+//def int_spu_si_dfceq: v2f64_rr<"dfceq">;
+//def int_spu_si_dfcmeq: v2f64_rr<"dfcmeq">;
+//def int_spu_si_dfcgt: v2f64_rr<"dfcgt">;
+//def int_spu_si_dfcmgt: v2f64_rr<"dfcmgt">;
+
+ def int_spu_si_dfnma: v2f64_rr<"dfnma">;
+ def int_spu_si_dfma: v2f64_rr<"dfma">;
+ def int_spu_si_dfnms: v2f64_rr<"dfnms">;
+ def int_spu_si_dfms: v2f64_rr<"dfms">;
+}
diff --git a/include/llvm/IntrinsicsHexagon.td b/include/llvm/IntrinsicsHexagon.td
new file mode 100644
index 00000000000..8a8872931f3
--- /dev/null
+++ b/include/llvm/IntrinsicsHexagon.td
@@ -0,0 +1,4877 @@
+//===- IntrinsicsHexagon.td - Defines Hexagon intrinsics ---*- tablegen -*-===//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines all of the Hexagon-specific intrinsics.
+//
+//===----------------------------------------------------------------------===//
+
+//===----------------------------------------------------------------------===//
+// Definitions for all Hexagon intrinsics.
+//
+// All Hexagon intrinsics start with "llvm.hexagon.".
+let TargetPrefix = "hexagon" in {
+ /// Hexagon_Intrinsic - Base class for all Hexagon intrinsics.
+ class Hexagon_Intrinsic<string GCCIntSuffix, list<LLVMType> ret_types,
+ list<LLVMType> param_types,
+ list<IntrinsicProperty> properties>
+ : GCCBuiltin<!strconcat("__builtin_", GCCIntSuffix)>,
+ Intrinsic<ret_types, param_types, properties>;
+}
+
+//===----------------------------------------------------------------------===//
+//
+// DEF_FUNCTION_TYPE_1(QI_ftype_MEM,BT_BOOL,BT_PTR) ->
+// Hexagon_qi_mem_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_mem_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_ptr_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(void_ftype_SI,BT_VOID,BT_INT) ->
+// Hexagon_void_si_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_void_si_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_void_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(HI_ftype_SI,BT_I16,BT_INT) ->
+// Hexagon_hi_si_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_hi_si_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i16_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(SI_ftype_SI,BT_INT,BT_INT) ->
+// Hexagon_si_si_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_si_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(DI_ftype_SI,BT_LONGLONG,BT_INT) ->
+// Hexagon_di_si_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_si_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(SI_ftype_DI,BT_INT,BT_LONGLONG) ->
+// Hexagon_si_di_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_di_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(DI_ftype_DI,BT_LONGLONG,BT_LONGLONG) ->
+// Hexagon_di_di_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_di_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(QI_ftype_QI,BT_BOOL,BT_BOOL) ->
+// Hexagon_qi_qi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_qi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(QI_ftype_SI,BT_BOOL,BT_INT) ->
+// Hexagon_qi_si_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_si_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(DI_ftype_QI,BT_LONGLONG,BT_BOOL) ->
+// Hexagon_di_qi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_qi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_1(SI_ftype_QI,BT_INT,BT_BOOL) ->
+// Hexagon_si_qi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_qi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(QI_ftype_SISI,BT_BOOL,BT_INT,BT_INT) ->
+// Hexagon_qi_sisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_sisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(void_ftype_SISI,BT_VOID,BT_INT,BT_INT) ->
+// Hexagon_void_sisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_void_sisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_void_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(SI_ftype_SISI,BT_INT,BT_INT,BT_INT) ->
+// Hexagon_si_sisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_sisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(USI_ftype_SISI,BT_UINT,BT_INT,BT_INT) ->
+// Hexagon_usi_sisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_usi_sisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(DI_ftype_SISI,BT_LONGLONG,BT_INT,BT_INT) ->
+// Hexagon_di_sisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_sisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(UDI_ftype_SISI,BT_ULONGLONG,BT_INT,BT_INT) ->
+// Hexagon_udi_sisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_udi_sisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(DI_ftype_SIDI,BT_LONGLONG,BT_INT,BT_LONGLONG) ->
+// Hexagon_di_sidi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_sidi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i32_ty, llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(DI_ftype_DISI,BT_LONGLONG,BT_LONGLONG,BT_INT) ->
+// Hexagon_di_disi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_disi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(SI_ftype_SIDI,BT_INT,BT_INT,BT_LONGLONG) ->
+// Hexagon_si_sidi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_sidi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(SI_ftype_DIDI,BT_INT,BT_LONGLONG,BT_LONGLONG) ->
+// Hexagon_si_didi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_didi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(DI_ftype_DIDI,BT_LONGLONG,BT_LONGLONG,BT_LONGLONG) ->
+// Hexagon_di_didi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_didi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(UDI_ftype_DIDI,BT_ULONGLONG,BT_LONGLONG,BT_LONGLONG) ->
+// Hexagon_udi_didi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_udi_didi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(SI_ftype_DISI,BT_INT,BT_LONGLONG,BT_INT) ->
+// Hexagon_si_disi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_disi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i64_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(QI_ftype_DIDI,BT_BOOL,BT_LONGLONG,BT_LONGLONG) ->
+// Hexagon_qi_didi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_didi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(QI_ftype_SIDI,BT_BOOL,BT_INT,BT_LONGLONG) ->
+// Hexagon_qi_didi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_sidi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_i32_ty, llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(QI_ftype_DISI,BT_BOOL,BT_LONGLONG,BT_INT) ->
+// Hexagon_qi_disi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_disi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_i64_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(QI_ftype_QIQI,BT_BOOL,BT_BOOL,BT_BOOL) ->
+// Hexagon_qi_qiqi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_qiqi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(QI_ftype_QIQIQI,BT_BOOL,BT_BOOL,BT_BOOL) ->
+// Hexagon_qi_qiqiqi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_qiqiqi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(SI_ftype_QIQI,BT_INT,BT_BOOL,BT_BOOL) ->
+// Hexagon_si_qiqi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_qiqi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_2(SI_ftype_QISI,BT_INT,BT_BOOL,BT_INT) ->
+// Hexagon_si_qisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_qisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i1_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(void_ftype_SISISI,BT_VOID,BT_INT,BT_INT,BT_INT) ->
+// Hexagon_void_sisisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_void_sisisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_void_ty], [llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(SI_ftype_SISISI,BT_INT,BT_INT,BT_INT,BT_INT) ->
+// Hexagon_si_sisisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_sisisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(DI_ftype_SISISI,BT_LONGLONG,BT_INT,BT_INT,BT_INT) ->
+// Hexagon_di_sisisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_sisisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(SI_ftype_DISISI,BT_INT,BT_LONGLONG,BT_INT,BT_INT) ->
+// Hexagon_si_disisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_disisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i64_ty, llvm_i32_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(DI_ftype_DISISI,BT_LONGLONG,BT_LONGLONG,BT_INT,BT_INT) ->
+// Hexagon_di_disisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_disisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i32_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(SI_ftype_SIDISI,BT_INT,BT_INT,BT_LONGLONG,BT_INT) ->
+// Hexagon_si_sidisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_sidisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i64_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(DI_ftype_DIDISI,BT_LONGLONG,BT_LONGLONG,
+// BT_LONGLONG,BT_INT) ->
+// Hexagon_di_didisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_didisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(SI_ftype_SIDIDI,BT_INT,BT_INT,BT_LONGLONG,BT_LONGLONG) ->
+// Hexagon_si_sididi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_sididi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i64_ty,
+ llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(DI_ftype_DIDIDI,BT_LONGLONG,BT_LONGLONG,BT_LONGLONG,
+// BT_LONGLONG) ->
+// Hexagon_di_dididi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_dididi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty,
+ llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(SI_ftype_SISIDI,BT_INT,BT_INT,BT_INT,BT_LONGLONG) ->
+// Hexagon_si_sisidi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_sisidi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty,
+ llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(SI_ftype_QISISI,BT_INT,BT_BOOL,BT_INT,BT_INT) ->
+// Hexagon_si_qisisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_qisisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(DI_ftype_QISISI,BT_LONGLONG,BT_BOOL,BT_INT,BT_INT) ->
+// Hexagon_di_qisisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_qisisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i1_ty, llvm_i32_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(DI_ftype_QIDIDI,BT_LONGLONG,BT_BOOL,BT_LONGLONG,
+// BT_LONGLONG) ->
+// Hexagon_di_qididi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_qididi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i32_ty, llvm_i64_ty,
+ llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_3(DI_ftype_DIDIQI,BT_LONGLONG,BT_LONGLONG,BT_LONGLONG,
+// BT_BOOL) ->
+// Hexagon_di_didiqi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_didiqi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_4(SI_ftype_SISISISI,BT_INT,BT_INT,BT_INT,BT_INT,BT_INT) ->
+// Hexagon_si_sisisisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_sisisisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty,
+ llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// DEF_FUNCTION_TYPE_4(DI_ftype_DIDISISI,BT_LONGLONG,BT_LONGLONG,
+// BT_LONGLONG,BT_INT,BT_INT) ->
+// Hexagon_di_didisisi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_didisisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty,
+ llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+
+class Hexagon_mem_memmemsisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_ptr_ty], [llvm_ptr_ty, llvm_ptr_ty,
+ llvm_i32_ty, llvm_i32_ty],
+ [IntrReadWriteArgMem]>;
+
+//
+// Hexagon_sf_df_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_sf_si_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_float_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_sf_df_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_sf_df_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_float_ty], [llvm_double_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_sf_di_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_sf_di_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_float_ty], [llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_df_sf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_df_sf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_double_ty], [llvm_float_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_di_sf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_sf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_float_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_sf_sf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_sf_sf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_float_ty], [llvm_float_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_si_sf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_sf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_float_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_si_df_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_si_df_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i32_ty], [llvm_double_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_sf_sfsf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_sf_sfsf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_qi_sfsf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_sfsf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_qi_sfsi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_sfsi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_float_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_qi_sfqi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_sfqi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_float_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_sf_sfsfsf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_sf_sfsfsf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_float_ty], [llvm_float_ty, llvm_float_ty,
+ llvm_float_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_sf_sfsfsfqi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_sf_sfsfsfqi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_float_ty], [llvm_float_ty, llvm_float_ty,
+ llvm_float_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_di_dididi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_dididisi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty,
+ llvm_i64_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_df_si_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_df_si_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_double_ty], [llvm_i32_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_df_di_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_df_di_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_double_ty], [llvm_i64_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_di_df_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_di_df_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i64_ty], [llvm_double_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_df_df_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_df_df_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_double_ty], [llvm_double_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_df_dfdf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_df_dfdf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_qi_dfdf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_dfdf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_qi_dfsi_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_qi_dfsi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_i1_ty], [llvm_double_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+//
+//
+// Hexagon_df_dfdfdf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_df_dfdfdf_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_double_ty], [llvm_double_ty, llvm_double_ty,
+ llvm_double_ty],
+ [IntrNoMem]>;
+//
+// Hexagon_df_dfdfdf_Intrinsic<string GCCIntSuffix>
+//
+class Hexagon_df_dfdfdfqi_Intrinsic<string GCCIntSuffix>
+ : Hexagon_Intrinsic<GCCIntSuffix,
+ [llvm_double_ty], [llvm_double_ty, llvm_double_ty,
+ llvm_double_ty,
+ llvm_i32_ty],
+ [IntrNoMem]>;
+
+
+// This one below will not be generated from iset.py.
+// So make sure, you don't overwrite this one.
+//
+// BUILTIN_INFO(SI_to_SXTHI_asrh,SI_ftype_SI,1)
+//
+def int_hexagon_SI_to_SXTHI_asrh :
+Hexagon_si_si_Intrinsic<"SI_to_SXTHI_asrh">;
+//
+// BUILTIN_INFO_NONCONST(circ_ldd,PTR_ftype_PTRPTRSISI,4)
+//
+def int_hexagon_circ_ldd :
+Hexagon_mem_memmemsisi_Intrinsic<"circ_ldd">;
+// This one above will not be generated from iset.py.
+// So make sure, you don't overwrite this one.
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpeq,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpeq :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpeq">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpgt,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpgt :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpgt">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpgtu,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpgtu :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpgtu">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpeqp,QI_ftype_DIDI,2)
+//
+def int_hexagon_C2_cmpeqp :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_C2_cmpeqp">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpgtp,QI_ftype_DIDI,2)
+//
+def int_hexagon_C2_cmpgtp :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_C2_cmpgtp">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpgtup,QI_ftype_DIDI,2)
+//
+def int_hexagon_C2_cmpgtup :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_C2_cmpgtup">;
+//
+// BUILTIN_INFO(HEXAGON.A4_rcmpeqi,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_rcmpeqi :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_rcmpeqi">;
+//
+// BUILTIN_INFO(HEXAGON.A4_rcmpneqi,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_rcmpneqi :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_rcmpneqi">;
+//
+// BUILTIN_INFO(HEXAGON.A4_rcmpeq,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_rcmpeq :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_rcmpeq">;
+//
+// BUILTIN_INFO(HEXAGON.A4_rcmpneq,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_rcmpneq :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_rcmpneq">;
+//
+// BUILTIN_INFO(HEXAGON.C2_bitsset,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_bitsset :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_bitsset">;
+//
+// BUILTIN_INFO(HEXAGON.C2_bitsclr,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_bitsclr :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_bitsclr">;
+//
+// BUILTIN_INFO(HEXAGON.C4_nbitsset,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_nbitsset :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_nbitsset">;
+//
+// BUILTIN_INFO(HEXAGON.C4_nbitsclr,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_nbitsclr :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_nbitsclr">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpeqi,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpeqi :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpeqi">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpgti,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpgti :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpgti">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpgtui,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpgtui :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpgtui">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpgei,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpgei :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpgei">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpgeui,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpgeui :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpgeui">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmplt,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmplt :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmplt">;
+//
+// BUILTIN_INFO(HEXAGON.C2_cmpltu,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_cmpltu :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_cmpltu">;
+//
+// BUILTIN_INFO(HEXAGON.C2_bitsclri,QI_ftype_SISI,2)
+//
+def int_hexagon_C2_bitsclri :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C2_bitsclri">;
+//
+// BUILTIN_INFO(HEXAGON.C4_nbitsclri,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_nbitsclri :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_nbitsclri">;
+//
+// BUILTIN_INFO(HEXAGON.C4_cmpneqi,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_cmpneqi :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_cmpneqi">;
+//
+// BUILTIN_INFO(HEXAGON.C4_cmpltei,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_cmpltei :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_cmpltei">;
+//
+// BUILTIN_INFO(HEXAGON.C4_cmplteui,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_cmplteui :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_cmplteui">;
+//
+// BUILTIN_INFO(HEXAGON.C4_cmpneq,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_cmpneq :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_cmpneq">;
+//
+// BUILTIN_INFO(HEXAGON.C4_cmplte,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_cmplte :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_cmplte">;
+//
+// BUILTIN_INFO(HEXAGON.C4_cmplteu,QI_ftype_SISI,2)
+//
+def int_hexagon_C4_cmplteu :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_C4_cmplteu">;
+//
+// BUILTIN_INFO(HEXAGON.C2_and,QI_ftype_QIQI,2)
+//
+def int_hexagon_C2_and :
+Hexagon_qi_qiqi_Intrinsic<"HEXAGON_C2_and">;
+//
+// BUILTIN_INFO(HEXAGON.C2_or,QI_ftype_QIQI,2)
+//
+def int_hexagon_C2_or :
+Hexagon_qi_qiqi_Intrinsic<"HEXAGON_C2_or">;
+//
+// BUILTIN_INFO(HEXAGON.C2_xor,QI_ftype_QIQI,2)
+//
+def int_hexagon_C2_xor :
+Hexagon_qi_qiqi_Intrinsic<"HEXAGON_C2_xor">;
+//
+// BUILTIN_INFO(HEXAGON.C2_andn,QI_ftype_QIQI,2)
+//
+def int_hexagon_C2_andn :
+Hexagon_qi_qiqi_Intrinsic<"HEXAGON_C2_andn">;
+//
+// BUILTIN_INFO(HEXAGON.C2_not,QI_ftype_QI,1)
+//
+def int_hexagon_C2_not :
+Hexagon_qi_qi_Intrinsic<"HEXAGON_C2_not">;
+//
+// BUILTIN_INFO(HEXAGON.C2_orn,QI_ftype_QIQI,2)
+//
+def int_hexagon_C2_orn :
+Hexagon_qi_qiqi_Intrinsic<"HEXAGON_C2_orn">;
+//
+// BUILTIN_INFO(HEXAGON.C4_and_and,QI_ftype_QIQIQI,3)
+//
+def int_hexagon_C4_and_and :
+Hexagon_qi_qiqiqi_Intrinsic<"HEXAGON_C4_and_and">;
+//
+// BUILTIN_INFO(HEXAGON.C4_and_or,QI_ftype_QIQIQI,3)
+//
+def int_hexagon_C4_and_or :
+Hexagon_qi_qiqiqi_Intrinsic<"HEXAGON_C4_and_or">;
+//
+// BUILTIN_INFO(HEXAGON.C4_or_and,QI_ftype_QIQIQI,3)
+//
+def int_hexagon_C4_or_and :
+Hexagon_qi_qiqiqi_Intrinsic<"HEXAGON_C4_or_and">;
+//
+// BUILTIN_INFO(HEXAGON.C4_or_or,QI_ftype_QIQIQI,3)
+//
+def int_hexagon_C4_or_or :
+Hexagon_qi_qiqiqi_Intrinsic<"HEXAGON_C4_or_or">;
+//
+// BUILTIN_INFO(HEXAGON.C4_and_andn,QI_ftype_QIQIQI,3)
+//
+def int_hexagon_C4_and_andn :
+Hexagon_qi_qiqiqi_Intrinsic<"HEXAGON_C4_and_andn">;
+//
+// BUILTIN_INFO(HEXAGON.C4_and_orn,QI_ftype_QIQIQI,3)
+//
+def int_hexagon_C4_and_orn :
+Hexagon_qi_qiqiqi_Intrinsic<"HEXAGON_C4_and_orn">;
+//
+// BUILTIN_INFO(HEXAGON.C4_or_andn,QI_ftype_QIQIQI,3)
+//
+def int_hexagon_C4_or_andn :
+Hexagon_qi_qiqiqi_Intrinsic<"HEXAGON_C4_or_andn">;
+//
+// BUILTIN_INFO(HEXAGON.C4_or_orn,QI_ftype_QIQIQI,3)
+//
+def int_hexagon_C4_or_orn :
+Hexagon_qi_qiqiqi_Intrinsic<"HEXAGON_C4_or_orn">;
+//
+// BUILTIN_INFO(HEXAGON.C2_pxfer_map,QI_ftype_QI,1)
+//
+def int_hexagon_C2_pxfer_map :
+Hexagon_qi_qi_Intrinsic<"HEXAGON_C2_pxfer_map">;
+//
+// BUILTIN_INFO(HEXAGON.C2_any8,QI_ftype_QI,1)
+//
+def int_hexagon_C2_any8 :
+Hexagon_qi_qi_Intrinsic<"HEXAGON_C2_any8">;
+//
+// BUILTIN_INFO(HEXAGON.C2_all8,QI_ftype_QI,1)
+//
+def int_hexagon_C2_all8 :
+Hexagon_qi_qi_Intrinsic<"HEXAGON_C2_all8">;
+//
+// BUILTIN_INFO(HEXAGON.C2_vitpack,SI_ftype_QIQI,2)
+//
+def int_hexagon_C2_vitpack :
+Hexagon_si_qiqi_Intrinsic<"HEXAGON_C2_vitpack">;
+//
+// BUILTIN_INFO(HEXAGON.C2_mux,SI_ftype_QISISI,3)
+//
+def int_hexagon_C2_mux :
+Hexagon_si_qisisi_Intrinsic<"HEXAGON_C2_mux">;
+//
+// BUILTIN_INFO(HEXAGON.C2_muxii,SI_ftype_QISISI,3)
+//
+def int_hexagon_C2_muxii :
+Hexagon_si_qisisi_Intrinsic<"HEXAGON_C2_muxii">;
+//
+// BUILTIN_INFO(HEXAGON.C2_muxir,SI_ftype_QISISI,3)
+//
+def int_hexagon_C2_muxir :
+Hexagon_si_qisisi_Intrinsic<"HEXAGON_C2_muxir">;
+//
+// BUILTIN_INFO(HEXAGON.C2_muxri,SI_ftype_QISISI,3)
+//
+def int_hexagon_C2_muxri :
+Hexagon_si_qisisi_Intrinsic<"HEXAGON_C2_muxri">;
+//
+// BUILTIN_INFO(HEXAGON.C2_vmux,DI_ftype_QIDIDI,3)
+//
+def int_hexagon_C2_vmux :
+Hexagon_di_qididi_Intrinsic<"HEXAGON_C2_vmux">;
+//
+// BUILTIN_INFO(HEXAGON.C2_mask,DI_ftype_QI,1)
+//
+def int_hexagon_C2_mask :
+Hexagon_di_qi_Intrinsic<"HEXAGON_C2_mask">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vcmpbeq,QI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vcmpbeq :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A2_vcmpbeq">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpbeqi,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmpbeqi :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmpbeqi">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpbeq_any,QI_ftype_DIDI,2)
+//
+def int_hexagon_A4_vcmpbeq_any :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A4_vcmpbeq_any">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vcmpbgtu,QI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vcmpbgtu :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A2_vcmpbgtu">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpbgtui,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmpbgtui :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmpbgtui">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpbgt,QI_ftype_DIDI,2)
+//
+def int_hexagon_A4_vcmpbgt :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A4_vcmpbgt">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpbgti,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmpbgti :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmpbgti">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmpbeq,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmpbeq :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmpbeq">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmpbeqi,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmpbeqi :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmpbeqi">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmpbgtu,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmpbgtu :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmpbgtu">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmpbgtui,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmpbgtui :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmpbgtui">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmpbgt,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmpbgt :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmpbgt">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmpbgti,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmpbgti :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmpbgti">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vcmpheq,QI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vcmpheq :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A2_vcmpheq">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vcmphgt,QI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vcmphgt :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A2_vcmphgt">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vcmphgtu,QI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vcmphgtu :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A2_vcmphgtu">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpheqi,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmpheqi :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmpheqi">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmphgti,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmphgti :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmphgti">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmphgtui,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmphgtui :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmphgtui">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmpheq,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmpheq :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmpheq">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmphgt,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmphgt :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmphgt">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmphgtu,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmphgtu :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmphgtu">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmpheqi,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmpheqi :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmpheqi">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmphgti,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmphgti :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmphgti">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cmphgtui,QI_ftype_SISI,2)
+//
+def int_hexagon_A4_cmphgtui :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_A4_cmphgtui">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vcmpweq,QI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vcmpweq :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A2_vcmpweq">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vcmpwgt,QI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vcmpwgt :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A2_vcmpwgt">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vcmpwgtu,QI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vcmpwgtu :
+Hexagon_qi_didi_Intrinsic<"HEXAGON_A2_vcmpwgtu">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpweqi,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmpweqi :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmpweqi">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpwgti,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmpwgti :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmpwgti">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vcmpwgtui,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_vcmpwgtui :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_vcmpwgtui">;
+//
+// BUILTIN_INFO(HEXAGON.A4_boundscheck,QI_ftype_SIDI,2)
+//
+def int_hexagon_A4_boundscheck :
+Hexagon_qi_sidi_Intrinsic<"HEXAGON_A4_boundscheck">;
+//
+// BUILTIN_INFO(HEXAGON.A4_tlbmatch,QI_ftype_DISI,2)
+//
+def int_hexagon_A4_tlbmatch :
+Hexagon_qi_disi_Intrinsic<"HEXAGON_A4_tlbmatch">;
+//
+// BUILTIN_INFO(HEXAGON.C2_tfrpr,SI_ftype_QI,1)
+//
+def int_hexagon_C2_tfrpr :
+Hexagon_si_qi_Intrinsic<"HEXAGON_C2_tfrpr">;
+//
+// BUILTIN_INFO(HEXAGON.C2_tfrrp,QI_ftype_SI,1)
+//
+def int_hexagon_C2_tfrrp :
+Hexagon_qi_si_Intrinsic<"HEXAGON_C2_tfrrp">;
+//
+// BUILTIN_INFO(HEXAGON.C4_fastcorner9,QI_ftype_QIQI,2)
+//
+def int_hexagon_C4_fastcorner9 :
+Hexagon_qi_qiqi_Intrinsic<"HEXAGON_C4_fastcorner9">;
+//
+// BUILTIN_INFO(HEXAGON.C4_fastcorner9_not,QI_ftype_QIQI,2)
+//
+def int_hexagon_C4_fastcorner9_not :
+Hexagon_qi_qiqi_Intrinsic<"HEXAGON_C4_fastcorner9_not">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_hh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_hh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_hh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_hh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_hl_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_hl_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_hl_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_hl_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_lh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_lh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_lh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_lh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_ll_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_ll_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_ll_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_ll_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_hh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_hh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_hh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_hh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_hl_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_hl_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_hl_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_hl_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_lh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_lh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_lh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_lh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_ll_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_ll_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_ll_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_ll_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_sat_hh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_sat_hh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_sat_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_sat_hh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_sat_hh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_sat_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_sat_hl_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_sat_hl_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_sat_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_sat_hl_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_sat_hl_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_sat_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_sat_lh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_sat_lh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_sat_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_sat_lh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_sat_lh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_sat_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_sat_ll_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_sat_ll_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_sat_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_acc_sat_ll_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_acc_sat_ll_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_acc_sat_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_sat_hh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_sat_hh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_sat_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_sat_hh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_sat_hh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_sat_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_sat_hl_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_sat_hl_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_sat_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_sat_hl_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_sat_hl_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_sat_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_sat_lh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_sat_lh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_sat_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_sat_lh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_sat_lh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_sat_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_sat_ll_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_sat_ll_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_sat_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_nac_sat_ll_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpy_nac_sat_ll_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpy_nac_sat_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_hh_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_hh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_hh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_hh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_hl_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_hl_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_hl_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_hl_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_lh_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_lh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_lh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_lh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_ll_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_ll_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_ll_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_ll_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_hh_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_hh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_hh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_hh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_hl_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_hl_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_hl_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_hl_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_lh_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_lh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_lh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_lh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_ll_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_ll_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_ll_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_ll_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_rnd_hh_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_rnd_hh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_rnd_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_rnd_hh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_rnd_hh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_rnd_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_rnd_hl_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_rnd_hl_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_rnd_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_rnd_hl_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_rnd_hl_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_rnd_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_rnd_lh_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_rnd_lh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_rnd_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_rnd_lh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_rnd_lh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_rnd_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_rnd_ll_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_rnd_ll_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_rnd_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_rnd_ll_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_rnd_ll_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_rnd_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_rnd_hh_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_rnd_hh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_rnd_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_rnd_hh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_rnd_hh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_rnd_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_rnd_hl_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_rnd_hl_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_rnd_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_rnd_hl_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_rnd_hl_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_rnd_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_rnd_lh_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_rnd_lh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_rnd_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_rnd_lh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_rnd_lh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_rnd_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_rnd_ll_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_rnd_ll_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_rnd_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_sat_rnd_ll_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_sat_rnd_ll_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_sat_rnd_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_acc_hh_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_acc_hh_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_acc_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_acc_hh_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_acc_hh_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_acc_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_acc_hl_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_acc_hl_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_acc_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_acc_hl_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_acc_hl_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_acc_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_acc_lh_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_acc_lh_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_acc_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_acc_lh_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_acc_lh_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_acc_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_acc_ll_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_acc_ll_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_acc_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_acc_ll_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_acc_ll_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_acc_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_nac_hh_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_nac_hh_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_nac_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_nac_hh_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_nac_hh_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_nac_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_nac_hl_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_nac_hl_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_nac_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_nac_hl_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_nac_hl_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_nac_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_nac_lh_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_nac_lh_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_nac_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_nac_lh_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_nac_lh_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_nac_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_nac_ll_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_nac_ll_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_nac_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_nac_ll_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyd_nac_ll_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyd_nac_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_hh_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_hh_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_hh_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_hh_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_hl_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_hl_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_hl_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_hl_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_lh_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_lh_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_lh_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_lh_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_ll_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_ll_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_ll_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_ll_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_rnd_hh_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_rnd_hh_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_rnd_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_rnd_hh_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_rnd_hh_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_rnd_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_rnd_hl_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_rnd_hl_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_rnd_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_rnd_hl_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_rnd_hl_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_rnd_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_rnd_lh_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_rnd_lh_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_rnd_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_rnd_lh_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_rnd_lh_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_rnd_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_rnd_ll_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_rnd_ll_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_rnd_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyd_rnd_ll_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyd_rnd_ll_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyd_rnd_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_acc_hh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_acc_hh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_acc_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_acc_hh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_acc_hh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_acc_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_acc_hl_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_acc_hl_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_acc_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_acc_hl_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_acc_hl_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_acc_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_acc_lh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_acc_lh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_acc_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_acc_lh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_acc_lh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_acc_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_acc_ll_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_acc_ll_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_acc_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_acc_ll_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_acc_ll_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_acc_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_nac_hh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_nac_hh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_nac_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_nac_hh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_nac_hh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_nac_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_nac_hl_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_nac_hl_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_nac_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_nac_hl_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_nac_hl_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_nac_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_nac_lh_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_nac_lh_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_nac_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_nac_lh_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_nac_lh_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_nac_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_nac_ll_s0,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_nac_ll_s0 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_nac_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_nac_ll_s1,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_mpyu_nac_ll_s1 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_mpyu_nac_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_hh_s0,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_hh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_hh_s1,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_hh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_hl_s0,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_hl_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_hl_s1,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_hl_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_lh_s0,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_lh_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_lh_s1,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_lh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_ll_s0,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_ll_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_ll_s1,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_ll_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_acc_hh_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_acc_hh_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_acc_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_acc_hh_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_acc_hh_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_acc_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_acc_hl_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_acc_hl_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_acc_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_acc_hl_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_acc_hl_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_acc_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_acc_lh_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_acc_lh_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_acc_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_acc_lh_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_acc_lh_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_acc_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_acc_ll_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_acc_ll_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_acc_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_acc_ll_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_acc_ll_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_acc_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_nac_hh_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_nac_hh_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_nac_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_nac_hh_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_nac_hh_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_nac_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_nac_hl_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_nac_hl_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_nac_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_nac_hl_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_nac_hl_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_nac_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_nac_lh_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_nac_lh_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_nac_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_nac_lh_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_nac_lh_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_nac_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_nac_ll_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_nac_ll_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_nac_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_nac_ll_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_mpyud_nac_ll_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_mpyud_nac_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_hh_s0,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyud_hh_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyud_hh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_hh_s1,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyud_hh_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyud_hh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_hl_s0,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyud_hl_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyud_hl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_hl_s1,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyud_hl_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyud_hl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_lh_s0,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyud_lh_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyud_lh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_lh_s1,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyud_lh_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyud_lh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_ll_s0,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyud_ll_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyud_ll_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyud_ll_s1,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyud_ll_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_mpyud_ll_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpysmi,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpysmi :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpysmi">;
+//
+// BUILTIN_INFO(HEXAGON.M2_macsip,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_macsip :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_macsip">;
+//
+// BUILTIN_INFO(HEXAGON.M2_macsin,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_macsin :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_macsin">;
+//
+// BUILTIN_INFO(HEXAGON.M2_dpmpyss_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_dpmpyss_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_dpmpyss_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_dpmpyss_acc_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_dpmpyss_acc_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_dpmpyss_acc_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_dpmpyss_nac_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_dpmpyss_nac_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_dpmpyss_nac_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_dpmpyuu_s0,UDI_ftype_SISI,2)
+//
+def int_hexagon_M2_dpmpyuu_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_dpmpyuu_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_dpmpyuu_acc_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_dpmpyuu_acc_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_dpmpyuu_acc_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_dpmpyuu_nac_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_dpmpyuu_nac_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_dpmpyuu_nac_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_up,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_up :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_up">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_up_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_up_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_up_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpy_up_s1_sat,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpy_up_s1_sat :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpy_up_s1_sat">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyu_up,USI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyu_up :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyu_up">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpysu_up,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpysu_up :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpysu_up">;
+//
+// BUILTIN_INFO(HEXAGON.M2_dpmpyss_rnd_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_dpmpyss_rnd_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_dpmpyss_rnd_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M4_mac_up_s1_sat,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_mac_up_s1_sat :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_mac_up_s1_sat">;
+//
+// BUILTIN_INFO(HEXAGON.M4_nac_up_s1_sat,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_nac_up_s1_sat :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_nac_up_s1_sat">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyi,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyi :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyi">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mpyui,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_mpyui :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_mpyui">;
+//
+// BUILTIN_INFO(HEXAGON.M2_maci,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_maci :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_maci">;
+//
+// BUILTIN_INFO(HEXAGON.M2_acci,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_acci :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_acci">;
+//
+// BUILTIN_INFO(HEXAGON.M2_accii,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_accii :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_accii">;
+//
+// BUILTIN_INFO(HEXAGON.M2_nacci,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_nacci :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_nacci">;
+//
+// BUILTIN_INFO(HEXAGON.M2_naccii,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_naccii :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_naccii">;
+//
+// BUILTIN_INFO(HEXAGON.M2_subacc,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_subacc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_subacc">;
+//
+// BUILTIN_INFO(HEXAGON.M4_mpyrr_addr,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_mpyrr_addr :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_mpyrr_addr">;
+//
+// BUILTIN_INFO(HEXAGON.M4_mpyri_addr_u2,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_mpyri_addr_u2 :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_mpyri_addr_u2">;
+//
+// BUILTIN_INFO(HEXAGON.M4_mpyri_addr,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_mpyri_addr :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_mpyri_addr">;
+//
+// BUILTIN_INFO(HEXAGON.M4_mpyri_addi,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_mpyri_addi :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_mpyri_addi">;
+//
+// BUILTIN_INFO(HEXAGON.M4_mpyrr_addi,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_mpyrr_addi :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_mpyrr_addi">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmpy2s_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_vmpy2s_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_vmpy2s_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmpy2s_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_vmpy2s_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_vmpy2s_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmac2s_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_vmac2s_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_vmac2s_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmac2s_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_vmac2s_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_vmac2s_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmpy2su_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_vmpy2su_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_vmpy2su_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmpy2su_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_vmpy2su_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_vmpy2su_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmac2su_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_vmac2su_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_vmac2su_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmac2su_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_vmac2su_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_vmac2su_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmpy2s_s0pack,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_vmpy2s_s0pack :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_vmpy2s_s0pack">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmpy2s_s1pack,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_vmpy2s_s1pack :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_vmpy2s_s1pack">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmac2,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_vmac2 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_vmac2">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmpy2es_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vmpy2es_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vmpy2es_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmpy2es_s1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vmpy2es_s1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vmpy2es_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmac2es_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vmac2es_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vmac2es_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmac2es_s1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vmac2es_s1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vmac2es_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vmac2es,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vmac2es :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vmac2es">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrmac_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vrmac_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vrmac_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrmpy_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vrmpy_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vrmpy_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vdmpyrs_s0,SI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vdmpyrs_s0 :
+Hexagon_si_didi_Intrinsic<"HEXAGON_M2_vdmpyrs_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vdmpyrs_s1,SI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vdmpyrs_s1 :
+Hexagon_si_didi_Intrinsic<"HEXAGON_M2_vdmpyrs_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vrmpybuu,DI_ftype_DIDI,2)
+//
+def int_hexagon_M5_vrmpybuu :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M5_vrmpybuu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vrmacbuu,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M5_vrmacbuu :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M5_vrmacbuu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vrmpybsu,DI_ftype_DIDI,2)
+//
+def int_hexagon_M5_vrmpybsu :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M5_vrmpybsu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vrmacbsu,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M5_vrmacbsu :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M5_vrmacbsu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vmpybuu,DI_ftype_SISI,2)
+//
+def int_hexagon_M5_vmpybuu :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M5_vmpybuu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vmpybsu,DI_ftype_SISI,2)
+//
+def int_hexagon_M5_vmpybsu :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M5_vmpybsu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vmacbuu,DI_ftype_DISISI,3)
+//
+def int_hexagon_M5_vmacbuu :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M5_vmacbuu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vmacbsu,DI_ftype_DISISI,3)
+//
+def int_hexagon_M5_vmacbsu :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M5_vmacbsu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vdmpybsu,DI_ftype_DIDI,2)
+//
+def int_hexagon_M5_vdmpybsu :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M5_vdmpybsu">;
+//
+// BUILTIN_INFO(HEXAGON.M5_vdmacbsu,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M5_vdmacbsu :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M5_vdmacbsu">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vdmacs_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vdmacs_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vdmacs_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vdmacs_s1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vdmacs_s1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vdmacs_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vdmpys_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vdmpys_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vdmpys_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vdmpys_s1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vdmpys_s1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vdmpys_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpyrs_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpyrs_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_cmpyrs_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpyrs_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpyrs_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_cmpyrs_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpyrsc_s0,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpyrsc_s0 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_cmpyrsc_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpyrsc_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpyrsc_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_cmpyrsc_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmacs_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cmacs_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cmacs_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmacs_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cmacs_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cmacs_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmacsc_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cmacsc_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cmacsc_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmacsc_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cmacsc_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cmacsc_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpys_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpys_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_cmpys_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpys_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpys_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_cmpys_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpysc_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpysc_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_cmpysc_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpysc_s1,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpysc_s1 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_cmpysc_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cnacs_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cnacs_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cnacs_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cnacs_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cnacs_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cnacs_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cnacsc_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cnacsc_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cnacsc_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cnacsc_s1,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cnacsc_s1 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cnacsc_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmpys_s1,DI_ftype_DISI,2)
+//
+def int_hexagon_M2_vrcmpys_s1 :
+Hexagon_di_disi_Intrinsic<"HEXAGON_M2_vrcmpys_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmpys_acc_s1,DI_ftype_DIDISI,3)
+//
+def int_hexagon_M2_vrcmpys_acc_s1 :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_M2_vrcmpys_acc_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmpys_s1rp,SI_ftype_DISI,2)
+//
+def int_hexagon_M2_vrcmpys_s1rp :
+Hexagon_si_disi_Intrinsic<"HEXAGON_M2_vrcmpys_s1rp">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmacls_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmacls_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmacls_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmacls_s1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmacls_s1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmacls_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmachs_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmachs_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmachs_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmachs_s1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmachs_s1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmachs_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyl_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyl_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyl_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyl_s1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyl_s1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyh_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyh_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyh_s1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyh_s1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmacls_rs0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmacls_rs0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmacls_rs0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmacls_rs1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmacls_rs1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmacls_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmachs_rs0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmachs_rs0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmachs_rs0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmachs_rs1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmachs_rs1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmachs_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyl_rs0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyl_rs0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyl_rs0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyl_rs1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyl_rs1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyl_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyh_rs0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyh_rs0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyh_rs0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyh_rs1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyh_rs1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyh_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vrmpyeh_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M4_vrmpyeh_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M4_vrmpyeh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vrmpyeh_s1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M4_vrmpyeh_s1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M4_vrmpyeh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vrmpyeh_acc_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M4_vrmpyeh_acc_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M4_vrmpyeh_acc_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vrmpyeh_acc_s1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M4_vrmpyeh_acc_s1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M4_vrmpyeh_acc_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vrmpyoh_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M4_vrmpyoh_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M4_vrmpyoh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vrmpyoh_s1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M4_vrmpyoh_s1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M4_vrmpyoh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vrmpyoh_acc_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M4_vrmpyoh_acc_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M4_vrmpyoh_acc_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vrmpyoh_acc_s1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M4_vrmpyoh_acc_s1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M4_vrmpyoh_acc_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_hmmpyl_rs1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_hmmpyl_rs1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_hmmpyl_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_hmmpyh_rs1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_hmmpyh_rs1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_hmmpyh_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_hmmpyl_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_hmmpyl_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_hmmpyl_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_hmmpyh_s1,SI_ftype_SISI,2)
+//
+def int_hexagon_M2_hmmpyh_s1 :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_M2_hmmpyh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmaculs_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmaculs_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmaculs_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmaculs_s1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmaculs_s1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmaculs_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmacuhs_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmacuhs_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmacuhs_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmacuhs_s1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmacuhs_s1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmacuhs_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyul_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyul_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyul_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyul_s1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyul_s1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyul_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyuh_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyuh_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyuh_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyuh_s1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyuh_s1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyuh_s1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmaculs_rs0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmaculs_rs0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmaculs_rs0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmaculs_rs1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmaculs_rs1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmaculs_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmacuhs_rs0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmacuhs_rs0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmacuhs_rs0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmacuhs_rs1,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_mmacuhs_rs1 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_mmacuhs_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyul_rs0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyul_rs0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyul_rs0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyul_rs1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyul_rs1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyul_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyuh_rs0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyuh_rs0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyuh_rs0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_mmpyuh_rs1,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_mmpyuh_rs1 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_mmpyuh_rs1">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmaci_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vrcmaci_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vrcmaci_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmacr_s0,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vrcmacr_s0 :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vrcmacr_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmaci_s0c,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vrcmaci_s0c :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vrcmaci_s0c">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmacr_s0c,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vrcmacr_s0c :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vrcmacr_s0c">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmaci_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cmaci_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cmaci_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmacr_s0,DI_ftype_DISISI,3)
+//
+def int_hexagon_M2_cmacr_s0 :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M2_cmacr_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmpyi_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vrcmpyi_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vrcmpyi_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmpyr_s0,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vrcmpyr_s0 :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vrcmpyr_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmpyi_s0c,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vrcmpyi_s0c :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vrcmpyi_s0c">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vrcmpyr_s0c,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vrcmpyr_s0c :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vrcmpyr_s0c">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpyi_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpyi_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_cmpyi_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M2_cmpyr_s0,DI_ftype_SISI,2)
+//
+def int_hexagon_M2_cmpyr_s0 :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M2_cmpyr_s0">;
+//
+// BUILTIN_INFO(HEXAGON.M4_cmpyi_wh,SI_ftype_DISI,2)
+//
+def int_hexagon_M4_cmpyi_wh :
+Hexagon_si_disi_Intrinsic<"HEXAGON_M4_cmpyi_wh">;
+//
+// BUILTIN_INFO(HEXAGON.M4_cmpyr_wh,SI_ftype_DISI,2)
+//
+def int_hexagon_M4_cmpyr_wh :
+Hexagon_si_disi_Intrinsic<"HEXAGON_M4_cmpyr_wh">;
+//
+// BUILTIN_INFO(HEXAGON.M4_cmpyi_whc,SI_ftype_DISI,2)
+//
+def int_hexagon_M4_cmpyi_whc :
+Hexagon_si_disi_Intrinsic<"HEXAGON_M4_cmpyi_whc">;
+//
+// BUILTIN_INFO(HEXAGON.M4_cmpyr_whc,SI_ftype_DISI,2)
+//
+def int_hexagon_M4_cmpyr_whc :
+Hexagon_si_disi_Intrinsic<"HEXAGON_M4_cmpyr_whc">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vcmpy_s0_sat_i,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vcmpy_s0_sat_i :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vcmpy_s0_sat_i">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vcmpy_s0_sat_r,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vcmpy_s0_sat_r :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vcmpy_s0_sat_r">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vcmpy_s1_sat_i,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vcmpy_s1_sat_i :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vcmpy_s1_sat_i">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vcmpy_s1_sat_r,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vcmpy_s1_sat_r :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vcmpy_s1_sat_r">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vcmac_s0_sat_i,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vcmac_s0_sat_i :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vcmac_s0_sat_i">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vcmac_s0_sat_r,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M2_vcmac_s0_sat_r :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M2_vcmac_s0_sat_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vcrotate,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_vcrotate :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_vcrotate">;
+//
+// BUILTIN_INFO(HEXAGON.S4_vrcrotate_acc,DI_ftype_DIDISISI,4)
+//
+def int_hexagon_S4_vrcrotate_acc :
+Hexagon_di_didisisi_Intrinsic<"HEXAGON_S4_vrcrotate_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S4_vrcrotate,DI_ftype_DISISI,3)
+//
+def int_hexagon_S4_vrcrotate :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_S4_vrcrotate">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vcnegh,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_vcnegh :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_vcnegh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vrcnegh,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_vrcnegh :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_vrcnegh">;
+//
+// BUILTIN_INFO(HEXAGON.M4_pmpyw,DI_ftype_SISI,2)
+//
+def int_hexagon_M4_pmpyw :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M4_pmpyw">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vpmpyh,DI_ftype_SISI,2)
+//
+def int_hexagon_M4_vpmpyh :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_M4_vpmpyh">;
+//
+// BUILTIN_INFO(HEXAGON.M4_pmpyw_acc,DI_ftype_DISISI,3)
+//
+def int_hexagon_M4_pmpyw_acc :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M4_pmpyw_acc">;
+//
+// BUILTIN_INFO(HEXAGON.M4_vpmpyh_acc,DI_ftype_DISISI,3)
+//
+def int_hexagon_M4_vpmpyh_acc :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_M4_vpmpyh_acc">;
+//
+// BUILTIN_INFO(HEXAGON.A2_add,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_add :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_add">;
+//
+// BUILTIN_INFO(HEXAGON.A2_sub,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_sub :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_sub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addsat,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addsat :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addsat">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subsat,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subsat :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subsat">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addi,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addi :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addi">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_l16_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_l16_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_l16_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_l16_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_l16_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_l16_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_l16_sat_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_l16_sat_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_l16_sat_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_l16_sat_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_l16_sat_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_l16_sat_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_l16_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_l16_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_l16_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_l16_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_l16_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_l16_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_l16_sat_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_l16_sat_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_l16_sat_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_l16_sat_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_l16_sat_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_l16_sat_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_h16_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_h16_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_h16_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_h16_lh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_h16_lh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_h16_lh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_h16_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_h16_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_h16_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_h16_hh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_h16_hh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_h16_hh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_h16_sat_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_h16_sat_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_h16_sat_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_h16_sat_lh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_h16_sat_lh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_h16_sat_lh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_h16_sat_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_h16_sat_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_h16_sat_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addh_h16_sat_hh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_addh_h16_sat_hh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_addh_h16_sat_hh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_h16_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_h16_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_h16_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_h16_lh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_h16_lh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_h16_lh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_h16_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_h16_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_h16_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_h16_hh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_h16_hh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_h16_hh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_h16_sat_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_h16_sat_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_h16_sat_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_h16_sat_lh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_h16_sat_lh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_h16_sat_lh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_h16_sat_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_h16_sat_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_h16_sat_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subh_h16_sat_hh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subh_h16_sat_hh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subh_h16_sat_hh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_aslh,SI_ftype_SI,1)
+//
+def int_hexagon_A2_aslh :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_aslh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_asrh,SI_ftype_SI,1)
+//
+def int_hexagon_A2_asrh :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_asrh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_addp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_addp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addpsat,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_addpsat :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_addpsat">;
+//
+// BUILTIN_INFO(HEXAGON.A2_addsp,DI_ftype_SIDI,2)
+//
+def int_hexagon_A2_addsp :
+Hexagon_di_sidi_Intrinsic<"HEXAGON_A2_addsp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_subp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_subp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_neg,SI_ftype_SI,1)
+//
+def int_hexagon_A2_neg :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_neg">;
+//
+// BUILTIN_INFO(HEXAGON.A2_negsat,SI_ftype_SI,1)
+//
+def int_hexagon_A2_negsat :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_negsat">;
+//
+// BUILTIN_INFO(HEXAGON.A2_abs,SI_ftype_SI,1)
+//
+def int_hexagon_A2_abs :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_abs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_abssat,SI_ftype_SI,1)
+//
+def int_hexagon_A2_abssat :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_abssat">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vconj,DI_ftype_DI,1)
+//
+def int_hexagon_A2_vconj :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_vconj">;
+//
+// BUILTIN_INFO(HEXAGON.A2_negp,DI_ftype_DI,1)
+//
+def int_hexagon_A2_negp :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_negp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_absp,DI_ftype_DI,1)
+//
+def int_hexagon_A2_absp :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_absp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_max,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_max :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_max">;
+//
+// BUILTIN_INFO(HEXAGON.A2_maxu,USI_ftype_SISI,2)
+//
+def int_hexagon_A2_maxu :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_maxu">;
+//
+// BUILTIN_INFO(HEXAGON.A2_min,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_min :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_min">;
+//
+// BUILTIN_INFO(HEXAGON.A2_minu,USI_ftype_SISI,2)
+//
+def int_hexagon_A2_minu :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_minu">;
+//
+// BUILTIN_INFO(HEXAGON.A2_maxp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_maxp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_maxp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_maxup,UDI_ftype_DIDI,2)
+//
+def int_hexagon_A2_maxup :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_maxup">;
+//
+// BUILTIN_INFO(HEXAGON.A2_minp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_minp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_minp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_minup,UDI_ftype_DIDI,2)
+//
+def int_hexagon_A2_minup :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_minup">;
+//
+// BUILTIN_INFO(HEXAGON.A2_tfr,SI_ftype_SI,1)
+//
+def int_hexagon_A2_tfr :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_tfr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_tfrsi,SI_ftype_SI,1)
+//
+def int_hexagon_A2_tfrsi :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_tfrsi">;
+//
+// BUILTIN_INFO(HEXAGON.A2_tfrp,DI_ftype_DI,1)
+//
+def int_hexagon_A2_tfrp :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_tfrp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_tfrpi,DI_ftype_SI,1)
+//
+def int_hexagon_A2_tfrpi :
+Hexagon_di_si_Intrinsic<"HEXAGON_A2_tfrpi">;
+//
+// BUILTIN_INFO(HEXAGON.A2_zxtb,SI_ftype_SI,1)
+//
+def int_hexagon_A2_zxtb :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_zxtb">;
+//
+// BUILTIN_INFO(HEXAGON.A2_sxtb,SI_ftype_SI,1)
+//
+def int_hexagon_A2_sxtb :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_sxtb">;
+//
+// BUILTIN_INFO(HEXAGON.A2_zxth,SI_ftype_SI,1)
+//
+def int_hexagon_A2_zxth :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_zxth">;
+//
+// BUILTIN_INFO(HEXAGON.A2_sxth,SI_ftype_SI,1)
+//
+def int_hexagon_A2_sxth :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_sxth">;
+//
+// BUILTIN_INFO(HEXAGON.A2_combinew,DI_ftype_SISI,2)
+//
+def int_hexagon_A2_combinew :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_A2_combinew">;
+//
+// BUILTIN_INFO(HEXAGON.A4_combineri,DI_ftype_SISI,2)
+//
+def int_hexagon_A4_combineri :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_A4_combineri">;
+//
+// BUILTIN_INFO(HEXAGON.A4_combineir,DI_ftype_SISI,2)
+//
+def int_hexagon_A4_combineir :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_A4_combineir">;
+//
+// BUILTIN_INFO(HEXAGON.A2_combineii,DI_ftype_SISI,2)
+//
+def int_hexagon_A2_combineii :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_A2_combineii">;
+//
+// BUILTIN_INFO(HEXAGON.A2_combine_hh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_combine_hh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_combine_hh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_combine_hl,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_combine_hl :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_combine_hl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_combine_lh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_combine_lh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_combine_lh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_combine_ll,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_combine_ll :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_combine_ll">;
+//
+// BUILTIN_INFO(HEXAGON.A2_tfril,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_tfril :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_tfril">;
+//
+// BUILTIN_INFO(HEXAGON.A2_tfrih,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_tfrih :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_tfrih">;
+//
+// BUILTIN_INFO(HEXAGON.A2_and,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_and :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_and">;
+//
+// BUILTIN_INFO(HEXAGON.A2_or,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_or :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_or">;
+//
+// BUILTIN_INFO(HEXAGON.A2_xor,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_xor :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_xor">;
+//
+// BUILTIN_INFO(HEXAGON.A2_not,SI_ftype_SI,1)
+//
+def int_hexagon_A2_not :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_not">;
+//
+// BUILTIN_INFO(HEXAGON.M2_xor_xacc,SI_ftype_SISISI,3)
+//
+def int_hexagon_M2_xor_xacc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M2_xor_xacc">;
+//
+// BUILTIN_INFO(HEXAGON.M4_xor_xacc,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_M4_xor_xacc :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_M4_xor_xacc">;
+//
+// BUILTIN_INFO(HEXAGON.A4_andn,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_andn :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_andn">;
+//
+// BUILTIN_INFO(HEXAGON.A4_orn,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_orn :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_orn">;
+//
+// BUILTIN_INFO(HEXAGON.A4_andnp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A4_andnp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A4_andnp">;
+//
+// BUILTIN_INFO(HEXAGON.A4_ornp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A4_ornp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A4_ornp">;
+//
+// BUILTIN_INFO(HEXAGON.S4_addaddi,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_addaddi :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_addaddi">;
+//
+// BUILTIN_INFO(HEXAGON.S4_subaddi,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_subaddi :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_subaddi">;
+//
+// BUILTIN_INFO(HEXAGON.M4_and_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_and_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_and_and">;
+//
+// BUILTIN_INFO(HEXAGON.M4_and_andn,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_and_andn :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_and_andn">;
+//
+// BUILTIN_INFO(HEXAGON.M4_and_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_and_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_and_or">;
+//
+// BUILTIN_INFO(HEXAGON.M4_and_xor,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_and_xor :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_and_xor">;
+//
+// BUILTIN_INFO(HEXAGON.M4_or_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_or_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_or_and">;
+//
+// BUILTIN_INFO(HEXAGON.M4_or_andn,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_or_andn :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_or_andn">;
+//
+// BUILTIN_INFO(HEXAGON.M4_or_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_or_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_or_or">;
+//
+// BUILTIN_INFO(HEXAGON.M4_or_xor,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_or_xor :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_or_xor">;
+//
+// BUILTIN_INFO(HEXAGON.S4_or_andix,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_or_andix :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_or_andix">;
+//
+// BUILTIN_INFO(HEXAGON.S4_or_andi,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_or_andi :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_or_andi">;
+//
+// BUILTIN_INFO(HEXAGON.S4_or_ori,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_or_ori :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_or_ori">;
+//
+// BUILTIN_INFO(HEXAGON.M4_xor_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_xor_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_xor_and">;
+//
+// BUILTIN_INFO(HEXAGON.M4_xor_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_xor_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_xor_or">;
+//
+// BUILTIN_INFO(HEXAGON.M4_xor_andn,SI_ftype_SISISI,3)
+//
+def int_hexagon_M4_xor_andn :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_M4_xor_andn">;
+//
+// BUILTIN_INFO(HEXAGON.A2_subri,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_subri :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_subri">;
+//
+// BUILTIN_INFO(HEXAGON.A2_andir,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_andir :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_andir">;
+//
+// BUILTIN_INFO(HEXAGON.A2_orir,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_orir :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_orir">;
+//
+// BUILTIN_INFO(HEXAGON.A2_andp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_andp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_andp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_orp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_orp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_orp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_xorp,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_xorp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_xorp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_notp,DI_ftype_DI,1)
+//
+def int_hexagon_A2_notp :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_notp">;
+//
+// BUILTIN_INFO(HEXAGON.A2_sxtw,DI_ftype_SI,1)
+//
+def int_hexagon_A2_sxtw :
+Hexagon_di_si_Intrinsic<"HEXAGON_A2_sxtw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_sat,SI_ftype_DI,1)
+//
+def int_hexagon_A2_sat :
+Hexagon_si_di_Intrinsic<"HEXAGON_A2_sat">;
+//
+// BUILTIN_INFO(HEXAGON.A2_roundsat,SI_ftype_DI,1)
+//
+def int_hexagon_A2_roundsat :
+Hexagon_si_di_Intrinsic<"HEXAGON_A2_roundsat">;
+//
+// BUILTIN_INFO(HEXAGON.A2_sath,SI_ftype_SI,1)
+//
+def int_hexagon_A2_sath :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_sath">;
+//
+// BUILTIN_INFO(HEXAGON.A2_satuh,SI_ftype_SI,1)
+//
+def int_hexagon_A2_satuh :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_satuh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_satub,SI_ftype_SI,1)
+//
+def int_hexagon_A2_satub :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_satub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_satb,SI_ftype_SI,1)
+//
+def int_hexagon_A2_satb :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_satb">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vaddub,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vaddub :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vaddub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vaddb_map,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vaddb_map :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vaddb_map">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vaddubs,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vaddubs :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vaddubs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vaddh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vaddh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vaddh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vaddhs,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vaddhs :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vaddhs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vadduhs,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vadduhs :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vadduhs">;
+//
+// BUILTIN_INFO(HEXAGON.A5_vaddhubs,SI_ftype_DIDI,2)
+//
+def int_hexagon_A5_vaddhubs :
+Hexagon_si_didi_Intrinsic<"HEXAGON_A5_vaddhubs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vaddw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vaddw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vaddw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vaddws,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vaddws :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vaddws">;
+//
+// BUILTIN_INFO(HEXAGON.S4_vxaddsubw,DI_ftype_DIDI,2)
+//
+def int_hexagon_S4_vxaddsubw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S4_vxaddsubw">;
+//
+// BUILTIN_INFO(HEXAGON.S4_vxsubaddw,DI_ftype_DIDI,2)
+//
+def int_hexagon_S4_vxsubaddw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S4_vxsubaddw">;
+//
+// BUILTIN_INFO(HEXAGON.S4_vxaddsubh,DI_ftype_DIDI,2)
+//
+def int_hexagon_S4_vxaddsubh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S4_vxaddsubh">;
+//
+// BUILTIN_INFO(HEXAGON.S4_vxsubaddh,DI_ftype_DIDI,2)
+//
+def int_hexagon_S4_vxsubaddh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S4_vxsubaddh">;
+//
+// BUILTIN_INFO(HEXAGON.S4_vxaddsubhr,DI_ftype_DIDI,2)
+//
+def int_hexagon_S4_vxaddsubhr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S4_vxaddsubhr">;
+//
+// BUILTIN_INFO(HEXAGON.S4_vxsubaddhr,DI_ftype_DIDI,2)
+//
+def int_hexagon_S4_vxsubaddhr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S4_vxsubaddhr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svavgh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svavgh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svavgh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svavghs,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svavghs :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svavghs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svnavgh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svnavgh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svnavgh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svaddh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svaddh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svaddh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svaddhs,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svaddhs :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svaddhs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svadduhs,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svadduhs :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svadduhs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svsubh,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svsubh :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svsubh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svsubhs,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svsubhs :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svsubhs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_svsubuhs,SI_ftype_SISI,2)
+//
+def int_hexagon_A2_svsubuhs :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A2_svsubuhs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vraddub,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vraddub :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vraddub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vraddub_acc,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_A2_vraddub_acc :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_A2_vraddub_acc">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vraddh,SI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vraddh :
+Hexagon_si_didi_Intrinsic<"HEXAGON_M2_vraddh">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vradduh,SI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vradduh :
+Hexagon_si_didi_Intrinsic<"HEXAGON_M2_vradduh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vsubub,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vsubub :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vsubub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vsubb_map,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vsubb_map :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vsubb_map">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vsububs,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vsububs :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vsububs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vsubh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vsubh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vsubh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vsubhs,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vsubhs :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vsubhs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vsubuhs,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vsubuhs :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vsubuhs">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vsubw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vsubw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vsubw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vsubws,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vsubws :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vsubws">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vabsh,DI_ftype_DI,1)
+//
+def int_hexagon_A2_vabsh :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_vabsh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vabshsat,DI_ftype_DI,1)
+//
+def int_hexagon_A2_vabshsat :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_vabshsat">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vabsw,DI_ftype_DI,1)
+//
+def int_hexagon_A2_vabsw :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_vabsw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vabswsat,DI_ftype_DI,1)
+//
+def int_hexagon_A2_vabswsat :
+Hexagon_di_di_Intrinsic<"HEXAGON_A2_vabswsat">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vabsdiffw,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vabsdiffw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vabsdiffw">;
+//
+// BUILTIN_INFO(HEXAGON.M2_vabsdiffh,DI_ftype_DIDI,2)
+//
+def int_hexagon_M2_vabsdiffh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_M2_vabsdiffh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vrsadub,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vrsadub :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vrsadub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vrsadub_acc,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_A2_vrsadub_acc :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_A2_vrsadub_acc">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavgub,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavgub :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavgub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavguh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavguh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavguh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavgh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavgh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavgh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vnavgh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vnavgh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vnavgh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavgw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavgw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavgw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vnavgw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vnavgw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vnavgw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavgwr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavgwr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavgwr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vnavgwr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vnavgwr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vnavgwr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavgwcr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavgwcr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavgwcr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vnavgwcr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vnavgwcr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vnavgwcr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavghcr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavghcr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavghcr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vnavghcr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vnavghcr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vnavghcr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavguw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavguw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavguw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavguwr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavguwr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavguwr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavgubr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavgubr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavgubr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavguhr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavguhr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavguhr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vavghr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vavghr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vavghr">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vnavghr,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vnavghr :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vnavghr">;
+//
+// BUILTIN_INFO(HEXAGON.A4_round_ri,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_round_ri :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_round_ri">;
+//
+// BUILTIN_INFO(HEXAGON.A4_round_rr,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_round_rr :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_round_rr">;
+//
+// BUILTIN_INFO(HEXAGON.A4_round_ri_sat,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_round_ri_sat :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_round_ri_sat">;
+//
+// BUILTIN_INFO(HEXAGON.A4_round_rr_sat,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_round_rr_sat :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_round_rr_sat">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cround_ri,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_cround_ri :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_cround_ri">;
+//
+// BUILTIN_INFO(HEXAGON.A4_cround_rr,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_cround_rr :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_cround_rr">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vrminh,DI_ftype_DIDISI,3)
+//
+def int_hexagon_A4_vrminh :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_A4_vrminh">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vrmaxh,DI_ftype_DIDISI,3)
+//
+def int_hexagon_A4_vrmaxh :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_A4_vrmaxh">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vrminuh,DI_ftype_DIDISI,3)
+//
+def int_hexagon_A4_vrminuh :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_A4_vrminuh">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vrmaxuh,DI_ftype_DIDISI,3)
+//
+def int_hexagon_A4_vrmaxuh :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_A4_vrmaxuh">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vrminw,DI_ftype_DIDISI,3)
+//
+def int_hexagon_A4_vrminw :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_A4_vrminw">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vrmaxw,DI_ftype_DIDISI,3)
+//
+def int_hexagon_A4_vrmaxw :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_A4_vrmaxw">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vrminuw,DI_ftype_DIDISI,3)
+//
+def int_hexagon_A4_vrminuw :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_A4_vrminuw">;
+//
+// BUILTIN_INFO(HEXAGON.A4_vrmaxuw,DI_ftype_DIDISI,3)
+//
+def int_hexagon_A4_vrmaxuw :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_A4_vrmaxuw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vminb,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vminb :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vminb">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vmaxb,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vmaxb :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vmaxb">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vminub,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vminub :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vminub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vmaxub,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vmaxub :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vmaxub">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vminh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vminh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vminh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vmaxh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vmaxh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vmaxh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vminuh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vminuh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vminuh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vmaxuh,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vmaxuh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vmaxuh">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vminw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vminw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vminw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vmaxw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vmaxw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vmaxw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vminuw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vminuw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vminuw">;
+//
+// BUILTIN_INFO(HEXAGON.A2_vmaxuw,DI_ftype_DIDI,2)
+//
+def int_hexagon_A2_vmaxuw :
+Hexagon_di_didi_Intrinsic<"HEXAGON_A2_vmaxuw">;
+//
+// BUILTIN_INFO(HEXAGON.A4_modwrapu,SI_ftype_SISI,2)
+//
+def int_hexagon_A4_modwrapu :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_A4_modwrapu">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfadd,SF_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfadd :
+Hexagon_sf_sfsf_Intrinsic<"HEXAGON_F2_sfadd">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfsub,SF_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfsub :
+Hexagon_sf_sfsf_Intrinsic<"HEXAGON_F2_sfsub">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfmpy,SF_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfmpy :
+Hexagon_sf_sfsf_Intrinsic<"HEXAGON_F2_sfmpy">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sffma,SF_ftype_SFSFSF,3)
+//
+def int_hexagon_F2_sffma :
+Hexagon_sf_sfsfsf_Intrinsic<"HEXAGON_F2_sffma">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sffma_sc,SF_ftype_SFSFSFQI,4)
+//
+def int_hexagon_F2_sffma_sc :
+Hexagon_sf_sfsfsfqi_Intrinsic<"HEXAGON_F2_sffma_sc">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sffms,SF_ftype_SFSFSF,3)
+//
+def int_hexagon_F2_sffms :
+Hexagon_sf_sfsfsf_Intrinsic<"HEXAGON_F2_sffms">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sffma_lib,SF_ftype_SFSFSF,3)
+//
+def int_hexagon_F2_sffma_lib :
+Hexagon_sf_sfsfsf_Intrinsic<"HEXAGON_F2_sffma_lib">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sffms_lib,SF_ftype_SFSFSF,3)
+//
+def int_hexagon_F2_sffms_lib :
+Hexagon_sf_sfsfsf_Intrinsic<"HEXAGON_F2_sffms_lib">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfcmpeq,QI_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfcmpeq :
+Hexagon_qi_sfsf_Intrinsic<"HEXAGON_F2_sfcmpeq">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfcmpgt,QI_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfcmpgt :
+Hexagon_qi_sfsf_Intrinsic<"HEXAGON_F2_sfcmpgt">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfcmpge,QI_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfcmpge :
+Hexagon_qi_sfsf_Intrinsic<"HEXAGON_F2_sfcmpge">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfcmpuo,QI_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfcmpuo :
+Hexagon_qi_sfsf_Intrinsic<"HEXAGON_F2_sfcmpuo">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfmax,SF_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfmax :
+Hexagon_sf_sfsf_Intrinsic<"HEXAGON_F2_sfmax">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfmin,SF_ftype_SFSF,2)
+//
+def int_hexagon_F2_sfmin :
+Hexagon_sf_sfsf_Intrinsic<"HEXAGON_F2_sfmin">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfclass,QI_ftype_SFSI,2)
+//
+def int_hexagon_F2_sfclass :
+Hexagon_qi_sfsi_Intrinsic<"HEXAGON_F2_sfclass">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfimm_p,SF_ftype_SI,1)
+//
+def int_hexagon_F2_sfimm_p :
+Hexagon_sf_si_Intrinsic<"HEXAGON_F2_sfimm_p">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sfimm_n,SF_ftype_SI,1)
+//
+def int_hexagon_F2_sfimm_n :
+Hexagon_sf_si_Intrinsic<"HEXAGON_F2_sfimm_n">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sffixupn,SF_ftype_SFSF,2)
+//
+def int_hexagon_F2_sffixupn :
+Hexagon_sf_sfsf_Intrinsic<"HEXAGON_F2_sffixupn">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sffixupd,SF_ftype_SFSF,2)
+//
+def int_hexagon_F2_sffixupd :
+Hexagon_sf_sfsf_Intrinsic<"HEXAGON_F2_sffixupd">;
+//
+// BUILTIN_INFO(HEXAGON.F2_sffixupr,SF_ftype_SF,1)
+//
+def int_hexagon_F2_sffixupr :
+Hexagon_sf_sf_Intrinsic<"HEXAGON_F2_sffixupr">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfadd,DF_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfadd :
+Hexagon_df_dfdf_Intrinsic<"HEXAGON_F2_dfadd">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfsub,DF_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfsub :
+Hexagon_df_dfdf_Intrinsic<"HEXAGON_F2_dfsub">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfmpy,DF_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfmpy :
+Hexagon_df_dfdf_Intrinsic<"HEXAGON_F2_dfmpy">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dffma,DF_ftype_DFDFDF,3)
+//
+def int_hexagon_F2_dffma :
+Hexagon_df_dfdfdf_Intrinsic<"HEXAGON_F2_dffma">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dffms,DF_ftype_DFDFDF,3)
+//
+def int_hexagon_F2_dffms :
+Hexagon_df_dfdfdf_Intrinsic<"HEXAGON_F2_dffms">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dffma_lib,DF_ftype_DFDFDF,3)
+//
+def int_hexagon_F2_dffma_lib :
+Hexagon_df_dfdfdf_Intrinsic<"HEXAGON_F2_dffma_lib">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dffms_lib,DF_ftype_DFDFDF,3)
+//
+def int_hexagon_F2_dffms_lib :
+Hexagon_df_dfdfdf_Intrinsic<"HEXAGON_F2_dffms_lib">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dffma_sc,DF_ftype_DFDFDFQI,4)
+//
+def int_hexagon_F2_dffma_sc :
+Hexagon_df_dfdfdfqi_Intrinsic<"HEXAGON_F2_dffma_sc">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfmax,DF_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfmax :
+Hexagon_df_dfdf_Intrinsic<"HEXAGON_F2_dfmax">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfmin,DF_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfmin :
+Hexagon_df_dfdf_Intrinsic<"HEXAGON_F2_dfmin">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfcmpeq,QI_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfcmpeq :
+Hexagon_qi_dfdf_Intrinsic<"HEXAGON_F2_dfcmpeq">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfcmpgt,QI_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfcmpgt :
+Hexagon_qi_dfdf_Intrinsic<"HEXAGON_F2_dfcmpgt">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfcmpge,QI_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfcmpge :
+Hexagon_qi_dfdf_Intrinsic<"HEXAGON_F2_dfcmpge">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfcmpuo,QI_ftype_DFDF,2)
+//
+def int_hexagon_F2_dfcmpuo :
+Hexagon_qi_dfdf_Intrinsic<"HEXAGON_F2_dfcmpuo">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfclass,QI_ftype_DFSI,2)
+//
+def int_hexagon_F2_dfclass :
+Hexagon_qi_dfsi_Intrinsic<"HEXAGON_F2_dfclass">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfimm_p,DF_ftype_SI,1)
+//
+def int_hexagon_F2_dfimm_p :
+Hexagon_df_si_Intrinsic<"HEXAGON_F2_dfimm_p">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dfimm_n,DF_ftype_SI,1)
+//
+def int_hexagon_F2_dfimm_n :
+Hexagon_df_si_Intrinsic<"HEXAGON_F2_dfimm_n">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dffixupn,DF_ftype_DFDF,2)
+//
+def int_hexagon_F2_dffixupn :
+Hexagon_df_dfdf_Intrinsic<"HEXAGON_F2_dffixupn">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dffixupd,DF_ftype_DFDF,2)
+//
+def int_hexagon_F2_dffixupd :
+Hexagon_df_dfdf_Intrinsic<"HEXAGON_F2_dffixupd">;
+//
+// BUILTIN_INFO(HEXAGON.F2_dffixupr,DF_ftype_DF,1)
+//
+def int_hexagon_F2_dffixupr :
+Hexagon_df_df_Intrinsic<"HEXAGON_F2_dffixupr">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2df,DF_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2df :
+Hexagon_df_sf_Intrinsic<"HEXAGON_F2_conv_sf2df">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2sf,SF_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2sf :
+Hexagon_sf_df_Intrinsic<"HEXAGON_F2_conv_df2sf">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_uw2sf,SF_ftype_SI,1)
+//
+def int_hexagon_F2_conv_uw2sf :
+Hexagon_sf_si_Intrinsic<"HEXAGON_F2_conv_uw2sf">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_uw2df,DF_ftype_SI,1)
+//
+def int_hexagon_F2_conv_uw2df :
+Hexagon_df_si_Intrinsic<"HEXAGON_F2_conv_uw2df">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_w2sf,SF_ftype_SI,1)
+//
+def int_hexagon_F2_conv_w2sf :
+Hexagon_sf_si_Intrinsic<"HEXAGON_F2_conv_w2sf">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_w2df,DF_ftype_SI,1)
+//
+def int_hexagon_F2_conv_w2df :
+Hexagon_df_si_Intrinsic<"HEXAGON_F2_conv_w2df">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_ud2sf,SF_ftype_DI,1)
+//
+def int_hexagon_F2_conv_ud2sf :
+Hexagon_sf_di_Intrinsic<"HEXAGON_F2_conv_ud2sf">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_ud2df,DF_ftype_DI,1)
+//
+def int_hexagon_F2_conv_ud2df :
+Hexagon_df_di_Intrinsic<"HEXAGON_F2_conv_ud2df">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_d2sf,SF_ftype_DI,1)
+//
+def int_hexagon_F2_conv_d2sf :
+Hexagon_sf_di_Intrinsic<"HEXAGON_F2_conv_d2sf">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_d2df,DF_ftype_DI,1)
+//
+def int_hexagon_F2_conv_d2df :
+Hexagon_df_di_Intrinsic<"HEXAGON_F2_conv_d2df">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2uw,SI_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2uw :
+Hexagon_si_sf_Intrinsic<"HEXAGON_F2_conv_sf2uw">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2w,SI_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2w :
+Hexagon_si_sf_Intrinsic<"HEXAGON_F2_conv_sf2w">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2ud,DI_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2ud :
+Hexagon_di_sf_Intrinsic<"HEXAGON_F2_conv_sf2ud">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2d,DI_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2d :
+Hexagon_di_sf_Intrinsic<"HEXAGON_F2_conv_sf2d">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2uw,SI_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2uw :
+Hexagon_si_df_Intrinsic<"HEXAGON_F2_conv_df2uw">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2w,SI_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2w :
+Hexagon_si_df_Intrinsic<"HEXAGON_F2_conv_df2w">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2ud,DI_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2ud :
+Hexagon_di_df_Intrinsic<"HEXAGON_F2_conv_df2ud">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2d,DI_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2d :
+Hexagon_di_df_Intrinsic<"HEXAGON_F2_conv_df2d">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2uw_chop,SI_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2uw_chop :
+Hexagon_si_sf_Intrinsic<"HEXAGON_F2_conv_sf2uw_chop">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2w_chop,SI_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2w_chop :
+Hexagon_si_sf_Intrinsic<"HEXAGON_F2_conv_sf2w_chop">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2ud_chop,DI_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2ud_chop :
+Hexagon_di_sf_Intrinsic<"HEXAGON_F2_conv_sf2ud_chop">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_sf2d_chop,DI_ftype_SF,1)
+//
+def int_hexagon_F2_conv_sf2d_chop :
+Hexagon_di_sf_Intrinsic<"HEXAGON_F2_conv_sf2d_chop">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2uw_chop,SI_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2uw_chop :
+Hexagon_si_df_Intrinsic<"HEXAGON_F2_conv_df2uw_chop">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2w_chop,SI_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2w_chop :
+Hexagon_si_df_Intrinsic<"HEXAGON_F2_conv_df2w_chop">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2ud_chop,DI_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2ud_chop :
+Hexagon_di_df_Intrinsic<"HEXAGON_F2_conv_df2ud_chop">;
+//
+// BUILTIN_INFO(HEXAGON.F2_conv_df2d_chop,DI_ftype_DF,1)
+//
+def int_hexagon_F2_conv_df2d_chop :
+Hexagon_di_df_Intrinsic<"HEXAGON_F2_conv_df2d_chop">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asr_r_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asr_r_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asl_r_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asl_r_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_lsr_r_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_lsr_r_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_lsl_r_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_lsl_r_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_p,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_r_p :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asr_r_p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_p,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asl_r_p :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asl_r_p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_p,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsr_r_p :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsr_r_p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_p,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsl_r_p :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsl_r_p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_r_acc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asr_r_r_acc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asr_r_r_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_r_acc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_r_r_acc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_r_r_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_r_acc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_r_r_acc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_r_r_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_r_acc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsl_r_r_acc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsl_r_r_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_p_acc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_r_p_acc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_r_p_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_p_acc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_r_p_acc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_r_p_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_p_acc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_r_p_acc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_r_p_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_p_acc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsl_r_p_acc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsl_r_p_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_r_nac,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asr_r_r_nac :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asr_r_r_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_r_nac,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_r_r_nac :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_r_r_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_r_nac,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_r_r_nac :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_r_r_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_r_nac,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsl_r_r_nac :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsl_r_r_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_p_nac,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_r_p_nac :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_r_p_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_p_nac,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_r_p_nac :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_r_p_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_p_nac,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_r_p_nac :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_r_p_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_p_nac,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsl_r_p_nac :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsl_r_p_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_r_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asr_r_r_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asr_r_r_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_r_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_r_r_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_r_r_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_r_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_r_r_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_r_r_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_r_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsl_r_r_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsl_r_r_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_r_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asr_r_r_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asr_r_r_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_r_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_r_r_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_r_r_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_r_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_r_r_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_r_r_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_r_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsl_r_r_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsl_r_r_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_p_and,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_r_p_and :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_r_p_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_p_and,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_r_p_and :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_r_p_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_p_and,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_r_p_and :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_r_p_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_p_and,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsl_r_p_and :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsl_r_p_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_p_or,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_r_p_or :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_r_p_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_p_or,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_r_p_or :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_r_p_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_p_or,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_r_p_or :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_r_p_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_p_or,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsl_r_p_or :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsl_r_p_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_p_xor,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_r_p_xor :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_r_p_xor">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_p_xor,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_r_p_xor :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_r_p_xor">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_p_xor,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_r_p_xor :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_r_p_xor">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_p_xor,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsl_r_p_xor :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsl_r_p_xor">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_r_sat,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asr_r_r_sat :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asr_r_r_sat">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_r_sat,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asl_r_r_sat :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asl_r_r_sat">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asr_i_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asr_i_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_lsr_i_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_lsr_i_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asl_i_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asl_i_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_p,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_i_p :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asr_i_p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_p,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsr_i_p :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsr_i_p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_p,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asl_i_p :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asl_i_p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_r_acc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asr_i_r_acc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asr_i_r_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_r_acc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_i_r_acc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_i_r_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_r_acc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_i_r_acc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_i_r_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_p_acc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_i_p_acc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_i_p_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_p_acc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_i_p_acc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_i_p_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_p_acc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_i_p_acc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_i_p_acc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_r_nac,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asr_i_r_nac :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asr_i_r_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_r_nac,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_i_r_nac :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_i_r_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_r_nac,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_i_r_nac :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_i_r_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_p_nac,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_i_p_nac :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_i_p_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_p_nac,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_i_p_nac :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_i_p_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_p_nac,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_i_p_nac :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_i_p_nac">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_r_xacc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_i_r_xacc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_i_r_xacc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_r_xacc,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_i_r_xacc :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_i_r_xacc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_p_xacc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_i_p_xacc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_i_p_xacc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_p_xacc,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_i_p_xacc :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_i_p_xacc">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_r_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asr_i_r_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asr_i_r_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_r_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_i_r_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_i_r_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_r_and,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_i_r_and :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_i_r_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_r_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asr_i_r_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asr_i_r_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_r_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_lsr_i_r_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_lsr_i_r_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_r_or,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_asl_i_r_or :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_asl_i_r_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_p_and,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_i_p_and :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_i_p_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_p_and,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_i_p_and :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_i_p_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_p_and,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_i_p_and :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_i_p_and">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_p_or,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asr_i_p_or :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asr_i_p_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_p_or,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_lsr_i_p_or :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_lsr_i_p_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_p_or,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_asl_i_p_or :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_asl_i_p_or">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_r_sat,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asl_i_r_sat :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asl_i_r_sat">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_r_rnd,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asr_i_r_rnd :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asr_i_r_rnd">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_r_rnd_goodsyntax,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_asr_i_r_rnd_goodsyntax :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_asr_i_r_rnd_goodsyntax">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_p_rnd,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_i_p_rnd :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asr_i_p_rnd">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_p_rnd_goodsyntax,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_i_p_rnd_goodsyntax :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asr_i_p_rnd_goodsyntax">;
+//
+// BUILTIN_INFO(HEXAGON.S4_lsli,SI_ftype_SISI,2)
+//
+def int_hexagon_S4_lsli :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S4_lsli">;
+//
+// BUILTIN_INFO(HEXAGON.S2_addasl_rrri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_addasl_rrri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_addasl_rrri">;
+//
+// BUILTIN_INFO(HEXAGON.S4_andi_asl_ri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_andi_asl_ri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_andi_asl_ri">;
+//
+// BUILTIN_INFO(HEXAGON.S4_ori_asl_ri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_ori_asl_ri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_ori_asl_ri">;
+//
+// BUILTIN_INFO(HEXAGON.S4_addi_asl_ri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_addi_asl_ri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_addi_asl_ri">;
+//
+// BUILTIN_INFO(HEXAGON.S4_subi_asl_ri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_subi_asl_ri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_subi_asl_ri">;
+//
+// BUILTIN_INFO(HEXAGON.S4_andi_lsr_ri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_andi_lsr_ri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_andi_lsr_ri">;
+//
+// BUILTIN_INFO(HEXAGON.S4_ori_lsr_ri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_ori_lsr_ri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_ori_lsr_ri">;
+//
+// BUILTIN_INFO(HEXAGON.S4_addi_lsr_ri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_addi_lsr_ri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_addi_lsr_ri">;
+//
+// BUILTIN_INFO(HEXAGON.S4_subi_lsr_ri,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_subi_lsr_ri :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_subi_lsr_ri">;
+//
+// BUILTIN_INFO(HEXAGON.S2_valignib,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_valignib :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_valignib">;
+//
+// BUILTIN_INFO(HEXAGON.S2_valignrb,DI_ftype_DIDIQI,3)
+//
+def int_hexagon_S2_valignrb :
+Hexagon_di_didiqi_Intrinsic<"HEXAGON_S2_valignrb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vspliceib,DI_ftype_DIDISI,3)
+//
+def int_hexagon_S2_vspliceib :
+Hexagon_di_didisi_Intrinsic<"HEXAGON_S2_vspliceib">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsplicerb,DI_ftype_DIDIQI,3)
+//
+def int_hexagon_S2_vsplicerb :
+Hexagon_di_didiqi_Intrinsic<"HEXAGON_S2_vsplicerb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsplatrh,DI_ftype_SI,1)
+//
+def int_hexagon_S2_vsplatrh :
+Hexagon_di_si_Intrinsic<"HEXAGON_S2_vsplatrh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsplatrb,SI_ftype_SI,1)
+//
+def int_hexagon_S2_vsplatrb :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_vsplatrb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_insert,SI_ftype_SISISISI,4)
+//
+def int_hexagon_S2_insert :
+Hexagon_si_sisisisi_Intrinsic<"HEXAGON_S2_insert">;
+//
+// BUILTIN_INFO(HEXAGON.S2_tableidxb_goodsyntax,SI_ftype_SISISISI,4)
+//
+def int_hexagon_S2_tableidxb_goodsyntax :
+Hexagon_si_sisisisi_Intrinsic<"HEXAGON_S2_tableidxb_goodsyntax">;
+//
+// BUILTIN_INFO(HEXAGON.S2_tableidxh_goodsyntax,SI_ftype_SISISISI,4)
+//
+def int_hexagon_S2_tableidxh_goodsyntax :
+Hexagon_si_sisisisi_Intrinsic<"HEXAGON_S2_tableidxh_goodsyntax">;
+//
+// BUILTIN_INFO(HEXAGON.S2_tableidxw_goodsyntax,SI_ftype_SISISISI,4)
+//
+def int_hexagon_S2_tableidxw_goodsyntax :
+Hexagon_si_sisisisi_Intrinsic<"HEXAGON_S2_tableidxw_goodsyntax">;
+//
+// BUILTIN_INFO(HEXAGON.S2_tableidxd_goodsyntax,SI_ftype_SISISISI,4)
+//
+def int_hexagon_S2_tableidxd_goodsyntax :
+Hexagon_si_sisisisi_Intrinsic<"HEXAGON_S2_tableidxd_goodsyntax">;
+//
+// BUILTIN_INFO(HEXAGON.A4_bitspliti,DI_ftype_SISI,2)
+//
+def int_hexagon_A4_bitspliti :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_A4_bitspliti">;
+//
+// BUILTIN_INFO(HEXAGON.A4_bitsplit,DI_ftype_SISI,2)
+//
+def int_hexagon_A4_bitsplit :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_A4_bitsplit">;
+//
+// BUILTIN_INFO(HEXAGON.S4_extract,SI_ftype_SISISI,3)
+//
+def int_hexagon_S4_extract :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S4_extract">;
+//
+// BUILTIN_INFO(HEXAGON.S2_extractu,SI_ftype_SISISI,3)
+//
+def int_hexagon_S2_extractu :
+Hexagon_si_sisisi_Intrinsic<"HEXAGON_S2_extractu">;
+//
+// BUILTIN_INFO(HEXAGON.S2_insertp,DI_ftype_DIDISISI,4)
+//
+def int_hexagon_S2_insertp :
+Hexagon_di_didisisi_Intrinsic<"HEXAGON_S2_insertp">;
+//
+// BUILTIN_INFO(HEXAGON.S4_extractp,DI_ftype_DISISI,3)
+//
+def int_hexagon_S4_extractp :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_S4_extractp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_extractup,DI_ftype_DISISI,3)
+//
+def int_hexagon_S2_extractup :
+Hexagon_di_disisi_Intrinsic<"HEXAGON_S2_extractup">;
+//
+// BUILTIN_INFO(HEXAGON.S2_insert_rp,SI_ftype_SISIDI,3)
+//
+def int_hexagon_S2_insert_rp :
+Hexagon_si_sisidi_Intrinsic<"HEXAGON_S2_insert_rp">;
+//
+// BUILTIN_INFO(HEXAGON.S4_extract_rp,SI_ftype_SIDI,2)
+//
+def int_hexagon_S4_extract_rp :
+Hexagon_si_sidi_Intrinsic<"HEXAGON_S4_extract_rp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_extractu_rp,SI_ftype_SIDI,2)
+//
+def int_hexagon_S2_extractu_rp :
+Hexagon_si_sidi_Intrinsic<"HEXAGON_S2_extractu_rp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_insertp_rp,DI_ftype_DIDIDI,3)
+//
+def int_hexagon_S2_insertp_rp :
+Hexagon_di_dididi_Intrinsic<"HEXAGON_S2_insertp_rp">;
+//
+// BUILTIN_INFO(HEXAGON.S4_extractp_rp,DI_ftype_DIDI,2)
+//
+def int_hexagon_S4_extractp_rp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S4_extractp_rp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_extractup_rp,DI_ftype_DIDI,2)
+//
+def int_hexagon_S2_extractup_rp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S2_extractup_rp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_tstbit_i,QI_ftype_SISI,2)
+//
+def int_hexagon_S2_tstbit_i :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_S2_tstbit_i">;
+//
+// BUILTIN_INFO(HEXAGON.S4_ntstbit_i,QI_ftype_SISI,2)
+//
+def int_hexagon_S4_ntstbit_i :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_S4_ntstbit_i">;
+//
+// BUILTIN_INFO(HEXAGON.S2_setbit_i,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_setbit_i :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_setbit_i">;
+//
+// BUILTIN_INFO(HEXAGON.S2_togglebit_i,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_togglebit_i :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_togglebit_i">;
+//
+// BUILTIN_INFO(HEXAGON.S2_clrbit_i,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_clrbit_i :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_clrbit_i">;
+//
+// BUILTIN_INFO(HEXAGON.S2_tstbit_r,QI_ftype_SISI,2)
+//
+def int_hexagon_S2_tstbit_r :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_S2_tstbit_r">;
+//
+// BUILTIN_INFO(HEXAGON.S4_ntstbit_r,QI_ftype_SISI,2)
+//
+def int_hexagon_S4_ntstbit_r :
+Hexagon_qi_sisi_Intrinsic<"HEXAGON_S4_ntstbit_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_setbit_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_setbit_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_setbit_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_togglebit_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_togglebit_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_togglebit_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_clrbit_r,SI_ftype_SISI,2)
+//
+def int_hexagon_S2_clrbit_r :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S2_clrbit_r">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_vh,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_i_vh :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asr_i_vh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_vh,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsr_i_vh :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsr_i_vh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_vh,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asl_i_vh :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asl_i_vh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_vh,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_r_vh :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asr_r_vh">;
+//
+// BUILTIN_INFO(HEXAGON.S5_asrhub_rnd_sat_goodsyntax,SI_ftype_DISI,2)
+//
+def int_hexagon_S5_asrhub_rnd_sat_goodsyntax :
+Hexagon_si_disi_Intrinsic<"HEXAGON_S5_asrhub_rnd_sat_goodsyntax">;
+//
+// BUILTIN_INFO(HEXAGON.S5_asrhub_sat,SI_ftype_DISI,2)
+//
+def int_hexagon_S5_asrhub_sat :
+Hexagon_si_disi_Intrinsic<"HEXAGON_S5_asrhub_sat">;
+//
+// BUILTIN_INFO(HEXAGON.S5_vasrhrnd_goodsyntax,DI_ftype_DISI,2)
+//
+def int_hexagon_S5_vasrhrnd_goodsyntax :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S5_vasrhrnd_goodsyntax">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_vh,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asl_r_vh :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asl_r_vh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_vh,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsr_r_vh :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsr_r_vh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_vh,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsl_r_vh :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsl_r_vh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_vw,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_i_vw :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asr_i_vw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_i_svw_trun,SI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_i_svw_trun :
+Hexagon_si_disi_Intrinsic<"HEXAGON_S2_asr_i_svw_trun">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_svw_trun,SI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_r_svw_trun :
+Hexagon_si_disi_Intrinsic<"HEXAGON_S2_asr_r_svw_trun">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_i_vw,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsr_i_vw :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsr_i_vw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_i_vw,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asl_i_vw :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asl_i_vw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asr_r_vw,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asr_r_vw :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asr_r_vw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_asl_r_vw,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_asl_r_vw :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_asl_r_vw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsr_r_vw,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsr_r_vw :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsr_r_vw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lsl_r_vw,DI_ftype_DISI,2)
+//
+def int_hexagon_S2_lsl_r_vw :
+Hexagon_di_disi_Intrinsic<"HEXAGON_S2_lsl_r_vw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vrndpackwh,SI_ftype_DI,1)
+//
+def int_hexagon_S2_vrndpackwh :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_vrndpackwh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vrndpackwhs,SI_ftype_DI,1)
+//
+def int_hexagon_S2_vrndpackwhs :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_vrndpackwhs">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsxtbh,DI_ftype_SI,1)
+//
+def int_hexagon_S2_vsxtbh :
+Hexagon_di_si_Intrinsic<"HEXAGON_S2_vsxtbh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vzxtbh,DI_ftype_SI,1)
+//
+def int_hexagon_S2_vzxtbh :
+Hexagon_di_si_Intrinsic<"HEXAGON_S2_vzxtbh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsathub,SI_ftype_DI,1)
+//
+def int_hexagon_S2_vsathub :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_vsathub">;
+//
+// BUILTIN_INFO(HEXAGON.S2_svsathub,SI_ftype_SI,1)
+//
+def int_hexagon_S2_svsathub :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_svsathub">;
+//
+// BUILTIN_INFO(HEXAGON.S2_svsathb,SI_ftype_SI,1)
+//
+def int_hexagon_S2_svsathb :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_svsathb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsathb,SI_ftype_DI,1)
+//
+def int_hexagon_S2_vsathb :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_vsathb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vtrunohb,SI_ftype_DI,1)
+//
+def int_hexagon_S2_vtrunohb :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_vtrunohb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vtrunewh,DI_ftype_DIDI,2)
+//
+def int_hexagon_S2_vtrunewh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S2_vtrunewh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vtrunowh,DI_ftype_DIDI,2)
+//
+def int_hexagon_S2_vtrunowh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S2_vtrunowh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vtrunehb,SI_ftype_DI,1)
+//
+def int_hexagon_S2_vtrunehb :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_vtrunehb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsxthw,DI_ftype_SI,1)
+//
+def int_hexagon_S2_vsxthw :
+Hexagon_di_si_Intrinsic<"HEXAGON_S2_vsxthw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vzxthw,DI_ftype_SI,1)
+//
+def int_hexagon_S2_vzxthw :
+Hexagon_di_si_Intrinsic<"HEXAGON_S2_vzxthw">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsatwh,SI_ftype_DI,1)
+//
+def int_hexagon_S2_vsatwh :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_vsatwh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsatwuh,SI_ftype_DI,1)
+//
+def int_hexagon_S2_vsatwuh :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_vsatwuh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_packhl,DI_ftype_SISI,2)
+//
+def int_hexagon_S2_packhl :
+Hexagon_di_sisi_Intrinsic<"HEXAGON_S2_packhl">;
+//
+// BUILTIN_INFO(HEXAGON.A2_swiz,SI_ftype_SI,1)
+//
+def int_hexagon_A2_swiz :
+Hexagon_si_si_Intrinsic<"HEXAGON_A2_swiz">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsathub_nopack,DI_ftype_DI,1)
+//
+def int_hexagon_S2_vsathub_nopack :
+Hexagon_di_di_Intrinsic<"HEXAGON_S2_vsathub_nopack">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsathb_nopack,DI_ftype_DI,1)
+//
+def int_hexagon_S2_vsathb_nopack :
+Hexagon_di_di_Intrinsic<"HEXAGON_S2_vsathb_nopack">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsatwh_nopack,DI_ftype_DI,1)
+//
+def int_hexagon_S2_vsatwh_nopack :
+Hexagon_di_di_Intrinsic<"HEXAGON_S2_vsatwh_nopack">;
+//
+// BUILTIN_INFO(HEXAGON.S2_vsatwuh_nopack,DI_ftype_DI,1)
+//
+def int_hexagon_S2_vsatwuh_nopack :
+Hexagon_di_di_Intrinsic<"HEXAGON_S2_vsatwuh_nopack">;
+//
+// BUILTIN_INFO(HEXAGON.S2_shuffob,DI_ftype_DIDI,2)
+//
+def int_hexagon_S2_shuffob :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S2_shuffob">;
+//
+// BUILTIN_INFO(HEXAGON.S2_shuffeb,DI_ftype_DIDI,2)
+//
+def int_hexagon_S2_shuffeb :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S2_shuffeb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_shuffoh,DI_ftype_DIDI,2)
+//
+def int_hexagon_S2_shuffoh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S2_shuffoh">;
+//
+// BUILTIN_INFO(HEXAGON.S2_shuffeh,DI_ftype_DIDI,2)
+//
+def int_hexagon_S2_shuffeh :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S2_shuffeh">;
+//
+// BUILTIN_INFO(HEXAGON.S5_popcountp,SI_ftype_DI,1)
+//
+def int_hexagon_S5_popcountp :
+Hexagon_si_di_Intrinsic<"HEXAGON_S5_popcountp">;
+//
+// BUILTIN_INFO(HEXAGON.S4_parity,SI_ftype_SISI,2)
+//
+def int_hexagon_S4_parity :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S4_parity">;
+//
+// BUILTIN_INFO(HEXAGON.S2_parityp,SI_ftype_DIDI,2)
+//
+def int_hexagon_S2_parityp :
+Hexagon_si_didi_Intrinsic<"HEXAGON_S2_parityp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_lfsp,DI_ftype_DIDI,2)
+//
+def int_hexagon_S2_lfsp :
+Hexagon_di_didi_Intrinsic<"HEXAGON_S2_lfsp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_clbnorm,SI_ftype_SI,1)
+//
+def int_hexagon_S2_clbnorm :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_clbnorm">;
+//
+// BUILTIN_INFO(HEXAGON.S4_clbaddi,SI_ftype_SISI,2)
+//
+def int_hexagon_S4_clbaddi :
+Hexagon_si_sisi_Intrinsic<"HEXAGON_S4_clbaddi">;
+//
+// BUILTIN_INFO(HEXAGON.S4_clbpnorm,SI_ftype_DI,1)
+//
+def int_hexagon_S4_clbpnorm :
+Hexagon_si_di_Intrinsic<"HEXAGON_S4_clbpnorm">;
+//
+// BUILTIN_INFO(HEXAGON.S4_clbpaddi,SI_ftype_DISI,2)
+//
+def int_hexagon_S4_clbpaddi :
+Hexagon_si_disi_Intrinsic<"HEXAGON_S4_clbpaddi">;
+//
+// BUILTIN_INFO(HEXAGON.S2_clb,SI_ftype_SI,1)
+//
+def int_hexagon_S2_clb :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_clb">;
+//
+// BUILTIN_INFO(HEXAGON.S2_cl0,SI_ftype_SI,1)
+//
+def int_hexagon_S2_cl0 :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_cl0">;
+//
+// BUILTIN_INFO(HEXAGON.S2_cl1,SI_ftype_SI,1)
+//
+def int_hexagon_S2_cl1 :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_cl1">;
+//
+// BUILTIN_INFO(HEXAGON.S2_clbp,SI_ftype_DI,1)
+//
+def int_hexagon_S2_clbp :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_clbp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_cl0p,SI_ftype_DI,1)
+//
+def int_hexagon_S2_cl0p :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_cl0p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_cl1p,SI_ftype_DI,1)
+//
+def int_hexagon_S2_cl1p :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_cl1p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_brev,SI_ftype_SI,1)
+//
+def int_hexagon_S2_brev :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_brev">;
+//
+// BUILTIN_INFO(HEXAGON.S2_brevp,DI_ftype_DI,1)
+//
+def int_hexagon_S2_brevp :
+Hexagon_di_di_Intrinsic<"HEXAGON_S2_brevp">;
+//
+// BUILTIN_INFO(HEXAGON.S2_ct0,SI_ftype_SI,1)
+//
+def int_hexagon_S2_ct0 :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_ct0">;
+//
+// BUILTIN_INFO(HEXAGON.S2_ct1,SI_ftype_SI,1)
+//
+def int_hexagon_S2_ct1 :
+Hexagon_si_si_Intrinsic<"HEXAGON_S2_ct1">;
+//
+// BUILTIN_INFO(HEXAGON.S2_ct0p,SI_ftype_DI,1)
+//
+def int_hexagon_S2_ct0p :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_ct0p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_ct1p,SI_ftype_DI,1)
+//
+def int_hexagon_S2_ct1p :
+Hexagon_si_di_Intrinsic<"HEXAGON_S2_ct1p">;
+//
+// BUILTIN_INFO(HEXAGON.S2_interleave,DI_ftype_DI,1)
+//
+def int_hexagon_S2_interleave :
+Hexagon_di_di_Intrinsic<"HEXAGON_S2_interleave">;
+//
+// BUILTIN_INFO(HEXAGON.S2_deinterleave,DI_ftype_DI,1)
+//
+def int_hexagon_S2_deinterleave :
+Hexagon_di_di_Intrinsic<"HEXAGON_S2_deinterleave">;
diff --git a/include/llvm/IntrinsicsMips.td b/include/llvm/IntrinsicsMips.td
new file mode 100644
index 00000000000..e40e162a158
--- /dev/null
+++ b/include/llvm/IntrinsicsMips.td
@@ -0,0 +1,389 @@
+//===- IntrinsicsMips.td - Defines Mips intrinsics ---------*- tablegen -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines all of the MIPS-specific intrinsics.
+//
+//===----------------------------------------------------------------------===//
+
+//===----------------------------------------------------------------------===//
+// MIPS DSP data types
+def mips_v2q15_ty: LLVMType<v2i16>;
+def mips_v4q7_ty: LLVMType<v4i8>;
+def mips_q31_ty: LLVMType<i32>;
+
+let TargetPrefix = "mips" in { // All intrinsics start with "llvm.mips.".
+
+//===----------------------------------------------------------------------===//
+// MIPS DSP Rev 1
+
+//===----------------------------------------------------------------------===//
+// Addition/subtraction
+
+def int_mips_addu_qb : GCCBuiltin<"__builtin_mips_addu_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_addu_s_qb : GCCBuiltin<"__builtin_mips_addu_s_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_subu_qb : GCCBuiltin<"__builtin_mips_subu_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty], []>;
+def int_mips_subu_s_qb : GCCBuiltin<"__builtin_mips_subu_s_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty], []>;
+
+def int_mips_addq_ph : GCCBuiltin<"__builtin_mips_addq_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+def int_mips_addq_s_ph : GCCBuiltin<"__builtin_mips_addq_s_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+def int_mips_subq_ph : GCCBuiltin<"__builtin_mips_subq_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_subq_s_ph : GCCBuiltin<"__builtin_mips_subq_s_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], []>;
+
+def int_mips_madd: GCCBuiltin<"__builtin_mips_madd">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+def int_mips_maddu: GCCBuiltin<"__builtin_mips_maddu">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+def int_mips_msub: GCCBuiltin<"__builtin_mips_msub">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+def int_mips_msubu: GCCBuiltin<"__builtin_mips_msubu">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+
+def int_mips_addq_s_w: GCCBuiltin<"__builtin_mips_addq_s_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, mips_q31_ty], [Commutative]>;
+def int_mips_subq_s_w: GCCBuiltin<"__builtin_mips_subq_s_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, mips_q31_ty], []>;
+
+def int_mips_addsc: GCCBuiltin<"__builtin_mips_addsc">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [Commutative]>;
+def int_mips_addwc: GCCBuiltin<"__builtin_mips_addwc">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [Commutative]>;
+
+def int_mips_modsub: GCCBuiltin<"__builtin_mips_modsub">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+
+def int_mips_raddu_w_qb: GCCBuiltin<"__builtin_mips_raddu_w_qb">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+
+//===----------------------------------------------------------------------===//
+// Absolute value
+
+def int_mips_absq_s_ph: GCCBuiltin<"__builtin_mips_absq_s_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty], []>;
+def int_mips_absq_s_w: GCCBuiltin<"__builtin_mips_absq_s_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty], []>;
+
+//===----------------------------------------------------------------------===//
+// Precision reduce/expand
+
+def int_mips_precrq_qb_ph: GCCBuiltin<"__builtin_mips_precrq_qb_ph">,
+ Intrinsic<[llvm_v4i8_ty], [mips_v2q15_ty, mips_v2q15_ty], [IntrNoMem]>;
+def int_mips_precrqu_s_qb_ph: GCCBuiltin<"__builtin_mips_precrqu_s_qb_ph">,
+ Intrinsic<[llvm_v4i8_ty], [mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_precrq_ph_w: GCCBuiltin<"__builtin_mips_precrq_ph_w">,
+ Intrinsic<[mips_v2q15_ty], [mips_q31_ty, mips_q31_ty], [IntrNoMem]>;
+def int_mips_precrq_rs_ph_w: GCCBuiltin<"__builtin_mips_precrq_rs_ph_w">,
+ Intrinsic<[mips_v2q15_ty], [mips_q31_ty, mips_q31_ty], []>;
+def int_mips_preceq_w_phl: GCCBuiltin<"__builtin_mips_preceq_w_phl">,
+ Intrinsic<[mips_q31_ty], [mips_v2q15_ty], [IntrNoMem]>;
+def int_mips_preceq_w_phr: GCCBuiltin<"__builtin_mips_preceq_w_phr">,
+ Intrinsic<[mips_q31_ty], [mips_v2q15_ty], [IntrNoMem]>;
+def int_mips_precequ_ph_qbl: GCCBuiltin<"__builtin_mips_precequ_ph_qbl">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+def int_mips_precequ_ph_qbr: GCCBuiltin<"__builtin_mips_precequ_ph_qbr">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+def int_mips_precequ_ph_qbla: GCCBuiltin<"__builtin_mips_precequ_ph_qbla">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+def int_mips_precequ_ph_qbra: GCCBuiltin<"__builtin_mips_precequ_ph_qbra">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+def int_mips_preceu_ph_qbl: GCCBuiltin<"__builtin_mips_preceu_ph_qbl">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+def int_mips_preceu_ph_qbr: GCCBuiltin<"__builtin_mips_preceu_ph_qbr">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+def int_mips_preceu_ph_qbla: GCCBuiltin<"__builtin_mips_preceu_ph_qbla">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+def int_mips_preceu_ph_qbra: GCCBuiltin<"__builtin_mips_preceu_ph_qbra">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty], [IntrNoMem]>;
+
+//===----------------------------------------------------------------------===//
+// Shift
+
+def int_mips_shll_qb: GCCBuiltin<"__builtin_mips_shll_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_i32_ty], []>;
+def int_mips_shrl_qb: GCCBuiltin<"__builtin_mips_shrl_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_i32_ty], [IntrNoMem]>;
+def int_mips_shll_ph: GCCBuiltin<"__builtin_mips_shll_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, llvm_i32_ty], []>;
+def int_mips_shll_s_ph: GCCBuiltin<"__builtin_mips_shll_s_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, llvm_i32_ty], []>;
+def int_mips_shra_ph: GCCBuiltin<"__builtin_mips_shra_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, llvm_i32_ty], [IntrNoMem]>;
+def int_mips_shra_r_ph: GCCBuiltin<"__builtin_mips_shra_r_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, llvm_i32_ty], [IntrNoMem]>;
+def int_mips_shll_s_w: GCCBuiltin<"__builtin_mips_shll_s_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, llvm_i32_ty], []>;
+def int_mips_shra_r_w: GCCBuiltin<"__builtin_mips_shra_r_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, llvm_i32_ty], [IntrNoMem]>;
+def int_mips_shilo: GCCBuiltin<"__builtin_mips_shilo">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i32_ty], [IntrNoMem]>;
+
+//===----------------------------------------------------------------------===//
+// Multiplication
+
+def int_mips_muleu_s_ph_qbl: GCCBuiltin<"__builtin_mips_muleu_s_ph_qbl">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty, mips_v2q15_ty], []>;
+def int_mips_muleu_s_ph_qbr: GCCBuiltin<"__builtin_mips_muleu_s_ph_qbr">,
+ Intrinsic<[mips_v2q15_ty], [llvm_v4i8_ty, mips_v2q15_ty], []>;
+def int_mips_mulq_rs_ph: GCCBuiltin<"__builtin_mips_mulq_rs_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+def int_mips_muleq_s_w_phl: GCCBuiltin<"__builtin_mips_muleq_s_w_phl">,
+ Intrinsic<[mips_q31_ty], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+def int_mips_muleq_s_w_phr: GCCBuiltin<"__builtin_mips_muleq_s_w_phr">,
+ Intrinsic<[mips_q31_ty], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+def int_mips_mulsaq_s_w_ph: GCCBuiltin<"__builtin_mips_mulsaq_s_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_maq_s_w_phl: GCCBuiltin<"__builtin_mips_maq_s_w_phl">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_maq_s_w_phr: GCCBuiltin<"__builtin_mips_maq_s_w_phr">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_maq_sa_w_phl: GCCBuiltin<"__builtin_mips_maq_sa_w_phl">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_maq_sa_w_phr: GCCBuiltin<"__builtin_mips_maq_sa_w_phr">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_mult: GCCBuiltin<"__builtin_mips_mult">,
+ Intrinsic<[llvm_i64_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+def int_mips_multu: GCCBuiltin<"__builtin_mips_multu">,
+ Intrinsic<[llvm_i64_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+//===----------------------------------------------------------------------===//
+// Dot product with accumulate/subtract
+
+def int_mips_dpau_h_qbl: GCCBuiltin<"__builtin_mips_dpau_h_qbl">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v4i8_ty, llvm_v4i8_ty],
+ [IntrNoMem]>;
+def int_mips_dpau_h_qbr: GCCBuiltin<"__builtin_mips_dpau_h_qbr">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v4i8_ty, llvm_v4i8_ty],
+ [IntrNoMem]>;
+def int_mips_dpsu_h_qbl: GCCBuiltin<"__builtin_mips_dpsu_h_qbl">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v4i8_ty, llvm_v4i8_ty],
+ [IntrNoMem]>;
+def int_mips_dpsu_h_qbr: GCCBuiltin<"__builtin_mips_dpsu_h_qbr">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v4i8_ty, llvm_v4i8_ty],
+ [IntrNoMem]>;
+def int_mips_dpaq_s_w_ph: GCCBuiltin<"__builtin_mips_dpaq_s_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_dpsq_s_w_ph: GCCBuiltin<"__builtin_mips_dpsq_s_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_dpaq_sa_l_w: GCCBuiltin<"__builtin_mips_dpaq_sa_l_w">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_q31_ty, mips_q31_ty], []>;
+def int_mips_dpsq_sa_l_w: GCCBuiltin<"__builtin_mips_dpsq_sa_l_w">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_q31_ty, mips_q31_ty], []>;
+
+//===----------------------------------------------------------------------===//
+// Comparison
+
+def int_mips_cmpu_eq_qb: GCCBuiltin<"__builtin_mips_cmpu_eq_qb">,
+ Intrinsic<[], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_cmpu_lt_qb: GCCBuiltin<"__builtin_mips_cmpu_lt_qb">,
+ Intrinsic<[], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_cmpu_le_qb: GCCBuiltin<"__builtin_mips_cmpu_le_qb">,
+ Intrinsic<[], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_cmpgu_eq_qb: GCCBuiltin<"__builtin_mips_cmpgu_eq_qb">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_cmpgu_lt_qb: GCCBuiltin<"__builtin_mips_cmpgu_lt_qb">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_cmpgu_le_qb: GCCBuiltin<"__builtin_mips_cmpgu_le_qb">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_cmp_eq_ph: GCCBuiltin<"__builtin_mips_cmp_eq_ph">,
+ Intrinsic<[], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+def int_mips_cmp_lt_ph: GCCBuiltin<"__builtin_mips_cmp_lt_ph">,
+ Intrinsic<[], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+def int_mips_cmp_le_ph: GCCBuiltin<"__builtin_mips_cmp_le_ph">,
+ Intrinsic<[], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+
+//===----------------------------------------------------------------------===//
+// Extracting
+
+def int_mips_extr_s_h: GCCBuiltin<"__builtin_mips_extr_s_h">,
+ Intrinsic<[llvm_i32_ty], [llvm_i64_ty, llvm_i32_ty], []>;
+def int_mips_extr_w: GCCBuiltin<"__builtin_mips_extr_w">,
+ Intrinsic<[llvm_i32_ty], [llvm_i64_ty, llvm_i32_ty], []>;
+def int_mips_extr_rs_w: GCCBuiltin<"__builtin_mips_extr_rs_w">,
+ Intrinsic<[llvm_i32_ty], [llvm_i64_ty, llvm_i32_ty], []>;
+def int_mips_extr_r_w: GCCBuiltin<"__builtin_mips_extr_r_w">,
+ Intrinsic<[llvm_i32_ty], [llvm_i64_ty, llvm_i32_ty], []>;
+def int_mips_extp: GCCBuiltin<"__builtin_mips_extp">,
+ Intrinsic<[llvm_i32_ty], [llvm_i64_ty, llvm_i32_ty], []>;
+def int_mips_extpdp: GCCBuiltin<"__builtin_mips_extpdp">,
+ Intrinsic<[llvm_i32_ty], [llvm_i64_ty, llvm_i32_ty], []>;
+
+//===----------------------------------------------------------------------===//
+// Misc
+
+def int_mips_wrdsp: GCCBuiltin<"__builtin_mips_wrdsp">,
+ Intrinsic<[], [llvm_i32_ty, llvm_i32_ty], []>;
+def int_mips_rddsp: GCCBuiltin<"__builtin_mips_rddsp">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], [IntrReadMem]>;
+
+def int_mips_insv: GCCBuiltin<"__builtin_mips_insv">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrReadMem]>;
+def int_mips_bitrev: GCCBuiltin<"__builtin_mips_bitrev">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], [IntrNoMem]>;
+
+def int_mips_packrl_ph: GCCBuiltin<"__builtin_mips_packrl_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], [IntrNoMem]>;
+
+def int_mips_repl_qb: GCCBuiltin<"__builtin_mips_repl_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_i32_ty], [IntrNoMem]>;
+def int_mips_repl_ph: GCCBuiltin<"__builtin_mips_repl_ph">,
+ Intrinsic<[mips_v2q15_ty], [llvm_i32_ty], [IntrNoMem]>;
+
+def int_mips_pick_qb: GCCBuiltin<"__builtin_mips_pick_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [IntrReadMem]>;
+def int_mips_pick_ph: GCCBuiltin<"__builtin_mips_pick_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], [IntrReadMem]>;
+
+def int_mips_mthlip: GCCBuiltin<"__builtin_mips_mthlip">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i32_ty], []>;
+
+def int_mips_bposge32: GCCBuiltin<"__builtin_mips_bposge32">,
+ Intrinsic<[llvm_i32_ty], [], [IntrReadMem]>;
+
+def int_mips_lbux: GCCBuiltin<"__builtin_mips_lbux">,
+ Intrinsic<[llvm_i32_ty], [llvm_ptr_ty, llvm_i32_ty], [IntrReadArgMem]>;
+def int_mips_lhx: GCCBuiltin<"__builtin_mips_lhx">,
+ Intrinsic<[llvm_i32_ty], [llvm_ptr_ty, llvm_i32_ty], [IntrReadArgMem]>;
+def int_mips_lwx: GCCBuiltin<"__builtin_mips_lwx">,
+ Intrinsic<[llvm_i32_ty], [llvm_ptr_ty, llvm_i32_ty], [IntrReadArgMem]>;
+
+//===----------------------------------------------------------------------===//
+// MIPS DSP Rev 2
+
+def int_mips_absq_s_qb: GCCBuiltin<"__builtin_mips_absq_s_qb">,
+ Intrinsic<[mips_v4q7_ty], [mips_v4q7_ty], []>;
+
+def int_mips_addqh_ph: GCCBuiltin<"__builtin_mips_addqh_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty],
+ [IntrNoMem, Commutative]>;
+def int_mips_addqh_r_ph: GCCBuiltin<"__builtin_mips_addqh_r_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty],
+ [IntrNoMem, Commutative]>;
+def int_mips_addqh_w: GCCBuiltin<"__builtin_mips_addqh_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, mips_q31_ty],
+ [IntrNoMem, Commutative]>;
+def int_mips_addqh_r_w: GCCBuiltin<"__builtin_mips_addqh_r_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, mips_q31_ty],
+ [IntrNoMem, Commutative]>;
+
+def int_mips_addu_ph: GCCBuiltin<"__builtin_mips_addu_ph">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_v2i16_ty, llvm_v2i16_ty], [Commutative]>;
+def int_mips_addu_s_ph: GCCBuiltin<"__builtin_mips_addu_s_ph">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_v2i16_ty, llvm_v2i16_ty], [Commutative]>;
+
+def int_mips_adduh_qb: GCCBuiltin<"__builtin_mips_adduh_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty],
+ [IntrNoMem, Commutative]>;
+def int_mips_adduh_r_qb: GCCBuiltin<"__builtin_mips_adduh_r_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty],
+ [IntrNoMem, Commutative]>;
+
+def int_mips_append: GCCBuiltin<"__builtin_mips_append">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+def int_mips_balign: GCCBuiltin<"__builtin_mips_balign">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+
+def int_mips_cmpgdu_eq_qb: GCCBuiltin<"__builtin_mips_cmpgdu_eq_qb">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_cmpgdu_lt_qb: GCCBuiltin<"__builtin_mips_cmpgdu_lt_qb">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+def int_mips_cmpgdu_le_qb: GCCBuiltin<"__builtin_mips_cmpgdu_le_qb">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [Commutative]>;
+
+def int_mips_dpa_w_ph: GCCBuiltin<"__builtin_mips_dpa_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v2i16_ty, llvm_v2i16_ty],
+ [IntrNoMem]>;
+def int_mips_dps_w_ph: GCCBuiltin<"__builtin_mips_dps_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v2i16_ty, llvm_v2i16_ty],
+ [IntrNoMem]>;
+
+def int_mips_dpaqx_s_w_ph: GCCBuiltin<"__builtin_mips_dpaqx_s_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_dpaqx_sa_w_ph: GCCBuiltin<"__builtin_mips_dpaqx_sa_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_dpax_w_ph: GCCBuiltin<"__builtin_mips_dpax_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v2i16_ty, llvm_v2i16_ty],
+ [IntrNoMem]>;
+def int_mips_dpsx_w_ph: GCCBuiltin<"__builtin_mips_dpsx_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v2i16_ty, llvm_v2i16_ty],
+ [IntrNoMem]>;
+def int_mips_dpsqx_s_w_ph: GCCBuiltin<"__builtin_mips_dpsqx_s_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+def int_mips_dpsqx_sa_w_ph: GCCBuiltin<"__builtin_mips_dpsqx_sa_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, mips_v2q15_ty, mips_v2q15_ty], []>;
+
+def int_mips_mul_ph: GCCBuiltin<"__builtin_mips_mul_ph">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_v2i16_ty, llvm_v2i16_ty], [Commutative]>;
+def int_mips_mul_s_ph: GCCBuiltin<"__builtin_mips_mul_s_ph">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_v2i16_ty, llvm_v2i16_ty], [Commutative]>;
+
+def int_mips_mulq_rs_w: GCCBuiltin<"__builtin_mips_mulq_rs_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, mips_q31_ty], [Commutative]>;
+def int_mips_mulq_s_ph: GCCBuiltin<"__builtin_mips_mulq_s_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], [Commutative]>;
+def int_mips_mulq_s_w: GCCBuiltin<"__builtin_mips_mulq_s_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, mips_q31_ty], [Commutative]>;
+def int_mips_mulsa_w_ph: GCCBuiltin<"__builtin_mips_mulsa_w_ph">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_v2i16_ty, llvm_v2i16_ty],
+ [IntrNoMem]>;
+
+def int_mips_precr_qb_ph: GCCBuiltin<"__builtin_mips_precr_qb_ph">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v2i16_ty, llvm_v2i16_ty], []>;
+def int_mips_precr_sra_ph_w: GCCBuiltin<"__builtin_mips_precr_sra_ph_w">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+def int_mips_precr_sra_r_ph_w: GCCBuiltin<"__builtin_mips_precr_sra_r_ph_w">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+
+def int_mips_prepend: GCCBuiltin<"__builtin_mips_prepend">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+
+def int_mips_shra_qb: GCCBuiltin<"__builtin_mips_shra_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_i32_ty], [IntrNoMem]>;
+def int_mips_shra_r_qb: GCCBuiltin<"__builtin_mips_shra_r_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_i32_ty], [IntrNoMem]>;
+def int_mips_shrl_ph: GCCBuiltin<"__builtin_mips_shrl_ph">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_v2i16_ty, llvm_i32_ty], [IntrNoMem]>;
+
+def int_mips_subqh_ph: GCCBuiltin<"__builtin_mips_subqh_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], [IntrNoMem]>;
+def int_mips_subqh_r_ph: GCCBuiltin<"__builtin_mips_subqh_r_ph">,
+ Intrinsic<[mips_v2q15_ty], [mips_v2q15_ty, mips_v2q15_ty], [IntrNoMem]>;
+def int_mips_subqh_w: GCCBuiltin<"__builtin_mips_subqh_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, mips_q31_ty], [IntrNoMem]>;
+def int_mips_subqh_r_w: GCCBuiltin<"__builtin_mips_subqh_r_w">,
+ Intrinsic<[mips_q31_ty], [mips_q31_ty, mips_q31_ty], [IntrNoMem]>;
+
+def int_mips_subu_ph: GCCBuiltin<"__builtin_mips_subu_ph">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_v2i16_ty, llvm_v2i16_ty], []>;
+def int_mips_subu_s_ph: GCCBuiltin<"__builtin_mips_subu_s_ph">,
+ Intrinsic<[llvm_v2i16_ty], [llvm_v2i16_ty, llvm_v2i16_ty], []>;
+
+def int_mips_subuh_qb: GCCBuiltin<"__builtin_mips_subuh_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [IntrNoMem]>;
+def int_mips_subuh_r_qb: GCCBuiltin<"__builtin_mips_subuh_r_qb">,
+ Intrinsic<[llvm_v4i8_ty], [llvm_v4i8_ty, llvm_v4i8_ty], [IntrNoMem]>;
+}
diff --git a/include/llvm/IntrinsicsNVVM.td b/include/llvm/IntrinsicsNVVM.td
new file mode 100644
index 00000000000..1853c9988b4
--- /dev/null
+++ b/include/llvm/IntrinsicsNVVM.td
@@ -0,0 +1,952 @@
+//===- IntrinsicsNVVM.td - Defines NVVM intrinsics ---------*- tablegen -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines all of the NVVM-specific intrinsics for use with NVPTX.
+//
+//===----------------------------------------------------------------------===//
+
+def llvm_anyi64ptr_ty : LLVMAnyPointerType<llvm_i64_ty>; // (space)i64*
+
+//
+// MISC
+//
+
+ def int_nvvm_clz_i : GCCBuiltin<"__nvvm_clz_i">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_clz_ll : GCCBuiltin<"__nvvm_clz_ll">,
+ Intrinsic<[llvm_i32_ty], [llvm_i64_ty], [IntrNoMem]>;
+
+ def int_nvvm_popc_i : GCCBuiltin<"__nvvm_popc_i">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_popc_ll : GCCBuiltin<"__nvvm_popc_ll">,
+ Intrinsic<[llvm_i32_ty], [llvm_i64_ty], [IntrNoMem]>;
+
+ def int_nvvm_prmt : GCCBuiltin<"__nvvm_prmt">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+//
+// Min Max
+//
+
+ def int_nvvm_min_i : GCCBuiltin<"__nvvm_min_i">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_min_ui : GCCBuiltin<"__nvvm_min_ui">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_min_ll : GCCBuiltin<"__nvvm_min_ll">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_min_ull : GCCBuiltin<"__nvvm_min_ull">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_max_i : GCCBuiltin<"__nvvm_max_i">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_max_ui : GCCBuiltin<"__nvvm_max_ui">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_max_ll : GCCBuiltin<"__nvvm_max_ll">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_max_ull : GCCBuiltin<"__nvvm_max_ull">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_fmin_f : GCCBuiltin<"__nvvm_fmin_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fmin_ftz_f : GCCBuiltin<"__nvvm_fmin_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_fmax_f : GCCBuiltin<"__nvvm_fmax_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty]
+ , [IntrNoMem, Commutative]>;
+ def int_nvvm_fmax_ftz_f : GCCBuiltin<"__nvvm_fmax_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_fmin_d : GCCBuiltin<"__nvvm_fmin_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fmax_d : GCCBuiltin<"__nvvm_fmax_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+
+//
+// Multiplication
+//
+
+ def int_nvvm_mulhi_i : GCCBuiltin<"__nvvm_mulhi_i">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mulhi_ui : GCCBuiltin<"__nvvm_mulhi_ui">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_mulhi_ll : GCCBuiltin<"__nvvm_mulhi_ll">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mulhi_ull : GCCBuiltin<"__nvvm_mulhi_ull">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_mul_rn_ftz_f : GCCBuiltin<"__nvvm_mul_rn_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rn_f : GCCBuiltin<"__nvvm_mul_rn_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rz_ftz_f : GCCBuiltin<"__nvvm_mul_rz_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rz_f : GCCBuiltin<"__nvvm_mul_rz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rm_ftz_f : GCCBuiltin<"__nvvm_mul_rm_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rm_f : GCCBuiltin<"__nvvm_mul_rm_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rp_ftz_f : GCCBuiltin<"__nvvm_mul_rp_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rp_f : GCCBuiltin<"__nvvm_mul_rp_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_mul_rn_d : GCCBuiltin<"__nvvm_mul_rn_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rz_d : GCCBuiltin<"__nvvm_mul_rz_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rm_d : GCCBuiltin<"__nvvm_mul_rm_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul_rp_d : GCCBuiltin<"__nvvm_mul_rp_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_mul24_i : GCCBuiltin<"__nvvm_mul24_i">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_mul24_ui : GCCBuiltin<"__nvvm_mul24_ui">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+//
+// Div
+//
+
+ def int_nvvm_div_approx_ftz_f : GCCBuiltin<"__nvvm_div_approx_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_div_approx_f : GCCBuiltin<"__nvvm_div_approx_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_div_rn_ftz_f : GCCBuiltin<"__nvvm_div_rn_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_div_rn_f : GCCBuiltin<"__nvvm_div_rn_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_div_rz_ftz_f : GCCBuiltin<"__nvvm_div_rz_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_div_rz_f : GCCBuiltin<"__nvvm_div_rz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_div_rm_ftz_f : GCCBuiltin<"__nvvm_div_rm_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_div_rm_f : GCCBuiltin<"__nvvm_div_rm_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_div_rp_ftz_f : GCCBuiltin<"__nvvm_div_rp_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_div_rp_f : GCCBuiltin<"__nvvm_div_rp_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_div_rn_d : GCCBuiltin<"__nvvm_div_rn_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_div_rz_d : GCCBuiltin<"__nvvm_div_rz_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_div_rm_d : GCCBuiltin<"__nvvm_div_rm_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_div_rp_d : GCCBuiltin<"__nvvm_div_rp_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+
+//
+// Brev
+//
+
+ def int_nvvm_brev32 : GCCBuiltin<"__nvvm_brev32">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_brev64 : GCCBuiltin<"__nvvm_brev64">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty], [IntrNoMem]>;
+
+//
+// Sad
+//
+
+ def int_nvvm_sad_i : GCCBuiltin<"__nvvm_sad_i">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_sad_ui : GCCBuiltin<"__nvvm_sad_ui">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+//
+// Floor Ceil
+//
+
+ def int_nvvm_floor_ftz_f : GCCBuiltin<"__nvvm_floor_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_floor_f : GCCBuiltin<"__nvvm_floor_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_floor_d : GCCBuiltin<"__nvvm_floor_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_ceil_ftz_f : GCCBuiltin<"__nvvm_ceil_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_ceil_f : GCCBuiltin<"__nvvm_ceil_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_ceil_d : GCCBuiltin<"__nvvm_ceil_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Abs
+//
+
+ def int_nvvm_abs_i : GCCBuiltin<"__nvvm_abs_i">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_abs_ll : GCCBuiltin<"__nvvm_abs_ll">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty], [IntrNoMem]>;
+
+ def int_nvvm_fabs_ftz_f : GCCBuiltin<"__nvvm_fabs_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_fabs_f : GCCBuiltin<"__nvvm_fabs_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_fabs_d : GCCBuiltin<"__nvvm_fabs_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Round
+//
+
+ def int_nvvm_round_ftz_f : GCCBuiltin<"__nvvm_round_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_round_f : GCCBuiltin<"__nvvm_round_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_round_d : GCCBuiltin<"__nvvm_round_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Trunc
+//
+
+ def int_nvvm_trunc_ftz_f : GCCBuiltin<"__nvvm_trunc_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_trunc_f : GCCBuiltin<"__nvvm_trunc_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_trunc_d : GCCBuiltin<"__nvvm_trunc_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Saturate
+//
+
+ def int_nvvm_saturate_ftz_f : GCCBuiltin<"__nvvm_saturate_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_saturate_f : GCCBuiltin<"__nvvm_saturate_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_saturate_d : GCCBuiltin<"__nvvm_saturate_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Exp2 Log2
+//
+
+ def int_nvvm_ex2_approx_ftz_f : GCCBuiltin<"__nvvm_ex2_approx_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_ex2_approx_f : GCCBuiltin<"__nvvm_ex2_approx_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_ex2_approx_d : GCCBuiltin<"__nvvm_ex2_approx_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_lg2_approx_ftz_f : GCCBuiltin<"__nvvm_lg2_approx_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_lg2_approx_f : GCCBuiltin<"__nvvm_lg2_approx_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_lg2_approx_d : GCCBuiltin<"__nvvm_lg2_approx_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Sin Cos
+//
+
+ def int_nvvm_sin_approx_ftz_f : GCCBuiltin<"__nvvm_sin_approx_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sin_approx_f : GCCBuiltin<"__nvvm_sin_approx_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_cos_approx_ftz_f : GCCBuiltin<"__nvvm_cos_approx_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_cos_approx_f : GCCBuiltin<"__nvvm_cos_approx_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+
+//
+// Fma
+//
+
+ def int_nvvm_fma_rn_ftz_f : GCCBuiltin<"__nvvm_fma_rn_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rn_f : GCCBuiltin<"__nvvm_fma_rn_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rz_ftz_f : GCCBuiltin<"__nvvm_fma_rz_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rz_f : GCCBuiltin<"__nvvm_fma_rz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rm_ftz_f : GCCBuiltin<"__nvvm_fma_rm_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rm_f : GCCBuiltin<"__nvvm_fma_rm_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rp_ftz_f : GCCBuiltin<"__nvvm_fma_rp_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rp_f : GCCBuiltin<"__nvvm_fma_rp_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_fma_rn_d : GCCBuiltin<"__nvvm_fma_rn_d">,
+ Intrinsic<[llvm_double_ty],
+ [llvm_double_ty, llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rz_d : GCCBuiltin<"__nvvm_fma_rz_d">,
+ Intrinsic<[llvm_double_ty],
+ [llvm_double_ty, llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rm_d : GCCBuiltin<"__nvvm_fma_rm_d">,
+ Intrinsic<[llvm_double_ty],
+ [llvm_double_ty, llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_fma_rp_d : GCCBuiltin<"__nvvm_fma_rp_d">,
+ Intrinsic<[llvm_double_ty],
+ [llvm_double_ty, llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+
+//
+// Rcp
+//
+
+ def int_nvvm_rcp_rn_ftz_f : GCCBuiltin<"__nvvm_rcp_rn_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rn_f : GCCBuiltin<"__nvvm_rcp_rn_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rz_ftz_f : GCCBuiltin<"__nvvm_rcp_rz_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rz_f : GCCBuiltin<"__nvvm_rcp_rz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rm_ftz_f : GCCBuiltin<"__nvvm_rcp_rm_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rm_f : GCCBuiltin<"__nvvm_rcp_rm_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rp_ftz_f : GCCBuiltin<"__nvvm_rcp_rp_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rp_f : GCCBuiltin<"__nvvm_rcp_rp_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_rcp_rn_d : GCCBuiltin<"__nvvm_rcp_rn_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rz_d : GCCBuiltin<"__nvvm_rcp_rz_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rm_d : GCCBuiltin<"__nvvm_rcp_rm_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_rcp_rp_d : GCCBuiltin<"__nvvm_rcp_rp_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_rcp_approx_ftz_d : GCCBuiltin<"__nvvm_rcp_approx_ftz_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Sqrt
+//
+
+ def int_nvvm_sqrt_rn_ftz_f : GCCBuiltin<"__nvvm_sqrt_rn_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rn_f : GCCBuiltin<"__nvvm_sqrt_rn_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rz_ftz_f : GCCBuiltin<"__nvvm_sqrt_rz_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rz_f : GCCBuiltin<"__nvvm_sqrt_rz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rm_ftz_f : GCCBuiltin<"__nvvm_sqrt_rm_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rm_f : GCCBuiltin<"__nvvm_sqrt_rm_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rp_ftz_f : GCCBuiltin<"__nvvm_sqrt_rp_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rp_f : GCCBuiltin<"__nvvm_sqrt_rp_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_approx_ftz_f : GCCBuiltin<"__nvvm_sqrt_approx_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_approx_f : GCCBuiltin<"__nvvm_sqrt_approx_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_sqrt_rn_d : GCCBuiltin<"__nvvm_sqrt_rn_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rz_d : GCCBuiltin<"__nvvm_sqrt_rz_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rm_d : GCCBuiltin<"__nvvm_sqrt_rm_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_sqrt_rp_d : GCCBuiltin<"__nvvm_sqrt_rp_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Rsqrt
+//
+
+ def int_nvvm_rsqrt_approx_ftz_f : GCCBuiltin<"__nvvm_rsqrt_approx_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rsqrt_approx_f : GCCBuiltin<"__nvvm_rsqrt_approx_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_rsqrt_approx_d : GCCBuiltin<"__nvvm_rsqrt_approx_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty], [IntrNoMem]>;
+
+//
+// Add
+//
+
+ def int_nvvm_add_rn_ftz_f : GCCBuiltin<"__nvvm_add_rn_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rn_f : GCCBuiltin<"__nvvm_add_rn_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rz_ftz_f : GCCBuiltin<"__nvvm_add_rz_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rz_f : GCCBuiltin<"__nvvm_add_rz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rm_ftz_f : GCCBuiltin<"__nvvm_add_rm_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rm_f : GCCBuiltin<"__nvvm_add_rm_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rp_ftz_f : GCCBuiltin<"__nvvm_add_rp_ftz_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rp_f : GCCBuiltin<"__nvvm_add_rp_f">,
+ Intrinsic<[llvm_float_ty], [llvm_float_ty, llvm_float_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_add_rn_d : GCCBuiltin<"__nvvm_add_rn_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rz_d : GCCBuiltin<"__nvvm_add_rz_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rm_d : GCCBuiltin<"__nvvm_add_rm_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+ def int_nvvm_add_rp_d : GCCBuiltin<"__nvvm_add_rp_d">,
+ Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty],
+ [IntrNoMem, Commutative]>;
+
+//
+// Convert
+//
+
+ def int_nvvm_d2f_rn_ftz : GCCBuiltin<"__nvvm_d2f_rn_ftz">,
+ Intrinsic<[llvm_float_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2f_rn : GCCBuiltin<"__nvvm_d2f_rn">,
+ Intrinsic<[llvm_float_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2f_rz_ftz : GCCBuiltin<"__nvvm_d2f_rz_ftz">,
+ Intrinsic<[llvm_float_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2f_rz : GCCBuiltin<"__nvvm_d2f_rz">,
+ Intrinsic<[llvm_float_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2f_rm_ftz : GCCBuiltin<"__nvvm_d2f_rm_ftz">,
+ Intrinsic<[llvm_float_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2f_rm : GCCBuiltin<"__nvvm_d2f_rm">,
+ Intrinsic<[llvm_float_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2f_rp_ftz : GCCBuiltin<"__nvvm_d2f_rp_ftz">,
+ Intrinsic<[llvm_float_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2f_rp : GCCBuiltin<"__nvvm_d2f_rp">,
+ Intrinsic<[llvm_float_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_d2i_rn : GCCBuiltin<"__nvvm_d2i_rn">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2i_rz : GCCBuiltin<"__nvvm_d2i_rz">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2i_rm : GCCBuiltin<"__nvvm_d2i_rm">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2i_rp : GCCBuiltin<"__nvvm_d2i_rp">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_d2ui_rn : GCCBuiltin<"__nvvm_d2ui_rn">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ui_rz : GCCBuiltin<"__nvvm_d2ui_rz">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ui_rm : GCCBuiltin<"__nvvm_d2ui_rm">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ui_rp : GCCBuiltin<"__nvvm_d2ui_rp">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_i2d_rn : GCCBuiltin<"__nvvm_i2d_rn">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_i2d_rz : GCCBuiltin<"__nvvm_i2d_rz">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_i2d_rm : GCCBuiltin<"__nvvm_i2d_rm">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_i2d_rp : GCCBuiltin<"__nvvm_i2d_rp">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty], [IntrNoMem]>;
+
+ def int_nvvm_ui2d_rn : GCCBuiltin<"__nvvm_ui2d_rn">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_ui2d_rz : GCCBuiltin<"__nvvm_ui2d_rz">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_ui2d_rm : GCCBuiltin<"__nvvm_ui2d_rm">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_ui2d_rp : GCCBuiltin<"__nvvm_ui2d_rp">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty], [IntrNoMem]>;
+
+ def int_nvvm_f2i_rn_ftz : GCCBuiltin<"__nvvm_f2i_rn_ftz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2i_rn : GCCBuiltin<"__nvvm_f2i_rn">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2i_rz_ftz : GCCBuiltin<"__nvvm_f2i_rz_ftz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2i_rz : GCCBuiltin<"__nvvm_f2i_rz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2i_rm_ftz : GCCBuiltin<"__nvvm_f2i_rm_ftz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2i_rm : GCCBuiltin<"__nvvm_f2i_rm">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2i_rp_ftz : GCCBuiltin<"__nvvm_f2i_rp_ftz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2i_rp : GCCBuiltin<"__nvvm_f2i_rp">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_f2ui_rn_ftz : GCCBuiltin<"__nvvm_f2ui_rn_ftz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ui_rn : GCCBuiltin<"__nvvm_f2ui_rn">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ui_rz_ftz : GCCBuiltin<"__nvvm_f2ui_rz_ftz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ui_rz : GCCBuiltin<"__nvvm_f2ui_rz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ui_rm_ftz : GCCBuiltin<"__nvvm_f2ui_rm_ftz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ui_rm : GCCBuiltin<"__nvvm_f2ui_rm">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ui_rp_ftz : GCCBuiltin<"__nvvm_f2ui_rp_ftz">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ui_rp : GCCBuiltin<"__nvvm_f2ui_rp">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_i2f_rn : GCCBuiltin<"__nvvm_i2f_rn">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_i2f_rz : GCCBuiltin<"__nvvm_i2f_rz">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_i2f_rm : GCCBuiltin<"__nvvm_i2f_rm">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_i2f_rp : GCCBuiltin<"__nvvm_i2f_rp">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+
+ def int_nvvm_ui2f_rn : GCCBuiltin<"__nvvm_ui2f_rn">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_ui2f_rz : GCCBuiltin<"__nvvm_ui2f_rz">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_ui2f_rm : GCCBuiltin<"__nvvm_ui2f_rm">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+ def int_nvvm_ui2f_rp : GCCBuiltin<"__nvvm_ui2f_rp">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+
+ def int_nvvm_lohi_i2d : GCCBuiltin<"__nvvm_lohi_i2d">,
+ Intrinsic<[llvm_double_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+
+ def int_nvvm_d2i_lo : GCCBuiltin<"__nvvm_d2i_lo">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2i_hi : GCCBuiltin<"__nvvm_d2i_hi">,
+ Intrinsic<[llvm_i32_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_f2ll_rn_ftz : GCCBuiltin<"__nvvm_f2ll_rn_ftz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ll_rn : GCCBuiltin<"__nvvm_f2ll_rn">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ll_rz_ftz : GCCBuiltin<"__nvvm_f2ll_rz_ftz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ll_rz : GCCBuiltin<"__nvvm_f2ll_rz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ll_rm_ftz : GCCBuiltin<"__nvvm_f2ll_rm_ftz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ll_rm : GCCBuiltin<"__nvvm_f2ll_rm">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ll_rp_ftz : GCCBuiltin<"__nvvm_f2ll_rp_ftz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ll_rp : GCCBuiltin<"__nvvm_f2ll_rp">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_f2ull_rn_ftz : GCCBuiltin<"__nvvm_f2ull_rn_ftz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ull_rn : GCCBuiltin<"__nvvm_f2ull_rn">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ull_rz_ftz : GCCBuiltin<"__nvvm_f2ull_rz_ftz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ull_rz : GCCBuiltin<"__nvvm_f2ull_rz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ull_rm_ftz : GCCBuiltin<"__nvvm_f2ull_rm_ftz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ull_rm : GCCBuiltin<"__nvvm_f2ull_rm">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ull_rp_ftz : GCCBuiltin<"__nvvm_f2ull_rp_ftz">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2ull_rp : GCCBuiltin<"__nvvm_f2ull_rp">,
+ Intrinsic<[llvm_i64_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_d2ll_rn : GCCBuiltin<"__nvvm_d2ll_rn">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ll_rz : GCCBuiltin<"__nvvm_d2ll_rz">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ll_rm : GCCBuiltin<"__nvvm_d2ll_rm">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ll_rp : GCCBuiltin<"__nvvm_d2ll_rp">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_d2ull_rn : GCCBuiltin<"__nvvm_d2ull_rn">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ull_rz : GCCBuiltin<"__nvvm_d2ull_rz">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ull_rm : GCCBuiltin<"__nvvm_d2ull_rm">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+ def int_nvvm_d2ull_rp : GCCBuiltin<"__nvvm_d2ull_rp">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+
+ def int_nvvm_ll2f_rn : GCCBuiltin<"__nvvm_ll2f_rn">,
+ Intrinsic<[llvm_float_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ll2f_rz : GCCBuiltin<"__nvvm_ll2f_rz">,
+ Intrinsic<[llvm_float_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ll2f_rm : GCCBuiltin<"__nvvm_ll2f_rm">,
+ Intrinsic<[llvm_float_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ll2f_rp : GCCBuiltin<"__nvvm_ll2f_rp">,
+ Intrinsic<[llvm_float_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ull2f_rn : GCCBuiltin<"__nvvm_ull2f_rn">,
+ Intrinsic<[llvm_float_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ull2f_rz : GCCBuiltin<"__nvvm_ull2f_rz">,
+ Intrinsic<[llvm_float_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ull2f_rm : GCCBuiltin<"__nvvm_ull2f_rm">,
+ Intrinsic<[llvm_float_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ull2f_rp : GCCBuiltin<"__nvvm_ull2f_rp">,
+ Intrinsic<[llvm_float_ty], [llvm_i64_ty], [IntrNoMem]>;
+
+ def int_nvvm_ll2d_rn : GCCBuiltin<"__nvvm_ll2d_rn">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ll2d_rz : GCCBuiltin<"__nvvm_ll2d_rz">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ll2d_rm : GCCBuiltin<"__nvvm_ll2d_rm">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ll2d_rp : GCCBuiltin<"__nvvm_ll2d_rp">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ull2d_rn : GCCBuiltin<"__nvvm_ull2d_rn">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ull2d_rz : GCCBuiltin<"__nvvm_ull2d_rz">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ull2d_rm : GCCBuiltin<"__nvvm_ull2d_rm">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_ull2d_rp : GCCBuiltin<"__nvvm_ull2d_rp">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+
+ def int_nvvm_f2h_rn_ftz : GCCBuiltin<"__nvvm_f2h_rn_ftz">,
+ Intrinsic<[llvm_i16_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_f2h_rn : GCCBuiltin<"__nvvm_f2h_rn">,
+ Intrinsic<[llvm_i16_ty], [llvm_float_ty], [IntrNoMem]>;
+
+ def int_nvvm_h2f : GCCBuiltin<"__nvvm_h2f">,
+ Intrinsic<[llvm_float_ty], [llvm_i16_ty], [IntrNoMem]>;
+
+//
+// Bitcast
+//
+
+ def int_nvvm_bitcast_f2i : GCCBuiltin<"__nvvm_bitcast_f2i">,
+ Intrinsic<[llvm_i32_ty], [llvm_float_ty], [IntrNoMem]>;
+ def int_nvvm_bitcast_i2f : GCCBuiltin<"__nvvm_bitcast_i2f">,
+ Intrinsic<[llvm_float_ty], [llvm_i32_ty], [IntrNoMem]>;
+
+ def int_nvvm_bitcast_ll2d : GCCBuiltin<"__nvvm_bitcast_ll2d">,
+ Intrinsic<[llvm_double_ty], [llvm_i64_ty], [IntrNoMem]>;
+ def int_nvvm_bitcast_d2ll : GCCBuiltin<"__nvvm_bitcast_d2ll">,
+ Intrinsic<[llvm_i64_ty], [llvm_double_ty], [IntrNoMem]>;
+
+
+// Atomic not available as an llvm intrinsic.
+ def int_nvvm_atomic_load_add_f32 : Intrinsic<[llvm_float_ty],
+ [LLVMAnyPointerType<llvm_float_ty>, llvm_float_ty],
+ [IntrReadWriteArgMem, NoCapture<0>]>;
+ def int_nvvm_atomic_load_inc_32 : Intrinsic<[llvm_i32_ty],
+ [LLVMAnyPointerType<llvm_i32_ty>, llvm_i32_ty],
+ [IntrReadWriteArgMem, NoCapture<0>]>;
+ def int_nvvm_atomic_load_dec_32 : Intrinsic<[llvm_i32_ty],
+ [LLVMAnyPointerType<llvm_i32_ty>, llvm_i32_ty],
+ [IntrReadWriteArgMem, NoCapture<0>]>;
+
+// Bar.Sync
+ def int_cuda_syncthreads : GCCBuiltin<"__syncthreads">,
+ Intrinsic<[], [], []>;
+ def int_nvvm_barrier0 : GCCBuiltin<"__nvvm_bar0">,
+ Intrinsic<[], [], []>;
+ def int_nvvm_barrier0_popc : GCCBuiltin<"__nvvm_bar0_popc">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], []>;
+ def int_nvvm_barrier0_and : GCCBuiltin<"__nvvm_bar0_and">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], []>;
+ def int_nvvm_barrier0_or : GCCBuiltin<"__nvvm_bar0_or">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty], []>;
+
+ // Membar
+ def int_nvvm_membar_cta : GCCBuiltin<"__nvvm_membar_cta">,
+ Intrinsic<[], [], []>;
+ def int_nvvm_membar_gl : GCCBuiltin<"__nvvm_membar_gl">,
+ Intrinsic<[], [], []>;
+ def int_nvvm_membar_sys : GCCBuiltin<"__nvvm_membar_sys">,
+ Intrinsic<[], [], []>;
+
+
+// Accessing special registers
+ def int_nvvm_read_ptx_sreg_tid_x :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_tid_x">;
+ def int_nvvm_read_ptx_sreg_tid_y :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_tid_y">;
+ def int_nvvm_read_ptx_sreg_tid_z :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_tid_z">;
+
+ def int_nvvm_read_ptx_sreg_ntid_x :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_ntid_x">;
+ def int_nvvm_read_ptx_sreg_ntid_y :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_ntid_y">;
+ def int_nvvm_read_ptx_sreg_ntid_z :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_ntid_z">;
+
+ def int_nvvm_read_ptx_sreg_ctaid_x :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_ctaid_x">;
+ def int_nvvm_read_ptx_sreg_ctaid_y :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_ctaid_y">;
+ def int_nvvm_read_ptx_sreg_ctaid_z :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_ctaid_z">;
+
+ def int_nvvm_read_ptx_sreg_nctaid_x :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_nctaid_x">;
+ def int_nvvm_read_ptx_sreg_nctaid_y :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_nctaid_y">;
+ def int_nvvm_read_ptx_sreg_nctaid_z :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_nctaid_z">;
+
+ def int_nvvm_read_ptx_sreg_warpsize :
+ Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<"__nvvm_read_ptx_sreg_warpsize">;
+
+
+// Generated within nvvm. Use for ldu on sm_20 or later
+// @TODO: Revisit this, Changed LLVMAnyPointerType to LLVMPointerType
+def int_nvvm_ldu_global_i : Intrinsic<[llvm_anyint_ty],
+ [LLVMPointerType<LLVMMatchType<0>>], [IntrReadMem, NoCapture<0>],
+ "llvm.nvvm.ldu.global.i">;
+def int_nvvm_ldu_global_f : Intrinsic<[llvm_anyfloat_ty],
+ [LLVMPointerType<LLVMMatchType<0>>], [IntrReadMem, NoCapture<0>],
+ "llvm.nvvm.ldu.global.f">;
+def int_nvvm_ldu_global_p : Intrinsic<[llvm_anyptr_ty],
+ [LLVMPointerType<LLVMMatchType<0>>], [IntrReadMem, NoCapture<0>],
+ "llvm.nvvm.ldu.global.p">;
+
+
+// Use for generic pointers
+// - These intrinsics are used to convert address spaces.
+// - The input pointer and output pointer must have the same type, except for
+// the address-space. (This restriction is not enforced here as there is
+// currently no way to describe it).
+// - This complements the llvm bitcast, which can be used to cast one type
+// of pointer to another type of pointer, while the address space remains
+// the same.
+def int_nvvm_ptr_local_to_gen: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty], [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.local.to.gen">;
+def int_nvvm_ptr_shared_to_gen: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty], [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.shared.to.gen">;
+def int_nvvm_ptr_global_to_gen: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty], [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.global.to.gen">;
+def int_nvvm_ptr_constant_to_gen: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty], [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.constant.to.gen">;
+
+def int_nvvm_ptr_gen_to_global: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty], [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.gen.to.global">;
+def int_nvvm_ptr_gen_to_shared: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty], [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.gen.to.shared">;
+def int_nvvm_ptr_gen_to_local: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty], [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.gen.to.local">;
+def int_nvvm_ptr_gen_to_constant: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty], [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.gen.to.constant">;
+
+// Used in nvvm internally to help address space opt and ptx code generation
+// This is for params that are passed to kernel functions by pointer by-val.
+def int_nvvm_ptr_gen_to_param: Intrinsic<[llvm_anyptr_ty],
+ [llvm_anyptr_ty],
+ [IntrNoMem, NoCapture<0>],
+ "llvm.nvvm.ptr.gen.to.param">;
+
+// Move intrinsics, used in nvvm internally
+
+def int_nvvm_move_i8 : Intrinsic<[llvm_i8_ty], [llvm_i8_ty], [IntrNoMem],
+ "llvm.nvvm.move.i8">;
+def int_nvvm_move_i16 : Intrinsic<[llvm_i16_ty], [llvm_i16_ty], [IntrNoMem],
+ "llvm.nvvm.move.i16">;
+def int_nvvm_move_i32 : Intrinsic<[llvm_i32_ty], [llvm_i32_ty], [IntrNoMem],
+ "llvm.nvvm.move.i32">;
+def int_nvvm_move_i64 : Intrinsic<[llvm_i64_ty], [llvm_i64_ty], [IntrNoMem],
+ "llvm.nvvm.move.i64">;
+def int_nvvm_move_float : Intrinsic<[llvm_float_ty], [llvm_float_ty],
+ [IntrNoMem], "llvm.nvvm.move.float">;
+def int_nvvm_move_double : Intrinsic<[llvm_double_ty], [llvm_double_ty],
+ [IntrNoMem], "llvm.nvvm.move.double">;
+def int_nvvm_move_ptr : Intrinsic<[llvm_anyptr_ty], [llvm_anyptr_ty],
+ [IntrNoMem, NoCapture<0>], "llvm.nvvm.move.ptr">;
+
+
+/// Error / Warn
+def int_nvvm_compiler_error :
+ Intrinsic<[], [llvm_anyptr_ty], [], "llvm.nvvm.compiler.error">;
+def int_nvvm_compiler_warn :
+ Intrinsic<[], [llvm_anyptr_ty], [], "llvm.nvvm.compiler.warn">;
+
+
+// Old PTX back-end intrinsics retained here for backwards-compatibility
+
+multiclass PTXReadSpecialRegisterIntrinsic_v4i32<string prefix> {
+// FIXME: Do we need the 128-bit integer type version?
+// def _r64 : Intrinsic<[llvm_i128_ty], [], [IntrNoMem]>;
+
+// FIXME: Enable this once v4i32 support is enabled in back-end.
+// def _v4i16 : Intrinsic<[llvm_v4i32_ty], [], [IntrNoMem]>;
+
+ def _x : Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<!strconcat(prefix, "_x")>;
+ def _y : Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<!strconcat(prefix, "_y")>;
+ def _z : Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<!strconcat(prefix, "_z")>;
+ def _w : Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<!strconcat(prefix, "_w")>;
+}
+
+class PTXReadSpecialRegisterIntrinsic_r32<string name>
+ : Intrinsic<[llvm_i32_ty], [], [IntrNoMem]>,
+ GCCBuiltin<name>;
+
+class PTXReadSpecialRegisterIntrinsic_r64<string name>
+ : Intrinsic<[llvm_i64_ty], [], [IntrNoMem]>,
+ GCCBuiltin<name>;
+
+defm int_ptx_read_tid : PTXReadSpecialRegisterIntrinsic_v4i32
+ <"__builtin_ptx_read_tid">;
+defm int_ptx_read_ntid : PTXReadSpecialRegisterIntrinsic_v4i32
+ <"__builtin_ptx_read_ntid">;
+
+def int_ptx_read_laneid : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_laneid">;
+def int_ptx_read_warpid : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_warpid">;
+def int_ptx_read_nwarpid : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_nwarpid">;
+
+defm int_ptx_read_ctaid : PTXReadSpecialRegisterIntrinsic_v4i32
+ <"__builtin_ptx_read_ctaid">;
+defm int_ptx_read_nctaid : PTXReadSpecialRegisterIntrinsic_v4i32
+ <"__builtin_ptx_read_nctaid">;
+
+def int_ptx_read_smid : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_smid">;
+def int_ptx_read_nsmid : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_nsmid">;
+def int_ptx_read_gridid : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_gridid">;
+
+def int_ptx_read_lanemask_eq : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_lanemask_eq">;
+def int_ptx_read_lanemask_le : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_lanemask_le">;
+def int_ptx_read_lanemask_lt : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_lanemask_lt">;
+def int_ptx_read_lanemask_ge : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_lanemask_ge">;
+def int_ptx_read_lanemask_gt : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_lanemask_gt">;
+
+def int_ptx_read_clock : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_clock">;
+def int_ptx_read_clock64 : PTXReadSpecialRegisterIntrinsic_r64
+ <"__builtin_ptx_read_clock64">;
+
+def int_ptx_read_pm0 : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_pm0">;
+def int_ptx_read_pm1 : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_pm1">;
+def int_ptx_read_pm2 : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_pm2">;
+def int_ptx_read_pm3 : PTXReadSpecialRegisterIntrinsic_r32
+ <"__builtin_ptx_read_pm3">;
+
+def int_ptx_bar_sync : Intrinsic<[], [llvm_i32_ty], []>,
+ GCCBuiltin<"__builtin_ptx_bar_sync">;
diff --git a/include/llvm/IntrinsicsPowerPC.td b/include/llvm/IntrinsicsPowerPC.td
new file mode 100644
index 00000000000..da85bfba863
--- /dev/null
+++ b/include/llvm/IntrinsicsPowerPC.td
@@ -0,0 +1,465 @@
+//===- IntrinsicsPowerPC.td - Defines PowerPC intrinsics ---*- tablegen -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines all of the PowerPC-specific intrinsics.
+//
+//===----------------------------------------------------------------------===//
+
+//===----------------------------------------------------------------------===//
+// Definitions for all PowerPC intrinsics.
+//
+
+// Non-altivec intrinsics.
+let TargetPrefix = "ppc" in { // All intrinsics start with "llvm.ppc.".
+ // dcba/dcbf/dcbi/dcbst/dcbt/dcbz/dcbzl(PPC970) instructions.
+ def int_ppc_dcba : Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_ppc_dcbf : Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_ppc_dcbi : Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_ppc_dcbst : Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_ppc_dcbt : Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_ppc_dcbtst: Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_ppc_dcbz : Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_ppc_dcbzl : Intrinsic<[], [llvm_ptr_ty], []>;
+
+ // sync instruction
+ def int_ppc_sync : Intrinsic<[], [], []>;
+}
+
+
+let TargetPrefix = "ppc" in { // All PPC intrinsics start with "llvm.ppc.".
+ /// PowerPC_Vec_Intrinsic - Base class for all altivec intrinsics.
+ class PowerPC_Vec_Intrinsic<string GCCIntSuffix, list<LLVMType> ret_types,
+ list<LLVMType> param_types,
+ list<IntrinsicProperty> properties>
+ : GCCBuiltin<!strconcat("__builtin_altivec_", GCCIntSuffix)>,
+ Intrinsic<ret_types, param_types, properties>;
+}
+
+//===----------------------------------------------------------------------===//
+// PowerPC Altivec Intrinsic Class Definitions.
+//
+
+/// PowerPC_Vec_FF_Intrinsic - A PowerPC intrinsic that takes one v4f32
+/// vector and returns one. These intrinsics have no side effects.
+class PowerPC_Vec_FF_Intrinsic<string GCCIntSuffix>
+ : PowerPC_Vec_Intrinsic<GCCIntSuffix,
+ [llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+
+/// PowerPC_Vec_FFF_Intrinsic - A PowerPC intrinsic that takes two v4f32
+/// vectors and returns one. These intrinsics have no side effects.
+class PowerPC_Vec_FFF_Intrinsic<string GCCIntSuffix>
+ : PowerPC_Vec_Intrinsic<GCCIntSuffix,
+ [llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+
+/// PowerPC_Vec_BBB_Intrinsic - A PowerPC intrinsic that takes two v16f8
+/// vectors and returns one. These intrinsics have no side effects.
+class PowerPC_Vec_BBB_Intrinsic<string GCCIntSuffix>
+ : PowerPC_Vec_Intrinsic<GCCIntSuffix,
+ [llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+
+/// PowerPC_Vec_HHH_Intrinsic - A PowerPC intrinsic that takes two v8i16
+/// vectors and returns one. These intrinsics have no side effects.
+class PowerPC_Vec_HHH_Intrinsic<string GCCIntSuffix>
+ : PowerPC_Vec_Intrinsic<GCCIntSuffix,
+ [llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+
+/// PowerPC_Vec_WWW_Intrinsic - A PowerPC intrinsic that takes two v4i32
+/// vectors and returns one. These intrinsics have no side effects.
+class PowerPC_Vec_WWW_Intrinsic<string GCCIntSuffix>
+ : PowerPC_Vec_Intrinsic<GCCIntSuffix,
+ [llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+
+
+//===----------------------------------------------------------------------===//
+// PowerPC Altivec Intrinsic Definitions.
+
+let TargetPrefix = "ppc" in { // All intrinsics start with "llvm.ppc.".
+ // Data Stream Control.
+ def int_ppc_altivec_dss : GCCBuiltin<"__builtin_altivec_dss">,
+ Intrinsic<[], [llvm_i32_ty], []>;
+ def int_ppc_altivec_dssall : GCCBuiltin<"__builtin_altivec_dssall">,
+ Intrinsic<[], [], []>;
+ def int_ppc_altivec_dst : GCCBuiltin<"__builtin_altivec_dst">,
+ Intrinsic<[],
+ [llvm_ptr_ty, llvm_i32_ty, llvm_i32_ty],
+ []>;
+ def int_ppc_altivec_dstt : GCCBuiltin<"__builtin_altivec_dstt">,
+ Intrinsic<[],
+ [llvm_ptr_ty, llvm_i32_ty, llvm_i32_ty],
+ []>;
+ def int_ppc_altivec_dstst : GCCBuiltin<"__builtin_altivec_dstst">,
+ Intrinsic<[],
+ [llvm_ptr_ty, llvm_i32_ty, llvm_i32_ty],
+ []>;
+ def int_ppc_altivec_dststt : GCCBuiltin<"__builtin_altivec_dststt">,
+ Intrinsic<[],
+ [llvm_ptr_ty, llvm_i32_ty, llvm_i32_ty],
+ []>;
+
+ // VSCR access.
+ def int_ppc_altivec_mfvscr : GCCBuiltin<"__builtin_altivec_mfvscr">,
+ Intrinsic<[llvm_v8i16_ty], [], [IntrReadMem]>;
+ def int_ppc_altivec_mtvscr : GCCBuiltin<"__builtin_altivec_mtvscr">,
+ Intrinsic<[], [llvm_v4i32_ty], []>;
+
+
+ // Loads. These don't map directly to GCC builtins because they represent the
+ // source address with a single pointer.
+ def int_ppc_altivec_lvx :
+ Intrinsic<[llvm_v4i32_ty], [llvm_ptr_ty], [IntrReadMem]>;
+ def int_ppc_altivec_lvxl :
+ Intrinsic<[llvm_v4i32_ty], [llvm_ptr_ty], [IntrReadMem]>;
+ def int_ppc_altivec_lvebx :
+ Intrinsic<[llvm_v16i8_ty], [llvm_ptr_ty], [IntrReadMem]>;
+ def int_ppc_altivec_lvehx :
+ Intrinsic<[llvm_v8i16_ty], [llvm_ptr_ty], [IntrReadMem]>;
+ def int_ppc_altivec_lvewx :
+ Intrinsic<[llvm_v4i32_ty], [llvm_ptr_ty], [IntrReadMem]>;
+
+ // Stores. These don't map directly to GCC builtins because they represent the
+ // source address with a single pointer.
+ def int_ppc_altivec_stvx :
+ Intrinsic<[], [llvm_v4i32_ty, llvm_ptr_ty], []>;
+ def int_ppc_altivec_stvxl :
+ Intrinsic<[], [llvm_v4i32_ty, llvm_ptr_ty], []>;
+ def int_ppc_altivec_stvebx :
+ Intrinsic<[], [llvm_v16i8_ty, llvm_ptr_ty], []>;
+ def int_ppc_altivec_stvehx :
+ Intrinsic<[], [llvm_v8i16_ty, llvm_ptr_ty], []>;
+ def int_ppc_altivec_stvewx :
+ Intrinsic<[], [llvm_v4i32_ty, llvm_ptr_ty], []>;
+
+ // Comparisons setting a vector.
+ def int_ppc_altivec_vcmpbfp : GCCBuiltin<"__builtin_altivec_vcmpbfp">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpeqfp : GCCBuiltin<"__builtin_altivec_vcmpeqfp">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgefp : GCCBuiltin<"__builtin_altivec_vcmpgefp">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtfp : GCCBuiltin<"__builtin_altivec_vcmpgtfp">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+
+ def int_ppc_altivec_vcmpequw : GCCBuiltin<"__builtin_altivec_vcmpequw">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtsw : GCCBuiltin<"__builtin_altivec_vcmpgtsw">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtuw : GCCBuiltin<"__builtin_altivec_vcmpgtuw">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+
+ def int_ppc_altivec_vcmpequh : GCCBuiltin<"__builtin_altivec_vcmpequh">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtsh : GCCBuiltin<"__builtin_altivec_vcmpgtsh">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtuh : GCCBuiltin<"__builtin_altivec_vcmpgtuh">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+
+ def int_ppc_altivec_vcmpequb : GCCBuiltin<"__builtin_altivec_vcmpequb">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtsb : GCCBuiltin<"__builtin_altivec_vcmpgtsb">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtub : GCCBuiltin<"__builtin_altivec_vcmpgtub">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+
+ // Predicate Comparisons. The first operand specifies interpretation of CR6.
+ def int_ppc_altivec_vcmpbfp_p : GCCBuiltin<"__builtin_altivec_vcmpbfp_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v4f32_ty,llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpeqfp_p : GCCBuiltin<"__builtin_altivec_vcmpeqfp_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v4f32_ty,llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgefp_p : GCCBuiltin<"__builtin_altivec_vcmpgefp_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v4f32_ty,llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtfp_p : GCCBuiltin<"__builtin_altivec_vcmpgtfp_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v4f32_ty,llvm_v4f32_ty],
+ [IntrNoMem]>;
+
+ def int_ppc_altivec_vcmpequw_p : GCCBuiltin<"__builtin_altivec_vcmpequw_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v4i32_ty,llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtsw_p : GCCBuiltin<"__builtin_altivec_vcmpgtsw_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v4i32_ty,llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtuw_p : GCCBuiltin<"__builtin_altivec_vcmpgtuw_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v4i32_ty,llvm_v4i32_ty],
+ [IntrNoMem]>;
+
+ def int_ppc_altivec_vcmpequh_p : GCCBuiltin<"__builtin_altivec_vcmpequh_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v8i16_ty,llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtsh_p : GCCBuiltin<"__builtin_altivec_vcmpgtsh_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v8i16_ty,llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtuh_p : GCCBuiltin<"__builtin_altivec_vcmpgtuh_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v8i16_ty,llvm_v8i16_ty],
+ [IntrNoMem]>;
+
+ def int_ppc_altivec_vcmpequb_p : GCCBuiltin<"__builtin_altivec_vcmpequb_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v16i8_ty,llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtsb_p : GCCBuiltin<"__builtin_altivec_vcmpgtsb_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v16i8_ty,llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcmpgtub_p : GCCBuiltin<"__builtin_altivec_vcmpgtub_p">,
+ Intrinsic<[llvm_i32_ty],[llvm_i32_ty,llvm_v16i8_ty,llvm_v16i8_ty],
+ [IntrNoMem]>;
+}
+
+// Vector average.
+def int_ppc_altivec_vavgsb : PowerPC_Vec_BBB_Intrinsic<"vavgsb">;
+def int_ppc_altivec_vavgsh : PowerPC_Vec_HHH_Intrinsic<"vavgsh">;
+def int_ppc_altivec_vavgsw : PowerPC_Vec_WWW_Intrinsic<"vavgsw">;
+def int_ppc_altivec_vavgub : PowerPC_Vec_BBB_Intrinsic<"vavgub">;
+def int_ppc_altivec_vavguh : PowerPC_Vec_HHH_Intrinsic<"vavguh">;
+def int_ppc_altivec_vavguw : PowerPC_Vec_WWW_Intrinsic<"vavguw">;
+
+// Vector maximum.
+def int_ppc_altivec_vmaxfp : PowerPC_Vec_FFF_Intrinsic<"vmaxfp">;
+def int_ppc_altivec_vmaxsb : PowerPC_Vec_BBB_Intrinsic<"vmaxsb">;
+def int_ppc_altivec_vmaxsh : PowerPC_Vec_HHH_Intrinsic<"vmaxsh">;
+def int_ppc_altivec_vmaxsw : PowerPC_Vec_WWW_Intrinsic<"vmaxsw">;
+def int_ppc_altivec_vmaxub : PowerPC_Vec_BBB_Intrinsic<"vmaxub">;
+def int_ppc_altivec_vmaxuh : PowerPC_Vec_HHH_Intrinsic<"vmaxuh">;
+def int_ppc_altivec_vmaxuw : PowerPC_Vec_WWW_Intrinsic<"vmaxuw">;
+
+// Vector minimum.
+def int_ppc_altivec_vminfp : PowerPC_Vec_FFF_Intrinsic<"vminfp">;
+def int_ppc_altivec_vminsb : PowerPC_Vec_BBB_Intrinsic<"vminsb">;
+def int_ppc_altivec_vminsh : PowerPC_Vec_HHH_Intrinsic<"vminsh">;
+def int_ppc_altivec_vminsw : PowerPC_Vec_WWW_Intrinsic<"vminsw">;
+def int_ppc_altivec_vminub : PowerPC_Vec_BBB_Intrinsic<"vminub">;
+def int_ppc_altivec_vminuh : PowerPC_Vec_HHH_Intrinsic<"vminuh">;
+def int_ppc_altivec_vminuw : PowerPC_Vec_WWW_Intrinsic<"vminuw">;
+
+// Saturating adds.
+def int_ppc_altivec_vaddubs : PowerPC_Vec_BBB_Intrinsic<"vaddubs">;
+def int_ppc_altivec_vaddsbs : PowerPC_Vec_BBB_Intrinsic<"vaddsbs">;
+def int_ppc_altivec_vadduhs : PowerPC_Vec_HHH_Intrinsic<"vadduhs">;
+def int_ppc_altivec_vaddshs : PowerPC_Vec_HHH_Intrinsic<"vaddshs">;
+def int_ppc_altivec_vadduws : PowerPC_Vec_WWW_Intrinsic<"vadduws">;
+def int_ppc_altivec_vaddsws : PowerPC_Vec_WWW_Intrinsic<"vaddsws">;
+def int_ppc_altivec_vaddcuw : PowerPC_Vec_WWW_Intrinsic<"vaddcuw">;
+
+// Saturating subs.
+def int_ppc_altivec_vsububs : PowerPC_Vec_BBB_Intrinsic<"vsububs">;
+def int_ppc_altivec_vsubsbs : PowerPC_Vec_BBB_Intrinsic<"vsubsbs">;
+def int_ppc_altivec_vsubuhs : PowerPC_Vec_HHH_Intrinsic<"vsubuhs">;
+def int_ppc_altivec_vsubshs : PowerPC_Vec_HHH_Intrinsic<"vsubshs">;
+def int_ppc_altivec_vsubuws : PowerPC_Vec_WWW_Intrinsic<"vsubuws">;
+def int_ppc_altivec_vsubsws : PowerPC_Vec_WWW_Intrinsic<"vsubsws">;
+def int_ppc_altivec_vsubcuw : PowerPC_Vec_WWW_Intrinsic<"vsubcuw">;
+
+let TargetPrefix = "ppc" in { // All PPC intrinsics start with "llvm.ppc.".
+ // Saturating multiply-adds.
+ def int_ppc_altivec_vmhaddshs : GCCBuiltin<"__builtin_altivec_vmhaddshs">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty, llvm_v8i16_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vmhraddshs : GCCBuiltin<"__builtin_altivec_vmhraddshs">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty, llvm_v8i16_ty], [IntrNoMem]>;
+
+ def int_ppc_altivec_vmaddfp : GCCBuiltin<"__builtin_altivec_vmaddfp">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty, llvm_v4f32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vnmsubfp : GCCBuiltin<"__builtin_altivec_vnmsubfp">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty, llvm_v4f32_ty], [IntrNoMem]>;
+
+ // Vector Multiply Sum Intructions.
+ def int_ppc_altivec_vmsummbm : GCCBuiltin<"__builtin_altivec_vmsummbm">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty, llvm_v16i8_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vmsumshm : GCCBuiltin<"__builtin_altivec_vmsumshm">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vmsumshs : GCCBuiltin<"__builtin_altivec_vmsumshs">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vmsumubm : GCCBuiltin<"__builtin_altivec_vmsumubm">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty, llvm_v16i8_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vmsumuhm : GCCBuiltin<"__builtin_altivec_vmsumuhm">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vmsumuhs : GCCBuiltin<"__builtin_altivec_vmsumuhs">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+
+ // Vector Multiply Intructions.
+ def int_ppc_altivec_vmulesb : GCCBuiltin<"__builtin_altivec_vmulesb">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vmulesh : GCCBuiltin<"__builtin_altivec_vmulesh">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vmuleub : GCCBuiltin<"__builtin_altivec_vmuleub">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vmuleuh : GCCBuiltin<"__builtin_altivec_vmuleuh">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+
+ def int_ppc_altivec_vmulosb : GCCBuiltin<"__builtin_altivec_vmulosb">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vmulosh : GCCBuiltin<"__builtin_altivec_vmulosh">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vmuloub : GCCBuiltin<"__builtin_altivec_vmuloub">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vmulouh : GCCBuiltin<"__builtin_altivec_vmulouh">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+
+ // Vector Sum Intructions.
+ def int_ppc_altivec_vsumsws : GCCBuiltin<"__builtin_altivec_vsumsws">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vsum2sws : GCCBuiltin<"__builtin_altivec_vsum2sws">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vsum4sbs : GCCBuiltin<"__builtin_altivec_vsum4sbs">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vsum4shs : GCCBuiltin<"__builtin_altivec_vsum4shs">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vsum4ubs : GCCBuiltin<"__builtin_altivec_vsum4ubs">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+
+ // Other multiplies.
+ def int_ppc_altivec_vmladduhm : GCCBuiltin<"__builtin_altivec_vmladduhm">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+
+ // Packs.
+ def int_ppc_altivec_vpkpx : GCCBuiltin<"__builtin_altivec_vpkpx">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vpkshss : GCCBuiltin<"__builtin_altivec_vpkshss">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vpkshus : GCCBuiltin<"__builtin_altivec_vpkshus">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vpkswss : GCCBuiltin<"__builtin_altivec_vpkswss">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vpkswus : GCCBuiltin<"__builtin_altivec_vpkswus">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ // vpkuhum is lowered to a shuffle.
+ def int_ppc_altivec_vpkuhus : GCCBuiltin<"__builtin_altivec_vpkuhus">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ // vpkuwum is lowered to a shuffle.
+ def int_ppc_altivec_vpkuwus : GCCBuiltin<"__builtin_altivec_vpkuwus">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+
+ // Unpacks.
+ def int_ppc_altivec_vupkhpx : GCCBuiltin<"__builtin_altivec_vupkhpx">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vupkhsb : GCCBuiltin<"__builtin_altivec_vupkhsb">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vupkhsh : GCCBuiltin<"__builtin_altivec_vupkhsh">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vupklpx : GCCBuiltin<"__builtin_altivec_vupklpx">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vupklsb : GCCBuiltin<"__builtin_altivec_vupklsb">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vupklsh : GCCBuiltin<"__builtin_altivec_vupklsh">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+
+
+ // FP <-> integer conversion.
+ def int_ppc_altivec_vcfsx : GCCBuiltin<"__builtin_altivec_vcfsx">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vcfux : GCCBuiltin<"__builtin_altivec_vcfux">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vctsxs : GCCBuiltin<"__builtin_altivec_vctsxs">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_ppc_altivec_vctuxs : GCCBuiltin<"__builtin_altivec_vctuxs">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+
+ def int_ppc_altivec_vrfim : GCCBuiltin<"__builtin_altivec_vrfim">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vrfin : GCCBuiltin<"__builtin_altivec_vrfin">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vrfip : GCCBuiltin<"__builtin_altivec_vrfip">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vrfiz : GCCBuiltin<"__builtin_altivec_vrfiz">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+}
+
+def int_ppc_altivec_vsl : PowerPC_Vec_WWW_Intrinsic<"vsl">;
+def int_ppc_altivec_vslo : PowerPC_Vec_WWW_Intrinsic<"vslo">;
+
+def int_ppc_altivec_vslb : PowerPC_Vec_BBB_Intrinsic<"vslb">;
+def int_ppc_altivec_vslh : PowerPC_Vec_HHH_Intrinsic<"vslh">;
+def int_ppc_altivec_vslw : PowerPC_Vec_WWW_Intrinsic<"vslw">;
+
+// Right Shifts.
+def int_ppc_altivec_vsr : PowerPC_Vec_WWW_Intrinsic<"vsr">;
+def int_ppc_altivec_vsro : PowerPC_Vec_WWW_Intrinsic<"vsro">;
+
+def int_ppc_altivec_vsrb : PowerPC_Vec_BBB_Intrinsic<"vsrb">;
+def int_ppc_altivec_vsrh : PowerPC_Vec_HHH_Intrinsic<"vsrh">;
+def int_ppc_altivec_vsrw : PowerPC_Vec_WWW_Intrinsic<"vsrw">;
+def int_ppc_altivec_vsrab : PowerPC_Vec_BBB_Intrinsic<"vsrab">;
+def int_ppc_altivec_vsrah : PowerPC_Vec_HHH_Intrinsic<"vsrah">;
+def int_ppc_altivec_vsraw : PowerPC_Vec_WWW_Intrinsic<"vsraw">;
+
+// Rotates.
+def int_ppc_altivec_vrlb : PowerPC_Vec_BBB_Intrinsic<"vrlb">;
+def int_ppc_altivec_vrlh : PowerPC_Vec_HHH_Intrinsic<"vrlh">;
+def int_ppc_altivec_vrlw : PowerPC_Vec_WWW_Intrinsic<"vrlw">;
+
+let TargetPrefix = "ppc" in { // All PPC intrinsics start with "llvm.ppc.".
+ // Miscellaneous.
+ def int_ppc_altivec_lvsl :
+ Intrinsic<[llvm_v16i8_ty], [llvm_ptr_ty], [IntrNoMem]>;
+ def int_ppc_altivec_lvsr :
+ Intrinsic<[llvm_v16i8_ty], [llvm_ptr_ty], [IntrNoMem]>;
+
+ def int_ppc_altivec_vperm : GCCBuiltin<"__builtin_altivec_vperm_4si">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty, llvm_v16i8_ty], [IntrNoMem]>;
+ def int_ppc_altivec_vsel : GCCBuiltin<"__builtin_altivec_vsel_4si">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty, llvm_v4i32_ty], [IntrNoMem]>;
+}
+
+def int_ppc_altivec_vexptefp : PowerPC_Vec_FF_Intrinsic<"vexptefp">;
+def int_ppc_altivec_vlogefp : PowerPC_Vec_FF_Intrinsic<"vlogefp">;
+def int_ppc_altivec_vrefp : PowerPC_Vec_FF_Intrinsic<"vrefp">;
+def int_ppc_altivec_vrsqrtefp : PowerPC_Vec_FF_Intrinsic<"vrsqrtefp">;
diff --git a/include/llvm/IntrinsicsX86.td b/include/llvm/IntrinsicsX86.td
new file mode 100644
index 00000000000..5ff085633e5
--- /dev/null
+++ b/include/llvm/IntrinsicsX86.td
@@ -0,0 +1,2561 @@
+//===- IntrinsicsX86.td - Defines X86 intrinsics -----------*- tablegen -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines all of the X86-specific intrinsics.
+//
+//===----------------------------------------------------------------------===//
+
+//===----------------------------------------------------------------------===//
+// Interrupt traps
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_int : Intrinsic<[], [llvm_i8_ty]>;
+}
+
+//===----------------------------------------------------------------------===//
+// 3DNow!
+
+let TargetPrefix = "x86" in {
+ def int_x86_3dnow_pavgusb : GCCBuiltin<"__builtin_ia32_pavgusb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pf2id : GCCBuiltin<"__builtin_ia32_pf2id">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_3dnow_pfacc : GCCBuiltin<"__builtin_ia32_pfacc">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfadd : GCCBuiltin<"__builtin_ia32_pfadd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfcmpeq : GCCBuiltin<"__builtin_ia32_pfcmpeq">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfcmpge : GCCBuiltin<"__builtin_ia32_pfcmpge">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfcmpgt : GCCBuiltin<"__builtin_ia32_pfcmpgt">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfmax : GCCBuiltin<"__builtin_ia32_pfmax">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfmin : GCCBuiltin<"__builtin_ia32_pfmin">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfmul : GCCBuiltin<"__builtin_ia32_pfmul">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfrcp : GCCBuiltin<"__builtin_ia32_pfrcp">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_3dnow_pfrcpit1 : GCCBuiltin<"__builtin_ia32_pfrcpit1">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfrcpit2 : GCCBuiltin<"__builtin_ia32_pfrcpit2">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfrsqrt : GCCBuiltin<"__builtin_ia32_pfrsqrt">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_3dnow_pfrsqit1 : GCCBuiltin<"__builtin_ia32_pfrsqit1">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfsub : GCCBuiltin<"__builtin_ia32_pfsub">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pfsubr : GCCBuiltin<"__builtin_ia32_pfsubr">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnow_pi2fd : GCCBuiltin<"__builtin_ia32_pi2fd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_3dnow_pmulhrw : GCCBuiltin<"__builtin_ia32_pmulhrw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// 3DNow! extensions
+
+let TargetPrefix = "x86" in {
+ def int_x86_3dnowa_pf2iw : GCCBuiltin<"__builtin_ia32_pf2iw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_3dnowa_pfnacc : GCCBuiltin<"__builtin_ia32_pfnacc">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnowa_pfpnacc : GCCBuiltin<"__builtin_ia32_pfpnacc">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_3dnowa_pi2fw : GCCBuiltin<"__builtin_ia32_pi2fw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_3dnowa_pswapd :
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// SSE1
+
+// Arithmetic ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse_add_ss : GCCBuiltin<"__builtin_ia32_addss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_sub_ss : GCCBuiltin<"__builtin_ia32_subss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_mul_ss : GCCBuiltin<"__builtin_ia32_mulss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_div_ss : GCCBuiltin<"__builtin_ia32_divss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_sqrt_ss : GCCBuiltin<"__builtin_ia32_sqrtss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse_sqrt_ps : GCCBuiltin<"__builtin_ia32_sqrtps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse_rcp_ss : GCCBuiltin<"__builtin_ia32_rcpss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse_rcp_ps : GCCBuiltin<"__builtin_ia32_rcpps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse_rsqrt_ss : GCCBuiltin<"__builtin_ia32_rsqrtss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse_rsqrt_ps : GCCBuiltin<"__builtin_ia32_rsqrtps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse_min_ss : GCCBuiltin<"__builtin_ia32_minss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_min_ps : GCCBuiltin<"__builtin_ia32_minps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_max_ss : GCCBuiltin<"__builtin_ia32_maxss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_max_ps : GCCBuiltin<"__builtin_ia32_maxps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+}
+
+// Comparison ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse_cmp_ss : GCCBuiltin<"__builtin_ia32_cmpss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_sse_cmp_ps : GCCBuiltin<"__builtin_ia32_cmpps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_sse_comieq_ss : GCCBuiltin<"__builtin_ia32_comieq">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_comilt_ss : GCCBuiltin<"__builtin_ia32_comilt">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_comile_ss : GCCBuiltin<"__builtin_ia32_comile">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_comigt_ss : GCCBuiltin<"__builtin_ia32_comigt">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_comige_ss : GCCBuiltin<"__builtin_ia32_comige">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_comineq_ss : GCCBuiltin<"__builtin_ia32_comineq">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_ucomieq_ss : GCCBuiltin<"__builtin_ia32_ucomieq">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_ucomilt_ss : GCCBuiltin<"__builtin_ia32_ucomilt">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_ucomile_ss : GCCBuiltin<"__builtin_ia32_ucomile">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_ucomigt_ss : GCCBuiltin<"__builtin_ia32_ucomigt">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_ucomige_ss : GCCBuiltin<"__builtin_ia32_ucomige">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_ucomineq_ss : GCCBuiltin<"__builtin_ia32_ucomineq">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+}
+
+
+// Conversion ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse_cvtss2si : GCCBuiltin<"__builtin_ia32_cvtss2si">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_cvtss2si64 : GCCBuiltin<"__builtin_ia32_cvtss2si64">,
+ Intrinsic<[llvm_i64_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_cvttss2si : GCCBuiltin<"__builtin_ia32_cvttss2si">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_cvttss2si64 : GCCBuiltin<"__builtin_ia32_cvttss2si64">,
+ Intrinsic<[llvm_i64_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_cvtsi2ss : GCCBuiltin<"__builtin_ia32_cvtsi2ss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse_cvtsi642ss : GCCBuiltin<"__builtin_ia32_cvtsi642ss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_i64_ty], [IntrNoMem]>;
+ def int_x86_sse_cvtps2pi : GCCBuiltin<"__builtin_ia32_cvtps2pi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_cvttps2pi: GCCBuiltin<"__builtin_ia32_cvttps2pi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_cvtpi2ps : GCCBuiltin<"__builtin_ia32_cvtpi2ps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+}
+
+// SIMD store ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse_storeu_ps : GCCBuiltin<"__builtin_ia32_storeups">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_v4f32_ty], [IntrReadWriteArgMem]>;
+}
+
+// Cacheability support ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse_sfence : GCCBuiltin<"__builtin_ia32_sfence">,
+ Intrinsic<[], [], []>;
+}
+
+// Control register.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse_stmxcsr :
+ Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_x86_sse_ldmxcsr :
+ Intrinsic<[], [llvm_ptr_ty], []>;
+}
+
+// Misc.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse_movmsk_ps : GCCBuiltin<"__builtin_ia32_movmskps">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// SSE2
+
+// FP arithmetic ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse2_add_sd : GCCBuiltin<"__builtin_ia32_addsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_sub_sd : GCCBuiltin<"__builtin_ia32_subsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_mul_sd : GCCBuiltin<"__builtin_ia32_mulsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_div_sd : GCCBuiltin<"__builtin_ia32_divsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_sqrt_sd : GCCBuiltin<"__builtin_ia32_sqrtsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_sse2_sqrt_pd : GCCBuiltin<"__builtin_ia32_sqrtpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_sse2_min_sd : GCCBuiltin<"__builtin_ia32_minsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_min_pd : GCCBuiltin<"__builtin_ia32_minpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_max_sd : GCCBuiltin<"__builtin_ia32_maxsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_max_pd : GCCBuiltin<"__builtin_ia32_maxpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+}
+
+// FP comparison ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse2_cmp_sd : GCCBuiltin<"__builtin_ia32_cmpsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_sse2_cmp_pd : GCCBuiltin<"__builtin_ia32_cmppd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_sse2_comieq_sd : GCCBuiltin<"__builtin_ia32_comisdeq">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_comilt_sd : GCCBuiltin<"__builtin_ia32_comisdlt">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_comile_sd : GCCBuiltin<"__builtin_ia32_comisdle">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_comigt_sd : GCCBuiltin<"__builtin_ia32_comisdgt">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_comige_sd : GCCBuiltin<"__builtin_ia32_comisdge">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_comineq_sd : GCCBuiltin<"__builtin_ia32_comisdneq">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_ucomieq_sd : GCCBuiltin<"__builtin_ia32_ucomisdeq">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_ucomilt_sd : GCCBuiltin<"__builtin_ia32_ucomisdlt">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_ucomile_sd : GCCBuiltin<"__builtin_ia32_ucomisdle">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_ucomigt_sd : GCCBuiltin<"__builtin_ia32_ucomisdgt">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_ucomige_sd : GCCBuiltin<"__builtin_ia32_ucomisdge">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_ucomineq_sd : GCCBuiltin<"__builtin_ia32_ucomisdneq">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+}
+
+// Integer arithmetic ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse2_padds_b : GCCBuiltin<"__builtin_ia32_paddsb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_padds_w : GCCBuiltin<"__builtin_ia32_paddsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_paddus_b : GCCBuiltin<"__builtin_ia32_paddusb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_paddus_w : GCCBuiltin<"__builtin_ia32_paddusw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_psubs_b : GCCBuiltin<"__builtin_ia32_psubsb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_sse2_psubs_w : GCCBuiltin<"__builtin_ia32_psubsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_sse2_psubus_b : GCCBuiltin<"__builtin_ia32_psubusb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_sse2_psubus_w : GCCBuiltin<"__builtin_ia32_psubusw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_sse2_pmulhu_w : GCCBuiltin<"__builtin_ia32_pmulhuw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pmulh_w : GCCBuiltin<"__builtin_ia32_pmulhw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pmulu_dq : GCCBuiltin<"__builtin_ia32_pmuludq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pmadd_wd : GCCBuiltin<"__builtin_ia32_pmaddwd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pavg_b : GCCBuiltin<"__builtin_ia32_pavgb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pavg_w : GCCBuiltin<"__builtin_ia32_pavgw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pmaxu_b : GCCBuiltin<"__builtin_ia32_pmaxub128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pmaxs_w : GCCBuiltin<"__builtin_ia32_pmaxsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pminu_b : GCCBuiltin<"__builtin_ia32_pminub128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_pmins_w : GCCBuiltin<"__builtin_ia32_pminsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_sse2_psad_bw : GCCBuiltin<"__builtin_ia32_psadbw128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem, Commutative]>;
+}
+
+// Integer shift ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse2_psll_w : GCCBuiltin<"__builtin_ia32_psllw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_sse2_psll_d : GCCBuiltin<"__builtin_ia32_pslld128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psll_q : GCCBuiltin<"__builtin_ia32_psllq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty,
+ llvm_v2i64_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrl_w : GCCBuiltin<"__builtin_ia32_psrlw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrl_d : GCCBuiltin<"__builtin_ia32_psrld128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrl_q : GCCBuiltin<"__builtin_ia32_psrlq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty,
+ llvm_v2i64_ty], [IntrNoMem]>;
+ def int_x86_sse2_psra_w : GCCBuiltin<"__builtin_ia32_psraw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_sse2_psra_d : GCCBuiltin<"__builtin_ia32_psrad128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+
+ def int_x86_sse2_pslli_w : GCCBuiltin<"__builtin_ia32_psllwi128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_pslli_d : GCCBuiltin<"__builtin_ia32_pslldi128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_pslli_q : GCCBuiltin<"__builtin_ia32_psllqi128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrli_w : GCCBuiltin<"__builtin_ia32_psrlwi128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrli_d : GCCBuiltin<"__builtin_ia32_psrldi128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrli_q : GCCBuiltin<"__builtin_ia32_psrlqi128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrai_w : GCCBuiltin<"__builtin_ia32_psrawi128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrai_d : GCCBuiltin<"__builtin_ia32_psradi128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+
+ def int_x86_sse2_psll_dq : GCCBuiltin<"__builtin_ia32_pslldqi128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrl_dq : GCCBuiltin<"__builtin_ia32_psrldqi128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psll_dq_bs : GCCBuiltin<"__builtin_ia32_pslldqi128_byteshift">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_psrl_dq_bs : GCCBuiltin<"__builtin_ia32_psrldqi128_byteshift">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Conversion ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse2_cvtdq2pd : GCCBuiltin<"__builtin_ia32_cvtdq2pd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtdq2ps : GCCBuiltin<"__builtin_ia32_cvtdq2ps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtpd2dq : GCCBuiltin<"__builtin_ia32_cvtpd2dq">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvttpd2dq : GCCBuiltin<"__builtin_ia32_cvttpd2dq">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtpd2ps : GCCBuiltin<"__builtin_ia32_cvtpd2ps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtps2dq : GCCBuiltin<"__builtin_ia32_cvtps2dq">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvttps2dq : GCCBuiltin<"__builtin_ia32_cvttps2dq">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtps2pd : GCCBuiltin<"__builtin_ia32_cvtps2pd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtsd2si : GCCBuiltin<"__builtin_ia32_cvtsd2si">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtsd2si64 : GCCBuiltin<"__builtin_ia32_cvtsd2si64">,
+ Intrinsic<[llvm_i64_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvttsd2si : GCCBuiltin<"__builtin_ia32_cvttsd2si">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvttsd2si64 : GCCBuiltin<"__builtin_ia32_cvttsd2si64">,
+ Intrinsic<[llvm_i64_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtsi2sd : GCCBuiltin<"__builtin_ia32_cvtsi2sd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtsi642sd : GCCBuiltin<"__builtin_ia32_cvtsi642sd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_i64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtsd2ss : GCCBuiltin<"__builtin_ia32_cvtsd2ss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_cvtss2sd : GCCBuiltin<"__builtin_ia32_cvtss2sd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse_cvtpd2pi : GCCBuiltin<"__builtin_ia32_cvtpd2pi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse_cvttpd2pi: GCCBuiltin<"__builtin_ia32_cvttpd2pi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse_cvtpi2pd : GCCBuiltin<"__builtin_ia32_cvtpi2pd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+}
+
+// SIMD store ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse2_storeu_pd : GCCBuiltin<"__builtin_ia32_storeupd">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_v2f64_ty], [IntrReadWriteArgMem]>;
+ def int_x86_sse2_storeu_dq : GCCBuiltin<"__builtin_ia32_storedqu">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_v16i8_ty], [IntrReadWriteArgMem]>;
+ def int_x86_sse2_storel_dq : GCCBuiltin<"__builtin_ia32_storelv4si">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_v4i32_ty], [IntrReadWriteArgMem]>;
+}
+
+// Misc.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse2_packsswb_128 : GCCBuiltin<"__builtin_ia32_packsswb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_sse2_packssdw_128 : GCCBuiltin<"__builtin_ia32_packssdw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_sse2_packuswb_128 : GCCBuiltin<"__builtin_ia32_packuswb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_sse2_movmsk_pd : GCCBuiltin<"__builtin_ia32_movmskpd">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse2_pmovmskb_128 : GCCBuiltin<"__builtin_ia32_pmovmskb128">,
+ Intrinsic<[llvm_i32_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_sse2_maskmov_dqu : GCCBuiltin<"__builtin_ia32_maskmovdqu">,
+ Intrinsic<[], [llvm_v16i8_ty,
+ llvm_v16i8_ty, llvm_ptr_ty], []>;
+ def int_x86_sse2_clflush : GCCBuiltin<"__builtin_ia32_clflush">,
+ Intrinsic<[], [llvm_ptr_ty], []>;
+ def int_x86_sse2_lfence : GCCBuiltin<"__builtin_ia32_lfence">,
+ Intrinsic<[], [], []>;
+ def int_x86_sse2_mfence : GCCBuiltin<"__builtin_ia32_mfence">,
+ Intrinsic<[], [], []>;
+}
+
+//===----------------------------------------------------------------------===//
+// SSE3
+
+// Addition / subtraction ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse3_addsub_ps : GCCBuiltin<"__builtin_ia32_addsubps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse3_addsub_pd : GCCBuiltin<"__builtin_ia32_addsubpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+}
+
+// Horizontal ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse3_hadd_ps : GCCBuiltin<"__builtin_ia32_haddps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse3_hadd_pd : GCCBuiltin<"__builtin_ia32_haddpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_sse3_hsub_ps : GCCBuiltin<"__builtin_ia32_hsubps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_sse3_hsub_pd : GCCBuiltin<"__builtin_ia32_hsubpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+}
+
+// Specialized unaligned load.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse3_ldu_dq : GCCBuiltin<"__builtin_ia32_lddqu">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_ptr_ty], [IntrReadMem]>;
+}
+
+// Thread synchronization ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse3_monitor : GCCBuiltin<"__builtin_ia32_monitor">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_i32_ty, llvm_i32_ty], []>;
+ def int_x86_sse3_mwait : GCCBuiltin<"__builtin_ia32_mwait">,
+ Intrinsic<[], [llvm_i32_ty,
+ llvm_i32_ty], []>;
+}
+
+//===----------------------------------------------------------------------===//
+// SSSE3
+
+// Horizontal arithmetic ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_ssse3_phadd_w : GCCBuiltin<"__builtin_ia32_phaddw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_phadd_w_128 : GCCBuiltin<"__builtin_ia32_phaddw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_phadd_d : GCCBuiltin<"__builtin_ia32_phaddd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_phadd_d_128 : GCCBuiltin<"__builtin_ia32_phaddd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_phadd_sw : GCCBuiltin<"__builtin_ia32_phaddsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_phadd_sw_128 : GCCBuiltin<"__builtin_ia32_phaddsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_phsub_w : GCCBuiltin<"__builtin_ia32_phsubw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_phsub_w_128 : GCCBuiltin<"__builtin_ia32_phsubw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_phsub_d : GCCBuiltin<"__builtin_ia32_phsubd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_phsub_d_128 : GCCBuiltin<"__builtin_ia32_phsubd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_phsub_sw : GCCBuiltin<"__builtin_ia32_phsubsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_phsub_sw_128 : GCCBuiltin<"__builtin_ia32_phsubsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_pmadd_ub_sw : GCCBuiltin<"__builtin_ia32_pmaddubsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_pmadd_ub_sw_128 : GCCBuiltin<"__builtin_ia32_pmaddubsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem]>;
+}
+
+// Packed multiply high with round and scale
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_ssse3_pmul_hr_sw : GCCBuiltin<"__builtin_ia32_pmulhrsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_ssse3_pmul_hr_sw_128 : GCCBuiltin<"__builtin_ia32_pmulhrsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem, Commutative]>;
+}
+
+// Shuffle ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_ssse3_pshuf_b : GCCBuiltin<"__builtin_ia32_pshufb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_pshuf_b_128 : GCCBuiltin<"__builtin_ia32_pshufb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_sse_pshuf_w : GCCBuiltin<"__builtin_ia32_pshufw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+}
+
+// Sign ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_ssse3_psign_b : GCCBuiltin<"__builtin_ia32_psignb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_psign_b_128 : GCCBuiltin<"__builtin_ia32_psignb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
+ llvm_v16i8_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_psign_w : GCCBuiltin<"__builtin_ia32_psignw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_psign_w_128 : GCCBuiltin<"__builtin_ia32_psignw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_psign_d : GCCBuiltin<"__builtin_ia32_psignd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_psign_d_128 : GCCBuiltin<"__builtin_ia32_psignd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+}
+
+// Absolute value ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_ssse3_pabs_b : GCCBuiltin<"__builtin_ia32_pabsb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_pabs_b_128 : GCCBuiltin<"__builtin_ia32_pabsb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_pabs_w : GCCBuiltin<"__builtin_ia32_pabsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_pabs_w_128 : GCCBuiltin<"__builtin_ia32_pabsw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+
+ def int_x86_ssse3_pabs_d : GCCBuiltin<"__builtin_ia32_pabsd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_ssse3_pabs_d_128 : GCCBuiltin<"__builtin_ia32_pabsd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// SSE4.1
+
+// FP rounding ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_round_ss : GCCBuiltin<"__builtin_ia32_roundss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse41_round_ps : GCCBuiltin<"__builtin_ia32_roundps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse41_round_sd : GCCBuiltin<"__builtin_ia32_roundsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty, llvm_v2f64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_sse41_round_pd : GCCBuiltin<"__builtin_ia32_roundpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Vector sign and zero extend
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_pmovsxbd : GCCBuiltin<"__builtin_ia32_pmovsxbd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovsxbq : GCCBuiltin<"__builtin_ia32_pmovsxbq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovsxbw : GCCBuiltin<"__builtin_ia32_pmovsxbw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovsxdq : GCCBuiltin<"__builtin_ia32_pmovsxdq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovsxwd : GCCBuiltin<"__builtin_ia32_pmovsxwd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovsxwq : GCCBuiltin<"__builtin_ia32_pmovsxwq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovzxbd : GCCBuiltin<"__builtin_ia32_pmovzxbd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovzxbq : GCCBuiltin<"__builtin_ia32_pmovzxbq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovzxbw : GCCBuiltin<"__builtin_ia32_pmovzxbw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovzxdq : GCCBuiltin<"__builtin_ia32_pmovzxdq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovzxwd : GCCBuiltin<"__builtin_ia32_pmovzxwd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pmovzxwq : GCCBuiltin<"__builtin_ia32_pmovzxwq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+}
+
+// Vector min element
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_phminposuw : GCCBuiltin<"__builtin_ia32_phminposuw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+}
+
+// Vector compare, min, max
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_pmaxsb : GCCBuiltin<"__builtin_ia32_pmaxsb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem, Commutative]>;
+ def int_x86_sse41_pmaxsd : GCCBuiltin<"__builtin_ia32_pmaxsd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_x86_sse41_pmaxud : GCCBuiltin<"__builtin_ia32_pmaxud128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_x86_sse41_pmaxuw : GCCBuiltin<"__builtin_ia32_pmaxuw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem, Commutative]>;
+ def int_x86_sse41_pminsb : GCCBuiltin<"__builtin_ia32_pminsb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem, Commutative]>;
+ def int_x86_sse41_pminsd : GCCBuiltin<"__builtin_ia32_pminsd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_x86_sse41_pminud : GCCBuiltin<"__builtin_ia32_pminud128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_x86_sse41_pminuw : GCCBuiltin<"__builtin_ia32_pminuw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem, Commutative]>;
+}
+
+// Advanced Encryption Standard (AES) Instructions
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_aesni_aesimc : GCCBuiltin<"__builtin_ia32_aesimc128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_aesni_aesenc : GCCBuiltin<"__builtin_ia32_aesenc128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_aesni_aesenclast : GCCBuiltin<"__builtin_ia32_aesenclast128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_aesni_aesdec : GCCBuiltin<"__builtin_ia32_aesdec128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_aesni_aesdeclast : GCCBuiltin<"__builtin_ia32_aesdeclast128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_aesni_aeskeygenassist :
+ GCCBuiltin<"__builtin_ia32_aeskeygenassist128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+}
+
+// PCLMUL instruction
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_pclmulqdq : GCCBuiltin<"__builtin_ia32_pclmulqdq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+}
+
+// Vector pack
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_packusdw : GCCBuiltin<"__builtin_ia32_packusdw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+}
+
+// Vector multiply
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_pmuldq : GCCBuiltin<"__builtin_ia32_pmuldq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem, Commutative]>;
+}
+
+// Vector extract
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_pextrb :
+ Intrinsic<[llvm_i32_ty], [llvm_v16i8_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pextrd :
+ Intrinsic<[llvm_i32_ty], [llvm_v4i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pextrq :
+ Intrinsic<[llvm_i64_ty], [llvm_v2i64_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_extractps : GCCBuiltin<"__builtin_ia32_extractps128">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+}
+
+// Vector insert
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_insertps : GCCBuiltin<"__builtin_ia32_insertps128">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty,llvm_i32_ty],
+ [IntrNoMem]>;
+}
+
+// Vector blend
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_pblendvb : GCCBuiltin<"__builtin_ia32_pblendvb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty,llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_pblendw : GCCBuiltin<"__builtin_ia32_pblendw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_blendpd : GCCBuiltin<"__builtin_ia32_blendpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty, llvm_v2f64_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_blendps : GCCBuiltin<"__builtin_ia32_blendps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_blendvpd : GCCBuiltin<"__builtin_ia32_blendvpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty, llvm_v2f64_ty,llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_blendvps : GCCBuiltin<"__builtin_ia32_blendvps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty,llvm_v4f32_ty],
+ [IntrNoMem]>;
+}
+
+// Vector dot product
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_dppd : GCCBuiltin<"__builtin_ia32_dppd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty, llvm_v2f64_ty,llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+ def int_x86_sse41_dpps : GCCBuiltin<"__builtin_ia32_dpps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty,llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+}
+
+// Vector sum of absolute differences
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_mpsadbw : GCCBuiltin<"__builtin_ia32_mpsadbw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty, llvm_v16i8_ty,llvm_i32_ty],
+ [IntrNoMem, Commutative]>;
+}
+
+// Cacheability support ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_movntdqa : GCCBuiltin<"__builtin_ia32_movntdqa">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_ptr_ty], [IntrReadMem]>;
+}
+
+// Test instruction with bitwise comparison.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse41_ptestz : GCCBuiltin<"__builtin_ia32_ptestz128">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_ptestc : GCCBuiltin<"__builtin_ia32_ptestc128">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_sse41_ptestnzc : GCCBuiltin<"__builtin_ia32_ptestnzc128">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// SSE4.2
+
+// Miscellaneous
+// CRC Instruction
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse42_crc32_32_8 : GCCBuiltin<"__builtin_ia32_crc32qi">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_crc32_32_16 : GCCBuiltin<"__builtin_ia32_crc32hi">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i16_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_crc32_32_32 : GCCBuiltin<"__builtin_ia32_crc32si">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_crc32_64_8 :
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_crc32_64_64 : GCCBuiltin<"__builtin_ia32_crc32di">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty],
+ [IntrNoMem]>;
+}
+
+// String/text processing ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse42_pcmpistrm128 : GCCBuiltin<"__builtin_ia32_pcmpistrm128">,
+ Intrinsic<[llvm_v16i8_ty],
+ [llvm_v16i8_ty, llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpistri128 : GCCBuiltin<"__builtin_ia32_pcmpistri128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpistria128 : GCCBuiltin<"__builtin_ia32_pcmpistria128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpistric128 : GCCBuiltin<"__builtin_ia32_pcmpistric128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpistrio128 : GCCBuiltin<"__builtin_ia32_pcmpistrio128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpistris128 : GCCBuiltin<"__builtin_ia32_pcmpistris128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpistriz128 : GCCBuiltin<"__builtin_ia32_pcmpistriz128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpestrm128 : GCCBuiltin<"__builtin_ia32_pcmpestrm128">,
+ Intrinsic<[llvm_v16i8_ty],
+ [llvm_v16i8_ty, llvm_i32_ty, llvm_v16i8_ty, llvm_i32_ty,
+ llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpestri128 : GCCBuiltin<"__builtin_ia32_pcmpestri128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_i32_ty, llvm_v16i8_ty, llvm_i32_ty,
+ llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpestria128 : GCCBuiltin<"__builtin_ia32_pcmpestria128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_i32_ty, llvm_v16i8_ty, llvm_i32_ty,
+ llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpestric128 : GCCBuiltin<"__builtin_ia32_pcmpestric128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_i32_ty, llvm_v16i8_ty, llvm_i32_ty,
+ llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpestrio128 : GCCBuiltin<"__builtin_ia32_pcmpestrio128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_i32_ty, llvm_v16i8_ty, llvm_i32_ty,
+ llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpestris128 : GCCBuiltin<"__builtin_ia32_pcmpestris128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_i32_ty, llvm_v16i8_ty, llvm_i32_ty,
+ llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse42_pcmpestriz128 : GCCBuiltin<"__builtin_ia32_pcmpestriz128">,
+ Intrinsic<[llvm_i32_ty],
+ [llvm_v16i8_ty, llvm_i32_ty, llvm_v16i8_ty, llvm_i32_ty,
+ llvm_i8_ty],
+ [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// SSE4A
+
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_sse4a_extrqi : GCCBuiltin<"__builtin_ia32_extrqi">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_sse4a_extrq : GCCBuiltin<"__builtin_ia32_extrq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v16i8_ty], [IntrNoMem]>;
+
+ def int_x86_sse4a_insertqi : GCCBuiltin<"__builtin_ia32_insertqi">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty,
+ llvm_i8_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_sse4a_insertq : GCCBuiltin<"__builtin_ia32_insertq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty], [IntrNoMem]>;
+
+ def int_x86_sse4a_movnt_ss : GCCBuiltin<"__builtin_ia32_movntss">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v4f32_ty], []>;
+ def int_x86_sse4a_movnt_sd : GCCBuiltin<"__builtin_ia32_movntsd">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v2f64_ty], []>;
+}
+
+//===----------------------------------------------------------------------===//
+// AVX
+
+// Arithmetic ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_addsub_pd_256 : GCCBuiltin<"__builtin_ia32_addsubpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_addsub_ps_256 : GCCBuiltin<"__builtin_ia32_addsubps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty], [IntrNoMem]>;
+ def int_x86_avx_max_pd_256 : GCCBuiltin<"__builtin_ia32_maxpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_max_ps_256 : GCCBuiltin<"__builtin_ia32_maxps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty], [IntrNoMem]>;
+ def int_x86_avx_min_pd_256 : GCCBuiltin<"__builtin_ia32_minpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_min_ps_256 : GCCBuiltin<"__builtin_ia32_minps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty], [IntrNoMem]>;
+
+ def int_x86_avx_sqrt_pd_256 : GCCBuiltin<"__builtin_ia32_sqrtpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_sqrt_ps_256 : GCCBuiltin<"__builtin_ia32_sqrtps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty], [IntrNoMem]>;
+
+ def int_x86_avx_rsqrt_ps_256 : GCCBuiltin<"__builtin_ia32_rsqrtps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty], [IntrNoMem]>;
+
+ def int_x86_avx_rcp_ps_256 : GCCBuiltin<"__builtin_ia32_rcpps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty], [IntrNoMem]>;
+
+ def int_x86_avx_round_pd_256 : GCCBuiltin<"__builtin_ia32_roundpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx_round_ps_256 : GCCBuiltin<"__builtin_ia32_roundps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Horizontal ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_hadd_pd_256 : GCCBuiltin<"__builtin_ia32_haddpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_hsub_ps_256 : GCCBuiltin<"__builtin_ia32_hsubps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty], [IntrNoMem]>;
+ def int_x86_avx_hsub_pd_256 : GCCBuiltin<"__builtin_ia32_hsubpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_hadd_ps_256 : GCCBuiltin<"__builtin_ia32_haddps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty], [IntrNoMem]>;
+}
+
+// Vector permutation
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_vpermilvar_pd : GCCBuiltin<"__builtin_ia32_vpermilvarpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
+ llvm_v2i64_ty], [IntrNoMem]>;
+ def int_x86_avx_vpermilvar_ps : GCCBuiltin<"__builtin_ia32_vpermilvarps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+
+ def int_x86_avx_vpermilvar_pd_256 :
+ GCCBuiltin<"__builtin_ia32_vpermilvarpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty, llvm_v4i64_ty], [IntrNoMem]>;
+ def int_x86_avx_vpermilvar_ps_256 :
+ GCCBuiltin<"__builtin_ia32_vpermilvarps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty, llvm_v8i32_ty], [IntrNoMem]>;
+
+ def int_x86_avx_vperm2f128_pd_256 :
+ GCCBuiltin<"__builtin_ia32_vperm2f128_pd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_avx_vperm2f128_ps_256 :
+ GCCBuiltin<"__builtin_ia32_vperm2f128_ps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_avx_vperm2f128_si_256 :
+ GCCBuiltin<"__builtin_ia32_vperm2f128_si256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty, llvm_i8_ty], [IntrNoMem]>;
+}
+
+// Vector blend
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_blend_pd_256 : GCCBuiltin<"__builtin_ia32_blendpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty, llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx_blend_ps_256 : GCCBuiltin<"__builtin_ia32_blendps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty, llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx_blendv_pd_256 : GCCBuiltin<"__builtin_ia32_blendvpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty, llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_blendv_ps_256 : GCCBuiltin<"__builtin_ia32_blendvps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty, llvm_v8f32_ty], [IntrNoMem]>;
+}
+
+// Vector dot product
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_dp_ps_256 : GCCBuiltin<"__builtin_ia32_dpps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty, llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Vector compare
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_cmp_pd_256 : GCCBuiltin<"__builtin_ia32_cmppd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_avx_cmp_ps_256 : GCCBuiltin<"__builtin_ia32_cmpps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty, llvm_i8_ty], [IntrNoMem]>;
+}
+
+// Vector extract and insert
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_vextractf128_pd_256 :
+ GCCBuiltin<"__builtin_ia32_vextractf128_pd256">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v4f64_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_avx_vextractf128_ps_256 :
+ GCCBuiltin<"__builtin_ia32_vextractf128_ps256">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v8f32_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_avx_vextractf128_si_256 :
+ GCCBuiltin<"__builtin_ia32_vextractf128_si256">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i32_ty, llvm_i8_ty], [IntrNoMem]>;
+
+ def int_x86_avx_vinsertf128_pd_256 :
+ GCCBuiltin<"__builtin_ia32_vinsertf128_pd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
+ llvm_v2f64_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_avx_vinsertf128_ps_256 :
+ GCCBuiltin<"__builtin_ia32_vinsertf128_ps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
+ llvm_v4f32_ty, llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_avx_vinsertf128_si_256 :
+ GCCBuiltin<"__builtin_ia32_vinsertf128_si256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v4i32_ty, llvm_i8_ty], [IntrNoMem]>;
+}
+
+// Vector convert
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_cvtdq2_pd_256 : GCCBuiltin<"__builtin_ia32_cvtdq2pd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_avx_cvtdq2_ps_256 : GCCBuiltin<"__builtin_ia32_cvtdq2ps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8i32_ty], [IntrNoMem]>;
+ def int_x86_avx_cvt_pd2_ps_256 : GCCBuiltin<"__builtin_ia32_cvtpd2ps256">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_cvt_ps2dq_256 : GCCBuiltin<"__builtin_ia32_cvtps2dq256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8f32_ty], [IntrNoMem]>;
+ def int_x86_avx_cvt_ps2_pd_256 : GCCBuiltin<"__builtin_ia32_cvtps2pd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_avx_cvtt_pd2dq_256 : GCCBuiltin<"__builtin_ia32_cvttpd2dq256">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_cvt_pd2dq_256 : GCCBuiltin<"__builtin_ia32_cvtpd2dq256">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_cvtt_ps2dq_256 : GCCBuiltin<"__builtin_ia32_cvttps2dq256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8f32_ty], [IntrNoMem]>;
+}
+
+// Vector bit test
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_vtestz_pd : GCCBuiltin<"__builtin_ia32_vtestzpd">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestc_pd : GCCBuiltin<"__builtin_ia32_vtestcpd">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestnzc_pd : GCCBuiltin<"__builtin_ia32_vtestnzcpd">,
+ Intrinsic<[llvm_i32_ty], [llvm_v2f64_ty,
+ llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestz_ps : GCCBuiltin<"__builtin_ia32_vtestzps">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestc_ps : GCCBuiltin<"__builtin_ia32_vtestcps">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestnzc_ps : GCCBuiltin<"__builtin_ia32_vtestnzcps">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty,
+ llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestz_pd_256 : GCCBuiltin<"__builtin_ia32_vtestzpd256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestc_pd_256 : GCCBuiltin<"__builtin_ia32_vtestcpd256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestnzc_pd_256 : GCCBuiltin<"__builtin_ia32_vtestnzcpd256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f64_ty,
+ llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestz_ps_256 : GCCBuiltin<"__builtin_ia32_vtestzps256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestc_ps_256 : GCCBuiltin<"__builtin_ia32_vtestcps256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty], [IntrNoMem]>;
+ def int_x86_avx_vtestnzc_ps_256 : GCCBuiltin<"__builtin_ia32_vtestnzcps256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v8f32_ty,
+ llvm_v8f32_ty], [IntrNoMem]>;
+ def int_x86_avx_ptestz_256 : GCCBuiltin<"__builtin_ia32_ptestz256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i64_ty,
+ llvm_v4i64_ty], [IntrNoMem]>;
+ def int_x86_avx_ptestc_256 : GCCBuiltin<"__builtin_ia32_ptestc256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i64_ty,
+ llvm_v4i64_ty], [IntrNoMem]>;
+ def int_x86_avx_ptestnzc_256 : GCCBuiltin<"__builtin_ia32_ptestnzc256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4i64_ty,
+ llvm_v4i64_ty], [IntrNoMem]>;
+}
+
+// Vector extract sign mask
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_movmsk_pd_256 : GCCBuiltin<"__builtin_ia32_movmskpd256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_avx_movmsk_ps_256 : GCCBuiltin<"__builtin_ia32_movmskps256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v8f32_ty], [IntrNoMem]>;
+}
+
+// Vector zero
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_vzeroall : GCCBuiltin<"__builtin_ia32_vzeroall">,
+ Intrinsic<[], [], []>;
+ def int_x86_avx_vzeroupper : GCCBuiltin<"__builtin_ia32_vzeroupper">,
+ Intrinsic<[], [], []>;
+}
+
+// Vector load with broadcast
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_vbroadcast_ss :
+ GCCBuiltin<"__builtin_ia32_vbroadcastss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_ptr_ty], [IntrReadArgMem]>;
+ def int_x86_avx_vbroadcast_sd_256 :
+ GCCBuiltin<"__builtin_ia32_vbroadcastsd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_ptr_ty], [IntrReadArgMem]>;
+ def int_x86_avx_vbroadcast_ss_256 :
+ GCCBuiltin<"__builtin_ia32_vbroadcastss256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_ptr_ty], [IntrReadArgMem]>;
+ def int_x86_avx_vbroadcastf128_pd_256 :
+ GCCBuiltin<"__builtin_ia32_vbroadcastf128_pd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_ptr_ty], [IntrReadArgMem]>;
+ def int_x86_avx_vbroadcastf128_ps_256 :
+ GCCBuiltin<"__builtin_ia32_vbroadcastf128_ps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_ptr_ty], [IntrReadArgMem]>;
+}
+
+// SIMD load ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_ldu_dq_256 : GCCBuiltin<"__builtin_ia32_lddqu256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_ptr_ty], [IntrReadMem]>;
+}
+
+// SIMD store ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_storeu_pd_256 : GCCBuiltin<"__builtin_ia32_storeupd256">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v4f64_ty], [IntrReadWriteArgMem]>;
+ def int_x86_avx_storeu_ps_256 : GCCBuiltin<"__builtin_ia32_storeups256">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v8f32_ty], [IntrReadWriteArgMem]>;
+ def int_x86_avx_storeu_dq_256 : GCCBuiltin<"__builtin_ia32_storedqu256">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v32i8_ty], [IntrReadWriteArgMem]>;
+}
+
+// Conditional load ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_maskload_pd : GCCBuiltin<"__builtin_ia32_maskloadpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_ptr_ty, llvm_v2f64_ty],
+ [IntrReadArgMem]>;
+ def int_x86_avx_maskload_ps : GCCBuiltin<"__builtin_ia32_maskloadps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_ptr_ty, llvm_v4f32_ty],
+ [IntrReadArgMem]>;
+ def int_x86_avx_maskload_pd_256 : GCCBuiltin<"__builtin_ia32_maskloadpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_ptr_ty, llvm_v4f64_ty],
+ [IntrReadArgMem]>;
+ def int_x86_avx_maskload_ps_256 : GCCBuiltin<"__builtin_ia32_maskloadps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_ptr_ty, llvm_v8f32_ty],
+ [IntrReadArgMem]>;
+}
+
+// Conditional store ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx_maskstore_pd : GCCBuiltin<"__builtin_ia32_maskstorepd">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_v2f64_ty, llvm_v2f64_ty], [IntrReadWriteArgMem]>;
+ def int_x86_avx_maskstore_ps : GCCBuiltin<"__builtin_ia32_maskstoreps">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_v4f32_ty, llvm_v4f32_ty], [IntrReadWriteArgMem]>;
+ def int_x86_avx_maskstore_pd_256 :
+ GCCBuiltin<"__builtin_ia32_maskstorepd256">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_v4f64_ty, llvm_v4f64_ty], [IntrReadWriteArgMem]>;
+ def int_x86_avx_maskstore_ps_256 :
+ GCCBuiltin<"__builtin_ia32_maskstoreps256">,
+ Intrinsic<[], [llvm_ptr_ty,
+ llvm_v8f32_ty, llvm_v8f32_ty], [IntrReadWriteArgMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// AVX2
+
+// Integer arithmetic ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_padds_b : GCCBuiltin<"__builtin_ia32_paddsb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_padds_w : GCCBuiltin<"__builtin_ia32_paddsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_paddus_b : GCCBuiltin<"__builtin_ia32_paddusb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_paddus_w : GCCBuiltin<"__builtin_ia32_paddusw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_psubs_b : GCCBuiltin<"__builtin_ia32_psubsb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_psubs_w : GCCBuiltin<"__builtin_ia32_psubsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_psubus_b : GCCBuiltin<"__builtin_ia32_psubusb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_psubus_w : GCCBuiltin<"__builtin_ia32_psubusw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_pmulhu_w : GCCBuiltin<"__builtin_ia32_pmulhuw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmulh_w : GCCBuiltin<"__builtin_ia32_pmulhw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmulu_dq : GCCBuiltin<"__builtin_ia32_pmuludq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmul_dq : GCCBuiltin<"__builtin_ia32_pmuldq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmadd_wd : GCCBuiltin<"__builtin_ia32_pmaddwd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pavg_b : GCCBuiltin<"__builtin_ia32_pavgb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pavg_w : GCCBuiltin<"__builtin_ia32_pavgw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_psad_bw : GCCBuiltin<"__builtin_ia32_psadbw256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+}
+
+// Vector min, max
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_pmaxu_b : GCCBuiltin<"__builtin_ia32_pmaxub256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmaxu_w : GCCBuiltin<"__builtin_ia32_pmaxuw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmaxu_d : GCCBuiltin<"__builtin_ia32_pmaxud256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmaxs_b : GCCBuiltin<"__builtin_ia32_pmaxsb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmaxs_w : GCCBuiltin<"__builtin_ia32_pmaxsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmaxs_d : GCCBuiltin<"__builtin_ia32_pmaxsd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pminu_b : GCCBuiltin<"__builtin_ia32_pminub256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pminu_w : GCCBuiltin<"__builtin_ia32_pminuw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pminu_d : GCCBuiltin<"__builtin_ia32_pminud256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmins_b : GCCBuiltin<"__builtin_ia32_pminsb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmins_w : GCCBuiltin<"__builtin_ia32_pminsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_pmins_d : GCCBuiltin<"__builtin_ia32_pminsd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+}
+
+// Integer shift ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_psll_w : GCCBuiltin<"__builtin_ia32_psllw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_psll_d : GCCBuiltin<"__builtin_ia32_pslld256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psll_q : GCCBuiltin<"__builtin_ia32_psllq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_v2i64_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrl_w : GCCBuiltin<"__builtin_ia32_psrlw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrl_d : GCCBuiltin<"__builtin_ia32_psrld256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrl_q : GCCBuiltin<"__builtin_ia32_psrlq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_v2i64_ty], [IntrNoMem]>;
+ def int_x86_avx2_psra_w : GCCBuiltin<"__builtin_ia32_psraw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_psra_d : GCCBuiltin<"__builtin_ia32_psrad256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v4i32_ty], [IntrNoMem]>;
+
+ def int_x86_avx2_pslli_w : GCCBuiltin<"__builtin_ia32_psllwi256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_pslli_d : GCCBuiltin<"__builtin_ia32_pslldi256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_pslli_q : GCCBuiltin<"__builtin_ia32_psllqi256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrli_w : GCCBuiltin<"__builtin_ia32_psrlwi256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrli_d : GCCBuiltin<"__builtin_ia32_psrldi256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrli_q : GCCBuiltin<"__builtin_ia32_psrlqi256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrai_w : GCCBuiltin<"__builtin_ia32_psrawi256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrai_d : GCCBuiltin<"__builtin_ia32_psradi256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+
+ def int_x86_avx2_psll_dq : GCCBuiltin<"__builtin_ia32_pslldqi256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrl_dq : GCCBuiltin<"__builtin_ia32_psrldqi256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psll_dq_bs : GCCBuiltin<"__builtin_ia32_pslldqi256_byteshift">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_psrl_dq_bs : GCCBuiltin<"__builtin_ia32_psrldqi256_byteshift">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Pack ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_packsswb : GCCBuiltin<"__builtin_ia32_packsswb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_packssdw : GCCBuiltin<"__builtin_ia32_packssdw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_packuswb : GCCBuiltin<"__builtin_ia32_packuswb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_packusdw : GCCBuiltin<"__builtin_ia32_packusdw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem]>;
+}
+
+// Absolute value ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_pabs_b : GCCBuiltin<"__builtin_ia32_pabsb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_pabs_w : GCCBuiltin<"__builtin_ia32_pabsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_pabs_d : GCCBuiltin<"__builtin_ia32_pabsd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty], [IntrNoMem]>;
+}
+
+// Horizontal arithmetic ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_phadd_w : GCCBuiltin<"__builtin_ia32_phaddw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_phadd_d : GCCBuiltin<"__builtin_ia32_phaddd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_phadd_sw : GCCBuiltin<"__builtin_ia32_phaddsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_phsub_w : GCCBuiltin<"__builtin_ia32_phsubw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_phsub_d : GCCBuiltin<"__builtin_ia32_phsubd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_phsub_sw : GCCBuiltin<"__builtin_ia32_phsubsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_pmadd_ub_sw : GCCBuiltin<"__builtin_ia32_pmaddubsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem]>;
+}
+
+// Sign ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_psign_b : GCCBuiltin<"__builtin_ia32_psignb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_psign_w : GCCBuiltin<"__builtin_ia32_psignw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_psign_d : GCCBuiltin<"__builtin_ia32_psignd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+ llvm_v8i32_ty], [IntrNoMem]>;
+}
+
+// Packed multiply high with round and scale
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_pmul_hr_sw : GCCBuiltin<"__builtin_ia32_pmulhrsw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+ llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+}
+
+// Vector sign and zero extend
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_pmovsxbd : GCCBuiltin<"__builtin_ia32_pmovsxbd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovsxbq : GCCBuiltin<"__builtin_ia32_pmovsxbq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovsxbw : GCCBuiltin<"__builtin_ia32_pmovsxbw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovsxdq : GCCBuiltin<"__builtin_ia32_pmovsxdq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovsxwd : GCCBuiltin<"__builtin_ia32_pmovsxwd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovsxwq : GCCBuiltin<"__builtin_ia32_pmovsxwq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovzxbd : GCCBuiltin<"__builtin_ia32_pmovzxbd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovzxbq : GCCBuiltin<"__builtin_ia32_pmovzxbq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovzxbw : GCCBuiltin<"__builtin_ia32_pmovzxbw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovzxdq : GCCBuiltin<"__builtin_ia32_pmovzxdq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovzxwd : GCCBuiltin<"__builtin_ia32_pmovzxwd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_pmovzxwq : GCCBuiltin<"__builtin_ia32_pmovzxwq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v8i16_ty],
+ [IntrNoMem]>;
+}
+
+// Vector blend
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_pblendvb : GCCBuiltin<"__builtin_ia32_pblendvb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty, llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_pblendw : GCCBuiltin<"__builtin_ia32_pblendw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty, llvm_v16i16_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_pblendd_128 : GCCBuiltin<"__builtin_ia32_pblendd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_pblendd_256 : GCCBuiltin<"__builtin_ia32_pblendd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Vector load with broadcast
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_vbroadcast_ss_ps :
+ GCCBuiltin<"__builtin_ia32_vbroadcastss_ps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_avx2_vbroadcast_sd_pd_256 :
+ GCCBuiltin<"__builtin_ia32_vbroadcastsd_pd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_avx2_vbroadcast_ss_ps_256 :
+ GCCBuiltin<"__builtin_ia32_vbroadcastss_ps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_avx2_vbroadcasti128 :
+ GCCBuiltin<"__builtin_ia32_vbroadcastsi256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_ptr_ty], [IntrReadArgMem]>;
+ def int_x86_avx2_pbroadcastb_128 :
+ GCCBuiltin<"__builtin_ia32_pbroadcastb128">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_pbroadcastb_256 :
+ GCCBuiltin<"__builtin_ia32_pbroadcastb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_pbroadcastw_128 :
+ GCCBuiltin<"__builtin_ia32_pbroadcastw128">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_pbroadcastw_256 :
+ GCCBuiltin<"__builtin_ia32_pbroadcastw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_avx2_pbroadcastd_128 :
+ GCCBuiltin<"__builtin_ia32_pbroadcastd128">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_pbroadcastd_256 :
+ GCCBuiltin<"__builtin_ia32_pbroadcastd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_avx2_pbroadcastq_128 :
+ GCCBuiltin<"__builtin_ia32_pbroadcastq128">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty], [IntrNoMem]>;
+ def int_x86_avx2_pbroadcastq_256 :
+ GCCBuiltin<"__builtin_ia32_pbroadcastq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v2i64_ty], [IntrNoMem]>;
+}
+
+// Vector permutation
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_permd : GCCBuiltin<"__builtin_ia32_permvarsi256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_permps : GCCBuiltin<"__builtin_ia32_permvarsf256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty, llvm_v8f32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_vperm2i128 : GCCBuiltin<"__builtin_ia32_permti256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_v4i64_ty, llvm_i8_ty], [IntrNoMem]>;
+}
+
+// Vector extract and insert
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_vextracti128 : GCCBuiltin<"__builtin_ia32_extract128i256">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v4i64_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_vinserti128 : GCCBuiltin<"__builtin_ia32_insert128i256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+ llvm_v2i64_ty, llvm_i8_ty], [IntrNoMem]>;
+}
+
+// Conditional load ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_maskload_d : GCCBuiltin<"__builtin_ia32_maskloadd">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_ptr_ty, llvm_v4i32_ty],
+ [IntrReadArgMem]>;
+ def int_x86_avx2_maskload_q : GCCBuiltin<"__builtin_ia32_maskloadq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_ptr_ty, llvm_v2i64_ty],
+ [IntrReadArgMem]>;
+ def int_x86_avx2_maskload_d_256 : GCCBuiltin<"__builtin_ia32_maskloadd256">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_ptr_ty, llvm_v8i32_ty],
+ [IntrReadArgMem]>;
+ def int_x86_avx2_maskload_q_256 : GCCBuiltin<"__builtin_ia32_maskloadq256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_ptr_ty, llvm_v4i64_ty],
+ [IntrReadArgMem]>;
+}
+
+// Conditional store ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_maskstore_d : GCCBuiltin<"__builtin_ia32_maskstored">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrReadWriteArgMem]>;
+ def int_x86_avx2_maskstore_q : GCCBuiltin<"__builtin_ia32_maskstoreq">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrReadWriteArgMem]>;
+ def int_x86_avx2_maskstore_d_256 :
+ GCCBuiltin<"__builtin_ia32_maskstored256">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v8i32_ty, llvm_v8i32_ty],
+ [IntrReadWriteArgMem]>;
+ def int_x86_avx2_maskstore_q_256 :
+ GCCBuiltin<"__builtin_ia32_maskstoreq256">,
+ Intrinsic<[], [llvm_ptr_ty, llvm_v4i64_ty, llvm_v4i64_ty],
+ [IntrReadWriteArgMem]>;
+}
+
+// Variable bit shift ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_psllv_d : GCCBuiltin<"__builtin_ia32_psllv4si">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_psllv_d_256 : GCCBuiltin<"__builtin_ia32_psllv8si">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_psllv_q : GCCBuiltin<"__builtin_ia32_psllv2di">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_psllv_q_256 : GCCBuiltin<"__builtin_ia32_psllv4di">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty, llvm_v4i64_ty],
+ [IntrNoMem]>;
+
+ def int_x86_avx2_psrlv_d : GCCBuiltin<"__builtin_ia32_psrlv4si">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_psrlv_d_256 : GCCBuiltin<"__builtin_ia32_psrlv8si">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_psrlv_q : GCCBuiltin<"__builtin_ia32_psrlv2di">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_psrlv_q_256 : GCCBuiltin<"__builtin_ia32_psrlv4di">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty, llvm_v4i64_ty],
+ [IntrNoMem]>;
+
+ def int_x86_avx2_psrav_d : GCCBuiltin<"__builtin_ia32_psrav4si">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_avx2_psrav_d_256 : GCCBuiltin<"__builtin_ia32_psrav8si">,
+ Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty],
+ [IntrNoMem]>;
+}
+
+// Gather ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_gather_d_pd : GCCBuiltin<"__builtin_ia32_gatherd_pd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_ptr_ty, llvm_v4i32_ty, llvm_v2f64_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_d_pd_256 : GCCBuiltin<"__builtin_ia32_gatherd_pd256">,
+ Intrinsic<[llvm_v4f64_ty],
+ [llvm_v4f64_ty, llvm_ptr_ty, llvm_v4i32_ty, llvm_v4f64_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_q_pd : GCCBuiltin<"__builtin_ia32_gatherq_pd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_ptr_ty, llvm_v2i64_ty, llvm_v2f64_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_q_pd_256 : GCCBuiltin<"__builtin_ia32_gatherq_pd256">,
+ Intrinsic<[llvm_v4f64_ty],
+ [llvm_v4f64_ty, llvm_ptr_ty, llvm_v4i64_ty, llvm_v4f64_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_d_ps : GCCBuiltin<"__builtin_ia32_gatherd_ps">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_ptr_ty, llvm_v4i32_ty, llvm_v4f32_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_d_ps_256 : GCCBuiltin<"__builtin_ia32_gatherd_ps256">,
+ Intrinsic<[llvm_v8f32_ty],
+ [llvm_v8f32_ty, llvm_ptr_ty, llvm_v8i32_ty, llvm_v8f32_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_q_ps : GCCBuiltin<"__builtin_ia32_gatherq_ps">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_ptr_ty, llvm_v2i64_ty, llvm_v4f32_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_q_ps_256 : GCCBuiltin<"__builtin_ia32_gatherq_ps256">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_ptr_ty, llvm_v4i64_ty, llvm_v4f32_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+
+ def int_x86_avx2_gather_d_q : GCCBuiltin<"__builtin_ia32_gatherd_q">,
+ Intrinsic<[llvm_v2i64_ty],
+ [llvm_v2i64_ty, llvm_ptr_ty, llvm_v4i32_ty, llvm_v2i64_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_d_q_256 : GCCBuiltin<"__builtin_ia32_gatherd_q256">,
+ Intrinsic<[llvm_v4i64_ty],
+ [llvm_v4i64_ty, llvm_ptr_ty, llvm_v4i32_ty, llvm_v4i64_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_q_q : GCCBuiltin<"__builtin_ia32_gatherq_q">,
+ Intrinsic<[llvm_v2i64_ty],
+ [llvm_v2i64_ty, llvm_ptr_ty, llvm_v2i64_ty, llvm_v2i64_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_q_q_256 : GCCBuiltin<"__builtin_ia32_gatherq_q256">,
+ Intrinsic<[llvm_v4i64_ty],
+ [llvm_v4i64_ty, llvm_ptr_ty, llvm_v4i64_ty, llvm_v4i64_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_d_d : GCCBuiltin<"__builtin_ia32_gatherd_d">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v4i32_ty, llvm_ptr_ty, llvm_v4i32_ty, llvm_v4i32_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_d_d_256 : GCCBuiltin<"__builtin_ia32_gatherd_d256">,
+ Intrinsic<[llvm_v8i32_ty],
+ [llvm_v8i32_ty, llvm_ptr_ty, llvm_v8i32_ty, llvm_v8i32_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_q_d : GCCBuiltin<"__builtin_ia32_gatherq_d">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v4i32_ty, llvm_ptr_ty, llvm_v2i64_ty, llvm_v4i32_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+ def int_x86_avx2_gather_q_d_256 : GCCBuiltin<"__builtin_ia32_gatherq_d256">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v4i32_ty, llvm_ptr_ty, llvm_v4i64_ty, llvm_v4i32_ty, llvm_i8_ty],
+ [IntrReadMem]>;
+}
+
+// Misc.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_avx2_pmovmskb : GCCBuiltin<"__builtin_ia32_pmovmskb256">,
+ Intrinsic<[llvm_i32_ty], [llvm_v32i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_pshuf_b : GCCBuiltin<"__builtin_ia32_pshufb256">,
+ Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+ llvm_v32i8_ty], [IntrNoMem]>;
+ def int_x86_avx2_mpsadbw : GCCBuiltin<"__builtin_ia32_mpsadbw256">,
+ Intrinsic<[llvm_v16i16_ty], [llvm_v32i8_ty, llvm_v32i8_ty,
+ llvm_i32_ty], [IntrNoMem, Commutative]>;
+ def int_x86_avx2_movntdqa : GCCBuiltin<"__builtin_ia32_movntdqa256">,
+ Intrinsic<[llvm_v4i64_ty], [llvm_ptr_ty], [IntrReadMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// FMA3 and FMA4
+
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_fma_vfmadd_ss : GCCBuiltin<"__builtin_ia32_vfmaddss">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmadd_sd : GCCBuiltin<"__builtin_ia32_vfmaddsd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmadd_ps : GCCBuiltin<"__builtin_ia32_vfmaddps">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmadd_pd : GCCBuiltin<"__builtin_ia32_vfmaddpd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmadd_ps_256 : GCCBuiltin<"__builtin_ia32_vfmaddps256">,
+ Intrinsic<[llvm_v8f32_ty],
+ [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmadd_pd_256 : GCCBuiltin<"__builtin_ia32_vfmaddpd256">,
+ Intrinsic<[llvm_v4f64_ty],
+ [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsub_ss : GCCBuiltin<"__builtin_ia32_vfmsubss">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsub_sd : GCCBuiltin<"__builtin_ia32_vfmsubsd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsub_ps : GCCBuiltin<"__builtin_ia32_vfmsubps">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsub_pd : GCCBuiltin<"__builtin_ia32_vfmsubpd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsub_ps_256 : GCCBuiltin<"__builtin_ia32_vfmsubps256">,
+ Intrinsic<[llvm_v8f32_ty],
+ [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsub_pd_256 : GCCBuiltin<"__builtin_ia32_vfmsubpd256">,
+ Intrinsic<[llvm_v4f64_ty],
+ [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmadd_ss : GCCBuiltin<"__builtin_ia32_vfnmaddss">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmadd_sd : GCCBuiltin<"__builtin_ia32_vfnmaddsd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmadd_ps : GCCBuiltin<"__builtin_ia32_vfnmaddps">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmadd_pd : GCCBuiltin<"__builtin_ia32_vfnmaddpd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmadd_ps_256 : GCCBuiltin<"__builtin_ia32_vfnmaddps256">,
+ Intrinsic<[llvm_v8f32_ty],
+ [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmadd_pd_256 : GCCBuiltin<"__builtin_ia32_vfnmaddpd256">,
+ Intrinsic<[llvm_v4f64_ty],
+ [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmsub_ss : GCCBuiltin<"__builtin_ia32_vfnmsubss">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmsub_sd : GCCBuiltin<"__builtin_ia32_vfnmsubsd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmsub_ps : GCCBuiltin<"__builtin_ia32_vfnmsubps">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmsub_pd : GCCBuiltin<"__builtin_ia32_vfnmsubpd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmsub_ps_256 : GCCBuiltin<"__builtin_ia32_vfnmsubps256">,
+ Intrinsic<[llvm_v8f32_ty],
+ [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfnmsub_pd_256 : GCCBuiltin<"__builtin_ia32_vfnmsubpd256">,
+ Intrinsic<[llvm_v4f64_ty],
+ [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmaddsub_ps : GCCBuiltin<"__builtin_ia32_vfmaddsubps">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmaddsub_pd : GCCBuiltin<"__builtin_ia32_vfmaddsubpd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmaddsub_ps_256 :
+ GCCBuiltin<"__builtin_ia32_vfmaddsubps256">,
+ Intrinsic<[llvm_v8f32_ty],
+ [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmaddsub_pd_256 :
+ GCCBuiltin<"__builtin_ia32_vfmaddsubpd256">,
+ Intrinsic<[llvm_v4f64_ty],
+ [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsubadd_ps : GCCBuiltin<"__builtin_ia32_vfmsubaddps">,
+ Intrinsic<[llvm_v4f32_ty],
+ [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsubadd_pd : GCCBuiltin<"__builtin_ia32_vfmsubaddpd">,
+ Intrinsic<[llvm_v2f64_ty],
+ [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsubadd_ps_256 :
+ GCCBuiltin<"__builtin_ia32_vfmsubaddps256">,
+ Intrinsic<[llvm_v8f32_ty],
+ [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+ [IntrNoMem]>;
+ def int_x86_fma_vfmsubadd_pd_256 :
+ GCCBuiltin<"__builtin_ia32_vfmsubaddpd256">,
+ Intrinsic<[llvm_v4f64_ty],
+ [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+ [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// XOP
+
+ def int_x86_xop_vpermil2pd : GCCBuiltin<"__builtin_ia32_vpermil2pd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty, llvm_v2f64_ty,
+ llvm_v2f64_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+
+ def int_x86_xop_vpermil2pd_256 :
+ GCCBuiltin<"__builtin_ia32_vpermil2pd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty, llvm_v4f64_ty,
+ llvm_v4f64_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+
+ def int_x86_xop_vpermil2ps : GCCBuiltin<"__builtin_ia32_vpermil2ps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty,
+ llvm_v4f32_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpermil2ps_256 :
+ GCCBuiltin<"__builtin_ia32_vpermil2ps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty, llvm_v8f32_ty,
+ llvm_v8f32_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+
+ def int_x86_xop_vfrcz_pd : GCCBuiltin<"__builtin_ia32_vfrczpd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_xop_vfrcz_ps : GCCBuiltin<"__builtin_ia32_vfrczps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_xop_vfrcz_sd : GCCBuiltin<"__builtin_ia32_vfrczsd">,
+ Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+ def int_x86_xop_vfrcz_ss : GCCBuiltin<"__builtin_ia32_vfrczss">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+ def int_x86_xop_vfrcz_pd_256 : GCCBuiltin<"__builtin_ia32_vfrczpd256">,
+ Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty], [IntrNoMem]>;
+ def int_x86_xop_vfrcz_ps_256 : GCCBuiltin<"__builtin_ia32_vfrczps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty], [IntrNoMem]>;
+
+ def int_x86_xop_vpcmov :
+ GCCBuiltin<"__builtin_ia32_vpcmov">,
+ Intrinsic<[llvm_v2i64_ty],
+ [llvm_v2i64_ty, llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpcmov_256 :
+ GCCBuiltin<"__builtin_ia32_vpcmov_256">,
+ Intrinsic<[llvm_v4i64_ty],
+ [llvm_v4i64_ty, llvm_v4i64_ty, llvm_v4i64_ty],
+ [IntrNoMem]>;
+
+ def int_x86_xop_vpcomb : GCCBuiltin<"__builtin_ia32_vpcomb">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vpcomw : GCCBuiltin<"__builtin_ia32_vpcomw">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vpcomd : GCCBuiltin<"__builtin_ia32_vpcomd">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vpcomq : GCCBuiltin<"__builtin_ia32_vpcomq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vpcomub : GCCBuiltin<"__builtin_ia32_vpcomub">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vpcomuw : GCCBuiltin<"__builtin_ia32_vpcomuw">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vpcomud : GCCBuiltin<"__builtin_ia32_vpcomud">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vpcomuq : GCCBuiltin<"__builtin_ia32_vpcomuq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty,
+ llvm_i8_ty], [IntrNoMem]>;
+
+ def int_x86_xop_vphaddbd :
+ GCCBuiltin<"__builtin_ia32_vphaddbd">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vphaddbq :
+ GCCBuiltin<"__builtin_ia32_vphaddbq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vphaddbw :
+ GCCBuiltin<"__builtin_ia32_vphaddbw">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vphadddq :
+ GCCBuiltin<"__builtin_ia32_vphadddq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_xop_vphaddubd :
+ GCCBuiltin<"__builtin_ia32_vphaddubd">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vphaddubq :
+ GCCBuiltin<"__builtin_ia32_vphaddubq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vphaddubw :
+ GCCBuiltin<"__builtin_ia32_vphaddubw">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vphaddudq :
+ GCCBuiltin<"__builtin_ia32_vphaddudq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_xop_vphadduwd :
+ GCCBuiltin<"__builtin_ia32_vphadduwd">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_xop_vphadduwq :
+ GCCBuiltin<"__builtin_ia32_vphadduwq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_xop_vphaddwd :
+ GCCBuiltin<"__builtin_ia32_vphaddwd">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_xop_vphaddwq :
+ GCCBuiltin<"__builtin_ia32_vphaddwq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_xop_vphsubbw :
+ GCCBuiltin<"__builtin_ia32_vphsubbw">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+ def int_x86_xop_vphsubdq :
+ GCCBuiltin<"__builtin_ia32_vphsubdq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+ def int_x86_xop_vphsubwd :
+ GCCBuiltin<"__builtin_ia32_vphsubwd">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_xop_vpmacsdd :
+ GCCBuiltin<"__builtin_ia32_vpmacsdd">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacsdqh :
+ GCCBuiltin<"__builtin_ia32_vpmacsdqh">,
+ Intrinsic<[llvm_v2i64_ty],
+ [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacsdql :
+ GCCBuiltin<"__builtin_ia32_vpmacsdql">,
+ Intrinsic<[llvm_v2i64_ty],
+ [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacssdd :
+ GCCBuiltin<"__builtin_ia32_vpmacssdd">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacssdqh :
+ GCCBuiltin<"__builtin_ia32_vpmacssdqh">,
+ Intrinsic<[llvm_v2i64_ty],
+ [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacssdql :
+ GCCBuiltin<"__builtin_ia32_vpmacssdql">,
+ Intrinsic<[llvm_v2i64_ty],
+ [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacsswd :
+ GCCBuiltin<"__builtin_ia32_vpmacsswd">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacssww :
+ GCCBuiltin<"__builtin_ia32_vpmacssww">,
+ Intrinsic<[llvm_v8i16_ty],
+ [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacswd :
+ GCCBuiltin<"__builtin_ia32_vpmacswd">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmacsww :
+ GCCBuiltin<"__builtin_ia32_vpmacsww">,
+ Intrinsic<[llvm_v8i16_ty],
+ [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmadcsswd :
+ GCCBuiltin<"__builtin_ia32_vpmadcsswd">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpmadcswd :
+ GCCBuiltin<"__builtin_ia32_vpmadcswd">,
+ Intrinsic<[llvm_v4i32_ty],
+ [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpperm :
+ GCCBuiltin<"__builtin_ia32_vpperm">,
+ Intrinsic<[llvm_v16i8_ty],
+ [llvm_v16i8_ty, llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+
+ def int_x86_xop_vprotb : GCCBuiltin<"__builtin_ia32_vprotb">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vprotd : GCCBuiltin<"__builtin_ia32_vprotd">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vprotq : GCCBuiltin<"__builtin_ia32_vprotq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vprotw : GCCBuiltin<"__builtin_ia32_vprotw">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vprotbi : GCCBuiltin<"__builtin_ia32_vprotbi">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vprotdi : GCCBuiltin<"__builtin_ia32_vprotdi">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vprotqi : GCCBuiltin<"__builtin_ia32_vprotqi">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vprotwi : GCCBuiltin<"__builtin_ia32_vprotwi">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_i8_ty],
+ [IntrNoMem]>;
+
+ def int_x86_xop_vpshab :
+ GCCBuiltin<"__builtin_ia32_vpshab">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpshad :
+ GCCBuiltin<"__builtin_ia32_vpshad">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpshaq :
+ GCCBuiltin<"__builtin_ia32_vpshaq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpshaw :
+ GCCBuiltin<"__builtin_ia32_vpshaw">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpshlb :
+ GCCBuiltin<"__builtin_ia32_vpshlb">,
+ Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpshld :
+ GCCBuiltin<"__builtin_ia32_vpshld">,
+ Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpshlq :
+ GCCBuiltin<"__builtin_ia32_vpshlq">,
+ Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+ [IntrNoMem]>;
+ def int_x86_xop_vpshlw :
+ GCCBuiltin<"__builtin_ia32_vpshlw">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+ [IntrNoMem]>;
+
+//===----------------------------------------------------------------------===//
+// MMX
+
+// Empty MMX state op.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_mmx_emms : GCCBuiltin<"__builtin_ia32_emms">,
+ Intrinsic<[], [], []>;
+ def int_x86_mmx_femms : GCCBuiltin<"__builtin_ia32_femms">,
+ Intrinsic<[], [], []>;
+}
+
+// Integer arithmetic ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ // Addition
+ def int_x86_mmx_padd_b : GCCBuiltin<"__builtin_ia32_paddb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_padd_w : GCCBuiltin<"__builtin_ia32_paddw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_padd_d : GCCBuiltin<"__builtin_ia32_paddd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_padd_q : GCCBuiltin<"__builtin_ia32_paddq">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+
+ def int_x86_mmx_padds_b : GCCBuiltin<"__builtin_ia32_paddsb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_padds_w : GCCBuiltin<"__builtin_ia32_paddsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+
+ def int_x86_mmx_paddus_b : GCCBuiltin<"__builtin_ia32_paddusb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_paddus_w : GCCBuiltin<"__builtin_ia32_paddusw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+
+ // Subtraction
+ def int_x86_mmx_psub_b : GCCBuiltin<"__builtin_ia32_psubb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_psub_w : GCCBuiltin<"__builtin_ia32_psubw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_psub_d : GCCBuiltin<"__builtin_ia32_psubd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_psub_q : GCCBuiltin<"__builtin_ia32_psubq">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+
+ def int_x86_mmx_psubs_b : GCCBuiltin<"__builtin_ia32_psubsb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_psubs_w : GCCBuiltin<"__builtin_ia32_psubsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+
+ def int_x86_mmx_psubus_b : GCCBuiltin<"__builtin_ia32_psubusb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_psubus_w : GCCBuiltin<"__builtin_ia32_psubusw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+
+ // Multiplication
+ def int_x86_mmx_pmulh_w : GCCBuiltin<"__builtin_ia32_pmulhw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pmull_w : GCCBuiltin<"__builtin_ia32_pmullw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pmulhu_w : GCCBuiltin<"__builtin_ia32_pmulhuw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pmulu_dq : GCCBuiltin<"__builtin_ia32_pmuludq">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pmadd_wd : GCCBuiltin<"__builtin_ia32_pmaddwd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+
+ // Bitwise operations
+ def int_x86_mmx_pand : GCCBuiltin<"__builtin_ia32_pand">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_pandn : GCCBuiltin<"__builtin_ia32_pandn">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_por : GCCBuiltin<"__builtin_ia32_por">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_pxor : GCCBuiltin<"__builtin_ia32_pxor">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+
+ // Averages
+ def int_x86_mmx_pavg_b : GCCBuiltin<"__builtin_ia32_pavgb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pavg_w : GCCBuiltin<"__builtin_ia32_pavgw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+
+ // Maximum
+ def int_x86_mmx_pmaxu_b : GCCBuiltin<"__builtin_ia32_pmaxub">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pmaxs_w : GCCBuiltin<"__builtin_ia32_pmaxsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+
+ // Minimum
+ def int_x86_mmx_pminu_b : GCCBuiltin<"__builtin_ia32_pminub">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pmins_w : GCCBuiltin<"__builtin_ia32_pminsw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+
+ // Packed sum of absolute differences
+ def int_x86_mmx_psad_bw : GCCBuiltin<"__builtin_ia32_psadbw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+}
+
+// Integer shift ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ // Shift left logical
+ def int_x86_mmx_psll_w : GCCBuiltin<"__builtin_ia32_psllw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_psll_d : GCCBuiltin<"__builtin_ia32_pslld">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_psll_q : GCCBuiltin<"__builtin_ia32_psllq">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+
+ def int_x86_mmx_psrl_w : GCCBuiltin<"__builtin_ia32_psrlw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_psrl_d : GCCBuiltin<"__builtin_ia32_psrld">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_psrl_q : GCCBuiltin<"__builtin_ia32_psrlq">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+
+ def int_x86_mmx_psra_w : GCCBuiltin<"__builtin_ia32_psraw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_psra_d : GCCBuiltin<"__builtin_ia32_psrad">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+
+ def int_x86_mmx_pslli_w : GCCBuiltin<"__builtin_ia32_psllwi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_mmx_pslli_d : GCCBuiltin<"__builtin_ia32_pslldi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_mmx_pslli_q : GCCBuiltin<"__builtin_ia32_psllqi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+
+ def int_x86_mmx_psrli_w : GCCBuiltin<"__builtin_ia32_psrlwi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_mmx_psrli_d : GCCBuiltin<"__builtin_ia32_psrldi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_mmx_psrli_q : GCCBuiltin<"__builtin_ia32_psrlqi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+
+ def int_x86_mmx_psrai_w : GCCBuiltin<"__builtin_ia32_psrawi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_mmx_psrai_d : GCCBuiltin<"__builtin_ia32_psradi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Pack ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_mmx_packsswb : GCCBuiltin<"__builtin_ia32_packsswb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_packssdw : GCCBuiltin<"__builtin_ia32_packssdw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_packuswb : GCCBuiltin<"__builtin_ia32_packuswb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+}
+
+// Unpacking ops.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_mmx_punpckhbw : GCCBuiltin<"__builtin_ia32_punpckhbw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_punpckhwd : GCCBuiltin<"__builtin_ia32_punpckhwd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_punpckhdq : GCCBuiltin<"__builtin_ia32_punpckhdq">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_punpcklbw : GCCBuiltin<"__builtin_ia32_punpcklbw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_punpcklwd : GCCBuiltin<"__builtin_ia32_punpcklwd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+ def int_x86_mmx_punpckldq : GCCBuiltin<"__builtin_ia32_punpckldq">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty, llvm_x86mmx_ty],
+ [IntrNoMem]>;
+}
+
+// Integer comparison ops
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_mmx_pcmpeq_b : GCCBuiltin<"__builtin_ia32_pcmpeqb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pcmpeq_w : GCCBuiltin<"__builtin_ia32_pcmpeqw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+ def int_x86_mmx_pcmpeq_d : GCCBuiltin<"__builtin_ia32_pcmpeqd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
+
+ def int_x86_mmx_pcmpgt_b : GCCBuiltin<"__builtin_ia32_pcmpgtb">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_pcmpgt_w : GCCBuiltin<"__builtin_ia32_pcmpgtw">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+ def int_x86_mmx_pcmpgt_d : GCCBuiltin<"__builtin_ia32_pcmpgtd">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty], [IntrNoMem]>;
+}
+
+// Misc.
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_mmx_maskmovq : GCCBuiltin<"__builtin_ia32_maskmovq">,
+ Intrinsic<[], [llvm_x86mmx_ty, llvm_x86mmx_ty, llvm_ptr_ty], []>;
+
+ def int_x86_mmx_pmovmskb : GCCBuiltin<"__builtin_ia32_pmovmskb">,
+ Intrinsic<[llvm_i32_ty], [llvm_x86mmx_ty], [IntrNoMem]>;
+
+ def int_x86_mmx_movnt_dq : GCCBuiltin<"__builtin_ia32_movntq">,
+ Intrinsic<[], [llvm_ptrx86mmx_ty, llvm_x86mmx_ty], []>;
+
+ def int_x86_mmx_palignr_b : GCCBuiltin<"__builtin_ia32_palignr">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_x86mmx_ty, llvm_i8_ty], [IntrNoMem]>;
+
+ def int_x86_mmx_pextr_w : GCCBuiltin<"__builtin_ia32_vec_ext_v4hi">,
+ Intrinsic<[llvm_i32_ty], [llvm_x86mmx_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+
+ def int_x86_mmx_pinsr_w : GCCBuiltin<"__builtin_ia32_vec_set_v4hi">,
+ Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
+ llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// BMI
+
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_bmi_bextr_32 : GCCBuiltin<"__builtin_ia32_bextr_u32">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_bmi_bextr_64 : GCCBuiltin<"__builtin_ia32_bextr_u64">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNoMem]>;
+ def int_x86_bmi_bzhi_32 : GCCBuiltin<"__builtin_ia32_bzhi_si">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_bmi_bzhi_64 : GCCBuiltin<"__builtin_ia32_bzhi_di">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNoMem]>;
+ def int_x86_bmi_pdep_32 : GCCBuiltin<"__builtin_ia32_pdep_si">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_bmi_pdep_64 : GCCBuiltin<"__builtin_ia32_pdep_di">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNoMem]>;
+ def int_x86_bmi_pext_32 : GCCBuiltin<"__builtin_ia32_pext_si">,
+ Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
+ def int_x86_bmi_pext_64 : GCCBuiltin<"__builtin_ia32_pext_di">,
+ Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// FS/GS Base
+
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_rdfsbase_32 : GCCBuiltin<"__builtin_ia32_rdfsbase32">,
+ Intrinsic<[llvm_i32_ty], []>;
+ def int_x86_rdgsbase_32 : GCCBuiltin<"__builtin_ia32_rdgsbase32">,
+ Intrinsic<[llvm_i32_ty], []>;
+ def int_x86_rdfsbase_64 : GCCBuiltin<"__builtin_ia32_rdfsbase64">,
+ Intrinsic<[llvm_i64_ty], []>;
+ def int_x86_rdgsbase_64 : GCCBuiltin<"__builtin_ia32_rdgsbase64">,
+ Intrinsic<[llvm_i64_ty], []>;
+ def int_x86_wrfsbase_32 : GCCBuiltin<"__builtin_ia32_wrfsbase32">,
+ Intrinsic<[], [llvm_i32_ty]>;
+ def int_x86_wrgsbase_32 : GCCBuiltin<"__builtin_ia32_wrgsbase32">,
+ Intrinsic<[], [llvm_i32_ty]>;
+ def int_x86_wrfsbase_64 : GCCBuiltin<"__builtin_ia32_wrfsbase64">,
+ Intrinsic<[], [llvm_i64_ty]>;
+ def int_x86_wrgsbase_64 : GCCBuiltin<"__builtin_ia32_wrgsbase64">,
+ Intrinsic<[], [llvm_i64_ty]>;
+}
+
+//===----------------------------------------------------------------------===//
+// Half float conversion
+
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ def int_x86_vcvtph2ps_128 : GCCBuiltin<"__builtin_ia32_vcvtph2ps">,
+ Intrinsic<[llvm_v4f32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_vcvtph2ps_256 : GCCBuiltin<"__builtin_ia32_vcvtph2ps256">,
+ Intrinsic<[llvm_v8f32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+ def int_x86_vcvtps2ph_128 : GCCBuiltin<"__builtin_ia32_vcvtps2ph">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v4f32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_x86_vcvtps2ph_256 : GCCBuiltin<"__builtin_ia32_vcvtps2ph256">,
+ Intrinsic<[llvm_v8i16_ty], [llvm_v8f32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+}
+
+//===----------------------------------------------------------------------===//
+// RDRAND intrinsics. Return a random value and whether it is valid.
+
+let TargetPrefix = "x86" in { // All intrinsics start with "llvm.x86.".
+ // These are declared side-effecting so they don't get eliminated by CSE or
+ // LICM.
+ def int_x86_rdrand_16 : Intrinsic<[llvm_i16_ty, llvm_i32_ty], [], []>;
+ def int_x86_rdrand_32 : Intrinsic<[llvm_i32_ty, llvm_i32_ty], [], []>;
+ def int_x86_rdrand_64 : Intrinsic<[llvm_i64_ty, llvm_i32_ty], [], []>;
+}
diff --git a/include/llvm/IntrinsicsXCore.td b/include/llvm/IntrinsicsXCore.td
new file mode 100644
index 00000000000..a4813135da8
--- /dev/null
+++ b/include/llvm/IntrinsicsXCore.td
@@ -0,0 +1,114 @@
+//==- IntrinsicsXCore.td - XCore intrinsics -*- tablegen -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines all of the XCore-specific intrinsics.
+//
+//===----------------------------------------------------------------------===//
+
+let TargetPrefix = "xcore" in { // All intrinsics start with "llvm.xcore.".
+ // Miscellaneous instructions.
+ def int_xcore_bitrev : Intrinsic<[llvm_i32_ty],[llvm_i32_ty],[IntrNoMem]>;
+ def int_xcore_crc8 : Intrinsic<[llvm_i32_ty, llvm_i32_ty],
+ [llvm_i32_ty,llvm_i32_ty,llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_xcore_crc32 : Intrinsic<[llvm_i32_ty],
+ [llvm_i32_ty,llvm_i32_ty,llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_xcore_sext : Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_xcore_zext : Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty],
+ [IntrNoMem]>;
+ def int_xcore_getid : Intrinsic<[llvm_i32_ty],[],[IntrNoMem]>;
+ def int_xcore_getps : Intrinsic<[llvm_i32_ty],[llvm_i32_ty]>;
+ def int_xcore_setps : Intrinsic<[],[llvm_i32_ty, llvm_i32_ty]>;
+ def int_xcore_geted : Intrinsic<[llvm_i32_ty],[]>;
+ def int_xcore_getet : Intrinsic<[llvm_i32_ty],[]>;
+ def int_xcore_setsr : Intrinsic<[],[llvm_i32_ty]>;
+ def int_xcore_clrsr : Intrinsic<[],[llvm_i32_ty]>;
+
+ // Resource instructions.
+ def int_xcore_getr : Intrinsic<[llvm_anyptr_ty],[llvm_i32_ty]>;
+ def int_xcore_freer : Intrinsic<[],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_in : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty],[NoCapture<0>]>;
+ def int_xcore_int : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_inct : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_out : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_outt : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_outct : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_chkct : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_testct : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_testwct : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_setd : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_setc : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_inshr : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_outshr : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_setpt : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_getts : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_syncr : Intrinsic<[],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_settw : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_setv : Intrinsic<[],[llvm_anyptr_ty, llvm_ptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_setev : Intrinsic<[],[llvm_anyptr_ty, llvm_ptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_eeu : Intrinsic<[],[llvm_anyptr_ty], [NoCapture<0>]>;
+ def int_xcore_setclk : Intrinsic<[],[llvm_anyptr_ty, llvm_anyptr_ty],
+ [NoCapture<0>, NoCapture<1>]>;
+ def int_xcore_setrdy : Intrinsic<[],[llvm_anyptr_ty, llvm_anyptr_ty],
+ [NoCapture<0>, NoCapture<1>]>;
+ def int_xcore_setpsc : Intrinsic<[],[llvm_anyptr_ty, llvm_i32_ty],
+ [NoCapture<0>]>;
+ def int_xcore_peek : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_endin : Intrinsic<[llvm_i32_ty],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+
+ // Intrinsics for events.
+ def int_xcore_waitevent : Intrinsic<[llvm_ptr_ty],[], [IntrReadMem]>;
+
+ // If any of the resources owned by the thread are ready this returns the
+ // vector of one of the ready resources. If no resources owned by the thread
+ // are ready then the operand passed to the intrinsic is returned.
+ def int_xcore_checkevent : Intrinsic<[llvm_ptr_ty],[llvm_ptr_ty]>;
+
+ def int_xcore_clre : Intrinsic<[],[],[]>;
+
+ // Intrinsics for threads.
+ def int_xcore_getst : Intrinsic <[llvm_anyptr_ty],[llvm_anyptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_msync : Intrinsic <[],[llvm_anyptr_ty], [NoCapture<0>]>;
+ def int_xcore_ssync : Intrinsic <[],[]>;
+ def int_xcore_mjoin : Intrinsic <[],[llvm_anyptr_ty], [NoCapture<0>]>;
+ def int_xcore_initsp : Intrinsic <[],[llvm_anyptr_ty, llvm_ptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_initpc : Intrinsic <[],[llvm_anyptr_ty, llvm_ptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_initlr : Intrinsic <[],[llvm_anyptr_ty, llvm_ptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_initcp : Intrinsic <[],[llvm_anyptr_ty, llvm_ptr_ty],
+ [NoCapture<0>]>;
+ def int_xcore_initdp : Intrinsic <[],[llvm_anyptr_ty, llvm_ptr_ty],
+ [NoCapture<0>]>;
+}
diff --git a/include/llvm/LLVMContext.h b/include/llvm/LLVMContext.h
new file mode 100644
index 00000000000..5903e2e55e1
--- /dev/null
+++ b/include/llvm/LLVMContext.h
@@ -0,0 +1,113 @@
+//===-- llvm/LLVMContext.h - Class for managing "global" state --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares LLVMContext, a container of "global" state in LLVM, such
+// as the global type and constant uniquing tables.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LLVMCONTEXT_H
+#define LLVM_LLVMCONTEXT_H
+
+#include "llvm/Support/Compiler.h"
+
+namespace llvm {
+
+class LLVMContextImpl;
+class StringRef;
+class Twine;
+class Instruction;
+class Module;
+class SMDiagnostic;
+template <typename T> class SmallVectorImpl;
+
+/// This is an important class for using LLVM in a threaded context. It
+/// (opaquely) owns and manages the core "global" data of LLVM's core
+/// infrastructure, including the type and constant uniquing tables.
+/// LLVMContext itself provides no locking guarantees, so you should be careful
+/// to have one context per thread.
+class LLVMContext {
+public:
+ LLVMContextImpl *const pImpl;
+ LLVMContext();
+ ~LLVMContext();
+
+ // Pinned metadata names, which always have the same value. This is a
+ // compile-time performance optimization, not a correctness optimization.
+ enum {
+ MD_dbg = 0, // "dbg"
+ MD_tbaa = 1, // "tbaa"
+ MD_prof = 2, // "prof"
+ MD_fpmath = 3, // "fpmath"
+ MD_range = 4, // "range"
+ MD_tbaa_struct = 5 // "tbaa.struct"
+ };
+
+ /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
+ /// This ID is uniqued across modules in the current LLVMContext.
+ unsigned getMDKindID(StringRef Name) const;
+
+ /// getMDKindNames - Populate client supplied SmallVector with the name for
+ /// custom metadata IDs registered in this LLVMContext.
+ void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
+
+
+ typedef void (*InlineAsmDiagHandlerTy)(const SMDiagnostic&, void *Context,
+ unsigned LocCookie);
+
+ /// setInlineAsmDiagnosticHandler - This method sets a handler that is invoked
+ /// when problems with inline asm are detected by the backend. The first
+ /// argument is a function pointer and the second is a context pointer that
+ /// gets passed into the DiagHandler.
+ ///
+ /// LLVMContext doesn't take ownership or interpret either of these
+ /// pointers.
+ void setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
+ void *DiagContext = 0);
+
+ /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
+ /// setInlineAsmDiagnosticHandler.
+ InlineAsmDiagHandlerTy getInlineAsmDiagnosticHandler() const;
+
+ /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
+ /// setInlineAsmDiagnosticHandler.
+ void *getInlineAsmDiagnosticContext() const;
+
+
+ /// emitError - Emit an error message to the currently installed error handler
+ /// with optional location information. This function returns, so code should
+ /// be prepared to drop the erroneous construct on the floor and "not crash".
+ /// The generated code need not be correct. The error message will be
+ /// implicitly prefixed with "error: " and should not end with a ".".
+ void emitError(unsigned LocCookie, const Twine &ErrorStr);
+ void emitError(const Instruction *I, const Twine &ErrorStr);
+ void emitError(const Twine &ErrorStr);
+
+private:
+ LLVMContext(LLVMContext&) LLVM_DELETED_FUNCTION;
+ void operator=(LLVMContext&) LLVM_DELETED_FUNCTION;
+
+ /// addModule - Register a module as being instantiated in this context. If
+ /// the context is deleted, the module will be deleted as well.
+ void addModule(Module*);
+
+ /// removeModule - Unregister a module from this context.
+ void removeModule(Module*);
+
+ // Module needs access to the add/removeModule methods.
+ friend class Module;
+};
+
+/// getGlobalContext - Returns a global context. This is for LLVM clients that
+/// only care about operating on a single thread.
+extern LLVMContext &getGlobalContext();
+
+}
+
+#endif
diff --git a/include/llvm/LinkAllPasses.h b/include/llvm/LinkAllPasses.h
new file mode 100644
index 00000000000..c01e4710248
--- /dev/null
+++ b/include/llvm/LinkAllPasses.h
@@ -0,0 +1,172 @@
+//===- llvm/LinkAllPasses.h ------------ Reference All Passes ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header file pulls in all transformation and analysis passes for tools
+// like opt and bugpoint that need this functionality.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LINKALLPASSES_H
+#define LLVM_LINKALLPASSES_H
+
+#include "llvm/Analysis/AliasSetTracker.h"
+#include "llvm/Analysis/DomPrinter.h"
+#include "llvm/Analysis/FindUsedTypes.h"
+#include "llvm/Analysis/IntervalPartition.h"
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Analysis/PostDominators.h"
+#include "llvm/Analysis/RegionPass.h"
+#include "llvm/Analysis/RegionPrinter.h"
+#include "llvm/Analysis/ScalarEvolution.h"
+#include "llvm/Analysis/Lint.h"
+#include "llvm/Assembly/PrintModulePass.h"
+#include "llvm/CodeGen/Passes.h"
+#include "llvm/Function.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/Transforms/Vectorize.h"
+#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
+#include <cstdlib>
+
+namespace {
+ struct ForcePassLinking {
+ ForcePassLinking() {
+ // We must reference the passes in such a way that compilers will not
+ // delete it all as dead code, even with whole program optimization,
+ // yet is effectively a NO-OP. As the compiler isn't smart enough
+ // to know that getenv() never returns -1, this will do the job.
+ if (std::getenv("bar") != (char*) -1)
+ return;
+
+ (void) llvm::createAAEvalPass();
+ (void) llvm::createAggressiveDCEPass();
+ (void) llvm::createAliasAnalysisCounterPass();
+ (void) llvm::createAliasDebugger();
+ (void) llvm::createArgumentPromotionPass();
+ (void) llvm::createBasicAliasAnalysisPass();
+ (void) llvm::createLibCallAliasAnalysisPass(0);
+ (void) llvm::createScalarEvolutionAliasAnalysisPass();
+ (void) llvm::createTypeBasedAliasAnalysisPass();
+ (void) llvm::createBlockPlacementPass();
+ (void) llvm::createBoundsCheckingPass();
+ (void) llvm::createBreakCriticalEdgesPass();
+ (void) llvm::createCFGSimplificationPass();
+ (void) llvm::createConstantMergePass();
+ (void) llvm::createConstantPropagationPass();
+ (void) llvm::createDeadArgEliminationPass();
+ (void) llvm::createDeadCodeEliminationPass();
+ (void) llvm::createDeadInstEliminationPass();
+ (void) llvm::createDeadStoreEliminationPass();
+ (void) llvm::createDomOnlyPrinterPass();
+ (void) llvm::createDomPrinterPass();
+ (void) llvm::createDomOnlyViewerPass();
+ (void) llvm::createDomViewerPass();
+ (void) llvm::createEdgeProfilerPass();
+ (void) llvm::createOptimalEdgeProfilerPass();
+ (void) llvm::createPathProfilerPass();
+ (void) llvm::createGCOVProfilerPass();
+ (void) llvm::createFunctionInliningPass();
+ (void) llvm::createAlwaysInlinerPass();
+ (void) llvm::createGlobalDCEPass();
+ (void) llvm::createGlobalOptimizerPass();
+ (void) llvm::createGlobalsModRefPass();
+ (void) llvm::createIPConstantPropagationPass();
+ (void) llvm::createIPSCCPPass();
+ (void) llvm::createIndVarSimplifyPass();
+ (void) llvm::createInstructionCombiningPass();
+ (void) llvm::createInternalizePass(false);
+ (void) llvm::createLCSSAPass();
+ (void) llvm::createLICMPass();
+ (void) llvm::createLazyValueInfoPass();
+ (void) llvm::createLoopDependenceAnalysisPass();
+ (void) llvm::createLoopExtractorPass();
+ (void) llvm::createLoopSimplifyPass();
+ (void) llvm::createLoopStrengthReducePass();
+ (void) llvm::createLoopUnrollPass();
+ (void) llvm::createLoopUnswitchPass();
+ (void) llvm::createLoopIdiomPass();
+ (void) llvm::createLoopRotatePass();
+ (void) llvm::createLowerExpectIntrinsicPass();
+ (void) llvm::createLowerInvokePass();
+ (void) llvm::createLowerSwitchPass();
+ (void) llvm::createNoAAPass();
+ (void) llvm::createNoProfileInfoPass();
+ (void) llvm::createObjCARCAliasAnalysisPass();
+ (void) llvm::createObjCARCAPElimPass();
+ (void) llvm::createObjCARCExpandPass();
+ (void) llvm::createObjCARCContractPass();
+ (void) llvm::createObjCARCOptPass();
+ (void) llvm::createProfileEstimatorPass();
+ (void) llvm::createProfileVerifierPass();
+ (void) llvm::createPathProfileVerifierPass();
+ (void) llvm::createProfileLoaderPass();
+ (void) llvm::createProfileMetadataLoaderPass();
+ (void) llvm::createPathProfileLoaderPass();
+ (void) llvm::createPromoteMemoryToRegisterPass();
+ (void) llvm::createDemoteRegisterToMemoryPass();
+ (void) llvm::createPruneEHPass();
+ (void) llvm::createPostDomOnlyPrinterPass();
+ (void) llvm::createPostDomPrinterPass();
+ (void) llvm::createPostDomOnlyViewerPass();
+ (void) llvm::createPostDomViewerPass();
+ (void) llvm::createReassociatePass();
+ (void) llvm::createRegionInfoPass();
+ (void) llvm::createRegionOnlyPrinterPass();
+ (void) llvm::createRegionOnlyViewerPass();
+ (void) llvm::createRegionPrinterPass();
+ (void) llvm::createRegionViewerPass();
+ (void) llvm::createSCCPPass();
+ (void) llvm::createScalarReplAggregatesPass();
+ (void) llvm::createSimplifyLibCallsPass();
+ (void) llvm::createSingleLoopExtractorPass();
+ (void) llvm::createStripSymbolsPass();
+ (void) llvm::createStripNonDebugSymbolsPass();
+ (void) llvm::createStripDeadDebugInfoPass();
+ (void) llvm::createStripDeadPrototypesPass();
+ (void) llvm::createTailCallEliminationPass();
+ (void) llvm::createJumpThreadingPass();
+ (void) llvm::createUnifyFunctionExitNodesPass();
+ (void) llvm::createInstCountPass();
+ (void) llvm::createCodeGenPreparePass();
+ (void) llvm::createEarlyCSEPass();
+ (void) llvm::createGVNPass();
+ (void) llvm::createMemCpyOptPass();
+ (void) llvm::createLoopDeletionPass();
+ (void) llvm::createPostDomTree();
+ (void) llvm::createInstructionNamerPass();
+ (void) llvm::createMetaRenamerPass();
+ (void) llvm::createFunctionAttrsPass();
+ (void) llvm::createMergeFunctionsPass();
+ (void) llvm::createPrintModulePass(0);
+ (void) llvm::createPrintFunctionPass("", 0);
+ (void) llvm::createDbgInfoPrinterPass();
+ (void) llvm::createModuleDebugInfoPrinterPass();
+ (void) llvm::createPartialInliningPass();
+ (void) llvm::createLintPass();
+ (void) llvm::createSinkingPass();
+ (void) llvm::createLowerAtomicPass();
+ (void) llvm::createCorrelatedValuePropagationPass();
+ (void) llvm::createMemDepPrinter();
+ (void) llvm::createInstructionSimplifierPass();
+ (void) llvm::createBBVectorizePass();
+
+ (void)new llvm::IntervalPartition();
+ (void)new llvm::FindUsedTypes();
+ (void)new llvm::ScalarEvolution();
+ ((llvm::Function*)0)->viewCFGOnly();
+ llvm::RGPassManager RGM;
+ ((llvm::RegionPass*)0)->runOnRegion((llvm::Region*)0, RGM);
+ llvm::AliasSetTracker X(*(llvm::AliasAnalysis*)0);
+ X.add((llvm::Value*)0, 0, 0); // for -print-alias-sets
+ }
+ } ForcePassLinking; // Force link by creating a global definition.
+}
+
+#endif
diff --git a/include/llvm/LinkAllVMCore.h b/include/llvm/LinkAllVMCore.h
new file mode 100644
index 00000000000..83684c0fb65
--- /dev/null
+++ b/include/llvm/LinkAllVMCore.h
@@ -0,0 +1,53 @@
+//===- LinkAllVMCore.h - Reference All VMCore Code --------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This header file pulls in all the object modules of the VMCore library so
+// that tools like llc, opt, and lli can ensure they are linked with all symbols
+// from libVMCore.a It should only be used from a tool's main program.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LINKALLVMCORE_H
+#define LLVM_LINKALLVMCORE_H
+
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/Instructions.h"
+#include "llvm/IntrinsicInst.h"
+#include "llvm/InlineAsm.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Support/DynamicLibrary.h"
+#include "llvm/Support/Memory.h"
+#include "llvm/Support/Mutex.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/TimeValue.h"
+#include "llvm/Support/Dwarf.h"
+#include "llvm/Support/MathExtras.h"
+#include <cstdlib>
+
+namespace {
+ struct ForceVMCoreLinking {
+ ForceVMCoreLinking() {
+ // We must reference VMCore in such a way that compilers will not
+ // delete it all as dead code, even with whole program optimization,
+ // yet is effectively a NO-OP. As the compiler isn't smart enough
+ // to know that getenv() never returns -1, this will do the job.
+ if (std::getenv("bar") != (char*) -1)
+ return;
+ (void)new llvm::Module("", llvm::getGlobalContext());
+ (void)new llvm::UnreachableInst(llvm::getGlobalContext());
+ (void) llvm::createVerifierPass();
+ }
+ } ForceVMCoreLinking;
+}
+
+#endif
diff --git a/include/llvm/Linker.h b/include/llvm/Linker.h
new file mode 100644
index 00000000000..1ebcd6b5386
--- /dev/null
+++ b/include/llvm/Linker.h
@@ -0,0 +1,306 @@
+//===- llvm/Linker.h - Module Linker Interface ------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the interface to the module/file/archive linker.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LINKER_H
+#define LLVM_LINKER_H
+
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace llvm {
+ namespace sys { class Path; }
+
+class Module;
+class LLVMContext;
+class StringRef;
+
+/// This class provides the core functionality of linking in LLVM. It retains a
+/// Module object which is the composite of the modules and libraries linked
+/// into it. The composite Module can be retrieved via the getModule() method.
+/// In this case the Linker still retains ownership of the Module. If the
+/// releaseModule() method is used, the ownership of the Module is transferred
+/// to the caller and the Linker object is only suitable for destruction.
+/// The Linker can link Modules from memory, bitcode files, or bitcode
+/// archives. It retains a set of search paths in which to find any libraries
+/// presented to it. By default, the linker will generate error and warning
+/// messages to stderr but this capability can be turned off with the
+/// QuietWarnings and QuietErrors flags. It can also be instructed to verbosely
+/// print out the linking actions it is taking with the Verbose flag.
+/// @brief The LLVM Linker.
+class Linker {
+
+ /// @name Types
+ /// @{
+ public:
+ /// This type is used to pass the linkage items (libraries and files) to
+ /// the LinkItems function. It is composed of string/bool pairs. The string
+ /// provides the name of the file or library (as with the -l option). The
+ /// bool should be true for libraries and false for files, signifying
+ /// "isLibrary".
+ /// @brief A list of linkage items
+ typedef std::vector<std::pair<std::string,bool> > ItemList;
+
+ /// This enumeration is used to control various optional features of the
+ /// linker.
+ enum ControlFlags {
+ Verbose = 1, ///< Print to stderr what steps the linker is taking
+ QuietWarnings = 2, ///< Don't print warnings to stderr.
+ QuietErrors = 4 ///< Don't print errors to stderr.
+ };
+
+ enum LinkerMode {
+ DestroySource = 0, // Allow source module to be destroyed.
+ PreserveSource = 1 // Preserve the source module.
+ };
+
+ /// @}
+ /// @name Constructors
+ /// @{
+ public:
+ /// Construct the Linker with an empty module which will be given the
+ /// name \p progname. \p progname will also be used for error messages.
+ /// @brief Construct with empty module
+ Linker(StringRef progname, ///< name of tool running linker
+ StringRef modulename, ///< name of linker's end-result module
+ LLVMContext &C, ///< Context for global info
+ unsigned Flags = 0 ///< ControlFlags (one or more |'d together)
+ );
+
+ /// Construct the Linker with a previously defined module, \p aModule. Use
+ /// \p progname for the name of the program in error messages.
+ /// @brief Construct with existing module
+ Linker(StringRef progname, Module* aModule, unsigned Flags = 0);
+
+ /// Destruct the Linker.
+ /// @brief Destructor
+ ~Linker();
+
+ /// @}
+ /// @name Accessors
+ /// @{
+ public:
+ /// This method gets the composite module into which linking is being
+ /// done. The Composite module starts out empty and accumulates modules
+ /// linked into it via the various LinkIn* methods. This method does not
+ /// release the Module to the caller. The Linker retains ownership and will
+ /// destruct the Module when the Linker is destructed.
+ /// @see releaseModule
+ /// @brief Get the linked/composite module.
+ Module* getModule() const { return Composite; }
+
+ /// This method releases the composite Module into which linking is being
+ /// done. Ownership of the composite Module is transferred to the caller who
+ /// must arrange for its destruct. After this method is called, the Linker
+ /// terminates the linking session for the returned Module. It will no
+ /// longer utilize the returned Module but instead resets itself for
+ /// subsequent linking as if the constructor had been called. The Linker's
+ /// LibPaths and flags to be reset, and memory will be released.
+ /// @brief Release the linked/composite module.
+ Module* releaseModule();
+
+ /// This method gets the list of libraries that form the path that the
+ /// Linker will search when it is presented with a library name.
+ /// @brief Get the Linkers library path
+ const std::vector<sys::Path>& getLibPaths() const { return LibPaths; }
+
+ /// This method returns an error string suitable for printing to the user.
+ /// The return value will be empty unless an error occurred in one of the
+ /// LinkIn* methods. In those cases, the LinkIn* methods will have returned
+ /// true, indicating an error occurred. At most one error is retained so
+ /// this function always returns the last error that occurred. Note that if
+ /// the Quiet control flag is not set, the error string will have already
+ /// been printed to stderr.
+ /// @brief Get the text of the last error that occurred.
+ const std::string &getLastError() const { return Error; }
+
+ /// @}
+ /// @name Mutators
+ /// @{
+ public:
+ /// Add a path to the list of paths that the Linker will search. The Linker
+ /// accumulates the set of libraries added
+ /// library paths for the target platform. The standard libraries will
+ /// always be searched last. The added libraries will be searched in the
+ /// order added.
+ /// @brief Add a path.
+ void addPath(const sys::Path& path);
+
+ /// Add a set of paths to the list of paths that the linker will search. The
+ /// Linker accumulates the set of libraries added. The \p paths will be
+ /// added to the end of the Linker's list. Order will be retained.
+ /// @brief Add a set of paths.
+ void addPaths(const std::vector<std::string>& paths);
+
+ /// This method augments the Linker's list of library paths with the system
+ /// paths of the host operating system, include LLVM_LIB_SEARCH_PATH.
+ /// @brief Add the system paths.
+ void addSystemPaths();
+
+ /// Control optional linker behavior by setting a group of flags. The flags
+ /// are defined in the ControlFlags enumeration.
+ /// @see ControlFlags
+ /// @brief Set control flags.
+ void setFlags(unsigned flags) { Flags = flags; }
+
+ /// This method is the main interface to the linker. It can be used to
+ /// link a set of linkage items into a module. A linkage item is either a
+ /// file name with fully qualified path, or a library for which the Linker's
+ /// LibraryPath will be utilized to locate the library. The bool value in
+ /// the LinkItemKind should be set to true for libraries. This function
+ /// allows linking to preserve the order of specification associated with
+ /// the command line, or for other purposes. Each item will be linked in
+ /// turn as it occurs in \p Items.
+ /// @returns true if an error occurred, false otherwise
+ /// @see LinkItemKind
+ /// @see getLastError
+ bool LinkInItems (
+ const ItemList& Items, ///< Set of libraries/files to link in
+ ItemList& NativeItems ///< Output list of native files/libs
+ );
+
+ /// This function links the bitcode \p Files into the composite module.
+ /// Note that this does not do any linking of unresolved symbols. The \p
+ /// Files are all completely linked into \p HeadModule regardless of
+ /// unresolved symbols. This function just loads each bitcode file and
+ /// calls LinkInModule on them.
+ /// @returns true if an error occurs, false otherwise
+ /// @see getLastError
+ /// @brief Link in multiple files.
+ bool LinkInFiles (
+ const std::vector<sys::Path> & Files ///< Files to link in
+ );
+
+ /// This function links a single bitcode file, \p File, into the composite
+ /// module. Note that this does not attempt to resolve symbols. This method
+ /// just loads the bitcode file and calls LinkInModule on it. If an error
+ /// occurs, the Linker's error string is set.
+ /// @returns true if an error occurs, false otherwise
+ /// @see getLastError
+ /// @brief Link in a single file.
+ bool LinkInFile(
+ const sys::Path& File, ///< File to link in.
+ bool &is_native ///< Indicates if the file is native object file
+ );
+
+ /// This function provides a way to selectively link in a set of modules,
+ /// found in libraries, based on the unresolved symbols in the composite
+ /// module. Each item in \p Libraries should be the base name of a library,
+ /// as if given with the -l option of a linker tool. The Linker's LibPaths
+ /// are searched for the \p Libraries and any found will be linked in with
+ /// LinkInArchive. If an error occurs, the Linker's error string is set.
+ /// @see LinkInArchive
+ /// @see getLastError
+ /// @returns true if an error occurs, false otherwise
+ /// @brief Link libraries into the module
+ bool LinkInLibraries (
+ const std::vector<std::string> & Libraries ///< Libraries to link in
+ );
+
+ /// This function provides a way to selectively link in a set of modules,
+ /// found in one library, based on the unresolved symbols in the composite
+ /// module.The \p Library should be the base name of a library, as if given
+ /// with the -l option of a linker tool. The Linker's LibPaths are searched
+ /// for the \p Library and if found, it will be linked in with via the
+ /// LinkInArchive method. If an error occurs, the Linker's error string is
+ /// set.
+ /// @see LinkInArchive
+ /// @see getLastError
+ /// @returns true if an error occurs, false otherwise
+ /// @brief Link one library into the module
+ bool LinkInLibrary (
+ StringRef Library, ///< The library to link in
+ bool& is_native ///< Indicates if lib a native library
+ );
+
+ /// This function links one bitcode archive, \p Filename, into the module.
+ /// The archive is searched to resolve outstanding symbols. Any modules in
+ /// the archive that resolve outstanding symbols will be linked in. The
+ /// library is searched repeatedly until no more modules that resolve
+ /// symbols can be found. If an error occurs, the error string is set.
+ /// To speed up this function, ensure the archive has been processed
+ /// llvm-ranlib or the S option was given to llvm-ar when the archive was
+ /// created. These tools add a symbol table to the archive which makes the
+ /// search for undefined symbols much faster.
+ /// @see getLastError
+ /// @returns true if an error occurs, otherwise false.
+ /// @brief Link in one archive.
+ bool LinkInArchive(
+ const sys::Path& Filename, ///< Filename of the archive to link
+ bool& is_native ///< Indicates if archive is a native archive
+ );
+
+ /// This method links the \p Src module into the Linker's Composite module
+ /// by calling LinkModules. All the other LinkIn* methods eventually
+ /// result in calling this method to link a Module into the Linker's
+ /// composite.
+ /// @see LinkModules
+ /// @returns True if an error occurs, false otherwise.
+ /// @brief Link in a module.
+ bool LinkInModule(
+ Module* Src, ///< Module linked into \p Dest
+ std::string* ErrorMsg = 0 /// Error/diagnostic string
+ ) {
+ return LinkModules(Composite, Src, Linker::DestroySource, ErrorMsg );
+ }
+
+ /// This is the heart of the linker. This method will take unconditional
+ /// control of the \p Src module and link it into the \p Dest module. The
+ /// \p Src module will be destructed or subsumed by this method. In either
+ /// case it is not usable by the caller after this method is invoked. Only
+ /// the \p Dest module will remain. The \p Src module is linked into the
+ /// Linker's composite module such that types, global variables, functions,
+ /// and etc. are matched and resolved. If an error occurs, this function
+ /// returns true and ErrorMsg is set to a descriptive message about the
+ /// error.
+ /// @returns True if an error occurs, false otherwise.
+ /// @brief Generically link two modules together.
+ static bool LinkModules(Module* Dest, Module* Src, unsigned Mode,
+ std::string* ErrorMsg);
+
+ /// This function looks through the Linker's LibPaths to find a library with
+ /// the name \p Filename. If the library cannot be found, the returned path
+ /// will be empty (i.e. sys::Path::isEmpty() will return true).
+ /// @returns A sys::Path to the found library
+ /// @brief Find a library from its short name.
+ sys::Path FindLib(StringRef Filename);
+
+ /// @}
+ /// @name Implementation
+ /// @{
+ private:
+ /// Read in and parse the bitcode file named by FN and return the
+ /// Module it contains (wrapped in an auto_ptr), or 0 if an error occurs.
+ std::auto_ptr<Module> LoadObject(const sys::Path& FN);
+
+ bool warning(StringRef message);
+ bool error(StringRef message);
+ void verbose(StringRef message);
+
+ /// @}
+ /// @name Data
+ /// @{
+ private:
+ LLVMContext& Context; ///< The context for global information
+ Module* Composite; ///< The composite module linked together
+ std::vector<sys::Path> LibPaths; ///< The library search paths
+ unsigned Flags; ///< Flags to control optional behavior.
+ std::string Error; ///< Text of error that occurred.
+ std::string ProgramName; ///< Name of the program being linked
+ /// @}
+
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/EDInstInfo.h b/include/llvm/MC/EDInstInfo.h
new file mode 100644
index 00000000000..5b024675cdc
--- /dev/null
+++ b/include/llvm/MC/EDInstInfo.h
@@ -0,0 +1,29 @@
+//===-- llvm/MC/EDInstInfo.h - EDis instruction info ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#ifndef EDINSTINFO_H
+#define EDINSTINFO_H
+
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+#define EDIS_MAX_OPERANDS 13
+#define EDIS_MAX_SYNTAXES 2
+
+struct EDInstInfo {
+ uint8_t instructionType;
+ uint8_t numOperands;
+ uint8_t operandTypes[EDIS_MAX_OPERANDS];
+ uint8_t operandFlags[EDIS_MAX_OPERANDS];
+ const signed char operandOrders[EDIS_MAX_SYNTAXES][EDIS_MAX_OPERANDS];
+};
+
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCAsmBackend.h b/include/llvm/MC/MCAsmBackend.h
new file mode 100644
index 00000000000..348a5f52d2a
--- /dev/null
+++ b/include/llvm/MC/MCAsmBackend.h
@@ -0,0 +1,157 @@
+//===-- llvm/MC/MCAsmBack.h - MC Asm Backend --------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCASMBACKEND_H
+#define LLVM_MC_MCASMBACKEND_H
+
+#include "llvm/MC/MCDirectives.h"
+#include "llvm/MC/MCFixup.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+
+namespace llvm {
+class MCAsmLayout;
+class MCAssembler;
+class MCELFObjectTargetWriter;
+struct MCFixupKindInfo;
+class MCFragment;
+class MCInst;
+class MCInstFragment;
+class MCObjectWriter;
+class MCSection;
+class MCValue;
+class raw_ostream;
+
+/// MCAsmBackend - Generic interface to target specific assembler backends.
+class MCAsmBackend {
+ MCAsmBackend(const MCAsmBackend &) LLVM_DELETED_FUNCTION;
+ void operator=(const MCAsmBackend &) LLVM_DELETED_FUNCTION;
+protected: // Can only create subclasses.
+ MCAsmBackend();
+
+ unsigned HasReliableSymbolDifference : 1;
+
+public:
+ virtual ~MCAsmBackend();
+
+ /// createObjectWriter - Create a new MCObjectWriter instance for use by the
+ /// assembler backend to emit the final object file.
+ virtual MCObjectWriter *createObjectWriter(raw_ostream &OS) const = 0;
+
+ /// createELFObjectTargetWriter - Create a new ELFObjectTargetWriter to enable
+ /// non-standard ELFObjectWriters.
+ virtual MCELFObjectTargetWriter *createELFObjectTargetWriter() const {
+ llvm_unreachable("createELFObjectTargetWriter is not supported by asm "
+ "backend");
+ }
+
+ /// hasReliableSymbolDifference - Check whether this target implements
+ /// accurate relocations for differences between symbols. If not, differences
+ /// between symbols will always be relocatable expressions and any references
+ /// to temporary symbols will be assumed to be in the same atom, unless they
+ /// reside in a different section.
+ ///
+ /// This should always be true (since it results in fewer relocations with no
+ /// loss of functionality), but is currently supported as a way to maintain
+ /// exact object compatibility with Darwin 'as' (on non-x86_64). It should
+ /// eventually should be eliminated.
+ bool hasReliableSymbolDifference() const {
+ return HasReliableSymbolDifference;
+ }
+
+ /// doesSectionRequireSymbols - Check whether the given section requires that
+ /// all symbols (even temporaries) have symbol table entries.
+ virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
+ return false;
+ }
+
+ /// isSectionAtomizable - Check whether the given section can be split into
+ /// atoms.
+ ///
+ /// \see MCAssembler::isSymbolLinkerVisible().
+ virtual bool isSectionAtomizable(const MCSection &Section) const {
+ return true;
+ }
+
+ /// @name Target Fixup Interfaces
+ /// @{
+
+ /// getNumFixupKinds - Get the number of target specific fixup kinds.
+ virtual unsigned getNumFixupKinds() const = 0;
+
+ /// getFixupKindInfo - Get information on a fixup kind.
+ virtual const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const;
+
+ /// processFixupValue - Target hook to adjust the literal value of a fixup
+ /// if necessary. IsResolved signals whether the caller believes a relocation
+ /// is needed; the target can modify the value. The default does nothing.
+ virtual void processFixupValue(const MCAssembler &Asm,
+ const MCAsmLayout &Layout,
+ const MCFixup &Fixup, const MCFragment *DF,
+ MCValue &Target, uint64_t &Value,
+ bool &IsResolved) {}
+
+ /// @}
+
+ /// applyFixup - Apply the \p Value for given \p Fixup into the provided
+ /// data fragment, at the offset specified by the fixup and following the
+ /// fixup kind as appropriate.
+ virtual void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
+ uint64_t Value) const = 0;
+
+ /// @}
+
+ /// @name Target Relaxation Interfaces
+ /// @{
+
+ /// mayNeedRelaxation - Check whether the given instruction may need
+ /// relaxation.
+ ///
+ /// \param Inst - The instruction to test.
+ virtual bool mayNeedRelaxation(const MCInst &Inst) const = 0;
+
+ /// fixupNeedsRelaxation - Target specific predicate for whether a given
+ /// fixup requires the associated instruction to be relaxed.
+ virtual bool fixupNeedsRelaxation(const MCFixup &Fixup,
+ uint64_t Value,
+ const MCInstFragment *DF,
+ const MCAsmLayout &Layout) const = 0;
+
+ /// RelaxInstruction - Relax the instruction in the given fragment to the next
+ /// wider instruction.
+ ///
+ /// \param Inst The instruction to relax, which may be the same as the
+ /// output.
+ /// \param [out] Res On return, the relaxed instruction.
+ virtual void relaxInstruction(const MCInst &Inst, MCInst &Res) const = 0;
+
+ /// @}
+
+ /// getMinimumNopSize - Returns the minimum size of a nop in bytes on this
+ /// target. The assembler will use this to emit excess padding in situations
+ /// where the padding required for simple alignment would be less than the
+ /// minimum nop size.
+ ///
+ virtual unsigned getMinimumNopSize() const { return 1; }
+
+ /// writeNopData - Write an (optimal) nop sequence of Count bytes to the given
+ /// output. If the target cannot generate such a sequence, it should return an
+ /// error.
+ ///
+ /// \return - True on success.
+ virtual bool writeNopData(uint64_t Count, MCObjectWriter *OW) const = 0;
+
+ /// handleAssemblerFlag - Handle any target-specific assembler flags.
+ /// By default, do nothing.
+ virtual void handleAssemblerFlag(MCAssemblerFlag Flag) {}
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCAsmInfo.h b/include/llvm/MC/MCAsmInfo.h
new file mode 100644
index 00000000000..97aad71fd95
--- /dev/null
+++ b/include/llvm/MC/MCAsmInfo.h
@@ -0,0 +1,561 @@
+//===-- llvm/MC/MCAsmInfo.h - Asm info --------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains a class to be used as the basis for target specific
+// asm writers. This class primarily takes care of global printing constants,
+// which are used in very similar ways across all targets.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_TARGET_ASM_INFO_H
+#define LLVM_TARGET_ASM_INFO_H
+
+#include "llvm/MC/MachineLocation.h"
+#include "llvm/MC/MCDirectives.h"
+#include <cassert>
+#include <vector>
+
+namespace llvm {
+ class MCExpr;
+ class MCSection;
+ class MCStreamer;
+ class MCSymbol;
+ class MCContext;
+
+ namespace ExceptionHandling {
+ enum ExceptionsType { None, DwarfCFI, SjLj, ARM, Win64 };
+ }
+
+ namespace LCOMM {
+ enum LCOMMType { NoAlignment, ByteAlignment, Log2Alignment };
+ }
+
+ /// MCAsmInfo - This class is intended to be used as a base class for asm
+ /// properties and features specific to the target.
+ class MCAsmInfo {
+ protected:
+ //===------------------------------------------------------------------===//
+ // Properties to be set by the target writer, used to configure asm printer.
+ //
+
+ /// PointerSize - Pointer size in bytes.
+ /// Default is 4.
+ unsigned PointerSize;
+
+ /// IsLittleEndian - True if target is little endian.
+ /// Default is true.
+ bool IsLittleEndian;
+
+ /// StackGrowsUp - True if target stack grow up.
+ /// Default is false.
+ bool StackGrowsUp;
+
+ /// HasSubsectionsViaSymbols - True if this target has the MachO
+ /// .subsections_via_symbols directive.
+ bool HasSubsectionsViaSymbols; // Default is false.
+
+ /// HasMachoZeroFillDirective - True if this is a MachO target that supports
+ /// the macho-specific .zerofill directive for emitting BSS Symbols.
+ bool HasMachoZeroFillDirective; // Default is false.
+
+ /// HasMachoTBSSDirective - True if this is a MachO target that supports
+ /// the macho-specific .tbss directive for emitting thread local BSS Symbols
+ bool HasMachoTBSSDirective; // Default is false.
+
+ /// HasStaticCtorDtorReferenceInStaticMode - True if the compiler should
+ /// emit a ".reference .constructors_used" or ".reference .destructors_used"
+ /// directive after the a static ctor/dtor list. This directive is only
+ /// emitted in Static relocation model.
+ bool HasStaticCtorDtorReferenceInStaticMode; // Default is false.
+
+ /// LinkerRequiresNonEmptyDwarfLines - True if the linker has a bug and
+ /// requires that the debug_line section be of a minimum size. In practice
+ /// such a linker requires a non empty line sequence if a file is present.
+ bool LinkerRequiresNonEmptyDwarfLines; // Default to false.
+
+ /// MaxInstLength - This is the maximum possible length of an instruction,
+ /// which is needed to compute the size of an inline asm.
+ unsigned MaxInstLength; // Defaults to 4.
+
+ /// PCSymbol - The symbol used to represent the current PC. Used in PC
+ /// relative expressions.
+ const char *PCSymbol; // Defaults to "$".
+
+ /// SeparatorString - This string, if specified, is used to separate
+ /// instructions from each other when on the same line.
+ const char *SeparatorString; // Defaults to ';'
+
+ /// CommentColumn - This indicates the comment num (zero-based) at
+ /// which asm comments should be printed.
+ unsigned CommentColumn; // Defaults to 40
+
+ /// CommentString - This indicates the comment character used by the
+ /// assembler.
+ const char *CommentString; // Defaults to "#"
+
+ /// LabelSuffix - This is appended to emitted labels.
+ const char *LabelSuffix; // Defaults to ":"
+
+ /// GlobalPrefix - If this is set to a non-empty string, it is prepended
+ /// onto all global symbols. This is often used for "_" or ".".
+ const char *GlobalPrefix; // Defaults to ""
+
+ /// PrivateGlobalPrefix - This prefix is used for globals like constant
+ /// pool entries that are completely private to the .s file and should not
+ /// have names in the .o file. This is often "." or "L".
+ const char *PrivateGlobalPrefix; // Defaults to "."
+
+ /// LinkerPrivateGlobalPrefix - This prefix is used for symbols that should
+ /// be passed through the assembler but be removed by the linker. This
+ /// is "l" on Darwin, currently used for some ObjC metadata.
+ const char *LinkerPrivateGlobalPrefix; // Defaults to ""
+
+ /// InlineAsmStart/End - If these are nonempty, they contain a directive to
+ /// emit before and after an inline assembly statement.
+ const char *InlineAsmStart; // Defaults to "#APP\n"
+ const char *InlineAsmEnd; // Defaults to "#NO_APP\n"
+
+ /// Code16Directive, Code32Directive, Code64Directive - These are assembly
+ /// directives that tells the assembler to interpret the following
+ /// instructions differently.
+ const char *Code16Directive; // Defaults to ".code16"
+ const char *Code32Directive; // Defaults to ".code32"
+ const char *Code64Directive; // Defaults to ".code64"
+
+ /// AssemblerDialect - Which dialect of an assembler variant to use.
+ unsigned AssemblerDialect; // Defaults to 0
+
+ /// AllowQuotesInName - This is true if the assembler allows for complex
+ /// symbol names to be surrounded in quotes. This defaults to false.
+ bool AllowQuotesInName;
+
+ /// AllowNameToStartWithDigit - This is true if the assembler allows symbol
+ /// names to start with a digit (e.g., "0x0021"). This defaults to false.
+ bool AllowNameToStartWithDigit;
+
+ /// AllowPeriodsInName - This is true if the assembler allows periods in
+ /// symbol names. This defaults to true.
+ bool AllowPeriodsInName;
+
+ /// AllowUTF8 - This is true if the assembler accepts UTF-8 input.
+ // FIXME: Make this a more general encoding setting?
+ bool AllowUTF8;
+
+ /// UseDataRegionDirectives - This is true if data region markers should
+ /// be printed as ".data_region/.end_data_region" directives. If false,
+ /// use "$d/$a" labels instead.
+ bool UseDataRegionDirectives;
+
+ //===--- Data Emission Directives -------------------------------------===//
+
+ /// ZeroDirective - this should be set to the directive used to get some
+ /// number of zero bytes emitted to the current section. Common cases are
+ /// "\t.zero\t" and "\t.space\t". If this is set to null, the
+ /// Data*bitsDirective's will be used to emit zero bytes.
+ const char *ZeroDirective; // Defaults to "\t.zero\t"
+
+ /// AsciiDirective - This directive allows emission of an ascii string with
+ /// the standard C escape characters embedded into it.
+ const char *AsciiDirective; // Defaults to "\t.ascii\t"
+
+ /// AscizDirective - If not null, this allows for special handling of
+ /// zero terminated strings on this target. This is commonly supported as
+ /// ".asciz". If a target doesn't support this, it can be set to null.
+ const char *AscizDirective; // Defaults to "\t.asciz\t"
+
+ /// DataDirectives - These directives are used to output some unit of
+ /// integer data to the current section. If a data directive is set to
+ /// null, smaller data directives will be used to emit the large sizes.
+ const char *Data8bitsDirective; // Defaults to "\t.byte\t"
+ const char *Data16bitsDirective; // Defaults to "\t.short\t"
+ const char *Data32bitsDirective; // Defaults to "\t.long\t"
+ const char *Data64bitsDirective; // Defaults to "\t.quad\t"
+
+ /// GPRel64Directive - if non-null, a directive that is used to emit a word
+ /// which should be relocated as a 64-bit GP-relative offset, e.g. .gpdword
+ /// on Mips.
+ const char *GPRel64Directive; // Defaults to NULL.
+
+ /// GPRel32Directive - if non-null, a directive that is used to emit a word
+ /// which should be relocated as a 32-bit GP-relative offset, e.g. .gpword
+ /// on Mips or .gprel32 on Alpha.
+ const char *GPRel32Directive; // Defaults to NULL.
+
+ /// getDataASDirective - Return the directive that should be used to emit
+ /// data of the specified size to the specified numeric address space.
+ virtual const char *getDataASDirective(unsigned Size, unsigned AS) const {
+ assert(AS != 0 && "Don't know the directives for default addr space");
+ return 0;
+ }
+
+ /// SunStyleELFSectionSwitchSyntax - This is true if this target uses "Sun
+ /// Style" syntax for section switching ("#alloc,#write" etc) instead of the
+ /// normal ELF syntax (,"a,w") in .section directives.
+ bool SunStyleELFSectionSwitchSyntax; // Defaults to false.
+
+ /// UsesELFSectionDirectiveForBSS - This is true if this target uses ELF
+ /// '.section' directive before the '.bss' one. It's used for PPC/Linux
+ /// which doesn't support the '.bss' directive only.
+ bool UsesELFSectionDirectiveForBSS; // Defaults to false.
+
+ /// HasMicrosoftFastStdCallMangling - True if this target uses microsoft
+ /// style mangling for functions with X86_StdCall/X86_FastCall calling
+ /// convention.
+ bool HasMicrosoftFastStdCallMangling; // Defaults to false.
+
+ //===--- Alignment Information ----------------------------------------===//
+
+ /// AlignDirective - The directive used to emit round up to an alignment
+ /// boundary.
+ ///
+ const char *AlignDirective; // Defaults to "\t.align\t"
+
+ /// AlignmentIsInBytes - If this is true (the default) then the asmprinter
+ /// emits ".align N" directives, where N is the number of bytes to align to.
+ /// Otherwise, it emits ".align log2(N)", e.g. 3 to align to an 8 byte
+ /// boundary.
+ bool AlignmentIsInBytes; // Defaults to true
+
+ /// TextAlignFillValue - If non-zero, this is used to fill the executable
+ /// space created as the result of a alignment directive.
+ unsigned TextAlignFillValue; // Defaults to 0
+
+ //===--- Global Variable Emission Directives --------------------------===//
+
+ /// GlobalDirective - This is the directive used to declare a global entity.
+ ///
+ const char *GlobalDirective; // Defaults to NULL.
+
+ /// ExternDirective - This is the directive used to declare external
+ /// globals.
+ ///
+ const char *ExternDirective; // Defaults to NULL.
+
+ /// HasSetDirective - True if the assembler supports the .set directive.
+ bool HasSetDirective; // Defaults to true.
+
+ /// HasAggressiveSymbolFolding - False if the assembler requires that we use
+ /// Lc = a - b
+ /// .long Lc
+ /// instead of
+ /// .long a - b
+ bool HasAggressiveSymbolFolding; // Defaults to true.
+
+ /// COMMDirectiveAlignmentIsInBytes - True is .comm's and .lcomms optional
+ /// alignment is to be specified in bytes instead of log2(n).
+ bool COMMDirectiveAlignmentIsInBytes; // Defaults to true;
+
+ /// LCOMMDirectiveAlignment - Describes if the .lcomm directive for the
+ /// target supports an alignment argument and how it is interpreted.
+ LCOMM::LCOMMType LCOMMDirectiveAlignmentType; // Defaults to NoAlignment.
+
+ /// HasDotTypeDotSizeDirective - True if the target has .type and .size
+ /// directives, this is true for most ELF targets.
+ bool HasDotTypeDotSizeDirective; // Defaults to true.
+
+ /// HasSingleParameterDotFile - True if the target has a single parameter
+ /// .file directive, this is true for ELF targets.
+ bool HasSingleParameterDotFile; // Defaults to true.
+
+ /// HasNoDeadStrip - True if this target supports the MachO .no_dead_strip
+ /// directive.
+ bool HasNoDeadStrip; // Defaults to false.
+
+ /// HasSymbolResolver - True if this target supports the MachO
+ /// .symbol_resolver directive.
+ bool HasSymbolResolver; // Defaults to false.
+
+ /// WeakRefDirective - This directive, if non-null, is used to declare a
+ /// global as being a weak undefined symbol.
+ const char *WeakRefDirective; // Defaults to NULL.
+
+ /// WeakDefDirective - This directive, if non-null, is used to declare a
+ /// global as being a weak defined symbol.
+ const char *WeakDefDirective; // Defaults to NULL.
+
+ /// LinkOnceDirective - This directive, if non-null is used to declare a
+ /// global as being a weak defined symbol. This is used on cygwin/mingw.
+ const char *LinkOnceDirective; // Defaults to NULL.
+
+ /// HiddenVisibilityAttr - This attribute, if not MCSA_Invalid, is used to
+ /// declare a symbol as having hidden visibility.
+ MCSymbolAttr HiddenVisibilityAttr; // Defaults to MCSA_Hidden.
+
+ /// HiddenDeclarationVisibilityAttr - This attribute, if not MCSA_Invalid,
+ /// is used to declare an undefined symbol as having hidden visibility.
+ MCSymbolAttr HiddenDeclarationVisibilityAttr; // Defaults to MCSA_Hidden.
+
+
+ /// ProtectedVisibilityAttr - This attribute, if not MCSA_Invalid, is used
+ /// to declare a symbol as having protected visibility.
+ MCSymbolAttr ProtectedVisibilityAttr; // Defaults to MCSA_Protected
+
+ //===--- Dwarf Emission Directives -----------------------------------===//
+
+ /// HasLEB128 - True if target asm supports leb128 directives.
+ bool HasLEB128; // Defaults to false.
+
+ /// SupportsDebugInformation - True if target supports emission of debugging
+ /// information.
+ bool SupportsDebugInformation; // Defaults to false.
+
+ /// SupportsExceptionHandling - True if target supports exception handling.
+ ExceptionHandling::ExceptionsType ExceptionsType; // Defaults to None
+
+ /// DwarfUsesInlineInfoSection - True if DwarfDebugInlineSection is used to
+ /// encode inline subroutine information.
+ bool DwarfUsesInlineInfoSection; // Defaults to false.
+
+ /// DwarfSectionOffsetDirective - Special section offset directive.
+ const char* DwarfSectionOffsetDirective; // Defaults to NULL
+
+ /// DwarfUsesRelocationsAcrossSections - True if Dwarf2 output generally
+ /// uses relocations for references to other .debug_* sections.
+ bool DwarfUsesRelocationsAcrossSections;
+
+ /// DwarfRegNumForCFI - True if dwarf register numbers are printed
+ /// instead of symbolic register names in .cfi_* directives.
+ bool DwarfRegNumForCFI; // Defaults to false;
+
+ //===--- Prologue State ----------------------------------------------===//
+
+ std::vector<MachineMove> InitialFrameState;
+
+ public:
+ explicit MCAsmInfo();
+ virtual ~MCAsmInfo();
+
+ // FIXME: move these methods to DwarfPrinter when the JIT stops using them.
+ static unsigned getSLEB128Size(int Value);
+ static unsigned getULEB128Size(unsigned Value);
+
+ /// getPointerSize - Get the pointer size in bytes.
+ unsigned getPointerSize() const {
+ return PointerSize;
+ }
+
+ /// islittleendian - True if the target is little endian.
+ bool isLittleEndian() const {
+ return IsLittleEndian;
+ }
+
+ /// isStackGrowthDirectionUp - True if target stack grow up.
+ bool isStackGrowthDirectionUp() const {
+ return StackGrowsUp;
+ }
+
+ bool hasSubsectionsViaSymbols() const { return HasSubsectionsViaSymbols; }
+
+ // Data directive accessors.
+ //
+ const char *getData8bitsDirective(unsigned AS = 0) const {
+ return AS == 0 ? Data8bitsDirective : getDataASDirective(8, AS);
+ }
+ const char *getData16bitsDirective(unsigned AS = 0) const {
+ return AS == 0 ? Data16bitsDirective : getDataASDirective(16, AS);
+ }
+ const char *getData32bitsDirective(unsigned AS = 0) const {
+ return AS == 0 ? Data32bitsDirective : getDataASDirective(32, AS);
+ }
+ const char *getData64bitsDirective(unsigned AS = 0) const {
+ return AS == 0 ? Data64bitsDirective : getDataASDirective(64, AS);
+ }
+ const char *getGPRel64Directive() const { return GPRel64Directive; }
+ const char *getGPRel32Directive() const { return GPRel32Directive; }
+
+ /// getNonexecutableStackSection - Targets can implement this method to
+ /// specify a section to switch to if the translation unit doesn't have any
+ /// trampolines that require an executable stack.
+ virtual const MCSection *getNonexecutableStackSection(MCContext &Ctx) const{
+ return 0;
+ }
+
+ virtual const MCExpr *
+ getExprForPersonalitySymbol(const MCSymbol *Sym,
+ unsigned Encoding,
+ MCStreamer &Streamer) const;
+
+ const MCExpr *
+ getExprForFDESymbol(const MCSymbol *Sym,
+ unsigned Encoding,
+ MCStreamer &Streamer) const;
+
+ bool usesSunStyleELFSectionSwitchSyntax() const {
+ return SunStyleELFSectionSwitchSyntax;
+ }
+
+ bool usesELFSectionDirectiveForBSS() const {
+ return UsesELFSectionDirectiveForBSS;
+ }
+
+ bool hasMicrosoftFastStdCallMangling() const {
+ return HasMicrosoftFastStdCallMangling;
+ }
+
+ // Accessors.
+ //
+ bool hasMachoZeroFillDirective() const { return HasMachoZeroFillDirective; }
+ bool hasMachoTBSSDirective() const { return HasMachoTBSSDirective; }
+ bool hasStaticCtorDtorReferenceInStaticMode() const {
+ return HasStaticCtorDtorReferenceInStaticMode;
+ }
+ bool getLinkerRequiresNonEmptyDwarfLines() const {
+ return LinkerRequiresNonEmptyDwarfLines;
+ }
+ unsigned getMaxInstLength() const {
+ return MaxInstLength;
+ }
+ const char *getPCSymbol() const {
+ return PCSymbol;
+ }
+ const char *getSeparatorString() const {
+ return SeparatorString;
+ }
+ unsigned getCommentColumn() const {
+ return CommentColumn;
+ }
+ const char *getCommentString() const {
+ return CommentString;
+ }
+ const char *getLabelSuffix() const {
+ return LabelSuffix;
+ }
+ const char *getGlobalPrefix() const {
+ return GlobalPrefix;
+ }
+ const char *getPrivateGlobalPrefix() const {
+ return PrivateGlobalPrefix;
+ }
+ const char *getLinkerPrivateGlobalPrefix() const {
+ return LinkerPrivateGlobalPrefix;
+ }
+ const char *getInlineAsmStart() const {
+ return InlineAsmStart;
+ }
+ const char *getInlineAsmEnd() const {
+ return InlineAsmEnd;
+ }
+ const char *getCode16Directive() const {
+ return Code16Directive;
+ }
+ const char *getCode32Directive() const {
+ return Code32Directive;
+ }
+ const char *getCode64Directive() const {
+ return Code64Directive;
+ }
+ unsigned getAssemblerDialect() const {
+ return AssemblerDialect;
+ }
+ bool doesAllowQuotesInName() const {
+ return AllowQuotesInName;
+ }
+ bool doesAllowNameToStartWithDigit() const {
+ return AllowNameToStartWithDigit;
+ }
+ bool doesAllowPeriodsInName() const {
+ return AllowPeriodsInName;
+ }
+ bool doesAllowUTF8() const {
+ return AllowUTF8;
+ }
+ bool doesSupportDataRegionDirectives() const {
+ return UseDataRegionDirectives;
+ }
+ const char *getZeroDirective() const {
+ return ZeroDirective;
+ }
+ const char *getAsciiDirective() const {
+ return AsciiDirective;
+ }
+ const char *getAscizDirective() const {
+ return AscizDirective;
+ }
+ const char *getAlignDirective() const {
+ return AlignDirective;
+ }
+ bool getAlignmentIsInBytes() const {
+ return AlignmentIsInBytes;
+ }
+ unsigned getTextAlignFillValue() const {
+ return TextAlignFillValue;
+ }
+ const char *getGlobalDirective() const {
+ return GlobalDirective;
+ }
+ const char *getExternDirective() const {
+ return ExternDirective;
+ }
+ bool hasSetDirective() const { return HasSetDirective; }
+ bool hasAggressiveSymbolFolding() const {
+ return HasAggressiveSymbolFolding;
+ }
+ bool getCOMMDirectiveAlignmentIsInBytes() const {
+ return COMMDirectiveAlignmentIsInBytes;
+ }
+ LCOMM::LCOMMType getLCOMMDirectiveAlignmentType() const {
+ return LCOMMDirectiveAlignmentType;
+ }
+ bool hasDotTypeDotSizeDirective() const {return HasDotTypeDotSizeDirective;}
+ bool hasSingleParameterDotFile() const { return HasSingleParameterDotFile; }
+ bool hasNoDeadStrip() const { return HasNoDeadStrip; }
+ bool hasSymbolResolver() const { return HasSymbolResolver; }
+ const char *getWeakRefDirective() const { return WeakRefDirective; }
+ const char *getWeakDefDirective() const { return WeakDefDirective; }
+ const char *getLinkOnceDirective() const { return LinkOnceDirective; }
+
+ MCSymbolAttr getHiddenVisibilityAttr() const { return HiddenVisibilityAttr;}
+ MCSymbolAttr getHiddenDeclarationVisibilityAttr() const {
+ return HiddenDeclarationVisibilityAttr;
+ }
+ MCSymbolAttr getProtectedVisibilityAttr() const {
+ return ProtectedVisibilityAttr;
+ }
+ bool hasLEB128() const {
+ return HasLEB128;
+ }
+ bool doesSupportDebugInformation() const {
+ return SupportsDebugInformation;
+ }
+ bool doesSupportExceptionHandling() const {
+ return ExceptionsType != ExceptionHandling::None;
+ }
+ ExceptionHandling::ExceptionsType getExceptionHandlingType() const {
+ return ExceptionsType;
+ }
+ bool isExceptionHandlingDwarf() const {
+ return
+ (ExceptionsType == ExceptionHandling::DwarfCFI ||
+ ExceptionsType == ExceptionHandling::ARM ||
+ ExceptionsType == ExceptionHandling::Win64);
+ }
+ bool doesDwarfUseInlineInfoSection() const {
+ return DwarfUsesInlineInfoSection;
+ }
+ const char *getDwarfSectionOffsetDirective() const {
+ return DwarfSectionOffsetDirective;
+ }
+ bool doesDwarfUseRelocationsAcrossSections() const {
+ return DwarfUsesRelocationsAcrossSections;
+ }
+ bool useDwarfRegNumForCFI() const {
+ return DwarfRegNumForCFI;
+ }
+
+ void addInitialFrameState(MCSymbol *label, const MachineLocation &D,
+ const MachineLocation &S) {
+ InitialFrameState.push_back(MachineMove(label, D, S));
+ }
+ const std::vector<MachineMove> &getInitialFrameState() const {
+ return InitialFrameState;
+ }
+ };
+}
+
+#endif
diff --git a/include/llvm/MC/MCAsmInfoCOFF.h b/include/llvm/MC/MCAsmInfoCOFF.h
new file mode 100644
index 00000000000..0ff3e127ed0
--- /dev/null
+++ b/include/llvm/MC/MCAsmInfoCOFF.h
@@ -0,0 +1,36 @@
+//===-- MCAsmInfoCOFF.h - COFF asm properties -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_COFF_TARGET_ASM_INFO_H
+#define LLVM_COFF_TARGET_ASM_INFO_H
+
+#include "llvm/MC/MCAsmInfo.h"
+
+namespace llvm {
+ class MCAsmInfoCOFF : public MCAsmInfo {
+ virtual void anchor();
+ protected:
+ explicit MCAsmInfoCOFF();
+ };
+
+ class MCAsmInfoMicrosoft : public MCAsmInfoCOFF {
+ virtual void anchor();
+ protected:
+ explicit MCAsmInfoMicrosoft();
+ };
+
+ class MCAsmInfoGNUCOFF : public MCAsmInfoCOFF {
+ virtual void anchor();
+ protected:
+ explicit MCAsmInfoGNUCOFF();
+ };
+}
+
+
+#endif // LLVM_COFF_TARGET_ASM_INFO_H
diff --git a/include/llvm/MC/MCAsmInfoDarwin.h b/include/llvm/MC/MCAsmInfoDarwin.h
new file mode 100644
index 00000000000..af552de6e69
--- /dev/null
+++ b/include/llvm/MC/MCAsmInfoDarwin.h
@@ -0,0 +1,29 @@
+//===---- MCAsmInfoDarwin.h - Darwin asm properties -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines target asm properties related what form asm statements
+// should take in general on Darwin-based targets
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_DARWIN_TARGET_ASM_INFO_H
+#define LLVM_DARWIN_TARGET_ASM_INFO_H
+
+#include "llvm/MC/MCAsmInfo.h"
+
+namespace llvm {
+ class MCAsmInfoDarwin : public MCAsmInfo {
+ virtual void anchor();
+ public:
+ explicit MCAsmInfoDarwin();
+ };
+}
+
+
+#endif // LLVM_DARWIN_TARGET_ASM_INFO_H
diff --git a/include/llvm/MC/MCAsmLayout.h b/include/llvm/MC/MCAsmLayout.h
new file mode 100644
index 00000000000..cf79216d076
--- /dev/null
+++ b/include/llvm/MC/MCAsmLayout.h
@@ -0,0 +1,105 @@
+//===- MCAsmLayout.h - Assembly Layout Object -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCASMLAYOUT_H
+#define LLVM_MC_MCASMLAYOUT_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace llvm {
+class MCAssembler;
+class MCFragment;
+class MCSectionData;
+class MCSymbolData;
+
+/// Encapsulates the layout of an assembly file at a particular point in time.
+///
+/// Assembly may requiring compute multiple layouts for a particular assembly
+/// file as part of the relaxation process. This class encapsulates the layout
+/// at a single point in time in such a way that it is always possible to
+/// efficiently compute the exact addresses of any symbol in the assembly file,
+/// even during the relaxation process.
+class MCAsmLayout {
+public:
+ typedef llvm::SmallVectorImpl<MCSectionData*>::const_iterator const_iterator;
+ typedef llvm::SmallVectorImpl<MCSectionData*>::iterator iterator;
+
+private:
+ MCAssembler &Assembler;
+
+ /// List of sections in layout order.
+ llvm::SmallVector<MCSectionData*, 16> SectionOrder;
+
+ /// The last fragment which was laid out, or 0 if nothing has been laid
+ /// out. Fragments are always laid out in order, so all fragments with a
+ /// lower ordinal will be up to date.
+ mutable DenseMap<const MCSectionData*, MCFragment *> LastValidFragment;
+
+ /// \brief Make sure that the layout for the given fragment is valid, lazily
+ /// computing it if necessary.
+ void EnsureValid(const MCFragment *F) const;
+
+ bool isFragmentUpToDate(const MCFragment *F) const;
+
+public:
+ MCAsmLayout(MCAssembler &_Assembler);
+
+ /// Get the assembler object this is a layout for.
+ MCAssembler &getAssembler() const { return Assembler; }
+
+ /// \brief Invalidate all following fragments because a fragment has been
+ /// resized. The fragments size should have already been updated.
+ void Invalidate(MCFragment *F);
+
+ /// \brief Perform layout for a single fragment, assuming that the previous
+ /// fragment has already been laid out correctly, and the parent section has
+ /// been initialized.
+ void LayoutFragment(MCFragment *Fragment);
+
+ /// @name Section Access (in layout order)
+ /// @{
+
+ llvm::SmallVectorImpl<MCSectionData*> &getSectionOrder() {
+ return SectionOrder;
+ }
+ const llvm::SmallVectorImpl<MCSectionData*> &getSectionOrder() const {
+ return SectionOrder;
+ }
+
+ /// @}
+ /// @name Fragment Layout Data
+ /// @{
+
+ /// \brief Get the offset of the given fragment inside its containing section.
+ uint64_t getFragmentOffset(const MCFragment *F) const;
+
+ /// @}
+ /// @name Utility Functions
+ /// @{
+
+ /// \brief Get the address space size of the given section, as it effects
+ /// layout. This may differ from the size reported by \see getSectionSize() by
+ /// not including section tail padding.
+ uint64_t getSectionAddressSize(const MCSectionData *SD) const;
+
+ /// \brief Get the data size of the given section, as emitted to the object
+ /// file. This may include additional padding, or be 0 for virtual sections.
+ uint64_t getSectionFileSize(const MCSectionData *SD) const;
+
+ /// \brief Get the offset of the given symbol, as computed in the current
+ /// layout.
+ uint64_t getSymbolOffset(const MCSymbolData *SD) const;
+
+ /// @}
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCAssembler.h b/include/llvm/MC/MCAssembler.h
new file mode 100644
index 00000000000..83c01ec5b98
--- /dev/null
+++ b/include/llvm/MC/MCAssembler.h
@@ -0,0 +1,973 @@
+//===- MCAssembler.h - Object File Generation -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCASSEMBLER_H
+#define LLVM_MC_MCASSEMBLER_H
+
+#include "llvm/MC/MCFixup.h"
+#include "llvm/MC/MCInst.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/ilist_node.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/DataTypes.h"
+#include <vector> // FIXME: Shouldn't be needed.
+
+namespace llvm {
+class raw_ostream;
+class MCAsmLayout;
+class MCAssembler;
+class MCContext;
+class MCCodeEmitter;
+class MCExpr;
+class MCFragment;
+class MCObjectWriter;
+class MCSection;
+class MCSectionData;
+class MCSymbol;
+class MCSymbolData;
+class MCValue;
+class MCAsmBackend;
+
+class MCFragment : public ilist_node<MCFragment> {
+ friend class MCAsmLayout;
+
+ MCFragment(const MCFragment&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCFragment&) LLVM_DELETED_FUNCTION;
+
+public:
+ enum FragmentType {
+ FT_Align,
+ FT_Data,
+ FT_Fill,
+ FT_Inst,
+ FT_Org,
+ FT_Dwarf,
+ FT_DwarfFrame,
+ FT_LEB
+ };
+
+private:
+ FragmentType Kind;
+
+ /// Parent - The data for the section this fragment is in.
+ MCSectionData *Parent;
+
+ /// Atom - The atom this fragment is in, as represented by it's defining
+ /// symbol. Atom's are only used by backends which set
+ /// \see MCAsmBackend::hasReliableSymbolDifference().
+ MCSymbolData *Atom;
+
+ /// @name Assembler Backend Data
+ /// @{
+ //
+ // FIXME: This could all be kept private to the assembler implementation.
+
+ /// Offset - The offset of this fragment in its section. This is ~0 until
+ /// initialized.
+ uint64_t Offset;
+
+ /// LayoutOrder - The layout order of this fragment.
+ unsigned LayoutOrder;
+
+ /// @}
+
+protected:
+ MCFragment(FragmentType _Kind, MCSectionData *_Parent = 0);
+
+public:
+ // Only for sentinel.
+ MCFragment();
+ virtual ~MCFragment();
+
+ FragmentType getKind() const { return Kind; }
+
+ MCSectionData *getParent() const { return Parent; }
+ void setParent(MCSectionData *Value) { Parent = Value; }
+
+ MCSymbolData *getAtom() const { return Atom; }
+ void setAtom(MCSymbolData *Value) { Atom = Value; }
+
+ unsigned getLayoutOrder() const { return LayoutOrder; }
+ void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
+
+ static bool classof(const MCFragment *O) { return true; }
+
+ void dump();
+};
+
+class MCDataFragment : public MCFragment {
+ virtual void anchor();
+ SmallString<32> Contents;
+
+ /// Fixups - The list of fixups in this fragment.
+ std::vector<MCFixup> Fixups;
+
+public:
+ typedef std::vector<MCFixup>::const_iterator const_fixup_iterator;
+ typedef std::vector<MCFixup>::iterator fixup_iterator;
+
+public:
+ MCDataFragment(MCSectionData *SD = 0) : MCFragment(FT_Data, SD) {}
+
+ /// @name Accessors
+ /// @{
+
+ SmallString<32> &getContents() { return Contents; }
+ const SmallString<32> &getContents() const { return Contents; }
+
+ /// @}
+ /// @name Fixup Access
+ /// @{
+
+ void addFixup(MCFixup Fixup) {
+ // Enforce invariant that fixups are in offset order.
+ assert((Fixups.empty() || Fixup.getOffset() >= Fixups.back().getOffset()) &&
+ "Fixups must be added in order!");
+ Fixups.push_back(Fixup);
+ }
+
+ std::vector<MCFixup> &getFixups() { return Fixups; }
+ const std::vector<MCFixup> &getFixups() const { return Fixups; }
+
+ fixup_iterator fixup_begin() { return Fixups.begin(); }
+ const_fixup_iterator fixup_begin() const { return Fixups.begin(); }
+
+ fixup_iterator fixup_end() {return Fixups.end();}
+ const_fixup_iterator fixup_end() const {return Fixups.end();}
+
+ size_t fixup_size() const { return Fixups.size(); }
+
+ /// @}
+
+ static bool classof(const MCFragment *F) {
+ return F->getKind() == MCFragment::FT_Data;
+ }
+ static bool classof(const MCDataFragment *) { return true; }
+};
+
+// FIXME: This current incarnation of MCInstFragment doesn't make much sense, as
+// it is almost entirely a duplicate of MCDataFragment. If we decide to stick
+// with this approach (as opposed to making MCInstFragment a very light weight
+// object with just the MCInst and a code size, then we should just change
+// MCDataFragment to have an optional MCInst at its end.
+class MCInstFragment : public MCFragment {
+ virtual void anchor();
+
+ /// Inst - The instruction this is a fragment for.
+ MCInst Inst;
+
+ /// Code - Binary data for the currently encoded instruction.
+ SmallString<8> Code;
+
+ /// Fixups - The list of fixups in this fragment.
+ SmallVector<MCFixup, 1> Fixups;
+
+public:
+ typedef SmallVectorImpl<MCFixup>::const_iterator const_fixup_iterator;
+ typedef SmallVectorImpl<MCFixup>::iterator fixup_iterator;
+
+public:
+ MCInstFragment(const MCInst &_Inst, MCSectionData *SD = 0)
+ : MCFragment(FT_Inst, SD), Inst(_Inst) {
+ }
+
+ /// @name Accessors
+ /// @{
+
+ SmallVectorImpl<char> &getCode() { return Code; }
+ const SmallVectorImpl<char> &getCode() const { return Code; }
+
+ unsigned getInstSize() const { return Code.size(); }
+
+ MCInst &getInst() { return Inst; }
+ const MCInst &getInst() const { return Inst; }
+
+ void setInst(const MCInst& Value) { Inst = Value; }
+
+ /// @}
+ /// @name Fixup Access
+ /// @{
+
+ SmallVectorImpl<MCFixup> &getFixups() { return Fixups; }
+ const SmallVectorImpl<MCFixup> &getFixups() const { return Fixups; }
+
+ fixup_iterator fixup_begin() { return Fixups.begin(); }
+ const_fixup_iterator fixup_begin() const { return Fixups.begin(); }
+
+ fixup_iterator fixup_end() {return Fixups.end();}
+ const_fixup_iterator fixup_end() const {return Fixups.end();}
+
+ size_t fixup_size() const { return Fixups.size(); }
+
+ /// @}
+
+ static bool classof(const MCFragment *F) {
+ return F->getKind() == MCFragment::FT_Inst;
+ }
+ static bool classof(const MCInstFragment *) { return true; }
+};
+
+class MCAlignFragment : public MCFragment {
+ virtual void anchor();
+
+ /// Alignment - The alignment to ensure, in bytes.
+ unsigned Alignment;
+
+ /// Value - Value to use for filling padding bytes.
+ int64_t Value;
+
+ /// ValueSize - The size of the integer (in bytes) of \p Value.
+ unsigned ValueSize;
+
+ /// MaxBytesToEmit - The maximum number of bytes to emit; if the alignment
+ /// cannot be satisfied in this width then this fragment is ignored.
+ unsigned MaxBytesToEmit;
+
+ /// EmitNops - Flag to indicate that (optimal) NOPs should be emitted instead
+ /// of using the provided value. The exact interpretation of this flag is
+ /// target dependent.
+ bool EmitNops : 1;
+
+public:
+ MCAlignFragment(unsigned _Alignment, int64_t _Value, unsigned _ValueSize,
+ unsigned _MaxBytesToEmit, MCSectionData *SD = 0)
+ : MCFragment(FT_Align, SD), Alignment(_Alignment),
+ Value(_Value),ValueSize(_ValueSize),
+ MaxBytesToEmit(_MaxBytesToEmit), EmitNops(false) {}
+
+ /// @name Accessors
+ /// @{
+
+ unsigned getAlignment() const { return Alignment; }
+
+ int64_t getValue() const { return Value; }
+
+ unsigned getValueSize() const { return ValueSize; }
+
+ unsigned getMaxBytesToEmit() const { return MaxBytesToEmit; }
+
+ bool hasEmitNops() const { return EmitNops; }
+ void setEmitNops(bool Value) { EmitNops = Value; }
+
+ /// @}
+
+ static bool classof(const MCFragment *F) {
+ return F->getKind() == MCFragment::FT_Align;
+ }
+ static bool classof(const MCAlignFragment *) { return true; }
+};
+
+class MCFillFragment : public MCFragment {
+ virtual void anchor();
+
+ /// Value - Value to use for filling bytes.
+ int64_t Value;
+
+ /// ValueSize - The size (in bytes) of \p Value to use when filling, or 0 if
+ /// this is a virtual fill fragment.
+ unsigned ValueSize;
+
+ /// Size - The number of bytes to insert.
+ uint64_t Size;
+
+public:
+ MCFillFragment(int64_t _Value, unsigned _ValueSize, uint64_t _Size,
+ MCSectionData *SD = 0)
+ : MCFragment(FT_Fill, SD),
+ Value(_Value), ValueSize(_ValueSize), Size(_Size) {
+ assert((!ValueSize || (Size % ValueSize) == 0) &&
+ "Fill size must be a multiple of the value size!");
+ }
+
+ /// @name Accessors
+ /// @{
+
+ int64_t getValue() const { return Value; }
+
+ unsigned getValueSize() const { return ValueSize; }
+
+ uint64_t getSize() const { return Size; }
+
+ /// @}
+
+ static bool classof(const MCFragment *F) {
+ return F->getKind() == MCFragment::FT_Fill;
+ }
+ static bool classof(const MCFillFragment *) { return true; }
+};
+
+class MCOrgFragment : public MCFragment {
+ virtual void anchor();
+
+ /// Offset - The offset this fragment should start at.
+ const MCExpr *Offset;
+
+ /// Value - Value to use for filling bytes.
+ int8_t Value;
+
+public:
+ MCOrgFragment(const MCExpr &_Offset, int8_t _Value, MCSectionData *SD = 0)
+ : MCFragment(FT_Org, SD),
+ Offset(&_Offset), Value(_Value) {}
+
+ /// @name Accessors
+ /// @{
+
+ const MCExpr &getOffset() const { return *Offset; }
+
+ uint8_t getValue() const { return Value; }
+
+ /// @}
+
+ static bool classof(const MCFragment *F) {
+ return F->getKind() == MCFragment::FT_Org;
+ }
+ static bool classof(const MCOrgFragment *) { return true; }
+};
+
+class MCLEBFragment : public MCFragment {
+ virtual void anchor();
+
+ /// Value - The value this fragment should contain.
+ const MCExpr *Value;
+
+ /// IsSigned - True if this is a sleb128, false if uleb128.
+ bool IsSigned;
+
+ SmallString<8> Contents;
+public:
+ MCLEBFragment(const MCExpr &Value_, bool IsSigned_, MCSectionData *SD)
+ : MCFragment(FT_LEB, SD),
+ Value(&Value_), IsSigned(IsSigned_) { Contents.push_back(0); }
+
+ /// @name Accessors
+ /// @{
+
+ const MCExpr &getValue() const { return *Value; }
+
+ bool isSigned() const { return IsSigned; }
+
+ SmallString<8> &getContents() { return Contents; }
+ const SmallString<8> &getContents() const { return Contents; }
+
+ /// @}
+
+ static bool classof(const MCFragment *F) {
+ return F->getKind() == MCFragment::FT_LEB;
+ }
+ static bool classof(const MCLEBFragment *) { return true; }
+};
+
+class MCDwarfLineAddrFragment : public MCFragment {
+ virtual void anchor();
+
+ /// LineDelta - the value of the difference between the two line numbers
+ /// between two .loc dwarf directives.
+ int64_t LineDelta;
+
+ /// AddrDelta - The expression for the difference of the two symbols that
+ /// make up the address delta between two .loc dwarf directives.
+ const MCExpr *AddrDelta;
+
+ SmallString<8> Contents;
+
+public:
+ MCDwarfLineAddrFragment(int64_t _LineDelta, const MCExpr &_AddrDelta,
+ MCSectionData *SD)
+ : MCFragment(FT_Dwarf, SD),
+ LineDelta(_LineDelta), AddrDelta(&_AddrDelta) { Contents.push_back(0); }
+
+ /// @name Accessors
+ /// @{
+
+ int64_t getLineDelta() const { return LineDelta; }
+
+ const MCExpr &getAddrDelta() const { return *AddrDelta; }
+
+ SmallString<8> &getContents() { return Contents; }
+ const SmallString<8> &getContents() const { return Contents; }
+
+ /// @}
+
+ static bool classof(const MCFragment *F) {
+ return F->getKind() == MCFragment::FT_Dwarf;
+ }
+ static bool classof(const MCDwarfLineAddrFragment *) { return true; }
+};
+
+class MCDwarfCallFrameFragment : public MCFragment {
+ virtual void anchor();
+
+ /// AddrDelta - The expression for the difference of the two symbols that
+ /// make up the address delta between two .cfi_* dwarf directives.
+ const MCExpr *AddrDelta;
+
+ SmallString<8> Contents;
+
+public:
+ MCDwarfCallFrameFragment(const MCExpr &_AddrDelta, MCSectionData *SD)
+ : MCFragment(FT_DwarfFrame, SD),
+ AddrDelta(&_AddrDelta) { Contents.push_back(0); }
+
+ /// @name Accessors
+ /// @{
+
+ const MCExpr &getAddrDelta() const { return *AddrDelta; }
+
+ SmallString<8> &getContents() { return Contents; }
+ const SmallString<8> &getContents() const { return Contents; }
+
+ /// @}
+
+ static bool classof(const MCFragment *F) {
+ return F->getKind() == MCFragment::FT_DwarfFrame;
+ }
+ static bool classof(const MCDwarfCallFrameFragment *) { return true; }
+};
+
+// FIXME: Should this be a separate class, or just merged into MCSection? Since
+// we anticipate the fast path being through an MCAssembler, the only reason to
+// keep it out is for API abstraction.
+class MCSectionData : public ilist_node<MCSectionData> {
+ friend class MCAsmLayout;
+
+ MCSectionData(const MCSectionData&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCSectionData&) LLVM_DELETED_FUNCTION;
+
+public:
+ typedef iplist<MCFragment> FragmentListType;
+
+ typedef FragmentListType::const_iterator const_iterator;
+ typedef FragmentListType::iterator iterator;
+
+ typedef FragmentListType::const_reverse_iterator const_reverse_iterator;
+ typedef FragmentListType::reverse_iterator reverse_iterator;
+
+private:
+ FragmentListType Fragments;
+ const MCSection *Section;
+
+ /// Ordinal - The section index in the assemblers section list.
+ unsigned Ordinal;
+
+ /// LayoutOrder - The index of this section in the layout order.
+ unsigned LayoutOrder;
+
+ /// Alignment - The maximum alignment seen in this section.
+ unsigned Alignment;
+
+ /// @name Assembler Backend Data
+ /// @{
+ //
+ // FIXME: This could all be kept private to the assembler implementation.
+
+ /// HasInstructions - Whether this section has had instructions emitted into
+ /// it.
+ unsigned HasInstructions : 1;
+
+ /// @}
+
+public:
+ // Only for use as sentinel.
+ MCSectionData();
+ MCSectionData(const MCSection &Section, MCAssembler *A = 0);
+
+ const MCSection &getSection() const { return *Section; }
+
+ unsigned getAlignment() const { return Alignment; }
+ void setAlignment(unsigned Value) { Alignment = Value; }
+
+ bool hasInstructions() const { return HasInstructions; }
+ void setHasInstructions(bool Value) { HasInstructions = Value; }
+
+ unsigned getOrdinal() const { return Ordinal; }
+ void setOrdinal(unsigned Value) { Ordinal = Value; }
+
+ unsigned getLayoutOrder() const { return LayoutOrder; }
+ void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
+
+ /// @name Fragment Access
+ /// @{
+
+ const FragmentListType &getFragmentList() const { return Fragments; }
+ FragmentListType &getFragmentList() { return Fragments; }
+
+ iterator begin() { return Fragments.begin(); }
+ const_iterator begin() const { return Fragments.begin(); }
+
+ iterator end() { return Fragments.end(); }
+ const_iterator end() const { return Fragments.end(); }
+
+ reverse_iterator rbegin() { return Fragments.rbegin(); }
+ const_reverse_iterator rbegin() const { return Fragments.rbegin(); }
+
+ reverse_iterator rend() { return Fragments.rend(); }
+ const_reverse_iterator rend() const { return Fragments.rend(); }
+
+ size_t size() const { return Fragments.size(); }
+
+ bool empty() const { return Fragments.empty(); }
+
+ void dump();
+
+ /// @}
+};
+
+// FIXME: Same concerns as with SectionData.
+class MCSymbolData : public ilist_node<MCSymbolData> {
+public:
+ const MCSymbol *Symbol;
+
+ /// Fragment - The fragment this symbol's value is relative to, if any.
+ MCFragment *Fragment;
+
+ /// Offset - The offset to apply to the fragment address to form this symbol's
+ /// value.
+ uint64_t Offset;
+
+ /// IsExternal - True if this symbol is visible outside this translation
+ /// unit.
+ unsigned IsExternal : 1;
+
+ /// IsPrivateExtern - True if this symbol is private extern.
+ unsigned IsPrivateExtern : 1;
+
+ /// CommonSize - The size of the symbol, if it is 'common', or 0.
+ //
+ // FIXME: Pack this in with other fields? We could put it in offset, since a
+ // common symbol can never get a definition.
+ uint64_t CommonSize;
+
+ /// SymbolSize - An expression describing how to calculate the size of
+ /// a symbol. If a symbol has no size this field will be NULL.
+ const MCExpr *SymbolSize;
+
+ /// CommonAlign - The alignment of the symbol, if it is 'common'.
+ //
+ // FIXME: Pack this in with other fields?
+ unsigned CommonAlign;
+
+ /// Flags - The Flags field is used by object file implementations to store
+ /// additional per symbol information which is not easily classified.
+ uint32_t Flags;
+
+ /// Index - Index field, for use by the object file implementation.
+ uint64_t Index;
+
+public:
+ // Only for use as sentinel.
+ MCSymbolData();
+ MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment, uint64_t _Offset,
+ MCAssembler *A = 0);
+
+ /// @name Accessors
+ /// @{
+
+ const MCSymbol &getSymbol() const { return *Symbol; }
+
+ MCFragment *getFragment() const { return Fragment; }
+ void setFragment(MCFragment *Value) { Fragment = Value; }
+
+ uint64_t getOffset() const { return Offset; }
+ void setOffset(uint64_t Value) { Offset = Value; }
+
+ /// @}
+ /// @name Symbol Attributes
+ /// @{
+
+ bool isExternal() const { return IsExternal; }
+ void setExternal(bool Value) { IsExternal = Value; }
+
+ bool isPrivateExtern() const { return IsPrivateExtern; }
+ void setPrivateExtern(bool Value) { IsPrivateExtern = Value; }
+
+ /// isCommon - Is this a 'common' symbol.
+ bool isCommon() const { return CommonSize != 0; }
+
+ /// setCommon - Mark this symbol as being 'common'.
+ ///
+ /// \param Size - The size of the symbol.
+ /// \param Align - The alignment of the symbol.
+ void setCommon(uint64_t Size, unsigned Align) {
+ CommonSize = Size;
+ CommonAlign = Align;
+ }
+
+ /// getCommonSize - Return the size of a 'common' symbol.
+ uint64_t getCommonSize() const {
+ assert(isCommon() && "Not a 'common' symbol!");
+ return CommonSize;
+ }
+
+ void setSize(const MCExpr *SS) {
+ SymbolSize = SS;
+ }
+
+ const MCExpr *getSize() const {
+ return SymbolSize;
+ }
+
+
+ /// getCommonAlignment - Return the alignment of a 'common' symbol.
+ unsigned getCommonAlignment() const {
+ assert(isCommon() && "Not a 'common' symbol!");
+ return CommonAlign;
+ }
+
+ /// getFlags - Get the (implementation defined) symbol flags.
+ uint32_t getFlags() const { return Flags; }
+
+ /// setFlags - Set the (implementation defined) symbol flags.
+ void setFlags(uint32_t Value) { Flags = Value; }
+
+ /// modifyFlags - Modify the flags via a mask
+ void modifyFlags(uint32_t Value, uint32_t Mask) {
+ Flags = (Flags & ~Mask) | Value;
+ }
+
+ /// getIndex - Get the (implementation defined) index.
+ uint64_t getIndex() const { return Index; }
+
+ /// setIndex - Set the (implementation defined) index.
+ void setIndex(uint64_t Value) { Index = Value; }
+
+ /// @}
+
+ void dump();
+};
+
+// FIXME: This really doesn't belong here. See comments below.
+struct IndirectSymbolData {
+ MCSymbol *Symbol;
+ MCSectionData *SectionData;
+};
+
+// FIXME: Ditto this. Purely so the Streamer and the ObjectWriter can talk
+// to one another.
+struct DataRegionData {
+ // This enum should be kept in sync w/ the mach-o definition in
+ // llvm/Object/MachOFormat.h.
+ enum KindTy { Data = 1, JumpTable8, JumpTable16, JumpTable32 } Kind;
+ MCSymbol *Start;
+ MCSymbol *End;
+};
+
+class MCAssembler {
+ friend class MCAsmLayout;
+
+public:
+ typedef iplist<MCSectionData> SectionDataListType;
+ typedef iplist<MCSymbolData> SymbolDataListType;
+
+ typedef SectionDataListType::const_iterator const_iterator;
+ typedef SectionDataListType::iterator iterator;
+
+ typedef SymbolDataListType::const_iterator const_symbol_iterator;
+ typedef SymbolDataListType::iterator symbol_iterator;
+
+ typedef std::vector<IndirectSymbolData>::const_iterator
+ const_indirect_symbol_iterator;
+ typedef std::vector<IndirectSymbolData>::iterator indirect_symbol_iterator;
+
+ typedef std::vector<DataRegionData>::const_iterator
+ const_data_region_iterator;
+ typedef std::vector<DataRegionData>::iterator data_region_iterator;
+
+private:
+ MCAssembler(const MCAssembler&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCAssembler&) LLVM_DELETED_FUNCTION;
+
+ MCContext &Context;
+
+ MCAsmBackend &Backend;
+
+ MCCodeEmitter &Emitter;
+
+ MCObjectWriter &Writer;
+
+ raw_ostream &OS;
+
+ iplist<MCSectionData> Sections;
+
+ iplist<MCSymbolData> Symbols;
+
+ /// The map of sections to their associated assembler backend data.
+ //
+ // FIXME: Avoid this indirection?
+ DenseMap<const MCSection*, MCSectionData*> SectionMap;
+
+ /// The map of symbols to their associated assembler backend data.
+ //
+ // FIXME: Avoid this indirection?
+ DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap;
+
+ std::vector<IndirectSymbolData> IndirectSymbols;
+
+ std::vector<DataRegionData> DataRegions;
+ /// The set of function symbols for which a .thumb_func directive has
+ /// been seen.
+ //
+ // FIXME: We really would like this in target specific code rather than
+ // here. Maybe when the relocation stuff moves to target specific,
+ // this can go with it? The streamer would need some target specific
+ // refactoring too.
+ SmallPtrSet<const MCSymbol*, 64> ThumbFuncs;
+
+ unsigned RelaxAll : 1;
+ unsigned NoExecStack : 1;
+ unsigned SubsectionsViaSymbols : 1;
+
+private:
+ /// Evaluate a fixup to a relocatable expression and the value which should be
+ /// placed into the fixup.
+ ///
+ /// \param Layout The layout to use for evaluation.
+ /// \param Fixup The fixup to evaluate.
+ /// \param DF The fragment the fixup is inside.
+ /// \param Target [out] On return, the relocatable expression the fixup
+ /// evaluates to.
+ /// \param Value [out] On return, the value of the fixup as currently laid
+ /// out.
+ /// \return Whether the fixup value was fully resolved. This is true if the
+ /// \p Value result is fixed, otherwise the value may change due to
+ /// relocation.
+ bool evaluateFixup(const MCAsmLayout &Layout,
+ const MCFixup &Fixup, const MCFragment *DF,
+ MCValue &Target, uint64_t &Value) const;
+
+ /// Check whether a fixup can be satisfied, or whether it needs to be relaxed
+ /// (increased in size, in order to hold its value correctly).
+ bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCInstFragment *DF,
+ const MCAsmLayout &Layout) const;
+
+ /// Check whether the given fragment needs relaxation.
+ bool fragmentNeedsRelaxation(const MCInstFragment *IF,
+ const MCAsmLayout &Layout) const;
+
+ /// layoutOnce - Perform one layout iteration and return true if any offsets
+ /// were adjusted.
+ bool layoutOnce(MCAsmLayout &Layout);
+
+ bool layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD);
+
+ bool relaxInstruction(MCAsmLayout &Layout, MCInstFragment &IF);
+
+ bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
+
+ bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF);
+ bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
+ MCDwarfCallFrameFragment &DF);
+
+ /// finishLayout - Finalize a layout, including fragment lowering.
+ void finishLayout(MCAsmLayout &Layout);
+
+ uint64_t handleFixup(const MCAsmLayout &Layout,
+ MCFragment &F, const MCFixup &Fixup);
+
+public:
+ /// Compute the effective fragment size assuming it is laid out at the given
+ /// \p SectionAddress and \p FragmentOffset.
+ uint64_t computeFragmentSize(const MCAsmLayout &Layout,
+ const MCFragment &F) const;
+
+ /// Find the symbol which defines the atom containing the given symbol, or
+ /// null if there is no such symbol.
+ const MCSymbolData *getAtom(const MCSymbolData *Symbol) const;
+
+ /// Check whether a particular symbol is visible to the linker and is required
+ /// in the symbol table, or whether it can be discarded by the assembler. This
+ /// also effects whether the assembler treats the label as potentially
+ /// defining a separate atom.
+ bool isSymbolLinkerVisible(const MCSymbol &SD) const;
+
+ /// Emit the section contents using the given object writer.
+ void writeSectionData(const MCSectionData *Section,
+ const MCAsmLayout &Layout) const;
+
+ /// Check whether a given symbol has been flagged with .thumb_func.
+ bool isThumbFunc(const MCSymbol *Func) const {
+ return ThumbFuncs.count(Func);
+ }
+
+ /// Flag a function symbol as the target of a .thumb_func directive.
+ void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); }
+
+public:
+ /// Construct a new assembler instance.
+ ///
+ /// \param OS The stream to output to.
+ //
+ // FIXME: How are we going to parameterize this? Two obvious options are stay
+ // concrete and require clients to pass in a target like object. The other
+ // option is to make this abstract, and have targets provide concrete
+ // implementations as we do with AsmParser.
+ MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
+ MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
+ raw_ostream &OS);
+ ~MCAssembler();
+
+ MCContext &getContext() const { return Context; }
+
+ MCAsmBackend &getBackend() const { return Backend; }
+
+ MCCodeEmitter &getEmitter() const { return Emitter; }
+
+ MCObjectWriter &getWriter() const { return Writer; }
+
+ /// Finish - Do final processing and write the object to the output stream.
+ /// \p Writer is used for custom object writer (as the MCJIT does),
+ /// if not specified it is automatically created from backend.
+ void Finish();
+
+ // FIXME: This does not belong here.
+ bool getSubsectionsViaSymbols() const {
+ return SubsectionsViaSymbols;
+ }
+ void setSubsectionsViaSymbols(bool Value) {
+ SubsectionsViaSymbols = Value;
+ }
+
+ bool getRelaxAll() const { return RelaxAll; }
+ void setRelaxAll(bool Value) { RelaxAll = Value; }
+
+ bool getNoExecStack() const { return NoExecStack; }
+ void setNoExecStack(bool Value) { NoExecStack = Value; }
+
+ /// @name Section List Access
+ /// @{
+
+ const SectionDataListType &getSectionList() const { return Sections; }
+ SectionDataListType &getSectionList() { return Sections; }
+
+ iterator begin() { return Sections.begin(); }
+ const_iterator begin() const { return Sections.begin(); }
+
+ iterator end() { return Sections.end(); }
+ const_iterator end() const { return Sections.end(); }
+
+ size_t size() const { return Sections.size(); }
+
+ /// @}
+ /// @name Symbol List Access
+ /// @{
+
+ const SymbolDataListType &getSymbolList() const { return Symbols; }
+ SymbolDataListType &getSymbolList() { return Symbols; }
+
+ symbol_iterator symbol_begin() { return Symbols.begin(); }
+ const_symbol_iterator symbol_begin() const { return Symbols.begin(); }
+
+ symbol_iterator symbol_end() { return Symbols.end(); }
+ const_symbol_iterator symbol_end() const { return Symbols.end(); }
+
+ size_t symbol_size() const { return Symbols.size(); }
+
+ /// @}
+ /// @name Indirect Symbol List Access
+ /// @{
+
+ // FIXME: This is a total hack, this should not be here. Once things are
+ // factored so that the streamer has direct access to the .o writer, it can
+ // disappear.
+ std::vector<IndirectSymbolData> &getIndirectSymbols() {
+ return IndirectSymbols;
+ }
+
+ indirect_symbol_iterator indirect_symbol_begin() {
+ return IndirectSymbols.begin();
+ }
+ const_indirect_symbol_iterator indirect_symbol_begin() const {
+ return IndirectSymbols.begin();
+ }
+
+ indirect_symbol_iterator indirect_symbol_end() {
+ return IndirectSymbols.end();
+ }
+ const_indirect_symbol_iterator indirect_symbol_end() const {
+ return IndirectSymbols.end();
+ }
+
+ size_t indirect_symbol_size() const { return IndirectSymbols.size(); }
+
+ /// @}
+ /// @name Data Region List Access
+ /// @{
+
+ // FIXME: This is a total hack, this should not be here. Once things are
+ // factored so that the streamer has direct access to the .o writer, it can
+ // disappear.
+ std::vector<DataRegionData> &getDataRegions() {
+ return DataRegions;
+ }
+
+ data_region_iterator data_region_begin() {
+ return DataRegions.begin();
+ }
+ const_data_region_iterator data_region_begin() const {
+ return DataRegions.begin();
+ }
+
+ data_region_iterator data_region_end() {
+ return DataRegions.end();
+ }
+ const_data_region_iterator data_region_end() const {
+ return DataRegions.end();
+ }
+
+ size_t data_region_size() const { return DataRegions.size(); }
+
+ /// @}
+ /// @name Backend Data Access
+ /// @{
+
+ MCSectionData &getSectionData(const MCSection &Section) const {
+ MCSectionData *Entry = SectionMap.lookup(&Section);
+ assert(Entry && "Missing section data!");
+ return *Entry;
+ }
+
+ MCSectionData &getOrCreateSectionData(const MCSection &Section,
+ bool *Created = 0) {
+ MCSectionData *&Entry = SectionMap[&Section];
+
+ if (Created) *Created = !Entry;
+ if (!Entry)
+ Entry = new MCSectionData(Section, this);
+
+ return *Entry;
+ }
+
+ MCSymbolData &getSymbolData(const MCSymbol &Symbol) const {
+ MCSymbolData *Entry = SymbolMap.lookup(&Symbol);
+ assert(Entry && "Missing symbol data!");
+ return *Entry;
+ }
+
+ MCSymbolData &getOrCreateSymbolData(const MCSymbol &Symbol,
+ bool *Created = 0) {
+ MCSymbolData *&Entry = SymbolMap[&Symbol];
+
+ if (Created) *Created = !Entry;
+ if (!Entry)
+ Entry = new MCSymbolData(Symbol, 0, 0, this);
+
+ return *Entry;
+ }
+
+ /// @}
+
+ void dump();
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCAtom.h b/include/llvm/MC/MCAtom.h
new file mode 100644
index 00000000000..682cf7cd76c
--- /dev/null
+++ b/include/llvm/MC/MCAtom.h
@@ -0,0 +1,68 @@
+//===-- llvm/MC/MCAtom.h - MCAtom class ---------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MCAtom class, which is used to
+// represent a contiguous region in a decoded object that is uniformly data or
+// instructions;
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCATOM_H
+#define LLVM_MC_MCATOM_H
+
+#include "llvm/MC/MCInst.h"
+#include "llvm/Support/DataTypes.h"
+#include <vector>
+
+namespace llvm {
+
+class MCModule;
+
+/// MCData - An entry in a data MCAtom.
+// NOTE: This may change to a more complex type in the future.
+typedef uint8_t MCData;
+
+/// MCAtom - Represents a contiguous range of either instructions (a TextAtom)
+/// or data (a DataAtom). Address ranges are expressed as _closed_ intervals.
+class MCAtom {
+ friend class MCModule;
+ typedef enum { TextAtom, DataAtom } AtomType;
+
+ AtomType Type;
+ MCModule *Parent;
+ uint64_t Begin, End;
+
+ std::vector<std::pair<uint64_t, MCInst> > Text;
+ std::vector<MCData> Data;
+
+ // Private constructor - only callable by MCModule
+ MCAtom(AtomType T, MCModule *P, uint64_t B, uint64_t E)
+ : Type(T), Parent(P), Begin(B), End(E) { }
+
+public:
+ bool isTextAtom() { return Type == TextAtom; }
+ bool isDataAtom() { return Type == DataAtom; }
+
+ void addInst(const MCInst &I, uint64_t Address, unsigned Size);
+ void addData(const MCData &D);
+
+ /// split - Splits the atom in two at a given address, which must align with
+ /// and instruction boundary if this is a TextAtom. Returns the newly created
+ /// atom representing the high part of the split.
+ MCAtom *split(uint64_t SplitPt);
+
+ /// truncate - Truncates an atom so that TruncPt is the last byte address
+ /// contained in the atom.
+ void truncate(uint64_t TruncPt);
+};
+
+}
+
+#endif
+
diff --git a/include/llvm/MC/MCCodeEmitter.h b/include/llvm/MC/MCCodeEmitter.h
new file mode 100644
index 00000000000..05748909029
--- /dev/null
+++ b/include/llvm/MC/MCCodeEmitter.h
@@ -0,0 +1,40 @@
+//===-- llvm/MC/MCCodeEmitter.h - Instruction Encoding ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCCODEEMITTER_H
+#define LLVM_MC_MCCODEEMITTER_H
+
+#include "llvm/Support/Compiler.h"
+
+namespace llvm {
+class MCFixup;
+class MCInst;
+class raw_ostream;
+template<typename T> class SmallVectorImpl;
+
+/// MCCodeEmitter - Generic instruction encoding interface.
+class MCCodeEmitter {
+private:
+ MCCodeEmitter(const MCCodeEmitter &) LLVM_DELETED_FUNCTION;
+ void operator=(const MCCodeEmitter &) LLVM_DELETED_FUNCTION;
+protected: // Can only create subclasses.
+ MCCodeEmitter();
+
+public:
+ virtual ~MCCodeEmitter();
+
+ /// EncodeInstruction - Encode the given \p Inst to bytes on the output
+ /// stream \p OS.
+ virtual void EncodeInstruction(const MCInst &Inst, raw_ostream &OS,
+ SmallVectorImpl<MCFixup> &Fixups) const = 0;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCCodeGenInfo.h b/include/llvm/MC/MCCodeGenInfo.h
new file mode 100644
index 00000000000..d1765e1240a
--- /dev/null
+++ b/include/llvm/MC/MCCodeGenInfo.h
@@ -0,0 +1,48 @@
+//===-- llvm/MC/MCCodeGenInfo.h - Target CodeGen Info -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file tracks information about the target which can affect codegen,
+// asm parsing, and asm printing. For example, relocation model.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCCODEGENINFO_H
+#define LLVM_MC_MCCODEGENINFO_H
+
+#include "llvm/Support/CodeGen.h"
+
+namespace llvm {
+
+ class MCCodeGenInfo {
+ /// RelocationModel - Relocation model: static, pic, etc.
+ ///
+ Reloc::Model RelocationModel;
+
+ /// CMModel - Code model.
+ ///
+ CodeModel::Model CMModel;
+
+ /// OptLevel - Optimization level.
+ ///
+ CodeGenOpt::Level OptLevel;
+
+ public:
+ void InitMCCodeGenInfo(Reloc::Model RM = Reloc::Default,
+ CodeModel::Model CM = CodeModel::Default,
+ CodeGenOpt::Level OL = CodeGenOpt::Default);
+
+ Reloc::Model getRelocationModel() const { return RelocationModel; }
+
+ CodeModel::Model getCodeModel() const { return CMModel; }
+
+ CodeGenOpt::Level getOptLevel() const { return OptLevel; }
+ };
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCContext.h b/include/llvm/MC/MCContext.h
new file mode 100644
index 00000000000..5a8830cb66c
--- /dev/null
+++ b/include/llvm/MC/MCContext.h
@@ -0,0 +1,411 @@
+//===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCCONTEXT_H
+#define LLVM_MC_MCCONTEXT_H
+
+#include "llvm/MC/SectionKind.h"
+#include "llvm/MC/MCDwarf.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/Support/Allocator.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/raw_ostream.h"
+#include <vector> // FIXME: Shouldn't be needed.
+
+namespace llvm {
+ class MCAsmInfo;
+ class MCExpr;
+ class MCSection;
+ class MCSymbol;
+ class MCLabel;
+ class MCDwarfFile;
+ class MCDwarfLoc;
+ class MCObjectFileInfo;
+ class MCRegisterInfo;
+ class MCLineSection;
+ class SMLoc;
+ class StringRef;
+ class Twine;
+ class MCSectionMachO;
+ class MCSectionELF;
+
+ /// MCContext - Context object for machine code objects. This class owns all
+ /// of the sections that it creates.
+ ///
+ class MCContext {
+ MCContext(const MCContext&) LLVM_DELETED_FUNCTION;
+ MCContext &operator=(const MCContext&) LLVM_DELETED_FUNCTION;
+ public:
+ typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
+ private:
+ /// The SourceMgr for this object, if any.
+ const SourceMgr *SrcMgr;
+
+ /// The MCAsmInfo for this target.
+ const MCAsmInfo &MAI;
+
+ /// The MCRegisterInfo for this target.
+ const MCRegisterInfo &MRI;
+
+ /// The MCObjectFileInfo for this target.
+ const MCObjectFileInfo *MOFI;
+
+ /// Allocator - Allocator object used for creating machine code objects.
+ ///
+ /// We use a bump pointer allocator to avoid the need to track all allocated
+ /// objects.
+ BumpPtrAllocator Allocator;
+
+ /// Symbols - Bindings of names to symbols.
+ SymbolTable Symbols;
+
+ /// UsedNames - Keeps tracks of names that were used both for used declared
+ /// and artificial symbols.
+ StringMap<bool, BumpPtrAllocator&> UsedNames;
+
+ /// NextUniqueID - The next ID to dole out to an unnamed assembler temporary
+ /// symbol.
+ unsigned NextUniqueID;
+
+ /// Instances of directional local labels.
+ DenseMap<unsigned, MCLabel *> Instances;
+ /// NextInstance() creates the next instance of the directional local label
+ /// for the LocalLabelVal and adds it to the map if needed.
+ unsigned NextInstance(int64_t LocalLabelVal);
+ /// GetInstance() gets the current instance of the directional local label
+ /// for the LocalLabelVal and adds it to the map if needed.
+ unsigned GetInstance(int64_t LocalLabelVal);
+
+ /// The file name of the log file from the environment variable
+ /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
+ /// directive is used or it is an error.
+ char *SecureLogFile;
+ /// The stream that gets written to for the .secure_log_unique directive.
+ raw_ostream *SecureLog;
+ /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
+ /// catch errors if .secure_log_unique appears twice without
+ /// .secure_log_reset appearing between them.
+ bool SecureLogUsed;
+
+ /// The dwarf file and directory tables from the dwarf .file directive.
+ std::vector<MCDwarfFile *> MCDwarfFiles;
+ std::vector<StringRef> MCDwarfDirs;
+
+ /// The current dwarf line information from the last dwarf .loc directive.
+ MCDwarfLoc CurrentDwarfLoc;
+ bool DwarfLocSeen;
+
+ /// Generate dwarf debugging info for assembly source files.
+ bool GenDwarfForAssembly;
+
+ /// The current dwarf file number when generate dwarf debugging info for
+ /// assembly source files.
+ unsigned GenDwarfFileNumber;
+
+ /// The default initial text section that we generate dwarf debugging line
+ /// info for when generating dwarf assembly source files.
+ const MCSection *GenDwarfSection;
+ /// Symbols created for the start and end of this section.
+ MCSymbol *GenDwarfSectionStartSym, *GenDwarfSectionEndSym;
+
+ /// The information gathered from labels that will have dwarf label
+ /// entries when generating dwarf assembly source files.
+ std::vector<const MCGenDwarfLabelEntry *> MCGenDwarfLabelEntries;
+
+ /// The string to embed in the debug information for the compile unit, if
+ /// non-empty.
+ StringRef DwarfDebugFlags;
+
+ /// Honor temporary labels, this is useful for debugging semantic
+ /// differences between temporary and non-temporary labels (primarily on
+ /// Darwin).
+ bool AllowTemporaryLabels;
+
+ /// The dwarf line information from the .loc directives for the sections
+ /// with assembled machine instructions have after seeing .loc directives.
+ DenseMap<const MCSection *, MCLineSection *> MCLineSections;
+ /// We need a deterministic iteration order, so we remember the order
+ /// the elements were added.
+ std::vector<const MCSection *> MCLineSectionOrder;
+
+ void *MachOUniquingMap, *ELFUniquingMap, *COFFUniquingMap;
+
+ MCSymbol *CreateSymbol(StringRef Name);
+
+ public:
+ explicit MCContext(const MCAsmInfo &MAI, const MCRegisterInfo &MRI,
+ const MCObjectFileInfo *MOFI, const SourceMgr *Mgr = 0);
+ ~MCContext();
+
+ const SourceMgr *getSourceManager() const { return SrcMgr; }
+
+ const MCAsmInfo &getAsmInfo() const { return MAI; }
+
+ const MCRegisterInfo &getRegisterInfo() const { return MRI; }
+
+ const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
+
+ void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
+
+ /// @name Symbol Management
+ /// @{
+
+ /// CreateTempSymbol - Create and return a new assembler temporary symbol
+ /// with a unique but unspecified name.
+ MCSymbol *CreateTempSymbol();
+
+ /// getUniqueSymbolID() - Return a unique identifier for use in constructing
+ /// symbol names.
+ unsigned getUniqueSymbolID() { return NextUniqueID++; }
+
+ /// CreateDirectionalLocalSymbol - Create the definition of a directional
+ /// local symbol for numbered label (used for "1:" definitions).
+ MCSymbol *CreateDirectionalLocalSymbol(int64_t LocalLabelVal);
+
+ /// GetDirectionalLocalSymbol - Create and return a directional local
+ /// symbol for numbered label (used for "1b" or 1f" references).
+ MCSymbol *GetDirectionalLocalSymbol(int64_t LocalLabelVal, int bORf);
+
+ /// GetOrCreateSymbol - Lookup the symbol inside with the specified
+ /// @p Name. If it exists, return it. If not, create a forward
+ /// reference and return it.
+ ///
+ /// @param Name - The symbol name, which must be unique across all symbols.
+ MCSymbol *GetOrCreateSymbol(StringRef Name);
+ MCSymbol *GetOrCreateSymbol(const Twine &Name);
+
+ /// LookupSymbol - Get the symbol for \p Name, or null.
+ MCSymbol *LookupSymbol(StringRef Name) const;
+ MCSymbol *LookupSymbol(const Twine &Name) const;
+
+ /// getSymbols - Get a reference for the symbol table for clients that
+ /// want to, for example, iterate over all symbols. 'const' because we
+ /// still want any modifications to the table itself to use the MCContext
+ /// APIs.
+ const SymbolTable &getSymbols() const {
+ return Symbols;
+ }
+
+ /// @}
+
+ /// @name Section Management
+ /// @{
+
+ /// getMachOSection - Return the MCSection for the specified mach-o section.
+ /// This requires the operands to be valid.
+ const MCSectionMachO *getMachOSection(StringRef Segment,
+ StringRef Section,
+ unsigned TypeAndAttributes,
+ unsigned Reserved2,
+ SectionKind K);
+ const MCSectionMachO *getMachOSection(StringRef Segment,
+ StringRef Section,
+ unsigned TypeAndAttributes,
+ SectionKind K) {
+ return getMachOSection(Segment, Section, TypeAndAttributes, 0, K);
+ }
+
+ const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
+ unsigned Flags, SectionKind Kind);
+
+ const MCSectionELF *getELFSection(StringRef Section, unsigned Type,
+ unsigned Flags, SectionKind Kind,
+ unsigned EntrySize, StringRef Group);
+
+ const MCSectionELF *CreateELFGroupSection();
+
+ const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
+ int Selection, SectionKind Kind);
+
+ const MCSection *getCOFFSection(StringRef Section, unsigned Characteristics,
+ SectionKind Kind) {
+ return getCOFFSection (Section, Characteristics, 0, Kind);
+ }
+
+
+ /// @}
+
+ /// @name Dwarf Management
+ /// @{
+
+ /// GetDwarfFile - creates an entry in the dwarf file and directory tables.
+ unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
+ unsigned FileNumber);
+
+ bool isValidDwarfFileNumber(unsigned FileNumber);
+
+ bool hasDwarfFiles() const {
+ return !MCDwarfFiles.empty();
+ }
+
+ const std::vector<MCDwarfFile *> &getMCDwarfFiles() {
+ return MCDwarfFiles;
+ }
+ const std::vector<StringRef> &getMCDwarfDirs() {
+ return MCDwarfDirs;
+ }
+
+ const DenseMap<const MCSection *, MCLineSection *>
+ &getMCLineSections() const {
+ return MCLineSections;
+ }
+ const std::vector<const MCSection *> &getMCLineSectionOrder() const {
+ return MCLineSectionOrder;
+ }
+ void addMCLineSection(const MCSection *Sec, MCLineSection *Line) {
+ MCLineSections[Sec] = Line;
+ MCLineSectionOrder.push_back(Sec);
+ }
+
+ /// setCurrentDwarfLoc - saves the information from the currently parsed
+ /// dwarf .loc directive and sets DwarfLocSeen. When the next instruction
+ /// is assembled an entry in the line number table with this information and
+ /// the address of the instruction will be created.
+ void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
+ unsigned Flags, unsigned Isa,
+ unsigned Discriminator) {
+ CurrentDwarfLoc.setFileNum(FileNum);
+ CurrentDwarfLoc.setLine(Line);
+ CurrentDwarfLoc.setColumn(Column);
+ CurrentDwarfLoc.setFlags(Flags);
+ CurrentDwarfLoc.setIsa(Isa);
+ CurrentDwarfLoc.setDiscriminator(Discriminator);
+ DwarfLocSeen = true;
+ }
+ void ClearDwarfLocSeen() { DwarfLocSeen = false; }
+
+ bool getDwarfLocSeen() { return DwarfLocSeen; }
+ const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
+
+ bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
+ void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
+ unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
+ unsigned nextGenDwarfFileNumber() { return ++GenDwarfFileNumber; }
+ const MCSection *getGenDwarfSection() { return GenDwarfSection; }
+ void setGenDwarfSection(const MCSection *Sec) { GenDwarfSection = Sec; }
+ MCSymbol *getGenDwarfSectionStartSym() { return GenDwarfSectionStartSym; }
+ void setGenDwarfSectionStartSym(MCSymbol *Sym) {
+ GenDwarfSectionStartSym = Sym;
+ }
+ MCSymbol *getGenDwarfSectionEndSym() { return GenDwarfSectionEndSym; }
+ void setGenDwarfSectionEndSym(MCSymbol *Sym) {
+ GenDwarfSectionEndSym = Sym;
+ }
+ const std::vector<const MCGenDwarfLabelEntry *>
+ &getMCGenDwarfLabelEntries() const {
+ return MCGenDwarfLabelEntries;
+ }
+ void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry *E) {
+ MCGenDwarfLabelEntries.push_back(E);
+ }
+
+ void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
+ StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
+
+ /// @}
+
+ char *getSecureLogFile() { return SecureLogFile; }
+ raw_ostream *getSecureLog() { return SecureLog; }
+ bool getSecureLogUsed() { return SecureLogUsed; }
+ void setSecureLog(raw_ostream *Value) {
+ SecureLog = Value;
+ }
+ void setSecureLogUsed(bool Value) {
+ SecureLogUsed = Value;
+ }
+
+ void *Allocate(unsigned Size, unsigned Align = 8) {
+ return Allocator.Allocate(Size, Align);
+ }
+ void Deallocate(void *Ptr) {
+ }
+
+ // Unrecoverable error has occured. Display the best diagnostic we can
+ // and bail via exit(1). For now, most MC backend errors are unrecoverable.
+ // FIXME: We should really do something about that.
+ LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg);
+ };
+
+} // end namespace llvm
+
+// operator new and delete aren't allowed inside namespaces.
+// The throw specifications are mandated by the standard.
+/// @brief Placement new for using the MCContext's allocator.
+///
+/// This placement form of operator new uses the MCContext's allocator for
+/// obtaining memory. It is a non-throwing new, which means that it returns
+/// null on error. (If that is what the allocator does. The current does, so if
+/// this ever changes, this operator will have to be changed, too.)
+/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
+/// @code
+/// // Default alignment (16)
+/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
+/// // Specific alignment
+/// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments);
+/// @endcode
+/// Please note that you cannot use delete on the pointer; it must be
+/// deallocated using an explicit destructor call followed by
+/// @c Context.Deallocate(Ptr).
+///
+/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
+/// @param C The MCContext that provides the allocator.
+/// @param Alignment The alignment of the allocated memory (if the underlying
+/// allocator supports it).
+/// @return The allocated memory. Could be NULL.
+inline void *operator new(size_t Bytes, llvm::MCContext &C,
+ size_t Alignment = 16) throw () {
+ return C.Allocate(Bytes, Alignment);
+}
+/// @brief Placement delete companion to the new above.
+///
+/// This operator is just a companion to the new above. There is no way of
+/// invoking it directly; see the new operator for more details. This operator
+/// is called implicitly by the compiler if a placement new expression using
+/// the MCContext throws in the object constructor.
+inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
+ throw () {
+ C.Deallocate(Ptr);
+}
+
+/// This placement form of operator new[] uses the MCContext's allocator for
+/// obtaining memory. It is a non-throwing new[], which means that it returns
+/// null on error.
+/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
+/// @code
+/// // Default alignment (16)
+/// char *data = new (Context) char[10];
+/// // Specific alignment
+/// char *data = new (Context, 8) char[10];
+/// @endcode
+/// Please note that you cannot use delete on the pointer; it must be
+/// deallocated using an explicit destructor call followed by
+/// @c Context.Deallocate(Ptr).
+///
+/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
+/// @param C The MCContext that provides the allocator.
+/// @param Alignment The alignment of the allocated memory (if the underlying
+/// allocator supports it).
+/// @return The allocated memory. Could be NULL.
+inline void *operator new[](size_t Bytes, llvm::MCContext& C,
+ size_t Alignment = 16) throw () {
+ return C.Allocate(Bytes, Alignment);
+}
+
+/// @brief Placement delete[] companion to the new[] above.
+///
+/// This operator is just a companion to the new[] above. There is no way of
+/// invoking it directly; see the new[] operator for more details. This operator
+/// is called implicitly by the compiler if a placement new[] expression using
+/// the MCContext throws in the object constructor.
+inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {
+ C.Deallocate(Ptr);
+}
+
+#endif
diff --git a/include/llvm/MC/MCDirectives.h b/include/llvm/MC/MCDirectives.h
new file mode 100644
index 00000000000..0461766c2fd
--- /dev/null
+++ b/include/llvm/MC/MCDirectives.h
@@ -0,0 +1,65 @@
+//===- MCDirectives.h - Enums for directives on various targets -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines various enums that represent target-specific directives.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCDIRECTIVES_H
+#define LLVM_MC_MCDIRECTIVES_H
+
+namespace llvm {
+
+enum MCSymbolAttr {
+ MCSA_Invalid = 0, ///< Not a valid directive.
+
+ // Various directives in alphabetical order.
+ MCSA_ELF_TypeFunction, ///< .type _foo, STT_FUNC # aka @function
+ MCSA_ELF_TypeIndFunction, ///< .type _foo, STT_GNU_IFUNC
+ MCSA_ELF_TypeObject, ///< .type _foo, STT_OBJECT # aka @object
+ MCSA_ELF_TypeTLS, ///< .type _foo, STT_TLS # aka @tls_object
+ MCSA_ELF_TypeCommon, ///< .type _foo, STT_COMMON # aka @common
+ MCSA_ELF_TypeNoType, ///< .type _foo, STT_NOTYPE # aka @notype
+ MCSA_ELF_TypeGnuUniqueObject, /// .type _foo, @gnu_unique_object
+ MCSA_Global, ///< .globl
+ MCSA_Hidden, ///< .hidden (ELF)
+ MCSA_IndirectSymbol, ///< .indirect_symbol (MachO)
+ MCSA_Internal, ///< .internal (ELF)
+ MCSA_LazyReference, ///< .lazy_reference (MachO)
+ MCSA_Local, ///< .local (ELF)
+ MCSA_NoDeadStrip, ///< .no_dead_strip (MachO)
+ MCSA_SymbolResolver, ///< .symbol_resolver (MachO)
+ MCSA_PrivateExtern, ///< .private_extern (MachO)
+ MCSA_Protected, ///< .protected (ELF)
+ MCSA_Reference, ///< .reference (MachO)
+ MCSA_Weak, ///< .weak
+ MCSA_WeakDefinition, ///< .weak_definition (MachO)
+ MCSA_WeakReference, ///< .weak_reference (MachO)
+ MCSA_WeakDefAutoPrivate ///< .weak_def_can_be_hidden (MachO)
+};
+
+enum MCAssemblerFlag {
+ MCAF_SyntaxUnified, ///< .syntax (ARM/ELF)
+ MCAF_SubsectionsViaSymbols, ///< .subsections_via_symbols (MachO)
+ MCAF_Code16, ///< .code16 (X86) / .code 16 (ARM)
+ MCAF_Code32, ///< .code32 (X86) / .code 32 (ARM)
+ MCAF_Code64 ///< .code64 (X86)
+};
+
+enum MCDataRegionType {
+ MCDR_DataRegion, ///< .data_region
+ MCDR_DataRegionJT8, ///< .data_region jt8
+ MCDR_DataRegionJT16, ///< .data_region jt16
+ MCDR_DataRegionJT32, ///< .data_region jt32
+ MCDR_DataRegionEnd ///< .end_data_region
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCDisassembler.h b/include/llvm/MC/MCDisassembler.h
new file mode 100644
index 00000000000..53a9ce0a364
--- /dev/null
+++ b/include/llvm/MC/MCDisassembler.h
@@ -0,0 +1,136 @@
+//===-- llvm/MC/MCDisassembler.h - Disassembler interface -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#ifndef MCDISASSEMBLER_H
+#define MCDISASSEMBLER_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm-c/Disassembler.h"
+
+namespace llvm {
+
+class MCInst;
+class MCSubtargetInfo;
+class MemoryObject;
+class raw_ostream;
+class MCContext;
+
+struct EDInstInfo;
+
+/// MCDisassembler - Superclass for all disassemblers. Consumes a memory region
+/// and provides an array of assembly instructions.
+class MCDisassembler {
+public:
+ /// Ternary decode status. Most backends will just use Fail and
+ /// Success, however some have a concept of an instruction with
+ /// understandable semantics but which is architecturally
+ /// incorrect. An example of this is ARM UNPREDICTABLE instructions
+ /// which are disassemblable but cause undefined behaviour.
+ ///
+ /// Because it makes sense to disassemble these instructions, there
+ /// is a "soft fail" failure mode that indicates the MCInst& is
+ /// valid but architecturally incorrect.
+ ///
+ /// The enum numbers are deliberately chosen such that reduction
+ /// from Success->SoftFail ->Fail can be done with a simple
+ /// bitwise-AND:
+ ///
+ /// LEFT & TOP = | Success Unpredictable Fail
+ /// --------------+-----------------------------------
+ /// Success | Success Unpredictable Fail
+ /// Unpredictable | Unpredictable Unpredictable Fail
+ /// Fail | Fail Fail Fail
+ ///
+ /// An easy way of encoding this is as 0b11, 0b01, 0b00 for
+ /// Success, SoftFail, Fail respectively.
+ enum DecodeStatus {
+ Fail = 0,
+ SoftFail = 1,
+ Success = 3
+ };
+
+ /// Constructor - Performs initial setup for the disassembler.
+ MCDisassembler(const MCSubtargetInfo &STI) : GetOpInfo(0), SymbolLookUp(0),
+ DisInfo(0), Ctx(0),
+ STI(STI), CommentStream(0) {}
+
+ virtual ~MCDisassembler();
+
+ /// getInstruction - Returns the disassembly of a single instruction.
+ ///
+ /// @param instr - An MCInst to populate with the contents of the
+ /// instruction.
+ /// @param size - A value to populate with the size of the instruction, or
+ /// the number of bytes consumed while attempting to decode
+ /// an invalid instruction.
+ /// @param region - The memory object to use as a source for machine code.
+ /// @param address - The address, in the memory space of region, of the first
+ /// byte of the instruction.
+ /// @param vStream - The stream to print warnings and diagnostic messages on.
+ /// @param cStream - The stream to print comments and annotations on.
+ /// @return - MCDisassembler::Success if the instruction is valid,
+ /// MCDisassembler::SoftFail if the instruction was
+ /// disassemblable but invalid,
+ /// MCDisassembler::Fail if the instruction was invalid.
+ virtual DecodeStatus getInstruction(MCInst& instr,
+ uint64_t& size,
+ const MemoryObject &region,
+ uint64_t address,
+ raw_ostream &vStream,
+ raw_ostream &cStream) const = 0;
+
+ /// getEDInfo - Returns the enhanced instruction information corresponding to
+ /// the disassembler.
+ ///
+ /// @return - An array of instruction information, with one entry for
+ /// each MCInst opcode this disassembler returns.
+ /// NULL if there is no info for this target.
+ virtual const EDInstInfo *getEDInfo() const { return (EDInstInfo*)0; }
+
+private:
+ //
+ // Hooks for symbolic disassembly via the public 'C' interface.
+ //
+ // The function to get the symbolic information for operands.
+ LLVMOpInfoCallback GetOpInfo;
+ // The function to lookup a symbol name.
+ LLVMSymbolLookupCallback SymbolLookUp;
+ // The pointer to the block of symbolic information for above call back.
+ void *DisInfo;
+ // The assembly context for creating symbols and MCExprs in place of
+ // immediate operands when there is symbolic information.
+ MCContext *Ctx;
+protected:
+ // Subtarget information, for instruction decoding predicates if required.
+ const MCSubtargetInfo &STI;
+
+public:
+ void setupForSymbolicDisassembly(LLVMOpInfoCallback getOpInfo,
+ LLVMSymbolLookupCallback symbolLookUp,
+ void *disInfo,
+ MCContext *ctx) {
+ GetOpInfo = getOpInfo;
+ SymbolLookUp = symbolLookUp;
+ DisInfo = disInfo;
+ Ctx = ctx;
+ }
+ LLVMOpInfoCallback getLLVMOpInfoCallback() const { return GetOpInfo; }
+ LLVMSymbolLookupCallback getLLVMSymbolLookupCallback() const {
+ return SymbolLookUp;
+ }
+ void *getDisInfoBlock() const { return DisInfo; }
+ MCContext *getMCContext() const { return Ctx; }
+
+ // Marked mutable because we cache it inside the disassembler, rather than
+ // having to pass it around as an argument through all the autogenerated code.
+ mutable raw_ostream *CommentStream;
+};
+
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCDwarf.h b/include/llvm/MC/MCDwarf.h
new file mode 100644
index 00000000000..8fc437f3e69
--- /dev/null
+++ b/include/llvm/MC/MCDwarf.h
@@ -0,0 +1,338 @@
+//===- MCDwarf.h - Machine Code Dwarf support -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MCDwarfFile to support the dwarf
+// .file directive and the .loc directive.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCDWARF_H
+#define LLVM_MC_MCDWARF_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/MC/MachineLocation.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/Dwarf.h"
+#include "llvm/Support/Compiler.h"
+#include <vector>
+
+namespace llvm {
+ class MCContext;
+ class MCObjectWriter;
+ class MCSection;
+ class MCStreamer;
+ class MCSymbol;
+ class SourceMgr;
+ class SMLoc;
+
+ /// MCDwarfFile - Instances of this class represent the name of the dwarf
+ /// .file directive and its associated dwarf file number in the MC file,
+ /// and MCDwarfFile's are created and unique'd by the MCContext class where
+ /// the file number for each is its index into the vector of DwarfFiles (note
+ /// index 0 is not used and not a valid dwarf file number).
+ class MCDwarfFile {
+ // Name - the base name of the file without its directory path.
+ // The StringRef references memory allocated in the MCContext.
+ StringRef Name;
+
+ // DirIndex - the index into the list of directory names for this file name.
+ unsigned DirIndex;
+
+ private: // MCContext creates and uniques these.
+ friend class MCContext;
+ MCDwarfFile(StringRef name, unsigned dirIndex)
+ : Name(name), DirIndex(dirIndex) {}
+
+ MCDwarfFile(const MCDwarfFile&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCDwarfFile&) LLVM_DELETED_FUNCTION;
+ public:
+ /// getName - Get the base name of this MCDwarfFile.
+ StringRef getName() const { return Name; }
+
+ /// getDirIndex - Get the dirIndex of this MCDwarfFile.
+ unsigned getDirIndex() const { return DirIndex; }
+
+
+ /// print - Print the value to the stream \p OS.
+ void print(raw_ostream &OS) const;
+
+ /// dump - Print the value to stderr.
+ void dump() const;
+ };
+
+ inline raw_ostream &operator<<(raw_ostream &OS, const MCDwarfFile &DwarfFile){
+ DwarfFile.print(OS);
+ return OS;
+ }
+
+ /// MCDwarfLoc - Instances of this class represent the information from a
+ /// dwarf .loc directive.
+ class MCDwarfLoc {
+ // FileNum - the file number.
+ unsigned FileNum;
+ // Line - the line number.
+ unsigned Line;
+ // Column - the column position.
+ unsigned Column;
+ // Flags (see #define's below)
+ unsigned Flags;
+ // Isa
+ unsigned Isa;
+ // Discriminator
+ unsigned Discriminator;
+
+// Flag that indicates the initial value of the is_stmt_start flag.
+#define DWARF2_LINE_DEFAULT_IS_STMT 1
+
+#define DWARF2_FLAG_IS_STMT (1 << 0)
+#define DWARF2_FLAG_BASIC_BLOCK (1 << 1)
+#define DWARF2_FLAG_PROLOGUE_END (1 << 2)
+#define DWARF2_FLAG_EPILOGUE_BEGIN (1 << 3)
+
+ private: // MCContext manages these
+ friend class MCContext;
+ friend class MCLineEntry;
+ MCDwarfLoc(unsigned fileNum, unsigned line, unsigned column, unsigned flags,
+ unsigned isa, unsigned discriminator)
+ : FileNum(fileNum), Line(line), Column(column), Flags(flags), Isa(isa),
+ Discriminator(discriminator) {}
+
+ // Allow the default copy constructor and assignment operator to be used
+ // for an MCDwarfLoc object.
+
+ public:
+ /// getFileNum - Get the FileNum of this MCDwarfLoc.
+ unsigned getFileNum() const { return FileNum; }
+
+ /// getLine - Get the Line of this MCDwarfLoc.
+ unsigned getLine() const { return Line; }
+
+ /// getColumn - Get the Column of this MCDwarfLoc.
+ unsigned getColumn() const { return Column; }
+
+ /// getFlags - Get the Flags of this MCDwarfLoc.
+ unsigned getFlags() const { return Flags; }
+
+ /// getIsa - Get the Isa of this MCDwarfLoc.
+ unsigned getIsa() const { return Isa; }
+
+ /// getDiscriminator - Get the Discriminator of this MCDwarfLoc.
+ unsigned getDiscriminator() const { return Discriminator; }
+
+ /// setFileNum - Set the FileNum of this MCDwarfLoc.
+ void setFileNum(unsigned fileNum) { FileNum = fileNum; }
+
+ /// setLine - Set the Line of this MCDwarfLoc.
+ void setLine(unsigned line) { Line = line; }
+
+ /// setColumn - Set the Column of this MCDwarfLoc.
+ void setColumn(unsigned column) { Column = column; }
+
+ /// setFlags - Set the Flags of this MCDwarfLoc.
+ void setFlags(unsigned flags) { Flags = flags; }
+
+ /// setIsa - Set the Isa of this MCDwarfLoc.
+ void setIsa(unsigned isa) { Isa = isa; }
+
+ /// setDiscriminator - Set the Discriminator of this MCDwarfLoc.
+ void setDiscriminator(unsigned discriminator) {
+ Discriminator = discriminator;
+ }
+ };
+
+ /// MCLineEntry - Instances of this class represent the line information for
+ /// the dwarf line table entries. Which is created after a machine
+ /// instruction is assembled and uses an address from a temporary label
+ /// created at the current address in the current section and the info from
+ /// the last .loc directive seen as stored in the context.
+ class MCLineEntry : public MCDwarfLoc {
+ MCSymbol *Label;
+
+ private:
+ // Allow the default copy constructor and assignment operator to be used
+ // for an MCLineEntry object.
+
+ public:
+ // Constructor to create an MCLineEntry given a symbol and the dwarf loc.
+ MCLineEntry(MCSymbol *label, const MCDwarfLoc loc) : MCDwarfLoc(loc),
+ Label(label) {}
+
+ MCSymbol *getLabel() const { return Label; }
+
+ // This is called when an instruction is assembled into the specified
+ // section and if there is information from the last .loc directive that
+ // has yet to have a line entry made for it is made.
+ static void Make(MCStreamer *MCOS, const MCSection *Section);
+ };
+
+ /// MCLineSection - Instances of this class represent the line information
+ /// for a section where machine instructions have been assembled after seeing
+ /// .loc directives. This is the information used to build the dwarf line
+ /// table for a section.
+ class MCLineSection {
+
+ private:
+ MCLineSection(const MCLineSection&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCLineSection&) LLVM_DELETED_FUNCTION;
+
+ public:
+ // Constructor to create an MCLineSection with an empty MCLineEntries
+ // vector.
+ MCLineSection() {}
+
+ // addLineEntry - adds an entry to this MCLineSection's line entries
+ void addLineEntry(const MCLineEntry &LineEntry) {
+ MCLineEntries.push_back(LineEntry);
+ }
+
+ typedef std::vector<MCLineEntry> MCLineEntryCollection;
+ typedef MCLineEntryCollection::iterator iterator;
+ typedef MCLineEntryCollection::const_iterator const_iterator;
+
+ private:
+ MCLineEntryCollection MCLineEntries;
+
+ public:
+ const MCLineEntryCollection *getMCLineEntries() const {
+ return &MCLineEntries;
+ }
+ };
+
+ class MCDwarfFileTable {
+ public:
+ //
+ // This emits the Dwarf file and the line tables.
+ //
+ static const MCSymbol *Emit(MCStreamer *MCOS);
+ };
+
+ class MCDwarfLineAddr {
+ public:
+ /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
+ static void Encode(int64_t LineDelta, uint64_t AddrDelta, raw_ostream &OS);
+
+ /// Utility function to emit the encoding to a streamer.
+ static void Emit(MCStreamer *MCOS,
+ int64_t LineDelta,uint64_t AddrDelta);
+
+ /// Utility function to write the encoding to an object writer.
+ static void Write(MCObjectWriter *OW,
+ int64_t LineDelta, uint64_t AddrDelta);
+ };
+
+ class MCGenDwarfInfo {
+ public:
+ //
+ // When generating dwarf for assembly source files this emits the Dwarf
+ // sections.
+ //
+ static void Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol);
+ };
+
+ // When generating dwarf for assembly source files this is the info that is
+ // needed to be gathered for each symbol that will have a dwarf label.
+ class MCGenDwarfLabelEntry {
+ private:
+ // Name of the symbol without a leading underbar, if any.
+ StringRef Name;
+ // The dwarf file number this symbol is in.
+ unsigned FileNumber;
+ // The line number this symbol is at.
+ unsigned LineNumber;
+ // The low_pc for the dwarf label is taken from this symbol.
+ MCSymbol *Label;
+
+ public:
+ MCGenDwarfLabelEntry(StringRef name, unsigned fileNumber,
+ unsigned lineNumber, MCSymbol *label) :
+ Name(name), FileNumber(fileNumber), LineNumber(lineNumber), Label(label){}
+
+ StringRef getName() const { return Name; }
+ unsigned getFileNumber() const { return FileNumber; }
+ unsigned getLineNumber() const { return LineNumber; }
+ MCSymbol *getLabel() const { return Label; }
+
+ // This is called when label is created when we are generating dwarf for
+ // assembly source files.
+ static void Make(MCSymbol *Symbol, MCStreamer *MCOS, SourceMgr &SrcMgr,
+ SMLoc &Loc);
+ };
+
+ class MCCFIInstruction {
+ public:
+ enum OpType { SameValue, RememberState, RestoreState, Move, RelMove, Escape,
+ Restore};
+ private:
+ OpType Operation;
+ MCSymbol *Label;
+ // Move to & from location.
+ MachineLocation Destination;
+ MachineLocation Source;
+ std::vector<char> Values;
+ public:
+ MCCFIInstruction(OpType Op, MCSymbol *L)
+ : Operation(Op), Label(L) {
+ assert(Op == RememberState || Op == RestoreState);
+ }
+ MCCFIInstruction(OpType Op, MCSymbol *L, unsigned Register)
+ : Operation(Op), Label(L), Destination(Register) {
+ assert(Op == SameValue || Op == Restore);
+ }
+ MCCFIInstruction(MCSymbol *L, const MachineLocation &D,
+ const MachineLocation &S)
+ : Operation(Move), Label(L), Destination(D), Source(S) {
+ }
+ MCCFIInstruction(OpType Op, MCSymbol *L, const MachineLocation &D,
+ const MachineLocation &S)
+ : Operation(Op), Label(L), Destination(D), Source(S) {
+ assert(Op == RelMove);
+ }
+ MCCFIInstruction(OpType Op, MCSymbol *L, StringRef Vals)
+ : Operation(Op), Label(L), Values(Vals.begin(), Vals.end()) {
+ assert(Op == Escape);
+ }
+ OpType getOperation() const { return Operation; }
+ MCSymbol *getLabel() const { return Label; }
+ const MachineLocation &getDestination() const { return Destination; }
+ const MachineLocation &getSource() const { return Source; }
+ const StringRef getValues() const {
+ return StringRef(&Values[0], Values.size());
+ }
+ };
+
+ struct MCDwarfFrameInfo {
+ MCDwarfFrameInfo() : Begin(0), End(0), Personality(0), Lsda(0),
+ Function(0), Instructions(), PersonalityEncoding(),
+ LsdaEncoding(0), CompactUnwindEncoding(0),
+ IsSignalFrame(false) {}
+ MCSymbol *Begin;
+ MCSymbol *End;
+ const MCSymbol *Personality;
+ const MCSymbol *Lsda;
+ const MCSymbol *Function;
+ std::vector<MCCFIInstruction> Instructions;
+ unsigned PersonalityEncoding;
+ unsigned LsdaEncoding;
+ uint32_t CompactUnwindEncoding;
+ bool IsSignalFrame;
+ };
+
+ class MCDwarfFrameEmitter {
+ public:
+ //
+ // This emits the frame info section.
+ //
+ static void Emit(MCStreamer &streamer, bool usingCFI,
+ bool isEH);
+ static void EmitAdvanceLoc(MCStreamer &Streamer, uint64_t AddrDelta);
+ static void EncodeAdvanceLoc(uint64_t AddrDelta, raw_ostream &OS);
+ };
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCELFObjectWriter.h b/include/llvm/MC/MCELFObjectWriter.h
new file mode 100644
index 00000000000..abbe188fe88
--- /dev/null
+++ b/include/llvm/MC/MCELFObjectWriter.h
@@ -0,0 +1,152 @@
+//===-- llvm/MC/MCELFObjectWriter.h - ELF Object Writer ---------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCELFOBJECTWRITER_H
+#define LLVM_MC_MCELFOBJECTWRITER_H
+
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ELF.h"
+#include <vector>
+
+namespace llvm {
+class MCAssembler;
+class MCFixup;
+class MCFragment;
+class MCObjectWriter;
+class MCSymbol;
+class MCValue;
+
+/// @name Relocation Data
+/// @{
+
+struct ELFRelocationEntry {
+ // Make these big enough for both 32-bit and 64-bit
+ uint64_t r_offset;
+ int Index;
+ unsigned Type;
+ const MCSymbol *Symbol;
+ uint64_t r_addend;
+ const MCFixup *Fixup;
+
+ ELFRelocationEntry()
+ : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0), Fixup(0) {}
+
+ ELFRelocationEntry(uint64_t RelocOffset, int Idx, unsigned RelType,
+ const MCSymbol *Sym, uint64_t Addend, const MCFixup &Fixup)
+ : r_offset(RelocOffset), Index(Idx), Type(RelType), Symbol(Sym),
+ r_addend(Addend), Fixup(&Fixup) {}
+
+ // Support lexicographic sorting.
+ bool operator<(const ELFRelocationEntry &RE) const {
+ return RE.r_offset < r_offset;
+ }
+};
+
+class MCELFObjectTargetWriter {
+ const uint8_t OSABI;
+ const uint16_t EMachine;
+ const unsigned HasRelocationAddend : 1;
+ const unsigned Is64Bit : 1;
+ const unsigned IsN64 : 1;
+
+protected:
+
+ MCELFObjectTargetWriter(bool Is64Bit_, uint8_t OSABI_,
+ uint16_t EMachine_, bool HasRelocationAddend,
+ bool IsN64=false);
+
+public:
+ static uint8_t getOSABI(Triple::OSType OSType) {
+ switch (OSType) {
+ case Triple::FreeBSD:
+ return ELF::ELFOSABI_FREEBSD;
+ case Triple::Linux:
+ return ELF::ELFOSABI_LINUX;
+ default:
+ return ELF::ELFOSABI_NONE;
+ }
+ }
+
+ virtual ~MCELFObjectTargetWriter() {}
+
+ virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
+ bool IsPCRel, bool IsRelocWithSymbol,
+ int64_t Addend) const = 0;
+ virtual unsigned getEFlags() const;
+ virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
+ const MCValue &Target,
+ const MCFragment &F,
+ const MCFixup &Fixup,
+ bool IsPCRel) const;
+ virtual void adjustFixupOffset(const MCFixup &Fixup,
+ uint64_t &RelocOffset);
+
+ virtual void sortRelocs(const MCAssembler &Asm,
+ std::vector<ELFRelocationEntry> &Relocs);
+
+ /// @name Accessors
+ /// @{
+ uint8_t getOSABI() { return OSABI; }
+ uint16_t getEMachine() { return EMachine; }
+ bool hasRelocationAddend() { return HasRelocationAddend; }
+ bool is64Bit() const { return Is64Bit; }
+ bool isN64() const { return IsN64; }
+ /// @}
+
+ // Instead of changing everyone's API we pack the N64 Type fields
+ // into the existing 32 bit data unsigned.
+#define R_TYPE_SHIFT 0
+#define R_TYPE_MASK 0xffffff00
+#define R_TYPE2_SHIFT 8
+#define R_TYPE2_MASK 0xffff00ff
+#define R_TYPE3_SHIFT 16
+#define R_TYPE3_MASK 0xff00ffff
+#define R_SSYM_SHIFT 24
+#define R_SSYM_MASK 0x00ffffff
+
+ // N64 relocation type accessors
+ unsigned getRType(uint32_t Type) const {
+ return (unsigned)((Type >> R_TYPE_SHIFT) & 0xff);
+ }
+ unsigned getRType2(uint32_t Type) const {
+ return (unsigned)((Type >> R_TYPE2_SHIFT) & 0xff);
+ }
+ unsigned getRType3(uint32_t Type) const {
+ return (unsigned)((Type >> R_TYPE3_SHIFT) & 0xff);
+ }
+ unsigned getRSsym(uint32_t Type) const {
+ return (unsigned)((Type >> R_SSYM_SHIFT) & 0xff);
+ }
+
+ // N64 relocation type setting
+ unsigned setRType(unsigned Value, unsigned Type) const {
+ return ((Type & R_TYPE_MASK) | ((Value & 0xff) << R_TYPE_SHIFT));
+ }
+ unsigned setRType2(unsigned Value, unsigned Type) const {
+ return (Type & R_TYPE2_MASK) | ((Value & 0xff) << R_TYPE2_SHIFT);
+ }
+ unsigned setRType3(unsigned Value, unsigned Type) const {
+ return (Type & R_TYPE3_MASK) | ((Value & 0xff) << R_TYPE3_SHIFT);
+ }
+ unsigned setRSsym(unsigned Value, unsigned Type) const {
+ return (Type & R_SSYM_MASK) | ((Value & 0xff) << R_SSYM_SHIFT);
+ }
+};
+
+/// \brief Construct a new ELF writer instance.
+///
+/// \param MOTW - The target specific ELF writer subclass.
+/// \param OS - The stream to write to.
+/// \returns The constructed object writer.
+MCObjectWriter *createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
+ raw_ostream &OS, bool IsLittleEndian);
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCELFSymbolFlags.h b/include/llvm/MC/MCELFSymbolFlags.h
new file mode 100644
index 00000000000..2225ea07868
--- /dev/null
+++ b/include/llvm/MC/MCELFSymbolFlags.h
@@ -0,0 +1,58 @@
+//===- MCELFSymbolFlags.h - ELF Symbol Flags ----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the SymbolFlags used for the ELF target.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCELFSYMBOLFLAGS_H
+#define LLVM_MC_MCELFSYMBOLFLAGS_H
+
+#include "llvm/Support/ELF.h"
+
+// Because all the symbol flags need to be stored in the MCSymbolData
+// 'flags' variable we need to provide shift constants per flag type.
+
+namespace llvm {
+ enum {
+ ELF_STT_Shift = 0, // Shift value for STT_* flags.
+ ELF_STB_Shift = 4, // Shift value for STB_* flags.
+ ELF_STV_Shift = 8, // Shift value for STV_* flags.
+ ELF_Other_Shift = 10 // Shift value for other flags.
+ };
+
+ enum SymbolFlags {
+ ELF_STB_Local = (ELF::STB_LOCAL << ELF_STB_Shift),
+ ELF_STB_Global = (ELF::STB_GLOBAL << ELF_STB_Shift),
+ ELF_STB_Weak = (ELF::STB_WEAK << ELF_STB_Shift),
+ ELF_STB_Loproc = (ELF::STB_LOPROC << ELF_STB_Shift),
+ ELF_STB_Hiproc = (ELF::STB_HIPROC << ELF_STB_Shift),
+
+ ELF_STT_Notype = (ELF::STT_NOTYPE << ELF_STT_Shift),
+ ELF_STT_Object = (ELF::STT_OBJECT << ELF_STT_Shift),
+ ELF_STT_Func = (ELF::STT_FUNC << ELF_STT_Shift),
+ ELF_STT_Section = (ELF::STT_SECTION << ELF_STT_Shift),
+ ELF_STT_File = (ELF::STT_FILE << ELF_STT_Shift),
+ ELF_STT_Common = (ELF::STT_COMMON << ELF_STT_Shift),
+ ELF_STT_Tls = (ELF::STT_TLS << ELF_STT_Shift),
+ ELF_STT_Loproc = (ELF::STT_LOPROC << ELF_STT_Shift),
+ ELF_STT_Hiproc = (ELF::STT_HIPROC << ELF_STT_Shift),
+
+ ELF_STV_Default = (ELF::STV_DEFAULT << ELF_STV_Shift),
+ ELF_STV_Internal = (ELF::STV_INTERNAL << ELF_STV_Shift),
+ ELF_STV_Hidden = (ELF::STV_HIDDEN << ELF_STV_Shift),
+ ELF_STV_Protected = (ELF::STV_PROTECTED << ELF_STV_Shift),
+
+ ELF_Other_Weakref = (1 << ELF_Other_Shift),
+ ELF_Other_ThumbFunc = (2 << ELF_Other_Shift)
+ };
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCExpr.h b/include/llvm/MC/MCExpr.h
new file mode 100644
index 00000000000..f36db3c05a3
--- /dev/null
+++ b/include/llvm/MC/MCExpr.h
@@ -0,0 +1,469 @@
+//===- MCExpr.h - Assembly Level Expressions --------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCEXPR_H
+#define LLVM_MC_MCEXPR_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+class MCAsmLayout;
+class MCAssembler;
+class MCContext;
+class MCSection;
+class MCSectionData;
+class MCSymbol;
+class MCValue;
+class raw_ostream;
+class StringRef;
+typedef DenseMap<const MCSectionData*, uint64_t> SectionAddrMap;
+
+/// MCExpr - Base class for the full range of assembler expressions which are
+/// needed for parsing.
+class MCExpr {
+public:
+ enum ExprKind {
+ Binary, ///< Binary expressions.
+ Constant, ///< Constant expressions.
+ SymbolRef, ///< References to labels and assigned expressions.
+ Unary, ///< Unary expressions.
+ Target ///< Target specific expression.
+ };
+
+private:
+ ExprKind Kind;
+
+ MCExpr(const MCExpr&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCExpr&) LLVM_DELETED_FUNCTION;
+
+ bool EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
+ const MCAsmLayout *Layout,
+ const SectionAddrMap *Addrs) const;
+protected:
+ explicit MCExpr(ExprKind _Kind) : Kind(_Kind) {}
+
+ bool EvaluateAsRelocatableImpl(MCValue &Res, const MCAssembler *Asm,
+ const MCAsmLayout *Layout,
+ const SectionAddrMap *Addrs,
+ bool InSet) const;
+public:
+ /// @name Accessors
+ /// @{
+
+ ExprKind getKind() const { return Kind; }
+
+ /// @}
+ /// @name Utility Methods
+ /// @{
+
+ void print(raw_ostream &OS) const;
+ void dump() const;
+
+ /// @}
+ /// @name Expression Evaluation
+ /// @{
+
+ /// EvaluateAsAbsolute - Try to evaluate the expression to an absolute value.
+ ///
+ /// @param Res - The absolute value, if evaluation succeeds.
+ /// @param Layout - The assembler layout object to use for evaluating symbol
+ /// values. If not given, then only non-symbolic expressions will be
+ /// evaluated.
+ /// @result - True on success.
+ bool EvaluateAsAbsolute(int64_t &Res, const MCAsmLayout &Layout,
+ const SectionAddrMap &Addrs) const;
+ bool EvaluateAsAbsolute(int64_t &Res) const;
+ bool EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const;
+ bool EvaluateAsAbsolute(int64_t &Res, const MCAsmLayout &Layout) const;
+
+ /// EvaluateAsRelocatable - Try to evaluate the expression to a relocatable
+ /// value, i.e. an expression of the fixed form (a - b + constant).
+ ///
+ /// @param Res - The relocatable value, if evaluation succeeds.
+ /// @param Layout - The assembler layout object to use for evaluating values.
+ /// @result - True on success.
+ bool EvaluateAsRelocatable(MCValue &Res, const MCAsmLayout &Layout) const;
+
+ /// FindAssociatedSection - Find the "associated section" for this expression,
+ /// which is currently defined as the absolute section for constants, or
+ /// otherwise the section associated with the first defined symbol in the
+ /// expression.
+ const MCSection *FindAssociatedSection() const;
+
+ /// @}
+
+ static bool classof(const MCExpr *) { return true; }
+};
+
+inline raw_ostream &operator<<(raw_ostream &OS, const MCExpr &E) {
+ E.print(OS);
+ return OS;
+}
+
+//// MCConstantExpr - Represent a constant integer expression.
+class MCConstantExpr : public MCExpr {
+ int64_t Value;
+
+ explicit MCConstantExpr(int64_t _Value)
+ : MCExpr(MCExpr::Constant), Value(_Value) {}
+
+public:
+ /// @name Construction
+ /// @{
+
+ static const MCConstantExpr *Create(int64_t Value, MCContext &Ctx);
+
+ /// @}
+ /// @name Accessors
+ /// @{
+
+ int64_t getValue() const { return Value; }
+
+ /// @}
+
+ static bool classof(const MCExpr *E) {
+ return E->getKind() == MCExpr::Constant;
+ }
+ static bool classof(const MCConstantExpr *) { return true; }
+};
+
+/// MCSymbolRefExpr - Represent a reference to a symbol from inside an
+/// expression.
+///
+/// A symbol reference in an expression may be a use of a label, a use of an
+/// assembler variable (defined constant), or constitute an implicit definition
+/// of the symbol as external.
+class MCSymbolRefExpr : public MCExpr {
+public:
+ enum VariantKind {
+ VK_None,
+ VK_Invalid,
+
+ VK_GOT,
+ VK_GOTOFF,
+ VK_GOTPCREL,
+ VK_GOTTPOFF,
+ VK_INDNTPOFF,
+ VK_NTPOFF,
+ VK_GOTNTPOFF,
+ VK_PLT,
+ VK_TLSGD,
+ VK_TLSLD,
+ VK_TLSLDM,
+ VK_TPOFF,
+ VK_DTPOFF,
+ VK_TLVP, // Mach-O thread local variable relocation
+ VK_SECREL,
+ // FIXME: We'd really like to use the generic Kinds listed above for these.
+ VK_ARM_PLT, // ARM-style PLT references. i.e., (PLT) instead of @PLT
+ VK_ARM_TLSGD, // ditto for TLSGD, GOT, GOTOFF, TPOFF and GOTTPOFF
+ VK_ARM_GOT,
+ VK_ARM_GOTOFF,
+ VK_ARM_TPOFF,
+ VK_ARM_GOTTPOFF,
+ VK_ARM_TARGET1,
+
+ VK_PPC_TOC, // TOC base
+ VK_PPC_TOC_ENTRY, // TOC entry
+ VK_PPC_DARWIN_HA16, // ha16(symbol)
+ VK_PPC_DARWIN_LO16, // lo16(symbol)
+ VK_PPC_GAS_HA16, // symbol@ha
+ VK_PPC_GAS_LO16, // symbol@l
+ VK_PPC_TPREL16_HA, // symbol@tprel@ha
+ VK_PPC_TPREL16_LO, // symbol@tprel@l
+
+ VK_Mips_GPREL,
+ VK_Mips_GOT_CALL,
+ VK_Mips_GOT16,
+ VK_Mips_GOT,
+ VK_Mips_ABS_HI,
+ VK_Mips_ABS_LO,
+ VK_Mips_TLSGD,
+ VK_Mips_TLSLDM,
+ VK_Mips_DTPREL_HI,
+ VK_Mips_DTPREL_LO,
+ VK_Mips_GOTTPREL,
+ VK_Mips_TPREL_HI,
+ VK_Mips_TPREL_LO,
+ VK_Mips_GPOFF_HI,
+ VK_Mips_GPOFF_LO,
+ VK_Mips_GOT_DISP,
+ VK_Mips_GOT_PAGE,
+ VK_Mips_GOT_OFST,
+ VK_Mips_HIGHER,
+ VK_Mips_HIGHEST
+ };
+
+private:
+ /// The symbol being referenced.
+ const MCSymbol *Symbol;
+
+ /// The symbol reference modifier.
+ const VariantKind Kind;
+
+ explicit MCSymbolRefExpr(const MCSymbol *_Symbol, VariantKind _Kind)
+ : MCExpr(MCExpr::SymbolRef), Symbol(_Symbol), Kind(_Kind) {
+ assert(Symbol);
+ }
+
+public:
+ /// @name Construction
+ /// @{
+
+ static const MCSymbolRefExpr *Create(const MCSymbol *Symbol, MCContext &Ctx) {
+ return MCSymbolRefExpr::Create(Symbol, VK_None, Ctx);
+ }
+
+ static const MCSymbolRefExpr *Create(const MCSymbol *Symbol, VariantKind Kind,
+ MCContext &Ctx);
+ static const MCSymbolRefExpr *Create(StringRef Name, VariantKind Kind,
+ MCContext &Ctx);
+
+ /// @}
+ /// @name Accessors
+ /// @{
+
+ const MCSymbol &getSymbol() const { return *Symbol; }
+
+ VariantKind getKind() const { return Kind; }
+
+ /// @}
+ /// @name Static Utility Functions
+ /// @{
+
+ static StringRef getVariantKindName(VariantKind Kind);
+
+ static VariantKind getVariantKindForName(StringRef Name);
+
+ /// @}
+
+ static bool classof(const MCExpr *E) {
+ return E->getKind() == MCExpr::SymbolRef;
+ }
+ static bool classof(const MCSymbolRefExpr *) { return true; }
+};
+
+/// MCUnaryExpr - Unary assembler expressions.
+class MCUnaryExpr : public MCExpr {
+public:
+ enum Opcode {
+ LNot, ///< Logical negation.
+ Minus, ///< Unary minus.
+ Not, ///< Bitwise negation.
+ Plus ///< Unary plus.
+ };
+
+private:
+ Opcode Op;
+ const MCExpr *Expr;
+
+ MCUnaryExpr(Opcode _Op, const MCExpr *_Expr)
+ : MCExpr(MCExpr::Unary), Op(_Op), Expr(_Expr) {}
+
+public:
+ /// @name Construction
+ /// @{
+
+ static const MCUnaryExpr *Create(Opcode Op, const MCExpr *Expr,
+ MCContext &Ctx);
+ static const MCUnaryExpr *CreateLNot(const MCExpr *Expr, MCContext &Ctx) {
+ return Create(LNot, Expr, Ctx);
+ }
+ static const MCUnaryExpr *CreateMinus(const MCExpr *Expr, MCContext &Ctx) {
+ return Create(Minus, Expr, Ctx);
+ }
+ static const MCUnaryExpr *CreateNot(const MCExpr *Expr, MCContext &Ctx) {
+ return Create(Not, Expr, Ctx);
+ }
+ static const MCUnaryExpr *CreatePlus(const MCExpr *Expr, MCContext &Ctx) {
+ return Create(Plus, Expr, Ctx);
+ }
+
+ /// @}
+ /// @name Accessors
+ /// @{
+
+ /// getOpcode - Get the kind of this unary expression.
+ Opcode getOpcode() const { return Op; }
+
+ /// getSubExpr - Get the child of this unary expression.
+ const MCExpr *getSubExpr() const { return Expr; }
+
+ /// @}
+
+ static bool classof(const MCExpr *E) {
+ return E->getKind() == MCExpr::Unary;
+ }
+ static bool classof(const MCUnaryExpr *) { return true; }
+};
+
+/// MCBinaryExpr - Binary assembler expressions.
+class MCBinaryExpr : public MCExpr {
+public:
+ enum Opcode {
+ Add, ///< Addition.
+ And, ///< Bitwise and.
+ Div, ///< Signed division.
+ EQ, ///< Equality comparison.
+ GT, ///< Signed greater than comparison (result is either 0 or some
+ ///< target-specific non-zero value)
+ GTE, ///< Signed greater than or equal comparison (result is either 0 or
+ ///< some target-specific non-zero value).
+ LAnd, ///< Logical and.
+ LOr, ///< Logical or.
+ LT, ///< Signed less than comparison (result is either 0 or
+ ///< some target-specific non-zero value).
+ LTE, ///< Signed less than or equal comparison (result is either 0 or
+ ///< some target-specific non-zero value).
+ Mod, ///< Signed remainder.
+ Mul, ///< Multiplication.
+ NE, ///< Inequality comparison.
+ Or, ///< Bitwise or.
+ Shl, ///< Shift left.
+ Shr, ///< Shift right (arithmetic or logical, depending on target)
+ Sub, ///< Subtraction.
+ Xor ///< Bitwise exclusive or.
+ };
+
+private:
+ Opcode Op;
+ const MCExpr *LHS, *RHS;
+
+ MCBinaryExpr(Opcode _Op, const MCExpr *_LHS, const MCExpr *_RHS)
+ : MCExpr(MCExpr::Binary), Op(_Op), LHS(_LHS), RHS(_RHS) {}
+
+public:
+ /// @name Construction
+ /// @{
+
+ static const MCBinaryExpr *Create(Opcode Op, const MCExpr *LHS,
+ const MCExpr *RHS, MCContext &Ctx);
+ static const MCBinaryExpr *CreateAdd(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Add, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateAnd(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(And, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateDiv(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Div, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateEQ(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(EQ, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateGT(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(GT, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateGTE(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(GTE, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateLAnd(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(LAnd, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateLOr(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(LOr, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateLT(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(LT, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateLTE(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(LTE, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateMod(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Mod, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateMul(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Mul, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateNE(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(NE, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateOr(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Or, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateShl(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Shl, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateShr(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Shr, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateSub(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Sub, LHS, RHS, Ctx);
+ }
+ static const MCBinaryExpr *CreateXor(const MCExpr *LHS, const MCExpr *RHS,
+ MCContext &Ctx) {
+ return Create(Xor, LHS, RHS, Ctx);
+ }
+
+ /// @}
+ /// @name Accessors
+ /// @{
+
+ /// getOpcode - Get the kind of this binary expression.
+ Opcode getOpcode() const { return Op; }
+
+ /// getLHS - Get the left-hand side expression of the binary operator.
+ const MCExpr *getLHS() const { return LHS; }
+
+ /// getRHS - Get the right-hand side expression of the binary operator.
+ const MCExpr *getRHS() const { return RHS; }
+
+ /// @}
+
+ static bool classof(const MCExpr *E) {
+ return E->getKind() == MCExpr::Binary;
+ }
+ static bool classof(const MCBinaryExpr *) { return true; }
+};
+
+/// MCTargetExpr - This is an extension point for target-specific MCExpr
+/// subclasses to implement.
+///
+/// NOTE: All subclasses are required to have trivial destructors because
+/// MCExprs are bump pointer allocated and not destructed.
+class MCTargetExpr : public MCExpr {
+ virtual void Anchor();
+protected:
+ MCTargetExpr() : MCExpr(Target) {}
+ virtual ~MCTargetExpr() {}
+public:
+
+ virtual void PrintImpl(raw_ostream &OS) const = 0;
+ virtual bool EvaluateAsRelocatableImpl(MCValue &Res,
+ const MCAsmLayout *Layout) const = 0;
+ virtual void AddValueSymbols(MCAssembler *) const = 0;
+ virtual const MCSection *FindAssociatedSection() const = 0;
+
+ static bool classof(const MCExpr *E) {
+ return E->getKind() == MCExpr::Target;
+ }
+ static bool classof(const MCTargetExpr *) { return true; }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCFixedLenDisassembler.h b/include/llvm/MC/MCFixedLenDisassembler.h
new file mode 100644
index 00000000000..22b3c32abde
--- /dev/null
+++ b/include/llvm/MC/MCFixedLenDisassembler.h
@@ -0,0 +1,32 @@
+//===-- llvm/MC/MCFixedLenDisassembler.h - Decoder driver -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+// Fixed length disassembler decoder state machine driver.
+//===----------------------------------------------------------------------===//
+#ifndef MCFIXEDLENDISASSEMBLER_H
+#define MCFIXEDLENDISASSEMBLER_H
+
+namespace llvm {
+
+namespace MCD {
+// Disassembler state machine opcodes.
+enum DecoderOps {
+ OPC_ExtractField = 1, // OPC_ExtractField(uint8_t Start, uint8_t Len)
+ OPC_FilterValue, // OPC_FilterValue(uleb128 Val, uint16_t NumToSkip)
+ OPC_CheckField, // OPC_CheckField(uint8_t Start, uint8_t Len,
+ // uleb128 Val, uint16_t NumToSkip)
+ OPC_CheckPredicate, // OPC_CheckPredicate(uleb128 PIdx, uint16_t NumToSkip)
+ OPC_Decode, // OPC_Decode(uleb128 Opcode, uleb128 DIdx)
+ OPC_SoftFail, // OPC_SoftFail(uleb128 PMask, uleb128 NMask)
+ OPC_Fail // OPC_Fail()
+};
+
+} // namespace MCDecode
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCFixup.h b/include/llvm/MC/MCFixup.h
new file mode 100644
index 00000000000..16e9eb730b4
--- /dev/null
+++ b/include/llvm/MC/MCFixup.h
@@ -0,0 +1,112 @@
+//===-- llvm/MC/MCFixup.h - Instruction Relocation and Patching -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCFIXUP_H
+#define LLVM_MC_MCFIXUP_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/SMLoc.h"
+#include <cassert>
+
+namespace llvm {
+class MCExpr;
+
+/// MCFixupKind - Extensible enumeration to represent the type of a fixup.
+enum MCFixupKind {
+ FK_Data_1 = 0, ///< A one-byte fixup.
+ FK_Data_2, ///< A two-byte fixup.
+ FK_Data_4, ///< A four-byte fixup.
+ FK_Data_8, ///< A eight-byte fixup.
+ FK_PCRel_1, ///< A one-byte pc relative fixup.
+ FK_PCRel_2, ///< A two-byte pc relative fixup.
+ FK_PCRel_4, ///< A four-byte pc relative fixup.
+ FK_PCRel_8, ///< A eight-byte pc relative fixup.
+ FK_GPRel_1, ///< A one-byte gp relative fixup.
+ FK_GPRel_2, ///< A two-byte gp relative fixup.
+ FK_GPRel_4, ///< A four-byte gp relative fixup.
+ FK_GPRel_8, ///< A eight-byte gp relative fixup.
+ FK_SecRel_1, ///< A one-byte section relative fixup.
+ FK_SecRel_2, ///< A two-byte section relative fixup.
+ FK_SecRel_4, ///< A four-byte section relative fixup.
+ FK_SecRel_8, ///< A eight-byte section relative fixup.
+
+ FirstTargetFixupKind = 128,
+
+ // Limit range of target fixups, in case we want to pack more efficiently
+ // later.
+ MaxTargetFixupKind = (1 << 8)
+};
+
+/// MCFixup - Encode information on a single operation to perform on a byte
+/// sequence (e.g., an encoded instruction) which requires assemble- or run-
+/// time patching.
+///
+/// Fixups are used any time the target instruction encoder needs to represent
+/// some value in an instruction which is not yet concrete. The encoder will
+/// encode the instruction assuming the value is 0, and emit a fixup which
+/// communicates to the assembler backend how it should rewrite the encoded
+/// value.
+///
+/// During the process of relaxation, the assembler will apply fixups as
+/// symbolic values become concrete. When relaxation is complete, any remaining
+/// fixups become relocations in the object file (or errors, if the fixup cannot
+/// be encoded on the target).
+class MCFixup {
+ /// The value to put into the fixup location. The exact interpretation of the
+ /// expression is target dependent, usually it will be one of the operands to
+ /// an instruction or an assembler directive.
+ const MCExpr *Value;
+
+ /// The byte index of start of the relocation inside the encoded instruction.
+ uint32_t Offset;
+
+ /// The target dependent kind of fixup item this is. The kind is used to
+ /// determine how the operand value should be encoded into the instruction.
+ unsigned Kind;
+
+ /// The source location which gave rise to the fixup, if any.
+ SMLoc Loc;
+public:
+ static MCFixup Create(uint32_t Offset, const MCExpr *Value,
+ MCFixupKind Kind, SMLoc Loc = SMLoc()) {
+ assert(unsigned(Kind) < MaxTargetFixupKind && "Kind out of range!");
+ MCFixup FI;
+ FI.Value = Value;
+ FI.Offset = Offset;
+ FI.Kind = unsigned(Kind);
+ FI.Loc = Loc;
+ return FI;
+ }
+
+ MCFixupKind getKind() const { return MCFixupKind(Kind); }
+
+ uint32_t getOffset() const { return Offset; }
+ void setOffset(uint32_t Value) { Offset = Value; }
+
+ const MCExpr *getValue() const { return Value; }
+
+ /// getKindForSize - Return the generic fixup kind for a value with the given
+ /// size. It is an error to pass an unsupported size.
+ static MCFixupKind getKindForSize(unsigned Size, bool isPCRel) {
+ switch (Size) {
+ default: llvm_unreachable("Invalid generic fixup size!");
+ case 1: return isPCRel ? FK_PCRel_1 : FK_Data_1;
+ case 2: return isPCRel ? FK_PCRel_2 : FK_Data_2;
+ case 4: return isPCRel ? FK_PCRel_4 : FK_Data_4;
+ case 8: return isPCRel ? FK_PCRel_8 : FK_Data_8;
+ }
+ }
+
+ SMLoc getLoc() const { return Loc; }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCFixupKindInfo.h b/include/llvm/MC/MCFixupKindInfo.h
new file mode 100644
index 00000000000..6979ad5807d
--- /dev/null
+++ b/include/llvm/MC/MCFixupKindInfo.h
@@ -0,0 +1,43 @@
+//===-- llvm/MC/MCFixupKindInfo.h - Fixup Descriptors -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCFIXUPKINDINFO_H
+#define LLVM_MC_MCFIXUPKINDINFO_H
+
+namespace llvm {
+
+/// MCFixupKindInfo - Target independent information on a fixup kind.
+struct MCFixupKindInfo {
+ enum FixupKindFlags {
+ /// Is this fixup kind PCrelative? This is used by the assembler backend to
+ /// evaluate fixup values in a target independent manner when possible.
+ FKF_IsPCRel = (1 << 0),
+
+ /// Should this fixup kind force a 4-byte aligned effective PC value?
+ FKF_IsAlignedDownTo32Bits = (1 << 1)
+ };
+
+ /// A target specific name for the fixup kind. The names will be unique for
+ /// distinct kinds on any given target.
+ const char *Name;
+
+ /// The bit offset to write the relocation into.
+ unsigned TargetOffset;
+
+ /// The number of bits written by this fixup. The bits are assumed to be
+ /// contiguous.
+ unsigned TargetSize;
+
+ /// Flags describing additional information on this fixup kind.
+ unsigned Flags;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCInst.h b/include/llvm/MC/MCInst.h
new file mode 100644
index 00000000000..e91c6a2e8ee
--- /dev/null
+++ b/include/llvm/MC/MCInst.h
@@ -0,0 +1,204 @@
+//===-- llvm/MC/MCInst.h - MCInst class -------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MCInst and MCOperand classes, which
+// is the basic representation used to represent low-level machine code
+// instructions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCINST_H
+#define LLVM_MC_MCINST_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/SMLoc.h"
+
+namespace llvm {
+class raw_ostream;
+class MCAsmInfo;
+class MCInstPrinter;
+class MCExpr;
+class MCInst;
+
+/// MCOperand - Instances of this class represent operands of the MCInst class.
+/// This is a simple discriminated union.
+class MCOperand {
+ enum MachineOperandType {
+ kInvalid, ///< Uninitialized.
+ kRegister, ///< Register operand.
+ kImmediate, ///< Immediate operand.
+ kFPImmediate, ///< Floating-point immediate operand.
+ kExpr, ///< Relocatable immediate operand.
+ kInst ///< Sub-instruction operand.
+ };
+ unsigned char Kind;
+
+ union {
+ unsigned RegVal;
+ int64_t ImmVal;
+ double FPImmVal;
+ const MCExpr *ExprVal;
+ const MCInst *InstVal;
+ };
+public:
+
+ MCOperand() : Kind(kInvalid), FPImmVal(0.0) {}
+
+ bool isValid() const { return Kind != kInvalid; }
+ bool isReg() const { return Kind == kRegister; }
+ bool isImm() const { return Kind == kImmediate; }
+ bool isFPImm() const { return Kind == kFPImmediate; }
+ bool isExpr() const { return Kind == kExpr; }
+ bool isInst() const { return Kind == kInst; }
+
+ /// getReg - Returns the register number.
+ unsigned getReg() const {
+ assert(isReg() && "This is not a register operand!");
+ return RegVal;
+ }
+
+ /// setReg - Set the register number.
+ void setReg(unsigned Reg) {
+ assert(isReg() && "This is not a register operand!");
+ RegVal = Reg;
+ }
+
+ int64_t getImm() const {
+ assert(isImm() && "This is not an immediate");
+ return ImmVal;
+ }
+ void setImm(int64_t Val) {
+ assert(isImm() && "This is not an immediate");
+ ImmVal = Val;
+ }
+
+ double getFPImm() const {
+ assert(isFPImm() && "This is not an FP immediate");
+ return FPImmVal;
+ }
+
+ void setFPImm(double Val) {
+ assert(isFPImm() && "This is not an FP immediate");
+ FPImmVal = Val;
+ }
+
+ const MCExpr *getExpr() const {
+ assert(isExpr() && "This is not an expression");
+ return ExprVal;
+ }
+ void setExpr(const MCExpr *Val) {
+ assert(isExpr() && "This is not an expression");
+ ExprVal = Val;
+ }
+
+ const MCInst *getInst() const {
+ assert(isInst() && "This is not a sub-instruction");
+ return InstVal;
+ }
+ void setInst(const MCInst *Val) {
+ assert(isInst() && "This is not a sub-instruction");
+ InstVal = Val;
+ }
+
+ static MCOperand CreateReg(unsigned Reg) {
+ MCOperand Op;
+ Op.Kind = kRegister;
+ Op.RegVal = Reg;
+ return Op;
+ }
+ static MCOperand CreateImm(int64_t Val) {
+ MCOperand Op;
+ Op.Kind = kImmediate;
+ Op.ImmVal = Val;
+ return Op;
+ }
+ static MCOperand CreateFPImm(double Val) {
+ MCOperand Op;
+ Op.Kind = kFPImmediate;
+ Op.FPImmVal = Val;
+ return Op;
+ }
+ static MCOperand CreateExpr(const MCExpr *Val) {
+ MCOperand Op;
+ Op.Kind = kExpr;
+ Op.ExprVal = Val;
+ return Op;
+ }
+ static MCOperand CreateInst(const MCInst *Val) {
+ MCOperand Op;
+ Op.Kind = kInst;
+ Op.InstVal = Val;
+ return Op;
+ }
+
+ void print(raw_ostream &OS, const MCAsmInfo *MAI) const;
+ void dump() const;
+};
+
+template <> struct isPodLike<MCOperand> { static const bool value = true; };
+
+/// MCInst - Instances of this class represent a single low-level machine
+/// instruction.
+class MCInst {
+ unsigned Opcode;
+ SMLoc Loc;
+ SmallVector<MCOperand, 8> Operands;
+public:
+ MCInst() : Opcode(0) {}
+
+ void setOpcode(unsigned Op) { Opcode = Op; }
+ unsigned getOpcode() const { return Opcode; }
+
+ void setLoc(SMLoc loc) { Loc = loc; }
+ SMLoc getLoc() const { return Loc; }
+
+ const MCOperand &getOperand(unsigned i) const { return Operands[i]; }
+ MCOperand &getOperand(unsigned i) { return Operands[i]; }
+ unsigned getNumOperands() const { return Operands.size(); }
+
+ void addOperand(const MCOperand &Op) {
+ Operands.push_back(Op);
+ }
+
+ void clear() { Operands.clear(); }
+ size_t size() { return Operands.size(); }
+
+ typedef SmallVector<MCOperand, 8>::iterator iterator;
+ iterator begin() { return Operands.begin(); }
+ iterator end() { return Operands.end(); }
+ iterator insert(iterator I, const MCOperand &Op) {
+ return Operands.insert(I, Op);
+ }
+
+ void print(raw_ostream &OS, const MCAsmInfo *MAI) const;
+ void dump() const;
+
+ /// \brief Dump the MCInst as prettily as possible using the additional MC
+ /// structures, if given. Operators are separated by the \p Separator
+ /// string.
+ void dump_pretty(raw_ostream &OS, const MCAsmInfo *MAI = 0,
+ const MCInstPrinter *Printer = 0,
+ StringRef Separator = " ") const;
+};
+
+inline raw_ostream& operator<<(raw_ostream &OS, const MCOperand &MO) {
+ MO.print(OS, 0);
+ return OS;
+}
+
+inline raw_ostream& operator<<(raw_ostream &OS, const MCInst &MI) {
+ MI.print(OS, 0);
+ return OS;
+}
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCInstPrinter.h b/include/llvm/MC/MCInstPrinter.h
new file mode 100644
index 00000000000..3c4f28be7ca
--- /dev/null
+++ b/include/llvm/MC/MCInstPrinter.h
@@ -0,0 +1,66 @@
+//===-- MCInstPrinter.h - Convert an MCInst to target assembly syntax -----===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCINSTPRINTER_H
+#define LLVM_MC_MCINSTPRINTER_H
+
+namespace llvm {
+class MCInst;
+class raw_ostream;
+class MCAsmInfo;
+class MCInstrInfo;
+class MCRegisterInfo;
+class StringRef;
+
+/// MCInstPrinter - This is an instance of a target assembly language printer
+/// that converts an MCInst to valid target assembly syntax.
+class MCInstPrinter {
+protected:
+ /// CommentStream - a stream that comments can be emitted to if desired.
+ /// Each comment must end with a newline. This will be null if verbose
+ /// assembly emission is disable.
+ raw_ostream *CommentStream;
+ const MCAsmInfo &MAI;
+ const MCInstrInfo &MII;
+ const MCRegisterInfo &MRI;
+
+ /// The current set of available features.
+ unsigned AvailableFeatures;
+
+ /// Utility function for printing annotations.
+ void printAnnotation(raw_ostream &OS, StringRef Annot);
+public:
+ MCInstPrinter(const MCAsmInfo &mai, const MCInstrInfo &mii,
+ const MCRegisterInfo &mri)
+ : CommentStream(0), MAI(mai), MII(mii), MRI(mri), AvailableFeatures(0) {}
+
+ virtual ~MCInstPrinter();
+
+ /// setCommentStream - Specify a stream to emit comments to.
+ void setCommentStream(raw_ostream &OS) { CommentStream = &OS; }
+
+ /// printInst - Print the specified MCInst to the specified raw_ostream.
+ ///
+ virtual void printInst(const MCInst *MI, raw_ostream &OS,
+ StringRef Annot) = 0;
+
+ /// getOpcodeName - Return the name of the specified opcode enum (e.g.
+ /// "MOV32ri") or empty if we can't resolve it.
+ StringRef getOpcodeName(unsigned Opcode) const;
+
+ /// printRegName - Print the assembler register name.
+ virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
+
+ unsigned getAvailableFeatures() const { return AvailableFeatures; }
+ void setAvailableFeatures(unsigned Value) { AvailableFeatures = Value; }
+};
+
+} // namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCInstrAnalysis.h b/include/llvm/MC/MCInstrAnalysis.h
new file mode 100644
index 00000000000..acad6336aca
--- /dev/null
+++ b/include/llvm/MC/MCInstrAnalysis.h
@@ -0,0 +1,61 @@
+//===-- llvm/MC/MCInstrAnalysis.h - InstrDesc target hooks ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MCInstrAnalysis class which the MCTargetDescs can
+// derive from to give additional information to MC.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCInstrDesc.h"
+#include "llvm/MC/MCInstrInfo.h"
+
+namespace llvm {
+
+class MCInstrAnalysis {
+protected:
+ friend class Target;
+ const MCInstrInfo *Info;
+
+public:
+ MCInstrAnalysis(const MCInstrInfo *Info) : Info(Info) {}
+
+ virtual ~MCInstrAnalysis() {}
+
+ virtual bool isBranch(const MCInst &Inst) const {
+ return Info->get(Inst.getOpcode()).isBranch();
+ }
+
+ virtual bool isConditionalBranch(const MCInst &Inst) const {
+ return Info->get(Inst.getOpcode()).isConditionalBranch();
+ }
+
+ virtual bool isUnconditionalBranch(const MCInst &Inst) const {
+ return Info->get(Inst.getOpcode()).isUnconditionalBranch();
+ }
+
+ virtual bool isIndirectBranch(const MCInst &Inst) const {
+ return Info->get(Inst.getOpcode()).isIndirectBranch();
+ }
+
+ virtual bool isCall(const MCInst &Inst) const {
+ return Info->get(Inst.getOpcode()).isCall();
+ }
+
+ virtual bool isReturn(const MCInst &Inst) const {
+ return Info->get(Inst.getOpcode()).isReturn();
+ }
+
+ /// evaluateBranch - Given a branch instruction try to get the address the
+ /// branch targets. Otherwise return -1.
+ virtual uint64_t
+ evaluateBranch(const MCInst &Inst, uint64_t Addr, uint64_t Size) const;
+};
+
+}
diff --git a/include/llvm/MC/MCInstrDesc.h b/include/llvm/MC/MCInstrDesc.h
new file mode 100644
index 00000000000..dbf16d87005
--- /dev/null
+++ b/include/llvm/MC/MCInstrDesc.h
@@ -0,0 +1,542 @@
+//===-- llvm/Mc/McInstrDesc.h - Instruction Descriptors -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MCOperandInfo and MCInstrDesc classes, which
+// are used to describe target instructions and their operands.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCINSTRDESC_H
+#define LLVM_MC_MCINSTRDESC_H
+
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// Machine Operand Flags and Description
+//===----------------------------------------------------------------------===//
+
+namespace MCOI {
+ // Operand constraints
+ enum OperandConstraint {
+ TIED_TO = 0, // Must be allocated the same register as.
+ EARLY_CLOBBER // Operand is an early clobber register operand
+ };
+
+ /// OperandFlags - These are flags set on operands, but should be considered
+ /// private, all access should go through the MCOperandInfo accessors.
+ /// See the accessors for a description of what these are.
+ enum OperandFlags {
+ LookupPtrRegClass = 0,
+ Predicate,
+ OptionalDef
+ };
+
+ /// Operand Type - Operands are tagged with one of the values of this enum.
+ enum OperandType {
+ OPERAND_UNKNOWN,
+ OPERAND_IMMEDIATE,
+ OPERAND_REGISTER,
+ OPERAND_MEMORY,
+ OPERAND_PCREL
+ };
+}
+
+/// MCOperandInfo - This holds information about one operand of a machine
+/// instruction, indicating the register class for register operands, etc.
+///
+class MCOperandInfo {
+public:
+ /// RegClass - This specifies the register class enumeration of the operand
+ /// if the operand is a register. If isLookupPtrRegClass is set, then this is
+ /// an index that is passed to TargetRegisterInfo::getPointerRegClass(x) to
+ /// get a dynamic register class.
+ int16_t RegClass;
+
+ /// Flags - These are flags from the MCOI::OperandFlags enum.
+ uint8_t Flags;
+
+ /// OperandType - Information about the type of the operand.
+ uint8_t OperandType;
+
+ /// Lower 16 bits are used to specify which constraints are set. The higher 16
+ /// bits are used to specify the value of constraints (4 bits each).
+ uint32_t Constraints;
+ /// Currently no other information.
+
+ /// isLookupPtrRegClass - Set if this operand is a pointer value and it
+ /// requires a callback to look up its register class.
+ bool isLookupPtrRegClass() const {return Flags&(1 <<MCOI::LookupPtrRegClass);}
+
+ /// isPredicate - Set if this is one of the operands that made up of
+ /// the predicate operand that controls an isPredicable() instruction.
+ bool isPredicate() const { return Flags & (1 << MCOI::Predicate); }
+
+ /// isOptionalDef - Set if this operand is a optional def.
+ ///
+ bool isOptionalDef() const { return Flags & (1 << MCOI::OptionalDef); }
+};
+
+
+//===----------------------------------------------------------------------===//
+// Machine Instruction Flags and Description
+//===----------------------------------------------------------------------===//
+
+/// MCInstrDesc flags - These should be considered private to the
+/// implementation of the MCInstrDesc class. Clients should use the predicate
+/// methods on MCInstrDesc, not use these directly. These all correspond to
+/// bitfields in the MCInstrDesc::Flags field.
+namespace MCID {
+ enum {
+ Variadic = 0,
+ HasOptionalDef,
+ Pseudo,
+ Return,
+ Call,
+ Barrier,
+ Terminator,
+ Branch,
+ IndirectBranch,
+ Compare,
+ MoveImm,
+ Bitcast,
+ Select,
+ DelaySlot,
+ FoldableAsLoad,
+ MayLoad,
+ MayStore,
+ Predicable,
+ NotDuplicable,
+ UnmodeledSideEffects,
+ Commutable,
+ ConvertibleTo3Addr,
+ UsesCustomInserter,
+ HasPostISelHook,
+ Rematerializable,
+ CheapAsAMove,
+ ExtraSrcRegAllocReq,
+ ExtraDefRegAllocReq
+ };
+}
+
+/// MCInstrDesc - Describe properties that are true of each instruction in the
+/// target description file. This captures information about side effects,
+/// register use and many other things. There is one instance of this struct
+/// for each target instruction class, and the MachineInstr class points to
+/// this struct directly to describe itself.
+class MCInstrDesc {
+public:
+ unsigned short Opcode; // The opcode number
+ unsigned short NumOperands; // Num of args (may be more if variable_ops)
+ unsigned short NumDefs; // Num of args that are definitions
+ unsigned short SchedClass; // enum identifying instr sched class
+ unsigned short Size; // Number of bytes in encoding.
+ unsigned Flags; // Flags identifying machine instr class
+ uint64_t TSFlags; // Target Specific Flag values
+ const uint16_t *ImplicitUses; // Registers implicitly read by this instr
+ const uint16_t *ImplicitDefs; // Registers implicitly defined by this instr
+ const MCOperandInfo *OpInfo; // 'NumOperands' entries about operands
+
+ /// getOperandConstraint - Returns the value of the specific constraint if
+ /// it is set. Returns -1 if it is not set.
+ int getOperandConstraint(unsigned OpNum,
+ MCOI::OperandConstraint Constraint) const {
+ if (OpNum < NumOperands &&
+ (OpInfo[OpNum].Constraints & (1 << Constraint))) {
+ unsigned Pos = 16 + Constraint * 4;
+ return (int)(OpInfo[OpNum].Constraints >> Pos) & 0xf;
+ }
+ return -1;
+ }
+
+ /// getOpcode - Return the opcode number for this descriptor.
+ unsigned getOpcode() const {
+ return Opcode;
+ }
+
+ /// getNumOperands - Return the number of declared MachineOperands for this
+ /// MachineInstruction. Note that variadic (isVariadic() returns true)
+ /// instructions may have additional operands at the end of the list, and note
+ /// that the machine instruction may include implicit register def/uses as
+ /// well.
+ unsigned getNumOperands() const {
+ return NumOperands;
+ }
+
+ /// getNumDefs - Return the number of MachineOperands that are register
+ /// definitions. Register definitions always occur at the start of the
+ /// machine operand list. This is the number of "outs" in the .td file,
+ /// and does not include implicit defs.
+ unsigned getNumDefs() const {
+ return NumDefs;
+ }
+
+ /// getFlags - Return flags of this instruction.
+ ///
+ unsigned getFlags() const { return Flags; }
+
+ /// isVariadic - Return true if this instruction can have a variable number of
+ /// operands. In this case, the variable operands will be after the normal
+ /// operands but before the implicit definitions and uses (if any are
+ /// present).
+ bool isVariadic() const {
+ return Flags & (1 << MCID::Variadic);
+ }
+
+ /// hasOptionalDef - Set if this instruction has an optional definition, e.g.
+ /// ARM instructions which can set condition code if 's' bit is set.
+ bool hasOptionalDef() const {
+ return Flags & (1 << MCID::HasOptionalDef);
+ }
+
+ /// isPseudo - Return true if this is a pseudo instruction that doesn't
+ /// correspond to a real machine instruction.
+ ///
+ bool isPseudo() const {
+ return Flags & (1 << MCID::Pseudo);
+ }
+
+ bool isReturn() const {
+ return Flags & (1 << MCID::Return);
+ }
+
+ bool isCall() const {
+ return Flags & (1 << MCID::Call);
+ }
+
+ /// isBarrier - Returns true if the specified instruction stops control flow
+ /// from executing the instruction immediately following it. Examples include
+ /// unconditional branches and return instructions.
+ bool isBarrier() const {
+ return Flags & (1 << MCID::Barrier);
+ }
+
+ /// isTerminator - Returns true if this instruction part of the terminator for
+ /// a basic block. Typically this is things like return and branch
+ /// instructions.
+ ///
+ /// Various passes use this to insert code into the bottom of a basic block,
+ /// but before control flow occurs.
+ bool isTerminator() const {
+ return Flags & (1 << MCID::Terminator);
+ }
+
+ /// isBranch - Returns true if this is a conditional, unconditional, or
+ /// indirect branch. Predicates below can be used to discriminate between
+ /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
+ /// get more information.
+ bool isBranch() const {
+ return Flags & (1 << MCID::Branch);
+ }
+
+ /// isIndirectBranch - Return true if this is an indirect branch, such as a
+ /// branch through a register.
+ bool isIndirectBranch() const {
+ return Flags & (1 << MCID::IndirectBranch);
+ }
+
+ /// isConditionalBranch - Return true if this is a branch which may fall
+ /// through to the next instruction or may transfer control flow to some other
+ /// block. The TargetInstrInfo::AnalyzeBranch method can be used to get more
+ /// information about this branch.
+ bool isConditionalBranch() const {
+ return isBranch() & !isBarrier() & !isIndirectBranch();
+ }
+
+ /// isUnconditionalBranch - Return true if this is a branch which always
+ /// transfers control flow to some other block. The
+ /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
+ /// about this branch.
+ bool isUnconditionalBranch() const {
+ return isBranch() & isBarrier() & !isIndirectBranch();
+ }
+
+ // isPredicable - Return true if this instruction has a predicate operand that
+ // controls execution. It may be set to 'always', or may be set to other
+ /// values. There are various methods in TargetInstrInfo that can be used to
+ /// control and modify the predicate in this instruction.
+ bool isPredicable() const {
+ return Flags & (1 << MCID::Predicable);
+ }
+
+ /// isCompare - Return true if this instruction is a comparison.
+ bool isCompare() const {
+ return Flags & (1 << MCID::Compare);
+ }
+
+ /// isMoveImmediate - Return true if this instruction is a move immediate
+ /// (including conditional moves) instruction.
+ bool isMoveImmediate() const {
+ return Flags & (1 << MCID::MoveImm);
+ }
+
+ /// isBitcast - Return true if this instruction is a bitcast instruction.
+ ///
+ bool isBitcast() const {
+ return Flags & (1 << MCID::Bitcast);
+ }
+
+ /// isSelect - Return true if this is a select instruction.
+ ///
+ bool isSelect() const {
+ return Flags & (1 << MCID::Select);
+ }
+
+ /// isNotDuplicable - Return true if this instruction cannot be safely
+ /// duplicated. For example, if the instruction has a unique labels attached
+ /// to it, duplicating it would cause multiple definition errors.
+ bool isNotDuplicable() const {
+ return Flags & (1 << MCID::NotDuplicable);
+ }
+
+ /// hasDelaySlot - Returns true if the specified instruction has a delay slot
+ /// which must be filled by the code generator.
+ bool hasDelaySlot() const {
+ return Flags & (1 << MCID::DelaySlot);
+ }
+
+ /// canFoldAsLoad - Return true for instructions that can be folded as
+ /// memory operands in other instructions. The most common use for this
+ /// is instructions that are simple loads from memory that don't modify
+ /// the loaded value in any way, but it can also be used for instructions
+ /// that can be expressed as constant-pool loads, such as V_SETALLONES
+ /// on x86, to allow them to be folded when it is beneficial.
+ /// This should only be set on instructions that return a value in their
+ /// only virtual register definition.
+ bool canFoldAsLoad() const {
+ return Flags & (1 << MCID::FoldableAsLoad);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Side Effect Analysis
+ //===--------------------------------------------------------------------===//
+
+ /// mayLoad - Return true if this instruction could possibly read memory.
+ /// Instructions with this flag set are not necessarily simple load
+ /// instructions, they may load a value and modify it, for example.
+ bool mayLoad() const {
+ return Flags & (1 << MCID::MayLoad);
+ }
+
+
+ /// mayStore - Return true if this instruction could possibly modify memory.
+ /// Instructions with this flag set are not necessarily simple store
+ /// instructions, they may store a modified value based on their operands, or
+ /// may not actually modify anything, for example.
+ bool mayStore() const {
+ return Flags & (1 << MCID::MayStore);
+ }
+
+ /// hasUnmodeledSideEffects - Return true if this instruction has side
+ /// effects that are not modeled by other flags. This does not return true
+ /// for instructions whose effects are captured by:
+ ///
+ /// 1. Their operand list and implicit definition/use list. Register use/def
+ /// info is explicit for instructions.
+ /// 2. Memory accesses. Use mayLoad/mayStore.
+ /// 3. Calling, branching, returning: use isCall/isReturn/isBranch.
+ ///
+ /// Examples of side effects would be modifying 'invisible' machine state like
+ /// a control register, flushing a cache, modifying a register invisible to
+ /// LLVM, etc.
+ ///
+ bool hasUnmodeledSideEffects() const {
+ return Flags & (1 << MCID::UnmodeledSideEffects);
+ }
+
+ //===--------------------------------------------------------------------===//
+ // Flags that indicate whether an instruction can be modified by a method.
+ //===--------------------------------------------------------------------===//
+
+ /// isCommutable - Return true if this may be a 2- or 3-address
+ /// instruction (of the form "X = op Y, Z, ..."), which produces the same
+ /// result if Y and Z are exchanged. If this flag is set, then the
+ /// TargetInstrInfo::commuteInstruction method may be used to hack on the
+ /// instruction.
+ ///
+ /// Note that this flag may be set on instructions that are only commutable
+ /// sometimes. In these cases, the call to commuteInstruction will fail.
+ /// Also note that some instructions require non-trivial modification to
+ /// commute them.
+ bool isCommutable() const {
+ return Flags & (1 << MCID::Commutable);
+ }
+
+ /// isConvertibleTo3Addr - Return true if this is a 2-address instruction
+ /// which can be changed into a 3-address instruction if needed. Doing this
+ /// transformation can be profitable in the register allocator, because it
+ /// means that the instruction can use a 2-address form if possible, but
+ /// degrade into a less efficient form if the source and dest register cannot
+ /// be assigned to the same register. For example, this allows the x86
+ /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
+ /// is the same speed as the shift but has bigger code size.
+ ///
+ /// If this returns true, then the target must implement the
+ /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
+ /// is allowed to fail if the transformation isn't valid for this specific
+ /// instruction (e.g. shl reg, 4 on x86).
+ ///
+ bool isConvertibleTo3Addr() const {
+ return Flags & (1 << MCID::ConvertibleTo3Addr);
+ }
+
+ /// usesCustomInsertionHook - Return true if this instruction requires
+ /// custom insertion support when the DAG scheduler is inserting it into a
+ /// machine basic block. If this is true for the instruction, it basically
+ /// means that it is a pseudo instruction used at SelectionDAG time that is
+ /// expanded out into magic code by the target when MachineInstrs are formed.
+ ///
+ /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
+ /// is used to insert this into the MachineBasicBlock.
+ bool usesCustomInsertionHook() const {
+ return Flags & (1 << MCID::UsesCustomInserter);
+ }
+
+ /// hasPostISelHook - Return true if this instruction requires *adjustment*
+ /// after instruction selection by calling a target hook. For example, this
+ /// can be used to fill in ARM 's' optional operand depending on whether
+ /// the conditional flag register is used.
+ bool hasPostISelHook() const {
+ return Flags & (1 << MCID::HasPostISelHook);
+ }
+
+ /// isRematerializable - Returns true if this instruction is a candidate for
+ /// remat. This flag is deprecated, please don't use it anymore. If this
+ /// flag is set, the isReallyTriviallyReMaterializable() method is called to
+ /// verify the instruction is really rematable.
+ bool isRematerializable() const {
+ return Flags & (1 << MCID::Rematerializable);
+ }
+
+ /// isAsCheapAsAMove - Returns true if this instruction has the same cost (or
+ /// less) than a move instruction. This is useful during certain types of
+ /// optimizations (e.g., remat during two-address conversion or machine licm)
+ /// where we would like to remat or hoist the instruction, but not if it costs
+ /// more than moving the instruction into the appropriate register. Note, we
+ /// are not marking copies from and to the same register class with this flag.
+ bool isAsCheapAsAMove() const {
+ return Flags & (1 << MCID::CheapAsAMove);
+ }
+
+ /// hasExtraSrcRegAllocReq - Returns true if this instruction source operands
+ /// have special register allocation requirements that are not captured by the
+ /// operand register classes. e.g. ARM::STRD's two source registers must be an
+ /// even / odd pair, ARM::STM registers have to be in ascending order.
+ /// Post-register allocation passes should not attempt to change allocations
+ /// for sources of instructions with this flag.
+ bool hasExtraSrcRegAllocReq() const {
+ return Flags & (1 << MCID::ExtraSrcRegAllocReq);
+ }
+
+ /// hasExtraDefRegAllocReq - Returns true if this instruction def operands
+ /// have special register allocation requirements that are not captured by the
+ /// operand register classes. e.g. ARM::LDRD's two def registers must be an
+ /// even / odd pair, ARM::LDM registers have to be in ascending order.
+ /// Post-register allocation passes should not attempt to change allocations
+ /// for definitions of instructions with this flag.
+ bool hasExtraDefRegAllocReq() const {
+ return Flags & (1 << MCID::ExtraDefRegAllocReq);
+ }
+
+
+ /// getImplicitUses - Return a list of registers that are potentially
+ /// read by any instance of this machine instruction. For example, on X86,
+ /// the "adc" instruction adds two register operands and adds the carry bit in
+ /// from the flags register. In this case, the instruction is marked as
+ /// implicitly reading the flags. Likewise, the variable shift instruction on
+ /// X86 is marked as implicitly reading the 'CL' register, which it always
+ /// does.
+ ///
+ /// This method returns null if the instruction has no implicit uses.
+ const uint16_t *getImplicitUses() const {
+ return ImplicitUses;
+ }
+
+ /// getNumImplicitUses - Return the number of implicit uses this instruction
+ /// has.
+ unsigned getNumImplicitUses() const {
+ if (ImplicitUses == 0) return 0;
+ unsigned i = 0;
+ for (; ImplicitUses[i]; ++i) /*empty*/;
+ return i;
+ }
+
+ /// getImplicitDefs - Return a list of registers that are potentially
+ /// written by any instance of this machine instruction. For example, on X86,
+ /// many instructions implicitly set the flags register. In this case, they
+ /// are marked as setting the FLAGS. Likewise, many instructions always
+ /// deposit their result in a physical register. For example, the X86 divide
+ /// instruction always deposits the quotient and remainder in the EAX/EDX
+ /// registers. For that instruction, this will return a list containing the
+ /// EAX/EDX/EFLAGS registers.
+ ///
+ /// This method returns null if the instruction has no implicit defs.
+ const uint16_t *getImplicitDefs() const {
+ return ImplicitDefs;
+ }
+
+ /// getNumImplicitDefs - Return the number of implicit defs this instruction
+ /// has.
+ unsigned getNumImplicitDefs() const {
+ if (ImplicitDefs == 0) return 0;
+ unsigned i = 0;
+ for (; ImplicitDefs[i]; ++i) /*empty*/;
+ return i;
+ }
+
+ /// hasImplicitUseOfPhysReg - Return true if this instruction implicitly
+ /// uses the specified physical register.
+ bool hasImplicitUseOfPhysReg(unsigned Reg) const {
+ if (const uint16_t *ImpUses = ImplicitUses)
+ for (; *ImpUses; ++ImpUses)
+ if (*ImpUses == Reg) return true;
+ return false;
+ }
+
+ /// hasImplicitDefOfPhysReg - Return true if this instruction implicitly
+ /// defines the specified physical register.
+ bool hasImplicitDefOfPhysReg(unsigned Reg) const {
+ if (const uint16_t *ImpDefs = ImplicitDefs)
+ for (; *ImpDefs; ++ImpDefs)
+ if (*ImpDefs == Reg) return true;
+ return false;
+ }
+
+ /// getSchedClass - Return the scheduling class for this instruction. The
+ /// scheduling class is an index into the InstrItineraryData table. This
+ /// returns zero if there is no known scheduling information for the
+ /// instruction.
+ ///
+ unsigned getSchedClass() const {
+ return SchedClass;
+ }
+
+ /// getSize - Return the number of bytes in the encoding of this instruction,
+ /// or zero if the encoding size cannot be known from the opcode.
+ unsigned getSize() const {
+ return Size;
+ }
+
+ /// findFirstPredOperandIdx() - Find the index of the first operand in the
+ /// operand list that is used to represent the predicate. It returns -1 if
+ /// none is found.
+ int findFirstPredOperandIdx() const {
+ if (isPredicable()) {
+ for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
+ if (OpInfo[i].isPredicate())
+ return i;
+ }
+ return -1;
+ }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCInstrInfo.h b/include/llvm/MC/MCInstrInfo.h
new file mode 100644
index 00000000000..1d3a36ca7c7
--- /dev/null
+++ b/include/llvm/MC/MCInstrInfo.h
@@ -0,0 +1,62 @@
+//===-- llvm/MC/MCInstrInfo.h - Target Instruction Info ---------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file describes the target machine instruction set.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCINSTRINFO_H
+#define LLVM_MC_MCINSTRINFO_H
+
+#include "llvm/MC/MCInstrDesc.h"
+#include <cassert>
+
+namespace llvm {
+
+//---------------------------------------------------------------------------
+///
+/// MCInstrInfo - Interface to description of machine instruction set
+///
+class MCInstrInfo {
+ const MCInstrDesc *Desc; // Raw array to allow static init'n
+ const unsigned *InstrNameIndices; // Array for name indices in InstrNameData
+ const char *InstrNameData; // Instruction name string pool
+ unsigned NumOpcodes; // Number of entries in the desc array
+
+public:
+ /// InitMCInstrInfo - Initialize MCInstrInfo, called by TableGen
+ /// auto-generated routines. *DO NOT USE*.
+ void InitMCInstrInfo(const MCInstrDesc *D, const unsigned *NI, const char *ND,
+ unsigned NO) {
+ Desc = D;
+ InstrNameIndices = NI;
+ InstrNameData = ND;
+ NumOpcodes = NO;
+ }
+
+ unsigned getNumOpcodes() const { return NumOpcodes; }
+
+ /// get - Return the machine instruction descriptor that corresponds to the
+ /// specified instruction opcode.
+ ///
+ const MCInstrDesc &get(unsigned Opcode) const {
+ assert(Opcode < NumOpcodes && "Invalid opcode!");
+ return Desc[Opcode];
+ }
+
+ /// getName - Returns the name for the instructions with the given opcode.
+ const char *getName(unsigned Opcode) const {
+ assert(Opcode < NumOpcodes && "Invalid opcode!");
+ return &InstrNameData[InstrNameIndices[Opcode]];
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCInstrItineraries.h b/include/llvm/MC/MCInstrItineraries.h
new file mode 100644
index 00000000000..65d1559ac66
--- /dev/null
+++ b/include/llvm/MC/MCInstrItineraries.h
@@ -0,0 +1,257 @@
+//===-- llvm/MC/MCInstrItineraries.h - Scheduling ---------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file describes the structures used for instruction
+// itineraries, stages, and operand reads/writes. This is used by
+// schedulers to determine instruction stages and latencies.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCINSTRITINERARIES_H
+#define LLVM_MC_MCINSTRITINERARIES_H
+
+#include "llvm/MC/MCSchedule.h"
+#include <algorithm>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+/// Instruction stage - These values represent a non-pipelined step in
+/// the execution of an instruction. Cycles represents the number of
+/// discrete time slots needed to complete the stage. Units represent
+/// the choice of functional units that can be used to complete the
+/// stage. Eg. IntUnit1, IntUnit2. NextCycles indicates how many
+/// cycles should elapse from the start of this stage to the start of
+/// the next stage in the itinerary. A value of -1 indicates that the
+/// next stage should start immediately after the current one.
+/// For example:
+///
+/// { 1, x, -1 }
+/// indicates that the stage occupies FU x for 1 cycle and that
+/// the next stage starts immediately after this one.
+///
+/// { 2, x|y, 1 }
+/// indicates that the stage occupies either FU x or FU y for 2
+/// consecuative cycles and that the next stage starts one cycle
+/// after this stage starts. That is, the stage requirements
+/// overlap in time.
+///
+/// { 1, x, 0 }
+/// indicates that the stage occupies FU x for 1 cycle and that
+/// the next stage starts in this same cycle. This can be used to
+/// indicate that the instruction requires multiple stages at the
+/// same time.
+///
+/// FU reservation can be of two different kinds:
+/// - FUs which instruction actually requires
+/// - FUs which instruction just reserves. Reserved unit is not available for
+/// execution of other instruction. However, several instructions can reserve
+/// the same unit several times.
+/// Such two types of units reservation is used to model instruction domain
+/// change stalls, FUs using the same resource (e.g. same register file), etc.
+
+struct InstrStage {
+ enum ReservationKinds {
+ Required = 0,
+ Reserved = 1
+ };
+
+ unsigned Cycles_; ///< Length of stage in machine cycles
+ unsigned Units_; ///< Choice of functional units
+ int NextCycles_; ///< Number of machine cycles to next stage
+ ReservationKinds Kind_; ///< Kind of the FU reservation
+
+ /// getCycles - returns the number of cycles the stage is occupied
+ unsigned getCycles() const {
+ return Cycles_;
+ }
+
+ /// getUnits - returns the choice of FUs
+ unsigned getUnits() const {
+ return Units_;
+ }
+
+ ReservationKinds getReservationKind() const {
+ return Kind_;
+ }
+
+ /// getNextCycles - returns the number of cycles from the start of
+ /// this stage to the start of the next stage in the itinerary
+ unsigned getNextCycles() const {
+ return (NextCycles_ >= 0) ? (unsigned)NextCycles_ : Cycles_;
+ }
+};
+
+
+//===----------------------------------------------------------------------===//
+/// Instruction itinerary - An itinerary represents the scheduling
+/// information for an instruction. This includes a set of stages
+/// occupies by the instruction, and the pipeline cycle in which
+/// operands are read and written.
+///
+struct InstrItinerary {
+ int NumMicroOps; ///< # of micro-ops, -1 means it's variable
+ unsigned FirstStage; ///< Index of first stage in itinerary
+ unsigned LastStage; ///< Index of last + 1 stage in itinerary
+ unsigned FirstOperandCycle; ///< Index of first operand rd/wr
+ unsigned LastOperandCycle; ///< Index of last + 1 operand rd/wr
+};
+
+
+//===----------------------------------------------------------------------===//
+/// Instruction itinerary Data - Itinerary data supplied by a subtarget to be
+/// used by a target.
+///
+class InstrItineraryData {
+public:
+ const MCSchedModel *SchedModel; ///< Basic machine properties.
+ const InstrStage *Stages; ///< Array of stages selected
+ const unsigned *OperandCycles; ///< Array of operand cycles selected
+ const unsigned *Forwardings; ///< Array of pipeline forwarding pathes
+ const InstrItinerary *Itineraries; ///< Array of itineraries selected
+
+ /// Ctors.
+ ///
+ InstrItineraryData() : SchedModel(&MCSchedModel::DefaultSchedModel),
+ Stages(0), OperandCycles(0),
+ Forwardings(0), Itineraries(0) {}
+
+ InstrItineraryData(const MCSchedModel *SM, const InstrStage *S,
+ const unsigned *OS, const unsigned *F)
+ : SchedModel(SM), Stages(S), OperandCycles(OS), Forwardings(F),
+ Itineraries(SchedModel->InstrItineraries) {}
+
+ /// isEmpty - Returns true if there are no itineraries.
+ ///
+ bool isEmpty() const { return Itineraries == 0; }
+
+ /// isEndMarker - Returns true if the index is for the end marker
+ /// itinerary.
+ ///
+ bool isEndMarker(unsigned ItinClassIndx) const {
+ return ((Itineraries[ItinClassIndx].FirstStage == ~0U) &&
+ (Itineraries[ItinClassIndx].LastStage == ~0U));
+ }
+
+ /// beginStage - Return the first stage of the itinerary.
+ ///
+ const InstrStage *beginStage(unsigned ItinClassIndx) const {
+ unsigned StageIdx = Itineraries[ItinClassIndx].FirstStage;
+ return Stages + StageIdx;
+ }
+
+ /// endStage - Return the last+1 stage of the itinerary.
+ ///
+ const InstrStage *endStage(unsigned ItinClassIndx) const {
+ unsigned StageIdx = Itineraries[ItinClassIndx].LastStage;
+ return Stages + StageIdx;
+ }
+
+ /// getStageLatency - Return the total stage latency of the given
+ /// class. The latency is the maximum completion time for any stage
+ /// in the itinerary.
+ ///
+ /// InstrStages override the itinerary's MinLatency property. In fact, if the
+ /// stage latencies, which may be zero, are less than MinLatency,
+ /// getStageLatency returns a value less than MinLatency.
+ ///
+ /// If no stages exist, MinLatency is used. If MinLatency is invalid (<0),
+ /// then it defaults to one cycle.
+ unsigned getStageLatency(unsigned ItinClassIndx) const {
+ // If the target doesn't provide itinerary information, use a simple
+ // non-zero default value for all instructions.
+ if (isEmpty())
+ return SchedModel->MinLatency < 0 ? 1 : SchedModel->MinLatency;
+
+ // Calculate the maximum completion time for any stage.
+ unsigned Latency = 0, StartCycle = 0;
+ for (const InstrStage *IS = beginStage(ItinClassIndx),
+ *E = endStage(ItinClassIndx); IS != E; ++IS) {
+ Latency = std::max(Latency, StartCycle + IS->getCycles());
+ StartCycle += IS->getNextCycles();
+ }
+
+ return Latency;
+ }
+
+ /// getOperandCycle - Return the cycle for the given class and
+ /// operand. Return -1 if no cycle is specified for the operand.
+ ///
+ int getOperandCycle(unsigned ItinClassIndx, unsigned OperandIdx) const {
+ if (isEmpty())
+ return -1;
+
+ unsigned FirstIdx = Itineraries[ItinClassIndx].FirstOperandCycle;
+ unsigned LastIdx = Itineraries[ItinClassIndx].LastOperandCycle;
+ if ((FirstIdx + OperandIdx) >= LastIdx)
+ return -1;
+
+ return (int)OperandCycles[FirstIdx + OperandIdx];
+ }
+
+ /// hasPipelineForwarding - Return true if there is a pipeline forwarding
+ /// between instructions of itinerary classes DefClass and UseClasses so that
+ /// value produced by an instruction of itinerary class DefClass, operand
+ /// index DefIdx can be bypassed when it's read by an instruction of
+ /// itinerary class UseClass, operand index UseIdx.
+ bool hasPipelineForwarding(unsigned DefClass, unsigned DefIdx,
+ unsigned UseClass, unsigned UseIdx) const {
+ unsigned FirstDefIdx = Itineraries[DefClass].FirstOperandCycle;
+ unsigned LastDefIdx = Itineraries[DefClass].LastOperandCycle;
+ if ((FirstDefIdx + DefIdx) >= LastDefIdx)
+ return false;
+ if (Forwardings[FirstDefIdx + DefIdx] == 0)
+ return false;
+
+ unsigned FirstUseIdx = Itineraries[UseClass].FirstOperandCycle;
+ unsigned LastUseIdx = Itineraries[UseClass].LastOperandCycle;
+ if ((FirstUseIdx + UseIdx) >= LastUseIdx)
+ return false;
+
+ return Forwardings[FirstDefIdx + DefIdx] ==
+ Forwardings[FirstUseIdx + UseIdx];
+ }
+
+ /// getOperandLatency - Compute and return the use operand latency of a given
+ /// itinerary class and operand index if the value is produced by an
+ /// instruction of the specified itinerary class and def operand index.
+ int getOperandLatency(unsigned DefClass, unsigned DefIdx,
+ unsigned UseClass, unsigned UseIdx) const {
+ if (isEmpty())
+ return -1;
+
+ int DefCycle = getOperandCycle(DefClass, DefIdx);
+ if (DefCycle == -1)
+ return -1;
+
+ int UseCycle = getOperandCycle(UseClass, UseIdx);
+ if (UseCycle == -1)
+ return -1;
+
+ UseCycle = DefCycle - UseCycle + 1;
+ if (UseCycle > 0 &&
+ hasPipelineForwarding(DefClass, DefIdx, UseClass, UseIdx))
+ // FIXME: This assumes one cycle benefit for every pipeline forwarding.
+ --UseCycle;
+ return UseCycle;
+ }
+
+ /// getNumMicroOps - Return the number of micro-ops that the given class
+ /// decodes to. Return -1 for classes that require dynamic lookup via
+ /// TargetInstrInfo.
+ int getNumMicroOps(unsigned ItinClassIndx) const {
+ if (isEmpty())
+ return 1;
+ return Itineraries[ItinClassIndx].NumMicroOps;
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCLabel.h b/include/llvm/MC/MCLabel.h
new file mode 100644
index 00000000000..f531de8b40d
--- /dev/null
+++ b/include/llvm/MC/MCLabel.h
@@ -0,0 +1,58 @@
+//===- MCLabel.h - Machine Code Directional Local Labels --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MCLabel class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCLABEL_H
+#define LLVM_MC_MCLABEL_H
+
+#include "llvm/Support/Compiler.h"
+
+namespace llvm {
+ class MCContext;
+ class raw_ostream;
+
+ /// MCLabel - Instances of this class represent a label name in the MC file,
+ /// and MCLabel are created and unique'd by the MCContext class. MCLabel
+ /// should only be constructed for valid instances in the object file.
+ class MCLabel {
+ // Instance - the instance number of this Directional Local Label
+ unsigned Instance;
+
+ private: // MCContext creates and uniques these.
+ friend class MCContext;
+ MCLabel(unsigned instance)
+ : Instance(instance) {}
+
+ MCLabel(const MCLabel&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCLabel&) LLVM_DELETED_FUNCTION;
+ public:
+ /// getInstance - Get the current instance of this Directional Local Label.
+ unsigned getInstance() const { return Instance; }
+
+ /// incInstance - Increment the current instance of this Directional Local
+ /// Label.
+ unsigned incInstance() { return ++Instance; }
+
+ /// print - Print the value to the stream \p OS.
+ void print(raw_ostream &OS) const;
+
+ /// dump - Print the value to stderr.
+ void dump() const;
+ };
+
+ inline raw_ostream &operator<<(raw_ostream &OS, const MCLabel &Label) {
+ Label.print(OS);
+ return OS;
+ }
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCMachOSymbolFlags.h b/include/llvm/MC/MCMachOSymbolFlags.h
new file mode 100644
index 00000000000..696436dffa6
--- /dev/null
+++ b/include/llvm/MC/MCMachOSymbolFlags.h
@@ -0,0 +1,46 @@
+//===- MCMachOSymbolFlags.h - MachO Symbol Flags ----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the SymbolFlags used for the MachO target.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCMACHOSYMBOLFLAGS_H
+#define LLVM_MC_MCMACHOSYMBOLFLAGS_H
+
+// These flags are mostly used in MCMachOStreamer.cpp but also needed in
+// MachObjectWriter.cpp to test for Weak Definitions of symbols to emit
+// the correct relocation information.
+
+namespace llvm {
+ /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest
+ /// 16 bits of the implementation defined flags.
+ enum SymbolFlags { // See <mach-o/nlist.h>.
+ SF_DescFlagsMask = 0xFFFF,
+
+ // Reference type flags.
+ SF_ReferenceTypeMask = 0x0007,
+ SF_ReferenceTypeUndefinedNonLazy = 0x0000,
+ SF_ReferenceTypeUndefinedLazy = 0x0001,
+ SF_ReferenceTypeDefined = 0x0002,
+ SF_ReferenceTypePrivateDefined = 0x0003,
+ SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004,
+ SF_ReferenceTypePrivateUndefinedLazy = 0x0005,
+
+ // Other 'desc' flags.
+ SF_ThumbFunc = 0x0008,
+ SF_NoDeadStrip = 0x0020,
+ SF_WeakReference = 0x0040,
+ SF_WeakDefinition = 0x0080,
+ SF_SymbolResolver = 0x0100
+ };
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCMachObjectWriter.h b/include/llvm/MC/MCMachObjectWriter.h
new file mode 100644
index 00000000000..efaabfb9e88
--- /dev/null
+++ b/include/llvm/MC/MCMachObjectWriter.h
@@ -0,0 +1,262 @@
+//===-- llvm/MC/MCMachObjectWriter.h - Mach Object Writer -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCMACHOBJECTWRITER_H
+#define LLVM_MC_MCMACHOBJECTWRITER_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCObjectWriter.h"
+#include "llvm/Object/MachOFormat.h"
+#include "llvm/Support/DataTypes.h"
+#include <vector>
+
+namespace llvm {
+
+class MCSectionData;
+class MachObjectWriter;
+
+class MCMachObjectTargetWriter {
+ const unsigned Is64Bit : 1;
+ const uint32_t CPUType;
+ const uint32_t CPUSubtype;
+ // FIXME: Remove this, we should just always use it once we no longer care
+ // about Darwin 'as' compatibility.
+ const unsigned UseAggressiveSymbolFolding : 1;
+ unsigned LocalDifference_RIT;
+
+protected:
+ MCMachObjectTargetWriter(bool Is64Bit_, uint32_t CPUType_,
+ uint32_t CPUSubtype_,
+ bool UseAggressiveSymbolFolding_ = false);
+
+ void setLocalDifferenceRelocationType(unsigned Type) {
+ LocalDifference_RIT = Type;
+ }
+
+public:
+ virtual ~MCMachObjectTargetWriter();
+
+ /// @name Accessors
+ /// @{
+
+ bool is64Bit() const { return Is64Bit; }
+ bool useAggressiveSymbolFolding() const { return UseAggressiveSymbolFolding; }
+ uint32_t getCPUType() const { return CPUType; }
+ uint32_t getCPUSubtype() const { return CPUSubtype; }
+ unsigned getLocalDifferenceRelocationType() const {
+ return LocalDifference_RIT;
+ }
+
+ /// @}
+
+ /// @name API
+ /// @{
+
+ virtual void RecordRelocation(MachObjectWriter *Writer,
+ const MCAssembler &Asm,
+ const MCAsmLayout &Layout,
+ const MCFragment *Fragment,
+ const MCFixup &Fixup,
+ MCValue Target,
+ uint64_t &FixedValue) = 0;
+
+ /// @}
+};
+
+class MachObjectWriter : public MCObjectWriter {
+ /// MachSymbolData - Helper struct for containing some precomputed information
+ /// on symbols.
+ struct MachSymbolData {
+ MCSymbolData *SymbolData;
+ uint64_t StringIndex;
+ uint8_t SectionIndex;
+
+ // Support lexicographic sorting.
+ bool operator<(const MachSymbolData &RHS) const;
+ };
+
+ /// The target specific Mach-O writer instance.
+ llvm::OwningPtr<MCMachObjectTargetWriter> TargetObjectWriter;
+
+ /// @name Relocation Data
+ /// @{
+
+ llvm::DenseMap<const MCSectionData*,
+ std::vector<object::macho::RelocationEntry> > Relocations;
+ llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
+
+ /// @}
+ /// @name Symbol Table Data
+ /// @{
+
+ SmallString<256> StringTable;
+ std::vector<MachSymbolData> LocalSymbolData;
+ std::vector<MachSymbolData> ExternalSymbolData;
+ std::vector<MachSymbolData> UndefinedSymbolData;
+
+ /// @}
+
+public:
+ MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_ostream &_OS,
+ bool _IsLittleEndian)
+ : MCObjectWriter(_OS, _IsLittleEndian), TargetObjectWriter(MOTW) {
+ }
+
+ /// @name Utility Methods
+ /// @{
+
+ bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
+
+ SectionAddrMap SectionAddress;
+
+ SectionAddrMap &getSectionAddressMap() { return SectionAddress; }
+
+ uint64_t getSectionAddress(const MCSectionData* SD) const {
+ return SectionAddress.lookup(SD);
+ }
+ uint64_t getSymbolAddress(const MCSymbolData* SD,
+ const MCAsmLayout &Layout) const;
+
+ uint64_t getFragmentAddress(const MCFragment *Fragment,
+ const MCAsmLayout &Layout) const;
+
+ uint64_t getPaddingSize(const MCSectionData *SD,
+ const MCAsmLayout &Layout) const;
+
+ bool doesSymbolRequireExternRelocation(const MCSymbolData *SD);
+
+ /// @}
+
+ /// @name Target Writer Proxy Accessors
+ /// @{
+
+ bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
+ bool isARM() const {
+ uint32_t CPUType = TargetObjectWriter->getCPUType() &
+ ~object::mach::CTFM_ArchMask;
+ return CPUType == object::mach::CTM_ARM;
+ }
+
+ /// @}
+
+ void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
+ bool SubsectionsViaSymbols);
+
+ /// WriteSegmentLoadCommand - Write a segment load command.
+ ///
+ /// \param NumSections The number of sections in this segment.
+ /// \param SectionDataSize The total size of the sections.
+ void WriteSegmentLoadCommand(unsigned NumSections,
+ uint64_t VMSize,
+ uint64_t SectionDataStartOffset,
+ uint64_t SectionDataSize);
+
+ void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
+ const MCSectionData &SD, uint64_t FileOffset,
+ uint64_t RelocationsStart, unsigned NumRelocations);
+
+ void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
+ uint32_t StringTableOffset,
+ uint32_t StringTableSize);
+
+ void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
+ uint32_t NumLocalSymbols,
+ uint32_t FirstExternalSymbol,
+ uint32_t NumExternalSymbols,
+ uint32_t FirstUndefinedSymbol,
+ uint32_t NumUndefinedSymbols,
+ uint32_t IndirectSymbolOffset,
+ uint32_t NumIndirectSymbols);
+
+ void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout);
+
+ void WriteLinkeditLoadCommand(uint32_t Type, uint32_t DataOffset,
+ uint32_t DataSize);
+
+ // FIXME: We really need to improve the relocation validation. Basically, we
+ // want to implement a separate computation which evaluates the relocation
+ // entry as the linker would, and verifies that the resultant fixup value is
+ // exactly what the encoder wanted. This will catch several classes of
+ // problems:
+ //
+ // - Relocation entry bugs, the two algorithms are unlikely to have the same
+ // exact bug.
+ //
+ // - Relaxation issues, where we forget to relax something.
+ //
+ // - Input errors, where something cannot be correctly encoded. 'as' allows
+ // these through in many cases.
+
+ void addRelocation(const MCSectionData *SD,
+ object::macho::RelocationEntry &MRE) {
+ Relocations[SD].push_back(MRE);
+ }
+
+ void RecordScatteredRelocation(const MCAssembler &Asm,
+ const MCAsmLayout &Layout,
+ const MCFragment *Fragment,
+ const MCFixup &Fixup, MCValue Target,
+ unsigned Log2Size,
+ uint64_t &FixedValue);
+
+ void RecordTLVPRelocation(const MCAssembler &Asm,
+ const MCAsmLayout &Layout,
+ const MCFragment *Fragment,
+ const MCFixup &Fixup, MCValue Target,
+ uint64_t &FixedValue);
+
+ void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
+ const MCFragment *Fragment, const MCFixup &Fixup,
+ MCValue Target, uint64_t &FixedValue);
+
+ void BindIndirectSymbols(MCAssembler &Asm);
+
+ /// ComputeSymbolTable - Compute the symbol table data
+ ///
+ /// \param StringTable [out] - The string table data.
+ /// \param StringIndexMap [out] - Map from symbol names to offsets in the
+ /// string table.
+ void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
+ std::vector<MachSymbolData> &LocalSymbolData,
+ std::vector<MachSymbolData> &ExternalSymbolData,
+ std::vector<MachSymbolData> &UndefinedSymbolData);
+
+ void computeSectionAddresses(const MCAssembler &Asm,
+ const MCAsmLayout &Layout);
+
+ void markAbsoluteVariableSymbols(MCAssembler &Asm,
+ const MCAsmLayout &Layout);
+ void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout);
+
+ virtual bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
+ const MCSymbolData &DataA,
+ const MCFragment &FB,
+ bool InSet,
+ bool IsPCRel) const;
+
+ void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
+};
+
+
+/// \brief Construct a new Mach-O writer instance.
+///
+/// This routine takes ownership of the target writer subclass.
+///
+/// \param MOTW - The target specific Mach-O writer subclass.
+/// \param OS - The stream to write to.
+/// \returns The constructed object writer.
+MCObjectWriter *createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
+ raw_ostream &OS, bool IsLittleEndian);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCModule.h b/include/llvm/MC/MCModule.h
new file mode 100644
index 00000000000..755fa025fbc
--- /dev/null
+++ b/include/llvm/MC/MCModule.h
@@ -0,0 +1,58 @@
+//===-- llvm/MC/MCModule.h - MCModule class ---------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MCModule class, which is used to
+// represent a complete, disassembled object file or executable.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCMODULE_H
+#define LLVM_MC_MCMODULE_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/IntervalMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+class MCAtom;
+
+/// MCModule - This class represent a completely disassembled object file or
+/// executable. It comprises a list of MCAtom's, and a branch target table.
+/// Each atom represents a contiguous range of either instructions or data.
+class MCModule {
+ /// AtomAllocationTracker - An MCModule owns its component MCAtom's, so it
+ /// must track them in order to ensure they are properly freed as atoms are
+ /// merged or otherwise manipulated.
+ SmallPtrSet<MCAtom*, 8> AtomAllocationTracker;
+
+ /// OffsetMap - Efficiently maps offset ranges to MCAtom's.
+ IntervalMap<uint64_t, MCAtom*> OffsetMap;
+
+ /// BranchTargetMap - Maps offsets that are determined to be branches and
+ /// can be statically resolved to their target offsets.
+ DenseMap<uint64_t, MCAtom*> BranchTargetMap;
+
+ friend class MCAtom;
+
+ /// remap - Update the interval mapping for an MCAtom.
+ void remap(MCAtom *Atom, uint64_t NewBegin, uint64_t NewEnd);
+
+public:
+ MCModule(IntervalMap<uint64_t, MCAtom*>::Allocator &A) : OffsetMap(A) { }
+
+ /// createAtom - Creates a new MCAtom covering the specified offset range.
+ MCAtom *createAtom(MCAtom::AtomType Type, uint64_t Begin, uint64_t End);
+};
+
+}
+
+#endif
+
diff --git a/include/llvm/MC/MCObjectFileInfo.h b/include/llvm/MC/MCObjectFileInfo.h
new file mode 100644
index 00000000000..74e2263c731
--- /dev/null
+++ b/include/llvm/MC/MCObjectFileInfo.h
@@ -0,0 +1,312 @@
+//===-- llvm/MC/MCObjectFileInfo.h - Object File Info -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file describes common object file formats.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCBJECTFILEINFO_H
+#define LLVM_MC_MCBJECTFILEINFO_H
+
+#include "llvm/Support/CodeGen.h"
+
+namespace llvm {
+ class MCContext;
+ class MCSection;
+ class StringRef;
+ class Triple;
+
+class MCObjectFileInfo {
+protected:
+ /// CommDirectiveSupportsAlignment - True if .comm supports alignment. This
+ /// is a hack for as long as we support 10.4 Tiger, whose assembler doesn't
+ /// support alignment on comm.
+ bool CommDirectiveSupportsAlignment;
+
+ /// SupportsWeakEmptyEHFrame - True if target object file supports a
+ /// weak_definition of constant 0 for an omitted EH frame.
+ bool SupportsWeakOmittedEHFrame;
+
+ /// IsFunctionEHFrameSymbolPrivate - This flag is set to true if the
+ /// "EH_frame" symbol for EH information should be an assembler temporary (aka
+ /// private linkage, aka an L or .L label) or false if it should be a normal
+ /// non-.globl label. This defaults to true.
+ bool IsFunctionEHFrameSymbolPrivate;
+
+ /// PersonalityEncoding, LSDAEncoding, FDEEncoding, TTypeEncoding - Some
+ /// encoding values for EH.
+ unsigned PersonalityEncoding;
+ unsigned LSDAEncoding;
+ unsigned FDEEncoding;
+ unsigned FDECFIEncoding;
+ unsigned TTypeEncoding;
+ // Section flags for eh_frame
+ unsigned EHSectionType;
+ unsigned EHSectionFlags;
+
+ /// TextSection - Section directive for standard text.
+ ///
+ const MCSection *TextSection;
+
+ /// DataSection - Section directive for standard data.
+ ///
+ const MCSection *DataSection;
+
+ /// BSSSection - Section that is default initialized to zero.
+ const MCSection *BSSSection;
+
+ /// ReadOnlySection - Section that is readonly and can contain arbitrary
+ /// initialized data. Targets are not required to have a readonly section.
+ /// If they don't, various bits of code will fall back to using the data
+ /// section for constants.
+ const MCSection *ReadOnlySection;
+
+ /// StaticCtorSection - This section contains the static constructor pointer
+ /// list.
+ const MCSection *StaticCtorSection;
+
+ /// StaticDtorSection - This section contains the static destructor pointer
+ /// list.
+ const MCSection *StaticDtorSection;
+
+ /// LSDASection - If exception handling is supported by the target, this is
+ /// the section the Language Specific Data Area information is emitted to.
+ const MCSection *LSDASection;
+
+ /// CompactUnwindSection - If exception handling is supported by the target
+ /// and the target can support a compact representation of the CIE and FDE,
+ /// this is the section to emit them into.
+ const MCSection *CompactUnwindSection;
+
+ /// DwarfAccelNamesSection, DwarfAccelObjCSection
+ /// If we use the DWARF accelerated hash tables then we want toe emit these
+ /// sections.
+ const MCSection *DwarfAccelNamesSection;
+ const MCSection *DwarfAccelObjCSection;
+ const MCSection *DwarfAccelNamespaceSection;
+ const MCSection *DwarfAccelTypesSection;
+
+ // Dwarf sections for debug info. If a target supports debug info, these must
+ // be set.
+ const MCSection *DwarfAbbrevSection;
+ const MCSection *DwarfInfoSection;
+ const MCSection *DwarfLineSection;
+ const MCSection *DwarfFrameSection;
+ const MCSection *DwarfPubTypesSection;
+ const MCSection *DwarfDebugInlineSection;
+ const MCSection *DwarfStrSection;
+ const MCSection *DwarfLocSection;
+ const MCSection *DwarfARangesSection;
+ const MCSection *DwarfRangesSection;
+ const MCSection *DwarfMacroInfoSection;
+
+ // Extra TLS Variable Data section. If the target needs to put additional
+ // information for a TLS variable, it'll go here.
+ const MCSection *TLSExtraDataSection;
+
+ /// TLSDataSection - Section directive for Thread Local data.
+ /// ELF, MachO and COFF.
+ const MCSection *TLSDataSection; // Defaults to ".tdata".
+
+ /// TLSBSSSection - Section directive for Thread Local uninitialized data.
+ /// Null if this target doesn't support a BSS section.
+ /// ELF and MachO only.
+ const MCSection *TLSBSSSection; // Defaults to ".tbss".
+
+
+ /// EHFrameSection - EH frame section. It is initialized on demand so it
+ /// can be overwritten (with uniquing).
+ const MCSection *EHFrameSection;
+
+ /// ELF specific sections.
+ ///
+ const MCSection *DataRelSection;
+ const MCSection *DataRelLocalSection;
+ const MCSection *DataRelROSection;
+ const MCSection *DataRelROLocalSection;
+ const MCSection *MergeableConst4Section;
+ const MCSection *MergeableConst8Section;
+ const MCSection *MergeableConst16Section;
+
+ /// MachO specific sections.
+ ///
+
+ /// TLSTLVSection - Section for thread local structure information.
+ /// Contains the source code name of the variable, visibility and a pointer
+ /// to the initial value (.tdata or .tbss).
+ const MCSection *TLSTLVSection; // Defaults to ".tlv".
+
+ /// TLSThreadInitSection - Section for thread local data initialization
+ /// functions.
+ const MCSection *TLSThreadInitSection; // Defaults to ".thread_init_func".
+
+ const MCSection *CStringSection;
+ const MCSection *UStringSection;
+ const MCSection *TextCoalSection;
+ const MCSection *ConstTextCoalSection;
+ const MCSection *ConstDataSection;
+ const MCSection *DataCoalSection;
+ const MCSection *DataCommonSection;
+ const MCSection *DataBSSSection;
+ const MCSection *FourByteConstantSection;
+ const MCSection *EightByteConstantSection;
+ const MCSection *SixteenByteConstantSection;
+ const MCSection *LazySymbolPointerSection;
+ const MCSection *NonLazySymbolPointerSection;
+
+ /// COFF specific sections.
+ ///
+ const MCSection *DrectveSection;
+ const MCSection *PDataSection;
+ const MCSection *XDataSection;
+
+public:
+ void InitMCObjectFileInfo(StringRef TT, Reloc::Model RM, CodeModel::Model CM,
+ MCContext &ctx);
+
+ bool isFunctionEHFrameSymbolPrivate() const {
+ return IsFunctionEHFrameSymbolPrivate;
+ }
+ bool getSupportsWeakOmittedEHFrame() const {
+ return SupportsWeakOmittedEHFrame;
+ }
+ bool getCommDirectiveSupportsAlignment() const {
+ return CommDirectiveSupportsAlignment;
+ }
+
+ unsigned getPersonalityEncoding() const { return PersonalityEncoding; }
+ unsigned getLSDAEncoding() const { return LSDAEncoding; }
+ unsigned getFDEEncoding(bool CFI) const {
+ return CFI ? FDECFIEncoding : FDEEncoding;
+ }
+ unsigned getTTypeEncoding() const { return TTypeEncoding; }
+
+ const MCSection *getTextSection() const { return TextSection; }
+ const MCSection *getDataSection() const { return DataSection; }
+ const MCSection *getBSSSection() const { return BSSSection; }
+ const MCSection *getLSDASection() const { return LSDASection; }
+ const MCSection *getCompactUnwindSection() const{
+ return CompactUnwindSection;
+ }
+ const MCSection *getDwarfAccelNamesSection() const {
+ return DwarfAccelNamesSection;
+ }
+ const MCSection *getDwarfAccelObjCSection() const {
+ return DwarfAccelObjCSection;
+ }
+ const MCSection *getDwarfAccelNamespaceSection() const {
+ return DwarfAccelNamespaceSection;
+ }
+ const MCSection *getDwarfAccelTypesSection() const {
+ return DwarfAccelTypesSection;
+ }
+ const MCSection *getDwarfAbbrevSection() const { return DwarfAbbrevSection; }
+ const MCSection *getDwarfInfoSection() const { return DwarfInfoSection; }
+ const MCSection *getDwarfLineSection() const { return DwarfLineSection; }
+ const MCSection *getDwarfFrameSection() const { return DwarfFrameSection; }
+ const MCSection *getDwarfPubTypesSection() const{return DwarfPubTypesSection;}
+ const MCSection *getDwarfDebugInlineSection() const {
+ return DwarfDebugInlineSection;
+ }
+ const MCSection *getDwarfStrSection() const { return DwarfStrSection; }
+ const MCSection *getDwarfLocSection() const { return DwarfLocSection; }
+ const MCSection *getDwarfARangesSection() const { return DwarfARangesSection;}
+ const MCSection *getDwarfRangesSection() const { return DwarfRangesSection; }
+ const MCSection *getDwarfMacroInfoSection() const {
+ return DwarfMacroInfoSection;
+ }
+ const MCSection *getTLSExtraDataSection() const {
+ return TLSExtraDataSection;
+ }
+ const MCSection *getTLSDataSection() const { return TLSDataSection; }
+ const MCSection *getTLSBSSSection() const { return TLSBSSSection; }
+
+ /// ELF specific sections.
+ ///
+ const MCSection *getDataRelSection() const { return DataRelSection; }
+ const MCSection *getDataRelLocalSection() const {
+ return DataRelLocalSection;
+ }
+ const MCSection *getDataRelROSection() const { return DataRelROSection; }
+ const MCSection *getDataRelROLocalSection() const {
+ return DataRelROLocalSection;
+ }
+ const MCSection *getMergeableConst4Section() const {
+ return MergeableConst4Section;
+ }
+ const MCSection *getMergeableConst8Section() const {
+ return MergeableConst8Section;
+ }
+ const MCSection *getMergeableConst16Section() const {
+ return MergeableConst16Section;
+ }
+
+ /// MachO specific sections.
+ ///
+ const MCSection *getTLSTLVSection() const { return TLSTLVSection; }
+ const MCSection *getTLSThreadInitSection() const {
+ return TLSThreadInitSection;
+ }
+ const MCSection *getCStringSection() const { return CStringSection; }
+ const MCSection *getUStringSection() const { return UStringSection; }
+ const MCSection *getTextCoalSection() const { return TextCoalSection; }
+ const MCSection *getConstTextCoalSection() const {
+ return ConstTextCoalSection;
+ }
+ const MCSection *getConstDataSection() const { return ConstDataSection; }
+ const MCSection *getDataCoalSection() const { return DataCoalSection; }
+ const MCSection *getDataCommonSection() const { return DataCommonSection; }
+ const MCSection *getDataBSSSection() const { return DataBSSSection; }
+ const MCSection *getFourByteConstantSection() const {
+ return FourByteConstantSection;
+ }
+ const MCSection *getEightByteConstantSection() const {
+ return EightByteConstantSection;
+ }
+ const MCSection *getSixteenByteConstantSection() const {
+ return SixteenByteConstantSection;
+ }
+ const MCSection *getLazySymbolPointerSection() const {
+ return LazySymbolPointerSection;
+ }
+ const MCSection *getNonLazySymbolPointerSection() const {
+ return NonLazySymbolPointerSection;
+ }
+
+ /// COFF specific sections.
+ ///
+ const MCSection *getDrectveSection() const { return DrectveSection; }
+ const MCSection *getPDataSection() const { return PDataSection; }
+ const MCSection *getXDataSection() const { return XDataSection; }
+
+ const MCSection *getEHFrameSection() {
+ if (!EHFrameSection)
+ InitEHFrameSection();
+ return EHFrameSection;
+ }
+
+private:
+ enum Environment { IsMachO, IsELF, IsCOFF };
+ Environment Env;
+ Reloc::Model RelocM;
+ CodeModel::Model CMModel;
+ MCContext *Ctx;
+
+ void InitMachOMCObjectFileInfo(Triple T);
+ void InitELFMCObjectFileInfo(Triple T);
+ void InitCOFFMCObjectFileInfo(Triple T);
+
+ /// InitEHFrameSection - Initialize EHFrameSection on demand.
+ ///
+ void InitEHFrameSection();
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCObjectStreamer.h b/include/llvm/MC/MCObjectStreamer.h
new file mode 100644
index 00000000000..b59b76c2be8
--- /dev/null
+++ b/include/llvm/MC/MCObjectStreamer.h
@@ -0,0 +1,91 @@
+//===- MCObjectStreamer.h - MCStreamer Object File Interface ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCOBJECTSTREAMER_H
+#define LLVM_MC_MCOBJECTSTREAMER_H
+
+#include "llvm/MC/MCStreamer.h"
+
+namespace llvm {
+class MCAssembler;
+class MCCodeEmitter;
+class MCSectionData;
+class MCExpr;
+class MCFragment;
+class MCDataFragment;
+class MCAsmBackend;
+class raw_ostream;
+
+/// \brief Streaming object file generation interface.
+///
+/// This class provides an implementation of the MCStreamer interface which is
+/// suitable for use with the assembler backend. Specific object file formats
+/// are expected to subclass this interface to implement directives specific
+/// to that file format or custom semantics expected by the object writer
+/// implementation.
+class MCObjectStreamer : public MCStreamer {
+ MCAssembler *Assembler;
+ MCSectionData *CurSectionData;
+
+ virtual void EmitInstToData(const MCInst &Inst) = 0;
+ virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
+ virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame);
+
+protected:
+ MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
+ raw_ostream &_OS, MCCodeEmitter *_Emitter);
+ MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
+ raw_ostream &_OS, MCCodeEmitter *_Emitter,
+ MCAssembler *_Assembler);
+ ~MCObjectStreamer();
+
+ MCSectionData *getCurrentSectionData() const {
+ return CurSectionData;
+ }
+
+ MCFragment *getCurrentFragment() const;
+
+ /// Get a data fragment to write into, creating a new one if the current
+ /// fragment is not a data fragment.
+ MCDataFragment *getOrCreateDataFragment() const;
+
+ const MCExpr *AddValueSymbols(const MCExpr *Value);
+
+public:
+ MCAssembler &getAssembler() { return *Assembler; }
+
+ /// @name MCStreamer Interface
+ /// @{
+
+ virtual void EmitLabel(MCSymbol *Symbol);
+ virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
+ unsigned AddrSpace);
+ virtual void EmitULEB128Value(const MCExpr *Value);
+ virtual void EmitSLEB128Value(const MCExpr *Value);
+ virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
+ virtual void ChangeSection(const MCSection *Section);
+ virtual void EmitInstruction(const MCInst &Inst);
+ virtual void EmitInstToFragment(const MCInst &Inst);
+ virtual bool EmitValueToOffset(const MCExpr *Offset, unsigned char Value);
+ virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
+ const MCSymbol *LastLabel,
+ const MCSymbol *Label,
+ unsigned PointerSize);
+ virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
+ const MCSymbol *Label);
+ virtual void EmitGPRel32Value(const MCExpr *Value);
+ virtual void EmitGPRel64Value(const MCExpr *Value);
+ virtual void FinishImpl();
+
+ /// @}
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCObjectWriter.h b/include/llvm/MC/MCObjectWriter.h
new file mode 100644
index 00000000000..14fe75fd4c3
--- /dev/null
+++ b/include/llvm/MC/MCObjectWriter.h
@@ -0,0 +1,190 @@
+//===-- llvm/MC/MCObjectWriter.h - Object File Writer Interface -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCOBJECTWRITER_H
+#define LLVM_MC_MCOBJECTWRITER_H
+
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+
+namespace llvm {
+class MCAsmLayout;
+class MCAssembler;
+class MCFixup;
+class MCFragment;
+class MCSymbolData;
+class MCSymbolRefExpr;
+class MCValue;
+
+/// MCObjectWriter - Defines the object file and target independent interfaces
+/// used by the assembler backend to write native file format object files.
+///
+/// The object writer contains a few callbacks used by the assembler to allow
+/// the object writer to modify the assembler data structures at appropriate
+/// points. Once assembly is complete, the object writer is given the
+/// MCAssembler instance, which contains all the symbol and section data which
+/// should be emitted as part of WriteObject().
+///
+/// The object writer also contains a number of helper methods for writing
+/// binary data to the output stream.
+class MCObjectWriter {
+ MCObjectWriter(const MCObjectWriter &) LLVM_DELETED_FUNCTION;
+ void operator=(const MCObjectWriter &) LLVM_DELETED_FUNCTION;
+
+protected:
+ raw_ostream &OS;
+
+ unsigned IsLittleEndian : 1;
+
+protected: // Can only create subclasses.
+ MCObjectWriter(raw_ostream &_OS, bool _IsLittleEndian)
+ : OS(_OS), IsLittleEndian(_IsLittleEndian) {}
+
+public:
+ virtual ~MCObjectWriter();
+
+ bool isLittleEndian() const { return IsLittleEndian; }
+
+ raw_ostream &getStream() { return OS; }
+
+ /// @name High-Level API
+ /// @{
+
+ /// Perform any late binding of symbols (for example, to assign symbol indices
+ /// for use when generating relocations).
+ ///
+ /// This routine is called by the assembler after layout and relaxation is
+ /// complete.
+ virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
+ const MCAsmLayout &Layout) = 0;
+
+ /// Record a relocation entry.
+ ///
+ /// This routine is called by the assembler after layout and relaxation, and
+ /// post layout binding. The implementation is responsible for storing
+ /// information about the relocation so that it can be emitted during
+ /// WriteObject().
+ virtual void RecordRelocation(const MCAssembler &Asm,
+ const MCAsmLayout &Layout,
+ const MCFragment *Fragment,
+ const MCFixup &Fixup, MCValue Target,
+ uint64_t &FixedValue) = 0;
+
+ /// \brief Check whether the difference (A - B) between two symbol
+ /// references is fully resolved.
+ ///
+ /// Clients are not required to answer precisely and may conservatively return
+ /// false, even when a difference is fully resolved.
+ bool
+ IsSymbolRefDifferenceFullyResolved(const MCAssembler &Asm,
+ const MCSymbolRefExpr *A,
+ const MCSymbolRefExpr *B,
+ bool InSet) const;
+
+ virtual bool
+ IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
+ const MCSymbolData &DataA,
+ const MCFragment &FB,
+ bool InSet,
+ bool IsPCRel) const;
+
+
+ /// Write the object file.
+ ///
+ /// This routine is called by the assembler after layout and relaxation is
+ /// complete, fixups have been evaluated and applied, and relocations
+ /// generated.
+ virtual void WriteObject(MCAssembler &Asm,
+ const MCAsmLayout &Layout) = 0;
+
+ /// @}
+ /// @name Binary Output
+ /// @{
+
+ void Write8(uint8_t Value) {
+ OS << char(Value);
+ }
+
+ void WriteLE16(uint16_t Value) {
+ Write8(uint8_t(Value >> 0));
+ Write8(uint8_t(Value >> 8));
+ }
+
+ void WriteLE32(uint32_t Value) {
+ WriteLE16(uint16_t(Value >> 0));
+ WriteLE16(uint16_t(Value >> 16));
+ }
+
+ void WriteLE64(uint64_t Value) {
+ WriteLE32(uint32_t(Value >> 0));
+ WriteLE32(uint32_t(Value >> 32));
+ }
+
+ void WriteBE16(uint16_t Value) {
+ Write8(uint8_t(Value >> 8));
+ Write8(uint8_t(Value >> 0));
+ }
+
+ void WriteBE32(uint32_t Value) {
+ WriteBE16(uint16_t(Value >> 16));
+ WriteBE16(uint16_t(Value >> 0));
+ }
+
+ void WriteBE64(uint64_t Value) {
+ WriteBE32(uint32_t(Value >> 32));
+ WriteBE32(uint32_t(Value >> 0));
+ }
+
+ void Write16(uint16_t Value) {
+ if (IsLittleEndian)
+ WriteLE16(Value);
+ else
+ WriteBE16(Value);
+ }
+
+ void Write32(uint32_t Value) {
+ if (IsLittleEndian)
+ WriteLE32(Value);
+ else
+ WriteBE32(Value);
+ }
+
+ void Write64(uint64_t Value) {
+ if (IsLittleEndian)
+ WriteLE64(Value);
+ else
+ WriteBE64(Value);
+ }
+
+ void WriteZeros(unsigned N) {
+ const char Zeros[16] = { 0 };
+
+ for (unsigned i = 0, e = N / 16; i != e; ++i)
+ OS << StringRef(Zeros, 16);
+
+ OS << StringRef(Zeros, N % 16);
+ }
+
+ void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
+ assert((ZeroFillSize == 0 || Str.size () <= ZeroFillSize) &&
+ "data size greater than fill size, unexpected large write will occur");
+ OS << Str;
+ if (ZeroFillSize)
+ WriteZeros(ZeroFillSize - Str.size());
+ }
+
+ /// @}
+
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCParser/AsmCond.h b/include/llvm/MC/MCParser/AsmCond.h
new file mode 100644
index 00000000000..92a115eb803
--- /dev/null
+++ b/include/llvm/MC/MCParser/AsmCond.h
@@ -0,0 +1,40 @@
+//===- AsmCond.h - Assembly file conditional assembly ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ASMCOND_H
+#define ASMCOND_H
+
+namespace llvm {
+
+/// AsmCond - Class to support conditional assembly
+///
+/// The conditional assembly feature (.if, .else, .elseif and .endif) is
+/// implemented with AsmCond that tells us what we are in the middle of
+/// processing. Ignore can be either true or false. When true we are ignoring
+/// the block of code in the middle of a conditional.
+
+class AsmCond {
+public:
+ enum ConditionalAssemblyType {
+ NoCond, // no conditional is being processed
+ IfCond, // inside if conditional
+ ElseIfCond, // inside elseif conditional
+ ElseCond // inside else conditional
+ };
+
+ ConditionalAssemblyType TheCond;
+ bool CondMet;
+ bool Ignore;
+
+ AsmCond() : TheCond(NoCond), CondMet(false), Ignore(false) {}
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCParser/AsmLexer.h b/include/llvm/MC/MCParser/AsmLexer.h
new file mode 100644
index 00000000000..e102dfb82c4
--- /dev/null
+++ b/include/llvm/MC/MCParser/AsmLexer.h
@@ -0,0 +1,70 @@
+//===- AsmLexer.h - Lexer for Assembly Files --------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This class declares the lexer for assembly files.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ASMLEXER_H
+#define ASMLEXER_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/MC/MCParser/MCAsmLexer.h"
+#include "llvm/Support/DataTypes.h"
+#include <string>
+
+namespace llvm {
+class MemoryBuffer;
+class MCAsmInfo;
+
+/// AsmLexer - Lexer class for assembly files.
+class AsmLexer : public MCAsmLexer {
+ const MCAsmInfo &MAI;
+
+ const char *CurPtr;
+ const MemoryBuffer *CurBuf;
+ bool isAtStartOfLine;
+
+ void operator=(const AsmLexer&) LLVM_DELETED_FUNCTION;
+ AsmLexer(const AsmLexer&) LLVM_DELETED_FUNCTION;
+
+protected:
+ /// LexToken - Read the next token and return its code.
+ virtual AsmToken LexToken();
+
+public:
+ AsmLexer(const MCAsmInfo &MAI);
+ ~AsmLexer();
+
+ void setBuffer(const MemoryBuffer *buf, const char *ptr = NULL);
+
+ virtual StringRef LexUntilEndOfStatement();
+ StringRef LexUntilEndOfLine();
+
+ bool isAtStartOfComment(char Char);
+ bool isAtStatementSeparator(const char *Ptr);
+
+ const MCAsmInfo &getMAI() const { return MAI; }
+
+private:
+ int getNextChar();
+ AsmToken ReturnError(const char *Loc, const std::string &Msg);
+
+ AsmToken LexIdentifier();
+ AsmToken LexSlash();
+ AsmToken LexLineComment();
+ AsmToken LexDigit();
+ AsmToken LexSingleQuote();
+ AsmToken LexQuote();
+ AsmToken LexFloatLiteral();
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCParser/MCAsmLexer.h b/include/llvm/MC/MCParser/MCAsmLexer.h
new file mode 100644
index 00000000000..1613a0e2f91
--- /dev/null
+++ b/include/llvm/MC/MCParser/MCAsmLexer.h
@@ -0,0 +1,182 @@
+//===-- llvm/MC/MCAsmLexer.h - Abstract Asm Lexer Interface -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCASMLEXER_H
+#define LLVM_MC_MCASMLEXER_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/SMLoc.h"
+
+namespace llvm {
+
+/// AsmToken - Target independent representation for an assembler token.
+class AsmToken {
+public:
+ enum TokenKind {
+ // Markers
+ Eof, Error,
+
+ // String values.
+ Identifier,
+ String,
+
+ // Integer values.
+ Integer,
+
+ // Real values.
+ Real,
+
+ // Register values (stored in IntVal). Only used by MCTargetAsmLexer.
+ Register,
+
+ // No-value.
+ EndOfStatement,
+ Colon,
+ Plus, Minus, Tilde,
+ Slash, // '/'
+ BackSlash, // '\'
+ LParen, RParen, LBrac, RBrac, LCurly, RCurly,
+ Star, Dot, Comma, Dollar, Equal, EqualEqual,
+
+ Pipe, PipePipe, Caret,
+ Amp, AmpAmp, Exclaim, ExclaimEqual, Percent, Hash,
+ Less, LessEqual, LessLess, LessGreater,
+ Greater, GreaterEqual, GreaterGreater, At
+ };
+
+private:
+ TokenKind Kind;
+
+ /// A reference to the entire token contents; this is always a pointer into
+ /// a memory buffer owned by the source manager.
+ StringRef Str;
+
+ int64_t IntVal;
+
+public:
+ AsmToken() {}
+ AsmToken(TokenKind _Kind, StringRef _Str, int64_t _IntVal = 0)
+ : Kind(_Kind), Str(_Str), IntVal(_IntVal) {}
+
+ TokenKind getKind() const { return Kind; }
+ bool is(TokenKind K) const { return Kind == K; }
+ bool isNot(TokenKind K) const { return Kind != K; }
+
+ SMLoc getLoc() const;
+ SMLoc getEndLoc() const;
+
+ /// getStringContents - Get the contents of a string token (without quotes).
+ StringRef getStringContents() const {
+ assert(Kind == String && "This token isn't a string!");
+ return Str.slice(1, Str.size() - 1);
+ }
+
+ /// getIdentifier - Get the identifier string for the current token, which
+ /// should be an identifier or a string. This gets the portion of the string
+ /// which should be used as the identifier, e.g., it does not include the
+ /// quotes on strings.
+ StringRef getIdentifier() const {
+ if (Kind == Identifier)
+ return getString();
+ return getStringContents();
+ }
+
+ /// getString - Get the string for the current token, this includes all
+ /// characters (for example, the quotes on strings) in the token.
+ ///
+ /// The returned StringRef points into the source manager's memory buffer, and
+ /// is safe to store across calls to Lex().
+ StringRef getString() const { return Str; }
+
+ // FIXME: Don't compute this in advance, it makes every token larger, and is
+ // also not generally what we want (it is nicer for recovery etc. to lex 123br
+ // as a single token, then diagnose as an invalid number).
+ int64_t getIntVal() const {
+ assert(Kind == Integer && "This token isn't an integer!");
+ return IntVal;
+ }
+
+ /// getRegVal - Get the register number for the current token, which should
+ /// be a register.
+ unsigned getRegVal() const {
+ assert(Kind == Register && "This token isn't a register!");
+ return static_cast<unsigned>(IntVal);
+ }
+};
+
+/// MCAsmLexer - Generic assembler lexer interface, for use by target specific
+/// assembly lexers.
+class MCAsmLexer {
+ /// The current token, stored in the base class for faster access.
+ AsmToken CurTok;
+
+ /// The location and description of the current error
+ SMLoc ErrLoc;
+ std::string Err;
+
+ MCAsmLexer(const MCAsmLexer &) LLVM_DELETED_FUNCTION;
+ void operator=(const MCAsmLexer &) LLVM_DELETED_FUNCTION;
+protected: // Can only create subclasses.
+ const char *TokStart;
+
+ MCAsmLexer();
+
+ virtual AsmToken LexToken() = 0;
+
+ void SetError(const SMLoc &errLoc, const std::string &err) {
+ ErrLoc = errLoc;
+ Err = err;
+ }
+
+public:
+ virtual ~MCAsmLexer();
+
+ /// Lex - Consume the next token from the input stream and return it.
+ ///
+ /// The lexer will continuosly return the end-of-file token once the end of
+ /// the main input file has been reached.
+ const AsmToken &Lex() {
+ return CurTok = LexToken();
+ }
+
+ virtual StringRef LexUntilEndOfStatement() = 0;
+
+ /// getLoc - Get the current source location.
+ SMLoc getLoc() const;
+
+ /// getTok - Get the current (last) lexed token.
+ const AsmToken &getTok() {
+ return CurTok;
+ }
+
+ /// getErrLoc - Get the current error location
+ const SMLoc &getErrLoc() {
+ return ErrLoc;
+ }
+
+ /// getErr - Get the current error string
+ const std::string &getErr() {
+ return Err;
+ }
+
+ /// getKind - Get the kind of current token.
+ AsmToken::TokenKind getKind() const { return CurTok.getKind(); }
+
+ /// is - Check if the current token has kind \p K.
+ bool is(AsmToken::TokenKind K) const { return CurTok.is(K); }
+
+ /// isNot - Check if the current token has kind \p K.
+ bool isNot(AsmToken::TokenKind K) const { return CurTok.isNot(K); }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCParser/MCAsmParser.h b/include/llvm/MC/MCParser/MCAsmParser.h
new file mode 100644
index 00000000000..adc960d27e0
--- /dev/null
+++ b/include/llvm/MC/MCParser/MCAsmParser.h
@@ -0,0 +1,144 @@
+//===-- llvm/MC/MCAsmParser.h - Abstract Asm Parser Interface ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCASMPARSER_H
+#define LLVM_MC_MCASMPARSER_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/ADT/ArrayRef.h"
+
+namespace llvm {
+class AsmToken;
+class MCAsmInfo;
+class MCAsmLexer;
+class MCAsmParserExtension;
+class MCContext;
+class MCExpr;
+class MCStreamer;
+class MCTargetAsmParser;
+class SMLoc;
+class SMRange;
+class SourceMgr;
+class StringRef;
+class Twine;
+
+/// MCAsmParser - Generic assembler parser interface, for use by target specific
+/// assembly parsers.
+class MCAsmParser {
+public:
+ typedef bool (*DirectiveHandler)(MCAsmParserExtension*, StringRef, SMLoc);
+
+private:
+ MCAsmParser(const MCAsmParser &) LLVM_DELETED_FUNCTION;
+ void operator=(const MCAsmParser &) LLVM_DELETED_FUNCTION;
+
+ MCTargetAsmParser *TargetParser;
+
+ unsigned ShowParsedOperands : 1;
+
+protected: // Can only create subclasses.
+ MCAsmParser();
+
+public:
+ virtual ~MCAsmParser();
+
+ virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
+ StringRef Directive,
+ DirectiveHandler Handler) = 0;
+
+ virtual SourceMgr &getSourceManager() = 0;
+
+ virtual MCAsmLexer &getLexer() = 0;
+
+ virtual MCContext &getContext() = 0;
+
+ /// getStreamer - Return the output streamer for the assembler.
+ virtual MCStreamer &getStreamer() = 0;
+
+ MCTargetAsmParser &getTargetParser() const { return *TargetParser; }
+ void setTargetParser(MCTargetAsmParser &P);
+
+ virtual unsigned getAssemblerDialect() { return 0;}
+ virtual void setAssemblerDialect(unsigned i) { }
+
+ bool getShowParsedOperands() const { return ShowParsedOperands; }
+ void setShowParsedOperands(bool Value) { ShowParsedOperands = Value; }
+
+ /// Run - Run the parser on the input source buffer.
+ virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false) = 0;
+
+ /// Warning - Emit a warning at the location \p L, with the message \p Msg.
+ ///
+ /// \return The return value is true, if warnings are fatal.
+ virtual bool Warning(SMLoc L, const Twine &Msg,
+ ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) = 0;
+
+ /// Error - Emit an error at the location \p L, with the message \p Msg.
+ ///
+ /// \return The return value is always true, as an idiomatic convenience to
+ /// clients.
+ virtual bool Error(SMLoc L, const Twine &Msg,
+ ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) = 0;
+
+ /// Lex - Get the next AsmToken in the stream, possibly handling file
+ /// inclusion first.
+ virtual const AsmToken &Lex() = 0;
+
+ /// getTok - Get the current AsmToken from the stream.
+ const AsmToken &getTok();
+
+ /// \brief Report an error at the current lexer location.
+ bool TokError(const Twine &Msg,
+ ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
+
+ /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
+ /// and set \p Res to the identifier contents.
+ virtual bool ParseIdentifier(StringRef &Res) = 0;
+
+ /// \brief Parse up to the end of statement and return the contents from the
+ /// current token until the end of the statement; the current token on exit
+ /// will be either the EndOfStatement or EOF.
+ virtual StringRef ParseStringToEndOfStatement() = 0;
+
+ /// EatToEndOfStatement - Skip to the end of the current statement, for error
+ /// recovery.
+ virtual void EatToEndOfStatement() = 0;
+
+ /// ParseExpression - Parse an arbitrary expression.
+ ///
+ /// @param Res - The value of the expression. The result is undefined
+ /// on error.
+ /// @result - False on success.
+ virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
+ bool ParseExpression(const MCExpr *&Res);
+
+ /// ParseParenExpression - Parse an arbitrary expression, assuming that an
+ /// initial '(' has already been consumed.
+ ///
+ /// @param Res - The value of the expression. The result is undefined
+ /// on error.
+ /// @result - False on success.
+ virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
+
+ /// ParseAbsoluteExpression - Parse an expression which must evaluate to an
+ /// absolute value.
+ ///
+ /// @param Res - The value of the absolute expression. The result is undefined
+ /// on error.
+ /// @result - False on success.
+ virtual bool ParseAbsoluteExpression(int64_t &Res) = 0;
+};
+
+/// \brief Create an MCAsmParser instance.
+MCAsmParser *createMCAsmParser(SourceMgr &, MCContext &,
+ MCStreamer &, const MCAsmInfo &);
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCParser/MCAsmParserExtension.h b/include/llvm/MC/MCParser/MCAsmParserExtension.h
new file mode 100644
index 00000000000..0918c93bdf3
--- /dev/null
+++ b/include/llvm/MC/MCParser/MCAsmParserExtension.h
@@ -0,0 +1,80 @@
+//===-- llvm/MC/MCAsmParserExtension.h - Asm Parser Hooks -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCASMPARSEREXTENSION_H
+#define LLVM_MC_MCASMPARSEREXTENSION_H
+
+#include "llvm/MC/MCParser/MCAsmParser.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/SMLoc.h"
+
+namespace llvm {
+class Twine;
+
+/// \brief Generic interface for extending the MCAsmParser,
+/// which is implemented by target and object file assembly parser
+/// implementations.
+class MCAsmParserExtension {
+ MCAsmParserExtension(const MCAsmParserExtension &) LLVM_DELETED_FUNCTION;
+ void operator=(const MCAsmParserExtension &) LLVM_DELETED_FUNCTION;
+
+ MCAsmParser *Parser;
+
+protected:
+ MCAsmParserExtension();
+
+ // Helper template for implementing static dispatch functions.
+ template<typename T, bool (T::*Handler)(StringRef, SMLoc)>
+ static bool HandleDirective(MCAsmParserExtension *Target,
+ StringRef Directive,
+ SMLoc DirectiveLoc) {
+ T *Obj = static_cast<T*>(Target);
+ return (Obj->*Handler)(Directive, DirectiveLoc);
+ }
+
+ bool BracketExpressionsSupported;
+
+public:
+ virtual ~MCAsmParserExtension();
+
+ /// \brief Initialize the extension for parsing using the given \p Parser.
+ /// The extension should use the AsmParser interfaces to register its
+ /// parsing routines.
+ virtual void Initialize(MCAsmParser &Parser);
+
+ /// @name MCAsmParser Proxy Interfaces
+ /// @{
+
+ MCContext &getContext() { return getParser().getContext(); }
+ MCAsmLexer &getLexer() { return getParser().getLexer(); }
+ MCAsmParser &getParser() { return *Parser; }
+ SourceMgr &getSourceManager() { return getParser().getSourceManager(); }
+ MCStreamer &getStreamer() { return getParser().getStreamer(); }
+ bool Warning(SMLoc L, const Twine &Msg) {
+ return getParser().Warning(L, Msg);
+ }
+ bool Error(SMLoc L, const Twine &Msg) {
+ return getParser().Error(L, Msg);
+ }
+ bool TokError(const Twine &Msg) {
+ return getParser().TokError(Msg);
+ }
+
+ const AsmToken &Lex() { return getParser().Lex(); }
+
+ const AsmToken &getTok() { return getParser().getTok(); }
+
+ bool HasBracketExpressions() const { return BracketExpressionsSupported; }
+
+ /// @}
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCParser/MCParsedAsmOperand.h b/include/llvm/MC/MCParser/MCParsedAsmOperand.h
new file mode 100644
index 00000000000..369bc72ff61
--- /dev/null
+++ b/include/llvm/MC/MCParser/MCParsedAsmOperand.h
@@ -0,0 +1,56 @@
+//===-- llvm/MC/MCParsedAsmOperand.h - Asm Parser Operand -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCASMOPERAND_H
+#define LLVM_MC_MCASMOPERAND_H
+
+namespace llvm {
+class SMLoc;
+class raw_ostream;
+
+/// MCParsedAsmOperand - This abstract class represents a source-level assembly
+/// instruction operand. It should be subclassed by target-specific code. This
+/// base class is used by target-independent clients and is the interface
+/// between parsing an asm instruction and recognizing it.
+class MCParsedAsmOperand {
+public:
+ MCParsedAsmOperand() {}
+ virtual ~MCParsedAsmOperand() {}
+
+ /// isToken - Is this a token operand?
+ virtual bool isToken() const = 0;
+ /// isImm - Is this an immediate operand?
+ virtual bool isImm() const = 0;
+ /// isReg - Is this a register operand?
+ virtual bool isReg() const = 0;
+ /// isMem - Is this a memory operand?
+ virtual bool isMem() const = 0;
+
+ /// getStartLoc - Get the location of the first token of this operand.
+ virtual SMLoc getStartLoc() const = 0;
+ /// getEndLoc - Get the location of the last token of this operand.
+ virtual SMLoc getEndLoc() const = 0;
+
+ /// print - Print a debug representation of the operand to the given stream.
+ virtual void print(raw_ostream &OS) const = 0;
+ /// dump - Print to the debug stream.
+ virtual void dump() const;
+};
+
+//===----------------------------------------------------------------------===//
+// Debugging Support
+
+inline raw_ostream& operator<<(raw_ostream &OS, const MCParsedAsmOperand &MO) {
+ MO.print(OS);
+ return OS;
+}
+
+} // end namespace llvm.
+
+#endif
diff --git a/include/llvm/MC/MCRegisterInfo.h b/include/llvm/MC/MCRegisterInfo.h
new file mode 100644
index 00000000000..6749bdffc2f
--- /dev/null
+++ b/include/llvm/MC/MCRegisterInfo.h
@@ -0,0 +1,503 @@
+//=== MC/MCRegisterInfo.h - Target Register Description ---------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file describes an abstract interface used to get information about a
+// target machines register file. This information is used for a variety of
+// purposed, especially register allocation.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCREGISTERINFO_H
+#define LLVM_MC_MCREGISTERINFO_H
+
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/ErrorHandling.h"
+#include <cassert>
+
+namespace llvm {
+
+/// MCRegisterClass - Base class of TargetRegisterClass.
+class MCRegisterClass {
+public:
+ typedef const uint16_t* iterator;
+ typedef const uint16_t* const_iterator;
+
+ const char *Name;
+ const iterator RegsBegin;
+ const uint8_t *const RegSet;
+ const uint16_t RegsSize;
+ const uint16_t RegSetSize;
+ const uint16_t ID;
+ const uint16_t RegSize, Alignment; // Size & Alignment of register in bytes
+ const int8_t CopyCost;
+ const bool Allocatable;
+
+ /// getID() - Return the register class ID number.
+ ///
+ unsigned getID() const { return ID; }
+
+ /// getName() - Return the register class name for debugging.
+ ///
+ const char *getName() const { return Name; }
+
+ /// begin/end - Return all of the registers in this class.
+ ///
+ iterator begin() const { return RegsBegin; }
+ iterator end() const { return RegsBegin + RegsSize; }
+
+ /// getNumRegs - Return the number of registers in this class.
+ ///
+ unsigned getNumRegs() const { return RegsSize; }
+
+ /// getRegister - Return the specified register in the class.
+ ///
+ unsigned getRegister(unsigned i) const {
+ assert(i < getNumRegs() && "Register number out of range!");
+ return RegsBegin[i];
+ }
+
+ /// contains - Return true if the specified register is included in this
+ /// register class. This does not include virtual registers.
+ bool contains(unsigned Reg) const {
+ unsigned InByte = Reg % 8;
+ unsigned Byte = Reg / 8;
+ if (Byte >= RegSetSize)
+ return false;
+ return (RegSet[Byte] & (1 << InByte)) != 0;
+ }
+
+ /// contains - Return true if both registers are in this class.
+ bool contains(unsigned Reg1, unsigned Reg2) const {
+ return contains(Reg1) && contains(Reg2);
+ }
+
+ /// getSize - Return the size of the register in bytes, which is also the size
+ /// of a stack slot allocated to hold a spilled copy of this register.
+ unsigned getSize() const { return RegSize; }
+
+ /// getAlignment - Return the minimum required alignment for a register of
+ /// this class.
+ unsigned getAlignment() const { return Alignment; }
+
+ /// getCopyCost - Return the cost of copying a value between two registers in
+ /// this class. A negative number means the register class is very expensive
+ /// to copy e.g. status flag register classes.
+ int getCopyCost() const { return CopyCost; }
+
+ /// isAllocatable - Return true if this register class may be used to create
+ /// virtual registers.
+ bool isAllocatable() const { return Allocatable; }
+};
+
+/// MCRegisterDesc - This record contains all of the information known about
+/// a particular register. The Overlaps field contains a pointer to a zero
+/// terminated array of registers that this register aliases, starting with
+/// itself. This is needed for architectures like X86 which have AL alias AX
+/// alias EAX. The SubRegs field is a zero terminated array of registers that
+/// are sub-registers of the specific register, e.g. AL, AH are sub-registers of
+/// AX. The SuperRegs field is a zero terminated array of registers that are
+/// super-registers of the specific register, e.g. RAX, EAX, are super-registers
+/// of AX.
+///
+struct MCRegisterDesc {
+ uint32_t Name; // Printable name for the reg (for debugging)
+ uint32_t Overlaps; // Overlapping registers, described above
+ uint32_t SubRegs; // Sub-register set, described above
+ uint32_t SuperRegs; // Super-register set, described above
+
+ // Offset into MCRI::SubRegIndices of a list of sub-register indices for each
+ // sub-register in SubRegs.
+ uint32_t SubRegIndices;
+
+ // RegUnits - Points to the list of register units. The low 4 bits holds the
+ // Scale, the high bits hold an offset into DiffLists. See MCRegUnitIterator.
+ uint32_t RegUnits;
+};
+
+/// MCRegisterInfo base class - We assume that the target defines a static
+/// array of MCRegisterDesc objects that represent all of the machine
+/// registers that the target has. As such, we simply have to track a pointer
+/// to this array so that we can turn register number into a register
+/// descriptor.
+///
+/// Note this class is designed to be a base class of TargetRegisterInfo, which
+/// is the interface used by codegen. However, specific targets *should never*
+/// specialize this class. MCRegisterInfo should only contain getters to access
+/// TableGen generated physical register data. It must not be extended with
+/// virtual methods.
+///
+class MCRegisterInfo {
+public:
+ typedef const MCRegisterClass *regclass_iterator;
+
+ /// DwarfLLVMRegPair - Emitted by tablegen so Dwarf<->LLVM reg mappings can be
+ /// performed with a binary search.
+ struct DwarfLLVMRegPair {
+ unsigned FromReg;
+ unsigned ToReg;
+
+ bool operator<(DwarfLLVMRegPair RHS) const { return FromReg < RHS.FromReg; }
+ };
+private:
+ const MCRegisterDesc *Desc; // Pointer to the descriptor array
+ unsigned NumRegs; // Number of entries in the array
+ unsigned RAReg; // Return address register
+ const MCRegisterClass *Classes; // Pointer to the regclass array
+ unsigned NumClasses; // Number of entries in the array
+ unsigned NumRegUnits; // Number of regunits.
+ const uint16_t (*RegUnitRoots)[2]; // Pointer to regunit root table.
+ const uint16_t *DiffLists; // Pointer to the difflists array
+ const char *RegStrings; // Pointer to the string table.
+ const uint16_t *SubRegIndices; // Pointer to the subreg lookup
+ // array.
+ unsigned NumSubRegIndices; // Number of subreg indices.
+ const uint16_t *RegEncodingTable; // Pointer to array of register
+ // encodings.
+
+ unsigned L2DwarfRegsSize;
+ unsigned EHL2DwarfRegsSize;
+ unsigned Dwarf2LRegsSize;
+ unsigned EHDwarf2LRegsSize;
+ const DwarfLLVMRegPair *L2DwarfRegs; // LLVM to Dwarf regs mapping
+ const DwarfLLVMRegPair *EHL2DwarfRegs; // LLVM to Dwarf regs mapping EH
+ const DwarfLLVMRegPair *Dwarf2LRegs; // Dwarf to LLVM regs mapping
+ const DwarfLLVMRegPair *EHDwarf2LRegs; // Dwarf to LLVM regs mapping EH
+ DenseMap<unsigned, int> L2SEHRegs; // LLVM to SEH regs mapping
+
+public:
+ /// DiffListIterator - Base iterator class that can traverse the
+ /// differentially encoded register and regunit lists in DiffLists.
+ /// Don't use this class directly, use one of the specialized sub-classes
+ /// defined below.
+ class DiffListIterator {
+ uint16_t Val;
+ const uint16_t *List;
+
+ protected:
+ /// Create an invalid iterator. Call init() to point to something useful.
+ DiffListIterator() : Val(0), List(0) {}
+
+ /// init - Point the iterator to InitVal, decoding subsequent values from
+ /// DiffList. The iterator will initially point to InitVal, sub-classes are
+ /// responsible for skipping the seed value if it is not part of the list.
+ void init(uint16_t InitVal, const uint16_t *DiffList) {
+ Val = InitVal;
+ List = DiffList;
+ }
+
+ /// advance - Move to the next list position, return the applied
+ /// differential. This function does not detect the end of the list, that
+ /// is the caller's responsibility (by checking for a 0 return value).
+ unsigned advance() {
+ assert(isValid() && "Cannot move off the end of the list.");
+ uint16_t D = *List++;
+ Val += D;
+ return D;
+ }
+
+ public:
+
+ /// isValid - returns true if this iterator is not yet at the end.
+ bool isValid() const { return List; }
+
+ /// Dereference the iterator to get the value at the current position.
+ unsigned operator*() const { return Val; }
+
+ /// Pre-increment to move to the next position.
+ void operator++() {
+ // The end of the list is encoded as a 0 differential.
+ if (!advance())
+ List = 0;
+ }
+ };
+
+ // These iterators are allowed to sub-class DiffListIterator and access
+ // internal list pointers.
+ friend class MCSubRegIterator;
+ friend class MCSuperRegIterator;
+ friend class MCRegAliasIterator;
+ friend class MCRegUnitIterator;
+ friend class MCRegUnitRootIterator;
+
+ /// InitMCRegisterInfo - Initialize MCRegisterInfo, called by TableGen
+ /// auto-generated routines. *DO NOT USE*.
+ void InitMCRegisterInfo(const MCRegisterDesc *D, unsigned NR, unsigned RA,
+ const MCRegisterClass *C, unsigned NC,
+ const uint16_t (*RURoots)[2],
+ unsigned NRU,
+ const uint16_t *DL,
+ const char *Strings,
+ const uint16_t *SubIndices,
+ unsigned NumIndices,
+ const uint16_t *RET) {
+ Desc = D;
+ NumRegs = NR;
+ RAReg = RA;
+ Classes = C;
+ DiffLists = DL;
+ RegStrings = Strings;
+ NumClasses = NC;
+ RegUnitRoots = RURoots;
+ NumRegUnits = NRU;
+ SubRegIndices = SubIndices;
+ NumSubRegIndices = NumIndices;
+ RegEncodingTable = RET;
+ }
+
+ /// mapLLVMRegsToDwarfRegs - Used to initialize LLVM register to Dwarf
+ /// register number mapping. Called by TableGen auto-generated routines.
+ /// *DO NOT USE*.
+ void mapLLVMRegsToDwarfRegs(const DwarfLLVMRegPair *Map, unsigned Size,
+ bool isEH) {
+ if (isEH) {
+ EHL2DwarfRegs = Map;
+ EHL2DwarfRegsSize = Size;
+ } else {
+ L2DwarfRegs = Map;
+ L2DwarfRegsSize = Size;
+ }
+ }
+
+ /// mapDwarfRegsToLLVMRegs - Used to initialize Dwarf register to LLVM
+ /// register number mapping. Called by TableGen auto-generated routines.
+ /// *DO NOT USE*.
+ void mapDwarfRegsToLLVMRegs(const DwarfLLVMRegPair *Map, unsigned Size,
+ bool isEH) {
+ if (isEH) {
+ EHDwarf2LRegs = Map;
+ EHDwarf2LRegsSize = Size;
+ } else {
+ Dwarf2LRegs = Map;
+ Dwarf2LRegsSize = Size;
+ }
+ }
+
+ /// mapLLVMRegToSEHReg - Used to initialize LLVM register to SEH register
+ /// number mapping. By default the SEH register number is just the same
+ /// as the LLVM register number.
+ /// FIXME: TableGen these numbers. Currently this requires target specific
+ /// initialization code.
+ void mapLLVMRegToSEHReg(unsigned LLVMReg, int SEHReg) {
+ L2SEHRegs[LLVMReg] = SEHReg;
+ }
+
+ /// getRARegister - This method should return the register where the return
+ /// address can be found.
+ unsigned getRARegister() const {
+ return RAReg;
+ }
+
+ const MCRegisterDesc &operator[](unsigned RegNo) const {
+ assert(RegNo < NumRegs &&
+ "Attempting to access record for invalid register number!");
+ return Desc[RegNo];
+ }
+
+ /// Provide a get method, equivalent to [], but more useful if we have a
+ /// pointer to this object.
+ ///
+ const MCRegisterDesc &get(unsigned RegNo) const {
+ return operator[](RegNo);
+ }
+
+ /// getSubReg - Returns the physical register number of sub-register "Index"
+ /// for physical register RegNo. Return zero if the sub-register does not
+ /// exist.
+ unsigned getSubReg(unsigned Reg, unsigned Idx) const;
+
+ /// getMatchingSuperReg - Return a super-register of the specified register
+ /// Reg so its sub-register of index SubIdx is Reg.
+ unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
+ const MCRegisterClass *RC) const;
+
+ /// getSubRegIndex - For a given register pair, return the sub-register index
+ /// if the second register is a sub-register of the first. Return zero
+ /// otherwise.
+ unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const;
+
+ /// getName - Return the human-readable symbolic target-specific name for the
+ /// specified physical register.
+ const char *getName(unsigned RegNo) const {
+ return RegStrings + get(RegNo).Name;
+ }
+
+ /// getNumRegs - Return the number of registers this target has (useful for
+ /// sizing arrays holding per register information)
+ unsigned getNumRegs() const {
+ return NumRegs;
+ }
+
+ /// getNumSubRegIndices - Return the number of sub-register indices
+ /// understood by the target. Index 0 is reserved for the no-op sub-register,
+ /// while 1 to getNumSubRegIndices() - 1 represent real sub-registers.
+ unsigned getNumSubRegIndices() const {
+ return NumSubRegIndices;
+ }
+
+ /// getNumRegUnits - Return the number of (native) register units in the
+ /// target. Register units are numbered from 0 to getNumRegUnits() - 1. They
+ /// can be accessed through MCRegUnitIterator defined below.
+ unsigned getNumRegUnits() const {
+ return NumRegUnits;
+ }
+
+ /// getDwarfRegNum - Map a target register to an equivalent dwarf register
+ /// number. Returns -1 if there is no equivalent value. The second
+ /// parameter allows targets to use different numberings for EH info and
+ /// debugging info.
+ int getDwarfRegNum(unsigned RegNum, bool isEH) const;
+
+ /// getLLVMRegNum - Map a dwarf register back to a target register.
+ ///
+ int getLLVMRegNum(unsigned RegNum, bool isEH) const;
+
+ /// getSEHRegNum - Map a target register to an equivalent SEH register
+ /// number. Returns LLVM register number if there is no equivalent value.
+ int getSEHRegNum(unsigned RegNum) const;
+
+ regclass_iterator regclass_begin() const { return Classes; }
+ regclass_iterator regclass_end() const { return Classes+NumClasses; }
+
+ unsigned getNumRegClasses() const {
+ return (unsigned)(regclass_end()-regclass_begin());
+ }
+
+ /// getRegClass - Returns the register class associated with the enumeration
+ /// value. See class MCOperandInfo.
+ const MCRegisterClass getRegClass(unsigned i) const {
+ assert(i < getNumRegClasses() && "Register Class ID out of range");
+ return Classes[i];
+ }
+
+ /// getEncodingValue - Returns the encoding for RegNo
+ uint16_t getEncodingValue(unsigned RegNo) const {
+ assert(RegNo < NumRegs &&
+ "Attempting to get encoding for invalid register number!");
+ return RegEncodingTable[RegNo];
+ }
+
+};
+
+//===----------------------------------------------------------------------===//
+// Register List Iterators
+//===----------------------------------------------------------------------===//
+
+// MCRegisterInfo provides lists of super-registers, sub-registers, and
+// aliasing registers. Use these iterator classes to traverse the lists.
+
+/// MCSubRegIterator enumerates all sub-registers of Reg.
+class MCSubRegIterator : public MCRegisterInfo::DiffListIterator {
+public:
+ MCSubRegIterator(unsigned Reg, const MCRegisterInfo *MCRI) {
+ init(Reg, MCRI->DiffLists + MCRI->get(Reg).SubRegs);
+ ++*this;
+ }
+};
+
+/// MCSuperRegIterator enumerates all super-registers of Reg.
+class MCSuperRegIterator : public MCRegisterInfo::DiffListIterator {
+public:
+ MCSuperRegIterator(unsigned Reg, const MCRegisterInfo *MCRI) {
+ init(Reg, MCRI->DiffLists + MCRI->get(Reg).SuperRegs);
+ ++*this;
+ }
+};
+
+/// MCRegAliasIterator enumerates all registers aliasing Reg.
+/// If IncludeSelf is set, Reg itself is included in the list.
+class MCRegAliasIterator : public MCRegisterInfo::DiffListIterator {
+public:
+ MCRegAliasIterator(unsigned Reg, const MCRegisterInfo *MCRI,
+ bool IncludeSelf) {
+ init(Reg, MCRI->DiffLists + MCRI->get(Reg).Overlaps);
+ // Initially, the iterator points to Reg itself.
+ if (!IncludeSelf)
+ ++*this;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// Register Units
+//===----------------------------------------------------------------------===//
+
+// Register units are used to compute register aliasing. Every register has at
+// least one register unit, but it can have more. Two registers overlap if and
+// only if they have a common register unit.
+//
+// A target with a complicated sub-register structure will typically have many
+// fewer register units than actual registers. MCRI::getNumRegUnits() returns
+// the number of register units in the target.
+
+// MCRegUnitIterator enumerates a list of register units for Reg. The list is
+// in ascending numerical order.
+class MCRegUnitIterator : public MCRegisterInfo::DiffListIterator {
+public:
+ /// MCRegUnitIterator - Create an iterator that traverses the register units
+ /// in Reg.
+ MCRegUnitIterator(unsigned Reg, const MCRegisterInfo *MCRI) {
+ // Decode the RegUnits MCRegisterDesc field.
+ unsigned RU = MCRI->get(Reg).RegUnits;
+ unsigned Scale = RU & 15;
+ unsigned Offset = RU >> 4;
+
+ // Initialize the iterator to Reg * Scale, and the List pointer to
+ // DiffLists + Offset.
+ init(Reg * Scale, MCRI->DiffLists + Offset);
+
+ // That may not be a valid unit, we need to advance by one to get the real
+ // unit number. The first differential can be 0 which would normally
+ // terminate the list, but since we know every register has at least one
+ // unit, we can allow a 0 differential here.
+ advance();
+ }
+};
+
+// Each register unit has one or two root registers. The complete set of
+// registers containing a register unit is the union of the roots and their
+// super-registers. All registers aliasing Unit can be visited like this:
+//
+// for (MCRegUnitRootIterator RI(Unit, MCRI); RI.isValid(); ++RI) {
+// unsigned Root = *RI;
+// visit(Root);
+// for (MCSuperRegIterator SI(Root, MCRI); SI.isValid(); ++SI)
+// visit(*SI);
+// }
+
+/// MCRegUnitRootIterator enumerates the root registers of a register unit.
+class MCRegUnitRootIterator {
+ uint16_t Reg0;
+ uint16_t Reg1;
+public:
+ MCRegUnitRootIterator(unsigned RegUnit, const MCRegisterInfo *MCRI) {
+ assert(RegUnit < MCRI->getNumRegUnits() && "Invalid register unit");
+ Reg0 = MCRI->RegUnitRoots[RegUnit][0];
+ Reg1 = MCRI->RegUnitRoots[RegUnit][1];
+ }
+
+ /// Dereference to get the current root register.
+ unsigned operator*() const {
+ return Reg0;
+ }
+
+ /// isValid - Check if the iterator is at the end of the list.
+ bool isValid() const {
+ return Reg0;
+ }
+
+ /// Preincrement to move to the next root register.
+ void operator++() {
+ assert(isValid() && "Cannot move off the end of the list.");
+ Reg0 = Reg1;
+ Reg1 = 0;
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCSchedule.h b/include/llvm/MC/MCSchedule.h
new file mode 100644
index 00000000000..41bdb02f615
--- /dev/null
+++ b/include/llvm/MC/MCSchedule.h
@@ -0,0 +1,230 @@
+//===-- llvm/MC/MCSchedule.h - Scheduling -----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the classes used to describe a subtarget's machine model
+// for scheduling and other instruction cost heuristics.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCSCHEDMODEL_H
+#define LLVM_MC_MCSCHEDMODEL_H
+
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+
+namespace llvm {
+
+struct InstrItinerary;
+
+/// Define a kind of processor resource that will be modeled by the scheduler.
+struct MCProcResourceDesc {
+#ifndef NDEBUG
+ const char *Name;
+#endif
+ unsigned Count; // Number of resource of this kind
+ unsigned SuperIdx; // Index of the resources kind that contains this kind.
+
+ bool operator==(const MCProcResourceDesc &Other) const {
+ return Count == Other.Count && SuperIdx == Other.SuperIdx;
+ }
+};
+
+/// Identify one of the processor resource kinds consumed by a particular
+/// scheduling class for the specified number of cycles.
+struct MCWriteProcResEntry {
+ unsigned ProcResourceIdx;
+ unsigned Cycles;
+
+ bool operator==(const MCWriteProcResEntry &Other) const {
+ return ProcResourceIdx == Other.ProcResourceIdx && Cycles == Other.Cycles;
+ }
+};
+
+/// Specify the latency in cpu cycles for a particular scheduling class and def
+/// index. Also identify the WriteResources of this def. When the operand
+/// expands to a sequence of writes, this ID is the last write in the sequence.
+struct MCWriteLatencyEntry {
+ unsigned Cycles;
+ unsigned WriteResourceID;
+
+ bool operator==(const MCWriteLatencyEntry &Other) const {
+ return Cycles == Other.Cycles && WriteResourceID == Other.WriteResourceID;
+ }
+};
+
+/// Specify the number of cycles allowed after instruction issue before a
+/// particular use operand reads its registers. This effectively reduces the
+/// write's latency. Here we allow negative cycles for corner cases where
+/// latency increases. This rule only applies when the entry's WriteResource
+/// matches the write's WriteResource.
+///
+/// MCReadAdvanceEntries are sorted first by operand index (UseIdx), then by
+/// WriteResourceIdx.
+struct MCReadAdvanceEntry {
+ unsigned UseIdx;
+ unsigned WriteResourceID;
+ int Cycles;
+
+ bool operator==(const MCReadAdvanceEntry &Other) const {
+ return UseIdx == Other.UseIdx && WriteResourceID == Other.WriteResourceID
+ && Cycles == Other.Cycles;
+ }
+};
+
+/// Summarize the scheduling resources required for an instruction of a
+/// particular scheduling class.
+///
+/// Defined as an aggregate struct for creating tables with initializer lists.
+struct MCSchedClassDesc {
+ static const unsigned short InvalidNumMicroOps = UINT16_MAX;
+ static const unsigned short VariantNumMicroOps = UINT16_MAX - 1;
+
+#ifndef NDEBUG
+ const char* Name;
+#endif
+ unsigned short NumMicroOps;
+ bool BeginGroup;
+ bool EndGroup;
+ unsigned WriteProcResIdx; // First index into WriteProcResTable.
+ unsigned NumWriteProcResEntries;
+ unsigned WriteLatencyIdx; // First index into WriteLatencyTable.
+ unsigned NumWriteLatencyEntries;
+ unsigned ReadAdvanceIdx; // First index into ReadAdvanceTable.
+ unsigned NumReadAdvanceEntries;
+
+ bool isValid() const {
+ return NumMicroOps != InvalidNumMicroOps;
+ }
+ bool isVariant() const {
+ return NumMicroOps == VariantNumMicroOps;
+ }
+};
+
+/// Machine model for scheduling, bundling, and heuristics.
+///
+/// The machine model directly provides basic information about the
+/// microarchitecture to the scheduler in the form of properties. It also
+/// optionally refers to scheduler resource tables and itinerary
+/// tables. Scheduler resource tables model the latency and cost for each
+/// instruction type. Itinerary tables are an independant mechanism that
+/// provides a detailed reservation table describing each cycle of instruction
+/// execution. Subtargets may define any or all of the above categories of data
+/// depending on the type of CPU and selected scheduler.
+class MCSchedModel {
+public:
+ static MCSchedModel DefaultSchedModel; // For unknown processors.
+
+ // IssueWidth is the maximum number of instructions that may be scheduled in
+ // the same per-cycle group.
+ unsigned IssueWidth;
+ static const unsigned DefaultIssueWidth = 1;
+
+ // MinLatency is the minimum latency between a register write
+ // followed by a data dependent read. This determines which
+ // instructions may be scheduled in the same per-cycle group. This
+ // is distinct from *expected* latency, which determines the likely
+ // critical path but does not guarantee a pipeline
+ // hazard. MinLatency can always be overridden by the number of
+ // InstrStage cycles.
+ //
+ // (-1) Standard in-order processor.
+ // Use InstrItinerary OperandCycles as MinLatency.
+ // If no OperandCycles exist, then use the cycle of the last InstrStage.
+ //
+ // (0) Out-of-order processor, or in-order with bundled dependencies.
+ // RAW dependencies may be dispatched in the same cycle.
+ // Optional InstrItinerary OperandCycles provides expected latency.
+ //
+ // (>0) In-order processor with variable latencies.
+ // Use the greater of this value or the cycle of the last InstrStage.
+ // Optional InstrItinerary OperandCycles provides expected latency.
+ // TODO: can't yet specify both min and expected latency per operand.
+ int MinLatency;
+ static const unsigned DefaultMinLatency = -1;
+
+ // LoadLatency is the expected latency of load instructions.
+ //
+ // If MinLatency >= 0, this may be overriden for individual load opcodes by
+ // InstrItinerary OperandCycles.
+ unsigned LoadLatency;
+ static const unsigned DefaultLoadLatency = 4;
+
+ // HighLatency is the expected latency of "very high latency" operations.
+ // See TargetInstrInfo::isHighLatencyDef().
+ // By default, this is set to an arbitrarily high number of cycles
+ // likely to have some impact on scheduling heuristics.
+ // If MinLatency >= 0, this may be overriden by InstrItinData OperandCycles.
+ unsigned HighLatency;
+ static const unsigned DefaultHighLatency = 10;
+
+ // MispredictPenalty is the typical number of extra cycles the processor
+ // takes to recover from a branch misprediction.
+ unsigned MispredictPenalty;
+ static const unsigned DefaultMispredictPenalty = 10;
+
+private:
+ unsigned ProcID;
+ const MCProcResourceDesc *ProcResourceTable;
+ const MCSchedClassDesc *SchedClassTable;
+ unsigned NumProcResourceKinds;
+ unsigned NumSchedClasses;
+ // Instruction itinerary tables used by InstrItineraryData.
+ friend class InstrItineraryData;
+ const InstrItinerary *InstrItineraries;
+
+public:
+ // Default's must be specified as static const literals so that tablegenerated
+ // target code can use it in static initializers. The defaults need to be
+ // initialized in this default ctor because some clients directly instantiate
+ // MCSchedModel instead of using a generated itinerary.
+ MCSchedModel(): IssueWidth(DefaultIssueWidth),
+ MinLatency(DefaultMinLatency),
+ LoadLatency(DefaultLoadLatency),
+ HighLatency(DefaultHighLatency),
+ MispredictPenalty(DefaultMispredictPenalty),
+ ProcID(0), ProcResourceTable(0), SchedClassTable(0),
+ NumProcResourceKinds(0), NumSchedClasses(0),
+ InstrItineraries(0) {
+ (void)NumProcResourceKinds;
+ (void)NumSchedClasses;
+ }
+
+ // Table-gen driven ctor.
+ MCSchedModel(unsigned iw, int ml, unsigned ll, unsigned hl, unsigned mp,
+ unsigned pi, const MCProcResourceDesc *pr,
+ const MCSchedClassDesc *sc, unsigned npr, unsigned nsc,
+ const InstrItinerary *ii):
+ IssueWidth(iw), MinLatency(ml), LoadLatency(ll), HighLatency(hl),
+ MispredictPenalty(mp), ProcID(pi), ProcResourceTable(pr),
+ SchedClassTable(sc), NumProcResourceKinds(npr), NumSchedClasses(nsc),
+ InstrItineraries(ii) {}
+
+ unsigned getProcessorID() const { return ProcID; }
+
+ /// Does this machine model include instruction-level scheduling.
+ bool hasInstrSchedModel() const { return SchedClassTable; }
+
+ const MCProcResourceDesc *getProcResource(unsigned ProcResourceIdx) const {
+ assert(hasInstrSchedModel() && "No scheduling machine model");
+
+ assert(ProcResourceIdx < NumProcResourceKinds && "bad proc resource idx");
+ return &ProcResourceTable[ProcResourceIdx];
+ }
+
+ const MCSchedClassDesc *getSchedClassDesc(unsigned SchedClassIdx) const {
+ assert(hasInstrSchedModel() && "No scheduling machine model");
+
+ assert(SchedClassIdx < NumSchedClasses && "bad scheduling class idx");
+ return &SchedClassTable[SchedClassIdx];
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCSection.h b/include/llvm/MC/MCSection.h
new file mode 100644
index 00000000000..a92fc379e19
--- /dev/null
+++ b/include/llvm/MC/MCSection.h
@@ -0,0 +1,73 @@
+//===- MCSection.h - Machine Code Sections ----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the MCSection class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCSECTION_H
+#define LLVM_MC_MCSECTION_H
+
+#include "llvm/MC/SectionKind.h"
+#include "llvm/Support/Compiler.h"
+
+namespace llvm {
+ class MCAsmInfo;
+ class raw_ostream;
+
+ /// MCSection - Instances of this class represent a uniqued identifier for a
+ /// section in the current translation unit. The MCContext class uniques and
+ /// creates these.
+ class MCSection {
+ public:
+ enum SectionVariant {
+ SV_COFF = 0,
+ SV_ELF,
+ SV_MachO
+ };
+
+ private:
+ MCSection(const MCSection&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCSection&) LLVM_DELETED_FUNCTION;
+ protected:
+ MCSection(SectionVariant V, SectionKind K) : Variant(V), Kind(K) {}
+ SectionVariant Variant;
+ SectionKind Kind;
+ public:
+ virtual ~MCSection();
+
+ SectionKind getKind() const { return Kind; }
+
+ SectionVariant getVariant() const { return Variant; }
+
+ virtual void PrintSwitchToSection(const MCAsmInfo &MAI,
+ raw_ostream &OS) const = 0;
+
+ /// isBaseAddressKnownZero - Return true if we know that this section will
+ /// get a base address of zero. In cases where we know that this is true we
+ /// can emit section offsets as direct references to avoid a subtraction
+ /// from the base of the section, saving a relocation.
+ virtual bool isBaseAddressKnownZero() const {
+ return false;
+ }
+
+ // UseCodeAlign - Return true if a .align directive should use
+ // "optimized nops" to fill instead of 0s.
+ virtual bool UseCodeAlign() const = 0;
+
+ /// isVirtualSection - Check whether this section is "virtual", that is
+ /// has no actual object file contents.
+ virtual bool isVirtualSection() const = 0;
+
+ static bool classof(const MCSection *) { return true; }
+ };
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCSectionCOFF.h b/include/llvm/MC/MCSectionCOFF.h
new file mode 100644
index 00000000000..7eacde57f48
--- /dev/null
+++ b/include/llvm/MC/MCSectionCOFF.h
@@ -0,0 +1,69 @@
+//===- MCSectionCOFF.h - COFF Machine Code Sections -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the MCSectionCOFF class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCSECTIONCOFF_H
+#define LLVM_MC_MCSECTIONCOFF_H
+
+#include "llvm/MC/MCSection.h"
+#include "llvm/Support/COFF.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+
+/// MCSectionCOFF - This represents a section on Windows
+ class MCSectionCOFF : public MCSection {
+ // The memory for this string is stored in the same MCContext as *this.
+ StringRef SectionName;
+
+ /// Characteristics - This is the Characteristics field of a section,
+ // drawn from the enums below.
+ unsigned Characteristics;
+
+ /// Selection - This is the Selection field for the section symbol, if
+ /// it is a COMDAT section (Characteristics & IMAGE_SCN_LNK_COMDAT) != 0
+ int Selection;
+
+ private:
+ friend class MCContext;
+ MCSectionCOFF(StringRef Section, unsigned Characteristics,
+ int Selection, SectionKind K)
+ : MCSection(SV_COFF, K), SectionName(Section),
+ Characteristics(Characteristics), Selection (Selection) {
+ assert ((Characteristics & 0x00F00000) == 0 &&
+ "alignment must not be set upon section creation");
+ }
+ ~MCSectionCOFF();
+
+ public:
+ /// ShouldOmitSectionDirective - Decides whether a '.section' directive
+ /// should be printed before the section name
+ bool ShouldOmitSectionDirective(StringRef Name, const MCAsmInfo &MAI) const;
+
+ StringRef getSectionName() const { return SectionName; }
+ unsigned getCharacteristics() const { return Characteristics; }
+ int getSelection () const { return Selection; }
+
+ virtual void PrintSwitchToSection(const MCAsmInfo &MAI,
+ raw_ostream &OS) const;
+ virtual bool UseCodeAlign() const;
+ virtual bool isVirtualSection() const;
+
+ static bool classof(const MCSection *S) {
+ return S->getVariant() == SV_COFF;
+ }
+ static bool classof(const MCSectionCOFF *) { return true; }
+ };
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCSectionELF.h b/include/llvm/MC/MCSectionELF.h
new file mode 100644
index 00000000000..7321ca83e89
--- /dev/null
+++ b/include/llvm/MC/MCSectionELF.h
@@ -0,0 +1,88 @@
+//===- MCSectionELF.h - ELF Machine Code Sections ---------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the MCSectionELF class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCSECTIONELF_H
+#define LLVM_MC_MCSECTIONELF_H
+
+#include "llvm/MC/MCSection.h"
+#include "llvm/Support/ELF.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+
+class MCSymbol;
+
+/// MCSectionELF - This represents a section on linux, lots of unix variants
+/// and some bare metal systems.
+class MCSectionELF : public MCSection {
+ /// SectionName - This is the name of the section. The referenced memory is
+ /// owned by TargetLoweringObjectFileELF's ELFUniqueMap.
+ StringRef SectionName;
+
+ /// Type - This is the sh_type field of a section, drawn from the enums below.
+ unsigned Type;
+
+ /// Flags - This is the sh_flags field of a section, drawn from the enums.
+ /// below.
+ unsigned Flags;
+
+ /// EntrySize - The size of each entry in this section. This size only
+ /// makes sense for sections that contain fixed-sized entries. If a
+ /// section does not contain fixed-sized entries 'EntrySize' will be 0.
+ unsigned EntrySize;
+
+ const MCSymbol *Group;
+
+private:
+ friend class MCContext;
+ MCSectionELF(StringRef Section, unsigned type, unsigned flags,
+ SectionKind K, unsigned entrySize, const MCSymbol *group)
+ : MCSection(SV_ELF, K), SectionName(Section), Type(type), Flags(flags),
+ EntrySize(entrySize), Group(group) {}
+ ~MCSectionELF();
+public:
+
+ /// ShouldOmitSectionDirective - Decides whether a '.section' directive
+ /// should be printed before the section name
+ bool ShouldOmitSectionDirective(StringRef Name, const MCAsmInfo &MAI) const;
+
+ StringRef getSectionName() const { return SectionName; }
+ unsigned getType() const { return Type; }
+ unsigned getFlags() const { return Flags; }
+ unsigned getEntrySize() const { return EntrySize; }
+ const MCSymbol *getGroup() const { return Group; }
+
+ void PrintSwitchToSection(const MCAsmInfo &MAI,
+ raw_ostream &OS) const;
+ virtual bool UseCodeAlign() const;
+ virtual bool isVirtualSection() const;
+
+ /// isBaseAddressKnownZero - We know that non-allocatable sections (like
+ /// debug info) have a base of zero.
+ virtual bool isBaseAddressKnownZero() const {
+ return (getFlags() & ELF::SHF_ALLOC) == 0;
+ }
+
+ static bool classof(const MCSection *S) {
+ return S->getVariant() == SV_ELF;
+ }
+ static bool classof(const MCSectionELF *) { return true; }
+
+ // Return the entry size for sections with fixed-width data.
+ static unsigned DetermineEntrySize(SectionKind Kind);
+
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCSectionMachO.h b/include/llvm/MC/MCSectionMachO.h
new file mode 100644
index 00000000000..15eb4f4a768
--- /dev/null
+++ b/include/llvm/MC/MCSectionMachO.h
@@ -0,0 +1,182 @@
+//===- MCSectionMachO.h - MachO Machine Code Sections -----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the MCSectionMachO class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCSECTIONMACHO_H
+#define LLVM_MC_MCSECTIONMACHO_H
+
+#include "llvm/MC/MCSection.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+
+/// MCSectionMachO - This represents a section on a Mach-O system (used by
+/// Mac OS X). On a Mac system, these are also described in
+/// /usr/include/mach-o/loader.h.
+class MCSectionMachO : public MCSection {
+ char SegmentName[16]; // Not necessarily null terminated!
+ char SectionName[16]; // Not necessarily null terminated!
+
+ /// TypeAndAttributes - This is the SECTION_TYPE and SECTION_ATTRIBUTES
+ /// field of a section, drawn from the enums below.
+ unsigned TypeAndAttributes;
+
+ /// Reserved2 - The 'reserved2' field of a section, used to represent the
+ /// size of stubs, for example.
+ unsigned Reserved2;
+
+ MCSectionMachO(StringRef Segment, StringRef Section,
+ unsigned TAA, unsigned reserved2, SectionKind K);
+ friend class MCContext;
+public:
+
+ /// These are the section type and attributes fields. A MachO section can
+ /// have only one Type, but can have any of the attributes specified.
+ enum {
+ // TypeAndAttributes bitmasks.
+ SECTION_TYPE = 0x000000FFU,
+ SECTION_ATTRIBUTES = 0xFFFFFF00U,
+
+ // Valid section types.
+
+ /// S_REGULAR - Regular section.
+ S_REGULAR = 0x00U,
+ /// S_ZEROFILL - Zero fill on demand section.
+ S_ZEROFILL = 0x01U,
+ /// S_CSTRING_LITERALS - Section with literal C strings.
+ S_CSTRING_LITERALS = 0x02U,
+ /// S_4BYTE_LITERALS - Section with 4 byte literals.
+ S_4BYTE_LITERALS = 0x03U,
+ /// S_8BYTE_LITERALS - Section with 8 byte literals.
+ S_8BYTE_LITERALS = 0x04U,
+ /// S_LITERAL_POINTERS - Section with pointers to literals.
+ S_LITERAL_POINTERS = 0x05U,
+ /// S_NON_LAZY_SYMBOL_POINTERS - Section with non-lazy symbol pointers.
+ S_NON_LAZY_SYMBOL_POINTERS = 0x06U,
+ /// S_LAZY_SYMBOL_POINTERS - Section with lazy symbol pointers.
+ S_LAZY_SYMBOL_POINTERS = 0x07U,
+ /// S_SYMBOL_STUBS - Section with symbol stubs, byte size of stub in
+ /// the Reserved2 field.
+ S_SYMBOL_STUBS = 0x08U,
+ /// S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for
+ /// initialization.
+ S_MOD_INIT_FUNC_POINTERS = 0x09U,
+ /// S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for
+ /// termination.
+ S_MOD_TERM_FUNC_POINTERS = 0x0AU,
+ /// S_COALESCED - Section contains symbols that are to be coalesced.
+ S_COALESCED = 0x0BU,
+ /// S_GB_ZEROFILL - Zero fill on demand section (that can be larger than 4
+ /// gigabytes).
+ S_GB_ZEROFILL = 0x0CU,
+ /// S_INTERPOSING - Section with only pairs of function pointers for
+ /// interposing.
+ S_INTERPOSING = 0x0DU,
+ /// S_16BYTE_LITERALS - Section with only 16 byte literals.
+ S_16BYTE_LITERALS = 0x0EU,
+ /// S_DTRACE_DOF - Section contains DTrace Object Format.
+ S_DTRACE_DOF = 0x0FU,
+ /// S_LAZY_DYLIB_SYMBOL_POINTERS - Section with lazy symbol pointers to
+ /// lazy loaded dylibs.
+ S_LAZY_DYLIB_SYMBOL_POINTERS = 0x10U,
+ /// S_THREAD_LOCAL_REGULAR - Section with ....
+ S_THREAD_LOCAL_REGULAR = 0x11U,
+ /// S_THREAD_LOCAL_ZEROFILL - Thread local zerofill section.
+ S_THREAD_LOCAL_ZEROFILL = 0x12U,
+ /// S_THREAD_LOCAL_VARIABLES - Section with thread local variable structure
+ /// data.
+ S_THREAD_LOCAL_VARIABLES = 0x13U,
+ /// S_THREAD_LOCAL_VARIABLE_POINTERS - Section with ....
+ S_THREAD_LOCAL_VARIABLE_POINTERS = 0x14U,
+ /// S_THREAD_LOCAL_INIT_FUNCTION_POINTERS - Section with thread local
+ /// variable initialization pointers to functions.
+ S_THREAD_LOCAL_INIT_FUNCTION_POINTERS = 0x15U,
+
+ LAST_KNOWN_SECTION_TYPE = S_THREAD_LOCAL_INIT_FUNCTION_POINTERS,
+
+
+ // Valid section attributes.
+
+ /// S_ATTR_PURE_INSTRUCTIONS - Section contains only true machine
+ /// instructions.
+ S_ATTR_PURE_INSTRUCTIONS = 1U << 31,
+ /// S_ATTR_NO_TOC - Section contains coalesced symbols that are not to be
+ /// in a ranlib table of contents.
+ S_ATTR_NO_TOC = 1U << 30,
+ /// S_ATTR_STRIP_STATIC_SYMS - Ok to strip static symbols in this section
+ /// in files with the MY_DYLDLINK flag.
+ S_ATTR_STRIP_STATIC_SYMS = 1U << 29,
+ /// S_ATTR_NO_DEAD_STRIP - No dead stripping.
+ S_ATTR_NO_DEAD_STRIP = 1U << 28,
+ /// S_ATTR_LIVE_SUPPORT - Blocks are live if they reference live blocks.
+ S_ATTR_LIVE_SUPPORT = 1U << 27,
+ /// S_ATTR_SELF_MODIFYING_CODE - Used with i386 code stubs written on by
+ /// dyld.
+ S_ATTR_SELF_MODIFYING_CODE = 1U << 26,
+ /// S_ATTR_DEBUG - A debug section.
+ S_ATTR_DEBUG = 1U << 25,
+ /// S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions.
+ S_ATTR_SOME_INSTRUCTIONS = 1U << 10,
+ /// S_ATTR_EXT_RELOC - Section has external relocation entries.
+ S_ATTR_EXT_RELOC = 1U << 9,
+ /// S_ATTR_LOC_RELOC - Section has local relocation entries.
+ S_ATTR_LOC_RELOC = 1U << 8
+ };
+
+ StringRef getSegmentName() const {
+ // SegmentName is not necessarily null terminated!
+ if (SegmentName[15])
+ return StringRef(SegmentName, 16);
+ return StringRef(SegmentName);
+ }
+ StringRef getSectionName() const {
+ // SectionName is not necessarily null terminated!
+ if (SectionName[15])
+ return StringRef(SectionName, 16);
+ return StringRef(SectionName);
+ }
+
+ unsigned getTypeAndAttributes() const { return TypeAndAttributes; }
+ unsigned getStubSize() const { return Reserved2; }
+
+ unsigned getType() const { return TypeAndAttributes & SECTION_TYPE; }
+ bool hasAttribute(unsigned Value) const {
+ return (TypeAndAttributes & Value) != 0;
+ }
+
+ /// ParseSectionSpecifier - Parse the section specifier indicated by "Spec".
+ /// This is a string that can appear after a .section directive in a mach-o
+ /// flavored .s file. If successful, this fills in the specified Out
+ /// parameters and returns an empty string. When an invalid section
+ /// specifier is present, this returns a string indicating the problem.
+ /// If no TAA was parsed, TAA is not altered, and TAAWasSet becomes false.
+ static std::string ParseSectionSpecifier(StringRef Spec, // In.
+ StringRef &Segment, // Out.
+ StringRef &Section, // Out.
+ unsigned &TAA, // Out.
+ bool &TAAParsed, // Out.
+ unsigned &StubSize); // Out.
+
+ virtual void PrintSwitchToSection(const MCAsmInfo &MAI,
+ raw_ostream &OS) const;
+ virtual bool UseCodeAlign() const;
+ virtual bool isVirtualSection() const;
+
+ static bool classof(const MCSection *S) {
+ return S->getVariant() == SV_MachO;
+ }
+ static bool classof(const MCSectionMachO *) { return true; }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCStreamer.h b/include/llvm/MC/MCStreamer.h
new file mode 100644
index 00000000000..44698989c17
--- /dev/null
+++ b/include/llvm/MC/MCStreamer.h
@@ -0,0 +1,626 @@
+//===- MCStreamer.h - High-level Streaming Machine Code Output --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the MCStreamer class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCSTREAMER_H
+#define LLVM_MC_MCSTREAMER_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/MC/MCDirectives.h"
+#include "llvm/MC/MCDwarf.h"
+#include "llvm/MC/MCWin64EH.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace llvm {
+ class MCAsmBackend;
+ class MCCodeEmitter;
+ class MCContext;
+ class MCExpr;
+ class MCInst;
+ class MCInstPrinter;
+ class MCSection;
+ class MCSymbol;
+ class StringRef;
+ class Twine;
+ class raw_ostream;
+ class formatted_raw_ostream;
+
+ /// MCStreamer - Streaming machine code generation interface. This interface
+ /// is intended to provide a programatic interface that is very similar to the
+ /// level that an assembler .s file provides. It has callbacks to emit bytes,
+ /// handle directives, etc. The implementation of this interface retains
+ /// state to know what the current section is etc.
+ ///
+ /// There are multiple implementations of this interface: one for writing out
+ /// a .s file, and implementations that write out .o files of various formats.
+ ///
+ class MCStreamer {
+ MCContext &Context;
+
+ MCStreamer(const MCStreamer&) LLVM_DELETED_FUNCTION;
+ MCStreamer &operator=(const MCStreamer&) LLVM_DELETED_FUNCTION;
+
+ bool EmitEHFrame;
+ bool EmitDebugFrame;
+
+ std::vector<MCDwarfFrameInfo> FrameInfos;
+ MCDwarfFrameInfo *getCurrentFrameInfo();
+ void EnsureValidFrame();
+
+ std::vector<MCWin64EHUnwindInfo *> W64UnwindInfos;
+ MCWin64EHUnwindInfo *CurrentW64UnwindInfo;
+ void setCurrentW64UnwindInfo(MCWin64EHUnwindInfo *Frame);
+ void EnsureValidW64UnwindInfo();
+
+ MCSymbol* LastSymbol;
+
+ /// SectionStack - This is stack of current and previous section
+ /// values saved by PushSection.
+ SmallVector<std::pair<const MCSection *,
+ const MCSection *>, 4> SectionStack;
+
+ protected:
+ MCStreamer(MCContext &Ctx);
+
+ const MCExpr *BuildSymbolDiff(MCContext &Context, const MCSymbol *A,
+ const MCSymbol *B);
+
+ const MCExpr *ForceExpAbs(const MCExpr* Expr);
+
+ void RecordProcStart(MCDwarfFrameInfo &Frame);
+ virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
+ void RecordProcEnd(MCDwarfFrameInfo &Frame);
+ virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame);
+ void EmitFrames(bool usingCFI);
+
+ MCWin64EHUnwindInfo *getCurrentW64UnwindInfo(){return CurrentW64UnwindInfo;}
+ void EmitW64Tables();
+
+ public:
+ virtual ~MCStreamer();
+
+ MCContext &getContext() const { return Context; }
+
+ unsigned getNumFrameInfos() {
+ return FrameInfos.size();
+ }
+
+ const MCDwarfFrameInfo &getFrameInfo(unsigned i) {
+ return FrameInfos[i];
+ }
+
+ ArrayRef<MCDwarfFrameInfo> getFrameInfos() {
+ return FrameInfos;
+ }
+
+ unsigned getNumW64UnwindInfos() {
+ return W64UnwindInfos.size();
+ }
+
+ MCWin64EHUnwindInfo &getW64UnwindInfo(unsigned i) {
+ return *W64UnwindInfos[i];
+ }
+
+ /// @name Assembly File Formatting.
+ /// @{
+
+ /// isVerboseAsm - Return true if this streamer supports verbose assembly
+ /// and if it is enabled.
+ virtual bool isVerboseAsm() const { return false; }
+
+ /// hasRawTextSupport - Return true if this asm streamer supports emitting
+ /// unformatted text to the .s file with EmitRawText.
+ virtual bool hasRawTextSupport() const { return false; }
+
+ /// AddComment - Add a comment that can be emitted to the generated .s
+ /// file if applicable as a QoI issue to make the output of the compiler
+ /// more readable. This only affects the MCAsmStreamer, and only when
+ /// verbose assembly output is enabled.
+ ///
+ /// If the comment includes embedded \n's, they will each get the comment
+ /// prefix as appropriate. The added comment should not end with a \n.
+ virtual void AddComment(const Twine &T) {}
+
+ /// GetCommentOS - Return a raw_ostream that comments can be written to.
+ /// Unlike AddComment, you are required to terminate comments with \n if you
+ /// use this method.
+ virtual raw_ostream &GetCommentOS();
+
+ /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
+ virtual void AddBlankLine() {}
+
+ /// @}
+
+ /// @name Symbol & Section Management
+ /// @{
+
+ /// getCurrentSection - Return the current section that the streamer is
+ /// emitting code to.
+ const MCSection *getCurrentSection() const {
+ if (!SectionStack.empty())
+ return SectionStack.back().first;
+ return NULL;
+ }
+
+ /// getPreviousSection - Return the previous section that the streamer is
+ /// emitting code to.
+ const MCSection *getPreviousSection() const {
+ if (!SectionStack.empty())
+ return SectionStack.back().second;
+ return NULL;
+ }
+
+ /// ChangeSection - Update streamer for a new active section.
+ ///
+ /// This is called by PopSection and SwitchSection, if the current
+ /// section changes.
+ virtual void ChangeSection(const MCSection *) = 0;
+
+ /// pushSection - Save the current and previous section on the
+ /// section stack.
+ void PushSection() {
+ SectionStack.push_back(std::make_pair(getCurrentSection(),
+ getPreviousSection()));
+ }
+
+ /// popSection - Restore the current and previous section from
+ /// the section stack. Calls ChangeSection as needed.
+ ///
+ /// Returns false if the stack was empty.
+ bool PopSection() {
+ if (SectionStack.size() <= 1)
+ return false;
+ const MCSection *oldSection = SectionStack.pop_back_val().first;
+ const MCSection *curSection = SectionStack.back().first;
+
+ if (oldSection != curSection)
+ ChangeSection(curSection);
+ return true;
+ }
+
+ /// SwitchSection - Set the current section where code is being emitted to
+ /// @p Section. This is required to update CurSection.
+ ///
+ /// This corresponds to assembler directives like .section, .text, etc.
+ void SwitchSection(const MCSection *Section) {
+ assert(Section && "Cannot switch to a null section!");
+ const MCSection *curSection = SectionStack.back().first;
+ SectionStack.back().second = curSection;
+ if (Section != curSection) {
+ SectionStack.back().first = Section;
+ ChangeSection(Section);
+ }
+ }
+
+ /// SwitchSectionNoChange - Set the current section where code is being
+ /// emitted to @p Section. This is required to update CurSection. This
+ /// version does not call ChangeSection.
+ void SwitchSectionNoChange(const MCSection *Section) {
+ assert(Section && "Cannot switch to a null section!");
+ const MCSection *curSection = SectionStack.back().first;
+ SectionStack.back().second = curSection;
+ if (Section != curSection)
+ SectionStack.back().first = Section;
+ }
+
+ /// InitSections - Create the default sections and set the initial one.
+ virtual void InitSections() = 0;
+
+ /// EmitLabel - Emit a label for @p Symbol into the current section.
+ ///
+ /// This corresponds to an assembler statement such as:
+ /// foo:
+ ///
+ /// @param Symbol - The symbol to emit. A given symbol should only be
+ /// emitted as a label once, and symbols emitted as a label should never be
+ /// used in an assignment.
+ virtual void EmitLabel(MCSymbol *Symbol);
+
+ virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
+ MCSymbol *EHSymbol);
+
+ /// EmitAssemblerFlag - Note in the output the specified @p Flag.
+ virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) = 0;
+
+ /// EmitDataRegion - Note in the output the specified region @p Kind.
+ virtual void EmitDataRegion(MCDataRegionType Kind) {}
+
+ /// EmitThumbFunc - Note in the output that the specified @p Func is
+ /// a Thumb mode function (ARM target only).
+ virtual void EmitThumbFunc(MCSymbol *Func) = 0;
+
+ /// EmitAssignment - Emit an assignment of @p Value to @p Symbol.
+ ///
+ /// This corresponds to an assembler statement such as:
+ /// symbol = value
+ ///
+ /// The assignment generates no code, but has the side effect of binding the
+ /// value in the current context. For the assembly streamer, this prints the
+ /// binding into the .s file.
+ ///
+ /// @param Symbol - The symbol being assigned to.
+ /// @param Value - The value for the symbol.
+ virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) = 0;
+
+ /// EmitWeakReference - Emit an weak reference from @p Alias to @p Symbol.
+ ///
+ /// This corresponds to an assembler statement such as:
+ /// .weakref alias, symbol
+ ///
+ /// @param Alias - The alias that is being created.
+ /// @param Symbol - The symbol being aliased.
+ virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) = 0;
+
+ /// EmitSymbolAttribute - Add the given @p Attribute to @p Symbol.
+ virtual void EmitSymbolAttribute(MCSymbol *Symbol,
+ MCSymbolAttr Attribute) = 0;
+
+ /// EmitSymbolDesc - Set the @p DescValue for the @p Symbol.
+ ///
+ /// @param Symbol - The symbol to have its n_desc field set.
+ /// @param DescValue - The value to set into the n_desc field.
+ virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) = 0;
+
+ /// BeginCOFFSymbolDef - Start emitting COFF symbol definition
+ ///
+ /// @param Symbol - The symbol to have its External & Type fields set.
+ virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) = 0;
+
+ /// EmitCOFFSymbolStorageClass - Emit the storage class of the symbol.
+ ///
+ /// @param StorageClass - The storage class the symbol should have.
+ virtual void EmitCOFFSymbolStorageClass(int StorageClass) = 0;
+
+ /// EmitCOFFSymbolType - Emit the type of the symbol.
+ ///
+ /// @param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h)
+ virtual void EmitCOFFSymbolType(int Type) = 0;
+
+ /// EndCOFFSymbolDef - Marks the end of the symbol definition.
+ virtual void EndCOFFSymbolDef() = 0;
+
+ /// EmitCOFFSecRel32 - Emits a COFF section relative relocation.
+ ///
+ /// @param Symbol - Symbol the section relative realocation should point to.
+ virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
+
+ /// EmitELFSize - Emit an ELF .size directive.
+ ///
+ /// This corresponds to an assembler statement such as:
+ /// .size symbol, expression
+ ///
+ virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) = 0;
+
+ /// EmitCommonSymbol - Emit a common symbol.
+ ///
+ /// @param Symbol - The common symbol to emit.
+ /// @param Size - The size of the common symbol.
+ /// @param ByteAlignment - The alignment of the symbol if
+ /// non-zero. This must be a power of 2.
+ virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+ unsigned ByteAlignment) = 0;
+
+ /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
+ ///
+ /// @param Symbol - The common symbol to emit.
+ /// @param Size - The size of the common symbol.
+ /// @param ByteAlignment - The alignment of the common symbol in bytes.
+ virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+ unsigned ByteAlignment) = 0;
+
+ /// EmitZerofill - Emit the zerofill section and an optional symbol.
+ ///
+ /// @param Section - The zerofill section to create and or to put the symbol
+ /// @param Symbol - The zerofill symbol to emit, if non-NULL.
+ /// @param Size - The size of the zerofill symbol.
+ /// @param ByteAlignment - The alignment of the zerofill symbol if
+ /// non-zero. This must be a power of 2 on some targets.
+ virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
+ uint64_t Size = 0,unsigned ByteAlignment = 0) = 0;
+
+ /// EmitTBSSSymbol - Emit a thread local bss (.tbss) symbol.
+ ///
+ /// @param Section - The thread local common section.
+ /// @param Symbol - The thread local common symbol to emit.
+ /// @param Size - The size of the symbol.
+ /// @param ByteAlignment - The alignment of the thread local common symbol
+ /// if non-zero. This must be a power of 2 on some targets.
+ virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
+ uint64_t Size, unsigned ByteAlignment = 0) = 0;
+
+ /// @}
+ /// @name Generating Data
+ /// @{
+
+ /// EmitBytes - Emit the bytes in \p Data into the output.
+ ///
+ /// This is used to implement assembler directives such as .byte, .ascii,
+ /// etc.
+ virtual void EmitBytes(StringRef Data, unsigned AddrSpace) = 0;
+
+ /// EmitValue - Emit the expression @p Value into the output as a native
+ /// integer of the given @p Size bytes.
+ ///
+ /// This is used to implement assembler directives such as .word, .quad,
+ /// etc.
+ ///
+ /// @param Value - The value to emit.
+ /// @param Size - The size of the integer (in bytes) to emit. This must
+ /// match a native machine width.
+ virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
+ unsigned AddrSpace) = 0;
+
+ void EmitValue(const MCExpr *Value, unsigned Size, unsigned AddrSpace = 0);
+
+ /// EmitIntValue - Special case of EmitValue that avoids the client having
+ /// to pass in a MCExpr for constant integers.
+ virtual void EmitIntValue(uint64_t Value, unsigned Size,
+ unsigned AddrSpace = 0);
+
+ /// EmitAbsValue - Emit the Value, but try to avoid relocations. On MachO
+ /// this is done by producing
+ /// foo = value
+ /// .long foo
+ void EmitAbsValue(const MCExpr *Value, unsigned Size,
+ unsigned AddrSpace = 0);
+
+ virtual void EmitULEB128Value(const MCExpr *Value) = 0;
+
+ virtual void EmitSLEB128Value(const MCExpr *Value) = 0;
+
+ /// EmitULEB128Value - Special case of EmitULEB128Value that avoids the
+ /// client having to pass in a MCExpr for constant integers.
+ void EmitULEB128IntValue(uint64_t Value, unsigned AddrSpace = 0,
+ unsigned Padding = 0);
+
+ /// EmitSLEB128Value - Special case of EmitSLEB128Value that avoids the
+ /// client having to pass in a MCExpr for constant integers.
+ void EmitSLEB128IntValue(int64_t Value, unsigned AddrSpace = 0);
+
+ /// EmitSymbolValue - Special case of EmitValue that avoids the client
+ /// having to pass in a MCExpr for MCSymbols.
+ void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
+ unsigned AddrSpace = 0);
+
+ /// EmitGPRel64Value - Emit the expression @p Value into the output as a
+ /// gprel64 (64-bit GP relative) value.
+ ///
+ /// This is used to implement assembler directives such as .gpdword on
+ /// targets that support them.
+ virtual void EmitGPRel64Value(const MCExpr *Value);
+
+ /// EmitGPRel32Value - Emit the expression @p Value into the output as a
+ /// gprel32 (32-bit GP relative) value.
+ ///
+ /// This is used to implement assembler directives such as .gprel32 on
+ /// targets that support them.
+ virtual void EmitGPRel32Value(const MCExpr *Value);
+
+ /// EmitFill - Emit NumBytes bytes worth of the value specified by
+ /// FillValue. This implements directives such as '.space'.
+ virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
+ unsigned AddrSpace);
+
+ /// EmitZeros - Emit NumBytes worth of zeros. This is a convenience
+ /// function that just wraps EmitFill.
+ void EmitZeros(uint64_t NumBytes, unsigned AddrSpace) {
+ EmitFill(NumBytes, 0, AddrSpace);
+ }
+
+
+ /// EmitValueToAlignment - Emit some number of copies of @p Value until
+ /// the byte alignment @p ByteAlignment is reached.
+ ///
+ /// If the number of bytes need to emit for the alignment is not a multiple
+ /// of @p ValueSize, then the contents of the emitted fill bytes is
+ /// undefined.
+ ///
+ /// This used to implement the .align assembler directive.
+ ///
+ /// @param ByteAlignment - The alignment to reach. This must be a power of
+ /// two on some targets.
+ /// @param Value - The value to use when filling bytes.
+ /// @param ValueSize - The size of the integer (in bytes) to emit for
+ /// @p Value. This must match a native machine width.
+ /// @param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
+ /// the alignment cannot be reached in this many bytes, no bytes are
+ /// emitted.
+ virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
+ unsigned ValueSize = 1,
+ unsigned MaxBytesToEmit = 0) = 0;
+
+ /// EmitCodeAlignment - Emit nops until the byte alignment @p ByteAlignment
+ /// is reached.
+ ///
+ /// This used to align code where the alignment bytes may be executed. This
+ /// can emit different bytes for different sizes to optimize execution.
+ ///
+ /// @param ByteAlignment - The alignment to reach. This must be a power of
+ /// two on some targets.
+ /// @param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
+ /// the alignment cannot be reached in this many bytes, no bytes are
+ /// emitted.
+ virtual void EmitCodeAlignment(unsigned ByteAlignment,
+ unsigned MaxBytesToEmit = 0) = 0;
+
+ /// EmitValueToOffset - Emit some number of copies of @p Value until the
+ /// byte offset @p Offset is reached.
+ ///
+ /// This is used to implement assembler directives such as .org.
+ ///
+ /// @param Offset - The offset to reach. This may be an expression, but the
+ /// expression must be associated with the current section.
+ /// @param Value - The value to use when filling bytes.
+ /// @return false on success, true if the offset was invalid.
+ virtual bool EmitValueToOffset(const MCExpr *Offset,
+ unsigned char Value = 0) = 0;
+
+ /// @}
+
+ /// EmitFileDirective - Switch to a new logical file. This is used to
+ /// implement the '.file "foo.c"' assembler directive.
+ virtual void EmitFileDirective(StringRef Filename) = 0;
+
+ /// EmitDwarfFileDirective - Associate a filename with a specified logical
+ /// file number. This implements the DWARF2 '.file 4 "foo.c"' assembler
+ /// directive.
+ virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
+ StringRef Filename);
+
+ /// EmitDwarfLocDirective - This implements the DWARF2
+ // '.loc fileno lineno ...' assembler directive.
+ virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
+ unsigned Column, unsigned Flags,
+ unsigned Isa,
+ unsigned Discriminator,
+ StringRef FileName);
+
+ virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
+ const MCSymbol *LastLabel,
+ const MCSymbol *Label,
+ unsigned PointerSize) = 0;
+
+ virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
+ const MCSymbol *Label) {
+ }
+
+ void EmitDwarfSetLineAddr(int64_t LineDelta, const MCSymbol *Label,
+ int PointerSize);
+
+ virtual void EmitCompactUnwindEncoding(uint32_t CompactUnwindEncoding);
+ virtual void EmitCFISections(bool EH, bool Debug);
+ void EmitCFIStartProc();
+ void EmitCFIEndProc();
+ virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
+ virtual void EmitCFIDefCfaOffset(int64_t Offset);
+ virtual void EmitCFIDefCfaRegister(int64_t Register);
+ virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
+ virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
+ virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
+ virtual void EmitCFIRememberState();
+ virtual void EmitCFIRestoreState();
+ virtual void EmitCFISameValue(int64_t Register);
+ virtual void EmitCFIRestore(int64_t Register);
+ virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
+ virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
+ virtual void EmitCFIEscape(StringRef Values);
+ virtual void EmitCFISignalFrame();
+
+ virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
+ virtual void EmitWin64EHEndProc();
+ virtual void EmitWin64EHStartChained();
+ virtual void EmitWin64EHEndChained();
+ virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
+ bool Except);
+ virtual void EmitWin64EHHandlerData();
+ virtual void EmitWin64EHPushReg(unsigned Register);
+ virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
+ virtual void EmitWin64EHAllocStack(unsigned Size);
+ virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
+ virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
+ virtual void EmitWin64EHPushFrame(bool Code);
+ virtual void EmitWin64EHEndProlog();
+
+ /// EmitInstruction - Emit the given @p Instruction into the current
+ /// section.
+ virtual void EmitInstruction(const MCInst &Inst) = 0;
+
+ /// EmitRawText - If this file is backed by a assembly streamer, this dumps
+ /// the specified string in the output .s file. This capability is
+ /// indicated by the hasRawTextSupport() predicate. By default this aborts.
+ virtual void EmitRawText(StringRef String);
+ void EmitRawText(const Twine &String);
+
+ /// ARM-related methods.
+ /// FIXME: Eventually we should have some "target MC streamer" and move
+ /// these methods there.
+ virtual void EmitFnStart();
+ virtual void EmitFnEnd();
+ virtual void EmitCantUnwind();
+ virtual void EmitPersonality(const MCSymbol *Personality);
+ virtual void EmitHandlerData();
+ virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
+ virtual void EmitPad(int64_t Offset);
+ virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
+ bool isVector);
+
+ /// FinishImpl - Streamer specific finalization.
+ virtual void FinishImpl() = 0;
+ /// Finish - Finish emission of machine code.
+ void Finish();
+ };
+
+ /// createNullStreamer - Create a dummy machine code streamer, which does
+ /// nothing. This is useful for timing the assembler front end.
+ MCStreamer *createNullStreamer(MCContext &Ctx);
+
+ /// createAsmStreamer - Create a machine code streamer which will print out
+ /// assembly for the native target, suitable for compiling with a native
+ /// assembler.
+ ///
+ /// \param InstPrint - If given, the instruction printer to use. If not given
+ /// the MCInst representation will be printed. This method takes ownership of
+ /// InstPrint.
+ ///
+ /// \param CE - If given, a code emitter to use to show the instruction
+ /// encoding inline with the assembly. This method takes ownership of \p CE.
+ ///
+ /// \param TAB - If given, a target asm backend to use to show the fixup
+ /// information in conjunction with encoding information. This method takes
+ /// ownership of \p TAB.
+ ///
+ /// \param ShowInst - Whether to show the MCInst representation inline with
+ /// the assembly.
+ MCStreamer *createAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
+ bool isVerboseAsm,
+ bool useLoc,
+ bool useCFI,
+ bool useDwarfDirectory,
+ MCInstPrinter *InstPrint = 0,
+ MCCodeEmitter *CE = 0,
+ MCAsmBackend *TAB = 0,
+ bool ShowInst = false);
+
+ /// createMachOStreamer - Create a machine code streamer which will generate
+ /// Mach-O format object files.
+ ///
+ /// Takes ownership of \p TAB and \p CE.
+ MCStreamer *createMachOStreamer(MCContext &Ctx, MCAsmBackend &TAB,
+ raw_ostream &OS, MCCodeEmitter *CE,
+ bool RelaxAll = false);
+
+ /// createWinCOFFStreamer - Create a machine code streamer which will
+ /// generate Microsoft COFF format object files.
+ ///
+ /// Takes ownership of \p TAB and \p CE.
+ MCStreamer *createWinCOFFStreamer(MCContext &Ctx,
+ MCAsmBackend &TAB,
+ MCCodeEmitter &CE, raw_ostream &OS,
+ bool RelaxAll = false);
+
+ /// createELFStreamer - Create a machine code streamer which will generate
+ /// ELF format object files.
+ MCStreamer *createELFStreamer(MCContext &Ctx, MCAsmBackend &TAB,
+ raw_ostream &OS, MCCodeEmitter *CE,
+ bool RelaxAll, bool NoExecStack);
+
+ /// createPureStreamer - Create a machine code streamer which will generate
+ /// "pure" MC object files, for use with MC-JIT and testing tools.
+ ///
+ /// Takes ownership of \p TAB and \p CE.
+ MCStreamer *createPureStreamer(MCContext &Ctx, MCAsmBackend &TAB,
+ raw_ostream &OS, MCCodeEmitter *CE);
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCSubtargetInfo.h b/include/llvm/MC/MCSubtargetInfo.h
new file mode 100644
index 00000000000..451f435fe39
--- /dev/null
+++ b/include/llvm/MC/MCSubtargetInfo.h
@@ -0,0 +1,136 @@
+//==-- llvm/MC/MCSubtargetInfo.h - Subtarget Information ---------*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file describes the subtarget options of a Target machine.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCSUBTARGET_H
+#define LLVM_MC_MCSUBTARGET_H
+
+#include "llvm/MC/SubtargetFeature.h"
+#include "llvm/MC/MCInstrItineraries.h"
+#include <string>
+
+namespace llvm {
+
+class StringRef;
+
+//===----------------------------------------------------------------------===//
+///
+/// MCSubtargetInfo - Generic base class for all target subtargets.
+///
+class MCSubtargetInfo {
+ std::string TargetTriple; // Target triple
+ const SubtargetFeatureKV *ProcFeatures; // Processor feature list
+ const SubtargetFeatureKV *ProcDesc; // Processor descriptions
+
+ // Scheduler machine model
+ const SubtargetInfoKV *ProcSchedModels;
+ const MCWriteProcResEntry *WriteProcResTable;
+ const MCWriteLatencyEntry *WriteLatencyTable;
+ const MCReadAdvanceEntry *ReadAdvanceTable;
+ const MCSchedModel *CPUSchedModel;
+
+ const InstrStage *Stages; // Instruction itinerary stages
+ const unsigned *OperandCycles; // Itinerary operand cycles
+ const unsigned *ForwardingPaths; // Forwarding paths
+ unsigned NumFeatures; // Number of processor features
+ unsigned NumProcs; // Number of processors
+ uint64_t FeatureBits; // Feature bits for current CPU + FS
+
+public:
+ void InitMCSubtargetInfo(StringRef TT, StringRef CPU, StringRef FS,
+ const SubtargetFeatureKV *PF,
+ const SubtargetFeatureKV *PD,
+ const SubtargetInfoKV *ProcSched,
+ const MCWriteProcResEntry *WPR,
+ const MCWriteLatencyEntry *WL,
+ const MCReadAdvanceEntry *RA,
+ const InstrStage *IS,
+ const unsigned *OC, const unsigned *FP,
+ unsigned NF, unsigned NP);
+
+ /// getTargetTriple - Return the target triple string.
+ StringRef getTargetTriple() const {
+ return TargetTriple;
+ }
+
+ /// getFeatureBits - Return the feature bits.
+ ///
+ uint64_t getFeatureBits() const {
+ return FeatureBits;
+ }
+
+ /// InitMCProcessorInfo - Set or change the CPU (optionally supplemented with
+ /// feature string). Recompute feature bits and scheduling model.
+ void InitMCProcessorInfo(StringRef CPU, StringRef FS);
+
+ /// ToggleFeature - Toggle a feature and returns the re-computed feature
+ /// bits. This version does not change the implied bits.
+ uint64_t ToggleFeature(uint64_t FB);
+
+ /// ToggleFeature - Toggle a feature and returns the re-computed feature
+ /// bits. This version will also change all implied bits.
+ uint64_t ToggleFeature(StringRef FS);
+
+ /// getSchedModelForCPU - Get the machine model of a CPU.
+ ///
+ const MCSchedModel *getSchedModelForCPU(StringRef CPU) const;
+
+ /// getSchedModel - Get the machine model for this subtarget's CPU.
+ ///
+ const MCSchedModel *getSchedModel() const { return CPUSchedModel; }
+
+ /// Return an iterator at the first process resource consumed by the given
+ /// scheduling class.
+ const MCWriteProcResEntry *getWriteProcResBegin(
+ const MCSchedClassDesc *SC) const {
+ return &WriteProcResTable[SC->WriteProcResIdx];
+ }
+ const MCWriteProcResEntry *getWriteProcResEnd(
+ const MCSchedClassDesc *SC) const {
+ return getWriteProcResBegin(SC) + SC->NumWriteProcResEntries;
+ }
+
+ const MCWriteLatencyEntry *getWriteLatencyEntry(const MCSchedClassDesc *SC,
+ unsigned DefIdx) const {
+ assert(DefIdx < SC->NumWriteLatencyEntries &&
+ "MachineModel does not specify a WriteResource for DefIdx");
+
+ return &WriteLatencyTable[SC->WriteLatencyIdx + DefIdx];
+ }
+
+ int getReadAdvanceCycles(const MCSchedClassDesc *SC, unsigned UseIdx,
+ unsigned WriteResID) const {
+ for (const MCReadAdvanceEntry *I = &ReadAdvanceTable[SC->ReadAdvanceIdx],
+ *E = I + SC->NumReadAdvanceEntries; I != E; ++I) {
+ if (I->UseIdx < UseIdx)
+ continue;
+ if (I->UseIdx > UseIdx)
+ break;
+ // Find the first WriteResIdx match, which has the highest cycle count.
+ if (!I->WriteResourceID || I->WriteResourceID == WriteResID) {
+ return I->Cycles;
+ }
+ }
+ return 0;
+ }
+
+ /// getInstrItineraryForCPU - Get scheduling itinerary of a CPU.
+ ///
+ InstrItineraryData getInstrItineraryForCPU(StringRef CPU) const;
+
+ /// Initialize an InstrItineraryData instance.
+ void initInstrItins(InstrItineraryData &InstrItins) const;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCSymbol.h b/include/llvm/MC/MCSymbol.h
new file mode 100644
index 00000000000..fe927555c49
--- /dev/null
+++ b/include/llvm/MC/MCSymbol.h
@@ -0,0 +1,165 @@
+//===- MCSymbol.h - Machine Code Symbols ------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MCSymbol class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCSYMBOL_H
+#define LLVM_MC_MCSYMBOL_H
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Compiler.h"
+
+namespace llvm {
+ class MCExpr;
+ class MCSection;
+ class MCContext;
+ class raw_ostream;
+
+ /// MCSymbol - Instances of this class represent a symbol name in the MC file,
+ /// and MCSymbols are created and unique'd by the MCContext class. MCSymbols
+ /// should only be constructed with valid names for the object file.
+ ///
+ /// If the symbol is defined/emitted into the current translation unit, the
+ /// Section member is set to indicate what section it lives in. Otherwise, if
+ /// it is a reference to an external entity, it has a null section.
+ class MCSymbol {
+ // Special sentinal value for the absolute pseudo section.
+ //
+ // FIXME: Use a PointerInt wrapper for this?
+ static const MCSection *AbsolutePseudoSection;
+
+ /// Name - The name of the symbol. The referred-to string data is actually
+ /// held by the StringMap that lives in MCContext.
+ StringRef Name;
+
+ /// Section - The section the symbol is defined in. This is null for
+ /// undefined symbols, and the special AbsolutePseudoSection value for
+ /// absolute symbols.
+ const MCSection *Section;
+
+ /// Value - If non-null, the value for a variable symbol.
+ const MCExpr *Value;
+
+ /// IsTemporary - True if this is an assembler temporary label, which
+ /// typically does not survive in the .o file's symbol table. Usually
+ /// "Lfoo" or ".foo".
+ unsigned IsTemporary : 1;
+
+ /// IsUsed - True if this symbol has been used.
+ mutable unsigned IsUsed : 1;
+
+ private: // MCContext creates and uniques these.
+ friend class MCExpr;
+ friend class MCContext;
+ MCSymbol(StringRef name, bool isTemporary)
+ : Name(name), Section(0), Value(0),
+ IsTemporary(isTemporary), IsUsed(false) {}
+
+ MCSymbol(const MCSymbol&) LLVM_DELETED_FUNCTION;
+ void operator=(const MCSymbol&) LLVM_DELETED_FUNCTION;
+ public:
+ /// getName - Get the symbol name.
+ StringRef getName() const { return Name; }
+
+ /// @name Accessors
+ /// @{
+
+ /// isTemporary - Check if this is an assembler temporary symbol.
+ bool isTemporary() const { return IsTemporary; }
+
+ /// isUsed - Check if this is used.
+ bool isUsed() const { return IsUsed; }
+ void setUsed(bool Value) const { IsUsed = Value; }
+
+ /// @}
+ /// @name Associated Sections
+ /// @{
+
+ /// isDefined - Check if this symbol is defined (i.e., it has an address).
+ ///
+ /// Defined symbols are either absolute or in some section.
+ bool isDefined() const {
+ return Section != 0;
+ }
+
+ /// isInSection - Check if this symbol is defined in some section (i.e., it
+ /// is defined but not absolute).
+ bool isInSection() const {
+ return isDefined() && !isAbsolute();
+ }
+
+ /// isUndefined - Check if this symbol undefined (i.e., implicitly defined).
+ bool isUndefined() const {
+ return !isDefined();
+ }
+
+ /// isAbsolute - Check if this is an absolute symbol.
+ bool isAbsolute() const {
+ return Section == AbsolutePseudoSection;
+ }
+
+ /// getSection - Get the section associated with a defined, non-absolute
+ /// symbol.
+ const MCSection &getSection() const {
+ assert(isInSection() && "Invalid accessor!");
+ return *Section;
+ }
+
+ /// setSection - Mark the symbol as defined in the section \p S.
+ void setSection(const MCSection &S) { Section = &S; }
+
+ /// setUndefined - Mark the symbol as undefined.
+ void setUndefined() {
+ Section = 0;
+ }
+
+ /// setAbsolute - Mark the symbol as absolute.
+ void setAbsolute() { Section = AbsolutePseudoSection; }
+
+ /// @}
+ /// @name Variable Symbols
+ /// @{
+
+ /// isVariable - Check if this is a variable symbol.
+ bool isVariable() const {
+ return Value != 0;
+ }
+
+ /// getVariableValue() - Get the value for variable symbols.
+ const MCExpr *getVariableValue() const {
+ assert(isVariable() && "Invalid accessor!");
+ IsUsed = true;
+ return Value;
+ }
+
+ // AliasedSymbol() - If this is an alias (a = b), return the symbol
+ // we ultimately point to. For a non alias, this just returns the symbol
+ // itself.
+ const MCSymbol &AliasedSymbol() const;
+
+ void setVariableValue(const MCExpr *Value);
+
+ /// @}
+
+ /// print - Print the value to the stream \p OS.
+ void print(raw_ostream &OS) const;
+
+ /// dump - Print the value to stderr.
+ void dump() const;
+ };
+
+ inline raw_ostream &operator<<(raw_ostream &OS, const MCSymbol &Sym) {
+ Sym.print(OS);
+ return OS;
+ }
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCTargetAsmLexer.h b/include/llvm/MC/MCTargetAsmLexer.h
new file mode 100644
index 00000000000..b1cc546e1ef
--- /dev/null
+++ b/include/llvm/MC/MCTargetAsmLexer.h
@@ -0,0 +1,89 @@
+//===-- llvm/MC/MCTargetAsmLexer.h - Target Assembly Lexer ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCTARGETASMLEXER_H
+#define LLVM_MC_MCTARGETASMLEXER_H
+
+#include "llvm/MC/MCParser/MCAsmLexer.h"
+
+namespace llvm {
+class Target;
+
+/// MCTargetAsmLexer - Generic interface to target specific assembly lexers.
+class MCTargetAsmLexer {
+ /// The current token
+ AsmToken CurTok;
+
+ /// The location and description of the current error
+ SMLoc ErrLoc;
+ std::string Err;
+
+ MCTargetAsmLexer(const MCTargetAsmLexer &) LLVM_DELETED_FUNCTION;
+ void operator=(const MCTargetAsmLexer &) LLVM_DELETED_FUNCTION;
+protected: // Can only create subclasses.
+ MCTargetAsmLexer(const Target &);
+
+ virtual AsmToken LexToken() = 0;
+
+ void SetError(const SMLoc &errLoc, const std::string &err) {
+ ErrLoc = errLoc;
+ Err = err;
+ }
+
+ /// TheTarget - The Target that this machine was created for.
+ const Target &TheTarget;
+ MCAsmLexer *Lexer;
+
+public:
+ virtual ~MCTargetAsmLexer();
+
+ const Target &getTarget() const { return TheTarget; }
+
+ /// InstallLexer - Set the lexer to get tokens from lower-level lexer \p L.
+ void InstallLexer(MCAsmLexer &L) {
+ Lexer = &L;
+ }
+
+ MCAsmLexer *getLexer() {
+ return Lexer;
+ }
+
+ /// Lex - Consume the next token from the input stream and return it.
+ const AsmToken &Lex() {
+ return CurTok = LexToken();
+ }
+
+ /// getTok - Get the current (last) lexed token.
+ const AsmToken &getTok() {
+ return CurTok;
+ }
+
+ /// getErrLoc - Get the current error location
+ const SMLoc &getErrLoc() {
+ return ErrLoc;
+ }
+
+ /// getErr - Get the current error string
+ const std::string &getErr() {
+ return Err;
+ }
+
+ /// getKind - Get the kind of current token.
+ AsmToken::TokenKind getKind() const { return CurTok.getKind(); }
+
+ /// is - Check if the current token has kind \p K.
+ bool is(AsmToken::TokenKind K) const { return CurTok.is(K); }
+
+ /// isNot - Check if the current token has kind \p K.
+ bool isNot(AsmToken::TokenKind K) const { return CurTok.isNot(K); }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCTargetAsmParser.h b/include/llvm/MC/MCTargetAsmParser.h
new file mode 100644
index 00000000000..709c2d245cc
--- /dev/null
+++ b/include/llvm/MC/MCTargetAsmParser.h
@@ -0,0 +1,122 @@
+//===-- llvm/MC/MCTargetAsmParser.h - Target Assembly Parser ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_TARGETPARSER_H
+#define LLVM_MC_TARGETPARSER_H
+
+#include "llvm/MC/MCParser/MCAsmParserExtension.h"
+
+namespace llvm {
+class MCStreamer;
+class StringRef;
+class SMLoc;
+class AsmToken;
+class MCParsedAsmOperand;
+class MCInst;
+template <typename T> class SmallVectorImpl;
+
+/// MCTargetAsmParser - Generic interface to target specific assembly parsers.
+class MCTargetAsmParser : public MCAsmParserExtension {
+public:
+ enum MatchResultTy {
+ Match_InvalidOperand,
+ Match_MissingFeature,
+ Match_MnemonicFail,
+ Match_Success,
+ FIRST_TARGET_MATCH_RESULT_TY
+ };
+
+private:
+ MCTargetAsmParser(const MCTargetAsmParser &) LLVM_DELETED_FUNCTION;
+ void operator=(const MCTargetAsmParser &) LLVM_DELETED_FUNCTION;
+protected: // Can only create subclasses.
+ MCTargetAsmParser();
+
+ /// AvailableFeatures - The current set of available features.
+ unsigned AvailableFeatures;
+
+public:
+ virtual ~MCTargetAsmParser();
+
+ unsigned getAvailableFeatures() const { return AvailableFeatures; }
+ void setAvailableFeatures(unsigned Value) { AvailableFeatures = Value; }
+
+ virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
+ SMLoc &EndLoc) = 0;
+
+ /// ParseInstruction - Parse one assembly instruction.
+ ///
+ /// The parser is positioned following the instruction name. The target
+ /// specific instruction parser should parse the entire instruction and
+ /// construct the appropriate MCInst, or emit an error. On success, the entire
+ /// line should be parsed up to and including the end-of-statement token. On
+ /// failure, the parser is not required to read to the end of the line.
+ //
+ /// \param Name - The instruction name.
+ /// \param NameLoc - The source location of the name.
+ /// \param Operands [out] - The list of parsed operands, this returns
+ /// ownership of them to the caller.
+ /// \return True on failure.
+ virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
+ SmallVectorImpl<MCParsedAsmOperand*> &Operands) = 0;
+
+ /// ParseDirective - Parse a target specific assembler directive
+ ///
+ /// The parser is positioned following the directive name. The target
+ /// specific directive parser should parse the entire directive doing or
+ /// recording any target specific work, or return true and do nothing if the
+ /// directive is not target specific. If the directive is specific for
+ /// the target, the entire line is parsed up to and including the
+ /// end-of-statement token and false is returned.
+ ///
+ /// \param DirectiveID - the identifier token of the directive.
+ virtual bool ParseDirective(AsmToken DirectiveID) = 0;
+
+ /// MatchInstruction - Recognize a series of operands of a parsed instruction
+ /// as an actual MCInst. This returns false on success and returns true on
+ /// failure to match.
+ ///
+ /// On failure, the target parser is responsible for emitting a diagnostic
+ /// explaining the match failure.
+ virtual bool
+ MatchInstruction(SMLoc IDLoc, unsigned &Kind,
+ SmallVectorImpl<MCParsedAsmOperand*> &Operands,
+ SmallVectorImpl<MCInst> &MCInsts,
+ unsigned &OrigErrorInfo,
+ bool matchingInlineAsm = false) {
+ OrigErrorInfo = ~0x0;
+ return true;
+ }
+
+ /// MatchAndEmitInstruction - Recognize a series of operands of a parsed
+ /// instruction as an actual MCInst and emit it to the specified MCStreamer.
+ /// This returns false on success and returns true on failure to match.
+ ///
+ /// On failure, the target parser is responsible for emitting a diagnostic
+ /// explaining the match failure.
+ virtual bool
+ MatchAndEmitInstruction(SMLoc IDLoc,
+ SmallVectorImpl<MCParsedAsmOperand*> &Operands,
+ MCStreamer &Out) = 0;
+
+ /// checkTargetMatchPredicate - Validate the instruction match against
+ /// any complex target predicates not expressible via match classes.
+ virtual unsigned checkTargetMatchPredicate(MCInst &Inst) {
+ return Match_Success;
+ }
+
+ virtual unsigned getMCInstOperandNum(unsigned Kind, MCInst &Inst,
+ const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
+ unsigned OperandNum,
+ unsigned &NumMCOperands) = 0;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MCValue.h b/include/llvm/MC/MCValue.h
new file mode 100644
index 00000000000..f9af8bcfbf6
--- /dev/null
+++ b/include/llvm/MC/MCValue.h
@@ -0,0 +1,77 @@
+//===-- llvm/MC/MCValue.h - MCValue class -----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains the declaration of the MCValue class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCVALUE_H
+#define LLVM_MC_MCVALUE_H
+
+#include "llvm/Support/DataTypes.h"
+#include "llvm/MC/MCSymbol.h"
+#include <cassert>
+
+namespace llvm {
+class MCAsmInfo;
+class MCSymbol;
+class MCSymbolRefExpr;
+class raw_ostream;
+
+/// MCValue - This represents an "assembler immediate". In its most general
+/// form, this can hold "SymbolA - SymbolB + imm64". Not all targets supports
+/// relocations of this general form, but we need to represent this anyway.
+///
+/// In the general form, SymbolB can only be defined if SymbolA is, and both
+/// must be in the same (non-external) section. The latter constraint is not
+/// enforced, since a symbol's section may not be known at construction.
+///
+/// Note that this class must remain a simple POD value class, because we need
+/// it to live in unions etc.
+class MCValue {
+ const MCSymbolRefExpr *SymA, *SymB;
+ int64_t Cst;
+public:
+
+ int64_t getConstant() const { return Cst; }
+ const MCSymbolRefExpr *getSymA() const { return SymA; }
+ const MCSymbolRefExpr *getSymB() const { return SymB; }
+
+ /// isAbsolute - Is this an absolute (as opposed to relocatable) value.
+ bool isAbsolute() const { return !SymA && !SymB; }
+
+ /// print - Print the value to the stream \p OS.
+ void print(raw_ostream &OS, const MCAsmInfo *MAI) const;
+
+ /// dump - Print the value to stderr.
+ void dump() const;
+
+ static MCValue get(const MCSymbolRefExpr *SymA, const MCSymbolRefExpr *SymB=0,
+ int64_t Val = 0) {
+ MCValue R;
+ assert((!SymB || SymA) && "Invalid relocatable MCValue!");
+ R.Cst = Val;
+ R.SymA = SymA;
+ R.SymB = SymB;
+ return R;
+ }
+
+ static MCValue get(int64_t Val) {
+ MCValue R;
+ R.Cst = Val;
+ R.SymA = 0;
+ R.SymB = 0;
+ return R;
+ }
+
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCWin64EH.h b/include/llvm/MC/MCWin64EH.h
new file mode 100644
index 00000000000..eb4665a2e99
--- /dev/null
+++ b/include/llvm/MC/MCWin64EH.h
@@ -0,0 +1,93 @@
+//===- MCWin64EH.h - Machine Code Win64 EH support --------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains declarations to support the Win64 Exception Handling
+// scheme in MC.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCWIN64EH_H
+#define LLVM_MC_MCWIN64EH_H
+
+#include "llvm/Support/Win64EH.h"
+#include <cassert>
+#include <vector>
+
+namespace llvm {
+ class StringRef;
+ class MCStreamer;
+ class MCSymbol;
+
+ class MCWin64EHInstruction {
+ public:
+ typedef Win64EH::UnwindOpcodes OpType;
+ private:
+ OpType Operation;
+ MCSymbol *Label;
+ unsigned Offset;
+ unsigned Register;
+ public:
+ MCWin64EHInstruction(OpType Op, MCSymbol *L, unsigned Reg)
+ : Operation(Op), Label(L), Offset(0), Register(Reg) {
+ assert(Op == Win64EH::UOP_PushNonVol);
+ }
+ MCWin64EHInstruction(MCSymbol *L, unsigned Size)
+ : Operation(Size>128 ? Win64EH::UOP_AllocLarge : Win64EH::UOP_AllocSmall),
+ Label(L), Offset(Size) { }
+ MCWin64EHInstruction(OpType Op, MCSymbol *L, unsigned Reg, unsigned Off)
+ : Operation(Op), Label(L), Offset(Off), Register(Reg) {
+ assert(Op == Win64EH::UOP_SetFPReg ||
+ Op == Win64EH::UOP_SaveNonVol ||
+ Op == Win64EH::UOP_SaveNonVolBig ||
+ Op == Win64EH::UOP_SaveXMM128 ||
+ Op == Win64EH::UOP_SaveXMM128Big);
+ }
+ MCWin64EHInstruction(OpType Op, MCSymbol *L, bool Code)
+ : Operation(Op), Label(L), Offset(Code ? 1 : 0) {
+ assert(Op == Win64EH::UOP_PushMachFrame);
+ }
+ OpType getOperation() const { return Operation; }
+ MCSymbol *getLabel() const { return Label; }
+ unsigned getOffset() const { return Offset; }
+ unsigned getSize() const { return Offset; }
+ unsigned getRegister() const { return Register; }
+ bool isPushCodeFrame() const { return Offset == 1; }
+ };
+
+ struct MCWin64EHUnwindInfo {
+ MCWin64EHUnwindInfo() : Begin(0), End(0), ExceptionHandler(0),
+ Function(0), PrologEnd(0), Symbol(0),
+ HandlesUnwind(false), HandlesExceptions(false),
+ LastFrameInst(-1), ChainedParent(0),
+ Instructions() {}
+ MCSymbol *Begin;
+ MCSymbol *End;
+ const MCSymbol *ExceptionHandler;
+ const MCSymbol *Function;
+ MCSymbol *PrologEnd;
+ MCSymbol *Symbol;
+ bool HandlesUnwind;
+ bool HandlesExceptions;
+ int LastFrameInst;
+ MCWin64EHUnwindInfo *ChainedParent;
+ std::vector<MCWin64EHInstruction> Instructions;
+ };
+
+ class MCWin64EHUnwindEmitter {
+ public:
+ static StringRef GetSectionSuffix(const MCSymbol *func);
+ //
+ // This emits the unwind info sections (.pdata and .xdata in PE/COFF).
+ //
+ static void Emit(MCStreamer &streamer);
+ static void EmitUnwindInfo(MCStreamer &streamer, MCWin64EHUnwindInfo *info);
+ };
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/MCWinCOFFObjectWriter.h b/include/llvm/MC/MCWinCOFFObjectWriter.h
new file mode 100644
index 00000000000..7a0b1ffaf0a
--- /dev/null
+++ b/include/llvm/MC/MCWinCOFFObjectWriter.h
@@ -0,0 +1,36 @@
+//===-- llvm/MC/MCWinCOFFObjectWriter.h - Win COFF Object Writer *- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_MCWINCOFFOBJECTWRITER_H
+#define LLVM_MC_MCWINCOFFOBJECTWRITER_H
+
+namespace llvm {
+ class MCWinCOFFObjectTargetWriter {
+ const unsigned Machine;
+
+ protected:
+ MCWinCOFFObjectTargetWriter(unsigned Machine_);
+
+ public:
+ virtual ~MCWinCOFFObjectTargetWriter() {}
+
+ unsigned getMachine() const { return Machine; }
+ virtual unsigned getRelocType(unsigned FixupKind) const = 0;
+ };
+
+ /// \brief Construct a new Win COFF writer instance.
+ ///
+ /// \param MOTW - The target specific WinCOFF writer subclass.
+ /// \param OS - The stream to write to.
+ /// \returns The constructed object writer.
+ MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
+ raw_ostream &OS);
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/MachineLocation.h b/include/llvm/MC/MachineLocation.h
new file mode 100644
index 00000000000..5caad337f82
--- /dev/null
+++ b/include/llvm/MC/MachineLocation.h
@@ -0,0 +1,98 @@
+//===-- llvm/MC/MachineLocation.h -------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+// The MachineLocation class is used to represent a simple location in a machine
+// frame. Locations will be one of two forms; a register or an address formed
+// from a base address plus an offset. Register indirection can be specified by
+// using an offset of zero.
+//
+// The MachineMove class is used to represent abstract move operations in the
+// prolog/epilog of a compiled function. A collection of these objects can be
+// used by a debug consumer to track the location of values when unwinding stack
+// frames.
+//===----------------------------------------------------------------------===//
+
+
+#ifndef LLVM_MC_MACHINELOCATION_H
+#define LLVM_MC_MACHINELOCATION_H
+
+namespace llvm {
+ class MCSymbol;
+
+class MachineLocation {
+private:
+ bool IsRegister; // True if location is a register.
+ unsigned Register; // gcc/gdb register number.
+ int Offset; // Displacement if not register.
+public:
+ enum {
+ // The target register number for an abstract frame pointer. The value is
+ // an arbitrary value that doesn't collide with any real target register.
+ VirtualFP = ~0U
+ };
+ MachineLocation()
+ : IsRegister(false), Register(0), Offset(0) {}
+ explicit MachineLocation(unsigned R)
+ : IsRegister(true), Register(R), Offset(0) {}
+ MachineLocation(unsigned R, int O)
+ : IsRegister(false), Register(R), Offset(O) {}
+
+ bool operator==(const MachineLocation &Other) const {
+ return IsRegister == Other.IsRegister && Register == Other.Register &&
+ Offset == Other.Offset;
+ }
+
+ // Accessors
+ bool isReg() const { return IsRegister; }
+ unsigned getReg() const { return Register; }
+ int getOffset() const { return Offset; }
+ void setIsRegister(bool Is) { IsRegister = Is; }
+ void setRegister(unsigned R) { Register = R; }
+ void setOffset(int O) { Offset = O; }
+ void set(unsigned R) {
+ IsRegister = true;
+ Register = R;
+ Offset = 0;
+ }
+ void set(unsigned R, int O) {
+ IsRegister = false;
+ Register = R;
+ Offset = O;
+ }
+
+#ifndef NDEBUG
+ void dump();
+#endif
+};
+
+/// MachineMove - This class represents the save or restore of a callee saved
+/// register that exception or debug info needs to know about.
+class MachineMove {
+private:
+ /// Label - Symbol for post-instruction address when result of move takes
+ /// effect.
+ MCSymbol *Label;
+
+ // Move to & from location.
+ MachineLocation Destination, Source;
+public:
+ MachineMove() : Label(0) {}
+
+ MachineMove(MCSymbol *label, const MachineLocation &D,
+ const MachineLocation &S)
+ : Label(label), Destination(D), Source(S) {}
+
+ // Accessors
+ MCSymbol *getLabel() const { return Label; }
+ const MachineLocation &getDestination() const { return Destination; }
+ const MachineLocation &getSource() const { return Source; }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/MC/SectionKind.h b/include/llvm/MC/SectionKind.h
new file mode 100644
index 00000000000..85a91c6b169
--- /dev/null
+++ b/include/llvm/MC/SectionKind.h
@@ -0,0 +1,240 @@
+//===-- llvm/Target/TargetLoweringObjectFile.h - Object Info ----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements classes used to handle lowerings specific to common
+// object file formats.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_SECTIONKIND_H
+#define LLVM_MC_SECTIONKIND_H
+
+namespace llvm {
+
+/// SectionKind - This is a simple POD value that classifies the properties of
+/// a section. A section is classified into the deepest possible
+/// classification, and then the target maps them onto their sections based on
+/// what capabilities they have.
+///
+/// The comments below describe these as if they were an inheritance hierarchy
+/// in order to explain the predicates below.
+///
+class SectionKind {
+ enum Kind {
+ /// Metadata - Debug info sections or other metadata.
+ Metadata,
+
+ /// Text - Text section, used for functions and other executable code.
+ Text,
+
+ /// ReadOnly - Data that is never written to at program runtime by the
+ /// program or the dynamic linker. Things in the top-level readonly
+ /// SectionKind are not mergeable.
+ ReadOnly,
+
+ /// MergableCString - Any null-terminated string which allows merging.
+ /// These values are known to end in a nul value of the specified size,
+ /// not otherwise contain a nul value, and be mergable. This allows the
+ /// linker to unique the strings if it so desires.
+
+ /// Mergeable1ByteCString - 1 byte mergable, null terminated, string.
+ Mergeable1ByteCString,
+
+ /// Mergeable2ByteCString - 2 byte mergable, null terminated, string.
+ Mergeable2ByteCString,
+
+ /// Mergeable4ByteCString - 4 byte mergable, null terminated, string.
+ Mergeable4ByteCString,
+
+ /// MergeableConst - These are sections for merging fixed-length
+ /// constants together. For example, this can be used to unique
+ /// constant pool entries etc.
+ MergeableConst,
+
+ /// MergeableConst4 - This is a section used by 4-byte constants,
+ /// for example, floats.
+ MergeableConst4,
+
+ /// MergeableConst8 - This is a section used by 8-byte constants,
+ /// for example, doubles.
+ MergeableConst8,
+
+ /// MergeableConst16 - This is a section used by 16-byte constants,
+ /// for example, vectors.
+ MergeableConst16,
+
+ /// Writeable - This is the base of all segments that need to be written
+ /// to during program runtime.
+
+ /// ThreadLocal - This is the base of all TLS segments. All TLS
+ /// objects must be writeable, otherwise there is no reason for them to
+ /// be thread local!
+
+ /// ThreadBSS - Zero-initialized TLS data objects.
+ ThreadBSS,
+
+ /// ThreadData - Initialized TLS data objects.
+ ThreadData,
+
+ /// GlobalWriteableData - Writeable data that is global (not thread
+ /// local).
+
+ /// BSS - Zero initialized writeable data.
+ BSS,
+
+ /// BSSLocal - This is BSS (zero initialized and writable) data
+ /// which has local linkage.
+ BSSLocal,
+
+ /// BSSExtern - This is BSS data with normal external linkage.
+ BSSExtern,
+
+ /// Common - Data with common linkage. These represent tentative
+ /// definitions, which always have a zero initializer and are never
+ /// marked 'constant'.
+ Common,
+
+ /// DataRel - This is the most general form of data that is written
+ /// to by the program, it can have random relocations to arbitrary
+ /// globals.
+ DataRel,
+
+ /// DataRelLocal - This is writeable data that has a non-zero
+ /// initializer and has relocations in it, but all of the
+ /// relocations are known to be within the final linked image
+ /// the global is linked into.
+ DataRelLocal,
+
+ /// DataNoRel - This is writeable data that has a non-zero
+ /// initializer, but whose initializer is known to have no
+ /// relocations.
+ DataNoRel,
+
+ /// ReadOnlyWithRel - These are global variables that are never
+ /// written to by the program, but that have relocations, so they
+ /// must be stuck in a writeable section so that the dynamic linker
+ /// can write to them. If it chooses to, the dynamic linker can
+ /// mark the pages these globals end up on as read-only after it is
+ /// done with its relocation phase.
+ ReadOnlyWithRel,
+
+ /// ReadOnlyWithRelLocal - This is data that is readonly by the
+ /// program, but must be writeable so that the dynamic linker
+ /// can perform relocations in it. This is used when we know
+ /// that all the relocations are to globals in this final
+ /// linked image.
+ ReadOnlyWithRelLocal
+
+ } K : 8;
+public:
+
+ bool isMetadata() const { return K == Metadata; }
+ bool isText() const { return K == Text; }
+
+ bool isReadOnly() const {
+ return K == ReadOnly || isMergeableCString() ||
+ isMergeableConst();
+ }
+
+ bool isMergeableCString() const {
+ return K == Mergeable1ByteCString || K == Mergeable2ByteCString ||
+ K == Mergeable4ByteCString;
+ }
+ bool isMergeable1ByteCString() const { return K == Mergeable1ByteCString; }
+ bool isMergeable2ByteCString() const { return K == Mergeable2ByteCString; }
+ bool isMergeable4ByteCString() const { return K == Mergeable4ByteCString; }
+
+ bool isMergeableConst() const {
+ return K == MergeableConst || K == MergeableConst4 ||
+ K == MergeableConst8 || K == MergeableConst16;
+ }
+ bool isMergeableConst4() const { return K == MergeableConst4; }
+ bool isMergeableConst8() const { return K == MergeableConst8; }
+ bool isMergeableConst16() const { return K == MergeableConst16; }
+
+ bool isWriteable() const {
+ return isThreadLocal() || isGlobalWriteableData();
+ }
+
+ bool isThreadLocal() const {
+ return K == ThreadData || K == ThreadBSS;
+ }
+
+ bool isThreadBSS() const { return K == ThreadBSS; }
+ bool isThreadData() const { return K == ThreadData; }
+
+ bool isGlobalWriteableData() const {
+ return isBSS() || isCommon() || isDataRel() || isReadOnlyWithRel();
+ }
+
+ bool isBSS() const { return K == BSS || K == BSSLocal || K == BSSExtern; }
+ bool isBSSLocal() const { return K == BSSLocal; }
+ bool isBSSExtern() const { return K == BSSExtern; }
+
+ bool isCommon() const { return K == Common; }
+
+ bool isDataRel() const {
+ return K == DataRel || K == DataRelLocal || K == DataNoRel;
+ }
+
+ bool isDataRelLocal() const {
+ return K == DataRelLocal || K == DataNoRel;
+ }
+
+ bool isDataNoRel() const { return K == DataNoRel; }
+
+ bool isReadOnlyWithRel() const {
+ return K == ReadOnlyWithRel || K == ReadOnlyWithRelLocal;
+ }
+
+ bool isReadOnlyWithRelLocal() const {
+ return K == ReadOnlyWithRelLocal;
+ }
+private:
+ static SectionKind get(Kind K) {
+ SectionKind Res;
+ Res.K = K;
+ return Res;
+ }
+public:
+
+ static SectionKind getMetadata() { return get(Metadata); }
+ static SectionKind getText() { return get(Text); }
+ static SectionKind getReadOnly() { return get(ReadOnly); }
+ static SectionKind getMergeable1ByteCString() {
+ return get(Mergeable1ByteCString);
+ }
+ static SectionKind getMergeable2ByteCString() {
+ return get(Mergeable2ByteCString);
+ }
+ static SectionKind getMergeable4ByteCString() {
+ return get(Mergeable4ByteCString);
+ }
+ static SectionKind getMergeableConst() { return get(MergeableConst); }
+ static SectionKind getMergeableConst4() { return get(MergeableConst4); }
+ static SectionKind getMergeableConst8() { return get(MergeableConst8); }
+ static SectionKind getMergeableConst16() { return get(MergeableConst16); }
+ static SectionKind getThreadBSS() { return get(ThreadBSS); }
+ static SectionKind getThreadData() { return get(ThreadData); }
+ static SectionKind getBSS() { return get(BSS); }
+ static SectionKind getBSSLocal() { return get(BSSLocal); }
+ static SectionKind getBSSExtern() { return get(BSSExtern); }
+ static SectionKind getCommon() { return get(Common); }
+ static SectionKind getDataRel() { return get(DataRel); }
+ static SectionKind getDataRelLocal() { return get(DataRelLocal); }
+ static SectionKind getDataNoRel() { return get(DataNoRel); }
+ static SectionKind getReadOnlyWithRel() { return get(ReadOnlyWithRel); }
+ static SectionKind getReadOnlyWithRelLocal(){
+ return get(ReadOnlyWithRelLocal);
+ }
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/MC/SubtargetFeature.h b/include/llvm/MC/SubtargetFeature.h
new file mode 100644
index 00000000000..87c5fd3969d
--- /dev/null
+++ b/include/llvm/MC/SubtargetFeature.h
@@ -0,0 +1,115 @@
+//===-- llvm/MC/SubtargetFeature.h - CPU characteristics --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines and manages user or tool specified CPU characteristics.
+// The intent is to be able to package specific features that should or should
+// not be used on a specific target processor. A tool, such as llc, could, as
+// as example, gather chip info from the command line, a long with features
+// that should be used on that chip.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MC_SUBTARGETFEATURE_H
+#define LLVM_MC_SUBTARGETFEATURE_H
+
+#include <vector>
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+ class raw_ostream;
+ class StringRef;
+
+//===----------------------------------------------------------------------===//
+///
+/// SubtargetFeatureKV - Used to provide key value pairs for feature and
+/// CPU bit flags.
+//
+struct SubtargetFeatureKV {
+ const char *Key; // K-V key string
+ const char *Desc; // Help descriptor
+ uint64_t Value; // K-V integer value
+ uint64_t Implies; // K-V bit mask
+
+ // Compare routine for std binary search
+ bool operator<(const SubtargetFeatureKV &S) const {
+ return strcmp(Key, S.Key) < 0;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+///
+/// SubtargetInfoKV - Used to provide key value pairs for CPU and arbitrary
+/// pointers.
+//
+struct SubtargetInfoKV {
+ const char *Key; // K-V key string
+ const void *Value; // K-V pointer value
+
+ // Compare routine for std binary search
+ bool operator<(const SubtargetInfoKV &S) const {
+ return strcmp(Key, S.Key) < 0;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+///
+/// SubtargetFeatures - Manages the enabling and disabling of subtarget
+/// specific features. Features are encoded as a string of the form
+/// "cpu,+attr1,+attr2,-attr3,...,+attrN"
+/// A comma separates each feature from the next (all lowercase.)
+/// The first feature is always the CPU subtype (eg. pentiumm). If the CPU
+/// value is "generic" then the CPU subtype should be generic for the target.
+/// Each of the remaining features is prefixed with + or - indicating whether
+/// that feature should be enabled or disabled contrary to the cpu
+/// specification.
+///
+
+class SubtargetFeatures {
+ std::vector<std::string> Features; // Subtarget features as a vector
+public:
+ explicit SubtargetFeatures(const StringRef Initial = "");
+
+ /// Features string accessors.
+ std::string getString() const;
+
+ /// Adding Features.
+ void AddFeature(const StringRef String, bool IsEnabled = true);
+
+ /// ToggleFeature - Toggle a feature and returns the newly updated feature
+ /// bits.
+ uint64_t ToggleFeature(uint64_t Bits, const StringRef String,
+ const SubtargetFeatureKV *FeatureTable,
+ size_t FeatureTableSize);
+
+ /// Get feature bits of a CPU.
+ uint64_t getFeatureBits(const StringRef CPU,
+ const SubtargetFeatureKV *CPUTable,
+ size_t CPUTableSize,
+ const SubtargetFeatureKV *FeatureTable,
+ size_t FeatureTableSize);
+
+ /// Get scheduling itinerary of a CPU.
+ const void *getItinerary(const StringRef CPU,
+ const SubtargetInfoKV *Table, size_t TableSize);
+
+ /// Print feature string.
+ void print(raw_ostream &OS) const;
+
+ // Dump feature info.
+ void dump() const;
+
+ /// Retrieve a formatted string of the default features for the specified
+ /// target triple.
+ void getDefaultSubtargetFeatures(const Triple& Triple);
+};
+
+} // End namespace llvm
+
+#endif
diff --git a/include/llvm/MDBuilder.h b/include/llvm/MDBuilder.h
new file mode 100644
index 00000000000..2aa48b0b472
--- /dev/null
+++ b/include/llvm/MDBuilder.h
@@ -0,0 +1,141 @@
+//===---- llvm/MDBuilder.h - Builder for LLVM metadata ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MDBuilder class, which is used as a convenient way to
+// create LLVM metadata with a consistent and simplified interface.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MDBUILDER_H
+#define LLVM_MDBUILDER_H
+
+#include "llvm/Constants.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Metadata.h"
+#include "llvm/ADT/APInt.h"
+
+namespace llvm {
+
+ class MDBuilder {
+ LLVMContext &Context;
+
+ public:
+ MDBuilder(LLVMContext &context) : Context(context) {}
+
+ /// \brief Return the given string as metadata.
+ MDString *createString(StringRef Str) {
+ return MDString::get(Context, Str);
+ }
+
+ //===------------------------------------------------------------------===//
+ // FPMath metadata.
+ //===------------------------------------------------------------------===//
+
+ /// \brief Return metadata with the given settings. The special value 0.0
+ /// for the Accuracy parameter indicates the default (maximal precision)
+ /// setting.
+ MDNode *createFPMath(float Accuracy) {
+ if (Accuracy == 0.0)
+ return 0;
+ assert(Accuracy > 0.0 && "Invalid fpmath accuracy!");
+ Value *Op = ConstantFP::get(Type::getFloatTy(Context), Accuracy);
+ return MDNode::get(Context, Op);
+ }
+
+ //===------------------------------------------------------------------===//
+ // Prof metadata.
+ //===------------------------------------------------------------------===//
+
+ /// \brief Return metadata containing two branch weights.
+ MDNode *createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight) {
+ uint32_t Weights[] = { TrueWeight, FalseWeight };
+ return createBranchWeights(Weights);
+ }
+
+ /// \brief Return metadata containing a number of branch weights.
+ MDNode *createBranchWeights(ArrayRef<uint32_t> Weights) {
+ assert(Weights.size() >= 2 && "Need at least two branch weights!");
+
+ SmallVector<Value *, 4> Vals(Weights.size()+1);
+ Vals[0] = createString("branch_weights");
+
+ Type *Int32Ty = Type::getInt32Ty(Context);
+ for (unsigned i = 0, e = Weights.size(); i != e; ++i)
+ Vals[i+1] = ConstantInt::get(Int32Ty, Weights[i]);
+
+ return MDNode::get(Context, Vals);
+ }
+
+ //===------------------------------------------------------------------===//
+ // Range metadata.
+ //===------------------------------------------------------------------===//
+
+ /// \brief Return metadata describing the range [Lo, Hi).
+ MDNode *createRange(const APInt &Lo, const APInt &Hi) {
+ assert(Lo.getBitWidth() == Hi.getBitWidth() && "Mismatched bitwidths!");
+ // If the range is everything then it is useless.
+ if (Hi == Lo)
+ return 0;
+
+ // Return the range [Lo, Hi).
+ Type *Ty = IntegerType::get(Context, Lo.getBitWidth());
+ Value *Range[2] = { ConstantInt::get(Ty, Lo), ConstantInt::get(Ty, Hi) };
+ return MDNode::get(Context, Range);
+ }
+
+
+ //===------------------------------------------------------------------===//
+ // TBAA metadata.
+ //===------------------------------------------------------------------===//
+
+ /// \brief Return metadata appropriate for a TBAA root node. Each returned
+ /// node is distinct from all other metadata and will never be identified
+ /// (uniqued) with anything else.
+ MDNode *createAnonymousTBAARoot() {
+ // To ensure uniqueness the root node is self-referential.
+ MDNode *Dummy = MDNode::getTemporary(Context, ArrayRef<Value*>());
+ MDNode *Root = MDNode::get(Context, Dummy);
+ // At this point we have
+ // !0 = metadata !{} <- dummy
+ // !1 = metadata !{metadata !0} <- root
+ // Replace the dummy operand with the root node itself and delete the dummy.
+ Root->replaceOperandWith(0, Root);
+ MDNode::deleteTemporary(Dummy);
+ // We now have
+ // !1 = metadata !{metadata !1} <- self-referential root
+ return Root;
+ }
+
+ /// \brief Return metadata appropriate for a TBAA root node with the given
+ /// name. This may be identified (uniqued) with other roots with the same
+ /// name.
+ MDNode *createTBAARoot(StringRef Name) {
+ return MDNode::get(Context, createString(Name));
+ }
+
+ /// \brief Return metadata for a non-root TBAA node with the given name,
+ /// parent in the TBAA tree, and value for 'pointsToConstantMemory'.
+ MDNode *createTBAANode(StringRef Name, MDNode *Parent,
+ bool isConstant = false) {
+ if (isConstant) {
+ Constant *Flags = ConstantInt::get(Type::getInt64Ty(Context), 1);
+ Value *Ops[3] = { createString(Name), Parent, Flags };
+ return MDNode::get(Context, Ops);
+ } else {
+ Value *Ops[2] = { createString(Name), Parent };
+ return MDNode::get(Context, Ops);
+ }
+ }
+
+ };
+
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Metadata.h b/include/llvm/Metadata.h
new file mode 100644
index 00000000000..d0e65246233
--- /dev/null
+++ b/include/llvm/Metadata.h
@@ -0,0 +1,244 @@
+//===-- llvm/Metadata.h - Metadata definitions ------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+/// @file
+/// This file contains the declarations for metadata subclasses.
+/// They represent the different flavors of metadata that live in LLVM.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_METADATA_H
+#define LLVM_METADATA_H
+
+#include "llvm/Value.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/ilist_node.h"
+
+namespace llvm {
+class Constant;
+class Instruction;
+class LLVMContext;
+class Module;
+template <typename T> class SmallVectorImpl;
+template<typename ValueSubClass, typename ItemParentClass>
+ class SymbolTableListTraits;
+
+
+//===----------------------------------------------------------------------===//
+/// MDString - a single uniqued string.
+/// These are used to efficiently contain a byte sequence for metadata.
+/// MDString is always unnamed.
+class MDString : public Value {
+ virtual void anchor();
+ MDString(const MDString &) LLVM_DELETED_FUNCTION;
+
+ explicit MDString(LLVMContext &C);
+public:
+ static MDString *get(LLVMContext &Context, StringRef Str);
+ static MDString *get(LLVMContext &Context, const char *Str) {
+ return get(Context, Str ? StringRef(Str) : StringRef());
+ }
+
+ StringRef getString() const { return getName(); }
+
+ unsigned getLength() const { return (unsigned)getName().size(); }
+
+ typedef StringRef::iterator iterator;
+
+ /// begin() - Pointer to the first byte of the string.
+ iterator begin() const { return getName().begin(); }
+
+ /// end() - Pointer to one byte past the end of the string.
+ iterator end() const { return getName().end(); }
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const MDString *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == MDStringVal;
+ }
+};
+
+
+class MDNodeOperand;
+
+//===----------------------------------------------------------------------===//
+/// MDNode - a tuple of other values.
+class MDNode : public Value, public FoldingSetNode {
+ MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
+ void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
+ friend class MDNodeOperand;
+ friend class LLVMContextImpl;
+ friend struct FoldingSetTrait<MDNode>;
+
+ /// Hash - If the MDNode is uniqued cache the hash to speed up lookup.
+ unsigned Hash;
+
+ /// NumOperands - This many 'MDNodeOperand' items are co-allocated onto the
+ /// end of this MDNode.
+ unsigned NumOperands;
+
+ // Subclass data enums.
+ enum {
+ /// FunctionLocalBit - This bit is set if this MDNode is function local.
+ /// This is true when it (potentially transitively) contains a reference to
+ /// something in a function, like an argument, basicblock, or instruction.
+ FunctionLocalBit = 1 << 0,
+
+ /// NotUniquedBit - This is set on MDNodes that are not uniqued because they
+ /// have a null operand.
+ NotUniquedBit = 1 << 1,
+
+ /// DestroyFlag - This bit is set by destroy() so the destructor can assert
+ /// that the node isn't being destroyed with a plain 'delete'.
+ DestroyFlag = 1 << 2
+ };
+
+ // FunctionLocal enums.
+ enum FunctionLocalness {
+ FL_Unknown = -1,
+ FL_No = 0,
+ FL_Yes = 1
+ };
+
+ /// replaceOperand - Replace each instance of F from the operand list of this
+ /// node with T.
+ void replaceOperand(MDNodeOperand *Op, Value *NewVal);
+ ~MDNode();
+
+ MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal);
+
+ static MDNode *getMDNode(LLVMContext &C, ArrayRef<Value*> Vals,
+ FunctionLocalness FL, bool Insert = true);
+public:
+ // Constructors and destructors.
+ static MDNode *get(LLVMContext &Context, ArrayRef<Value*> Vals);
+ // getWhenValsUnresolved - Construct MDNode determining function-localness
+ // from isFunctionLocal argument, not by analyzing Vals.
+ static MDNode *getWhenValsUnresolved(LLVMContext &Context,
+ ArrayRef<Value*> Vals,
+ bool isFunctionLocal);
+
+ static MDNode *getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals);
+
+ /// getTemporary - Return a temporary MDNode, for use in constructing
+ /// cyclic MDNode structures. A temporary MDNode is not uniqued,
+ /// may be RAUW'd, and must be manually deleted with deleteTemporary.
+ static MDNode *getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals);
+
+ /// deleteTemporary - Deallocate a node created by getTemporary. The
+ /// node must not have any users.
+ static void deleteTemporary(MDNode *N);
+
+ /// replaceOperandWith - Replace a specific operand.
+ void replaceOperandWith(unsigned i, Value *NewVal);
+
+ /// getOperand - Return specified operand.
+ Value *getOperand(unsigned i) const;
+
+ /// getNumOperands - Return number of MDNode operands.
+ unsigned getNumOperands() const { return NumOperands; }
+
+ /// isFunctionLocal - Return whether MDNode is local to a function.
+ bool isFunctionLocal() const {
+ return (getSubclassDataFromValue() & FunctionLocalBit) != 0;
+ }
+
+ // getFunction - If this metadata is function-local and recursively has a
+ // function-local operand, return the first such operand's parent function.
+ // Otherwise, return null. getFunction() should not be used for performance-
+ // critical code because it recursively visits all the MDNode's operands.
+ const Function *getFunction() const;
+
+ /// Profile - calculate a unique identifier for this MDNode to collapse
+ /// duplicates
+ void Profile(FoldingSetNodeID &ID) const;
+
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
+ static inline bool classof(const MDNode *) { return true; }
+ static bool classof(const Value *V) {
+ return V->getValueID() == MDNodeVal;
+ }
+
+ /// Methods for metadata merging.
+ static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
+ static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
+ static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
+private:
+ // destroy - Delete this node. Only when there are no uses.
+ void destroy();
+
+ bool isNotUniqued() const {
+ return (getSubclassDataFromValue() & NotUniquedBit) != 0;
+ }
+ void setIsNotUniqued();
+
+ // Shadow Value::setValueSubclassData with a private forwarding method so that
+ // any future subclasses cannot accidentally use it.
+ void setValueSubclassData(unsigned short D) {
+ Value::setValueSubclassData(D);
+ }
+};
+
+//===----------------------------------------------------------------------===//
+/// NamedMDNode - a tuple of MDNodes. Despite its name, a NamedMDNode isn't
+/// itself an MDNode. NamedMDNodes belong to modules, have names, and contain
+/// lists of MDNodes.
+class NamedMDNode : public ilist_node<NamedMDNode> {
+ friend class SymbolTableListTraits<NamedMDNode, Module>;
+ friend struct ilist_traits<NamedMDNode>;
+ friend class LLVMContextImpl;
+ friend class Module;
+ NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
+
+ std::string Name;
+ Module *Parent;
+ void *Operands; // SmallVector<TrackingVH<MDNode>, 4>
+
+ void setParent(Module *M) { Parent = M; }
+
+ explicit NamedMDNode(const Twine &N);
+
+public:
+ /// eraseFromParent - Drop all references and remove the node from parent
+ /// module.
+ void eraseFromParent();
+
+ /// dropAllReferences - Remove all uses and clear node vector.
+ void dropAllReferences();
+
+ /// ~NamedMDNode - Destroy NamedMDNode.
+ ~NamedMDNode();
+
+ /// getParent - Get the module that holds this named metadata collection.
+ inline Module *getParent() { return Parent; }
+ inline const Module *getParent() const { return Parent; }
+
+ /// getOperand - Return specified operand.
+ MDNode *getOperand(unsigned i) const;
+
+ /// getNumOperands - Return the number of NamedMDNode operands.
+ unsigned getNumOperands() const;
+
+ /// addOperand - Add metadata operand.
+ void addOperand(MDNode *M);
+
+ /// getName - Return a constant reference to this named metadata's name.
+ StringRef getName() const;
+
+ /// print - Implement operator<< on NamedMDNode.
+ void print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW = 0) const;
+
+ /// dump() - Allow printing of NamedMDNodes from the debugger.
+ void dump() const;
+};
+
+} // end llvm namespace
+
+#endif
diff --git a/include/llvm/Module.h b/include/llvm/Module.h
new file mode 100644
index 00000000000..e6303ac7752
--- /dev/null
+++ b/include/llvm/Module.h
@@ -0,0 +1,605 @@
+//===-- llvm/Module.h - C++ class to represent a VM module ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+/// @file
+/// Module.h This file contains the declarations for the Module class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_MODULE_H
+#define LLVM_MODULE_H
+
+#include "llvm/Function.h"
+#include "llvm/GlobalVariable.h"
+#include "llvm/GlobalAlias.h"
+#include "llvm/Metadata.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/Support/DataTypes.h"
+#include <vector>
+
+namespace llvm {
+
+class FunctionType;
+class GVMaterializer;
+class LLVMContext;
+class StructType;
+template<typename T> struct DenseMapInfo;
+template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
+
+template<> struct ilist_traits<Function>
+ : public SymbolTableListTraits<Function, Module> {
+
+ // createSentinel is used to get hold of the node that marks the end of the
+ // list... (same trick used here as in ilist_traits<Instruction>)
+ Function *createSentinel() const {
+ return static_cast<Function*>(&Sentinel);
+ }
+ static void destroySentinel(Function*) {}
+
+ Function *provideInitialHead() const { return createSentinel(); }
+ Function *ensureHead(Function*) const { return createSentinel(); }
+ static void noteHead(Function*, Function*) {}
+
+private:
+ mutable ilist_node<Function> Sentinel;
+};
+
+template<> struct ilist_traits<GlobalVariable>
+ : public SymbolTableListTraits<GlobalVariable, Module> {
+ // createSentinel is used to create a node that marks the end of the list.
+ GlobalVariable *createSentinel() const {
+ return static_cast<GlobalVariable*>(&Sentinel);
+ }
+ static void destroySentinel(GlobalVariable*) {}
+
+ GlobalVariable *provideInitialHead() const { return createSentinel(); }
+ GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
+ static void noteHead(GlobalVariable*, GlobalVariable*) {}
+private:
+ mutable ilist_node<GlobalVariable> Sentinel;
+};
+
+template<> struct ilist_traits<GlobalAlias>
+ : public SymbolTableListTraits<GlobalAlias, Module> {
+ // createSentinel is used to create a node that marks the end of the list.
+ GlobalAlias *createSentinel() const {
+ return static_cast<GlobalAlias*>(&Sentinel);
+ }
+ static void destroySentinel(GlobalAlias*) {}
+
+ GlobalAlias *provideInitialHead() const { return createSentinel(); }
+ GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
+ static void noteHead(GlobalAlias*, GlobalAlias*) {}
+private:
+ mutable ilist_node<GlobalAlias> Sentinel;
+};
+
+template<> struct ilist_traits<NamedMDNode>
+ : public ilist_default_traits<NamedMDNode> {
+ // createSentinel is used to get hold of a node that marks the end of
+ // the list...
+ NamedMDNode *createSentinel() const {
+ return static_cast<NamedMDNode*>(&Sentinel);
+ }
+ static void destroySentinel(NamedMDNode*) {}
+
+ NamedMDNode *provideInitialHead() const { return createSentinel(); }
+ NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
+ static void noteHead(NamedMDNode*, NamedMDNode*) {}
+ void addNodeToList(NamedMDNode *) {}
+ void removeNodeFromList(NamedMDNode *) {}
+private:
+ mutable ilist_node<NamedMDNode> Sentinel;
+};
+
+/// A Module instance is used to store all the information related to an
+/// LLVM module. Modules are the top level container of all other LLVM
+/// Intermediate Representation (IR) objects. Each module directly contains a
+/// list of globals variables, a list of functions, a list of libraries (or
+/// other modules) this module depends on, a symbol table, and various data
+/// about the target's characteristics.
+///
+/// A module maintains a GlobalValRefMap object that is used to hold all
+/// constant references to global variables in the module. When a global
+/// variable is destroyed, it should have no entries in the GlobalValueRefMap.
+/// @brief The main container class for the LLVM Intermediate Representation.
+class Module {
+/// @name Types And Enumerations
+/// @{
+public:
+ /// The type for the list of global variables.
+ typedef iplist<GlobalVariable> GlobalListType;
+ /// The type for the list of functions.
+ typedef iplist<Function> FunctionListType;
+ /// The type for the list of aliases.
+ typedef iplist<GlobalAlias> AliasListType;
+ /// The type for the list of named metadata.
+ typedef ilist<NamedMDNode> NamedMDListType;
+
+ /// The type for the list of dependent libraries.
+ typedef std::vector<std::string> LibraryListType;
+
+ /// The Global Variable iterator.
+ typedef GlobalListType::iterator global_iterator;
+ /// The Global Variable constant iterator.
+ typedef GlobalListType::const_iterator const_global_iterator;
+
+ /// The Function iterators.
+ typedef FunctionListType::iterator iterator;
+ /// The Function constant iterator
+ typedef FunctionListType::const_iterator const_iterator;
+
+ /// The Global Alias iterators.
+ typedef AliasListType::iterator alias_iterator;
+ /// The Global Alias constant iterator
+ typedef AliasListType::const_iterator const_alias_iterator;
+
+ /// The named metadata iterators.
+ typedef NamedMDListType::iterator named_metadata_iterator;
+ /// The named metadata constant interators.
+ typedef NamedMDListType::const_iterator const_named_metadata_iterator;
+ /// The Library list iterator.
+ typedef LibraryListType::const_iterator lib_iterator;
+
+ /// An enumeration for describing the endianess of the target machine.
+ enum Endianness { AnyEndianness, LittleEndian, BigEndian };
+
+ /// An enumeration for describing the size of a pointer on the target machine.
+ enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
+
+ /// An enumeration for the supported behaviors of module flags. The following
+ /// module flags behavior values are supported:
+ ///
+ /// Value Behavior
+ /// ----- --------
+ /// 1 Error
+ /// Emits an error if two values disagree.
+ ///
+ /// 2 Warning
+ /// Emits a warning if two values disagree.
+ ///
+ /// 3 Require
+ /// Emits an error when the specified value is not present
+ /// or doesn't have the specified value. It is an error for
+ /// two (or more) llvm.module.flags with the same ID to have
+ /// the Require behavior but different values. There may be
+ /// multiple Require flags per ID.
+ ///
+ /// 4 Override
+ /// Uses the specified value if the two values disagree. It
+ /// is an error for two (or more) llvm.module.flags with the
+ /// same ID to have the Override behavior but different
+ /// values.
+ enum ModFlagBehavior { Error = 1, Warning = 2, Require = 3, Override = 4 };
+
+ struct ModuleFlagEntry {
+ ModFlagBehavior Behavior;
+ MDString *Key;
+ Value *Val;
+ ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
+ : Behavior(B), Key(K), Val(V) {}
+ };
+
+/// @}
+/// @name Member Variables
+/// @{
+private:
+ LLVMContext &Context; ///< The LLVMContext from which types and
+ ///< constants are allocated.
+ GlobalListType GlobalList; ///< The Global Variables in the module
+ FunctionListType FunctionList; ///< The Functions in the module
+ AliasListType AliasList; ///< The Aliases in the module
+ LibraryListType LibraryList; ///< The Libraries needed by the module
+ NamedMDListType NamedMDList; ///< The named metadata in the module
+ std::string GlobalScopeAsm; ///< Inline Asm at global scope.
+ ValueSymbolTable *ValSymTab; ///< Symbol table for values
+ OwningPtr<GVMaterializer> Materializer; ///< Used to materialize GlobalValues
+ std::string ModuleID; ///< Human readable identifier for the module
+ std::string TargetTriple; ///< Platform target triple Module compiled on
+ std::string DataLayout; ///< Target data description
+ void *NamedMDSymTab; ///< NamedMDNode names.
+
+ friend class Constant;
+
+/// @}
+/// @name Constructors
+/// @{
+public:
+ /// The Module constructor. Note that there is no default constructor. You
+ /// must provide a name for the module upon construction.
+ explicit Module(StringRef ModuleID, LLVMContext& C);
+ /// The module destructor. This will dropAllReferences.
+ ~Module();
+
+/// @}
+/// @name Module Level Accessors
+/// @{
+
+ /// Get the module identifier which is, essentially, the name of the module.
+ /// @returns the module identifier as a string
+ const std::string &getModuleIdentifier() const { return ModuleID; }
+
+ /// Get the data layout string for the module's target platform. This encodes
+ /// the type sizes and alignments expected by this module.
+ /// @returns the data layout as a string
+ const std::string &getDataLayout() const { return DataLayout; }
+
+ /// Get the target triple which is a string describing the target host.
+ /// @returns a string containing the target triple.
+ const std::string &getTargetTriple() const { return TargetTriple; }
+
+ /// Get the target endian information.
+ /// @returns Endianess - an enumeration for the endianess of the target
+ Endianness getEndianness() const;
+
+ /// Get the target pointer size.
+ /// @returns PointerSize - an enumeration for the size of the target's pointer
+ PointerSize getPointerSize() const;
+
+ /// Get the global data context.
+ /// @returns LLVMContext - a container for LLVM's global information
+ LLVMContext &getContext() const { return Context; }
+
+ /// Get any module-scope inline assembly blocks.
+ /// @returns a string containing the module-scope inline assembly blocks.
+ const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
+
+/// @}
+/// @name Module Level Mutators
+/// @{
+
+ /// Set the module identifier.
+ void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
+
+ /// Set the data layout
+ void setDataLayout(StringRef DL) { DataLayout = DL; }
+
+ /// Set the target triple.
+ void setTargetTriple(StringRef T) { TargetTriple = T; }
+
+ /// Set the module-scope inline assembly blocks.
+ void setModuleInlineAsm(StringRef Asm) {
+ GlobalScopeAsm = Asm;
+ if (!GlobalScopeAsm.empty() &&
+ GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
+ GlobalScopeAsm += '\n';
+ }
+
+ /// Append to the module-scope inline assembly blocks, automatically inserting
+ /// a separating newline if necessary.
+ void appendModuleInlineAsm(StringRef Asm) {
+ GlobalScopeAsm += Asm;
+ if (!GlobalScopeAsm.empty() &&
+ GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
+ GlobalScopeAsm += '\n';
+ }
+
+/// @}
+/// @name Generic Value Accessors
+/// @{
+
+ /// getNamedValue - Return the global value in the module with
+ /// the specified name, of arbitrary type. This method returns null
+ /// if a global with the specified name is not found.
+ GlobalValue *getNamedValue(StringRef Name) const;
+
+ /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
+ /// This ID is uniqued across modules in the current LLVMContext.
+ unsigned getMDKindID(StringRef Name) const;
+
+ /// getMDKindNames - Populate client supplied SmallVector with the name for
+ /// custom metadata IDs registered in this LLVMContext.
+ void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
+
+
+ typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*> >
+ NumeredTypesMapTy;
+
+ /// getTypeByName - Return the type with the specified name, or null if there
+ /// is none by that name.
+ StructType *getTypeByName(StringRef Name) const;
+
+/// @}
+/// @name Function Accessors
+/// @{
+
+ /// getOrInsertFunction - Look up the specified function in the module symbol
+ /// table. Four possibilities:
+ /// 1. If it does not exist, add a prototype for the function and return it.
+ /// 2. If it exists, and has a local linkage, the existing function is
+ /// renamed and a new one is inserted.
+ /// 3. Otherwise, if the existing function has the correct prototype, return
+ /// the existing function.
+ /// 4. Finally, the function exists but has the wrong prototype: return the
+ /// function with a constantexpr cast to the right prototype.
+ Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
+ AttrListPtr AttributeList);
+
+ Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
+
+ /// getOrInsertFunction - Look up the specified function in the module symbol
+ /// table. If it does not exist, add a prototype for the function and return
+ /// it. This function guarantees to return a constant of pointer to the
+ /// specified function type or a ConstantExpr BitCast of that type if the
+ /// named function has a different type. This version of the method takes a
+ /// null terminated list of function arguments, which makes it easier for
+ /// clients to use.
+ Constant *getOrInsertFunction(StringRef Name,
+ AttrListPtr AttributeList,
+ Type *RetTy, ...) END_WITH_NULL;
+
+ /// getOrInsertFunction - Same as above, but without the attributes.
+ Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
+ END_WITH_NULL;
+
+ Constant *getOrInsertTargetIntrinsic(StringRef Name,
+ FunctionType *Ty,
+ AttrListPtr AttributeList);
+
+ /// getFunction - Look up the specified function in the module symbol table.
+ /// If it does not exist, return null.
+ Function *getFunction(StringRef Name) const;
+
+/// @}
+/// @name Global Variable Accessors
+/// @{
+
+ /// getGlobalVariable - Look up the specified global variable in the module
+ /// symbol table. If it does not exist, return null. If AllowInternal is set
+ /// to true, this function will return types that have InternalLinkage. By
+ /// default, these types are not returned.
+ GlobalVariable *getGlobalVariable(StringRef Name,
+ bool AllowInternal = false) const;
+
+ /// getNamedGlobal - Return the global variable in the module with the
+ /// specified name, of arbitrary type. This method returns null if a global
+ /// with the specified name is not found.
+ GlobalVariable *getNamedGlobal(StringRef Name) const {
+ return getGlobalVariable(Name, true);
+ }
+
+ /// getOrInsertGlobal - Look up the specified global in the module symbol
+ /// table.
+ /// 1. If it does not exist, add a declaration of the global and return it.
+ /// 2. Else, the global exists but has the wrong type: return the function
+ /// with a constantexpr cast to the right type.
+ /// 3. Finally, if the existing global is the correct declaration, return
+ /// the existing global.
+ Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
+
+/// @}
+/// @name Global Alias Accessors
+/// @{
+
+ /// getNamedAlias - Return the global alias in the module with the
+ /// specified name, of arbitrary type. This method returns null if a global
+ /// with the specified name is not found.
+ GlobalAlias *getNamedAlias(StringRef Name) const;
+
+/// @}
+/// @name Named Metadata Accessors
+/// @{
+
+ /// getNamedMetadata - Return the NamedMDNode in the module with the
+ /// specified name. This method returns null if a NamedMDNode with the
+ /// specified name is not found.
+ NamedMDNode *getNamedMetadata(const Twine &Name) const;
+
+ /// getOrInsertNamedMetadata - Return the named MDNode in the module
+ /// with the specified name. This method returns a new NamedMDNode if a
+ /// NamedMDNode with the specified name is not found.
+ NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
+
+ /// eraseNamedMetadata - Remove the given NamedMDNode from this module
+ /// and delete it.
+ void eraseNamedMetadata(NamedMDNode *NMD);
+
+/// @}
+/// @name Module Flags Accessors
+/// @{
+
+ /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
+ void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
+
+ /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
+ /// represents module-level flags. This method returns null if there are no
+ /// module-level flags.
+ NamedMDNode *getModuleFlagsMetadata() const;
+
+ /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
+ /// that represents module-level flags. If module-level flags aren't found,
+ /// it creates the named metadata that contains them.
+ NamedMDNode *getOrInsertModuleFlagsMetadata();
+
+ /// addModuleFlag - Add a module-level flag to the module-level flags
+ /// metadata. It will create the module-level flags named metadata if it
+ /// doesn't already exist.
+ void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
+ void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
+ void addModuleFlag(MDNode *Node);
+
+/// @}
+/// @name Materialization
+/// @{
+
+ /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
+ /// yet have a Materializer. To reset the materializer for a module that
+ /// already has one, call MaterializeAllPermanently first. Destroying this
+ /// module will destroy its materializer without materializing any more
+ /// GlobalValues. Without destroying the Module, there is no way to detach or
+ /// destroy a materializer without materializing all the GVs it controls, to
+ /// avoid leaving orphan unmaterialized GVs.
+ void setMaterializer(GVMaterializer *GVM);
+ /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
+ GVMaterializer *getMaterializer() const { return Materializer.get(); }
+
+ /// isMaterializable - True if the definition of GV has yet to be materialized
+ /// from the GVMaterializer.
+ bool isMaterializable(const GlobalValue *GV) const;
+ /// isDematerializable - Returns true if this GV was loaded from this Module's
+ /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
+ bool isDematerializable(const GlobalValue *GV) const;
+
+ /// Materialize - Make sure the GlobalValue is fully read. If the module is
+ /// corrupt, this returns true and fills in the optional string with
+ /// information about the problem. If successful, this returns false.
+ bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
+ /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
+ /// supports it, release the memory for the function, and set it up to be
+ /// materialized lazily. If !isDematerializable(), this method is a noop.
+ void Dematerialize(GlobalValue *GV);
+
+ /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
+ /// If the module is corrupt, this returns true and fills in the optional
+ /// string with information about the problem. If successful, this returns
+ /// false.
+ bool MaterializeAll(std::string *ErrInfo = 0);
+
+ /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
+ /// fully read and clear the Materializer. If the module is corrupt, this
+ /// returns true, fills in the optional string with information about the
+ /// problem, and DOES NOT clear the old Materializer. If successful, this
+ /// returns false.
+ bool MaterializeAllPermanently(std::string *ErrInfo = 0);
+
+/// @}
+/// @name Direct access to the globals list, functions list, and symbol table
+/// @{
+
+ /// Get the Module's list of global variables (constant).
+ const GlobalListType &getGlobalList() const { return GlobalList; }
+ /// Get the Module's list of global variables.
+ GlobalListType &getGlobalList() { return GlobalList; }
+ static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
+ return &Module::GlobalList;
+ }
+ /// Get the Module's list of functions (constant).
+ const FunctionListType &getFunctionList() const { return FunctionList; }
+ /// Get the Module's list of functions.
+ FunctionListType &getFunctionList() { return FunctionList; }
+ static iplist<Function> Module::*getSublistAccess(Function*) {
+ return &Module::FunctionList;
+ }
+ /// Get the Module's list of aliases (constant).
+ const AliasListType &getAliasList() const { return AliasList; }
+ /// Get the Module's list of aliases.
+ AliasListType &getAliasList() { return AliasList; }
+ static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
+ return &Module::AliasList;
+ }
+ /// Get the Module's list of named metadata (constant).
+ const NamedMDListType &getNamedMDList() const { return NamedMDList; }
+ /// Get the Module's list of named metadata.
+ NamedMDListType &getNamedMDList() { return NamedMDList; }
+ static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
+ return &Module::NamedMDList;
+ }
+ /// Get the symbol table of global variable and function identifiers
+ const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
+ /// Get the Module's symbol table of global variable and function identifiers.
+ ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
+
+/// @}
+/// @name Global Variable Iteration
+/// @{
+
+ global_iterator global_begin() { return GlobalList.begin(); }
+ const_global_iterator global_begin() const { return GlobalList.begin(); }
+ global_iterator global_end () { return GlobalList.end(); }
+ const_global_iterator global_end () const { return GlobalList.end(); }
+ bool global_empty() const { return GlobalList.empty(); }
+
+/// @}
+/// @name Function Iteration
+/// @{
+
+ iterator begin() { return FunctionList.begin(); }
+ const_iterator begin() const { return FunctionList.begin(); }
+ iterator end () { return FunctionList.end(); }
+ const_iterator end () const { return FunctionList.end(); }
+ size_t size() const { return FunctionList.size(); }
+ bool empty() const { return FunctionList.empty(); }
+
+/// @}
+/// @name Dependent Library Iteration
+/// @{
+
+ /// @brief Get a constant iterator to beginning of dependent library list.
+ inline lib_iterator lib_begin() const { return LibraryList.begin(); }
+ /// @brief Get a constant iterator to end of dependent library list.
+ inline lib_iterator lib_end() const { return LibraryList.end(); }
+ /// @brief Returns the number of items in the list of libraries.
+ inline size_t lib_size() const { return LibraryList.size(); }
+ /// @brief Add a library to the list of dependent libraries
+ void addLibrary(StringRef Lib);
+ /// @brief Remove a library from the list of dependent libraries
+ void removeLibrary(StringRef Lib);
+ /// @brief Get all the libraries
+ inline const LibraryListType& getLibraries() const { return LibraryList; }
+
+/// @}
+/// @name Alias Iteration
+/// @{
+
+ alias_iterator alias_begin() { return AliasList.begin(); }
+ const_alias_iterator alias_begin() const { return AliasList.begin(); }
+ alias_iterator alias_end () { return AliasList.end(); }
+ const_alias_iterator alias_end () const { return AliasList.end(); }
+ size_t alias_size () const { return AliasList.size(); }
+ bool alias_empty() const { return AliasList.empty(); }
+
+
+/// @}
+/// @name Named Metadata Iteration
+/// @{
+
+ named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
+ const_named_metadata_iterator named_metadata_begin() const {
+ return NamedMDList.begin();
+ }
+
+ named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
+ const_named_metadata_iterator named_metadata_end() const {
+ return NamedMDList.end();
+ }
+
+ size_t named_metadata_size() const { return NamedMDList.size(); }
+ bool named_metadata_empty() const { return NamedMDList.empty(); }
+
+
+/// @}
+/// @name Utility functions for printing and dumping Module objects
+/// @{
+
+ /// Print the module to an output stream with an optional
+ /// AssemblyAnnotationWriter.
+ void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
+
+ /// Dump the module to stderr (for debugging).
+ void dump() const;
+
+ /// This function causes all the subinstructions to "let go" of all references
+ /// that they are maintaining. This allows one to 'delete' a whole class at
+ /// a time, even though there may be circular references... first all
+ /// references are dropped, and all use counts go to zero. Then everything
+ /// is delete'd for real. Note that no operations are valid on an object
+ /// that has "dropped all references", except operator delete.
+ void dropAllReferences();
+/// @}
+};
+
+/// An raw_ostream inserter for modules.
+inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
+ M.print(O, 0);
+ return O;
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Object/Archive.h b/include/llvm/Object/Archive.h
new file mode 100644
index 00000000000..358b27a416c
--- /dev/null
+++ b/include/llvm/Object/Archive.h
@@ -0,0 +1,145 @@
+//===- Archive.h - ar archive file format -----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the ar archive file format class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_ARCHIVE_H
+#define LLVM_OBJECT_ARCHIVE_H
+
+#include "llvm/Object/Binary.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+namespace object {
+
+class Archive : public Binary {
+ virtual void anchor();
+public:
+ class Child {
+ const Archive *Parent;
+ StringRef Data;
+
+ public:
+ Child(const Archive *p, StringRef d) : Parent(p), Data(d) {}
+
+ bool operator ==(const Child &other) const {
+ return (Parent == other.Parent) && (Data.begin() == other.Data.begin());
+ }
+
+ bool operator <(const Child &other) const {
+ return Data.begin() < other.Data.begin();
+ }
+
+ Child getNext() const;
+ error_code getName(StringRef &Result) const;
+ int getLastModified() const;
+ int getUID() const;
+ int getGID() const;
+ int getAccessMode() const;
+ ///! Return the size of the archive member without the header or padding.
+ uint64_t getSize() const;
+
+ MemoryBuffer *getBuffer() const;
+ error_code getAsBinary(OwningPtr<Binary> &Result) const;
+ };
+
+ class child_iterator {
+ Child child;
+ public:
+ child_iterator() : child(Child(0, StringRef())) {}
+ child_iterator(const Child &c) : child(c) {}
+ const Child* operator->() const {
+ return &child;
+ }
+
+ bool operator==(const child_iterator &other) const {
+ return child == other.child;
+ }
+
+ bool operator!=(const child_iterator &other) const {
+ return !(*this == other);
+ }
+
+ bool operator <(const child_iterator &other) const {
+ return child < other.child;
+ }
+
+ child_iterator& operator++() { // Preincrement
+ child = child.getNext();
+ return *this;
+ }
+ };
+
+ class Symbol {
+ const Archive *Parent;
+ uint32_t SymbolIndex;
+ uint32_t StringIndex; // Extra index to the string.
+
+ public:
+ bool operator ==(const Symbol &other) const {
+ return (Parent == other.Parent) && (SymbolIndex == other.SymbolIndex);
+ }
+
+ Symbol(const Archive *p, uint32_t symi, uint32_t stri)
+ : Parent(p)
+ , SymbolIndex(symi)
+ , StringIndex(stri) {}
+ error_code getName(StringRef &Result) const;
+ error_code getMember(child_iterator &Result) const;
+ Symbol getNext() const;
+ };
+
+ class symbol_iterator {
+ Symbol symbol;
+ public:
+ symbol_iterator(const Symbol &s) : symbol(s) {}
+ const Symbol *operator->() const {
+ return &symbol;
+ }
+
+ bool operator==(const symbol_iterator &other) const {
+ return symbol == other.symbol;
+ }
+
+ bool operator!=(const symbol_iterator &other) const {
+ return !(*this == other);
+ }
+
+ symbol_iterator& operator++() { // Preincrement
+ symbol = symbol.getNext();
+ return *this;
+ }
+ };
+
+ Archive(MemoryBuffer *source, error_code &ec);
+
+ child_iterator begin_children(bool skip_internal = true) const;
+ child_iterator end_children() const;
+
+ symbol_iterator begin_symbols() const;
+ symbol_iterator end_symbols() const;
+
+ // Cast methods.
+ static inline bool classof(Archive const *v) { return true; }
+ static inline bool classof(Binary const *v) {
+ return v->isArchive();
+ }
+
+private:
+ child_iterator SymbolTable;
+ child_iterator StringTable;
+};
+
+}
+}
+
+#endif
diff --git a/include/llvm/Object/Binary.h b/include/llvm/Object/Binary.h
new file mode 100644
index 00000000000..baed81827d0
--- /dev/null
+++ b/include/llvm/Object/Binary.h
@@ -0,0 +1,104 @@
+//===- Binary.h - A generic binary file -------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the Binary class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_BINARY_H
+#define LLVM_OBJECT_BINARY_H
+
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/Object/Error.h"
+
+namespace llvm {
+
+class MemoryBuffer;
+class StringRef;
+
+namespace object {
+
+class Binary {
+private:
+ Binary() LLVM_DELETED_FUNCTION;
+ Binary(const Binary &other) LLVM_DELETED_FUNCTION;
+
+ unsigned int TypeID;
+
+protected:
+ MemoryBuffer *Data;
+
+ Binary(unsigned int Type, MemoryBuffer *Source);
+
+ enum {
+ ID_Archive,
+ // Object and children.
+ ID_StartObjects,
+ ID_COFF,
+ ID_ELF32L, // ELF 32-bit, little endian
+ ID_ELF32B, // ELF 32-bit, big endian
+ ID_ELF64L, // ELF 64-bit, little endian
+ ID_ELF64B, // ELF 64-bit, big endian
+ ID_MachO,
+ ID_EndObjects
+ };
+
+ static inline unsigned int getELFType(bool isLittleEndian, bool is64Bits) {
+ if (isLittleEndian)
+ return is64Bits ? ID_ELF64L : ID_ELF32L;
+ else
+ return is64Bits ? ID_ELF64B : ID_ELF32B;
+ }
+
+public:
+ virtual ~Binary();
+
+ StringRef getData() const;
+ StringRef getFileName() const;
+
+ // Cast methods.
+ unsigned int getType() const { return TypeID; }
+ static inline bool classof(const Binary *v) { return true; }
+
+ // Convenience methods
+ bool isObject() const {
+ return TypeID > ID_StartObjects && TypeID < ID_EndObjects;
+ }
+
+ bool isArchive() const {
+ return TypeID == ID_Archive;
+ }
+
+ bool isELF() const {
+ return TypeID >= ID_ELF32L && TypeID <= ID_ELF64B;
+ }
+
+ bool isMachO() const {
+ return TypeID == ID_MachO;
+ }
+
+ bool isCOFF() const {
+ return TypeID == ID_COFF;
+ }
+};
+
+/// @brief Create a Binary from Source, autodetecting the file type.
+///
+/// @param Source The data to create the Binary from. Ownership is transferred
+/// to Result if successful. If an error is returned, Source is destroyed
+/// by createBinary before returning.
+/// @param Result A pointer to the resulting Binary if no error occured.
+error_code createBinary(MemoryBuffer *Source, OwningPtr<Binary> &Result);
+
+error_code createBinary(StringRef Path, OwningPtr<Binary> &Result);
+
+}
+}
+
+#endif
diff --git a/include/llvm/Object/COFF.h b/include/llvm/Object/COFF.h
new file mode 100644
index 00000000000..967420ec9f1
--- /dev/null
+++ b/include/llvm/Object/COFF.h
@@ -0,0 +1,206 @@
+//===- COFF.h - COFF object file implementation -----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the COFFObjectFile class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_COFF_H
+#define LLVM_OBJECT_COFF_H
+
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Support/COFF.h"
+#include "llvm/Support/Endian.h"
+
+namespace llvm {
+ template <typename T>
+ class ArrayRef;
+
+namespace object {
+
+struct coff_file_header {
+ support::ulittle16_t Machine;
+ support::ulittle16_t NumberOfSections;
+ support::ulittle32_t TimeDateStamp;
+ support::ulittle32_t PointerToSymbolTable;
+ support::ulittle32_t NumberOfSymbols;
+ support::ulittle16_t SizeOfOptionalHeader;
+ support::ulittle16_t Characteristics;
+};
+
+struct coff_symbol {
+ struct StringTableOffset {
+ support::ulittle32_t Zeroes;
+ support::ulittle32_t Offset;
+ };
+
+ union {
+ char ShortName[8];
+ StringTableOffset Offset;
+ } Name;
+
+ support::ulittle32_t Value;
+ support::little16_t SectionNumber;
+
+ support::ulittle16_t Type;
+
+ support::ulittle8_t StorageClass;
+ support::ulittle8_t NumberOfAuxSymbols;
+
+ uint8_t getBaseType() const {
+ return Type & 0x0F;
+ }
+
+ uint8_t getComplexType() const {
+ return (Type & 0xF0) >> 4;
+ }
+};
+
+struct coff_section {
+ char Name[8];
+ support::ulittle32_t VirtualSize;
+ support::ulittle32_t VirtualAddress;
+ support::ulittle32_t SizeOfRawData;
+ support::ulittle32_t PointerToRawData;
+ support::ulittle32_t PointerToRelocations;
+ support::ulittle32_t PointerToLinenumbers;
+ support::ulittle16_t NumberOfRelocations;
+ support::ulittle16_t NumberOfLinenumbers;
+ support::ulittle32_t Characteristics;
+};
+
+struct coff_relocation {
+ support::ulittle32_t VirtualAddress;
+ support::ulittle32_t SymbolTableIndex;
+ support::ulittle16_t Type;
+};
+
+struct coff_aux_section_definition {
+ support::ulittle32_t Length;
+ support::ulittle16_t NumberOfRelocations;
+ support::ulittle16_t NumberOfLinenumbers;
+ support::ulittle32_t CheckSum;
+ support::ulittle16_t Number;
+ support::ulittle8_t Selection;
+ char Unused[3];
+};
+
+class COFFObjectFile : public ObjectFile {
+private:
+ const coff_file_header *Header;
+ const coff_section *SectionTable;
+ const coff_symbol *SymbolTable;
+ const char *StringTable;
+ uint32_t StringTableSize;
+
+ error_code getString(uint32_t offset, StringRef &Res) const;
+
+ const coff_symbol *toSymb(DataRefImpl Symb) const;
+ const coff_section *toSec(DataRefImpl Sec) const;
+ const coff_relocation *toRel(DataRefImpl Rel) const;
+
+protected:
+ virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
+ virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
+ virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
+ virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
+ virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res) const;
+ virtual error_code getSymbolSection(DataRefImpl Symb,
+ section_iterator &Res) const;
+
+ virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
+ virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
+ virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
+ virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
+ bool &Res) const;
+ virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
+ bool &Result) const;
+ virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
+ virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
+
+ virtual error_code getRelocationNext(DataRefImpl Rel,
+ RelocationRef &Res) const;
+ virtual error_code getRelocationAddress(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationOffset(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationSymbol(DataRefImpl Rel,
+ SymbolRef &Res) const;
+ virtual error_code getRelocationType(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationTypeName(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const;
+ virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
+ int64_t &Res) const;
+ virtual error_code getRelocationValueString(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const;
+
+ virtual error_code getLibraryNext(DataRefImpl LibData,
+ LibraryRef &Result) const;
+ virtual error_code getLibraryPath(DataRefImpl LibData,
+ StringRef &Result) const;
+
+public:
+ COFFObjectFile(MemoryBuffer *Object, error_code &ec);
+ virtual symbol_iterator begin_symbols() const;
+ virtual symbol_iterator end_symbols() const;
+ virtual symbol_iterator begin_dynamic_symbols() const;
+ virtual symbol_iterator end_dynamic_symbols() const;
+ virtual library_iterator begin_libraries_needed() const;
+ virtual library_iterator end_libraries_needed() const;
+ virtual section_iterator begin_sections() const;
+ virtual section_iterator end_sections() const;
+
+ const coff_section *getCOFFSection(section_iterator &It) const;
+ const coff_symbol *getCOFFSymbol(symbol_iterator &It) const;
+ const coff_relocation *getCOFFRelocation(relocation_iterator &It) const;
+
+ virtual uint8_t getBytesInAddress() const;
+ virtual StringRef getFileFormatName() const;
+ virtual unsigned getArch() const;
+ virtual StringRef getLoadName() const;
+
+ error_code getHeader(const coff_file_header *&Res) const;
+ error_code getSection(int32_t index, const coff_section *&Res) const;
+ error_code getSymbol(uint32_t index, const coff_symbol *&Res) const;
+ template <typename T>
+ error_code getAuxSymbol(uint32_t index, const T *&Res) const {
+ const coff_symbol *s;
+ error_code ec = getSymbol(index, s);
+ Res = reinterpret_cast<const T*>(s);
+ return ec;
+ }
+ error_code getSymbolName(const coff_symbol *symbol, StringRef &Res) const;
+ ArrayRef<uint8_t> getSymbolAuxData(const coff_symbol *symbol) const;
+
+ error_code getSectionName(const coff_section *Sec, StringRef &Res) const;
+ error_code getSectionContents(const coff_section *Sec,
+ ArrayRef<uint8_t> &Res) const;
+
+ static inline bool classof(const Binary *v) {
+ return v->isCOFF();
+ }
+ static inline bool classof(const COFFObjectFile *v) { return true; }
+};
+
+}
+}
+
+#endif
diff --git a/include/llvm/Object/ELF.h b/include/llvm/Object/ELF.h
new file mode 100644
index 00000000000..03a1417bedf
--- /dev/null
+++ b/include/llvm/Object/ELF.h
@@ -0,0 +1,2595 @@
+//===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the ELFObjectFile template class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_ELF_H
+#define LLVM_OBJECT_ELF_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/ELF.h"
+#include "llvm/Support/Endian.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/raw_ostream.h"
+#include <algorithm>
+#include <limits>
+#include <utility>
+
+namespace llvm {
+namespace object {
+
+// Subclasses of ELFObjectFile may need this for template instantiation
+inline std::pair<unsigned char, unsigned char>
+getElfArchType(MemoryBuffer *Object) {
+ if (Object->getBufferSize() < ELF::EI_NIDENT)
+ return std::make_pair((uint8_t)ELF::ELFCLASSNONE,(uint8_t)ELF::ELFDATANONE);
+ return std::make_pair( (uint8_t)Object->getBufferStart()[ELF::EI_CLASS]
+ , (uint8_t)Object->getBufferStart()[ELF::EI_DATA]);
+}
+
+// Templates to choose Elf_Addr and Elf_Off depending on is64Bits.
+template<support::endianness target_endianness>
+struct ELFDataTypeTypedefHelperCommon {
+ typedef support::detail::packed_endian_specific_integral
+ <uint16_t, target_endianness, support::aligned> Elf_Half;
+ typedef support::detail::packed_endian_specific_integral
+ <uint32_t, target_endianness, support::aligned> Elf_Word;
+ typedef support::detail::packed_endian_specific_integral
+ <int32_t, target_endianness, support::aligned> Elf_Sword;
+ typedef support::detail::packed_endian_specific_integral
+ <uint64_t, target_endianness, support::aligned> Elf_Xword;
+ typedef support::detail::packed_endian_specific_integral
+ <int64_t, target_endianness, support::aligned> Elf_Sxword;
+};
+
+template<support::endianness target_endianness, bool is64Bits>
+struct ELFDataTypeTypedefHelper;
+
+/// ELF 32bit types.
+template<support::endianness target_endianness>
+struct ELFDataTypeTypedefHelper<target_endianness, false>
+ : ELFDataTypeTypedefHelperCommon<target_endianness> {
+ typedef uint32_t value_type;
+ typedef support::detail::packed_endian_specific_integral
+ <value_type, target_endianness, support::aligned> Elf_Addr;
+ typedef support::detail::packed_endian_specific_integral
+ <value_type, target_endianness, support::aligned> Elf_Off;
+};
+
+/// ELF 64bit types.
+template<support::endianness target_endianness>
+struct ELFDataTypeTypedefHelper<target_endianness, true>
+ : ELFDataTypeTypedefHelperCommon<target_endianness>{
+ typedef uint64_t value_type;
+ typedef support::detail::packed_endian_specific_integral
+ <value_type, target_endianness, support::aligned> Elf_Addr;
+ typedef support::detail::packed_endian_specific_integral
+ <value_type, target_endianness, support::aligned> Elf_Off;
+};
+
+// I really don't like doing this, but the alternative is copypasta.
+#define LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits) \
+typedef typename \
+ ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Addr Elf_Addr; \
+typedef typename \
+ ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Off Elf_Off; \
+typedef typename \
+ ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Half Elf_Half; \
+typedef typename \
+ ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Word Elf_Word; \
+typedef typename \
+ ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sword Elf_Sword; \
+typedef typename \
+ ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Xword Elf_Xword; \
+typedef typename \
+ ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sxword Elf_Sxword;
+
+ // Section header.
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Shdr_Base;
+
+template<support::endianness target_endianness>
+struct Elf_Shdr_Base<target_endianness, false> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, false)
+ Elf_Word sh_name; // Section name (index into string table)
+ Elf_Word sh_type; // Section type (SHT_*)
+ Elf_Word sh_flags; // Section flags (SHF_*)
+ Elf_Addr sh_addr; // Address where section is to be loaded
+ Elf_Off sh_offset; // File offset of section data, in bytes
+ Elf_Word sh_size; // Size of section, in bytes
+ Elf_Word sh_link; // Section type-specific header table index link
+ Elf_Word sh_info; // Section type-specific extra information
+ Elf_Word sh_addralign;// Section address alignment
+ Elf_Word sh_entsize; // Size of records contained within the section
+};
+
+template<support::endianness target_endianness>
+struct Elf_Shdr_Base<target_endianness, true> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, true)
+ Elf_Word sh_name; // Section name (index into string table)
+ Elf_Word sh_type; // Section type (SHT_*)
+ Elf_Xword sh_flags; // Section flags (SHF_*)
+ Elf_Addr sh_addr; // Address where section is to be loaded
+ Elf_Off sh_offset; // File offset of section data, in bytes
+ Elf_Xword sh_size; // Size of section, in bytes
+ Elf_Word sh_link; // Section type-specific header table index link
+ Elf_Word sh_info; // Section type-specific extra information
+ Elf_Xword sh_addralign;// Section address alignment
+ Elf_Xword sh_entsize; // Size of records contained within the section
+};
+
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Shdr_Impl : Elf_Shdr_Base<target_endianness, is64Bits> {
+ using Elf_Shdr_Base<target_endianness, is64Bits>::sh_entsize;
+ using Elf_Shdr_Base<target_endianness, is64Bits>::sh_size;
+
+ /// @brief Get the number of entities this section contains if it has any.
+ unsigned getEntityCount() const {
+ if (sh_entsize == 0)
+ return 0;
+ return sh_size / sh_entsize;
+ }
+};
+
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Sym_Base;
+
+template<support::endianness target_endianness>
+struct Elf_Sym_Base<target_endianness, false> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, false)
+ Elf_Word st_name; // Symbol name (index into string table)
+ Elf_Addr st_value; // Value or address associated with the symbol
+ Elf_Word st_size; // Size of the symbol
+ unsigned char st_info; // Symbol's type and binding attributes
+ unsigned char st_other; // Must be zero; reserved
+ Elf_Half st_shndx; // Which section (header table index) it's defined in
+};
+
+template<support::endianness target_endianness>
+struct Elf_Sym_Base<target_endianness, true> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, true)
+ Elf_Word st_name; // Symbol name (index into string table)
+ unsigned char st_info; // Symbol's type and binding attributes
+ unsigned char st_other; // Must be zero; reserved
+ Elf_Half st_shndx; // Which section (header table index) it's defined in
+ Elf_Addr st_value; // Value or address associated with the symbol
+ Elf_Xword st_size; // Size of the symbol
+};
+
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Sym_Impl : Elf_Sym_Base<target_endianness, is64Bits> {
+ using Elf_Sym_Base<target_endianness, is64Bits>::st_info;
+
+ // These accessors and mutators correspond to the ELF32_ST_BIND,
+ // ELF32_ST_TYPE, and ELF32_ST_INFO macros defined in the ELF specification:
+ unsigned char getBinding() const { return st_info >> 4; }
+ unsigned char getType() const { return st_info & 0x0f; }
+ void setBinding(unsigned char b) { setBindingAndType(b, getType()); }
+ void setType(unsigned char t) { setBindingAndType(getBinding(), t); }
+ void setBindingAndType(unsigned char b, unsigned char t) {
+ st_info = (b << 4) + (t & 0x0f);
+ }
+};
+
+/// Elf_Versym: This is the structure of entries in the SHT_GNU_versym section
+/// (.gnu.version). This structure is identical for ELF32 and ELF64.
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Versym_Impl {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
+ Elf_Half vs_index; // Version index with flags (e.g. VERSYM_HIDDEN)
+};
+
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Verdaux_Impl;
+
+/// Elf_Verdef: This is the structure of entries in the SHT_GNU_verdef section
+/// (.gnu.version_d). This structure is identical for ELF32 and ELF64.
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Verdef_Impl {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
+ typedef Elf_Verdaux_Impl<target_endianness, is64Bits> Elf_Verdaux;
+ Elf_Half vd_version; // Version of this structure (e.g. VER_DEF_CURRENT)
+ Elf_Half vd_flags; // Bitwise flags (VER_DEF_*)
+ Elf_Half vd_ndx; // Version index, used in .gnu.version entries
+ Elf_Half vd_cnt; // Number of Verdaux entries
+ Elf_Word vd_hash; // Hash of name
+ Elf_Word vd_aux; // Offset to the first Verdaux entry (in bytes)
+ Elf_Word vd_next; // Offset to the next Verdef entry (in bytes)
+
+ /// Get the first Verdaux entry for this Verdef.
+ const Elf_Verdaux *getAux() const {
+ return reinterpret_cast<const Elf_Verdaux*>((const char*)this + vd_aux);
+ }
+};
+
+/// Elf_Verdaux: This is the structure of auxiliary data in the SHT_GNU_verdef
+/// section (.gnu.version_d). This structure is identical for ELF32 and ELF64.
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Verdaux_Impl {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
+ Elf_Word vda_name; // Version name (offset in string table)
+ Elf_Word vda_next; // Offset to next Verdaux entry (in bytes)
+};
+
+/// Elf_Verneed: This is the structure of entries in the SHT_GNU_verneed
+/// section (.gnu.version_r). This structure is identical for ELF32 and ELF64.
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Verneed_Impl {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
+ Elf_Half vn_version; // Version of this structure (e.g. VER_NEED_CURRENT)
+ Elf_Half vn_cnt; // Number of associated Vernaux entries
+ Elf_Word vn_file; // Library name (string table offset)
+ Elf_Word vn_aux; // Offset to first Vernaux entry (in bytes)
+ Elf_Word vn_next; // Offset to next Verneed entry (in bytes)
+};
+
+/// Elf_Vernaux: This is the structure of auxiliary data in SHT_GNU_verneed
+/// section (.gnu.version_r). This structure is identical for ELF32 and ELF64.
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Vernaux_Impl {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
+ Elf_Word vna_hash; // Hash of dependency name
+ Elf_Half vna_flags; // Bitwise Flags (VER_FLAG_*)
+ Elf_Half vna_other; // Version index, used in .gnu.version entries
+ Elf_Word vna_name; // Dependency name
+ Elf_Word vna_next; // Offset to next Vernaux entry (in bytes)
+};
+
+/// Elf_Dyn_Base: This structure matches the form of entries in the dynamic
+/// table section (.dynamic) look like.
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Dyn_Base;
+
+template<support::endianness target_endianness>
+struct Elf_Dyn_Base<target_endianness, false> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, false)
+ Elf_Sword d_tag;
+ union {
+ Elf_Word d_val;
+ Elf_Addr d_ptr;
+ } d_un;
+};
+
+template<support::endianness target_endianness>
+struct Elf_Dyn_Base<target_endianness, true> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, true)
+ Elf_Sxword d_tag;
+ union {
+ Elf_Xword d_val;
+ Elf_Addr d_ptr;
+ } d_un;
+};
+
+/// Elf_Dyn_Impl: This inherits from Elf_Dyn_Base, adding getters and setters.
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Dyn_Impl : Elf_Dyn_Base<target_endianness, is64Bits> {
+ using Elf_Dyn_Base<target_endianness, is64Bits>::d_tag;
+ using Elf_Dyn_Base<target_endianness, is64Bits>::d_un;
+ int64_t getTag() const { return d_tag; }
+ uint64_t getVal() const { return d_un.d_val; }
+ uint64_t getPtr() const { return d_un.ptr; }
+};
+
+template<support::endianness target_endianness, bool is64Bits>
+class ELFObjectFile;
+
+// DynRefImpl: Reference to an entry in the dynamic table
+// This is an ELF-specific interface.
+template<support::endianness target_endianness, bool is64Bits>
+class DynRefImpl {
+ typedef Elf_Dyn_Impl<target_endianness, is64Bits> Elf_Dyn;
+ typedef ELFObjectFile<target_endianness, is64Bits> OwningType;
+
+ DataRefImpl DynPimpl;
+ const OwningType *OwningObject;
+
+public:
+ DynRefImpl() : OwningObject(NULL) { }
+
+ DynRefImpl(DataRefImpl DynP, const OwningType *Owner);
+
+ bool operator==(const DynRefImpl &Other) const;
+ bool operator <(const DynRefImpl &Other) const;
+
+ error_code getNext(DynRefImpl &Result) const;
+ int64_t getTag() const;
+ uint64_t getVal() const;
+ uint64_t getPtr() const;
+
+ DataRefImpl getRawDataRefImpl() const;
+};
+
+// Elf_Rel: Elf Relocation
+template<support::endianness target_endianness, bool is64Bits, bool isRela>
+struct Elf_Rel_Base;
+
+template<support::endianness target_endianness>
+struct Elf_Rel_Base<target_endianness, false, false> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, false)
+ Elf_Addr r_offset; // Location (file byte offset, or program virtual addr)
+ Elf_Word r_info; // Symbol table index and type of relocation to apply
+};
+
+template<support::endianness target_endianness>
+struct Elf_Rel_Base<target_endianness, true, false> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, true)
+ Elf_Addr r_offset; // Location (file byte offset, or program virtual addr)
+ Elf_Xword r_info; // Symbol table index and type of relocation to apply
+};
+
+template<support::endianness target_endianness>
+struct Elf_Rel_Base<target_endianness, false, true> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, false)
+ Elf_Addr r_offset; // Location (file byte offset, or program virtual addr)
+ Elf_Word r_info; // Symbol table index and type of relocation to apply
+ Elf_Sword r_addend; // Compute value for relocatable field by adding this
+};
+
+template<support::endianness target_endianness>
+struct Elf_Rel_Base<target_endianness, true, true> {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, true)
+ Elf_Addr r_offset; // Location (file byte offset, or program virtual addr)
+ Elf_Xword r_info; // Symbol table index and type of relocation to apply
+ Elf_Sxword r_addend; // Compute value for relocatable field by adding this.
+};
+
+template<support::endianness target_endianness, bool is64Bits, bool isRela>
+struct Elf_Rel_Impl;
+
+template<support::endianness target_endianness, bool isRela>
+struct Elf_Rel_Impl<target_endianness, true, isRela>
+ : Elf_Rel_Base<target_endianness, true, isRela> {
+ using Elf_Rel_Base<target_endianness, true, isRela>::r_info;
+ LLVM_ELF_IMPORT_TYPES(target_endianness, true)
+
+ // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE,
+ // and ELF64_R_INFO macros defined in the ELF specification:
+ uint64_t getSymbol() const { return (r_info >> 32); }
+ unsigned char getType() const {
+ return (unsigned char) (r_info & 0xffffffffL);
+ }
+ void setSymbol(uint64_t s) { setSymbolAndType(s, getType()); }
+ void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
+ void setSymbolAndType(uint64_t s, unsigned char t) {
+ r_info = (s << 32) + (t&0xffffffffL);
+ }
+};
+
+template<support::endianness target_endianness, bool isRela>
+struct Elf_Rel_Impl<target_endianness, false, isRela>
+ : Elf_Rel_Base<target_endianness, false, isRela> {
+ using Elf_Rel_Base<target_endianness, false, isRela>::r_info;
+ LLVM_ELF_IMPORT_TYPES(target_endianness, false)
+
+ // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE,
+ // and ELF32_R_INFO macros defined in the ELF specification:
+ uint32_t getSymbol() const { return (r_info >> 8); }
+ unsigned char getType() const { return (unsigned char) (r_info & 0x0ff); }
+ void setSymbol(uint32_t s) { setSymbolAndType(s, getType()); }
+ void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
+ void setSymbolAndType(uint32_t s, unsigned char t) {
+ r_info = (s << 8) + t;
+ }
+};
+
+template<support::endianness target_endianness, bool is64Bits>
+struct Elf_Ehdr_Impl {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
+ unsigned char e_ident[ELF::EI_NIDENT]; // ELF Identification bytes
+ Elf_Half e_type; // Type of file (see ET_*)
+ Elf_Half e_machine; // Required architecture for this file (see EM_*)
+ Elf_Word e_version; // Must be equal to 1
+ Elf_Addr e_entry; // Address to jump to in order to start program
+ Elf_Off e_phoff; // Program header table's file offset, in bytes
+ Elf_Off e_shoff; // Section header table's file offset, in bytes
+ Elf_Word e_flags; // Processor-specific flags
+ Elf_Half e_ehsize; // Size of ELF header, in bytes
+ Elf_Half e_phentsize;// Size of an entry in the program header table
+ Elf_Half e_phnum; // Number of entries in the program header table
+ Elf_Half e_shentsize;// Size of an entry in the section header table
+ Elf_Half e_shnum; // Number of entries in the section header table
+ Elf_Half e_shstrndx; // Section header table index of section name
+ // string table
+ bool checkMagic() const {
+ return (memcmp(e_ident, ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
+ }
+ unsigned char getFileClass() const { return e_ident[ELF::EI_CLASS]; }
+ unsigned char getDataEncoding() const { return e_ident[ELF::EI_DATA]; }
+};
+
+template<support::endianness target_endianness, bool is64Bits>
+class ELFObjectFile : public ObjectFile {
+ LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
+
+ typedef Elf_Ehdr_Impl<target_endianness, is64Bits> Elf_Ehdr;
+ typedef Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
+ typedef Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
+ typedef Elf_Dyn_Impl<target_endianness, is64Bits> Elf_Dyn;
+ typedef Elf_Rel_Impl<target_endianness, is64Bits, false> Elf_Rel;
+ typedef Elf_Rel_Impl<target_endianness, is64Bits, true> Elf_Rela;
+ typedef Elf_Verdef_Impl<target_endianness, is64Bits> Elf_Verdef;
+ typedef Elf_Verdaux_Impl<target_endianness, is64Bits> Elf_Verdaux;
+ typedef Elf_Verneed_Impl<target_endianness, is64Bits> Elf_Verneed;
+ typedef Elf_Vernaux_Impl<target_endianness, is64Bits> Elf_Vernaux;
+ typedef Elf_Versym_Impl<target_endianness, is64Bits> Elf_Versym;
+ typedef DynRefImpl<target_endianness, is64Bits> DynRef;
+ typedef content_iterator<DynRef> dyn_iterator;
+
+protected:
+ // This flag is used for classof, to distinguish ELFObjectFile from
+ // its subclass. If more subclasses will be created, this flag will
+ // have to become an enum.
+ bool isDyldELFObject;
+
+private:
+ typedef SmallVector<const Elf_Shdr*, 1> Sections_t;
+ typedef DenseMap<unsigned, unsigned> IndexMap_t;
+ typedef DenseMap<const Elf_Shdr*, SmallVector<uint32_t, 1> > RelocMap_t;
+
+ const Elf_Ehdr *Header;
+ const Elf_Shdr *SectionHeaderTable;
+ const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
+ const Elf_Shdr *dot_strtab_sec; // Symbol header string table.
+ const Elf_Shdr *dot_dynstr_sec; // Dynamic symbol string table.
+
+ // SymbolTableSections[0] always points to the dynamic string table section
+ // header, or NULL if there is no dynamic string table.
+ Sections_t SymbolTableSections;
+ IndexMap_t SymbolTableSectionsIndexMap;
+ DenseMap<const Elf_Sym*, ELF::Elf64_Word> ExtendedSymbolTable;
+
+ const Elf_Shdr *dot_dynamic_sec; // .dynamic
+ const Elf_Shdr *dot_gnu_version_sec; // .gnu.version
+ const Elf_Shdr *dot_gnu_version_r_sec; // .gnu.version_r
+ const Elf_Shdr *dot_gnu_version_d_sec; // .gnu.version_d
+
+ // Pointer to SONAME entry in dynamic string table
+ // This is set the first time getLoadName is called.
+ mutable const char *dt_soname;
+
+public:
+ /// \brief Iterate over relocations in a .rel or .rela section.
+ template<class RelocT>
+ class ELFRelocationIterator {
+ public:
+ typedef void difference_type;
+ typedef const RelocT value_type;
+ typedef std::forward_iterator_tag iterator_category;
+ typedef value_type &reference;
+ typedef value_type *pointer;
+
+ /// \brief Default construct iterator.
+ ELFRelocationIterator() : Section(0), Current(0) {}
+ ELFRelocationIterator(const Elf_Shdr *Sec, const char *Start)
+ : Section(Sec)
+ , Current(Start) {}
+
+ reference operator *() {
+ assert(Current && "Attempted to dereference an invalid iterator!");
+ return *reinterpret_cast<const RelocT*>(Current);
+ }
+
+ pointer operator ->() {
+ assert(Current && "Attempted to dereference an invalid iterator!");
+ return reinterpret_cast<const RelocT*>(Current);
+ }
+
+ bool operator ==(const ELFRelocationIterator &Other) {
+ return Section == Other.Section && Current == Other.Current;
+ }
+
+ bool operator !=(const ELFRelocationIterator &Other) {
+ return !(*this == Other);
+ }
+
+ ELFRelocationIterator &operator ++(int) {
+ assert(Current && "Attempted to increment an invalid iterator!");
+ Current += Section->sh_entsize;
+ return *this;
+ }
+
+ ELFRelocationIterator operator ++() {
+ ELFRelocationIterator Tmp = *this;
+ ++*this;
+ return Tmp;
+ }
+
+ private:
+ const Elf_Shdr *Section;
+ const char *Current;
+ };
+
+private:
+ // Records for each version index the corresponding Verdef or Vernaux entry.
+ // This is filled the first time LoadVersionMap() is called.
+ class VersionMapEntry : public PointerIntPair<const void*, 1> {
+ public:
+ // If the integer is 0, this is an Elf_Verdef*.
+ // If the integer is 1, this is an Elf_Vernaux*.
+ VersionMapEntry() : PointerIntPair<const void*, 1>(NULL, 0) { }
+ VersionMapEntry(const Elf_Verdef *verdef)
+ : PointerIntPair<const void*, 1>(verdef, 0) { }
+ VersionMapEntry(const Elf_Vernaux *vernaux)
+ : PointerIntPair<const void*, 1>(vernaux, 1) { }
+ bool isNull() const { return getPointer() == NULL; }
+ bool isVerdef() const { return !isNull() && getInt() == 0; }
+ bool isVernaux() const { return !isNull() && getInt() == 1; }
+ const Elf_Verdef *getVerdef() const {
+ return isVerdef() ? (const Elf_Verdef*)getPointer() : NULL;
+ }
+ const Elf_Vernaux *getVernaux() const {
+ return isVernaux() ? (const Elf_Vernaux*)getPointer() : NULL;
+ }
+ };
+ mutable SmallVector<VersionMapEntry, 16> VersionMap;
+ void LoadVersionDefs(const Elf_Shdr *sec) const;
+ void LoadVersionNeeds(const Elf_Shdr *ec) const;
+ void LoadVersionMap() const;
+
+ /// @brief Map sections to an array of relocation sections that reference
+ /// them sorted by section index.
+ RelocMap_t SectionRelocMap;
+
+ /// @brief Get the relocation section that contains \a Rel.
+ const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
+ return getSection(Rel.w.b);
+ }
+
+ bool isRelocationHasAddend(DataRefImpl Rel) const;
+ template<typename T>
+ const T *getEntry(uint16_t Section, uint32_t Entry) const;
+ template<typename T>
+ const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
+ const Elf_Shdr *getSection(DataRefImpl index) const;
+ const Elf_Shdr *getSection(uint32_t index) const;
+ const Elf_Rel *getRel(DataRefImpl Rel) const;
+ const Elf_Rela *getRela(DataRefImpl Rela) const;
+ const char *getString(uint32_t section, uint32_t offset) const;
+ const char *getString(const Elf_Shdr *section, uint32_t offset) const;
+ error_code getSymbolVersion(const Elf_Shdr *section,
+ const Elf_Sym *Symb,
+ StringRef &Version,
+ bool &IsDefault) const;
+ void VerifyStrTab(const Elf_Shdr *sh) const;
+
+protected:
+ const Elf_Sym *getSymbol(DataRefImpl Symb) const; // FIXME: Should be private?
+ void validateSymbol(DataRefImpl Symb) const;
+
+public:
+ error_code getSymbolName(const Elf_Shdr *section,
+ const Elf_Sym *Symb,
+ StringRef &Res) const;
+ error_code getSectionName(const Elf_Shdr *section,
+ StringRef &Res) const;
+ const Elf_Dyn *getDyn(DataRefImpl DynData) const;
+ error_code getSymbolVersion(SymbolRef Symb, StringRef &Version,
+ bool &IsDefault) const;
+protected:
+ virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
+ virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
+ virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
+ virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
+ virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res) const;
+ virtual error_code getSymbolSection(DataRefImpl Symb,
+ section_iterator &Res) const;
+
+ friend class DynRefImpl<target_endianness, is64Bits>;
+ virtual error_code getDynNext(DataRefImpl DynData, DynRef &Result) const;
+
+ virtual error_code getLibraryNext(DataRefImpl Data, LibraryRef &Result) const;
+ virtual error_code getLibraryPath(DataRefImpl Data, StringRef &Res) const;
+
+ virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
+ virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
+ virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
+ virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
+ bool &Res) const;
+ virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const;
+ virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
+ bool &Result) const;
+ virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
+ virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
+
+ virtual error_code getRelocationNext(DataRefImpl Rel,
+ RelocationRef &Res) const;
+ virtual error_code getRelocationAddress(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationOffset(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationSymbol(DataRefImpl Rel,
+ SymbolRef &Res) const;
+ virtual error_code getRelocationType(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationTypeName(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const;
+ virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
+ int64_t &Res) const;
+ virtual error_code getRelocationValueString(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const;
+
+public:
+ ELFObjectFile(MemoryBuffer *Object, error_code &ec);
+ virtual symbol_iterator begin_symbols() const;
+ virtual symbol_iterator end_symbols() const;
+
+ virtual symbol_iterator begin_dynamic_symbols() const;
+ virtual symbol_iterator end_dynamic_symbols() const;
+
+ virtual section_iterator begin_sections() const;
+ virtual section_iterator end_sections() const;
+
+ virtual library_iterator begin_libraries_needed() const;
+ virtual library_iterator end_libraries_needed() const;
+
+ virtual dyn_iterator begin_dynamic_table() const;
+ virtual dyn_iterator end_dynamic_table() const;
+
+ typedef ELFRelocationIterator<Elf_Rela> Elf_Rela_Iter;
+ typedef ELFRelocationIterator<Elf_Rel> Elf_Rel_Iter;
+
+ virtual Elf_Rela_Iter beginELFRela(const Elf_Shdr *sec) const {
+ return Elf_Rela_Iter(sec, (const char *)(base() + sec->sh_offset));
+ }
+
+ virtual Elf_Rela_Iter endELFRela(const Elf_Shdr *sec) const {
+ return Elf_Rela_Iter(sec, (const char *)
+ (base() + sec->sh_offset + sec->sh_size));
+ }
+
+ virtual Elf_Rel_Iter beginELFRel(const Elf_Shdr *sec) const {
+ return Elf_Rel_Iter(sec, (const char *)(base() + sec->sh_offset));
+ }
+
+ virtual Elf_Rel_Iter endELFRel(const Elf_Shdr *sec) const {
+ return Elf_Rel_Iter(sec, (const char *)
+ (base() + sec->sh_offset + sec->sh_size));
+ }
+
+ virtual uint8_t getBytesInAddress() const;
+ virtual StringRef getFileFormatName() const;
+ virtual StringRef getObjectType() const { return "ELF"; }
+ virtual unsigned getArch() const;
+ virtual StringRef getLoadName() const;
+ virtual error_code getSectionContents(const Elf_Shdr *sec,
+ StringRef &Res) const;
+
+ uint64_t getNumSections() const;
+ uint64_t getStringTableIndex() const;
+ ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
+ const Elf_Shdr *getSection(const Elf_Sym *symb) const;
+ const Elf_Shdr *getElfSection(section_iterator &It) const;
+ const Elf_Sym *getElfSymbol(symbol_iterator &It) const;
+ const Elf_Sym *getElfSymbol(uint32_t index) const;
+
+ // Methods for type inquiry through isa, cast, and dyn_cast
+ bool isDyldType() const { return isDyldELFObject; }
+ static inline bool classof(const Binary *v) {
+ return v->getType() == getELFType(target_endianness == support::little,
+ is64Bits);
+ }
+ static inline bool classof(const ELFObjectFile *v) { return true; }
+};
+
+// Iterate through the version definitions, and place each Elf_Verdef
+// in the VersionMap according to its index.
+template<support::endianness target_endianness, bool is64Bits>
+void ELFObjectFile<target_endianness, is64Bits>::
+ LoadVersionDefs(const Elf_Shdr *sec) const {
+ unsigned vd_size = sec->sh_size; // Size of section in bytes
+ unsigned vd_count = sec->sh_info; // Number of Verdef entries
+ const char *sec_start = (const char*)base() + sec->sh_offset;
+ const char *sec_end = sec_start + vd_size;
+ // The first Verdef entry is at the start of the section.
+ const char *p = sec_start;
+ for (unsigned i = 0; i < vd_count; i++) {
+ if (p + sizeof(Elf_Verdef) > sec_end)
+ report_fatal_error("Section ended unexpectedly while scanning "
+ "version definitions.");
+ const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
+ if (vd->vd_version != ELF::VER_DEF_CURRENT)
+ report_fatal_error("Unexpected verdef version");
+ size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
+ if (index >= VersionMap.size())
+ VersionMap.resize(index+1);
+ VersionMap[index] = VersionMapEntry(vd);
+ p += vd->vd_next;
+ }
+}
+
+// Iterate through the versions needed section, and place each Elf_Vernaux
+// in the VersionMap according to its index.
+template<support::endianness target_endianness, bool is64Bits>
+void ELFObjectFile<target_endianness, is64Bits>::
+ LoadVersionNeeds(const Elf_Shdr *sec) const {
+ unsigned vn_size = sec->sh_size; // Size of section in bytes
+ unsigned vn_count = sec->sh_info; // Number of Verneed entries
+ const char *sec_start = (const char*)base() + sec->sh_offset;
+ const char *sec_end = sec_start + vn_size;
+ // The first Verneed entry is at the start of the section.
+ const char *p = sec_start;
+ for (unsigned i = 0; i < vn_count; i++) {
+ if (p + sizeof(Elf_Verneed) > sec_end)
+ report_fatal_error("Section ended unexpectedly while scanning "
+ "version needed records.");
+ const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
+ if (vn->vn_version != ELF::VER_NEED_CURRENT)
+ report_fatal_error("Unexpected verneed version");
+ // Iterate through the Vernaux entries
+ const char *paux = p + vn->vn_aux;
+ for (unsigned j = 0; j < vn->vn_cnt; j++) {
+ if (paux + sizeof(Elf_Vernaux) > sec_end)
+ report_fatal_error("Section ended unexpected while scanning auxiliary "
+ "version needed records.");
+ const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
+ size_t index = vna->vna_other & ELF::VERSYM_VERSION;
+ if (index >= VersionMap.size())
+ VersionMap.resize(index+1);
+ VersionMap[index] = VersionMapEntry(vna);
+ paux += vna->vna_next;
+ }
+ p += vn->vn_next;
+ }
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+void ELFObjectFile<target_endianness, is64Bits>::LoadVersionMap() const {
+ // If there is no dynamic symtab or version table, there is nothing to do.
+ if (SymbolTableSections[0] == NULL || dot_gnu_version_sec == NULL)
+ return;
+
+ // Has the VersionMap already been loaded?
+ if (VersionMap.size() > 0)
+ return;
+
+ // The first two version indexes are reserved.
+ // Index 0 is LOCAL, index 1 is GLOBAL.
+ VersionMap.push_back(VersionMapEntry());
+ VersionMap.push_back(VersionMapEntry());
+
+ if (dot_gnu_version_d_sec)
+ LoadVersionDefs(dot_gnu_version_d_sec);
+
+ if (dot_gnu_version_r_sec)
+ LoadVersionNeeds(dot_gnu_version_r_sec);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+void ELFObjectFile<target_endianness, is64Bits>
+ ::validateSymbol(DataRefImpl Symb) const {
+ const Elf_Sym *symb = getSymbol(Symb);
+ const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
+ // FIXME: We really need to do proper error handling in the case of an invalid
+ // input file. Because we don't use exceptions, I think we'll just pass
+ // an error object around.
+ if (!( symb
+ && SymbolTableSection
+ && symb >= (const Elf_Sym*)(base()
+ + SymbolTableSection->sh_offset)
+ && symb < (const Elf_Sym*)(base()
+ + SymbolTableSection->sh_offset
+ + SymbolTableSection->sh_size)))
+ // FIXME: Proper error handling.
+ report_fatal_error("Symb must point to a valid symbol!");
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolNext(DataRefImpl Symb,
+ SymbolRef &Result) const {
+ validateSymbol(Symb);
+ const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
+
+ ++Symb.d.a;
+ // Check to see if we are at the end of this symbol table.
+ if (Symb.d.a >= SymbolTableSection->getEntityCount()) {
+ // We are at the end. If there are other symbol tables, jump to them.
+ // If the symbol table is .dynsym, we are iterating dynamic symbols,
+ // and there is only one table of these.
+ if (Symb.d.b != 0) {
+ ++Symb.d.b;
+ Symb.d.a = 1; // The 0th symbol in ELF is fake.
+ }
+ // Otherwise return the terminator.
+ if (Symb.d.b == 0 || Symb.d.b >= SymbolTableSections.size()) {
+ Symb.d.a = std::numeric_limits<uint32_t>::max();
+ Symb.d.b = std::numeric_limits<uint32_t>::max();
+ }
+ }
+
+ Result = SymbolRef(Symb, this);
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolName(DataRefImpl Symb,
+ StringRef &Result) const {
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+ return getSymbolName(SymbolTableSections[Symb.d.b], symb, Result);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolVersion(SymbolRef SymRef,
+ StringRef &Version,
+ bool &IsDefault) const {
+ DataRefImpl Symb = SymRef.getRawDataRefImpl();
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+ return getSymbolVersion(SymbolTableSections[Symb.d.b], symb,
+ Version, IsDefault);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+ELF::Elf64_Word ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolTableIndex(const Elf_Sym *symb) const {
+ if (symb->st_shndx == ELF::SHN_XINDEX)
+ return ExtendedSymbolTable.lookup(symb);
+ return symb->st_shndx;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
+ELFObjectFile<target_endianness, is64Bits>
+ ::getSection(const Elf_Sym *symb) const {
+ if (symb->st_shndx == ELF::SHN_XINDEX)
+ return getSection(ExtendedSymbolTable.lookup(symb));
+ if (symb->st_shndx >= ELF::SHN_LORESERVE)
+ return 0;
+ return getSection(symb->st_shndx);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
+ELFObjectFile<target_endianness, is64Bits>
+ ::getElfSection(section_iterator &It) const {
+ llvm::object::DataRefImpl ShdrRef = It->getRawDataRefImpl();
+ return reinterpret_cast<const Elf_Shdr *>(ShdrRef.p);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
+ELFObjectFile<target_endianness, is64Bits>
+ ::getElfSymbol(symbol_iterator &It) const {
+ return getSymbol(It->getRawDataRefImpl());
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
+ELFObjectFile<target_endianness, is64Bits>
+ ::getElfSymbol(uint32_t index) const {
+ DataRefImpl SymbolData;
+ SymbolData.d.a = index;
+ SymbolData.d.b = 1;
+ return getSymbol(SymbolData);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolFileOffset(DataRefImpl Symb,
+ uint64_t &Result) const {
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+ const Elf_Shdr *Section;
+ switch (getSymbolTableIndex(symb)) {
+ case ELF::SHN_COMMON:
+ // Unintialized symbols have no offset in the object file
+ case ELF::SHN_UNDEF:
+ Result = UnknownAddressOrSize;
+ return object_error::success;
+ case ELF::SHN_ABS:
+ Result = symb->st_value;
+ return object_error::success;
+ default: Section = getSection(symb);
+ }
+
+ switch (symb->getType()) {
+ case ELF::STT_SECTION:
+ Result = Section ? Section->sh_addr : UnknownAddressOrSize;
+ return object_error::success;
+ case ELF::STT_FUNC:
+ case ELF::STT_OBJECT:
+ case ELF::STT_NOTYPE:
+ Result = symb->st_value +
+ (Section ? Section->sh_offset : 0);
+ return object_error::success;
+ default:
+ Result = UnknownAddressOrSize;
+ return object_error::success;
+ }
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolAddress(DataRefImpl Symb,
+ uint64_t &Result) const {
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+ const Elf_Shdr *Section;
+ switch (getSymbolTableIndex(symb)) {
+ case ELF::SHN_COMMON:
+ case ELF::SHN_UNDEF:
+ Result = UnknownAddressOrSize;
+ return object_error::success;
+ case ELF::SHN_ABS:
+ Result = symb->st_value;
+ return object_error::success;
+ default: Section = getSection(symb);
+ }
+
+ switch (symb->getType()) {
+ case ELF::STT_SECTION:
+ Result = Section ? Section->sh_addr : UnknownAddressOrSize;
+ return object_error::success;
+ case ELF::STT_FUNC:
+ case ELF::STT_OBJECT:
+ case ELF::STT_NOTYPE:
+ Result = symb->st_value + (Section ? Section->sh_addr : 0);
+ return object_error::success;
+ default:
+ Result = UnknownAddressOrSize;
+ return object_error::success;
+ }
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolSize(DataRefImpl Symb,
+ uint64_t &Result) const {
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+ if (symb->st_size == 0)
+ Result = UnknownAddressOrSize;
+ Result = symb->st_size;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolNMTypeChar(DataRefImpl Symb,
+ char &Result) const {
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+ const Elf_Shdr *Section = getSection(symb);
+
+ char ret = '?';
+
+ if (Section) {
+ switch (Section->sh_type) {
+ case ELF::SHT_PROGBITS:
+ case ELF::SHT_DYNAMIC:
+ switch (Section->sh_flags) {
+ case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
+ ret = 't'; break;
+ case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
+ ret = 'd'; break;
+ case ELF::SHF_ALLOC:
+ case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
+ case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
+ ret = 'r'; break;
+ }
+ break;
+ case ELF::SHT_NOBITS: ret = 'b';
+ }
+ }
+
+ switch (getSymbolTableIndex(symb)) {
+ case ELF::SHN_UNDEF:
+ if (ret == '?')
+ ret = 'U';
+ break;
+ case ELF::SHN_ABS: ret = 'a'; break;
+ case ELF::SHN_COMMON: ret = 'c'; break;
+ }
+
+ switch (symb->getBinding()) {
+ case ELF::STB_GLOBAL: ret = ::toupper(ret); break;
+ case ELF::STB_WEAK:
+ if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
+ ret = 'w';
+ else
+ if (symb->getType() == ELF::STT_OBJECT)
+ ret = 'V';
+ else
+ ret = 'W';
+ }
+
+ if (ret == '?' && symb->getType() == ELF::STT_SECTION) {
+ StringRef name;
+ if (error_code ec = getSymbolName(Symb, name))
+ return ec;
+ Result = StringSwitch<char>(name)
+ .StartsWith(".debug", 'N')
+ .StartsWith(".note", 'n')
+ .Default('?');
+ return object_error::success;
+ }
+
+ Result = ret;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolType(DataRefImpl Symb,
+ SymbolRef::Type &Result) const {
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+
+ switch (symb->getType()) {
+ case ELF::STT_NOTYPE:
+ Result = SymbolRef::ST_Unknown;
+ break;
+ case ELF::STT_SECTION:
+ Result = SymbolRef::ST_Debug;
+ break;
+ case ELF::STT_FILE:
+ Result = SymbolRef::ST_File;
+ break;
+ case ELF::STT_FUNC:
+ Result = SymbolRef::ST_Function;
+ break;
+ case ELF::STT_OBJECT:
+ case ELF::STT_COMMON:
+ case ELF::STT_TLS:
+ Result = SymbolRef::ST_Data;
+ break;
+ default:
+ Result = SymbolRef::ST_Other;
+ break;
+ }
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolFlags(DataRefImpl Symb,
+ uint32_t &Result) const {
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+
+ Result = SymbolRef::SF_None;
+
+ if (symb->getBinding() != ELF::STB_LOCAL)
+ Result |= SymbolRef::SF_Global;
+
+ if (symb->getBinding() == ELF::STB_WEAK)
+ Result |= SymbolRef::SF_Weak;
+
+ if (symb->st_shndx == ELF::SHN_ABS)
+ Result |= SymbolRef::SF_Absolute;
+
+ if (symb->getType() == ELF::STT_FILE ||
+ symb->getType() == ELF::STT_SECTION)
+ Result |= SymbolRef::SF_FormatSpecific;
+
+ if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
+ Result |= SymbolRef::SF_Undefined;
+
+ if (symb->getType() == ELF::STT_COMMON ||
+ getSymbolTableIndex(symb) == ELF::SHN_COMMON)
+ Result |= SymbolRef::SF_Common;
+
+ if (symb->getType() == ELF::STT_TLS)
+ Result |= SymbolRef::SF_ThreadLocal;
+
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolSection(DataRefImpl Symb,
+ section_iterator &Res) const {
+ validateSymbol(Symb);
+ const Elf_Sym *symb = getSymbol(Symb);
+ const Elf_Shdr *sec = getSection(symb);
+ if (!sec)
+ Res = end_sections();
+ else {
+ DataRefImpl Sec;
+ Sec.p = reinterpret_cast<intptr_t>(sec);
+ Res = section_iterator(SectionRef(Sec, this));
+ }
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionNext(DataRefImpl Sec, SectionRef &Result) const {
+ const uint8_t *sec = reinterpret_cast<const uint8_t *>(Sec.p);
+ sec += Header->e_shentsize;
+ Sec.p = reinterpret_cast<intptr_t>(sec);
+ Result = SectionRef(Sec, this);
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionName(DataRefImpl Sec,
+ StringRef &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ Result = StringRef(getString(dot_shstrtab_sec, sec->sh_name));
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionAddress(DataRefImpl Sec,
+ uint64_t &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ Result = sec->sh_addr;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionSize(DataRefImpl Sec,
+ uint64_t &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ Result = sec->sh_size;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionContents(DataRefImpl Sec,
+ StringRef &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ const char *start = (const char*)base() + sec->sh_offset;
+ Result = StringRef(start, sec->sh_size);
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionContents(const Elf_Shdr *Sec,
+ StringRef &Result) const {
+ const char *start = (const char*)base() + Sec->sh_offset;
+ Result = StringRef(start, Sec->sh_size);
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionAlignment(DataRefImpl Sec,
+ uint64_t &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ Result = sec->sh_addralign;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::isSectionText(DataRefImpl Sec,
+ bool &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ if (sec->sh_flags & ELF::SHF_EXECINSTR)
+ Result = true;
+ else
+ Result = false;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::isSectionData(DataRefImpl Sec,
+ bool &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
+ && sec->sh_type == ELF::SHT_PROGBITS)
+ Result = true;
+ else
+ Result = false;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::isSectionBSS(DataRefImpl Sec,
+ bool &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
+ && sec->sh_type == ELF::SHT_NOBITS)
+ Result = true;
+ else
+ Result = false;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::isSectionRequiredForExecution(DataRefImpl Sec,
+ bool &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ if (sec->sh_flags & ELF::SHF_ALLOC)
+ Result = true;
+ else
+ Result = false;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::isSectionVirtual(DataRefImpl Sec,
+ bool &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ if (sec->sh_type == ELF::SHT_NOBITS)
+ Result = true;
+ else
+ Result = false;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>::isSectionZeroInit(DataRefImpl Sec,
+ bool &Result) const {
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ // For ELF, all zero-init sections are virtual (that is, they occupy no space
+ // in the object image) and vice versa.
+ if (sec->sh_flags & ELF::SHT_NOBITS)
+ Result = true;
+ else
+ Result = false;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::sectionContainsSymbol(DataRefImpl Sec,
+ DataRefImpl Symb,
+ bool &Result) const {
+ // FIXME: Unimplemented.
+ Result = false;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+relocation_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionRelBegin(DataRefImpl Sec) const {
+ DataRefImpl RelData;
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
+ if (sec != 0 && ittr != SectionRelocMap.end()) {
+ RelData.w.a = getSection(ittr->second[0])->sh_info;
+ RelData.w.b = ittr->second[0];
+ RelData.w.c = 0;
+ }
+ return relocation_iterator(RelocationRef(RelData, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+relocation_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionRelEnd(DataRefImpl Sec) const {
+ DataRefImpl RelData;
+ const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
+ typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
+ if (sec != 0 && ittr != SectionRelocMap.end()) {
+ // Get the index of the last relocation section for this section.
+ std::size_t relocsecindex = ittr->second[ittr->second.size() - 1];
+ const Elf_Shdr *relocsec = getSection(relocsecindex);
+ RelData.w.a = relocsec->sh_info;
+ RelData.w.b = relocsecindex;
+ RelData.w.c = relocsec->sh_size / relocsec->sh_entsize;
+ }
+ return relocation_iterator(RelocationRef(RelData, this));
+}
+
+// Relocations
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getRelocationNext(DataRefImpl Rel,
+ RelocationRef &Result) const {
+ ++Rel.w.c;
+ const Elf_Shdr *relocsec = getSection(Rel.w.b);
+ if (Rel.w.c >= (relocsec->sh_size / relocsec->sh_entsize)) {
+ // We have reached the end of the relocations for this section. See if there
+ // is another relocation section.
+ typename RelocMap_t::mapped_type relocseclist =
+ SectionRelocMap.lookup(getSection(Rel.w.a));
+
+ // Do a binary search for the current reloc section index (which must be
+ // present). Then get the next one.
+ typename RelocMap_t::mapped_type::const_iterator loc =
+ std::lower_bound(relocseclist.begin(), relocseclist.end(), Rel.w.b);
+ ++loc;
+
+ // If there is no next one, don't do anything. The ++Rel.w.c above sets Rel
+ // to the end iterator.
+ if (loc != relocseclist.end()) {
+ Rel.w.b = *loc;
+ Rel.w.a = 0;
+ }
+ }
+ Result = RelocationRef(Rel, this);
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getRelocationSymbol(DataRefImpl Rel,
+ SymbolRef &Result) const {
+ uint32_t symbolIdx;
+ const Elf_Shdr *sec = getSection(Rel.w.b);
+ switch (sec->sh_type) {
+ default :
+ report_fatal_error("Invalid section type in Rel!");
+ case ELF::SHT_REL : {
+ symbolIdx = getRel(Rel)->getSymbol();
+ break;
+ }
+ case ELF::SHT_RELA : {
+ symbolIdx = getRela(Rel)->getSymbol();
+ break;
+ }
+ }
+ DataRefImpl SymbolData;
+ IndexMap_t::const_iterator it = SymbolTableSectionsIndexMap.find(sec->sh_link);
+ if (it == SymbolTableSectionsIndexMap.end())
+ report_fatal_error("Relocation symbol table not found!");
+ SymbolData.d.a = symbolIdx;
+ SymbolData.d.b = it->second;
+ Result = SymbolRef(SymbolData, this);
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getRelocationAddress(DataRefImpl Rel,
+ uint64_t &Result) const {
+ uint64_t offset;
+ const Elf_Shdr *sec = getSection(Rel.w.b);
+ switch (sec->sh_type) {
+ default :
+ report_fatal_error("Invalid section type in Rel!");
+ case ELF::SHT_REL : {
+ offset = getRel(Rel)->r_offset;
+ break;
+ }
+ case ELF::SHT_RELA : {
+ offset = getRela(Rel)->r_offset;
+ break;
+ }
+ }
+
+ Result = offset;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getRelocationOffset(DataRefImpl Rel,
+ uint64_t &Result) const {
+ uint64_t offset;
+ const Elf_Shdr *sec = getSection(Rel.w.b);
+ switch (sec->sh_type) {
+ default :
+ report_fatal_error("Invalid section type in Rel!");
+ case ELF::SHT_REL : {
+ offset = getRel(Rel)->r_offset;
+ break;
+ }
+ case ELF::SHT_RELA : {
+ offset = getRela(Rel)->r_offset;
+ break;
+ }
+ }
+
+ Result = offset - sec->sh_addr;
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getRelocationType(DataRefImpl Rel,
+ uint64_t &Result) const {
+ const Elf_Shdr *sec = getSection(Rel.w.b);
+ switch (sec->sh_type) {
+ default :
+ report_fatal_error("Invalid section type in Rel!");
+ case ELF::SHT_REL : {
+ Result = getRel(Rel)->getType();
+ break;
+ }
+ case ELF::SHT_RELA : {
+ Result = getRela(Rel)->getType();
+ break;
+ }
+ }
+ return object_error::success;
+}
+
+#define LLVM_ELF_SWITCH_RELOC_TYPE_NAME(enum) \
+ case ELF::enum: res = #enum; break;
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getRelocationTypeName(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const {
+ const Elf_Shdr *sec = getSection(Rel.w.b);
+ uint8_t type;
+ StringRef res;
+ switch (sec->sh_type) {
+ default :
+ return object_error::parse_failed;
+ case ELF::SHT_REL : {
+ type = getRel(Rel)->getType();
+ break;
+ }
+ case ELF::SHT_RELA : {
+ type = getRela(Rel)->getType();
+ break;
+ }
+ }
+ switch (Header->e_machine) {
+ case ELF::EM_X86_64:
+ switch (type) {
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_NONE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_64);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOT32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PLT32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_COPY);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GLOB_DAT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_JUMP_SLOT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_RELATIVE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32S);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPMOD64);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF64);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF64);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSGD);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSLD);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTTPOFF);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC64);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTOFF64);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE64);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32_TLSDESC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC_CALL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC);
+ default:
+ res = "Unknown";
+ }
+ break;
+ case ELF::EM_386:
+ switch (type) {
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_NONE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOT32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PLT32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_COPY);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GLOB_DAT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_JUMP_SLOT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_RELATIVE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTOFF);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTPC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32PLT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTIE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_PUSH);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_CALL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_POP);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_PUSH);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_CALL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_POP);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDO_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPMOD32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPOFF32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTDESC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC_CALL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_IRELATIVE);
+ default:
+ res = "Unknown";
+ }
+ break;
+ case ELF::EM_ARM:
+ switch (type) {
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_NONE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PC24);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ABS32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_REL32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDR_PC_G0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ABS16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ABS12);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_ABS5);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ABS8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_SBREL32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_CALL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_PC8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_BREL_ADJ);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_DESC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_SWI8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_XPC25);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_XPC22);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_DTPMOD32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_DTPOFF32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_TPOFF32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_COPY);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GLOB_DAT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_JUMP_SLOT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_RELATIVE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GOTOFF32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_BASE_PREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GOT_BREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PLT32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_CALL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_JUMP24);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_JUMP24);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_BASE_ABS);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_PCREL_7_0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_PCREL_15_8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_PCREL_23_15);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDR_SBREL_11_0_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_SBREL_19_12_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_SBREL_27_20_CK);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TARGET1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_SBREL31);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_V4BX);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TARGET2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PREL31);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_MOVW_ABS_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_MOVT_ABS);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_MOVW_PREL_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_MOVT_PREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_MOVW_ABS_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_MOVT_ABS);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_MOVW_PREL_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_MOVT_PREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_JUMP19);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_JUMP6);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_ALU_PREL_11_0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_PC12);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ABS32_NOI);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_REL32_NOI);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_PC_G0_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_PC_G0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_PC_G1_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_PC_G1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_PC_G2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDR_PC_G1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDR_PC_G2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDRS_PC_G0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDRS_PC_G1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDRS_PC_G2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDC_PC_G0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDC_PC_G1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDC_PC_G2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_SB_G0_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_SB_G0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_SB_G1_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_SB_G1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ALU_SB_G2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDR_SB_G0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDR_SB_G1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDR_SB_G2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDRS_SB_G0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDRS_SB_G1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDRS_SB_G2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDC_SB_G0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDC_SB_G1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_LDC_SB_G2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_MOVW_BREL_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_MOVT_BREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_MOVW_BREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_MOVW_BREL_NC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_MOVT_BREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_MOVW_BREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_GOTDESC);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_CALL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_DESCSEQ);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_TLS_CALL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PLT32_ABS);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GOT_ABS);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GOT_PREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GOT_BREL12);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GOTOFF12);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GOTRELAX);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GNU_VTENTRY);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_GNU_VTINHERIT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_JUMP11);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_JUMP8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_GD32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_LDM32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_LDO32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_IE32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_LE32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_LDO12);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_LE12);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_TLS_IE12GP);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_3);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_4);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_5);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_6);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_7);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_9);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_10);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_11);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_12);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_13);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_14);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_PRIVATE_15);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_ME_TOO);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_TLS_DESCSEQ16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_ARM_THM_TLS_DESCSEQ32);
+ default:
+ res = "Unknown";
+ }
+ break;
+ case ELF::EM_HEXAGON:
+ switch (type) {
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_NONE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B22_PCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B15_PCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B7_PCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_LO16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_HI16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_8);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GPREL16_0);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GPREL16_1);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GPREL16_2);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GPREL16_3);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_HL16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B13_PCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B9_PCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B32_PCREL_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_32_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B22_PCREL_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B15_PCREL_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B13_PCREL_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B9_PCREL_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B7_PCREL_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_16_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_12_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_11_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_10_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_9_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_8_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_7_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_32_PCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_COPY);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GLOB_DAT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_JMP_SLOT);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_RELATIVE);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_PLT_B22_PCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_LO16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_HI16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_LO16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_HI16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPMOD_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_LO16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_HI16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_PLT_B22_PCREL);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_LO16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_HI16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_LO16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_HI16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_LO16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_HI16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_LO16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_HI16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_32);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_16);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_6_PCREL_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_32_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_16_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_11_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_32_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_16_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_11_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_32_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_16_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_11_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_32_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_16_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_11_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_32_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_16_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_32_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_16_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_11_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_32_6_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_16_X);
+ LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_11_X);
+ default:
+ res = "Unknown";
+ }
+ break;
+ default:
+ res = "Unknown";
+ }
+ Result.append(res.begin(), res.end());
+ return object_error::success;
+}
+
+#undef LLVM_ELF_SWITCH_RELOC_TYPE_NAME
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getRelocationAdditionalInfo(DataRefImpl Rel,
+ int64_t &Result) const {
+ const Elf_Shdr *sec = getSection(Rel.w.b);
+ switch (sec->sh_type) {
+ default :
+ report_fatal_error("Invalid section type in Rel!");
+ case ELF::SHT_REL : {
+ Result = 0;
+ return object_error::success;
+ }
+ case ELF::SHT_RELA : {
+ Result = getRela(Rel)->r_addend;
+ return object_error::success;
+ }
+ }
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getRelocationValueString(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const {
+ const Elf_Shdr *sec = getSection(Rel.w.b);
+ uint8_t type;
+ StringRef res;
+ int64_t addend = 0;
+ uint16_t symbol_index = 0;
+ switch (sec->sh_type) {
+ default:
+ return object_error::parse_failed;
+ case ELF::SHT_REL: {
+ type = getRel(Rel)->getType();
+ symbol_index = getRel(Rel)->getSymbol();
+ // TODO: Read implicit addend from section data.
+ break;
+ }
+ case ELF::SHT_RELA: {
+ type = getRela(Rel)->getType();
+ symbol_index = getRela(Rel)->getSymbol();
+ addend = getRela(Rel)->r_addend;
+ break;
+ }
+ }
+ const Elf_Sym *symb = getEntry<Elf_Sym>(sec->sh_link, symbol_index);
+ StringRef symname;
+ if (error_code ec = getSymbolName(getSection(sec->sh_link), symb, symname))
+ return ec;
+ switch (Header->e_machine) {
+ case ELF::EM_X86_64:
+ switch (type) {
+ case ELF::R_X86_64_PC8:
+ case ELF::R_X86_64_PC16:
+ case ELF::R_X86_64_PC32: {
+ std::string fmtbuf;
+ raw_string_ostream fmt(fmtbuf);
+ fmt << symname << (addend < 0 ? "" : "+") << addend << "-P";
+ fmt.flush();
+ Result.append(fmtbuf.begin(), fmtbuf.end());
+ }
+ break;
+ case ELF::R_X86_64_8:
+ case ELF::R_X86_64_16:
+ case ELF::R_X86_64_32:
+ case ELF::R_X86_64_32S:
+ case ELF::R_X86_64_64: {
+ std::string fmtbuf;
+ raw_string_ostream fmt(fmtbuf);
+ fmt << symname << (addend < 0 ? "" : "+") << addend;
+ fmt.flush();
+ Result.append(fmtbuf.begin(), fmtbuf.end());
+ }
+ break;
+ default:
+ res = "Unknown";
+ }
+ break;
+ case ELF::EM_ARM:
+ case ELF::EM_HEXAGON:
+ res = symname;
+ break;
+ default:
+ res = "Unknown";
+ }
+ if (Result.empty())
+ Result.append(res.begin(), res.end());
+ return object_error::success;
+}
+
+// Verify that the last byte in the string table in a null.
+template<support::endianness target_endianness, bool is64Bits>
+void ELFObjectFile<target_endianness, is64Bits>
+ ::VerifyStrTab(const Elf_Shdr *sh) const {
+ const char *strtab = (const char*)base() + sh->sh_offset;
+ if (strtab[sh->sh_size - 1] != 0)
+ // FIXME: Proper error handling.
+ report_fatal_error("String table must end with a null terminator!");
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+ELFObjectFile<target_endianness, is64Bits>::ELFObjectFile(MemoryBuffer *Object
+ , error_code &ec)
+ : ObjectFile(getELFType(target_endianness == support::little, is64Bits),
+ Object, ec)
+ , isDyldELFObject(false)
+ , SectionHeaderTable(0)
+ , dot_shstrtab_sec(0)
+ , dot_strtab_sec(0)
+ , dot_dynstr_sec(0)
+ , dot_dynamic_sec(0)
+ , dot_gnu_version_sec(0)
+ , dot_gnu_version_r_sec(0)
+ , dot_gnu_version_d_sec(0)
+ , dt_soname(0)
+ {
+
+ const uint64_t FileSize = Data->getBufferSize();
+
+ if (sizeof(Elf_Ehdr) > FileSize)
+ // FIXME: Proper error handling.
+ report_fatal_error("File too short!");
+
+ Header = reinterpret_cast<const Elf_Ehdr *>(base());
+
+ if (Header->e_shoff == 0)
+ return;
+
+ const uint64_t SectionTableOffset = Header->e_shoff;
+
+ if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
+ // FIXME: Proper error handling.
+ report_fatal_error("Section header table goes past end of file!");
+
+ // The getNumSections() call below depends on SectionHeaderTable being set.
+ SectionHeaderTable =
+ reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
+ const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
+
+ if (SectionTableOffset + SectionTableSize > FileSize)
+ // FIXME: Proper error handling.
+ report_fatal_error("Section table goes past end of file!");
+
+ // To find the symbol tables we walk the section table to find SHT_SYMTAB.
+ const Elf_Shdr* SymbolTableSectionHeaderIndex = 0;
+ const Elf_Shdr* sh = SectionHeaderTable;
+
+ // Reserve SymbolTableSections[0] for .dynsym
+ SymbolTableSections.push_back(NULL);
+
+ for (uint64_t i = 0, e = getNumSections(); i != e; ++i) {
+ switch (sh->sh_type) {
+ case ELF::SHT_SYMTAB_SHNDX: {
+ if (SymbolTableSectionHeaderIndex)
+ // FIXME: Proper error handling.
+ report_fatal_error("More than one .symtab_shndx!");
+ SymbolTableSectionHeaderIndex = sh;
+ break;
+ }
+ case ELF::SHT_SYMTAB: {
+ SymbolTableSectionsIndexMap[i] = SymbolTableSections.size();
+ SymbolTableSections.push_back(sh);
+ break;
+ }
+ case ELF::SHT_DYNSYM: {
+ if (SymbolTableSections[0] != NULL)
+ // FIXME: Proper error handling.
+ report_fatal_error("More than one .dynsym!");
+ SymbolTableSectionsIndexMap[i] = 0;
+ SymbolTableSections[0] = sh;
+ break;
+ }
+ case ELF::SHT_REL:
+ case ELF::SHT_RELA: {
+ SectionRelocMap[getSection(sh->sh_info)].push_back(i);
+ break;
+ }
+ case ELF::SHT_DYNAMIC: {
+ if (dot_dynamic_sec != NULL)
+ // FIXME: Proper error handling.
+ report_fatal_error("More than one .dynamic!");
+ dot_dynamic_sec = sh;
+ break;
+ }
+ case ELF::SHT_GNU_versym: {
+ if (dot_gnu_version_sec != NULL)
+ // FIXME: Proper error handling.
+ report_fatal_error("More than one .gnu.version section!");
+ dot_gnu_version_sec = sh;
+ break;
+ }
+ case ELF::SHT_GNU_verdef: {
+ if (dot_gnu_version_d_sec != NULL)
+ // FIXME: Proper error handling.
+ report_fatal_error("More than one .gnu.version_d section!");
+ dot_gnu_version_d_sec = sh;
+ break;
+ }
+ case ELF::SHT_GNU_verneed: {
+ if (dot_gnu_version_r_sec != NULL)
+ // FIXME: Proper error handling.
+ report_fatal_error("More than one .gnu.version_r section!");
+ dot_gnu_version_r_sec = sh;
+ break;
+ }
+ }
+ ++sh;
+ }
+
+ // Sort section relocation lists by index.
+ for (typename RelocMap_t::iterator i = SectionRelocMap.begin(),
+ e = SectionRelocMap.end(); i != e; ++i) {
+ std::sort(i->second.begin(), i->second.end());
+ }
+
+ // Get string table sections.
+ dot_shstrtab_sec = getSection(getStringTableIndex());
+ if (dot_shstrtab_sec) {
+ // Verify that the last byte in the string table in a null.
+ VerifyStrTab(dot_shstrtab_sec);
+ }
+
+ // Merge this into the above loop.
+ for (const char *i = reinterpret_cast<const char *>(SectionHeaderTable),
+ *e = i + getNumSections() * Header->e_shentsize;
+ i != e; i += Header->e_shentsize) {
+ const Elf_Shdr *sh = reinterpret_cast<const Elf_Shdr*>(i);
+ if (sh->sh_type == ELF::SHT_STRTAB) {
+ StringRef SectionName(getString(dot_shstrtab_sec, sh->sh_name));
+ if (SectionName == ".strtab") {
+ if (dot_strtab_sec != 0)
+ // FIXME: Proper error handling.
+ report_fatal_error("Already found section named .strtab!");
+ dot_strtab_sec = sh;
+ VerifyStrTab(dot_strtab_sec);
+ } else if (SectionName == ".dynstr") {
+ if (dot_dynstr_sec != 0)
+ // FIXME: Proper error handling.
+ report_fatal_error("Already found section named .dynstr!");
+ dot_dynstr_sec = sh;
+ VerifyStrTab(dot_dynstr_sec);
+ }
+ }
+ }
+
+ // Build symbol name side-mapping if there is one.
+ if (SymbolTableSectionHeaderIndex) {
+ const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
+ SymbolTableSectionHeaderIndex->sh_offset);
+ error_code ec;
+ for (symbol_iterator si = begin_symbols(),
+ se = end_symbols(); si != se; si.increment(ec)) {
+ if (ec)
+ report_fatal_error("Fewer extended symbol table entries than symbols!");
+ if (*ShndxTable != ELF::SHN_UNDEF)
+ ExtendedSymbolTable[getSymbol(si->getRawDataRefImpl())] = *ShndxTable;
+ ++ShndxTable;
+ }
+ }
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+symbol_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::begin_symbols() const {
+ DataRefImpl SymbolData;
+ if (SymbolTableSections.size() <= 1) {
+ SymbolData.d.a = std::numeric_limits<uint32_t>::max();
+ SymbolData.d.b = std::numeric_limits<uint32_t>::max();
+ } else {
+ SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
+ SymbolData.d.b = 1; // The 0th table is .dynsym
+ }
+ return symbol_iterator(SymbolRef(SymbolData, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+symbol_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::end_symbols() const {
+ DataRefImpl SymbolData;
+ SymbolData.d.a = std::numeric_limits<uint32_t>::max();
+ SymbolData.d.b = std::numeric_limits<uint32_t>::max();
+ return symbol_iterator(SymbolRef(SymbolData, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+symbol_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::begin_dynamic_symbols() const {
+ DataRefImpl SymbolData;
+ if (SymbolTableSections[0] == NULL) {
+ SymbolData.d.a = std::numeric_limits<uint32_t>::max();
+ SymbolData.d.b = std::numeric_limits<uint32_t>::max();
+ } else {
+ SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
+ SymbolData.d.b = 0; // The 0th table is .dynsym
+ }
+ return symbol_iterator(SymbolRef(SymbolData, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+symbol_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::end_dynamic_symbols() const {
+ DataRefImpl SymbolData;
+ SymbolData.d.a = std::numeric_limits<uint32_t>::max();
+ SymbolData.d.b = std::numeric_limits<uint32_t>::max();
+ return symbol_iterator(SymbolRef(SymbolData, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+section_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::begin_sections() const {
+ DataRefImpl ret;
+ ret.p = reinterpret_cast<intptr_t>(base() + Header->e_shoff);
+ return section_iterator(SectionRef(ret, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+section_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::end_sections() const {
+ DataRefImpl ret;
+ ret.p = reinterpret_cast<intptr_t>(base()
+ + Header->e_shoff
+ + (Header->e_shentsize*getNumSections()));
+ return section_iterator(SectionRef(ret, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+typename ELFObjectFile<target_endianness, is64Bits>::dyn_iterator
+ELFObjectFile<target_endianness, is64Bits>::begin_dynamic_table() const {
+ DataRefImpl DynData;
+ if (dot_dynamic_sec == NULL || dot_dynamic_sec->sh_size == 0) {
+ DynData.d.a = std::numeric_limits<uint32_t>::max();
+ } else {
+ DynData.d.a = 0;
+ }
+ return dyn_iterator(DynRef(DynData, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+typename ELFObjectFile<target_endianness, is64Bits>::dyn_iterator
+ELFObjectFile<target_endianness, is64Bits>
+ ::end_dynamic_table() const {
+ DataRefImpl DynData;
+ DynData.d.a = std::numeric_limits<uint32_t>::max();
+ return dyn_iterator(DynRef(DynData, this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getDynNext(DataRefImpl DynData,
+ DynRef &Result) const {
+ ++DynData.d.a;
+
+ // Check to see if we are at the end of .dynamic
+ if (DynData.d.a >= dot_dynamic_sec->getEntityCount()) {
+ // We are at the end. Return the terminator.
+ DynData.d.a = std::numeric_limits<uint32_t>::max();
+ }
+
+ Result = DynRef(DynData, this);
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+StringRef
+ELFObjectFile<target_endianness, is64Bits>::getLoadName() const {
+ if (!dt_soname) {
+ // Find the DT_SONAME entry
+ dyn_iterator it = begin_dynamic_table();
+ dyn_iterator ie = end_dynamic_table();
+ error_code ec;
+ while (it != ie) {
+ if (it->getTag() == ELF::DT_SONAME)
+ break;
+ it.increment(ec);
+ if (ec)
+ report_fatal_error("dynamic table iteration failed");
+ }
+ if (it != ie) {
+ if (dot_dynstr_sec == NULL)
+ report_fatal_error("Dynamic string table is missing");
+ dt_soname = getString(dot_dynstr_sec, it->getVal());
+ } else {
+ dt_soname = "";
+ }
+ }
+ return dt_soname;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+library_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::begin_libraries_needed() const {
+ // Find the first DT_NEEDED entry
+ dyn_iterator i = begin_dynamic_table();
+ dyn_iterator e = end_dynamic_table();
+ error_code ec;
+ while (i != e) {
+ if (i->getTag() == ELF::DT_NEEDED)
+ break;
+ i.increment(ec);
+ if (ec)
+ report_fatal_error("dynamic table iteration failed");
+ }
+ // Use the same DataRefImpl format as DynRef.
+ return library_iterator(LibraryRef(i->getRawDataRefImpl(), this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getLibraryNext(DataRefImpl Data,
+ LibraryRef &Result) const {
+ // Use the same DataRefImpl format as DynRef.
+ dyn_iterator i = dyn_iterator(DynRef(Data, this));
+ dyn_iterator e = end_dynamic_table();
+
+ // Skip the current dynamic table entry.
+ error_code ec;
+ if (i != e) {
+ i.increment(ec);
+ // TODO: proper error handling
+ if (ec)
+ report_fatal_error("dynamic table iteration failed");
+ }
+
+ // Find the next DT_NEEDED entry.
+ while (i != e) {
+ if (i->getTag() == ELF::DT_NEEDED)
+ break;
+ i.increment(ec);
+ if (ec)
+ report_fatal_error("dynamic table iteration failed");
+ }
+ Result = LibraryRef(i->getRawDataRefImpl(), this);
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getLibraryPath(DataRefImpl Data, StringRef &Res) const {
+ dyn_iterator i = dyn_iterator(DynRef(Data, this));
+ if (i == end_dynamic_table())
+ report_fatal_error("getLibraryPath() called on iterator end");
+
+ if (i->getTag() != ELF::DT_NEEDED)
+ report_fatal_error("Invalid library_iterator");
+
+ // This uses .dynstr to lookup the name of the DT_NEEDED entry.
+ // THis works as long as DT_STRTAB == .dynstr. This is true most of
+ // the time, but the specification allows exceptions.
+ // TODO: This should really use DT_STRTAB instead. Doing this requires
+ // reading the program headers.
+ if (dot_dynstr_sec == NULL)
+ report_fatal_error("Dynamic string table is missing");
+ Res = getString(dot_dynstr_sec, i->getVal());
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+library_iterator ELFObjectFile<target_endianness, is64Bits>
+ ::end_libraries_needed() const {
+ dyn_iterator e = end_dynamic_table();
+ // Use the same DataRefImpl format as DynRef.
+ return library_iterator(LibraryRef(e->getRawDataRefImpl(), this));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+uint8_t ELFObjectFile<target_endianness, is64Bits>::getBytesInAddress() const {
+ return is64Bits ? 8 : 4;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+StringRef ELFObjectFile<target_endianness, is64Bits>
+ ::getFileFormatName() const {
+ switch(Header->e_ident[ELF::EI_CLASS]) {
+ case ELF::ELFCLASS32:
+ switch(Header->e_machine) {
+ case ELF::EM_386:
+ return "ELF32-i386";
+ case ELF::EM_X86_64:
+ return "ELF32-x86-64";
+ case ELF::EM_ARM:
+ return "ELF32-arm";
+ case ELF::EM_HEXAGON:
+ return "ELF32-hexagon";
+ default:
+ return "ELF32-unknown";
+ }
+ case ELF::ELFCLASS64:
+ switch(Header->e_machine) {
+ case ELF::EM_386:
+ return "ELF64-i386";
+ case ELF::EM_X86_64:
+ return "ELF64-x86-64";
+ default:
+ return "ELF64-unknown";
+ }
+ default:
+ // FIXME: Proper error handling.
+ report_fatal_error("Invalid ELFCLASS!");
+ }
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+unsigned ELFObjectFile<target_endianness, is64Bits>::getArch() const {
+ switch(Header->e_machine) {
+ case ELF::EM_386:
+ return Triple::x86;
+ case ELF::EM_X86_64:
+ return Triple::x86_64;
+ case ELF::EM_ARM:
+ return Triple::arm;
+ case ELF::EM_HEXAGON:
+ return Triple::hexagon;
+ case ELF::EM_MIPS:
+ return (target_endianness == support::little) ?
+ Triple::mipsel : Triple::mips;
+ default:
+ return Triple::UnknownArch;
+ }
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+uint64_t ELFObjectFile<target_endianness, is64Bits>::getNumSections() const {
+ assert(Header && "Header not initialized!");
+ if (Header->e_shnum == ELF::SHN_UNDEF) {
+ assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
+ return SectionHeaderTable->sh_size;
+ }
+ return Header->e_shnum;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+uint64_t
+ELFObjectFile<target_endianness, is64Bits>::getStringTableIndex() const {
+ if (Header->e_shnum == ELF::SHN_UNDEF) {
+ if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
+ return SectionHeaderTable->sh_link;
+ if (Header->e_shstrndx >= getNumSections())
+ return 0;
+ }
+ return Header->e_shstrndx;
+}
+
+
+template<support::endianness target_endianness, bool is64Bits>
+template<typename T>
+inline const T *
+ELFObjectFile<target_endianness, is64Bits>::getEntry(uint16_t Section,
+ uint32_t Entry) const {
+ return getEntry<T>(getSection(Section), Entry);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+template<typename T>
+inline const T *
+ELFObjectFile<target_endianness, is64Bits>::getEntry(const Elf_Shdr * Section,
+ uint32_t Entry) const {
+ return reinterpret_cast<const T *>(
+ base()
+ + Section->sh_offset
+ + (Entry * Section->sh_entsize));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
+ELFObjectFile<target_endianness, is64Bits>::getSymbol(DataRefImpl Symb) const {
+ return getEntry<Elf_Sym>(SymbolTableSections[Symb.d.b], Symb.d.a);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Dyn *
+ELFObjectFile<target_endianness, is64Bits>::getDyn(DataRefImpl DynData) const {
+ return getEntry<Elf_Dyn>(dot_dynamic_sec, DynData.d.a);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rel *
+ELFObjectFile<target_endianness, is64Bits>::getRel(DataRefImpl Rel) const {
+ return getEntry<Elf_Rel>(Rel.w.b, Rel.w.c);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rela *
+ELFObjectFile<target_endianness, is64Bits>::getRela(DataRefImpl Rela) const {
+ return getEntry<Elf_Rela>(Rela.w.b, Rela.w.c);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
+ELFObjectFile<target_endianness, is64Bits>::getSection(DataRefImpl Symb) const {
+ const Elf_Shdr *sec = getSection(Symb.d.b);
+ if (sec->sh_type != ELF::SHT_SYMTAB || sec->sh_type != ELF::SHT_DYNSYM)
+ // FIXME: Proper error handling.
+ report_fatal_error("Invalid symbol table section!");
+ return sec;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
+ELFObjectFile<target_endianness, is64Bits>::getSection(uint32_t index) const {
+ if (index == 0)
+ return 0;
+ if (!SectionHeaderTable || index >= getNumSections())
+ // FIXME: Proper error handling.
+ report_fatal_error("Invalid section index!");
+
+ return reinterpret_cast<const Elf_Shdr *>(
+ reinterpret_cast<const char *>(SectionHeaderTable)
+ + (index * Header->e_shentsize));
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const char *ELFObjectFile<target_endianness, is64Bits>
+ ::getString(uint32_t section,
+ ELF::Elf32_Word offset) const {
+ return getString(getSection(section), offset);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+const char *ELFObjectFile<target_endianness, is64Bits>
+ ::getString(const Elf_Shdr *section,
+ ELF::Elf32_Word offset) const {
+ assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
+ if (offset >= section->sh_size)
+ // FIXME: Proper error handling.
+ report_fatal_error("Symbol name offset outside of string table!");
+ return (const char *)base() + section->sh_offset + offset;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolName(const Elf_Shdr *section,
+ const Elf_Sym *symb,
+ StringRef &Result) const {
+ if (symb->st_name == 0) {
+ const Elf_Shdr *section = getSection(symb);
+ if (!section)
+ Result = "";
+ else
+ Result = getString(dot_shstrtab_sec, section->sh_name);
+ return object_error::success;
+ }
+
+ if (section == SymbolTableSections[0]) {
+ // Symbol is in .dynsym, use .dynstr string table
+ Result = getString(dot_dynstr_sec, symb->st_name);
+ } else {
+ // Use the default symbol table name section.
+ Result = getString(dot_strtab_sec, symb->st_name);
+ }
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSectionName(const Elf_Shdr *section,
+ StringRef &Result) const {
+ Result = StringRef(getString(dot_shstrtab_sec, section->sh_name));
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+error_code ELFObjectFile<target_endianness, is64Bits>
+ ::getSymbolVersion(const Elf_Shdr *section,
+ const Elf_Sym *symb,
+ StringRef &Version,
+ bool &IsDefault) const {
+ // Handle non-dynamic symbols.
+ if (section != SymbolTableSections[0]) {
+ // Non-dynamic symbols can have versions in their names
+ // A name of the form 'foo@V1' indicates version 'V1', non-default.
+ // A name of the form 'foo@@V2' indicates version 'V2', default version.
+ StringRef Name;
+ error_code ec = getSymbolName(section, symb, Name);
+ if (ec != object_error::success)
+ return ec;
+ size_t atpos = Name.find('@');
+ if (atpos == StringRef::npos) {
+ Version = "";
+ IsDefault = false;
+ return object_error::success;
+ }
+ ++atpos;
+ if (atpos < Name.size() && Name[atpos] == '@') {
+ IsDefault = true;
+ ++atpos;
+ } else {
+ IsDefault = false;
+ }
+ Version = Name.substr(atpos);
+ return object_error::success;
+ }
+
+ // This is a dynamic symbol. Look in the GNU symbol version table.
+ if (dot_gnu_version_sec == NULL) {
+ // No version table.
+ Version = "";
+ IsDefault = false;
+ return object_error::success;
+ }
+
+ // Determine the position in the symbol table of this entry.
+ const char *sec_start = (const char*)base() + section->sh_offset;
+ size_t entry_index = ((const char*)symb - sec_start)/section->sh_entsize;
+
+ // Get the corresponding version index entry
+ const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
+ size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
+
+ // Special markers for unversioned symbols.
+ if (version_index == ELF::VER_NDX_LOCAL ||
+ version_index == ELF::VER_NDX_GLOBAL) {
+ Version = "";
+ IsDefault = false;
+ return object_error::success;
+ }
+
+ // Lookup this symbol in the version table
+ LoadVersionMap();
+ if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
+ report_fatal_error("Symbol has version index without corresponding "
+ "define or reference entry");
+ const VersionMapEntry &entry = VersionMap[version_index];
+
+ // Get the version name string
+ size_t name_offset;
+ if (entry.isVerdef()) {
+ // The first Verdaux entry holds the name.
+ name_offset = entry.getVerdef()->getAux()->vda_name;
+ } else {
+ name_offset = entry.getVernaux()->vna_name;
+ }
+ Version = getString(dot_dynstr_sec, name_offset);
+
+ // Set IsDefault
+ if (entry.isVerdef()) {
+ IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
+ } else {
+ IsDefault = false;
+ }
+
+ return object_error::success;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+inline DynRefImpl<target_endianness, is64Bits>
+ ::DynRefImpl(DataRefImpl DynP, const OwningType *Owner)
+ : DynPimpl(DynP)
+ , OwningObject(Owner) {}
+
+template<support::endianness target_endianness, bool is64Bits>
+inline bool DynRefImpl<target_endianness, is64Bits>
+ ::operator==(const DynRefImpl &Other) const {
+ return DynPimpl == Other.DynPimpl;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+inline bool DynRefImpl<target_endianness, is64Bits>
+ ::operator <(const DynRefImpl &Other) const {
+ return DynPimpl < Other.DynPimpl;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+inline error_code DynRefImpl<target_endianness, is64Bits>
+ ::getNext(DynRefImpl &Result) const {
+ return OwningObject->getDynNext(DynPimpl, Result);
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+inline int64_t DynRefImpl<target_endianness, is64Bits>
+ ::getTag() const {
+ return OwningObject->getDyn(DynPimpl)->d_tag;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+inline uint64_t DynRefImpl<target_endianness, is64Bits>
+ ::getVal() const {
+ return OwningObject->getDyn(DynPimpl)->d_un.d_val;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+inline uint64_t DynRefImpl<target_endianness, is64Bits>
+ ::getPtr() const {
+ return OwningObject->getDyn(DynPimpl)->d_un.d_ptr;
+}
+
+template<support::endianness target_endianness, bool is64Bits>
+inline DataRefImpl DynRefImpl<target_endianness, is64Bits>
+ ::getRawDataRefImpl() const {
+ return DynPimpl;
+}
+
+/// This is a generic interface for retrieving GNU symbol version
+/// information from an ELFObjectFile.
+static inline error_code GetELFSymbolVersion(const ObjectFile *Obj,
+ const SymbolRef &Sym,
+ StringRef &Version,
+ bool &IsDefault) {
+ // Little-endian 32-bit
+ if (const ELFObjectFile<support::little, false> *ELFObj =
+ dyn_cast<ELFObjectFile<support::little, false> >(Obj))
+ return ELFObj->getSymbolVersion(Sym, Version, IsDefault);
+
+ // Big-endian 32-bit
+ if (const ELFObjectFile<support::big, false> *ELFObj =
+ dyn_cast<ELFObjectFile<support::big, false> >(Obj))
+ return ELFObj->getSymbolVersion(Sym, Version, IsDefault);
+
+ // Little-endian 64-bit
+ if (const ELFObjectFile<support::little, true> *ELFObj =
+ dyn_cast<ELFObjectFile<support::little, true> >(Obj))
+ return ELFObj->getSymbolVersion(Sym, Version, IsDefault);
+
+ // Big-endian 64-bit
+ if (const ELFObjectFile<support::big, true> *ELFObj =
+ dyn_cast<ELFObjectFile<support::big, true> >(Obj))
+ return ELFObj->getSymbolVersion(Sym, Version, IsDefault);
+
+ llvm_unreachable("Object passed to GetELFSymbolVersion() is not ELF");
+}
+
+}
+}
+
+#endif
diff --git a/include/llvm/Object/Error.h b/include/llvm/Object/Error.h
new file mode 100644
index 00000000000..fbaf71c17b8
--- /dev/null
+++ b/include/llvm/Object/Error.h
@@ -0,0 +1,50 @@
+//===- Error.h - system_error extensions for Object -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This declares a new error_category for the Object library.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_ERROR_H
+#define LLVM_OBJECT_ERROR_H
+
+#include "llvm/Support/system_error.h"
+
+namespace llvm {
+namespace object {
+
+const error_category &object_category();
+
+struct object_error {
+enum _ {
+ success = 0,
+ invalid_file_type,
+ parse_failed,
+ unexpected_eof
+};
+ _ v_;
+
+ object_error(_ v) : v_(v) {}
+ explicit object_error(int v) : v_(_(v)) {}
+ operator int() const {return v_;}
+};
+
+inline error_code make_error_code(object_error e) {
+ return error_code(static_cast<int>(e), object_category());
+}
+
+} // end namespace object.
+
+template <> struct is_error_code_enum<object::object_error> : true_type { };
+
+template <> struct is_error_code_enum<object::object_error::_> : true_type { };
+
+} // end namespace llvm.
+
+#endif
diff --git a/include/llvm/Object/MachO.h b/include/llvm/Object/MachO.h
new file mode 100644
index 00000000000..0b73f948316
--- /dev/null
+++ b/include/llvm/Object/MachO.h
@@ -0,0 +1,133 @@
+//===- MachO.h - MachO object file implementation ---------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the MachOObjectFile class, which binds the MachOObject
+// class to the generic ObjectFile wrapper.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_MACHO_H
+#define LLVM_OBJECT_MACHO_H
+
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Object/MachOObject.h"
+#include "llvm/Support/MachO.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace llvm {
+namespace object {
+
+typedef MachOObject::LoadCommandInfo LoadCommandInfo;
+
+class MachOObjectFile : public ObjectFile {
+public:
+ MachOObjectFile(MemoryBuffer *Object, MachOObject *MOO, error_code &ec);
+
+ virtual symbol_iterator begin_symbols() const;
+ virtual symbol_iterator end_symbols() const;
+ virtual symbol_iterator begin_dynamic_symbols() const;
+ virtual symbol_iterator end_dynamic_symbols() const;
+ virtual library_iterator begin_libraries_needed() const;
+ virtual library_iterator end_libraries_needed() const;
+ virtual section_iterator begin_sections() const;
+ virtual section_iterator end_sections() const;
+
+ virtual uint8_t getBytesInAddress() const;
+ virtual StringRef getFileFormatName() const;
+ virtual unsigned getArch() const;
+ virtual StringRef getLoadName() const;
+
+ MachOObject *getObject() { return MachOObj; }
+
+ static inline bool classof(const Binary *v) {
+ return v->isMachO();
+ }
+ static inline bool classof(const MachOObjectFile *v) { return true; }
+
+protected:
+ virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
+ virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
+ virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
+ virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
+ virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
+ virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res) const;
+ virtual error_code getSymbolSection(DataRefImpl Symb,
+ section_iterator &Res) const;
+
+ virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
+ virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
+ virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
+ virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
+ virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
+ bool &Res) const;
+ virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const;
+ virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const;
+ virtual error_code sectionContainsSymbol(DataRefImpl DRI, DataRefImpl S,
+ bool &Result) const;
+ virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
+ virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
+
+ virtual error_code getRelocationNext(DataRefImpl Rel,
+ RelocationRef &Res) const;
+ virtual error_code getRelocationAddress(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationOffset(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationSymbol(DataRefImpl Rel,
+ SymbolRef &Res) const;
+ virtual error_code getRelocationType(DataRefImpl Rel,
+ uint64_t &Res) const;
+ virtual error_code getRelocationTypeName(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const;
+ virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
+ int64_t &Res) const;
+ virtual error_code getRelocationValueString(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const;
+ virtual error_code getRelocationHidden(DataRefImpl Rel, bool &Result) const;
+
+ virtual error_code getLibraryNext(DataRefImpl LibData, LibraryRef &Res) const;
+ virtual error_code getLibraryPath(DataRefImpl LibData, StringRef &Res) const;
+
+private:
+ MachOObject *MachOObj;
+ mutable uint32_t RegisteredStringTable;
+ typedef SmallVector<DataRefImpl, 1> SectionList;
+ SectionList Sections;
+
+
+ void moveToNextSection(DataRefImpl &DRI) const;
+ void getSymbolTableEntry(DataRefImpl DRI,
+ InMemoryStruct<macho::SymbolTableEntry> &Res) const;
+ void getSymbol64TableEntry(DataRefImpl DRI,
+ InMemoryStruct<macho::Symbol64TableEntry> &Res) const;
+ void moveToNextSymbol(DataRefImpl &DRI) const;
+ void getSection(DataRefImpl DRI, InMemoryStruct<macho::Section> &Res) const;
+ void getSection64(DataRefImpl DRI,
+ InMemoryStruct<macho::Section64> &Res) const;
+ void getRelocation(DataRefImpl Rel,
+ InMemoryStruct<macho::RelocationEntry> &Res) const;
+ std::size_t getSectionIndex(DataRefImpl Sec) const;
+
+ void printRelocationTargetName(InMemoryStruct<macho::RelocationEntry>& RE,
+ raw_string_ostream &fmt) const;
+};
+
+}
+}
+
+#endif
+
diff --git a/include/llvm/Object/MachOFormat.h b/include/llvm/Object/MachOFormat.h
new file mode 100644
index 00000000000..e4bfcc67fea
--- /dev/null
+++ b/include/llvm/Object/MachOFormat.h
@@ -0,0 +1,396 @@
+//===- MachOFormat.h - Mach-O Format Structures And Constants ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares various structures and constants which are platform
+// independent and can be shared by any client which wishes to interact with
+// Mach object files.
+//
+// The definitions here are purposely chosen to match the LLVM style as opposed
+// to following the platform specific definition of the format.
+//
+// On a Mach system, see the <mach-o/...> includes for more information, in
+// particular <mach-o/loader.h>.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_MACHOFORMAT_H
+#define LLVM_OBJECT_MACHOFORMAT_H
+
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+namespace object {
+
+/// General Mach platform information.
+namespace mach {
+ /// @name CPU Type and Subtype Information
+ /// {
+
+ /// \brief Capability bits used in CPU type encoding.
+ enum CPUTypeFlagsMask {
+ CTFM_ArchMask = 0xFF000000,
+ CTFM_ArchABI64 = 0x01000000
+ };
+
+ /// \brief Machine type IDs used in CPU type encoding.
+ enum CPUTypeMachine {
+ CTM_i386 = 7,
+ CTM_x86_64 = CTM_i386 | CTFM_ArchABI64,
+ CTM_ARM = 12,
+ CTM_SPARC = 14,
+ CTM_PowerPC = 18,
+ CTM_PowerPC64 = CTM_PowerPC | CTFM_ArchABI64
+ };
+
+ /// \brief Capability bits used in CPU subtype encoding.
+ enum CPUSubtypeFlagsMask {
+ CSFM_SubtypeMask = 0xFF000000,
+ CSFM_SubtypeLib64 = 0x80000000
+ };
+
+ /// \brief ARM Machine Subtypes.
+ enum CPUSubtypeARM {
+ CSARM_ALL = 0,
+ CSARM_V4T = 5,
+ CSARM_V6 = 6,
+ CSARM_V5TEJ = 7,
+ CSARM_XSCALE = 8,
+ CSARM_V7 = 9
+ };
+
+ /// \brief PowerPC Machine Subtypes.
+ enum CPUSubtypePowerPC {
+ CSPPC_ALL = 0
+ };
+
+ /// \brief SPARC Machine Subtypes.
+ enum CPUSubtypeSPARC {
+ CSSPARC_ALL = 0
+ };
+
+ /// \brief x86 Machine Subtypes.
+ enum CPUSubtypeX86 {
+ CSX86_ALL = 3
+ };
+
+ /// @}
+
+} // end namespace mach
+
+/// Format information for Mach object files.
+namespace macho {
+ /// \brief Constants for structure sizes.
+ enum StructureSizes {
+ Header32Size = 28,
+ Header64Size = 32,
+ SegmentLoadCommand32Size = 56,
+ SegmentLoadCommand64Size = 72,
+ Section32Size = 68,
+ Section64Size = 80,
+ SymtabLoadCommandSize = 24,
+ DysymtabLoadCommandSize = 80,
+ Nlist32Size = 12,
+ Nlist64Size = 16,
+ RelocationInfoSize = 8,
+ LinkeditLoadCommandSize = 16
+ };
+
+ /// \brief Constants for header magic field.
+ enum HeaderMagic {
+ HM_Object32 = 0xFEEDFACE, ///< 32-bit mach object file
+ HM_Object64 = 0xFEEDFACF, ///< 64-bit mach object file
+ HM_Universal = 0xCAFEBABE ///< Universal object file
+ };
+
+ /// \brief Header common to all Mach object files.
+ struct Header {
+ uint32_t Magic;
+ uint32_t CPUType;
+ uint32_t CPUSubtype;
+ uint32_t FileType;
+ uint32_t NumLoadCommands;
+ uint32_t SizeOfLoadCommands;
+ uint32_t Flags;
+ };
+
+ /// \brief Extended header for 64-bit object files.
+ struct Header64Ext {
+ uint32_t Reserved;
+ };
+
+ // See <mach-o/loader.h>.
+ enum HeaderFileType {
+ HFT_Object = 0x1
+ };
+
+ enum HeaderFlags {
+ HF_SubsectionsViaSymbols = 0x2000
+ };
+
+ enum LoadCommandType {
+ LCT_Segment = 0x1,
+ LCT_Symtab = 0x2,
+ LCT_Dysymtab = 0xb,
+ LCT_Segment64 = 0x19,
+ LCT_UUID = 0x1b,
+ LCT_CodeSignature = 0x1d,
+ LCT_SegmentSplitInfo = 0x1e,
+ LCT_FunctionStarts = 0x26,
+ LCT_DataInCode = 0x29
+ };
+
+ /// \brief Load command structure.
+ struct LoadCommand {
+ uint32_t Type;
+ uint32_t Size;
+ };
+
+ /// @name Load Command Structures
+ /// @{
+
+ struct SegmentLoadCommand {
+ uint32_t Type;
+ uint32_t Size;
+ char Name[16];
+ uint32_t VMAddress;
+ uint32_t VMSize;
+ uint32_t FileOffset;
+ uint32_t FileSize;
+ uint32_t MaxVMProtection;
+ uint32_t InitialVMProtection;
+ uint32_t NumSections;
+ uint32_t Flags;
+ };
+
+ struct Segment64LoadCommand {
+ uint32_t Type;
+ uint32_t Size;
+ char Name[16];
+ uint64_t VMAddress;
+ uint64_t VMSize;
+ uint64_t FileOffset;
+ uint64_t FileSize;
+ uint32_t MaxVMProtection;
+ uint32_t InitialVMProtection;
+ uint32_t NumSections;
+ uint32_t Flags;
+ };
+
+ struct SymtabLoadCommand {
+ uint32_t Type;
+ uint32_t Size;
+ uint32_t SymbolTableOffset;
+ uint32_t NumSymbolTableEntries;
+ uint32_t StringTableOffset;
+ uint32_t StringTableSize;
+ };
+
+ struct DysymtabLoadCommand {
+ uint32_t Type;
+ uint32_t Size;
+
+ uint32_t LocalSymbolsIndex;
+ uint32_t NumLocalSymbols;
+
+ uint32_t ExternalSymbolsIndex;
+ uint32_t NumExternalSymbols;
+
+ uint32_t UndefinedSymbolsIndex;
+ uint32_t NumUndefinedSymbols;
+
+ uint32_t TOCOffset;
+ uint32_t NumTOCEntries;
+
+ uint32_t ModuleTableOffset;
+ uint32_t NumModuleTableEntries;
+
+ uint32_t ReferenceSymbolTableOffset;
+ uint32_t NumReferencedSymbolTableEntries;
+
+ uint32_t IndirectSymbolTableOffset;
+ uint32_t NumIndirectSymbolTableEntries;
+
+ uint32_t ExternalRelocationTableOffset;
+ uint32_t NumExternalRelocationTableEntries;
+
+ uint32_t LocalRelocationTableOffset;
+ uint32_t NumLocalRelocationTableEntries;
+ };
+
+ struct LinkeditDataLoadCommand {
+ uint32_t Type;
+ uint32_t Size;
+ uint32_t DataOffset;
+ uint32_t DataSize;
+ };
+
+ /// @}
+ /// @name Section Data
+ /// @{
+
+ struct Section {
+ char Name[16];
+ char SegmentName[16];
+ uint32_t Address;
+ uint32_t Size;
+ uint32_t Offset;
+ uint32_t Align;
+ uint32_t RelocationTableOffset;
+ uint32_t NumRelocationTableEntries;
+ uint32_t Flags;
+ uint32_t Reserved1;
+ uint32_t Reserved2;
+ };
+ struct Section64 {
+ char Name[16];
+ char SegmentName[16];
+ uint64_t Address;
+ uint64_t Size;
+ uint32_t Offset;
+ uint32_t Align;
+ uint32_t RelocationTableOffset;
+ uint32_t NumRelocationTableEntries;
+ uint32_t Flags;
+ uint32_t Reserved1;
+ uint32_t Reserved2;
+ uint32_t Reserved3;
+ };
+
+ /// @}
+ /// @name Symbol Table Entries
+ /// @{
+
+ struct SymbolTableEntry {
+ uint32_t StringIndex;
+ uint8_t Type;
+ uint8_t SectionIndex;
+ uint16_t Flags;
+ uint32_t Value;
+ };
+ // Despite containing a uint64_t, this structure is only 4-byte aligned within
+ // a MachO file.
+#pragma pack(push)
+#pragma pack(4)
+ struct Symbol64TableEntry {
+ uint32_t StringIndex;
+ uint8_t Type;
+ uint8_t SectionIndex;
+ uint16_t Flags;
+ uint64_t Value;
+ };
+#pragma pack(pop)
+
+ /// @}
+ /// @name Data-in-code Table Entry
+ /// @{
+
+ // See <mach-o/loader.h>.
+ enum DataRegionType { Data = 1, JumpTable8, JumpTable16, JumpTable32 };
+ struct DataInCodeTableEntry {
+ uint32_t Offset; /* from mach_header to start of data region */
+ uint16_t Length; /* number of bytes in data region */
+ uint16_t Kind; /* a DataRegionType value */
+ };
+
+ /// @}
+ /// @name Indirect Symbol Table
+ /// @{
+
+ struct IndirectSymbolTableEntry {
+ uint32_t Index;
+ };
+
+ /// @}
+ /// @name Relocation Data
+ /// @{
+
+ struct RelocationEntry {
+ uint32_t Word0;
+ uint32_t Word1;
+ };
+
+ /// @}
+
+ // See <mach-o/nlist.h>.
+ enum SymbolTypeType {
+ STT_Undefined = 0x00,
+ STT_Absolute = 0x02,
+ STT_Section = 0x0e
+ };
+
+ enum SymbolTypeFlags {
+ // If any of these bits are set, then the entry is a stab entry number (see
+ // <mach-o/stab.h>. Otherwise the other masks apply.
+ STF_StabsEntryMask = 0xe0,
+
+ STF_TypeMask = 0x0e,
+ STF_External = 0x01,
+ STF_PrivateExtern = 0x10
+ };
+
+ /// IndirectSymbolFlags - Flags for encoding special values in the indirect
+ /// symbol entry.
+ enum IndirectSymbolFlags {
+ ISF_Local = 0x80000000,
+ ISF_Absolute = 0x40000000
+ };
+
+ /// RelocationFlags - Special flags for addresses.
+ enum RelocationFlags {
+ RF_Scattered = 0x80000000
+ };
+
+ /// Common relocation info types.
+ enum RelocationInfoType {
+ RIT_Vanilla = 0,
+ RIT_Pair = 1,
+ RIT_Difference = 2
+ };
+
+ /// Generic relocation info types, which are shared by some (but not all)
+ /// platforms.
+ enum RelocationInfoType_Generic {
+ RIT_Generic_PreboundLazyPointer = 3,
+ RIT_Generic_LocalDifference = 4,
+ RIT_Generic_TLV = 5
+ };
+
+ /// X86_64 uses its own relocation types.
+ enum RelocationInfoTypeX86_64 {
+ // Note that x86_64 doesn't even share the common relocation types.
+ RIT_X86_64_Unsigned = 0,
+ RIT_X86_64_Signed = 1,
+ RIT_X86_64_Branch = 2,
+ RIT_X86_64_GOTLoad = 3,
+ RIT_X86_64_GOT = 4,
+ RIT_X86_64_Subtractor = 5,
+ RIT_X86_64_Signed1 = 6,
+ RIT_X86_64_Signed2 = 7,
+ RIT_X86_64_Signed4 = 8,
+ RIT_X86_64_TLV = 9
+ };
+
+ /// ARM uses its own relocation types.
+ enum RelocationInfoTypeARM {
+ RIT_ARM_LocalDifference = 3,
+ RIT_ARM_PreboundLazyPointer = 4,
+ RIT_ARM_Branch24Bit = 5,
+ RIT_ARM_ThumbBranch22Bit = 6,
+ RIT_ARM_ThumbBranch32Bit = 7,
+ RIT_ARM_Half = 8,
+ RIT_ARM_HalfDifference = 9
+
+ };
+
+} // end namespace macho
+
+} // end namespace object
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Object/MachOObject.h b/include/llvm/Object/MachOObject.h
new file mode 100644
index 00000000000..86f150a2940
--- /dev/null
+++ b/include/llvm/Object/MachOObject.h
@@ -0,0 +1,207 @@
+//===- MachOObject.h - Mach-O Object File Wrapper ---------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_MACHOOBJECT_H
+#define LLVM_OBJECT_MACHOOBJECT_H
+
+#include <string>
+#include "llvm/ADT/InMemoryStruct.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Object/MachOFormat.h"
+
+namespace llvm {
+
+class MemoryBuffer;
+class raw_ostream;
+
+namespace object {
+
+/// \brief Wrapper object for manipulating Mach-O object files.
+///
+/// This class is designed to implement a full-featured, efficient, portable,
+/// and robust Mach-O interface to Mach-O object files. It does not attempt to
+/// smooth over rough edges in the Mach-O format or generalize access to object
+/// independent features.
+///
+/// The class is designed around accessing the Mach-O object which is expected
+/// to be fully loaded into memory.
+///
+/// This class is *not* suitable for concurrent use. For efficient operation,
+/// the class uses APIs which rely on the ability to cache the results of
+/// certain calls in internal objects which are not safe for concurrent
+/// access. This allows the API to be zero-copy on the common paths.
+//
+// FIXME: It would be cool if we supported a "paged" MemoryBuffer
+// implementation. This would allow us to implement a more sensible version of
+// MemoryObject which can work like a MemoryBuffer, but be more efficient for
+// objects which are in the current address space.
+class MachOObject {
+public:
+ struct LoadCommandInfo {
+ /// The load command information.
+ macho::LoadCommand Command;
+
+ /// The offset to the start of the load command in memory.
+ uint64_t Offset;
+ };
+
+private:
+ OwningPtr<MemoryBuffer> Buffer;
+
+ /// Whether the object is little endian.
+ bool IsLittleEndian;
+ /// Whether the object is 64-bit.
+ bool Is64Bit;
+ /// Whether the object is swapped endianness from the host.
+ bool IsSwappedEndian;
+ /// Whether the string table has been registered.
+ bool HasStringTable;
+
+ /// The cached information on the load commands.
+ LoadCommandInfo *LoadCommands;
+ mutable unsigned NumLoadedCommands;
+
+ /// The cached copy of the header.
+ macho::Header Header;
+ macho::Header64Ext Header64Ext;
+
+ /// Cache string table information.
+ StringRef StringTable;
+
+private:
+ MachOObject(MemoryBuffer *Buffer, bool IsLittleEndian, bool Is64Bit);
+
+public:
+ ~MachOObject();
+
+ /// \brief Load a Mach-O object from a MemoryBuffer object.
+ ///
+ /// \param Buffer - The buffer to load the object from. This routine takes
+ /// exclusive ownership of the buffer (which is passed to the returned object
+ /// on success).
+ /// \param ErrorStr [out] - If given, will be set to a user readable error
+ /// message on failure.
+ /// \returns The loaded object, or null on error.
+ static MachOObject *LoadFromBuffer(MemoryBuffer *Buffer,
+ std::string *ErrorStr = 0);
+
+ /// @name File Information
+ /// @{
+
+ bool isLittleEndian() const { return IsLittleEndian; }
+ bool isSwappedEndian() const { return IsSwappedEndian; }
+ bool is64Bit() const { return Is64Bit; }
+
+ unsigned getHeaderSize() const {
+ return Is64Bit ? macho::Header64Size : macho::Header32Size;
+ }
+
+ StringRef getData(size_t Offset, size_t Size) const;
+
+ /// @}
+ /// @name String Table Data
+ /// @{
+
+ StringRef getStringTableData() const {
+ assert(HasStringTable && "String table has not been registered!");
+ return StringTable;
+ }
+
+ StringRef getStringAtIndex(unsigned Index) const {
+ size_t End = getStringTableData().find('\0', Index);
+ return getStringTableData().slice(Index, End);
+ }
+
+ void RegisterStringTable(macho::SymtabLoadCommand &SLC);
+
+ /// @}
+ /// @name Object Header Access
+ /// @{
+
+ const macho::Header &getHeader() const { return Header; }
+ const macho::Header64Ext &getHeader64Ext() const {
+ assert(is64Bit() && "Invalid access!");
+ return Header64Ext;
+ }
+
+ /// @}
+ /// @name Object Structure Access
+ /// @{
+
+ /// \brief Retrieve the information for the given load command.
+ const LoadCommandInfo &getLoadCommandInfo(unsigned Index) const;
+
+ void ReadSegmentLoadCommand(
+ const LoadCommandInfo &LCI,
+ InMemoryStruct<macho::SegmentLoadCommand> &Res) const;
+ void ReadSegment64LoadCommand(
+ const LoadCommandInfo &LCI,
+ InMemoryStruct<macho::Segment64LoadCommand> &Res) const;
+ void ReadSymtabLoadCommand(
+ const LoadCommandInfo &LCI,
+ InMemoryStruct<macho::SymtabLoadCommand> &Res) const;
+ void ReadDysymtabLoadCommand(
+ const LoadCommandInfo &LCI,
+ InMemoryStruct<macho::DysymtabLoadCommand> &Res) const;
+ void ReadLinkeditDataLoadCommand(
+ const LoadCommandInfo &LCI,
+ InMemoryStruct<macho::LinkeditDataLoadCommand> &Res) const;
+ void ReadIndirectSymbolTableEntry(
+ const macho::DysymtabLoadCommand &DLC,
+ unsigned Index,
+ InMemoryStruct<macho::IndirectSymbolTableEntry> &Res) const;
+ void ReadSection(
+ const LoadCommandInfo &LCI,
+ unsigned Index,
+ InMemoryStruct<macho::Section> &Res) const;
+ void ReadSection64(
+ const LoadCommandInfo &LCI,
+ unsigned Index,
+ InMemoryStruct<macho::Section64> &Res) const;
+ void ReadRelocationEntry(
+ uint64_t RelocationTableOffset, unsigned Index,
+ InMemoryStruct<macho::RelocationEntry> &Res) const;
+ void ReadSymbolTableEntry(
+ uint64_t SymbolTableOffset, unsigned Index,
+ InMemoryStruct<macho::SymbolTableEntry> &Res) const;
+ void ReadSymbol64TableEntry(
+ uint64_t SymbolTableOffset, unsigned Index,
+ InMemoryStruct<macho::Symbol64TableEntry> &Res) const;
+ void ReadDataInCodeTableEntry(
+ uint64_t TableOffset, unsigned Index,
+ InMemoryStruct<macho::DataInCodeTableEntry> &Res) const;
+ void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
+
+ /// @}
+
+ /// @name Object Dump Facilities
+ /// @{
+ /// dump - Support for debugging, callable in GDB: V->dump()
+ //
+ void dump() const;
+ void dumpHeader() const;
+
+ /// print - Implement operator<< on Value.
+ ///
+ void print(raw_ostream &O) const;
+ void printHeader(raw_ostream &O) const;
+
+ /// @}
+};
+
+inline raw_ostream &operator<<(raw_ostream &OS, const MachOObject &V) {
+ V.print(OS);
+ return OS;
+}
+
+} // end namespace object
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/Object/ObjectFile.h b/include/llvm/Object/ObjectFile.h
new file mode 100644
index 00000000000..da4cef22665
--- /dev/null
+++ b/include/llvm/Object/ObjectFile.h
@@ -0,0 +1,604 @@
+//===- ObjectFile.h - File format independent object file -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares a file format independent ObjectFile class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OBJECT_OBJECT_FILE_H
+#define LLVM_OBJECT_OBJECT_FILE_H
+
+#include "llvm/Object/Binary.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include <cstring>
+#include <vector>
+
+namespace llvm {
+namespace object {
+
+class ObjectFile;
+
+union DataRefImpl {
+ struct {
+ // ELF needs this for relocations. This entire union should probably be a
+ // char[max(8, sizeof(uintptr_t))] and require the impl to cast.
+ uint16_t a, b;
+ uint32_t c;
+ } w;
+ struct {
+ uint32_t a, b;
+ } d;
+ uintptr_t p;
+ DataRefImpl() {
+ std::memset(this, 0, sizeof(DataRefImpl));
+ }
+};
+
+template<class content_type>
+class content_iterator {
+ content_type Current;
+public:
+ content_iterator(content_type symb)
+ : Current(symb) {}
+
+ const content_type* operator->() const {
+ return &Current;
+ }
+
+ const content_type &operator*() const {
+ return Current;
+ }
+
+ bool operator==(const content_iterator &other) const {
+ return Current == other.Current;
+ }
+
+ bool operator!=(const content_iterator &other) const {
+ return !(*this == other);
+ }
+
+ content_iterator& increment(error_code &err) {
+ content_type next;
+ if (error_code ec = Current.getNext(next))
+ err = ec;
+ else
+ Current = next;
+ return *this;
+ }
+};
+
+inline bool operator ==(const DataRefImpl &a, const DataRefImpl &b) {
+ // Check bitwise identical. This is the only legal way to compare a union w/o
+ // knowing which member is in use.
+ return std::memcmp(&a, &b, sizeof(DataRefImpl)) == 0;
+}
+
+inline bool operator <(const DataRefImpl &a, const DataRefImpl &b) {
+ // Check bitwise identical. This is the only legal way to compare a union w/o
+ // knowing which member is in use.
+ return std::memcmp(&a, &b, sizeof(DataRefImpl)) < 0;
+}
+
+class SymbolRef;
+
+/// RelocationRef - This is a value type class that represents a single
+/// relocation in the list of relocations in the object file.
+class RelocationRef {
+ DataRefImpl RelocationPimpl;
+ const ObjectFile *OwningObject;
+
+public:
+ RelocationRef() : OwningObject(NULL) { }
+
+ RelocationRef(DataRefImpl RelocationP, const ObjectFile *Owner);
+
+ bool operator==(const RelocationRef &Other) const;
+
+ error_code getNext(RelocationRef &Result) const;
+
+ error_code getAddress(uint64_t &Result) const;
+ error_code getOffset(uint64_t &Result) const;
+ error_code getSymbol(SymbolRef &Result) const;
+ error_code getType(uint64_t &Result) const;
+
+ /// @brief Indicates whether this relocation should hidden when listing
+ /// relocations, usually because it is the trailing part of a multipart
+ /// relocation that will be printed as part of the leading relocation.
+ error_code getHidden(bool &Result) const;
+
+ /// @brief Get a string that represents the type of this relocation.
+ ///
+ /// This is for display purposes only.
+ error_code getTypeName(SmallVectorImpl<char> &Result) const;
+ error_code getAdditionalInfo(int64_t &Result) const;
+
+ /// @brief Get a string that represents the calculation of the value of this
+ /// relocation.
+ ///
+ /// This is for display purposes only.
+ error_code getValueString(SmallVectorImpl<char> &Result) const;
+
+ DataRefImpl getRawDataRefImpl() const;
+};
+typedef content_iterator<RelocationRef> relocation_iterator;
+
+/// SectionRef - This is a value type class that represents a single section in
+/// the list of sections in the object file.
+class SectionRef {
+ friend class SymbolRef;
+ DataRefImpl SectionPimpl;
+ const ObjectFile *OwningObject;
+
+public:
+ SectionRef() : OwningObject(NULL) { }
+
+ SectionRef(DataRefImpl SectionP, const ObjectFile *Owner);
+
+ bool operator==(const SectionRef &Other) const;
+ bool operator <(const SectionRef &Other) const;
+
+ error_code getNext(SectionRef &Result) const;
+
+ error_code getName(StringRef &Result) const;
+ error_code getAddress(uint64_t &Result) const;
+ error_code getSize(uint64_t &Result) const;
+ error_code getContents(StringRef &Result) const;
+
+ /// @brief Get the alignment of this section as the actual value (not log 2).
+ error_code getAlignment(uint64_t &Result) const;
+
+ // FIXME: Move to the normalization layer when it's created.
+ error_code isText(bool &Result) const;
+ error_code isData(bool &Result) const;
+ error_code isBSS(bool &Result) const;
+ error_code isRequiredForExecution(bool &Result) const;
+ error_code isVirtual(bool &Result) const;
+ error_code isZeroInit(bool &Result) const;
+
+ error_code containsSymbol(SymbolRef S, bool &Result) const;
+
+ relocation_iterator begin_relocations() const;
+ relocation_iterator end_relocations() const;
+
+ DataRefImpl getRawDataRefImpl() const;
+};
+typedef content_iterator<SectionRef> section_iterator;
+
+/// SymbolRef - This is a value type class that represents a single symbol in
+/// the list of symbols in the object file.
+class SymbolRef {
+ friend class SectionRef;
+ DataRefImpl SymbolPimpl;
+ const ObjectFile *OwningObject;
+
+public:
+ SymbolRef() : OwningObject(NULL) { }
+
+ enum Type {
+ ST_Unknown, // Type not specified
+ ST_Data,
+ ST_Debug,
+ ST_File,
+ ST_Function,
+ ST_Other
+ };
+
+ enum Flags {
+ SF_None = 0,
+ SF_Undefined = 1U << 0, // Symbol is defined in another object file
+ SF_Global = 1U << 1, // Global symbol
+ SF_Weak = 1U << 2, // Weak symbol
+ SF_Absolute = 1U << 3, // Absolute symbol
+ SF_ThreadLocal = 1U << 4, // Thread local symbol
+ SF_Common = 1U << 5, // Symbol has common linkage
+ SF_FormatSpecific = 1U << 31 // Specific to the object file format
+ // (e.g. section symbols)
+ };
+
+ SymbolRef(DataRefImpl SymbolP, const ObjectFile *Owner);
+
+ bool operator==(const SymbolRef &Other) const;
+ bool operator <(const SymbolRef &Other) const;
+
+ error_code getNext(SymbolRef &Result) const;
+
+ error_code getName(StringRef &Result) const;
+ error_code getAddress(uint64_t &Result) const;
+ error_code getFileOffset(uint64_t &Result) const;
+ error_code getSize(uint64_t &Result) const;
+ error_code getType(SymbolRef::Type &Result) const;
+
+ /// Returns the ascii char that should be displayed in a symbol table dump via
+ /// nm for this symbol.
+ error_code getNMTypeChar(char &Result) const;
+
+ /// Get symbol flags (bitwise OR of SymbolRef::Flags)
+ error_code getFlags(uint32_t &Result) const;
+
+ /// @brief Return true for common symbols such as uninitialized globals
+ error_code isCommon(bool &Result) const;
+
+ /// @brief Get section this symbol is defined in reference to. Result is
+ /// end_sections() if it is undefined or is an absolute symbol.
+ error_code getSection(section_iterator &Result) const;
+
+ DataRefImpl getRawDataRefImpl() const;
+};
+typedef content_iterator<SymbolRef> symbol_iterator;
+
+/// LibraryRef - This is a value type class that represents a single library in
+/// the list of libraries needed by a shared or dynamic object.
+class LibraryRef {
+ friend class SectionRef;
+ DataRefImpl LibraryPimpl;
+ const ObjectFile *OwningObject;
+
+public:
+ LibraryRef() : OwningObject(NULL) { }
+
+ LibraryRef(DataRefImpl LibraryP, const ObjectFile *Owner);
+
+ bool operator==(const LibraryRef &Other) const;
+ bool operator <(const LibraryRef &Other) const;
+
+ error_code getNext(LibraryRef &Result) const;
+
+ // Get the path to this library, as stored in the object file.
+ error_code getPath(StringRef &Result) const;
+
+ DataRefImpl getRawDataRefImpl() const;
+};
+typedef content_iterator<LibraryRef> library_iterator;
+
+const uint64_t UnknownAddressOrSize = ~0ULL;
+
+/// ObjectFile - This class is the base class for all object file types.
+/// Concrete instances of this object are created by createObjectFile, which
+/// figure out which type to create.
+class ObjectFile : public Binary {
+ virtual void anchor();
+ ObjectFile() LLVM_DELETED_FUNCTION;
+ ObjectFile(const ObjectFile &other) LLVM_DELETED_FUNCTION;
+
+protected:
+ ObjectFile(unsigned int Type, MemoryBuffer *source, error_code &ec);
+
+ const uint8_t *base() const {
+ return reinterpret_cast<const uint8_t *>(Data->getBufferStart());
+ }
+
+ // These functions are for SymbolRef to call internally. The main goal of
+ // this is to allow SymbolRef::SymbolPimpl to point directly to the symbol
+ // entry in the memory mapped object file. SymbolPimpl cannot contain any
+ // virtual functions because then it could not point into the memory mapped
+ // file.
+ //
+ // Implementations assume that the DataRefImpl is valid and has not been
+ // modified externally. It's UB otherwise.
+ friend class SymbolRef;
+ virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const = 0;
+ virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const = 0;
+ virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const =0;
+ virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) const =0;
+ virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const = 0;
+ virtual error_code getSymbolType(DataRefImpl Symb,
+ SymbolRef::Type &Res) const = 0;
+ virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const = 0;
+ virtual error_code getSymbolFlags(DataRefImpl Symb,
+ uint32_t &Res) const = 0;
+ virtual error_code getSymbolSection(DataRefImpl Symb,
+ section_iterator &Res) const = 0;
+
+ // Same as above for SectionRef.
+ friend class SectionRef;
+ virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const = 0;
+ virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const = 0;
+ virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const =0;
+ virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const = 0;
+ virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res)const=0;
+ virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res)const=0;
+ virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const = 0;
+ virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const = 0;
+ virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const = 0;
+ virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
+ bool &Res) const = 0;
+ // A section is 'virtual' if its contents aren't present in the object image.
+ virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const = 0;
+ virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const = 0;
+ virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
+ bool &Result) const = 0;
+ virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const = 0;
+ virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const = 0;
+
+
+ // Same as above for RelocationRef.
+ friend class RelocationRef;
+ virtual error_code getRelocationNext(DataRefImpl Rel,
+ RelocationRef &Res) const = 0;
+ virtual error_code getRelocationAddress(DataRefImpl Rel,
+ uint64_t &Res) const =0;
+ virtual error_code getRelocationOffset(DataRefImpl Rel,
+ uint64_t &Res) const =0;
+ virtual error_code getRelocationSymbol(DataRefImpl Rel,
+ SymbolRef &Res) const = 0;
+ virtual error_code getRelocationType(DataRefImpl Rel,
+ uint64_t &Res) const = 0;
+ virtual error_code getRelocationTypeName(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const = 0;
+ virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
+ int64_t &Res) const = 0;
+ virtual error_code getRelocationValueString(DataRefImpl Rel,
+ SmallVectorImpl<char> &Result) const = 0;
+ virtual error_code getRelocationHidden(DataRefImpl Rel, bool &Result) const {
+ Result = false;
+ return object_error::success;
+ }
+
+ // Same for LibraryRef
+ friend class LibraryRef;
+ virtual error_code getLibraryNext(DataRefImpl Lib, LibraryRef &Res) const = 0;
+ virtual error_code getLibraryPath(DataRefImpl Lib, StringRef &Res) const = 0;
+
+public:
+
+ virtual symbol_iterator begin_symbols() const = 0;
+ virtual symbol_iterator end_symbols() const = 0;
+
+ virtual symbol_iterator begin_dynamic_symbols() const = 0;
+ virtual symbol_iterator end_dynamic_symbols() const = 0;
+
+ virtual section_iterator begin_sections() const = 0;
+ virtual section_iterator end_sections() const = 0;
+
+ virtual library_iterator begin_libraries_needed() const = 0;
+ virtual library_iterator end_libraries_needed() const = 0;
+
+ /// @brief The number of bytes used to represent an address in this object
+ /// file format.
+ virtual uint8_t getBytesInAddress() const = 0;
+
+ virtual StringRef getFileFormatName() const = 0;
+ virtual /* Triple::ArchType */ unsigned getArch() const = 0;
+
+ /// For shared objects, returns the name which this object should be
+ /// loaded from at runtime. This corresponds to DT_SONAME on ELF and
+ /// LC_ID_DYLIB (install name) on MachO.
+ virtual StringRef getLoadName() const = 0;
+
+ /// @returns Pointer to ObjectFile subclass to handle this type of object.
+ /// @param ObjectPath The path to the object file. ObjectPath.isObject must
+ /// return true.
+ /// @brief Create ObjectFile from path.
+ static ObjectFile *createObjectFile(StringRef ObjectPath);
+ static ObjectFile *createObjectFile(MemoryBuffer *Object);
+
+ static inline bool classof(const Binary *v) {
+ return v->isObject();
+ }
+ static inline bool classof(const ObjectFile *v) { return true; }
+
+public:
+ static ObjectFile *createCOFFObjectFile(MemoryBuffer *Object);
+ static ObjectFile *createELFObjectFile(MemoryBuffer *Object);
+ static ObjectFile *createMachOObjectFile(MemoryBuffer *Object);
+};
+
+// Inline function definitions.
+inline SymbolRef::SymbolRef(DataRefImpl SymbolP, const ObjectFile *Owner)
+ : SymbolPimpl(SymbolP)
+ , OwningObject(Owner) {}
+
+inline bool SymbolRef::operator==(const SymbolRef &Other) const {
+ return SymbolPimpl == Other.SymbolPimpl;
+}
+
+inline bool SymbolRef::operator <(const SymbolRef &Other) const {
+ return SymbolPimpl < Other.SymbolPimpl;
+}
+
+inline error_code SymbolRef::getNext(SymbolRef &Result) const {
+ return OwningObject->getSymbolNext(SymbolPimpl, Result);
+}
+
+inline error_code SymbolRef::getName(StringRef &Result) const {
+ return OwningObject->getSymbolName(SymbolPimpl, Result);
+}
+
+inline error_code SymbolRef::getAddress(uint64_t &Result) const {
+ return OwningObject->getSymbolAddress(SymbolPimpl, Result);
+}
+
+inline error_code SymbolRef::getFileOffset(uint64_t &Result) const {
+ return OwningObject->getSymbolFileOffset(SymbolPimpl, Result);
+}
+
+inline error_code SymbolRef::getSize(uint64_t &Result) const {
+ return OwningObject->getSymbolSize(SymbolPimpl, Result);
+}
+
+inline error_code SymbolRef::getNMTypeChar(char &Result) const {
+ return OwningObject->getSymbolNMTypeChar(SymbolPimpl, Result);
+}
+
+inline error_code SymbolRef::getFlags(uint32_t &Result) const {
+ return OwningObject->getSymbolFlags(SymbolPimpl, Result);
+}
+
+inline error_code SymbolRef::getSection(section_iterator &Result) const {
+ return OwningObject->getSymbolSection(SymbolPimpl, Result);
+}
+
+inline error_code SymbolRef::getType(SymbolRef::Type &Result) const {
+ return OwningObject->getSymbolType(SymbolPimpl, Result);
+}
+
+inline DataRefImpl SymbolRef::getRawDataRefImpl() const {
+ return SymbolPimpl;
+}
+
+
+/// SectionRef
+inline SectionRef::SectionRef(DataRefImpl SectionP,
+ const ObjectFile *Owner)
+ : SectionPimpl(SectionP)
+ , OwningObject(Owner) {}
+
+inline bool SectionRef::operator==(const SectionRef &Other) const {
+ return SectionPimpl == Other.SectionPimpl;
+}
+
+inline bool SectionRef::operator <(const SectionRef &Other) const {
+ return SectionPimpl < Other.SectionPimpl;
+}
+
+inline error_code SectionRef::getNext(SectionRef &Result) const {
+ return OwningObject->getSectionNext(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::getName(StringRef &Result) const {
+ return OwningObject->getSectionName(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::getAddress(uint64_t &Result) const {
+ return OwningObject->getSectionAddress(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::getSize(uint64_t &Result) const {
+ return OwningObject->getSectionSize(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::getContents(StringRef &Result) const {
+ return OwningObject->getSectionContents(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::getAlignment(uint64_t &Result) const {
+ return OwningObject->getSectionAlignment(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::isText(bool &Result) const {
+ return OwningObject->isSectionText(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::isData(bool &Result) const {
+ return OwningObject->isSectionData(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::isBSS(bool &Result) const {
+ return OwningObject->isSectionBSS(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::isRequiredForExecution(bool &Result) const {
+ return OwningObject->isSectionRequiredForExecution(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::isVirtual(bool &Result) const {
+ return OwningObject->isSectionVirtual(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::isZeroInit(bool &Result) const {
+ return OwningObject->isSectionZeroInit(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::containsSymbol(SymbolRef S, bool &Result) const {
+ return OwningObject->sectionContainsSymbol(SectionPimpl, S.SymbolPimpl,
+ Result);
+}
+
+inline relocation_iterator SectionRef::begin_relocations() const {
+ return OwningObject->getSectionRelBegin(SectionPimpl);
+}
+
+inline relocation_iterator SectionRef::end_relocations() const {
+ return OwningObject->getSectionRelEnd(SectionPimpl);
+}
+
+inline DataRefImpl SectionRef::getRawDataRefImpl() const {
+ return SectionPimpl;
+}
+
+/// RelocationRef
+inline RelocationRef::RelocationRef(DataRefImpl RelocationP,
+ const ObjectFile *Owner)
+ : RelocationPimpl(RelocationP)
+ , OwningObject(Owner) {}
+
+inline bool RelocationRef::operator==(const RelocationRef &Other) const {
+ return RelocationPimpl == Other.RelocationPimpl;
+}
+
+inline error_code RelocationRef::getNext(RelocationRef &Result) const {
+ return OwningObject->getRelocationNext(RelocationPimpl, Result);
+}
+
+inline error_code RelocationRef::getAddress(uint64_t &Result) const {
+ return OwningObject->getRelocationAddress(RelocationPimpl, Result);
+}
+
+inline error_code RelocationRef::getOffset(uint64_t &Result) const {
+ return OwningObject->getRelocationOffset(RelocationPimpl, Result);
+}
+
+inline error_code RelocationRef::getSymbol(SymbolRef &Result) const {
+ return OwningObject->getRelocationSymbol(RelocationPimpl, Result);
+}
+
+inline error_code RelocationRef::getType(uint64_t &Result) const {
+ return OwningObject->getRelocationType(RelocationPimpl, Result);
+}
+
+inline error_code RelocationRef::getTypeName(SmallVectorImpl<char> &Result)
+ const {
+ return OwningObject->getRelocationTypeName(RelocationPimpl, Result);
+}
+
+inline error_code RelocationRef::getAdditionalInfo(int64_t &Result) const {
+ return OwningObject->getRelocationAdditionalInfo(RelocationPimpl, Result);
+}
+
+inline error_code RelocationRef::getValueString(SmallVectorImpl<char> &Result)
+ const {
+ return OwningObject->getRelocationValueString(RelocationPimpl, Result);
+}
+
+inline error_code RelocationRef::getHidden(bool &Result) const {
+ return OwningObject->getRelocationHidden(RelocationPimpl, Result);
+}
+
+inline DataRefImpl RelocationRef::getRawDataRefImpl() const {
+ return RelocationPimpl;
+}
+
+// Inline function definitions.
+inline LibraryRef::LibraryRef(DataRefImpl LibraryP, const ObjectFile *Owner)
+ : LibraryPimpl(LibraryP)
+ , OwningObject(Owner) {}
+
+inline bool LibraryRef::operator==(const LibraryRef &Other) const {
+ return LibraryPimpl == Other.LibraryPimpl;
+}
+
+inline bool LibraryRef::operator <(const LibraryRef &Other) const {
+ return LibraryPimpl < Other.LibraryPimpl;
+}
+
+inline error_code LibraryRef::getNext(LibraryRef &Result) const {
+ return OwningObject->getLibraryNext(LibraryPimpl, Result);
+}
+
+inline error_code LibraryRef::getPath(StringRef &Result) const {
+ return OwningObject->getLibraryPath(LibraryPimpl, Result);
+}
+
+} // end namespace object
+} // end namespace llvm
+
+#endif
diff --git a/include/llvm/OperandTraits.h b/include/llvm/OperandTraits.h
new file mode 100644
index 00000000000..3d8dc329b39
--- /dev/null
+++ b/include/llvm/OperandTraits.h
@@ -0,0 +1,160 @@
+//===-- llvm/OperandTraits.h - OperandTraits class definition ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the traits classes that are handy for enforcing the correct
+// layout of various User subclasses. It also provides the means for accessing
+// the operands in the most efficient manner.
+//
+
+#ifndef LLVM_OPERAND_TRAITS_H
+#define LLVM_OPERAND_TRAITS_H
+
+#include "llvm/User.h"
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// FixedNumOperand Trait Class
+//===----------------------------------------------------------------------===//
+
+/// FixedNumOperandTraits - determine the allocation regime of the Use array
+/// when it is a prefix to the User object, and the number of Use objects is
+/// known at compile time.
+
+template <typename SubClass, unsigned ARITY>
+struct FixedNumOperandTraits {
+ static Use *op_begin(SubClass* U) {
+ return reinterpret_cast<Use*>(U) - ARITY;
+ }
+ static Use *op_end(SubClass* U) {
+ return reinterpret_cast<Use*>(U);
+ }
+ static unsigned operands(const User*) {
+ return ARITY;
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// OptionalOperand Trait Class
+//===----------------------------------------------------------------------===//
+
+/// OptionalOperandTraits - when the number of operands may change at runtime.
+/// Naturally it may only decrease, because the allocations may not change.
+
+template <typename SubClass, unsigned ARITY = 1>
+struct OptionalOperandTraits : public FixedNumOperandTraits<SubClass, ARITY> {
+ static unsigned operands(const User *U) {
+ return U->getNumOperands();
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// VariadicOperand Trait Class
+//===----------------------------------------------------------------------===//
+
+/// VariadicOperandTraits - determine the allocation regime of the Use array
+/// when it is a prefix to the User object, and the number of Use objects is
+/// only known at allocation time.
+
+template <typename SubClass, unsigned MINARITY = 0>
+struct VariadicOperandTraits {
+ static Use *op_begin(SubClass* U) {
+ return reinterpret_cast<Use*>(U) - static_cast<User*>(U)->getNumOperands();
+ }
+ static Use *op_end(SubClass* U) {
+ return reinterpret_cast<Use*>(U);
+ }
+ static unsigned operands(const User *U) {
+ return U->getNumOperands();
+ }
+};
+
+//===----------------------------------------------------------------------===//
+// HungoffOperand Trait Class
+//===----------------------------------------------------------------------===//
+
+/// HungoffOperandTraits - determine the allocation regime of the Use array
+/// when it is not a prefix to the User object, but allocated at an unrelated
+/// heap address.
+/// Assumes that the User subclass that is determined by this traits class
+/// has an OperandList member of type User::op_iterator. [Note: this is now
+/// trivially satisfied, because User has that member for historic reasons.]
+///
+/// This is the traits class that is needed when the Use array must be
+/// resizable.
+
+template <unsigned MINARITY = 1>
+struct HungoffOperandTraits {
+ static Use *op_begin(User* U) {
+ return U->OperandList;
+ }
+ static Use *op_end(User* U) {
+ return U->OperandList + U->getNumOperands();
+ }
+ static unsigned operands(const User *U) {
+ return U->getNumOperands();
+ }
+};
+
+/// Macro for generating in-class operand accessor declarations.
+/// It should only be called in the public section of the interface.
+///
+#define DECLARE_TRANSPARENT_OPERAND_ACCESSORS(VALUECLASS) \
+ public: \
+ inline VALUECLASS *getOperand(unsigned) const; \
+ inline void setOperand(unsigned, VALUECLASS*); \
+ inline op_iterator op_begin(); \
+ inline const_op_iterator op_begin() const; \
+ inline op_iterator op_end(); \
+ inline const_op_iterator op_end() const; \
+ protected: \
+ template <int> inline Use &Op(); \
+ template <int> inline const Use &Op() const; \
+ public: \
+ inline unsigned getNumOperands() const
+
+/// Macro for generating out-of-class operand accessor definitions
+#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS) \
+CLASS::op_iterator CLASS::op_begin() { \
+ return OperandTraits<CLASS>::op_begin(this); \
+} \
+CLASS::const_op_iterator CLASS::op_begin() const { \
+ return OperandTraits<CLASS>::op_begin(const_cast<CLASS*>(this)); \
+} \
+CLASS::op_iterator CLASS::op_end() { \
+ return OperandTraits<CLASS>::op_end(this); \
+} \
+CLASS::const_op_iterator CLASS::op_end() const { \
+ return OperandTraits<CLASS>::op_end(const_cast<CLASS*>(this)); \
+} \
+VALUECLASS *CLASS::getOperand(unsigned i_nocapture) const { \
+ assert(i_nocapture < OperandTraits<CLASS>::operands(this) \
+ && "getOperand() out of range!"); \
+ return cast_or_null<VALUECLASS>( \
+ OperandTraits<CLASS>::op_begin(const_cast<CLASS*>(this))[i_nocapture].get()); \
+} \
+void CLASS::setOperand(unsigned i_nocapture, VALUECLASS *Val_nocapture) { \
+ assert(i_nocapture < OperandTraits<CLASS>::operands(this) \
+ && "setOperand() out of range!"); \
+ OperandTraits<CLASS>::op_begin(this)[i_nocapture] = Val_nocapture; \
+} \
+unsigned CLASS::getNumOperands() const { \
+ return OperandTraits<CLASS>::operands(this); \
+} \
+template <int Idx_nocapture> Use &CLASS::Op() { \
+ return this->OpFrom<Idx_nocapture>(this); \
+} \
+template <int Idx_nocapture> const Use &CLASS::Op() const { \
+ return this->OpFrom<Idx_nocapture>(this); \
+}
+
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Operator.h b/include/llvm/Operator.h
new file mode 100644
index 00000000000..cf6d8e2c379
--- /dev/null
+++ b/include/llvm/Operator.h
@@ -0,0 +1,326 @@
+//===-- llvm/Operator.h - Operator utility subclass -------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines various classes for working with Instructions and
+// ConstantExprs.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_OPERATOR_H
+#define LLVM_OPERATOR_H
+
+#include "llvm/Constants.h"
+#include "llvm/Instruction.h"
+#include "llvm/Type.h"
+
+namespace llvm {
+
+class GetElementPtrInst;
+class BinaryOperator;
+class ConstantExpr;
+
+/// Operator - This is a utility class that provides an abstraction for the
+/// common functionality between Instructions and ConstantExprs.
+///
+class Operator : public User {
+private:
+ // Do not implement any of these. The Operator class is intended to be used
+ // as a utility, and is never itself instantiated.
+ void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
+ void *operator new(size_t s) LLVM_DELETED_FUNCTION;
+ Operator() LLVM_DELETED_FUNCTION;
+ ~Operator() LLVM_DELETED_FUNCTION;
+
+public:
+ /// getOpcode - Return the opcode for this Instruction or ConstantExpr.
+ ///
+ unsigned getOpcode() const {
+ if (const Instruction *I = dyn_cast<Instruction>(this))
+ return I->getOpcode();
+ return cast<ConstantExpr>(this)->getOpcode();
+ }
+
+ /// getOpcode - If V is an Instruction or ConstantExpr, return its
+ /// opcode. Otherwise return UserOp1.
+ ///
+ static unsigned getOpcode(const Value *V) {
+ if (const Instruction *I = dyn_cast<Instruction>(V))
+ return I->getOpcode();
+ if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
+ return CE->getOpcode();
+ return Instruction::UserOp1;
+ }
+
+ static inline bool classof(const Operator *) { return true; }
+ static inline bool classof(const Instruction *) { return true; }
+ static inline bool classof(const ConstantExpr *) { return true; }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) || isa<ConstantExpr>(V);
+ }
+};
+
+/// OverflowingBinaryOperator - Utility class for integer arithmetic operators
+/// which may exhibit overflow - Add, Sub, and Mul. It does not include SDiv,
+/// despite that operator having the potential for overflow.
+///
+class OverflowingBinaryOperator : public Operator {
+public:
+ enum {
+ NoUnsignedWrap = (1 << 0),
+ NoSignedWrap = (1 << 1)
+ };
+
+private:
+ ~OverflowingBinaryOperator() LLVM_DELETED_FUNCTION;
+
+ friend class BinaryOperator;
+ friend class ConstantExpr;
+ void setHasNoUnsignedWrap(bool B) {
+ SubclassOptionalData =
+ (SubclassOptionalData & ~NoUnsignedWrap) | (B * NoUnsignedWrap);
+ }
+ void setHasNoSignedWrap(bool B) {
+ SubclassOptionalData =
+ (SubclassOptionalData & ~NoSignedWrap) | (B * NoSignedWrap);
+ }
+
+public:
+ /// hasNoUnsignedWrap - Test whether this operation is known to never
+ /// undergo unsigned overflow, aka the nuw property.
+ bool hasNoUnsignedWrap() const {
+ return SubclassOptionalData & NoUnsignedWrap;
+ }
+
+ /// hasNoSignedWrap - Test whether this operation is known to never
+ /// undergo signed overflow, aka the nsw property.
+ bool hasNoSignedWrap() const {
+ return (SubclassOptionalData & NoSignedWrap) != 0;
+ }
+
+ static inline bool classof(const OverflowingBinaryOperator *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Instruction::Add ||
+ I->getOpcode() == Instruction::Sub ||
+ I->getOpcode() == Instruction::Mul ||
+ I->getOpcode() == Instruction::Shl;
+ }
+ static inline bool classof(const ConstantExpr *CE) {
+ return CE->getOpcode() == Instruction::Add ||
+ CE->getOpcode() == Instruction::Sub ||
+ CE->getOpcode() == Instruction::Mul ||
+ CE->getOpcode() == Instruction::Shl;
+ }
+ static inline bool classof(const Value *V) {
+ return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
+ (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
+ }
+};
+
+/// PossiblyExactOperator - A udiv or sdiv instruction, which can be marked as
+/// "exact", indicating that no bits are destroyed.
+class PossiblyExactOperator : public Operator {
+public:
+ enum {
+ IsExact = (1 << 0)
+ };
+
+private:
+ ~PossiblyExactOperator() LLVM_DELETED_FUNCTION;
+
+ friend class BinaryOperator;
+ friend class ConstantExpr;
+ void setIsExact(bool B) {
+ SubclassOptionalData = (SubclassOptionalData & ~IsExact) | (B * IsExact);
+ }
+
+public:
+ /// isExact - Test whether this division is known to be exact, with
+ /// zero remainder.
+ bool isExact() const {
+ return SubclassOptionalData & IsExact;
+ }
+
+ static bool isPossiblyExactOpcode(unsigned OpC) {
+ return OpC == Instruction::SDiv ||
+ OpC == Instruction::UDiv ||
+ OpC == Instruction::AShr ||
+ OpC == Instruction::LShr;
+ }
+ static inline bool classof(const ConstantExpr *CE) {
+ return isPossiblyExactOpcode(CE->getOpcode());
+ }
+ static inline bool classof(const Instruction *I) {
+ return isPossiblyExactOpcode(I->getOpcode());
+ }
+ static inline bool classof(const Value *V) {
+ return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
+ (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
+ }
+};
+
+/// FPMathOperator - Utility class for floating point operations which can have
+/// information about relaxed accuracy requirements attached to them.
+class FPMathOperator : public Operator {
+private:
+ ~FPMathOperator() LLVM_DELETED_FUNCTION;
+
+public:
+
+ /// \brief Get the maximum error permitted by this operation in ULPs. An
+ /// accuracy of 0.0 means that the operation should be performed with the
+ /// default precision.
+ float getFPAccuracy() const;
+
+ static inline bool classof(const FPMathOperator *) { return true; }
+ static inline bool classof(const Instruction *I) {
+ return I->getType()->isFPOrFPVectorTy();
+ }
+ static inline bool classof(const Value *V) {
+ return isa<Instruction>(V) && classof(cast<Instruction>(V));
+ }
+};
+
+
+/// ConcreteOperator - A helper template for defining operators for individual
+/// opcodes.
+template<typename SuperClass, unsigned Opc>
+class ConcreteOperator : public SuperClass {
+ ~ConcreteOperator() LLVM_DELETED_FUNCTION;
+public:
+ static inline bool classof(const ConcreteOperator<SuperClass, Opc> *) {
+ return true;
+ }
+ static inline bool classof(const Instruction *I) {
+ return I->getOpcode() == Opc;
+ }
+ static inline bool classof(const ConstantExpr *CE) {
+ return CE->getOpcode() == Opc;
+ }
+ static inline bool classof(const Value *V) {
+ return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
+ (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
+ }
+};
+
+class AddOperator
+ : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Add> {
+ ~AddOperator() LLVM_DELETED_FUNCTION;
+};
+class SubOperator
+ : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Sub> {
+ ~SubOperator() LLVM_DELETED_FUNCTION;
+};
+class MulOperator
+ : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Mul> {
+ ~MulOperator() LLVM_DELETED_FUNCTION;
+};
+class ShlOperator
+ : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Shl> {
+ ~ShlOperator() LLVM_DELETED_FUNCTION;
+};
+
+
+class SDivOperator
+ : public ConcreteOperator<PossiblyExactOperator, Instruction::SDiv> {
+ ~SDivOperator() LLVM_DELETED_FUNCTION;
+};
+class UDivOperator
+ : public ConcreteOperator<PossiblyExactOperator, Instruction::UDiv> {
+ ~UDivOperator() LLVM_DELETED_FUNCTION;
+};
+class AShrOperator
+ : public ConcreteOperator<PossiblyExactOperator, Instruction::AShr> {
+ ~AShrOperator() LLVM_DELETED_FUNCTION;
+};
+class LShrOperator
+ : public ConcreteOperator<PossiblyExactOperator, Instruction::LShr> {
+ ~LShrOperator() LLVM_DELETED_FUNCTION;
+};
+
+
+
+class GEPOperator
+ : public ConcreteOperator<Operator, Instruction::GetElementPtr> {
+ ~GEPOperator() LLVM_DELETED_FUNCTION;
+
+ enum {
+ IsInBounds = (1 << 0)
+ };
+
+ friend class GetElementPtrInst;
+ friend class ConstantExpr;
+ void setIsInBounds(bool B) {
+ SubclassOptionalData =
+ (SubclassOptionalData & ~IsInBounds) | (B * IsInBounds);
+ }
+
+public:
+ /// isInBounds - Test whether this is an inbounds GEP, as defined
+ /// by LangRef.html.
+ bool isInBounds() const {
+ return SubclassOptionalData & IsInBounds;
+ }
+
+ inline op_iterator idx_begin() { return op_begin()+1; }
+ inline const_op_iterator idx_begin() const { return op_begin()+1; }
+ inline op_iterator idx_end() { return op_end(); }
+ inline const_op_iterator idx_end() const { return op_end(); }
+
+ Value *getPointerOperand() {
+ return getOperand(0);
+ }
+ const Value *getPointerOperand() const {
+ return getOperand(0);
+ }
+ static unsigned getPointerOperandIndex() {
+ return 0U; // get index for modifying correct operand
+ }
+
+ /// getPointerOperandType - Method to return the pointer operand as a
+ /// PointerType.
+ Type *getPointerOperandType() const {
+ return getPointerOperand()->getType();
+ }
+
+ unsigned getNumIndices() const { // Note: always non-negative
+ return getNumOperands() - 1;
+ }
+
+ bool hasIndices() const {
+ return getNumOperands() > 1;
+ }
+
+ /// hasAllZeroIndices - Return true if all of the indices of this GEP are
+ /// zeros. If so, the result pointer and the first operand have the same
+ /// value, just potentially different types.
+ bool hasAllZeroIndices() const {
+ for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
+ if (ConstantInt *C = dyn_cast<ConstantInt>(I))
+ if (C->isZero())
+ continue;
+ return false;
+ }
+ return true;
+ }
+
+ /// hasAllConstantIndices - Return true if all of the indices of this GEP are
+ /// constant integers. If so, the result pointer and the first operand have
+ /// a constant offset between them.
+ bool hasAllConstantIndices() const {
+ for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
+ if (!isa<ConstantInt>(I))
+ return false;
+ }
+ return true;
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Pass.h b/include/llvm/Pass.h
new file mode 100644
index 00000000000..cd651db1f1c
--- /dev/null
+++ b/include/llvm/Pass.h
@@ -0,0 +1,376 @@
+//===- llvm/Pass.h - Base class for Passes ----------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines a base class that indicates that a specified class is a
+// transformation pass implementation.
+//
+// Passes are designed this way so that it is possible to run passes in a cache
+// and organizationally optimal order without having to specify it at the front
+// end. This allows arbitrary passes to be strung together and have them
+// executed as efficiently as possible.
+//
+// Passes should extend one of the classes below, depending on the guarantees
+// that it can make about what will be modified as it is run. For example, most
+// global optimizations should derive from FunctionPass, because they do not add
+// or delete functions, they operate on the internals of the function.
+//
+// Note that this file #includes PassSupport.h and PassAnalysisSupport.h (at the
+// bottom), so the APIs exposed by these files are also automatically available
+// to all users of this file.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_PASS_H
+#define LLVM_PASS_H
+
+#include "llvm/Support/Compiler.h"
+#include <string>
+
+namespace llvm {
+
+class BasicBlock;
+class Function;
+class Module;
+class AnalysisUsage;
+class PassInfo;
+class ImmutablePass;
+class PMStack;
+class AnalysisResolver;
+class PMDataManager;
+class raw_ostream;
+class StringRef;
+
+// AnalysisID - Use the PassInfo to identify a pass...
+typedef const void* AnalysisID;
+
+/// Different types of internal pass managers. External pass managers
+/// (PassManager and FunctionPassManager) are not represented here.
+/// Ordering of pass manager types is important here.
+enum PassManagerType {
+ PMT_Unknown = 0,
+ PMT_ModulePassManager = 1, ///< MPPassManager
+ PMT_CallGraphPassManager, ///< CGPassManager
+ PMT_FunctionPassManager, ///< FPPassManager
+ PMT_LoopPassManager, ///< LPPassManager
+ PMT_RegionPassManager, ///< RGPassManager
+ PMT_BasicBlockPassManager, ///< BBPassManager
+ PMT_Last
+};
+
+// Different types of passes.
+enum PassKind {
+ PT_BasicBlock,
+ PT_Region,
+ PT_Loop,
+ PT_Function,
+ PT_CallGraphSCC,
+ PT_Module,
+ PT_PassManager
+};
+
+//===----------------------------------------------------------------------===//
+/// Pass interface - Implemented by all 'passes'. Subclass this if you are an
+/// interprocedural optimization or you do not fit into any of the more
+/// constrained passes described below.
+///
+class Pass {
+ AnalysisResolver *Resolver; // Used to resolve analysis
+ const void *PassID;
+ PassKind Kind;
+ void operator=(const Pass&) LLVM_DELETED_FUNCTION;
+ Pass(const Pass &) LLVM_DELETED_FUNCTION;
+
+public:
+ explicit Pass(PassKind K, char &pid) : Resolver(0), PassID(&pid), Kind(K) { }
+ virtual ~Pass();
+
+
+ PassKind getPassKind() const { return Kind; }
+
+ /// getPassName - Return a nice clean name for a pass. This usually
+ /// implemented in terms of the name that is registered by one of the
+ /// Registration templates, but can be overloaded directly.
+ ///
+ virtual const char *getPassName() const;
+
+ /// getPassID - Return the PassID number that corresponds to this pass.
+ AnalysisID getPassID() const {
+ return PassID;
+ }
+
+ /// print - Print out the internal state of the pass. This is called by
+ /// Analyze to print out the contents of an analysis. Otherwise it is not
+ /// necessary to implement this method. Beware that the module pointer MAY be
+ /// null. This automatically forwards to a virtual function that does not
+ /// provide the Module* in case the analysis doesn't need it it can just be
+ /// ignored.
+ ///
+ virtual void print(raw_ostream &O, const Module *M) const;
+ void dump() const; // dump - Print to stderr.
+
+ /// createPrinterPass - Get a Pass appropriate to print the IR this
+ /// pass operates on (Module, Function or MachineFunction).
+ virtual Pass *createPrinterPass(raw_ostream &O,
+ const std::string &Banner) const = 0;
+
+ /// Each pass is responsible for assigning a pass manager to itself.
+ /// PMS is the stack of available pass manager.
+ virtual void assignPassManager(PMStack &,
+ PassManagerType) {}
+ /// Check if available pass managers are suitable for this pass or not.
+ virtual void preparePassManager(PMStack &);
+
+ /// Return what kind of Pass Manager can manage this pass.
+ virtual PassManagerType getPotentialPassManagerType() const;
+
+ // Access AnalysisResolver
+ void setResolver(AnalysisResolver *AR);
+ AnalysisResolver *getResolver() const { return Resolver; }
+
+ /// getAnalysisUsage - This function should be overriden by passes that need
+ /// analysis information to do their job. If a pass specifies that it uses a
+ /// particular analysis result to this function, it can then use the
+ /// getAnalysis<AnalysisType>() function, below.
+ ///
+ virtual void getAnalysisUsage(AnalysisUsage &) const;
+
+ /// releaseMemory() - This member can be implemented by a pass if it wants to
+ /// be able to release its memory when it is no longer needed. The default
+ /// behavior of passes is to hold onto memory for the entire duration of their
+ /// lifetime (which is the entire compile time). For pipelined passes, this
+ /// is not a big deal because that memory gets recycled every time the pass is
+ /// invoked on another program unit. For IP passes, it is more important to
+ /// free memory when it is unused.
+ ///
+ /// Optionally implement this function to release pass memory when it is no
+ /// longer used.
+ ///
+ virtual void releaseMemory();
+
+ /// getAdjustedAnalysisPointer - This method is used when a pass implements
+ /// an analysis interface through multiple inheritance. If needed, it should
+ /// override this to adjust the this pointer as needed for the specified pass
+ /// info.
+ virtual void *getAdjustedAnalysisPointer(AnalysisID ID);
+ virtual ImmutablePass *getAsImmutablePass();
+ virtual PMDataManager *getAsPMDataManager();
+
+ /// verifyAnalysis() - This member can be implemented by a analysis pass to
+ /// check state of analysis information.
+ virtual void verifyAnalysis() const;
+
+ // dumpPassStructure - Implement the -debug-passes=PassStructure option
+ virtual void dumpPassStructure(unsigned Offset = 0);
+
+ // lookupPassInfo - Return the pass info object for the specified pass class,
+ // or null if it is not known.
+ static const PassInfo *lookupPassInfo(const void *TI);
+
+ // lookupPassInfo - Return the pass info object for the pass with the given
+ // argument string, or null if it is not known.
+ static const PassInfo *lookupPassInfo(StringRef Arg);
+
+ // createPass - Create a object for the specified pass class,
+ // or null if it is not known.
+ static Pass *createPass(AnalysisID ID);
+
+ /// getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to
+ /// get analysis information that might be around, for example to update it.
+ /// This is different than getAnalysis in that it can fail (if the analysis
+ /// results haven't been computed), so should only be used if you can handle
+ /// the case when the analysis is not available. This method is often used by
+ /// transformation APIs to update analysis results for a pass automatically as
+ /// the transform is performed.
+ ///
+ template<typename AnalysisType> AnalysisType *
+ getAnalysisIfAvailable() const; // Defined in PassAnalysisSupport.h
+
+ /// mustPreserveAnalysisID - This method serves the same function as
+ /// getAnalysisIfAvailable, but works if you just have an AnalysisID. This
+ /// obviously cannot give you a properly typed instance of the class if you
+ /// don't have the class name available (use getAnalysisIfAvailable if you
+ /// do), but it can tell you if you need to preserve the pass at least.
+ ///
+ bool mustPreserveAnalysisID(char &AID) const;
+
+ /// getAnalysis<AnalysisType>() - This function is used by subclasses to get
+ /// to the analysis information that they claim to use by overriding the
+ /// getAnalysisUsage function.
+ ///
+ template<typename AnalysisType>
+ AnalysisType &getAnalysis() const; // Defined in PassAnalysisSupport.h
+
+ template<typename AnalysisType>
+ AnalysisType &getAnalysis(Function &F); // Defined in PassAnalysisSupport.h
+
+ template<typename AnalysisType>
+ AnalysisType &getAnalysisID(AnalysisID PI) const;
+
+ template<typename AnalysisType>
+ AnalysisType &getAnalysisID(AnalysisID PI, Function &F);
+};
+
+
+//===----------------------------------------------------------------------===//
+/// ModulePass class - This class is used to implement unstructured
+/// interprocedural optimizations and analyses. ModulePasses may do anything
+/// they want to the program.
+///
+class ModulePass : public Pass {
+public:
+ /// createPrinterPass - Get a module printer pass.
+ Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
+
+ /// runOnModule - Virtual method overriden by subclasses to process the module
+ /// being operated on.
+ virtual bool runOnModule(Module &M) = 0;
+
+ virtual void assignPassManager(PMStack &PMS,
+ PassManagerType T);
+
+ /// Return what kind of Pass Manager can manage this pass.
+ virtual PassManagerType getPotentialPassManagerType() const;
+
+ explicit ModulePass(char &pid) : Pass(PT_Module, pid) {}
+ // Force out-of-line virtual method.
+ virtual ~ModulePass();
+};
+
+
+//===----------------------------------------------------------------------===//
+/// ImmutablePass class - This class is used to provide information that does
+/// not need to be run. This is useful for things like target information and
+/// "basic" versions of AnalysisGroups.
+///
+class ImmutablePass : public ModulePass {
+public:
+ /// initializePass - This method may be overriden by immutable passes to allow
+ /// them to perform various initialization actions they require. This is
+ /// primarily because an ImmutablePass can "require" another ImmutablePass,
+ /// and if it does, the overloaded version of initializePass may get access to
+ /// these passes with getAnalysis<>.
+ ///
+ virtual void initializePass();
+
+ virtual ImmutablePass *getAsImmutablePass() { return this; }
+
+ /// ImmutablePasses are never run.
+ ///
+ bool runOnModule(Module &) { return false; }
+
+ explicit ImmutablePass(char &pid)
+ : ModulePass(pid) {}
+
+ // Force out-of-line virtual method.
+ virtual ~ImmutablePass();
+};
+
+//===----------------------------------------------------------------------===//
+/// FunctionPass class - This class is used to implement most global
+/// optimizations. Optimizations should subclass this class if they meet the
+/// following constraints:
+///
+/// 1. Optimizations are organized globally, i.e., a function at a time
+/// 2. Optimizing a function does not cause the addition or removal of any
+/// functions in the module
+///
+class FunctionPass : public Pass {
+public:
+ explicit FunctionPass(char &pid) : Pass(PT_Function, pid) {}
+
+ /// createPrinterPass - Get a function printer pass.
+ Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
+
+ /// doInitialization - Virtual method overridden by subclasses to do
+ /// any necessary per-module initialization.
+ ///
+ virtual bool doInitialization(Module &);
+
+ /// runOnFunction - Virtual method overriden by subclasses to do the
+ /// per-function processing of the pass.
+ ///
+ virtual bool runOnFunction(Function &F) = 0;
+
+ /// doFinalization - Virtual method overriden by subclasses to do any post
+ /// processing needed after all passes have run.
+ ///
+ virtual bool doFinalization(Module &);
+
+ virtual void assignPassManager(PMStack &PMS,
+ PassManagerType T);
+
+ /// Return what kind of Pass Manager can manage this pass.
+ virtual PassManagerType getPotentialPassManagerType() const;
+};
+
+
+
+//===----------------------------------------------------------------------===//
+/// BasicBlockPass class - This class is used to implement most local
+/// optimizations. Optimizations should subclass this class if they
+/// meet the following constraints:
+/// 1. Optimizations are local, operating on either a basic block or
+/// instruction at a time.
+/// 2. Optimizations do not modify the CFG of the contained function, or any
+/// other basic block in the function.
+/// 3. Optimizations conform to all of the constraints of FunctionPasses.
+///
+class BasicBlockPass : public Pass {
+public:
+ explicit BasicBlockPass(char &pid) : Pass(PT_BasicBlock, pid) {}
+
+ /// createPrinterPass - Get a basic block printer pass.
+ Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
+
+ /// doInitialization - Virtual method overridden by subclasses to do
+ /// any necessary per-module initialization.
+ ///
+ virtual bool doInitialization(Module &);
+
+ /// doInitialization - Virtual method overridden by BasicBlockPass subclasses
+ /// to do any necessary per-function initialization.
+ ///
+ virtual bool doInitialization(Function &);
+
+ /// runOnBasicBlock - Virtual method overriden by subclasses to do the
+ /// per-basicblock processing of the pass.
+ ///
+ virtual bool runOnBasicBlock(BasicBlock &BB) = 0;
+
+ /// doFinalization - Virtual method overriden by BasicBlockPass subclasses to
+ /// do any post processing needed after all passes have run.
+ ///
+ virtual bool doFinalization(Function &);
+
+ /// doFinalization - Virtual method overriden by subclasses to do any post
+ /// processing needed after all passes have run.
+ ///
+ virtual bool doFinalization(Module &);
+
+ virtual void assignPassManager(PMStack &PMS,
+ PassManagerType T);
+
+ /// Return what kind of Pass Manager can manage this pass.
+ virtual PassManagerType getPotentialPassManagerType() const;
+};
+
+/// If the user specifies the -time-passes argument on an LLVM tool command line
+/// then the value of this boolean will be true, otherwise false.
+/// @brief This is the storage for the -time-passes option.
+extern bool TimePassesIsEnabled;
+
+} // End llvm namespace
+
+// Include support files that contain important APIs commonly used by Passes,
+// but that we want to separate out to make it easier to read the header files.
+//
+#include "llvm/PassSupport.h"
+#include "llvm/PassAnalysisSupport.h"
+
+#endif
diff --git a/include/llvm/PassAnalysisSupport.h b/include/llvm/PassAnalysisSupport.h
new file mode 100644
index 00000000000..d14d73b1b14
--- /dev/null
+++ b/include/llvm/PassAnalysisSupport.h
@@ -0,0 +1,253 @@
+//===- llvm/PassAnalysisSupport.h - Analysis Pass Support code --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines stuff that is used to define and "use" Analysis Passes.
+// This file is automatically #included by Pass.h, so:
+//
+// NO .CPP FILES SHOULD INCLUDE THIS FILE DIRECTLY
+//
+// Instead, #include Pass.h
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_PASS_ANALYSIS_SUPPORT_H
+#define LLVM_PASS_ANALYSIS_SUPPORT_H
+
+#include "llvm/Pass.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+#include <vector>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// AnalysisUsage - Represent the analysis usage information of a pass. This
+// tracks analyses that the pass REQUIRES (must be available when the pass
+// runs), REQUIRES TRANSITIVE (must be available throughout the lifetime of the
+// pass), and analyses that the pass PRESERVES (the pass does not invalidate the
+// results of these analyses). This information is provided by a pass to the
+// Pass infrastructure through the getAnalysisUsage virtual function.
+//
+class AnalysisUsage {
+public:
+ typedef SmallVector<AnalysisID, 32> VectorType;
+
+private:
+ // Sets of analyses required and preserved by a pass
+ VectorType Required, RequiredTransitive, Preserved;
+ bool PreservesAll;
+
+public:
+ AnalysisUsage() : PreservesAll(false) {}
+
+ // addRequired - Add the specified ID to the required set of the usage info
+ // for a pass.
+ //
+ AnalysisUsage &addRequiredID(const void *ID);
+ AnalysisUsage &addRequiredID(char &ID);
+ template<class PassClass>
+ AnalysisUsage &addRequired() {
+ return addRequiredID(PassClass::ID);
+ }
+
+ AnalysisUsage &addRequiredTransitiveID(char &ID);
+ template<class PassClass>
+ AnalysisUsage &addRequiredTransitive() {
+ return addRequiredTransitiveID(PassClass::ID);
+ }
+
+ // addPreserved - Add the specified ID to the set of analyses preserved by
+ // this pass
+ //
+ AnalysisUsage &addPreservedID(const void *ID) {
+ Preserved.push_back(ID);
+ return *this;
+ }
+ AnalysisUsage &addPreservedID(char &ID) {
+ Preserved.push_back(&ID);
+ return *this;
+ }
+
+ // addPreserved - Add the specified Pass class to the set of analyses
+ // preserved by this pass.
+ //
+ template<class PassClass>
+ AnalysisUsage &addPreserved() {
+ Preserved.push_back(&PassClass::ID);
+ return *this;
+ }
+
+ // addPreserved - Add the Pass with the specified argument string to the set
+ // of analyses preserved by this pass. If no such Pass exists, do nothing.
+ // This can be useful when a pass is trivially preserved, but may not be
+ // linked in. Be careful about spelling!
+ //
+ AnalysisUsage &addPreserved(StringRef Arg);
+
+ // setPreservesAll - Set by analyses that do not transform their input at all
+ void setPreservesAll() { PreservesAll = true; }
+ bool getPreservesAll() const { return PreservesAll; }
+
+ /// setPreservesCFG - This function should be called by the pass, iff they do
+ /// not:
+ ///
+ /// 1. Add or remove basic blocks from the function
+ /// 2. Modify terminator instructions in any way.
+ ///
+ /// This function annotates the AnalysisUsage info object to say that analyses
+ /// that only depend on the CFG are preserved by this pass.
+ ///
+ void setPreservesCFG();
+
+ const VectorType &getRequiredSet() const { return Required; }
+ const VectorType &getRequiredTransitiveSet() const {
+ return RequiredTransitive;
+ }
+ const VectorType &getPreservedSet() const { return Preserved; }
+};
+
+//===----------------------------------------------------------------------===//
+// AnalysisResolver - Simple interface used by Pass objects to pull all
+// analysis information out of pass manager that is responsible to manage
+// the pass.
+//
+class PMDataManager;
+class AnalysisResolver {
+private:
+ AnalysisResolver() LLVM_DELETED_FUNCTION;
+
+public:
+ explicit AnalysisResolver(PMDataManager &P) : PM(P) { }
+
+ inline PMDataManager &getPMDataManager() { return PM; }
+
+ // Find pass that is implementing PI.
+ Pass *findImplPass(AnalysisID PI) {
+ Pass *ResultPass = 0;
+ for (unsigned i = 0; i < AnalysisImpls.size() ; ++i) {
+ if (AnalysisImpls[i].first == PI) {
+ ResultPass = AnalysisImpls[i].second;
+ break;
+ }
+ }
+ return ResultPass;
+ }
+
+ // Find pass that is implementing PI. Initialize pass for Function F.
+ Pass *findImplPass(Pass *P, AnalysisID PI, Function &F);
+
+ void addAnalysisImplsPair(AnalysisID PI, Pass *P) {
+ if (findImplPass(PI) == P)
+ return;
+ std::pair<AnalysisID, Pass*> pir = std::make_pair(PI,P);
+ AnalysisImpls.push_back(pir);
+ }
+
+ /// clearAnalysisImpls - Clear cache that is used to connect a pass to the
+ /// the analysis (PassInfo).
+ void clearAnalysisImpls() {
+ AnalysisImpls.clear();
+ }
+
+ // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist
+ Pass *getAnalysisIfAvailable(AnalysisID ID, bool Direction) const;
+
+private:
+ // AnalysisImpls - This keeps track of which passes implements the interfaces
+ // that are required by the current pass (to implement getAnalysis()).
+ std::vector<std::pair<AnalysisID, Pass*> > AnalysisImpls;
+
+ // PassManager that is used to resolve analysis info
+ PMDataManager &PM;
+};
+
+/// getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to
+/// get analysis information that might be around, for example to update it.
+/// This is different than getAnalysis in that it can fail (if the analysis
+/// results haven't been computed), so should only be used if you can handle
+/// the case when the analysis is not available. This method is often used by
+/// transformation APIs to update analysis results for a pass automatically as
+/// the transform is performed.
+///
+template<typename AnalysisType>
+AnalysisType *Pass::getAnalysisIfAvailable() const {
+ assert(Resolver && "Pass not resident in a PassManager object!");
+
+ const void *PI = &AnalysisType::ID;
+
+ Pass *ResultPass = Resolver->getAnalysisIfAvailable(PI, true);
+ if (ResultPass == 0) return 0;
+
+ // Because the AnalysisType may not be a subclass of pass (for
+ // AnalysisGroups), we use getAdjustedAnalysisPointer here to potentially
+ // adjust the return pointer (because the class may multiply inherit, once
+ // from pass, once from AnalysisType).
+ return (AnalysisType*)ResultPass->getAdjustedAnalysisPointer(PI);
+}
+
+/// getAnalysis<AnalysisType>() - This function is used by subclasses to get
+/// to the analysis information that they claim to use by overriding the
+/// getAnalysisUsage function.
+///
+template<typename AnalysisType>
+AnalysisType &Pass::getAnalysis() const {
+ assert(Resolver && "Pass has not been inserted into a PassManager object!");
+ return getAnalysisID<AnalysisType>(&AnalysisType::ID);
+}
+
+template<typename AnalysisType>
+AnalysisType &Pass::getAnalysisID(AnalysisID PI) const {
+ assert(PI && "getAnalysis for unregistered pass!");
+ assert(Resolver&&"Pass has not been inserted into a PassManager object!");
+ // PI *must* appear in AnalysisImpls. Because the number of passes used
+ // should be a small number, we just do a linear search over a (dense)
+ // vector.
+ Pass *ResultPass = Resolver->findImplPass(PI);
+ assert (ResultPass &&
+ "getAnalysis*() called on an analysis that was not "
+ "'required' by pass!");
+
+ // Because the AnalysisType may not be a subclass of pass (for
+ // AnalysisGroups), we use getAdjustedAnalysisPointer here to potentially
+ // adjust the return pointer (because the class may multiply inherit, once
+ // from pass, once from AnalysisType).
+ return *(AnalysisType*)ResultPass->getAdjustedAnalysisPointer(PI);
+}
+
+/// getAnalysis<AnalysisType>() - This function is used by subclasses to get
+/// to the analysis information that they claim to use by overriding the
+/// getAnalysisUsage function.
+///
+template<typename AnalysisType>
+AnalysisType &Pass::getAnalysis(Function &F) {
+ assert(Resolver &&"Pass has not been inserted into a PassManager object!");
+
+ return getAnalysisID<AnalysisType>(&AnalysisType::ID, F);
+}
+
+template<typename AnalysisType>
+AnalysisType &Pass::getAnalysisID(AnalysisID PI, Function &F) {
+ assert(PI && "getAnalysis for unregistered pass!");
+ assert(Resolver && "Pass has not been inserted into a PassManager object!");
+ // PI *must* appear in AnalysisImpls. Because the number of passes used
+ // should be a small number, we just do a linear search over a (dense)
+ // vector.
+ Pass *ResultPass = Resolver->findImplPass(this, PI, F);
+ assert(ResultPass && "Unable to find requested analysis info");
+
+ // Because the AnalysisType may not be a subclass of pass (for
+ // AnalysisGroups), we use getAdjustedAnalysisPointer here to potentially
+ // adjust the return pointer (because the class may multiply inherit, once
+ // from pass, once from AnalysisType).
+ return *(AnalysisType*)ResultPass->getAdjustedAnalysisPointer(PI);
+}
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/PassManager.h b/include/llvm/PassManager.h
new file mode 100644
index 00000000000..ce5fda79f9c
--- /dev/null
+++ b/include/llvm/PassManager.h
@@ -0,0 +1,103 @@
+//===- llvm/PassManager.h - Container for Passes ----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the PassManager class. This class is used to hold,
+// maintain, and optimize execution of Passes. The PassManager class ensures
+// that analysis results are available before a pass runs, and that Pass's are
+// destroyed when the PassManager is destroyed.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_PASSMANAGER_H
+#define LLVM_PASSMANAGER_H
+
+#include "llvm/Pass.h"
+
+namespace llvm {
+
+class Pass;
+class Module;
+
+class PassManagerImpl;
+class FunctionPassManagerImpl;
+
+/// PassManagerBase - An abstract interface to allow code to add passes to
+/// a pass manager without having to hard-code what kind of pass manager
+/// it is.
+class PassManagerBase {
+public:
+ virtual ~PassManagerBase();
+
+ /// add - Add a pass to the queue of passes to run. This passes ownership of
+ /// the Pass to the PassManager. When the PassManager is destroyed, the pass
+ /// will be destroyed as well, so there is no need to delete the pass. This
+ /// implies that all passes MUST be allocated with 'new'.
+ virtual void add(Pass *P) = 0;
+};
+
+/// PassManager manages ModulePassManagers
+class PassManager : public PassManagerBase {
+public:
+
+ PassManager();
+ ~PassManager();
+
+ /// add - Add a pass to the queue of passes to run. This passes ownership of
+ /// the Pass to the PassManager. When the PassManager is destroyed, the pass
+ /// will be destroyed as well, so there is no need to delete the pass. This
+ /// implies that all passes MUST be allocated with 'new'.
+ void add(Pass *P);
+
+ /// run - Execute all of the passes scheduled for execution. Keep track of
+ /// whether any of the passes modifies the module, and if so, return true.
+ bool run(Module &M);
+
+private:
+ /// PassManagerImpl_New is the actual class. PassManager is just the
+ /// wraper to publish simple pass manager interface
+ PassManagerImpl *PM;
+};
+
+/// FunctionPassManager manages FunctionPasses and BasicBlockPassManagers.
+class FunctionPassManager : public PassManagerBase {
+public:
+ /// FunctionPassManager ctor - This initializes the pass manager. It needs,
+ /// but does not take ownership of, the specified Module.
+ explicit FunctionPassManager(Module *M);
+ ~FunctionPassManager();
+
+ /// add - Add a pass to the queue of passes to run. This passes
+ /// ownership of the Pass to the PassManager. When the
+ /// PassManager_X is destroyed, the pass will be destroyed as well, so
+ /// there is no need to delete the pass.
+ /// This implies that all passes MUST be allocated with 'new'.
+ void add(Pass *P);
+
+ /// run - Execute all of the passes scheduled for execution. Keep
+ /// track of whether any of the passes modifies the function, and if
+ /// so, return true.
+ ///
+ bool run(Function &F);
+
+ /// doInitialization - Run all of the initializers for the function passes.
+ ///
+ bool doInitialization();
+
+ /// doFinalization - Run all of the finalizers for the function passes.
+ ///
+ bool doFinalization();
+
+private:
+ FunctionPassManagerImpl *FPM;
+ Module *M;
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/PassManagers.h b/include/llvm/PassManagers.h
new file mode 100644
index 00000000000..0af58533805
--- /dev/null
+++ b/include/llvm/PassManagers.h
@@ -0,0 +1,461 @@
+//===- llvm/PassManagers.h - Pass Infrastructure classes -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the LLVM Pass Manager infrastructure.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_PASSMANAGERS_H
+#define LLVM_PASSMANAGERS_H
+
+#include "llvm/Pass.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/DenseMap.h"
+#include <vector>
+#include <map>
+
+//===----------------------------------------------------------------------===//
+// Overview:
+// The Pass Manager Infrastructure manages passes. It's responsibilities are:
+//
+// o Manage optimization pass execution order
+// o Make required Analysis information available before pass P is run
+// o Release memory occupied by dead passes
+// o If Analysis information is dirtied by a pass then regenerate Analysis
+// information before it is consumed by another pass.
+//
+// Pass Manager Infrastructure uses multiple pass managers. They are
+// PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
+// This class hierarchy uses multiple inheritance but pass managers do not
+// derive from another pass manager.
+//
+// PassManager and FunctionPassManager are two top-level pass manager that
+// represents the external interface of this entire pass manager infrastucture.
+//
+// Important classes :
+//
+// [o] class PMTopLevelManager;
+//
+// Two top level managers, PassManager and FunctionPassManager, derive from
+// PMTopLevelManager. PMTopLevelManager manages information used by top level
+// managers such as last user info.
+//
+// [o] class PMDataManager;
+//
+// PMDataManager manages information, e.g. list of available analysis info,
+// used by a pass manager to manage execution order of passes. It also provides
+// a place to implement common pass manager APIs. All pass managers derive from
+// PMDataManager.
+//
+// [o] class BBPassManager : public FunctionPass, public PMDataManager;
+//
+// BBPassManager manages BasicBlockPasses.
+//
+// [o] class FunctionPassManager;
+//
+// This is a external interface used by JIT to manage FunctionPasses. This
+// interface relies on FunctionPassManagerImpl to do all the tasks.
+//
+// [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
+// public PMTopLevelManager;
+//
+// FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
+//
+// [o] class FPPassManager : public ModulePass, public PMDataManager;
+//
+// FPPassManager manages FunctionPasses and BBPassManagers
+//
+// [o] class MPPassManager : public Pass, public PMDataManager;
+//
+// MPPassManager manages ModulePasses and FPPassManagers
+//
+// [o] class PassManager;
+//
+// This is a external interface used by various tools to manages passes. It
+// relies on PassManagerImpl to do all the tasks.
+//
+// [o] class PassManagerImpl : public Pass, public PMDataManager,
+// public PMTopLevelManager
+//
+// PassManagerImpl is a top level pass manager responsible for managing
+// MPPassManagers.
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Support/PrettyStackTrace.h"
+
+namespace llvm {
+ class Module;
+ class Pass;
+ class StringRef;
+ class Value;
+ class Timer;
+ class PMDataManager;
+
+// enums for debugging strings
+enum PassDebuggingString {
+ EXECUTION_MSG, // "Executing Pass '"
+ MODIFICATION_MSG, // "' Made Modification '"
+ FREEING_MSG, // " Freeing Pass '"
+ ON_BASICBLOCK_MSG, // "' on BasicBlock '" + PassName + "'...\n"
+ ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
+ ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
+ ON_REGION_MSG, // " 'on Region ...\n'"
+ ON_LOOP_MSG, // " 'on Loop ...\n'"
+ ON_CG_MSG // "' on Call Graph ...\n'"
+};
+
+/// PassManagerPrettyStackEntry - This is used to print informative information
+/// about what pass is running when/if a stack trace is generated.
+class PassManagerPrettyStackEntry : public PrettyStackTraceEntry {
+ Pass *P;
+ Value *V;
+ Module *M;
+public:
+ explicit PassManagerPrettyStackEntry(Pass *p)
+ : P(p), V(0), M(0) {} // When P is releaseMemory'd.
+ PassManagerPrettyStackEntry(Pass *p, Value &v)
+ : P(p), V(&v), M(0) {} // When P is run on V
+ PassManagerPrettyStackEntry(Pass *p, Module &m)
+ : P(p), V(0), M(&m) {} // When P is run on M
+
+ /// print - Emit information about this stack frame to OS.
+ virtual void print(raw_ostream &OS) const;
+};
+
+
+//===----------------------------------------------------------------------===//
+// PMStack
+//
+/// PMStack - This class implements a stack data structure of PMDataManager
+/// pointers.
+///
+/// Top level pass managers (see PassManager.cpp) maintain active Pass Managers
+/// using PMStack. Each Pass implements assignPassManager() to connect itself
+/// with appropriate manager. assignPassManager() walks PMStack to find
+/// suitable manager.
+class PMStack {
+public:
+ typedef std::vector<PMDataManager *>::const_reverse_iterator iterator;
+ iterator begin() const { return S.rbegin(); }
+ iterator end() const { return S.rend(); }
+
+ void pop();
+ PMDataManager *top() const { return S.back(); }
+ void push(PMDataManager *PM);
+ bool empty() const { return S.empty(); }
+
+ void dump() const;
+
+private:
+ std::vector<PMDataManager *> S;
+};
+
+
+//===----------------------------------------------------------------------===//
+// PMTopLevelManager
+//
+/// PMTopLevelManager manages LastUser info and collects common APIs used by
+/// top level pass managers.
+class PMTopLevelManager {
+protected:
+ explicit PMTopLevelManager(PMDataManager *PMDM);
+
+ virtual unsigned getNumContainedManagers() const {
+ return (unsigned)PassManagers.size();
+ }
+
+ void initializeAllAnalysisInfo();
+
+private:
+ virtual PMDataManager *getAsPMDataManager() = 0;
+ virtual PassManagerType getTopLevelPassManagerType() = 0;
+
+public:
+ /// Schedule pass P for execution. Make sure that passes required by
+ /// P are run before P is run. Update analysis info maintained by
+ /// the manager. Remove dead passes. This is a recursive function.
+ void schedulePass(Pass *P);
+
+ /// Set pass P as the last user of the given analysis passes.
+ void setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P);
+
+ /// Collect passes whose last user is P
+ void collectLastUses(SmallVectorImpl<Pass *> &LastUses, Pass *P);
+
+ /// Find the pass that implements Analysis AID. Search immutable
+ /// passes and all pass managers. If desired pass is not found
+ /// then return NULL.
+ Pass *findAnalysisPass(AnalysisID AID);
+
+ /// Find analysis usage information for the pass P.
+ AnalysisUsage *findAnalysisUsage(Pass *P);
+
+ virtual ~PMTopLevelManager();
+
+ /// Add immutable pass and initialize it.
+ inline void addImmutablePass(ImmutablePass *P) {
+ P->initializePass();
+ ImmutablePasses.push_back(P);
+ }
+
+ inline SmallVectorImpl<ImmutablePass *>& getImmutablePasses() {
+ return ImmutablePasses;
+ }
+
+ void addPassManager(PMDataManager *Manager) {
+ PassManagers.push_back(Manager);
+ }
+
+ // Add Manager into the list of managers that are not directly
+ // maintained by this top level pass manager
+ inline void addIndirectPassManager(PMDataManager *Manager) {
+ IndirectPassManagers.push_back(Manager);
+ }
+
+ // Print passes managed by this top level manager.
+ void dumpPasses() const;
+ void dumpArguments() const;
+
+ // Active Pass Managers
+ PMStack activeStack;
+
+protected:
+
+ /// Collection of pass managers
+ SmallVector<PMDataManager *, 8> PassManagers;
+
+private:
+
+ /// Collection of pass managers that are not directly maintained
+ /// by this pass manager
+ SmallVector<PMDataManager *, 8> IndirectPassManagers;
+
+ // Map to keep track of last user of the analysis pass.
+ // LastUser->second is the last user of Lastuser->first.
+ DenseMap<Pass *, Pass *> LastUser;
+
+ // Map to keep track of passes that are last used by a pass.
+ // This inverse map is initialized at PM->run() based on
+ // LastUser map.
+ DenseMap<Pass *, SmallPtrSet<Pass *, 8> > InversedLastUser;
+
+ /// Immutable passes are managed by top level manager.
+ SmallVector<ImmutablePass *, 8> ImmutablePasses;
+
+ DenseMap<Pass *, AnalysisUsage *> AnUsageMap;
+};
+
+
+
+//===----------------------------------------------------------------------===//
+// PMDataManager
+
+/// PMDataManager provides the common place to manage the analysis data
+/// used by pass managers.
+class PMDataManager {
+public:
+
+ explicit PMDataManager() : TPM(NULL), Depth(0) {
+ initializeAnalysisInfo();
+ }
+
+ virtual ~PMDataManager();
+
+ virtual Pass *getAsPass() = 0;
+
+ /// Augment AvailableAnalysis by adding analysis made available by pass P.
+ void recordAvailableAnalysis(Pass *P);
+
+ /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
+ void verifyPreservedAnalysis(Pass *P);
+
+ /// Remove Analysis that is not preserved by the pass
+ void removeNotPreservedAnalysis(Pass *P);
+
+ /// Remove dead passes used by P.
+ void removeDeadPasses(Pass *P, StringRef Msg,
+ enum PassDebuggingString);
+
+ /// Remove P.
+ void freePass(Pass *P, StringRef Msg,
+ enum PassDebuggingString);
+
+ /// Add pass P into the PassVector. Update
+ /// AvailableAnalysis appropriately if ProcessAnalysis is true.
+ void add(Pass *P, bool ProcessAnalysis = true);
+
+ /// Add RequiredPass into list of lower level passes required by pass P.
+ /// RequiredPass is run on the fly by Pass Manager when P requests it
+ /// through getAnalysis interface.
+ virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
+
+ virtual Pass *getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F);
+
+ /// Initialize available analysis information.
+ void initializeAnalysisInfo() {
+ AvailableAnalysis.clear();
+ for (unsigned i = 0; i < PMT_Last; ++i)
+ InheritedAnalysis[i] = NULL;
+ }
+
+ // Return true if P preserves high level analysis used by other
+ // passes that are managed by this manager.
+ bool preserveHigherLevelAnalysis(Pass *P);
+
+
+ /// Populate RequiredPasses with analysis pass that are required by
+ /// pass P and are available. Populate ReqPassNotAvailable with analysis
+ /// pass that are required by pass P but are not available.
+ void collectRequiredAnalysis(SmallVectorImpl<Pass *> &RequiredPasses,
+ SmallVectorImpl<AnalysisID> &ReqPassNotAvailable,
+ Pass *P);
+
+ /// All Required analyses should be available to the pass as it runs! Here
+ /// we fill in the AnalysisImpls member of the pass so that it can
+ /// successfully use the getAnalysis() method to retrieve the
+ /// implementations it needs.
+ void initializeAnalysisImpl(Pass *P);
+
+ /// Find the pass that implements Analysis AID. If desired pass is not found
+ /// then return NULL.
+ Pass *findAnalysisPass(AnalysisID AID, bool Direction);
+
+ // Access toplevel manager
+ PMTopLevelManager *getTopLevelManager() { return TPM; }
+ void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
+
+ unsigned getDepth() const { return Depth; }
+ void setDepth(unsigned newDepth) { Depth = newDepth; }
+
+ // Print routines used by debug-pass
+ void dumpLastUses(Pass *P, unsigned Offset) const;
+ void dumpPassArguments() const;
+ void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
+ enum PassDebuggingString S2, StringRef Msg);
+ void dumpRequiredSet(const Pass *P) const;
+ void dumpPreservedSet(const Pass *P) const;
+
+ virtual unsigned getNumContainedPasses() const {
+ return (unsigned)PassVector.size();
+ }
+
+ virtual PassManagerType getPassManagerType() const {
+ assert ( 0 && "Invalid use of getPassManagerType");
+ return PMT_Unknown;
+ }
+
+ std::map<AnalysisID, Pass*> *getAvailableAnalysis() {
+ return &AvailableAnalysis;
+ }
+
+ // Collect AvailableAnalysis from all the active Pass Managers.
+ void populateInheritedAnalysis(PMStack &PMS) {
+ unsigned Index = 0;
+ for (PMStack::iterator I = PMS.begin(), E = PMS.end();
+ I != E; ++I)
+ InheritedAnalysis[Index++] = (*I)->getAvailableAnalysis();
+ }
+
+protected:
+
+ // Top level manager.
+ PMTopLevelManager *TPM;
+
+ // Collection of pass that are managed by this manager
+ SmallVector<Pass *, 16> PassVector;
+
+ // Collection of Analysis provided by Parent pass manager and
+ // used by current pass manager. At at time there can not be more
+ // then PMT_Last active pass mangers.
+ std::map<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last];
+
+
+ /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
+ /// or higher is specified.
+ bool isPassDebuggingExecutionsOrMore() const;
+
+private:
+ void dumpAnalysisUsage(StringRef Msg, const Pass *P,
+ const AnalysisUsage::VectorType &Set) const;
+
+ // Set of available Analysis. This information is used while scheduling
+ // pass. If a pass requires an analysis which is not available then
+ // the required analysis pass is scheduled to run before the pass itself is
+ // scheduled to run.
+ std::map<AnalysisID, Pass*> AvailableAnalysis;
+
+ // Collection of higher level analysis used by the pass managed by
+ // this manager.
+ SmallVector<Pass *, 8> HigherLevelAnalysis;
+
+ unsigned Depth;
+};
+
+//===----------------------------------------------------------------------===//
+// FPPassManager
+//
+/// FPPassManager manages BBPassManagers and FunctionPasses.
+/// It batches all function passes and basic block pass managers together and
+/// sequence them to process one function at a time before processing next
+/// function.
+class FPPassManager : public ModulePass, public PMDataManager {
+public:
+ static char ID;
+ explicit FPPassManager()
+ : ModulePass(ID), PMDataManager() { }
+
+ /// run - Execute all of the passes scheduled for execution. Keep track of
+ /// whether any of the passes modifies the module, and if so, return true.
+ bool runOnFunction(Function &F);
+ bool runOnModule(Module &M);
+
+ /// cleanup - After running all passes, clean up pass manager cache.
+ void cleanup();
+
+ /// doInitialization - Run all of the initializers for the function passes.
+ ///
+ bool doInitialization(Module &M);
+
+ /// doFinalization - Run all of the finalizers for the function passes.
+ ///
+ bool doFinalization(Module &M);
+
+ virtual PMDataManager *getAsPMDataManager() { return this; }
+ virtual Pass *getAsPass() { return this; }
+
+ /// Pass Manager itself does not invalidate any analysis info.
+ void getAnalysisUsage(AnalysisUsage &Info) const {
+ Info.setPreservesAll();
+ }
+
+ // Print passes managed by this manager
+ void dumpPassStructure(unsigned Offset);
+
+ virtual const char *getPassName() const {
+ return "Function Pass Manager";
+ }
+
+ FunctionPass *getContainedPass(unsigned N) {
+ assert ( N < PassVector.size() && "Pass number out of range!");
+ FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
+ return FP;
+ }
+
+ virtual PassManagerType getPassManagerType() const {
+ return PMT_FunctionPassManager;
+ }
+};
+
+Timer *getPassTimer(Pass *);
+
+}
+
+#endif
diff --git a/include/llvm/PassRegistry.h b/include/llvm/PassRegistry.h
new file mode 100644
index 00000000000..5d89c492218
--- /dev/null
+++ b/include/llvm/PassRegistry.h
@@ -0,0 +1,84 @@
+//===- llvm/PassRegistry.h - Pass Information Registry ----------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines PassRegistry, a class that is used in the initialization
+// and registration of passes. At application startup, passes are registered
+// with the PassRegistry, which is later provided to the PassManager for
+// dependency resolution and similar tasks.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_PASSREGISTRY_H
+#define LLVM_PASSREGISTRY_H
+
+#include "llvm/ADT/StringRef.h"
+
+namespace llvm {
+
+class PassInfo;
+struct PassRegistrationListener;
+
+/// PassRegistry - This class manages the registration and intitialization of
+/// the pass subsystem as application startup, and assists the PassManager
+/// in resolving pass dependencies.
+/// NOTE: PassRegistry is NOT thread-safe. If you want to use LLVM on multiple
+/// threads simultaneously, you will need to use a separate PassRegistry on
+/// each thread.
+class PassRegistry {
+ mutable void *pImpl;
+ void *getImpl() const;
+
+public:
+ PassRegistry() : pImpl(0) { }
+ ~PassRegistry();
+
+ /// getPassRegistry - Access the global registry object, which is
+ /// automatically initialized at application launch and destroyed by
+ /// llvm_shutdown.
+ static PassRegistry *getPassRegistry();
+
+ /// getPassInfo - Look up a pass' corresponding PassInfo, indexed by the pass'
+ /// type identifier (&MyPass::ID).
+ const PassInfo *getPassInfo(const void *TI) const;
+
+ /// getPassInfo - Look up a pass' corresponding PassInfo, indexed by the pass'
+ /// argument string.
+ const PassInfo *getPassInfo(StringRef Arg) const;
+
+ /// registerPass - Register a pass (by means of its PassInfo) with the
+ /// registry. Required in order to use the pass with a PassManager.
+ void registerPass(const PassInfo &PI, bool ShouldFree = false);
+
+ /// registerPass - Unregister a pass (by means of its PassInfo) with the
+ /// registry.
+ void unregisterPass(const PassInfo &PI);
+
+ /// registerAnalysisGroup - Register an analysis group (or a pass implementing
+ // an analysis group) with the registry. Like registerPass, this is required
+ // in order for a PassManager to be able to use this group/pass.
+ void registerAnalysisGroup(const void *InterfaceID, const void *PassID,
+ PassInfo& Registeree, bool isDefault,
+ bool ShouldFree = false);
+
+ /// enumerateWith - Enumerate the registered passes, calling the provided
+ /// PassRegistrationListener's passEnumerate() callback on each of them.
+ void enumerateWith(PassRegistrationListener *L);
+
+ /// addRegistrationListener - Register the given PassRegistrationListener
+ /// to receive passRegistered() callbacks whenever a new pass is registered.
+ void addRegistrationListener(PassRegistrationListener *L);
+
+ /// removeRegistrationListener - Unregister a PassRegistrationListener so that
+ /// it no longer receives passRegistered() callbacks.
+ void removeRegistrationListener(PassRegistrationListener *L);
+};
+
+}
+
+#endif
diff --git a/include/llvm/PassSupport.h b/include/llvm/PassSupport.h
new file mode 100644
index 00000000000..c6ad44f5f4e
--- /dev/null
+++ b/include/llvm/PassSupport.h
@@ -0,0 +1,341 @@
+//===- llvm/PassSupport.h - Pass Support code -------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines stuff that is used to define and "use" Passes. This file
+// is automatically #included by Pass.h, so:
+//
+// NO .CPP FILES SHOULD INCLUDE THIS FILE DIRECTLY
+//
+// Instead, #include Pass.h.
+//
+// This file defines Pass registration code and classes used for it.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_PASS_SUPPORT_H
+#define LLVM_PASS_SUPPORT_H
+
+#include "Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Support/Atomic.h"
+#include "llvm/Support/Valgrind.h"
+#include <vector>
+
+namespace llvm {
+
+//===---------------------------------------------------------------------------
+/// PassInfo class - An instance of this class exists for every pass known by
+/// the system, and can be obtained from a live Pass by calling its
+/// getPassInfo() method. These objects are set up by the RegisterPass<>
+/// template, defined below.
+///
+class PassInfo {
+public:
+ typedef Pass* (*NormalCtor_t)();
+
+private:
+ const char *const PassName; // Nice name for Pass
+ const char *const PassArgument; // Command Line argument to run this pass
+ const void *PassID;
+ const bool IsCFGOnlyPass; // Pass only looks at the CFG.
+ const bool IsAnalysis; // True if an analysis pass.
+ const bool IsAnalysisGroup; // True if an analysis group.
+ std::vector<const PassInfo*> ItfImpl;// Interfaces implemented by this pass
+
+ NormalCtor_t NormalCtor;
+
+public:
+ /// PassInfo ctor - Do not call this directly, this should only be invoked
+ /// through RegisterPass.
+ PassInfo(const char *name, const char *arg, const void *pi,
+ NormalCtor_t normal, bool isCFGOnly, bool is_analysis)
+ : PassName(name), PassArgument(arg), PassID(pi),
+ IsCFGOnlyPass(isCFGOnly),
+ IsAnalysis(is_analysis), IsAnalysisGroup(false), NormalCtor(normal) { }
+ /// PassInfo ctor - Do not call this directly, this should only be invoked
+ /// through RegisterPass. This version is for use by analysis groups; it
+ /// does not auto-register the pass.
+ PassInfo(const char *name, const void *pi)
+ : PassName(name), PassArgument(""), PassID(pi),
+ IsCFGOnlyPass(false),
+ IsAnalysis(false), IsAnalysisGroup(true), NormalCtor(0) { }
+
+ /// getPassName - Return the friendly name for the pass, never returns null
+ ///
+ const char *getPassName() const { return PassName; }
+
+ /// getPassArgument - Return the command line option that may be passed to
+ /// 'opt' that will cause this pass to be run. This will return null if there
+ /// is no argument.
+ ///
+ const char *getPassArgument() const { return PassArgument; }
+
+ /// getTypeInfo - Return the id object for the pass...
+ /// TODO : Rename
+ const void *getTypeInfo() const { return PassID; }
+
+ /// Return true if this PassID implements the specified ID pointer.
+ bool isPassID(const void *IDPtr) const {
+ return PassID == IDPtr;
+ }
+
+ /// isAnalysisGroup - Return true if this is an analysis group, not a normal
+ /// pass.
+ ///
+ bool isAnalysisGroup() const { return IsAnalysisGroup; }
+ bool isAnalysis() const { return IsAnalysis; }
+
+ /// isCFGOnlyPass - return true if this pass only looks at the CFG for the
+ /// function.
+ bool isCFGOnlyPass() const { return IsCFGOnlyPass; }
+
+ /// getNormalCtor - Return a pointer to a function, that when called, creates
+ /// an instance of the pass and returns it. This pointer may be null if there
+ /// is no default constructor for the pass.
+ ///
+ NormalCtor_t getNormalCtor() const {
+ return NormalCtor;
+ }
+ void setNormalCtor(NormalCtor_t Ctor) {
+ NormalCtor = Ctor;
+ }
+
+ /// createPass() - Use this method to create an instance of this pass.
+ Pass *createPass() const;
+
+ /// addInterfaceImplemented - This method is called when this pass is
+ /// registered as a member of an analysis group with the RegisterAnalysisGroup
+ /// template.
+ ///
+ void addInterfaceImplemented(const PassInfo *ItfPI) {
+ ItfImpl.push_back(ItfPI);
+ }
+
+ /// getInterfacesImplemented - Return a list of all of the analysis group
+ /// interfaces implemented by this pass.
+ ///
+ const std::vector<const PassInfo*> &getInterfacesImplemented() const {
+ return ItfImpl;
+ }
+
+private:
+ void operator=(const PassInfo &) LLVM_DELETED_FUNCTION;
+ PassInfo(const PassInfo &) LLVM_DELETED_FUNCTION;
+};
+
+#define CALL_ONCE_INITIALIZATION(function) \
+ static volatile sys::cas_flag initialized = 0; \
+ sys::cas_flag old_val = sys::CompareAndSwap(&initialized, 1, 0); \
+ if (old_val == 0) { \
+ function(Registry); \
+ sys::MemoryFence(); \
+ TsanIgnoreWritesBegin(); \
+ TsanHappensBefore(&initialized); \
+ initialized = 2; \
+ TsanIgnoreWritesEnd(); \
+ } else { \
+ sys::cas_flag tmp = initialized; \
+ sys::MemoryFence(); \
+ while (tmp != 2) { \
+ tmp = initialized; \
+ sys::MemoryFence(); \
+ } \
+ } \
+ TsanHappensAfter(&initialized);
+
+#define INITIALIZE_PASS(passName, arg, name, cfg, analysis) \
+ static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
+ PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
+ PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
+ Registry.registerPass(*PI, true); \
+ return PI; \
+ } \
+ void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
+ CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
+ }
+
+#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis) \
+ static void* initialize##passName##PassOnce(PassRegistry &Registry) {
+
+#define INITIALIZE_PASS_DEPENDENCY(depName) \
+ initialize##depName##Pass(Registry);
+#define INITIALIZE_AG_DEPENDENCY(depName) \
+ initialize##depName##AnalysisGroup(Registry);
+
+#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis) \
+ PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
+ PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
+ Registry.registerPass(*PI, true); \
+ return PI; \
+ } \
+ void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
+ CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
+ }
+
+template<typename PassName>
+Pass *callDefaultCtor() { return new PassName(); }
+
+//===---------------------------------------------------------------------------
+/// RegisterPass<t> template - This template class is used to notify the system
+/// that a Pass is available for use, and registers it into the internal
+/// database maintained by the PassManager. Unless this template is used, opt,
+/// for example will not be able to see the pass and attempts to create the pass
+/// will fail. This template is used in the follow manner (at global scope, in
+/// your .cpp file):
+///
+/// static RegisterPass<YourPassClassName> tmp("passopt", "My Pass Name");
+///
+/// This statement will cause your pass to be created by calling the default
+/// constructor exposed by the pass. If you have a different constructor that
+/// must be called, create a global constructor function (which takes the
+/// arguments you need and returns a Pass*) and register your pass like this:
+///
+/// static RegisterPass<PassClassName> tmp("passopt", "My Name");
+///
+template<typename passName>
+struct RegisterPass : public PassInfo {
+
+ // Register Pass using default constructor...
+ RegisterPass(const char *PassArg, const char *Name, bool CFGOnly = false,
+ bool is_analysis = false)
+ : PassInfo(Name, PassArg, &passName::ID,
+ PassInfo::NormalCtor_t(callDefaultCtor<passName>),
+ CFGOnly, is_analysis) {
+ PassRegistry::getPassRegistry()->registerPass(*this);
+ }
+};
+
+
+/// RegisterAnalysisGroup - Register a Pass as a member of an analysis _group_.
+/// Analysis groups are used to define an interface (which need not derive from
+/// Pass) that is required by passes to do their job. Analysis Groups differ
+/// from normal analyses because any available implementation of the group will
+/// be used if it is available.
+///
+/// If no analysis implementing the interface is available, a default
+/// implementation is created and added. A pass registers itself as the default
+/// implementation by specifying 'true' as the second template argument of this
+/// class.
+///
+/// In addition to registering itself as an analysis group member, a pass must
+/// register itself normally as well. Passes may be members of multiple groups
+/// and may still be "required" specifically by name.
+///
+/// The actual interface may also be registered as well (by not specifying the
+/// second template argument). The interface should be registered to associate
+/// a nice name with the interface.
+///
+class RegisterAGBase : public PassInfo {
+public:
+ RegisterAGBase(const char *Name,
+ const void *InterfaceID,
+ const void *PassID = 0,
+ bool isDefault = false);
+};
+
+template<typename Interface, bool Default = false>
+struct RegisterAnalysisGroup : public RegisterAGBase {
+ explicit RegisterAnalysisGroup(PassInfo &RPB)
+ : RegisterAGBase(RPB.getPassName(),
+ &Interface::ID, RPB.getTypeInfo(),
+ Default) {
+ }
+
+ explicit RegisterAnalysisGroup(const char *Name)
+ : RegisterAGBase(Name, &Interface::ID) {
+ }
+};
+
+#define INITIALIZE_ANALYSIS_GROUP(agName, name, defaultPass) \
+ static void* initialize##agName##AnalysisGroupOnce(PassRegistry &Registry) { \
+ initialize##defaultPass##Pass(Registry); \
+ PassInfo *AI = new PassInfo(name, & agName :: ID); \
+ Registry.registerAnalysisGroup(& agName ::ID, 0, *AI, false, true); \
+ return AI; \
+ } \
+ void llvm::initialize##agName##AnalysisGroup(PassRegistry &Registry) { \
+ CALL_ONCE_INITIALIZATION(initialize##agName##AnalysisGroupOnce) \
+ }
+
+
+#define INITIALIZE_AG_PASS(passName, agName, arg, name, cfg, analysis, def) \
+ static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
+ if (!def) initialize##agName##AnalysisGroup(Registry); \
+ PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
+ PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
+ Registry.registerPass(*PI, true); \
+ \
+ PassInfo *AI = new PassInfo(name, & agName :: ID); \
+ Registry.registerAnalysisGroup(& agName ::ID, & passName ::ID, \
+ *AI, def, true); \
+ return AI; \
+ } \
+ void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
+ CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
+ }
+
+
+#define INITIALIZE_AG_PASS_BEGIN(passName, agName, arg, n, cfg, analysis, def) \
+ static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
+ if (!def) initialize##agName##AnalysisGroup(Registry);
+
+#define INITIALIZE_AG_PASS_END(passName, agName, arg, n, cfg, analysis, def) \
+ PassInfo *PI = new PassInfo(n, arg, & passName ::ID, \
+ PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
+ Registry.registerPass(*PI, true); \
+ \
+ PassInfo *AI = new PassInfo(n, & agName :: ID); \
+ Registry.registerAnalysisGroup(& agName ::ID, & passName ::ID, \
+ *AI, def, true); \
+ return AI; \
+ } \
+ void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
+ CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
+ }
+
+//===---------------------------------------------------------------------------
+/// PassRegistrationListener class - This class is meant to be derived from by
+/// clients that are interested in which passes get registered and unregistered
+/// at runtime (which can be because of the RegisterPass constructors being run
+/// as the program starts up, or may be because a shared object just got
+/// loaded). Deriving from the PassRegistationListener class automatically
+/// registers your object to receive callbacks indicating when passes are loaded
+/// and removed.
+///
+struct PassRegistrationListener {
+
+ /// PassRegistrationListener ctor - Add the current object to the list of
+ /// PassRegistrationListeners...
+ PassRegistrationListener();
+
+ /// dtor - Remove object from list of listeners...
+ ///
+ virtual ~PassRegistrationListener();
+
+ /// Callback functions - These functions are invoked whenever a pass is loaded
+ /// or removed from the current executable.
+ ///
+ virtual void passRegistered(const PassInfo *) {}
+
+ /// enumeratePasses - Iterate over the registered passes, calling the
+ /// passEnumerate callback on each PassInfo object.
+ ///
+ void enumeratePasses();
+
+ /// passEnumerate - Callback function invoked when someone calls
+ /// enumeratePasses on this PassRegistrationListener object.
+ ///
+ virtual void passEnumerate(const PassInfo *) {}
+};
+
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Support/AIXDataTypesFix.h b/include/llvm/Support/AIXDataTypesFix.h
new file mode 100644
index 00000000000..a9a9147de29
--- /dev/null
+++ b/include/llvm/Support/AIXDataTypesFix.h
@@ -0,0 +1,25 @@
+//===-- llvm/Support/AIXDataTypesFix.h - Fix datatype defs ------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file overrides default system-defined types and limits which cannot be
+// done in DataTypes.h.in because it is processed by autoheader first, which
+// comments out any #undef statement
+//
+//===----------------------------------------------------------------------===//
+
+// No include guards desired!
+
+#ifndef SUPPORT_DATATYPES_H
+#error "AIXDataTypesFix.h must only be included via DataTypes.h!"
+#endif
+
+// GCC is strict about defining large constants: they must have LL modifier.
+// These will be defined properly at the end of DataTypes.h
+#undef INT64_MAX
+#undef INT64_MIN
diff --git a/include/llvm/Support/AlignOf.h b/include/llvm/Support/AlignOf.h
new file mode 100644
index 00000000000..22c07d04fad
--- /dev/null
+++ b/include/llvm/Support/AlignOf.h
@@ -0,0 +1,170 @@
+//===--- AlignOf.h - Portable calculation of type alignment -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the AlignOf function that computes alignments for
+// arbitrary types.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_ALIGNOF_H
+#define LLVM_SUPPORT_ALIGNOF_H
+
+#include "llvm/Support/Compiler.h"
+#include <cstddef>
+
+namespace llvm {
+
+template <typename T>
+struct AlignmentCalcImpl {
+ char x;
+ T t;
+private:
+ AlignmentCalcImpl() {} // Never instantiate.
+};
+
+/// AlignOf - A templated class that contains an enum value representing
+/// the alignment of the template argument. For example,
+/// AlignOf<int>::Alignment represents the alignment of type "int". The
+/// alignment calculated is the minimum alignment, and not necessarily
+/// the "desired" alignment returned by GCC's __alignof__ (for example). Note
+/// that because the alignment is an enum value, it can be used as a
+/// compile-time constant (e.g., for template instantiation).
+template <typename T>
+struct AlignOf {
+ enum { Alignment =
+ static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T)) };
+
+ enum { Alignment_GreaterEqual_2Bytes = Alignment >= 2 ? 1 : 0 };
+ enum { Alignment_GreaterEqual_4Bytes = Alignment >= 4 ? 1 : 0 };
+ enum { Alignment_GreaterEqual_8Bytes = Alignment >= 8 ? 1 : 0 };
+ enum { Alignment_GreaterEqual_16Bytes = Alignment >= 16 ? 1 : 0 };
+
+ enum { Alignment_LessEqual_2Bytes = Alignment <= 2 ? 1 : 0 };
+ enum { Alignment_LessEqual_4Bytes = Alignment <= 4 ? 1 : 0 };
+ enum { Alignment_LessEqual_8Bytes = Alignment <= 8 ? 1 : 0 };
+ enum { Alignment_LessEqual_16Bytes = Alignment <= 16 ? 1 : 0 };
+
+};
+
+/// alignOf - A templated function that returns the minimum alignment of
+/// of a type. This provides no extra functionality beyond the AlignOf
+/// class besides some cosmetic cleanliness. Example usage:
+/// alignOf<int>() returns the alignment of an int.
+template <typename T>
+inline unsigned alignOf() { return AlignOf<T>::Alignment; }
+
+
+/// \brief Helper for building an aligned character array type.
+///
+/// This template is used to explicitly build up a collection of aligned
+/// character types. We have to build these up using a macro and explicit
+/// specialization to cope with old versions of MSVC and GCC where only an
+/// integer literal can be used to specify an alignment constraint. Once built
+/// up here, we can then begin to indirect between these using normal C++
+/// template parameters.
+template <size_t Alignment> struct AlignedCharArrayImpl;
+
+// MSVC requires special handling here.
+#ifndef _MSC_VER
+
+#if __has_feature(cxx_alignas)
+#define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \
+ template <> struct AlignedCharArrayImpl<x> { \
+ char alignas(x) aligned; \
+ }
+#elif defined(__GNUC__)
+#define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \
+ template <> struct AlignedCharArrayImpl<x> { \
+ char aligned __attribute__((aligned(x))); \
+ }
+#else
+# error No supported align as directive.
+#endif
+
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(512);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1024);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2048);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4096);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8192);
+
+#undef LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT
+
+#else // _MSC_VER
+
+// We provide special variations of this template for the most common
+// alignments because __declspec(align(...)) doesn't actually work when it is
+// a member of a by-value function argument in MSVC, even if the alignment
+// request is something reasonably like 8-byte or 16-byte.
+template <> struct AlignedCharArrayImpl<1> { char aligned; };
+template <> struct AlignedCharArrayImpl<2> { short aligned; };
+template <> struct AlignedCharArrayImpl<4> { int aligned; };
+template <> struct AlignedCharArrayImpl<8> { double aligned; };
+
+#define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \
+ template <> struct AlignedCharArrayImpl<x> { \
+ __declspec(align(x)) char aligned; \
+ }
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(512);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1024);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2048);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4096);
+LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8192);
+// Any larger and MSVC complains.
+#undef LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT
+
+#endif // _MSC_VER
+
+/// \brief This union template exposes a suitably aligned and sized character
+/// array member which can hold elements of any of up to four types.
+///
+/// These types may be arrays, structs, or any other types. The goal is to
+/// produce a union type containing a character array which, when used, forms
+/// storage suitable to placement new any of these types over. Support for more
+/// than four types can be added at the cost of more boiler plate.
+template <typename T1,
+ typename T2 = char, typename T3 = char, typename T4 = char>
+union AlignedCharArrayUnion {
+private:
+ class AlignerImpl {
+ T1 t1; T2 t2; T3 t3; T4 t4;
+
+ AlignerImpl(); // Never defined or instantiated.
+ };
+ union SizerImpl {
+ char arr1[sizeof(T1)], arr2[sizeof(T2)], arr3[sizeof(T3)], arr4[sizeof(T4)];
+ };
+
+public:
+ /// \brief The character array buffer for use by clients.
+ ///
+ /// No other member of this union should be referenced. The exist purely to
+ /// constrain the layout of this character array.
+ char buffer[sizeof(SizerImpl)];
+
+private:
+ // Tests seem to indicate that both Clang and GCC will properly register the
+ // alignment of a struct containing an aligned member, and this alignment
+ // should carry over to the character array in the union.
+ llvm::AlignedCharArrayImpl<AlignOf<AlignerImpl>::Alignment> nonce_member;
+};
+
+} // end namespace llvm
+#endif
diff --git a/include/llvm/Support/Allocator.h b/include/llvm/Support/Allocator.h
new file mode 100644
index 00000000000..6ad5f5cb816
--- /dev/null
+++ b/include/llvm/Support/Allocator.h
@@ -0,0 +1,242 @@
+//===--- Allocator.h - Simple memory allocation abstraction -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the MallocAllocator and BumpPtrAllocator interfaces.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_ALLOCATOR_H
+#define LLVM_SUPPORT_ALLOCATOR_H
+
+#include "llvm/Support/AlignOf.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/DataTypes.h"
+#include <algorithm>
+#include <cassert>
+#include <cstdlib>
+#include <cstddef>
+
+namespace llvm {
+template <typename T> struct ReferenceAdder { typedef T& result; };
+template <typename T> struct ReferenceAdder<T&> { typedef T result; };
+
+class MallocAllocator {
+public:
+ MallocAllocator() {}
+ ~MallocAllocator() {}
+
+ void Reset() {}
+
+ void *Allocate(size_t Size, size_t /*Alignment*/) { return malloc(Size); }
+
+ template <typename T>
+ T *Allocate() { return static_cast<T*>(malloc(sizeof(T))); }
+
+ template <typename T>
+ T *Allocate(size_t Num) {
+ return static_cast<T*>(malloc(sizeof(T)*Num));
+ }
+
+ void Deallocate(const void *Ptr) { free(const_cast<void*>(Ptr)); }
+
+ void PrintStats() const {}
+};
+
+/// MemSlab - This structure lives at the beginning of every slab allocated by
+/// the bump allocator.
+class MemSlab {
+public:
+ size_t Size;
+ MemSlab *NextPtr;
+};
+
+/// SlabAllocator - This class can be used to parameterize the underlying
+/// allocation strategy for the bump allocator. In particular, this is used
+/// by the JIT to allocate contiguous swathes of executable memory. The
+/// interface uses MemSlab's instead of void *'s so that the allocator
+/// doesn't have to remember the size of the pointer it allocated.
+class SlabAllocator {
+public:
+ virtual ~SlabAllocator();
+ virtual MemSlab *Allocate(size_t Size) = 0;
+ virtual void Deallocate(MemSlab *Slab) = 0;
+};
+
+/// MallocSlabAllocator - The default slab allocator for the bump allocator
+/// is an adapter class for MallocAllocator that just forwards the method
+/// calls and translates the arguments.
+class MallocSlabAllocator : public SlabAllocator {
+ /// Allocator - The underlying allocator that we forward to.
+ ///
+ MallocAllocator Allocator;
+
+public:
+ MallocSlabAllocator() : Allocator() { }
+ virtual ~MallocSlabAllocator();
+ virtual MemSlab *Allocate(size_t Size);
+ virtual void Deallocate(MemSlab *Slab);
+};
+
+/// BumpPtrAllocator - This allocator is useful for containers that need
+/// very simple memory allocation strategies. In particular, this just keeps
+/// allocating memory, and never deletes it until the entire block is dead. This
+/// makes allocation speedy, but must only be used when the trade-off is ok.
+class BumpPtrAllocator {
+ BumpPtrAllocator(const BumpPtrAllocator &) LLVM_DELETED_FUNCTION;
+ void operator=(const BumpPtrAllocator &) LLVM_DELETED_FUNCTION;
+
+ /// SlabSize - Allocate data into slabs of this size unless we get an
+ /// allocation above SizeThreshold.
+ size_t SlabSize;
+
+ /// SizeThreshold - For any allocation larger than this threshold, we should
+ /// allocate a separate slab.
+ size_t SizeThreshold;
+
+ /// Allocator - The underlying allocator we use to get slabs of memory. This
+ /// defaults to MallocSlabAllocator, which wraps malloc, but it could be
+ /// changed to use a custom allocator.
+ SlabAllocator &Allocator;
+
+ /// CurSlab - The slab that we are currently allocating into.
+ ///
+ MemSlab *CurSlab;
+
+ /// CurPtr - The current pointer into the current slab. This points to the
+ /// next free byte in the slab.
+ char *CurPtr;
+
+ /// End - The end of the current slab.
+ ///
+ char *End;
+
+ /// BytesAllocated - This field tracks how many bytes we've allocated, so
+ /// that we can compute how much space was wasted.
+ size_t BytesAllocated;
+
+ /// AlignPtr - Align Ptr to Alignment bytes, rounding up. Alignment should
+ /// be a power of two. This method rounds up, so AlignPtr(7, 4) == 8 and
+ /// AlignPtr(8, 4) == 8.
+ static char *AlignPtr(char *Ptr, size_t Alignment);
+
+ /// StartNewSlab - Allocate a new slab and move the bump pointers over into
+ /// the new slab. Modifies CurPtr and End.
+ void StartNewSlab();
+
+ /// DeallocateSlabs - Deallocate all memory slabs after and including this
+ /// one.
+ void DeallocateSlabs(MemSlab *Slab);
+
+ static MallocSlabAllocator DefaultSlabAllocator;
+
+ template<typename T> friend class SpecificBumpPtrAllocator;
+public:
+ BumpPtrAllocator(size_t size = 4096, size_t threshold = 4096,
+ SlabAllocator &allocator = DefaultSlabAllocator);
+ ~BumpPtrAllocator();
+
+ /// Reset - Deallocate all but the current slab and reset the current pointer
+ /// to the beginning of it, freeing all memory allocated so far.
+ void Reset();
+
+ /// Allocate - Allocate space at the specified alignment.
+ ///
+ void *Allocate(size_t Size, size_t Alignment);
+
+ /// Allocate space, but do not construct, one object.
+ ///
+ template <typename T>
+ T *Allocate() {
+ return static_cast<T*>(Allocate(sizeof(T),AlignOf<T>::Alignment));
+ }
+
+ /// Allocate space for an array of objects. This does not construct the
+ /// objects though.
+ template <typename T>
+ T *Allocate(size_t Num) {
+ return static_cast<T*>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment));
+ }
+
+ /// Allocate space for a specific count of elements and with a specified
+ /// alignment.
+ template <typename T>
+ T *Allocate(size_t Num, size_t Alignment) {
+ // Round EltSize up to the specified alignment.
+ size_t EltSize = (sizeof(T)+Alignment-1)&(-Alignment);
+ return static_cast<T*>(Allocate(Num * EltSize, Alignment));
+ }
+
+ void Deallocate(const void * /*Ptr*/) {}
+
+ unsigned GetNumSlabs() const;
+
+ void PrintStats() const;
+
+ /// Compute the total physical memory allocated by this allocator.
+ size_t getTotalMemory() const;
+};
+
+/// SpecificBumpPtrAllocator - Same as BumpPtrAllocator but allows only
+/// elements of one type to be allocated. This allows calling the destructor
+/// in DestroyAll() and when the allocator is destroyed.
+template <typename T>
+class SpecificBumpPtrAllocator {
+ BumpPtrAllocator Allocator;
+public:
+ SpecificBumpPtrAllocator(size_t size = 4096, size_t threshold = 4096,
+ SlabAllocator &allocator = BumpPtrAllocator::DefaultSlabAllocator)
+ : Allocator(size, threshold, allocator) {}
+
+ ~SpecificBumpPtrAllocator() {
+ DestroyAll();
+ }
+
+ /// Call the destructor of each allocated object and deallocate all but the
+ /// current slab and reset the current pointer to the beginning of it, freeing
+ /// all memory allocated so far.
+ void DestroyAll() {
+ MemSlab *Slab = Allocator.CurSlab;
+ while (Slab) {
+ char *End = Slab == Allocator.CurSlab ? Allocator.CurPtr :
+ (char *)Slab + Slab->Size;
+ for (char *Ptr = (char*)(Slab+1); Ptr < End; Ptr += sizeof(T)) {
+ Ptr = Allocator.AlignPtr(Ptr, alignOf<T>());
+ if (Ptr + sizeof(T) <= End)
+ reinterpret_cast<T*>(Ptr)->~T();
+ }
+ Slab = Slab->NextPtr;
+ }
+ Allocator.Reset();
+ }
+
+ /// Allocate space for a specific count of elements.
+ T *Allocate(size_t num = 1) {
+ return Allocator.Allocate<T>(num);
+ }
+};
+
+} // end namespace llvm
+
+inline void *operator new(size_t Size, llvm::BumpPtrAllocator &Allocator) {
+ struct S {
+ char c;
+ union {
+ double D;
+ long double LD;
+ long long L;
+ void *P;
+ } x;
+ };
+ return Allocator.Allocate(Size, std::min((size_t)llvm::NextPowerOf2(Size),
+ offsetof(S, x)));
+}
+
+inline void operator delete(void *, llvm::BumpPtrAllocator &) {}
+
+#endif // LLVM_SUPPORT_ALLOCATOR_H
diff --git a/include/llvm/Support/Atomic.h b/include/llvm/Support/Atomic.h
new file mode 100644
index 00000000000..1a6c606aa5f
--- /dev/null
+++ b/include/llvm/Support/Atomic.h
@@ -0,0 +1,39 @@
+//===- llvm/Support/Atomic.h - Atomic Operations -----------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file declares the llvm::sys atomic operations.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SYSTEM_ATOMIC_H
+#define LLVM_SYSTEM_ATOMIC_H
+
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+ namespace sys {
+ void MemoryFence();
+
+#ifdef _MSC_VER
+ typedef long cas_flag;
+#else
+ typedef uint32_t cas_flag;
+#endif
+ cas_flag CompareAndSwap(volatile cas_flag* ptr,
+ cas_flag new_value,
+ cas_flag old_value);
+ cas_flag AtomicIncrement(volatile cas_flag* ptr);
+ cas_flag AtomicDecrement(volatile cas_flag* ptr);
+ cas_flag AtomicAdd(volatile cas_flag* ptr, cas_flag val);
+ cas_flag AtomicMul(volatile cas_flag* ptr, cas_flag val);
+ cas_flag AtomicDiv(volatile cas_flag* ptr, cas_flag val);
+ }
+}
+
+#endif
diff --git a/include/llvm/Support/BlockFrequency.h b/include/llvm/Support/BlockFrequency.h
new file mode 100644
index 00000000000..839cf937124
--- /dev/null
+++ b/include/llvm/Support/BlockFrequency.h
@@ -0,0 +1,65 @@
+//===-------- BlockFrequency.h - Block Frequency Wrapper --------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements Block Frequency class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_BLOCKFREQUENCY_H
+#define LLVM_SUPPORT_BLOCKFREQUENCY_H
+
+#include "llvm/Support/DataTypes.h"
+
+namespace llvm {
+
+class raw_ostream;
+class BranchProbability;
+
+// This class represents Block Frequency as a 64-bit value.
+class BlockFrequency {
+
+ uint64_t Frequency;
+ static const int64_t ENTRY_FREQ = 1024;
+
+public:
+ BlockFrequency(uint64_t Freq = 0) : Frequency(Freq) { }
+
+ static uint64_t getEntryFrequency() { return ENTRY_FREQ; }
+ uint64_t getFrequency() const { return Frequency; }
+
+ BlockFrequency &operator*=(const BranchProbability &Prob);
+ const BlockFrequency operator*(const BranchProbability &Prob) const;
+
+ BlockFrequency &operator+=(const BlockFrequency &Freq);
+ const BlockFrequency operator+(const BlockFrequency &Freq) const;
+
+ bool operator<(const BlockFrequency &RHS) const {
+ return Frequency < RHS.Frequency;
+ }
+
+ bool operator<=(const BlockFrequency &RHS) const {
+ return Frequency <= RHS.Frequency;
+ }
+
+ bool operator>(const BlockFrequency &RHS) const {
+ return Frequency > RHS.Frequency;
+ }
+
+ bool operator>=(const BlockFrequency &RHS) const {
+ return Frequency >= RHS.Frequency;
+ }
+
+ void print(raw_ostream &OS) const;
+};
+
+raw_ostream &operator<<(raw_ostream &OS, const BlockFrequency &Freq);
+
+}
+
+#endif
diff --git a/include/llvm/Support/BranchProbability.h b/include/llvm/Support/BranchProbability.h
new file mode 100644
index 00000000000..eedf69247ef
--- /dev/null
+++ b/include/llvm/Support/BranchProbability.h
@@ -0,0 +1,77 @@
+//===- BranchProbability.h - Branch Probability Wrapper ---------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Definition of BranchProbability shared by IR and Machine Instructions.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_BRANCHPROBABILITY_H
+#define LLVM_SUPPORT_BRANCHPROBABILITY_H
+
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+
+namespace llvm {
+
+class raw_ostream;
+
+// This class represents Branch Probability as a non-negative fraction.
+class BranchProbability {
+ // Numerator
+ uint32_t N;
+
+ // Denominator
+ uint32_t D;
+
+public:
+ BranchProbability(uint32_t n, uint32_t d) : N(n), D(d) {
+ assert(d > 0 && "Denomiator cannot be 0!");
+ assert(n <= d && "Probability cannot be bigger than 1!");
+ }
+
+ static BranchProbability getZero() { return BranchProbability(0, 1); }
+ static BranchProbability getOne() { return BranchProbability(1, 1); }
+
+ uint32_t getNumerator() const { return N; }
+ uint32_t getDenominator() const { return D; }
+
+ // Return (1 - Probability).
+ BranchProbability getCompl() const {
+ return BranchProbability(D - N, D);
+ }
+
+ void print(raw_ostream &OS) const;
+
+ void dump() const;
+
+ bool operator==(BranchProbability RHS) const {
+ return (uint64_t)N * RHS.D == (uint64_t)D * RHS.N;
+ }
+ bool operator!=(BranchProbability RHS) const {
+ return !(*this == RHS);
+ }
+ bool operator<(BranchProbability RHS) const {
+ return (uint64_t)N * RHS.D < (uint64_t)D * RHS.N;
+ }
+ bool operator>(BranchProbability RHS) const {
+ return RHS < *this;
+ }
+ bool operator<=(BranchProbability RHS) const {
+ return (uint64_t)N * RHS.D <= (uint64_t)D * RHS.N;
+ }
+ bool operator>=(BranchProbability RHS) const {
+ return RHS <= *this;
+ }
+};
+
+raw_ostream &operator<<(raw_ostream &OS, const BranchProbability &Prob);
+
+}
+
+#endif
diff --git a/include/llvm/Support/CFG.h b/include/llvm/Support/CFG.h
new file mode 100644
index 00000000000..f5dc8ea055a
--- /dev/null
+++ b/include/llvm/Support/CFG.h
@@ -0,0 +1,357 @@
+//===-- llvm/Support/CFG.h - Process LLVM structures as graphs --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines specializations of GraphTraits that allow Function and
+// BasicBlock graphs to be treated as proper graphs for generic algorithms.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_CFG_H
+#define LLVM_SUPPORT_CFG_H
+
+#include "llvm/ADT/GraphTraits.h"
+#include "llvm/Function.h"
+#include "llvm/InstrTypes.h"
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// BasicBlock pred_iterator definition
+//===----------------------------------------------------------------------===//
+
+template <class Ptr, class USE_iterator> // Predecessor Iterator
+class PredIterator : public std::iterator<std::forward_iterator_tag,
+ Ptr, ptrdiff_t> {
+ typedef std::iterator<std::forward_iterator_tag, Ptr, ptrdiff_t> super;
+ typedef PredIterator<Ptr, USE_iterator> Self;
+ USE_iterator It;
+
+ inline void advancePastNonTerminators() {
+ // Loop to ignore non terminator uses (for example BlockAddresses).
+ while (!It.atEnd() && !isa<TerminatorInst>(*It))
+ ++It;
+ }
+
+public:
+ typedef typename super::pointer pointer;
+
+ PredIterator() {}
+ explicit inline PredIterator(Ptr *bb) : It(bb->use_begin()) {
+ advancePastNonTerminators();
+ }
+ inline PredIterator(Ptr *bb, bool) : It(bb->use_end()) {}
+
+ inline bool operator==(const Self& x) const { return It == x.It; }
+ inline bool operator!=(const Self& x) const { return !operator==(x); }
+
+ inline pointer operator*() const {
+ assert(!It.atEnd() && "pred_iterator out of range!");
+ return cast<TerminatorInst>(*It)->getParent();
+ }
+ inline pointer *operator->() const { return &operator*(); }
+
+ inline Self& operator++() { // Preincrement
+ assert(!It.atEnd() && "pred_iterator out of range!");
+ ++It; advancePastNonTerminators();
+ return *this;
+ }
+
+ inline Self operator++(int) { // Postincrement
+ Self tmp = *this; ++*this; return tmp;
+ }
+
+ /// getOperandNo - Return the operand number in the predecessor's
+ /// terminator of the successor.
+ unsigned getOperandNo() const {
+ return It.getOperandNo();
+ }
+
+ /// getUse - Return the operand Use in the predecessor's terminator
+ /// of the successor.
+ Use &getUse() const {
+ return It.getUse();
+ }
+};
+
+typedef PredIterator<BasicBlock, Value::use_iterator> pred_iterator;
+typedef PredIterator<const BasicBlock,
+ Value::const_use_iterator> const_pred_iterator;
+
+inline pred_iterator pred_begin(BasicBlock *BB) { return pred_iterator(BB); }
+inline const_pred_iterator pred_begin(const BasicBlock *BB) {
+ return const_pred_iterator(BB);
+}
+inline pred_iterator pred_end(BasicBlock *BB) { return pred_iterator(BB, true);}
+inline const_pred_iterator pred_end(const BasicBlock *BB) {
+ return const_pred_iterator(BB, true);
+}
+
+
+
+//===----------------------------------------------------------------------===//
+// BasicBlock succ_iterator definition
+//===----------------------------------------------------------------------===//
+
+template <class Term_, class BB_> // Successor Iterator
+class SuccIterator : public std::iterator<std::bidirectional_iterator_tag,
+ BB_, ptrdiff_t> {
+ const Term_ Term;
+ unsigned idx;
+ typedef std::iterator<std::bidirectional_iterator_tag, BB_, ptrdiff_t> super;
+ typedef SuccIterator<Term_, BB_> Self;
+
+ inline bool index_is_valid(int idx) {
+ return idx >= 0 && (unsigned) idx < Term->getNumSuccessors();
+ }
+
+public:
+ typedef typename super::pointer pointer;
+ // TODO: This can be random access iterator, only operator[] missing.
+
+ explicit inline SuccIterator(Term_ T) : Term(T), idx(0) {// begin iterator
+ }
+ inline SuccIterator(Term_ T, bool) // end iterator
+ : Term(T) {
+ if (Term)
+ idx = Term->getNumSuccessors();
+ else
+ // Term == NULL happens, if a basic block is not fully constructed and
+ // consequently getTerminator() returns NULL. In this case we construct a
+ // SuccIterator which describes a basic block that has zero successors.
+ // Defining SuccIterator for incomplete and malformed CFGs is especially
+ // useful for debugging.
+ idx = 0;
+ }
+
+ inline const Self &operator=(const Self &I) {
+ assert(Term == I.Term &&"Cannot assign iterators to two different blocks!");
+ idx = I.idx;
+ return *this;
+ }
+
+ /// getSuccessorIndex - This is used to interface between code that wants to
+ /// operate on terminator instructions directly.
+ unsigned getSuccessorIndex() const { return idx; }
+
+ inline bool operator==(const Self& x) const { return idx == x.idx; }
+ inline bool operator!=(const Self& x) const { return !operator==(x); }
+
+ inline pointer operator*() const { return Term->getSuccessor(idx); }
+ inline pointer operator->() const { return operator*(); }
+
+ inline Self& operator++() { ++idx; return *this; } // Preincrement
+
+ inline Self operator++(int) { // Postincrement
+ Self tmp = *this; ++*this; return tmp;
+ }
+
+ inline Self& operator--() { --idx; return *this; } // Predecrement
+ inline Self operator--(int) { // Postdecrement
+ Self tmp = *this; --*this; return tmp;
+ }
+
+ inline bool operator<(const Self& x) const {
+ assert(Term == x.Term && "Cannot compare iterators of different blocks!");
+ return idx < x.idx;
+ }
+
+ inline bool operator<=(const Self& x) const {
+ assert(Term == x.Term && "Cannot compare iterators of different blocks!");
+ return idx <= x.idx;
+ }
+ inline bool operator>=(const Self& x) const {
+ assert(Term == x.Term && "Cannot compare iterators of different blocks!");
+ return idx >= x.idx;
+ }
+
+ inline bool operator>(const Self& x) const {
+ assert(Term == x.Term && "Cannot compare iterators of different blocks!");
+ return idx > x.idx;
+ }
+
+ inline Self& operator+=(int Right) {
+ unsigned new_idx = idx + Right;
+ assert(index_is_valid(new_idx) && "Iterator index out of bound");
+ idx = new_idx;
+ return *this;
+ }
+
+ inline Self operator+(int Right) {
+ Self tmp = *this;
+ tmp += Right;
+ return tmp;
+ }
+
+ inline Self& operator-=(int Right) {
+ return operator+=(-Right);
+ }
+
+ inline Self operator-(int Right) {
+ return operator+(-Right);
+ }
+
+ inline int operator-(const Self& x) {
+ assert(Term == x.Term && "Cannot work on iterators of different blocks!");
+ int distance = idx - x.idx;
+ return distance;
+ }
+
+ // This works for read access, however write access is difficult as changes
+ // to Term are only possible with Term->setSuccessor(idx). Pointers that can
+ // be modified are not available.
+ //
+ // inline pointer operator[](int offset) {
+ // Self tmp = *this;
+ // tmp += offset;
+ // return tmp.operator*();
+ // }
+
+ /// Get the source BB of this iterator.
+ inline BB_ *getSource() {
+ assert(Term && "Source not available, if basic block was malformed");
+ return Term->getParent();
+ }
+};
+
+typedef SuccIterator<TerminatorInst*, BasicBlock> succ_iterator;
+typedef SuccIterator<const TerminatorInst*,
+ const BasicBlock> succ_const_iterator;
+
+inline succ_iterator succ_begin(BasicBlock *BB) {
+ return succ_iterator(BB->getTerminator());
+}
+inline succ_const_iterator succ_begin(const BasicBlock *BB) {
+ return succ_const_iterator(BB->getTerminator());
+}
+inline succ_iterator succ_end(BasicBlock *BB) {
+ return succ_iterator(BB->getTerminator(), true);
+}
+inline succ_const_iterator succ_end(const BasicBlock *BB) {
+ return succ_const_iterator(BB->getTerminator(), true);
+}
+
+
+
+//===--------------------------------------------------------------------===//
+// GraphTraits specializations for basic block graphs (CFGs)
+//===--------------------------------------------------------------------===//
+
+// Provide specializations of GraphTraits to be able to treat a function as a
+// graph of basic blocks...
+
+template <> struct GraphTraits<BasicBlock*> {
+ typedef BasicBlock NodeType;
+ typedef succ_iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(BasicBlock *BB) { return BB; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return succ_begin(N);
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return succ_end(N);
+ }
+};
+
+template <> struct GraphTraits<const BasicBlock*> {
+ typedef const BasicBlock NodeType;
+ typedef succ_const_iterator ChildIteratorType;
+
+ static NodeType *getEntryNode(const BasicBlock *BB) { return BB; }
+
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return succ_begin(N);
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return succ_end(N);
+ }
+};
+
+// Provide specializations of GraphTraits to be able to treat a function as a
+// graph of basic blocks... and to walk it in inverse order. Inverse order for
+// a function is considered to be when traversing the predecessor edges of a BB
+// instead of the successor edges.
+//
+template <> struct GraphTraits<Inverse<BasicBlock*> > {
+ typedef BasicBlock NodeType;
+ typedef pred_iterator ChildIteratorType;
+ static NodeType *getEntryNode(Inverse<BasicBlock *> G) { return G.Graph; }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return pred_begin(N);
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return pred_end(N);
+ }
+};
+
+template <> struct GraphTraits<Inverse<const BasicBlock*> > {
+ typedef const BasicBlock NodeType;
+ typedef const_pred_iterator ChildIteratorType;
+ static NodeType *getEntryNode(Inverse<const BasicBlock*> G) {
+ return G.Graph;
+ }
+ static inline ChildIteratorType child_begin(NodeType *N) {
+ return pred_begin(N);
+ }
+ static inline ChildIteratorType child_end(NodeType *N) {
+ return pred_end(N);
+ }
+};
+
+
+
+//===--------------------------------------------------------------------===//
+// GraphTraits specializations for function basic block graphs (CFGs)
+//===--------------------------------------------------------------------===//
+
+// Provide specializations of GraphTraits to be able to treat a function as a
+// graph of basic blocks... these are the same as the basic block iterators,
+// except that the root node is implicitly the first node of the function.
+//
+template <> struct GraphTraits<Function*> : public GraphTraits<BasicBlock*> {
+ static NodeType *getEntryNode(Function *F) { return &F->getEntryBlock(); }
+
+ // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
+ typedef Function::iterator nodes_iterator;
+ static nodes_iterator nodes_begin(Function *F) { return F->begin(); }
+ static nodes_iterator nodes_end (Function *F) { return F->end(); }
+ static unsigned size (Function *F) { return F->size(); }
+};
+template <> struct GraphTraits<const Function*> :
+ public GraphTraits<const BasicBlock*> {
+ static NodeType *getEntryNode(const Function *F) {return &F->getEntryBlock();}
+
+ // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
+ typedef Function::const_iterator nodes_iterator;
+ static nodes_iterator nodes_begin(const Function *F) { return F->begin(); }
+ static nodes_iterator nodes_end (const Function *F) { return F->end(); }
+ static unsigned size (const Function *F) { return F->size(); }
+};
+
+
+// Provide specializations of GraphTraits to be able to treat a function as a
+// graph of basic blocks... and to walk it in inverse order. Inverse order for
+// a function is considered to be when traversing the predecessor edges of a BB
+// instead of the successor edges.
+//
+template <> struct GraphTraits<Inverse<Function*> > :
+ public GraphTraits<Inverse<BasicBlock*> > {
+ static NodeType *getEntryNode(Inverse<Function*> G) {
+ return &G.Graph->getEntryBlock();
+ }
+};
+template <> struct GraphTraits<Inverse<const Function*> > :
+ public GraphTraits<Inverse<const BasicBlock*> > {
+ static NodeType *getEntryNode(Inverse<const Function *> G) {
+ return &G.Graph->getEntryBlock();
+ }
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Support/COFF.h b/include/llvm/Support/COFF.h
new file mode 100644
index 00000000000..ba8adb01817
--- /dev/null
+++ b/include/llvm/Support/COFF.h
@@ -0,0 +1,594 @@
+//===-- llvm/Support/COFF.h -------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains an definitions used in Windows COFF Files.
+//
+// Structures and enums defined within this file where created using
+// information from Microsoft's publicly available PE/COFF format document:
+//
+// Microsoft Portable Executable and Common Object File Format Specification
+// Revision 8.1 - February 15, 2008
+//
+// As of 5/2/2010, hosted by Microsoft at:
+// http://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_WIN_COFF_H
+#define LLVM_SUPPORT_WIN_COFF_H
+
+#include "llvm/Support/DataTypes.h"
+#include <cassert>
+#include <cstring>
+
+namespace llvm {
+namespace COFF {
+
+ // Sizes in bytes of various things in the COFF format.
+ enum {
+ HeaderSize = 20,
+ NameSize = 8,
+ SymbolSize = 18,
+ SectionSize = 40,
+ RelocationSize = 10
+ };
+
+ struct header {
+ uint16_t Machine;
+ uint16_t NumberOfSections;
+ uint32_t TimeDateStamp;
+ uint32_t PointerToSymbolTable;
+ uint32_t NumberOfSymbols;
+ uint16_t SizeOfOptionalHeader;
+ uint16_t Characteristics;
+ };
+
+ enum MachineTypes {
+ MT_Invalid = 0xffff,
+
+ IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
+ IMAGE_FILE_MACHINE_AM33 = 0x13,
+ IMAGE_FILE_MACHINE_AMD64 = 0x8664,
+ IMAGE_FILE_MACHINE_ARM = 0x1C0,
+ IMAGE_FILE_MACHINE_ARMV7 = 0x1C4,
+ IMAGE_FILE_MACHINE_EBC = 0xEBC,
+ IMAGE_FILE_MACHINE_I386 = 0x14C,
+ IMAGE_FILE_MACHINE_IA64 = 0x200,
+ IMAGE_FILE_MACHINE_M32R = 0x9041,
+ IMAGE_FILE_MACHINE_MIPS16 = 0x266,
+ IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
+ IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
+ IMAGE_FILE_MACHINE_POWERPC = 0x1F0,
+ IMAGE_FILE_MACHINE_POWERPCFP = 0x1F1,
+ IMAGE_FILE_MACHINE_R4000 = 0x166,
+ IMAGE_FILE_MACHINE_SH3 = 0x1A2,
+ IMAGE_FILE_MACHINE_SH3DSP = 0x1A3,
+ IMAGE_FILE_MACHINE_SH4 = 0x1A6,
+ IMAGE_FILE_MACHINE_SH5 = 0x1A8,
+ IMAGE_FILE_MACHINE_THUMB = 0x1C2,
+ IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169
+ };
+
+ enum Characteristics {
+ C_Invalid = 0,
+
+ /// The file does not contain base relocations and must be loaded at its
+ /// preferred base. If this cannot be done, the loader will error.
+ IMAGE_FILE_RELOCS_STRIPPED = 0x0001,
+ /// The file is valid and can be run.
+ IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002,
+ /// COFF line numbers have been stripped. This is deprecated and should be
+ /// 0.
+ IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004,
+ /// COFF symbol table entries for local symbols have been removed. This is
+ /// deprecated and should be 0.
+ IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008,
+ /// Aggressively trim working set. This is deprecated and must be 0.
+ IMAGE_FILE_AGGRESSIVE_WS_TRIM = 0x0010,
+ /// Image can handle > 2GiB addresses.
+ IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020,
+ /// Little endian: the LSB precedes the MSB in memory. This is deprecated
+ /// and should be 0.
+ IMAGE_FILE_BYTES_REVERSED_LO = 0x0080,
+ /// Machine is based on a 32bit word architecture.
+ IMAGE_FILE_32BIT_MACHINE = 0x0100,
+ /// Debugging info has been removed.
+ IMAGE_FILE_DEBUG_STRIPPED = 0x0200,
+ /// If the image is on removable media, fully load it and copy it to swap.
+ IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400,
+ /// If the image is on network media, fully load it and copy it to swap.
+ IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800,
+ /// The image file is a system file, not a user program.
+ IMAGE_FILE_SYSTEM = 0x1000,
+ /// The image file is a DLL.
+ IMAGE_FILE_DLL = 0x2000,
+ /// This file should only be run on a uniprocessor machine.
+ IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000,
+ /// Big endian: the MSB precedes the LSB in memory. This is deprecated
+ /// and should be 0.
+ IMAGE_FILE_BYTES_REVERSED_HI = 0x8000
+ };
+
+ struct symbol {
+ char Name[NameSize];
+ uint32_t Value;
+ uint16_t SectionNumber;
+ uint16_t Type;
+ uint8_t StorageClass;
+ uint8_t NumberOfAuxSymbols;
+ };
+
+ enum SymbolFlags {
+ SF_TypeMask = 0x0000FFFF,
+ SF_TypeShift = 0,
+
+ SF_ClassMask = 0x00FF0000,
+ SF_ClassShift = 16,
+
+ SF_WeakExternal = 0x01000000
+ };
+
+ enum SymbolSectionNumber {
+ IMAGE_SYM_DEBUG = -2,
+ IMAGE_SYM_ABSOLUTE = -1,
+ IMAGE_SYM_UNDEFINED = 0
+ };
+
+ /// Storage class tells where and what the symbol represents
+ enum SymbolStorageClass {
+ SSC_Invalid = 0xff,
+
+ IMAGE_SYM_CLASS_END_OF_FUNCTION = -1, ///< Physical end of function
+ IMAGE_SYM_CLASS_NULL = 0, ///< No symbol
+ IMAGE_SYM_CLASS_AUTOMATIC = 1, ///< Stack variable
+ IMAGE_SYM_CLASS_EXTERNAL = 2, ///< External symbol
+ IMAGE_SYM_CLASS_STATIC = 3, ///< Static
+ IMAGE_SYM_CLASS_REGISTER = 4, ///< Register variable
+ IMAGE_SYM_CLASS_EXTERNAL_DEF = 5, ///< External definition
+ IMAGE_SYM_CLASS_LABEL = 6, ///< Label
+ IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7, ///< Undefined label
+ IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8, ///< Member of structure
+ IMAGE_SYM_CLASS_ARGUMENT = 9, ///< Function argument
+ IMAGE_SYM_CLASS_STRUCT_TAG = 10, ///< Structure tag
+ IMAGE_SYM_CLASS_MEMBER_OF_UNION = 11, ///< Member of union
+ IMAGE_SYM_CLASS_UNION_TAG = 12, ///< Union tag
+ IMAGE_SYM_CLASS_TYPE_DEFINITION = 13, ///< Type definition
+ IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14, ///< Undefined static
+ IMAGE_SYM_CLASS_ENUM_TAG = 15, ///< Enumeration tag
+ IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16, ///< Member of enumeration
+ IMAGE_SYM_CLASS_REGISTER_PARAM = 17, ///< Register parameter
+ IMAGE_SYM_CLASS_BIT_FIELD = 18, ///< Bit field
+ /// ".bb" or ".eb" - beginning or end of block
+ IMAGE_SYM_CLASS_BLOCK = 100,
+ /// ".bf" or ".ef" - beginning or end of function
+ IMAGE_SYM_CLASS_FUNCTION = 101,
+ IMAGE_SYM_CLASS_END_OF_STRUCT = 102, ///< End of structure
+ IMAGE_SYM_CLASS_FILE = 103, ///< File name
+ /// Line number, reformatted as symbol
+ IMAGE_SYM_CLASS_SECTION = 104,
+ IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105, ///< Duplicate tag
+ /// External symbol in dmert public lib
+ IMAGE_SYM_CLASS_CLR_TOKEN = 107
+ };
+
+ enum SymbolBaseType {
+ IMAGE_SYM_TYPE_NULL = 0, ///< No type information or unknown base type.
+ IMAGE_SYM_TYPE_VOID = 1, ///< Used with void pointers and functions.
+ IMAGE_SYM_TYPE_CHAR = 2, ///< A character (signed byte).
+ IMAGE_SYM_TYPE_SHORT = 3, ///< A 2-byte signed integer.
+ IMAGE_SYM_TYPE_INT = 4, ///< A natural integer type on the target.
+ IMAGE_SYM_TYPE_LONG = 5, ///< A 4-byte signed integer.
+ IMAGE_SYM_TYPE_FLOAT = 6, ///< A 4-byte floating-point number.
+ IMAGE_SYM_TYPE_DOUBLE = 7, ///< An 8-byte floating-point number.
+ IMAGE_SYM_TYPE_STRUCT = 8, ///< A structure.
+ IMAGE_SYM_TYPE_UNION = 9, ///< An union.
+ IMAGE_SYM_TYPE_ENUM = 10, ///< An enumerated type.
+ IMAGE_SYM_TYPE_MOE = 11, ///< A member of enumeration (a specific value).
+ IMAGE_SYM_TYPE_BYTE = 12, ///< A byte; unsigned 1-byte integer.
+ IMAGE_SYM_TYPE_WORD = 13, ///< A word; unsigned 2-byte integer.
+ IMAGE_SYM_TYPE_UINT = 14, ///< An unsigned integer of natural size.
+ IMAGE_SYM_TYPE_DWORD = 15 ///< An unsigned 4-byte integer.
+ };
+
+ enum SymbolComplexType {
+ IMAGE_SYM_DTYPE_NULL = 0, ///< No complex type; simple scalar variable.
+ IMAGE_SYM_DTYPE_POINTER = 1, ///< A pointer to base type.
+ IMAGE_SYM_DTYPE_FUNCTION = 2, ///< A function that returns a base type.
+ IMAGE_SYM_DTYPE_ARRAY = 3, ///< An array of base type.
+
+ /// Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
+ SCT_COMPLEX_TYPE_SHIFT = 4
+ };
+
+ struct section {
+ char Name[NameSize];
+ uint32_t VirtualSize;
+ uint32_t VirtualAddress;
+ uint32_t SizeOfRawData;
+ uint32_t PointerToRawData;
+ uint32_t PointerToRelocations;
+ uint32_t PointerToLineNumbers;
+ uint16_t NumberOfRelocations;
+ uint16_t NumberOfLineNumbers;
+ uint32_t Characteristics;
+ };
+
+ enum SectionCharacteristics {
+ SC_Invalid = 0xffffffff,
+
+ IMAGE_SCN_TYPE_NO_PAD = 0x00000008,
+ IMAGE_SCN_CNT_CODE = 0x00000020,
+ IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040,
+ IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080,
+ IMAGE_SCN_LNK_OTHER = 0x00000100,
+ IMAGE_SCN_LNK_INFO = 0x00000200,
+ IMAGE_SCN_LNK_REMOVE = 0x00000800,
+ IMAGE_SCN_LNK_COMDAT = 0x00001000,
+ IMAGE_SCN_GPREL = 0x00008000,
+ IMAGE_SCN_MEM_PURGEABLE = 0x00020000,
+ IMAGE_SCN_MEM_16BIT = 0x00020000,
+ IMAGE_SCN_MEM_LOCKED = 0x00040000,
+ IMAGE_SCN_MEM_PRELOAD = 0x00080000,
+ IMAGE_SCN_ALIGN_1BYTES = 0x00100000,
+ IMAGE_SCN_ALIGN_2BYTES = 0x00200000,
+ IMAGE_SCN_ALIGN_4BYTES = 0x00300000,
+ IMAGE_SCN_ALIGN_8BYTES = 0x00400000,
+ IMAGE_SCN_ALIGN_16BYTES = 0x00500000,
+ IMAGE_SCN_ALIGN_32BYTES = 0x00600000,
+ IMAGE_SCN_ALIGN_64BYTES = 0x00700000,
+ IMAGE_SCN_ALIGN_128BYTES = 0x00800000,
+ IMAGE_SCN_ALIGN_256BYTES = 0x00900000,
+ IMAGE_SCN_ALIGN_512BYTES = 0x00A00000,
+ IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000,
+ IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000,
+ IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000,
+ IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000,
+ IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000,
+ IMAGE_SCN_MEM_DISCARDABLE = 0x02000000,
+ IMAGE_SCN_MEM_NOT_CACHED = 0x04000000,
+ IMAGE_SCN_MEM_NOT_PAGED = 0x08000000,
+ IMAGE_SCN_MEM_SHARED = 0x10000000,
+ IMAGE_SCN_MEM_EXECUTE = 0x20000000,
+ IMAGE_SCN_MEM_READ = 0x40000000,
+ IMAGE_SCN_MEM_WRITE = 0x80000000
+ };
+
+ struct relocation {
+ uint32_t VirtualAddress;
+ uint32_t SymbolTableIndex;
+ uint16_t Type;
+ };
+
+ enum RelocationTypeX86 {
+ IMAGE_REL_I386_ABSOLUTE = 0x0000,
+ IMAGE_REL_I386_DIR16 = 0x0001,
+ IMAGE_REL_I386_REL16 = 0x0002,
+ IMAGE_REL_I386_DIR32 = 0x0006,
+ IMAGE_REL_I386_DIR32NB = 0x0007,
+ IMAGE_REL_I386_SEG12 = 0x0009,
+ IMAGE_REL_I386_SECTION = 0x000A,
+ IMAGE_REL_I386_SECREL = 0x000B,
+ IMAGE_REL_I386_TOKEN = 0x000C,
+ IMAGE_REL_I386_SECREL7 = 0x000D,
+ IMAGE_REL_I386_REL32 = 0x0014,
+
+ IMAGE_REL_AMD64_ABSOLUTE = 0x0000,
+ IMAGE_REL_AMD64_ADDR64 = 0x0001,
+ IMAGE_REL_AMD64_ADDR32 = 0x0002,
+ IMAGE_REL_AMD64_ADDR32NB = 0x0003,
+ IMAGE_REL_AMD64_REL32 = 0x0004,
+ IMAGE_REL_AMD64_REL32_1 = 0x0005,
+ IMAGE_REL_AMD64_REL32_2 = 0x0006,
+ IMAGE_REL_AMD64_REL32_3 = 0x0007,
+ IMAGE_REL_AMD64_REL32_4 = 0x0008,
+ IMAGE_REL_AMD64_REL32_5 = 0x0009,
+ IMAGE_REL_AMD64_SECTION = 0x000A,
+ IMAGE_REL_AMD64_SECREL = 0x000B,
+ IMAGE_REL_AMD64_SECREL7 = 0x000C,
+ IMAGE_REL_AMD64_TOKEN = 0x000D,
+ IMAGE_REL_AMD64_SREL32 = 0x000E,
+ IMAGE_REL_AMD64_PAIR = 0x000F,
+ IMAGE_REL_AMD64_SSPAN32 = 0x0010
+ };
+
+ enum RelocationTypesARM {
+ IMAGE_REL_ARM_ABSOLUTE = 0x0000,
+ IMAGE_REL_ARM_ADDR32 = 0x0001,
+ IMAGE_REL_ARM_ADDR32NB = 0x0002,
+ IMAGE_REL_ARM_BRANCH24 = 0x0003,
+ IMAGE_REL_ARM_BRANCH11 = 0x0004,
+ IMAGE_REL_ARM_TOKEN = 0x0005,
+ IMAGE_REL_ARM_BLX24 = 0x0008,
+ IMAGE_REL_ARM_BLX11 = 0x0009,
+ IMAGE_REL_ARM_SECTION = 0x000E,
+ IMAGE_REL_ARM_SECREL = 0x000F,
+ IMAGE_REL_ARM_MOV32A = 0x0010,
+ IMAGE_REL_ARM_MOV32T = 0x0011,
+ IMAGE_REL_ARM_BRANCH20T = 0x0012,
+ IMAGE_REL_ARM_BRANCH24T = 0x0014,
+ IMAGE_REL_ARM_BLX23T = 0x0015
+ };
+
+ enum COMDATType {
+ IMAGE_COMDAT_SELECT_NODUPLICATES = 1,
+ IMAGE_COMDAT_SELECT_ANY,
+ IMAGE_COMDAT_SELECT_SAME_SIZE,
+ IMAGE_COMDAT_SELECT_EXACT_MATCH,
+ IMAGE_COMDAT_SELECT_ASSOCIATIVE,
+ IMAGE_COMDAT_SELECT_LARGEST
+ };
+
+ // Auxiliary Symbol Formats
+ struct AuxiliaryFunctionDefinition {
+ uint32_t TagIndex;
+ uint32_t TotalSize;
+ uint32_t PointerToLinenumber;
+ uint32_t PointerToNextFunction;
+ uint8_t unused[2];
+ };
+
+ struct AuxiliarybfAndefSymbol {
+ uint8_t unused1[4];
+ uint16_t Linenumber;
+ uint8_t unused2[6];
+ uint32_t PointerToNextFunction;
+ uint8_t unused3[2];
+ };
+
+ struct AuxiliaryWeakExternal {
+ uint32_t TagIndex;
+ uint32_t Characteristics;
+ uint8_t unused[10];
+ };
+
+ /// These are not documented in the spec, but are located in WinNT.h.
+ enum WeakExternalCharacteristics {
+ IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1,
+ IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2,
+ IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3
+ };
+
+ struct AuxiliaryFile {
+ uint8_t FileName[18];
+ };
+
+ struct AuxiliarySectionDefinition {
+ uint32_t Length;
+ uint16_t NumberOfRelocations;
+ uint16_t NumberOfLinenumbers;
+ uint32_t CheckSum;
+ uint16_t Number;
+ uint8_t Selection;
+ uint8_t unused[3];
+ };
+
+ union Auxiliary {
+ AuxiliaryFunctionDefinition FunctionDefinition;
+ AuxiliarybfAndefSymbol bfAndefSymbol;
+ AuxiliaryWeakExternal WeakExternal;
+ AuxiliaryFile File;
+ AuxiliarySectionDefinition SectionDefinition;
+ };
+
+ /// @brief The Import Directory Table.
+ ///
+ /// There is a single array of these and one entry per imported DLL.
+ struct ImportDirectoryTableEntry {
+ uint32_t ImportLookupTableRVA;
+ uint32_t TimeDateStamp;
+ uint32_t ForwarderChain;
+ uint32_t NameRVA;
+ uint32_t ImportAddressTableRVA;
+ };
+
+ /// @brief The PE32 Import Lookup Table.
+ ///
+ /// There is an array of these for each imported DLL. It represents either
+ /// the ordinal to import from the target DLL, or a name to lookup and import
+ /// from the target DLL.
+ ///
+ /// This also happens to be the same format used by the Import Address Table
+ /// when it is initially written out to the image.
+ struct ImportLookupTableEntry32 {
+ uint32_t data;
+
+ /// @brief Is this entry specified by ordinal, or name?
+ bool isOrdinal() const { return data & 0x80000000; }
+
+ /// @brief Get the ordinal value of this entry. isOrdinal must be true.
+ uint16_t getOrdinal() const {
+ assert(isOrdinal() && "ILT entry is not an ordinal!");
+ return data & 0xFFFF;
+ }
+
+ /// @brief Set the ordinal value and set isOrdinal to true.
+ void setOrdinal(uint16_t o) {
+ data = o;
+ data |= 0x80000000;
+ }
+
+ /// @brief Get the Hint/Name entry RVA. isOrdinal must be false.
+ uint32_t getHintNameRVA() const {
+ assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
+ return data;
+ }
+
+ /// @brief Set the Hint/Name entry RVA and set isOrdinal to false.
+ void setHintNameRVA(uint32_t rva) { data = rva; }
+ };
+
+ /// @brief The DOS compatible header at the front of all PEs.
+ struct DOSHeader {
+ uint16_t Magic;
+ uint16_t UsedBytesInTheLastPage;
+ uint16_t FileSizeInPages;
+ uint16_t NumberOfRelocationItems;
+ uint16_t HeaderSizeInParagraphs;
+ uint16_t MinimumExtraParagraphs;
+ uint16_t MaximumExtraParagraphs;
+ uint16_t InitialRelativeSS;
+ uint16_t InitialSP;
+ uint16_t Checksum;
+ uint16_t InitialIP;
+ uint16_t InitialRelativeCS;
+ uint16_t AddressOfRelocationTable;
+ uint16_t OverlayNumber;
+ uint16_t Reserved[4];
+ uint16_t OEMid;
+ uint16_t OEMinfo;
+ uint16_t Reserved2[10];
+ uint32_t AddressOfNewExeHeader;
+ };
+
+ struct PEHeader {
+ uint32_t Signature;
+ header COFFHeader;
+ uint16_t Magic;
+ uint8_t MajorLinkerVersion;
+ uint8_t MinorLinkerVersion;
+ uint32_t SizeOfCode;
+ uint32_t SizeOfInitializedData;
+ uint32_t SizeOfUninitializedData;
+ uint32_t AddressOfEntryPoint; // RVA
+ uint32_t BaseOfCode; // RVA
+ uint32_t BaseOfData; // RVA
+ uint64_t ImageBase;
+ uint32_t SectionAlignment;
+ uint32_t FileAlignment;
+ uint16_t MajorOperatingSystemVersion;
+ uint16_t MinorOperatingSystemVersion;
+ uint16_t MajorImageVersion;
+ uint16_t MinorImageVersion;
+ uint16_t MajorSubsystemVersion;
+ uint16_t MinorSubsystemVersion;
+ uint32_t Win32VersionValue;
+ uint32_t SizeOfImage;
+ uint32_t SizeOfHeaders;
+ uint32_t CheckSum;
+ uint16_t Subsystem;
+ uint16_t DLLCharacteristics;
+ uint64_t SizeOfStackReserve;
+ uint64_t SizeOfStackCommit;
+ uint64_t SizeOfHeapReserve;
+ uint64_t SizeOfHeapCommit;
+ uint32_t LoaderFlags;
+ uint32_t NumberOfRvaAndSize;
+ };
+
+ struct DataDirectory {
+ uint32_t RelativeVirtualAddress;
+ uint32_t Size;
+ };
+
+ enum WindowsSubsystem {
+ IMAGE_SUBSYSTEM_UNKNOWN = 0, ///< An unknown subsystem.
+ IMAGE_SUBSYSTEM_NATIVE = 1, ///< Device drivers and native Windows processes
+ IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, ///< The Windows GUI subsystem.
+ IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, ///< The Windows character subsystem.
+ IMAGE_SUBSYSTEM_POSIX_CUI = 7, ///< The POSIX character subsystem.
+ IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9, ///< Windows CE.
+ IMAGE_SUBSYSTEM_EFI_APPLICATION = 10, ///< An EFI application.
+ IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, ///< An EFI driver with boot
+ /// services.
+ IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, ///< An EFI driver with run-time
+ /// services.
+ IMAGE_SUBSYSTEM_EFI_ROM = 13, ///< An EFI ROM image.
+ IMAGE_SUBSYSTEM_XBOX = 14 ///< XBOX.
+ };
+
+ enum DLLCharacteristics {
+ /// DLL can be relocated at load time.
+ IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040,
+ /// Code integrity checks are enforced.
+ IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080,
+ IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100, ///< Image is NX compatible.
+ /// Isolation aware, but do not isolate the image.
+ IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION = 0x0200,
+ /// Does not use structured exception handling (SEH). No SEH handler may be
+ /// called in this image.
+ IMAGE_DLL_CHARACTERISTICS_NO_SEH = 0x0400,
+ /// Do not bind the image.
+ IMAGE_DLL_CHARACTERISTICS_NO_BIND = 0x0800,
+ IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER = 0x2000, ///< A WDM driver.
+ /// Terminal Server aware.
+ IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
+ };
+
+ enum DebugType {
+ IMAGE_DEBUG_TYPE_UNKNOWN = 0,
+ IMAGE_DEBUG_TYPE_COFF = 1,
+ IMAGE_DEBUG_TYPE_CODEVIEW = 2,
+ IMAGE_DEBUG_TYPE_FPO = 3,
+ IMAGE_DEBUG_TYPE_MISC = 4,
+ IMAGE_DEBUG_TYPE_EXCEPTION = 5,
+ IMAGE_DEBUG_TYPE_FIXUP = 6,
+ IMAGE_DEBUG_TYPE_OMAP_TO_SRC = 7,
+ IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = 8,
+ IMAGE_DEBUG_TYPE_BORLAND = 9,
+ IMAGE_DEBUG_TYPE_CLSID = 11
+ };
+
+ enum BaseRelocationType {
+ IMAGE_REL_BASED_ABSOLUTE = 0,
+ IMAGE_REL_BASED_HIGH = 1,
+ IMAGE_REL_BASED_LOW = 2,
+ IMAGE_REL_BASED_HIGHLOW = 3,
+ IMAGE_REL_BASED_HIGHADJ = 4,
+ IMAGE_REL_BASED_MIPS_JMPADDR = 5,
+ IMAGE_REL_BASED_ARM_MOV32A = 5,
+ IMAGE_REL_BASED_ARM_MOV32T = 7,
+ IMAGE_REL_BASED_MIPS_JMPADDR16 = 9,
+ IMAGE_REL_BASED_DIR64 = 10
+ };
+
+ enum ImportType {
+ IMPORT_CODE = 0,
+ IMPORT_DATA = 1,
+ IMPORT_CONST = 2
+ };
+
+ enum ImportNameType {
+ /// Import is by ordinal. This indicates that the value in the Ordinal/Hint
+ /// field of the import header is the import's ordinal. If this constant is
+ /// not specified, then the Ordinal/Hint field should always be interpreted
+ /// as the import's hint.
+ IMPORT_ORDINAL = 0,
+ /// The import name is identical to the public symbol name
+ IMPORT_NAME = 1,
+ /// The import name is the public symbol name, but skipping the leading ?,
+ /// @, or optionally _.
+ IMPORT_NAME_NOPREFIX = 2,
+ /// The import name is the public symbol name, but skipping the leading ?,
+ /// @, or optionally _, and truncating at the first @.
+ IMPORT_NAME_UNDECORATE = 3
+ };
+
+ struct ImportHeader {
+ uint16_t Sig1; ///< Must be IMAGE_FILE_MACHINE_UNKNOWN (0).
+ uint16_t Sig2; ///< Must be 0xFFFF.
+ uint16_t Version;
+ uint16_t Machine;
+ uint32_t TimeDateStamp;
+ uint32_t SizeOfData;
+ uint16_t OrdinalHint;
+ uint16_t TypeInfo;
+
+ ImportType getType() const {
+ return static_cast<ImportType>(TypeInfo & 0x3);
+ }
+
+ ImportNameType getNameType() const {
+ return static_cast<ImportNameType>((TypeInfo & 0x1C) >> 3);
+ }
+ };
+
+} // End namespace COFF.
+} // End namespace llvm.
+
+#endif
diff --git a/include/llvm/Support/CallSite.h b/include/llvm/Support/CallSite.h
new file mode 100644
index 00000000000..8905e1e33b7
--- /dev/null
+++ b/include/llvm/Support/CallSite.h
@@ -0,0 +1,316 @@
+//===-- llvm/Support/CallSite.h - Abstract Call & Invoke instrs -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the CallSite class, which is a handy wrapper for code that
+// wants to treat Call and Invoke instructions in a generic way. When in non-
+// mutation context (e.g. an analysis) ImmutableCallSite should be used.
+// Finally, when some degree of customization is necessary between these two
+// extremes, CallSiteBase<> can be supplied with fine-tuned parameters.
+//
+// NOTE: These classes are supposed to have "value semantics". So they should be
+// passed by value, not by reference; they should not be "new"ed or "delete"d.
+// They are efficiently copyable, assignable and constructable, with cost
+// equivalent to copying a pointer (notice that they have only a single data
+// member). The internal representation carries a flag which indicates which of
+// the two variants is enclosed. This allows for cheaper checks when various
+// accessors of CallSite are employed.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_CALLSITE_H
+#define LLVM_SUPPORT_CALLSITE_H
+
+#include "llvm/Attributes.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/BasicBlock.h"
+#include "llvm/CallingConv.h"
+#include "llvm/Instructions.h"
+
+namespace llvm {
+
+class CallInst;
+class InvokeInst;
+
+template <typename FunTy = const Function,
+ typename ValTy = const Value,
+ typename UserTy = const User,
+ typename InstrTy = const Instruction,
+ typename CallTy = const CallInst,
+ typename InvokeTy = const InvokeInst,
+ typename IterTy = User::const_op_iterator>
+class CallSiteBase {
+protected:
+ PointerIntPair<InstrTy*, 1, bool> I;
+public:
+ CallSiteBase() : I(0, false) {}
+ CallSiteBase(CallTy *CI) : I(CI, true) { assert(CI); }
+ CallSiteBase(InvokeTy *II) : I(II, false) { assert(II); }
+ CallSiteBase(ValTy *II) { *this = get(II); }
+protected:
+ /// CallSiteBase::get - This static method is sort of like a constructor. It
+ /// will create an appropriate call site for a Call or Invoke instruction, but
+ /// it can also create a null initialized CallSiteBase object for something
+ /// which is NOT a call site.
+ ///
+ static CallSiteBase get(ValTy *V) {
+ if (InstrTy *II = dyn_cast<InstrTy>(V)) {
+ if (II->getOpcode() == Instruction::Call)
+ return CallSiteBase(static_cast<CallTy*>(II));
+ else if (II->getOpcode() == Instruction::Invoke)
+ return CallSiteBase(static_cast<InvokeTy*>(II));
+ }
+ return CallSiteBase();
+ }
+public:
+ /// isCall - true if a CallInst is enclosed.
+ /// Note that !isCall() does not mean it is an InvokeInst enclosed,
+ /// it also could signify a NULL Instruction pointer.
+ bool isCall() const { return I.getInt(); }
+
+ /// isInvoke - true if a InvokeInst is enclosed.
+ ///
+ bool isInvoke() const { return getInstruction() && !I.getInt(); }
+
+ InstrTy *getInstruction() const { return I.getPointer(); }
+ InstrTy *operator->() const { return I.getPointer(); }
+ operator bool() const { return I.getPointer(); }
+
+ /// getCalledValue - Return the pointer to function that is being called.
+ ///
+ ValTy *getCalledValue() const {
+ assert(getInstruction() && "Not a call or invoke instruction!");
+ return *getCallee();
+ }
+
+ /// getCalledFunction - Return the function being called if this is a direct
+ /// call, otherwise return null (if it's an indirect call).
+ ///
+ FunTy *getCalledFunction() const {
+ return dyn_cast<FunTy>(getCalledValue());
+ }
+
+ /// setCalledFunction - Set the callee to the specified value.
+ ///
+ void setCalledFunction(Value *V) {
+ assert(getInstruction() && "Not a call or invoke instruction!");
+ *getCallee() = V;
+ }
+
+ /// isCallee - Determine whether the passed iterator points to the
+ /// callee operand's Use.
+ ///
+ bool isCallee(value_use_iterator<UserTy> UI) const {
+ return getCallee() == &UI.getUse();
+ }
+
+ ValTy *getArgument(unsigned ArgNo) const {
+ assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!");
+ return *(arg_begin() + ArgNo);
+ }
+
+ void setArgument(unsigned ArgNo, Value* newVal) {
+ assert(getInstruction() && "Not a call or invoke instruction!");
+ assert(arg_begin() + ArgNo < arg_end() && "Argument # out of range!");
+ getInstruction()->setOperand(ArgNo, newVal);
+ }
+
+ /// Given a value use iterator, returns the argument that corresponds to it.
+ /// Iterator must actually correspond to an argument.
+ unsigned getArgumentNo(value_use_iterator<UserTy> I) const {
+ assert(getInstruction() && "Not a call or invoke instruction!");
+ assert(arg_begin() <= &I.getUse() && &I.getUse() < arg_end()
+ && "Argument # out of range!");
+ return &I.getUse() - arg_begin();
+ }
+
+ /// arg_iterator - The type of iterator to use when looping over actual
+ /// arguments at this call site.
+ typedef IterTy arg_iterator;
+
+ /// arg_begin/arg_end - Return iterators corresponding to the actual argument
+ /// list for a call site.
+ IterTy arg_begin() const {
+ assert(getInstruction() && "Not a call or invoke instruction!");
+ // Skip non-arguments
+ return (*this)->op_begin();
+ }
+
+ IterTy arg_end() const { return (*this)->op_end() - getArgumentEndOffset(); }
+ bool arg_empty() const { return arg_end() == arg_begin(); }
+ unsigned arg_size() const { return unsigned(arg_end() - arg_begin()); }
+
+ /// getType - Return the type of the instruction that generated this call site
+ ///
+ Type *getType() const { return (*this)->getType(); }
+
+ /// getCaller - Return the caller function for this call site
+ ///
+ FunTy *getCaller() const { return (*this)->getParent()->getParent(); }
+
+#define CALLSITE_DELEGATE_GETTER(METHOD) \
+ InstrTy *II = getInstruction(); \
+ return isCall() \
+ ? cast<CallInst>(II)->METHOD \
+ : cast<InvokeInst>(II)->METHOD
+
+#define CALLSITE_DELEGATE_SETTER(METHOD) \
+ InstrTy *II = getInstruction(); \
+ if (isCall()) \
+ cast<CallInst>(II)->METHOD; \
+ else \
+ cast<InvokeInst>(II)->METHOD
+
+ /// getCallingConv/setCallingConv - get or set the calling convention of the
+ /// call.
+ CallingConv::ID getCallingConv() const {
+ CALLSITE_DELEGATE_GETTER(getCallingConv());
+ }
+ void setCallingConv(CallingConv::ID CC) {
+ CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
+ }
+
+ /// getAttributes/setAttributes - get or set the parameter attributes of
+ /// the call.
+ const AttrListPtr &getAttributes() const {
+ CALLSITE_DELEGATE_GETTER(getAttributes());
+ }
+ void setAttributes(const AttrListPtr &PAL) {
+ CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
+ }
+
+ /// \brief Return true if this function has the given attribute.
+ bool hasFnAttr(Attributes N) const {
+ CALLSITE_DELEGATE_GETTER(hasFnAttr(N));
+ }
+
+ /// paramHasAttr - whether the call or the callee has the given attribute.
+ bool paramHasAttr(uint16_t i, Attributes attr) const {
+ CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
+ }
+
+ /// @brief Extract the alignment for a call or parameter (0=unknown).
+ uint16_t getParamAlignment(uint16_t i) const {
+ CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
+ }
+
+ /// @brief Return true if the call should not be inlined.
+ bool isNoInline() const {
+ CALLSITE_DELEGATE_GETTER(isNoInline());
+ }
+ void setIsNoInline(bool Value = true) {
+ CALLSITE_DELEGATE_SETTER(setIsNoInline(Value));
+ }
+
+ /// @brief Determine if the call does not access memory.
+ bool doesNotAccessMemory() const {
+ CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
+ }
+ void setDoesNotAccessMemory(bool doesNotAccessMemory = true) {
+ CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
+ }
+
+ /// @brief Determine if the call does not access or only reads memory.
+ bool onlyReadsMemory() const {
+ CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
+ }
+ void setOnlyReadsMemory(bool onlyReadsMemory = true) {
+ CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
+ }
+
+ /// @brief Determine if the call cannot return.
+ bool doesNotReturn() const {
+ CALLSITE_DELEGATE_GETTER(doesNotReturn());
+ }
+ void setDoesNotReturn(bool doesNotReturn = true) {
+ CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
+ }
+
+ /// @brief Determine if the call cannot unwind.
+ bool doesNotThrow() const {
+ CALLSITE_DELEGATE_GETTER(doesNotThrow());
+ }
+ void setDoesNotThrow(bool doesNotThrow = true) {
+ CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
+ }
+
+#undef CALLSITE_DELEGATE_GETTER
+#undef CALLSITE_DELEGATE_SETTER
+
+ /// @brief Determine whether this argument is not captured.
+ bool doesNotCapture(unsigned ArgNo) const {
+ return paramHasAttr(ArgNo + 1, Attribute::NoCapture);
+ }
+
+ /// @brief Determine whether this argument is passed by value.
+ bool isByValArgument(unsigned ArgNo) const {
+ return paramHasAttr(ArgNo + 1, Attribute::ByVal);
+ }
+
+ /// hasArgument - Returns true if this CallSite passes the given Value* as an
+ /// argument to the called function.
+ bool hasArgument(const Value *Arg) const {
+ for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E;
+ ++AI)
+ if (AI->get() == Arg)
+ return true;
+ return false;
+ }
+
+private:
+ unsigned getArgumentEndOffset() const {
+ if (isCall())
+ return 1; // Skip Callee
+ else
+ return 3; // Skip BB, BB, Callee
+ }
+
+ IterTy getCallee() const {
+ if (isCall()) // Skip Callee
+ return cast<CallInst>(getInstruction())->op_end() - 1;
+ else // Skip BB, BB, Callee
+ return cast<InvokeInst>(getInstruction())->op_end() - 3;
+ }
+};
+
+class CallSite : public CallSiteBase<Function, Value, User, Instruction,
+ CallInst, InvokeInst, User::op_iterator> {
+ typedef CallSiteBase<Function, Value, User, Instruction,
+ CallInst, InvokeInst, User::op_iterator> Base;
+public:
+ CallSite() {}
+ CallSite(Base B) : Base(B) {}
+ CallSite(Value* V) : Base(V) {}
+ CallSite(CallInst *CI) : Base(CI) {}
+ CallSite(InvokeInst *II) : Base(II) {}
+ CallSite(Instruction *II) : Base(II) {}
+
+ bool operator==(const CallSite &CS) const { return I == CS.I; }
+ bool operator!=(const CallSite &CS) const { return I != CS.I; }
+ bool operator<(const CallSite &CS) const {
+ return getInstruction() < CS.getInstruction();
+ }
+
+private:
+ User::op_iterator getCallee() const;
+};
+
+/// ImmutableCallSite - establish a view to a call site for examination
+class ImmutableCallSite : public CallSiteBase<> {
+ typedef CallSiteBase<> Base;
+public:
+ ImmutableCallSite(const Value* V) : Base(V) {}
+ ImmutableCallSite(const CallInst *CI) : Base(CI) {}
+ ImmutableCallSite(const InvokeInst *II) : Base(II) {}
+ ImmutableCallSite(const Instruction *II) : Base(II) {}
+ ImmutableCallSite(CallSite CS) : Base(CS.getInstruction()) {}
+};
+
+} // End llvm namespace
+
+#endif
diff --git a/include/llvm/Support/Capacity.h b/include/llvm/Support/Capacity.h
new file mode 100644
index 00000000000..7460f9825bd
--- /dev/null
+++ b/include/llvm/Support/Capacity.h
@@ -0,0 +1,32 @@
+//===--- Capacity.h - Generic computation of ADT memory use -----*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the capacity function that computes the amount of
+// memory used by an ADT.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_CAPACITY_H
+#define LLVM_SUPPORT_CAPACITY_H
+
+#include <cstddef>
+
+namespace llvm {
+
+template <typename T>
+static inline size_t capacity_in_bytes(const T &x) {
+ // This default definition of capacity should work for things like std::vector
+ // and friends. More specialized versions will work for others.
+ return x.capacity() * sizeof(typename T::value_type);
+}
+
+} // end namespace llvm
+
+#endif
+
diff --git a/include/llvm/Support/Casting.h b/include/llvm/Support/Casting.h
new file mode 100644
index 00000000000..3aab4367f5b
--- /dev/null
+++ b/include/llvm/Support/Casting.h
@@ -0,0 +1,233 @@
+//===-- llvm/Support/Casting.h - Allow flexible, checked, casts -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
+// and dyn_cast_or_null<X>() templates.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_SUPPORT_CASTING_H
+#define LLVM_SUPPORT_CASTING_H
+
+#include <cassert>
+
+namespace llvm {
+
+//===----------------------------------------------------------------------===//
+// isa<x> Support Templates
+//===----------------------------------------------------------------------===//
+
+// Define a template that can be specialized by smart pointers to reflect the
+// fact that they are automatically dereferenced, and are not involved with the
+// template selection process... the default implementation is a noop.
+//
+template<typename From> struct simplify_type {
+ typedef From SimpleType; // The real type this represents...
+
+ // An accessor to get the real value...
+ static SimpleType &getSimplifiedValue(From &Val) { return Val; }
+};
+
+template<typename From> struct simplify_type<const From> {
+ typedef const From SimpleType;
+ static SimpleType &getSimplifiedValue(const From &Val) {